6.18.66-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 759/990 software node: only let the owner release a managed node
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit f8623ce596492d2e96ca57eeec992938d3d79f00 upstream.
device_create_managed_software_node() creates a node whose lifetime is tied to the device it was created for. software_node_notify_remove() is called for every device that has the node as its fwnode (primary OR secondary) and, if the node is managed, unconditionally detaches it from that device and drops the creation reference.
This breaks when the node is shared with another device. Example: the i2c-designware copies the parent's fwnode to the adapter's struct device. When the adapter is deleted, it releases the reference that belongs to the owner and the latter ends up with a dangling pointer.
Record the device's "manager" and only perform the actual release when notify is called for that "owner" device.
Note that it was never the intention that managed software nodes would be shared, but descendants reusing ancestor firmware nodes is not uncommon and such use is hard to predict when allocating software nodes.
[ johan: drop temporary variable; skip clearing owner field;
mention reuse not intended in commit message ]
--- drivers/base/swnode.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/base/swnode.c +4 -3
@@ -29,6 +29,8 @@ struct swnode {struct fwnode_handle fwnode;const struct software_node *node;int id; +/* Device the managed node's lifetime is tied to. */ +struct device *owner;/* hierarchy */ struct ida child_ids;
@@ -37,7 +39,6 @@ struct swnode {struct swnode *parent; unsigned int allocated:1; - unsigned int managed:1; };static DEFINE_IDA (swnode_root_ids);
@@ -1060,7 +1061,7 @@ int device_create_managed_software_node(if (IS_ERR (fwnode))return PTR_ERR (fwnode); -to_swnode (fwnode)->managed = true; +to_swnode (fwnode)->owner = dev;set_secondary_fwnode (dev, fwnode);if (device_is_registered (dev))
@@ -1103,7 +1104,7 @@ void software_node_notify_remove(structsysfs_remove_link (&dev->kobj,"software_node" );kobject_put (&swnode->kobj); -if (swnode->managed) { +if (swnode->owner == dev) {set_secondary_fwnode (dev,NULL );kobject_put (&swnode->kobj); }
Greg Kroah-Hartman
maintainerPATCH 760/990 SUNRPC: Fix TCP-with-TLS transport class identification
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
commit 0502c7e7f171a8c9c892bdef89e6aa6f44d7b2a3 upstream.
xs_setup_tcp_tls() assigns the ordinary TCP transport class to a TCP-with-TLS transport. When rpc_clnt_add_xprt() is called with an unspecified transport type, it inherits the class identifier and can create an unencrypted TCP transport.
Looks like a copy-paste error from the commit 3 years ago.
NFSv4 trunk discovery uses an unspecified transport type when adding server-advertised addresses. If the additional transport passes server-identity validation, it can be admitted to the client's transport switch.
An isolated loopback test reproduced plaintext application RPC transmission for TLS- and mTLS-configured clients, including an unpinned TLS-client RPC that selected the added transport.
Assign the TCP-with-TLS class instead. With the fix, the plaintext-only test peer receives TLS negotiation probes but no application payloads.
--- net/sunrpc/xprtsock.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sunrpc/xprtsock.c +1 -1
@@ -3524,7 +3524,7 @@ static struct rpc_xprt *xs_setup_tcp_tls transport = container_of(xprt, struct sock_xprt, xprt); xprt->prot =IPPROTO_TCP ; - xprt->xprt_class = &xs_tcp_transport; + xprt->xprt_class = &xs_tcp_tls_transport; xprt->max_payload =RPC_MAX_FRAGMENT_SIZE ; xprt->bind_timeout =XS_BIND_TO ;
Greg Kroah-Hartman
maintainerPATCH 761/990 timekeeping: Read getboottime64() offsets under the sequence counter
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit 385b5ec1f31dd39297578eed42be74b07ae74017 upstream.
getboottime64() computes the wall-clock boot timestamp from offs_real minus offs_boot without checking tk_core.seq. A concurrent timekeeping update can leave the reader with an inconsistent pair of offsets or, on 32-bit systems, a torn 64-bit offset, producing an incorrect boot timestamp.
Read both offsets under tk_core.seq and retry if an update overlaps the sample. Convert the resulting local value to a timespec64 afterward.
--- kernel/time/timekeeping.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
kernel/time/timekeeping.c +7 -1
@@ -2419,7 +2419,13 @@ void update_wall_time(void)void getboottime64 (struct timespec64 *ts) {struct timekeeper *tk = &tk_core.timekeeper; -ktime_t t =ktime_sub (tk->offs_real, tk->offs_boot); +unsigned int seq; +ktime_t t; + +do { + seq =read_seqcount_begin (&tk_core.seq); + t =ktime_sub (tk->offs_real, tk->offs_boot); + }while (read_seqcount_retry (&tk_core.seq, seq)); *ts =ktime_to_timespec64 (t); }
Greg Kroah-Hartman
maintainerPATCH 762/990 timekeeping: Refresh auxiliary base before offset validation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Avi Weiss <[email protected]>
commit c1b96ba87e3caaa701d6dba254e58db7cc3c99be upstream.
timekeeping_forward_now() can advance an auxiliary timekeeper across a second boundary without refreshing tkr_mono.base. The negative-time check in __timekeeping_inject_offset() then uses the stale base and rejects valid ADJ_SETOFFSET adjustments with -EINVAL.
Refresh the derived timekeeper data before calculating the current auxiliary time, as aux_clock_set() already does.
On 7.4-rc1, a valid negative adjustment fails at the first second rollover. The patched kernel accepts all 12 tested rollover adjustments and continues to reject invalid negative offsets.
--- kernel/time/timekeeping.c | 1 + 1 file changed, 1 insertion(+)
kernel/time/timekeeping.c +1 -0
@@ -1503,6 +1503,7 @@ static int __timekeeping_inject_offset(sstruct tk_read_base *tkr_mono = &tks->tkr_mono;ktime_t now, offs; +tk_update_ktime_data (tks);/* Get the current time */ now =ktime_add_ns (tkr_mono->base,timekeeping_get_ns (tkr_mono));/* Add the relative offset change */
Greg Kroah-Hartman
maintainerPATCH 763/990 tpm: acpi: Fix memory leak at tpm_read_log_acpi() error path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Takashi Iwai <[email protected]>
commit 03fcb358249dc715124b3616f814ea0ecc6ec36c upstream.
When devm_add_action() returns an error, tpm_read_log_acpi() clears log->bios_event_log unnecessarily to NULL before calling tpm_bios_log_free(), and it would lead to a memory leak of the allocated log buffer.
Fix it by simply jumping to the err.
--- drivers/char/tpm/eventlog/acpi.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/char/tpm/eventlog/acpi.c +1 -3
@@ -167,10 +167,8 @@ int tpm_read_log_acpi(struct tpm_chip *c } ret =devm_add_action (&chip->dev, tpm_bios_log_free, log->bios_event_log); -if (ret) { - log->bios_event_log =NULL ; +if (ret) goto err; - }return format;
Greg Kroah-Hartman
maintainerPATCH 764/990 tpm: Check return value of crypto_kpp_set_secret()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Biggers <[email protected]>
commit 8cff8f1c89d33e55c9af82177b14f6f9f6a899fe upstream.
crypto_kpp_set_secret() can fail, for example if the kernel is booted with fips=1 and the broken-by-design FIPS RNG used for ECC private key generation doesn't feel like generating random bytes at the moment. Check for error, cancelling the TPM session creation rather than proceeding with a zero or uninitialized private key.
--- drivers/char/tpm/tpm2-sessions.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm2-sessions.c +3 -1
@@ -535,7 +535,9 @@ static int tpm_buf_append_salt(struct tp }crypto_ecdh_encode_key (encoded_key, buf_len, &p);/* this generates a random private key */ -crypto_kpp_set_secret (kpp, encoded_key, buf_len); + rc =crypto_kpp_set_secret (kpp, encoded_key, buf_len); +if (rc) + goto err_free_kpp;/* salt is now the public point of this private key */ req =kpp_request_alloc (kpp,GFP_KERNEL );
Greg Kroah-Hartman
maintainerPATCH 765/990 tpm: eventlog: check the payload size before reading tag events
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guanglei Zhu <[email protected]>
commit 0a385f668ba77d29ae167c1668fd452418ebc9d6 upstream.
The EVENT_TAG branch of get_event_name() casts the event payload to struct tcpa_pc_event and reads from it:
pc_event = (struct tcpa_pc_event *)event_entry;
switch (do_endian_conversion(pc_event->event_id)) {
...
for (i = 0; i < 20; i++)
d_len += sprintf(&data[2*i], "%02x",
pc_event->event_data[i]);The log iterators only verify that the event header plus the declared event_size stays within the log buffer; they do not require the payload of an EVENT_TAG entry to be large enough for the fields the branch reads. A truncated entry makes the branch read up to 20 bytes of event_data[] past the end of the entry, and, for the last entry in the log, past the end of the buffer itself.
The legacy PC Client spec defines the EV_EVENT_TAG payload as a TCPA_PC_EVENT - event_id, event_size and event-type-specific data - so a conformant entry carries the 8-byte header and the hash-type ids carry a full digest. The log itself, however, is an ACPI table the firmware leaves in memory: the TPM never measures the log, so the kernel cannot tell a conformant log from a corrupted one. The iterators already work on that assumption - they stop once the declared event_size runs past the buffer end - and the readers should apply the same rule to what they take off the payload.
Skip entries whose payload cannot even hold the event id, and skip the 20-byte digest dump when the payload cannot hold the full tcpa_pc_event header plus the digest, so the branch never reads beyond the entry it is formatting.
--- drivers/char/tpm/eventlog/tpm1.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/char/tpm/eventlog/tpm1.c +7 -0
@@ -178,6 +178,10 @@ static int get_event_name(char *dest, st }break ;case EVENT_TAG : +if (do_endian_conversion (event->event_size) < +sizeof (pc_event->event_id)) +break ; + pc_event = (struct tcpa_pc_event *)event_entry;/* ToDo Row data -> Base64 */
@@ -203,6 +207,9 @@ static int get_event_name(char *dest, st name = tcpa_pc_event_id_strings[do_endian_conversion (pc_event->event_id)]; n_len =strlen (name); +if (do_endian_conversion (event->event_size) < +sizeof (struct tcpa_pc_event ) +20 ) +break ;for (i =0 ; i <20 ; i++) d_len +=sprintf (&data[2 *i],"%02x" , pc_event->event_data[i]);
Greg Kroah-Hartman
maintainerPATCH 766/990 tpm: flush timeout work outside buffer_mutex to avoid deadlock
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyunjung Ko <[email protected]>
commit c22052a012698ce56d599d75b669d55778521c7c upstream.
tpm_common_read() calls flush_work(&priv->timeout_work) under priv->buffer_mutex, but tpm_timeout_work() also takes buffer_mutex, so a running timeout work deadlocks the flush. Flush after unlocking; the timer is deleted under the lock, so no new work can be queued.
--- drivers/char/tpm/tpm-dev-common.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-)
drivers/char/tpm/tpm-dev-common.c +11 -1
@@ -132,6 +132,7 @@ ssize_t tpm_common_read(struct file *fil {struct file_priv *priv = file->private_data;ssize_t ret_size =0 ; +bool flush = false;int rc;if (!size)
@@ -164,9 +165,18 @@ out:if (!priv->response_length) { *off =0 ;timer_delete_sync (&priv->user_read_timer); -flush_work (&priv->timeout_work); + flush = true; }mutex_unlock (&priv->buffer_mutex); + +/* +* tpm_timeout_work() takes buffer_mutex, so flush it after dropping +* the mutex to avoid a deadlock; the timer is deleted above, so no new +* timeout work can be queued once the mutex is released. +*/ +if (flush) +flush_work (&priv->timeout_work); +return ret_size; }
Greg Kroah-Hartman
maintainerPATCH 767/990 spi: tegra210-quad: Track DMA mapping state
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vishwaroop A <[email protected]>
commit 7b9e6f7bc13c0259b192d0a964e802d4ad53b8b8 upstream.
tegra_qspi_dma_unmap_xfer() assumes a streaming mapping is always outstanding and recomputes its length from the live tqspi->curr_dma_words. Nothing records whether tegra_qspi_dma_map_xfer() mapped anything, so neither assumption holds.
For a multi-chunk transfer, handle_dma_based_xfer() unmaps the chunk that just completed, recalculates the parameters for the next chunk, which overwrites curr_dma_words, and re-arms the hardware. If tegra_qspi_start_dma_based_transfer() then fails at its tegra_qspi_dma_map_xfer() call, nothing is mapped. That early return also sits above the smp_store_release() that clears tqspi->trans_status, so the previous chunk's QSPI_RDY survives, and the re-arm's return value is never checked, so handle_dma_based_xfer() returns IRQ_HANDLED without completing the transfer.
The caller times out, tegra_qspi_handle_timeout() sees the stale QSPI_RDY, concludes the transfer completed and calls handle_dma_based_xfer() again. No DMA completion arrives, so num_errors is incremented and tegra_qspi_dma_unmap_xfer() runs with nothing mapped. t->tx_dma then holds either the DMA_MAPPING_ERROR sentinel or, if the RX mapping was the one that failed, the preceding chunk's address that has already been released. Behind an IOMMU the latter frees an IOVA that may since have been reallocated.
Record whether a mapping is outstanding and the length that was mapped, and return early from tegra_qspi_dma_unmap_xfer() when there is nothing to release. is_dma_mapped is only updated under tqspi->lock, or on the timeout path after synchronize_irq() and cancel_work_sync() have quiesced the ISR and the bottom half.
Also skip releasing the TX mapping on the RX failure path unless a TX mapping was created; t->tx_dma is uninitialised when t->tx_buf is NULL.
--- drivers/spi/spi-tegra210-quad.c | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-)
drivers/spi/spi-tegra210-quad.c +25 -6
@@ -215,6 +215,17 @@ struct tegra_qspi {bool is_packed;bool use_dma; +/* +* Set while a streaming mapping created by +* tegra_qspi_dma_map_xfer() is outstanding, together with the +* length that was handed to dma_map_single(). is_curr_dma_xfer +* only records that the last armed chunk took the DMA path, +* which is not the same thing: a chunk whose mapping failed +* leaves the DMA path flagged with nothing mapped. +*/ +bool is_dma_mapped; +unsigned int dma_map_len; +u32 command1_reg;u32 dma_control_reg;u32 def_command1_reg;
@@ -584,24 +595,32 @@ static int tegra_qspi_dma_map_xfer(strucif (t->rx_buf) { t->rx_dma =dma_map_single (tqspi->rx_dma_dev, (void *)rx_buf, len,DMA_FROM_DEVICE );if (dma_mapping_error (tqspi->rx_dma_dev, t->rx_dma)) { -dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, len,DMA_TO_DEVICE ); +if (t->tx_buf) +dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, + len,DMA_TO_DEVICE );return -ENOMEM ; } } + tqspi->dma_map_len = len; + tqspi->is_dma_mapped = true; +return 0 ; }static void tegra_qspi_dma_unmap_xfer (struct tegra_qspi *tqspi,struct spi_transfer *t) { -unsigned int len; - - len =DIV_ROUND_UP (tqspi->curr_dma_words * tqspi->bytes_per_word,4 ) *4 ; +if (!tqspi->is_dma_mapped) +return ;if (t->tx_buf) -dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, len,DMA_TO_DEVICE ); +dma_unmap_single (tqspi->tx_dma_dev, t->tx_dma, + tqspi->dma_map_len,DMA_TO_DEVICE );if (t->rx_buf) -dma_unmap_single (tqspi->rx_dma_dev, t->rx_dma, len,DMA_FROM_DEVICE ); +dma_unmap_single (tqspi->rx_dma_dev, t->rx_dma, + tqspi->dma_map_len,DMA_FROM_DEVICE ); + + tqspi->is_dma_mapped = false; }static int tegra_qspi_start_dma_based_transfer (struct tegra_qspi *tqspi,struct spi_transfer *t)
Greg Kroah-Hartman
maintainerPATCH 768/990 watchdog: npcm: fix clock prepare leak when setting timeout on a running watchdog
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Feng <[email protected]>
commit 57c7cbe21acc77291ec0fbdd4bd72aa259cf4986 upstream.
npcm_wdt_start() unconditionally prepares and enables the watchdog clock, and npcm_wdt_stop() is the only place that disables it. npcm_wdt_set_timeout() calls npcm_wdt_start() again whenever the watchdog is already active, so every WDIOC_SETTIMEOUT ioctl issued while the watchdog is running takes one extra clock prepare/enable reference that is never dropped.
Split the register programming out of npcm_wdt_start() into a __npcm_wdt_start() helper that assumes the clock is already running, and call the helper from npcm_wdt_set_timeout() instead; only the watchdog .start callback (and the restart path, which intentionally keeps the clock) now acquires the clock.
--- drivers/watchdog/npcm_wdt.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/watchdog/npcm_wdt.c +11 -4
@@ -63,13 +63,11 @@ static int npcm_wdt_ping(struct watchdogreturn 0 ; } -static int npcm_wdt_start (struct watchdog_device *wdd) +static void __npcm_wdt_start (struct watchdog_device *wdd) {struct npcm_wdt *wdt =to_npcm_wdt (wdd);u32 val; -clk_prepare_enable (wdt->clk); -if (wdd->timeout <2 ) val =0x800 ;else if (wdd->timeout <3 )
@@ -94,6 +92,15 @@ static int npcm_wdt_start(struct watchdo val |=NPCM_WTRE |NPCM_WTE |NPCM_WTR |NPCM_WTIE ;writel (val, wdt->reg); +} + +static int npcm_wdt_start (struct watchdog_device *wdd) +{ +struct npcm_wdt *wdt =to_npcm_wdt (wdd); + +clk_prepare_enable (wdt->clk); + +__npcm_wdt_start (wdd);return 0 ; }
@@ -134,7 +141,7 @@ static int npcm_wdt_set_timeout(struct w wdd->timeout =2750 ;if (watchdog_active (wdd)) -npcm_wdt_start (wdd); +__npcm_wdt_start (wdd);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 769/990 x86/CPU/AMD: Dont print reset reason in VMs
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jason Andryuk <[email protected]>
commit ea51d1a4c31fc8320c34f897dc5296a0bfc5c7ca upstream.
print_s5_reset_status_mmio() expects to read FCH MMIO on baremetal. VMs don't have emulated FCH registers, so there is nothing to check. Add an early exit when running on a hypervisor.
The real motivation is Xen PV domUs can't boot on Zen CPUs. PV domUs PTEs contain system physical addresses - they don't have the concept of guest physical addresses. domUs can only map physical addresses they are assigned, so a domU fails to map the FCH MMIO addresses.
However set_pte() does not return failure, so ioremap() returns a pointer while the PTEs are unpopulated. print_s5_reset_status_mmio() faults when reading through the pointer, breaking the boot.
Limit the reset reason printing to baremetal only where it actually makes sense.
[ bp: Massage commit message. ]
--- arch/x86/kernel/cpu/amd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
arch/x86/kernel/cpu/amd.c +2 -1
@@ -1370,7 +1370,8 @@ static __init int print_s5_reset_status_u32 value;int i; -if (!cpu_feature_enabled (X86_FEATURE_ZEN )) +if (!cpu_feature_enabled (X86_FEATURE_ZEN ) || +cpu_feature_enabled (X86_FEATURE_HYPERVISOR ))return 0 ; addr =ioremap (FCH_PM_BASE +FCH_PM_S5_RESET_STATUS ,sizeof (value));
Greg Kroah-Hartman
maintainerPATCH 770/990 x86/mm: Ensure write visibility during LDT installation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Hansen <[email protected]>
commit 0dc2a4dac3d04e9e4479aeb0b46172feab1cca0a upstream.
During LDT installation, the intent is to overwrite the old per-mm LDT value, then send an IPI to the mm user CPUs to have each load the new value.
But there is an ordering problem: a new mm user CPU sets itself in mm_cpumask() and then reads mm->context.ldt. The LDT-installing CPU writes mm->context.ldt and then reads mm_cpumask(). But, there is nothing which orders the LDT installation side actions. The CPU can read mm_cpumask() before its write becomes visible.
Ensure that new mm user CPUs see the new mm->context.ldt. Make mm->context.ldt visible before reading mm_cpumask().
Also convert the smp_store_release() over to a WRITE_ONCE(). smp_store_release() has an internal barrier which is weaker than the new smp_mb(). Avoid an extra barrier by converting it to WRITE_ONCE().
Also refresh/correct misleading comments. READ/WRITE_ONCE() do not "synchronize" anything themselves.
--- arch/x86/kernel/ldt.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
arch/x86/kernel/ldt.c +9 -3
@@ -43,7 +43,7 @@ void load_mm_ldt(struct mm_struct *mm) {struct ldt_struct *ldt; -/* READ_ONCE synchronizes with smp_store_release */ +/* Pairs with WRITE_ONCE() in install_ldt() */ ldt =READ_ONCE (mm->context.ldt);/*
@@ -422,8 +422,14 @@ static void install_ldt(struct mm_struct {mutex_lock (&mm->context.lock); -/* Synchronizes with READ_ONCE in load_mm_ldt. */ -smp_store_release (&mm->context.ldt, ldt); +/* +* Ensure that new mm user CPUs either see the new LDT value +* or get an IPI. Make the store visible before reading +* mm_cpumask(). New mm users make their mm_cpumask() writes +* visible before reading mm->context.ldt. +*/ +WRITE_ONCE (mm->context.ldt, ldt); +smp_mb ();/* Activate the LDT for all CPUs using currents mm. */ on_each_cpu_mask (mm_cpumask (mm), flush_ldt, mm, true);
Greg Kroah-Hartman
maintainerPATCH 771/990 x86/video: Preserve the default VGA fallback for legacy modes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hengyu Liang <[email protected]>
commit 3b4c98b47ba7c3c57bcf54fb85f54a854622041c upstream.
Commit
596b3678326d ("x86/video: Only fall back to vga_default_device() without screen info")
made video_is_primary_device() rely exclusively on screen_info resources whenever any are available.
However, screen_info_resources() also returns legacy I/O and memory ranges for VGA text modes. These ranges are not PCI BARs, so pci_find_resource() does not find them and the default VGA fallback is skipped. As a result, no device is primary in VGA text mode.
On a SeaBIOS QEMU guest with bochs and VKMS, the boot VGA (bochs) loses its DRM boot_display attribute. VKMS registers fb0 and bochs registers fb1. VKMS is not a PCI device, so it is not primary either. With no primary device, fbcon keeps the console on fb0 and never remaps it to bochs. This can be checked with:
cat /sys/class/drm/card1/boot_display
stty -F /dev/tty1 size
Without the fix, boot_display is missing and tty1 is 48 rows by 128 columns. With it, boot_display contains 1 and tty1 is 50 rows by 160 columns. VKMS only makes the console part visible. Without VKMS, tty1 has the same size with and without the fix, but boot_display is still missing without it.
Use resource-based selection only for linear framebuffers. Fall back to vga_default_device() for legacy display modes, while keeping EFI and VESA framebuffer ownership authoritative.
--- arch/x86/video/video-common.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/video/video-common.c +1 -1
@@ -45,7 +45,7 @@ bool video_is_primary_device(struct devi#ifdef CONFIG_SCREEN_INFO numres =screen_info_resources (si, res,ARRAY_SIZE (res)); -if (numres >0 ) { +if (numres >0 &&__screen_info_has_lfb (screen_info_video_type (si))) {for (i =0 ; i < numres; ++i) {if (!(res[i].flags &IORESOURCE_MEM ))continue ;
Greg Kroah-Hartman
maintainerPATCH 772/990 xen/gntdev: fix deadlock between map ioctl and mmap
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 7620a997e4854c94eacebf0c2d453fbd78ccdb46 upstream.
Commit 45ca1afe2fd1 ("xen/gntdev: fix error handling in ioctl") moved copy_to_user() in gntdev_ioctl_map_grant_ref() under priv->lock. A fault in copy_to_user() takes mmap_lock, while gntdev_mmap() is called with mmap_lock held and takes priv->lock:
ioctl thread mmap thread
mutex_lock(&priv->lock)
mmap_write_lock(mm)
gntdev_mmap()
mutex_lock(&priv->lock) copy_to_user() faults
mmap_read_lock(mm)
Reproduced on Debian 6.12.111 in a Xen guest, with the ioctl argument on a MAP_PRIVATE file page that has not been written yet. sysrq-w:
task:repro state:D stack:0 pid:4479 tgid:4477 ppid:1 flags:0x00000000
rwsem_down_read_slowpath+0x25c/0x480 down_read_killable+0x48/0xc0 lock_mm_and_find_vma+0x96/0x250 do_user_addr_fault+0x12d/0x620 exc_page_fault+0x7e/0x180 asm_exc_page_fault+0x26/0x30 _copy_to_user+0x36/0x50 gntdev_ioctl+0x3b9/0xa00 [xen_gntdev] __x64_sys_ioctl+0x97/0xc0 task:repro state:D stack:0 pid:4480 tgid:4477 ppid:1 flags:0x00000000 __mutex_lock.constprop.0+0x41b/0x720 gntdev_mmap+0x4d/0x330 [xen_gntdev] __mmap_region+0x697/0xb10 mmap_region+0x78/0xa0 do_mmap+0x45d/0x630 vm_mmap_pgoff+0xf8/0x1c0
Drop priv->lock before copy_to_user() again. On failure, re-take it and remove the map by index, as IOCTL_GNTDEV_UNMAP_GRANT_REF does, since another thread may have unmapped it meanwhile.
Message-ID: <[email protected]>
--- drivers/xen/gntdev.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/xen/gntdev.c +6 -2
@@ -676,15 +676,19 @@ static long gntdev_ioctl_map_grant_ref(smutex_lock (&priv->lock);gntdev_add_map (priv, map); op.index = map->index <<PAGE_SHIFT ; +mutex_unlock (&priv->lock);if (copy_to_user (u, &op,sizeof (op)) !=0 ) { -list_del (&map->next); +mutex_lock (&priv->lock); + map =gntdev_find_map_index (priv, op.index >>PAGE_SHIFT , + op.count); +if (map) +list_del (&map->next);mutex_unlock (&priv->lock);gntdev_put_map (priv, map);return -EFAULT ; } -mutex_unlock (&priv->lock);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 773/990 xen/privcmd: fix double free when an irqfd is shut down twice
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qihang <[email protected]>
commit 72a900c666adb97df77b05cf8540c4117f9c83ba upstream.
irqfd_deactivate() takes the irqfd off irqfds_list and queues irqfd_shutdown(). queue_work() is not a once-only gate: it refuses to enqueue a work item only while WORK_STRUCT_PENDING is set, and process_one_work() clears that bit before it calls the work function. So nothing records that the shutdown work has already been queued, and nothing protects the window between the start of irqfd_shutdown() and the kfree() at its end.
Two paths call irqfd_deactivate() for the same irqfd:
- privcmd_irqfd_deassign(), from the PRIVCMD_IRQFD_FLAG_DEASSIGN ioctl;
- irqfd_wakeup(), with EPOLLHUP set, when the last reference to the
eventfd file goes away, which runs wake_up_poll(&ctx->wqh, EPOLLHUP)
from eventfd_release().irqfds_lock serialises the two calls, but it does not make the second one a no-op, and eventfd_ctx_fdget() takes a reference to the eventfd_ctx, not to the struct file, so the last fd can still be closed while the ioctl is running:
CPU0 CPU1
eventfd_ctx_fdget()
spin_lock(irqfds_lock)
list_del_init(&kirqfd->list)
queue_work(&kirqfd->shutdown) close(fd)
eventfd_release()
wake_up_poll(EPOLLHUP)
irqfd_wakeup() spin_lock(irqfds_lock) irqfd_deactivate() again
If the work item has already started by then, its pending bit has been cleared and the second queue_work() succeeds. irqfd_shutdown() then runs twice, so eventfd_ctx_remove_wait_queue(), eventfd_ctx_put() and kfree() each hit the same object a second time; and when the second queue_work() lands after the irqfd has been freed, the workqueue list operations write to freed memory.
virt/kvm/eventfd.c has the same two callers and has had this guard since the original irqfd support (721eecbf4fe99): irqfd_wakeup() calls irqfd_deactivate() only if irqfd_is_active(). The comment there explains why that is enough: the other side deactivates the irqfd before it takes it off the waitqueue, and irqfd_shutdown() needs the waitqueue lock, which this callback holds, so the irqfd cannot be freed under it.
Do the same here. list_del_init() leaves the list head empty and the irqfd stays off the list until kfree(), so it serves as a one-way "active" flag. The test is in irqfd_deactivate() rather than in irqfd_wakeup() because privcmd_irqfd_deassign() walks irqfds_list and can therefore never reach an inactive irqfd; only the wakeup path can, and a single test covers both callers.
Message-ID: <[email protected]>
--- drivers/xen/privcmd.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
drivers/xen/privcmd.c +15 -0
@@ -901,10 +901,25 @@ struct privcmd_kernel_irqfd {poll_table pt; }; +static bool irqfd_is_active (struct privcmd_kernel_irqfd *kirqfd) +{ +lockdep_assert_held (&irqfds_lock); + +return !list_empty (&kirqfd->list); +} +static void irqfd_deactivate (struct privcmd_kernel_irqfd *kirqfd) {lockdep_assert_held (&irqfds_lock); +/* +* Both the deassign ioctl and the eventfd wakeup path can reach +* this function. list_del_init() marks the irqfd inactive, so +* only the first caller may queue the shutdown work. +*/ +if (!irqfd_is_active (kirqfd)) +return ; +list_del_init (&kirqfd->list);queue_work (irqfd_cleanup_wq, &kirqfd->shutdown); }
Greg Kroah-Hartman
maintainerPATCH 774/990 xen/pvcalls: unwind pvcalls_new_active_socket() step by step
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 702ba3c80a8736898813a2c7484d695278aa114d upstream.
Every error path in pvcalls_new_active_socket() jumps to one shared label that does list_del(&map->list) and then hands map to pvcalls_back_release_active(). But map comes from kzalloc() and its list_head is only published at the very end of the function, after the last of those jumps:
down(&fedata->socket_lock); list_add_tail(&map->list, &fedata->socket_mappings); up(&fedata->socket_lock);
so on the error path map->list is still {NULL, NULL} and __list_del() writes through a NULL pointer.
A frontend gets there with one value it owns: the ring_order field of the page it granted. Anything above MAX_RING_ORDER takes the second goto, and nothing else in the function has run by then.
The result is an oops in whichever context handled the request - the pvcalls-back threaded IRQ handler for PVCALLS_CONNECT, mappass->wq for PVCALLS_ACCEPT - and because it happens after down(&fedata->socket_lock) that semaphore is never released, so every later operation on the frontend blocks on it and the backend never completes backend_disconnect(). (With CONFIG_DEBUG_LIST the list_del() only reports and returns, and pvcalls_back_release_active() then runs on a map whose irq is still 0 and whose bytes, ioworker.wq and saved_data_ready are all NULL.)
A frontend asking for ring_order 5, on a dom0 built with KASAN (the request was issued by a test-only change to the frontend):
[ 133.728877] pvcalls_new_active_socket frontend requested ring_order 5, which is > MAX (4) [ 133.732868] Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI [ 133.737910] KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f] [ 133.741666] CPU: 0 UID: 0 PID: 133 Comm: irq/39-pvcalls- Not tainted 7.3.0-kCTLblk2-15482-g21a7f44fd076-dirty #1 PREEMPT(full) [ 133.746986] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 [ 133.751512] RIP: 0010:pvcalls_new_active_socket+0x821/0xb90 [ 133.754237] Code: 48 89 fa 48 c1 ea 03 80 3c 02 00 0f 85 f6 01 00 00 48 8d 79 08 4c 8b 6b 08 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <80> 3c 02 00 0f 85 14 02 00 00 4c 89 ea 4c 89 69 08 48 b8 00 00 00 [ 133.763126] RSP: 0018:ffffc900004afb38 EFLAGS: 00010202 [ 133.765861] RAX: dffffc0000000000 RBX: ffff88810886c900 RCX: 0000000000000000 [ 133.769348] RDX: 0000000000000001 RSI: 0000000000000246 RDI: 0000000000000008 [ 133.772787] RBP: 1ffff92000095f6b R08: 0000000000000001 R09: fffff52000095f58 [ 133.776260] R10: 0000000000000003 R11: ffff888100077320 R12: ffff88810858b410 [ 133.779823] R13: 0000000000000000 R14: ffff88810858b460 R15: ffff88810858b400 [ 133.783382] FS: 0000000000000000(0000) GS:ffff8881b034c000(0000) knlGS:0000000000000000 [ 133.787351] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 133.790308] CR2: 00000000006042c0 CR3: 0000000108400001 CR4: 0000000000770ef0 [ 133.793822] PKRU: 55555554 [ 133.795347] Call Trace: [ 133.796778] <TASK> [ 133.798082] ? __pfx_pvcalls_new_active_socket+0x10/0x10 [ 133.800801] ? security_socket_post_create+0x4d/0x60 [ 133.803275] ? release_sock+0x1a/0x1d0 [ 133.805182] pvcalls_back_event+0x1b09/0x23e0 [ 133.807431] ? __pfx_pvcalls_back_event+0x10/0x10 [ 133.809814] ? __pfx__raw_spin_lock_irqsave+0x10/0x10 [ 133.812251] ? __pfx_pvcalls_back_event+0x10/0x10 [ 133.814554] irq_thread_fn+0x86/0x150 [ 133.816468] irq_thread+0x2da/0x580 [ 133.818363] ? __pfx_irq_thread_fn+0x10/0x10 [ 133.820586] ? __pfx_irq_thread+0x10/0x10 [ 133.822670] ? __kthread_parkme+0x88/0x170 [ 133.824803] ? __pfx_irq_thread+0x10/0x10 [ 133.827153] ? __pfx_irq_thread+0x10/0x10 [ 133.829304] kthread+0x2c8/0x3b0 [ 133.831176] ? recalc_sigpending+0x15c/0x1e0 [ 133.833570] ? __pfx_kthread+0x10/0x10 [ 133.835572] ret_from_fork+0x373/0x5b0 [ 133.837581] ? __pfx_ret_from_fork+0x10/0x10 [ 133.839978] ? __switch_to+0x3c4/0xb40 [ 133.841984] ? __pfx_kthread+0x10/0x10 [ 133.843970] ret_from_fork_asm+0x1a/0x30 [ 133.846031] </TASK> [ 133.847420] Modules linked in: [ 133.849240] ---[ end trace 0000000000000000 ]---
Give each failure its own label, so that only resources that were actually acquired are released and the list the map was never added to is left
alone. The map is not published anywhere at that point, so the error path needs no socket_lock at all. sock_release() stays in the callee on every error path, the way
commit 8fafac202d18 ("xen/pvcalls-back: fix double frees with pvcalls_new_active_socket()") arranged it.
Message-ID: <[email protected]>
--- drivers/xen/pvcalls-back.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-)
drivers/xen/pvcalls-back.c +15 -10
@@ -337,7 +337,7 @@ static struct sock_mapping *pvcalls_new_ ret =xenbus_map_ring_valloc (fedata->dev, &ref,1 , &page);if (ret <0 ) - goto out; + goto out_map; map->ring = page; map->ring_order = map->ring->ring_order;/* first read the order, then map the data ring */
@@ -345,19 +345,19 @@ static struct sock_mapping *pvcalls_new_if (map->ring_order >MAX_RING_ORDER ) {pr_warn ("%s frontend requested ring_order %u, which is > MAX (%u)\n" , __func__, map->ring_order,MAX_RING_ORDER ); - goto out; + goto out_unmap_ring; } ret =xenbus_map_ring_valloc (fedata->dev, map->ring->ref, (1 << map->ring_order), &page);if (ret <0 ) - goto out; + goto out_unmap_ring; map->bytes = page; ret =bind_interdomain_evtchn_to_irqhandler_lateeoi ( fedata->dev, evtchn, pvcalls_back_conn_event,0 ,"pvcalls-backend" , map);if (ret <0 ) - goto out; + goto out_unmap_bytes; map->irq = ret; map->data.in = map->bytes;
@@ -365,7 +365,7 @@ static struct sock_mapping *pvcalls_new_ map->ioworker.wq =alloc_ordered_workqueue ("pvcalls_io" ,0 );if (!map->ioworker.wq) - goto out; + goto out_unbind;atomic_set (&map->io,1 );INIT_WORK (&map->ioworker.register_work, pvcalls_back_ioworker);
@@ -381,11 +381,16 @@ static struct sock_mapping *pvcalls_new_write_unlock_bh (&map->sock->sk->sk_callback_lock);return map; -out: -down (&fedata->socket_lock); -list_del (&map->list); -pvcalls_back_release_active (fedata->dev, fedata, map); -up (&fedata->socket_lock); + +out_unbind: +unbind_from_irqhandler (map->irq, map); +out_unmap_bytes: +xenbus_unmap_ring_vfree (fedata->dev, map->bytes); +out_unmap_ring: +xenbus_unmap_ring_vfree (fedata->dev, (void *)map->ring); +out_map: +sock_release (sock); +kfree (map);return NULL ; }
Greg Kroah-Hartman
maintainerPATCH 775/990 xen/pvcalls: destroy the per-socket workqueue on release
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 6b3feb6bfa9ac384f7a3ec25c40b9b4d3da96d25 upstream.
pvcalls_new_active_socket() gives every active socket its own ordered workqueue:
map->ioworker.wq = alloc_ordered_workqueue("pvcalls_io", 0);and nothing ever destroys it. pvcalls_back_release_active() flushes map->ioworker.register_work and frees map, but the workqueue and its pool_workqueues stay allocated, so a frontend leaks a workqueue per socket it connects and releases - a loop a guest can run as long as it likes.
Destroy it right after flush_work(): the IRQ is disabled and sk_data_ready restored by then, so nothing can queue new work, and the rings are still mapped while it drains - pvcalls_conn_back_read() reads map->ring and map->data, which xenbus_unmap_ring_vfree() takes away a few lines later. pvcalls_back_ioworker() does not take fedata->socket_lock, which the backend_disconnect() caller holds here - only the socket's own sk_receive_queue lock - so draining it from this point is safe; the flush_work() just above already has the same requirement.
Message-ID: <[email protected]>
--- drivers/xen/pvcalls-back.c | 1 + 1 file changed, 1 insertion(+)
drivers/xen/pvcalls-back.c +1 -0
@@ -452,6 +452,7 @@ static int pvcalls_back_release_active(satomic_set (&map->release,1 );flush_work (&map->ioworker.register_work); +destroy_workqueue (map->ioworker.wq);xenbus_unmap_ring_vfree (dev, map->bytes);xenbus_unmap_ring_vfree (dev, (void *)map->ring);
Greg Kroah-Hartman
maintainerPATCH 776/990 hwmon: (aht10) Fix update_interval overflow on 64-bit
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rupesh Majhi <[email protected]>
commit b5c5b67e02406fb48acf57cf2c30a570230fd6aa upstream.
On 64-bit, update_interval writes are clamped to LONG_MAX ms, but ms_to_ktime() overflows above 9223372036854 ms and the interval wraps. LONG_MAX becomes -1 ms, so every read starts a new measurement and update_interval reads back -1.
Clamp to INT_MAX like sht4x, so the limit is the same on all platforms.
--- drivers/hwmon/aht10.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/aht10.c +1 -1
@@ -229,7 +229,7 @@ static int aht10_read_values(struct aht1static ssize_t aht10_interval_write (struct aht10_data *data,long val) { - data->min_poll_interval =ms_to_ktime (clamp_val (val,2000 ,LONG_MAX )); + data->min_poll_interval =ms_to_ktime (clamp_val (val,2000 ,INT_MAX ));return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 777/990 hwmon: (gpio-fan) Fix runtime PM imbalance in probe and teardown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
commit 221b565a3316b1ba3a9bcd1f61238440207b3e00 upstream.
In gpio_fan_probe(), gpio_fan_stop() is registered conditionally as a devres action before runtime PM is initialized, while gpio_fan_stop() unconditionally calls pm_runtime_disable(). This breaks runtime PM disable_depth and usage_count invariants across several paths:
- On alarm-only devices without control GPIOs, gpio_fan_stop() is never registered, leaving pm_runtime_enable() unbalanced on unbind and triggering "Unbalanced pm_runtime_enable!" on subsequent binds.
- When control GPIOs are present and devm_add_action_or_reset(), hwmon registration, or fan_alarm_init() fails, gpio_fan_stop() runs before pm_runtime_enable(), incrementing disable_depth to 2 (leaving runtime PM permanently disabled on re-probe) and, if speed_index > 0, underflowing usage_count via pm_runtime_put_sync().
- If pm_runtime_resume_and_get() fails when speed_index > 0, it drops its reference while speed_index remains non-zero, causing gpio_fan_stop() to call pm_runtime_put_sync() and underflow usage_count.
- Registering the hwmon device before enabling runtime PM exposes sysfs attributes that can invoke set_fan_speed() before runtime PM state is initialized.
Initialize runtime PM upfront with pm_runtime_set_suspended() and devm_pm_runtime_enable(), remove pm_runtime_disable() from gpio_fan_stop(), and acquire the initial active runtime PM reference before registering gpio_fan_stop() and the hwmon device.
--- drivers/hwmon/gpio-fan.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-)
drivers/hwmon/gpio-fan.c +11 -13
@@ -531,8 +531,6 @@ static void gpio_fan_stop(void *data)mutex_lock (&fan_data->lock);set_fan_speed (data,0 );mutex_unlock (&fan_data->lock); - -pm_runtime_disable (fan_data->dev); }static int gpio_fan_probe (struct platform_device *pdev)
@@ -560,6 +558,11 @@ static int gpio_fan_probe(struct platforreturn dev_err_probe (dev,PTR_ERR (fan_data->supply),"Failed to get fan-supply" ); +pm_runtime_set_suspended (dev); + err =devm_pm_runtime_enable (dev); +if (err) +return err; +/* Configure control GPIOs if available. */ if (fan_data->gpios && fan_data->num_gpios >0 ) {if (!fan_data->speed || fan_data->num_speed <=1 )
@@ -567,6 +570,12 @@ static int gpio_fan_probe(struct platfor err =fan_ctrl_init (fan_data);if (err)return err; +/* If current GPIO state is active, mark RPM as active as well */ +if (fan_data->speed_index >0 ) { + err =pm_runtime_resume_and_get (dev); +if (err) +return err; + } err =devm_add_action_or_reset (dev, gpio_fan_stop, fan_data);if (err)return err;
@@ -587,17 +596,6 @@ static int gpio_fan_probe(struct platforreturn err; } -pm_runtime_set_suspended (&pdev->dev); -pm_runtime_enable (&pdev->dev); -/* If current GPIO state is active, mark RPM as active as well */ -if (fan_data->speed_index >0 ) { -int ret; - - ret =pm_runtime_resume_and_get (&pdev->dev); -if (ret) -return ret; - } -/* Optional cooling device register for Device tree platforms */ fan_data->cdev =devm_thermal_of_cooling_device_register (dev, np,"gpio-fan" , fan_data, &gpio_fan_cool_ops);
Greg Kroah-Hartman
maintainerPATCH 778/990 hwmon: (pmbus/mp2975) Get vout fault limits dynamically
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Felix Radensky <[email protected]>
commit 00944852275efd39706fe7b9ce75c28edde983eb upstream.
The over- and under-voltage fault limits of the tracking mode are relative to the voltage reference, which follows the VID/AVS requests issued to the device and therefore changes at runtime.
The driver reads the voltage reference once during probe and derives the limits from that snapshot, which the PMBus core caches in addition. As a result in2_crit and in2_lcrit reflect the operating point at probe, rather than the thresholds the device enforces. On systems where the device supplies the CPU core voltage, in2_crit was reported anywhere between 1.15V and 1.70V across identical systems, causing false over-voltage reports once the CPU voltage exceeded the value latched at probe.
Read the voltage reference and the over-voltage offset selector whenever a limit is requested, and mark both limits with pmbus_set_update(), so that the core does not cache them. The voltage reference is available on page 3 only. Let the core change the page, so that the page it caches matches the device, except for a single rail configuration, for which the core does not issue PAGE commands, and the page is changed directly.
With the selector read at runtime, a device configured with an unsupported selector no longer fails to probe. The OVP1 threshold, which does not depend on the selector, is reported for it instead, with a warning.
Clamp the under-voltage limit to zero, since the offset can exceed a low voltage reference, while a negative value would be reported as a read error.
--- drivers/hwmon/pmbus/mp2975.c | 207 +++++++++++++++++++++++-------------------- 1 file changed, 115 insertions(+), 92 deletions(-)
drivers/hwmon/pmbus/mp2975.c +115 -92
@@ -110,10 +110,7 @@ struct mp2975_data {int vout_scale;int max_phases[MP2975_PAGE_NUM ];int vid_step[MP2975_PAGE_NUM ]; -int vref[MP2975_PAGE_NUM ]; -int vref_off[MP2975_PAGE_NUM ];int vout_max[MP2975_PAGE_NUM ]; -int vout_ov_fixed[MP2975_PAGE_NUM ];int curr_sense_gain[MP2975_PAGE_NUM ]; };
@@ -466,12 +463,77 @@ static int mp2973_write_word_data(structreturn pmbus_write_word_data (client,0 ,PMBUS_SMBALERT_MASK , ret); } +/* +* Let the PMBus core change the page, so that the page it caches matches the +* device. The core does not issue PAGE commands for a single rail +* configuration, thus change the page directly then. +*/ +static int +mp2975_page_set (struct i2c_client *client,struct mp2975_data *data,int page) +{ +if (data->info.pages >1 ) +return pmbus_set_page (client, page,0xff ); + +return i2c_smbus_write_byte_data (client,PMBUS_PAGE , page); +} + +/* +* Voltage reference is available on page 3 only. The callers read a register +* of the rail through the core first, thus the core caches the rail page. +*/ +static int +mp2975_vref_get (struct i2c_client *client,struct mp2975_data *data,int page) +{ +int ret, vref; + + ret =mp2975_page_set (client, data,3 ); +if (ret <0 ) +return ret; + + vref =i2c_smbus_read_word_data (client, page ?MP2975_MFR_READ_VREF_R2 : +MP2975_MFR_READ_VREF_R1 ); + + ret =mp2975_page_set (client, data, page); +if (ret <0 ) +return ret; + +return (vref <0 ) ? vref : vref * data->vid_step[page]; +} + +static int +mp2975_ovp2_offset_get (int ovp_th_set) +{ +switch ((ovp_th_set &GENMASK (5 ,3 )) >>3 ) { +case 1 : +return 140 ; +case 2 : +return 220 ; +case 4 : +return 400 ; +default : +return -EINVAL ; + } +} + +static int +mp2975_vout_ovp2_get (struct i2c_client *client,struct mp2975_data *data, +int page,int vref_off) +{ +int vref; + + vref =mp2975_vref_get (client, data, page); +if (vref <0 ) +return vref; + +return vref +DIV_ROUND_CLOSEST (vref_off * data->vout_scale,10 ); +} +static int mp2975_read_word_data (struct i2c_client *client,int page,int phase,int reg) {const struct pmbus_driver_info *info =pmbus_get_driver_info (client);struct mp2975_data *data =to_mp2975_data (info); -int ret; +int ret, ovp1, vref_off, uv_off;switch (reg) {case PMBUS_OT_FAULT_LIMIT :
@@ -488,19 +550,35 @@ static int mp2975_read_word_data(structbreak ;case PMBUS_VOUT_OV_FAULT_LIMIT :/* -* Register provides two values for over-voltage protection -* threshold for fixed (ovp2) and tracking (ovp1) modes. The -* minimum of these two values is provided as over-voltage -* fault alarm. +* Device provides dual over-voltage protection. OVP1 is +* referred to the maximum reference voltage, while OVP2 is +* referred to the current voltage reference, which is changed +* at runtime. Protection is tripped by any of them, thus the +* minimum of the two is exposed as over-voltage fault alarm, +* and OVP2 is obtained on each read. */ ret =mp2975_read_word_helper (client, page, phase,MP2975_MFR_OVP_TH_SET , -GENMASK (2 ,0 )); +GENMASK (5 ,0 ));if (ret <0 )return ret; - ret =min_t (int, data->vout_max[page] +50 * (ret +1 ), - data->vout_ov_fixed[page]); + ovp1 = data->vout_max[page] +50 * ((ret &GENMASK (2 ,0 )) +1 ); + +/* OVP1 still applies if the OVP2 threshold is unknown. */ + vref_off =mp2975_ovp2_offset_get (ret); +if (vref_off <0 ) { +dev_warn_once (&client->dev, +"unsupported OVP2 selector, reporting OVP1 threshold\n" ); + ret = ovp1; +break ; + } + + ret =mp2975_vout_ovp2_get (client, data, page, vref_off); +if (ret <0 ) +return ret; + + ret =min_t (int, ovp1, ret);break ;case PMBUS_VOUT_UV_FAULT_LIMIT : ret = mp2975_read_word_helper(client, page, phase,
@@ -509,8 +587,17 @@ static int mp2975_read_word_data(structif (ret <0 )return ret; - ret =DIV_ROUND_CLOSEST (data->vref[page] *10 -50 * - (ret +1 ) * data->vout_scale,10 ); + uv_off =50 * (ret +1 ) * data->vout_scale; + + ret =mp2975_vref_get (client, data, page); +if (ret <0 ) +return ret; + +/* +* Offset can exceed the voltage reference, while a negative +* value would be reported as a read error. +*/ + ret =max_t (int,DIV_ROUND_CLOSEST (ret *10 - uv_off,10 ),0 );break ;case PMBUS_VIRT_READ_POUT_MAX : ret = mp2975_read_word_helper(client, page, phase,
@@ -760,60 +847,6 @@ mp2975_current_sense_gain_get(struct i2c }static int -mp2975_vref_get (struct i2c_client *client,struct mp2975_data *data, -struct pmbus_driver_info *info) -{ -int ret; - - ret =i2c_smbus_write_byte_data (client,PMBUS_PAGE ,3 ); -if (ret <0 ) -return ret; - -/* Get voltage reference value for rail 1. */ - ret =i2c_smbus_read_word_data (client,MP2975_MFR_READ_VREF_R1 ); -if (ret <0 ) -return ret; - - data->vref[0 ] = ret * data->vid_step[0 ]; - -/* Get voltage reference value for rail 2, if connected. */ -if (data->info.pages ==MP2975_PAGE_NUM ) { - ret =i2c_smbus_read_word_data (client,MP2975_MFR_READ_VREF_R2 ); -if (ret <0 ) -return ret; - - data->vref[1 ] = ret * data->vid_step[1 ]; - } -return 0 ; -} - -static int -mp2975_vref_offset_get (struct i2c_client *client,struct mp2975_data *data, -int page) -{ -int ret; - - ret =i2c_smbus_read_word_data (client,MP2975_MFR_OVP_TH_SET ); -if (ret <0 ) -return ret; - -switch ((ret &GENMASK (5 ,3 )) >>3 ) { -case 1 : - data->vref_off[page] =140 ; -break ; -case 2 : - data->vref_off[page] =220 ; -break ; -case 4 : - data->vref_off[page] =400 ; -break ; -default : -return -EINVAL ; - } -return 0 ; -} - -static int mp2975_vout_max_get (struct i2c_client *client,struct mp2975_data *data,struct pmbus_driver_info *info,int page) {
@@ -917,25 +950,6 @@ mp2975_vout_per_rail_config_get(struct i ret =mp2975_vout_max_get (client, data, info, i);if (ret <0 )return ret; - -/* Skip if reading Vref is unsupported */ -if (data->chip_id != mp2975) -continue ; - -/* Obtain voltage reference offsets. */ - ret =mp2975_vref_offset_get (client, data, i); -if (ret <0 ) -return ret; - -/* -* Set over-voltage fixed value. Thresholds are provided as -* fixed value, and tracking value. The minimum of them are -* exposed as over-voltage critical threshold. -*/ - data->vout_ov_fixed[i] = data->vref[i] + -DIV_ROUND_CLOSEST (data->vref_off[i] * - data->vout_scale, -10 ); }return 0 ;
@@ -1049,11 +1063,6 @@ static int mp2975_probe(struct i2c_clienif (ret)return ret; -/* Obtain voltage reference values. */ - ret =mp2975_vref_get (client, data, info); -if (ret) -return ret; -/* Obtain vout over-voltage scales. */ ret =mp2975_vout_ov_scale_get (client, data, info);if (ret <0 )
@@ -1070,7 +1079,21 @@ static int mp2975_probe(struct i2c_clienif (ret)return ret; -return pmbus_do_probe (client, info); + ret =pmbus_do_probe (client, info); +if (ret) +return ret; + +/* +* Vout over- and under-voltage fault limits are relative to the +* voltage reference, which is changed at runtime. Do not allow the +* PMBus core to cache them. +*/ +if (data->chip_id == mp2975) { +pmbus_set_update (client,PMBUS_VOUT_OV_FAULT_LIMIT , true); +pmbus_set_update (client,PMBUS_VOUT_UV_FAULT_LIMIT , true); + } + +return 0 ; }static const struct of_device_id mp2975_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 779/990 hwmon: (sy7636a) fix negative temperatures
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pablo Mazzini <[email protected]>
commit fc8519fab34e162b0c29dacccf73031820878917 upstream.
The thermistor readout is a signed 8-bit value in degrees Celsius.
--- drivers/hwmon/sy7636a-hwmon.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hwmon/sy7636a-hwmon.c +1 -1
@@ -29,7 +29,7 @@ static int sy7636a_read(struct device *dif (ret)return ret; - *temp = reg_val *1000 ; + *temp = (s8 )reg_val *1000 ;return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 780/990 hwmon: (scmi) Check channel config allocation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sudeep Holla <[email protected]>
commit a2996d892d0150d059d39c683d95d6fd7a37630a upstream.
scmi_hwmon_add_chan_info() can fail to allocate a channel's config array. Ignoring that error leaves a channel with a NULL config pointer in the hwmon chip info, which hwmon dereferences while registering the device.
Check the helper's return value and abort probe on failure.
--- drivers/hwmon/scmi-hwmon.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/hwmon/scmi-hwmon.c +7 -5
@@ -228,8 +228,8 @@ static int scmi_thermal_sensor_register(static int scmi_hwmon_probe (struct scmi_device *sdev) { -int i, idx;u16 nr_sensors; +int i, idx, ret;enum hwmon_sensor_types type;struct scmi_sensors *scmi_sensors;const struct scmi_sensor_info *sensor;
@@ -297,8 +297,12 @@ static int scmi_hwmon_probe(struct scmi_if (!nr_count[type])continue ; -scmi_hwmon_add_chan_info (scmi_hwmon_chan, dev, nr_count[type], - type, hwmon_attributes[type]); + ret =scmi_hwmon_add_chan_info (scmi_hwmon_chan, dev, + nr_count[type], type, + hwmon_attributes[type]); +if (ret) +return ret; + *ptr_scmi_ci++ = scmi_hwmon_chan++; scmi_sensors->info[type] =
@@ -333,8 +337,6 @@ static int scmi_hwmon_probe(struct scmi_return PTR_ERR (hwdev);for (i =0 ; i < nr_count_temp; i++) { -int ret; - sensor = *(scmi_sensors->info[hwmon_temp] + i);if (!sensor)continue ;
Greg Kroah-Hartman
maintainerPATCH 781/990 hwmon: (max31760) Fix the local temperature limit registers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 028ed93145d9be88eee670088ef13482b5d36c1a upstream.
temp2_max and temp2_crit use each other's registers, so reading them shows the local limits swapped and writing temp2_max changes the overtemperature (SHDN) threshold.
Use the high limit (0x0C) for temp2_max and the overtemperature limit (0x08) for temp2_crit.
--- drivers/hwmon/max31760.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +2 -2
@@ -27,8 +27,8 @@#define REG_TACH (ch) (0x52 + (ch) * 2)#define REG_TEMP_INPUT (ch) (0x56 + (ch) * 2) -#define REG_TEMP_MAX (ch) (0x06 + (ch) * 2) -#define REG_TEMP_CRIT (ch) (0x0A + (ch) * 2) +#define REG_TEMP_MAX (ch) ((ch) ? 0x0C : 0x06) +#define REG_TEMP_CRIT (ch) ((ch) ? 0x08 : 0x0A)#define TEMP11_FROM_REG (reg) ((reg) / 32 * 125)#define TEMP11_TO_REG (val) (DIV_ROUND_CLOSEST(clamp_val((val), -128000, \
Greg Kroah-Hartman
maintainerPATCH 782/990 hwmon: (max31760) Leave standby mode at probe
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 95bddc5252a4c0a2ed9d62e7e53a3461265d9603 upstream.
The driver never clears the standby bit (CR2_STBY) during probe. While max31760_resume() clears this bit on resume, probe only configured CR2_ALERTS.
If the chip was left in standby (for example, by boot firmware or a previously running OS before a warm reboot), it remains in standby:
temperature sensing, fan speed counting, and PWM output are halted. This occurs on the Samsung Galaxy XR, where the bootloader places the chip in standby during boot.
Clear CR2_STBY alongside setting CR2_ALERTS in probe.
--- drivers/hwmon/max31760.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/hwmon/max31760.c +3 -2
@@ -533,8 +533,9 @@ static int max31760_probe(struct i2c_clidev_set_drvdata (dev, state); -/* Set alert output to comparator mode */ - ret =regmap_set_bits (state->regmap,REG_CR2 ,CR2_ALERTS ); +/* Leave standby mode, set alert output to comparator mode */ + ret =regmap_update_bits (state->regmap,REG_CR2 ,CR2_STBY |CR2_ALERTS , +CR2_ALERTS );if (ret)return dev_err_probe (dev, ret,"cannot write register\n" );
Greg Kroah-Hartman
maintainerPATCH 783/990 hwmon: (max31760) Report 0 RPM before the first fan speed measurement
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stanislav Aleksandrov <[email protected]>
commit 33d58cbf2ab26bda81bc3052158d8b9867d5b9a6 upstream.
The tachometer count registers initialize to 0 until the first measurement cycle completes after power-on. To prevent division by zero, tach_to_rpm() clamped tach == 0 to 1, causing it to compute and report 3,000,000 RPM (60 * 100000 / 1 / 2).
Return 0 RPM when tach == 0 instead.
--- drivers/hwmon/max31760.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/hwmon/max31760.c +2 -1
@@ -68,8 +68,9 @@ static const int max31760_pwm_freq[] = {static int tach_to_rpm (u16 tach) { +/* The count is 0 until the first measurement */ if (tach ==0 ) - tach =1 ; +return 0 ;return 60 *100000 / tach /2 ; }
Greg Kroah-Hartman
maintainerPATCH 784/990 s390/dasd: Fix wrong free and refcount leak in build_check_tcw error path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stefan Haberland <[email protected]>
commit df56f7a6c20a5eb2794c0a7391bde50ba7c8c54b upstream.
dasd_eckd_build_check_tcw() allocates its request with dasd_fmalloc_request(), but its out_err path frees it with dasd_sfree_request(). The latter uses a different pool and therefor, leading to invalid pointer arithmetic and a crash.
Use the matching dasd_ffree_request() instead.
The same error path also leaves start_priv->count incremented without ever decrementing it again.
This leaks a permanent reference on every build failure. Decrement it before freeing the request.
--- drivers/s390/block/dasd_eckd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_eckd.c +2 -1
@@ -2594,7 +2594,8 @@ dasd_eckd_build_check_tcw(struct dasd_dereturn cqr; out_err: -dasd_sfree_request (cqr, startdev); + start_priv->count--; +dasd_ffree_request (cqr, startdev);return ERR_PTR (rc); }
Greg Kroah-Hartman
maintainerPATCH 785/990 s390/dasd: Dont trust userspace-supplied result field in format check
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Stefan Haberland <[email protected]>
commit 7cc2dda4f7aaf596c1796184649007151ff98f8d upstream.
BIODASDCHECKFMT used to copy the entire format_check_t struct from userspace, including the result/unit/rec/num_records/blksize/ key_length fields that are output fields only. dasd_eckd_format_evaluate_tracks() relies on cdata->result being zero to decide whether to apply an index correction (i--/pos--) after a successful check. A caller that pre-sets result to a non-zero value can suppress that correction, leaving pos advanced past the last valid entry; the (partially out-of-bounds) fmt_buffer[pos] fields are then copied back to userspace, leaking heap contents.
Only expect is an Input field; copy just that member in and zero the rest of cdata.
--- drivers/s390/block/dasd_ioctl.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/s390/block/dasd_ioctl.c +3 -1
@@ -304,7 +304,9 @@ static int dasd_ioctl_check_format(struc goto out_err; } -if (copy_from_user (&cdata, argp,sizeof (cdata))) { +/* copy only input fields, clear the rest */ +memset (&cdata,0 ,sizeof (cdata)); +if (copy_from_user (&cdata.expect, argp,sizeof (cdata.expect))) { rc = -EFAULT ; goto out_err; }
Greg Kroah-Hartman
maintainerPATCH 786/990 sched/deadline: Fix spurious -EPERM for migration-disabled tasks
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 6616bffa9b52da1338cf8bff9882404e02b9e361 upstream.
sched_setattr() can refuse to make a task SCHED_DEADLINE with -EPERM, even though the task's affinity covers the whole root domain. A retry can succeed, but the error blames an affinity the task does not have.
__sched_setscheduler() tests p->cpus_ptr, which is not always the task's affinity. When a task is scheduled out inside a migrate_disable() section, migrate_disable_switch() points p->cpus_ptr at the current CPU until migrate_enable(). On PREEMPT_RT every spinlock_t holder is in such a section, so ordinary kernel work opens the window. Elsewhere, seccomp filters run in one.
Test p->cpus_mask instead, which keeps the task's affinity and is what sched_getaffinity() reports. This should be safe because an admitted task's cpus_mask covers the root domain, so set_cpus_allowed_dl() moves no bandwidth when migrate_enable() restores p->cpus_ptr.
The following program, run as root, had 553679, 453720 and 424623 of its 1000000 requests refused on three boots of a 4-CPU PREEMPT_RT guest, and 236182, 217174 and 237183 without PREEMPT_RT. With this applied the count is 0, also with lockdep, and a task pinned to one CPU is still refused:
#define _GNU_SOURCE
#include <errno.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
#define REQUESTS 1000000
#define INSNS 300
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
}; static volatile int stop;
static volatile pid_t target;
static long set(struct attr a)
{
a.size = sizeof(a);
return syscall(SYS_sched_setattr, target, &a, 0);
}
static void *worker(void *arg)
{
struct sock_filter f[INSNS + 1];
struct sock_fprog prog = { .len = INSNS + 1, .filter = f };
int i; /* Reading the arguments keeps seccomp from caching the result */
for (i = 0; i < INSNS; i++)
f[i] = (struct sock_filter)
BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
offsetof(struct seccomp_data, args));
f[INSNS] = (struct sock_filter)
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW);
syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog);
target = syscall(SYS_gettid);
while (!stop)
syscall(SYS_getppid);
return arg;}
static void *hog(void *arg)
{
while (!stop)
;
return arg;
}
int main(void)
{
pthread_t t[9];
long refused = 0;
int i; pthread_create(&t[0], NULL, worker, NULL);
while (!target)
usleep(100);
for (i = 1; i < 9; i++)
pthread_create(&t[i], NULL, hog, NULL);
for (i = 0; i < REQUESTS; i++) {
/* SCHED_DEADLINE, 2us every 1s */
if (set((struct attr){ .policy = 6, .runtime = 2000,
.deadline = 1000000000,
.period = 1000000000 }) && errno == EPERM)
refused++;
set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
}
stop = 1;
for (i = 0; i < 9; i++)
pthread_join(t[i], NULL);
printf("%ld of %d requests refused\n", refused, REQUESTS);
return 0;}
An LLM helped find this bug and write this patch and its test.
--- kernel/sched/syscalls.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/syscalls.c +1 -1
@@ -638,7 +638,7 @@ change:* the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ -if (!cpumask_subset (span, p->cpus_ptr) || +if (!cpumask_subset (span, &p->cpus_mask) || rq->rd->dl_bw.bw ==0 ) { retval = -EPERM ; goto unlock;
Greg Kroah-Hartman
maintainerPATCH 787/990 sched/uclamp: Reject clamp values above SCHED_CAPACITY_SCALE
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 8127ec8458df29bd702db602473042ccb9e619b9 upstream.
sched_setattr() accepts sched_util_min and sched_util_max values that do not fit in uclamp_se::value. A single thread can do:
sched_setattr(max = 800) returns 0
sched_setattr(min = 0xfffffffe) returns 0
sched_getattr() min=2046 max=800
which leaves the minimum above both SCHED_CAPACITY_SCALE and the task's own maximum.
The range check in uclamp_validate() relies on the + 1 wrapping -1, the reset value, to 0:
if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
That only works for an unsigned type. util_min and util_max are int and SCHED_CAPACITY_SCALE is a long, so every negative value passes the check, and so does INT_MAX, whose + 1 wraps.
uclamp_se_set() then truncates what got through to the 11 bits of uclamp_se::value, but computes the bucket from the full value. A minimum of 0xfffff800 is stored as 0 in the top bucket, where uclamp_rq_max_value() takes it for the highest active clamp once a higher value leaves the rq. The rq clamp falls below what the remaining tasks requested, and emptying their bucket trips the WARN_ON_ONCE() in uclamp_rq_dec_id(), without any privilege:
WARNING: kernel/sched/core.c:1862 at dequeue_task+0x2a3/0x2b0, CPU#0: repro/126 Call Trace: __schedule+0x933/0x1320 schedule+0x36/0x100 do_nanosleep+0x61/0x190 hrtimer_nanosleep+0xb5/0x1d0
Make util_min and util_max unsigned int, so that -1 is the only value that wraps. The pair check below is unaffected, since it skips -1 explicitly and anything else is at most SCHED_CAPACITY_SCALE by then.
Requests that were only accepted because of this now fail with -EINVAL.
The following program triggers the warning when run by any user outside a child cpu cgroup. With this applied, its 0xfffff800 request fails with -EINVAL and the warning no longer appears:
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
uint32_t util_min, util_max;
};static volatile int stop;
static void set_min(uint32_t v)
{
/* KEEP_POLICY | KEEP_PARAMS | UTIL_CLAMP_MIN */
struct attr a = { .size = sizeof(a), .flags = 0x38, .util_min = v };syscall(SYS_sched_setattr, 0, &a, 0);
}
static void burn(long us)
{
struct timespec s, n; clock_gettime(CLOCK_MONOTONIC, &s);
do
clock_gettime(CLOCK_MONOTONIC, &n);
while ((n.tv_sec - s.tv_sec) * 1000000 +
(n.tv_nsec - s.tv_nsec) / 1000 < us);}
static void *bogus(void *arg)
{
set_min(0xfffff800);
while (!stop)
burn(1000);
return arg;
}
static void *worker(void *arg)
{
long v = (long)arg; set_min(v);
while (!stop) {
burn(v == 800 ? 300 : 1500);
usleep(100);
}
return arg;}
int main(void)
{
pthread_t t[3];
cpu_set_t c;
int i; CPU_ZERO(&c);
CPU_SET(0, &c);
sched_setaffinity(0, sizeof(c), &c);
pthread_create(&t[0], NULL, bogus, NULL);
usleep(50000);
pthread_create(&t[1], NULL, worker, (void *)500L);
pthread_create(&t[2], NULL, worker, (void *)800L);
sleep(15);
stop = 1;
for (i = 0; i < 3; i++)
pthread_join(t[i], NULL);
return 0;}
An LLM helped find the warning and write this patch and its tests.
--- kernel/sched/syscalls.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/sched/syscalls.c +2 -2
@@ -328,8 +328,8 @@ static inline void __setscheduler_dl_pi(static int uclamp_validate (struct task_struct *p,const struct sched_attr *attr) { -int util_min = p->uclamp_req[UCLAMP_MIN ].value; -int util_max = p->uclamp_req[UCLAMP_MAX ].value; +unsigned int util_min = p->uclamp_req[UCLAMP_MIN ].value; +unsigned int util_max = p->uclamp_req[UCLAMP_MAX ].value;if (attr->sched_flags &SCHED_FLAG_UTIL_CLAMP_MIN ) { util_min = attr->sched_util_min;
Greg Kroah-Hartman
maintainerPATCH 788/990 sched/core: Fix cpuset_mutex double unlock in __sched_setscheduler()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit f7141257dd67d4936f906a6cfd1d0007721f6898 upstream.
A sched_setattr() with SCHED_FLAG_KEEP_POLICY on a SCHED_DEADLINE task unlocks cpuset_mutex twice if the task's policy changes concurrently:
WARNING: bad unlock balance detected! 7.4.0-rc1 #1 Not tainted
-------------------------------------
repro/126 is trying to release lock (cpuset_mutex) at:
[<ffffffff9a17cacc>] __sched_setscheduler+0x9cc/0xc40 but there are no more locks to release! ... Call Trace: print_unlock_imbalance_bug.part.0+0xfb/0x110 lock_release+0x286/0x2e0 __mutex_unlock_slowpath+0x1a/0x400 __sched_setscheduler+0x9cc/0xc40 __x64_sys_sched_setattr+0xa3/0x1b0 do_syscall_64+0x106/0x5f0 entry_SYSCALL_64_after_hwframe+0x77/0x7f
__sched_setscheduler() samples p->policy before taking any lock, and restarts from the recheck label if p->policy differs under the rq lock. The restart drops cpuset_mutex but leaves cpuset_locked set, so a pass that no longer needs the mutex still unlocks it on its way out:
CPU 1 CPU 2
__sched_setscheduler(KEEP_POLICY)
policy = p->policy /* DEADLINE */
__sched_setscheduler(SCHED_OTHER)
p->policy = SCHED_OTHER
cpuset_locked = true
cpuset_lock()
rq = task_rq_lock(p)
oldpolicy != p->policy
cpuset_unlock()
goto recheck
/* no cpuset_lock() this time */
...
if (cpuset_locked)
cpuset_unlock()Without CONFIG_DEBUG_MUTEXES, or CONFIG_DEBUG_RT_MUTEXES on PREEMPT_RT, nothing warns. The second unlock still clears the owner field regardless of who holds the mutex, so another task can lose cpuset_mutex inside its critical section. Entering SCHED_DEADLINE needs CAP_SYS_NICE, but a racing caller that owns the task does not need it if it samples a policy other than SCHED_DEADLINE.
Clear cpuset_locked when dropping the mutex for the restart. This should be safe because the flag is only tested on the paths leaving the next pass, after that pass has set it again if it took the mutex.
The following program, run as root, reproduces the splat, which no longer appears with this applied. On PREEMPT_RT it crashes the kernel within seconds, which this also fixes:
#define _GNU_SOURCE
#include <pthread.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <unistd.h>
struct attr {
uint32_t size, policy;
uint64_t flags;
int32_t nice;
uint32_t prio;
uint64_t runtime, deadline, period;
}; static volatile int stop;
static volatile pid_t target;
static void set(struct attr a)
{
a.size = sizeof(a);
syscall(SYS_sched_setattr, target, &a, 0);
}
static void *sleeper(void *arg)
{
target = syscall(SYS_gettid);
while (!stop)
usleep(1000);
return arg;
}
static void *switcher(void *arg)
{
while (!stop) {
/* SCHED_DEADLINE, 2us every 1s */
set((struct attr){ .policy = 6, .runtime = 2000,
.deadline = 1000000000,
.period = 1000000000 });
set((struct attr){ .policy = 0 }); /* SCHED_OTHER */
}
return arg;
}
static void *racer(void *arg)
{
/* KEEP_POLICY | KEEP_PARAMS */
while (!stop)
set((struct attr){ .flags = 0x18 });
return arg;
}
int main(void)
{
pthread_t t[5];
int i; pthread_create(&t[0], NULL, sleeper, NULL);
while (!target)
usleep(100);
pthread_create(&t[1], NULL, switcher, NULL);
for (i = 2; i < 5; i++)
pthread_create(&t[i], NULL, racer, NULL);
sleep(30);
stop = 1;
for (i = 0; i < 5; i++)
pthread_join(t[i], NULL);
return 0;}
An LLM helped find the PREEMPT_RT crash and write this patch and its test.
--- kernel/sched/syscalls.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +3 -1
@@ -650,8 +650,10 @@ change:if (unlikely (oldpolicy !=-1 && oldpolicy != p->policy)) { policy = oldpolicy =-1 ;task_rq_unlock (rq, p, &rf); -if (cpuset_locked) +if (cpuset_locked) {cpuset_unlock (); + cpuset_locked = false; + } goto recheck; }
Greg Kroah-Hartman
maintainerPATCH 789/990 sctp: abort unordered partial delivery when its message is skipped
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 05852c8b70f2291a50bb3f740a66ce9caf9cb98d upstream.
When an I-FORWARD-TSN skips unordered messages on a stream, sctp_intl_skip() only aborts the stream's unordered partial delivery if the MID being delivered is lower than the skipped MID. If the skipped message is the one being partially delivered, partial delivery stays in
progress: no PARTIAL_DELIVERY_ABORTED is sent, and the next unordered message on the stream is delivered as the rest of the abandoned one.
Abort the partial delivery when the MID being delivered is at or below the skipped MID, as the ordered case already does.
Reproduced on an unmodified kernel with the uo_pd test of the sctp_ifwdtsn.sh selftest added later in this series; its partial delivery checks pass with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream_interleave.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/stream_interleave.c +1 -1
@@ -1255,7 +1255,7 @@ static void sctp_intl_skip(struct sctp_ustruct sctp_stream *stream = &ulpq->asoc->stream;if (flags &SCTP_FTSN_U_BIT ) { -if (sin->pd_mode_uo &&MID_lt (sin->mid_uo, mid)) { +if (sin->pd_mode_uo && !MID_lt (mid, sin->mid_uo)) { sin->pd_mode_uo =0 ;sctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 ,GFP_ATOMIC );
Greg Kroah-Hartman
maintainerPATCH 790/990 sctp: avoid requeueing pending control chunks
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 665b4149e91b781a71bce8637c3a4d7d64dba05f upstream.
The T4 and RE-CONFIG timeout handlers take a reference to their cached control chunk and submit it through SCTP_CMD_REPLY. A previous transmission can still be on the control outqueue when output is corked or suppressed, or when sctp_packet_transmit_chunk() could not append the chunk.
sctp_outq_tail() then adds the same list node a second time. Re-adding a non-tail entry can corrupt the list without being caught by the insertion-time list checks. A subsequent flush or association teardown can access an already freed chunk. The ASCONF path is reproducible by an unprivileged SCTP socket owner in a user/network namespace, with KASAN reporting a use-after-free in __sctp_outq_teardown().
Check sctp_chunk_pending() in both timeout handlers before taking the extra reference and issuing SCTP_CMD_REPLY. If the chunk is already linked, leave the existing entry for normal output processing. Keep the remaining timer and error-handling commands unchanged. This also covers RE-CONFIG retransmission after sctp_assoc_rm_peer() moves the request to another transport and starts its timer.
The issue was found by an LLM.
--- net/sctp/sm_statefuns.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-)
net/sctp/sm_statefuns.c +10 -6
@@ -1122,9 +1122,11 @@ enum sctp_disposition sctp_sf_send_reconreturn SCTP_DISPOSITION_DELETE_TCB ; } -sctp_chunk_hold (asoc->strreset_chunk); -sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , -SCTP_CHUNK (asoc->strreset_chunk)); +if (!sctp_chunk_pending (asoc->strreset_chunk)) { +sctp_chunk_hold (asoc->strreset_chunk); +sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , +SCTP_CHUNK (asoc->strreset_chunk)); + }sctp_add_cmd_sf (commands,SCTP_CMD_STRIKE ,SCTP_TRANSPORT (transport));return SCTP_DISPOSITION_CONSUME ;
@@ -6194,9 +6196,11 @@ enum sctp_disposition sctp_sf_t4_timer_e* chunk, it MUST be the same (including its serial number) as the last * ASCONF sent. */ -sctp_chunk_hold (asoc->addip_last_asconf); -sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , -SCTP_CHUNK (asoc->addip_last_asconf)); +if (!sctp_chunk_pending (asoc->addip_last_asconf)) { +sctp_chunk_hold (asoc->addip_last_asconf); +sctp_add_cmd_sf (commands,SCTP_CMD_REPLY , +SCTP_CHUNK (asoc->addip_last_asconf)); + }/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different * destination is selected, then the RTO used will be that of the new
Greg Kroah-Hartman
maintainerPATCH 791/990 sctp: fix ASCONF address change on single-homed hosts
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 5175b2fb34c77cf2cd56a290affa45412cb3a228 upstream.
Commit 9b2854f86f0b ("sctp: don't free the ASCONF's own transport in DEL-IP processing") refuses a DEL-IP of the transport the ASCONF was located by, so that a later wildcard DEL-IP cannot use it after free.
This also breaks the single-homed address change (RFC 5061 5.3.2). The host sends [Address Parameter L] [ADD-IP S] [DEL-IP L], the association is located by L, and DEL-IP L is now refused. The sender never gets an all-success ASCONF-ACK, keeps src_out_of_asoc_ok set and stops sending data, so the association stalls.
Fix the wildcard DEL-IP instead: look up the transport of the packet source rather than reusing asconf->transport. Both DEL-IP paths can now free asconf->transport, and chunks bundled after the ASCONF still use it, so point it at a surviving transport: the packet source for the wildcard delete, the primary path for a plain one.
Found by manual code inspection while reviewing a backport of commit 9b2854f86f0b; reproduced on a two-namespace single-homed renumber.
--- net/sctp/sm_make_chunk.c | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
net/sctp/sm_make_chunk.c +8 -9
@@ -3157,9 +3157,12 @@ static __be16 sctp_process_asconf_param(* packet MUST be deleted. */ if (af->is_any (&addr)) { -sctp_assoc_set_primary (asoc, asconf->transport); -sctp_assoc_del_nonprimary_peers (asoc, - asconf->transport); + peer =sctp_assoc_lookup_paddr (asoc, &asconf->source); +if (!peer) +return SCTP_ERROR_REQ_REFUSED ; +sctp_assoc_set_primary (asoc, peer); +sctp_assoc_del_nonprimary_peers (asoc, peer); + asconf->transport = peer;return SCTP_ERROR_NO_ERROR ; }
@@ -3172,13 +3175,9 @@ static __be16 sctp_process_asconf_param(if (!peer)return SCTP_ERROR_DNS_FAILED ; -/* Don't free asconf->transport; a later wildcard DEL-IP -* parameter reuses it. -*/ -if (peer == asconf->transport) -return SCTP_ERROR_REQ_REFUSED ; -sctp_assoc_rm_peer (asoc, peer); +if (asconf->transport == peer) + asconf->transport = asoc->peer.primary_path;break ;case SCTP_PARAM_SET_PRIMARY :/* ADDIP Section 4.2.4
Greg Kroah-Hartman
maintainerPATCH 792/990 sctp: fix I-FORWARD-TSN handling of fragments on other streams
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 5b9cfc6491a6e32e7315dc222992c7dbd5baa3e9 upstream.
sctp_report_iftsn() incorrectly frees queued I-DATA fragments in two cases. First, it drops any queued fragments with TSN less than or equal to the New Cumulative TSN. This prevents reconstruction of messages still being received on other streams and can fully block an ordered stream. Second, it calls sctp_intl_abort_pd() if the New Cumulative TSN equals the highest TSN seen. This check exists for association resets but can be inadvertently triggered by any I-FORWARD-TSN that arrives before data with a higher TSN, causing data loss and, if a partial delivery is in progress on an ordered stream, an aborted association.
Fix the first by freeing fragments from sctp_intl_skip() based on stream, U bit, and MID instead of TSN. Fix the second by moving the call to sctp_intl_abort_pd() from sctp_report_iftsn() to the corresponding reset handlers.
Observed in real use as unexpected message loss. Reproduced on an unmodified kernel with the sctp_ifwdtsn.sh selftest added later in this series, which passes with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream.c | 2 ++ net/sctp/stream_interleave.c | 32 +++++++++++--------------------- 2 files changed, 13 insertions(+), 21 deletions(-)
net/sctp/stream.c +2 -0
@@ -749,6 +749,7 @@ struct sctp_chunk *sctp_process_strreset*/ max_tsn_seen =sctp_tsnmap_get_max_tsn_seen (&asoc->peer.tsn_map); asoc->stream.si->report_ftsn (&asoc->ulpq, max_tsn_seen); + asoc->stream.si->abort_pd (&asoc->ulpq,GFP_ATOMIC );/* G1: Compute an appropriate value for the Receiver's Next TSN -- the * TSN that the peer should use to send the next DATA chunk. The
@@ -1028,6 +1029,7 @@ struct sctp_chunk *sctp_process_strresetLIST_HEAD (temp); asoc->stream.si->report_ftsn (&asoc->ulpq, mtsn); + asoc->stream.si->abort_pd (&asoc->ulpq,GFP_ATOMIC ); sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
net/sctp/stream_interleave.c +11 -21
@@ -1203,28 +1203,21 @@ static void sctp_report_fwdtsn(struct scsctp_ulpq_abort_pd (ulpq,GFP_ATOMIC ); } -static void sctp_intl_reasm_flushtsn (struct sctp_ulpq *ulpq,__u32 ftsn) +static void sctp_intl_reasm_flush_mid (struct sk_buff_head *reasm,__u16 sid, +__u32 mid) {struct sk_buff *pos, *tmp; - skb_queue_walk_safe(&ulpq->reasm, pos, tmp) { + skb_queue_walk_safe(reasm, pos, tmp) {struct sctp_ulpevent *event =sctp_skb2event (pos); -__u32 tsn = event->tsn; -if (TSN_lte (tsn, ftsn)) { -__skb_unlink (pos, &ulpq->reasm); -sctp_ulpevent_free (event); - } - } +if (event->stream < sid) +continue ; +if (event->stream > sid ||MID_lt (mid, event->mid)) +break ; - skb_queue_walk_safe(&ulpq->reasm_uo, pos, tmp) { -struct sctp_ulpevent *event =sctp_skb2event (pos); -__u32 tsn = event->tsn; - -if (TSN_lte (tsn, ftsn)) { -__skb_unlink (pos, &ulpq->reasm_uo); -sctp_ulpevent_free (event); - } +__skb_unlink (pos, reasm); +sctp_ulpevent_free (event); } }
@@ -1232,11 +1225,6 @@ static void sctp_report_iftsn(struct sct {/* Move the Cumulattive TSN Ack ahead. */ sctp_tsnmap_skip (&ulpq->asoc->peer.tsn_map, ftsn); -/* purge the fragmentation queue */ -sctp_intl_reasm_flushtsn (ulpq, ftsn); -/* abort only when it's for all data */ -if (ftsn ==sctp_tsnmap_get_max_tsn_seen (&ulpq->asoc->peer.tsn_map)) -sctp_intl_abort_pd (ulpq,GFP_ATOMIC ); }static void sctp_handle_fwdtsn (struct sctp_ulpq *ulpq,struct sctp_chunk *chunk)
@@ -1260,6 +1248,7 @@ static void sctp_intl_skip(struct sctp_usctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 ,GFP_ATOMIC ); } +sctp_intl_reasm_flush_mid (&ulpq->reasm_uo, sid, mid);return ; }
@@ -1271,6 +1260,7 @@ static void sctp_intl_skip(struct sctp_usctp_intl_stream_abort_pd (ulpq, sid, mid,0x0 ,GFP_ATOMIC ); } +sctp_intl_reasm_flush_mid (&ulpq->reasm, sid, mid);sctp_mid_skip (stream, in, sid, mid);sctp_intl_reap_ordered (ulpq, sid);
Greg Kroah-Hartman
maintainerPATCH 793/990 sctp: report the partially delivered MID in PARTIAL_DELIVERY_ABORTED
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tim Budding <[email protected]>
commit 3097fba868019924e92b8786ebd473992565f015 upstream.
When an I-FORWARD-TSN skips the message being partially delivered on a stream, sctp_intl_skip() passes the MID from the I-FORWARD-TSN to the PARTIAL_DELIVERY_ABORTED notification as pdapi_seq. That MID is the highest one skipped on the stream, so when more than one message is skipped, the notification names a later message instead of the one whose partial delivery was aborted.
Report the MID being partially delivered, sin->mid_uo or sin->mid, instead.
Reproduced on an unmodified kernel with the pdapi and pdapi_uo tests of the sctp_ifwdtsn.sh selftest added later in this series, which pass with this fix. Reproduction and fix done with AI assistance.
--- net/sctp/stream_interleave.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
net/sctp/stream_interleave.c +2 -2
@@ -1245,7 +1245,7 @@ static void sctp_intl_skip(struct sctp_uif (flags &SCTP_FTSN_U_BIT ) {if (sin->pd_mode_uo && !MID_lt (mid, sin->mid_uo)) { sin->pd_mode_uo =0 ; -sctp_intl_stream_abort_pd (ulpq, sid, mid,0x1 , +sctp_intl_stream_abort_pd (ulpq, sid, sin->mid_uo,0x1 ,GFP_ATOMIC ); }sctp_intl_reasm_flush_mid (&ulpq->reasm_uo, sid, mid);
@@ -1257,7 +1257,7 @@ static void sctp_intl_skip(struct sctp_uif (sin->pd_mode) { sin->pd_mode =0 ; -sctp_intl_stream_abort_pd (ulpq, sid, mid,0x0 ,GFP_ATOMIC ); +sctp_intl_stream_abort_pd (ulpq, sid, sin->mid,0x0 ,GFP_ATOMIC ); }sctp_intl_reasm_flush_mid (&ulpq->reasm, sid, mid);
Greg Kroah-Hartman
maintainerPATCH 794/990 sctp: reset stored flag for each association
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
commit 173712d868eb20628ad82deb07f6829a68a9e064 upstream.
sctp_send_asconf_del_ip() walks every association on an endpoint. The stored flag records that the current association took the single-homed deferral path and therefore did not allocate an ASCONF chunk. It is currently scoped to the whole function. Once one association sets it, later eligible multihomed associations allocate chunks but skip sctp_send_asconf(), leaking each chunk and its skb.
Reset stored for every association so only an association taking the deferral path skips transmission. In an A/B kmemleak test, the vulnerable kernel reported 210 leaked objects from this call path and the fixed kernel reported none.
--- net/sctp/socket.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sctp/socket.c +1 -1
@@ -808,7 +808,6 @@ static int sctp_send_asconf_del_ip(strucstruct sctp_sockaddr_entry *saddr;int i;int retval =0 ; -int stored =0 ; chunk =NULL ; sp =sctp_sk (sk);
@@ -821,6 +820,7 @@ static int sctp_send_asconf_del_ip(struc __func__, sk, addrs, addrcnt);list_for_each_entry (asoc, &ep->asocs, asocs) { +int stored =0 ;if (!asoc->peer.asconf_capable)continue ;
Greg Kroah-Hartman
maintainerPATCH 795/990 LoongArch: kexec_file: Fix a modified cmdline leak
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jinjie Ruan <[email protected]>
commit b7000844b374a1ab75f0cc561f1d4d321cd6eeb0 upstream.
machine_kexec_prepare() copies it to KEXEC_CMDLINE_ADDR and overwrites the pointer. Free the heap buffer after the copy here.
--- arch/loongarch/kernel/machine_kexec.c | 2 ++ 1 file changed, 2 insertions(+)
arch/loongarch/kernel/machine_kexec.c +2 -0
@@ -14,6 +14,7 @@#include <linux/mm.h> #include <linux/of_fdt.h> #include <linux/reboot.h> +#include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/task_stack.h>
@@ -56,6 +57,7 @@ int machine_kexec_prepare(struct kimage *kimage)*/ memcpy ((void *)KEXEC_CMDLINE_ADDR , (void *)kimage->arch.cmdline_ptr,strlen ((char *)kimage->arch.cmdline_ptr) +1 ); +kfree ((void *)kimage->arch.cmdline_ptr); kimage->arch.cmdline_ptr = (unsigned long )KEXEC_CMDLINE_ADDR ; }else {/* Find the command line */
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 796/990 LoongArch: kexec_file: Fix elf_headers memory leak in retry loop
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jinjie Ruan <[email protected]>
commit 065dd1636abef6b9962fd5af82accac69850bbe8 upstream.
A retry allocates new elf headers and overwrites image->elf_headers, leaking the previous buffer. Free it before assigning here.
--- arch/loongarch/kernel/machine_kexec_file.c | 4 ++++ 1 file changed, 4 insertions(+)
arch/loongarch/kernel/machine_kexec_file.c +4 -0
@@ -182,6 +182,10 @@ int load_other_segments(struct kimage *ivfree (headers); goto out_err; } + +if (unlikely (image->elf_headers)) +vfree (image->elf_headers); + image->elf_headers = headers; image->elf_load_addr = kbuf.mem; image->elf_headers_sz = headers_sz;
Greg Kroah-Hartman
maintainerPATCH 797/990 LoongArch: Restore KFENCE pages through DMW on resume
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Rapoport (Microsoft) <[email protected]>
commit 40d7a3e63c3d88b43e9115d23d9937dd506bbd02 upstream.
With KFENCE enabled, resume from hibernation triggers KFENCE reports while swsusp_asm_resume() copies the image pages, for example:
BUG: KFENCE: use-after-free write in swsusp_asm_resume+0x20/0x94
Use-after-free write at 0x00000000a57ee925 (in kfence-#254):
swsusp_asm_resume+0x20/0x94 hibernation_restore+0x128/0x1a0 load_image_and_restore+0x6c/0xc8 software_resume+0x240/0x260 do_one_initcall+0x68/0x200 kernel_init_freeable+0x26c/0x304 kernel_init+0x20/0x134 ret_from_kernel_thread+0x24/0x1d0 ret_from_kernel_thread_asm+0xc/0x98
During resume from hibernation, the image pages that occupy physical pages used by the restore kernel are first loaded into free pages and then, as the very last step, swsusp_asm_resume() copies them to their final location pointed to by pbe->orig_address, which the hibernation core sets to page_address() of the page in the restore kernel.
The early KFENCE pool is allocated from memblock and normally occupies the same physical pages in the restore kernel and in the image kernel, so these pages are usually copied by swsusp_asm_resume().
The KFENCE pool is remapped into the KFENCE area above vm_map_base and set_page_address() adjusts page->virtual so that page_address() returns the page-table mapped alias rather than the DMW virtual address of the pool pages.
Hence, pbe->orig_address of KFENCE pages points to that alias and swsusp_asm_resume() writes them through the page tables. But:
* the copy loop overwrites the kernel page tables, so a TLB refill for the KFENCE alias may use a partially restored page table
* the KFENCE pool pages that are protected in the restore kernel fault in the middle of the copy
Convert pbe->orig_address to DMW addresses before starting the copy.
--- arch/loongarch/power/hibernate.c | 6 ++++++ 1 file changed, 6 insertions(+)
arch/loongarch/power/hibernate.c +6 -0
@@ -59,6 +59,12 @@ extern int swsusp_asm_resume(void);int swsusp_arch_resume (void ) { +#ifdef CONFIG_KFENCE +struct pbe *pbe; + +for (pbe = restore_pblist; pbe; pbe = pbe->next) + pbe->orig_address =__va (virt_to_phys (pbe->orig_address)); +#endif /* Avoid TLB mismatch during and after kernel resume */ local_flush_tlb_all ();return swsusp_asm_resume ();
Greg Kroah-Hartman
maintainerPATCH 798/990 LoongArch: KVM: Propagate real error code in kvm_pch_pic_create()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tao Cui <[email protected]>
commit 20f3bf3d3dce16f43b82881293586ce7d73982b6 upstream.
The real error code of kvm_setup_default_irq_routing() is replaced by kvm_pch_pic_create() with a fixed -ENOMEM. Return the actual error code, as kvm_eiointc_create() already does; while the kvm_ipi_create() case is fixed separately by "Return the actual error code in kvm_ipi_create()" (Chaithanya Lagisetty).
--- arch/loongarch/kvm/intc/pch_pic.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kvm/intc/pch_pic.c +1 -1
@@ -436,7 +436,7 @@ static int kvm_pch_pic_create(struct kvm ret =kvm_setup_default_irq_routing (kvm);if (ret) -return -ENOMEM ; +return ret; s =kzalloc (sizeof (struct loongarch_pch_pic ),GFP_KERNEL );if (!s)
Greg Kroah-Hartman
maintainerPATCH 799/990 LoongArch: KVM: Reject repeated PCH-PIC CTRL_INIT
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tao Cui <[email protected]>
commit 422e532809572ba1043192bf6a0c653bc68b3140 upstream.
KVM_DEV_LOONGARCH_PCH_PIC_CTRL_INIT has no guard against repeated
invocation: every call overwrites pch_pic_base and registers the same kvm_io_device on the MMIO bus at the new base address, while the kvm_pch_pic_destroy() unregisters only one bus range. After a repeated init, MMIO to the stale ranges computes its register offset against the new base address and silently reads 0 / drops writes, and the leftover bus entries persist until the VM is destroyed.
Reject repeated initialization with -EEXIST, using the initialized state of the kvm_io_device as the indicator. The check, the MMIO base update and the bus registration are serialized by slots_lock, and the real registration error is propagated instead of being replaced with -EFAULT. On a registration failure the base addr and the device state are rolled back so that a retry can start over.
--- arch/loongarch/kvm/intc/pch_pic.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-)
arch/loongarch/kvm/intc/pch_pic.c +12 -3
@@ -273,16 +273,25 @@ static int kvm_pch_pic_init(struct kvm_dstruct kvm_io_device *device;struct loongarch_pch_pic *s = dev->kvm->arch.pch_pic; - s->pch_pic_base = addr; device = &s->device; +mutex_lock (&kvm->slots_lock); +if (s->device.ops) { + ret = -EEXIST ; + goto out; + } + s->pch_pic_base = addr;/* init device by pch pic writing and reading ops */ kvm_iodevice_init (device, &kvm_pch_pic_ops); -mutex_lock (&kvm->slots_lock);/* register pch pic device */ ret =kvm_io_bus_register_dev (kvm,KVM_MMIO_BUS , addr,PCH_PIC_SIZE , device); +if (ret) { + s->pch_pic_base =0 ; + s->device.ops =NULL ; + } +out:mutex_unlock (&kvm->slots_lock); -return (ret <0 ) ? -EFAULT :0 ; +return ret; }/* used by user space to get or set pch pic registers */
Greg Kroah-Hartman
maintainerPATCH 800/990 tracing/perf: Clear stop state in perf_trace_add()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paolo Bertinetti <[email protected]>
commit fb3f6b21b04f1e8b8982e90e9bf62db9f0dcb5e4 upstream.
Since commit 18dbcbfabfff ("perf: Fix the POLL_HUP delivery breakage"), __perf_event_overflow() stops the event with pmu->stop() and disables it when the PERF_EVENT_IOC_REFRESH limit is reached. When userspace re-arms the event with PERF_EVENT_IOC_REFRESH, the event is enabled again and pmu->add() is called with PERF_EF_START.
perf_trace_add() sets PERF_HES_STOPPED when PERF_EF_START is missing, but never clears it. The flag set by pmu->stop() stays, and perf_tp_event_match() drops every later hit. A tracepoint, kprobe or uprobe event re-armed this way delivers only its first overflow. This breaks self-profilers such as async-profiler, and the "Event re-armed with PERF_EVENT_IOC_REFRESH" perf test fails:
1000 events, count 1, 1 overflows (1 POLL_HUP), re-arm errno 0 Tracepoint event : FAILED!
Set the state from PERF_EF_START on every add, as perf_swevent_add() does.
--- kernel/trace/trace_event_perf.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/trace/trace_event_perf.c +1 -2
@@ -354,8 +354,7 @@ int perf_trace_add(struct perf_event *p_struct trace_event_call *tp_event = p_event->tp_event;struct hw_perf_event *hwc = &p_event->hw; -if (!(flags &PERF_EF_START )) - p_event->hw.state =PERF_HES_STOPPED ; + hwc->state = (flags &PERF_EF_START ) ?0 :PERF_HES_STOPPED ;if (is_sampling_event (p_event)) { hwc->last_period = hwc->sample_period;
Greg Kroah-Hartman
maintainerPATCH 801/990 tracing/uprobes: Fix memory leak of tail in __trace_uprobe_create()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit c15120853eebbda98f3fe1f1e59370439c6c4447 upstream.
When generating a default event name in __trace_uprobe_create(), tail is allocated with kstrdup() without __free(kfree). If the subsequent kmalloc() for buf fails, the function returns -ENOMEM immediately and leaks tail.
Declare tail with __free(kfree) so it is automatically freed on all exit paths.
--- kernel/trace/trace_uprobe.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/trace/trace_uprobe.c +1 -2
@@ -666,7 +666,7 @@ static int __trace_uprobe_create(int arg }if (!event) { -char *tail; + char *tail __free(kfree) = NULL;char *ptr; tail =kstrdup (kbasename (filename),GFP_KERNEL );
@@ -682,7 +682,6 @@ static int __trace_uprobe_create(int arg goto fail_mem;snprintf (buf,MAX_EVENT_NAME_LEN ,"%c_%s_0x%lx" ,'p' , tail, offset); event = buf; -kfree (tail); } argc -=2 ;
Greg Kroah-Hartman
maintainerPATCH 802/990 tracing/eprobe: Fix 1-byte signed field fetch in get_event_field()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit a0f836eea463d4c468edb58eedb03911c9c0791d upstream.
Because the kernel is built with -funsigned-char, plain 'char' is unsigned on all architectures. Reading 1-byte signed trace event fields via *(char *)addr in get_event_field() therefore zero-extends instead of sign-extending negative s8 values.
Use explicit fixed-width integer types (s8/u8, s16/u16, s32/u32) when reading event fields.
--- kernel/trace/trace_eprobe.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
kernel/trace/trace_eprobe.c +6 -6
@@ -328,21 +328,21 @@ get_event_field(struct fetch_insn *code,switch (field->size) {case 1 :if (field->is_signed) - val = *(char *)addr; + val = *(s8 *)addr;else - val = *(unsigned char *)addr; + val = *(u8 *)addr;break ;case 2 :if (field->is_signed) - val = *(short *)addr; + val = *(s16 *)addr;else - val = *(unsigned short *)addr; + val = *(u16 *)addr;break ;case 4 :if (field->is_signed) - val = *(int *)addr; + val = *(s32 *)addr;else - val = *(unsigned int *)addr; + val = *(u32 *)addr;break ;default :if (field->size ==sizeof (long )) {
Greg Kroah-Hartman
maintainerPATCH 803/990 tracing/eprobe: Disallow attaching eprobes to fprobe events
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 92d9fa0ed69e1f724feed908bd0a462a42df4b88 upstream.
Event probes (eprobes) are not allowed to attach to other dynamic probe events (kprobes, uprobes, and eprobes) to avoid recursive probe chains and lifecycle dependencies. However, when fprobe events were introduced, TRACE_EVENT_FL_FPROBE was omitted from the exclusion mask in find_and_get_event(), allowing eprobes to attach to fprobe and tprobe events.
Exclude TRACE_EVENT_FL_FPROBE events in find_and_get_event().
--- kernel/trace/trace_eprobe.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/trace/trace_eprobe.c +2 -1
@@ -756,7 +756,8 @@ find_and_get_event(const char *system, c (TRACE_EVENT_FL_IGNORE_ENABLE |TRACE_EVENT_FL_KPROBE |TRACE_EVENT_FL_UPROBE | - TRACE_EVENT_FL_EPROBE)) +TRACE_EVENT_FL_EPROBE | + TRACE_EVENT_FL_FPROBE)) continue;if (!tp_event->class->system ||strcmp (system, tp_event->class->system))
Greg Kroah-Hartman
maintainerPATCH 804/990 tracing/probes: Check enabled and busy state before unlinking sibling probes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit f1d9b7a3fe99b4228acdbab3c744c29f7ffe86ef upstream.
When a multiprobe event is enabled or referenced (for example, by an eprobe, trigger, or open tracefs file) and a user attempts to delete the event or one of its probes via dynamic_events, checking trace_probe_has_sibling() before the enabled and busy checks allows the first probe to be unlinked and freed while the event is still active, only returning -EBUSY on the last sibling probe. For uprobe events, unlinking and freeing an enabled sibling probe without unregistering its uprobe_consumer also causes a use-after-free.
Ensure all four probe types (kprobe, fprobe, uprobe, and eprobe) verify that the event is neither enabled nor busy before unlinking any sibling probe.
--- kernel/trace/trace_eprobe.c | 12 ++++++++---- kernel/trace/trace_fprobe.c | 8 ++++---- kernel/trace/trace_kprobe.c | 8 ++++---- kernel/trace/trace_uprobe.c | 8 ++++++-- 4 files changed, 22 insertions(+), 14 deletions(-)
kernel/trace/trace_eprobe.c +8 -4
@@ -89,14 +89,18 @@ static int eprobe_dyn_event_show(structstatic int unregister_trace_eprobe (struct trace_eprobe *ep) { -/* If other probes are on the event, just unregister eprobe */ -if (trace_probe_has_sibling (&ep->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&ep->tp))return -EBUSY ; +/* If there's a reference to the dynamic event */ +if (trace_event_dyn_busy (trace_probe_event_call (&ep->tp))) +return -EBUSY ; + +/* If other probes are on the event, just unregister eprobe */ +if (trace_probe_has_sibling (&ep->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (trace_probe_unregister_event_call (&ep->tp))return -EBUSY ;
kernel/trace/trace_fprobe.c +4 -4
@@ -857,10 +857,6 @@ static void __unregister_trace_fprobe(st/* Unregister a trace_probe and probe_event */ static int unregister_trace_fprobe (struct trace_fprobe *tf) { -/* If other probes are on the event, just unregister fprobe */ -if (trace_probe_has_sibling (&tf->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&tf->tp))return -EBUSY ;
@@ -869,6 +865,10 @@ static int unregister_trace_fprobe(strucif (trace_event_dyn_busy (trace_probe_event_call (&tf->tp)))return -EBUSY ; +/* If other probes are on the event, just unregister fprobe */ +if (trace_probe_has_sibling (&tf->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (unregister_fprobe_event (tf))return -EBUSY ;
kernel/trace/trace_kprobe.c +4 -4
@@ -538,10 +538,6 @@ static void __unregister_trace_kprobe(st/* Unregister a trace_probe and probe_event */ static int unregister_trace_kprobe (struct trace_kprobe *tk) { -/* If other probes are on the event, just unregister kprobe */ -if (trace_probe_has_sibling (&tk->tp)) - goto unreg; -/* Enabled event can not be unregistered */ if (trace_probe_is_enabled (&tk->tp))return -EBUSY ;
@@ -550,6 +546,10 @@ static int unregister_trace_kprobe(strucif (trace_event_dyn_busy (trace_probe_event_call (&tk->tp)))return -EBUSY ; +/* If other probes are on the event, just unregister kprobe */ +if (trace_probe_has_sibling (&tk->tp)) + goto unreg; +/* Will fail if probe is being used by ftrace or perf */ if (unregister_kprobe_event (tk))return -EBUSY ;
kernel/trace/trace_uprobe.c +6 -2
@@ -396,13 +396,17 @@ static int unregister_trace_uprobe(struc {int ret; -if (trace_probe_has_sibling (&tu->tp)) - goto unreg; +/* Enabled event can not be unregistered */ +if (trace_probe_is_enabled (&tu->tp)) +return -EBUSY ;/* If there's a reference to the dynamic event */ if (trace_event_dyn_busy (trace_probe_event_call (&tu->tp)))return -EBUSY ; +if (trace_probe_has_sibling (&tu->tp)) + goto unreg; + ret =unregister_uprobe_event (tu);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 805/990 tracing/probes: Enable newly appended probe when target event is enabled
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 72d3a5cb0cd7335553549aaffecc683e3ecc0c43 upstream.
Unlike kprobe events, fprobe and uprobe events only register their underlying probes when the trace event is enabled. When a new probe is appended to an existing multiprobe fprobe or uprobe event that is already enabled, the appended probe is linked into the event's probe list without being registered.
As a result, the newly appended probe never fires until the event is disabled and re-enabled. Moreover, disabling an fprobe event calls unregister_fprobe() on the unregistered fprobe, and opening or closing a perf event on an enabled uprobe event dereferences a NULL tu->uprobe in uprobe_apply().
Register and enable the newly appended fprobe or uprobe immediately when the target event is already enabled.
--- kernel/trace/trace_fprobe.c | 14 ++++------- kernel/trace/trace_uprobe.c | 56 +++++++++++++++++++++++++++++--------------- 2 files changed, 43 insertions(+), 27 deletions(-)
kernel/trace/trace_fprobe.c +6 -8
@@ -937,7 +937,10 @@ static int append_trace_fprobe_event(strif (ret)return ret; - ret =trace_fprobe_verify_target (tf); +if (trace_probe_is_enabled (&tf->tp)) + ret =__register_trace_fprobe (tf); +else + ret =trace_fprobe_verify_target (tf);if (ret)trace_probe_unlink (&tf->tp);else
@@ -1522,13 +1525,8 @@ static int disable_trace_fprobe(struct ttrace_probe_clear_flag (tp,TP_FLAG_PROFILE );if (!trace_probe_is_enabled (tp)) { -list_for_each_entry (tf,trace_probe_probe_list (tp), tp.list) { -unregister_fprobe (&tf->fp); -if (tf->tuser) { -tracepoint_user_put (tf->tuser); - tf->tuser =NULL ; - } - } +list_for_each_entry (tf,trace_probe_probe_list (tp), tp.list) +__unregister_trace_fprobe (tf); } out:
kernel/trace/trace_uprobe.c +37 -19
75 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 806/990 tracing/probes: Fix missing BTF kind checks in char pointer/array helpers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit c1e2c63e65421068566db3dde44dfd4fe7adb46d upstream.
In struct btf_type, the type ID and byte size share a union, and only BTF_KIND_INT types are followed by a 32-bit integer encoding word. Because btf_type_is_char_ptr() and btf_type_is_char_array() do not verify that the outer type is BTF_KIND_PTR or that the resolved element type is a non-NULL BTF_KIND_INT before inspecting it, non-pointer BTF types can have their byte size misinterpreted as a BTF type ID, and arrays of non-integer types read out-of-bounds or misinterpret trailing BTF metadata as BTF_INT_* encoding bits.
Validate the BTF type kinds and NULL pointers before reading inner type metadata in both helpers.
--- kernel/trace/trace_probe.c | 8 ++++++++ 1 file changed, 8 insertions(+)
kernel/trace/trace_probe.c +8 -0
@@ -356,6 +356,9 @@ static bool btf_type_is_char_ptr(structconst struct btf_type *real_type;u32 intdata; +if (BTF_INFO_KIND (type->info) !=BTF_KIND_PTR ) +return false; + real_type =btf_type_skip_modifiers (btf, type->type,NULL );if (!real_type)return false;
@@ -380,6 +383,11 @@ static bool btf_type_is_char_array(struc array = (const struct btf_array *)(type +1 ); real_type =btf_type_skip_modifiers (btf, array->type,NULL ); +if (!real_type) +return false; + +if (BTF_INFO_KIND (real_type->info) !=BTF_KIND_INT ) +return false; intdata =btf_type_int (real_type);return !(BTF_INT_ENCODING (intdata) &BTF_INT_SIGNED )
Greg Kroah-Hartman
maintainerPATCH 807/990 tracing/probes: Fix user-space dereference string array store type
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 2721573e6c6faaba2e31f352f2c02ec5f3ecf5e9 upstream.
When finalizing a string array argument (e.g. +0u(%reg):string[N]), finalize_fetch_insn() advances the instruction pointer to a new slot for the store operation before checking whether the preceding operation was FETCH_OP_UDEREF. As a result, user-space dereference string arrays with type "string" emit FETCH_OP_ST_STRING (kernel memory read) instead of FETCH_OP_ST_USTRING.
Check for FETCH_OP_UDEREF before advancing the instruction pointer.
--- kernel/trace/trace_probe.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
kernel/trace/trace_probe.c +4 -2
@@ -1484,6 +1484,8 @@ static int finalize_fetch_insn(struct fe/* Store operation */ if (parg->type->is_string) { +bool is_uderef; +/* Check bad combination of the type and the last fetch_insn. */ if (!strcmp (parg->type->name,"symstr" )) { if (code->op != FETCH_OP_REG && code->op != FETCH_OP_STACK &&
@@ -1503,6 +1505,7 @@ static int finalize_fetch_insn(struct fe } } + is_uderef = (code->op ==FETCH_OP_UDEREF ); if (!strcmp(parg->type->name, "symstr") || (code->op == FETCH_OP_IMM || code->op == FETCH_OP_COMM || code->op == FETCH_OP_DATA) || code->op == FETCH_OP_TP_ARG ||
@@ -1523,8 +1526,7 @@ static int finalize_fetch_insn(struct fe }/* If op == DEREF, replace it with STRING */ -if (!strcmp (parg->type->name,"ustring" ) || - code->op ==FETCH_OP_UDEREF ) +if (!strcmp (parg->type->name,"ustring" ) || is_uderef) code->op =FETCH_OP_ST_USTRING ;else if (!strcmp (parg->type->name,"symstr" )) code->op =FETCH_OP_ST_SYMSTR ;
Greg Kroah-Hartman
maintainerPATCH 808/990 tracing/probes: Reject array count on non-dereference string sources
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Masami Hiramatsu (Google) <[email protected]>
commit 0941144ebeaf3ce46c80711f00e935921eb28b21 upstream.
The runtime array loop (FETCH_OP_LP_ARRAY) for string types requires a preceding memory dereference instruction so it can advance the pointer address on each iteration. Non-dereference string sources such as $comm, immediate strings, and eprobe event fields cannot be indexed as pointer arrays, but finalize_fetch_insn() still accepts an array count on them and emits an invalid FETCH_OP_LP_ARRAY sequence.
Reject string array counts when the preceding operation is not a memory dereference.
--- kernel/trace/trace_probe.c | 6 ++++++ 1 file changed, 6 insertions(+)
kernel/trace/trace_probe.c +6 -0
@@ -1518,6 +1518,12 @@ static int finalize_fetch_insn(struct fe* For the symstr, it doesn't need to dereference, thus * it just get the value. */ +if (parg->count && (code->op !=FETCH_OP_DEREF && + code->op !=FETCH_OP_UDEREF )) { +trace_probe_log_err (ctx->offset + type_offset, +BAD_STRING ); +return -EINVAL ; + } code++;if (code->op !=FETCH_OP_NOP ) {trace_probe_log_err (ctx->offset,TOO_MANY_OPS );
Greg Kroah-Hartman
maintainerPATCH 809/990 wifi: ath12k: assign device id from the WSI index
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benoit Masson <[email protected]>
commit 81986a81f09fae73926c7c44863b335880269c90 upstream.
Devices of a hardware group are added to ag->ab[] in PCI probe completion order (ab->device_id = ag->num_probed++), which is not stable across boots. The wiphy radio array is built from ag->ab[] and the wiphy device is taken from its first entry, so the wiphy sysfs path and the mapping of radio indices to bands change on every boot.
Persisted wireless configurations reference radios by index (e.g. OpenWrt/hostapd "radio0"), so such a configuration attaches to a random band at each boot. This affects any multi-chip group with single-band radios, e.g. TP-Link Archer BE800 (three QCN9274/QCN9224 radios in one group).
Store each ab in ag->ab[] at its wsi_info.index, which is derived from the device tree WSI ring and is therefore deterministic. ag->num_probed remains the group device counter. The unassign path is unchanged, it already indexes ag->ab[] by ab->device_id.
--- drivers/net/wireless/ath/ath12k/core.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/wireless/ath/ath12k/core.c +2 -1
@@ -1943,7 +1943,8 @@ exit: goto invalid_group; } - ab->device_id = ag->num_probed++; + ag->num_probed++; + ab->device_id = wsi->index; ag->ab[ab->device_id] = ab; ab->ag = ag;
Greg Kroah-Hartman
maintainerPATCH 810/990 wifi: ath9k_htc: do not start ANI before the first channel is set
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mehmet Fide <[email protected]>
commit dda63dd136ba2bc3b297079b190ac81a0aea40ae upstream.
ath9k_htc_add_interface() starts ANI for the first AP interface, before any channel is configured. The per-channel calibration data only gets attached by the first ath9k_htc_set_channel() that is not a fast channel change, and that same call cancels the ANI work a few milliseconds after add_interface, so normally the work never runs.
When the bring-up stalls for more than the 100 ms ANI poll interval in between, it does run, and ar9002_hw_per_calibration() records the IQ calibration result in the calibration data that does not exist yet:
Unable to handle kernel NULL pointer dereference at virtual address 00000008 PC is at ar9002_hw_calibrate+0x1f8/0x570 [ath9k_hw] Workqueue: phy0 ath9k_htc_ani_work [ath9k_htc]
Seen about once per thousand AP starts with an AR9271 on a Cortex-A5 board that starts hostapd while still booting; a 500 ms delay after add_interface reproduces it on every start. The crashed work never completes, so the next cancel_delayed_work_sync() blocks for good.
Drop the start; it has nothing to calibrate against and is cancelled anyway. The TSF adjust bit that shared its condition is now set for every AP interface, which is harmless: the next reset applies it. The next patch starts ANI once the interface beacons.
--- drivers/net/wireless/ath/ath9k/htc_drv_main.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/net/wireless/ath/ath9k/htc_drv_main.c +1 -4
@@ -1098,11 +1098,8 @@ static int ath9k_htc_add_interface(strucath9k_htc_set_opmode (priv); -if ((priv->ah->opmode ==NL80211_IFTYPE_AP ) && - !test_bit (ATH_OP_ANI_RUN , &common->op_flags)) { +if (priv->ah->opmode ==NL80211_IFTYPE_AP )ath9k_hw_set_tsfadjust (priv->ah, true); -ath9k_htc_start_ani (priv); - }ath_dbg (common,CONFIG ,"Attach a VIF of type: %d at idx: %d\n" , vif->type, avp->index);
Greg Kroah-Hartman
maintainerPATCH 811/990 wifi: cfg80211: release rejected nontransmitted BSS reference
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit f3c45d5b741a7d7586e639c2f55d2557029f2e1a upstream.
Repeated MBSSID reports without an SSID can leak BSS entries outside the scan cache, where the BSS entry limit cannot account for them.
__cfg80211_bss_update() returns a referenced BSS. If adding it to the transmitting BSS list fails, unlinking drops the cache reference, but the caller reference is lost when res is cleared.
Release the caller reference before discarding the unlinked BSS.
LLM assistance was used to find the bug and review.
--- net/wireless/scan.c | 1 + 1 file changed, 1 insertion(+)
net/wireless/scan.c +1 -0
@@ -2437,6 +2437,7 @@ cfg80211_inform_single_bss_data(struct wif (cfg80211_add_nontrans_list (data->source_bss, &res->pub)) {if (__cfg80211_unlink_bss (rdev, res)) { rdev->bss_generation++; +bss_ref_put (rdev, res); res =NULL ; } }
Greg Kroah-Hartman
maintainerPATCH 812/990 wifi: cfg80211: preserve mesh A-MSDU lengths when adding mesh headers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 9083da9dd3223068237395432323b407012aec1f upstream.
A malformed mesh A-MSDU subframe with a declared payload length near 65535 bytes can pass validation against a much shorter aggregate.
ieee80211_amsdu_subframe_length() adds the mesh control length to the declared length in a u16, and ieee80211_is_valid_amsdu() stores the result in a u16 local. The sum therefore wraps before either walker compares it with the remaining aggregate length. The decomposer then splits and delivers the malformed aggregate instead of rejecting it.
Keep the computed length in unsigned int in both the helper and the validator so oversized subframes cannot wrap.
LLM assistance was used to find the bug and review.
--- net/wireless/util.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
net/wireless/util.c +3 -3
@@ -745,12 +745,12 @@ __ieee80211_amsdu_copy(struct sk_buff *sreturn frame; } -static u16 +static unsigned int ieee80211_amsdu_subframe_length (void *field,u8 mesh_flags,u8 hdr_type) {__le16 *field_le = field;__be16 *field_be = field; -u16 len; +unsigned int len;if (hdr_type >=2 ) len =le16_to_cpu (*field_le);
@@ -772,7 +772,7 @@ bool ieee80211_is_valid_amsdu(struct sk___be16 len;u8 mesh_flags; } hdr; -u16 len; +unsigned int len;if (sizeof (hdr) > remaining)return false;
Greg Kroah-Hartman
maintainerPATCH 813/990 wifi: cfg80211: dont truncate the merged MBSSID profile length
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wahid Khan <[email protected]>
commit 3ea152f3f77eeffc37b2f4423688b4df9136f90c upstream.
cfg80211_parse_mbssid_data() keeps the length of a non-transmitted BSSID profile in a u8. cfg80211_merge_profile() returns a size_t, and it concatenates a profile that is split over several Multiple BSSID elements, so the merged length can be well above 255 even though every single sub-element is at most 255 bytes long.
The value is then cut to its low 8 bits. A 300 byte profile is handled as a 44 byte one: the elements after the cut are lost from the generated non-transmitted BSS, and if the Multiple BSSID-Index element lies past the cut the BSS is dropped altogether. Any AP in range can send such a profile.
The multi-link code further down in the same file already uses a signed size type for the profile length. Do the same here, cfg80211_find_ie() and cfg80211_gen_new_ie() take a size_t anyway.
--- net/wireless/scan.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/wireless/scan.c +1 -1
@@ -2580,7 +2580,7 @@ cfg80211_parse_mbssid_data(struct wiphyif (elem->data[0 ] <1 || (int )elem->data[0 ] >8 )continue ;for_each_element (sub, elem->data +1 , elem->datalen -1 ) { -u8 profile_len; +size_t profile_len;if (sub->id !=0 || sub->datalen <4 ) {/* not a valid BSS profile */
Greg Kroah-Hartman
maintainerPATCH 814/990 wifi: mac80211: fix use-after-free when MLO link setup is rolled back
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit a155ef2ef79531c139244289c5b8f15c05d16a0e upstream.
Rolling back an MLO link addition can free link containers while RCU readers still hold pointers to them. ieee80211_vif_update_links() publishes new links before checking for duplicate addresses and calling drv_change_vif_links(). If either fails, it restores the old pointers and frees the new containers without waiting for readers.
During a non-MLO to MLO transition, the published link 0 replaces the deflink, so existing link 0 users can acquire the new container. Readers such as ieee80211_csa_finish() and ieee80211_obss_color_collision_notify() can also queue work embedded in the link. If they queue after ieee80211_link_stop() cancels that work, it remains queued when the container is freed.
Wait for RCU readers after restoring the old pointers and before stopping the new links, so their work is queued before it is cancelled.
--- net/mac80211/link.c | 2 ++ 1 file changed, 2 insertions(+)
net/mac80211/link.c +2 -0
@@ -385,6 +385,8 @@ static int ieee80211_vif_update_links(stmemcpy (sdata->link, old_data,sizeof (old_data));memcpy (sdata->vif.link_conf, old,sizeof (old));ieee80211_set_vif_links_bitmaps (sdata, old_links, dormant_links); +/* drain RCU readers before cancelling work they may queue */ +synchronize_rcu ();for_each_set_bit (link_id, &add,IEEE80211_MLD_MAX_NUM_LINKS ) {ieee80211_link_debugfs_remove (&links[link_id]->data);ieee80211_link_stop (&links[link_id]->data);
Greg Kroah-Hartman
maintainerPATCH 815/990 wifi: mac80211: drain link readers before stopping removed links
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 745f5d04395dfc4c311f443c7c04ccb00c436984 upstream.
Removing an MLO link can leave work queued on its link container after the container is freed.
ieee80211_tear_down_links() stops each link before the RCU grace period. A reader that fetched the link earlier can therefore queue work after ieee80211_link_stop() has canceled it. ieee80211_request_smps() and ieee80211_csa_finish() can both reach this window.
Record each removed link while removing its keys and debugfs state. Wait for RCU readers, then stop the recorded links so cancellation includes work queued by those readers. Free the detached keys after the grace period as before.
LLM assistance was used to find the bug and review.
--- net/mac80211/link.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
net/mac80211/link.c +7 -1
@@ -179,6 +179,7 @@ struct link_container {static void ieee80211_tear_down_links (struct ieee80211_sub_if_data *sdata,struct link_container **links,u16 mask) { +struct ieee80211_link_data *stop[IEEE80211_MLD_MAX_NUM_LINKS ] = {};struct ieee80211_link_data *link;LIST_HEAD (keys);unsigned int link_id;
@@ -193,11 +194,16 @@ static void ieee80211_tear_down_links(stcontinue ;ieee80211_remove_link_keys (link, &keys);ieee80211_link_debugfs_remove (link); -ieee80211_link_stop (link); + stop[link_id] = link; } +/* drain RCU readers before cancelling work they may queue */ synchronize_rcu (); +for (link_id =0 ; link_id <IEEE80211_MLD_MAX_NUM_LINKS ; link_id++) +if (stop[link_id]) +ieee80211_link_stop (stop[link_id]); +ieee80211_free_key_list (sdata->local, &keys); }
Greg Kroah-Hartman
maintainerPATCH 816/990 wifi: mac80211: recheck injected headers after removing FCS
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 339564c7ac50464695dfed847f89d118f4cc1dc5 upstream.
Injecting a short frame with IEEE80211_RADIOTAP_F_FCS on a monitor interface can pass a truncated 802.11 header to transmit handlers.
ieee80211_monitor_start_xmit() validates the linear 802.11 header before parsing radiotap. Radiotap parsing then removes the four-byte FCS without rechecking the remaining header length. Software encryption can subtract the larger header length and pass the resulting negative length as an unsigned size.
Recheck the required linear header length after pulling the radiotap header and before handing the frame to the transmit path. Require at least addr1, which the transmit path reads even for extension frames whose header is shorter.
LLM assistance was used to find the bug and review.
--- net/mac80211/tx.c | 6 ++++++ 1 file changed, 6 insertions(+)
net/mac80211/tx.c +6 -0
@@ -2552,6 +2552,12 @@ netdev_tx_t ieee80211_monitor_start_xmit/* remove the injection radiotap header */ skb_pull (skb, len_rthdr); +/* FCS removal may have shortened the 802.11 header. */ + hdrlen =max_t (int, hdrlen, + offsetofend(struct ieee80211_hdr, addr1)); +if (skb_headlen (skb) < hdrlen) + goto fail_rcu; +ieee80211_xmit (sdata,NULL , skb);rcu_read_unlock ();
Greg Kroah-Hartman
maintainerPATCH 817/990 wifi: mac80211: recheck the IBSS station limit before insertion
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit f7670bcdf650b37551a9c5d084521f877d939f11 upstream.
Frames from successive unknown IBSS peers can make the deferred worker install more than 128 stations.
The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.
Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.
LLM assistance was used to find the bug and review.
--- net/mac80211/ibss.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ibss.c +6 -2
@@ -1656,8 +1656,12 @@ void ieee80211_ibss_work(struct ieee8021list_del (&sta->list);spin_unlock_bh (&ifibss->incomplete_lock); -ieee80211_ibss_finish_sta (sta); -rcu_read_unlock (); +if (sdata->local->num_sta >=IEEE80211_IBSS_MAX_STA_ENTRIES ) { +sta_info_free (sdata->local, sta); + }else { +ieee80211_ibss_finish_sta (sta); +rcu_read_unlock (); + }spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 818/990 wifi: mac80211: recheck the OCB station limit before insertion
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 27e29a077b4887d0e0a813337f8b7e06bd020c81 upstream.
Frames from successive unknown OCB peers can make the deferred worker install more than 128 stations.
The receive path checks local->num_sta before allocating each station, but pending stations are not included in that count. Several allocations can therefore pass before the worker inserts any of them, and the worker then drains the list without rechecking the limit.
Recheck the installed-station limit in the worker under the wiphy mutex and free entries that no longer fit.
LLM assistance was used to find the bug and review.
--- net/mac80211/ocb.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/ocb.c +6 -2
@@ -136,8 +136,12 @@ void ieee80211_ocb_work(struct ieee80211list_del (&sta->list);spin_unlock_bh (&ifocb->incomplete_lock); -ieee80211_ocb_finish_sta (sta); -rcu_read_unlock (); +if (sdata->local->num_sta >=IEEE80211_OCB_MAX_STA_ENTRIES ) { +sta_info_free (sdata->local, sta); + }else { +ieee80211_ocb_finish_sta (sta); +rcu_read_unlock (); + }spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 819/990 wifi: mac80211: reject invalid EHT guard intervals in airtime estimates
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 582edbdbc5d288bd128b54935738fe38f15c8c29 upstream.
An invalid EHT guard interval can select the wrong airtime group and, at 320 MHz, read beyond airtime_mcs_groups.
Guard interval 3 advances EHT_GROUP_IDX() into the next bandwidth group at narrower widths. With one spatial stream and 320 MHz, it evaluates to 264, one past the 264-entry table. RX rate parsing rejects the value, but the common TX-status validator has no EHT check and last_rate_info can carry it to the airtime helper.
Reject values above NL80211_RATE_INFO_EHT_GI_3_2 in the helper. This also protects exported ieee80211_calc_rx_airtime() callers that do not pass through the TX-status validator.
LLM assistance was used to find the bug and review.
--- net/mac80211/airtime.c | 2 ++ 1 file changed, 2 insertions(+)
net/mac80211/airtime.c +2 -0
@@ -550,6 +550,8 @@ static u32 ieee80211_get_rate_duration(s group =HE_GROUP_IDX (streams, status->he_gi, bw);break ;case RX_ENC_EHT : +if (status->eht.gi >NL80211_RATE_INFO_EHT_GI_3_2 ) +return 0 ; streams = status->nss; idx = status->rate_idx; group =EHT_GROUP_IDX (streams, status->eht.gi, bw);
Greg Kroah-Hartman
maintainerPATCH 820/990 wifi: mac80211: restore dormant links when link updates fail
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit bb22f3b2d8f8a2f883944f24678cf84e18b162e8 upstream.
A failed MLO link update can leave the interface with the requested dormant-links bitmap instead of its previous one. This can disable active links or trigger a bitmap warning during rollback.
The error path restores the old valid-links bitmap but passes the new dormant_links argument to ieee80211_set_vif_links_bitmaps().
Save the old dormant bitmap before changing link state and use it when restoring the old configuration.
LLM assistance was used to find the bug and review.
--- net/mac80211/link.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/mac80211/link.c +2 -1
@@ -284,6 +284,7 @@ static int ieee80211_vif_update_links(st {u16 old_links = sdata->vif.valid_links;u16 old_active = sdata->vif.active_links; +u16 old_dormant = sdata->vif.dormant_links;unsigned long add = new_links & ~old_links;unsigned long rem = old_links & ~new_links;unsigned long sta_rem = rem;
@@ -390,7 +391,7 @@ static int ieee80211_vif_update_links(st/* restore config */ memcpy (sdata->link, old_data,sizeof (old_data));memcpy (sdata->vif.link_conf, old,sizeof (old)); -ieee80211_set_vif_links_bitmaps (sdata, old_links, dormant_links); +ieee80211_set_vif_links_bitmaps (sdata, old_links, old_dormant);/* drain RCU readers before cancelling work they may queue */ synchronize_rcu ();for_each_set_bit (link_id, &add,IEEE80211_MLD_MAX_NUM_LINKS ) {
Greg Kroah-Hartman
maintainerPATCH 821/990 wifi: mac80211: fix use-after-free on TTLM disconnect
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johannes Berg <[email protected]>
commit 4af2b71495a3f12196cbea1c9a502c62ada867be upstream.
If ieee80211_process_adv_ttlm() disconnects, and some other changes were also detected in the beacon, the link update to the driver is still done, leading to use-after-free. Fix this by returning, like other functions, whether or not the update was accepted by the function.
--- net/mac80211/mlme.c | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-)
net/mac80211/mlme.c +14 -11
@@ -7127,15 +7127,15 @@ static void ieee80211_tid_to_link_map_wo sdata->u.mgd.ttlm_info.switch_time =0 ; } -static void ieee80211_process_adv_ttlm (struct ieee80211_sub_if_data *sdata, -struct ieee802_11_elems *elems, -u64 beacon_ts) +static bool ieee80211_process_adv_ttlm (struct ieee80211_sub_if_data *sdata, +struct ieee802_11_elems *elems, +u64 beacon_ts) {u8 i;int ret;if (!ieee80211_vif_is_mld (&sdata->vif)) -return ; +return true;if (!elems->ttlm_num) {if (sdata->u.mgd.ttlm_info.switch_time) {
@@ -7153,14 +7153,14 @@ static void ieee80211_process_adv_ttlm(s 0);if (ret) {sdata_info (sdata,"Failed setting valid/dormant links\n" ); -return ; +return true; }ieee80211_vif_cfg_change_notify (sdata,BSS_CHANGED_MLD_VALID_LINKS ); }memset (&sdata->u.mgd.ttlm_info,0 ,sizeof (sdata->u.mgd.ttlm_info)); -return ; +return true; }for (i =0 ; i < elems->ttlm_num; i++) {
@@ -7172,7 +7172,7 @@ static void ieee80211_process_adv_ttlm(sif (res) {__ieee80211_disconnect (sdata); -return ; +return false; }if (ttlm_info.switch_time) {
@@ -7197,7 +7197,7 @@ static void ieee80211_process_adv_ttlm(s* switch the AP will continue to announce it anyway. */ if (delay >IEEE80211_ADV_TTLM_ST_UNDERFLOW ) -return ; +return true; delay_usec =ieee80211_tu_to_usec (delay);
@@ -7216,9 +7216,11 @@ static void ieee80211_process_adv_ttlm(swiphy_hrtimer_work_queue (sdata->local->hw.wiphy, &sdata->u.mgd.ttlm_work,us_to_ktime (delay_usec)); -return ; +return true; } } + +return true; } static void
@@ -7738,8 +7740,9 @@ static void ieee80211_rx_mgmt_beacon(str elems->cisco_dtpc_elem);ieee80211_ml_reconfiguration (sdata, elems); -ieee80211_process_adv_ttlm (sdata, elems, -le64_to_cpu (mgmt->u.beacon.timestamp)); +if (!ieee80211_process_adv_ttlm (sdata, elems, +le64_to_cpu (mgmt->u.beacon.timestamp))) + goto free; apply:ieee80211_link_info_change_notify (sdata, link, changed);
Greg Kroah-Hartman
maintainerPATCH 822/990 wifi: mac80211: bound pending IBSS station allocations
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 3029ca2112d7bee4d3e3eadd02decdb3eddb9485 upstream.
Delaying the IBSS station worker while frames arrive from new peers can retain an unbounded number of station allocations.
The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.
Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when disconnect frees the pending list.
LLM assistance was used to find the bug and review.
--- net/mac80211/ibss.c | 13 ++++++++++++- net/mac80211/ieee80211_i.h | 1 + 2 files changed, 13 insertions(+), 1 deletion(-)
net/mac80211/ibss.c +12 -1
@@ -691,6 +691,7 @@ static void ieee80211_ibss_disconnect(stspin_unlock_bh (&ifibss->incomplete_lock);sta_info_free (local, sta); +atomic_dec (&ifibss->incomplete_sta_count);spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
@@ -1207,9 +1208,18 @@ void ieee80211_ibss_rx_no_sta(struct iee band = chanctx_conf->def.chan->band;rcu_read_unlock (); +if (!atomic_add_unless (&ifibss->incomplete_sta_count,1 , +IEEE80211_IBSS_MAX_STA_ENTRIES )) { +net_info_ratelimited ("%s: No room for a new IBSS STA entry %pM\n" , + sdata->name, addr); +return ; + } + sta =sta_info_alloc (sdata, addr,GFP_ATOMIC ); -if (!sta) +if (!sta) { +atomic_dec (&ifibss->incomplete_sta_count);return ; + }/* make sure mandatory rates are always added */ sband = local->hw.wiphy->bands[band];
@@ -1662,6 +1672,7 @@ void ieee80211_ibss_work(struct ieee8021ieee80211_ibss_finish_sta (sta);rcu_read_unlock (); } +atomic_dec (&ifibss->incomplete_sta_count);spin_lock_bh (&ifibss->incomplete_lock); }spin_unlock_bh (&ifibss->incomplete_lock);
net/mac80211/ieee80211_i.h +1 -0
@@ -668,6 +668,7 @@ struct ieee80211_if_ibss {spinlock_t incomplete_lock;struct list_head incomplete_stations; +atomic_t incomplete_sta_count;enum {IEEE80211_IBSS_MLME_SEARCH ,
Greg Kroah-Hartman
maintainerPATCH 823/990 wifi: mac80211: bound pending OCB station allocations
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit ee1a5e92dba0a98cabe476c780e3af4f0ab88b27 upstream.
Delaying the OCB station worker while frames arrive from new peers can retain an unbounded number of station allocations.
The receive-side limit counts installed stations, while new allocations wait on incomplete_stations until process context inserts them. The list lock does not cover the interval between allocation and list insertion.
Reserve one of 128 pending slots per interface before allocation. Release the reservation on allocation failure, after the worker inserts or frees the station, and when leave frees the pending list.
LLM assistance was used to find the bug and review.
--- net/mac80211/ieee80211_i.h | 2 ++ net/mac80211/ocb.c | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-)
net/mac80211/ieee80211_i.h +2 -0
@@ -683,6 +683,7 @@ struct ieee80211_if_ibss {* @wrkq_flags: OCB deferred task action * @incomplete_lock: delayed STA insertion lock * @incomplete_stations: list of STAs waiting for delayed insertion +* @incomplete_sta_count: pending entries and reserved allocations * @joined: indication if the interface is connected to an OCB network */ struct ieee80211_if_ocb {
@@ -691,6 +692,7 @@ struct ieee80211_if_ocb {spinlock_t incomplete_lock;struct list_head incomplete_stations; +atomic_t incomplete_sta_count;bool joined; };
net/mac80211/ocb.c +12 -1
@@ -70,9 +70,18 @@ void ieee80211_ocb_rx_no_sta(struct ieee band = chanctx_conf->def.chan->band;rcu_read_unlock (); +if (!atomic_add_unless (&ifocb->incomplete_sta_count,1 , +IEEE80211_OCB_MAX_STA_ENTRIES )) { +net_info_ratelimited ("%s: No room for a new OCB STA entry %pM\n" , + sdata->name, addr); +return ; + } + sta =sta_info_alloc (sdata, addr,GFP_ATOMIC ); -if (!sta) +if (!sta) { +atomic_dec (&ifocb->incomplete_sta_count);return ; + }/* Add only mandatory rates for now */ sband = local->hw.wiphy->bands[band];
@@ -142,6 +151,7 @@ void ieee80211_ocb_work(struct ieee80211ieee80211_ocb_finish_sta (sta);rcu_read_unlock (); } +atomic_dec (&ifocb->incomplete_sta_count);spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
@@ -225,6 +235,7 @@ int ieee80211_ocb_leave(struct ieee80211spin_unlock_bh (&ifocb->incomplete_lock);sta_info_free (local, sta); +atomic_dec (&ifocb->incomplete_sta_count);spin_lock_bh (&ifocb->incomplete_lock); }spin_unlock_bh (&ifocb->incomplete_lock);
Greg Kroah-Hartman
maintainerPATCH 824/990 gpio: aspeed: Clear only the acked lines G4 interrupt status
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Billy Tsai <[email protected]>
commit 5d362564bd2982def7e80d7f1e756a97440c7adb upstream.
The G4 interrupt status registers are write-1-to-clear: writing 0 to a bit has no effect and writing 1 clears that line's status flag. aspeed_gpio_irq_ack() clears a line's status through aspeed_g4_reg_bit_set(), which reads the bank's status register, sets the line's bit and writes the whole value back. That write clears every interrupt pending in the 32-line bank, not just the acked one.
aspeed_gpio_irq_handler() reads each bank's status register once and dispatches the lines that were set. If another line in the same bank latches an edge after that read and before an ack in the bank, the ack clears its status and the handler is never called for it, so the edge is lost.
Write only the line's own bit when clearing the interrupt status on G4.
--- drivers/gpio/gpio-aspeed.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
drivers/gpio/gpio-aspeed.c +11 -0
@@ -1045,6 +1045,17 @@ static void aspeed_g4_reg_bit_set(structvoid __iomem *addr =aspeed_gpio_g4_bank_reg (gpio, bank, reg);u32 temp; +/* +* The interrupt status register is write-1-to-clear. Write only this +* line's bit so that interrupts pending on the other lines of the bank +* stay latched. +*/ +if (reg == reg_irq_status) { +if (val) +iowrite32 (GPIO_BIT (offset), addr); +return ; + } +if (reg == reg_val) temp = gpio->dcache[GPIO_BANK (offset)];else
Greg Kroah-Hartman
maintainerPATCH 825/990 gpio: aspeed: Preserve the pending G7 interrupt status on control writes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Billy Tsai <[email protected]>
commit 18cc1d1ad94df8a6760fff2617d3d6923550cba0 upstream.
On G7 each line has its own control register, and its interrupt status bit (bit 12) is write-1-to-clear. aspeed_g7_reg_bit_set() updates a field by reading the control register, replacing that field and writing the value back. When the line's interrupt is pending, the status bit reads as 1 and is written back as 1, so updating an unrelated field such as the interrupt enable, trigger type, direction or debounce selection also clears the pending interrupt.
Mask out the status bit when composing the value to write, so it is written as 1 only when the status field itself is being set to ack the interrupt.
--- drivers/gpio/gpio-aspeed.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/gpio/gpio-aspeed.c +7 -1
@@ -1172,7 +1172,13 @@ static void aspeed_g7_reg_bit_set(structu32 write_val;if (mask) { - write_val = (ioread32 (addr) & ~(mask)) |field_prep (mask, val); +/* +* The interrupt status bit is write-1-to-clear. Keep it zero +* unless it is the field being written, so that updating any +* other field leaves a pending interrupt latched. +*/ + write_val =ioread32 (addr) & ~(mask |GPIO_G7_CTRL_IRQ_STS ); + write_val |=field_prep (mask, val);iowrite32 (write_val, addr); } }
Greg Kroah-Hartman
maintainerPATCH 826/990 gpio: brcmstb: fix UAF after IRQ domain setup failure
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
commit baa14758afb3e2828de1f76511edc1de50216f39 upstream.
When devm_request_irq() fails in brcmstb_gpio_irq_setup(), the error path removes the IRQ domain but leaves priv->irq_domain non-NULL.
The probe error path subsequently calls brcmstb_gpio_remove(), which checks priv->irq_domain and attempts to access the already-freed domain through irq_find_mapping(). It also attempts to remove the domain again, resulting in a use-after-free and potentially further memory corruption.
Set priv->irq_domain to NULL after removing it so that the common cleanup path skips the already-freed IRQ domain.
This issue was found by our static analysis tool under development.
--- drivers/gpio/gpio-brcmstb.c | 1 + 1 file changed, 1 insertion(+)
drivers/gpio/gpio-brcmstb.c +1 -0
@@ -486,6 +486,7 @@ static int brcmstb_gpio_irq_setup(struct out_free_domain:irq_domain_remove (priv->irq_domain); + priv->irq_domain =NULL ;return err; }
Greg Kroah-Hartman
maintainerPATCH 827/990 gpio: rockchip: Fix debounce arithmetic for GPIO v2
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cunhao Lu <[email protected]>
commit 13467fd6998f5da4f5b4f172f1af3d9c48d5de8f upstream.
The debounce interval calculations use unsigned long operands. On 32-bit systems, the numerator used to calculate the maximum interval overflows before division, while multiplying the requested interval by the clock rate overflows before it is assigned to a u64. A zero debounce clock rate also causes division by zero.
Use 64-bit arithmetic for both calculations and reject a zero clock rate before division.
At 32768 Hz, a 1 us request rounds to zero divider periods. Subtracting one then wraps the divider value to ULONG_MAX. Decrement only a nonzero rounded period count so that such requests use the smallest divider value.
--- drivers/gpio/gpio-rockchip.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/gpio/gpio-rockchip.c +10 -5
@@ -201,20 +201,25 @@ static int rockchip_gpio_set_debounce(st {struct rockchip_pin_bank *bank =gpiochip_get_data (gc);const struct rockchip_gpio_regs *reg = bank->gpio_regs; -unsigned long flags, div_reg, freq, max_debounce; +unsigned long flags, div_reg, freq;bool div_debounce_support;unsigned int cur_div_reg; -u64 div; +u64 div, max_debounce;if (bank->gpio_type ==GPIO_TYPE_V2 && !IS_ERR (bank->db_clk)) { div_debounce_support = true; freq =clk_get_rate (bank->db_clk); - max_debounce = (GENMASK (23 ,0 ) +1 ) *2 *1000000 / freq; +if (!freq) +return -EINVAL ; + + div = (u64)(GENMASK (23 ,0 ) +1 ) *2 *USEC_PER_SEC ; + max_debounce =div64_u64 (div, freq);if (debounce > max_debounce)return -EINVAL ; - div = debounce * freq; - div_reg =DIV_ROUND_CLOSEST_ULL (div,2 *USEC_PER_SEC ) -1 ; + div = (u64 )debounce * freq; + div_reg =DIV_ROUND_CLOSEST_ULL (div,2 *USEC_PER_SEC ); + div_reg = div_reg ? div_reg -1 :0 ; }else { div_debounce_support = false; }
Greg Kroah-Hartman
maintainerPATCH 828/990 gpio: sodaville: fix use-after-free bug when registering the irqchip
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit ab9102375b7c77e0c4d33c7594e514454dc9f2b3 upstream.
In sdv_register_irqsupport(), if irq_domain_create_legacy() fails during device probing, a generic IRQ chip is left registered in the global gc_list while its underlying memory is freed, leading to a use-after-free. Use the managed variant of irq_setup_generic_chip() to ensure that the chip gets unregistered before the memory it uses is freed.
--- drivers/gpio/gpio-sodaville.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/gpio/gpio-sodaville.c +6 -3
@@ -166,9 +166,12 @@ static int sdv_register_irqsupport(struc ct->chip.irq_eoi = irq_gc_eoi; ct->chip.irq_set_type = sdv_gpio_pub_set_type; -irq_setup_generic_chip (sd->gc,IRQ_MSK (SDV_NUM_PUB_GPIOS ), -IRQ_GC_INIT_MASK_CACHE ,IRQ_NOREQUEST , -IRQ_LEVEL |IRQ_NOPROBE ); + ret =devm_irq_setup_generic_chip (&pdev->dev, sd->gc, +IRQ_MSK (SDV_NUM_PUB_GPIOS ), +IRQ_GC_INIT_MASK_CACHE ,IRQ_NOREQUEST , +IRQ_LEVEL |IRQ_NOPROBE ); +if (ret) +return ret; sd->id =irq_domain_create_legacy (dev_fwnode (&pdev->dev),SDV_NUM_PUB_GPIOS , sd->irq_base,0 , &irq_domain_sdv_ops, sd);
Greg Kroah-Hartman
maintainerPATCH 829/990 gpio: virtuser: fix interrupt leak and UAF
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
commit 24cafd9580627f9f066296f4a6ce1b282a3f425d upstream.
When configuring interrupt handlers for GPIOs requested by virtual users, we never verify if an interrupt has been previously requested and just leak it if it was.
We also never free the interrupts at device unbind. This is both a leak and a potential UAF bug.
We use atomic_t for the irq field for now reason, it can't be modifying or read from atomic context. Let's repurpose the existing consumer_lock mutex and serialize access to the irq field. Let's add sanitization of input and schedule a tear-down action.
--- drivers/gpio/gpio-virtuser.c | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -10
@@ -58,9 +58,9 @@ struct gpio_virtuser_line_array_data {struct gpio_virtuser_line_data {struct gpio_virtuser_attr_data ad;char consumer[GPIO_VIRTUSER_NAME_BUF_LEN ]; -struct mutex consumer_lock; +struct mutex lock;unsigned int debounce; -atomic_t irq; +int irq;atomic_t irq_count; };
@@ -612,7 +612,7 @@ static ssize_t gpio_virtuser_consumer_rememset (buf,0x0 ,sizeof (buf)); -scoped_guard (mutex, &data->consumer_lock) +scoped_guard (mutex, &data->lock) ret = snprintf(buf, sizeof(buf), "%s\n", data->consumer);return simple_read_from_buffer (user_buf, size, ppos, buf, ret);
@@ -640,7 +640,7 @@ static ssize_t gpio_virtuser_consumer_wrif (ret)return ret; - scoped_guard(mutex, &data->consumer_lock) + scoped_guard(mutex, &data->lock)strscpy (data->consumer, buf,sizeof (data->consumer));return count;
@@ -680,7 +680,12 @@ static int gpio_virtuser_interrupts_set(if (val >1 )return -EINVAL ; +guard (mutex)(&ld->lock); +if (val) { +if (ld->irq >=0 ) +return -EBUSY ; + irq =gpiod_to_irq (ld->ad.desc);if (irq <0 )return irq;
@@ -694,11 +699,13 @@ static int gpio_virtuser_interrupts_set(if (ret)return ret; -atomic_set (&ld->irq, irq); + ld->irq = irq; }else { - irq =atomic_xchg (&ld->irq,0 ); -if (irq) -free_irq (irq, ld); +if (ld->irq <0 ) +return -EBUSY ; + +free_irq (ld->irq, ld); + ld->irq =-1 ; }return 0 ;
@@ -798,6 +805,14 @@ static int gpio_virtuser_dbgfs_init_line data->ad.dbgfs_dir, data); } +static void gpio_virtuser_free_irq (void *data) +{ +struct gpio_virtuser_line_data *ld = data; + +if (ld->irq >=0 ) +free_irq (ld->irq, ld); +} + static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev, struct gpio_desc *desc, const char *id,
@@ -814,14 +829,18 @@ static int gpio_virtuser_dbgfs_init_line data->ad.desc = desc;strscpy (data->consumer, id); -atomic_set (&data->irq,0 ); + data->irq =-1 ;atomic_set (&data->irq_count,0 ); + ret =devm_add_action_or_reset (dev, gpio_virtuser_free_irq, data); +if (ret) +return ret; + name =devm_kasprintf (dev,GFP_KERNEL ,"gpiod:%s:%u" , id, index);if (!name)return -ENOMEM ; - ret =devm_mutex_init (dev, &data->consumer_lock); + ret =devm_mutex_init (dev, &data->lock);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 830/990 gpio: virtuser: remove the debugfs files before freeing the line data
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu Zhang <[email protected]>
commit c2d0710318b8cd57d0ef6088d0ee4bbc1e827fd3 upstream.
gpio_virtuser_probe() registers the devm action that removes the debugfs directory before it allocates the per-line and per-array data that the debugfs files point to. devres releases resources in reverse order, so on unbind the line data is freed, the consumer_lock mutex is destroyed and the GPIO descriptors are put first, and the debugfs files are only removed afterwards.
A read or write of any of the per-line debugfs files (value, direction, consumer, interrupts, ...) that runs in that window dereferences the freed data. debugfs_remove_recursive() waits for in-flight file operations, but by then the data has already been freed.
Running eight threads that read the per-line debugfs files while another task writes 1 and 0 to the configfs "live" attribute triggers this within a second on a KASAN kernel, with gpio-sim as the provider:
BUG: KASAN: slab-use-after-free in gpio_virtuser_value_get+0x19/0x60 Read of size 8 at addr ffff888005109e38 by task vu_race/3479 Call Trace: gpio_virtuser_value_get+0x19/0x60 simple_attr_read+0x109/0x290 debugfs_attr_read+0x5e/0x80 full_proxy_read+0xae/0xe0 vfs_read+0x1bc/0x7a0 Allocated by task 1: devm_kmalloc+0x89/0x1d0 gpio_virtuser_probe+0x56f/0x910 Freed by task 1: kfree+0x196/0x430 release_nodes+0x77/0xa0 devres_release_all+0xf3/0x150 device_unbind_cleanup+0x18/0x130 ... platform_device_unregister+0x3c/0x50 gpio_virtuser_device_deactivate+0x3c/0xc0
The same run also reports use-after-free on the freed consumer_lock from the consumer attribute.
Register the debugfs removal action after the line data has been set up, so that it runs first on unbind, and remove the directory by hand on the probe error paths before that point.
--- drivers/gpio/gpio-virtuser.c | 46 +++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 17 deletions(-)
drivers/gpio/gpio-virtuser.c +29 -17
@@ -951,38 +951,50 @@ static int gpio_virtuser_probe(struct pl "Failed to get the IDs of GPIOs to request\n"); dbgfs_entry =debugfs_create_dir (dev_name (dev), gpio_virtuser_dbg_root); - ret =devm_add_action_or_reset (dev, gpio_virtuser_debugfs_remove, - dbgfs_entry); -if (ret) -return ret;for (i =0 ; i < num_ids; i++) { descs =devm_gpiod_get_array (dev, ids[i],GPIOD_ASIS ); -if (IS_ERR (descs)) -return dev_err_probe (dev,PTR_ERR (descs), -"Failed to request the '%s' GPIOs\n" , - ids[i]); +if (IS_ERR (descs)) { + ret =dev_err_probe (dev,PTR_ERR (descs), +"Failed to request the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + } ret =gpio_virtuser_dbgfs_init_line_array_attrs (dev, descs, ids[i], dbgfs_entry); -if (ret) -return dev_err_probe (dev, ret, -"Failed to setup the debugfs array interface for the '%s' GPIOs\n" , - ids[i]); +if (ret) { +dev_err_probe (dev, ret, +"Failed to setup the debugfs array interface for the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + }for (j =0 ; j < descs->ndescs; j++) { ret =gpio_virtuser_dbgfs_init_line_attrs (dev, descs->desc[j], ids[i], j, dbgfs_entry); -if (ret) -return dev_err_probe (dev, ret, -"Failed to setup the debugfs line interface for the '%s' GPIOs\n" , - ids[i]); +if (ret) { +dev_err_probe (dev, ret, +"Failed to setup the debugfs line interface for the '%s' GPIOs\n" , + ids[i]); + goto err_remove_debugfs; + } } } -return 0 ; +/* +* The debugfs files point to the devres-managed line data allocated +* above. Register the removal last so that it runs first on unbind, +* before any of that data is released. +*/ +return devm_add_action_or_reset (dev, gpio_virtuser_debugfs_remove, + dbgfs_entry); + +err_remove_debugfs: +debugfs_remove_recursive (dbgfs_entry); +return ret; }static const struct of_device_id gpio_virtuser_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 831/990 ovl: do not always clear absolute_redirect
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giuseppe Scrivano <[email protected]>
commit 477449a7a5fd1b2fe973fe2978b0c921115a65f3 upstream.
ovl_check_redirect() clears d->absolute_redirect before it checks that the path element has a redirect xattr. An element without one, such as an intermediate directory in a lower layer, then clears the flag set by the absolute redirect of a metacopy file found in a higher layer. The lookup of the data in the data-only layers is not deferred any more and the lookup fails with -EIO:
# l2/f: metacopy, redirect "/dir/file"; l1/dir/ exists, no "file"
mount -t overlay none -o metacopy=on,redirect_dir=on,\
lowerdir+=l2,lowerdir+=l1,datadir+=data m
cat m/f # Input/output errorSet d->absolute_redirect only when a redirect xattr was read.
--- fs/overlayfs/namei.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
fs/overlayfs/namei.c +2 -3
@@ -38,13 +38,12 @@ static int ovl_check_redirect(const struchar *buf;struct ovl_fs *ofs =OVL_FS (d->sb); - d->absolute_redirect = false; buf =ovl_get_redirect_xattr (ofs, path, prelen +strlen (post));if (IS_ERR_OR_NULL (buf))return PTR_ERR (buf); -if (buf[0 ] =='/' ) { - d->absolute_redirect = true; + d->absolute_redirect = buf[0 ] =='/' ; +if (d->absolute_redirect) {/* * One of the ancestor path elements in an absolute path * lookup in ovl_lookup_layer() could have been opaque and
Greg Kroah-Hartman
maintainerPATCH 832/990 ovl: reject different lower idmaps on the same fs
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 720f40c05b2785406121da0151543751204f2953 upstream.
Overayfs mounted with index=on or nfs_export=on require file handle support from backing filesystems.
Overlay file handles identify a backing filesystem, but not the lower mount used to decode it. If lower layers share a superblock and use different idmaps, a handle can decode through the wrong layer.
Record the first idmap on a private lower clone for each backing filesystem. Fail if another clone has a different idmap. Comparing the private clones prevents mount_setattr() from changing the checked state. Distinct idmap objects are treated as ambiguous.
--- fs/overlayfs/ovl_entry.h | 2 ++ fs/overlayfs/super.c | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+)
fs/overlayfs/ovl_entry.h +2 -0
@@ -24,6 +24,8 @@ struct ovl_config {struct ovl_sb {struct super_block *sb;dev_t pseudo_dev; +/* Idmap of the first lower layer on this fs */ +const struct mnt_idmap *lower_idmap;/* Unusable (conflicting) uuid */ bool bad_uuid;/* Used as a lower layer (but maybe also as upper) */
fs/overlayfs/super.c +23 -0
@@ -1125,6 +1125,29 @@ static int ovl_get_layers(struct super_b }/* +* Lower file handles identify the lower fs, but not the layer, +* so with different idmaps on the same lower fs, index and +* nfs_export may decode a file handle through a layer with the +* wrong idmap. Following copy up origin without index is only +* used for st_ino, which does not depend on the idmap. +*/ +if (i < nr_merged_lower && + (ofs->config.index || ofs->config.nfs_export)) { +const struct mnt_idmap *idmap =mnt_idmap (mnt); +struct ovl_sb *fs = &ofs->fs[fsid]; + +if (!fs->lower_idmap) { + fs->lower_idmap = idmap; + }else if (fs->lower_idmap != idmap) { +pr_err ("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n" , + l->path.dentry); +iput (trap); +kern_unmount (mnt); +return -EINVAL ; + } + } + +/* * Make lower layers R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. */
Greg Kroah-Hartman
maintainerPATCH 833/990 ovl: report the requested redirect_dir mode in conflicting options
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit 248503755b3cab89742edcc3cfd53adbcf7bfec2 upstream.
Since the redirect_dir mode is stored as an enum, "off" is translated to "follow" or "nofollow" when parsing the option and redirect_dir=follow is translated to "on" for a non-upper mount, so the errors about options that conflict with an explicit redirect_dir= report a mode that the user did not request.
Translate "off" when verifying the mount options instead of when parsing them and report the requested mode in those errors.
--- fs/overlayfs/overlayfs.h | 10 +++++++--- fs/overlayfs/params.c | 43 ++++++++++++++++++++++++++++++------------- 2 files changed, 37 insertions(+), 16 deletions(-)
fs/overlayfs/overlayfs.h +7 -3
@@ -74,9 +74,13 @@ enum ovl_entry_flag { };enum { -OVL_REDIRECT_OFF ,/* "off" mode is never used. In effect */ -OVL_REDIRECT_FOLLOW ,/* ...it translates to either "follow" */ -OVL_REDIRECT_NOFOLLOW ,/* ...or "nofollow". */ +/* +* "off" mode is never used after mount options are verified. In effect +* it translates to either "follow" or "nofollow". +*/ +OVL_REDIRECT_OFF , +OVL_REDIRECT_FOLLOW , +OVL_REDIRECT_NOFOLLOW ,OVL_REDIRECT_ON , };
fs/overlayfs/params.c +30 -13
99 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 834/990 ovl: return EIO if the lowerdata is missing
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giuseppe Scrivano <[email protected]>
commit 0d5e729c515f4ae4eacc179dbcf350d9b499a161 upstream.
The data of a metacopy file that redirects to a data-only layer is looked up when the file is opened, and the error of the lookup is returned as is. If the data file is missing, open() fails with ENOENT even though the file is there and stat() works.
This can be an integrity problem when using composefs: a data file that is changed or has the wrong fs-verity digest is reported with EIO, but a missing one is not reported, the file just looks like it does not exist, e.g. a configuration file that overrides the defaults.
Return EIO as it is already done in ovl_lookup() when no lower data is found for a metacopy file. ENOMEM is not changed.
--- fs/overlayfs/namei.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/overlayfs/namei.c +8 -0
@@ -1047,6 +1047,14 @@ out: out_err:pr_warn_ratelimited ("lazy lowerdata lookup failed (%pd2, err=%i)\n" , dentry, err); +/* +* The data of a metacopy file is missing or is not a regular file in +* the data-only layers: the layers are corrupted. Do not return the +* error of the lookup (e.g. ENOENT) to the caller, it would make the +* file look like it does not exist. +*/ +if (err != -ENOMEM ) + err = -EIO ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 835/990 ovl: do not allow nfs_export with data-only layers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit fba955b070d13e2fdac097577ce3c6ffbeda4ea9 upstream.
Since data-only layers no longer require metacopy=on, which conflicts with nfs_export=on, an overlay with data-only layers can be mounted with nfs_export=on.
Decoding a file handle of a lower metacopy file whose data is in a data-only layer builds the inode only from the decoded lower dentry, without the lazy lowerdata redirect, so the data of the file would be read from the metacopy file in the lower layer.
Fail the mount with explicit nfs_export=on and data-only layers and otherwise disable nfs_export with data-only layers.
--- fs/overlayfs/params.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
fs/overlayfs/params.c +10 -0
@@ -945,6 +945,16 @@ int ovl_fs_params_verify(const struct ov } } +/* Resolve nfs_export -> !data-only layers dependency */ +if (config->nfs_export && ctx->nr_data) { +if (set.nfs_export) { +pr_err ("NFS export is not supported with data-only layers\n" ); +return -EINVAL ; + } +pr_info ("disabling nfs_export due to data-only layers\n" ); + config->nfs_export = false; + } +/* Resolve nfs_export -> index dependency */ if (config->nfs_export && !config->index) { if (!config->upperdir &&
Greg Kroah-Hartman
maintainerPATCH 836/990 smb: client: bound invalid NTLMSSP signature diagnostic
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yifan Zhang <[email protected]>
commit 0584b02669c3e76188097174b4f25ed13723e94c upstream.
The NTLMSSP Signature field is an eight-byte binary value and need not be NUL-terminated. decode_ntlmssp_challenge() prints it with %s on the signature-mismatch path, so the diagnostic can continue beyond the received blob until it encounters a zero byte.
KASAN reports:
BUG: KASAN: slab-out-of-bounds in string Read of size 1 string vsnprintf _printk decode_ntlmssp_challenge
Print the fixed-width field with the bounded hexadecimal format.
The patched kernel reaches the invalid-signature path and returns -EINVAL without a KASAN report.
--- fs/smb/client/sess.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/client/sess.c +2 -2
@@ -934,8 +934,8 @@ int decode_ntlmssp_challenge(char *bcc_p }if (memcmp (pblob->Signature,"NTLMSSP" ,8 )) { -cifs_dbg (VFS ,"blob signature incorrect %s\n" , - pblob->Signature); +cifs_dbg (VFS ,"%s: blob signature incorrect: %8phN\n" , + __func__, pblob->Signature);return -EINVAL ; }if (pblob->MessageType != NtLmChallenge) {
Greg Kroah-Hartman
maintainerPATCH 837/990 smb: client: compare owner and group SIDs using their encoded lengths
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: liuyong <[email protected]>
commit a2dabe73ea05ad3b3f8e1cc08fb2e7c2ddc5564b upstream.
populate_new_aces() compares owner and group SIDs over sizeof(struct smb_sid), including storage for all 15 possible subauthorities. Received SIDs contain only their encoded subauthorities. The comparison can read past the security descriptor, as shown by the supplied KASAN report for a 44-byte descriptor during chmod.
The input SIDs have already been checked by sid_from_sd(). Require equal subauthority counts, then compare only the fixed SID header and the encoded subauthorities with memcmp(). The count check ensures that both validated SIDs contain the number of bytes being compared.
These issues were discovered and fixed by Qihoo 360's Tulongfeng multi-agent system.
--- fs/smb/client/cifsacl.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/client/cifsacl.c +4 -1
@@ -1061,7 +1061,10 @@ static void populate_new_aces(char *nacl* updated in the inode. */ -if (!memcmp (pownersid, pgrpsid,sizeof (struct smb_sid ))) { +if (pownersid->num_subauth == pgrpsid->num_subauth && + !memcmp (pownersid, pgrpsid, +CIFS_SID_BASE_SIZE + + pownersid->num_subauth *sizeof (__le32))) {/* * Case when owner and group SIDs are the same. * Set the more restrictive of the two modes.
Greg Kroah-Hartman
maintainerPATCH 838/990 smb: client: dont block dying tasks waiting for writeback on close
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 15ea186abbcd04157c62e0901701870b812bb2bd upstream.
cifs_flush() waits uninterruptibly for the writeback it starts. A task that gets killed while closing a file on a hard mount with an unresponsive server is stuck in D state until the server comes back. It also consumes any writeback error for a caller that is about to exit, hiding it from everyone else.
Wait killably instead. If the closer gets killed, stop waiting and leave the error bits in the mapping for others to see; writeback already in flight completes on its own. Don't wait at all, nor check for errors, if it is already dying.
This is also needed before letting dying tasks issue their writes from a worker, which would otherwise make them wait for every one of them.
--- fs/smb/client/file.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-)
fs/smb/client/file.c +30 -3
@@ -2856,17 +2856,44 @@ fsync_exit:return rc; } +static int cifs_wait_writeback_killable (struct address_space *mapping) +{ +struct folio_batch fbatch; +pgoff_t index =0 ; +int rc =0 ; + +folio_batch_init (&fbatch); +while (!rc && +filemap_get_folios_tag (mapping, &index, (pgoff_t)-1 , +PAGECACHE_TAG_WRITEBACK , &fbatch)) { +for (unsigned int i =0 ; + !rc && i <folio_batch_count (&fbatch); i++) + rc =folio_wait_writeback_killable (fbatch.folios[i]); +folio_batch_release (&fbatch); +cond_resched (); + } +return rc; +} +/* * As file closes, flush all cached write data for this inode checking * for write behind errors. */ int cifs_flush (struct file *file,fl_owner_t id) { +struct address_space *mapping = file->f_mapping;struct inode *inode =file_inode (file); -int rc =0 ; +int rc =0 , rc2; -if (file->f_mode &FMODE_WRITE ) - rc =filemap_write_and_wait (inode->i_mapping); +if (file->f_mode &FMODE_WRITE ) { + rc =filemap_fdatawrite (mapping); +if (fatal_signal_pending (current) || +cifs_wait_writeback_killable (mapping)) +return 0 ; + rc2 =filemap_check_errors (mapping); +if (!rc) + rc = rc2; + }cifs_dbg (FYI ,"Flush inode %p file %p rc %d\n" , inode, file, rc);if (rc) {
Greg Kroah-Hartman
maintainerPATCH 839/990 smb: client: dont block dying tasks waiting for writeback on fsync
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 0df0f24803061b6c2bef0d24de7c63c9cce46a49 upstream.
cifs_fsync() and cifs_strict_fsync() wait uninterruptibly for writeback through file_write_and_wait_range(). As with close, a task killed in fsync(2) on a hard mount with an unresponsive server is stuck in D state until the server comes back.
Wait killably instead, using the same helper as cifs_flush(). The writeback keeps going and its errors stay in the mapping; only the dying caller stops waiting for it.
--- fs/smb/client/file.c | 64 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 42 insertions(+), 22 deletions(-)
fs/smb/client/file.c +42 -22
@@ -2778,6 +2778,45 @@ cifs_get_readable_path(struct cifs_tconreturn -ENOENT ; } +static int cifs_wait_writeback_killable (struct address_space *mapping, +loff_t start,loff_t end) +{ +pgoff_t end_index = end >>PAGE_SHIFT ; +pgoff_t index = start >>PAGE_SHIFT ; +struct folio_batch fbatch; +int rc =0 ; + +folio_batch_init (&fbatch); +while (!rc && +filemap_get_folios_tag (mapping, &index, end_index, +PAGECACHE_TAG_WRITEBACK , &fbatch)) { +for (unsigned int i =0 ; + !rc && i <folio_batch_count (&fbatch); i++) + rc =folio_wait_writeback_killable (fbatch.folios[i]); +folio_batch_release (&fbatch); +cond_resched (); + } +return rc; +} + +static int cifs_file_write_and_wait_killable (struct file *file, +loff_t start,loff_t end) +{ +struct address_space *mapping = file->f_mapping; +int rc, rc2; + +if (end < start) +return 0 ; + + rc =filemap_fdatawrite_range (mapping, start, end); +if (cifs_wait_writeback_killable (mapping, start, end)) +return -EINTR ; + rc2 =file_check_and_advance_wb_err (file); +if (!rc) + rc = rc2; +return rc; +} +/* * Flush data on a strict file. */
@@ -2789,7 +2828,7 @@ int cifs_strict_fsync(struct file *file,unsigned int xid;int rc; - rc =file_write_and_wait_range (file, start, end); + rc =cifs_file_write_and_wait_killable (file, start, end);if (rc) {trace_cifs_fsync_err (inode->i_ino, rc);return rc;
@@ -2821,7 +2860,7 @@ int cifs_fsync(struct file *file, loff_tstruct inode *inode =file_inode (file);struct cifs_sb_info *cifs_sb =CIFS_FILE_SB (file); - rc =file_write_and_wait_range (file, start, end); + rc =cifs_file_write_and_wait_killable (file, start, end);if (rc) {trace_cifs_fsync_err (file_inode (file)->i_ino, rc);return rc;
@@ -2856,25 +2895,6 @@ fsync_exit:return rc; } -static int cifs_wait_writeback_killable (struct address_space *mapping) -{ -struct folio_batch fbatch; -pgoff_t index =0 ; -int rc =0 ; - -folio_batch_init (&fbatch); -while (!rc && -filemap_get_folios_tag (mapping, &index, (pgoff_t)-1 , -PAGECACHE_TAG_WRITEBACK , &fbatch)) { -for (unsigned int i =0 ; - !rc && i <folio_batch_count (&fbatch); i++) - rc =folio_wait_writeback_killable (fbatch.folios[i]); -folio_batch_release (&fbatch); -cond_resched (); - } -return rc; -} -/* * As file closes, flush all cached write data for this inode checking * for write behind errors.
@@ -2888,7 +2908,7 @@ int cifs_flush(struct file *file, fl_ownif (file->f_mode &FMODE_WRITE ) { rc =filemap_fdatawrite (mapping);if (fatal_signal_pending (current) || -cifs_wait_writeback_killable (mapping)) +cifs_wait_writeback_killable (mapping,0 ,LLONG_MAX ))return 0 ; rc2 =filemap_check_errors (mapping);if (!rc)
Greg Kroah-Hartman
maintainerPATCH 840/990 smb: client: fix double conversion of DFS path in setup_dfs_ref()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fredric Cover <[email protected]>
commit 92509ce64ffff02d05fe9f3c82b889e1cc500076 upstream.
setup_dfs_ref() converts the path from the mount charset to the DFS cache charset (utf8) via dfs_get_path(), and then passes that already converted string to dfs_get_referral(). dfs_cache_find() converts its input again, assuming it is still in the mount charset.
When the mount charset is not utf8 (iocharset=iso8859-1, or a kernel built with a non-utf8 CONFIG_NLS_DEFAULT) and the DFS path contains non-ASCII characters, the utf8 bytes are interpreted as mount-charset characters and encoded a second time. For example, "é" is sent as c3 83 c2 a9 instead of c3 a9. The server then fails the second-level referral with STATUS_OBJECT_PATH_NOT_FOUND and the mount fails with -ENOENT, even though the path exists.
Pass the unconverted path to dfs_get_referral() so that it is converted exactly once.
Such mounts now get past the second-level referral and reach dfs_parse_target_referral(), which is why this change depends on "smb: client: fix out-of-bounds read in dfs_parse_target_referral()".
Tested with a Samba DFS root containing a link named "café", mounted with iocharset=iso8859-1 and the single Latin-1 byte 0xe9 in the path:
before, the mount failed with -ENOENT; with both patches applied, it succeeds.
--- fs/smb/client/dfs.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
fs/smb/client/dfs.c +5 -5
@@ -103,6 +103,7 @@ static int setup_dfs_ref(struct dfs_infostruct cifs_sb_info *cifs_sb = rw->mnt_ctx->cifs_sb;struct smb3_fs_context *ctx = rw->mnt_ctx->fs_ctx;char *ref_path, *full_path; +const char *raw_path;int rc;set_root_smb_session (rw->mnt_ctx);
@@ -114,9 +115,10 @@ static int setup_dfs_ref(struct dfs_infoif (!tgt || (tgt->server_type ==DFS_TYPE_LINK &&DFS_INTERLINK (tgt->flags))) - ref_path =dfs_get_path (cifs_sb, ctx->UNC); + raw_path = ctx->UNC;else - ref_path =dfs_get_path (cifs_sb, full_path); + raw_path = full_path; + ref_path =dfs_get_path (cifs_sb, raw_path);if (IS_ERR (ref_path)) { rc =PTR_ERR (ref_path);kfree (full_path);
@@ -125,9 +127,7 @@ static int setup_dfs_ref(struct dfs_inforef_walk_path (rw) = ref_path;ref_walk_fpath (rw) = full_path; -return dfs_get_referral (rw->mnt_ctx, -ref_walk_path (rw) +1 , -ref_walk_tl (rw)); +return dfs_get_referral (rw->mnt_ctx, raw_path +1 ,ref_walk_tl (rw)); }static int __dfs_referral_walk (struct dfs_ref_walk *rw)
Greg Kroah-Hartman
maintainerPATCH 841/990 smb: client: fix OOB write when compounding SMB2_IOCTL with encryption
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrey Misiurov <[email protected]>
commit 73a0060cb22a1d2bd8bff364c18a4259ec0cb528 upstream.
On an encrypted ("seal") mount, SMB2_ioctl_init() keeps the IOCTL input in a separate iov (iov[1]); iov[0] is a 448-byte buffer from cifs_small_buf_get(). When such an IOCTL is not the last request of a compound, smb2_set_next_command() pads it for alignment by copying the whole request into iov[0]. A large enough input overflows that 448-byte buffer and corrupts the slab; the copy also sets rq_nvec to 1, so the input buffer is leaked too.
An unprivileged user can trigger it by creating a symlink with a long target on such a mount: the native symlink is sent as FSCTL_SET_REPARSE_POINT + QUERY_INFO + CLOSE in one compound, so the IOCTL is not the last request.
With slub_debug red zones on the cifs_small_rq cache, the overflow is caught on the next allocation from that cache in the same compound (the 0x61 bytes are the 'a' characters of the symlink target):
BUG cifs_small_rq (Not tainted): Object corrupt
[Left Redzone overwritten] 0xffff8a59c7790500-0xffff8a59c779053f First byte 0x61 instead of 0xbb
Call Trace: check_object+0x1a8/0x350 alloc_debug_processing+0xab/0x110 ___slab_alloc+0x7e/0x2f0 kmem_cache_alloc_noprof+0x28d/0x4b0 mempool_alloc_slab+0x16/0x30 cifs_small_buf_get+0x1a/0x30 [cifs] SMB2_close_init+0x8a/0x100 [cifs] smb2_compound_op+0x2571/0x2b50 [cifs] smb2_create_reparse_inode+0x27e/0x490 [cifs] mknod_nfs+0x1ce/0x2e0 [cifs] create_reparse_symlink+0x119/0x180 [cifs] cifs_symlink+0x19f/0x8e0 [cifs] vfs_symlink+0xa3/0x1b0 __x64_sys_symlink+0x41/0x70
Pad the input to a multiple of 8 bytes when encryption is required. The request is then already aligned and smb2_set_next_command() no longer copies it; InputCount still carries the real length.
--- fs/smb/client/smb2pdu.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/smb/client/smb2pdu.c +8 -4
@@ -3354,11 +3354,12 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, char *in_data, u32 indatalen, __u32 max_response_size) { - struct smb2_ioctl_req *req; struct kvec *iov = rqst->rq_iov; +struct smb2_ioctl_req *req; +u32 in_buf_len = indatalen;unsigned int total_len; -int rc;char *in_data_buf; +int rc; rc =smb2_ioctl_req_init (opcode, tcon, server, (void **) &req, &total_len);
@@ -3366,15 +3367,18 @@ SMB2_ioctl_init(struct cifs_tcon *tcon,return rc;if (indatalen) { +if (smb3_encryption_required (tcon)) + in_buf_len =ALIGN (indatalen,8 );/* * indatalen is usually small at a couple of bytes max, so * just allocate through generic pool */ - in_data_buf =kmemdup (in_data, indatalen,GFP_NOFS ); + in_data_buf =kzalloc (in_buf_len,GFP_NOFS );if (!in_data_buf) {cifs_small_buf_release (req);return -ENOMEM ; } +memcpy (in_data_buf, in_data, indatalen); } req->CtlCode =cpu_to_le32 (opcode);
@@ -3398,7 +3402,7 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, rqst->rq_nvec =2 ; iov[0 ].iov_len = total_len -1 ; iov[1 ].iov_base = in_data_buf; - iov[1 ].iov_len = indatalen; + iov[1 ].iov_len = in_buf_len; }else { rqst->rq_nvec =1 ; iov[0 ].iov_len = total_len;
Greg Kroah-Hartman
maintainerPATCH 842/990 smb: client: fix out-of-bounds read in dfs_parse_target_referral()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fredric Cover <[email protected]>
commit 86aacc2f3f6ba18e1d87feee24f37c94b3ce863a upstream.
dfs_parse_target_referral() decides whether a prefix path remains after the consumed part of full_path with:
if (strlen(full_path) - ref->path_consumed)
strlen() returns size_t, so if path_consumed is larger than the length of full_path, the subtraction wraps around to a huge non-zero value. The branch is then taken, prepath is set to a pointer past the terminating NUL of full_path, and *prepath reads out of bounds.
path_consumed can exceed strlen(full_path) when the mount charset is not utf8. The referral code derives path_consumed from the canonical path, which is in the DFS cache charset (utf8), but it is applied here to full_path, which is in the mount charset. Each non-ASCII character in the consumed part of the path that is longer in utf8 than in the mount charset makes the count too large by the difference.
This was reproduced with iocharset=iso8859-1 against a Samba DFS root containing a link named "café", mounting with the single Latin-1 byte 0xe9 in the path. On an unmodified tree such a mount fails earlier with -ENOENT because the path is converted to utf8 twice in setup_dfs_ref(); with that fixed ("smb: client: fix double conversion of DFS path in setup_dfs_ref()"), the mount reaches this code. full_path was 29 bytes while path_consumed was 30:
BUG: KASAN: slab-out-of-bounds in dfs_parse_target_referral+0x26a/0x270 Read of size 1 at addr ffff88810db89d5f by task mount/1743 ... The buggy address is located 0 bytes to the right of allocated 31-byte region [ffff88810db89d40, ffff88810db89d5f)
Compare path_consumed against the string length instead of subtracting, so that no prefix path is used when the consumed count covers the whole string. With the bounds check in place the same mount succeeds and no KASAN report is produced.
This only prevents the out-of-bounds access. path_consumed is still in the wrong units, so a non-ASCII link followed by a path component can still produce a wrong prefix path. That needs a separate fix.
--- fs/smb/client/dfs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/dfs.c +1 -1
@@ -33,7 +33,7 @@ int dfs_parse_target_referral(const charif (WARN_ON_ONCE (!ref->node_name || ref->path_consumed <0 ))return -EINVAL ; -if (strlen (full_path) - ref->path_consumed) { +if ((size_t )ref->path_consumed <strlen (full_path)) { prepath = full_path + ref->path_consumed;/* skip initial delimiter */ if (*prepath =='/' || *prepath =='\\' )
Greg Kroah-Hartman
maintainerPATCH 843/990 smb: client: flush deferred handles of other names before a hard link open
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 25912ed3b75dcf5ff623dcb549b925dd0d0948f7 upstream.
Opening a hard link of a file whose other name still holds a deferred, leased handle fails with EINVAL over SMB3. The client caches lease keys per inode, but the server ties a lease to the file name it was granted under, so reusing the inode's lease key to open a different name of the same inode is rejected with STATUS_INVALID_PARAMETER (MS-SMB2 3.3.5.9.11).
Commit 262b73ef442e ("smb3 client: fix open hardlink on deferred close file error") already closes the inode's deferred handles before such an open so the new name can take a fresh lease, but cifs_get_hardlink_path() only triggered that flush when a cached handle had the same open flags as the new open, so a differently accessed name - written then read, say - slipped through and still failed.
Match on the name instead: flush when a cached handle for another name of the inode is open, regardless of access mode.
--- fs/smb/client/file.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/file.c +1 -1
@@ -2206,7 +2206,7 @@ cifs_get_hardlink_path(struct cifs_tconspin_lock (&cinode->open_file_lock);list_for_each_entry (open_file, &cinode->openFileList, flist) { -if (file->f_flags == open_file->f_flags) { +if (open_file->dentry !=file_dentry (file)) { rc = -EINVAL ;break ; }
Greg Kroah-Hartman
maintainerPATCH 844/990 smb: client: hold the inode across cifs_oplock_break()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit fce78321f1b59531cf6fc94860550db1db8dec55 upstream.
cifs_oplock_break() drops the handle reference in the middle of the handler and keeps using cinode afterwards, to send the break acknowledgment and again in cifs_done_oplock_break(). The reference cifs_queue_oplock_break() takes is the only pin: the handle holds the dentry and the dentry is what keeps the inode alive.
When that put is the last reference, the dput() in cifsFileInfo_put_final() kills an unhashed dentry, drops the last i_count and evicts the inode, so the rest of the handler runs on an object whose free is only RCU-deferred. An unhashed dentry that a handle still references is an ordinary state: unlinking an open file leaves the dentry that way, and so does the dcache teardown at unmount.
Take a reference on the inode for the lifetime of the handler and drop it once the break has been reported. This also covers the cifs_get_tlink() failure path, where the put is followed directly by the out label.
--- fs/smb/client/file.c | 9 +++++++++ 1 file changed, 9 insertions(+)
fs/smb/client/file.c +9 -0
@@ -3284,6 +3284,14 @@ void cifs_oplock_break(struct work_struc__u64 persistent_fid, volatile_fid;__u16 net_fid; +/* +* Dropping the handle reference below also drops the dentry +* reference that pins this inode, and cinode is still needed to +* acknowledge the break and to report it as complete. Hold the inode +* until that is done. +*/ +ihold (inode); +wait_on_bit (&cinode->flags,CIFS_INODE_PENDING_WRITERS ,TASK_UNINTERRUPTIBLE );
@@ -3359,6 +3367,7 @@ oplock_break_ack:cifs_put_tlink (tlink); out:cifs_done_oplock_break (cinode); +iput (inode); } static int cifs_swap_activate(struct swap_info_struct *sis,
Greg Kroah-Hartman
maintainerPATCH 845/990 smb: client: issue writes from a worker if the task is dying
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 1a747bacf250959703c68fed1bb643f888dd3ad2 upstream.
A task with a fatal signal pending can't send on the socket:__smb_send_rqst() refuses it upfront with -ERESTARTSYS, as SIGKILL can't be blocked and a send interrupted halfway forces a reconnect. Writeback, however, runs in the context of whoever starts it, so when a dying task flushes dirty pages - close() racing with SIGKILL, or fd teardown during exit_group() - every write subrequest gets refused:
smb3_write_err: ... offset=0x1400000 len=0x400000 rc=-512
cifs_flush_err: ino=... rc=-512
Since the switch to netfslib, a failed upload ends writeback with the folios clean, so the data is silently lost: the server ends up with 20MiB of a 64MiB file while stat(2) reports the full size.
Issue writeback subrequests of dying tasks from a new cifswritebackd workqueue instead, like afs does for all of its writes, so they get sent from a context with no signals. Leave direct and unbuffered writes alone, as their callers get the error. Use a dedicated WQ_UNBOUND workqueue as the writes may block for long on credits, sends or reopens, e.g. on hard mounts with an unresponsive server, and must not hold up other cifs work such as reconnects, nor starve the WQ_MEM_RECLAIM rescuer of cifsiod_wq.
--- fs/smb/client/cifsfs.c | 13 ++++++++++++- fs/smb/client/cifsglob.h | 1 + fs/smb/client/file.c | 26 +++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 2 deletions(-)
fs/smb/client/cifsfs.c +12 -1
@@ -198,6 +198,7 @@ struct workqueue_struct *cifsoplockd_wq;struct workqueue_struct *deferredclose_wq;struct workqueue_struct *serverclose_wq;struct workqueue_struct *cfid_put_wq; +struct workqueue_struct *cifs_writeback_wq;__u32 cifs_lock_secret;/*
@@ -2076,9 +2077,16 @@ init_cifs(void) goto out_destroy_serverclose_wq; } + cifs_writeback_wq =alloc_workqueue ("cifswritebackd" , +WQ_UNBOUND |WQ_MEM_RECLAIM ,0 ); +if (!cifs_writeback_wq) { + rc = -ENOMEM ; + goto out_destroy_cfid_put_wq; + } + rc =cifs_init_inodecache ();if (rc) - goto out_destroy_cfid_put_wq; + goto out_destroy_writeback_wq; rc =cifs_init_netfs ();if (rc)
@@ -2149,6 +2157,8 @@ out_destroy_netfs:cifs_destroy_netfs (); out_destroy_inodecache:cifs_destroy_inodecache (); +out_destroy_writeback_wq: +destroy_workqueue (cifs_writeback_wq); out_destroy_cfid_put_wq:destroy_workqueue (cfid_put_wq); out_destroy_serverclose_wq:
@@ -2194,6 +2204,7 @@ exit_cifs(void)destroy_workqueue (fileinfo_put_wq);destroy_workqueue (serverclose_wq);destroy_workqueue (cfid_put_wq); +destroy_workqueue (cifs_writeback_wq);destroy_workqueue (cifsiod_wq); }
fs/smb/client/cifsglob.h +1 -0
@@ -2108,6 +2108,7 @@ extern struct workqueue_struct *cifsoploextern struct workqueue_struct *deferredclose_wq;extern struct workqueue_struct *serverclose_wq;extern struct workqueue_struct *cfid_put_wq; +extern struct workqueue_struct *cifs_writeback_wq;extern __u32 cifs_lock_secret;extern mempool_t *cifs_sm_req_poolp;
fs/smb/client/file.c +25 -1
@@ -106,10 +106,16 @@ retry:#endif } +static bool cifs_writeback_dying (struct netfs_io_subrequest *subreq) +{ +return subreq->rreq->origin ==NETFS_WRITEBACK && +fatal_signal_pending (current); +} +/* * Issue a subrequest to upload to the server. */ -static void cifs_issue_write (struct netfs_io_subrequest *subreq) +static void __cifs_issue_write (struct netfs_io_subrequest *subreq) {struct cifs_io_subrequest *wdata = container_of(subreq, struct cifs_io_subrequest, subreq);
@@ -143,6 +149,24 @@ fail: goto out; } +static void cifs_issue_write_worker (struct work_struct *work) +{ +struct netfs_io_subrequest *subreq; + + subreq = container_of(work, struct netfs_io_subrequest, work); +__cifs_issue_write (subreq); +} + +static void cifs_issue_write (struct netfs_io_subrequest *subreq) +{ +if (unlikely (cifs_writeback_dying (subreq))) { + subreq->work.func = cifs_issue_write_worker; +WARN_ON_ONCE (!queue_work (cifs_writeback_wq, &subreq->work)); +return ; + } +__cifs_issue_write (subreq); +} +static void cifs_netfs_invalidate_cache (struct netfs_io_request *wreq) {cifs_invalidate_cache (wreq->inode,0 );
Greg Kroah-Hartman
maintainerPATCH 846/990 smb: client: retry writes that couldnt be issued due to a reconnect
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit 64db0dc1f3e689145e698bc1b20ee70b1724b945 upstream.
__cifs_issue_write() fails a subrequest with -EAGAIN when its handle got invalidated or its credits belong to a session from before a reconnect, both before sending anything. netfs used to retry any -EAGAIN by itself, but now only retries subrequests marked for it, so these writes fail and their folios end writeback clean, losing the data.
Mark them for retry instead. The retry gets the handle reopened and fresh credits in cifs_prepare_write().
--- fs/smb/client/file.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/client/file.c +4 -2
@@ -140,10 +140,12 @@ out:return ; fail: -if (rc == -EAGAIN ) +if (rc == -EAGAIN ) {trace_netfs_sreq (subreq, netfs_sreq_trace_retry); -else +__set_bit (NETFS_SREQ_NEED_RETRY , &subreq->flags); + }else {trace_netfs_sreq (subreq, netfs_sreq_trace_fail); + }add_credits_and_wake_if (wdata->server, &wdata->credits,0 );cifs_write_subrequest_terminated (wdata, rc); goto out;
Greg Kroah-Hartman
maintainerPATCH 847/990 smb: client: skip NULL channel in __cifs_put_smb_ses()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit 8deaf64a59a263161dfc5128f8398fb3dcba4fac upstream.
cifs_chan_skip_or_disable() clears a secondary channel's slot in the session (ses->chans[chan_index].server = NULL) without lowering chan_count when the server stops supporting multichannel. When the session is later released, __cifs_put_smb_ses() walks every slot up to chan_count and calls cifs_put_tcp_session() on it, which dereferences the server pointer immediately, so a slot left NULL by the skip path makes the release crash with a NULL pointer dereference.
Clearing a slot without lowering chan_count is older than cifs_chan_skip_or_disable(): cifs_chan_update_iface() could already do the same since commit b54034a73baf9 ("cifs: during reconnect, update interface if necessary"), and the release loop has been unguarded since then. Commit 12d1e301bdfd1 ("cifs: do not let cifs_chan_update_iface deallocate channels") later removed that trigger, but the crash is reachable through it on older kernels.
cifs_decrease_secondary_channels() already guards the same put with if (server). Add the same guard to the release loop so a skipped channel slot is left alone.
--- fs/smb/client/connect.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/smb/client/connect.c +2 -1
@@ -2178,7 +2178,8 @@ void __cifs_put_smb_ses(struct cifs_seskref_put (&ses->chans[i].iface->refcount, release_iface); ses->chans[i].iface =NULL ; } -cifs_put_tcp_session (ses->chans[i].server,0 ); +if (ses->chans[i].server) +cifs_put_tcp_session (ses->chans[i].server,0 ); ses->chans[i].server =NULL ; }
Greg Kroah-Hartman
maintainerPATCH 848/990 smb: client: validate descriptor headers before query result allocation
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: liuyong <[email protected]>
commit ffb59029c0d52bf76fdd2678f5d6fd13e26220dd upstream.
query_info() uses the server's returned length instead of the caller's minimum when a dynamic result is requested. A zero-length ACL response can therefore return ZERO_SIZE_PTR to id_mode_to_cifs_acl(), whose ownership-change path reads dacloffset before checking the header size. A KASAN-enabled test shows a read at address 0x20 and a kernel Oops.
Validate the returned range and the caller's minimum before allocating the dynamic result. Keep the reported length zero if validation fails.
Use the security descriptor header size as the minimum in SMB2_query_acl(). DACL-only and SACL-only xattr queries do not require owner and group SIDs, so enforcing MIN_SEC_DESC_LEN would reject short descriptors that these queries could previously return. The rewrite paths validate the required owner/group SIDs and DACL separately before using their contents.
These issues were discovered and fixed by Qihoo 360's Tulongfeng multi-agent system.
--- fs/smb/client/cifsacl.h | 14 -------------- fs/smb/client/smb2pdu.c | 11 ++++++++++- 2 files changed, 10 insertions(+), 15 deletions(-)
fs/smb/client/cifsacl.h +0 -14
@@ -93,18 +93,4 @@ struct owner_group_sids { struct owner_sid group; } __packed; -/* -* Minimum security identifier can be one for system defined Users -* and Groups such as NULL SID and World or Built-in accounts such -* as Administrator and Guest and consists of -* Revision + Num (Sub)Auths + Authority + Domain (one Subauthority) -*/ -#define MIN_SID_LEN (1 + 1 + 6 + 4)/* in bytes */ - -/* -* Minimum security descriptor can be one without any SACL and DACL and can -* consist of revision, type, and two sids of minimum size for owner and group -*/ -#define MIN_SEC_DESC_LEN (sizeof(struct smb_ntsd) + (2 * MIN_SID_LEN)) -#endif /* _CIFSACL_H */
fs/smb/client/smb2pdu.c +10 -1
@@ -3940,6 +3940,14 @@ replay_again: ses->Suid, info_class, (__u32)info_type);if (dlen) { + rc =smb2_validate_iov (le16_to_cpu (rsp->OutputBufferOffset), +le32_to_cpu (rsp->OutputBufferLength), + &rsp_iov, min_len); +if (rc) { + *dlen =0 ; + goto qinf_exit; + } + *dlen =le32_to_cpu (rsp->OutputBufferLength);if (!*data) { *data =kmalloc (*dlen,GFP_KERNEL );
@@ -4012,7 +4020,8 @@ SMB2_query_acl(const unsigned int xid, sreturn query_info (xid, tcon, persistent_fid, volatile_fid,0 ,SMB2_O_INFO_SECURITY , extra_info, -SMB2_MAX_BUFFER_SIZE ,MIN_SEC_DESC_LEN , data, plen); +SMB2_MAX_BUFFER_SIZE ,sizeof (struct smb_ntsd ), + data, plen); }int
Greg Kroah-Hartman
maintainerPATCH 849/990 dm log userspace: drop the device reference on error
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: [email protected] <[email protected]>
commit 0550d3b14e008b033b02cfce668008ec6addffe4 upstream.
userspace_ctr() takes a reference on the log device with dm_get_device(). When the integrated-flush workqueue allocation fails it jumps to the shared error path, which frees the log context without dropping that reference, so the device stays busy and cannot be removed.
userspace_dtr() drops the reference correctly; do the same here.
--- drivers/md/dm-log-userspace-base.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm-log-userspace-base.c +5 -1
@@ -294,9 +294,11 @@ static int userspace_ctr(struct dm_dirty } r =dm_get_device (ti, devices_rdata,dm_table_get_mode (ti->table), &lc->log_dev); -if (r) +if (r) {DMERR ("Failed to register %s with device-mapper" , devices_rdata); + goto out; + } }if (lc->integrated_flush) {
@@ -315,6 +317,8 @@ static int userspace_ctr(struct dm_dirty out:kfree (devices_rdata);if (r) { +if (lc->log_dev) +dm_put_device (lc->ti, lc->log_dev);mempool_exit (&lc->flush_entry_pool);kfree (lc);kfree (ctr_str);
Greg Kroah-Hartman
maintainerPATCH 850/990 dm: avoid double-dropping the zone reset submission reference
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yaohan Li <[email protected]>
commit c4965effbe15f837a8089e79c0fc17ab19363cce upstream.
On an error in __send_zone_reset_all(), the submission reference held by the dm_io can be decremented there and again by the caller's error path. If another clone is still outstanding, the second drop can release the dm_io before that clone completes.
Only drop the submission reference in __send_zone_reset_all() on success. On failure, leave the reference for the caller's existing error handling to release once.
The error path was reproduced under KASAN with an injected GFP_NOIO allocation failure while another zone-reset clone remained in flight. With the change, the same failure was reported normally, without the observed use-after-free, and ordinary zone resets continued to work.
--- drivers/md/dm.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/md/dm.c +7 -2
@@ -1924,8 +1924,13 @@ static blk_status_t __send_zone_reset_albreak ; } -/* Release the reference that alloc_io() took for submission. */ -atomic_sub (1 , &ci->io->io_count); +/* +* Release the reference that alloc_io() took for submission. On error, +* that reference was not consumed: dm_split_and_process_bio() releases +* it on the error path, so do not release it here a second time. +*/ +if (sts ==BLK_STS_OK ) +atomic_dec (&ci->io->io_count);return sts; }
Greg Kroah-Hartman
maintainerPATCH 851/990 dm: fail a REQ_PREFLUSH bio with data when its preflush fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
commit e92cd41e8e5ee5616c6c7cd4378661d942f0a7c0 upstream.
For a bio with REQ_PREFLUSH and data, dm core may send an empty flush first. If the flush fails, __dm_io_complete() still reissues the bio without REQ_PREFLUSH and drops the error. When that write succeeds, the XFS log keeps running and fsync() can return 0.
End the bio with the flush error instead of writing the data, as blk-mq does.
--- drivers/md/dm.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/md/dm.c +2 -2
@@ -983,7 +983,7 @@ static void __dm_io_complete(struct dm_iif (requeued)return ; -if (unlikely (requeue_flush_with_data)) { +if (unlikely (requeue_flush_with_data) && !io_error) {/* * Preflush done for flush with data, reissue * without REQ_PREFLUSH.
@@ -991,7 +991,7 @@ static void __dm_io_complete(struct dm_i bio->bi_opf &= ~REQ_PREFLUSH ;queue_io (md, bio); }else { -/* done with normal IO or empty flush */ +/* done with normal IO, empty flush or failed preflush */ if (io_error) bio->bi_status = io_error;bio_endio (bio);
Greg Kroah-Hartman
maintainerPATCH 852/990 dm: fix infinite loop in dm_blk_do_report_zones()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mark Bundschuh <[email protected]>
commit 648320de920b30ae1730bbf0e8b86c0df0fb490a upstream.
If the device underlying a zoned target is removed, its capacity is set to 0 and blkdev_report_zones() returns 0 without reporting any zones. The mapped device keeps its old capacity, so args->zone_idx and args->next_sector never advance and dm_blk_do_report_zones() loops forever. On non-preemptible kernels this causes soft lockups and RCU stalls.
The following sequence of commands triggers the hang:
modprobe scsi_debug zbc=managed dev_size_mb=1024 zone_size_mb=64 udevadm settle
echo '0 2097152 linear /dev/sda 0' | dmsetup create lin echo 1 > /sys/block/sda/device/delete
blkzone report -o 0 -c 1 /dev/mapper/lin
Fix this by returning -EIO when a target reports no zones. The target always maps args->next_sector, so a zero return means the underlying device no longer covers that sector.
--- drivers/md/dm-zone.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/md/dm-zone.c +2 -0
@@ -33,6 +33,8 @@ static int dm_blk_do_report_zones(struct nr_zones - args->zone_idx);if (ret <0 )return ret; +if (!ret) +return -EIO ; }while (args->zone_idx < nr_zones && args->next_sector <get_capacity (md->disk));
Greg Kroah-Hartman
maintainerPATCH 853/990 dm: Reject table setup after queue or disk teardown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kirtikumar Anandrao Ramchandani <[email protected]>
commit ae310e4ad872a42f4707a596e66417f2aaa52826 upstream.
A failed table load can leave a mapped device in a state where its queue has already been initialized or its disk has been removed, while md->type is still DM_TYPE_NONE. A later table load then calls blk_mq_init_allocated_queue() on the same queue. If del_gendisk() exited the old hardware contexts, blk_mq_exit_hctx() dereferences their cleared flush queue pointer.
Reject setup attempts after queue initialization or disk removal. A failed request queue initialization still leaves md->tag_set NULL and can be retried. Set the request-based disk operations only after that initialization succeeds, so an unsuccessful attempt cannot leave a bio-based retry with request-based operations.
--- drivers/md/dm.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm.c +5 -1
@@ -2596,13 +2596,17 @@ int dm_setup_md_queue(struct mapped_deviWARN_ON_ONCE (type ==DM_TYPE_NONE ); +/* A failed setup may have left the queue initialized or the disk dead. */ +if (md->tag_set ||test_bit (GD_DEAD , &md->disk->state)) +return -ENODEV ; +if (type ==DM_TYPE_REQUEST_BASED ) { - md->disk->fops = &dm_rq_blk_dops; r =dm_mq_init_request_queue (md, t);if (r) {DMERR ("Cannot initialize queue for request-based dm mapped device" );return r; } + md->disk->fops = &dm_rq_blk_dops; } r =dm_calculate_queue_limits (t, &limits);
Greg Kroah-Hartman
maintainerPATCH 854/990 dm cache: reject kcopyd client destory if it setup failed
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Edward Adam Davis <[email protected]>
commit 8b97b168eb4d3affcf23d2980a0c3f35ed9262e2 upstream.
The value of cache->copier is -EINTR when failed to create a rescuer kthread for wq kcopyd, in cache_create(), the code jumps directly to __destroy(cache), it merely performs a simple check to see whether copier is NULL, potentially hitting:
BUG: KASAN: null-ptr-deref in dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980 Read of size 4 at addr 0000000000000174 by task syz.2.19/6560 Call Trace: dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980 __destroy+0x172/0x2f0 drivers/md/dm-cache-target.c:1973 cache_create drivers/md/dm-cache-target.c:2604 [inline] cache_ctr+0x1674/0x2bf0 drivers/md/dm-cache-target.c:2649 dm_table_add_target+0x58d/0xc70 drivers/md/dm-table.c:749 populate_table drivers/md/dm-ioctl.c:1602 [inline] table_load+0x325/0x8a0 drivers/md/dm-ioctl.c:1645 ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]
Set copier to NULL to avoid destroying a invalid kcopy client.
--- drivers/md/dm-cache-target.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-cache-target.c +1 -0
@@ -2550,6 +2550,7 @@ static int cache_create(struct cache_argif (IS_ERR (cache->copier)) { *error ="could not create kcopyd client" ; r =PTR_ERR (cache->copier); + cache->copier =NULL ; goto bad; }
Greg Kroah-Hartman
maintainerPATCH 855/990 dm crypt: fix use of uninitialized percpu_counter in ctr error path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Feng <[email protected]>
commit 8ba1ade3e6b595b9091040feaa3341d7e45ba95d upstream.
If percpu_counter_init() fails in crypt_ctr() (e.g. when the underlying percpu allocation fails under memory pressure or fault injection), the error path jumps to "bad", which calls crypt_dtr(). crypt_dtr() then evaluates WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0) and calls percpu_counter_destroy() on a counter that was never initialized, because __percpu_counter_init_many() returns -ENOMEM before calling raw_spin_lock_init() on fbc->lock.
With lockdep enabled this triggers "INFO: trying to register non-static key" in __percpu_counter_sum(), as reported by syzbot. The console additionally shows "crypt: Unknown error (-ENOMEM)" because this failure path sets no ti->error.
Move percpu_counter_init() to right after the allocation of cc, before ti->private is set and before any "goto bad" can happen. On failure, set ti->error and free cc directly, so that crypt_dtr() is only ever called with an initialized counter.
--- drivers/md/dm-crypt.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/md/dm-crypt.c +8 -4
@@ -3287,6 +3287,14 @@ static int crypt_ctr(struct dm_target *t ti->error ="Cannot allocate encryption context" ;return -ENOMEM ; } + + ret =percpu_counter_init (&cc->n_allocated_pages,0 ,GFP_KERNEL ); +if (ret <0 ) { + ti->error ="Cannot initialize page counter" ; +kfree_sensitive (cc); +return ret; + } + cc->key_size = key_size; cc->sector_size = (1 <<SECTOR_SHIFT ); cc->sector_shift =0 ;
@@ -3298,10 +3306,6 @@ static int crypt_ctr(struct dm_target *tcrypt_calculate_pages_per_client ();spin_unlock (&dm_crypt_clients_lock); - ret =percpu_counter_init (&cc->n_allocated_pages,0 ,GFP_KERNEL ); -if (ret <0 ) - goto bad; -/* Optional parameters need to be read before cipher constructor */ if (argc >5 ) { ret =crypt_ctr_optional (ti, argc -5 , &argv[5 ]);
Greg Kroah-Hartman
maintainerPATCH 856/990 dm mpath: fix buffer overflow in parse_hw_handler()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: [email protected] <[email protected]>
commit 8f611fe94a781c6fb658488cc7eab4e4923e6df6 upstream.
parse_hw_handler() builds the hw_handler parameter string in a buffer sized with
len = 4;
plus one byte per argument. Those four bytes were meant for the decimal form of the parameter count, three digits plus the terminating NUL. dm_read_arg_group() accepts up to 1024 arguments and the count written is 'hw_argc - 1', so a count of 1000 or more needs four digits plus the NUL and sprintf() writes one byte past the allocation.
Size the buffer from the actual string length instead.
--- drivers/md/dm-mpath.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -1084,8 +1084,9 @@ static int parse_hw_handler(struct dm_arif (hw_argc >1 ) {char *p; -int i, j, len =4 ; +int i, j, len; + len =snprintf (NULL ,0 ,"%d" , hw_argc -1 ) +1 ;for (i =0 ; i <= hw_argc -2 ; i++) len +=strlen (as->argv[i]) +1 ; p = m->hw_handler_params =kzalloc (len,GFP_KERNEL );
Greg Kroah-Hartman
maintainerPATCH 857/990 dm mpath: cap queue_if_no_path_timeout_secs
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit ae5b40accbc06f93e6a513e0e9a07fd32b197e49 upstream.
enable_nopath_timeout() arms the no-path timer with
jiffies + queue_if_no_path_timeout_secs * HZ. The module parameter is an unbounded unsigned long, so the delay can exceed what mod_timer()
handles: a delay above LONG_MAX is treated as already expired, and values above ULONG_MAX / HZ also wrap in the multiplication. The timer then clears queue_if_no_path right away, and I/O queued after the last path fails gets -EIO instead of waiting for the configured time.
On x86-64 with HZ=1000, 9223372036854776 seconds failed a write after 124 ms while one second less remained queued throughout a 4.2-second observation window. A value of 18446744073709552 seconds wrapped to 384 jiffies and failed the write after 455 ms. On 32-bit kernels with HZ=1000 the delay passes LONG_MAX above 2147483 seconds, a little under 25 days.
Cap the seconds value at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET before multiplying by HZ. This prevents signed-delta overflow and multiplication wrap. The timer wheel's existing handling of very long delays is unchanged.
--- drivers/md/dm-mpath.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -803,7 +803,8 @@ static void queue_if_no_path_timeout_worstatic void enable_nopath_timeout (struct multipath *m) {unsigned long queue_if_no_path_timeout = -READ_ONCE (queue_if_no_path_timeout_secs) *HZ ; + min_t(unsigned long, READ_ONCE(queue_if_no_path_timeout_secs), +MAX_JIFFY_OFFSET /HZ ) *HZ ;lockdep_assert_held (&m->lock);
Greg Kroah-Hartman
maintainerPATCH 858/990 dm thin: avoid wrapping no_space_timeout
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
commit bcb78d49620f666b4a9d62997691e8d031fd4ebc upstream.
set_pool_mode() converts the no_space_timeout module parameter with READ_ONCE(no_space_timeout_secs) * HZ. The usual arithmetic conversions evaluate the product as unsigned int, so it can wrap before being stored in the unsigned long delay. With HZ=1000, 4294968 seconds becomes 704
jiffies: a pool that runs out of data space switches to error_if_no_space and fails queued writes with -ENOSPC after about 0.7 seconds.
Widen the value before the multiplication and cap it at MAX_JIFFY_OFFSET / HZ, so large timeouts no longer wrap into short delays. On 32-bit kernels, values beyond the supported jiffies range saturate at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET. The timer wheel's existing handling of very long delays is unchanged.
--- drivers/md/dm-thin.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-thin.c +3 -1
@@ -2544,7 +2544,9 @@ static void set_pool_mode(struct pool *pstruct pool_c *pt = pool->ti->private;bool needs_check =dm_pool_metadata_needs_check (pool->pmd);enum pool_mode old_mode =get_pool_mode (pool); -unsigned long no_space_timeout =READ_ONCE (no_space_timeout_secs) *HZ ; +unsigned long no_space_timeout = + min_t(unsigned long, READ_ONCE(no_space_timeout_secs), +MAX_JIFFY_OFFSET /HZ ) *HZ ;/* * Never allow the pool to transition to PM_WRITE mode if user
Greg Kroah-Hartman
maintainerPATCH 859/990 dm-pcache: do not advance dirty_tail after backing flush failure
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: guolingxing <[email protected]>
commit b1310cb291935c788f34ed6eb1e7e9b42cfac045 upstream.
After all writeback bios for a kset complete, writeback_ctx_end() flushes the backing device and then advances the persistent dirty_tail. However, backing_dev_flush() discards the error returned by blkdev_issue_flush(), so dirty_tail is advanced even when the written data is not known to be durable.
dirty_tail points to the first kset that still requires writeback. Advancing it causes recovery to treat the preceding kset as clean and allows its cache copy to eventually be reclaimed by garbage collection. If the backing device flush failed, a subsequent power failure may therefore result in data loss.
Make backing_dev_flush() return the flush status and handle a flush failure like a writeback I/O failure. Leave dirty_tail unchanged so that the same kset will be retried.
--- drivers/md/dm-pcache/backing_dev.c | 4 ++-- drivers/md/dm-pcache/backing_dev.h | 2 +- drivers/md/dm-pcache/cache_writeback.c | 28 +++++++++++++++++++------- 3 files changed, 24 insertions(+), 10 deletions(-)
drivers/md/dm-pcache/backing_dev.c +2 -2
@@ -336,9 +336,9 @@ struct pcache_backing_dev_req *backing_dev_req_create(struct pcache_backing_devreturn backing_req; } -void backing_dev_flush (struct pcache_backing_dev *backing_dev) +int backing_dev_flush (struct pcache_backing_dev *backing_dev) { -blkdev_issue_flush (backing_dev->dm_dev->bdev); +return blkdev_issue_flush (backing_dev->dm_dev->bdev); }int pcache_backing_init (void )
drivers/md/dm-pcache/backing_dev.h +1 -1
@@ -120,7 +120,7 @@ struct pcache_backing_dev_req *backing_dev_req_alloc(struct pcache_backing_dev * struct pcache_backing_dev_req_opts *opts);void backing_dev_req_init (struct pcache_backing_dev_req *backing_req,struct pcache_backing_dev_req_opts *opts); -void backing_dev_flush (struct pcache_backing_dev *backing_dev); +int backing_dev_flush (struct pcache_backing_dev *backing_dev);int pcache_backing_init (void );void pcache_backing_exit (void );
drivers/md/dm-pcache/cache_writeback.c +21 -7
@@ -18,12 +18,18 @@ static void writeback_ctx_end(struct pcache_cache *cache, int ret)return ;if (!cache->writeback_ctx.ret) { -backing_dev_flush (cache->backing_dev); - -mutex_lock (&cache->dirty_tail_lock); -cache_pos_advance (&cache->dirty_tail, cache->writeback_ctx.advance); -cache_encode_dirty_tail (cache); -mutex_unlock (&cache->dirty_tail_lock); + ret =backing_dev_flush (cache->backing_dev); +if (ret) { +pcache_dev_err (CACHE_TO_PCACHE (cache), +"failed to flush backing device: %d" , ret); + cache->writeback_ctx.ret = ret; + }else { +mutex_lock (&cache->dirty_tail_lock); +cache_pos_advance (&cache->dirty_tail, + cache->writeback_ctx.advance); +cache_encode_dirty_tail (cache); +mutex_unlock (&cache->dirty_tail_lock); + } }queue_delayed_work (cache_get_wq (cache), &cache->writeback_work,0 ); }
@@ -76,8 +82,16 @@ static inline bool is_cache_clean(struct pcache_cache *cache, struct pcache_cachvoid cache_writeback_exit (struct pcache_cache *cache) { +int ret; +cancel_delayed_work_sync (&cache->writeback_work); -backing_dev_flush (cache->backing_dev); + + ret =backing_dev_flush (cache->backing_dev); +if (ret) +pcache_dev_err (CACHE_TO_PCACHE (cache), +"failed to flush backing device during exit: %d" , + ret); +cache_tree_exit (&cache->writeback_key_tree); }
Signature · 1 line
2.56.1
Greg Kroah-Hartman
maintainerPATCH 860/990 dm-sysfs: fix misbehavior if kobject_init_and_add fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 406d576cc457203cf86eac7f17839b2efec81db4 upstream.
If kobject_init_and_add fails, we must call kobject_put (see the comment at kobject_init_and_add).
Before calling kobject_init_and_add, we must zero the kobject (see
https://lwn.net/Articles/52085/). If the first call to dm_sysfs_init failed, it may be called again, and that second call would see an uninitialized kobject.
--- drivers/md/dm-sysfs.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-)
drivers/md/dm-sysfs.c +14 -3
@@ -132,9 +132,20 @@ static const struct kobj_type dm_ktype =*/ int dm_sysfs_init (struct mapped_device *md) { -return kobject_init_and_add (dm_kobject (md), &dm_ktype, - &disk_to_dev (dm_disk (md))->kobj, -"%s" ,"dm" ); +struct kobject *kobj =dm_kobject (md); +int r; + +/* The kobject must be zeroed before calling kobject_init */ +memset (kobj,0 ,sizeof (struct kobject )); + r =kobject_init_and_add (kobj, &dm_ktype, + &disk_to_dev (dm_disk (md))->kobj, +"%s" ,"dm" ); +if (unlikely (r)) { +/* Weird semantics - we must call kobject_put on failure */ +dm_sysfs_exit (md); +return r; + } +return 0 ; }/*
Greg Kroah-Hartman
maintainerPATCH 861/990 dm-verity: dont restart or panic on errors during system shutdown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weijiang Zhou <[email protected]>
commit 47930d1236d2988cdc580c10d3af21b6b02d7ece upstream.
Commit 252bd1256396 ("dm verity: skip verity work if I/O error when system is shutting down") stopped I/O errors during shutdown from triggering a restart, since devices may legitimately be gone by then. Errors that reach verity_handle_err(), e.g. through a failed hash block read followed by a failed FEC attempt, are not covered and still call kernel_restart() or panic().
During a reboot that is both wrong (nothing is corrupt) and harmful: it races with the reboot already in progress and replaces its reason with "dm-verity device corrupted", which bootloaders such as Android's treat as a verity failure and switch the device to EIO mode.
Apply the same shutdown check in verity_handle_err(). Corruption is still logged, recorded in hash_failed and reported via uevent, and the I/O still fails.
--- drivers/md/dm-verity-target.c | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-)
drivers/md/dm-verity-target.c +18 -9
@@ -156,6 +156,15 @@ static void verity_hash_at_level(struct }/* +* Skip verity work in response to I/O error when system is shutting down. +*/ +static inline bool verity_is_system_shutting_down (void ) +{ +return system_state ==SYSTEM_HALT || system_state ==SYSTEM_POWER_OFF + || system_state ==SYSTEM_RESTART ; +} + +/* * Handle verification errors. */ static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
@@ -204,6 +213,15 @@ out:if (v->mode ==DM_VERITY_MODE_LOGGING )return 0 ; +/* +* Devices may already be quiesced (e.g. UFS set offline by its +* shutdown hook), so a failure here does not imply corruption. Fail +* the I/O but do not restart or panic, which would also override the +* reboot reason of the shutdown already in progress. +*/ +if (verity_is_system_shutting_down ()) +return 1 ; +if (v->mode ==DM_VERITY_MODE_RESTART )kernel_restart ("dm-verity device corrupted" );
@@ -523,15 +541,6 @@ static int verity_verify_io(struct dm_vereturn 0 ; } -/* -* Skip verity work in response to I/O error when system is shutting down. -*/ -static inline bool verity_is_system_shutting_down (void ) -{ -return system_state ==SYSTEM_HALT || system_state ==SYSTEM_POWER_OFF - || system_state ==SYSTEM_RESTART ; -} -static void restart_io_error (struct work_struct *w) {kernel_restart ("dm-verity device has I/O error" );
Greg Kroah-Hartman
maintainerPATCH 862/990 dm persistent data: test return value of node_copy
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 624d146d97c5fbe7200ef4b2dd5350ecf57d6b79 upstream.
There were 3 places where the return value of node_copy was not tested.
--- drivers/md/persistent-data/dm-btree-remove.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-btree-remove.c +10 -3
@@ -253,7 +253,9 @@ static int __rebalance2(struct dm_btree_/* * Merge */ -node_copy (left, right, -nr_right); + ret =node_copy (left, right, -nr_right); +if (unlikely (ret)) +return ret; left->header.nr_entries =cpu_to_le32 (nr_left + nr_right);delete_at (parent, r->index);
@@ -315,13 +317,16 @@ static int delete_center_node(struct dm_ {uint32_t max_entries =le32_to_cpu (left->header.max_entries);unsigned int shift =min (max_entries - nr_left, nr_center); +int ret;if (nr_left + shift > max_entries) {DMERR ("node shift out of bounds" );return -EINVAL ; } -node_copy (left, center, -shift); + ret =node_copy (left, center, -shift); +if (unlikely (ret)) +return ret; left->header.nr_entries =cpu_to_le32 (nr_left + shift);if (shift != nr_center) {
@@ -333,7 +338,9 @@ static int delete_center_node(struct dm_ }node_shift (right, shift); -node_copy (center, right, shift); + ret =node_copy (center, right, shift); +if (unlikely (ret)) +return ret; right->header.nr_entries =cpu_to_le32 (nr_right + shift); } *key_ptr (parent, r->index) = right->keys[0 ];
Greg Kroah-Hartman
maintainerPATCH 863/990 dm persistent data: dont ignore writeback errors
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit fa887f2ebee7aff97eb87b3365939616ade09774 upstream.
An error returned by ie_cache_writeback could be silently overwritten by another successful ie_cache_writeback. This commit fixes disk_ll_commit, so that it doesn't ignore the error and returns it immediatelly.
--- drivers/md/persistent-data/dm-space-map-common.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-space-map-common.c +6 -3
@@ -1190,17 +1190,20 @@ static dm_block_t disk_ll_max_entries(ststatic int disk_ll_commit (struct ll_disk *ll) { -int r =0 ; +int r;unsigned int i;for (i =0 ; i <IE_CACHE_SIZE ; i++) {struct ie_cache *iec = ll->ie_cache + i; -if (iec->valid && iec->dirty) +if (iec->valid && iec->dirty) { r =ie_cache_writeback (ll, iec); +if (unlikely (r)) +return r; + } } -return r; +return 0 ; }int sm_ll_new_disk (struct ll_disk *ll,struct dm_transaction_manager *tm)
Greg Kroah-Hartman
maintainerPATCH 864/990 dm persistent data: dont leak bufio buffer if find_leaf fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit b27523a0781aae0b51ac13f29dc65373d14b8434 upstream.
If find_leaf fails, the function dm_btree_cursor_begin would return an error, but it would keep the dm-bufio buffers held. This would result in a memory leak and a warning when releasing the dm-bufio cache.
This commit fixes it, so that dm_btree_cursor_begin releases the buffers on error.
--- drivers/md/persistent-data/dm-btree.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/persistent-data/dm-btree.c +7 -1
@@ -1582,7 +1582,13 @@ int dm_btree_cursor_begin(struct dm_btreif (r)return r; -return find_leaf (c); + r =find_leaf (c); +if (unlikely (r)) { +dm_btree_cursor_end (c); +return r; + } + +return 0 ; }EXPORT_SYMBOL_GPL (dm_btree_cursor_begin);
Greg Kroah-Hartman
maintainerPATCH 865/990 dm snapshot: fix discard_granularity unit in snapshot_io_hints
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: wuyuehong <[email protected]>
commit d7216d7be2bbfdf3312695b6e41a4fc7c5e22902 upstream.
snapshot_io_hints() copies the snapshot store's chunk_size, which is in 512-byte sectors, into queue_limits.discard_granularity, which, like all other members of struct queue_limits, is in bytes.
For snapshots with a chunk size smaller than 512 sectors, e.g. the 16 KiB (32-sector) chunks created by the syzkaller reproducer, the resulting granularity is smaller than a single sector. When dm_calculate_queue_limits() then stacks the target limits into the table limits:
blk_stack_limits(limits, &ti_limits, 0)
queue_limit_discard_alignment() truncates that granularity to zero sectors and sector_div() divides by zero:
Oops: divide error: 0000 [#1] SMP KASAN NOPTI RIP: 0010:queue_limit_discard_alignment block/blk-settings.c:645 [inline] RIP: 0010:blk_stack_limits+0x1105/0x2d00 block/blk-settings.c:916 Call Trace: dm_calculate_queue_limits+0x70c/0x1510 drivers/md/dm-table.c:1823 dm_setup_md_queue+0x199/0x4f0 drivers/md/dm.c:2618 table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661
The divide fault itself only became reachable when commit e924da7d6622 ("block: Drop granularity check in queue_limit_discard_alignment()") removed the check for a sub-sector granularity in v6.13. Kernels before that returned a zero discard alignment instead of faulting, but they still advertised a granularity 512 times too small.
Use the same chunk_size << SECTOR_SHIFT conversion that io_overlaps_chunk() already applies to turn chunk_size into bytes.
--- drivers/md/dm-snap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-snap.c +1 -1
@@ -2420,7 +2420,7 @@ static void snapshot_io_hints(struct dm_ snap = snap_src;/* All discards are split on chunk_size boundary */ - limits->discard_granularity = snap->store->chunk_size; + limits->discard_granularity = snap->store->chunk_size <<SECTOR_SHIFT ; limits->max_hw_discard_sectors = snap->store->chunk_size;up_read (&_origins_lock);
Greg Kroah-Hartman
maintainerPATCH 866/990 dm snapshot: split discards on chunk boundaries
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chen Cheng <[email protected]>
commit 4fe2c2baad01da64d47f1a0c8fc093df994bcef5 upstream.
dm-snapshot did not set ti->max_discard_granularity when it allows discards, so a discard could reach the target unaligned, or spanning several chunks. Set the flag, so dm splits discards on chunk boundaries.
--- drivers/md/dm-snap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-snap.c +3 -1
@@ -1364,8 +1364,10 @@ static int snapshot_ctr(struct dm_target ti->private = s; ti->num_flush_bios = num_flush_bios; -if (s->discard_zeroes_cow) +if (s->discard_zeroes_cow) { ti->num_discard_bios = (s->discard_passdown_origin ?2 :1 ); + ti->max_discard_granularity = true; + } ti->per_io_data_size =sizeof (struct dm_snap_tracked_chunk );/* Add snapshot to the list of snapshots for this origin */
Greg Kroah-Hartman
maintainerPATCH 867/990 dm snapshot: fix discard writing into the next COW chunk
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chen Cheng <[email protected]>
commit 73174b4bb6fcd0e6cf973c9402a0fae2e567ad9f upstream.
zero_exception() zeroes one chunk of the COW device and takes the start sector from bio->bi_iter.bi_sector. remap_exception() has already set that to the COW chunk start plus the offset inside the chunk. That offset is needed for reads and writes, but for a discard it is wrong:
the zeroing window is shifted, so the head of the target chunk keeps its old data and the tail lands in the next COW chunk, which holds a different exception.
io_overlaps_chunk() should have caught this, but it only compares the length. "maps to entire chunks" in snapshot.rst also means the discard has to start on a chunk boundary.
A discard that is not a full chunk has a second problem: after remap_exception() it is sent to the COW device, where it hits a chunk that still backs a live exception. After a discard the contents are undefined, but the exception stays in the table and keeps pointing at that chunk, so a later read returns whatever the discard left instead of the snapshot's data.
Reproducer:
truncate -s 4M o.img c.img o=$(losetup -f --show o.img) c=$(losetup -f --show c.img) dmsetup create snap --table \ "0 8192 snapshot $o $c P 512 1 discard_zeroes_cow" # write two chunks, this creates two exceptions head -c 256K /dev/zero | tr '\000' '\252' > pat dd if=pat of=/dev/mapper/snap bs=256K seek=1 count=1 conv=notrunc dd if=pat of=/dev/mapper/snap bs=256K seek=2 count=1 conv=notrunc # shift the snapshot by 8 sectors, so a discard that is aligned on # top is unaligned inside the snapshot dmsetup create top --table "0 8184 linear /dev/mapper/snap 8" blkdiscard -o 262144 -l 262144 /dev/mapper/top sync echo 3 > /proc/sys/vm/drop_caches # chunk 1 dd if=/dev/mapper/snap bs=512 skip=512 count=8 | od -An -tx1 -N1 # chunk 2 dd if=/dev/mapper/snap bs=512 skip=1024 count=8 | od -An -tx1 -N1
Before: aa 00 <- chunk 2 was zeroed although it was not discarded After: aa aa <- nothing written, a discard is only a hint
Fix it by requiring the discard to start on a chunk boundary in io_overlaps_chunk(), and by finishing a discard that is not a full chunk with bio_endio() instead of passing it down to the COW device.
--- drivers/md/dm-snap.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/md/dm-snap.c +7 -5
@@ -1954,8 +1954,8 @@ static void zero_exception(struct dm_snastatic bool io_overlaps_chunk (struct dm_snapshot *s,struct bio *bio) { -return bio->bi_iter.bi_size == - (s->store->chunk_size <<SECTOR_SHIFT ); +return bio->bi_iter.bi_size == (s->store->chunk_size <<SECTOR_SHIFT ) && + !(bio->bi_iter.bi_sector & s->store->chunk_mask); }static int snapshot_map (struct dm_target *ti,struct bio *bio)
@@ -2015,11 +2015,13 @@ static int snapshot_map(struct dm_target e =dm_lookup_exception (&s->complete, chunk);if (e) {remap_exception (s, e, bio, chunk); -if (unlikely (bio_op (bio) ==REQ_OP_DISCARD ) && -io_overlaps_chunk (s, bio)) { +if (unlikely (bio_op (bio) ==REQ_OP_DISCARD )) {dm_exception_table_unlock (&lock);up_read (&s->lock); -zero_exception (s, e, bio, chunk); +if (io_overlaps_chunk (s, bio)) +zero_exception (s, e, bio, chunk); +else +bio_endio (bio); r =DM_MAPIO_SUBMITTED ;/* discard is not issued */ goto out; }
Greg Kroah-Hartman
maintainerPATCH 868/990 dm zoned: back off when reclaim cannot make progress
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyrylo Biryuk <[email protected]>
commit 9bb1d14877f4929be17f7fdbeb4cfdf5025d464b upstream.
When a reclaim pass cannot make progress, dmz_reclaim_work() still ends with dmz_schedule_reclaim(). If the target is idle, dmz_should_reclaim() keeps returning true, the work is queued again with no delay and the worker spins on the same failing pass. This patch handles two such cases:
- dmz_do_reclaim() fails with -ENOSPC because no free zone is available to copy the data into, for example on a target without cache zones that has no free sequential zone left. The next patch also makes this the expected result when an idle target with cache zones has random zones but no free sequential zone.
- dmz_do_reclaim() finds no zone it can lock for reclaim and returns -EBUSY. Since commit 90a9b8693f1b ("dm zoned: reclaim random zones when idle"), dmz_should_reclaim() returns true on an idle target whenever the total number of random (and cache) zones is non-zero, whether or not any of them holds data. Each pass then also runs dmz_check_dev(), which checks every device for media events (a TEST UNIT READY on SCSI disks).
The -EBUSY loop lasts as long as the target stays idle; it ends when a pass finishes while the target is busy and has enough free zones. On three 27 TB host-managed SATA drives used as md RAID5 members (7.2.10 with the module built out of tree, all random zones free, target idle for 300 seconds, kprobes attached, two other drives on the controller being zero-filled), each member's SCSI device counted about 108,000 requests per second with the stock module and the system used about 915 s of CPU time, against about 46 s with this series. libata completes TEST UNIT READY in software, so these counters do not measure commands sent to the drives; the cost is CPU time.
When a pass fails with -ENOSPC or -EBUSY, retrying at once is unlikely to make progress: re-arm the idle poll instead, so that reclaim is retried after DMZ_IDLE_PERIOD unless a zone allocation or a "reclaim" message queues it earlier. On a busy target, zone allocations can restart reclaim immediately when free space is low enough to require reclaim. Re-arming also keeps the poll running after a complete idle drain. The poll can still stop after a pass that ends while reclaim is not needed; that is unchanged.
Skip the device check for these two results: they normally mean that there is no zone to copy into or no zone to reclaim, not that a device failed, and the I/O paths check the devices themselves. Use queue_delayed_work() so that work an allocation has already queued is not postponed.
A pass that fails with an I/O error, for example on an unreadable block of a device that stays online, is still retried at once while the target is idle; this patch does not change that.
Tested on 7.4-rc1 with this patch and the next one, on three emulated host-managed drives (scsi_debug, 1 GiB, 32 MiB zones) each under dm-zoned as md RAID5 members, all random zones free and the target idle for 300 seconds. With the stock module each member's SCSI device counted about 70.2 million requests and the reclaim workers used 726 s of CPU. With this series: 75 requests per member, 30 passes per worker (one per DMZ_IDLE_PERIOD) and 0.08 s of CPU. Data written during the tests read back with matching checksums, and no kernel warnings were logged.
--- drivers/md/dm-zoned-reclaim.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
drivers/md/dm-zoned-reclaim.c +10 -0
@@ -539,6 +539,16 @@ static void dmz_reclaim_work(struct work dmz_nr_rnd_zones(zmd, zrc->dev_idx)); ret =dmz_do_reclaim (zrc); +if (ret == -ENOSPC || ret == -EBUSY ) { +/* +* No zone to copy into (-ENOSPC) or no zone to reclaim +* (-EBUSY): retrying at once cannot make progress and would +* spin. Poll again after the idle period instead, without +* postponing work that an allocation has already queued. +*/ +queue_delayed_work (zrc->wq, &zrc->work,DMZ_IDLE_PERIOD ); +return ; + }if (ret && ret != -EINTR ) {if (!dmz_check_dev (zmd))return ;
Greg Kroah-Hartman
maintainerPATCH 869/990 dm zoned: do not reclaim a random zone into another random zone
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyrylo Biryuk <[email protected]>
commit dab527d83462a618d99bfc96370ce45ae3428706 upstream.
dmz_reclaim_rnd_data() falls back to a random destination zone when no free sequential zone is available and the target has cache zones. When the target is idle and the cache zone list is empty, dmz_get_rnd_zone_for_reclaim() selects random zones of the zoned device as well, so a random zone is then copied into another random zone. That frees nothing: the next pass picks the next random zone and copies it again, for as long as the target stays idle.
Seen on a two-device target (256 GiB regular cache device plus a 27 TB host-managed drive) used as an md RAID5 member: after a full rebuild every chunk was mapped and no sequential zone was free, and the idle drive kept reading and writing while the free zone counters in "dmsetup status" did not change.
Only switch to a random destination zone when the zone being reclaimed is a cache zone: moving it to the zoned device still frees cache space.
This depends on "dm zoned: back off when reclaim cannot make progress":
without it, dmz_reclaim_work() would retry the resulting -ENOSPC at once, and run dmz_check_dev(), for as long as the target stays idle.
Tested on 7.4-rc1 together with the previous patch, on a two-device target (a 512 MiB RAM-backed regular cache device plus a 1 GiB scsi_debug host-managed drive) filled until no sequential zone was free, then idle for 60 seconds: the stock module made 877 random-to-random copies; with this series it made none, and each pass failed with -ENOSPC once per DMZ_IDLE_PERIOD without a device check.
--- drivers/md/dm-zoned-reclaim.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/dm-zoned-reclaim.c +7 -1
@@ -290,7 +290,13 @@ static int dmz_reclaim_rnd_data(struct d again: szone =dmz_alloc_zone (zmd, zrc->dev_idx, alloc_flags |DMZ_ALLOC_RECLAIM ); -if (!szone && alloc_flags ==DMZ_ALLOC_SEQ &&dmz_nr_cache_zones (zmd)) { +/* +* If no free sequential zone is available, a cache zone can still be +* moved into a free random zone of the zoned device, which frees cache +* space. Do not do this for a random zone: moving it into another +* random zone frees nothing and, on an idle target, repeats forever. +*/ +if (!szone && alloc_flags ==DMZ_ALLOC_SEQ &&dmz_is_cache (dzone)) { alloc_flags =DMZ_ALLOC_RND ; goto again; }
Greg Kroah-Hartman
maintainerPATCH 870/990 dm-cache: fix NULL pointer dereference on open failure
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit d12afc2f9ed6e14019fed9c02a74ad699915dc85 upstream.
When __begin_transaction_flags in metadata_open fails, dm_cache_metadata_close is called. dm_cache_metadata_close attempts to execute list_del(&cmd->list);, but the "cmd" object is not on any list yet, thus it crashes with NULL pointer dereference.
Fix this by initializing cmd->list after cmd is allocated.
--- drivers/md/dm-cache-metadata.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-cache-metadata.c +1 -0
@@ -766,6 +766,7 @@ static struct dm_cache_metadata *metadatreturn ERR_PTR (-ENOMEM ); } +INIT_LIST_HEAD (&cmd->list); cmd->version = metadata_version;refcount_set (&cmd->ref_count,1 );init_rwsem (&cmd->root_lock);
Greg Kroah-Hartman
maintainerPATCH 871/990 dm-cache: fix ending a cursor that never began
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 421420758be348cb90715bfaa26e1211a12ff1d0 upstream.
If dm_bitset_cursor_begin fails, dm_array_cursor_end(&cmd->hint_cursor) is called. However, cmd->hint_cursor was only initialized if the variable hints_valid is true. Thus, we must also destroy hint_cursor only if hints_valid is true.
--- drivers/md/dm-cache-metadata.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-cache-metadata.c +2 -1
@@ -1433,7 +1433,8 @@ static int __load_mappings(struct dm_cacfrom_cblock (cmd->cache_blocks), &cmd->dirty_cursor);if (r) { -dm_array_cursor_end (&cmd->hint_cursor); +if (hints_valid) +dm_array_cursor_end (&cmd->hint_cursor);dm_array_cursor_end (&cmd->mapping_cursor);return r; }
Greg Kroah-Hartman
maintainerPATCH 872/990 dm-crypt: reject integrity_key_size with non-authenc AEAD ciphers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: xietangxin <[email protected]>
commit bd93c4e59c5132282c01f142806e307c7380e7ea upstream.
When integrity_key_size parameter is paired with a pure AEAD cipher that is not an authenc composite, crypt_ctr_auth_cipher() returns 0 early without allocating cc->authenc_key, but cc->key_mac_size remains non-zero because CRYPT_KEY_MAC_SIZE_SET was set during option parsing. As a result crypt_copy_authenckey() dereferences NULL crashes the kernel.
Reject the contradictory configuration explicitly instead of silently returning 0, so userspace gets a clear -EINVAL.
--- drivers/md/dm-crypt.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/md/dm-crypt.c +4 -1
@@ -2905,8 +2905,11 @@ static int crypt_ctr_auth_cipher(structchar *start, *end, *mac_alg =NULL ;struct crypto_ahash *mac; -if (!strstarts (cipher_api,"authenc(" )) +if (!strstarts (cipher_api,"authenc(" )) { +if (test_bit (CRYPT_KEY_MAC_SIZE_SET , &cc->cipher_flags)) +return -EINVAL ;return 0 ; + } start =strchr (cipher_api,'(' ); end =strchr (cipher_api,',' );
Greg Kroah-Hartman
maintainerPATCH 873/990 dm-crypt: defer async write submission to write thread
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Schlehofer <[email protected]>
commit 6fed9e26810f0b466dbcebe35a73d1fd48793ff5 upstream.
With no_write_workqueue, kcryptd_crypt_write_io_submit() submits the bio directly, even when called from kcryptd_async_done(). An async cipher may run this callback in softirq or with BH disabled, where submit_bio_noacct() must not be called because it can sleep.
Submit inline only when async is false. Async completions are sent to the write thread, as is already done for submit_from_crypt_cpus. Use the async flag rather than in_interrupt(), since callback context depends on the cipher driver. Sync ciphers still submit inline.
Tested with cryptd in QEMU (x86_64 and arm64) with CONFIG_DEBUG_ATOMIC_SLEEP, and on a P2020 running 6.18.55 without it.
In QEMU:
- 4k writes logging "sleeping function called from invalid context":
100/100 unpatched, 0/155 patched.
- nr_requests=4 on a loop device: 0/6 unpatched runs completed, 4/4 patched runs completed.
On the P2020, a warning in blk_mq_run_hw_queue() appeared in the 6th unpatched run and did not appear in 30 patched runs.
--- drivers/md/dm-crypt.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/md/dm-crypt.c +3 -2
@@ -2039,8 +2039,9 @@ static void kcryptd_crypt_write_io_submi/* crypt_convert should have filled the clone bio */ BUG_ON (io->ctx.iter_out.bi_size); -if ((likely (!async) &&test_bit (DM_CRYPT_NO_OFFLOAD , &cc->flags)) || -test_bit (DM_CRYPT_NO_WRITE_WORKQUEUE , &cc->flags)) { +if (likely (!async) && + (test_bit (DM_CRYPT_NO_OFFLOAD , &cc->flags) || +test_bit (DM_CRYPT_NO_WRITE_WORKQUEUE , &cc->flags))) {dm_submit_bio_remap (io->base_bio, clone);return ; }
Greg Kroah-Hartman
maintainerPATCH 874/990 dm-integrity: dont recalculate with HMAC because of a dirty bitmap
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sinan Polat <[email protected]>
commit 875a7161fe1574205293c36f7bbd0815023e48a1 upstream.
Commit 5c02406428d5 ("dm integrity: conditionally disable "recalculate" feature") refuses a superblock with SB_FLAG_RECALCULATING if a keyed hash is used without "legacy_recalculate". Otherwise someone who can write to the device, but does not know the key, could modify data and have the kernel compute valid tags for it.
dm_integrity_resume() can still start the same recalculation in J or D
mode: if SB_FLAG_DIRTY_BITMAP is set and the bitmap is not clear, or log2_blocks_per_bitmap_bit does not match, it sets SB_FLAG_RECALCULATING and recalc_sector = 0. The superblock is not authenticated unless fix_hmac and journal_mac are both used, so the flag can be set offline. Resume also runs on the first activation.
Apply the constructor's policy there. If recalculation is not allowed, log an error and keep the existing tags, so modified blocks fail verification. This also avoids queueing recalc_work on a NULL recalc_wq when internal_hash is not used.
--- drivers/md/dm-integrity.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-)
drivers/md/dm-integrity.c +22 -2
@@ -3886,6 +3886,24 @@ static bool superblock_changed(struct dmmemcmp (ic->sb->salt, ic->sb_copy->salt,SALT_SIZE ) !=0 ; } +/* +* The superblock is authenticated only if fix_hmac and journal_mac are used, +* so SB_FLAG_DIRTY_BITMAP may have been set by someone who doesn't know the +* key. Apply the policy that the constructor applies to SB_FLAG_RECALCULATING. +*/ +static bool dm_integrity_may_recalc_dirty_bitmap (struct dm_integrity_c *ic) +{ +if (!ic->internal_hash) { +DMERR ("Dirty bitmap found, but internal_hash is not used" ); +return false; + } +if (dm_integrity_disable_recalculate (ic)) { +DMERR ("Dirty bitmap found, but HMAC recalculation requires \"legacy_recalculate\"" ); +return false; + } +return true; +} +static void dm_integrity_resume (struct dm_target *ti) {struct dm_integrity_c *ic = ti->private;
@@ -3975,8 +3993,10 @@ static void dm_integrity_resume(struct dif (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&block_bitmap_op (ic, ic->journal,0 , ic->provided_data_sectors,BITMAP_OP_TEST_ALL_CLEAR )) || ic->reset_recalculate_flag) { - ic->sb->flags |=cpu_to_le32 (SB_FLAG_RECALCULATING ); - ic->sb->recalc_sector =cpu_to_le64 (0 ); +if (dm_integrity_may_recalc_dirty_bitmap (ic)) { + ic->sb->flags |=cpu_to_le32 (SB_FLAG_RECALCULATING ); + ic->sb->recalc_sector =cpu_to_le64 (0 ); + } }init_journal (ic,0 , ic->journal_sections,0 );replay_journal (ic);
Greg Kroah-Hartman
maintainerPATCH 875/990 dm-integrity: dont attempt to commit journal on disabled device
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit e5e03918fbec31f0c896f4f43c2bd2aadf35d43d upstream.
If the device is disabled due to an error, we shouldn't attempt to flush the journal. We jump straight to the label release_flush_bios, that will call do_endio on all queued bios. do_endio will terminate the bios with the error.
This fixes WARN_ON in the function pad_uncommitted reported by syzkaller.
--- drivers/md/dm-integrity.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm-integrity.c +5 -1
@@ -2906,6 +2906,11 @@ static void integrity_commit(struct workspin_lock_irq (&ic->endio_wait.lock); flushes =bio_list_get (&ic->flush_bio_list); +if (unlikely (dm_integrity_failed (ic))) { +wake_up_locked (&ic->endio_wait); +spin_unlock_irq (&ic->endio_wait.lock); + goto release_flush_bios; + }if (unlikely (ic->mode !='J' )) {spin_unlock_irq (&ic->endio_wait.lock);dm_integrity_flush_buffers (ic, true);
@@ -5418,7 +5423,6 @@ try_smaller_buffer: r =create_journal (ic, &ti->error);if (r) goto bad; - }if (ic->mode =='B' ) {
Greg Kroah-Hartman
maintainerPATCH 876/990 dm-raid: bound array_position before indexing failed_devices
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jay Vadayath <[email protected]>
commit 11b5cd14c0eecae458cecbe53d21a3dbc10190f5 upstream.
super_init_validation() reads role = le32_to_cpu(sb2->array_position) out of an on-disk dm_raid_superblock and then uses it as a bit index into the failed_devices bitmap via test_bit(role, (void *)failed_devices). failed_devices is a uint64_t[DISKS_ARRAY_ELEMS] (DISKS_ARRAY_ELEMS == 4, i.e. 256 bits) living on the stack. The only guard is role < 0, so any on-disk array_position >= 256 makes test_bit() read past the end of the stack array (array_position == 256 reads failed_devices[4], 8 bytes past the object). For a raid1 set the role != raid_disk reorder branch falls through to the same test_bit().
A crafted dm-raid superblock therefore causes a stack out-of-bounds read during table load. Reachable by anyone able to issue a dmsetup create with attacker-controlled metadata (CAP_SYS_ADMIN in the target namespace); the crash fires in the constructor / analyse_superblocks path, before any md_run or array sizing.
BUG: KASAN: stack-out-of-bounds in super_validate+0x1cd0/0x3390 Read of size 8 at addr ffff888007b17828 by task poc/152 Call Trace: dump_stack_lvl+0x64/0x80 print_report+0xd0/0x630 kasan_report+0xe5/0x120 kasan_check_range+0x105/0x1b0 super_validate+0x1cd0/0x3390 (super_init_validation, inlined) raid_ctr+0x2c4b/0xa0f0 dm_table_add_target+0x66f/0xf80 table_load+0x2ee/0x780 ctl_ioctl+0x362/0x9f0 dm_ctl_ioctl+0x9/0x10 __x64_sys_ioctl+0x134/0x1c0 do_syscall_64+0xe2/0x4b0 entry_SYSCALL_64_after_hwframe+0x77/0x7f
role is a device position that must refer to an actual member of the array, so reject anything outside [0, rs->raid_disks) instead of only the negative case. rs->raid_disks is always <= the 256-bit capacity of failed_devices, so this both closes the out-of-bounds access and matches the intended semantics.
This bug was discovered by Artiphishell's vTriage pipeline, which generated a crafted raid1 superblock (magic "DmRd", compat_features=1, num_devices=2, array_position=256, level=1) and a dmsetup-create reproducer that reliably triggers the KASAN report on an unpatched kernel (the precursor DMINFO "raid device #256 now at position #0" is visible in the serial log just before the splat). The fix below was drafted with the Claude coding assistant; a userspace reproducer is available on request.
--- drivers/md/dm-raid.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-raid.c +2 -1
@@ -2420,7 +2420,8 @@ static int super_init_validation(struct*/ if (!test_bit (FirstUse, &r->flags) && (r->raid_disk >=0 )) { role =le32_to_cpu (sb2->array_position); -if (role <0 ) +/* Bound @role before it indexes the failed_devices stack bitmap. */ +if (role <0 || role >= rs->raid_disks)continue ;if (role != r->raid_disk) {
Greg Kroah-Hartman
maintainerPATCH 877/990 dm-raid: fix use-after-free in raid_dtr()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Youhong <[email protected]>
commit 46af2c975958119290ddcd984a98491966123a7b upstream.
raid_dtr() currently flushes event_work only if work_pending() is true. This is insufficient because once a worker has dequeued the work, the PENDING bit is cleared while do_table_event() is still running. In that window raid_set_free() can free the raid_set, leading to a use-after-free when do_table_event() accesses rs->ti->table.
Flush event_work whenever it has been initialized, so raid_set is not freed while the event handler is still running. The .func guard skips the flush for mddev instances where INIT_WORK has not run yet.
--- drivers/md/dm-raid.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-raid.c +1 -1
@@ -3334,7 +3334,7 @@ static void raid_dtr(struct dm_target *t rs->md.dm_gendisk =NULL ;mddev_unlock (&rs->md); -if (work_pending (&rs->md.event_work)) +if (rs->md.event_work.func)flush_work (&rs->md.event_work);raid_set_free (rs); }
Greg Kroah-Hartman
maintainerPATCH 878/990 dm-thin: fix data corruption if discard races with regular I/O
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit 62ee9c09366cad69410330087d990e469dd92314 upstream.
In the function break_up_discard_bio, if a discard hits the same block as regular I/O, it was intended to skip the discard for the affected range. However, the skip code only advances "data_begin", it doesn't advance "virt_begin". So, the data_begin and virt_begin variables become unsynchronized.
process_prepared_discard_passdown_pt1 calculates "data_end = m->data_block + (m->virt_end - m->virt_begin);" - if m->data_block is incremented and m->virt_begin isn't, it will overshoot the intended discard range.
--- drivers/md/dm-thin.c | 1 + 1 file changed, 1 insertion(+)
drivers/md/dm-thin.c +1 -0
@@ -1705,6 +1705,7 @@ static void break_up_discard_bio(struct (void )build_key (tc->td,PHYSICAL , data_begin, data_begin + len, &data_key);if (bio_detain (tc->pool, &data_key,NULL , &data_cell)) {/* contention, we'll give up with this range */ + virt_begin += len; data_begin += len;continue ; }
Greg Kroah-Hartman
maintainerPATCH 879/990 dm-thin: fix leak if __set_snapshot_details fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit dfb95816cf6f2f2660af2ec64c65dc204c60b5e7 upstream.
If __set_snapshot_details fails, the variable td is leaked - this prevents any other snapshot with the same id from being created.
Fix this by removing it from the list and freeing it.
--- drivers/md/dm-thin-metadata.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/md/dm-thin-metadata.c +4 -1
@@ -1225,10 +1225,13 @@ static int __create_snap(struct dm_pool___close_device (td);if (r) - goto bad; + goto bad2;return 0 ; +bad2: +list_del (&td->list); +kfree (td); bad:dm_btree_remove (&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_remove(&pmd->details_info, pmd->details_root,
Greg Kroah-Hartman
maintainerPATCH 880/990 dm-thin: fix parsing of feature arguments
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mikulas Patocka <[email protected]>
commit c557fa19a83efad1e20eb733df821b745a4589ff upstream.
"struct dm_arg _args" limits the number of arguments to 4, but there are 5 possible arguments that can be specified.
--- drivers/md/dm-thin.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-thin.c +1 -1
@@ -3151,7 +3151,7 @@ static int parse_pool_features(struct dmconst char *arg_name;static const struct dm_arg _args[] = { - {0 ,4 ,"Invalid number of pool feature arguments" }, + {0 ,5 ,"Invalid number of pool feature arguments" }, };/*
Greg Kroah-Hartman
maintainerPATCH 881/990 vt: serialise the producers of the flip buffer
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 5d1d814408c1c8e797031eac8ddd40de1a9e8e93 upstream.
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.
--- drivers/tty/vt/keyboard.c | 6 ++++++ drivers/tty/vt/vt.c | 2 ++ 2 files changed, 8 insertions(+)
drivers/tty/vt/keyboard.c +6 -0
@@ -321,15 +321,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); }
@@ -589,6 +594,7 @@ static void fn_inc_console(struct vc_datstatic 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); }
drivers/tty/vt/vt.c +2 -0
@@ -1830,6 +1830,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); }
Greg Kroah-Hartman
maintainerPATCH 882/990 comedi: addi_apci_1500: fix clearing of the gate enable
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit ade85ceef46892425a08f3ee52ca06729ee4922e upstream.
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.
--- drivers/comedi/drivers/addi_apci_1500.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/addi_apci_1500.c +1 -1
@@ -696,7 +696,7 @@ static int apci1500_timer_insn_config(streturn -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 )
Greg Kroah-Hartman
maintainerPATCH 883/990 comedi: ni_660x: dont poll without a DMA channel
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 5a0c88567a5ebbe24ecb7828e200f63ed972718f upstream.
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.
--- drivers/comedi/drivers/ni_660x.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/comedi/drivers/ni_660x.c +2 -1
@@ -459,7 +459,8 @@ static int ni_660x_input_poll(struct com/* 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); }
Greg Kroah-Hartman
maintainerPATCH 884/990 comedi: ni_tio: Fix overflow of the clock period
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit ec214735bb113be747454812035b83010892e0d2 upstream.
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.
--- drivers/comedi/drivers/ni_tio.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/ni_tio.c +1 -1
@@ -800,7 +800,7 @@ static int ni_tio_set_clock_src(struct nGI_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 ; }
Greg Kroah-Hartman
maintainerPATCH 885/990 comedi: vmk80xx: report failed transfers of the K8061
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 92fa93505576188acc22c5de1999db9a1c70c09b upstream.
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.
--- drivers/comedi/drivers/vmk80xx.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-)
drivers/comedi/drivers/vmk80xx.c +12 -13
@@ -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 cunsigned 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 c 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 costruct 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 c 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);
Greg Kroah-Hartman
maintainerPATCH 886/990 iio: accel: adxl380: dont stay in standby on -EINVAL
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 4c56180167ea4d419a0578545bf62110494b563d upstream.
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.
--- drivers/iio/accel/adxl380.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
drivers/iio/accel/adxl380.c +10 -1
@@ -341,8 +341,11 @@ static int adxl380_set_act_inact_threshoreturn 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); }
@@ -709,6 +712,12 @@ static int adxl380_set_range(struct adxlguard (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;
Greg Kroah-Hartman
maintainerPATCH 887/990 iio: adc: check the result of ad_sd_init()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 905b5d93b795b0e2311a8c855c1cdd97c9cc2989 upstream.
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.
--- 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(-)
drivers/iio/adc/ad7780.c +3 -1
@@ -318,7 +318,9 @@ static int ad7780_probe(struct spi_devic 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];
drivers/iio/adc/ad7791.c +3 -1
@@ -436,7 +436,9 @@ static int ad7791_probe(struct spi_devicreturn 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 ;
drivers/iio/adc/ad7793.c +3 -1
@@ -796,7 +796,9 @@ static int ad7793_probe(struct spi_devic 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 (&spi->dev,"refin" );
drivers/iio/adc/max11205.c +3 -1
@@ -114,7 +114,9 @@ static int max11205_probe(struct spi_dev 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)
Greg Kroah-Hartman
maintainerPATCH 888/990 iio: addac: ad74413r: fix the values of set_multiple
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit e6dfbd84b833ed595a5236b027357e917de28260 upstream.
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.
--- drivers/iio/addac/ad74413r.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/addac/ad74413r.c +1 -1
@@ -313,7 +313,7 @@ static int ad74413r_gpio_set_multiple(streturn ret; real_mask |=BIT (real_offset); -if (*bits & offset) +if (test_bit (offset, bits)) real_bits |=BIT (real_offset); }
Greg Kroah-Hartman
maintainerPATCH 889/990 iio: hid-sensors: fix a division by zero
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit fd4c92bbd3a64556e81042ff8d30545b15a3b93a upstream.
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.
--- drivers/iio/common/hid-sensors/hid-sensor-attributes.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/iio/common/hid-sensors/hid-sensor-attributes.c +4 -1
@@ -141,7 +141,10 @@ static u32 convert_to_vtf_format(int sizif (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;
Greg Kroah-Hartman
maintainerPATCH 890/990 iio: sx9310: use the data of the I2C table
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit f3fc8718af9189aad13a2ad7f5b256475bb14b21 upstream.
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.
--- drivers/iio/proximity/sx9310.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/proximity/sx9310.c +1 -1
@@ -892,7 +892,7 @@ static int sx9310_check_whoami(struct deif (ret)return ret; - ddata =device_get_match_data (dev); + ddata =i2c_get_match_data (data->client);if (ddata->whoami != whoami)return -ENODEV ;
Greg Kroah-Hartman
maintainerPATCH 891/990 misc: bcm-vk: fix DMA allocation memory leak
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
commit a36b3db60466d44eefcc5c252ce927c043429922 upstream.
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.
--- drivers/misc/bcm-vk/bcm_vk_sg.c | 43 +++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-)
drivers/misc/bcm-vk/bcm_vk_sg.c +36 -7
@@ -80,7 +80,8 @@ static int bcm_vk_dma_alloc(struct devic 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 */
@@ -92,8 +93,10 @@ static int bcm_vk_dma_alloc(struct devic 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;
@@ -110,8 +113,8 @@ static int bcm_vk_dma_alloc(struct devic 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++) {
@@ -123,8 +126,8 @@ static int bcm_vk_dma_alloc(struct devic size, dma->direction);if (unlikely (dma_mapping_error (dev, addr))) { -__free_page (dma->pages[i]); -return -EIO ; + err = -EIO ; + goto err_unmap; }/*
@@ -169,6 +172,32 @@ static int bcm_vk_dma_alloc(struct devic#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,
Greg Kroah-Hartman
maintainerPATCH 892/990 misc: ibmvmc: initialize HMC state before device registration
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 2022f170e5655c40b93ed98629f7d0adb98cea49 upstream.
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.
--- drivers/misc/ibmvmc.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
drivers/misc/ibmvmc.c +8 -8
@@ -2365,14 +2365,6 @@ static int __init ibmvmc_module_init(voi 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++) {
@@ -2382,6 +2374,14 @@ static int __init ibmvmc_module_init(voi 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 ();
Greg Kroah-Hartman
maintainerPATCH 893/990 misc: vmw_vmci: wait for callbacks in event unsubscribe
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 824a27d391cf934d3232e8e2dabee221fc4e18ae upstream.
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.
--- drivers/misc/vmw_vmci/vmci_event.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/misc/vmw_vmci/vmci_event.c +6 -1
@@ -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 ; }
Greg Kroah-Hartman
maintainerPATCH 894/990 serial: 8250_lpss: dont divide by 0 above 6.25 Mbaud
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 08daebfd63e9054e097eb2653eff9381de43a422 upstream.
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.
--- drivers/tty/serial/8250/8250_lpss.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/tty/serial/8250/8250_lpss.c +3 -0
@@ -82,6 +82,9 @@ static void byt_set_termios(struct uart_/* 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);
Greg Kroah-Hartman
maintainerPATCH 895/990 serial: core: respect runtime PM when sending x_char
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 84da8238f7bd3025fc16da32c4cd9992c95a783b upstream.
__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.
--- drivers/tty/serial/serial_core.c | 25 +++++++++++++++---------- drivers/tty/serial/serial_port.c | 4 ++-- 2 files changed, 17 insertions(+), 12 deletions(-)
drivers/tty/serial/serial_core.c +15 -10
@@ -135,17 +135,11 @@ static void uart_stop(struct tty_structuart_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_stapm_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;
@@ -722,8 +726,9 @@ static void uart_send_xchar(struct tty_selse {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); }
drivers/tty/serial/serial_port.c +2 -2
@@ -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)
Greg Kroah-Hartman
maintainerPATCH 896/990 serial: rda: free the interrupt on shutdown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 859f7c56709b161a72b629b6f2f1384dcd374404 upstream.
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().
--- drivers/tty/serial/rda-uart.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/tty/serial/rda-uart.c +2 -0
@@ -471,6 +471,8 @@ static void rda_uart_shutdown(struct uarrda_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)
Greg Kroah-Hartman
maintainerPATCH 897/990 serial: samsung: dont leak the tty on an RX IRQ
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit 7ada442f5ef77f8d53f608a0141a5e88a888ca9f upstream.
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.
--- drivers/tty/serial/samsung_tty.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/tty/serial/samsung_tty.c +2 -3
@@ -736,14 +736,13 @@ static irqreturn_t s3c24xx_serial_rx_chas3c24xx_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 ;
Greg Kroah-Hartman
maintainerPATCH 898/990 serial: samsung: put the previous baud clock
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit eedf2cf3505c1562a2fb24f8b997056f023d242b upstream.
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.
--- drivers/tty/serial/samsung_tty.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/tty/serial/samsung_tty.c +3 -0
@@ -1498,11 +1498,14 @@ static void s3c24xx_serial_set_termios(sif (!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) {
Greg Kroah-Hartman
maintainerPATCH 899/990 tty: fix misapplied compat_ptr() in tty_compat_ioctl()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiri Slaby (SUSE) <[email protected]>
commit 895dc0eaa2779ff46a0b2a20b5ce9eb0b1125cb2 upstream.
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)?
--- drivers/tty/tty_io.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/tty/tty_io.c +1 -2
@@ -2996,8 +2996,7 @@ static long tty_compat_ioctl(struct fileif (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;
Greg Kroah-Hartman
maintainerPATCH 900/990 USB: cdc-acm: fix NULL-deref on hangup
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
commit bc9dd21ec61acd152d9e7c12cb07db37c63ad41a upstream.
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.
--- drivers/usb/class/cdc-acm.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
drivers/usb/class/cdc-acm.c +12 -6
@@ -294,6 +294,7 @@ static void acm_process_notification(strunsigned 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(str 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); } }
Greg Kroah-Hartman
maintainerPATCH 901/990 usb: pci-quirks: always assert xHCI OS ownership
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rishabh Jain <[email protected]>
commit 5550405351199fe78f4a3cd606c07f5ad7220e1b upstream.
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.
--- drivers/usb/host/pci-quirks.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-)
drivers/usb/host/pci-quirks.c +8 -5
@@ -1194,10 +1194,11 @@ static void quirk_usb_handoff_xhci(struc && 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 */
@@ -1209,7 +1210,9 @@ static void quirk_usb_handoff_xhci(strucdev_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); } }
Greg Kroah-Hartman
maintainerPATCH 902/990 USB: serial: garmin_gps: fix deadlock on reset request
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
commit ab89a9dab02d9553eb0cc27fd3e4a4998acbc8e9 upstream.
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).
--- drivers/usb/serial/garmin_gps.c | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-)
drivers/usb/serial/garmin_gps.c +3 -9
@@ -821,10 +821,9 @@ static void priv_status_resp(struct usb_* 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);
@@ -833,13 +832,8 @@ static int process_resetdev_request(stru 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); }
Greg Kroah-Hartman
maintainerPATCH 903/990 USB: serial: oti6858: fix the teardown order in close
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
commit f184ae84a5d19554d980a918a9c8baaef87ac301 upstream.
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.
--- drivers/usb/serial/oti6858.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
drivers/usb/serial/oti6858.c +12 -4
@@ -251,7 +251,7 @@ static void setup_line(struct work_strucdev_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); }
@@ -303,7 +303,7 @@ static void send_data(struct work_structdev_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); }
@@ -564,6 +564,13 @@ static void oti6858_close(struct usb_serdev_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);
@@ -572,7 +579,8 @@ static void oti6858_close(struct usb_serdev_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,
@@ -829,7 +837,7 @@ static void oti6858_write_bulk_callback(/* 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); }
Greg Kroah-Hartman
maintainerPATCH 904/990 usb: typec: mux: fsa4480: Keep the USB 2.0 switch on in DP-only modes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joonhoe Kim <[email protected]>
commit 89aaaa26f6985d55676fc5c90440f279733fa132 upstream.
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.
--- drivers/usb/typec/mux/fsa4480.c | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-)
drivers/usb/typec/mux/fsa4480.c +1 -8
@@ -93,16 +93,9 @@ static int fsa4480_set(struct fsa4480 *f 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 ;
Greg Kroah-Hartman
maintainerPATCH 905/990 usb: typec: nb7vpq904m: Set client data in probe to avoid crash on remove
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chaz Bailey <[email protected]>
commit 2022b10726be78849626ea3fa33038ee96a54e46 upstream.
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.
--- drivers/usb/typec/mux/nb7vpq904m.c | 1 + 1 file changed, 1 insertion(+)
drivers/usb/typec/mux/nb7vpq904m.c +1 -0
@@ -396,6 +396,7 @@ static int nb7vpq904m_probe(struct i2c_creturn -ENOMEM ; nb7->client = client; +i2c_set_clientdata (client, nb7); nb7->regmap =devm_regmap_init_i2c (client, &nb7_regmap);if (IS_ERR (nb7->regmap)) {
Greg Kroah-Hartman
maintainerPATCH 906/990 usb: uas: ignore UAS for ASMT135x bridges (174c:55aa)
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Olivier Kaloudoff <[email protected]>
commit fafd23d61494461256d374f67c121f2712e1af2f upstream.
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.
--- drivers/usb/storage/uas-detect.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/usb/storage/uas-detect.h +7 -1
@@ -78,6 +78,8 @@ static int uas_use_uas_driver(struct usb* 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 (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 ;