6.6.163-rc1 review
Subsystems (6)
Greg Kroah-Hartman
maintainerPATCH 608/3318 klist: avoid accesses after waking klist_remove()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit 732e3e10234cbe302d0dcbaa98c91c66628209cb upstream.
klist_remove() waits until a node is unreferenced so that its caller can free the containing object. klist_release() currently publishes waiter->woken and wakes the waiter before its final accesses to the waiter and node. klist_remove() can then return, allowing its stack waiter and the containing object to be freed or reused while klist_release() is still running. In particular, bus_remove_driver() can free drv->p while __device_attach() walks the same bus klist with bus_for_each_drv().
On an arm64 Cortex-A72 system, an unpatched 7.2.0-rc3 kernel with CONFIG_PREEMPT_RT=y and CONFIG_KASAN=y reproduced the bug through the in-tree I2C/at24 path. KASAN reported a use-after-free in klist_dec_and_del() reached from klist_next()/bus_for_each_drv() while at24 was being unregistered.
Clear n_klist and take a task reference before publishing woken. Use release/acquire accesses for that publication and wake the referenced task. The task reference keeps the waiter task alive if it returns and exits before wake_up_process().
--- lib/klist.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
lib/klist.c +12 -4
@@ -36,6 +36,7 @@#include <linux/klist.h> #include <linux/export.h> #include <linux/sched.h> +#include <linux/sched/task.h> /* * Use the lowest bit of n_klist to mark deleted nodes and exclude
@@ -187,18 +188,24 @@ static void klist_release(struct kref *kWARN_ON (!knode_dead (n));list_del (&n->n_node); +knode_set_klist (n,NULL );spin_lock (&klist_remove_lock);list_for_each_entry_safe (waiter, tmp, &klist_remove_waiters, list) { +struct task_struct *p; +if (waiter->node != n)continue ; + p = waiter->process; +get_task_struct (p);list_del (&waiter->list); - waiter->woken =1 ; +/* Publish only after the final waiter and n accesses */ +smp_store_release (&waiter->woken,1 );mb (); -wake_up_process (waiter->process); +wake_up_process (p); +put_task_struct (p); }spin_unlock (&klist_remove_lock); -knode_set_klist (n,NULL ); }static int klist_dec_and_del (struct klist_node *n)
@@ -250,7 +257,8 @@ void klist_remove(struct klist_node *n)for (;;) {set_current_state (TASK_UNINTERRUPTIBLE ); -if (waiter.woken) +/* Pairs with the release store in klist_release() */ +if (smp_load_acquire (&waiter.woken))break ;schedule (); }
Greg Kroah-Hartman
maintainerPATCH 609/3318 ALSA: control: Fix UAF in snd_ctl_elem_add() on card disconnect
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Takashi Iwai <[email protected]>
commit d4febca239be3c91498762dd0535a87d4af1eabc upstream.
A use-after-free can be triggered via SNDRV_CTL_IOCTL_ELEM_ADD when a USB audio card is disconnected while an ELEM_ADD ioctl is in flight.
The reproducer parks the ioctl thread inside copy_from_user() using userfaultfd, then tears down the USB device. Unlike every other ALSA control _user handler (ELEM_INFO, ELEM_READ, ELEM_WRITE, TLV_*), snd_ctl_elem_add_user() never calls snd_power_ref_and_wait(), so the parked thread holds no power reference. snd_card_disconnect() therefore cannot observe it via snd_power_sync_ref() and proceeds unimpeded:
1. card->shutdown is set to 1
2. device_del(&card->card_dev) drops the kobject reference on the
parent USB interface device (card->dev = &intf->dev)
3. The USB core drops its own reference and calls device_release(), freeing the struct usb_interface, including the embedded struct device that card->dev points to
When the userfaultfd is resolved and the thread resumes, snd_ctl_elem_add() acquires controls_rwsem without checking card->shutdown and calls __snd_ctl_add_replace(). Because the reproducer pre-registered the same control, the CTL_ADD_EXCLUSIVE path calls dev_err(card->dev, ...) on the freed USB interface:
KASAN: slab-use-after-free Read in __dev_printk
Add a card->shutdown guard immediately after acquiring controls_rwsem in snd_ctl_elem_add(). At that point card->shutdown is guaranteed to be stable: snd_card_disconnect() sets it before freeing the parent device, and it never transitions back to 0. A thread that acquired the lock before disconnect sees shutdown=0 and holds the write lock through the rest of the operation, preventing concurrent disconnect from proceeding past its own controls_rwsem-less shutdown=1 store (which happened earlier, outside the lock) from racing with dev_err().
--- sound/core/control.c | 2 ++ 1 file changed, 2 insertions(+)
sound/core/control.c +2 -0
@@ -1699,6 +1699,8 @@ static int snd_ctl_elem_add(struct snd_c alloc_size =compute_user_elem_size (private_size, count);guard (rwsem_write)(&card->controls_rwsem); +if (card->shutdown) +return -ENODEV ;if (check_user_elem_overflow (card, alloc_size))return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 610/3318 ALSA: pcmtest: handle multiple wraps in random capture fill
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sung Byeongchan <[email protected]>
commit 6541871e8e63e721733cd120af4d9cd22c5ef62f upstream.
The random capture helpers assume that the data generated for one timer tick wraps the DMA ring at most once. However, b_rw describes 200 ms of audio because the timer runs at 5 Hz, so it can be several times larger than a small ring.
For 48 kHz, S16_LE, four-channel capture with a 512-frame buffer, the DMA ring is 4096 bytes while one tick generates 76800 bytes. After filling the 4096-byte tail, the existing code issues a second 72704-byte write from the ring base, writing 68608 bytes beyond the ring. Both interleaved and non-interleaved capture are affected.
KASAN reports the first write into the adjacent free page as a use-after-free in the random-byte generator. The underlying defect is an out-of-bounds write from the live DMA ring, not a stale DMA allocation.
Split each random write repeatedly at the interleaved ring or per-channel block boundary. Keep the hardware-pointer update exactly once after the complete logical write.
The issue reproduced on three of three clean boots. With this change, the same vulnerable geometry completed six times without a sanitizer finding. Boundary, pattern-fill, no-timer, open/close, and module-reload controls also completed normally.
snd-pcmtest is a test driver, and selecting random fill requires an administrator-controlled module parameter. The written values come from the kernel random generator; no privilege escalation or attacker-controlled write primitive was demonstrated.
--- sound/drivers/pcmtest.c | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-)
sound/drivers/pcmtest.c +19 -23
@@ -279,39 +279,35 @@ static void fill_block_pattern(struct pcfill_block_pattern_n (v_iter, runtime); } +static void fill_random_block (char *buf,size_t buf_size,size_t pos, +size_t count) +{ +while (count) { +size_t chunk =min (count, buf_size - pos); + +get_random_bytes (buf + pos, chunk); + count -= chunk; + pos =0 ; + } +} +static void fill_block_rand_n (struct pcmtst_buf_iter *v_iter,struct snd_pcm_runtime *runtime) {unsigned int channels = runtime->channels; -// Remaining space in all channel buffers -size_t bytes_remain = runtime->dma_bytes - v_iter->buf_pos; +size_t pos = v_iter->buf_pos / channels;unsigned int i; -for (i =0 ; i < channels; i++) { -if (v_iter->b_rw <= bytes_remain) { -//b_rw - count of bytes must be written for all channels at each timer tick -get_random_bytes (runtime->dma_area +buf_pos_n (v_iter, channels, i), - v_iter->b_rw / channels); - }else { -// Write to the end of buffer and start from the beginning of it -get_random_bytes (runtime->dma_area +buf_pos_n (v_iter, channels, i), - bytes_remain / channels); -get_random_bytes (runtime->dma_area + v_iter->chan_block * i, - (v_iter->b_rw - bytes_remain) / channels); - } - } +for (i =0 ; i < channels; i++) +fill_random_block (runtime->dma_area + v_iter->chan_block * i, + v_iter->chan_block, pos, + v_iter->b_rw / channels);inc_buf_pos (v_iter, v_iter->b_rw, runtime->dma_bytes); }static void fill_block_rand_i (struct pcmtst_buf_iter *v_iter,struct snd_pcm_runtime *runtime) { -size_t in_cur_block = runtime->dma_bytes - v_iter->buf_pos; - -if (v_iter->b_rw <= in_cur_block) { -get_random_bytes (&runtime->dma_area[v_iter->buf_pos], v_iter->b_rw); - }else { -get_random_bytes (&runtime->dma_area[v_iter->buf_pos], in_cur_block); -get_random_bytes (runtime->dma_area, v_iter->b_rw - in_cur_block); - } +fill_random_block (runtime->dma_area, runtime->dma_bytes, + v_iter->buf_pos, v_iter->b_rw);inc_buf_pos (v_iter, v_iter->b_rw, runtime->dma_bytes); }
Greg Kroah-Hartman
maintainerPATCH 611/3318 Bluetooth: hci_vhci: Pin module for debugfs file operations
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bui Viet Dung <[email protected]>
commit 645ee6b176c958579cff1c783413d5cff65c8197 upstream.
An open debugfs file retains its file_operations pointer in the debugfs proxy state. However, force_suspend_fops, force_wakeup_fops, aosp_capable_fops, and force_devcoredump_fops have no .owner set to THIS_MODULE. As a result, full_proxy_open_regular() calls fops_get() which succeeds without taking a reference to the hci_vhci module.
When userspace opens any of these debugfs files and later closes the /dev/vhci file descriptor (triggering vhci_release() and debugfs file removal), the open debugfs file descriptor remains valid in userspace. Because the module refcount was not incremented, the hci_vhci module can be unloaded via delete_module (rmmod hci_vhci).
When the userspace process subsequently closes the debugfs file descriptor, full_proxy_release() accesses the already unmapped file_operations structure, resulting in a kernel page fault / oops:
BUG: unable to handle page fault for address: fffffbfff846f18b #PF: supervisor read access in kernel mode #PF: error_code(0x0000) - not-present page Oops: Oops: 0000 [#1] SMP KASAN NOPTI RIP: 0010:full_proxy_release+0x8e/0x140 Call Trace: <TASK> __fput+0x39f/0xa60 fput_close_sync+0xff/0x200 __x64_sys_close+0x8c/0xf0 do_syscall_64+0xc3/0x590 entry_SYSCALL_64_after_hwframe+0x76/0x7e </TASK> Modules linked in: ... [last unloaded: hci_vhci(E)]
The issue was discovered via manual code audit of drivers/bluetooth/hci_vhci.c and verified on a Linux 7.3-rc6 test VM with CONFIG_BT_VHCI=m by keeping a debugfs file open across controller teardown and module unload.
Set .owner = THIS_MODULE on all four file_operations structures so that debugfs pins the module until all file descriptors are closed.
--- drivers/bluetooth/hci_vhci.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/bluetooth/hci_vhci.c +4 -0
@@ -155,6 +155,7 @@ static ssize_t force_suspend_write(struc }static const struct file_operations force_suspend_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = force_suspend_read, .write = force_suspend_write,
@@ -194,6 +195,7 @@ static ssize_t force_wakeup_write(struct }static const struct file_operations force_wakeup_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = force_wakeup_read, .write = force_wakeup_write,
@@ -263,6 +265,7 @@ static ssize_t aosp_capable_write(struct }static const struct file_operations aosp_capable_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = aosp_capable_read, .write = aosp_capable_write,
@@ -386,6 +389,7 @@ static ssize_t force_devcd_write(struct }static const struct file_operations force_devcoredump_fops = { + .owner =THIS_MODULE , .open = simple_open, .write = force_devcd_write, };
Greg Kroah-Hartman
maintainerPATCH 612/3318 fbdev: atmel_lcdfb: Prevent FIFO work after removal
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yibo Tan <[email protected]>
commit 20b3b97cf89cb381bf07516090d99399cc9b91fd upstream.
The LCD controller IRQ schedules sinfo->task to recover from a FIFO underflow. Probe currently requests the IRQ before initializing the work, so an early interrupt can schedule an uninitialized work item.
The probe error path and remove path cancel the work before freeing the IRQ. A FIFO-underflow interrupt can schedule the work again after that cancellation. framebuffer_release() may then free sinfo while the work is still pending.
KASAN reported a use-after-free in atmel_lcdfb_task() when an underflow interrupt occurred during removal. With the IRQ freed before the work was cancelled, the same test completed without a kernel diagnostic.
Initialize the work before requesting the IRQ. In both cleanup paths, free the IRQ before cancelling the work so that it cannot be scheduled again after cancellation.
--- drivers/video/fbdev/atmel_lcdfb.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +5 -6
@@ -1149,6 +1149,9 @@ static int __init atmel_lcdfb_probe(stru/* Initialize PWM for contrast or backlight ("off") */ init_contrast (sinfo); +/* Some LCDC recovery operations require process context. */ +INIT_WORK (&sinfo->task, atmel_lcdfb_task); +/* interrupt */ ret =request_irq (sinfo->irq_base, atmel_lcdfb_interrupt,0 , pdev->name, info);if (ret) {
@@ -1156,10 +1159,6 @@ static int __init atmel_lcdfb_probe(stru goto unmap_mmio; } -/* Some operations on the LCDC might sleep and -* require a preemptible task context */ -INIT_WORK (&sinfo->task, atmel_lcdfb_task); - ret =atmel_lcdfb_init_fbinfo (sinfo);if (ret <0 ) {dev_err (dev,"init fbinfo failed: %d\n" , ret);
@@ -1195,8 +1194,8 @@ reset_drvdata:dev_set_drvdata (dev,NULL );fb_dealloc_cmap (&info->cmap); unregister_irqs: -cancel_work_sync (&sinfo->task);free_irq (sinfo->irq_base, info); +cancel_work_sync (&sinfo->task); unmap_mmio:exit_backlight (sinfo);iounmap (sinfo->mmio);
@@ -1233,6 +1232,7 @@ static int __exit atmel_lcdfb_remove(strreturn 0 ; sinfo = info->par; +free_irq (sinfo->irq_base, info);cancel_work_sync (&sinfo->task);exit_backlight (sinfo);atmel_lcdfb_power_control (sinfo,0 );
@@ -1241,7 +1241,6 @@ static int __exit atmel_lcdfb_remove(strclk_put (sinfo->lcdc_clk);clk_put (sinfo->bus_clk);fb_dealloc_cmap (&info->cmap); -free_irq (sinfo->irq_base, info);iounmap (sinfo->mmio);release_mem_region (info->fix.mmio_start, info->fix.mmio_len);if (platform_get_resource (pdev,IORESOURCE_MEM ,1 )) {
Greg Kroah-Hartman
maintainerPATCH 613/3318 fbdev: udlfb: dont rebuild the mode list while the framebuffer is in use
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
commit ac9cfa552102b8e80e88c2872e80dc9cb5f07dda upstream.
dlfb_setup_modes() frees info->modelist with fb_destroy_modelist() and rebuilds it, but fbcon holds raw pointers into that list in fb_display[i].mode and nothing un-publishes them the way do_unregister_framebuffer() and store_modes() do with fbcon_delete_modelist(). The function does refuse to install a new mode while the framebuffer has users (dlfb->fb_count != 0), but only after the list is already destroyed. Reached from the 0666 "edid" sysfs attribute, an unprivileged write to /sys/class/graphics/fb0/edid therefore fails with -EINVAL and still leaves every fb_display[i].mode dangling; the next console switch reads the freed fb_videomode in fb_videomode_to_var().
Test fb_count before touching the list. fbcon takes a reference through fbcon_open(), so that condition covers exactly the states in which fb_display[] points into the list, and the errno returned to userspace is unchanged.
BUG: KASAN: slab-use-after-free in fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) Read of size 4 at addr ffff8880107b449c by task kworker/1:1/47 Workqueue: events console_callback Call Trace: fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) display_to_var (drivers/video/fbdev/core/fbcon.c:998) fbcon_switch (drivers/video/fbdev/core/fbcon.c:2182) redraw_screen (drivers/tty/vt/vt.c:994) complete_change_console (drivers/tty/vt/vt_ioctl.c:1141) console_callback (drivers/tty/vt/vt.c:3358) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) ... The buggy address is located 28 bytes inside of freed 96-byte region [ffff8880107b4480, ffff8880107b44e0)
--- drivers/video/fbdev/udlfb.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/video/fbdev/udlfb.c +5 -0
@@ -1336,6 +1336,11 @@ static int dlfb_setup_modes(struct dlfb_ goto error; } +if (dlfb->fb_count) { + result = -EINVAL ; + goto error; + } +fb_destroy_modelist (&info->modelist);memset (&info->monspecs,0 ,sizeof (info->monspecs));
Greg Kroah-Hartman
maintainerPATCH 614/3318 genirq: Defer kfree(irqaction) until irq_thread_dtor() finishes
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Patel <[email protected]>
commit d04adff6860587e843948b0c31174f8ae11b8dfe upstream.
When an interrupt thread exits abnormally via do_exit() (e.g. the interrupt handler oopses) without returning from irq_thread(), a concurrent call to free_irq() could free the irqaction before the irq_thread_dtor() exit task work runs.
irq thread (oopsed) free_irq()
------------------- ----------
do_exit()
exit_mm()
complete_vfork_done() -------> kthread_stop() returns
exit_files() ... kfree(action)
exit_task_work()
irq_thread_dtor()
action->... <- use-after-freeTrack the pending exit work with the IRQTF_EXIT_WORK thread flag, and have __free_irq() wait for the bit to clear before kfree().
irq_thread_dtor() only runs on irq_thread abnormal exit. If that dtor also faults, free_irq() will hang indefinitely, but double IRQ thread faults require a reboot anyways.
[ tglx: Add missing include ]
--- kernel/irq/internals.h | 2 ++ kernel/irq/manage.c | 26 ++++++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-)
kernel/irq/internals.h +2 -0
@@ -30,6 +30,7 @@ extern struct irqaction chained_action;* IRQTF_AFFINITY - irq thread is requested to adjust affinity * IRQTF_FORCED_THREAD - irq action is force threaded * IRQTF_READY - signals that irq thread is ready +* IRQTF_EXIT_WORK - irq thread exit task_work is pending */ enum {IRQTF_RUNTHREAD ,
@@ -37,6 +38,7 @@ enum {IRQTF_AFFINITY ,IRQTF_FORCED_THREAD ,IRQTF_READY , + IRQTF_EXIT_WORK, };/*
kernel/irq/manage.c +20 -6
@@ -21,6 +21,7 @@#include <linux/sched/isolation.h> #include <uapi/linux/sched/types.h> #include <linux/task_work.h> +#include <linux/wait_bit.h> #include "internals.h"
@@ -1228,17 +1229,14 @@ void wake_threads_waitq(struct irq_descwake_up (&desc->wait_for_threads); } -static void irq_thread_dtor (struct callback_head *unused) +static void __irq_thread_dtor (struct irqaction *action) {struct task_struct *tsk = current;struct irq_desc *desc; -struct irqaction *action;if (WARN_ON_ONCE (!(current->flags &PF_EXITING )))return ; - action =kthread_data (tsk); -pr_err ("exiting task \"%s\" (%d) is an active IRQ thread (irq %d)\n" , tsk->comm, tsk->pid, action->irq);
@@ -1255,6 +1253,14 @@ static void irq_thread_dtor(struct callbirq_finalize_oneshot (desc, action); } +static void irq_thread_dtor (struct callback_head *unused) +{ +struct irqaction *action =kthread_data (current); + +__irq_thread_dtor (action); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags); +} +static void irq_wake_secondary (struct irq_desc *desc,struct irqaction *action) {struct irqaction *secondary = action->secondary;
@@ -1313,6 +1319,7 @@ static int irq_thread(void *data)else handler_fn = irq_thread_fn; +set_bit (IRQTF_EXIT_WORK , &action->thread_flags);init_task_work (&on_exit_work, irq_thread_dtor);task_work_add (current, &on_exit_work,TWA_NONE );
@@ -1337,6 +1344,7 @@ static int irq_thread(void *data)* oneshot mask bit can be set. */ task_work_cancel_func (current, irq_thread_dtor); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags);return 0 ; }
@@ -1869,6 +1877,12 @@ out_mput:return ret; } +static void irq_stop_thread (struct irqaction *action) +{ +kthread_stop_put (action->thread); +wait_on_bit (&action->thread_flags,IRQTF_EXIT_WORK ,TASK_UNINTERRUPTIBLE ); +} +/* * Internal function to unregister an irqaction - used to free * regular and special interrupts that are part of the architecture.
@@ -1973,9 +1987,9 @@ static struct irqaction *__free_irq(stru* the same bit to a newly requested action. */ if (action->thread) { -kthread_stop_put (action->thread); +irq_stop_thread (action);if (action->secondary && action->secondary->thread) -kthread_stop_put (action->secondary->thread); +irq_stop_thread (action->secondary); }/* Last action releases resources */
Greg Kroah-Hartman
maintainerPATCH 615/3318 genirq: Move interrupt thread exit_work object to irqaction
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Patel <[email protected]>
commit 89a9e003a2ef73f67dff03dfd59e0a5474b56b0b upstream.
irq_thread() registers irq_thread_dtor() as exit task_work using a stack-allocated callback_head. On normal interrupt thread exit, this work gets cancelled and never runs.
On x86, an abnormal interrupt thread exit (e.g. handler oops) discards the stack, including the callback_head, while that callback_head is still pending. By the time exit_task_work() runs, the stack memory formerly backing callback_head is already clobbered.
irq_thread() <-- on_exit_work allocated
** IRQ handler faults **
oops_end()
rewind_stack_and_make_dead() <-- on_exit_work freed
make_task_dead()
do_exit(SIGSEGV)
...
exit_shm() <-- on_exit_work clobbered
...
exit_task_work() <-- stack use-after-free
exit_shm()+0x30 <-- wild jump to return addrThus, a benign threaded IRQ oops (e.g. a NULL pointer deref) is turned into a wild jump. This is caught by kernel IBT:
** first fault **
Oops: general protection fault, kernel NULL pointer dereference 0x3c0: 0000 [#1] SMP NOPTI ... ** second fault ** Missing ENDBR: exit_shm+0x30/0x1c0 kernel BUG at arch/x86/kernel/cet.c:133! ... ? task_work_run+0x5c/0x90 ? do_exit+0x209/0x460 ? rewind_stack_and_make_dead+0x16/0x20 ... note: irq/165-AudioDS[1427] exited with irqs disabled Fixing recursive fault but reboot is needed!
Fix this by storing the callback_head in struct irqaction. The irqaction is only freed once irq_thread_dtor() finishes.
--- include/linux/interrupt.h | 2 ++ kernel/irq/manage.c | 9 ++++----- 2 files changed, 6 insertions(+), 5 deletions(-)
include/linux/interrupt.h +2 -0
@@ -114,6 +114,7 @@ typedef irqreturn_t (*irq_handler_t)(int* @thread_flags: flags related to @thread * @thread_mask: bitmask for keeping track of @thread activity * @dir: pointer to the proc/irq/NN/name entry +* @thread_dtor: task_work for @thread irregular exit cleanup */ struct irqaction {irq_handler_t handler;
@@ -129,6 +130,7 @@ struct irqaction {unsigned long thread_mask;const char *name;struct proc_dir_entry *dir; +struct callback_head thread_dtor; }____cacheline_internodealigned_in_smp ;extern irqreturn_t no_action (int cpl,void *dev_id);
kernel/irq/manage.c +4 -5
@@ -1253,9 +1253,9 @@ static void __irq_thread_dtor(struct irqirq_finalize_oneshot (desc, action); } -static void irq_thread_dtor (struct callback_head *unused) +static void irq_thread_dtor (struct callback_head *work) { -struct irqaction *action =kthread_data (current); + struct irqaction *action = container_of(work, struct irqaction, thread_dtor);__irq_thread_dtor (action);clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags);
@@ -1303,7 +1303,6 @@ static void wake_up_and_wait_for_irq_thr*/ static int irq_thread (void *data) { -struct callback_head on_exit_work;struct irqaction *action = data;struct irq_desc *desc =irq_to_desc (action->irq); irqreturn_t (*handler_fn)(struct irq_desc *desc,
@@ -1320,8 +1319,8 @@ static int irq_thread(void *data) handler_fn = irq_thread_fn;set_bit (IRQTF_EXIT_WORK , &action->thread_flags); -init_task_work (&on_exit_work, irq_thread_dtor); -task_work_add (current, &on_exit_work,TWA_NONE ); +init_task_work (&action->thread_dtor, irq_thread_dtor); +task_work_add (current, &action->thread_dtor,TWA_NONE );irq_thread_check_affinity (desc, action);
Greg Kroah-Hartman
maintainerPATCH 616/3318 HID: hiddev: keep state alive through disconnect unlock
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yousef Alhouseen <[email protected]>
commit 03f449b5de36a25fc5eba7dabf2b4494389bdb91 upstream.
mutex_unlock() clears the mutex owner before taking its wait lock. A thread spinning in the final hiddev file release can acquire existancelock after hiddev_disconnect() clears the owner, then free hiddev before the disconnecting thread reaches the mutex wait lock. This causes a use-after-free in the mutex slow unlock path.
Give the connection and each open file an explicit reference. Drop each reference only after its existancelock critical section has completed, so neither unlock path can free the mutex while the other is still using it.
--- drivers/hid/usbhid/hiddev.c | 37 +++++++++++++++++++------------------ include/linux/hiddev.h | 2 ++ 2 files changed, 21 insertions(+), 18 deletions(-)
drivers/hid/usbhid/hiddev.c +19 -18
@@ -46,6 +46,12 @@ struct hiddev_list {struct mutex thread_lock; }; +static void hiddev_put (struct hiddev *hiddev) +{ +if (refcount_dec_and_test (&hiddev->refcount)) +kfree (hiddev); +} +/* * Find a report, given the report's type and ID. The ID can be specified * indirectly by REPORT_ID_FIRST (which returns the first report of the given
@@ -216,26 +222,21 @@ static int hiddev_fasync(int fd, structstatic int hiddev_release (struct inode * inode,struct file * file) {struct hiddev_list *list = file->private_data; +struct hiddev *hiddev = list->hiddev;unsigned long flags; -spin_lock_irqsave (&list->hiddev->list_lock, flags); +spin_lock_irqsave (&hiddev->list_lock, flags);list_del (&list->node); -spin_unlock_irqrestore (&list->hiddev->list_lock, flags); +spin_unlock_irqrestore (&hiddev->list_lock, flags); -mutex_lock (&list->hiddev->existancelock); -if (!--list->hiddev->open) { -if (list->hiddev->exist) { -hid_hw_close (list->hiddev->hid); -hid_hw_power (list->hiddev->hid,PM_HINT_NORMAL ); - }else { -mutex_unlock (&list->hiddev->existancelock); -kfree (list->hiddev); -vfree (list); -return 0 ; - } +mutex_lock (&hiddev->existancelock); +if (!--hiddev->open && hiddev->exist) { +hid_hw_close (hiddev->hid); +hid_hw_power (hiddev->hid,PM_HINT_NORMAL ); } -mutex_unlock (&list->hiddev->existancelock); +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev);vfree (list);return 0 ;
@@ -270,6 +271,7 @@ static int __hiddev_open(struct hiddev *spin_unlock_irq (&hiddev->list_lock); file->private_data = list; +refcount_inc (&hiddev->refcount);return 0 ;
@@ -897,6 +899,7 @@ int hiddev_connect(struct hid_device *hiINIT_LIST_HEAD (&hiddev->list);spin_lock_init (&hiddev->list_lock);mutex_init (&hiddev->existancelock); +refcount_set (&hiddev->refcount,1 ); hid->hiddev = hiddev; hiddev->hid = hid; hiddev->exist =1 ;
@@ -937,9 +940,7 @@ void hiddev_disconnect(struct hid_deviceif (hiddev->open) {hid_hw_close (hiddev->hid);wake_up_interruptible (&hiddev->wait); -mutex_unlock (&hiddev->existancelock); - }else { -mutex_unlock (&hiddev->existancelock); -kfree (hiddev); } +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev); }
include/linux/hiddev.h +2 -0
@@ -13,6 +13,7 @@#ifndef _HIDDEV_H#define _HIDDEV_H +#include <linux/refcount.h> #include <uapi/linux/hiddev.h>
@@ -24,6 +25,7 @@ struct hiddev {int minor;int exist;int open; +refcount_t refcount;struct mutex existancelock;wait_queue_head_t wait;struct hid_device *hid;
Greg Kroah-Hartman
maintainerPATCH 617/3318 io_uring/io-wq: save worker type before dropping its reference
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 37e425460b7c41687e51e3254b1eb1d799da9614 upstream.
io_wq_cancel_tw_create() inspects cb->func after calling io_worker_cancel_cb(). For an existing worker, that call can drop the last worker reference and wake io_worker_exit(). If the canceling task is preempted, the worker can be unlinked and freed by kfree_rcu() before the callback function is inspected. KASAN reports a slab-use-after-free read in this path.
Save whether the callback belongs to an unpublished continuation worker while its reference is still held, then use the saved result for the conditional free. This preserves the existing accounting and frees only the worker allocated for the canceled continuation.
--- io_uring/io-wq.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
io_uring/io-wq.c +5 -3
@@ -1326,14 +1326,16 @@ static void io_wq_cancel_tw_create(strucwhile ((cb =task_work_cancel_match (wq->task, io_task_work_match, wq)) !=NULL ) {struct io_worker *worker; +bool free_worker; worker = container_of(cb, struct io_worker, create_work); -io_worker_cancel_cb (worker);/* * Only the worker continuation helper has worker allocated and -* hence needs freeing. +* hence needs freeing. Save this before dropping its reference. */ -if (cb->func == create_worker_cont) + free_worker = cb->func == create_worker_cont; +io_worker_cancel_cb (worker); +if (free_worker)kfree (worker); } }
Greg Kroah-Hartman
maintainerPATCH 618/3318 KVM: PPC: Book3S HV: Add SRCU protection for virtual-mode HPT hcalls
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 61a39797bb136243c48b46e2586d8a9e2cea6a89 upstream.
The virtual-mode HPT hcall handlers (H_ENTER, H_REMOVE, H_BULK_REMOVE, H_CLEAR_REF, H_CLEAR_MOD) call into book3s_hv_rm_mmu.c, which accesses memslots via kvm_memslots_raw(). kvm_memslots_raw() uses rcu_dereference_raw_check() to bypass SRCU lockdep annotation checking. This is safe in real mode because the entire guest entry/exit is wrapped in srcu_read_lock/unlock inside kvmppc_run_core() and kvmhv_run_single_vcpu().
However, since commit 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults"), these same handlers are also executed in virtual mode via kvmppc_pseries_do_hcall(), which runs after SRCU has already been released on guest exit.
A concurrent KVM_SET_USER_MEMORY_REGION deletion or move can therefore call synchronize_srcu_expedited() — which does not wait for this thread — and then kfree(slot) and vfree(slot->arch.rmap) while the hcall handler still holds a raw pointer to the memslot. lock_rmap() then writes to freed vmalloc memory, leading to use-after-free and memory corruption. Because kvm_memslots_raw() suppresses lockdep checks, this race is entirely silent.
Fix this by factoring out the 7 HPT hcall handlers (H_REMOVE, H_ENTER, H_READ, H_CLEAR_MOD, H_CLEAR_REF, H_PROTECT, H_BULK_REMOVE) into a helper function, kvmppc_pseries_do_hpt_hcall(), and wrapping its call site in srcu_read_lock(&kvm->srcu) / srcu_read_unlock(&kvm->srcu, idx). Targeting only the HPT hcalls avoids wrapping non-HPT hcalls that sleep (such as H_CONFER, H_REGISTER_VPA, H_PAGE_INIT) or handlers that already acquire SRCU internally (such as H_RTAS).
--- arch/powerpc/kvm/book3s_hv.c | 70 +++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 35 deletions(-)
arch/powerpc/kvm/book3s_hv.c +35 -35
@@ -1088,6 +1088,38 @@ static long kvmppc_h_rpt_invalidate(strureturn H_SUCCESS ; } +static long kvmppc_pseries_do_hpt_hcall (struct kvm_vcpu *vcpu,unsigned long req) +{ +switch (req) { +case H_REMOVE : +return kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_ENTER : +return kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 ), +kvmppc_get_gpr (vcpu,7 )); +case H_READ : +return kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_MOD : +return kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_REF : +return kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_PROTECT : +return kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_BULK_REMOVE : +return kvmppc_h_bulk_remove (vcpu); + } + +return H_FUNCTION ; +} +int kvmppc_pseries_do_hcall (struct kvm_vcpu *vcpu) {struct kvm *kvm = vcpu->kvm;
@@ -1103,47 +1135,15 @@ int kvmppc_pseries_do_hcall(struct kvm_vswitch (req) {case H_REMOVE : - ret =kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_ENTER : - ret =kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 ), -kvmppc_get_gpr (vcpu,7 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_READ : - ret =kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_MOD : - ret =kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_REF : - ret =kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_PROTECT : - ret =kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_BULK_REMOVE : - ret =kvmppc_h_bulk_remove (vcpu); + idx =srcu_read_lock (&kvm->srcu); + ret =kvmppc_pseries_do_hpt_hcall (vcpu, req); +srcu_read_unlock (&kvm->srcu, idx);if (ret ==H_TOO_HARD )return RESUME_HOST ;break ;
Greg Kroah-Hartman
maintainerPATCH 619/3318 media: cx23885: unregister DVB bus when SP2 CI setup fails
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 22f552ff726a82a086be4ef02ce5099a0e8624b6 upstream.
The DVBSKY S950C, DVBSKY T980C and TechnoTrend CT2-4500 CI paths register the DVB bus before attaching their SP2 CI client. If that client cannot be created, bound, or pinned, the current error path removes the I2C frontend components and only deallocates the frontend list, leaving the registered DVB adapter behind. Removing an I2C demod before unregistering the DVB bus can also expose the use-after-free ordering fixed for the normal remove path.
Unregister the DVB bus immediately when SP2 CI setup fails, before the existing I2C client cleanup. The bus helper empties the frontend list, so the later frontend deallocation has nothing left to release. Keep failures from vb2_dvb_register_bus() on the existing cleanup path. Also release an unbound SP2 client and propagate the actual I2C creation or CI registration error.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/media/pci/cx23885/cx23885-dvb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/media/pci/cx23885/cx23885-dvb.c +10 -4
@@ -1160,8 +1160,12 @@ static int dvb_register_ci_mac(struct cx info.platform_data = &sp2_config;request_module (info.type); client_ci =i2c_new_client_device (&i2c_bus->i2c_adap, &info); -if (!i2c_client_has_driver (client_ci)) +if (IS_ERR (client_ci)) +return PTR_ERR (client_ci); +if (!client_ci->dev.driver) { +i2c_unregister_device (client_ci);return -ENODEV ; + }if (!try_module_get (client_ci->dev.driver->owner)) {i2c_unregister_device (client_ci);return -ENODEV ;
@@ -1204,7 +1208,7 @@ static int dvb_register(struct cx23885_tint (*p_set_voltage)(struct dvb_frontend *fe,enum fe_sec_voltage voltage) =NULL ;int mfe_shared =0 ;/* bus not shared by default */ -int ret; +int ret = -EINVAL ;/* Get the first frontend */ fe0 =vb2_dvb_get_frontend (&port->frontends,1 );
@@ -2586,8 +2590,10 @@ static int dvb_register(struct cx23885_t goto frontend_detach; ret =dvb_register_ci_mac (port); -if (ret) +if (ret) { +vb2_dvb_unregister_bus (&port->frontends); goto frontend_detach; + }return 0 ;
@@ -2618,7 +2624,7 @@ frontend_detach: port->gate_ctrl =NULL ;vb2_dvb_dealloc_frontends (&port->frontends); -return -EINVAL ; +return ret; }int cx23885_dvb_register (struct cx23885_tsport *port)
Greg Kroah-Hartman
maintainerPATCH 620/3318 media: gspca: use vb2_video_unregister_device() on disconnect
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shuangpeng Bai <[email protected]>
commit 3dbbbc3cafa2de377d9b97af4e35b8b6b5282047 upstream.
gspca uses vb2_fop_release(), but gspca_disconnect() only unregisters the video device. If the queue owner closes the device after USB disconnect, vb2_fop_release() releases the queue and invokes gspca_stop_streaming() at that point.
gspca_stream_off() calls subdriver stop callbacks and usb_set_interface() through gspca_dev->dev. By the time the late close runs, the USB core can have freed the usb_device, resulting in a use-after-free. This was observed as a KASAN use-after-free in sd_stopN().
Use vb2_video_unregister_device() so the queue is released and streaming is stopped synchronously during disconnect, while the usb_device is still valid. Since the helper takes the queue lock, which is usb_lock, call it after dropping that lock.
--- drivers/media/usb/gspca/gspca.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/media/usb/gspca/gspca.c +1 -2
@@ -1643,9 +1643,8 @@ void gspca_disconnect(struct usb_interfa#endif v4l2_device_disconnect (&gspca_dev->v4l2_dev); -video_unregister_device (&gspca_dev->vdev); -mutex_unlock (&gspca_dev->usb_lock); +vb2_video_unregister_device (&gspca_dev->vdev);/* (this will call gspca_release() immediately or on last close) */ v4l2_device_put (&gspca_dev->v4l2_dev);
Greg Kroah-Hartman
maintainerPATCH 621/3318 media: imx-jpeg: cancel timeout worker when streaming stops
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 78fdfbf117c409273eecbfa7a528ef42358a0e38 upstream.
Each per-fd context ctx owns a delayed_work (ctx->task_timer, callback mxc_jpeg_device_run_timeout) armed via schedule_delayed_work() at the end of mxc_jpeg_device_run() to recover a stalled encode/decode job. The only existing cancellation is cancel_delayed_work() in the frame-done IRQ handler, which de-queues a pending work item but does not wait for a callback that has already started, and it only runs when a frame completes.
When the fd is closed while a job is in flight (the frame-done IRQ has not fired yet), nothing syncs the worker before mxc_jpeg_release() frees ctx with kfree() after v4l2_m2m_ctx_release(). A queued or executing mxc_jpeg_device_run_timeout() can then recover ctx through container_of(&ctx->task_timer) and dereference it (ctx->mxc_jpeg, slot_data, dev_warn) after ctx has been freed.
Cancel the worker from mxc_jpeg_stop_streaming(). The cancel cannot live in mxc_jpeg_release(): mxc_jpeg_device_run() arms the timer while holding only hw_lock, not the mxc_jpeg->lock mutex that release holds, so a cancel in release could still race a concurrent mxc_jpeg_device_run() that re-arms the timer afterwards. mxc_jpeg_stop_streaming() instead runs inside v4l2_m2m_ctx_release() -> vb2_queue_release(), i.e. after v4l2_m2m_cancel_job() has set TRANS_ABORT and waited for any in-flight job to finish (so __v4l2_m2m_try_queue() will not queue and v4l2_m2m_try_run() will not run any further job for this context, which prevents mxc_jpeg_device_run() from re-arming the timer) and before the m2m context is freed. cancel_delayed_work_sync() removes a pending work item and waits for a running callback, so the worker can no longer race with the subsequent kfree(). The cancel is placed before the buffer-release loop so a concurrently running timeout callback cannot race with it over the same buffers. If the frame-done IRQ canceled a still-pending timer, this cancel is a no-op; if the timeout callback has already started, it waits for the callback to finish. The same mxc_jpeg_stop_streaming() call is also reached from VIDIOC_STREAMOFF, which drains the worker early, although STREAMOFF itself does not free ctx -- the use-after-free arises only when the fd is later closed.
This bug was found by static analysis.
--- drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c +2 -0
@@ -1658,6 +1658,8 @@ static void mxc_jpeg_stop_streaming(strudev_dbg (ctx->mxc_jpeg->dev,"Stop streaming ctx=%p" , ctx); +cancel_delayed_work_sync (&ctx->task_timer); +/* Release all active buffers */ for (;;) {if (V4L2_TYPE_IS_OUTPUT (q->type))
Greg Kroah-Hartman
maintainerPATCH 622/3318 media: microchip-csi2dc: fix async notifier leak on probe error path
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cong Nguyen <[email protected]>
commit c7528789244ce7329ca883170fb9315d739ae985 upstream.
csi2dc_of_parse() ends up calling csi2dc_prepare_notifier(), which registers the V4L2 async notifier with v4l2_async_nf_register(). The probe error label csi2dc_probe_cleanup_notifier is reached after csi2dc_of_parse() has already succeeded (e.g. when media entity init, csi2dc_power() or v4l2_async_register_subdev() fail), but it calls only v4l2_async_nf_cleanup() and never v4l2_async_nf_unregister().
The notifier therefore stays chained in the global notifier_list while the enclosing struct csi2dc_device is freed, leading to list corruption and a use-after-free when the list is next walked.
Unregister the notifier before cleaning it up on the error path, matching the teardown already done in csi2dc_remove().
--- drivers/media/platform/microchip/microchip-csi2dc.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/platform/microchip/microchip-csi2dc.c +1 -0
@@ -733,6 +733,7 @@ static int csi2dc_probe(struct platform_return 0 ; csi2dc_probe_cleanup_notifier: +v4l2_async_nf_unregister (&csi2dc->notifier);v4l2_async_nf_cleanup (&csi2dc->notifier); csi2dc_probe_cleanup_entity:media_entity_cleanup (&csi2dc->csi2dc_sd.entity);
Greg Kroah-Hartman
maintainerPATCH 623/3318 media: redrat3: fix UAF in probe error path leaving rc device registered
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rik van Riel <[email protected]>
commit af452b9e01331b5338a1e5141624f17607239207 upstream.
redrat3 stores its device name and phys path inside the main rr3 structure, and the rc device's device_name and input_phys point into rr3. When the RC device is registered, it keeps those pointers.
KASAN: slab-use-after-free in string_nocheck lib/vsprintf.c:648 Read of size 1 at addr ffff888051fda758 by task udevd/7464 Call Trace: string_nocheck lib/vsprintf.c:648 [inline] string+0x216/0x2d0 lib/vsprintf.c:730 vsnprintf+0x74a/0xef0 lib/vsprintf.c:2945 vscnprintf+0x41/0x90 lib/vsprintf.c:3014 sysfs_emit+0x10e/0x180 fs/sysfs/file.c:761 input_dev_show_name+0x58/0x70 drivers/input/input.c:1282 Allocated by task 10: redrat3_dev_probe+0x477/0x2570 drivers/media/rc/redrat3.c:1023 Freed by task 10: redrat3_delete drivers/media/rc/redrat3.c:466 [inline] redrat3_dev_probe+0x1bf4/0x2570 drivers/media/rc/redrat3.c:1124
Syzkaller triggers this via usb probing. It probes the RedRat3 USB interface, which calls redrat3_dev_probe() in redrat3.c. That function allocates rr3, then builds an rc device whose name points into rr3 via redrat3_init_rc_dev() in redrat3.c, and registers it with rc_register_device().
When the detector enable fails after the RC device is registered, the probe jumps to the led_free path. That path unregisters the LED but does not unregister the RC device before freeing rr3 via redrat3_delete() in redrat3.c. The RC device still holds device_name = rr3->name which is now freed.
Later udevd reads /sys/.../input device name via sysfs_emit() in file.c, which calls input_dev_show_name() in input.c, which emits dev->name which is the freed rr3->name.
When the detector enable fails after the RC device is registered, the error path must not leave the RC device registered. Make the probe error path clean up the same way redrat3_dev_disconnect() does.
This change should be safe because the RC device is fully registered at this point and its teardown via rc_unregister_device() is protected by the input device mutex, and rr3 is still alive during unregister so device_name remains valid until after unregister. The URBs are killed before rc_free, so no completion can run after rc is freed. No new lock ordering is introduced.
--- drivers/media/rc/redrat3.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/redrat3.c +4 -0
@@ -977,6 +977,7 @@ static int redrat3_dev_probe(struct usb_struct device *dev = &intf->dev;struct usb_host_interface *uhi;struct redrat3_dev *rr3; +struct rc_dev *rc;struct usb_endpoint_descriptor *ep;struct usb_endpoint_descriptor *ep_narrow =NULL ;struct usb_endpoint_descriptor *ep_wide =NULL ;
@@ -1121,9 +1122,12 @@ static int redrat3_dev_probe(struct usb_return 0 ; led_free: +rc_unregister_device (rr3->rc);led_classdev_unregister (&rr3->led); redrat_free: + rc = rr3->rc;redrat3_delete (rr3, rr3->udev); +rc_free_device (rc); no_endpoints:return retval;
Greg Kroah-Hartman
maintainerPATCH 624/3318 serial: core: shut down initialized port on removal
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Putko <[email protected]>
commit 810d467c11f0c85107874d08dfdd11acba6aa0c0 upstream.
When a serial port configured as a console is opened and subsequently closed, tty_port_shutdown() skips invoking port->ops->shutdown() because port->console is true. As a result, tty_port_initialized() remains true and the port's interrupt handler stays registered in the irq subsystem.
If the underlying device is later unbound or removed (e.g. via sysfs driver unbind or device hot-unplug), serial_core_remove_one_port() unregisters the console, frees uport->name via kfree(), and tears down the port without shutting it down or freeing its IRQ. Consequently, the irqaction descriptor remains registered in genirq with action->name pointing to freed memory.
This triggers a use-after-free read whenever genirq accesses action->name, such as when reading /proc/interrupts:
BUG: KASAN: slab-use-after-free in string+0x476/0x570 Call Trace: string+0x476/0x570 vsnprintf+0x422/0x1300 seq_printf+0x... show_interrupts+...
Fix this by acquiring port->mutex in serial_core_remove_one_port() after console unregistration, clearing port->console under the mutex to prevent data races with concurrent tty_port_shutdown(), and invoking uart_shutdown(NULL, state) if the port remains initialized. This ensures that port->ops->shutdown() is called and the IRQ is freed before kfree(uport->name).
--- drivers/tty/serial/serial_core.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/tty/serial/serial_core.c +7 -0
@@ -3282,6 +3282,13 @@ static void serial_core_remove_one_port(if (uart_console (uport))unregister_console (uport->cons); + scoped_guard(mutex, &port->mutex) { + port->console = false; + +if (tty_port_initialized (port)) +uart_shutdown (NULL , state); + } +/* * Free the port IO and memory resources, if any. */
Greg Kroah-Hartman
maintainerPATCH 625/3318 xen-blkfront: unbind irq before tearing down ring and shadow requests
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuchao Zhang <[email protected]>
commit f3e27b7955727a4d7c0e9264a2a209fbba788bdc upstream.
In blkif_free_ring(), the driver tears down the ring's persistent grants, shadow request arrays, and shared ring structure (xenbus_teardown_ring), and only calls unbind_from_irqhandler() at the very end.
While blkif_free_ring() is freeing persistent grants and clearing the shadow array, the event channel interrupt (blkif_interrupt) is still registered and active. If an interrupt arrives from the backend during this teardown window, blkif_interrupt() reads rinfo->ring.sring and, via blkif_completion(), accesses rinfo->shadow[id].grants_used and rinfo->shadow[id].sg. blkif_free_ring() tears these structures down without holding rinfo->ring_lock, and the handler only checks info->connected at entry, so this is a real race resulting in a use-after-free or NULL pointer dereference.
Fix this by moving unbind_from_irqhandler() to the beginning of blkif_free_ring(). Calling unbind_from_irqhandler() first frees the IRQ and synchronizes with any in-flight interrupt handlers on other CPUs before ring memory and shadow request structures are deallocated, matching the teardown order in drivers/net/xen-netfront.c.
Message-ID: <[email protected]>
--- drivers/block/xen-blkfront.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/block/xen-blkfront.c +8 -4
@@ -1211,6 +1211,14 @@ static void blkif_free_ring(struct blkfrint i, j, segs;/* +* Interrupt teardown must be done ahead of freeing queue-related +* data, otherwise the interrupt handler can race with the cleanup. +*/ +if (rinfo->irq) +unbind_from_irqhandler (rinfo->irq, rinfo); + rinfo->evtchn = rinfo->irq =0 ; + +/* * Remove indirect pages, this only happens when using indirect * descriptors but not persistent grants */
@@ -1292,10 +1300,6 @@ free_shadow:/* Free resources associated with old device channel. */ xenbus_teardown_ring ((void **)&rinfo->ring.sring, info->nr_ring_pages, rinfo->ring_ref); - -if (rinfo->irq) -unbind_from_irqhandler (rinfo->irq, rinfo); - rinfo->evtchn = rinfo->irq =0 ; }static void blkif_free (struct blkfront_info *info,int suspend)
Greg Kroah-Hartman
maintainerPATCH 626/3318 wifi: ath9k: delete channel-context timers on deinit
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
commit 81394dfb9a7905472957628b560ae894eae3a30f upstream.
ath9k_deinit_channel_context() cancels chanctx_work but does not delete the offchannel and sched timers set up by ath9k_init_channel_context(). If either timer fires after deinit (e.g. during driver unload or suspend), it accesses sc->sc_ah which may already be freed by ath9k_hw_deinit(), causing a use-after-free.
Delete both timers with timer_shutdown_sync() before cancelling the work item.
--- drivers/net/wireless/ath/ath9k/channel.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/net/wireless/ath/ath9k/channel.c +2 -0
@@ -1368,6 +1368,8 @@ void ath9k_init_channel_context(struct avoid ath9k_deinit_channel_context (struct ath_softc *sc) { +timer_shutdown_sync (&sc->sched.timer); +timer_shutdown_sync (&sc->offchannel.timer);cancel_work_sync (&sc->chanctx_work); }
Greg Kroah-Hartman
maintainerPATCH 627/3318 usb: gadget: fix refcount underflow in gadgetfs_bind() error path
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nguyen Quang Le Kien <[email protected]>
commit cb3b441f2698455a48e9a023d5f7f4e3fcb94c73 upstream.
gadgetfs_bind() calls get_dev() only on the success path, but gadgetfs_unbind() called from the enomem error label unconditionally calls put_dev(). When bind fails (e.g. ENOMEM), put_dev() fires without a matching get_dev(), leaving the refcount unbalanced.
A subsequent close of the ep0 file descriptor calls dev_release() -> put_dev() which hits zero and frees the object; then gadgetfs_kill_sb() calls put_dev(the_device) again on the already-freed pointer, triggering a refcount underflow and use-after-free.
Fix by calling get_dev() at the start of gadgetfs_bind(), before any error path that invokes gadgetfs_unbind(), so the reference is always balanced regardless of whether bind succeeds or fails.
--- drivers/usb/gadget/legacy/inode.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/gadget/legacy/inode.c +2 -1
@@ -1682,6 +1682,8 @@ static int gadgetfs_bind(struct usb_gadg dev->gadget = gadget; gadget->ep0->driver_data = dev; +get_dev (dev); +/* preallocate control response and buffer */ dev->req =usb_ep_alloc_request (gadget->ep0,GFP_KERNEL );if (!dev->req)
@@ -1696,7 +1698,6 @@ static int gadgetfs_bind(struct usb_gadgspin_lock_irq (&dev->lock); dev->state =STATE_DEV_UNCONNECTED ;spin_unlock_irq (&dev->lock); -get_dev (dev);return 0 ; enomem:
Greg Kroah-Hartman
maintainerPATCH 628/3318 ufs: use u64 for directory size in ufs_last_byte
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: YANXIN LI <[email protected]>
commit 1eff23433e73d7da4f9e3529d2701e34962b161f upstream.
ufs1_read_inode() and ufs2_read_inode() copy the untrusted 64-bit on-disk size into inode->i_size. ufs_last_byte() then truncates that value to an unsigned int before calculating the valid extent of a directory folio.
A directory size of exactly 4 GiB is truncated to zero. In ufs_find_entry(), subtracting the requested record length from that zero forms an endpoint almost 4 GiB beyond the mapped folio. A crafted UFS2 image produces:
BUG: KASAN: use-after-free in ufs_find_entry+0x583/0x6e0 [ufs] Read of size 1 ... ufs_find_entry ufs_inode_by_name ufs_lookup __lookup_slow path_lookupat
The KASAN classification reflects that the adjacent physical page was free; the source-level operation is an out-of-folio read. A controlled UFS1 test with CONFIG_UFS_FS_WRITE enabled also made ufs_find_entry() return a directory entry from an adjacent anonymous page. unlink() then passed that pointer to ufs_delete_entry(), which cleared the adjacent page's 3
2-bit d_ino. This write result reproduced three out of three times.
UFS normally requires a privileged mount path. A relevant boundary is a privileged automounter or image-processing service handling an attacker-supplied filesystem. The write primitive additionally requires UFS1 to be mounted read-write with CONFIG_UFS_FS_WRITE enabled; the read is reachable with read-only UFS2.
Keep the intermediate size arithmetic at 64 bits so non-final pages are bounded at PAGE_SIZE. With this change, the same controlled tests reach the real on-disk directory entry and produce no adjacent-page write or KASAN report. A reproducer and full validation logs are available on request.
The vulnerable helper is present in v7.2-rc3, v7.1, v6.18.38, v6.12.95, v6.6.111, and upstream master at 1229e2e57a5c. Runtime reproduction and fix validation were performed in an x86-64 QEMU guest running v7.2-rc3 with generic KASAN.
--- fs/ufs/dir.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ufs/dir.c +1 -1
@@ -221,7 +221,7 @@ fail:static unsigned ufs_last_byte (struct inode *inode,unsigned long page_nr) { -unsigned last_byte = inode->i_size; +u64 last_byte = inode->i_size; last_byte -= page_nr <<PAGE_SHIFT ;if (last_byte >PAGE_SIZE )
Greg Kroah-Hartman
maintainerPATCH 629/3318 resource: report a devm_request_resource() conflict under the lock
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nickolai Zeldovich <[email protected]>
commit d2f7bdfdeac8137e942b32e0badc40e181127d7b upstream.
devm_request_resource() calls request_resource_conflict(), which takes resource_lock, tries to insert the new resource and returns a pointer to the conflicting resource after dropping the lock. The error message is then formatted from that pointer: conflict->name and the %pR argument read the name, start, end, flags and desc of a resource that nothing pins any more. The owner of the conflicting resource may call release_resource() and free it the moment the lock is dropped.
The conflicting resource normally belongs to another device. With two devices whose drivers claim overlapping regions (two PCI host bridges whose "ranges" windows overlap, two instances of a controller on the same aperture, or a stale claim an administrator is replacing), the following interleaving reads freed memory:
CPU 0: driver B probe CPU 1: driver A unbind
devm_request_resource(devB, root, resB)
request_resource_conflict()
write_lock(&resource_lock)
__request_resource() -> resA
write_unlock(&resource_lock)
devres_release_all(devA)
devm_resource_release()
release_resource(resA)
put_device() -> kfree(resA)
dev_err(..., resA->name, resA) use after freeBoth halves are reachable from userspace on any kernel: a write to the "unbind" file of the driver that holds the region and a write to the "bind" file of the driver that wants it. One in-tree path is drivers/pci/bus.c devm_request_pci_bus_resources(), called from host bridge probe for every bridge window; the windows are the embedded struct resource of kzalloc'ed resource_entry objects that pci_free_resource_list() frees when the other bridge is released. In the common case the "resource collision" message is garbled; with the slab object poisoned (CONFIG_SLUB_DEBUG) or reused, formatting conflict->name oopses, and KASAN reports a slab-use-after-free read in devm_request_resource(). All of this happens in a probe that is already failing with -EBUSY. The window is a few hundred instructions wide and exists only when two devices actually collide, so the race has not been observed outside of analysis.
Do the same here: take resource_lock, insert with __request_resource() and print the diagnostic while the lock still keeps the conflicting resource in the tree, then drop the lock. The return values and the devres handling are unchanged.
The change was built for x86_64 and RISC-V; the resource KUnit tests pass on both.
Found by formal verification of kernel/resource.c against the kernel binary.
--- kernel/resource.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/resource.c +7 -2
@@ -1547,10 +1547,15 @@ int devm_request_resource(struct device *ptr = new; - conflict =request_resource_conflict (root, new); -if (conflict) { +/* Report a conflict while the lock still keeps it in the tree. */ +write_lock (&resource_lock); + conflict =__request_resource (root, new); +if (conflict)dev_err (dev,"resource collision: %pR conflicts with %s %pR\n" , new, conflict->name, conflict); +write_unlock (&resource_lock); + +if (conflict) {devres_free (ptr);return -EBUSY ; }
Greg Kroah-Hartman
maintainerPATCH 630/3318 phy: core: Fix race-condition between _of_phy_get() and try_module_get()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryan O'Donoghue <[email protected]>
commit 090055ee629523092688da42428558ba56d4272f upstream.
Sashiko asked during a patch review if the existing usage pattern had a race condition; specifically in of_phy_get() if it was possible between returning from _of_phy_get() and running try_module_get() that a module might be unbound leading to use-after-free.
Looking at the code this appears to be so, there is no linkage between the phy and module under a synchronisation primitive.
Using the phy_provider_mutex in phy_get() will ensure there is a link between the returned phy pointer and the module_get() bumping the module reference count.
Amend phy_get(), of_phy_get() and devm_of_phy_get_by_index() to fix the same usage pattern.
phy_provider_unregister() must take the phy_provider_mutex so amending phy_get()/of_phy_get() to take that same mutex guarantees there is no use-after-free.
--- drivers/phy/phy-core.c | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-)
drivers/phy/phy-core.c +30 -15
@@ -119,13 +119,13 @@ static struct phy *phy_find(struct devicconst char *dev_id =dev_name (dev);struct phy_lookup *p, *pl =NULL ; -mutex_lock (&phy_provider_mutex); +lockdep_assert_held (&phy_provider_mutex); +list_for_each_entry (p, &phys, node)if (!strcmp (p->dev_id, dev_id) && !strcmp (p->con_id, con_id)) { pl = p;break ; } -mutex_unlock (&phy_provider_mutex);return pl ? pl->phy :ERR_PTR (-ENODEV ); }
@@ -574,6 +574,8 @@ static struct phy *_of_phy_get(struct destruct phy *phy =NULL ;struct of_phandle_args args; +lockdep_assert_held (&phy_provider_mutex); + ret =of_parse_phandle_with_args (np,"phys" ,"#phy-cells" , index, &args);if (ret)
@@ -585,11 +587,10 @@ static struct phy *_of_phy_get(struct de goto out_put_node; } -mutex_lock (&phy_provider_mutex); phy_provider =of_phy_provider_lookup (args.np);if (IS_ERR (phy_provider) || !try_module_get (phy_provider->owner)) { phy =ERR_PTR (-EPROBE_DEFER ); - goto out_unlock; + goto out_put_node; }if (!of_device_is_available (args.np)) {
@@ -603,8 +604,6 @@ static struct phy *_of_phy_get(struct de out_put_module:module_put (phy_provider->owner); -out_unlock: -mutex_unlock (&phy_provider_mutex); out_put_node:of_node_put (args.np);
@@ -628,15 +627,21 @@ struct phy *of_phy_get(struct device_nodif (con_id) index =of_property_match_string (np,"phy-names" , con_id); +mutex_lock (&phy_provider_mutex); + phy =_of_phy_get (np, index);if (IS_ERR (phy)) -return phy; + goto out_unlock; -if (!try_module_get (phy->ops->owner)) -return ERR_PTR (-EPROBE_DEFER ); +if (!try_module_get (phy->ops->owner)) { + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; + }get_device (&phy->dev); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (of_phy_get);
@@ -743,6 +748,7 @@ struct phy *phy_get(struct device *dev,struct phy *phy;struct device_link *link; +mutex_lock (&phy_provider_mutex);if (dev->of_node) {if (string) index = of_property_match_string(dev->of_node, "phy-names",
@@ -753,15 +759,18 @@ struct phy *phy_get(struct device *dev, }else {if (string ==NULL ) {dev_WARN (dev,"missing string\n" ); -return ERR_PTR (-EINVAL ); + phy =ERR_PTR (-EINVAL ); + goto out_unlock; } phy =phy_find (dev, string); }if (IS_ERR (phy)) -return phy; + goto out_unlock; -if (!try_module_get (phy->ops->owner)) -return ERR_PTR (-EPROBE_DEFER ); +if (!try_module_get (phy->ops->owner)) { + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; + }get_device (&phy->dev);
@@ -770,6 +779,8 @@ struct phy *phy_get(struct device *dev,dev_dbg (dev,"failed to create device link to %s\n" ,dev_name (phy->dev.parent)); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (phy_get);
@@ -918,15 +929,17 @@ struct phy *devm_of_phy_get_by_index(strif (!ptr)return ERR_PTR (-ENOMEM ); +mutex_lock (&phy_provider_mutex); phy =_of_phy_get (np, index);if (IS_ERR (phy)) {devres_free (ptr); -return phy; + goto out_unlock; }if (!try_module_get (phy->ops->owner)) {devres_free (ptr); -return ERR_PTR (-EPROBE_DEFER ); + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; }get_device (&phy->dev);
@@ -939,6 +952,8 @@ struct phy *devm_of_phy_get_by_index(strdev_dbg (dev,"failed to create device link to %s\n" ,dev_name (phy->dev.parent)); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (devm_of_phy_get_by_index);
Greg Kroah-Hartman
maintainerPATCH 631/3318 media: rc: Ensure that rc_unregister_device() does not free input device
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit 61c7ca95d2483c77dfdde1b007cbe846f145dec4 upstream.
During or after rc_unregister_device(), IR may still be reported which results in a input event being reported. This could result in a null pointer deref in rc_keydown() or a use-after-free of the input device if the pointer was read before it is set to NULL.
--- drivers/media/rc/rc-main.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/media/rc/rc-main.c +4 -4
@@ -1742,7 +1742,7 @@ void rc_free_device(struct rc_dev *dev)if (!dev)return ; -input_free_device (dev->input_dev); +input_put_device (dev->input_dev);put_device (&dev->dev);
@@ -1854,6 +1854,8 @@ static int rc_setup_rx_device(struct rc_if (rc)return rc; +input_get_device (dev->input_dev); +/* * Default delay of 250ms is too short for some protocols, especially * since the timeout is currently set to 250ms. Increase it to 500ms,
@@ -1880,10 +1882,8 @@ static void rc_free_rx_device(struct rc_if (!dev)return ; -if (dev->input_dev) { +if (dev->input_dev)input_unregister_device (dev->input_dev); - dev->input_dev =NULL ; - }ir_free_table (&dev->rc_map); }
Greg Kroah-Hartman
maintainerPATCH 632/3318 media: rc: Ensure registered is cleared in error path
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit 37efd09ba2c62e46e3a3a793025c186f8cd1a417 upstream.
If rc_register_device() fails, ensure that registered is not set to true. If lirc_register() succeeded, then userspace could have an open file descriptor open. This leads to a use-after-free.
lirc_unregister() must be called with registered = false, else there is a possibility that an fd is open and polling, which would never return POLLERR unless registered is false.
Note that registered must be changed under dev->lock, many functions read registered under lock (e.g. lirc_ioctl).
--- drivers/media/rc/rc-main.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
drivers/media/rc/rc-main.c +12 -4
@@ -1929,7 +1929,8 @@ int rc_register_device(struct rc_dev *de goto out_raw; } - dev->registered = true; +scoped_guard (mutex, &dev->lock) + dev->registered = true; rc =device_add (&dev->dev);if (rc)
@@ -1949,7 +1950,7 @@ int rc_register_device(struct rc_dev *deif (dev->allowed_protocols !=RC_PROTO_BIT_CEC ) { rc =lirc_register (dev);if (rc <0 ) - goto out_dev; + goto out_lirc; }if (dev->driver_type !=RC_DRIVER_IR_RAW_TX ) {
@@ -1972,11 +1973,18 @@ int rc_register_device(struct rc_dev *de out_rx:rc_free_rx_device (dev); out_lirc: -if (dev->allowed_protocols !=RC_PROTO_BIT_CEC ) +scoped_guard (mutex, &dev->lock) + dev->registered = false; + +if (device_is_registered (&dev->lirc_dev))lirc_unregister (dev); -out_dev:device_del (&dev->dev); +/* registered already cleared above */ + goto out_free_table; out_rx_free: +scoped_guard (mutex, &dev->lock) + dev->registered = false; +out_free_table:ir_free_table (&dev->rc_map); out_raw:ir_raw_event_free (dev);
Greg Kroah-Hartman
maintainerPATCH 633/3318 media: rc: fintek-cir: process a full RX buffer instead of overflowing it
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weigang He <[email protected]>
commit d1febef1bcfa7bbc401729f994c375b91a833911 upstream.
fintek_get_rx_ir_data() drains the CIR RX FIFO into fintek->buf[], which holds RX_BUF_LEN (32) bytes, for as long as CIR_STATUS reports pending RX data:
do {
sample = fintek_cir_reg_read(fintek, CIR_RX_DATA);
...
fintek->buf[fintek->pkts] = sample;
fintek->pkts++;
...
} while (status & rx_irqs);Nothing bounds fintek->pkts. If the hardware reports data for more than RX_BUF_LEN reads in one interrupt, the loop writes past the end of buf[], starting with the pkts counter that follows it in struct fintek_dev.
Hand a full buffer to fintek_process_rx_ir_data(), which parses the samples and resets fintek->pkts, before storing the next sample. This keeps the parser state consistent and drops no samples. The loop still relies on the status register to terminate.
The driver does not document the hardware FIFO depth, so it is not known whether a working device can trigger this.
Found by static analysis tool CodeQL.
--- drivers/media/rc/fintek-cir.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/fintek-cir.c +4 -0
@@ -340,6 +340,10 @@ static void fintek_get_rx_ir_data(struct sample =fintek_cir_reg_read (fintek,CIR_RX_DATA );fit_dbg ("%s: sample: 0x%02x" , __func__, sample); +/* Process a full buffer before storing the next sample. */ +if (fintek->pkts >=RX_BUF_LEN ) +fintek_process_rx_ir_data (fintek); + fintek->buf[fintek->pkts] = sample; fintek->pkts++;
Greg Kroah-Hartman
maintainerPATCH 634/3318 media: rc: mce_kbd: Fix inconsistent locking of keylock
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit 29ee25fa9beb3232808e6d0b3e8ebfb0427cb820 upstream.
data->keylock is taken with spin_lock() in ir_mce_kbd_decode(), which runs in the raw IR decode kthread with local interrupts enabled, but with spin_lock_irqsave() in mce_kbd_rx_timeout(), the rx_timeout timer callback, which runs in softirq context.
If the decode kthread is holding keylock via spin_lock() when a timer interrupt fires on the same CPU and the softirq runs mce_kbd_rx_timeout(), the softirq spins forever waiting for a lock that only the now-preempted kthread can release, while the kthread cannot run again until the softirq gives up the CPU. This deadlocks the CPU.
--- drivers/media/rc/ir-mce_kbd-decoder.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/media/rc/ir-mce_kbd-decoder.c +3 -2
@@ -218,6 +218,7 @@ static int ir_mce_kbd_decode(struct rc_dstruct mce_kbd_dec *data = &dev->raw->mce_kbd;u32 scancode;unsigned long delay; +unsigned long flags;struct lirc_scancode lsc = {};if (!is_timing_event (ev)) {
@@ -318,7 +319,7 @@ again: scancode = data->body &0xffffff ;dev_dbg (&dev->dev,"keyboard data 0x%08x\n" , data->body); -spin_lock (&data->keylock); +spin_lock_irqsave (&data->keylock, flags);if (scancode) { delay =usecs_to_jiffies (dev->timeout) +msecs_to_jiffies (100 );
@@ -328,7 +329,7 @@ again: }/* Pass data to keyboard buffer parser */ ir_mce_kbd_process_keyboard_data (dev, scancode); -spin_unlock (&data->keylock); +spin_unlock_irqrestore (&data->keylock, flags); lsc.rc_proto =RC_PROTO_MCIR2_KBD ;break ;case MCIR2_MOUSE_NBITS :
Greg Kroah-Hartman
maintainerPATCH 635/3318 media: rc: Use after free in ir_raw_event_handle()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit 3ae19773168104fa57d2a2ec57731e89df54175f upstream.
If rc_unregister_device() is called while IR is being processed, then ir_raw_event_handle() could call wake_up_process(dev->raw->thread) after kthread_stop(dev->raw->thread). Avoid use after free by using get_task_struct().
--- drivers/media/rc/rc-ir-raw.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
drivers/media/rc/rc-ir-raw.c +14 -2
@@ -647,8 +647,13 @@ int ir_raw_event_register(struct rc_devvoid ir_raw_event_free (struct rc_dev *dev) { -kfree (dev->raw); - dev->raw =NULL ; +if (dev->raw) { +timer_delete_sync (&dev->raw->edge_handle); +if (dev->raw->thread) +put_task_struct (dev->raw->thread); +kfree (dev->raw); + dev->raw =NULL ; + } }void ir_raw_event_unregister (struct rc_dev *dev)
@@ -658,6 +663,13 @@ void ir_raw_event_unregister(struct rc_dif (!dev || !dev->raw)return ; +/* +* After ir_raw_event_unregister() is called, an sync +* call to ir_raw_event_handle() can still arrive. This function +* may call wake_up_process(dev->raw->thread). Ensure this memory +* is not freed by kthread_stop(). +*/ +get_task_struct (dev->raw->thread);kthread_stop (dev->raw->thread);del_timer_sync (&dev->raw->edge_handle);
Greg Kroah-Hartman
maintainerPATCH 636/3318 media: rc: After rc_unregister_device() timers can be re-armed
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit ef41a67979aed4d7d4f393c56c1e25b6754e2b78 upstream.
If rc_keydown() is called after rc_register_device(), then the timers can be re-armed. Delete them again for a final time.
--- drivers/media/rc/rc-main.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/media/rc/rc-main.c +5 -0
@@ -1742,6 +1742,11 @@ void rc_free_device(struct rc_dev *dev)if (!dev)return ; +if (dev->input_dev) { +timer_delete_sync (&dev->timer_keyup); +timer_delete_sync (&dev->timer_repeat); + } +input_put_device (dev->input_dev);put_device (&dev->dev);
Greg Kroah-Hartman
maintainerPATCH 637/3318 media: rc: Fix use after free in bpf progs
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit f95a9f8472f97c30106513fc7494b7abad243949 upstream.
Since commit dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks"), rcdev->raw is no longer set to NULL after device unregister. raw->progs could point to stale data.
--- drivers/media/rc/bpf-lirc.c | 18 +++++++++++++----- drivers/media/rc/rc-ir-raw.c | 11 +++-------- 2 files changed, 16 insertions(+), 13 deletions(-)
drivers/media/rc/bpf-lirc.c +13 -5
@@ -148,12 +148,13 @@ static int lirc_bpf_attach(struct rc_devif (ret)return ret; - raw = rcdev->raw; -if (!raw) { +if (!rcdev->registered) { ret = -ENODEV ; goto unlock; } + raw = rcdev->raw; + old_array =lirc_rcu_dereference (raw->progs);if (old_array &&bpf_prog_array_length (old_array) >=BPF_MAX_PROGS ) { ret = -E2BIG ;
@@ -186,12 +187,13 @@ static int lirc_bpf_detach(struct rc_devif (ret)return ret; - raw = rcdev->raw; -if (!raw) { +if (!rcdev->registered) { ret = -ENODEV ; goto unlock; } + raw = rcdev->raw; + old_array =lirc_rcu_dereference (raw->progs); ret =bpf_prog_array_copy (old_array, prog,NULL ,0 , &new_array);/*
@@ -235,7 +237,8 @@ void lirc_bpf_free(struct rc_dev *rcdev)struct bpf_prog_array_item *item;struct bpf_prog_array *array; - array =lirc_rcu_dereference (rcdev->raw->progs); + array =rcu_replace_pointer (rcdev->raw->progs,NULL , +lockdep_is_held (&ir_raw_handler_lock));if (!array)return ;
@@ -316,6 +319,11 @@ int lirc_prog_query(const union bpf_attrif (ret) goto put; +if (!rcdev->registered) { + ret = -ENODEV ; + goto unlock; + } + progs =lirc_rcu_dereference (rcdev->raw->progs); cnt = progs ?bpf_prog_array_length (progs) :0 ;
drivers/media/rc/rc-ir-raw.c +3 -8
@@ -649,8 +649,11 @@ void ir_raw_event_free(struct rc_dev *de {if (dev->raw) {timer_delete_sync (&dev->raw->edge_handle); +mutex_lock (&ir_raw_handler_lock);if (dev->raw->thread)put_task_struct (dev->raw->thread); +lirc_bpf_free (dev); +mutex_unlock (&ir_raw_handler_lock);kfree (dev->raw); dev->raw =NULL ; }
@@ -660,9 +663,6 @@ void ir_raw_event_unregister(struct rc_d {struct ir_raw_handler *handler; -if (!dev || !dev->raw) -return ; -/* * After ir_raw_event_unregister() is called, an sync * call to ir_raw_event_handle() can still arrive. This function
@@ -682,11 +682,6 @@ void ir_raw_event_unregister(struct rc_dlirc_bpf_free (dev); -/* -* A user can be calling bpf(BPF_PROG_{QUERY|ATTACH|DETACH}), so -* ensure that the raw member is null on unlock; this is how -* "device gone" is checked. -*/ mutex_unlock (&ir_raw_handler_lock); }
Greg Kroah-Hartman
maintainerPATCH 638/3318 media: rc: Fix ABBA deadlock by making locks more fine grained
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit c6d68866ad8aa1e957a3e5a6ede971148f1e3d59 upstream.
The ir_raw_event_unregister() function takes the ir_raw_handler_lock first and then the rc_dev->lock. Other functions like change_protocol do this in the reverse order.
This means that an ir decoder module unload and writing to the protocol sysfs file can cause a deadlock.
ir_raw_handler_lock protects the client list, amongst other things. Split this out into a separate lock so we can ensure the locking order is always the same.
--- drivers/media/rc/rc-ir-raw.c | 39 ++++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-)
drivers/media/rc/rc-ir-raw.c +24 -15
@@ -10,7 +10,8 @@#include <linux/sched.h> #include "rc-core-priv.h" -/* Used to keep track of IR raw clients, protected by ir_raw_handler_lock */ +/* Used to keep track of IR raw clients, protected by ir_raw_client_lock */ +static DEFINE_MUTEX (ir_raw_client_lock);static LIST_HEAD (ir_raw_client_list);/* Used to handle IR raw handler extensions */
@@ -288,13 +289,6 @@ static int change_protocol(struct rc_devreturn 0 ; } -static void ir_raw_disable_protocols (struct rc_dev *dev,u64 protocols) -{ -mutex_lock (&dev->lock); - dev->enabled_protocols &= ~protocols; -mutex_unlock (&dev->lock); -} -/** * ir_raw_gen_manchester() - Encode data with Manchester (bi-phase) modulation. * @ev: Pointer to pointer to next free event. *@ev is incremented for
@@ -632,15 +626,18 @@ int ir_raw_event_register(struct rc_dev {struct task_struct *thread; +/* Holding dev->lock could result in a dead-lock */ +lockdep_assert_not_held (&dev->lock); + thread =kthread_run (ir_raw_event_thread, dev->raw,"rc%u" , dev->minor);if (IS_ERR (thread))return PTR_ERR (thread); dev->raw->thread = thread; -mutex_lock (&ir_raw_handler_lock); +mutex_lock (&ir_raw_client_lock);list_add_tail (&dev->raw->list, &ir_raw_client_list); -mutex_unlock (&ir_raw_handler_lock); +mutex_unlock (&ir_raw_client_lock);return 0 ; }
@@ -673,16 +670,19 @@ void ir_raw_event_unregister(struct rc_dkthread_stop (dev->raw->thread);del_timer_sync (&dev->raw->edge_handle); -mutex_lock (&ir_raw_handler_lock); +mutex_lock (&ir_raw_client_lock);list_del (&dev->raw->list); + +mutex_lock (&ir_raw_handler_lock);list_for_each_entry (handler, &ir_raw_handler_list, list)if (handler->raw_unregister && (handler->protocols & dev->enabled_protocols)) handler->raw_unregister (dev);lirc_bpf_free (dev); -mutex_unlock (&ir_raw_handler_lock); + +mutex_unlock (&ir_raw_client_lock); }/*
@@ -705,15 +705,24 @@ void ir_raw_handler_unregister(struct irstruct ir_raw_event_ctrl *raw;u64 protocols = ir_raw_handler->protocols; +mutex_lock (&ir_raw_client_lock); +mutex_lock (&ir_raw_handler_lock);list_del (&ir_raw_handler->list); +atomic64_andnot (protocols, &available_protocols); +mutex_unlock (&ir_raw_handler_lock); +list_for_each_entry (raw, &ir_raw_client_list, list) { +mutex_lock (&raw->dev->lock); +mutex_lock (&ir_raw_handler_lock);if (ir_raw_handler->raw_unregister && (raw->dev->enabled_protocols & protocols)) ir_raw_handler->raw_unregister (raw->dev); -ir_raw_disable_protocols (raw->dev, protocols); + raw->dev->enabled_protocols &= ~protocols; +mutex_unlock (&ir_raw_handler_lock); +mutex_unlock (&raw->dev->lock); } -atomic64_andnot (protocols, &available_protocols); -mutex_unlock (&ir_raw_handler_lock); + +mutex_unlock (&ir_raw_client_lock); }EXPORT_SYMBOL (ir_raw_handler_unregister);
Greg Kroah-Hartman
maintainerPATCH 639/3318 ocfs2/heartbeat: unlink live slots when their node is missing
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 3ccd24c3f7a577b84a532cb027f1378385b82ef6 upstream.
o2hb_shutdown_slot() returns immediately when its node is no longer in the configfs registry. A slot can still be linked in o2hb_live_slots when that lookup fails. Region teardown or startup-error cleanup then frees the slot array without removing its embedded list member.
With the same peer live in another region, the next list update can follow a predecessor into the freed array. Reusing the node number can also make a later insertion encounter that stale member.
Always remove the slot under o2hb_live_lock, even when node lookup fails. Preserve aggregate membership accounting and the last-region DOWN
callback: the existing callback interface explicitly permits a NULL node for DOWN events. Only drop the node reference when lookup returned one. This closes both normal release and startup-abort paths without changing the publication or callback locking protocol.
Also require a configured node before admitting a new live slot in o2hb_check_slot(). The early live-bitmap check is not held through
admission: the last live slot in another region can be removed in between. Without a node, admission can then queue an UP event with a NULL argument and hit the event helper's BUG_ON. Existing live slots can still leave and generate NULL-node DOWN events.
A controlled probe-instrumented test reproduced this while stopping one of two regions after removing the peer from configfs. Its KASAN report includes:
BUG: KASAN: slab-use-after-free in __list_del_entry_valid_or_report+0x1e0/0x210 Read of size 8 at addr ffff888106a4ac60 by task o2hb-pmbd0058_b/497 Call Trace: <TASK> dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 kasan_report+0xe0/0x110 __list_del_entry_valid_or_report+0x1e0/0x210 o2hb_do_disk_heartbeat+0x1591/0x2c50 o2hb_thread+0x1ed/0xe70 kthread+0x351/0x460 ret_from_fork+0x659/0x940 ret_from_fork_asm+0x1a/0x30 </TASK> Allocated by task 491: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0xaa/0xb0 __kmalloc_noprof+0x2de/0x780 o2hb_region_dev_store+0x7c2/0x1b60 configfs_write_iter+0x2f9/0x4f0 vfs_write+0x639/0x1010 ksys_write+0x111/0x200 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f Freed by task 491: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 kasan_save_free_info+0x3b/0x60 __kasan_slab_free+0x5f/0x80 kfree+0x308/0x580 o2hb_unmap_slot_data+0x1db/0x330 o2hb_region_release+0x14b/0x4f0 config_item_cleanup+0x14b/0x230 config_item_put+0x79/0x90 configfs_rmdir+0x58a/0x910 vfs_rmdir+0x2e8/0x820 filename_rmdir+0x3b1/0x520 __x64_sys_rmdir+0x4b/0x70 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f
--- fs/ocfs2/cluster/heartbeat.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/ocfs2/cluster/heartbeat.c +8 -4
@@ -860,8 +860,11 @@ static void o2hb_shutdown_slot(struct o2int queued =0 ; node =o2nm_get_node_by_num (slot->ds_node_num); -if (!node) -return ; +/* +* The node may have been removed from the node table while this +* region's slot is still linked. The list member must still be +* removed before the region releases its slot array. +*/ spin_lock (&o2hb_live_lock);if (!list_empty (&slot->ds_live_item)) {
@@ -883,7 +886,8 @@ static void o2hb_shutdown_slot(struct o2if (queued)o2hb_run_event_list (&event); -o2nm_node_put (node); +if (node) +o2nm_node_put (node); }static void o2hb_set_quorum_device (struct o2hb_region *reg)
@@ -1018,7 +1022,7 @@ static int o2hb_check_slot(struct o2hb_r fire_callbacks:/* dead nodes only come to life after some number of * changes at any time during their dead time */ -if (list_empty (&slot->ds_live_item) && +if (node &&list_empty (&slot->ds_live_item) && slot->ds_changed_samples >=O2HB_LIVE_THRESHOLD ) {mlog (ML_HEARTBEAT ,"Node %d (id 0x%llx) joined my region\n" , slot->ds_node_num, (long long )slot->ds_last_generation);
Greg Kroah-Hartman
maintainerPATCH 640/3318 ocfs2/dlm: hold a lock reference across grant AST enqueue
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 71743471204e21113295c786e5cfa570294234a4 upstream.
A newly granted remote lock must remain alive until its grant AST is queued. dlmlock_master() publishes the lock on res->granted with its base and queue references, then drops res->spinlock before calling dlm_queue_ast(). The resource's reserved AST count does not retain the lock itself.
This can fail when a peer dies with an immediately grantable CREATE buffered on its socket. O2NET's node-down callback flushes receive work before DLM cleanup, but the flush only waits for work queued on entry. A data-ready callback that already selected the socket container can queue new receive work after the flush advances its work color. Socket shutdown does not discard bytes already queued for TCP receive.
The late receive work and DLM node-down cleanup can interleave as follows (the lock reference operations shown are before this fix):
Socket data-ready Node-down thread Receive worker ----------------- ---------------- --------------
o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered CREATE dlmlock_master()
lock res->spinlock add lock to granted unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put queue/base refs
free lock
unlock res->spinlock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)
DLM cleanup holds res->spinlock while dlm_free_dead_locks() drops the queue and base references. The CREATE handler no longer holds that spinlock when __dlm_queue_ast() reads the lock, before taking its AST list reference.
Take a temporary lock reference under res->spinlock when a grant AST will be queued, and drop it after dlm_queue_ast(). This keeps the lock alive across cleanup until the AST path has taken its own reference, without reversing the existing AST/resource lock order.
KASAN report as below:
BUG: KASAN: slab-use-after-free in __dlm_queue_ast+0x8a4/0xc00
Read of size 8 at addr ffff88810ead5940 by task kworker/u16:3/52
CPU: 3 UID: 0 PID: 52 Comm: kworker/u16:3 Not tainted 7.3.0-rc4-next-20260921-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
Workqueue: o2net o2net_rx_until_empty
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? __dlm_queue_ast+0x8a4/0xc00
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? __dlm_queue_ast+0x8a4/0xc00
kasan_report+0xe0/0x110
? __dlm_queue_ast+0x8a4/0xc00
__dlm_queue_ast+0x8a4/0xc00
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? do_raw_spin_lock+0x130/0x270
? __pfx___dlm_queue_ast+0x10/0x10
? __pfx_do_raw_spin_lock+0x10/0x10
? _raw_spin_unlock_irqrestore+0x45/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? lockdep_hardirqs_on_prepare+0xeb/0x1a0
dlm_queue_ast+0x46/0x70
dlmlock_master+0x51f/0xf50
? __pfx_dlmlock_master+0x10/0x10
? dlm_create_lock_handler+0x2b2/0x870
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
dlm_create_lock_handler+0x35b/0x870
? __pfx_dlm_create_lock_handler+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
? kvm_clock_get_cycles+0x31/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_dlm_create_lock_handler+0x10/0x10
o2net_rx_until_empty+0x1dae/0x32c0
? reacquire_held_locks+0xdd/0x200
? __pfx_o2net_rx_until_empty+0x10/0x10
? lock_acquire+0x190/0x300
? process_one_work+0x935/0x1b40
? process_one_work+0x834/0x1b40
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
? srso_alias_return_thunk+0x5/0xfbef5
process_one_work+0x9a8/0x1b40
? __pfx_process_one_work+0x10/0x10
? lock_acquire+0x190/0x300
? lock_is_held_type+0x8f/0x100
? srso_alias_return_thunk+0x5/0xfbef5
worker_thread+0x65c/0xe40
? srso_alias_return_thunk+0x5/0xfbef5
? __kthread_parkme+0x177/0x220
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_worker_thread+0x10/0x10
kthread+0x351/0x460
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_kthread+0x10/0x10
ret_from_fork+0x659/0x940
? __pfx_ret_from_fork+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __switch_to+0x74f/0xf70
? __pfx_kthread+0x10/0x10
ret_from_fork_asm+0x1a/0x30
</TASK>
Allocated by task 52:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_slab_alloc+0x89/0x90
kmem_cache_alloc_noprof+0x20b/0x5c0
dlm_new_lock+0x39/0x5f0
dlm_create_lock_handler+0x16e/0x870
o2net_rx_until_empty+0x1dae/0x32c0
process_one_work+0x9a8/0x1b40
worker_thread+0x65c/0xe40
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 603:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kmem_cache_free+0x242/0x580
dlm_lock_release+0x1df/0x2f0
dlm_lock_put+0x51/0x80
__dlm_hb_node_down+0x15be/0x2710
dlm_hb_node_down_cb+0x6c/0xa0
o2hb_run_event_list+0x34a/0x500
o2hb_do_disk_heartbeat+0x1a07/0x2950
o2hb_thread+0x1ed/0xdc0
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
The buggy address belongs to the object at ffff88810ead5900
which belongs to the cache o2dlm_lock of size 184
The buggy address is located 64 bytes inside of
freed 184-byte region [ffff88810ead5900, ffff88810ead59b8)[Page and shadow memory dumps omitted.]
--- fs/ocfs2/dlm/dlmlock.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
fs/ocfs2/dlm/dlmlock.c +6 -2
@@ -138,6 +138,8 @@ static enum dlm_status dlmlock_master(st res->lockname.len)) { kick_thread = 1; call_ast = 1; + /* Keep the lock alive through AST enqueue. */ + dlm_lock_get(lock); } else { mlog(0, "%s: returning DLM_NORMAL to " "node %u for reco lock\n", dlm->name,
@@ -166,10 +168,12 @@ static enum dlm_status dlmlock_master(stwake_up (&res->wq);/* either queue the ast or release it */ -if (call_ast) +if (call_ast) {dlm_queue_ast (dlm, lock); -else +dlm_lock_put (lock); + }else {dlm_lockres_release_ast (dlm, res); + }dlm_lockres_calc_usage (dlm, res);if (kick_thread)
Greg Kroah-Hartman
maintainerPATCH 641/3318 ocfs2/dlm: hold the lookup reference across convert AST enqueue
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit 125fe08ff6cfa064e1212f586f01993ee45c0330 upstream.
dlm_convert_lock_handler() drops the reference it took when it found the lock on res->granted at its leave label, one statement before it calls dlm_queue_ast(). dlm_free_dead_locks() takes res->spinlock and drops the list and base references, so a peer death landing in that gap leaves the handler's own put as the one that frees the lock, and __dlm_queue_ast() then reads lock->lockres from freed memory.
The handler is registered next to dlm_create_lock_handler(), so a convert message buffered on a dying peer's socket arrives on the same o2net receive work that o2net_disconnect_node() does not wait for. The two can interleave as follows, with the reference counts as they are before this fix:
Socket data-ready Node-down thread Receive worker ----------------- ---------------- --------------
o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered convert_lock dlm_convert_lock_handler()
find lock on res->granted dlm_lock_get() refs = 3 lock res->spinlock __dlmconvert_master()
call_ast = 1
unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put list ref refs = 2
put base ref refs = 1
unlock res->spinlock
dlm_lock_put() refs = 0
free lock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)
__dlmconvert_master() only moves the lock between lists, so the count entering the gap is base, list and lookup. Drop the lookup reference after the AST is queued instead of before it and the race ends with the one __dlm_queue_ast() took, which dlm_flush_asts() releases later with ast_pending cleared and ast_list unlinked. No extra get is needed, and the normal case ends with the same count as before.
dlmconvert_master() has the same shape but is only reached from dlmlock() for a lock this node owns, which dlm_free_dead_locks() never matches.
--- fs/ocfs2/dlm/dlmconvert.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
fs/ocfs2/dlm/dlmconvert.c +7 -3
@@ -534,15 +534,19 @@ int dlm_convert_lock_handler(struct o2ne } leave: -if (lock) -dlm_lock_put (lock); -/* either queue the ast or release it, if reserved */ if (call_ast)dlm_queue_ast (dlm, lock);else if (ast_reserved)dlm_lockres_release_ast (dlm, res); +/* +* Keep the lock alive through AST enqueue: a concurrent +* dlm_free_dead_locks() drops the list and base references. +*/ +if (lock) +dlm_lock_put (lock); +if (kick_thread)dlm_kick_thread (dlm, res);
Greg Kroah-Hartman
maintainerPATCH 642/3318 ocfs2: cancel quota sync work before freeing quota info
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 1dd1f005026d52642b994d63baa16b0b31f3b14f upstream.
OCFS2 quota info owns dqi_sync_work and must outlive both its timer and qsync_work_fn(). ocfs2_local_free_info() frees that owner without cancelling the work, relying on the quota suspend/disable wrappers.
Loading quotas on a read-only to read-write remount can successfully queue the work in ocfs2_global_read_info() and then fail while attaching a dquot to an existing inode in add_dquot_ref(). The quota core unwinds that failure directly through dquot_disable(), bypassing the OCFS2 wrapper:
Remount task (s_umount write) Timer/workqueue
ocfs2_global_read_info()
schedules dqi_sync_work
add_dquot_ref() returns an error
dquot_disable()
ocfs2_local_free_info()
frees oinfo
delayed-work timer expires qsync_work_fn() reads oinfo
The timer core can then write to the freed embedded timer, or qsync_work_fn() can read oinfo->dqi_gqinode before its s_umount trylock. The outer ocfs2_disable_quotas() cleanup skips the failed type because dquot_disable() has already cleared its loaded state.
Cancel dqi_sync_work synchronously at the start of ocfs2_local_free_info(), before dropping the global inode or freeing any owner state. The work is initialized whenever read_file_info() succeeds. dquot_disable() holds s_umount for write, so the callback skips its quota scan via down_read_trylock() and can finish without waiting for teardown. The synchronous cancel also handles its self-rearm.
KASAN report as below:
BUG: KASAN: slab-use-after-free in __run_timers+0x9e9/0xa10
Write of size 8 at addr ffff888111b0aad0 by task swapper/3/0
Call Trace:
<IRQ>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? __run_timers+0x9e9/0xa10
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? __run_timers+0x9e9/0xa10
kasan_report+0xe0/0x110
? __run_timers+0x9e9/0xa10
__run_timers+0x9e9/0xa10
? __pfx___run_timers+0x10/0x10
? __lock_acquire+0x5a3/0x2140
? __pfx_do_raw_spin_lock+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
timer_expire_remote+0xfa/0x160
? __pfx_timer_expire_remote+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
tmigr_handle_remote_up+0x4ba/0x9d0
? __pfx_tmigr_handle_remote_up+0x10/0x10
? tmigr_handle_remote+0x21a/0x340
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
? __pfx_tmigr_handle_remote_up+0x10/0x10
__walk_groups_from+0x5a/0x160
tmigr_handle_remote+0x24f/0x340
? __pfx_tmigr_handle_remote+0x10/0x10
? lock_acquire+0x190/0x300
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
run_timer_softirq+0x222/0x270
? __pfx_run_timer_softirq+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? lockdep_hardirqs_on_prepare+0xb8/0x1a0
? srso_alias_return_thunk+0x5/0xfbef5
handle_softirqs+0x1fa/0x8d0
? __pfx_handle_softirqs+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? _raw_spin_unlock+0x23/0x40
? srso_alias_return_thunk+0x5/0xfbef5
? __hrtimer_rearm_deferred+0x1fb/0x5d0
__irq_exit_rcu+0x113/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
</IRQ>
<TASK>
asm_sysvec_apic_timer_interrupt+0x1a/0x20
? ct_kernel_exit.constprop.0+0xc5/0xf0
? do_idle+0x3ae/0x650
default_idle+0x9/0x10
default_idle_call+0x6c/0xb0
do_idle+0x3ae/0x650
? cpuhp_online_idle+0x9c/0xb0
? __pfx_do_idle+0x10/0x10
? __entry_text_end+0x1020f6/0x1020f9
? lockdep_hardirqs_on_prepare+0xeb/0x1a0
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
cpu_startup_entry+0x54/0x60
start_secondary+0x223/0x2d0
? __pfx_start_secondary+0x10/0x10
common_startup_64+0x13e/0x158
</TASK>
Allocated by task 523:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x28d/0x610
ocfs2_local_read_info+0x181/0x1580
dquot_load_quota_sb+0x69e/0x11c0
dquot_load_quota_inode+0x227/0x3e0
ocfs2_enable_quotas+0x27c/0x520
ocfs2_reconfigure+0x964/0xd00
reconfigure_super+0x3ca/0xa70
path_mount+0x141e/0x1e80
__x64_sys_mount+0x24b/0x2d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 523:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x308/0x580
ocfs2_local_free_info+0x47b/0x800
dquot_disable+0x5d9/0x17a0
dquot_load_quota_sb+0xd3c/0x11c0
dquot_load_quota_inode+0x227/0x3e0
ocfs2_enable_quotas+0x27c/0x520
ocfs2_reconfigure+0x964/0xd00
reconfigure_super+0x3ca/0xa70
path_mount+0x141e/0x1e80
__x64_sys_mount+0x24b/0x2d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
The buggy address belongs to the object at ffff888111b0a800
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 720 bytes inside of
freed 1024-byte region [ffff888111b0a800, ffff888111b0ac00)Host details, register and page dumps omitted.
--- fs/ocfs2/quota_local.c | 3 +++ 1 file changed, 3 insertions(+)
fs/ocfs2/quota_local.c +3 -0
@@ -813,6 +813,9 @@ static int ocfs2_local_free_info(structint mark_clean =1 , len;int status =0 ; +/* Quota-core error paths can bypass ocfs2_disable_quotas(). */ +cancel_delayed_work_sync (&oinfo->dqi_sync_work); +iput (oinfo->dqi_gqinode);ocfs2_simple_drop_lockres (OCFS2_SB (sb), &oinfo->dqi_gqlock);ocfs2_lock_res_free (&oinfo->dqi_gqlock);
Greg Kroah-Hartman
maintainerPATCH 643/3318 ocfs2: fix chunk number of the first chunk in a local quota file
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiaming Zhang <[email protected]>
commit 4effccfd50baee4f325694964aeee997dca7bd96 upstream.
Mounting a crafted OCFS2 image can corrupt kernel memory. When the local quota file header of such an image claims zero chunks, the first quota entry allocated during the mount gets a chunk number taken from a kernel pointer, and releasing that entry clears a bit far outside the chunk bitmap.
The write will corrupt the data stored at that address, and the corruption may lead to a system crash or damage unrelated data. Mounting requires CAP_SYS_ADMIN, so it takes an untrusted image, such as removable media or a loop mount of a file from elsewhere.
Since the chunk number comes from a kernel pointer, the address of the bit that gets cleared differs from boot to boot, and the issue has been reported under several titles:
- BUG: unable to handle kernel paging request in ocfs2_local_release_dquot
- KASAN: use-after-free Write in ocfs2_local_release_dquot
- KASAN: slab-out-of-bounds Write in ocfs2_local_release_dquot
- KASAN: slab-use-after-free Write in ocfs2_local_release_dquot
- KFENCE: use-after-free write in ocfs2_local_release_dquot
Note that none of these is a use-after-free in the quota code: the chunk and its buffer head are alive. The bit that gets cleared lies far outside the bitmap. KASAN and KFENCE name each report based on the object occupying that address, which explains why the same issue is reported under so many different titles. In the report I sent, the address fell in a free page, which KASAN labels use-after-free.
There are known reproducers. Both a syzkaller and a C reproducer are available from the Google Drive link [1] in my report thread. The issue was found by our modified syzkaller, not a theoretical thing found by an LLM. I have not seen it outside fuzzing, so it is not affecting me in the real world.
The local quota file in OCFS2 is divided into chunks, and each chunk begins with a header block holding a bitmap of the quota entries that chunk has handed out. Chunks are numbered from zero, and that number is used to convert the file offset of an entry back into a bit position in the bitmap. ocfs2_local_quota_add_chunk() appends a new chunk to the in-memory list and numbers it one past the chunk that was last:
list_add_tail(&chunk->qc_chunk, &oinfo->dqi_chunk); chunk->qc_num = list_entry(chunk->qc_chunk.prev, struct ocfs2_quota_chunk, qc_chunk)->qc_num + 1;
The predecessor is looked up after the new chunk is added to the list, so if the list was empty, the prev pointer is the list head itself. The head is the dqi_chunk member of struct ocfs2_mem_dqinfo and is not a chunk, so reading qc_num through it lands 16 bytes past the start of the head, on the dqi_gqinode pointer that follows it. The first chunk of the file is then numbered with the lower half of a kernel pointer instead of 0.
The list is empty when the local quota file header claims the file has no chunks. ocfs2_local_read_info() takes dqi_chunks from that header without validating it, so an image with dqi_chunks == 0 takes this path when the first quota entry is allocated.
ocfs2_create_local_dquot() turns the bad number into a file offset with ol_dqblk_off(), which shifts a 32-bit block number left by the block size bits, so the top bits of such a large block number are lost. ocfs2_local_release_dquot() turns the offset back into a bit index with ol_dqblk_chunk_off(), using the full chunk number, so the lost bits push that index far outside the bitmap, and clearing it corrupts unrelated memory.
Compute the chunk number before putting the chunk on the list, and use 0 when the list is empty.
--- fs/ocfs2/quota_local.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
fs/ocfs2/quota_local.c +6 -3
@@ -1071,10 +1071,13 @@ static struct ocfs2_quota_chunk *ocfs2_l goto out; } +if (list_empty (&oinfo->dqi_chunk)) + chunk->qc_num =0 ; +else + chunk->qc_num =list_entry (oinfo->dqi_chunk.prev, + struct ocfs2_quota_chunk, + qc_chunk)->qc_num +1 ;list_add_tail (&chunk->qc_chunk, &oinfo->dqi_chunk); - chunk->qc_num =list_entry (chunk->qc_chunk.prev, - struct ocfs2_quota_chunk, - qc_chunk)->qc_num +1 ; chunk->qc_headerbh = bh; *offset =0 ;return chunk;
Greg Kroah-Hartman
maintainerPATCH 644/3318 ocfs2: pin refcount trees before dropping the lookup lock
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 8c714a074074af7ae59233c1fa6ef9d7aa710462 upstream.
A refcount tree returned to ocfs2_lock_refcount_tree() must stay alive until that caller releases its operation reference. However, ocfs2_get_refcount_tree() returns the cached pointer after dropping osb_lock, and the caller only takes its kref afterwards. The registry reference does not protect this gap from concurrent removal.
This can happen when another node frees a refcount root and reuses its block with a different generation while this mount retains the old cached tree. Two local operations on different inodes sharing the new root, such as data CoW and an external xattr update, can then look up the same stale tree. Their inode locks are independent, and both the REFCOUNT DLM lock and rf_sem are acquired after the first operation reference.
The following ordering is possible, with no other operation references:
Data CoW Xattr update
-------- ------------
Look up the old tree under
osb_lock, then drop osb_lock
Look up the same tree and take a kref Acquire the tree locks and read the
new on-disk generation
Erase the old tree under osb_lock Unlock and drop the operation kref Drop the registry kref, freeing tree
Take a kref through the
freed tree pointer
The final kref_get() accesses freed rf_getcnt storage, and subsequent accesses in ocfs2_lock_refcount_tree() also use the freed allocation.
Take the operation reference in ocfs2_get_refcount_tree() before releasing osb_lock, including when an insertion loses to another lookup. Removal must acquire the same lock, so it cannot drop the registry reference before the lookup has pinned the tree. Keep the existing unlock and error path puts. The two callers that already hold the refcount tree lock keep their borrowed lookup behavior and do not acquire an extra reference.
KASAN report as below:
BUG: KASAN: slab-use-after-free in ocfs2_lock_refcount_tree+0x94a/0x9b0
Read of size 4 at addr ffff888117212820 by task python3/497[Kernel and hardware identification omitted.]
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? ocfs2_lock_refcount_tree+0x94a/0x9b0
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? ocfs2_lock_refcount_tree+0x94a/0x9b0
kasan_report+0xe0/0x110
? ocfs2_lock_refcount_tree+0x94a/0x9b0
ocfs2_lock_refcount_tree+0x94a/0x9b0
? __pfx_ocfs2_lock_refcount_tree+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? ocfs2_refcount_cow+0x3b6/0xd90
? srso_alias_return_thunk+0x5/0xfbef5
? __kmalloc_cache_noprof+0x28d/0x610
? ocfs2_refcount_cow+0x3b6/0xd90
ocfs2_refcount_cow+0x410/0xd90
? __pfx_ocfs2_refcount_cow+0x10/0x10
? __pfx___might_resched+0x10/0x10
? down_write+0x11a/0x1f0
? __pfx_down_write+0x10/0x10
? ocfs2_inode_unlock+0x1a9/0x260
? __pfx_ocfs2_inode_unlock+0x10/0x10
? ocfs2_file_write_iter+0x1413/0x1d30
ocfs2_file_write_iter+0x157b/0x1d30
? __pfx_ocfs2_file_write_iter+0x10/0x10
? lock_acquire+0x190/0x300
? __x64_sys_pwrite64+0x1b7/0x220
? __pfx___might_resched+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? security_file_permission+0x26/0x80
? srso_alias_return_thunk+0x5/0xfbef5
? lock_is_held_type+0x8f/0x100
vfs_write+0x639/0x1010
? __pfx_ocfs2_file_write_iter+0x10/0x10
? lock_vma_under_rcu+0x154/0x4a0
? __pfx_vfs_write+0x10/0x10
? lock_release+0x121/0x290
? srso_alias_return_thunk+0x5/0xfbef5
__x64_sys_pwrite64+0x1b7/0x220
? __pfx___x64_sys_pwrite64+0x10/0x10
? irqentry_exit+0xbe/0x820
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on_prepare+0x11d/0x150
? srso_alias_return_thunk+0x5/0xfbef5
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f[Register dump omitted.]
</TASK>
Allocated by task 491:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x28d/0x610
ocfs2_allocate_refcount_tree+0x49/0x1a0
ocfs2_create_refcount_tree+0x5d7/0x1630
ocfs2_attach_refcount_tree+0x57d/0x1100
__ocfs2_reflink.isra.0+0x1c4/0x1940
ocfs2_reflink+0x501/0x9b0
ocfs2_reflink_ioctl+0x6b2/0x920
ocfs2_ioctl+0x538/0x640
__x64_sys_ioctl+0x163/0x1d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 498:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x308/0x580
ocfs2_lock_refcount_tree+0x672/0x9b0
ocfs2_xattr_set+0x72c/0x2530
ocfs2_xattr_user_set+0xaf/0xf0
__vfs_setxattr+0x143/0x1b0
__vfs_setxattr_noperm+0x112/0x5b0
__vfs_setxattr_locked+0xfe/0x2b0
vfs_setxattr+0x13c/0x370
do_setxattr+0x128/0x170
filename_setxattr+0x147/0x190
path_setxattrat+0x1ac/0x260
__x64_sys_setxattr+0xcb/0x140
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
The buggy address belongs to the object at ffff888117212800
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 32 bytes inside of
freed 1024-byte region [ffff888117212800, ffff888117212c00)[Page and memory dumps omitted.]
--- fs/ocfs2/refcounttree.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-)
fs/ocfs2/refcounttree.c +9 -6
@@ -348,8 +348,10 @@ ocfs2_allocate_refcount_tree(struct ocfsreturn new; } +/* Callers without the refcount tree lock must request a reference. */ static int ocfs2_get_refcount_tree (struct ocfs2_super *osb,u64 rf_blkno, -struct ocfs2_refcount_tree **ret_tree) +struct ocfs2_refcount_tree **ret_tree, +bool get_ref) {int ret =0 ;struct ocfs2_refcount_tree *tree, *new =NULL ;
@@ -406,6 +408,8 @@ static int ocfs2_get_refcount_tree(struc new =NULL ; out: +if (get_ref) +ocfs2_refcount_tree_get (tree); *ret_tree = tree; osb->osb_ref_tree_lru = tree;
@@ -479,14 +483,12 @@ int ocfs2_lock_refcount_tree(struct ocfsstruct ocfs2_refcount_block *rb; again: - ret =ocfs2_get_refcount_tree (osb, ref_blkno, &tree); + ret =ocfs2_get_refcount_tree (osb, ref_blkno, &tree, true);if (ret) {mlog_errno (ret);return ret; } -ocfs2_refcount_tree_get (tree); - ret =__ocfs2_lock_refcount_tree (osb, tree, rw);if (ret) {mlog_errno (ret);
@@ -2330,7 +2332,8 @@ int ocfs2_decrease_refcount(struct inode goto out; } - ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), ref_blkno, &tree); + ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), ref_blkno, + &tree, false);if (ret) {mlog_errno (ret); goto out;
@@ -2565,7 +2568,7 @@ int ocfs2_prepare_refcount_change_for_deBUG_ON (!ocfs2_is_refcount_inode (inode)); ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), - refcount_loc, &tree); + refcount_loc, &tree, false);if (ret) {mlog_errno (ret); goto out;
Greg Kroah-Hartman
maintainerPATCH 645/3318 ocfs2: snapshot dentry names in file and setattr traces
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 8cd3ff30659775a6831c66687a69d2b83d163591 upstream.
Patch series "ocfs2: stabilize dentry names in file and setattr traces", v4.
Snapshot names at all six users of ocfs2__file_ops and at the separate setattr event. Patch 1 handles the five ordinary file-operation callers and setattr. Patch 2 handles release separately to preserve its locked open-count sample and take the snapshot outside that critical section.
The release explanation distinguishes its existing RCU lifetime coverage from name/length consistency. It does not claim that the ordinary callers' external-name UAF interleaving crosses the held inode spinlock. The release source change is unchanged from v3.
Patch 1 also removes the read callback's redundant NULL-inode check. The two patches apply independently and leave trace formats unchanged.
This patch (of 2):
The open, fsync, read, write and splice-read trace calls pass the live dentry name and length to the shared ocfs2__file_ops event class. ocfs2_setattr() passes the same unprotected arguments to its own event. Both events size and copy a __string field separately. A reference to the dentry does not pin the external storage backing an individual name.
With an event enabled, a caller can be preempted after loading the name pointer. A long-to-short rename can then replace the name and reclaim its old external allocation before the trace callback sizes or copies it, provided no other snapshot retains that allocation.
The setattr inode lock does not exclude every rename: a same-directory rename of a source directory need not take that directory's inode lock. It can therefore change the dentry name while setattr records its event. Inline names and separately loaded lengths can also change during trace record sizing and copying.
Take a dentry name snapshot around each of these six trace calls and pass both the string and length from the snapshot. Check event enablement before taking a snapshot. Keep the event classes and formats unchanged.
Also remove the redundant NULL-inode check in the read callback. file_inode() returns the open file's inode, which is already used by the trace call above the check.
The historical report below is from the read path.
KASAN report as below:
BUG: KASAN: slab-use-after-free in strlen+0x85/0xa0
Read of size 1 at addr ffff88810a5b2b18 by task python3/496 [CPU and host details omitted.]
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? strlen+0x85/0xa0
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? strlen+0x85/0xa0
kasan_report+0xe0/0x110
? strlen+0x85/0xa0
strlen+0x85/0xa0
trace_event_raw_event_ocfs2__file_ops+0xf0/0x480
? __pfx_trace_event_raw_event_ocfs2__file_ops+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? pmbd_probe_hit_cookie+0xe7/0x1c0
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_pmbd_probe_hit_cookie+0x10/0x10
ocfs2_file_read_iter+0x6cd/0xb30
? __pfx_ocfs2_file_read_iter+0x10/0x10
? selinux_file_permission+0x11d/0x540
? srso_alias_return_thunk+0x5/0xfbef5
? security_file_permission+0x26/0x80
vfs_read+0x7d2/0xc20
? __pfx_vfs_read+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_do_sys_openat2+0x10/0x10
ksys_read+0x111/0x200
? __pfx_ksys_read+0x10/0x10
? irqentry_exit+0xbe/0x820
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on_prepare+0x11d/0x150
? srso_alias_return_thunk+0x5/0xfbef5
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
[User register dump omitted.]
</TASK>
Allocated by task 489:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_noprof+0x2de/0x780
__d_alloc+0x5fc/0x8c0
d_alloc_parallel+0x106/0x11d0
lookup_open+0x3ff/0x13e0
path_openat+0x95e/0x2020
do_file_open+0x21e/0x470
do_sys_openat2+0xf4/0x1b0
__x64_sys_openat+0x136/0x1e0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 0:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
__rcu_free_sheaf_prepare+0x65/0x2a0
rcu_free_sheaf_nobarn+0x1d/0x50
rcu_core+0x6be/0x1ed0
handle_softirqs+0x1fa/0x8d0
__irq_exit_rcu+0x113/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
asm_sysvec_apic_timer_interrupt+0x1a/0x20
The buggy address belongs to the object at ffff88810a5b2b00
which belongs to the cache kmalloc-rcl-192 of size 192
The buggy address is located 24 bytes inside of
freed 192-byte region [ffff88810a5b2b00, ffff88810a5b2bc0)
[Page and shadow-memory dumps omitted.]--- fs/ocfs2/file.c | 102 +++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 65 insertions(+), 37 deletions(-)
fs/ocfs2/file.c +65 -37
@@ -84,10 +84,17 @@ static int ocfs2_file_open(struct inodeint mode = file->f_flags;struct ocfs2_inode_info *oi =OCFS2_I (inode); -trace_ocfs2_file_open (inode, file, file->f_path.dentry, - (unsigned long long )oi->ip_blkno, - file->f_path.dentry->d_name.len, - file->f_path.dentry->d_name.name, mode); +if (trace_ocfs2_file_open_enabled ()) { +struct dentry *dentry = file->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_file_open (inode, file, dentry, + oi->ip_blkno, + name.name.len, name.name.name, + mode); +release_dentry_name_snapshot (&name); + }if (file->f_mode &FMODE_WRITE ) { status =dquot_initialize (inode);
@@ -173,11 +180,17 @@ static int ocfs2_sync_file(struct file *tid_t commit_tid;bool needs_barrier = false; -trace_ocfs2_sync_file (inode, file, file->f_path.dentry, - oi->ip_blkno, - file->f_path.dentry->d_name.len, - file->f_path.dentry->d_name.name, - (unsigned long long )datasync); +if (trace_ocfs2_sync_file_enabled ()) { +struct dentry *dentry = file->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_sync_file (inode, file, dentry, + oi->ip_blkno, + name.name.len, name.name.name, + (unsigned long long )datasync); +release_dentry_name_snapshot (&name); + }if (ocfs2_is_hard_readonly (osb) ||ocfs2_is_soft_readonly (osb))return -EROFS ;
@@ -1125,15 +1138,19 @@ int ocfs2_setattr(struct mnt_idmap *idmaint had_lock;struct ocfs2_lock_holder oh; -trace_ocfs2_setattr (inode, dentry, - (unsigned long long )OCFS2_I (inode)->ip_blkno, - dentry->d_name.len, dentry->d_name.name, - attr->ia_valid, - attr->ia_valid &ATTR_MODE ? attr->ia_mode :0 , - attr->ia_valid &ATTR_UID ? +if (trace_ocfs2_setattr_enabled ()) { +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_setattr (inode, dentry,OCFS2_I (inode)->ip_blkno, + name.name.len, name.name.name, attr->ia_valid, + attr->ia_valid &ATTR_MODE ? attr->ia_mode :0 , + attr->ia_valid &ATTR_UID ?from_kuid (&init_user_ns, attr->ia_uid) :0 , - attr->ia_valid &ATTR_GID ? + attr->ia_valid &ATTR_GID ?from_kgid (&init_user_ns, attr->ia_gid) :0 ); +release_dentry_name_snapshot (&name); + }/* ensuring we don't even attempt to truncate a symlink */ if (S_ISLNK (inode->i_mode))
@@ -2379,11 +2396,17 @@ static ssize_t ocfs2_file_write_iter(strint direct_io = iocb->ki_flags &IOCB_DIRECT ?1 :0 ;int nowait = iocb->ki_flags &IOCB_NOWAIT ?1 :0 ; -trace_ocfs2_file_write_iter (inode, file, file->f_path.dentry, - (unsigned long long )OCFS2_I (inode)->ip_blkno, - file->f_path.dentry->d_name.len, - file->f_path.dentry->d_name.name, - (unsigned int )from->nr_segs);/* GRRRRR */ +if (trace_ocfs2_file_write_iter_enabled ()) { +struct dentry *dentry = file->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_file_write_iter (inode, file, dentry, +OCFS2_I (inode)->ip_blkno, + name.name.len, name.name.name, + (unsigned int )from->nr_segs); +release_dentry_name_snapshot (&name); + }if (!direct_io && nowait)return -EOPNOTSUPP ;
@@ -2529,17 +2552,16 @@ static ssize_t ocfs2_file_read_iter(struint direct_io = iocb->ki_flags &IOCB_DIRECT ?1 :0 ;int nowait = iocb->ki_flags &IOCB_NOWAIT ?1 :0 ; -trace_ocfs2_file_read_iter (inode, filp, filp->f_path.dentry, - (unsigned long long )OCFS2_I (inode)->ip_blkno, - filp->f_path.dentry->d_name.len, - filp->f_path.dentry->d_name.name, - to->nr_segs);/* GRRRRR */ - - -if (!inode) { - ret = -EINVAL ; -mlog_errno (ret); - goto bail; +if (trace_ocfs2_file_read_iter_enabled ()) { +struct dentry *dentry = filp->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_file_read_iter (inode, filp, dentry, +OCFS2_I (inode)->ip_blkno, + name.name.len, name.name.name, + to->nr_segs); +release_dentry_name_snapshot (&name); }if (!direct_io && nowait)
@@ -2611,11 +2633,17 @@ static ssize_t ocfs2_file_splice_read(stssize_t ret =0 ;int lock_level =0 ; -trace_ocfs2_file_splice_read (inode, in, in->f_path.dentry, - (unsigned long long )OCFS2_I (inode)->ip_blkno, - in->f_path.dentry->d_name.len, - in->f_path.dentry->d_name.name, - flags); +if (trace_ocfs2_file_splice_read_enabled ()) { +struct dentry *dentry = in->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_file_splice_read (inode, in, dentry, +OCFS2_I (inode)->ip_blkno, + name.name.len, name.name.name, + flags); +release_dentry_name_snapshot (&name); + }/* * We're fine letting folks race truncates and extending writes with
Greg Kroah-Hartman
maintainerPATCH 646/3318 smb: client: fix OOB last_entry pointer from unbounded LastNameOffset
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Diego Oliva <[email protected]>
commit 570c783a96f054dd3ac409a92772e9afb705d21c upstream.
CIFSFindFirst() and CIFSFindNext() locate the last entry of a TRANS2_FIND_FIRST2 or TRANS2_FIND_NEXT2 response by adding the LastNameOffset of the response parameters to the start of the data area, and store the result in psrch_inf->last_entry. MS-CIFS 2.2.6.2.2 defines that offset as the offset of the entry's file name; the client follows the reading of NT and Samba servers, which point it at the entry. LastNameOffset is only checked against CIFSMaxBufSize, which says nothing about the response actually received: validate_t2() lets the data area start up to 1024 bytes into the buffer, and SendReceive() copies at most CIFSMaxBufSize + MAX_CIFS_HDR_SIZE bytes of a response, 16468 by default, into a cifs_request allocation of CIFSMaxBufSize + MAX_SMB2_HDR_SIZE bytes, 16588 by default. The pointer itself can therefore be placed anywhere from the end of the received data to 820 bytes past the end of the allocation.
The read through that pointer is far larger than its displacement. find_cifs_entry() hands last_entry to cifs_save_resume_key() after every FindNext and after the FindFirst of a search rewind, and cifs_fill_dirent() takes the length of the name from the entry itself: a __le32 FileNameLength for most levels, a __u8 for SMB_FIND_FILE_INFO_STANDARD, and for SMB_FIND_FILE_UNIX the result of a scan for the terminating NUL over up to PATH_MAX + 1 UTF-16 units. The name is recorded as the resume name of the search, and the next CIFSFindNext() rejects only a recorded length of PATH_MAX or more before copying the name into the ResumeFileName of its request and sending it with the resume key taken from the same entry: up to 4 KiB of memory from past the end of the allocation leaks to the server, and for SMB_FIND_FILE_UNIX the NUL scan runs about twice as far before the length is even known. The entry does not have to lie outside the response for that either: a maximal response ends about 120 bytes before the end of the allocation, so an entry in its last bytes with a name just under PATH_MAX has nearly all of that name copied from past the allocation.
It needs nothing unusual from the client: a FindNext response that reports no entries and does not end the search makes find_cifs_entry() send the next FindNext at once, carrying whatever was parsed at LastNameOffset, and a search rewind can do the same after its FindFirst. SMB1 is not negotiated by default: this takes a malicious or compromised server, a mount of it with an explicit vers=1.0, which CONFIG_CIFS_ALLOW_INSECURE_LEGACY (default y) permits, and a directory listing on that mount.
With KASAN enabled, a response that places the last entry past the buffer, with a large DataOffset and a LastNameOffset near the end of its range, gives:
==================================================================
BUG: KASAN: slab-out-of-bounds in cifs_save_resume_key.isra.0+0x7aa/0x7f0 Read of size 4 at addr ffff88807b55c33b by task ls/83 CPU: 1 UID: 0 PID: 83 Comm: ls Not tainted 7.3.0-rc4-00457-gf14572c203d5 #69 PREEMPT(lazy) Call Trace: <TASK> kasan_report+0xdf/0x1a0 cifs_save_resume_key.isra.0+0x7aa/0x7f0 cifs_readdir+0x1ed6/0x29c0 iterate_dir+0x1c0/0x570 __x64_sys_getdents64+0x133/0x270 do_syscall_64+0x109/0x5d0 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK> Allocated by task 83 on cpu 0 at 19.317556s: cifs_buf_get+0x36/0x90 smb_init+0x4f/0x110 CIFSFindNext+0xf7/0x14c0 cifs_readdir+0xf51/0x29c0 The buggy address belongs to the object at ffff88807b558000 which belongs to the cache cifs_request of size 16588 The buggy address is located 623 bytes to the right of allocated 16588-byte region [ffff88807b558000, ffff88807b55c0cc) ==================================================================
The four bytes read there are the FileNameLength of the entry, which cifs_fill_dirent() takes before anything checks where the entry lies.
Ignore the last entry when it does not start inside the received response or the response holds no entries; for a response without entries, last_entry pointed into or past its empty data area and cifs_save_resume_key() parsed whatever the buffer held there. The entry is bounded by the response that was received, which is what the buffer holds, rather than by the data area the response declares, which a later patch checks against the received length. Record the search handle before the last entry is examined, since a response without a usable last entry still carries the handle that the search is continued and closed with; leaving the assignment in the else branch would drop the handle of every response without entries.
This bounds where the last entry starts, not how far it is parsed: an entry that starts within the final bytes of the response still has its fixed part read past the end of the received data and its name, up to 4095 bytes, copied from past the end of the allocation, until the following patch bounds the parse itself. A response without a usable last entry continues the search with an empty resume name, since the preceding patch, "smb: client: fix use-after-free infoleak via the readdir resume name", drops the recorded name whenever a new response is installed. This patch applies on top of that one and relies on it: without it, every response rejected here would leave the previous name in place, pointing into a buffer that has been released.
A conforming server is not affected: the last entry lies inside the data area of the response.
--- fs/smb/client/cifssmb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
fs/smb/client/cifssmb.c +10 -4
@@ -4098,14 +4098,17 @@ findFirstRetry: psrch_inf->presume_name =NULL ; psrch_inf->resume_name_len =0 ; psrch_inf->resume_key =0 ; +if (pnetfid) + *pnetfid = parms->SearchHandle; lnoff =le16_to_cpu (parms->LastNameOffset); -if (CIFSMaxBufSize < lnoff) { +if (!psrch_inf->entries_in_buffer) { + psrch_inf->last_entry =NULL ; + }else if (psrch_inf->srch_entries_start + lnoff >= + psrch_inf->ntwrk_buf_start + bytes_returned) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); psrch_inf->last_entry =NULL ; }else { psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff; -if (pnetfid) - *pnetfid = parms->SearchHandle; }return 0 ; }
@@ -4223,7 +4226,10 @@ int CIFSFindNext(const unsigned int xid, psrch_inf->resume_name_len =0 ; psrch_inf->resume_key =0 ; lnoff =le16_to_cpu (parms->LastNameOffset); -if (CIFSMaxBufSize < lnoff) { +if (!psrch_inf->entries_in_buffer) { + psrch_inf->last_entry =NULL ; + }else if (psrch_inf->srch_entries_start + lnoff >= + psrch_inf->ntwrk_buf_start + bytes_returned) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); psrch_inf->last_entry =NULL ; }else {
Greg Kroah-Hartman
maintainerPATCH 647/3318 smb: client: stop processing a read response after a receive error
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
commit 51efca72345acdbedc4af76782d464bd15ba50ff upstream.
cifs_read_iter_from_socket() may call cifs_reconnect() before returning an error. The reconnect path aborts pending mids and invokes their callbacks. The callback can then release the cifs_io_subrequest containing rdata.
cifs_readv_receive() nevertheless continues after a negative return and may dereference rdata in cifs_readv_discard(). KASAN reports the resulting UAF:
BUG: KASAN: slab-use-after-free in cifs_readv_receive Read of size 4 by task cifsd cifs_readv_receive (fs/smb/client/transport.c:1284) cifs_demultiplex_thread (fs/smb/client/connect.c:1355) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) Freed by task 148: netfs_put_subrequest (fs/netfs/objects.c:267) netfs_read_collection (fs/netfs/read_collect.c:460) netfs_wait_for_in_progress (fs/netfs/misc.c:462)
Return the socket error immediately, as this path did before the iterator conversion. This also avoids adding a negative length to total_read.
--- fs/smb/client/transport.c | 2 ++ 1 file changed, 2 insertions(+)
fs/smb/client/transport.c +2 -0
@@ -1862,6 +1862,8 @@ cifs_readv_receive(struct TCP_Server_Inf#endif length =cifs_read_iter_from_socket (server, &rdata->iter, data_len); +if (length <0 ) +return length;if (length >0 ) rdata->got_bytes += length; server->total_read += length;
Greg Kroah-Hartman
maintainerPATCH 648/3318 ovl: do not copy up an xattr value that was never read
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 755b5c5c9277be251a51623d6065abab948c61bc upstream.
Copy-up stores uninitialized kernel memory in an xattr of the upper file, where the user can read it.
ovl_copy_xattr() may only pass bytes to ovl_do_setxattr() that ovl_do_getxattr() has read. When the read fails with -ERANGE the function asks for the size again, and if the new size fits the buffer it stores the buffer although nothing was read into it. The buffer comes from kvmalloc(), or it still holds the value of the previous xattr.
A FUSE lower layer that answers every sized GETXATTR with -ERANGE made copy-up store 4096 bytes that the server never sent, with a kernel pointer in them, as an xattr of the upper file.
Fix this by failing the copy-up with -EIO when the size that follows -ERANGE fits the buffer.
--- fs/overlayfs/copy_up.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
fs/overlayfs/copy_up.c +5 -1
@@ -132,8 +132,12 @@ int ovl_copy_xattr(struct super_block *s retry: size =ovl_do_getxattr (oldpath, name, value, value_size); -if (size == -ERANGE ) +if (size == -ERANGE ) { size =ovl_do_getxattr (oldpath, name,NULL ,0 ); +/* Nothing was read into value, so it must not be used */ +if (size >=0 && size <= value_size) + size = -EIO ; + }if (size <0 ) { error = size;
Greg Kroah-Hartman
maintainerPATCH 649/3318 ovl: fix a torn path in ovl_get_redirect()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 2001cd7ca5560198131e46c6ca3c3472b06145c2 upstream.
A hard link of a metacopy file that races with a rename of an ancestor stores a redirect to the wrong lower file.
Each component of an absolute redirect must be the name that a dentry has in the parent that the walk continues with. ovl_get_redirect() copies the name under d_lock and calls dget_parent() after the unlock, and the callers for a hard link hold no lock that stops a rename across directories. A rename between the two steps combines the old name with the new parent.
With delays in ovl_get_redirect(), an unprivileged user hard-linked a metacopy file while renaming its ancestor to another directory, the stored redirect named another lower path, and after a remount the file showed the data of a root-only file.
Fix this by taking the parent first and checking it again under d_lock.
--- fs/overlayfs/dir.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
fs/overlayfs/dir.c +13 -1
@@ -975,7 +975,19 @@ static char *ovl_get_redirect(struct denconst char *name;int thislen; +/* +* A rename can move d to another directory at any time. Hold +* d_lock to copy the name that d has in this very parent, or +* else the path mixes the old name with the new parent. +*/ + tmp =dget_parent (d);spin_lock (&d->d_lock); +if (unlikely (tmp != d->d_parent)) { +spin_unlock (&d->d_lock); +dput (tmp); +continue ; + } + name =ovl_dentry_get_redirect (d);if (name) { thislen =strlen (name);
@@ -988,13 +1000,13 @@ static char *ovl_get_redirect(struct denif (thislen + (name[0 ] !='/' ) > buflen) { ret =ERR_PTR (-EXDEV );spin_unlock (&d->d_lock); +dput (tmp); goto out_put; } buflen -= thislen;memcpy (&buf[buflen], name, thislen);spin_unlock (&d->d_lock); - tmp =dget_parent (d);dput (d); d = tmp;
Greg Kroah-Hartman
maintainerPATCH 650/3318 ovl: fortify ovl_copy_xattr() against underlying layer modifications
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit e6b9117076fb4c0ff4a670efa9c876d9a50d79ab upstream.
Adapt ovl_getxattr_value() to be used from ovl_copy_xattr(), by allowing to pass it a pre-allocated buffer, which can be resized and by handling the ENODATA/EOPNOTSUPP return codes in the caller.
This replaces the retry loop in ovl_copy_xattr() with a single retry after resizing the buffer. If the value changed again by then, the underlying layer was modified, so return -EIO instead of retrying.
As a side effect, ovl_copy_up_meta_inode_data() now returns -EIO instead of -ERANGE in this case of underlying xattr size changes.
--- fs/overlayfs/copy_up.c | 68 +++++++++++++++++++++++-------------------------- 1 file changed, 32 insertions(+), 36 deletions(-)
fs/overlayfs/copy_up.c +32 -36
@@ -73,6 +73,9 @@ static int ovl_copy_acl(struct ovl_fs *oreturn err; } +static ssize_t ovl_getxattr_value (const struct path *path,char *name, +char **value,ssize_t *value_size); +int ovl_copy_xattr (struct super_block *sb,const struct path *oldpath,struct dentry *new) {struct dentry *old = oldpath->dentry;
@@ -130,34 +133,12 @@ int ovl_copy_xattr(struct super_block *sbreak ; } -retry: - size =ovl_do_getxattr (oldpath, name, value, value_size); -if (size == -ERANGE ) { - size =ovl_do_getxattr (oldpath, name,NULL ,0 ); -/* Nothing was read into value, so it must not be used */ -if (size >=0 && size <= value_size) - size = -EIO ; - } - + size =ovl_getxattr_value (oldpath, name, &value, &value_size);if (size <0 ) { error = size;break ; } -if (size > value_size) { -void *new; - - new =kvmalloc (size,GFP_KERNEL ); -if (!new) { - error = -ENOMEM ; -break ; - } -kvfree (value); - value = new; - value_size = size; - goto retry; - } - error =ovl_do_setxattr (OVL_FS (sb), new, name, value, size,0 );if (error) {if (error != -EOPNOTSUPP ||ovl_must_copy_xattr (name))
@@ -972,26 +953,39 @@ static bool ovl_need_meta_copy_up(structreturn true; } -static ssize_t ovl_getxattr_value (const struct path *path,char *name,char **value) +static ssize_t ovl_getxattr_value (const struct path *path,char *name, +char **value,ssize_t *value_size) {ssize_t res;char *buf; - res =ovl_do_getxattr (path, name,NULL ,0 ); -if (res == -ENODATA || res == -EOPNOTSUPP ) - res =0 ; + res =ovl_do_getxattr (path, name, *value, *value_size); +if (res == -ERANGE ) { + res =ovl_do_getxattr (path, name,NULL ,0 ); +/* Xattr changed underneath us? */ +if (res >=0 && res <= *value_size) +return -EIO ; + } -if (res >0 ) { - buf =kzalloc (res,GFP_KERNEL ); +if (res > *value_size) { + buf =kvmalloc (res,GFP_KERNEL );if (!buf)return -ENOMEM ; res =ovl_do_getxattr (path, name, buf, res); -if (res <0 ) -kfree (buf); -else - *value = buf; +if (res <0 ) { +kvfree (buf); +/* Xattr changed underneath us? */ +if (res == -ERANGE ) +return -EIO ; +return res; + } + +kvfree (*value); + *value = buf; + *value_size = res; } +return res; }
@@ -1002,7 +996,7 @@ static int ovl_copy_up_meta_inode_data(sstruct path upperpath;int err;char *capability =NULL ; -ssize_t cap_size; +ssize_t cap_size =0 ;ovl_path_upper (c->dentry, &upperpath);if (WARN_ON (upperpath.dentry ==NULL ))
@@ -1010,7 +1004,9 @@ static int ovl_copy_up_meta_inode_data(sif (c->stat.size) { err = cap_size =ovl_getxattr_value (&upperpath,XATTR_NAME_CAPS , - &capability); + &capability, &cap_size); +if (cap_size == -ENODATA || cap_size == -EOPNOTSUPP ) + cap_size =0 ;if (cap_size <0 ) goto out; }
@@ -1039,7 +1035,7 @@ static int ovl_copy_up_meta_inode_data(sovl_clear_flag (OVL_VERIFIED_DIGEST ,d_inode (c->dentry));ovl_set_upperdata (d_inode (c->dentry)); out_free: -kfree (capability); +kvfree (capability); out:return err; }
Greg Kroah-Hartman
maintainerPATCH 651/3318 ovl: read the nlink xattr of every indexed non-dir
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit eb644ed5c6d9afdb1554c41cef1f39d150fbc554 upstream.
With nfs_export=on, data written through a file handle to a lower file, i.e. a file that exists only in a lower layer of the overlay, can be lost on the next mount. A lookup of the file by name then returns -EIO. Also, a file with one name reports st_nlink 2 once it has been copied to the upper layer. After such a file is removed, its file handle can still open it until the next mount.
Before a lower file is changed for the first time, overlayfs copies it to the writable upper layer. This is called copy up.
The index directory is $workdir/index, where $workdir is the directory given by the workdir= option. Each entry is named after the file handle of a lower inode, so that overlayfs can get from the handle to the copied up inode.
With nfs_export=on, copy up indexes every non-directory: it copies the file to an entry in the index directory and then hard links that entry into the upper directory. The index entry is an extra link to the upper inode, so overlayfs stores the link count that users should see in the overlay.nlink xattr.
A file can also be opened by handle, either by an NFS client or by a process with CAP_DAC_READ_SEARCH calling open_by_handle_at(). If the file is not in the dcache, its overlay dentry is disconnected, i.e. it has no parent yet. Copy up then creates the index entry but no hard link in the upper directory. The index entry has i_nlink 1 and holds the only copy of the data written to the file.
ovl_get_nlink() reads the stored count. Its caller passes a default, which the function returns if there is no stored count. If the lower inode has i_nlink 1, the function returns the default without reading the xattr. That was correct as long as only lower files with multiple links were indexed.
On the next mount, ovl_verify_index() looks for orphans, i.e. index entries of files whose last name was removed. For an index entry with i_nlink 1, it passes a default of 0 to ovl_get_nlink() and treats a result of 0 as an orphan. Here the lower inode also has i_nlink 1, so the result is the default. ovl_indexdir_cleanup() then replaces the entry with a whiteout, which in the index marks a file as deleted. The written data is lost.
A lookup by name then returns -EIO, because a whiteout as the index entry of a lower file that still exists is a bad index.
ovl_get_inode() gets the wrong count the same way. Its default is the i_nlink of the upper inode, which includes the index entry, so a copied up file with one name reports st_nlink 2.
When that name is removed, the count drops to 1 rather than 0. ovl_nlink_end() replaces the index entry with a whiteout only at a count of 0, so the entry stays, and the handle of the removed file still opens it.
Reproduced by writing through open_by_handle_at() to an uncached lower file with one link. After a remount the data was lost, and the name returned EIO.
Fix this by adding an argument to ovl_get_nlink() that says whether the caller found an index entry, and by skipping the xattr only if the caller found none.
Known gaps:
- An index entry that a kernel without this patch left behind for a removed file now stays, and the handle of that file keeps working. The entry has i_nlink 1 and a stored count of 1, just like the entry of a file that was only written by handle. Without this patch, the next mount treated it as an orphan.
--- fs/overlayfs/inode.c | 14 +++++++++++--- fs/overlayfs/namei.c | 2 +- fs/overlayfs/overlayfs.h | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-)
fs/overlayfs/inode.c +11 -3
@@ -1125,7 +1125,7 @@ int ovl_set_nlink_lower(struct dentry *d }unsigned int ovl_get_nlink (struct ovl_fs *ofs,struct dentry *lowerdentry, -struct dentry *upperdentry, +struct dentry *upperdentry,bool indexed,unsigned int fallback) {int nlink_diff;
@@ -1133,7 +1133,15 @@ unsigned int ovl_get_nlink(struct ovl_fschar buf[13 ];int err; -if (!lowerdentry || !upperdentry ||d_inode (lowerdentry)->i_nlink ==1 ) +if (!lowerdentry || !upperdentry) +return fallback; + +/* +* A lower inode with one link is not indexed on copy up, unless all +* files are indexed for NFS export. If the caller found an index entry, +* then the xattr holds the union nlink, whatever the lower nlink is. +*/ +if (!indexed &&d_inode (lowerdentry)->i_nlink ==1 )return fallback; err = ovl_getxattr_upper(ofs, upperdentry, OVL_XATTR_NLINK,
@@ -1390,7 +1398,7 @@ struct inode *ovl_get_inode(struct super/* Recalculate nlink for non-dir due to indexing */ if (!is_dir) nlink =ovl_get_nlink (ofs, lowerdentry, upperdentry, - nlink); + oip->index, nlink);set_nlink (inode, nlink); ino = key->i_ino; }else {
fs/overlayfs/namei.c +1 -1
@@ -662,7 +662,7 @@ int ovl_verify_index(struct ovl_fs *ofs,if (err) goto fail; -if (ovl_get_nlink (ofs, origin.dentry, index,0 ) ==0 ) +if (ovl_get_nlink (ofs, origin.dentry, index, true,0 ) ==0 ) goto orphan; }
fs/overlayfs/overlayfs.h +1 -1
@@ -688,7 +688,7 @@ static inline bool ovl_dir_is_real(strucint ovl_set_nlink_upper (struct dentry *dentry);int ovl_set_nlink_lower (struct dentry *dentry);unsigned int ovl_get_nlink (struct ovl_fs *ofs,struct dentry *lowerdentry, -struct dentry *upperdentry, +struct dentry *upperdentry,bool indexed,unsigned int fallback);int ovl_setattr (struct mnt_idmap *idmap,struct dentry *dentry,struct iattr *attr);
Greg Kroah-Hartman
maintainerPATCH 652/3318 ovl: set the revalidate flags after d_instantiate()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 75e89c0055c1d7f7eeb462995f11253ca5864f79 upstream.
stat() of a file on an overlayfs mount triggers a kernel warning and fails with ECHILD if another task is creating that file at the same time. This happens on an overlay with a FUSE upper layer, which is the layer where overlayfs creates new files. Write access to a directory on such an overlay is all a user needs to run the two tasks.
The revalidate flags are DCACHE_OP_REVALIDATE and DCACHE_OP_WEAK_REVALIDATE. They tell path walk to call ->d_revalidate() or ->d_weak_revalidate() on a dentry, so that the filesystem can check that the cached dentry is still valid. An overlay dentry only has one of these flags if a dentry in one of its layers has it. FUSE dentries have the first one.
When a flag is set on an overlay dentry, path walk calls ovl_dentry_revalidate_common(). That function only expects a dentry without an inode in RCU walk, while the dentry is being destroyed. For such a dentry outside of RCU walk, it hits a WARN_ON() and returns -ECHILD. So a negative overlay dentry must never have the flags set.
ovl_instantiate() breaks this rule. When a task creates a file, the overlay dentry for the new name is hashed but still negative. ovl_instantiate() then works in this order:
- It copies the flags from the new upper dentry to the overlay dentry.
- It calls ovl_get_inode(), which can sleep in a getxattr request to the FUSE server.
- Only then does it call d_instantiate().
A second task that looks up the name between the first step and the last finds a negative dentry with the flags set and revalidates it.
Reproduced with a FUSE server that delays its getxattr reply: stat() of a name that was being created hit the WARN_ON() and failed with ECHILD.
Fix this by setting the flags after d_instantiate().
--- fs/overlayfs/dir.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
fs/overlayfs/dir.c +7 -1
@@ -269,7 +269,6 @@ static int ovl_instantiate(struct dentryovl_dir_modified (dentry->d_parent, false);ovl_dentry_set_upper_alias (dentry); -ovl_dentry_init_reval (dentry, newdentry,NULL );if (!hardlink) {/*
@@ -296,6 +295,13 @@ static int ovl_instantiate(struct dentry }d_instantiate (dentry, inode); +/* +* Unless it is a tmpfile, the dentry is hashed and a path walk can find +* it at any time. Set the revalidate flags only now, because +* ovl_dentry_revalidate_common() does not expect them on a negative +* dentry. +*/ +ovl_dentry_init_reval (dentry,ovl_dentry_upper (dentry),NULL );if (inode != oip.newinode) {pr_warn_ratelimited ("newly created inode found in cache (%pd2)\n" , dentry);
Greg Kroah-Hartman
maintainerPATCH 653/3318 ovl: skip copy up of empty security.capability
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit 50912a1715b8a7c614b654011a0db750e372b43e upstream.
ovl_copy_xattr() gives up if it can't read an attribute that listxattr() has named. An empty security.capability, which anybody has been able to store on any file for a long time, is such a case: it is listed, and getxattr() has nothing to return for it. A file in a lower layer that carries one can't be copied up: it can't be written to, renamed or have its mode changed.
There is nothing to copy if there are no data. Go on with the next one.
[amir: treat -EINVAL as no capability too, and do the same in
ovl_copy_up_meta_inode_data()]
--- fs/overlayfs/copy_up.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +15 -2
@@ -76,6 +76,15 @@ static int ovl_copy_acl(struct ovl_fs *ostatic ssize_t ovl_getxattr_value (const struct path *path,char *name,char **value,ssize_t *value_size); +/* +* Any user can store an empty security.capability, which fails to read with +* -EINVAL. It grants no capability, so treat it as none, like no xattr. +*/ +static bool ovl_no_fscap (ssize_t err) +{ +return err == -ENODATA || err == -EOPNOTSUPP || err == -EINVAL ; +} +int ovl_copy_xattr (struct super_block *sb,const struct path *oldpath,struct dentry *new) {struct dentry *old = oldpath->dentry;
@@ -135,6 +144,10 @@ int ovl_copy_xattr(struct super_block *s size =ovl_getxattr_value (oldpath, name, &value, &value_size);if (size <0 ) { +if (!strcmp (name,XATTR_NAME_CAPS ) &&ovl_no_fscap (size)) { + error =0 ; +continue ; + } error = size;break ; }
@@ -1005,9 +1018,9 @@ static int ovl_copy_up_meta_inode_data(sif (c->stat.size) { err = cap_size =ovl_getxattr_value (&upperpath,XATTR_NAME_CAPS , &capability, &cap_size); -if (cap_size == -ENODATA || cap_size == -EOPNOTSUPP ) +if (ovl_no_fscap (cap_size)) cap_size =0 ; -if (cap_size <0 ) +else if (cap_size <0 ) goto out; }
Greg Kroah-Hartman
maintainerPATCH 654/3318 xfs: fix unnecessary dapos truncation in xchk_dir_walk
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit f60a2ef8d8a7ac6dedf4d0c3325cc3fc2fe0d948 upstream.
LOLLM points out that the all the implementations of xchk_dirent_fn can handle a signed @dapos parameter, so the truncation here breaks the information captured in scrub tracepoints if the directory is very large. I don't think it ever made sense to do the truncation for the VFS readdir code for programs that can handle 64-bit offsets, but commit 15440319767942 has been around for 17 years without complaints so I'll leave that alone.
Stumbled-over: 15440319767942 ("[XFS] truncate readdir offsets to signed 32 bit values")
--- fs/xfs/scrub/readdir.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/readdir.c +1 -1
@@ -239,7 +239,7 @@ xchk_dir_walk_leaf( dep = bp->b_addr + offset; length =xfs_dir2_data_entsize (mp, dep->namelen); - dapos =xfs_dir2_byte_to_dataptr (curoff) &0x7fffffff ; + dapos =xfs_dir2_byte_to_dataptr (curoff); ino =be64_to_cpu (dep->inumber); name.name = dep->name; name.len = dep->namelen;
Greg Kroah-Hartman
maintainerPATCH 655/3318 xfs: assign an owner to scrub_stats_fops
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit fe67a493c7a76cf75556152af24285a114f69d34 upstream.
LOLLM complains that file_operations structs for debugfs files are supposed to have an owner set so that the module can't get unloaded if someone's sitting on a debugfs file long after unmount/rmmod. Fix that.
--- fs/xfs/scrub/stats.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/scrub/stats.c +2 -0
@@ -286,6 +286,7 @@ out: }static const struct file_operations scrub_stats_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = xchk_scrub_stats_read, };
@@ -313,6 +314,7 @@ xchk_clear_scrub_stats_write( }static const struct file_operations clear_scrub_stats_fops = { + .owner =THIS_MODULE , .open = simple_open, .write = xchk_clear_scrub_stats_write, };
Greg Kroah-Hartman
maintainerPATCH 656/3318 xfs: check fork type against dabtree block magic number
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 43030b72a11a532e7e3c21ac84a8625425b4201b upstream.
LOLLM complains that we fail to flag dabtree blocks that should never be associated with the file fork -- data forks can't point to xattr leaves, and attr forks can't point to dirent blocks. Add the missing checks.
--- fs/xfs/scrub/dabtree.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
fs/xfs/scrub/dabtree.c +12 -0
@@ -393,6 +393,10 @@ xchk_da_btree_block( XFS_BLFT_ATTR_LEAF_BUF); blk->magic =XFS_ATTR_LEAF_MAGIC ; blk->hashval =xfs_attr_leaf_lasthash (blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_ATTR_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
@@ -402,6 +406,10 @@ xchk_da_btree_block( XFS_BLFT_DIR_LEAFN_BUF); blk->magic =XFS_DIR2_LEAFN_MAGIC ; blk->hashval =xfs_dir2_leaf_lasthash (ip, blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_DATA_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
@@ -411,6 +419,10 @@ xchk_da_btree_block( XFS_BLFT_DIR_LEAF1_BUF); blk->magic =XFS_DIR2_LEAF1_MAGIC ; blk->hashval =xfs_dir2_leaf_lasthash (ip, blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_DATA_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
Greg Kroah-Hartman
maintainerPATCH 657/3318 xfs: mark overfull dabtree node blocks as corrupt
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit f61c91a2e5994fa81141d6c06dadae1fed206018 upstream.
LOLLM observes that we need to range-check the dabtree node record count before using it to index an array. Fix that.
--- fs/xfs/scrub/dabtree.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/xfs/scrub/dabtree.c +4 -0
@@ -434,6 +434,10 @@ xchk_da_btree_block( node = blk->bp->b_addr;xfs_da3_node_hdr_from_disk (ip->i_mount, &nodehdr, node); btree = nodehdr.btree; +if (nodehdr.count > dargs->geo->node_ents) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + } *pmaxrecs = nodehdr.count; blk->hashval =be32_to_cpu (btree[*pmaxrecs -1 ].hashval);if (level ==0 ) {
Greg Kroah-Hartman
maintainerPATCH 658/3318 xfs: jump out of xchk_bmap_check_rmap if fatal signals
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 49d300a51442bd64b627645b7b0b1cd66e492905 upstream.
LOLLM observes that we never check for fatal signals inside the loop that checks file fork mappings against the rmapbt. This can lead to lengthy delays in responding to a ^C, so add some bailout checks.
--- fs/xfs/scrub/bmap.c | 7 +++++++ 1 file changed, 7 insertions(+)
fs/xfs/scrub/bmap.c +7 -0
@@ -542,6 +542,10 @@ xchk_bmap_check_rmap(struct xfs_ifork *ifp;struct xfs_scrub *sc = sbcri->sc;bool have_map; +int error =0 ; + +if (xchk_should_terminate (sc, &error)) +return error;/* Is this even the right fork? */ if (rec->rm_owner != sc->ip->i_ino)
@@ -573,6 +577,9 @@ xchk_bmap_check_rmap(*/ check_rec = *rec;while (have_map) { +if (xchk_should_terminate (sc, &error)) +return error; +if (irec.br_startoff != check_rec.rm_offset)xchk_fblock_set_corrupt (sc, sbcri->whichfork, check_rec.rm_offset);
Greg Kroah-Hartman
maintainerPATCH 659/3318 xfs: fix xchk_stats_estimate_bufsize to allow for the trailing null
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 6b8d60784b61a17bd591cb4c6e8aa9ed29c24f5c upstream.
LOLLM complains that xchk_stats_estimate_bufsize underestimates the buffer size by 1 byte because scnprintf wants to store a null byte after the newline in each line. Each call to scnprintf overwrites the null left by the previous call, but we still need the null byte for the last line in the file.
--- fs/xfs/scrub/stats.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
fs/xfs/scrub/stats.c +2 -1
@@ -158,7 +158,8 @@ xchk_stats_estimate_bufsize( ret += field_width +1 ; } -return ret; +/* null byte for scnprintf */ +return ret +1 ; }/* Clear all counters. */
Greg Kroah-Hartman
maintainerPATCH 660/3318 ksmbd: serialize directory emptiness checks with readdir
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yongjun Gwon <[email protected]>
[ Upstream commit 7220980b2423d06a0604516129bfa4cec8a697ae ]
SMB2 QUERY_DIRECTORY holds fp->readdir_lock while it calls iterate_dir() on fp->filp. An SMB2 SET_INFO request with FILE_DISPOSITION_INFORMATION can resolve the same FileId and call ksmbd_vfs_empty_dir() on the same filp without that lock.
iterate_dir()'s inode read lock permits concurrent readers and does not serialize per-file iterator state. ext4 stores its dx readdir cursor and fname RB tree in file->private_data. Concurrent reset or refill can therefore free a fname node while the other worker still traverses it or retains its RB-tree link, resulting in use-after-free accesses.
An authenticated SMB client with list and delete rights on a directory in a writable KSMBD share backed by ext4 can trigger this when the directory takes the dx readdir path. The client overlaps an SMB2 QUERY_DIRECTORY request with an SMB2 SET_INFO request carrying FILE_DISPOSITION_INFORMATION on one live FileId.
In one x86_64 SMP KASAN multi-shot guest using ksmbd-for-next at 171df27077fb, the unmodified kernel reported a cross-worker use-after-free before a panic. The first report's access and free stacks show the two request paths directly (trimmed):
BUG: KASAN: slab-use-after-free in ext4_htree_store_dirent+0x488/0x550 Read of size 8 by task kworker/2:0/29 Workqueue: ksmbd-io handle_ksmbd_work Call Trace: ext4_htree_store_dirent+0x488/0x550 htree_dirblock_to_tree+0x535/0x990 ext4_htree_fill_tree+0x319/0xba0 ext4_readdir+0x175a/0x2f40 iterate_dir+0x1b6/0x630 smb2_query_dir+0x1003/0x1cc0 Freed by task 279: free_rb_tree_fname+0x67/0xc0 ext4_readdir+0x13a9/0x2f40 iterate_dir+0x1b6/0x630 ksmbd_vfs_empty_dir+0xa2/0x100 smb2_set_info+0x2ffa/0x45d0
Take fp->readdir_lock across the entire emptiness check. This places both iterators over that handle's filp in the same lock domain while preserving the disposition status handling. The exact code change completed a warning-free x86_64 KASAN bzImage build. Tracing three request pairs showed that the two iterate_dir() calls no longer overlapped and the expected statuses were preserved. A further 1,600 reproducer iterations completed with expected statuses and no KASAN report, Oops, or panic.
The reproducer and complete guest configuration are available privately to maintainers on request.
--- fs/smb/server/smb2pdu.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-)
fs/smb/server/smb2pdu.c +8 -3
@@ -6542,6 +6542,7 @@ static int set_file_disposition_info(struct ksmbd_work *work, struct smb2_file_disposition_info *file_info) {struct inode *inode; +int err;if (!(fp->daccess &FILE_DELETE_LE )) {pr_err ("no right to delete : 0x%x\n" , fp->daccess);
@@ -6550,9 +6551,13 @@ static int set_file_disposition_info(struct ksmbd_work *work, inode =file_inode (fp->filp);if (file_info->DeletePending) { -if (S_ISDIR (inode->i_mode) && -ksmbd_vfs_empty_dir (fp) == -ENOTEMPTY ) -return -EBUSY ; +if (S_ISDIR (inode->i_mode)) { +mutex_lock (&fp->readdir_lock); + err =ksmbd_vfs_empty_dir (fp); +mutex_unlock (&fp->readdir_lock); +if (err == -ENOTEMPTY ) +return -EBUSY ; + }smb_break_all_levII_oplock (work, fp,0 );ksmbd_set_inode_pending_delete (fp); }else {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 661/3318 ksmbd: fix breaking_cnt leak on early return in oplock_break()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
For leases, oplock_break() increments breaking_cnt before calling oplock_break_pending(), and returns early when the pending check reports nothing to break: the level is already at or below the requested level and, for a lease, the state is not HANDLE|READ caching. Neither early return decrements the counter, and wait_lease_breaking(), the only place that force-clears it, sits below those returns, so breaking_cnt stays elevated for the life of the open.
A stuck breaking_cnt makes same_client_has_lease() skip lease upgrades forever, and every subsequent same-client CREATE on that lease is answered with SMB2_LEASE_FLAG_BREAK_IN_PROGRESS, so the client never resumes caching.
The ordering dates back to the original SMB3 server code, but the early return became routinely reachable for leases already broken to NONE when smb_break_all_levII_oplock() stopped filtering out non-level-II leases in 17699905a381, "ksmbd: fix lease break and ack state handling".
Move the increment below the pending check so the early returns cannot strand the counter. This is the minimal equivalent of the reorder that mainline made in b0148dc5625d, "ksmbd: serialize oplock close with pending break ownership".
--- fs/smb/server/oplock.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
fs/smb/server/oplock.c +6 -1
@@ -1012,10 +1012,15 @@ static int oplock_break(struct oplock_info *brk_opinfo, struct ksmbd_inode *ci,if (brk_opinfo->is_lease) {struct lease *lease = brk_opinfo->o_lease; -atomic_inc (&brk_opinfo->breaking_cnt); err =oplock_break_pending (brk_opinfo, req_op_level);if (err)return err <0 ? err :0 ; +/* +* Increment breaking_cnt only after the pending check +* above: its early returns would otherwise strand the +* counter, as wait_lease_breaking() is never reached. +*/ +atomic_inc (&brk_opinfo->breaking_cnt);if (brk_opinfo->open_trunc) {/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 662/3318 EDAC/mc: Really fix error path ordering in edac_mc_alloc()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jean Delvare <[email protected]>
The backport of 51520e03e70d ("EDAC/mc: Fix error path ordering in edac_mc_alloc()") to stable kernel branches is incomplete due to a different memory allocation scheme. In v6.19 and earlier, the device initialization must be moved further up so that all jumps to the error label are covered.
--- drivers/edac/edac_mc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/edac/edac_mc.c +3 -3
@@ -365,13 +365,13 @@ struct mem_ctl_info *edac_mc_alloc(unsigned int mc_num,if (!mci)return NULL ; + mci->dev.release = mci_release; +device_initialize (&mci->dev); + mci->layers =kcalloc (n_layers,sizeof (struct edac_mc_layer ),GFP_KERNEL );if (!mci->layers) goto error; - mci->dev.release = mci_release; -device_initialize (&mci->dev); - mci->pvt_info =kzalloc (sz_pvt,GFP_KERNEL );if (!mci->pvt_info) goto error;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 663/3318 smb: client: fix busy dentry warning on unmount after DIO
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Siddharth Chintamaneni <[email protected]>
commit 75f5c412fa867efa0bf9b646bffe0d912109e84a upstream.
In mainline, commit 75f5c412fa86 ("smb: client: fix busy dentry warning on unmount after DIO") fixes a busy-dentry warning during unmount by tracking in-flight netfs_io_request instances in cifs_init_request() and cifs_free_request(), waiting for the counter to reach zero in cifs_kill_sb() before kill_anon_super(), and then flushing serverclose_wq and fileinfo_put_wq. Because mainline routes all CIFS I/O (direct I/O, uncached I/O, buffered readahead, and buffered writeback) through netfs_io_request, that single counter covers every path that holds a cifsFileInfo reference across asynchronous I/O completion.
Kernel 6.6 predates the netfs I/O request conversion and instead splits I/O across three reference-counted structures that each hold a cifsFileInfo reference:
- struct cifs_aio_ctx, used by direct and uncached I/O (__cifs_readv() and __cifs_writev()).
- struct cifs_readdata, allocated for uncached reads (cifs_send_async_read()) and directly without a cifs_aio_ctx for buffered readahead (cifs_readahead()).
- struct cifs_writedata, allocated for uncached writes (cifs_write_from_iter(), cifs_writev_requeue()) and directly without a cifs_aio_ctx for buffered writeback (cifs_write_back_from_locked_folio()).
In both the DIO/uncached paths (where collect_uncached_read_data() and collect_uncached_write_data() signal completion via complete(&ctx->done) or ctx->iocb->ki_complete() before the worker drops its rdata/wdata and ctx references) and the buffered paths (where cifs_readahead_complete() unlocks folios and cifs_writev_complete() ends folio writeback before calling kref_put() on rdata/wdata to drop their cfile reference), a racing close() and umount() can reach shrink_dcache_for_umount() before the final cifsFileInfo_put() has been queued and flushed. This triggers:
BUG: Dentry ... still in use (1) [unmount of cifs cifs]
followed by a use-after-free when deferred cifsFileInfo_put_work runs after superblock teardown.
Fix this in 6.6 by:
1. Adding cifs_sb->outstanding_aio and incrementing it whenever ctx->cfile, rdata->cfile, or wdata->cfile is assigned.
2. Releasing wdata->cfile and rdata->cfile before dropping ctx->refcount in cifs_uncached_writedata_release() and cifs_readdata_release().
3. Decrementing cifs_sb->outstanding_aio in cifs_aio_ctx_release(), cifs_readdata_release(), and cifs_writedata_release() only after cifsFileInfo_put() has been called, and waiting for it to reach zero in cifs_kill_sb() before flushing serverclose_wq and fileinfo_put_wq.
--- fs/smb/client/cifs_fs_sb.h | 1 + fs/smb/client/cifsfs.c | 11 +++++++++++ fs/smb/client/connect.c | 1 + fs/smb/client/file.c | 33 ++++++++++++++++++++++++++++----- fs/smb/client/misc.c | 4 ++++ 5 files changed, 45 insertions(+), 5 deletions(-)
fs/smb/client/cifs_fs_sb.h +1 -0
@@ -54,6 +54,7 @@ struct cifs_sb_info {struct nls_table *local_nls;struct smb3_fs_context *ctx;atomic_t active; +atomic_t outstanding_aio;/* nr of AIO contexts not yet fully deinitialized */ unsigned int mnt_cifs_flags;struct delayed_work prune_tlinks;struct rcu_head rcu;
fs/smb/client/cifsfs.c +11 -0
@@ -301,6 +301,17 @@ static void cifs_kill_sb(struct super_block *sb)/* Wait for all opened files to release */ flush_workqueue (deferredclose_wq); +/* +* Wait for all in-flight AIO contexts to finish cleanup so +* that their cifsFileInfo final puts have been queued, then +* drain the workqueues so the dentry refs are dropped before +* kill_anon_super(). +*/ +wait_var_event (&cifs_sb->outstanding_aio, + !atomic_read (&cifs_sb->outstanding_aio)); +flush_workqueue (serverclose_wq); +flush_workqueue (fileinfo_put_wq); +/* finally release root dentry */ dput (cifs_sb->root); cifs_sb->root =NULL ;
fs/smb/client/connect.c +1 -0
@@ -3396,6 +3396,7 @@ int cifs_setup_cifs_sb(struct cifs_sb_info *cifs_sb)spin_lock_init (&cifs_sb->tlink_tree_lock); cifs_sb->tlink_tree =RB_ROOT ; +atomic_set (&cifs_sb->outstanding_aio,0 );cifs_dbg (FYI ,"file mode: %04ho dir mode: %04ho\n" , ctx->file_mode, ctx->dir_mode);
fs/smb/client/file.c +28 -5
@@ -2618,6 +2618,8 @@ cifs_writedata_release(struct kref *refcount) {struct cifs_writedata *wdata =container_of (refcount, struct cifs_writedata, refcount); +struct cifs_sb_info *cifs_sb =NULL ; +#ifdef CONFIG_CIFS_SMB_DIRECT if (wdata->mr) {smbd_deregister_mr (wdata->mr);
@@ -2625,10 +2627,15 @@ cifs_writedata_release(struct kref *refcount) }#endif -if (wdata->cfile) +if (wdata->cfile) { + cifs_sb =CIFS_SB (wdata->cfile->dentry->d_sb);cifsFileInfo_put (wdata->cfile); + }kfree (wdata); + +if (cifs_sb &&atomic_dec_and_test (&cifs_sb->outstanding_aio)) +wake_up_var (&cifs_sb->outstanding_aio); }/*
@@ -2690,6 +2697,7 @@ cifs_writev_requeue(struct cifs_writedata *wdata)if (!is_retryable_error (rc)) rc = -EBADF ; }else { +atomic_inc (&CIFS_SB (inode->i_sb)->outstanding_aio); wdata2->pid = wdata2->cfile->pid; rc = server->ops->async_writev (wdata2, cifs_writedata_release);
@@ -2998,6 +3006,7 @@ static ssize_t cifs_write_back_from_locked_folio(struct address_space *mapping, wdata->pid = cfile->pid; wdata->credits = credits_on_stack; wdata->cfile = cfile; +atomic_inc (&cifs_sb->outstanding_aio); wdata->server = server; cfile =NULL ;
@@ -3491,9 +3500,10 @@ cifs_uncached_writedata_release(struct kref *refcount) {struct cifs_writedata *wdata =container_of (refcount, struct cifs_writedata, refcount); +struct cifs_aio_ctx *ctx = wdata->ctx; -kref_put (&wdata->ctx->refcount, cifs_aio_ctx_release);cifs_writedata_release (refcount); +kref_put (&ctx->refcount, cifs_aio_ctx_release); }static void collect_uncached_write_data (struct cifs_aio_ctx *ctx);
@@ -3704,6 +3714,7 @@ cifs_write_from_iter(loff_t fpos, size_t len, struct iov_iter *from, wdata->sync_mode =WB_SYNC_ALL ; wdata->offset = (__u64 )fpos; wdata->cfile =cifsFileInfo_get (open_file); +atomic_inc (&cifs_sb->outstanding_aio); wdata->server = server; wdata->pid = pid; wdata->bytes = cur_len;
@@ -3852,6 +3863,7 @@ static ssize_t __cifs_writev(return -ENOMEM ; ctx->cfile =cifsFileInfo_get (cfile); +atomic_inc (&cifs_sb->outstanding_aio);if (!is_sync_kiocb (iocb)) ctx->iocb = iocb;
@@ -4067,19 +4079,27 @@ cifs_readdata_release(struct kref *refcount) {struct cifs_readdata *rdata =container_of (refcount, struct cifs_readdata, refcount); +struct cifs_aio_ctx *ctx = rdata->ctx; +struct cifs_sb_info *cifs_sb =NULL ; -if (rdata->ctx) -kref_put (&rdata->ctx->refcount, cifs_aio_ctx_release);#ifdef CONFIG_CIFS_SMB_DIRECT if (rdata->mr) {smbd_deregister_mr (rdata->mr); rdata->mr =NULL ; }#endif -if (rdata->cfile) +if (rdata->cfile) { + cifs_sb =CIFS_SB (rdata->cfile->dentry->d_sb);cifsFileInfo_put (rdata->cfile); + }kfree (rdata); + +if (ctx) +kref_put (&ctx->refcount, cifs_aio_ctx_release); + +if (cifs_sb &&atomic_dec_and_test (&cifs_sb->outstanding_aio)) +wake_up_var (&cifs_sb->outstanding_aio); }static void collect_uncached_read_data (struct cifs_aio_ctx *ctx);
@@ -4234,6 +4254,7 @@ cifs_send_async_read(loff_t fpos, size_t len, struct cifsFileInfo *open_file, rdata->server = server; rdata->cfile =cifsFileInfo_get (open_file); +atomic_inc (&cifs_sb->outstanding_aio); rdata->offset = fpos; rdata->bytes = cur_len; rdata->pid = pid;
@@ -4387,6 +4408,7 @@ static ssize_t __cifs_readv( ctx->direct_io = direct; ctx->len = len; ctx->cfile =cifsFileInfo_get (cfile); +atomic_inc (&cifs_sb->outstanding_aio); ctx->nr_pinned_pages =0 ;if (!is_sync_kiocb (iocb))
@@ -4881,6 +4903,7 @@ static void cifs_readahead(struct readahead_control *ractl) rdata->offset = ra_index *PAGE_SIZE ; rdata->bytes = nr_pages *PAGE_SIZE ; rdata->cfile =cifsFileInfo_get (open_file); +atomic_inc (&cifs_sb->outstanding_aio); rdata->server = server; rdata->mapping = ractl->mapping; rdata->pid = pid;
fs/smb/client/misc.c +4 -0
@@ -1185,6 +1185,7 @@ cifs_aio_ctx_release(struct kref *refcount) {struct cifs_aio_ctx *ctx =container_of (refcount, struct cifs_aio_ctx, refcount); +struct cifs_sb_info *cifs_sb =CIFS_SB (ctx->cfile->dentry->d_sb);cifsFileInfo_put (ctx->cfile);
@@ -1211,6 +1212,9 @@ cifs_aio_ctx_release(struct kref *refcount) }kfree (ctx); + +if (atomic_dec_and_test (&cifs_sb->outstanding_aio)) +wake_up_var (&cifs_sb->outstanding_aio); }/**
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 664/3318 ufs: fix ufs_read_cylinder() failure handling
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Al Viro <[email protected]>
commit 0bfd3e1078c537cd66a8addb1c01835de4234a4c upstream.
1) ufs_load_cylinder() should return NULL on ufs_read_cylinder() failures. ufs_error() is not enough. As it is, IO failure on attempt to read a part of cylinder group metadata is likely to end up with an oops.
2) we drop the wrong buffer heads when undoing sb_bread() on IO failure halfway through the read - we need to brelse() what we've got from sb_bread(), TYVM...
--- fs/ufs/cylinder.c | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-)
fs/ufs/cylinder.c +18 -13
@@ -26,7 +26,7 @@* Read cylinder group into cache. The memory space for ufs_cg_private_info * structure is already allocated during ufs_read_super. */ -static void ufs_read_cylinder (struct super_block * sb, +static bool ufs_read_cylinder (struct super_block *sb,unsigned cgno,unsigned bitmap_nr) {struct ufs_sb_info * sbi =UFS_SB (sb);
@@ -46,9 +46,11 @@ static void ufs_read_cylinder (struct super_block * sb,* We have already the first fragment of cylinder group block in buffer */ UCPI_UBH (ucpi)->bh[0 ] = sbi->s_ucg[cgno]; -for (i =1 ; i <UCPI_UBH (ucpi)->count; i++) -if (!(UCPI_UBH (ucpi)->bh[i] =sb_bread (sb,UCPI_UBH (ucpi)->fragment + i))) +for (i =1 ; i <UCPI_UBH (ucpi)->count; i++) { +UCPI_UBH (ucpi)->bh[i] =sb_bread (sb,UCPI_UBH (ucpi)->fragment + i); +if (!UCPI_UBH (ucpi)->bh[i]) goto failed; + } sbi->s_cgno[bitmap_nr] = cgno; ucpi->c_cgx =fs32_to_cpu (sb, ucg->cg_cgx);
@@ -77,13 +79,14 @@ static void ufs_read_cylinder (struct super_block * sb, goto failed; }UFSD ("EXIT\n" ); -return ; +return true; failed:for (j =1 ; j < i; j++) -brelse (sbi->s_ucg[j]); +brelse (UCPI_UBH (ucpi)->bh[j]); sbi->s_cgno[bitmap_nr] =UFS_CGNO_EMPTY ;ufs_error (sb,"ufs_read_cylinder" ,"can't read cylinder group block %u" , cgno); +return false; }/*
@@ -166,15 +169,14 @@ struct ufs_cg_private_info * ufs_load_cylinder (UFSD ("EXIT (FAILED)\n" );return NULL ; } -else { -UFSD ("EXIT\n" ); -return sbi->s_ucpi[cgno]; - } }else { -ufs_read_cylinder (sb, cgno, cgno); -UFSD ("EXIT\n" ); -return sbi->s_ucpi[cgno]; +if (unlikely (!ufs_read_cylinder (sb, cgno, cgno))) { +UFSD ("EXIT (FAILED)\n" ); +return NULL ; + } } +UFSD ("EXIT\n" ); +return sbi->s_ucpi[cgno]; }/* * Cylinder group number cg is in cache but it was not last used,
@@ -205,7 +207,10 @@ struct ufs_cg_private_info * ufs_load_cylinder ( sbi->s_ucpi[j] = sbi->s_ucpi[j-1 ]; } sbi->s_ucpi[0 ] = ucpi; -ufs_read_cylinder (sb, cgno,0 ); +if (unlikely (!ufs_read_cylinder (sb, cgno,0 ))) { +UFSD ("EXIT (FAILED)\n" ); +return NULL ; + } }UFSD ("EXIT\n" );return sbi->s_ucpi[0 ];
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 665/3318 media: usbtv: drop redundant device reference
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
[ Upstream commit dbc6798b80481a20f9aff671bc4d529eae63c9e8 ]
Driver core holds a reference to the USB interface and its parent USB device while the interface is bound to a driver and there is no need to take additional references unless the structures are needed after disconnect.
Drop the redundant device reference to reduce cargo culting, make it easier to spot drivers where an extra reference is needed, and reduce the risk of memory leaks when drivers fail to release it.
Stable-dep-of: cb705f75d03e ("media: usbtv: fix null-pointer dereference on disconnect")
--- drivers/media/usb/usbtv/usbtv-core.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/media/usb/usbtv/usbtv-core.c +1 -3
@@ -91,7 +91,7 @@ static int usbtv_probe(struct usb_interface *intf,if (usbtv ==NULL )return -ENOMEM ; usbtv->dev = dev; - usbtv->udev =usb_get_dev (interface_to_usbdev (intf)); + usbtv->udev =interface_to_usbdev (intf); usbtv->iso_size = size;
@@ -119,7 +119,6 @@ static int usbtv_probe(struct usb_interface *intf, usbtv_video_fail:usb_set_intfdata (intf,NULL ); -usb_put_dev (usbtv->udev);kfree (usbtv);return ret;
@@ -137,7 +136,6 @@ static void usbtv_disconnect(struct usb_interface *intf)usbtv_audio_free (usbtv);usbtv_video_free (usbtv); -usb_put_dev (usbtv->udev); usbtv->udev =NULL ;/* the usbtv structure will be deallocated when v4l2 will be
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 666/3318 media: usbtv: fix null-pointer dereference on disconnect
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aleksandr Nogikh <[email protected]>
[ Upstream commit cb705f75d03e946a4514488beb9e3bac9bcdb2e6 ]
A null-pointer dereference can occur in usb_make_path() when called from usbtv_querycap() (and other ioctl handlers) during device disconnection.
Oops: general protection fault, probably for non-canonical address 0xdffffc000000000a: 0000 [#1] SMP KASAN NOPTI KASAN: null-ptr-deref in range [0x0000000000000050-0x0000000000000057] RIP: 0010:usb_make_path include/linux/usb.h:985 [inline] RIP: 0010:usbtv_querycap+0x9c/0x100 drivers/media/usb/usbtv/usbtv-video.c:612 ... Call Trace: <TASK> v4l_querycap+0x236/0x470 drivers/media/v4l2-core/v4l2-ioctl.c:1106 __video_do_ioctl+0x8af/0xc70 drivers/media/v4l2-core/v4l2-ioctl.c:3133 video_usercopy+0x860/0x1430 drivers/media/v4l2-core/v4l2-ioctl.c:3475 v4l2_ioctl+0x18d/0x1e0 drivers/media/v4l2-core/v4l2-dev.c:366 vfs_ioctl fs/ioctl.c:51 [inline] __do_sys_ioctl fs/ioctl.c:597 [inline] __se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline] do_syscall_64+0x174/0x580 arch/x86/entry/syscall_64.c:94
This happens due to a race condition between the USB device disconnect routine (usbtv_disconnect()) and V4L2 ioctls. When the device is disconnected, usbtv_disconnect() sets usbtv->udev = NULL without holding the usbtv->v4l2_lock mutex. Concurrently, an ioctl handler like usbtv_querycap() can be executing under the v4l2_lock and attempt to use usbtv->udev, leading to a crash.
To fix this, move the usbtv->udev = NULL assignment into usbtv_video_free() and protect it with mutex_lock(&usbtv->v4l2_lock). This ensures that no non-queue ioctl handler can run concurrently with the pointer being nullified. If an ioctl is already running, the mutex will block the disconnect path until the ioctl finishes. If an ioctl is blocked waiting for the lock, it will acquire it after the disconnect routine releases it, but will then check video_is_registered() (which was cleared by vb2_video_unregister_device()) and safely return -ENODEV.
Acquiring v4l2_lock after vb2_video_unregister_device() avoids reintroducing a historical deadlock issue, and usbtv_audio_free() remains safe as it is called before usbtv_video_free().
--- drivers/media/usb/usbtv/usbtv-core.c | 2 -- drivers/media/usb/usbtv/usbtv-video.c | 4 ++++ 2 files changed, 4 insertions(+), 2 deletions(-)
drivers/media/usb/usbtv/usbtv-core.c +0 -2
@@ -136,8 +136,6 @@ static void usbtv_disconnect(struct usb_interface *intf)usbtv_audio_free (usbtv);usbtv_video_free (usbtv); - usbtv->udev =NULL ; -/* the usbtv structure will be deallocated when v4l2 will be done using it */ v4l2_device_put (&usbtv->v4l2_dev);
drivers/media/usb/usbtv/usbtv-video.c +4 -0
@@ -969,5 +969,9 @@ void usbtv_video_free(struct usbtv *usbtv)vb2_video_unregister_device (&usbtv->vdev);v4l2_device_disconnect (&usbtv->v4l2_dev); +mutex_lock (&usbtv->v4l2_lock); + usbtv->udev =NULL ; +mutex_unlock (&usbtv->v4l2_lock); +v4l2_device_put (&usbtv->v4l2_dev); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 667/3318 xfs: reject out-of-range attribute value lengths in xfs_attr_copy_value
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 0643549ffecaeb716c0b75590a9b76dfa5eb35b3 upstream.
xfs_attr_copy_value() takes the value length as a signed int and, for a remote xattr, is handed args->rmtvaluelen. That field is filled from the on-disk __be32 xfs_attr_leaf_name_remote.valuelen in xfs_attr3_leaf_getvalue(), so a crafted length such as 0x80000000 is stored into the signed rmtvaluelen as a negative number.
The "buffer too small" guard in xfs_attr_copy_value() is a signed comparison:
if (args->valuelen < valuelen) return -ERANGE;
A negative valuelen therefore compares as smaller than the caller's buffer size, skips the -ERANGE path, and is then used as a copy length, leading to an out-of-bounds copy of a full remote block into a small getxattr(2) buffer on a mounted crafted image.
Reject a value length that is negative or larger than the maximum xattr size before it is used, so a bogus on-disk length can no longer slip through the value copier.
--- fs/xfs/libxfs/xfs_attr_leaf.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +11 -0
@@ -517,6 +517,17 @@ xfs_attr_copy_value( int valuelen) {/* +* A value length that is negative or larger than the maximum xattr +* size is on-disk corruption. The remote value length is an on-disk +* __be32 stored into the signed args->rmtvaluelen, so a crafted value +* such as 0x80000000 becomes negative and would slip past the +* "args->valuelen < valuelen" check below and be used as a copy +* length. Reject it before that can happen. +*/ +if (valuelen <0 || valuelen >XFS_XATTR_SIZE_MAX ) +return -EFSCORRUPTED ; + +/* * No copy if all we have to do is get the length */ if (!args->valuelen) {
Greg Kroah-Hartman
maintainerPATCH 668/3318 xfs: reject remote xattr entries with an out-of-range value length
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 15ccd92a782a0253f4a17895f3d3f71e5c1d1973 upstream.
xfs_attr3_leaf_verify_entry() validates a remote attribute entry's name but never bounds its on-disk value length (xfs_attr_leaf_name_remote. valuelen, a __be32). A crafted leaf with valuelen = 0x80000000 passes the verifier and the CRC.
That length is later assigned into the signed int args->rmtvaluelen (xfs_attr3_leaf_getvalue), becoming negative, which slips past the signed -ERANGE check in xfs_attr_copy_value(); a getxattr() with a small buffer then memcpy()s a full remote block into the small kvalue buffer (xfs_attr_rmtval_copyout) -- a heap out-of-bounds write with attacker-controlled content, from an unprivileged getxattr(2) on a mounted crafted image.
Reject remote entries whose value length exceeds XFS_XATTR_SIZE_MAX in the leaf verifier, so the malicious block is rejected at read time.
--- fs/xfs/libxfs/xfs_attr_leaf.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +2 -0
@@ -295,6 +295,8 @@ xfs_attr3_leaf_verify_entry(if (!(ent->flags &XFS_ATTR_INCOMPLETE ) && rentry->valueblk ==0 )return __this_address; +if (be32_to_cpu (rentry->valuelen) >XFS_XATTR_SIZE_MAX ) +return __this_address; }if (name_end > buf_end)
Greg Kroah-Hartman
maintainerPATCH 669/3318 xfs: bound inode fork length against the fork size during log recovery
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 9232301894a06e664d8de2da97175cf98419bd16 upstream.
xlog_recover_inode_commit_pass2() copies an inode log item's data/attr fork region into the inode buffer using the on-log region length without bounding it against the fork capacity, e.g.:
len = item->ri_buf[2].iov_len; memcpy(XFS_DFORK_DPTR(dip), src, len);
The only guard is an ASSERT, which is a no-op on production kernels (CONFIG_XFS_DEBUG off), and xfs_dinode_verify() runs only after the copy. A crafted image with a dirty log can therefore drive a heap out-of-bounds write at mount time. The XFS_ILOG_DBROOT sibling already passes XFS_DFORK_DSIZE as a bound; the DDATA/DEXT and ADATA/AEXT memcpy paths did not.
Bound each logged fork region against the destination fork size before copying it, and reject the log item with -EFSCORRUPTED when it does not fit. Because the recovered inode is only verified after the fork data has been copied in, the checks are done up front, before any memcpy into the on-disk inode.
--- fs/xfs/xfs_inode_item_recover.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
fs/xfs/xfs_inode_item_recover.c +19 -1
@@ -467,6 +467,25 @@ xlog_recover_inode_commit_pass2(ASSERT (!(fields &XFS_ILOG_DFORK ) || (len ==xlog_calc_iovec_len (in_f->ilf_dsize))); +/* +* The recovered inode is verified only after the fork data has been +* copied into it, so bound each logged fork region against the size of +* its fork now, before the memcpy below can overrun the on-disk inode. +* The DBROOT/ABROOT cases already bound their copies against the fork +* size. +*/ +if ((fields & (XFS_ILOG_DDATA |XFS_ILOG_DEXT )) && + item->ri_buf[2 ].iov_len >XFS_DFORK_DSIZE (dip, mp)) { + error = -EFSCORRUPTED ; + goto out_release; + } +if ((fields & (XFS_ILOG_ADATA |XFS_ILOG_AEXT )) && + item->ri_buf[(fields &XFS_ILOG_DFORK ) ?3 :2 ].iov_len > +XFS_DFORK_ASIZE (dip, mp)) { + error = -EFSCORRUPTED ; + goto out_release; + } +switch (fields &XFS_ILOG_DFORK ) {case XFS_ILOG_DDATA :case XFS_ILOG_DEXT :
@@ -506,7 +525,6 @@ xlog_recover_inode_commit_pass2(case XFS_ILOG_ADATA :case XFS_ILOG_AEXT : dest =XFS_DFORK_APTR (dip); -ASSERT (len <=XFS_DFORK_ASIZE (dip, mp));memcpy (dest, src, len);break ;
Greg Kroah-Hartman
maintainerPATCH 670/3318 xfs: check for fragments when full-extent sharing matches
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 95e213c1ddb40dfb0a8178ed35c9f29992a320e1 upstream.
LOLLM noticed that xchk_refcountbt_process_rmap_fragments returns early if there are enough rmap records that overlap the space referenced by a refcountbt record to match the refcount in that refcountbt record. Unfortunately, it never checks the fragment list in this case, so it won't find the discrepancy between the rmap and refcount btrees.
--- fs/xfs/scrub/refcount.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/refcount.c +4 -1
@@ -162,8 +162,11 @@ xchk_refcountbt_process_rmap_fragments(xfs_nlink_t target_nr; target_nr = refchk->refcount - refchk->seen; -if (target_nr ==0 ) +if (target_nr ==0 ) { +if (!list_empty (&refchk->fragments)) + refchk->seen =0 ;return ; + }/* * There are (refchk->rc.rc_refcount - refchk->nr refcount)
Greg Kroah-Hartman
maintainerPATCH 671/3318 xfs: dont rescan ifree and icount when frozen
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 18028768415e3c05ab7edb22d740e2f4dc52836a upstream.
LOLLM points out that it's pointless to rescan the AGs if we've already frozen the filesystem because there won't be any more perturbations. Fix this to mark the scan incomplete and exit.
--- fs/xfs/scrub/fscounters.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/xfs/scrub/fscounters.c +5 -0
@@ -380,6 +380,11 @@ retry:* to maintain ifree <= icount before giving up. */ if (fsc->ifree > fsc->icount) { +if (fsc->frozen) { +xchk_set_incomplete (sc); +return -EFSCORRUPTED ; + } +if (tries--) goto retry;return -EDEADLOCK ;
Greg Kroah-Hartman
maintainerPATCH 672/3318 xfs: only written file data blocks can be shared
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 634b63baf05062988456a0bd5df2696c14ea2949 upstream.
LOLLM noticed that xchk_refcountbt_rmap_check (and its rt equivalent) will count any rmap owner towards the shared count. However, the only blocks that can be shared between xfs files are written file data blocks; and the only blocks that can have single-refcount entries are COW staging extents. Fix the checking code.
--- fs/xfs/scrub/refcount.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
fs/xfs/scrub/refcount.c +12 -0
@@ -117,6 +117,18 @@ xchk_refcountbt_rmap_check(return 0 ; } +/* +* The refcount btree should only have records for written file data +* blocks or for COW staging blocks. +*/ +if ((XFS_RMAP_NON_INODE_OWNER (rec->rm_owner) && + rec->rm_owner !=XFS_RMAP_OWN_COW ) || + (rec->rm_flags & (XFS_RMAP_ATTR_FORK |XFS_RMAP_BMBT_BLOCK | +XFS_RMAP_UNWRITTEN ))) { +xchk_btree_xref_set_corrupt (refchk->sc, cur,0 ); +return 0 ; + } +if (rec->rm_startblock <= refchk->bno && rm_last >= rc_last) {/* * The rmap overlaps the refcount record, so we can confirm
Greg Kroah-Hartman
maintainerPATCH 673/3318 xfs: opportunistically skip btree block checks
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 4ce244b234c251963fca6dff9de6edf26a209d08 upstream.
LOLLM notices that both callers of xchk_btree_get_block will return early if *pblock is NULL after a successful return. However, xchk_btree_get_block itself can return 0 after flagging a corruption. There's no point in continuing after we've found a corruption, so null the pointer out.
--- fs/xfs/scrub/btree.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/xfs/scrub/btree.c +8 -0
@@ -612,6 +612,14 @@ xchk_btree_get_block( level, *pbp);if (failed_at) {xchk_btree_set_corrupt (bs->sc, bs->cur, level); +/* +* The btree block fails basic checks, so we know it's corrupt. +* There's no need to continue looking for corruptions, so we +* null out pblock. If *pbp is non-null then it's also +* attached to the transaction so we won't leak it despite the +* 0 return code. +*/ + *pblock =NULL ;return 0 ; }if (*pbp)
Greg Kroah-Hartman
maintainerPATCH 674/3318 xfs: propagate errors while checking null siblings
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit e5bde75a816b3549942f4b09a8bf09006b7ea9de upstream.
LOLLM observes that if xfs_da3_path_shift returns an error here, scrub doesn't handle it the way that it handles most runtime errors. Instead, it drops the error and keeps going, even though that's not how that's supposed to work. Fix that by calling xchk_da_process_error to set corruption flags and then jump out of the flow of execution.
--- fs/xfs/scrub/dabtree.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
fs/xfs/scrub/dabtree.c +3 -2
@@ -237,9 +237,10 @@ xchk_da_btree_block_check_sibling(if (sibling ==0 ) { error =xfs_da3_path_shift (ds->state, altpath, direction, false, &retval); -if (error ==0 && retval ==0 ) +if (!xchk_da_process_error (ds, level, &error)) + goto out; +if (retval ==0 )xchk_da_set_corrupt (ds, level); - error =0 ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 675/3318 xfs: range-check bc_levels array access in scrub tracepoints
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 73b7276b8a4b5eb272f3c3b36ea3042e786f4741 upstream.
LOLLM noticed xchk_btree()'s odd habit of passing cur->bc_nlevels to xchk_btree_ptr_ok when we're checking the pointer to the root block at the start of the btree scan. This enables us to skip checking the pointer for an inode btree's root (since it doesn't have one) but doesn't handle per-AG btrees quite correctly. There isn't a problem for __xfs_btree_check_ptr itself, but the corruption tracepoint naively walks off the end of bc_level[]. Fix that by adding a helper to do an implicit range check.
--- fs/xfs/scrub/trace.c | 13 +++++++++++++ fs/xfs/scrub/trace.h | 10 +++++----- 2 files changed, 18 insertions(+), 5 deletions(-)
fs/xfs/scrub/trace.c +13 -0
@@ -23,6 +23,9 @@ xchk_btree_cur_fsbno( struct xfs_btree_cur *cur, int level) { +if (level <0 ) +return NULLFSBLOCK ; +if (level < cur->bc_nlevels && cur->bc_levels[level].bp)return XFS_DADDR_TO_FSB (cur->bc_mp,xfs_buf_daddr (cur->bc_levels[level].bp));
@@ -34,6 +37,16 @@ xchk_btree_cur_fsbno(return NULLFSBLOCK ; } +static inline int +xchk_btree_cur_ptr ( +const struct xfs_btree_cur *cur, +int level) +{ +if (level >=0 && level < cur->bc_nlevels) +return cur->bc_levels[level].ptr; +return -1 ; +} +/* * We include this last to have the helpers above available for the trace * event implementations.
fs/xfs/scrub/trace.h +5 -5
@@ -390,7 +390,7 @@ TRACE_EVENT(xchk_btree_op_error, __entry->level = level; __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->error = error; __entry->ret_ip = ret_ip; ),
@@ -431,7 +431,7 @@ TRACE_EVENT(xchk_ifork_btree_op_error, __entry->type = sc->sm->sm_type; __entry->btnum = cur->bc_btnum; __entry->level = level; - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); __entry->error = error;
@@ -473,7 +473,7 @@ TRACE_EVENT(xchk_btree_error, __entry->level = level; __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->ret_ip = ret_ip; ), TP_printk("dev %d:%d type %s btree %s level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -513,7 +513,7 @@ TRACE_EVENT(xchk_ifork_btree_error, __entry->level = level; __entry->agno =XFS_FSB_TO_AGNO (cur->bc_mp, fsbno); __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); __entry->ret_ip = ret_ip; ), TP_printk("dev %d:%d ino 0x%llx fork %s type %s btree %s level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -553,7 +553,7 @@ DECLARE_EVENT_CLASS(xchk_sbtree_class, __entry->bno =XFS_FSB_TO_AGBNO (cur->bc_mp, fsbno); __entry->level = level; __entry->nlevels = cur->bc_nlevels; - __entry->ptr = cur->bc_levels[level].ptr; + __entry->ptr =xchk_btree_cur_ptr (cur, level); ), TP_printk("dev %d:%d type %s btree %s agno 0x%x agbno 0x%x level %d nlevels %d ptr %d", MAJOR(__entry->dev), MINOR(__entry->dev),
Greg Kroah-Hartman
maintainerPATCH 676/3318 smb: client: dont resurrect an exiting tcon from cached dir workers
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
commit d58e7b40908a8a57755811d5b37af1df3380278f upstream.
cfids_laundromat_worker() bumps tcon->tc_count for every expired open cfid and queues cached_dir_offload_close() without checking whether the tcon is already being torn down. Racing with the final cifs_put_tcon(), the tcon comes back from zero and gets torn down twice:
T1 T2
cifs_put_tcon()
--tc_count == 0, TID_EXITING
tconInfoFree()
free_cached_dirs()
cancel_delayed_work_sync() cfids_laundromat_worker()
++tc_count == 1
queue_work(serverclose_wq)
kfree(tcon->origin_fullpath)
kfree(tcon)
cached_dir_offload_close()
close_cached_dir() [UAF]
cifs_put_tcon()
tconInfoFree() [double free]cached_dir_lease_break() also bumps tc_count without tc_lock, racing with the laundromat's locked update.
Take the tcon reference through a helper that refuses once the tcon is TID_EXITING or its refcount has dropped to zero. Queued put_work and close_work then always hold a tcon reference, so tconInfoFree() can't run before they finish and free_cached_dirs() doesn't need to flush any workqueue. If the laundromat can't get a reference, put the cfid back on the dying list for free_cached_dirs() to free; its handle goes away with the tree connection.
The lease break path finds the tcon on ses->tcon_list under cifs_tcp_ses_lock, so it can't see TID_EXITING, but it now takes tc_lock.
--- fs/smb/client/cached_dir.c | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-)
fs/smb/client/cached_dir.c +21 -9
@@ -614,6 +614,17 @@ void invalidate_all_cached_dirs(struct cspin_unlock (&cfids->cfid_list_lock); } +static bool cached_dir_get_tcon (struct cifs_tcon *tcon, +enum smb3_tcon_ref_trace trace) +{ +guard (spinlock)(&tcon->tc_lock); +if (tcon->status ==TID_EXITING || tcon->tc_count <=0 ) +return false; + ++tcon->tc_count; +trace_smb3_tcon_ref (tcon->debug_id, tcon->tc_count, trace); +return true; +} +static void cached_dir_offload_close (struct work_struct *work) {
@@ -663,6 +674,9 @@ int cached_dir_lease_break(struct cifs_t !memcmp(lease_key, cfid->fid.lease_key, SMB2_LEASE_KEY_SIZE)) { +if (!cached_dir_get_tcon (tcon, + netfs_trace_tcon_ref_get_cached_lease_break)) +break ; cfid->has_lease = false; cfid->time =0 ;/*
@@ -673,9 +687,6 @@ int cached_dir_lease_break(struct cifs_t cfid->on_list = false; cfids->num_entries--; - ++tcon->tc_count; -trace_smb3_tcon_ref (tcon->debug_id, tcon->tc_count, - netfs_trace_tcon_ref_get_cached_lease_break);queue_work (cfid_put_wq, &cfid->put_work);spin_unlock (&cfids->cfid_list_lock);return true;
@@ -789,12 +800,13 @@ static void cfids_laundromat_worker(strudput (dentry);if (cfid->is_open) { -spin_lock (&cfid->tcon->tc_lock); - ++cfid->tcon->tc_count; -trace_smb3_tcon_ref (cfid->tcon->debug_id, cfid->tcon->tc_count, - netfs_trace_tcon_ref_get_cached_laundromat); -spin_unlock (&cfid->tcon->tc_lock); -queue_work (serverclose_wq, &cfid->close_work); +if (cached_dir_get_tcon (cfid->tcon, + netfs_trace_tcon_ref_get_cached_laundromat)) { +queue_work (serverclose_wq, &cfid->close_work); +continue ; + } + scoped_guard(spinlock, &cfids->cfid_list_lock) +list_add_tail (&cfid->entry, &cfids->dying); }else /* * Drop the ref-count from above, either the lease-ref (if there
Greg Kroah-Hartman
maintainerPATCH 677/3318 smb: client: fix buffer overflow in SMB2_tcon()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Luxiao Xu <[email protected]>
commit 73cc469b0ff7551f8537ea919709973e6dc4f514 upstream.
In SMB2_tcon(), unc_path is allocated with a fixed buffer size of MAX_SHARENAME_LENGTH * 2 bytes (672 bytes). However, the user-controlled UNC path (tree) length is passed to cifs_strtoUTF16(), which assumes the destination buffer is large enough and writes strlen(tree) + 1 UTF-16 code units.
Commit 62a1a439e0fd ("cifs: clean up handling of unc= option") removed the length check on UNC mount options, allowing mount paths to exceed MAX_SHARENAME_LENGTH while retaining the fixed-size buffer allocation in SMB2_tcon(). Consequently, an oversized UNC string causes cifs_strtoUTF16() to write past the end of the heap object, resulting in a slab-out-of-bounds write. Furthermore, if a tree exceeds MAX_TREE_SIZE characters, strscpy() truncates it in cifs_tcon::tree_name, causing subsequent reconnects or failovers to fail.
Fix this by first verifying that the length of tree does not exceed MAX_TREE_SIZE, returning -EINVAL if it does. Then, dynamically allocate unc_path based on the length of tree so that it safely accommodates all UTF-16 code units for paths within MAX_TREE_SIZE.
--- fs/smb/client/smb2pdu.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
fs/smb/client/smb2pdu.c +9 -3
@@ -2024,8 +2024,6 @@ static inline void cifs_stats_fail_inc(scifs_stats_inc (&tcon->stats.smb2_stats.smb2_com_failed[code]); } -#define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */) -/* These are similar values to what Windows uses */ static inline void init_copy_chunk_defaults (struct cifs_tcon *tcon) {
@@ -2056,7 +2054,15 @@ SMB2_tcon(const unsigned int xid, structif (!server || !tree)return -EIO ; - unc_path =kmalloc (MAX_SHARENAME_LENGTH *2 ,GFP_KERNEL ); + total_len =strlen (tree); +if (total_len >MAX_TREE_SIZE ) { +cifs_server_dbg (VFS |ONCE , +"%s: tree name exceeded %u characters\n" , + __func__,MAX_TREE_SIZE ); +return -EINVAL ; + } + + unc_path =kmalloc ((total_len +1 ) *sizeof (*unc_path),GFP_KERNEL );if (unc_path ==NULL )return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 678/3318 smb: client: fix fiemap wild read on empty truncated response
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Abdifatah Suruur <[email protected]>
commit f5baa17a0f316c235d61623ac8e8fb32c2b3c0cc upstream.
smb3_fiemap() treats -E2BIG from SMB2_ioctl() as a truncated range blob and loops for the next chunk. If the server reports STATUS_BUFFER_OVERFLOW with OutputCount == 0, SMB2_ioctl() returns -E2BIG with out_data == NULL and out_data_len == 0, and the existing length checks accept the empty result. The loop then evaluates
next = out_data[num - 1].file_offset + ...
with num == 0, reading 16 bytes before NULL.
Reject a truncated range blob that contains no range, so the resume offset is never computed from an empty response. Also require the last range in a truncated blob to advance the resume offset without overflowing, and to stay within the requested range; a malicious or broken server could otherwise make no progress or underflow len and loop forever. Free the previous response buffer before retrying.
Reproduced on 6.6.87.2 with a malicious SMB2 server that answers FSCTL_QUERY_ALLOCATED_RANGES with STATUS_BUFFER_OVERFLOW and OutputCount == 0; an FS_IOC_FIEMAP ioctl on the mount oopses in cifs_fiemap() with CR2 = fffffffffffffff8. The code path is unchanged on mainline.
--- fs/smb/client/smb2ops.c | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-)
fs/smb/client/smb2ops.c +27 -3
@@ -3988,6 +3988,15 @@ static int smb3_fiemap(struct cifs_tcon goto out; } +/* +* A truncated range blob must contain at least one range, otherwise +* there is no offset to resume from and out_data is NULL. +*/ +if (!last_blob && out_data_len ==0 ) { + rc = -EINVAL ; + goto out; + } + num = out_data_len /sizeof (struct file_allocated_range_buffer );for (i =0 ; i < num; i++) { flags =0 ;
@@ -4008,10 +4017,25 @@ static int smb3_fiemap(struct cifs_tcon }if (!last_blob) { - next =le64_to_cpu (out_data[num -1 ].file_offset) + -le64_to_cpu (out_data[num -1 ].length); - len = len - (next - start); +u64 last_start, last_len; + + last_start =le64_to_cpu (out_data[num -1 ].file_offset); + last_len =le64_to_cpu (out_data[num -1 ].length); + +if (check_add_overflow (last_start, last_len, &next) || + next <= start) { + rc = -EINVAL ; + goto out; + } +if (next - start >= len) { + rc =0 ; + goto out; + } + + len -= next - start; start = next; +kfree (out_data); + out_data =NULL ; goto again; }
Greg Kroah-Hartman
maintainerPATCH 679/3318 smb: client: fix slab-out-of-bounds write in id_mode_to_cifs_acl()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dominik Maier <[email protected]>
commit a377a3645c7d0246af0bc4ef24db94bb2670bdde upstream.
In id_mode_to_cifs_acl(), while the chown branch reserves sizeof(struct smb_ntsd) + 2 * sizeof(struct smb_sid) (plus sizeof(struct smb_acl) and the worst-case ACE space after commit 0ee150794c75 ("smb: client: fix heap overflow in DACL owner/group rewrite")), the chmod branch only adds 2 * sizeof(struct smb_ace) or 5 * sizeof(struct smb_ace) to secdesclen (or 1 * sizeof(struct smb_ace) on posix).
However, the chmod branch also invokes build_sec_desc() -> copy_sec_desc(), which unconditionally writes the Owner SID at pnntsd + sidsoffset and the Group SID at
pnntsd + sidsoffset + sizeof(struct smb_sid) (2 * 68 = 136 bytes total), and set_chmod_dacl() always writes a struct smb_acl header (8 bytes) even when the source descriptor has dacloffset == 0. When a security descriptor has compact or overlapping Owner/Group SIDs (or dacloffset == 0), calling chmod() under-allocates pnntsd and writes past the end of the slab buffer.
Reserve sizeof(struct smb_acl) + 2 * sizeof(struct smb_sid) (plus sizeof(struct smb_ntsd) on the posix path) in the chmod branch of id_mode_to_cifs_acl().
--- fs/smb/client/cifsacl.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
fs/smb/client/cifsacl.c +6 -3
@@ -1767,12 +1767,15 @@ id_mode_to_cifs_acl(struct inode *inode,/* Potentially, five new ACEs can be added to the ACL for U,G,O mapping */ if (pnmode && *pnmode !=NO_CHANGE_64 ) {/* chmod */ + nsecdesclen =sizeof (struct smb_acl ) + +2 *sizeof (struct smb_sid );if (posix) - nsecdesclen =1 *sizeof (struct smb_ace ); + nsecdesclen +=sizeof (struct smb_ntsd ) + +sizeof (struct smb_ace );else if (mode_from_sid) - nsecdesclen = secdesclen + (2 *sizeof (struct smb_ace )); + nsecdesclen += secdesclen +2 *sizeof (struct smb_ace );else /* cifsacl */ - nsecdesclen = secdesclen + (5 *sizeof (struct smb_ace )); + nsecdesclen += secdesclen +5 *sizeof (struct smb_ace ); }else {/* chown */ /* When ownership changes, changes new owner sid length could be different */ nsecdesclen =sizeof (struct smb_ntsd ) + (sizeof (struct smb_sid ) *2 );
Greg Kroah-Hartman
maintainerPATCH 680/3318 pNFS: Fix CB_NOTIFY_DEVICEID CHANGE to consume ndc_immediate
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit a0cb76dc3b2919af8257fc08b4f9a79a35442483 upstream.
decode_devicenotify_args() gated the trailing ndc_immediate on cbd_layout_type rather than cbd_notify_type, so the flag was never consumed and a multi-item cnda_changes<> misaligned after the first entry.
--- fs/nfs/callback_xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfs/callback_xdr.c +1 -1
@@ -313,7 +313,7 @@ __be32 decode_devicenotify_args(struct smemcpy (dev->cbd_dev_id.data, p,NFS4_DEVICEID4_SIZE ); p +=XDR_QUADLEN (NFS4_DEVICEID4_SIZE ); -if (dev->cbd_layout_type ==NOTIFY_DEVICEID4_CHANGE ) { +if (dev->cbd_notify_type ==NOTIFY_DEVICEID4_CHANGE ) { p =xdr_inline_decode (xdr,sizeof (uint32_t ));if (unlikely (p ==NULL )) { status =htonl (NFS4ERR_BADXDR );
Greg Kroah-Hartman
maintainerPATCH 681/3318 pnfs/blocklayout: Complete a device upcall only on its own reply
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit acfbea6c5e27c68d6b6d12849eb2b7f8466ccf06 upstream.
bl_pipe_downcall() wakes bl_resolve_deviceid() on any write of the right size, without checking that blkmapd has read the upcall being replied to. A write that arrives first returns the waiter while its struct rpc_pipe_msg is still queued on the pipe, which then holds a list_head into a dead stack frame. Reaching the pipe takes root, so the trigger is a broken or hostile blkmapd.
The wait has two further defects. bl_resolve_deviceid() sets TASK_UNINTERRUPTIBLE only after rpc_queue_upcall() has made the message visible, so a reply that lands in between wakes a running task and the schedule() that follows sleeps forever holding bl_mutex. And nn->bl_mount_reply is never reset, so when the pipe purges an unread upcall the waiter takes the previous reply as its own.
Move the message into struct nfs_net, where bl_mutex already limits the pipe to one upcall per net namespace. Accept a reply only while blkmapd has read the whole message and no earlier reply has been taken, and reject any other write with -EINVAL. Wait for that reply on a completion so it cannot slip past the sleep, and check msg->errno before trusting it.
--- fs/nfs/blocklayout/blocklayout.h | 5 --- fs/nfs/blocklayout/rpc_pipefs.c | 58 ++++++++++++++++++++++++--------------- fs/nfs/netns.h | 5 ++- 3 files changed, 41 insertions(+), 27 deletions(-)
fs/nfs/blocklayout/blocklayout.h +0 -5
@@ -155,11 +155,6 @@ BLK_LSEG2EXT(struct pnfs_layout_segmentreturn BLK_LO2EXT (lseg->pls_layout); } -struct bl_pipe_msg { -struct rpc_pipe_msg msg; -wait_queue_head_t *bl_wq; -}; -struct bl_msg_hdr {u8 type;u16 totallen;/* length of entire message, including hdr itself */
fs/nfs/blocklayout/rpc_pipefs.c +37 -21
104 lines not on this page · raw message
fs/nfs/netns.h +4 -1
@@ -10,6 +10,8 @@#include <net/net_namespace.h> #include <net/netns/generic.h> #include <linux/sunrpc/stats.h> +#include <linux/sunrpc/rpc_pipe_fs.h> +#include <linux/completion.h> struct bl_dev_msg {int32_t status;
@@ -21,8 +23,9 @@ struct nfs_netns_client;struct nfs_net {struct cache_detail *nfs_dns_resolve;struct rpc_pipe *bl_device_pipe; +struct rpc_pipe_msg bl_pipe_msg;struct bl_dev_msg bl_mount_reply; -wait_queue_head_t bl_wq; +struct completion bl_done;struct mutex bl_mutex;struct list_head nfs_client_list;struct list_head nfs_volume_list;
Greg Kroah-Hartman
maintainerPATCH 682/3318 pnfs/blocklayout: Complete a device upcall when the pipe is closed
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 2a25cc8e984610828a526086313b8a7aeefe507d upstream.
Once blkmapd has read a whole upcall, rpc_pipe_read() unlinks the message from every pipe list, so the purges in rpc_pipe_release() and rpc_close_pipes() no longer reach it. bl_upcall_ops supplies no .release_pipe callback, and bl_pipe_destroy_msg() returns without completing the upcall because a downcall is expected to follow. A daemon that exits between the read and the write therefore strands its waiter: bl_resolve_deviceid() sleeps in wait_for_completion() and never returns, and it holds nn->bl_mutex across that wait, so every later device resolution in the net namespace blocks behind it.
Add a .release_pipe that completes an upcall blkmapd has consumed and left unanswered. Completing an upcall retires it, so a message the framework has already purged is no longer in flight and is not completed a second time here.
--- fs/nfs/blocklayout/rpc_pipefs.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
fs/nfs/blocklayout/rpc_pipefs.c +21 -0
@@ -151,10 +151,31 @@ static void bl_pipe_destroy_msg(struct rcomplete (&nn->bl_done); } +/* +* An upcall blkmapd has consumed is off every pipe list, so the +* purges in rpc_pipe_release() and rpc_close_pipes() cannot reach it. +* No downcall can arrive once the pipe is closed; release its waiter +* here. +*/ +static void bl_release_pipe (struct inode *inode) +{ +struct nfs_net *nn =net_generic (inode->i_sb->s_fs_info, nfs_net_id); +struct rpc_pipe *pipe = nn->bl_device_pipe; + +spin_lock (&pipe->lock); +if (rpc_msg_is_inflight (&nn->bl_pipe_msg)) { + nn->bl_pipe_msg.copied =0 ; + nn->bl_pipe_msg.errno = -EPIPE ; +complete (&nn->bl_done); + } +spin_unlock (&pipe->lock); +} +static const struct rpc_pipe_ops bl_upcall_ops = { .upcall = rpc_pipe_generic_upcall, .downcall = bl_pipe_downcall, .destroy_msg = bl_pipe_destroy_msg, + .release_pipe = bl_release_pipe, }; static struct dentry *nfs4blocklayout_register_sb(struct super_block *sb,
Greg Kroah-Hartman
maintainerPATCH 683/3318 NFSv4.1/pnfs: suspend pNFS on NFS4ERR_TOOSMALL from LAYOUTGET
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit 28c950413605fb5b6cb3863c5e3274ea69701097 upstream.
If the layout for the requested range is larger than the size the client advertised in loga_maxcount, RFC 8881 Section 18.43.3 has the metadata server return NFS4ERR_TOOSMALL. The client caps loga_maxcount at a single page, so a flexfiles server that stripes a layout segment across several dozen data servers produces this error today.
The client has no handling for it: nfs4_stat_to_errno() maps the error to -ETOOSMALL during decode, which nothing in the layoutget path recognizes and nfs_error_is_fatal() does not consider fatal, so pnfs_update_layout() clears the layout fail bit and returns no segment. The I/O falls back to the MDS, but because no fail bit was set, every subsequent pageio attempt sends another LAYOUTGET that is doomed to the same NFS4ERR_TOOSMALL. Files whose layouts do not fit the reply buffer never use pNFS and pay an extra round trip on every pageio.
Map -ETOOSMALL to -EMSGSIZE in the layoutget exception handler and have pnfs_update_layout() treat it like NFS4ERR_LAYOUTUNAVAILABLE:
mark the layout mode as failed and fall back to I/O through the MDS.
--- fs/nfs/nfs4proc.c | 8 ++++++++ fs/nfs/pnfs.c | 2 ++ 2 files changed, 10 insertions(+)
fs/nfs/nfs4proc.c +8 -0
@@ -9706,6 +9706,14 @@ nfs4_layoutget_handle_exception(struct r status = -EOVERFLOW ; goto out;/* +* NFS4ERR_TOOSMALL means the layout for the requested range +* exceeds what the client advertised in loga_maxcount (see +* RFC8881 section 18.43.3). +*/ +case -ETOOSMALL : + status = -EMSGSIZE ; + goto out; +/* * NFS4ERR_LAYOUTTRYLATER is a conflict with another client * (or clients) writing to the same RAID stripe except when * the minlength argument is 0 (see RFC5661 section 18.43.3).
fs/nfs/pnfs.c +2 -0
@@ -2195,6 +2195,8 @@ lookup_again:break ;case -ENODATA :/* The server returned NFS4ERR_LAYOUTUNAVAILABLE */ +case -EMSGSIZE : +/* The layout exceeded loga_maxcount (NFS4ERR_TOOSMALL) */ pnfs_layout_set_fail_bit ( lo,pnfs_iomode_to_fail_bit (iomode)); lseg =NULL ;
Greg Kroah-Hartman
maintainerPATCH 684/3318 NFSv4/filelayout: Anchor page coalescing on pattern_offset
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit 7f2d221b01f356b6bb3bb6efef998f8b28339824 upstream.
filelayout_pg_test() bounds page coalescing to a single stripe unit using an offset relative to pls_range.offset, but the data server is selected by nfs4_fl_calc_j_index() using an offset relative to pattern_offset. When a segment's pattern_offset and range offset are not congruent modulo the stripe unit, the coalescing window is shifted off the DS-selection grid, so a coalesced I/O can straddle a stripe boundary and send the bytes past it to the wrong data server.
Anchor coalescing on pattern_offset to match nfs4_fl_calc_j_index(). Stripe-congruent segments, including the common whole-file pattern_offset 0 case, are unchanged.
--- fs/nfs/filelayout/filelayout.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
fs/nfs/filelayout/filelayout.c +4 -4
@@ -804,7 +804,7 @@ filelayout_pg_test(struct nfs_pageio_desunsigned int size;u64 p_stripe, r_stripe;u32 stripe_offset; -u64 segment_offset = pgio->pg_lseg->pls_range.offset; +u64 pattern_offset =FILELAYOUT_LSEG (pgio->pg_lseg)->pattern_offset;u32 stripe_unit =FILELAYOUT_LSEG (pgio->pg_lseg)->stripe_unit;/* calls nfs_generic_pg_test */
@@ -816,8 +816,8 @@ filelayout_pg_test(struct nfs_pageio_des/* see if req and prev are in the same stripe */ if (prev) { - p_stripe = (u64 )req_offset (prev) - segment_offset; - r_stripe = (u64 )req_offset (req) - segment_offset; + p_stripe = (u64 )req_offset (prev) - pattern_offset; + r_stripe = (u64 )req_offset (req) - pattern_offset;do_div (p_stripe, stripe_unit);do_div (r_stripe, stripe_unit);
@@ -826,7 +826,7 @@ filelayout_pg_test(struct nfs_pageio_des }/* calculate remaining bytes in the current stripe */ -div_u64_rem ((u64 )req_offset (req) - segment_offset, +div_u64_rem ((u64 )req_offset (req) - pattern_offset, stripe_unit, &stripe_offset);WARN_ON_ONCE (stripe_offset > stripe_unit);
Greg Kroah-Hartman
maintainerPATCH 685/3318 nfsd: clear XDR padding in GETXATTR replies
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit daba58690339ae86f1ebeb5197aa1369fae37e57 upstream.
nfsd4_vbuf_to_stream() uses a raw memcpy() for the first fragment of an attribute value. xdr_reserve_space() aligns the reservation but does not initialize the extra bytes. If the complete value fits in that fragment, the loop that clears padding for the final fragment is never entered.
A remote client reading an attribute whose length is not a multiple of four can therefore receive one to three stale bytes from the response page.
Encode the first fragment with xdr_encode_opaque_fixed(), matching the final-fragment path and ensuring that any XDR padding is zeroed.
--- fs/nfsd/nfs4xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfsd/nfs4xdr.c +1 -1
@@ -5048,7 +5048,7 @@ nfsd4_vbuf_to_stream(struct xdr_stream *if (!p)return nfserr_resource; -memcpy (p, buf, cplen); +xdr_encode_opaque_fixed (p, buf, cplen); buf += cplen; buflen -= cplen;
Greg Kroah-Hartman
maintainerPATCH 686/3318 NFSD: copy SETXATTR data from all XDR buffer segments
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit b01319947c69b0e3ea0fcd4b675eb892f9cad8a0 upstream.
nfsd4_vbuf_from_vector() manually copies the head followed by whole pages starting at offset zero. This assumes that all remaining data starts at the beginning of the page array and that no data is stored in the tail.
However, nfsd4_decode_setxattr() passes an xdr_buf returned by xdr_stream_subsegment(). Such a sub-buffer can have a nonzero page_base and can span its page and tail segments. Ignoring that layout can copy the wrong bytes into the value passed to vfs_setxattr().
Use read_bytes_from_xdr_buf(), which observes the complete xdr_buf layout.
--- fs/nfsd/nfs4xdr.c | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-)
fs/nfsd/nfs4xdr.c +3 -16
@@ -2117,10 +2117,8 @@ static __be32 nfsd4_vbuf_from_vector(struct nfsd4_compoundargs *argp, struct xdr_buf *xdr, char **bufp, u32 buflen) { - struct page **pages = xdr->pages; struct kvec *head = xdr->head; -char *tmp, *dp; -u32 len; +char *tmp;if (buflen <= head->iov_len) {/*
@@ -2135,19 +2133,8 @@ nfsd4_vbuf_from_vector(struct nfsd4_compif (tmp ==NULL )return nfserr_jukebox; - dp = tmp; -memcpy (dp, head->iov_base, head->iov_len); - buflen -= head->iov_len; - dp += head->iov_len; - -while (buflen >0 ) { - len =min_t (u32, buflen,PAGE_SIZE ); -memcpy (dp,page_address (*pages), len); - - buflen -= len; - dp += len; - pages++; - } +if (read_bytes_from_xdr_buf (xdr,0 , tmp, buflen)) +return nfserr_bad_xdr; *bufp = tmp;return 0 ;
Greg Kroah-Hartman
maintainerPATCH 687/3318 NFSD: Do not send CB_RECALL_ANY to NFSv4.0 clients
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 95ff0c079b9cab91f2327beb4197a3bc48c71f55 upstream.
deleg_reaper() sends CB_RECALL_ANY to every ACTIVE client holding delegations, but CB_RECALL_ANY is an NFSv4.1 operation. An NFSv4.0 client's callback service accepts only CB_GETATTR and CB_RECALL, so it replies OP_ILLEGAL. The decoder maps the unexpected opnum to -EIO, and nfsd4_cb_done() marks the client's callback channel down.
Nothing brings the channel back. nfsd4_run_cb_work() sets NFSD4_CB_UP only for a minor version above zero, and the only nfsd4_probe_callback() call site an NFSv4.0 client reaches is nfsd4_setclientid_confirm(). One visit from the reaper therefore leaves the channel marked down until the client re-establishes its clientid. RENEW then returns NFS4ERR_CB_PATH_DOWN for as long as the client holds delegations. nfsd4_cb_channel_good() stops returning true, so the client is granted no further delegations.
Skip clients at minor version zero.
--- fs/nfsd/nfs4state.c | 2 ++ 1 file changed, 2 insertions(+)
fs/nfsd/nfs4state.c +2 -0
@@ -6498,6 +6498,8 @@ deleg_reaper(struct nfsd_net *nn)list_for_each_safe (pos, next, &nn->client_lru) { clp = list_entry(pos, struct nfs4_client, cl_lru); +if (clp->cl_minorversion ==0 ) +continue ;if (clp->cl_state !=NFSD4_ACTIVE )continue ;if (list_empty (&clp->cl_delegations))
Greg Kroah-Hartman
maintainerPATCH 688/3318 NFSD: Dont complete a cld upcall the daemon has not read
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 7f4bf851aca4e18940ebf2bddf4ba6783802ee81 upstream.
cld_pipe_downcall() matches a reply to its upcall on the xid alone. A write that arrives before the daemon has read that upcall completes __cld_pipe_upcall() while its struct rpc_pipe_msg is still queued on the pipe. The waiter returns, its stack frame goes away, and the pipe keeps a list_head that points into it. The next rpc_queue_upcall() walks that pointer:
BUG: KASAN: vmalloc-out-of-bounds in __list_add_valid_or_report Read of size 8 at addr ffffc90007027950 by task syz.0.96/13066 __list_add_valid_or_report+0x6a/0x130 rpc_queue_upcall cld_pipe_upcall nfsd4_cld_grace_start nfsd4_cld_tracking_init
The pipe is mode 0600 in rpc_pipefs, so the trigger is a broken or hostile nfsdcld rather than an unprivileged task.
Record whether the daemon has consumed the whole message and complete only when it has. cld_pipe_destroy_msg() runs on every path by which the pipe releases a message, so it can maintain that flag under cn_lock. nfsdcld sends its -EINPROGRESS downcalls only after reading the upcall, so the new check does not break the GraceStart record stream.
--- fs/nfsd/nfs4recover.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-)
fs/nfsd/nfs4recover.c +20 -3
@@ -724,6 +724,8 @@ struct cld_upcall {struct list_head cu_list;struct cld_net *cu_net;struct completion cu_done; +/* daemon has read the whole upcall; protected by cn_lock */ +bool cu_inflight;union {struct cld_msg_hdr cu_hdr;struct cld_msg cu_msg;
@@ -883,6 +885,13 @@ cld_pipe_downcall(struct file *filp, conspin_lock (&cn->cn_lock);list_for_each_entry (tmp, &cn->cn_list, cu_list) {if (get_unaligned (&tmp->cu_u.cu_hdr.cm_xid) == xid) { +/* +* Completing now would return the waiter +* while its message is still queued on the +* pipe. +*/ +if (!tmp->cu_inflight) +break ; cup = tmp;if (status != -EINPROGRESS )list_del_init (&cup->cu_list);
@@ -891,9 +900,9 @@ cld_pipe_downcall(struct file *filp, con }spin_unlock (&cn->cn_lock); -/* couldn't find upcall? */ +/* no upcall to complete? */ if (!cup) { -dprintk ("%s: couldn't find upcall -- xid=%u\n" , __func__, xid); +dprintk ("%s: no completable upcall -- xid=%u\n" , __func__, xid);return -EINVAL ; }
@@ -913,8 +922,16 @@ cld_pipe_destroy_msg(struct rpc_pipe_msgstruct cld_msg *cmsg = msg->data; struct cld_upcall *cup = container_of(cmsg, struct cld_upcall, cu_u.cu_msg); +struct cld_net *cn = cup->cu_net; + +/* +* errno >= 0 means the daemon read the whole message and a +* downcall will complete the upcall. +*/ +spin_lock (&cn->cn_lock); + cup->cu_inflight = msg->errno >=0 ; +spin_unlock (&cn->cn_lock); -/* errno >= 0 means we got a downcall */ if (msg->errno >=0 )return ;
Greg Kroah-Hartman
maintainerPATCH 689/3318 nfsd: dont modify a session slot when replaying its cached reply
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ameer Hamza <[email protected]>
commit 2987838317501ff67b672ac2a441fe34b7729f3d upstream.
nfsd4_sequence() claims a session slot by setting NFSD4_SLOT_INUSE under nn->client_lock. A reply served from the slot's reply cache does not claim it, and that distinction lived only in cstate->status, which nfsd4_sequence() set to nfserr_replay_cache. Commit cc028a10a48c ("NFSD: Hoist status code encoding into XDR encoder functions") moved nfsd4_proc_compound()'s cstate->status assignment below the out:
label, and the replay path's goto out was the one path that relied on skipping it. The test in nfsd4_sequence_done() therefore no longer identifies a replay, and every replay now stores its reply and clears NFSD4_SLOT_INUSE as though it owned the slot.
NFSD4_SLOT_INUSE is the interlock: check_slot_seqid() rejects every sequence id for a slot that is in use, before replay_matches_cache() runs. A replay never sets it, so two replays can be in flight on the same slot at once. One can read slot->sl_cred under nn->client_lock while the other's completion frees and rebuilds it from the XDR encoder without that lock. Two completions can also collide with each other and release the same group_info twice. free_svc_cred() leaves cr_uid, cr_gid and cr_flavor intact, so the reader passes every earlier test in same_creds() and dereferences a NULL cr_group_info.
Quoted 1 line
From a 6.12.91 production server:
BUG: kernel NULL pointer dereference, address: 0000000000000004 CPU: 63 UID: 0 PID: 39015 Comm: nfsd RIP: 0010:same_creds+0x38/0xa0 [nfsd] RDX: 0000000000000000 Call Trace: nfsd4_sequence+0x6a8/0x910 [nfsd] nfsd4_proc_compound+0x345/0x670 [nfsd] nfsd_dispatch+0x100/0x220 [nfsd] svc_process_common+0x311/0x700 [sunrpc] svc_process+0x131/0x1c0 [sunrpc] svc_recv+0x7ef/0x9c0 [sunrpc] nfsd+0xa3/0x100 [nfsd] Kernel panic - not syncing: Fatal exception
Since v6.14 a live session's slot table can shrink, and the unowned store becomes a use-after-free write. nfsd4_sequence() defers the shrink while a slot is in use, but it tests NFSD4_SLOT_INUSE, which a replay does not set, so free_session_slots() can kfree() the slot the replay still holds in cstate->slot.
Record the claim in cstate->slot_owned when nfsd4_sequence() accepts a request and test that in nfsd4_sequence_done(), so only the request that claimed the slot updates its cached reply and clears NFSD4_SLOT_INUSE. svc_generic_init_request() zeroes the compound response before each request, so the flag starts clear.
--- fs/nfsd/nfs4state.c | 7 ++++++- fs/nfsd/xdr4.h | 1 + 2 files changed, 7 insertions(+), 1 deletion(-)
fs/nfsd/nfs4state.c +6 -1
@@ -4156,6 +4156,7 @@ nfsd4_sequence(struct svc_rqst *rqstp, s slot->sl_flags &= ~NFSD4_SLOT_CACHETHIS ; cstate->slot = slot; + cstate->slot_owned = true; cstate->session = session; cstate->clp = clp;
@@ -4188,7 +4189,11 @@ nfsd4_sequence_done(struct nfsd4_compounstruct nfsd4_compound_state *cs = &resp->cstate;if (nfsd4_has_session (cs)) { -if (cs->status != nfserr_replay_cache) { +/* +* Only the request that claimed the slot may update its +* cached reply and clear NFSD4_SLOT_INUSE. +*/ +if (cs->slot_owned) {nfsd4_store_cache_entry (resp); cs->slot->sl_flags &= ~NFSD4_SLOT_INUSE ; }
fs/nfsd/xdr4.h +1 -0
@@ -171,6 +171,7 @@ struct nfsd4_compound_state {struct nfsd4_slot *slot;int data_offset;bool spo_must_allowed; +bool slot_owned;size_t iovlen;u32 minorversion;__be32 status;
Greg Kroah-Hartman
maintainerPATCH 690/3318 NFSD: Fail a pool_threads read whose reply does not fit
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit e27c63245903402ccfdb46c576462981a7e032e3 upstream.
The reply to a pool_threads read is the list of per-pool thread counts, formatted into a buffer of SIMPLE_TRANSACTION_LIMIT bytes. snprintf() truncates its last write and strlen() measures only what fit, so a reply too long for that buffer ends mid-number with no terminating newline. A pool running 4096 threads is reported as 40. Nothing marks the reply as incomplete, so an administrator reads a plausible but wrong count.
Take snprintf()'s return value, which reports the truncation strlen() cannot see, and fail the read with -ENAMETOOLONG when the list does not fit. That is the errno svc_one_xprt_name() already returns for the same condition.
--- fs/nfsd/nfsctl.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/nfsd/nfsctl.c +8 -4
@@ -453,7 +453,7 @@ static ssize_t write_pool_threads(structchar *mesg = buf;int i;int rv; -int len; +size_t len;int npools;int *nthreads;struct net *net =netns (file);
@@ -499,9 +499,13 @@ static ssize_t write_pool_threads(struct mesg = buf; size =SIMPLE_TRANSACTION_LIMIT ; -for (i =0 ; i < npools && size >0 ; i++) { -snprintf (mesg, size,"%d%c" , nthreads[i], (i == npools-1 ?'\n' :' ' )); - len =strlen (mesg); +for (i =0 ; i < npools; i++) { + len =snprintf (mesg, size,"%d%c" , nthreads[i], + (i == npools -1 ?'\n' :' ' )); +if (len >= size) { + rv = -ENAMETOOLONG ; + goto out_free; + } size -= len; mesg += len; }
Greg Kroah-Hartman
maintainerPATCH 691/3318 nfsd: Fix id-to-name cache entry leak in idtoname_parse()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wentao Liang <[email protected]>
commit 8ca3b74c0c447af17d0e27e76658a3d4cae3c5ba upstream.
idtoname_lookup() returns the id-to-name cache entry with a new reference. The name is parsed between the lookup and the update call, and when the parsed name is malformed (negative length or longer than IDMAP_NAMESZ), idtoname_parse() jumps to the error label without dropping the reference returned by idtoname_lookup(), leaking the cache entry.
Release the reference with cache_put() before taking the error exit.
--- fs/nfsd/nfs4idmap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/nfsd/nfs4idmap.c +3 -1
@@ -252,8 +252,10 @@ idtoname_parse(struct cache_detail *cd,/* Name */ error = -EINVAL ; len =qword_get (&buf, buf1,PAGE_SIZE ); -if (len <0 || len >=IDMAP_NAMESZ ) +if (len <0 || len >=IDMAP_NAMESZ ) { +cache_put (&res->h, cd); goto out; + }if (len ==0 )set_bit (CACHE_NEGATIVE , &ent.h.flags);else
Greg Kroah-Hartman
maintainerPATCH 692/3318 nfsd: hold cl_lock in client_has_openowners()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft Security FORGE Labs) <[email protected]>
commit 5336899b5491eaa2ac22c2925d87daab2b140eb3 upstream.
client_has_openowners() walks clp->cl_openowners and reads so_stateids without clp->cl_lock. nfs4_put_stateowner() unhashes that openowner under cl_lock and then frees it, so a concurrent EXCHANGE_ID with mismatched creds can use-after-free the nfs4_openowner.
BUG: KASAN: slab-use-after-free in client_has_state+0x10a/0x140 fs/nfsd/nfs4state.c:3718 client_has_openowners() nfsd4_exchange_id nfsd4_proc_compound nfsd_dispatch svc_process
Take clp->cl_lock while client_has_openowners() walks the openowner list.
--- fs/nfsd/nfs4state.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
fs/nfsd/nfs4state.c +9 -3
@@ -3349,12 +3349,18 @@ nfsd4_set_ex_flags(struct nfs4_client *nstatic bool client_has_openowners (struct nfs4_client *clp) {struct nfs4_openowner *oo; +bool found = false; +spin_lock (&clp->cl_lock);list_for_each_entry (oo, &clp->cl_openowners, oo_perclient) { -if (!list_empty (&oo->oo_owner.so_stateids)) -return true; +if (!list_empty (&oo->oo_owner.so_stateids)) { + found = true; +break ; + } } -return false; +spin_unlock (&clp->cl_lock); + +return found; }static bool client_has_state (struct nfs4_client *clp)
Greg Kroah-Hartman
maintainerPATCH 693/3318 nfsd: honour client-provided attributes for NFS4_CREATE_EXCLUSIVE4_1
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: NeilBrown <[email protected]>
commit ddfabbc7840891e09cd500ab97c9cd36b650ec24 upstream.
When a file is created with a v4.1 OPEN which requests NFS4_CREATE_EXCLUSIVE4_1, the request can include attributes to be set. However when the mtime/atime are set to hold the verifier, the other ia_valid flags are cleared, so no attributes requested by the client are used.
This code was originally written for NFSv3 where NFS3_CREATE_EXCLUSIVE never includes attributes. When it was updated for v4.1, the fact that an exclusive create CAN include attributes was not handled properly.
--- fs/nfsd/nfs4proc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/nfsd/nfs4proc.c +2 -2
@@ -358,8 +358,8 @@ nfsd4_create_file(struct svc_rqst *rqstpif ((iap->ia_valid &ATTR_SIZE ) && (iap->ia_size ==0 )) iap->ia_valid &= ~ATTR_SIZE ;if (nfsd4_create_is_exclusive (open->op_createmode)) { - iap->ia_valid =ATTR_MTIME |ATTR_ATIME | -ATTR_MTIME_SET |ATTR_ATIME_SET ; + iap->ia_valid |=ATTR_MTIME |ATTR_ATIME | +ATTR_MTIME_SET |ATTR_ATIME_SET ; iap->ia_mtime.tv_sec = v_mtime; iap->ia_atime.tv_sec = v_atime; iap->ia_mtime.tv_nsec =0 ;
Greg Kroah-Hartman
maintainerPATCH 694/3318 nfsd: preflight SEQUENCE replies before accepting a slot
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 35ff1a7a7e3835c3e974bc5c45d335897564ceae upstream.
nfsd4_sequence() narrows the reply buffer to the session's cached reply limit before it accepts the slot seqid. A client may negotiate ca_maxresponsesize_cached down to NFSD_MIN_HDR_SEQ_SZ, and nfsd4_alloc_slot() then gives every slot a zero-length sl_data[]. A COMPOUND tag can fill that narrowed buffer until it holds the SEQUENCE opcode but not the status word that follows. nfsd4_encode_operation() returns without running nfsd4_encode_sequence(), so cstate.data_offset stays zero. It leaves op->status at nfs_ok as well, so the COMPOUND is treated as having succeeded.
nfsd4_store_cache_entry() declines to cache a lone SEQUENCE that returned an error. That test reads the status the operation reported, so it passes here. The copy starts at offset zero and takes the whole reply, RPC and COMPOUND headers included, into the zero-length sl_data[]. The COMPOUND tag is copied along with it, so the client picks most of the bytes written past the end of the slot:
BUG: KASAN: slab-out-of-bounds in read_bytes_from_xdr_buf+0x1bc/0x390 Write of size 80 at addr ffff888003a549cd by task kunit_try_catch/24 __asan_memcpy+0x38/0x60 read_bytes_from_xdr_buf+0x1bc/0x390 nfsd4_sequence_done+0x5b0/0x810 nfs4svc_encode_compoundres+0x1bf/0x240
Check that the fixed-size SEQUENCE result, plus room for a following operation's error status, fits the negotiated limit before narrowing the buffer and consuming the slot seqid. The slot and its reply cache are left unchanged, as RFC 8881 Section 2.10.6.1.2 requires of an error returned from SEQUENCE.
--- fs/nfsd/nfs4state.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-)
fs/nfsd/nfs4state.c +18 -1
@@ -4068,6 +4068,7 @@ __be32 nfsd4_sequence(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, union nfsd4_op_u *u) { + struct nfsd4_compoundargs *args = rqstp->rq_argp;struct nfsd4_sequence *seq = &u->sequence;struct nfsd4_compoundres *resp = rqstp->rq_resp;struct xdr_stream *xdr = resp->xdr;
@@ -4077,6 +4078,7 @@ nfsd4_sequence(struct svc_rqst *rqstp, sstruct nfsd4_conn *conn;__be32 status;int buflen; +u32 maxlen, respsize;struct net *net =SVC_NET (rqstp);struct nfsd_net *nn =net_generic (net, nfsd_net_id);
@@ -4148,7 +4150,22 @@ nfsd4_sequence(struct svc_rqst *rqstp, s session->se_fchannel.maxresp_sz; status = (seq->cachethis) ? nfserr_rep_too_big_to_cache : nfserr_rep_too_big; -if (xdr_restrict_buflen (xdr, buflen - rqstp->rq_auth_slack)) +if (buflen < rqstp->rq_auth_slack) + goto out_put_session; + maxlen = buflen - rqstp->rq_auth_slack; + +/* +* A SEQUENCE result too large for maxlen never reaches +* nfsd4_encode_sequence(), so cstate.data_offset stays zero and +* the reply cache overruns the slot. +*/ + respsize =nfsd4_max_reply (rqstp, &args->ops[0 ]); +if (!nfsd4_last_compound_op (rqstp)) + respsize +=COMPOUND_ERR_SLACK_SPACE ; +if (xdr->buf->len + respsize > maxlen) + goto out_put_session; + +if (xdr_restrict_buflen (xdr, maxlen)) goto out_put_session;svc_reserve (rqstp, buflen);
Greg Kroah-Hartman
maintainerPATCH 695/3318 nfsd: propagate SETXATTR value decode errors
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit cfcfe0b38a66bbc4122c78a2b75e1b97b3534761 upstream.
nfsd4_decode_setxattr() stores the status returned while assembling a non-empty attribute value, but then unconditionally returns nfs_ok. An allocation failure can therefore leave a NULL value buffer paired with a non-zero length and allow compound processing to continue.
Return the decoder status so that the operation stops on the original error.
--- fs/nfsd/nfs4xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfsd/nfs4xdr.c +1 -1
@@ -2251,7 +2251,7 @@ nfsd4_decode_setxattr(struct nfsd4_compo &setxattr->setxa_buf, size); } -return nfs_ok; +return status; } static __be32
Greg Kroah-Hartman
maintainerPATCH 696/3318 NFSD: Reject an oversized principal hash from nfsdcld
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit dbed9418c48906dae1a7bc328fb3bc0d0d0020c8 upstream.
__cld_pipe_inprogress_downcall() takes the principal hash length from the daemon's GraceStart downcall without checking it against the cc_princhash payload it describes, which holds at most SHA256_DIGEST_SIZE bytes. The length is stored verbatim in the reclaim record, and nfsd4_cld_check_v2() later hands it to memcmp() against a digest array of SHA256_DIGEST_SIZE bytes on the stack. A length up to U8_MAX reads past the end of that array, and the stray bytes can only make the comparison fail, denying the client its reclaim. The pipe is mode 0600 in rpc_pipefs, so the trigger is a broken or hostile nfsdcld rather than an unprivileged task.
Reject a length larger than the wire field, as the existing check on the client name length does.
--- fs/nfsd/nfs4recover.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/nfsd/nfs4recover.c +5 -0
@@ -806,6 +806,11 @@ __cld_pipe_inprogress_downcall(const str name.len = namelen;if (get_user (princhashlen, &ci->cc_princhash.cp_len))return -EFAULT ; +if (princhashlen >SHA256_DIGEST_SIZE ) { +dprintk ("%s: invalid princhashlen (%u)" , + __func__, princhashlen); +return -EINVAL ; + }if (princhashlen >0 ) { princhashcopy = memdup_user( &ci->cc_princhash.cp_data,
Greg Kroah-Hartman
maintainerPATCH 697/3318 NFSD: Resolve the recall-any mask names in the trace format
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit c563a1f0679566d7d586802e5346591d0af8da78 upstream.
RCA4_TYPE_MASK_* are enum constants, so the preprocessor cannot fold them into the print format that show_rca_mask() builds for the nfsd_cb_recall_any event. Nothing declares an eval map for them either, so trace_event_eval_update() has no substitution to apply at module load, and the event's format file ships the enumerator names verbatim. trace-cmd and perf cannot decode the bmval0 field.
Declare the eval maps for the nine mask bits show_rca_mask() decodes. The format then carries the shift counts as integers, the same shape the SUNRPC trace points already emit from their BIT() flag decoders.
--- include/trace/misc/nfs.h | 10 ++++++++++ 1 file changed, 10 insertions(+)
include/trace/misc/nfs.h +10 -0
@@ -359,6 +359,16 @@ TRACE_DEFINE_ENUM(IOMODE_ANY); { IOMODE_RW, "RW" }, \ { IOMODE_ANY, "ANY" }) +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_RDATA_DLG ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_WDATA_DLG ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_DIR_DLG ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_FILE_LAYOUT ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_BLK_LAYOUT ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OBJ_LAYOUT_MIN ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OBJ_LAYOUT_MAX ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OTHER_LAYOUT_MIN ); +TRACE_DEFINE_ENUM (RCA4_TYPE_MASK_OTHER_LAYOUT_MAX ); +#define show_rca_mask (x) \ __print_flags(x, "|", \ { BIT(RCA4_TYPE_MASK_RDATA_DLG), "RDATA_DLG" }, \
Greg Kroah-Hartman
maintainerPATCH 698/3318 nfsd: zero NFSv4 COMPOUND tag padding
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 3f1181cb09c85499286c7f462d93530b0ebcafcc upstream.
nfs4svc_encode_compoundres() copies the tag bytes into reserved XDR space and skips directly to the aligned end of the field. xdr_reserve_space() rounds the reservation up but does not initialize the padding bytes.
A remote client can choose a tag length that is not a multiple of four, causing one to three stale bytes from the response page to be returned in the COMPOUND reply.
Use xdr_encode_opaque_fixed() to copy the tag and clear its XDR padding.
--- fs/nfsd/nfs4xdr.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
fs/nfsd/nfs4xdr.c +1 -2
@@ -5539,8 +5539,7 @@ nfs4svc_encode_compoundres(struct svc_rq *p++ = resp->cstate.status; *p++ =htonl (resp->taglen); -memcpy (p, resp->tag, resp->taglen); - p +=XDR_QUADLEN (resp->taglen); + p =xdr_encode_opaque_fixed (p, resp->tag, resp->taglen); *p++ =htonl (resp->opcnt);nfsd4_sequence_done (resp);
Greg Kroah-Hartman
maintainerPATCH 699/3318 SUNRPC: Copy the deferred RPC Call from the head buffer
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 2192a56b0686599358909c3e12e9a366f5b5d452 upstream.
svc_defer() snapshots the RPC Call for replay once a pending cache upcall resolves. It copies the Call starting (rq_arg.len - head[0].iov_len) bytes before head[0].iov_base, a back-up that once covered a transport header. No transport has had one since commit 983084b2672c ("SUNRPC: Remove svc_rqst::rq_xprt_hlen"), so the two lengths are meant to be equal.
An RPCSEC_GSS Call breaks that assumption. Unwrapping the integrity service truncates rq_arg.len by the length of the trailing checksum, and unwrapping the privacy service leaves rq_arg.len short by an amount the client sets with trailing bytes after the wrap token. Neither adjusts head[0].iov_len. Both lengths are size_t, so the subtraction underflows and the copy starts past head[0].iov_base. Every deferred integrity Call replays a shifted snapshot.
A deferred replay skips GSS verification, so a shifted snapshot runs as an authenticated Call. With the privacy service the offset is client-chosen. A forged Call placed in that window, naming another user's GSS context handle, runs under that identity.
Copy the Call from head[0].iov_base. Refuse to defer a Call whose length runs past the head buffer, so the copy cannot read out of bounds.
--- net/sunrpc/svc_xprt.c | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-)
net/sunrpc/svc_xprt.c +7 -15
@@ -1171,13 +1171,8 @@ static void svc_revisit(struct cache_def }/* -* Save the request off for later processing. The request buffer looks -* like this: -* -* <xprt-header><rpc-header><rpc-pagelist><rpc-tail> -* -* This code can only handle requests that consist of an xprt-header -* and rpc-header. +* Save the request off for later processing. Only a Call that fits +* entirely in rq_arg.head[0] can be deferred. */ static struct cache_deferred_req *svc_defer (struct cache_req *req) {
@@ -1190,8 +1185,11 @@ static struct cache_deferred_req *svc_de dr = rqstp->rq_deferred; rqstp->rq_deferred =NULL ; }else { -size_t skip;size_t size; + +if (rqstp->rq_arg.len > rqstp->rq_arg.head[0 ].iov_len) +return NULL ; +/* FIXME maybe discard if size too large */ size =sizeof (struct svc_deferred_req ) + rqstp->rq_arg.len; dr =kmalloc (size,GFP_KERNEL );
@@ -1205,9 +1203,7 @@ static struct cache_deferred_req *svc_de dr->daddr = rqstp->rq_daddr; dr->argslen = rqstp->rq_arg.len >>2 ; -/* back up head to the start of the buffer and copy */ - skip = rqstp->rq_arg.len - rqstp->rq_arg.head[0 ].iov_len; -memcpy (dr->args, rqstp->rq_arg.head[0 ].iov_base - skip, +memcpy (dr->args, rqstp->rq_arg.head[0 ].iov_base, dr->argslen <<2 ); } dr->xprt_ctxt = rqstp->rq_xprt_ctxt;
@@ -1230,17 +1226,13 @@ static noinline int svc_deferred_recv(sttrace_svc_defer_recv (dr); -/* setup iov_base past transport header */ rqstp->rq_arg.head[0 ].iov_base = dr->args; -/* The iov_len does not include the transport header bytes */ rqstp->rq_arg.head[0 ].iov_len = dr->argslen <<2 ; rqstp->rq_arg.page_len =0 ; -/* The rq_arg.len includes the transport header bytes */ rqstp->rq_arg.len = dr->argslen <<2 ; rqstp->rq_prot = dr->prot;memcpy (&rqstp->rq_addr, &dr->addr, dr->addrlen); rqstp->rq_addrlen = dr->addrlen; -/* Save off transport header len in case we get deferred again */ rqstp->rq_daddr = dr->daddr; rqstp->rq_respages = rqstp->rq_pages; rqstp->rq_xprt_ctxt = dr->xprt_ctxt;
Greg Kroah-Hartman
maintainerPATCH 700/3318 SUNRPC: Do not credit control-record octets to the RPC stream
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 129e7107b971009bc81643d23f3ab949f540d321 upstream.
svc_tcp_sock_recv_cmsg() receives up to two octets into a local buffer, and returns that count for any record type other than TLS_RECORD_TYPE_ALERT. Nothing reached the caller's buffer, but svc_tcp_read_marker() adds the count to sk_tcplen and svc_tcp_read_msg()'s caller adds it to sk_datalen. The RPC stream advances over octets it never received. The fragment marker is assembled from stale sk_marker octets. The message body comes from pages nothing wrote.
A conforming client reaches this. RFC 8446 Section 4.6.3 lets either peer send KeyUpdate once it has sent its Finished, and svcsock has no rekey path. kTLS leaves the partially consumed record on ctx->rx_list, so the body drains two octets per svc_tcp_recvfrom() call. Each pair is credited the same way.
Return -EAGAIN for a record that is not an alert. That is what svc_tcp_sock_process_cmsg()'s default arm returned before the receive moved into a local buffer.
--- net/sunrpc/svcsock.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
net/sunrpc/svcsock.c +7 -2
@@ -289,8 +289,13 @@ svc_tcp_sock_recv_cmsg(struct socket *soiov_iter_kvec (&msg.msg_iter,ITER_DEST , &alert_kvec,1 , alert_kvec.iov_len); ret =sock_recvmsg (sock, &msg,MSG_DONTWAIT ); -if (ret >0 && -tls_get_record_type (sock->sk, &u.cmsg) ==TLS_RECORD_TYPE_ALERT ) { +if (ret >0 ) { +/* Returning the count would credit the RPC stream with +* octets that never reached the caller's buffer. +*/ +if (tls_get_record_type (sock->sk, &u.cmsg) != +TLS_RECORD_TYPE_ALERT ) +return -EAGAIN ;iov_iter_revert (&msg.msg_iter, ret); ret =svc_tcp_sock_process_cmsg (sock, &msg, &u.cmsg, -EAGAIN ); }
Greg Kroah-Hartman
maintainerPATCH 701/3318 SUNRPC: fix oversized GSS proxy token copy
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 62319c2534b603b416fa2aa2f3ef18c311f75010 upstream.
gss_read_proxy_verf() allocates one page per token chunk, but it copies the entire linear head of an RPC request into in_token->pages[0]. A UDP datagram can leave more than PAGE_SIZE bytes in the linear head, so a large RPCSEC_GSS INIT token overwrites following pages.
Copy the linear head in page-sized chunks before switching to the request page array. The linear head itself can span multiple pages.
--- net/sunrpc/auth_gss/svcauth_gss.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
net/sunrpc/auth_gss/svcauth_gss.c +4 -3
@@ -1095,10 +1095,11 @@ static int gss_read_proxy_verf(struct sv } length = min_t(unsigned int, inlen, (char *)xdr->end - (char *)xdr->p); -if (length) -memcpy (page_address (in_token->pages[0 ]), xdr->p, length); +for (to_offs =0 ; to_offs < length; to_offs +=PAGE_SIZE ) +memcpy (page_address (in_token->pages[to_offs >>PAGE_SHIFT ]), + (char *)xdr->p + to_offs, + min_t(unsigned int, length - to_offs, PAGE_SIZE)); inlen -= length; - to_offs = length; from_offs = rqstp->rq_arg.page_base;while (inlen) {
Greg Kroah-Hartman
maintainerPATCH 702/3318 SUNRPC: keep the first error in svc_register()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeff Layton <[email protected]>
commit 9ed91d7c4698e611ea5bfca45076008def831fb3 upstream.
svc_register() assigns every pg_rpcbind_set() result to the same "error" variable and returns the last one, so a later result erases an earlier failure.
Keep the first error instead of the last.
--- net/sunrpc/svc.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
net/sunrpc/svc.c +6 -3
@@ -1198,13 +1198,16 @@ int svc_register(const struct svc_serv *for (progp = serv->sv_program; progp; progp = progp->pg_next) {for (i =0 ; i < progp->pg_nvers; i++) { +int ret; - error = progp->pg_rpcbind_set (net, progp, i, + ret = progp->pg_rpcbind_set (net, progp, i, family, proto, port); -if (error <0 ) { +if (ret <0 ) {printk (KERN_WARNING "svc: failed to register " "%sv%u RPC service (errno %d).\n" , - progp->pg_name, i, -error); + progp->pg_name, i, -ret); +if (!error) + error = ret;break ; } }
Greg Kroah-Hartman
maintainerPATCH 703/3318 sunrpc: pin gss module across auth_domain RCU free
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit b64d21116374688c33302a6704387c27d1156d72 upstream.
A gss auth_domain stores a raw pointer to svcauthops_gss in dom->flavour, and its release queues svcauth_gss_domain_release_rcu() via call_rcu(). Both live in auth_rpcgss.ko text, and nothing pins the module while a domain referencing it is reachable. rmmod auth_rpcgss can therefore unmap that text while an NFSD export still holds a reference to the domain.
The export cache is one such holder. When the export is finally released, the domain reference drops from module text:
svc_export_put()
auth_domain_put(exp->ex_client)
auth_domain_release()
dom->flavour->domain_release(dom) /* into module text */
svcauth_gss_domain_release()
call_rcu(&dom->rcu_head,
svcauth_gss_domain_release_rcu)Once auth_rpcgss is unloaded, the domain_release call lands in unmapped memory. The rcu_barrier() in exit_rpcsec_gss() does not
help: it waits only for callbacks already queued, and this one is not queued until the export goes away.
NFSD's NFSv4 objects import symbols from auth_rpcgss.ko, so only a server built without CONFIG_NFSD_V4 can unload auth_rpcgss while exports still name a gss domain.
Take a module reference in svcauth_gss_register_pseudoflavor() before publishing the domain and drop it at the end of svcauth_gss_domain_release_rcu(). The rcu_barrier() then holds the module image until this callback has returned.
--- net/sunrpc/auth_gss/svcauth_gss.c | 8 ++++++++ 1 file changed, 8 insertions(+)
net/sunrpc/auth_gss/svcauth_gss.c +8 -0
@@ -824,12 +824,18 @@ svcauth_gss_register_pseudoflavor(u32 ps new->h.flavour = &svcauthops_gss; new->pseudoflavor = pseudoflavor; +if (!try_module_get (svcauthops_gss.owner)) { + stat = -ENODEV ; + goto out_free_name; + } + test =auth_domain_lookup (name, &new->h);if (test != &new->h) {pr_warn ("svc: duplicate registration of gss pseudo flavour %s.\n" , name); stat = -EADDRINUSE ;auth_domain_put (test); +module_put (svcauthops_gss.owner); goto out_free_name; }return test;
@@ -2013,9 +2019,11 @@ svcauth_gss_domain_release_rcu(struct rc { struct auth_domain *dom = container_of(head, struct auth_domain, rcu_head); struct gss_domain *gd = container_of(dom, struct gss_domain, h); +struct module *owner = dom->flavour->owner;kfree (dom->name);kfree (gd); +module_put (owner); } static void
Greg Kroah-Hartman
maintainerPATCH 704/3318 SUNRPC: Reject a socket that already has an svc_sock attached
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 0995447b8059c4d23853cdcddbe789c4a2b6bb88 upstream.
Writing the same socket descriptor to /proc/fs/nfsd/portlist twice attaches a second svc_sock to one socket. svc_setup_socket() saves the socket's callbacks before installing its own, so the second attach records svc_write_space() as the old write_space callback. svc_udp_init() invokes that callback by way of svc_sock_setbufsize(), and svc_write_space() then calls itself until the kernel stack is exhausted:
BUG: TASK stack guard page was hit at ffffc900037d7ff8 svc_write_space+0x90/0x2b0 net/sunrpc/svcsock.c:429 svc_write_space+0xe6/0x2b0 net/sunrpc/svcsock.c:430 ... 700 more ... svc_sock_setbufsize+0x18d/0x220 net/sunrpc/svcsock.c:386 svc_udp_init net/sunrpc/svcsock.c:854 [inline] svc_setup_socket+0xb2f/0x1090 net/sunrpc/svcsock.c:1498 svc_addsock+0x2fd/0x760 net/sunrpc/svcsock.c:1547 __write_ports_addfd fs/nfsd/nfsctl.c:742 [inline] write_ports+0xa5b/0xcc0 fs/nfsd/nfsctl.c:861 nfsctl_transaction_write+0x106/0x1a0 fs/nfsd/nfsctl.c:112
svc_data_ready() and svc_tcp_state_change() chain through their saved callbacks the same way, so a TCP descriptor added twice recurses on the next incoming segment instead. Reaching any of this takes a writer on portlist, and the nfsd filesystem sets no FS_USERNS_MOUNT, so the reproducer needs CAP_SYS_ADMIN in the initial user namespace.
Reject a socket that already carries sk_user_data. svc_setup_socket() overwrites that field unconditionally, so a socket some other consumer has claimed is one NFSD would corrupt whether or not the callbacks recurse.
--- net/sunrpc/svcsock.c | 3 +++ 1 file changed, 3 insertions(+)
net/sunrpc/svcsock.c +3 -0
@@ -1540,6 +1540,9 @@ int svc_addsock(struct svc_serv *serv, s err = -EISCONN ;if (so->state >SS_UNCONNECTED ) goto out; + err = -EBUSY ; +if (so->sk->sk_user_data) + goto out; err = -ENOENT ;if (!try_module_get (THIS_MODULE )) goto out;
Greg Kroah-Hartman
maintainerPATCH 705/3318 SUNRPC: Reject a TLS alert record that is not two octets
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit d16bebe45272ced4f962d27b9efd8b32a3876bd9 upstream.
tls_alert_recv() reads two octets from the kvec it is handed and does not check the length (net/handshake/alert.c). svc_tcp_sock_recv_cmsg() calls it for any positive receive, and the alert[] buffer it supplies carries no initializer. A one-octet alert body leaves the description read from uninitialized stack and reported through trace_tls_alert_recv().
The peer controls that length. Neither tls_rx_msg_size() nor tls_rx_one_record() enforces the two-octet Alert payload. A TLS 1.3 record carrying only the inner content-type octet decrypts to a zero-length payload. RFC 8446 Section 5.1 requires a record with an Alert type to carry exactly one message, so any other length is malformed.
Require exactly two octets before parsing and return -EBADMSG otherwise. That closes the transport rather than acting on a partly uninitialized alert. Gate the path on a control message rather than a positive count so that a zero-length record reaches the check.
--- net/sunrpc/svcsock.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-)
net/sunrpc/svcsock.c +11 -1
@@ -289,13 +289,23 @@ svc_tcp_sock_recv_cmsg(struct socket *sock, unsigned int *msg_flags)iov_iter_kvec (&msg.msg_iter,ITER_DEST , &alert_kvec,1 , alert_kvec.iov_len); ret =sock_recvmsg (sock, &msg,MSG_DONTWAIT ); -if (ret >0 ) { +/* put_cmsg() shrinks msg_controllen, so a short one means +* kTLS filled in u.cmsg. +*/ +if (ret >=0 && msg.msg_controllen <sizeof (u)) {/* Returning the count would credit the RPC stream with * octets that never reached the caller's buffer. */ if (tls_get_record_type (sock->sk, &u.cmsg) !=TLS_RECORD_TYPE_ALERT )return -EAGAIN ; +/* An Alert record carries exactly one two-octet message +* (RFC 8446 Section 5.1). alert_kvec caps the receive at two, +* so a longer record produces the same count. MSG_EOR appears +* only once kTLS has drained the whole record. +*/ +if (ret !=sizeof (alert) || !(msg.msg_flags &MSG_EOR )) +return -EBADMSG ;iov_iter_revert (&msg.msg_iter, ret); ret =svc_tcp_sock_process_cmsg (sock, &msg, &u.cmsg, -EAGAIN ); }
Signature · 1 line
2.56.0
Greg Kroah-Hartman
maintainerPATCH 706/3318 SUNRPC: Resume receiving after a TLS control record
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 8079c660b247f282340fbe7f55cf8a354009db9e upstream.
A TLS control record delivers no payload to the RPC layer. svc_tcp_recvfrom() clears XPT_DATA before the receive, and svc_tcp_sock_recv_cmsg() returns -EAGAIN for the record it consumed. Nothing marks the transport ready again. kTLS raises data_ready for arriving TCP segments, not for records it has already decrypted. An RPC Call queued behind an alert or a KeyUpdate waits until the client sends more. The client blocks until its RPC timeout expires.
The receive takes only the first two octets of the record. kTLS holds the remainder on its receive list, where each later receive takes two octets more.
Drain a record that is not an alert, then mark the transport ready once a control record has been consumed.
--- net/sunrpc/svcsock.c | 55 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-)
net/sunrpc/svcsock.c +52 -3
@@ -238,6 +238,39 @@ static int svc_one_sock_name(struct svc_return len; } +/* +* kTLS delivers a record only up to the caller's buffer and keeps +* the remainder on its receive list, where no further data_ready +* announces it. Consume the whole record. +*/ +static void +svc_tcp_sock_drain_record (struct socket *sock) +{ +union { +struct cmsghdr cmsg; +u8 buf[CMSG_SPACE (sizeof (u8))]; + } u; +u8 discard[64 ]; +struct kvec discard_kvec = { + .iov_base = discard, + .iov_len =sizeof (discard), + }; + +for (;;) { +struct msghdr msg = { + .msg_control = &u, + .msg_controllen =sizeof (u), + }; + +iov_iter_kvec (&msg.msg_iter,ITER_DEST , &discard_kvec,1 , + discard_kvec.iov_len); +if (sock_recvmsg (sock, &msg,MSG_DONTWAIT ) <=0 ) +break ; +if (msg.msg_flags &MSG_EOR ) +break ; + } +} +static int svc_tcp_sock_process_cmsg (struct socket *sock,struct msghdr *msg,struct cmsghdr *cmsg,int ret)
@@ -293,12 +326,20 @@ svc_tcp_sock_recv_cmsg(struct socket *so* kTLS filled in u.cmsg. */ if (ret >=0 && msg.msg_controllen <sizeof (u)) { +u8 content_type =tls_get_record_type (sock->sk, &u.cmsg); +/* Returning the count would credit the RPC stream with * octets that never reached the caller's buffer. */ -if (tls_get_record_type (sock->sk, &u.cmsg) != -TLS_RECORD_TYPE_ALERT ) +if (content_type !=TLS_RECORD_TYPE_ALERT ) { +/* An application data record carries RPC payload. +* Draining one breaks RPC fragment framing. +*/ +if (content_type !=TLS_RECORD_TYPE_DATA && + !(msg.msg_flags &MSG_EOR )) +svc_tcp_sock_drain_record (sock);return -EAGAIN ; + }/* An Alert record carries exactly one two-octet message * (RFC 8446 Section 5.1). alert_kvec caps the receive at two, * so a longer record produces the same count. MSG_EOR appears
@@ -321,8 +362,16 @@ svc_tcp_sock_recvmsg(struct svc_sock *sv ret =sock_recvmsg (sock, msg,MSG_DONTWAIT );if (msg->msg_flags &MSG_CTRUNC ) { msg->msg_flags &= ~(MSG_CTRUNC |MSG_EOR ); -if (ret ==0 || ret == -EIO ) +if (ret ==0 || ret == -EIO ) { ret =svc_tcp_sock_recv_cmsg (sock, &msg->msg_flags); +/* A control record delivers nothing to the caller, +* and kTLS announces no data_ready for records it +* already holds. Mark the transport ready so that +* the records behind this one can be received. +*/ +if (ret == -EAGAIN ) +set_bit (XPT_DATA , &svsk->sk_xprt.xpt_flags); + } }return ret; }
Greg Kroah-Hartman
maintainerPATCH 707/3318 SUNRPC: trace an accepted transport before publishing it
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhiling Zou <[email protected]>
commit 06f90cf104fc21ee01e7ef1eb80e092173089b9f upstream.
svc_handle_xprt() publishes a newly accepted transport before tracing it. svc_add_new_temp_xprt() places the transport on sv_tempsocks and clears XPT_BUSY, so another nfsd thread can dequeue it at once. If the peer has already closed the connection, that thread runs svc_delete_xprt(), which drops the list reference, the only reference the new transport holds. trace_svc_xprt_accept() then reads the transport's addresses and network namespace from freed memory.
Before publication the accepting thread owns the transport
exclusively: XPT_BUSY is still set from svc_xprt_init() and the transport is on no list. Emit the tracepoint there.
--- net/sunrpc/svc_xprt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/sunrpc/svc_xprt.c +1 -1
@@ -807,8 +807,8 @@ static void svc_handle_xprt(struct svc_r newxpt = xprt->xpt_ops->xpo_accept (xprt);if (newxpt) { newxpt->xpt_cred =get_cred (xprt->xpt_cred); -svc_add_new_temp_xprt (serv, newxpt);trace_svc_xprt_accept (newxpt, serv->sv_name); +svc_add_new_temp_xprt (serv, newxpt); }else {module_put (xprt->xpt_class->xcl_owner); }
Greg Kroah-Hartman
maintainerPATCH 708/3318 sunrpc: treat empty auth.unix.gid replies as negative entries
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ameer Hamza <[email protected]>
commit a12cc0930235b86b934ade7c077a1935c2ac333d upstream.
When rpc.mountd cannot resolve a uid (getpwuid() or getgrouplist() failure, e.g. while winbind or sssd is briefly unreachable), it answers the auth.unix.gid upcall with zero groups. unix_gid_parse() installs that as a valid positive entry, and svcauth_unix_set_client() then replaces the credential's group list with the empty one on every request, RPCSEC_GSS included via svcauth_gss_set_client(). One failed lookup strips that uid of all supplementary groups on every export for up to mountd's configured TTL (30 minutes by default), long after the NSS backend has recovered.
mountd cannot send an empty list for a successful lookup, since getgrouplist(3) always includes at least the user's primary group, so a zero-group reply can only mean the lookup failed. Record it as a negative entry: unix_gid_find() then returns -ENOENT and svcauth_unix_set_client() keeps the groups the RPC credential already carries. This is the fallback that
commit 3fc605a2aa38 ("[PATCH] knfsd: allow the server to provide a gid list when using AUTH_UNIX authentication") promised when no answer is available, and the same state try_to_negate_entry() already creates when no listener holds the channel open.
--- net/sunrpc/svcauth_unix.c | 7 +++++++ 1 file changed, 7 insertions(+)
net/sunrpc/svcauth_unix.c +7 -0
@@ -537,6 +537,13 @@ static int unix_gid_parse(struct cache_dif (ugp) {struct cache_head *ch; ug.h.flags =0 ; +/* +* mountd sends at least the user's primary group on +* success, so an empty list can only mean the lookup +* failed. Keep the credential's own groups instead. +*/ +if (gids ==0 ) +set_bit (CACHE_NEGATIVE , &ug.h.flags); ug.h.expiry_time = expiry; ch = sunrpc_cache_update(cd, &ug.h, &ugp->h,
Greg Kroah-Hartman
maintainerPATCH 709/3318 SUNRPC: Treat every TLS error alert as fatal
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 2c0dfe9d6d81e4bc9201b11dab3876cbfd01884e upstream.
svc_tcp_sock_process_cmsg() decides whether an alert ends the session by reading the alert's level octet. RFC 8446 Section 6 retired that field. The severity is implicit in the description, and a receiver treats every alert listed in Section 6.2 as an error alert "regardless of the AlertLevel in the message". A peer that aborts with unexpected_message but leaves the legacy octet set to warning makes the server return -EAGAIN. svc_tcp_recvfrom() then leaves a dead TLS session attached to an open transport. NFSD keeps polling it.
Decide from the alert description instead. close_notify and user_canceled are the closure alerts (RFC 8446 Section 6.1). Every other description ends the session, including one this kernel does not recognize.
--- net/sunrpc/svcsock.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
net/sunrpc/svcsock.c +11 -2
@@ -290,8 +290,17 @@ svc_tcp_sock_process_cmsg(struct socketbreak ;case TLS_RECORD_TYPE_ALERT :tls_alert_recv (sock->sk, msg, &level, &description); - ret = (level ==TLS_ALERT_LEVEL_FATAL ) ? - -ENOTCONN : -EAGAIN ; +/* RFC 8446 Section 6: every alert but a closure alert is +* an error alert. +*/ +switch (description) { +case TLS_ALERT_DESC_CLOSE_NOTIFY : +case TLS_ALERT_DESC_USER_CANCELED : + ret = -EAGAIN ; +break ; +default : + ret = -ENOTCONN ; + }break ;default :/* discard this record type */
Greg Kroah-Hartman
maintainerPATCH 710/3318 rxrpc: Fix double IRQ enablement
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Howells <[email protected]>
commit 41eb0af096ba8754e584d47e6de42f1e4980ceae upstream.
rxrpc_notify_socket() explicitly disables and then re-enables IRQs, but one of its call chains (rxrpc_input_queue_data() -> rxrpc_end_rx_phase() -> rxrpc_call_completed() -> rxrpc_set_call_completion()) has IRQs disabled around it.
Fix this by making rxrpc_notify_socket() use irqsave spinlocks.
--- net/rxrpc/recvmsg.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
net/rxrpc/recvmsg.c +5 -4
@@ -24,6 +24,7 @@ void rxrpc_notify_socket(struct rxrpc_call *call) {struct rxrpc_sock *rx;struct sock *sk; +unsigned long flags;_enter ("%d" , call->debug_id);
@@ -38,16 +39,16 @@ void rxrpc_notify_socket(struct rxrpc_call *call) sk = &rx->sk;if (rx && sk->sk_state <RXRPC_CLOSE ) {if (call->notify_rx) { -spin_lock_irq (&call->notify_lock); +spin_lock_irqsave (&call->notify_lock, flags); call->notify_rx (sk, call, call->user_call_ID); -spin_unlock_irq (&call->notify_lock); +spin_unlock_irqrestore (&call->notify_lock, flags); }else { -spin_lock_irq (&rx->recvmsg_lock); +spin_lock_irqsave (&rx->recvmsg_lock, flags);if (list_empty (&call->recvmsg_link)) {rxrpc_get_call (call, rxrpc_call_get_notify_socket);list_add_tail (&call->recvmsg_link, &rx->recvmsg_q); } -spin_unlock_irq (&rx->recvmsg_lock); +spin_unlock_irqrestore (&rx->recvmsg_lock, flags);if (!sock_flag (sk,SOCK_DEAD )) {_debug ("call %ps" , sk->sk_data_ready);
Signature · 1 line
2.56.0
Greg Kroah-Hartman
maintainerPATCH 711/3318 KVM: SVM: Trigger new ASID allocation in both VMCBs on pCPU switch
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
commit bf260dc9e7b8bfcd06c1a8e739797b1cf0917c72 upstream.
When the pCPU where the VMCB was most recently used is switched, reset the ASID generation in both VMCBs, triggering new ASID allocation for the immediate VMRUN as well as the next VMRUN on the other VMCB.
The ASID is shared between vmcb01 and vmcb02, and gets flushed on every nested transition. However, since pCPU tracking is done per VMCB, it is possible for one VMCB to allocate a new ASID when migrated to a new pCPU, and then the other VMCB reuses that ASID on the old pCPU. This can result in the same ASID being used by multiple vCPUs on the old pCPU.
Example scenario:
- vCPU runs on pCPU A, vmcb01 is active, asid=1.
- vCPU migrates to pCPU B, vmcb01 pCPU changes, new asid=2.
- Another vCPU runs on pCPU A and allocates asid=2 as well.
- vCPU migrates back to pCPU A, and then switches to vmcb02 before it runs again with vmcb01.
- No pCPU switch is detected for vmcb02, so VMRUN is done with asid=2.
- Two vCPUs end up using asid=2 on the same pCPU.
Keep the VMCB dirtying to the active VMCB only. Clean bits are tracked by a pCPU for each VMCB, so do not unnecessarily dirty a VMCB if its pCPU does not change.
Additionally, initialize the tracked pCPU for vmcb02 to -1 on nested enablement as hardening, so that a new ASID allocation is always triggered when nested is disabled and re-enabled.
No performance regression was noticed when overcommitting L1 vCPUs in L0 (to force rescheduling), pinning L1 <-> L2 vCPUs, and running CPUID in a tight loop bouncing between 2 vCPUs in L2.
An alternative (and perhaps more proper) fix would be tracking the ASID per-VMCB instead (e.g. [1]). However, that's a more involved change, and it would result in having different ASIDs for L1 and L2 without actually properly maintaining them. It would probably work because all TLB flushes target the current VMCB, and the other VMCB is always flushed on nested transitions, but the code ends up in an arguably more fragile state. Punt a proper clean fix to an incoming (and overdue) overhaul of SVM's ASID usage [2].
[1] https://lore.kernel.org/lkml/[email protected]
[2] https://lore.kernel.org/kvm/[email protected]
--- arch/x86/kvm/svm/nested.c | 1 + arch/x86/kvm/svm/svm.c | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/nested.c +1 -0
@@ -1232,6 +1232,7 @@ int svm_allocate_nested(struct vcpu_svm goto err_free_vmcb02;svm_vcpu_init_msrpm (&svm->vcpu, svm->nested.msrpm); + svm->nested.vmcb02.cpu =-1 ; svm->nested.initialized = true;return 0 ;
arch/x86/kvm/svm/svm.c +15 -4
@@ -3649,14 +3649,25 @@ static void pre_svm_run(struct kvm_vcpustruct vcpu_svm *svm =to_svm (vcpu);/* -* If the previous vmrun of the vmcb occurred on a different physical -* cpu, then mark the vmcb dirty and assign a new asid. Hardware's -* vmcb clean bits are per logical CPU, as are KVM's asid assignments. +* If the previous VMRUN of the VMCB occurred on a different physical +* cpu, then mark the VMCB dirty as hardware's clean bits are per pCPU. +* +* Reset the ASID generation in both VMCBs. This will lead to assigning +* a new ASID now, and then again when switching to the other VMCB. +* However, this is needed as the ASID is shared between the VMCBs, and +* otherwise it would be possible to use an ASID allocated on one pCPU +* on another, for example: +* - vCPU migrates from pCPU A to pCPU B, allocates a new ASID. +* - vCPU migrates back to pCPU A, and then switches the VMCB. +* - The new VMCB does not detect a pCPU change and runs on pCPU A with +* the new ASID allocated on pCPU B, which is potentially used by +* another vCPU/VM. */ if (unlikely (svm->current_vmcb->cpu != vcpu->cpu)) { - svm->current_vmcb->asid_generation =0 ;vmcb_mark_all_dirty (svm->vmcb); svm->current_vmcb->cpu = vcpu->cpu; + svm->vmcb01.asid_generation =0 ; + svm->nested.vmcb02.asid_generation =0 ; }if (sev_guest (vcpu->kvm))
Greg Kroah-Hartman
maintainerPATCH 712/3318 KVM: nSVM: Ignore EFER.LMA if EFER.LME=0 when preparing L2 state
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 1c4c84a643b704e473cb171f7b61359ff29b12a4 upstream.
Force EFER.LMA=0 if EFER.LME=0 when preparing L2 state for VMRUN, i.e. mimic real hardware's behavior of ignoring EFER.LMA if EFER.LME=0. VMRUN unfortunately allows the nonsensical combination, i.e. doesn't fail, but KVM itself has an invariant EFER.LMA can be set et if and only if EFER.LME
is set. Breaking that invariant can lead to a variety of issue,
particularly in MMU code that keys off EFER.LMA when determining whether to emulate/virtualization 4/5-level paging versus PAE paging.
--- arch/x86/kvm/svm/nested.c | 4 ++++ 1 file changed, 4 insertions(+)
arch/x86/kvm/svm/nested.c +4 -0
@@ -592,6 +592,10 @@ static void nested_vmcb02_prepare_save(skvm_set_rflags (vcpu, vmcb12->save.rflags |X86_EFLAGS_FIXED ); +/* SVM ignores EFER.LMA if EFER.LME=0 (instead of failing VMRUN). */ +if (!(svm->nested.save.efer &EFER_LME )) + svm->nested.save.efer &= ~EFER_LMA ; +svm_set_efer (vcpu, svm->nested.save.efer);svm_set_cr0 (vcpu, svm->nested.save.cr0);
Greg Kroah-Hartman
maintainerPATCH 713/3318 KVM: Use goto to handle errors during memslot preparation
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 23a205797cec86f391d0be886b9bc741e1262063 upstream.
Use a goto to unwind early memslot changes if preparing for a memslot operation fails. This will allow moving the creation of guest_memfd bindings into kvm_set_memslot() without needing to copy+paste the unwind logic.
No functional change intended.
--- virt/kvm/kvm_main.c | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-)
virt/kvm/kvm_main.c +16 -15
@@ -1877,21 +1877,8 @@ static int kvm_set_memslot(struct kvm *k } r =kvm_prepare_memory_region (kvm, old, new, change); -if (r) { -/* -* For DELETE/MOVE, revert the above INVALID change. No -* modifications required since the original slot was preserved -* in the inactive slots. Changing the active memslots also -* release slots_arch_lock. -*/ -if (change ==KVM_MR_DELETE || change ==KVM_MR_MOVE ) { -kvm_activate_memslot (kvm, invalid_slot, old); -kfree (invalid_slot); - }else { -mutex_unlock (&kvm->slots_arch_lock); - } -return r; - } +if (r) + goto err;/* * For DELETE and MOVE, the working slot is now active as the INVALID
@@ -1923,6 +1910,20 @@ static int kvm_set_memslot(struct kvm *kkvm_commit_memory_region (kvm, old, new, change);return 0 ; + +err: +/* +* For DELETE/MOVE, revert the above INVALID change. No modifications +* required since the original slot was preserved in the inactive slots. +* Changing the active memslots also release slots_arch_lock. +*/ +if (change ==KVM_MR_DELETE || change ==KVM_MR_MOVE ) { +kvm_activate_memslot (kvm, invalid_slot, old); +kfree (invalid_slot); + }else { +mutex_unlock (&kvm->slots_arch_lock); + } +return r; } static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id,
Greg Kroah-Hartman
maintainerPATCH 714/3318 KVM: x86/mmu: Bug the VM if KVM attempts to walk more levels than the MMU has
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 115f9405a2ed6d78ee7ad8436bdd638743f6d1d4 upstream.
Extend the "EFER.LMA && !CR4.PAE" check, which exists largely to guard against KVM configuring a paging32 MMU with more than 2 levels of paging, with a very explicit check for exactly that: that KVM isn't trying to walk more levels of paging than the MMU template provides. I.e. harden KVM against all bugs that would cause KVM to generates accesses beyond the bounds of guest_walker's arrays, regardless of how KVM ended up with the misconfigured MMU.
Note, don't use w->cpu_role.base.level directly as the paging64 template only provides two levels of page tables for PAE paging on 32-bit hosts, and handles the third level by manually emulating the PDPTR access.
--- arch/x86/kvm/mmu/paging_tmpl.h | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-)
arch/x86/kvm/mmu/paging_tmpl.h +7 -6
@@ -349,13 +349,14 @@ retry_walk: pte_access = ~0 ;/* -* Queue a page fault for injection if this assertion fails, as callers -* assume that walker.fault contains sane info on a walk failure. I.e. -* avoid making the situation worse by inducing even worse badness -* between when the assertion fails and when KVM kicks the vCPU out to -* userspace (because the VM is bugged). +* Queue a page fault for injection if any of the below assertions fail, +* as callers assume that walker.fault contains sane info on a walk +* failure. I.e. avoid making the situation worse by inducing even +* worse badness between when the assertion fails and when KVM kicks +* the vCPU out to userspace (because the VM is bugged). */ -if (KVM_BUG_ON (is_long_mode (vcpu) && !is_pae (vcpu), vcpu->kvm)) +if (KVM_BUG_ON (is_long_mode (vcpu) && !is_pae (vcpu), vcpu->kvm) || +KVM_BUG_ON (walker->max_level >PT_MAX_FULL_LEVELS , vcpu->kvm)) goto error; ++walker->level;
Greg Kroah-Hartman
maintainerPATCH 715/3318 KVM: x86/mmu: Bug the VM if KVM calcs a CPU role with EFER.LMA=1 && CR4.PAE=0
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 34dacbe7ae93f2d3c26cd0bf3e08200b1fa2c180 upstream.
Bug the VM if KVM attempts to construct a CPU role with the should-be- impossible combination of long mode being active without PAE paging being enabled. KVM's MMU construction assumes that EFER.LMA can be set if and only CR4.PAE is set, and will create a completely invalid MMU if that assumption fails. FNAME(walk_addr_generic) already has sanity checks to try and mitigate the fallout, but attempt to catch such bugs earlier, as this is (at least) the second time KVM has had bugs that escaped into FNAME(walk_addr_generic), and it's entirely possible the bad state could cause problems elsewhere.
--- arch/x86/kvm/mmu/mmu.c | 3 +++ 1 file changed, 3 insertions(+)
arch/x86/kvm/mmu/mmu.c +3 -0
@@ -5137,6 +5137,9 @@ static union kvm_cpu_role kvm_calc_cpu_rreturn role; } +if (KVM_BUG_ON (____is_efer_lma (regs) && !____is_cr4_pae (regs), vcpu->kvm)) + *(u64 *)®s->efer &= ~EFER_LMA ; + role.base.efer_nx =____is_efer_nx (regs); role.base.cr0_wp =____is_cr0_wp (regs); role.base.smep_andnot_wp =____is_cr4_smep (regs) && !____is_cr0_wp (regs);
Greg Kroah-Hartman
maintainerPATCH 716/3318 KVM: x86/xen: Take kvm->srcu in __kvm_xen_has_interrupt()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Woodhouse <[email protected]>
commit aa8ad943f242ef14d136c5440b1178de77466c9e upstream.
kvm_gpc_check() checks the cached memslot generation against the current one, which dereferences kvm->memslots and therefore requires kvm->srcu to be held. __kvm_xen_has_interrupt() does not take it.
Most callers do happen to hold kvm->srcu, but not all of them:
- kvm_emulate_halt() on the VM-Exit path, via kvm_vcpu_has_events() and kvm_cpu_has_extint(). vcpu_enter_guest() drops the vCPU's SRCU lock before entering the guest, so it is not held on the way back out.
- kvm_vcpu_block() -> kvm_vcpu_check_block() -> kvm_arch_vcpu_runnable(), which is the case the existing comment in this function describes.
On a PROVE_RCU kernel the former produces:
WARNING: suspicious RCU usage
include/linux/kvm_host.h:1092 suspicious rcu_dereference_check() usage!
...
kvm_gpc_check+0x344/0x3e0 [kvm] __kvm_xen_has_interrupt+0x83/0x310 [kvm] kvm_cpu_has_extint+0x1ff/0x370 [kvm] kvm_cpu_has_interrupt+0x16/0x100 [kvm] kvm_vcpu_has_events+0x4ce/0x690 [kvm] kvm_emulate_halt+0x52/0x1f0 [kvm] vmx_vcpu_run+0x988/0x2630 [kvm_intel]
Use guard(srcu) so that the three existing early returns don't each need an explicit unlock. SRCU read sections nest, so this is harmless on the paths which already hold it, and srcu_read_lock() does not sleep, so it is also safe in the atomic case which this function already handles.
--- arch/x86/kvm/xen.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
arch/x86/kvm/xen.c +10 -0
@@ -571,6 +571,16 @@ int __kvm_xen_has_interrupt(struct kvm_vBUILD_BUG_ON (sizeof (rc) != sizeof_field(struct compat_vcpu_info, evtchn_upcall_pending)); +/* +* kvm_gpc_check() checks the memslot generation, so kvm->srcu must be +* held. Most callers hold it already, but this is also reached from +* kvm_emulate_halt() on the VM-Exit path and from kvm_vcpu_block(), +* where vcpu_enter_guest() has already dropped the vCPU's SRCU lock. +* Taking SRCU does not sleep, so it is safe even in the atomic case +* which is handled below. +*/ +guard (srcu)(&v->kvm->srcu); +read_lock_irqsave (&gpc->lock, flags);while (!kvm_gpc_check (gpc,sizeof (struct vcpu_info ))) {read_unlock_irqrestore (&gpc->lock, flags);
Greg Kroah-Hartman
maintainerPATCH 717/3318 KVM: x86: Preserve DR6.BLD (Bus Lock Detect) when delivering #DB payload
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 719a1d58bf43edd03b271df90b67c58c1e9a7da4 upstream.
Preserve Bus Lock Detect if it isn't present in the payload. Unlike RTM, which is explicitly modified on every #DB, DR6.BLD is modified if and only if the #DB is due to a (coincident) Bus Lock Detect.
Per Intel's SDM:
Other debug exceptions do not modify this bit.
And AMD's APM
All other #DB exceptions leave DR6[BLD] unmodified,
Restore the explicit RTM handling that was clobbered by commit 9a3ecd5e2aa1 ("KVM: X86: Rename DR6_INIT to DR6_ACTIVE_LOW"), as the semantics of any given bit are feature specific, i.e. are obviously not consistent for active-high versus active-low. In other words, while the bug was technically introduced when support for Bus Lock Detect was added, it's really that attempt to genericize handling of active-low bits that set KVM up to fail.
--- arch/x86/kvm/x86.c | 52 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 22 deletions(-)
arch/x86/kvm/x86.c +30 -22
@@ -570,30 +570,37 @@ void kvm_deliver_exception_payload(strucswitch (ex->vector) {case DB_VECTOR :/* -* "Certain debug exceptions may clear bit 0-3. The -* remaining contents of the DR6 register are never -* cleared by the processor". -*/ - vcpu->arch.dr6 &= ~DR_TRAP_BITS ; -/* -* In order to reflect the #DB exception payload in guest -* dr6, three components need to be considered: active low -* bit, FIXED_1 bits and active high bits (e.g. DR6_BD, -* DR6_BS and DR6_BT) -* DR6_ACTIVE_LOW contains the FIXED_1 and active low bits. -* In the target guest dr6: -* FIXED_1 bits should always be set. -* Active low bits should be cleared if 1-setting in payload. -* Active high bits should be set if 1-setting in payload. +* DR6 is a mess. Reserved/unused bits are fixed-to-1, and so +* to maintain backwards compatibility with existing software, +* features that use previously-reserved bits have active-low +* semantics, i.e. clear the bit when the feature is present in +* the payload. +* +* Further complicating matters, some DR6 bits are preserved by +* hardware, while others are explicitly modified on every #DB. +* The trap bits are always set based on the payload, as is the +* RTM flag (but it's active low). All other bits are modified +* if and only if a relevant debug exception occurs, e.g. BD, +* BS, and BT are never cleared by hardware, and BLD is never +* set by hardware (when supported, excepting RESET). * -* Note, the payload is compatible with the pending debug -* exceptions/exit qualification under VMX, that active_low bits -* are active high in payload. -* So they need to be flipped for DR6. +* Lastly, the payload does NOT have active-low semantics, e.g. +* so that it's compatible VMX's pending debug exceptions and +* qualification fields, and to avoid bleeding the DR6 madness +* into other KVM code. +* +* To compute DR6: +* +* 1. "Reset" the bits that are modified on all #DBs +* 2. Clear active-low bits that are present in the payload. +* 3. Set active-high bits that are present in the payload. +* 4. Clear fixed-0 bits. +* 5. Set fixed-1 bits. */ - vcpu->arch.dr6 |=DR6_ACTIVE_LOW ; - vcpu->arch.dr6 |= ex->payload; - vcpu->arch.dr6 ^= ex->payload &DR6_ACTIVE_LOW ; + vcpu->arch.dr6 &= ~DR_TRAP_BITS ; + vcpu->arch.dr6 |=DR6_RTM ; + vcpu->arch.dr6 &= ~(ex->payload &DR6_ACTIVE_LOW ); + vcpu->arch.dr6 |= (ex->payload & ~DR6_ACTIVE_LOW );/* * The #DB payload is defined as compatible with the 'pending
@@ -602,6 +609,7 @@ void kvm_deliver_exception_payload(struc* breakpoint), it is reserved and must be zero in DR6. */ vcpu->arch.dr6 &= ~BIT (12 ); + vcpu->arch.dr6 |=DR6_FIXED_1 ;break ;case PF_VECTOR : vcpu->arch.cr2 = ex->payload;
Greg Kroah-Hartman
maintainerPATCH 718/3318 KVM: x86: Request event processing for exception VM-Exits
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Loc Nguyen <[email protected]>
commit 88b23a2e8286b7016c3b58dc10093cf28c22aa3d upstream.
Request event processing whenever kvm_queue_exception_vmexit() queues an exception VM-Exit. Most callers reach the helper through kvm_multiple_exception(), which already sets KVM_REQ_EVENT, but nested asynchronous page faults call it directly.
Without another event request, vcpu_enter_guest() skips kvm_check_and_inject_events() and re-enters L2. A subsequent VM-Exit can clear the pending exception while reconstructing vectoring state, losing the synthetic #PF VM-Exit. The APF reason remains PAGE_NOT_PRESENT and a later regular #PF can consume the stale value.
Setting KVM_REQ_EVENT in the common helper ensures that L1 receives the queued VM-Exit before KVM re-enters L2.
--- arch/x86/kvm/x86.c | 2 ++ 1 file changed, 2 insertions(+)
arch/x86/kvm/x86.c +2 -0
@@ -627,6 +627,8 @@ static void kvm_queue_exception_vmexit(s {struct kvm_queued_exception *ex = &vcpu->arch.exception_vmexit; +kvm_make_request (KVM_REQ_EVENT , vcpu); + ex->vector = vector; ex->injected = false; ex->pending = true;
Greg Kroah-Hartman
maintainerPATCH 719/3318 KVM: x86: Zero reserved synic flags when delivering message to avoid stack leak
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 2616f497506a772db53e7bb1024cde50b4c165e0 upstream.
Ensure all reserved flags are zeroed when setting the msg_pending flag as part of SynIC message delivery, as setting only msg_pending can leak seven bits of kernel stack data to the guest. E.g. gcc typically uses a bitwise-OR to set the msg_pending flag, without initializing the on-stack variable.
Precisely zero the flags, e.g. as opposed to zeroing the entire structure, to make it somewhat more obvious that the flags *need* to be zeroed. E.g. it would be quite easy to misread the initial read of guest memory and think that zeroing the entire structure is completely superfluous.
--- arch/x86/kvm/hyperv.c | 2 ++ 1 file changed, 2 insertions(+)
arch/x86/kvm/hyperv.c +2 -0
@@ -794,7 +794,9 @@ static int synic_deliver_msg(struct kvm_if (no_retry)return 0 ; + hv_hdr.message_flags.asu8 =0 ; hv_hdr.message_flags.msg_pending =1 ; + r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn, &hv_hdr.message_flags, msg_off +
Greg Kroah-Hartman
maintainerPATCH 720/3318 KVM: PPC: Book3S HV: Add preempt_disable() around virtual-mode HPTE bit-lock users
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit abbbe5ff83e7c9ed3a4d61b73011f1df7bf87907 upstream.
kvmppc_hv_find_lock_hpte() requires virtual-mode callers to run with preemption disabled, because it can return with HPTE_V_HVLOCK still held until the caller later unlocks the HPTE. Existing virtual-mode callers in book3s_64_mmu_hv.c already follow that rule.
Two virtual-mode call paths do not:
1. kvmppc_handle_exit_hv() calls kvmppc_hpte_hv_fault() for hash-mode data-side and instruction-side faults after guest exit, with preemption already enabled. kvmppc_hpte_hv_fault() calls kvmppc_hv_find_lock_hpte() directly.
2. kvmppc_pseries_do_hcall() executes virtual-mode handlers for HPT hcalls via kvmppc_pseries_do_hpt_hcall() with preemption enabled. The handlers for H_ENTER, H_REMOVE, H_READ, H_CLEAR_MOD, H_CLEAR_REF, H_PROTECT, and H_BULK_REMOVE spin on try_lock_hpte() or lock_rmap(), and H_ENTER also reaches kvmppc_do_h_enter(), which uses arch_spin_lock() on kvm->mmu_lock. That raw lock choice is intentional because kvmppc_do_h_enter() is also used by real-mode callers, so the correct fix is to establish the proper preemption context at the virtual-mode caller boundary.
If a vCPU thread is preempted while holding HPTE_V_HVLOCK, any other thread on the same CPU trying to acquire the same bit-lock can spin indefinitely. The same applies to lock_rmap() users and to the H_ENTER path while holding the raw mmu_lock.
Fix this by adding preempt_disable()/preempt_enable() pairs around the two kvmppc_hpte_hv_fault() call sites in kvmppc_handle_exit_hv(), and around the kvmppc_pseries_do_hpt_hcall() invocation in kvmppc_pseries_do_hcall(). Targeting only the HPT hcall helper avoids wrapping non-HPT hcalls (such as H_RTAS, H_CONFER, H_REGISTER_VPA) that perform page faults, blocking memory allocations, or context switches.
--- arch/powerpc/kvm/book3s_hv.c | 6 ++++++ 1 file changed, 6 insertions(+)
arch/powerpc/kvm/book3s_hv.c +6 -0
@@ -1141,9 +1141,11 @@ int kvmppc_pseries_do_hcall(struct kvm_vcase H_CLEAR_REF :case H_PROTECT :case H_BULK_REMOVE : +preempt_disable (); idx =srcu_read_lock (&kvm->srcu); ret =kvmppc_pseries_do_hpt_hcall (vcpu, req);srcu_read_unlock (&kvm->srcu, idx); +preempt_enable ();if (ret ==H_TOO_HARD )return RESUME_HOST ;break ;
@@ -1759,8 +1761,10 @@ static int kvmppc_handle_exit_hv(structelse vsid = vcpu->arch.fault_gpa; +preempt_disable (); err =kvmppc_hpte_hv_fault (vcpu, vcpu->arch.fault_dar, vsid, vcpu->arch.fault_dsisr, true); +preempt_enable ();if (err ==0 ) { r =RESUME_GUEST ; }else if (err ==-1 || err ==-2 ) {
@@ -1806,8 +1810,10 @@ static int kvmppc_handle_exit_hv(structelse vsid = vcpu->arch.fault_gpa; +preempt_disable (); err =kvmppc_hpte_hv_fault (vcpu, vcpu->arch.fault_dar, vsid, vcpu->arch.fault_dsisr, false); +preempt_enable ();if (err ==0 ) { r =RESUME_GUEST ; }else if (err ==-1 ) {
Greg Kroah-Hartman
maintainerPATCH 721/3318 KVM: PPC: Fix get_d_signext() 12-bit displacement for paired-single D-form
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 31895b0ff96778b524c74b43a108090581271603 upstream.
get_d_signext() has two compounding bugs since its introduction in 2010:
1. The extraction mask 0x8FF silently drops bits 8-10 of the 12-bit D field (PPC ISA bits 21-23), corrupting any displacement that has any of those bits set.
2. The sign-magnitude idiom "-(d & 0x7ff)" is wrong for two's-complement:
for D=0xFFC (encoding of -4) it returns -252 instead of -4.
Together these errors produce a wrong effective address for psq_l, psq_lu, psq_st, and psq_stu whenever the displacement is negative or is a positive value >= 0x100 with bits 8-10 set — essentially any real-world paired- single stack-relative access.
The D field occupies the bottom 12 bits of the instruction word (confirmed by the adjacent W and I extractions via inst_get_field(inst,16,16) and inst_get_field(inst,17,19)). Replace the open-coded logic with the standard sign_extend32(inst & 0xfff, 11), which correctly performs two's-complement sign extension from 12 bits to 32 bits.
--- arch/powerpc/kvm/book3s_paired_singles.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-)
arch/powerpc/kvm/book3s_paired_singles.c +1 -6
@@ -479,12 +479,7 @@ static bool kvmppc_inst_is_paired_singlestatic int get_d_signext (u32 inst) { -int d = inst &0x8ff ; - -if (d &0x800 ) -return -(d &0x7ff ); - -return (d &0x7ff ); +return sign_extend32 (inst &0xfff ,11 ); } static int kvmppc_ps_three_in(struct kvm_vcpu *vcpu, bool rc,
Greg Kroah-Hartman
maintainerPATCH 722/3318 HID: zydacron: validate key report length
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 9932c9af185f8586e883d44ca562c12f4487c762 upstream.
The HID core invokes raw_event callbacks before validating the report length. zc_raw_event() verifies the report ID in byte zero and then reads the key code from byte one for report IDs 0x02 and 0x03 without checking that the second byte is present.
A one-byte report reproduced the issue under KASAN:
BUG: KASAN: slab-out-of-bounds in zc_raw_event+0x54c/0x580 Read of size 1 by task hidtrigger/93 Call Trace: zc_raw_event+0x54c/0x580 __hid_input_report+0x2ef/0x3a0 inject_store+0x479/0x490 [faketrans]
Require both the report ID and key code before processing the report.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-zydacron.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-zydacron.c +3 -0
@@ -114,6 +114,9 @@ static int zc_raw_event(struct hid_devicunsigned key;unsigned short index; +if (size <2 ) +return 0 ; +if (report->id == data[0 ] && (hdev->claimed &HID_CLAIMED_INPUT )) {/* break keys */
Greg Kroah-Hartman
maintainerPATCH 723/3318 HID: amd_sfh: Remove unsupported motion-state field from accelerometer report
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Basavaraj Natikar <[email protected]>
commit 6ff86122906357687735dd379c6279e3b2fa26af upstream.
The accelerometer HID report descriptor declares a trailing motion-state field (usage 0x0451), but the Sensor Fusion Hub never reports this data, so each accelerometer input report is one byte shorter than the descriptor advertises.
This was previously harmless because hid-core zero-padded short reports. Since commit 0a3fe972a7cb ("HID: core: Mitigate potential OOB by removing bogus memset()") such reports are rejected instead:
hid-sensor-hub 0020:1022:0001.0003: Event data for report 1 was too short (15 vs 14)
As a result the accelerometer input events are dropped and screen auto-rotation stops working on AMD SFH systems.
Remove the motion-state field from the accelerometer report descriptor and drop the unused in_accel_shake_detection member, so the descriptor matches the report actually provided by the hardware.
--- drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_desc.h | 2 -- drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_report_desc.h | 7 ------- 2 files changed, 9 deletions(-)
drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_desc.h +0 -2
@@ -48,8 +48,6 @@ struct accel3_input_report {int in_accel_x_value;int in_accel_y_value;int in_accel_z_value; -/* include if required to support the "shake" event */ -u8 in_accel_shake_detection; } __packed;struct gyro_feature_report {
drivers/hid/amd-sfh-hid/hid_descriptor/amd_sfh_hid_report_desc.h +0 -7
@@ -169,13 +169,6 @@ static const u8 accel3_report_descriptor0x95 ,1 ,/* HID report count (1) */ 0x55 ,0x0E ,/* HID unit exponent(0x0E) */ 0X81 ,0x02 ,/* HID Input (Data_Arr_Abs) */ - -0x0A ,0x51 ,0x04 ,/* HID usage sensor data motion state */ -0x15 ,0 ,/* HID logical Min_8(0) False = Still*/ -0x25 ,1 ,/* HID logical Min_8(1) True = In motion */ -0x75 ,8 ,/* HID report size(8) */ -0x95 ,1 ,/* HID report count (1) */ -0X81 ,0x02 ,/* HID Input (Data_Arr_Abs) */ 0xC0 /* HID end collection */ };
Greg Kroah-Hartman
maintainerPATCH 724/3318 HID: amd_sfh: Use report type from request node
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Basavaraj Natikar <[email protected]>
commit 85f1bea97f1909f81577cfcf3e4db9017e7f5337 upstream.
Use report type from request node while sending feature and input reports to HID core. The cli_data report type array is never assigned and feature reports are sent as input reports.
--- drivers/hid/amd-sfh-hid/amd_sfh_client.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hid/amd-sfh-hid/amd_sfh_client.c +2 -2
@@ -90,7 +90,7 @@ void amd_sfh_work(struct work_struct *wo cli_data->feature_report[current_index]);if (report_size)hid_input_report (cli_data->hid_sensor_hubs[current_index], - cli_data->report_type[current_index], + node_type, cli_data->feature_report[current_index], report_size,0 );else pr_err ("AMDSFH: Invalid report size\n" );
@@ -99,7 +99,7 @@ void amd_sfh_work(struct work_struct *wo report_size = mp2_ops->get_in_rep (current_index, sensor_index, report_id, in_data);if (report_size)hid_input_report (cli_data->hid_sensor_hubs[current_index], - cli_data->report_type[current_index], + node_type, in_data->input_report[current_index], report_size,0 );else pr_err ("AMDSFH: Invalid report size\n" );
Greg Kroah-Hartman
maintainerPATCH 725/3318 HID: core: Fix out-of-bounds left shift by 32 in s32ton()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alan Stern <[email protected]>
commit 5fe63b415c636c7f4f6848a8e53bdd4bbf0c300d upstream.
Syzbot reported an out-of-bounds shift (32-bit integer shifted left by
32) in the s32ton() routine in the HID core. This routine converts a signed 32-bit integer to a signed n-bit integer, and it caps the value of n at 32. But when n == 32 there's no need to do anything; it can simply return the input value. This will avoid calculating (1 << n) when n is 32, which was the cause of the invalid shift.
--- drivers/hid/hid-core.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hid/hid-core.c +2 -2
@@ -1366,8 +1366,8 @@ static u32 s32ton(__s32 value, unsignedif (!value || !n)return 0 ; -if (n >32 ) - n =32 ; +if (n >=32 ) +return (u32 ) value; a = value >> (n -1 );if (a && a !=-1 )
Greg Kroah-Hartman
maintainerPATCH 726/3318 HID: cougar: reject short special-key reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit c6c0df8a4b73a0d563c5e64de640ef5ff525fc82 upstream.
The HID core invokes raw_event callbacks before validating the report length. cougar_raw_event() reads the key code and action from offsets one and two without checking that those bytes are present. A short report on the special interface can therefore cause an out-of-bounds read.
Consume reports that do not contain the action field before accessing the fixed offsets, consistent with the callback's handling of other reports on the special interface.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-cougar.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-cougar.c +3 -0
@@ -270,6 +270,9 @@ static int cougar_raw_event(struct hid_dif (!shared->enabled || !shared->input)return -EPERM ; +if (size <=COUGAR_FIELD_ACTION ) +return -EPERM ; + code = data[COUGAR_FIELD_CODE ]; action = data[COUGAR_FIELD_ACTION ];for (i =0 ; cougar_mapping[i][0 ]; i++) {
Greg Kroah-Hartman
maintainerPATCH 727/3318 HID: cp2112: validate response report lengths
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit fc54e71a063c0dcc4bceba6d0f71805a9b84082d upstream.
The HID core invokes raw_event callbacks before validating the report length. cp2112_raw_event() reads every field of a transfer status response without checking size. For a data response, it reads the length at offset two and copies that many bytes from offset three, again without ensuring that the input report contains them.
Require a complete transfer status structure. For data responses, first require the header and then ensure the clamped payload length fits in the received report before copying it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-cp2112.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
drivers/hid/hid-cp2112.c +8 -1
@@ -1372,6 +1372,9 @@ static int cp2112_raw_event(struct hid_dswitch (data[0 ]) {case CP2112_TRANSFER_STATUS_RESPONSE : +if (size <sizeof (*xfer)) +return 0 ; +hid_dbg (hdev,"xfer status: %02x %02x %04x %04x\n" , xfer->status0, xfer->status1,be16_to_cpu (xfer->retries),be16_to_cpu (xfer->length));
@@ -1405,11 +1408,16 @@ static int cp2112_raw_event(struct hid_datomic_set (&dev->xfer_avail,1 );break ;case CP2112_DATA_READ_RESPONSE : +if (size <3 ) +return 0 ; +hid_dbg (hdev,"read response: %02x %02x\n" , data[1 ], data[2 ]); dev->read_length = data[2 ];if (dev->read_length >sizeof (dev->read_data)) dev->read_length =sizeof (dev->read_data); +if (dev->read_length > size -3 ) +return 0 ;memcpy (dev->read_data, &data[3 ], dev->read_length);atomic_set (&dev->read_avail,1 );
@@ -1436,4 +1444,3 @@ module_hid_driver(cp2112_driver);MODULE_DESCRIPTION ("Silicon Labs HID USB to SMBus master bridge" );MODULE_AUTHOR ("David Barksdale <[email protected]>" );MODULE_LICENSE ("GPL" ); -
Greg Kroah-Hartman
maintainerPATCH 728/3318 HID: elo: reject short touchscreen reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1cb92fcb2ac344d78737e3c5cb7b061dfb2850b1 upstream.
The HID core invokes raw_event callbacks before validating the report length. elo_raw_event() only checks the first-byte packet marker before elo_process_data() reads coordinates, flags, and pressure through offset seven. A truncated packet beginning with the expected marker can therefore cause an out-of-bounds read.
Require the complete eight-byte SmartSet packet before parsing it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-elo.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-elo.c +3 -0
@@ -85,6 +85,9 @@ static int elo_raw_event(struct hid_deviif (!(hdev->claimed &HID_CLAIMED_INPUT ) ||list_empty (&hdev->inputs))return 0 ; +if (size <ELO_SMARTSET_PACKET_SIZE ) +return 0 ; + hidinput = list_first_entry(&hdev->inputs, struct hid_input, list);switch (report->id) {
Greg Kroah-Hartman
maintainerPATCH 729/3318 HID: logitech-dj: validate unnumbered keyboard reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit c2deafcb4c8227771f768d77ed3c0a489250e9b2 upstream.
The HID core invokes raw_event callbacks before validating the report length. For an unnumbered keyboard report, logi_dj_raw_event() uses the second byte as temporary storage while prepending a report ID. A one-byte report therefore makes both the initial write and the later restoration access data beyond the received report.
Reject unnumbered keyboard reports that do not provide the temporary byte.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-logitech-dj.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-logitech-dj.c +3 -0
@@ -1682,6 +1682,9 @@ static int logi_dj_raw_event(struct hid_if (!hdev->report_enum[HID_INPUT_REPORT ].numbered) {if (djrcv_dev->unnumbered_application ==HID_GD_KEYBOARD ) { +if (size <2 ) +return false; +/* * For the keyboard, we can reuse the same report by * using the second byte which is constant in the USB
Greg Kroah-Hartman
maintainerPATCH 730/3318 HID: mcp2200: validate READ_ALL response length
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 26ce0e6bf0b27fc6a2f490f38555dfd0a27c9605 upstream.
The HID core invokes raw_event callbacks before validating the report length. mcp2200_raw_event() casts a READ_ALL response to struct mcp_read_all_resp and reads fields through offset ten without checking that the response contains the structure.
A one-byte READ_ALL response reproduced the issue under KASAN:
BUG: KASAN: slab-out-of-bounds in mcp2200_raw_event+0x24b/0x3a0 Read of size 1 by task hidtrigger/89 Call Trace: mcp2200_raw_event+0x24b/0x3a0 kasan_report+0x139/0x170
Reject an incomplete READ_ALL response with a protocol error before reading its fields. The common completion path then wakes the command waiter with the error instead of leaving it to time out.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-mcp2200.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/hid/hid-mcp2200.c +5 -0
@@ -296,6 +296,11 @@ static int mcp2200_raw_event(struct hid_switch (data[0 ]) {case READ_ALL : +if (size <sizeof (*all_resp)) { + mcp->status = -EPROTO ; +break ; + } + all_resp = (struct mcp_read_all_resp *) data; mcp->status =0 ; mcp->gpio_inval = all_resp->io_port_val_bmap;
Greg Kroah-Hartman
maintainerPATCH 731/3318 HID: mcp2221: validate response report length
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1ae40774d386b7a51e4799200106429a7e14e8ec upstream.
MCP2221 responses are 64-byte reports, but mcp2221_raw_event() currently accepts any report of at least four bytes. Several response handlers read far beyond that minimum. In particular, the I2C status response reads offset 20 and copies ADC samples starting at offset 50. Other GPIO, SRAM, and flash response handlers also access fixed offsets beyond byte three.
The HID core invokes raw_event callbacks before validating the report length, so a truncated response can cause an out-of-bounds read. Require a complete protocol report before dispatching any response handler.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-mcp2221.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/hid-mcp2221.c +1 -1
@@ -768,7 +768,7 @@ static int mcp2221_raw_event(struct hid_u8 *buf;struct mcp2221 *mcp =hid_get_drvdata (hdev); -if (size <4 ) +if (size <sizeof (mcp->txbuf))return 0 ;switch (data[0 ]) {
Greg Kroah-Hartman
maintainerPATCH 732/3318 HID: picoLCD: check for fb_deferred_io_init() error
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
commit feade898fc958ff355101adf12d5632272e64220 upstream.
fb_deferred_io_init() allocates deferred I/O state, populating info->fbdefio_state, or leaving it NULL if an error occurs.
Currently picolcd_init_framebuffer() ignores its return value.
Therefore if an error arises in fb_deferred_io_init() (for instance, due to an allocation failure) info->fbdefio_state is left NULL.
When the file is subsequently opened, fb_open() will dereference a NULL pointer (calling fb_deferred_io_open()).
Fix this by checking for the error.
Also correct cleanup ordering - defio is initialised after the sysfs file, so cleanup defio first.
--- drivers/hid/hid-picolcd_fb.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/hid/hid-picolcd_fb.c +9 -3
@@ -557,17 +557,23 @@ int picolcd_init_framebuffer(struct pico goto err_cleanup; } -fb_deferred_io_init (info); + error =fb_deferred_io_init (info); +if (error) { +dev_err (dev,"failed to initialize deferred I/O\n" ); + goto err_sysfs; + } + error =register_framebuffer (info);if (error) {dev_err (dev,"failed to register framebuffer\n" ); - goto err_sysfs; + goto err_defio; }return 0 ; +err_defio: +fb_deferred_io_cleanup (info); err_sysfs:device_remove_file (dev, &dev_attr_fb_update_rate); -fb_deferred_io_cleanup (info); err_cleanup: data->fb_info =NULL ;
Greg Kroah-Hartman
maintainerPATCH 733/3318 HID: pxrc: reject short input reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 0deb22da5a8c6663c3e071f55fd7d7e3189f5517 upstream.
The HID core invokes raw_event callbacks before validating the report length. pxrc_raw_event() reads byte seven and writes bytes one and seven without checking that the report contains those bytes.
A one-byte input report reproduced the first invalid access under KASAN:
BUG: KASAN: slab-out-of-bounds in pxrc_raw_event+0x161/0x260 Read of size 1 by task hidtrigger/90 Call Trace: pxrc_raw_event+0x161/0x260 kasan_report+0x139/0x170
Require all eight bytes before reading or rewriting the report.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-pxrc.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-pxrc.c +3 -0
@@ -55,6 +55,9 @@ static int pxrc_raw_event(struct hid_dev {struct pxrc_priv *priv =hid_get_drvdata (hdev); +if (size <8 ) +return 0 ; +if (priv->alternate) priv->slider = data[7 ];else
Greg Kroah-Hartman
maintainerPATCH 734/3318 HID: quirks: Always poll the Anne Pro 2 with product ID a292
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gabor Tanz <[email protected]>
commit cbc13a78a89d087252947d0a51048e576cfcb3ef upstream.
The wired Anne Pro 2 identifying as 04d9:a292 stops delivering keyboard input after a period of inactivity. Unplugging and reconnecting the keyboard restores input.
Keeping ObinsKit running prevents the problem. A read-only userspace reader that keeps USB HID interface 1 open also prevents it, as does usbhid.quirks=0x04d9:0xa292:0x00000400 without either application running.
Commit ca28aff0e1dc ("HID: quirks: Always poll Obins Anne Pro 2 keyboard") added HID_QUIRK_ALWAYS_POLL for product ID a293. The variant identifying as 04d9:a292 exhibits the same symptom. Apply the quirk to this product ID as well.
--- drivers/hid/hid-ids.h | 1 + drivers/hid/hid-quirks.c | 1 + 2 files changed, 2 insertions(+)
drivers/hid/hid-ids.h +1 -0
@@ -704,6 +704,7 @@#define USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A081 0xa081#define USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A0C2 0xa0c2#define USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A096 0xa096 +#define USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A292 0xa292#define USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A293 0xa293#define USB_VENDOR_ID_IMATION 0x0718
drivers/hid/hid-quirks.c +1 -0
@@ -102,6 +102,7 @@ static const struct hid_device_id hid_qu { HID_USB_DEVICE(USB_VENDOR_ID_HAPP, USB_DEVICE_ID_UGCI_FIGHTING), HID_QUIRK_BADPAD | HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_HAPP, USB_DEVICE_ID_UGCI_FLYING), HID_QUIRK_BADPAD | HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A096), HID_QUIRK_NO_INIT_REPORTS }, + { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A292), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A293), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_HP, USB_PRODUCT_ID_HP_LOGITECH_OEM_USB_OPTICAL_MOUSE_0A4A), HID_QUIRK_ALWAYS_POLL }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_HP, USB_PRODUCT_ID_HP_ELITE_PRESENTER_MOUSE_464A), HID_QUIRK_MULTI_INPUT },
Greg Kroah-Hartman
maintainerPATCH 735/3318 HID: roccat: isku: reject short button reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 93e5f7f6189af76a2b2e2dfe647838a7b9f99d21 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and, for a button report, read the complete struct isku_report_button. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-isku.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-isku.c +3 -0
@@ -411,6 +411,9 @@ static int isku_raw_event(struct hid_devif (isku ==NULL )return 0 ; +if (size <sizeof (struct isku_report_button )) +return 0 ; +isku_keep_values_up_to_date (isku, data);if (isku->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 736/3318 HID: roccat: koneplus: reject short button reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit d879e17a8b4c572c0b53b4e42a36849484e8f00c upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and, for a button report, read the complete struct koneplus_mouse_report_button. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-koneplus.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-koneplus.c +3 -0
@@ -523,6 +523,9 @@ static int koneplus_raw_event(struct hidif (koneplus ==NULL )return 0 ; +if (size <sizeof (struct koneplus_mouse_report_button )) +return 0 ; +koneplus_keep_values_up_to_date (koneplus, data);if (koneplus->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 737/3318 HID: roccat: konepure: reject short button reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1590b7c9bea0abe7a5d25dbfe06287c48c238a6f upstream.
The raw event callback runs before HID core validates and zero-pads the report. It reads the report number without checking the received length and passes matching data to roccat_report_event(), which copies a complete struct konepure_mouse_report_button. A truncated report can therefore cause an out-of-bounds read and expose adjacent data through the Roccat character device.
Require a complete button report before inspecting or forwarding it. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-konepure.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-konepure.c +3 -0
@@ -181,6 +181,9 @@ static int konepure_raw_event(struct hid != USB_INTERFACE_PROTOCOL_MOUSE)return 0 ; +if (size <sizeof (struct konepure_mouse_report_button )) +return 0 ; +if (data[0 ] !=KONEPURE_MOUSE_REPORT_NUMBER_BUTTON )return 0 ;
Greg Kroah-Hartman
maintainerPATCH 738/3318 HID: roccat: kovaplus: reject short button reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit e95917a606f486e46f5136fc1b72190742a091d6 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and read a complete struct kovaplus_mouse_report_button for button reports. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-kovaplus.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-kovaplus.c +3 -0
@@ -614,6 +614,9 @@ static int kovaplus_raw_event(struct hidif (kovaplus ==NULL )return 0 ; +if (size <sizeof (struct kovaplus_mouse_report_button )) +return 0 ; +kovaplus_keep_values_up_to_date (kovaplus, data);if (kovaplus->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 739/3318 HID: roccat: pyra: reject short button reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 493268f459bb6aeeecbc77f2204c11ad74d05213 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and read a complete struct pyra_mouse_event_button for button reports. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-pyra.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-pyra.c +3 -0
@@ -557,6 +557,9 @@ static int pyra_raw_event(struct hid_devif (pyra ==NULL )return 0 ; +if (size <sizeof (struct pyra_mouse_event_button )) +return 0 ; +pyra_keep_values_up_to_date (pyra, data);if (pyra->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 740/3318 HID: roccat: ryos: reject short special reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 02f3607d0beb82e76481568bf631235e6a319b47 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It reads the report number without checking the received length and passes matching data to roccat_report_event(), which copies a complete struct ryos_report_special. A truncated report can therefore cause an out-of-bounds read and expose adjacent data through the Roccat character device.
Require a complete special report before inspecting or forwarding it. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-ryos.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-ryos.c +3 -0
@@ -189,6 +189,9 @@ static int ryos_raw_event(struct hid_dev != RYOS_USB_INTERFACE_PROTOCOL)return 0 ; +if (size <sizeof (struct ryos_report_special )) +return 0 ; +if (data[0 ] !=RYOS_REPORT_NUMBER_SPECIAL )return 0 ;
Greg Kroah-Hartman
maintainerPATCH 741/3318 HID: roccat: savu: reject short special reports
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 76c51fdc825a0486f8d88ff896d39acec8f377b4 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to a helper which inspects data[0] and, for a special report, reads the complete struct savu_mouse_report_special. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the special report before calling the helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-savu.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-savu.c +3 -0
@@ -182,6 +182,9 @@ static int savu_raw_event(struct hid_devif (savu ==NULL )return 0 ; +if (size <sizeof (struct savu_mouse_report_special )) +return 0 ; +if (savu->roccat_claimed)savu_report_to_chrdev (savu, data);
Greg Kroah-Hartman
maintainerPATCH 742/3318 ovl: take a snapshot of the name for copy up
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 65bf000962a33ec9d2488e4e1797b6cf630abcbb upstream.
The copy up of a directory reads a freed dentry name when a lookup moves the directory at the same time.
A pointer to the name of a dentry is only valid while something stops a move of the dentry. ovl_do_copy_up() keeps a plain copy of c->dentry->d_name in c->destname, and ovl_copy_up_start() only keeps ovl_rename() away. When a lookup finds the same directory under another name after a change to the lower layer, d_splice_alias() moves the dentry and frees its external name.
With a delay in ovl_do_copy_up(), a chmod of a lower-only directory with a 60 byte name raced with a rename of that directory in the lower layer and a stat of the new name, and KASAN reported a use-after-free in lookup_noperm_common().
Fix this by using take_dentry_name_snapshot() for c->destname.
[backport: destname is set in ovl_copy_up_one(), take the snapshot in
the non-index branch of ovl_do_copy_up() instead]
--- fs/overlayfs/copy_up.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +14 -2
@@ -867,6 +867,7 @@ static int ovl_do_copy_up(struct ovl_cop {int err;struct ovl_fs *ofs =OVL_FS (c->dentry->d_sb); +struct name_snapshot name;bool to_index = false;/*
@@ -896,12 +897,22 @@ static int ovl_do_copy_up(struct ovl_copreturn -EIO ; }else {/* +* ovl_copy_up_start() keeps ovl_rename() away from c->dentry, +* because ovl_rename() calls ovl_copy_up() on source and target +* dentry. It does not stop d_splice_alias() from moving a +* directory that a lookup found under another name after a +* change to the lower layer. That move frees an external name, +* so take a snapshot. +*/ +take_dentry_name_snapshot (&name, c->dentry); + c->destname = name.name; +/* * Mark parent "impure" because it may now contain non-pure * upper */ err =ovl_set_impure (c->parent, c->destdir);if (err) -return err; + goto out; }/* Should we copyup with O_TMPFILE or with workdir? */
@@ -933,6 +944,8 @@ static int ovl_do_copy_up(struct ovl_cop out:if (to_index)kfree (c->destname.name); +else +release_dentry_name_snapshot (&name);return err; }
@@ -1083,7 +1096,6 @@ static int ovl_copy_up_one(struct dentryif (parent) {ovl_path_upper (parent, &parentpath); ctx.destdir = parentpath.dentry; - ctx.destname = dentry->d_name; err = vfs_getattr(&parentpath, &ctx.pstat, STATX_ATIME | STATX_MTIME,
Greg Kroah-Hartman
maintainerPATCH 743/3318 ovl: use the pinned upper dir in ovl_fix_origin()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 4f61ff2ebfb3d2967b83b6a4d456242244d5a61f upstream.
Renames made directly on the upper filesystem during a lookup crash the kernel.
A dentry that is passed to vfs_setxattr() must be pinned. ovl_fix_origin() passes upper->d_parent to ovl_set_impure() without a reference, and the lookup holds no lock of the upper directory. A rename on the upper filesystem changes d_parent, and only the child pins the new parent, so a second rename and an rmdir free it.
With delays in ovl_fix_origin() and ovl_set_impure(), renaming the upper directory twice and removing the intermediate parent during the lookup of a merge directory without an origin xattr gave a KASAN use-after-free in vfs_setxattr().
Fix this by passing the upper dentry that the overlay parent holds.
---
[ backport: context: ovl_fix_origin() calls ovl_set_origin() ]
fs/overlayfs/namei.c | 6 ++++-- fs/overlayfs/overlayfs.h | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-)
fs/overlayfs/namei.c +4 -2
@@ -883,8 +883,10 @@ static int ovl_fix_origin(struct ovl_fsreturn err; err =ovl_set_origin (ofs, lower, upper); -if (!err) - err =ovl_set_impure (dentry->d_parent, upper->d_parent); +if (!err) { +/* upper->d_parent is not stable, use the overlay parent */ + err =ovl_set_impure_dir (dentry->d_parent); + }ovl_drop_write (dentry);return err;
fs/overlayfs/overlayfs.h +6 -0
@@ -492,6 +492,12 @@ int ovl_check_setxattr(struct ovl_fs *of enum ovl_xattr ox, const void *value, size_t size, int xerr);int ovl_set_impure (struct dentry *dentry,struct dentry *upperdentry); + +static inline int ovl_set_impure_dir (struct dentry *dentry) +{ +return ovl_set_impure (dentry,ovl_dentry_upper (dentry)); +} +bool ovl_inuse_trylock (struct dentry *dentry);void ovl_inuse_unlock (struct dentry *dentry);bool ovl_is_inuse (struct dentry *dentry);
Greg Kroah-Hartman
maintainerPATCH 744/3318 ovl: set OVL_WHITEOUTS before publishing the upper dir
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit cbec8610ec5aaf35df50094ff639febc23f20773 upstream.
Listing a directory while it is copied up causes a use-after-free of the readdir cache.
A merge directory must never be iterated as a real upper directory:
that mode frees the cache in OVL_I(inode)->cache without looking at its refcount, while files opened in merged mode still use it. ovl_copy_up_workdir() publishes the upper dentry before it sets OVL_WHITEOUTS, and ovl_dir_open() samples both without a lock, so an open between the two stores finds the upper directory and takes it for a real one.
With a delay between the two stores, an unprivileged process that listed a directory during its copy-up saw only "." and "..", and its next getdents freed the readdir cache of another descriptor.
Fix this by setting OVL_WHITEOUTS before ovl_inode_update(), so that ovl_dir_reset() agrees with ovl_dir_open(), and by testing OVL_TYPE_MERGE() of the path type in ovl_dir_open(), so that an open that observes the upper dentry never iterates a merge dir as a real dir, regardless of the order in which it observes the flag.
---
[ backport: context: the store is followed by the unlock: label ]
fs/overlayfs/copy_up.c | 2 +- fs/overlayfs/readdir.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +1 -1
@@ -772,9 +772,9 @@ static int ovl_copy_up_workdir(struct ovif (!c->metacopy)ovl_set_upperdata (inode); -ovl_inode_update (inode, temp);if (S_ISDIR (inode->i_mode))ovl_set_flag (OVL_WHITEOUTS , inode); +ovl_inode_update (inode, temp); unlock:unlock_rename (c->workdir, c->destdir);
fs/overlayfs/readdir.c +2 -1
@@ -947,7 +947,8 @@ static int ovl_dir_open(struct inode *inreturn PTR_ERR (realfile); } od->realfile = realfile; - od->is_real =ovl_dir_is_real (inode); + od->is_real = !OVL_TYPE_MERGE (type) && + !ovl_test_flag (OVL_WHITEOUTS , inode); od->is_upper =OVL_TYPE_UPPER (type); file->private_data = od;
Greg Kroah-Hartman
maintainerPATCH 745/3318 io_uring/net: keep recvmsg buffer select length within MAX_RW_COUNT
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yichong Chen <[email protected]>
Commit 18d3f56eb6e6500a65d81cf265f0fe74fd9ecab6 upstream.
io_recvmsg() takes the transfer length from the ring provided buffer when sqe->len is 0, and such a buffer can be up to 4G. min_ret is an int, so 2G or more makes it negative and the (ret < min_ret) block is skipped, and the oversized length reaches the socket layer unchanged: an empty socket then completes with 0 instead of arming poll, and a short read is reported as complete. Clamp the length to MAX_RW_COUNT, as io_recv() does.
--- io_uring/net.c | 1 + 1 file changed, 1 insertion(+)
io_uring/net.c +1 -0
@@ -857,6 +857,7 @@ retry_multishot: buf =io_buffer_select (req, &len, issue_flags);if (!buf)return -ENOBUFS ; + len =min_t (size_t, len,MAX_RW_COUNT );if (req->flags &REQ_F_APOLL_MULTISHOT ) { ret =io_recvmsg_prep_multishot (kmsg, sr, &buf, &len);
Greg Kroah-Hartman
maintainerPATCH 746/3318 io_uring/net: dont retry a non-blocking connect() that fails with -EAGAIN
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daan De Meyer <[email protected]>
Commit 71537ed811107c514c0342e98902d489d6d2b7cd upstream.
IORING_OP_CONNECT on an O_NONBLOCK AF_UNIX stream socket retries a connect that fails with -EAGAIN because the listener's backlog is full. Polling the client socket doesn't help: an unconnected stream socket reports EPOLLOUT and EPOLLHUP right away, before the backlog drains. So io_uring retries the connect until the apoll retry limit is hit, then punts the request to io-wq. With a full backlog, io_connect() runs 128 times in the submitting task and once more in a new io-wq worker. That worker stays in the task's thread group, so a later unshare(CLONE_NEWUSER) fails with -EINVAL.
None of this changes the result. __sys_connect_file() adds the socket's own O_NONBLOCK to every attempt, so the attempt from io-wq fails with -EAGAIN as well. That -EAGAIN becomes the CQE result, and connect(2) returns the same -EAGAIN.
Let's complete the request with -EAGAIN right away when the socket has O_NONBLOCK set, like connect(2) does. io_accept() already completes -EAGAIN this way for IORING_ACCEPT_DONTWAIT. -EINPROGRESS still waits for the connection to complete. A blocking socket still ends up in io-wq, where the connect sleeps until the listener accepts.
--- io_uring/net.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
io_uring/net.c +11 -0
@@ -1564,6 +1564,17 @@ int io_connect(struct io_kiocb *req, unsif (connect->seen_econnaborted) goto out; connect->seen_econnaborted = true; + }else if (req->file->f_flags &O_NONBLOCK ) { +/* +* __sys_connect_file() adds O_NONBLOCK from the socket +* to every attempt, so a retry from io-wq fails with +* -EAGAIN as well. A poll on the socket doesn't wait +* until a retry can succeed. For example, an AF_UNIX +* client reports EPOLLOUT right away while the +* listener's backlog is full. Complete the request +* with -EAGAIN, like connect(2) does. +*/ + goto out; }if (req_has_async_data (req))return -EAGAIN ;
Greg Kroah-Hartman
maintainerPATCH 747/3318 io_uring/io-wq: no new workers once the exit has begun
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
Commit 47c68f925062a6013235d06add85a59f7d91e0fb upstream.
io_wq_exit_start() sets IO_WQ_BIT_EXIT, but worker creation task_work queued before that stays queued until io_wq_exit_workers() cancels it. In between the task runs its task_work while canceling requests, and a worker can still get created.
That's a problem for exec. begin_new_exec() calls io_uring_task_cancel() after de_thread(), when it's supposedly the only thread left, and io_wq_exit_workers() only waits for ->worker_done, which a worker completes before do_exit(). So the exiting worker is still in the thread group, using the mm, files and sighand, while exec replaces them. Easy to hit with a signal pending when create_io_thread() fails and the retry gets queued right before execve().
Cancel the queued creation task_work as soon as the exit bit is set. Pending work that isn't otherwise canceled now ends with -ECANCELED when the io-wq is destroyed, rather than depending on whether the task happened to run its task_work first.
[axboe: the barrier is already upstream, see 0e5663856b69, only the
cancel is new]
--- io_uring/io-wq.c | 6 ++++++ 1 file changed, 6 insertions(+)
io_uring/io-wq.c +6 -0
@@ -1318,6 +1318,12 @@ void io_wq_exit_start(struct io_wq *wq)set_bit (IO_WQ_BIT_EXIT , &wq->state);/* Pairs with task_work_add() in io_queue_worker_create(). */ smp_mb__after_atomic (); +/* +* No more workers from here on. The caller is going to run its task +* work, and on exec a thread that is created now would still be +* around, exiting, by the time that the caller must be on its own. +*/ +io_wq_cancel_tw_create (wq); }static void io_wq_cancel_tw_create (struct io_wq *wq)
Greg Kroah-Hartman
maintainerPATCH 748/3318 io_uring/rsrc: charge buffer arrays and nodes to memcg
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
Commit 075d5837bafc317e796548f721b8fbf7add6821d upstream.
The io_mapped_ubuf of a registered buffer has one bio_vec per page, unless the pages coalesce into huge pages. Huge pages only count against RLIMIT_MEMLOCK once per ring, so a buffer that maps the same 2MB folio over and over in a way that defeats coalescing gets a full bvec array per registration while only the one folio counts as locked. 1GB of that registered in 100 slots took several times a 64MB memory.max, with 2.6MB charged.
Allocate the io_mapped_ubuf and the io_rsrc_node with GFP_KERNEL_ACCOUNT. An object reused from the ring caches stays charged to whoever allocated it first, same as the io_kiocb cache.
[axboe: 6.6 predates the rsrc node rework, charge the imu kvmalloc() and the node kzalloc() instead]
--- io_uring/rsrc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
io_uring/rsrc.c +2 -2
@@ -203,7 +203,7 @@ struct io_rsrc_node *io_rsrc_node_alloc(if (entry) { ref_node = container_of(entry, struct io_rsrc_node, cache); }else { - ref_node =kzalloc (sizeof (*ref_node),GFP_KERNEL ); + ref_node =kzalloc (sizeof (*ref_node),GFP_KERNEL_ACCOUNT );if (!ref_node)return NULL ; }
@@ -923,7 +923,7 @@ static int io_sqe_buffer_register(struct } } - imu =kvmalloc (struct_size (imu, bvec, nr_pages),GFP_KERNEL ); + imu =kvmalloc (struct_size (imu, bvec, nr_pages),GFP_KERNEL_ACCOUNT );if (!imu) goto done;
Greg Kroah-Hartman
maintainerPATCH 749/3318 io_uring: charge tctx nodes and personalities
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
Commit 0b34e7b20a48710b6f53716bf7030920b69fdbdd upstream.
The io_tctx_node allocated the first time a task touches a ring, and the XArray nodes behind tctx->xa and ctx->personalities, are plain GFP_KERNEL. tctx->xa is indexed by the ring pointer, so nearly every entry needs nodes of its own, and a task gets one entry per ring it has used. 642 threads on 4000 rings held 2.3GB with 59MB charged against a 64MB memory.max.
Allocate the node with GFP_KERNEL_ACCOUNT and set XA_FLAGS_ACCOUNT on both XArrays.
[axboe: 6.6 has kmalloc() for the node, inline in__io_uring_add_tctx_node()]
--- io_uring/io_uring.c | 2 +- io_uring/tctx.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-)
io_uring/io_uring.c +1 -1
@@ -319,7 +319,7 @@ static __cold struct io_ring_ctx *io_rinio_alloc_cache_init (&ctx->netmsg_cache,IO_ALLOC_CACHE_MAX ,sizeof (struct io_async_msghdr ));init_completion (&ctx->ref_comp); -xa_init_flags (&ctx->personalities,XA_FLAGS_ALLOC1 ); +xa_init_flags (&ctx->personalities,XA_FLAGS_ALLOC1 |XA_FLAGS_ACCOUNT );mutex_init (&ctx->uring_lock);init_waitqueue_head (&ctx->cq_wait);init_waitqueue_head (&ctx->poll_wq);
io_uring/tctx.c +2 -2
@@ -93,7 +93,7 @@ __cold int io_uring_alloc_task_context(sreturn ret; } -xa_init (&tctx->xa); +xa_init_flags (&tctx->xa,XA_FLAGS_ACCOUNT );init_waitqueue_head (&tctx->wait);atomic_set (&tctx->in_cancel,0 );atomic_set (&tctx->inflight_tracked,0 );
@@ -125,7 +125,7 @@ int __io_uring_add_tctx_node(struct io_r } }if (!xa_load (&tctx->xa, (unsigned long )ctx)) { - node =kmalloc (sizeof (*node),GFP_KERNEL ); + node =kmalloc (sizeof (*node),GFP_KERNEL_ACCOUNT );if (!node)return -ENOMEM ; node->ctx = ctx;
Greg Kroah-Hartman
maintainerPATCH 750/3318 io_uring: free XArray nodes left by a failed store
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
Commit 51bab09b7ca1a9a6dd9303a3b7ee346f8128c963 upstream.
A failed xa_store() can leave nodes without entries in the tree, and erasing every entry doesn't free those. An XArray needs xa_destroy() before it goes away, even an empty one. That was dropped for tctx->xa in commit ca6484cd308a ("io_uring: no need to call xa_destroy() on empty xarray") over a lockdep report from freeing the tctx in softirq context, and ctx->personalities never had it.
Now that the nodes are charged, a store can fail at memory.max and the leaked nodes stay charged. Call xa_destroy() in io_uring_clean_tctx(), which the task runs itself in process context before the tctx is freed, in the error path of __io_uring_add_tctx_node(), and for ctx->personalities in io_ring_ctx_free().
[axboe: 6.6 installs the tctx before adding the node and has no error path that frees it, drop that hunk. There's no ctx->hpage_acct either]
--- io_uring/io_uring.c | 1 + io_uring/tctx.c | 2 ++ 2 files changed, 3 insertions(+)
io_uring/io_uring.c +1 -0
@@ -3123,6 +3123,7 @@ static __cold void io_ring_ctx_free(strukfree (ctx->cancel_table.hbs);kfree (ctx->cancel_table_locked.hbs);xa_destroy (&ctx->io_bl_xa); +xa_destroy (&ctx->personalities);kfree (ctx); }
io_uring/tctx.c +2 -0
@@ -197,6 +197,8 @@ __cold void io_uring_clean_tctx(struct iio_uring_del_tctx_node (index);cond_resched (); } +/* A failed xa_store() leaves nodes with no entry behind. */ +xa_destroy (&tctx->xa);if (wq) {/* * Must be after io_uring_del_tctx_node() (removes nodes under
Greg Kroah-Hartman
maintainerPATCH 751/3318 io_uring/sqpoll: dont wait for the thread to exit
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
Commit 360395e8dbf9d23579f74b84a1af11190813b0f8 upstream.
io_sq_thread_stop() wakes the SQPOLL thread and waits for it to exit. The thread belongs to the thread group that created the ring, so a SIGSTOP or the cgroup freezer holds it in get_signal(), and the wake up doesn't change that. io_ring_exit_work() then sleeps in that wait until someone continues or kills the process. iou_exit has 64 slots, so 64 closed SQPOLL rings of a stopped process keep every other ring from being freed, for everyone.
Don't wait. Set the stop bit, wake the thread, and let it exit when it gets to run again. The sqd can now outlive its last ring, so give it a second refcount with one reference for the rings and one for the thread, and free it with the last one. The thread can't reach a freed ring, rings leave ctx_list before dropping their reference, and the io-wq hash is refcounted.
[axboe: 6.6 has a single exit path in io_sq_thread(), drop the thread's free_refs share there]
--- io_uring/sqpoll.c | 28 +++++++++++++++++++++++----- io_uring/sqpoll.h | 3 ++- 2 files changed, 25 insertions(+), 6 deletions(-)
io_uring/sqpoll.c +23 -5
@@ -52,6 +52,24 @@ void io_sq_thread_park(struct io_sq_datawake_up_process (sqd->thread); } +/* +* The sqd has two holders: its rings, as one, and its thread. Neither waits +* for the other to let go. The one that lets go last frees the sqd. +*/ +static void io_sq_data_release (struct io_sq_data *sqd) +{ +if (refcount_dec_and_test (&sqd->free_refs)) +kfree (sqd); +} + +/* +* Ask the thread to exit, and don't wait for it. A thread that is stopped or +* frozen exits only when a user lets it run again, and the exit work of the +* ring would keep its place in the workqueue until then. All rings have left +* ctx_list by now and have no request left, so the thread can reach none of +* them. What it still uses is its own or counted: the sqd by free_refs, the +* hash of its io-wq by hash->refs. +*/ void io_sq_thread_stop (struct io_sq_data *sqd) {WARN_ON_ONCE (sqd->thread == current);
@@ -62,7 +80,6 @@ void io_sq_thread_stop(struct io_sq_dataif (sqd->thread)wake_up_process (sqd->thread);mutex_unlock (&sqd->lock); -wait_for_completion (&sqd->exited); }void io_put_sq_data (struct io_sq_data *sqd)
@@ -71,7 +88,7 @@ void io_put_sq_data(struct io_sq_data *sWARN_ON_ONCE (atomic_read (&sqd->park_pending));io_sq_thread_stop (sqd); -kfree (sqd); +io_sq_data_release (sqd); } }
@@ -153,10 +170,10 @@ static struct io_sq_data *io_get_sq_dataatomic_set (&sqd->park_pending,0 );refcount_set (&sqd->refs,1 ); +refcount_set (&sqd->free_refs,2 );INIT_LIST_HEAD (&sqd->ctx_list);mutex_init (&sqd->lock);init_waitqueue_head (&sqd->wait); -init_completion (&sqd->exited);return sqd; }
@@ -335,7 +352,7 @@ static int io_sq_thread(void *data)io_run_task_work ();mutex_unlock (&sqd->lock); -complete (&sqd->exited); +io_sq_data_release (sqd);do_exit (0 ); }
@@ -455,7 +472,8 @@ __cold int io_sq_offload_create(struct iput_task_struct (task_to_put);return 0 ; err_sqpoll: -complete (&ctx->sq_data->exited); +/* no thread was made: let go of its share */ +io_sq_data_release (ctx->sq_data); err:io_sq_thread_finish (ctx);if (task_to_put)
io_uring/sqpoll.h +2 -1
@@ -2,6 +2,8 @@struct io_sq_data {refcount_t refs; +/* one for all the rings, one for the thread: the last put frees */ +refcount_t free_refs;atomic_t park_pending;struct mutex lock;
@@ -17,7 +19,6 @@ struct io_sq_data {pid_t task_tgid;unsigned long state; -struct completion exited; };int io_sq_offload_create (struct io_ring_ctx *ctx,struct io_uring_params *p);
Greg Kroah-Hartman
maintainerPATCH 752/3318 io_uring/timeout: count cancelled timeouts in cq_timeouts
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cheng Yongkang <[email protected]>
Commit 1c8b49851543f41fc8bb18bcd1f15cc93d14b530 upstream.
io_timeout_cancel() posts the cancelled timeout's -ECANCELED CQE without advancing ctx->cq_timeouts. io_timeout_fn() and io_kill_timeout() advance it for every timeout CQE they post, and io_flush_timeouts() computes the number of non-timeout completions as
seq = cached_cq_tail - cq_timeouts
to compare against each off timeout's target_seq. The cancelled timeout's CQE is therefore counted as a regular completion, so every cancellation makes an already armed off timeout fire one completion early.
A ring with a keep-alive timeout of off=4 completes it after two NOPs when one off=100 victim is cancelled through IORING_OP_ASYNC_CANCEL, and before any NOP when two victims are cancelled. The cancel CQE should count, but the cancelled timeouts' -ECANCELED CQEs must not: the expected counts are three and two NOPs respectively.
Advance cq_timeouts when io_timeout_extract() succeeds, under timeout_lock and before the -ECANCELED completion is queued, matching io_timeout_fn() and io_kill_timeout(). The -ENOENT and -EALREADY paths post no new timeout CQE and keep their accounting. Both the ASYNC_CANCEL and the TIMEOUT_REMOVE path go through io_timeout_cancel().
--- io_uring/timeout.c | 3 +++ 1 file changed, 3 insertions(+)
io_uring/timeout.c +3 -0
@@ -306,6 +306,9 @@ int io_timeout_cancel(struct io_ring_ctxspin_lock_irq (&ctx->timeout_lock); req =io_timeout_extract (ctx, cd); +if (!IS_ERR (req)) +atomic_set (&ctx->cq_timeouts, +atomic_read (&ctx->cq_timeouts) +1 );spin_unlock_irq (&ctx->timeout_lock);if (IS_ERR (req))
Greg Kroah-Hartman
maintainerPATCH 753/3318 media: rc: Fix build failure with CONFIG_LIRC disabled
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit 0c795849fd70d6bdb99aea5dd08d9b43128612f6 upstream.
commit 37efd09ba2c6 ("media: rc: Ensure registered is cleared in error path") broke the build if CONFIG_LIRC was not enabled.
--- drivers/media/rc/lirc_dev.c | 3 +++ drivers/media/rc/rc-main.c | 3 +-- 2 files changed, 4 insertions(+), 2 deletions(-)
drivers/media/rc/lirc_dev.c +3 -0
@@ -774,6 +774,9 @@ void lirc_unregister(struct rc_dev *dev)unsigned long flags;struct lirc_fh *fh; +if (!device_is_registered (&dev->lirc_dev)) +return ; +dev_dbg (&dev->dev,"lirc_dev: driver %s unregistered from minor = %d\n" , dev->driver_name,MINOR (dev->lirc_dev.devt));
drivers/media/rc/rc-main.c +1 -2
@@ -1981,8 +1981,7 @@ out_lirc:scoped_guard (mutex, &dev->lock) dev->registered = false; -if (device_is_registered (&dev->lirc_dev)) -lirc_unregister (dev); +lirc_unregister (dev);device_del (&dev->dev);/* registered already cleared above */ goto out_free_table;
Greg Kroah-Hartman
maintainerPATCH 754/3318 drm/amdgpu/powerplay: Align get_tonga_state_array() header with prototype
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Srinivasan Shanmugam <[email protected]>
commit 4986757d3207383c052689532e505edccc6df7c8 upstream.
The function header above get_tonga_state_array() still refers to check_powerplay_tables() and does not describe all of the function parameters.
Update it to match the current function prototype and include the missing parameter description.
--- drivers/gpu/drm/amd/pm/powerplay/hwmgr/process_pptables_v1_0.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/pm/powerplay/hwmgr/process_pptables_v1_0.c +4 -3
@@ -1502,11 +1502,12 @@ static int init_thermal_controller( }/** -* check_powerplay_tables - Private Function used during initialization. -* Inspect the PowerPlay table for obvious signs of corruption. +* get_tonga_state_array - Get the Tonga state array from the PowerPlay table. * @hwmgr: Pointer to the hardware manager. * @powerplay_table: Pointer to the PowerPlay Table. -* Exception: 2 if the powerplay table is incorrect. +* @state_array: Pointer to the returned Tonga state array. +* +* Return: 0 on success, negative error code on failure. */ static int get_tonga_state_array(struct pp_hwmgr *hwmgr, const ATOM_Tonga_POWERPLAYTABLE *powerplay_table,
Greg Kroah-Hartman
maintainerPATCH 755/3318 netfilter: conntrack: always lower timeout for non-closing RST packets
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pablo Neira Ayuso <[email protected]>
commit 73df81b38cb7f70a347a97370386378a86e53019 upstream.
The existing check might extend the timeout if the ESTABLISHED timeout has been tuned to be lower than UNACK via sysctl. Reported by sashiko.
--- net/netfilter/nf_conntrack_proto_tcp.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/netfilter/nf_conntrack_proto_tcp.c +2 -1
@@ -1325,7 +1325,8 @@ int nf_conntrack_tcp_packet(struct nf_co timeouts[new_state] > timeouts[TCP_CONNTRACK_RETRANS]) timeout = timeouts[TCP_CONNTRACK_RETRANS ]; else if (unlikely(index == TCP_RST_SET && - new_state == TCP_CONNTRACK_ESTABLISHED)) + new_state == TCP_CONNTRACK_ESTABLISHED) && + timeouts[new_state] > timeouts[TCP_CONNTRACK_UNACK]) timeout = timeouts[TCP_CONNTRACK_UNACK ]; else if ((ct->proto.tcp.seen[0].flags | ct->proto.tcp.seen[1].flags) & IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED &&
Greg Kroah-Hartman
maintainerPATCH 756/3318 opp: fix use after free in _update_opp_table_clk()
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peter Griffin <[email protected]>
commit 1f6de65e3314519ce462bfd3a1d29e918f97e4e5 upstream.
dev_pm_opp_put_opp_table() frees the opp_table which is subsquently used by dev_err_probe(). This causes an Oops during boot on gs101-oriole.
cpu cpu0: error 000000006b6b6b6b: Couldn't find clock
Unable to handle kernel paging request at virtual address 006b6b6b6b6b6cd3 ... Hardware name: Oriole (DT) pstate: 00400005 (nzcv daif +PAN -UAO -TCO -DIT -SSBS BTYPE=--) pc : _of_add_table_indexed+0x80/0xbb0 lr : _of_add_table_indexed+0x6c/0xbb0 ... Call trace: _of_add_table_indexed+0x80/0xbb0 (P) dev_pm_opp_of_cpumask_add_table+0x70/0x120 dt_cpufreq_probe+0x23c/0x480 platform_probe+0x64/0xb8
--- drivers/opp/core.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/opp/core.c +4 -2
@@ -1485,6 +1485,8 @@ static struct opp_table *_update_opp_tab struct opp_table *opp_table, bool getclk) { +int ret; +/* * Return early if we don't need to get clk or we have already done it * earlier.
@@ -1511,9 +1513,9 @@ static struct opp_table *_update_opp_tab opp_table->clk =clk_get_optional (dev,NULL );if (IS_ERR (opp_table->clk)) { + ret =dev_err_probe (dev,PTR_ERR (opp_table->clk),"Couldn't find clock\n" );dev_pm_opp_put_opp_table (opp_table); -dev_err_probe (dev,PTR_ERR (opp_table->clk),"Couldn't find clock\n" ); -return ERR_CAST (opp_table->clk); +return ERR_PTR (ret); }if (opp_table->clk)
Greg Kroah-Hartman
maintainerPATCH 757/3318 tun: Require CAP_NET_ADMIN to attach to an ownerless device
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Woodhouse <[email protected]>
commit ffdf678dd16610e3f006dac904bd37c09684673c upstream.
Twenty years ago I made creating a tuntap device require CAP_NET_ADMIN in commit ca6bb5d7ab22 ("[NET]: Require CAP_NET_ADMIN to create tuntap devices.")
The idea was to allow the permissions on /dev/net/tun to be relaxed to 0666 and thus allow owners of tun devices assigned with TUNSETOWNER to actually open it and get at their devices.
What we missed at the time was that persistent devices with *no* owner were already essentially world-consumable, and anyone who could open the device node could also attach to those.
Even then, using persistent devices with no explicitly set owner — on the (false) presumption that CAP_NET_ADMIN would be required to open them — wasn't an egregious userspace bug. There are cases where it does make sense to separate the creation/configuration of the netdevice, from the process which shovels packets into it.
Since then, TUNSETGROUP was added a year later in commit 8c644623fe7e ("[NET]: Allow group ownership of TUN/TAP devices."). Its commit message noted that if both uid and gid are set, both have to match (in itself a bizarre choice) — but still not that with *neither* set, no permission at all was required.
Then in 2012 commit c8d68e6be1c3 ("tuntap: multiqueue support") allowed new queues to be attached to a device from the moment of its creation, with no way for userspace to close the race between creation and a subsequent TUNSET{OWNER,GROUP}.
In 2024, commit 3ca459eaba1bf ("tun: fix group permission check") tried to fix things to be saner: only require the user *or* the group to match, in line with standard POSIX permissions, and require CAP_NET_ADMIN if neither the user nor group authorised the access (although it put the CAP_NET_ADMIN check first, and would wrongly have reported the capability as having been used even when it was not).
That fix was reverted in commit a70c7b3cbc06 ("tun: revert fix group permission check") due to allegedly causing a regression in an selinux test suite which *expected* the attachment to succeed when authorised by none of user, group, nor CAP_NET_ADMIN:
https://lore.kernel.org/netdev/CAFqZXNtkCBT4f+PwyVRmQGoT3p1eVa01fCG_aNtpt6dakXncUg@mail.gmail.com/
We should not break UAPI. But we don't have to consider an selinux test case which deliberately exercises a security flaw to be UAPI worth preserving either. To which end, I have fixed it in selinux-testsuite commit b2f894f0016b ("tests/tun_tap: set an owner on the device for the relabel tests").
So: fix the lack of CAP_NET_ADMIN check on devices which *haven't* been assigned an owner or group, while leaving the weird tun ownership model as it was (user *and* group have to match, if both are set). If someone still wants to fix the latter (which wasn't actually the reason the previous attempt was reverted), they can do it under separate cover.
Permit attaching to an existing device only if an owner and/or group was set and the caller matches all that were set, or if the caller has CAP_NET_ADMIN. The only behavioural change is that a device with no owner or group now requires CAP_NET_ADMIN to attach — precisely the loophole we want to close.
And put the CAP_NET_ADMIN check in the right place this time.
--- drivers/net/tun.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-)
drivers/net/tun.c +9 -5
@@ -574,14 +574,18 @@ static u16 tun_select_queue(struct net_dreturn ret; } -static inline bool tun_not_capable (struct tun_struct *tun) +static inline bool tun_permitted (struct tun_struct *tun) {const struct cred *cred =current_cred ();struct net *net =dev_net (tun->dev); -return ((uid_valid (tun->owner) && !uid_eq (cred->euid, tun->owner)) || - (gid_valid (tun->group) && !in_egroup_p (tun->group))) && - !ns_capable (net->user_ns,CAP_NET_ADMIN ); +/* If both uid and gid are set, *both* must match */ +if ((uid_valid (tun->owner) ||gid_valid (tun->group)) && + (!uid_valid (tun->owner) ||uid_eq (cred->euid, tun->owner)) && + (!gid_valid (tun->group) ||in_egroup_p (tun->group))) +return true; + +return ns_capable (net->user_ns,CAP_NET_ADMIN ); }static void tun_set_real_num_queues (struct tun_struct *tun)
@@ -2792,7 +2796,7 @@ static int tun_set_iff(struct net *net, !!(tun->flags & IFF_MULTI_QUEUE))return -EINVAL ; -if (tun_not_capable (tun)) +if (!tun_permitted (tun))return -EPERM ; err =security_tun_dev_open (tun->security);if (err <0 )
Greg Kroah-Hartman
maintainerPATCH 758/3318 smb: client: fix early procfs exposure race
In reply to Greg Kroah-Hartman6.6-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fredric Cover <[email protected]>
[ Upstream commit 7b1afb631395c958993cda4631002258ef4151ea ]
Currently, init_cifs() calls cifs_proc_init() near the beginning of the function, before INIT_LIST_HEAD, leading to a momentarily uninitialized, but exposed, procfs. If a userspace process reads this empty procfs, iterating over a zeroed list_head leads to a NULL pointer dereference and a kernel oops/panic.
For example, if a delay is added between cifs_proc_init() and INIT_LIST_HEAD, and a userspace process is polling /proc/fs/cifs/DebugData, the following oops occurs:
BUG: kernel NULL pointer dereference, address: 0000000000000608 Oops: Oops: 0000 [#1] SMP PTI CPU: 0 UID: 0 PID: 3477 Comm: cat Not tainted 7.3.0-02212-g4df4d2a577db-dirty #6 PREEMPT(lazy) RIP: 0010:cifs_debug_data_proc_show+0x103/0xd80 [cifs] Call Trace: <TASK> ? seq_read_iter+0x86/0x400 ? seq_read_iter+0x86/0x400 seq_read_iter+0x183/0x400 proc_reg_read_iter+0x62/0x90 copy_splice_read+0x215/0x310 splice_file_to_pipe+0xec/0x1c0 do_splice+0x4b8/0x780 __se_sys_splice+0x18f/0x250 do_syscall_64+0x109/0x330 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
Fix this by moving cifs_proc_init() down in init_cifs(), ensuring it runs only after all internal lists, locks, counters, and workqueues are fully ready, but before registering the filesystem. Update the error cleanup ladder and exit_cifs() to maintain proper LIFO order.
--- fs/smb/client/cifsfs.c | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-)
fs/smb/client/cifsfs.c +9 -11
@@ -1859,7 +1859,6 @@ static int __initinit_cifs (void) {int rc =0 ; -cifs_proc_init ();INIT_LIST_HEAD (&cifs_tcp_ses_list);/* * Initialize Global counters
@@ -1908,10 +1907,8 @@ init_cifs(void) } cifsiod_wq =alloc_workqueue ("cifsiod" ,WQ_FREEZABLE |WQ_MEM_RECLAIM ,0 ); -if (!cifsiod_wq) { - rc = -ENOMEM ; - goto out_clean_proc; - } +if (!cifsiod_wq) +return -ENOMEM ;/* * Consider in future setting limit!=0 maybe to min(num_of_cores - 1, 3)
@@ -1994,19 +1991,22 @@ init_cifs(void)if (rc) goto out_cifs_swn_init; +cifs_proc_init (); + rc =register_filesystem (&cifs_fs_type);if (rc) - goto out_init_cifs_idmap; + goto out_clean_proc; rc =register_filesystem (&smb3_fs_type);if (rc) {unregister_filesystem (&cifs_fs_type); - goto out_init_cifs_idmap; + goto out_clean_proc; }return 0 ; -out_init_cifs_idmap: +out_clean_proc: +cifs_proc_clean ();exit_cifs_idmap (); out_cifs_swn_init: #ifdef CONFIG_CIFS_SWN_UPCALL
@@ -2040,8 +2040,6 @@ init_cifs(void)destroy_workqueue (decrypt_wq); out_destroy_cifsiod_wq:destroy_workqueue (cifsiod_wq); -out_clean_proc: -cifs_proc_clean ();return rc; }
@@ -2051,6 +2049,7 @@ exit_cifs(void)cifs_dbg (NOISY ,"exit_smb3\n" );unregister_filesystem (&cifs_fs_type);unregister_filesystem (&smb3_fs_type); +cifs_proc_clean ();cifs_release_automount_timer ();exit_cifs_idmap ();#ifdef CONFIG_CIFS_SWN_UPCALL
@@ -2072,7 +2071,6 @@ exit_cifs(void)destroy_workqueue (serverclose_wq);destroy_workqueue (cfid_put_wq);destroy_workqueue (cifsiod_wq); -cifs_proc_clean (); }MODULE_AUTHOR ("Steve French" );
Signature · 1 line
2.53.0