6.12.117-rc1 review
Subsystems (5)
Greg Kroah-Hartman
maintainerPATCH 655/1536 usb: gadget: fix refcount underflow in gadgetfs_bind() error path
In reply to Greg Kroah-Hartman6.12-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
@@ -1702,6 +1702,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)
@@ -1716,7 +1718,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 656/1536 ufs: use u64 for directory size in ufs_last_byte
In reply to Greg Kroah-Hartman6.12-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
@@ -211,7 +211,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 657/1536 resource: report a devm_request_resource() conflict under the lock
In reply to Greg Kroah-Hartman6.12-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
@@ -1588,10 +1588,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 658/1536 phy: core: Fix race-condition between _of_phy_get() and try_module_get()
In reply to Greg Kroah-Hartman6.12-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
@@ -124,13 +124,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 ); }
@@ -626,6 +626,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)
@@ -637,11 +639,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)) {
@@ -655,8 +656,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);
@@ -680,15 +679,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);
@@ -795,6 +800,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",
@@ -805,15 +811,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);
@@ -822,6 +831,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);
@@ -970,15 +981,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);
@@ -991,6 +1004,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 659/1536 power: supply: sbs-battery: disable polling before supply teardown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 5c1c602463d597c5189ddc5a73dece588ba2c57a upstream.
The managed poll-work cancellation is registered before the power supply, so cleanup unregisters the supply before draining polling. A pending or running poller can then call power_supply_changed() on the released supply.
Commit 8d59cf3887fb ("power: supply: sbs-battery: Fix use-after-free in power_supply_changed()") moved the IRQ request after supply registration, but did not change the poll-work cancellation order.
Add a later managed action that disables and drains polling before supply teardown. Its retained disabled state prevents external-power callbacks from rearming the poll work after it has been drained. Keep the original autocancel to initialize work before supply callbacks can run and to cover failed supply registration.
The teardown ordering issue was found by static analysis.
--- drivers/power/supply/sbs-battery.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
drivers/power/supply/sbs-battery.c +11 -0
@@ -1059,6 +1059,13 @@ static void sbs_alert(struct i2c_clientsbs_supply_changed (i2c_get_clientdata (client)); } +static void sbs_disable_work (void *data) +{ +struct sbs_info *chip = data; + +disable_delayed_work_sync (&chip->work); +} +static void sbs_external_power_changed (struct power_supply *psy) {struct sbs_info *chip =power_supply_get_drvdata (psy);
@@ -1199,6 +1206,10 @@ static int sbs_probe(struct i2c_client *return dev_err_probe (&client->dev,PTR_ERR (chip->power_supply),"Failed to register power supply\n" ); + rc =devm_add_action_or_reset (&client->dev, sbs_disable_work, chip); +if (rc) +return rc; +if (!chip->gpio_detect) goto out;
Greg Kroah-Hartman
maintainerPATCH 660/1536 nvmem: core: Fix OOB read for bit offsets of more than one byte
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Janne Grunau <[email protected]>
commit 24530401e8001aaa637dd5007fcdc6fbc00300be upstream.
When the bit offset is BITS_PER_BYTE or larger the read position is advanced by bytes_offset. This is not taken into account in the per-byte read loop which still reads cell->bytes resulting in an out of bounds read of bytes_offset bytes. The information read OOB does not leak directly as the erroneously read bits are cleared.
Detected by KASAN while looking for a use-after-free in simplefb.c.
--- drivers/nvmem/core.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/nvmem/core.c +3 -1
@@ -1626,12 +1626,14 @@ static void nvmem_shift_read_buffer_in_p *p = *b++ >> bit_offset;/* setup rest of the bytes if any */ -for (i =1 ; i < cell->bytes; i++) { +for (i =1 ; i < (cell->bytes - bytes_offset); i++) {/* Get bits from next byte and shift them towards msb */ *p++ |= *b << (BITS_PER_BYTE - bit_offset); *p = *b++ >> bit_offset; } +/* point to end of the buffer unused bits will be cleared */ + p = buf + cell->bytes -1 ; }else if (p != b) {memmove (p, b, cell->bytes - bytes_offset); p += cell->bytes -1 ;
Greg Kroah-Hartman
maintainerPATCH 661/1536 media: rc: Ensure that rc_unregister_device() does not free input device
In reply to Greg Kroah-Hartman6.12-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 662/1536 media: rc: Ensure registered is cleared in error path
In reply to Greg Kroah-Hartman6.12-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 663/1536 media: rc: fintek-cir: process a full RX buffer instead of overflowing it
In reply to Greg Kroah-Hartman6.12-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 664/1536 media: rc: mce_kbd: Fix inconsistent locking of keylock
In reply to Greg Kroah-Hartman6.12-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 665/1536 media: rc: Use after free in ir_raw_event_handle()
In reply to Greg Kroah-Hartman6.12-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 666/1536 media: rc: After rc_unregister_device() timers can be re-armed
In reply to Greg Kroah-Hartman6.12-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 667/1536 media: rc: Fix use after free in bpf progs
In reply to Greg Kroah-Hartman6.12-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 668/1536 media: rc: Fix ABBA deadlock by making locks more fine grained
In reply to Greg Kroah-Hartman6.12-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 669/1536 ocfs2/heartbeat: unlink live slots when their node is missing
In reply to Greg Kroah-Hartman6.12-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
@@ -867,8 +867,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)) {
@@ -890,7 +893,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)
@@ -1025,7 +1029,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 670/1536 ocfs2/dlm: hold a lock reference across grant AST enqueue
In reply to Greg Kroah-Hartman6.12-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 671/1536 ocfs2/dlm: hold the lookup reference across convert AST enqueue
In reply to Greg Kroah-Hartman6.12-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 672/1536 ocfs2: cancel quota sync work before freeing quota info
In reply to Greg Kroah-Hartman6.12-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
@@ -816,6 +816,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 673/1536 ocfs2: fix chunk number of the first chunk in a local quota file
In reply to Greg Kroah-Hartman6.12-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
@@ -1074,10 +1074,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 674/1536 ocfs2: pin refcount trees before dropping the lookup lock
In reply to Greg Kroah-Hartman6.12-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);
@@ -2323,7 +2325,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;
@@ -2558,7 +2561,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 675/1536 ocfs2: snapshot dentry names in file and setattr traces
In reply to Greg Kroah-Hartman6.12-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 ;
@@ -1126,15 +1139,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))
@@ -2380,11 +2397,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 ;
@@ -2530,17 +2553,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)
@@ -2612,11 +2634,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 676/1536 smb: client: fix OOB last_entry pointer from unbounded LastNameOffset
In reply to Greg Kroah-Hartman6.12-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
@@ -4134,14 +4134,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 ; }
@@ -4259,7 +4262,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 677/1536 smb: client: stop processing a read response after a receive error
In reply to Greg Kroah-Hartman6.12-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
@@ -1852,6 +1852,8 @@ cifs_readv_receive(struct TCP_Server_Inf#endif length =cifs_read_iter_from_socket (server, &rdata->subreq.io_iter, data_len); +if (length <0 ) +return length;if (length >0 ) rdata->got_bytes += length; server->total_read += length;
Greg Kroah-Hartman
maintainerPATCH 678/1536 ovl: take a snapshot of the name for copy up
In reply to Greg Kroah-Hartman6.12-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.
--- fs/overlayfs/copy_up.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
fs/overlayfs/copy_up.c +12 -6
@@ -948,6 +948,7 @@ static int ovl_do_copy_up(struct ovl_copstruct ovl_fs *ofs =OVL_FS (c->dentry->d_sb);struct dentry *origin = c->lowerpath.dentry;struct ovl_fh *fh =NULL ; +struct name_snapshot name;bool to_index = false;/*
@@ -985,12 +986,15 @@ static int ovl_do_copy_up(struct ovl_cop goto out_free_fh; }else {/* -* c->dentry->d_name is stabilzed by ovl_copy_up_start(), -* because if we got here, it means that c->dentry has no upper -* alias and changing ->d_name means going through ovl_rename() -* that will call ovl_copy_up() on source and target dentry. +* 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. */ - c->destname = c->dentry->d_name; +take_dentry_name_snapshot (&name, c->dentry); + c->destname = name.name;/* * Mark parent "impure" because it may now contain non-pure * upper
@@ -999,7 +1003,7 @@ static int ovl_do_copy_up(struct ovl_cop err =ovl_set_impure (c->parent, c->destdir);ovl_end_write (c->dentry);if (err) - goto out_free_fh; + goto out; }/* Should we copyup with O_TMPFILE or with workdir? */
@@ -1033,6 +1037,8 @@ static int ovl_do_copy_up(struct ovl_cop out:if (to_index)kfree (c->destname.name); +else +release_dentry_name_snapshot (&name); out_free_fh:kfree (fh);return err;
Greg Kroah-Hartman
maintainerPATCH 679/1536 ovl: use the pinned upper dir in ovl_fix_origin()
In reply to Greg Kroah-Hartman6.12-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.
--- fs/overlayfs/namei.c | 6 ++++-- fs/overlayfs/overlayfs.h | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-)
fs/overlayfs/namei.c +4 -2
@@ -910,8 +910,10 @@ static int ovl_fix_origin(struct ovl_fs goto out; err =ovl_set_origin_fh (ofs, fh, 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); out:
fs/overlayfs/overlayfs.h +6 -0
@@ -539,6 +539,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 680/1536 ovl: always encode the origin fh when index is enabled
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 949f9d8a5580c77a45fa759123367682aba4d173 upstream.
On an overlay with index=on,nfs_export=on, copy up of a directory crashes the kernel once an LSM has started to deny CAP_DAC_READ_SEARCH to the mounter, the task that mounted the overlay. The mount and the LSM policy change require root. After that, any user who can write to a directory that exists only in a lower layer triggers the oops by doing so.
Before a file or directory that exists only in a lower layer is changed for the first time, overlayfs copies it to the writable upper layer. This is called copy up.
On copy up, ovl_get_origin_fh() encodes the file handle of the lower inode, called the origin. It returns NULL if ovl_can_decode_fh() says that the lower filesystem cannot decode handles. Whether the callers can handle NULL depends on the index option:
- Without an index, NULL is fine: the callers store an empty origin xattr.
- With index enabled, overlayfs keeps entries for copied up inodes in an internal index directory. The name of an index entry is derived from the handle, so ovl_get_origin_fh() must return a handle or an error.
The mount only enables the index if ovl_can_decode_fh() succeeds for all layers, but the result can change later. The function checks the export operations of the filesystem and capable(CAP_DAC_READ_SEARCH). Copy up runs with the mounter's credentials, and an LSM can start to deny the capability to those credentials after the mount. ovl_get_origin_fh() then returns NULL with index enabled.
This goes wrong in two callers:
- With nfs_export=on, copy up of a directory creates an index entry for the directory. ovl_create_index() passes the NULL handle to ovl_get_index_name_fh(), which dereferences it.
- If the result changes while mount(2) is still running, ovl_get_indexdir() passes a NULL from ovl_get_origin_fh() to ovl_verify_set_fh() in the same way.
Before the commit in the Fixes tag, these two callers encoded the handle themselves, without consulting ovl_can_decode_fh().
Reproduced with a BPF LSM program that started to deny the capability after the mount. An unprivileged touch in a directory that had not been copied up yet oopsed in ovl_get_index_name_fh(). With this patch the touch succeeds and the directory gets its index entry.
Fix this by calling ovl_can_decode_fh() in ovl_get_origin_fh() only when index is disabled.
--- fs/overlayfs/copy_up.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
fs/overlayfs/copy_up.c +5 -1
@@ -476,8 +476,12 @@ struct ovl_fh *ovl_get_origin_fh(struct* When lower layer doesn't support export operations store a 'null' fh, * so we can use the overlay.origin xattr to distignuish between a copy * up and a pure upper inode. +* +* With index enabled, mount already found that all layers can decode +* file handles. Do not ask again, because an LSM may change its answer +* about CAP_DAC_READ_SEARCH and index users cannot cope with a 'null' fh. */ -if (!ovl_can_decode_fh (origin->d_sb)) +if (!ofs->config.index && !ovl_can_decode_fh (origin->d_sb))return NULL ;return ovl_encode_real_fh (ofs,d_inode (origin), false);
Greg Kroah-Hartman
maintainerPATCH 681/1536 ovl: do not copy up an xattr value that was never read
In reply to Greg Kroah-Hartman6.12-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
@@ -131,8 +131,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 682/1536 ovl: fix a torn path in ovl_get_redirect()
In reply to Greg Kroah-Hartman6.12-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
@@ -980,7 +980,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);
@@ -993,13 +1005,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 683/1536 ovl: fortify ovl_copy_xattr() against underlying layer modifications
In reply to Greg Kroah-Hartman6.12-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
@@ -72,6 +72,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;
@@ -129,34 +132,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))
@@ -1082,26 +1063,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; }
@@ -1112,7 +1106,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 ))
@@ -1120,7 +1114,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; }
@@ -1150,7 +1146,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 684/1536 ovl: read the nlink xattr of every indexed non-dir
In reply to Greg Kroah-Hartman6.12-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
@@ -1000,7 +1000,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;
@@ -1008,7 +1008,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,
@@ -1265,7 +1273,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
@@ -680,7 +680,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
@@ -774,7 +774,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_permission (struct mnt_idmap *idmap,struct inode *inode,int mask);
Greg Kroah-Hartman
maintainerPATCH 685/1536 ovl: set the revalidate flags after d_instantiate()
In reply to Greg Kroah-Hartman6.12-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 dentry };ovl_dentry_set_upper_alias (dentry); -ovl_dentry_init_reval (dentry, newdentry,NULL );if (!hardlink) {/*
@@ -299,6 +298,13 @@ static int ovl_instantiate(struct dentryd_mark_tmpfile (tmpfile, inode);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 686/1536 ovl: skip copy up of empty security.capability
In reply to Greg Kroah-Hartman6.12-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
@@ -75,6 +75,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;
@@ -134,6 +143,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 ; }
@@ -1115,9 +1128,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 687/1536 xfs: clear the symlink zapped flag if inline symlink is ok
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit f8d0d90f2e24b1f4a14796ae63cebfd820cadfcd upstream.
LOLLM noticed that we fail to clear the SYMLINK_ZAPPED flag if an inline symlink checks out ok, even after a repair. Fix that.
--- fs/xfs/scrub/symlink.c | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-)
fs/xfs/scrub/symlink.c +8 -9
@@ -70,21 +70,20 @@ xchk_symlink(return 0 ; } -/* Inline symlink? */ if (ifp->if_format ==XFS_DINODE_FMT_LOCAL ) { +/* Inline symlink? */ if (len >xfs_inode_data_fork_size (ip) || len >strnlen (ifp->if_data,xfs_inode_data_fork_size (ip)))xchk_fblock_set_corrupt (sc,XFS_DATA_FORK ,0 ); -return 0 ; + }else { +/* Remote symlink; must read the contents. */ + error =xfs_symlink_remote_read (sc->ip, sc->buf); +if (!xchk_fblock_process_error (sc,XFS_DATA_FORK ,0 , &error)) +return error; +if (strnlen (sc->buf,XFS_SYMLINK_MAXLEN ) < len) +xchk_fblock_set_corrupt (sc,XFS_DATA_FORK ,0 ); } -/* Remote symlink; must read the contents. */ - error =xfs_symlink_remote_read (sc->ip, sc->buf); -if (!xchk_fblock_process_error (sc,XFS_DATA_FORK ,0 , &error)) -return error; -if (strnlen (sc->buf,XFS_SYMLINK_MAXLEN ) < len) -xchk_fblock_set_corrupt (sc,XFS_DATA_FORK ,0 ); -/* If a remote symlink is clean, it is clearly not zapped. */ xchk_mark_healthy_if_clean (sc,XFS_SICK_INO_SYMLINK_ZAPPED );return 0 ;
Greg Kroah-Hartman
maintainerPATCH 688/1536 xfs: compute the correct fdblocks/frextents for repair when theyre negative
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit f98d007017acf0eaec2e116ff9c0ece735f61bb3 upstream.
LOLLM observed that if either fdblocks or frextents are negative, we'll set the CORRUPT flag and exit immediately. This doesn't work for a repair because we still have to walk the filesystem metadata to compute the correct summary counters so that we can install the new values. Currently we just write zeroes into the summary counters, which isn't right.
--- fs/xfs/scrub/fscounters.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/fscounters.c +4 -1
@@ -533,7 +533,10 @@ xchk_fscounters(return -EDEADLOCK ;xchk_set_corrupt (sc); -return 0 ; + +/* Need to compute all the fields in fsc for a repair */ +if (!xchk_could_repair (sc)) +return 0 ; }/* See if icount is obviously wrong. */
Greg Kroah-Hartman
maintainerPATCH 689/1536 xfs: fix ondisk symlink target validation in xrep_dinode_check_dfork
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit aafe21c23ad8263251085291019d8860ddc51da9 upstream.
LOLLM noticed that online repair of a broken symlink file could fail unnecessarily if a local-format symlink target isn't null terminated. The ondisk target isn't required to be null terminated, but repair enforces that anyway because it uses the validator for the incore symlink target. (The incore buffer is always null-terminated). Fix this by reverting the changes to xfs_symlink_shortform_verify and adding an ondisk-specific helper in inode_repair.c.
--- fs/xfs/libxfs/xfs_inode_fork.c | 4 +--- fs/xfs/libxfs/xfs_symlink_remote.c | 8 ++++++-- fs/xfs/libxfs/xfs_symlink_remote.h | 2 +- fs/xfs/scrub/inode_repair.c | 26 +++++++++++++++++++++++++- 4 files changed, 33 insertions(+), 7 deletions(-)
fs/xfs/libxfs/xfs_inode_fork.c +1 -3
@@ -722,9 +722,7 @@ xfs_ifork_verify_local_data(break ; }case S_IFLNK : { -struct xfs_ifork *ifp =xfs_ifork_ptr (ip,XFS_DATA_FORK ); - - fa =xfs_symlink_shortform_verify (ifp->if_data, ifp->if_bytes); + fa =xfs_symlink_shortform_verify (ip);break ; }default :
fs/xfs/libxfs/xfs_symlink_remote.c +6 -2
@@ -208,11 +208,15 @@ xfs_symlink_local_to_remote(*/ xfs_failaddr_t xfs_symlink_shortform_verify ( -void *sfp, -int64_t size) +struct xfs_inode *ip) { +struct xfs_ifork *ifp =xfs_ifork_ptr (ip,XFS_DATA_FORK ); +char *sfp = (char *)ifp->if_data; +int size = ifp->if_bytes;char *endp = sfp + size; +ASSERT (ifp->if_format ==XFS_DINODE_FMT_LOCAL ); +/* * Zero length symlinks should never occur in memory as they are * never allowed to exist on disk.
fs/xfs/libxfs/xfs_symlink_remote.h +1 -1
@@ -18,7 +18,7 @@ bool xfs_symlink_hdr_ok(xfs_ino_t ino, uvoid xfs_symlink_local_to_remote (struct xfs_trans *tp,struct xfs_buf *bp,struct xfs_inode *ip,struct xfs_ifork *ifp,void *priv); -xfs_failaddr_t xfs_symlink_shortform_verify (void *sfp,int64_t size); +xfs_failaddr_t xfs_symlink_shortform_verify (struct xfs_inode *ip);int xfs_symlink_remote_read (struct xfs_inode *ip,char *link); int xfs_symlink_write_target(struct xfs_trans *tp, struct xfs_inode *ip, xfs_ino_t owner, const char *target_path, int pathlen,
fs/xfs/scrub/inode_repair.c +25 -1
@@ -872,6 +872,30 @@ xrep_dinode_bad_bmbt_fork(return false; } +static xfs_failaddr_t +xrep_symlink_shortform_verify ( +void *sfp, +int64_t size) +{ +/* +* Zero length symlinks should never occur in memory as they are +* never allowed to exist on disk. +*/ +if (!size) +return __this_address; + +/* No negative sizes or overly long symlink targets. */ +if (size <0 || size >XFS_SYMLINK_MAXLEN ) +return __this_address; + +/* No NULLs in the target either. */ +if (memchr (sfp,0 , size)) +return __this_address; + +/* ondisk symlink target isn't null terminated, unlike incore */ +return NULL ; +} +/* * Check the data fork for things that will fail the ifork verifiers or the * ifork formatters.
@@ -939,7 +963,7 @@ xrep_dinode_check_dfork(return true;/* symlink structure must pass verification. */ if (S_ISLNK (mode) && -xfs_symlink_shortform_verify (dfork_ptr, data_size) !=NULL ) +xrep_symlink_shortform_verify (dfork_ptr, data_size) !=NULL )return true;break ;case XFS_DINODE_FMT_EXTENTS :
Greg Kroah-Hartman
maintainerPATCH 690/1536 xfs: fix xfs_rename_space_res for non-pptr filesystems
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit a800b926346c3aa2482421f5c0272280ee7d32e8 upstream.
We don't need to reserve space for a parent pointer update for an existing target if parent pointers are disabled. Fix this regression (which LOLLM noticed) so that rename reservations go back to what they were before parent pointers.
--- fs/xfs/libxfs/xfs_trans_space.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
fs/xfs/libxfs/xfs_trans_space.c +3 -3
@@ -112,10 +112,10 @@ xfs_rename_space_res(if (has_whiteout) ret +=xfs_parent_calc_space_res (mp, src_namelen); ret +=2 *xfs_parent_calc_space_res (mp, target_namelen); - } -if (target_exists) - ret +=xfs_parent_calc_space_res (mp, target_namelen); +if (target_exists) + ret +=xfs_parent_calc_space_res (mp, target_namelen); + }return ret; }
Greg Kroah-Hartman
maintainerPATCH 691/1536 xfs: fix missing xfs_qm_adjust_dqlimits call in quotacheck repair
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit da483b8a9c2c3e7b23655699680feb57a194000c upstream.
LOLLM noticed that everywhere else in the kernel, a call to xfs_qm_adjust_dqlimits precedes every call to xfs_qm_adjust_dqtimers. In particular, mount-time quotacheck does this, but online quotacheck does not.
Looking at xfs_qm_adjust_dqlimits, that function is in charge of conveying default limits to a dquot if that dquot's limits have been zeroed. That's quite possible in a repair, so we actually need to do that.
However, there's a pre-existing pattern in the kernel -- for non-root dquots, first we call xfs_qm_adjust_dqlimits to set the dquot's limits to the defaults if they are zero, and then xfs_qm_adjust_dqtimers to start grace periods if the dquot's usage is above the softlimit. The grace period decision cannot be made correctly if we forget to import the default limits.
Therefore, let's combine both into a single xfs_qm_adjust_dqenforcement helper that takes care of both pieces, which fixes quotacheck and makes it hard to repeat this mistake.
--- fs/xfs/scrub/quota_repair.c | 5 +---- fs/xfs/scrub/quotacheck_repair.c | 3 +-- fs/xfs/xfs_dquot.c | 20 +++++++++++++++----- fs/xfs/xfs_dquot.h | 2 +- fs/xfs/xfs_qm.c | 6 +----- fs/xfs/xfs_trans_dquot.c | 6 +----- 6 files changed, 20 insertions(+), 22 deletions(-)
fs/xfs/scrub/quota_repair.c +1 -4
@@ -252,10 +252,7 @@ xrep_quota_item( dq->q_flags |=XFS_DQFLAG_DIRTY ;xfs_trans_dqjoin (sc->tp, dq); -if (dq->q_id) { -xfs_qm_adjust_dqlimits (dq); -xfs_qm_adjust_dqtimers (dq); - } +xfs_qm_adjust_dqenforcement (dq);xfs_trans_log_dquot (sc->tp, dq); error =xfs_trans_roll (&sc->tp);xfs_dqlock (dq);
fs/xfs/scrub/quotacheck_repair.c +1 -2
@@ -112,8 +112,7 @@ xqcheck_commit_dquot(/* Commit the dirty dquot to disk. */ dq->q_flags |=XFS_DQFLAG_DIRTY ; -if (dq->q_id) -xfs_qm_adjust_dqtimers (dq); +xfs_qm_adjust_dqenforcement (dq);xfs_trans_log_dquot (xqc->sc->tp, dq);/*
fs/xfs/xfs_dquot.c +15 -5
@@ -115,18 +115,15 @@ xfs_qm_dqdestroy(* We overwrite the dquot limits only if they are zero and this * is not the root dquot. */ -void +static void xfs_qm_adjust_dqlimits (struct xfs_dquot *dq) {struct xfs_mount *mp = dq->q_mount;struct xfs_quotainfo *q = mp->m_quotainfo; -struct xfs_def_quota *defq; +struct xfs_def_quota *defq =xfs_get_defquota (q,xfs_dquot_type (dq));int prealloc =0 ; -ASSERT (dq->q_id); - defq =xfs_get_defquota (q,xfs_dquot_type (dq)); -if (!dq->q_blk.softlimit) { dq->q_blk.softlimit = defq->blk.soft; prealloc =1 ;
@@ -219,6 +216,19 @@ xfs_qm_adjust_dqtimers(xfs_qm_adjust_res_timer (dq->q_mount, &dq->q_rtb, &defq->rtb); } +/* Adjust enforcement limits and timers after a change in usage. */ +void +xfs_qm_adjust_dqenforcement ( +struct xfs_dquot *dq) +{ +if (dq->q_id ==0 ) +return ; + +xfs_qm_adjust_dqlimits (dq); +xfs_qm_adjust_dqtimers (dq); + dq->q_flags |=XFS_DQFLAG_DIRTY ; +} +/* * initialize a buffer full of dquots and log the whole thing */
fs/xfs/xfs_dquot.h +1 -1
@@ -207,7 +207,7 @@ void xfs_qm_dqdestroy(struct xfs_dquotint xfs_qm_dqflush (struct xfs_dquot *dqp,struct xfs_buf *bp);void xfs_qm_dqunpin_wait (struct xfs_dquot *dqp);void xfs_qm_adjust_dqtimers (struct xfs_dquot *d); -void xfs_qm_adjust_dqlimits (struct xfs_dquot *d); +void xfs_qm_adjust_dqenforcement (struct xfs_dquot *d);xfs_dqid_t xfs_qm_id_for_quotatype (struct xfs_inode *ip,xfs_dqtype_t type); int xfs_qm_dqget(struct xfs_mount *mp, xfs_dqid_t id,
fs/xfs/xfs_qm.c +1 -5
@@ -1135,11 +1135,7 @@ xfs_qm_quotacheck_dqadjust(* * There are no timers for the default values set in the root dquot. */ -if (dqp->q_id) { -xfs_qm_adjust_dqlimits (dqp); -xfs_qm_adjust_dqtimers (dqp); - } - +xfs_qm_adjust_dqenforcement (dqp); dqp->q_flags |=XFS_DQFLAG_DIRTY ; out_unlock:xfs_qm_dqput (dqp);
fs/xfs/xfs_trans_dquot.c +1 -5
@@ -562,11 +562,7 @@ xfs_trans_apply_dquot_deltas(* Get any default limits in use. * Start/reset the timer(s) if needed. */ -if (dqp->q_id) { -xfs_qm_adjust_dqlimits (dqp); -xfs_qm_adjust_dqtimers (dqp); - } - +xfs_qm_adjust_dqenforcement (dqp); dqp->q_flags |=XFS_DQFLAG_DIRTY ;/* * add this to the list of items to get logged
Greg Kroah-Hartman
maintainerPATCH 692/1536 xfs: fix buffer overruns in xfs_ioc_attr_list
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 0b9081a774ee7b9dff1e9ac3765b73c1d6bba5b2 upstream.
When we converted the al_offset array in struct xfs_attrlist into a VLA, the size of the object shrank by 4 bytes. Unfortunately, the buffer size validation in the attrlist ioctl wasn't updated to notice this, so the al_offset[0] assignment blindly writes off the end of the buffer. LOLLM noticed the omitted check and complained.
--- fs/xfs/xfs_handle.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/xfs_handle.c +1 -1
@@ -433,7 +433,7 @@ xfs_ioc_attr_list(void *buffer;int error; -if (bufsize <sizeof (struct xfs_attrlist ) || +if (bufsize <struct_size (alist, al_offset,1 ) || bufsize >XFS_XATTR_LIST_MAX )return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 693/1536 xfs: online quotacheck must dirty dquot if enforcement adjustments needed
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 244425cf63d7e3a0ff5736b41f0e0afe807f7031 upstream.
LOLLM noticed that we have no way to force xchk_commit_dquot to call xfs_qm_adjust_dqenforcement if nothing else is wrong with the dquot. Therefore, add a new predicate to force the dirty flag if the dquot has zero limits and there are default limits; or if the grace period timer needs adjusting.
--- fs/xfs/scrub/quotacheck_repair.c | 51 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+)
fs/xfs/scrub/quotacheck_repair.c +51 -0
@@ -39,6 +39,54 @@* dquot is locked. */ +static bool +xqcheck_dqres_force_dirty ( +const struct xfs_dquot_res *res, +const struct xfs_quota_limits *qlim) +{ +/* zero limits mean that we should set the default limits */ +if (res->softlimit ==0 && qlim->soft !=0 ) +return true; +if (res->hardlimit ==0 && qlim->hard !=0 ) +return true; + +/* do we need to adjust the timer setting? */ +if ((res->softlimit && res->count > res->softlimit) || + (res->hardlimit && res->count > res->hardlimit)) { +if (!res->timer) +return true; + }else { +if (res->timer) +return true; + } + +return false; +} + +/* Decide if we need to adjust the dquot limits or timers */ +static bool +xqcheck_dquot_force_dirty ( +const struct xfs_dquot *dq) +{ +struct xfs_quotainfo *qi = dq->q_mount->m_quotainfo; +struct xfs_def_quota *defq; + +/* root dquot does not enforce limits */ +if (dq->q_id ==0 ) +return false; + + defq =xfs_get_defquota (qi,xfs_dquot_type (dq)); + +if (xqcheck_dqres_force_dirty (&dq->q_blk, &defq->blk)) +return true; +if (xqcheck_dqres_force_dirty (&dq->q_ino, &defq->ino)) +return true; +if (xqcheck_dqres_force_dirty (&dq->q_rtb, &defq->rtb)) +return true; + +return false; +} +/* Commit new counters to a dquot. */ static int xqcheck_commit_dquot(
@@ -93,6 +141,9 @@ xqcheck_commit_dquot( dirty = true; } +if (!dirty &&xqcheck_dquot_force_dirty (dq)) + dirty = true; + xcdq.flags |= (XQCHECK_DQUOT_REPAIR_SCANNED |XQCHECK_DQUOT_WRITTEN ); error =xfarray_store (counts, dq->q_id, &xcdq);if (error == -EFBIG ) {
Greg Kroah-Hartman
maintainerPATCH 694/1536 xfs: fix unnecessary dapos truncation in xchk_dir_walk
In reply to Greg Kroah-Hartman6.12-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
@@ -238,7 +238,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 695/1536 xfs: fix buffer overflow in corrupt inline attr structure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 017dd7a84ff4cd2275eb62f4ee6d63c705bac107 upstream.
LOLLM noticed a buffer overrun if the xattr scrubber encounters a file with a shortform attr fork with sf->count > 0 but if_bytes == sizeof(struct xfs_attr_sf_hdr). Basically, we have enough data to have a header with a nonzero count, but no space for any of those shortform entries. In this case, the xfs_attr_sf_nextentry() call will run off the end of if_data and blow up.
--- fs/xfs/scrub/attr.c | 11 +++++++++-- fs/xfs/scrub/attr_repair.c | 3 +++ 2 files changed, 12 insertions(+), 2 deletions(-)
fs/xfs/scrub/attr.c +9 -2
@@ -590,12 +590,17 @@ xchk_xattr_check_sf( }for (i =0 ; i < sf->count; i++) { -unsigned char *name = sfe->nameval; -unsigned char *value = &sfe->nameval[sfe->namelen]; +unsigned char *name; +unsigned char *value;if (xchk_should_terminate (sc, &error))return error; +if ((unsigned char *)(sfe +1 ) >= end) { +xchk_fblock_set_corrupt (sc,XFS_ATTR_FORK ,0 ); +break ; + } + next =xfs_attr_sf_nextentry (sfe);if ((unsigned char *)next > end) {xchk_fblock_set_corrupt (sc,XFS_ATTR_FORK ,0 );
@@ -618,6 +623,7 @@ xchk_xattr_check_sf(break ; } + name = sfe->nameval;if (!xchk_xattr_set_map (sc, ab->usedmap, (char *)name - (char *)sf, sfe->namelen)) {
@@ -625,6 +631,7 @@ xchk_xattr_check_sf(break ; } + value = &sfe->nameval[sfe->namelen];if (!xchk_xattr_set_map (sc, ab->usedmap, (char *)value - (char *)sf, sfe->valuelen)) {
fs/xfs/scrub/attr_repair.c +3 -0
@@ -477,6 +477,9 @@ xrep_xattr_recover_sf(if (xchk_should_terminate (sc, &error))return error; +if ((unsigned char *)(sfe +1 ) >= end) +break ; + next =xfs_attr_sf_nextentry (sfe);if ((unsigned char *)next > end)break ;
Greg Kroah-Hartman
maintainerPATCH 696/1536 xfs: actually report corrupt xattrs as XFAIL during cross-referencing
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit b339cc253019518c61b8b150fb7ea727fdae59f4 upstream.
Some LLM reports that xchk_dir_parent_pointer really ought to report xattr corruption errors as XFAIL (cross-referencing failed) when a directory scrub tries to find the parent pointer for a dirent name. Let's do that.
--- fs/xfs/scrub/dir.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/scrub/dir.c +2 -0
@@ -147,6 +147,8 @@ xchk_dir_parent_pointer( &sd->pptr_args);if (error == -ENOATTR )xchk_fblock_xref_set_corrupt (sc,XFS_DATA_FORK ,0 ); +else +xchk_fblock_xref_process_error (sc,XFS_DATA_FORK ,0 , &error);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 697/1536 xfs: fix inode btree repair when a cluster is larger than a chunk
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 65b89ac3e8c2f041384f715a71b9d113edfa32e5 upstream.
LOLLM noticed that on filesystems where an inode cluster buffer is larger than an inode chunk, we can run through the loop body in xrep_ibt_process_cluster more than once, and the number of inodes that we pass to xrep_ibt_cluster_record is incorrectly large. In this case we can run right off the end of the buffer. Fix this by moving the nr_inodes computation inside the loop.
Note that this is only likely to happen on filesystems with (say) 512b inodes and 64k fsblocks.
--- fs/xfs/scrub/ialloc_repair.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
fs/xfs/scrub/ialloc_repair.c +4 -4
@@ -296,12 +296,8 @@ xrep_ibt_process_cluster(struct xfs_ino_geometry *igeo =M_IGEO (mp);xfs_agino_t cluster_ag_base;xfs_agino_t irec_index; -unsigned int nr_inodes;int error; - nr_inodes = min_t(unsigned int, igeo->inodes_per_cluster, -XFS_INODES_PER_CHUNK ); -/* * Grab the inode cluster buffer. This is safe to do with a broken * inobt because imap_to_bp directly maps the buffer without touching
@@ -322,6 +318,10 @@ xrep_ibt_process_cluster(for (irec_index =0 ; irec_index < igeo->inodes_per_cluster; irec_index +=XFS_INODES_PER_CHUNK ) { +unsigned int nr_inodes = + min_t(unsigned int, XFS_INODES_PER_CHUNK, + igeo->inodes_per_cluster - irec_index); + error =xrep_ibt_cluster_record (ri, cluster_ag_base + irec_index, cluster_bp, nr_inodes);
Greg Kroah-Hartman
maintainerPATCH 698/1536 xfs: always reset incore attr fork buffer when resetting fork
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 71cb13685e72a3c5d118732559c727a0c9090b7f upstream.
LOLLM noticed that the local format attr fork verifier depends on if_bytes being set correctly. However, the fork reset function doesn't reset that correctly, which can cause post-repair verifier failures. Fix that.
--- fs/xfs/scrub/attr_repair.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/xfs/scrub/attr_repair.c +2 -2
@@ -840,11 +840,11 @@ xrep_xattr_full_reset(ASSERT (ifp->if_bytes ==0 ); ifp->if_format =XFS_DINODE_FMT_LOCAL ; -xfs_idata_realloc (sc->tempip,sizeof (*hdr),XFS_ATTR_FORK ); }/* Reinitialize the attr fork to an empty shortform structure. */ - hdr = ifp->if_data; + hdr =xfs_idata_realloc (sc->tempip, + (int64_t )sizeof (*hdr) - ifp->if_bytes,XFS_ATTR_FORK );memset (hdr,0 ,sizeof (*hdr)); hdr->totsize =cpu_to_be16 (sizeof (*hdr));xfs_trans_log_inode (sc->tp, sc->tempip,XFS_ILOG_CORE |XFS_ILOG_ADATA );
Signature · 1 line
2.56.0
Greg Kroah-Hartman
maintainerPATCH 699/1536 xfs: dont pass iget failures up when marking ondisk inodes
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 7f5e8bf335e5e257fb82cf5b3521980ded60e863 upstream.
LOLLM observes a couple of problems with this callsite -- an ENOMEM return is completely ignored and a subsequent run through the loop body obliterates the return value completely. Also, an error value indicating that the list is corrupt can get passed up (thus terminating the repair) even though we can handle corrupt lists. Fix the callsite not to have these problems.
--- fs/xfs/scrub/agheader_repair.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
fs/xfs/scrub/agheader_repair.c +5 -1
@@ -1323,8 +1323,12 @@ xrep_iunlink_mark_ondisk_rec(XFS_AGINO_TO_INO (mp, sc->sa.pag->pag_agno, agino), &ip); -if (error) +if (error == -ENOMEM ) +return error; +if (error) { + error =0 ;continue ; + }trace_xrep_iunlink_reload_ondisk (ip);
Greg Kroah-Hartman
maintainerPATCH 700/1536 xfs: dont fix the directory tree if live update fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit c8226f3d1a7eafe472addc232689e9c9a0c36a1c upstream.
LOLLM complains that we don't double-check dl->aborted one last time to before committing repairs to the filesystem. This is important because the live update handler could have set ->aborted if it encountered a runtime error.
--- fs/xfs/scrub/dirtree_repair.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/xfs/scrub/dirtree_repair.c +5 -0
@@ -427,6 +427,11 @@ again: error = -ESTALE ; goto out_trans_cancel; } +if (dl->aborted) { +mutex_unlock (&dl->lock); + error = -EIO ; + goto out_trans_cancel; + }xrep_dirpath_set_outcome (dl, path,XREP_DIRPATH_DELETING );mutex_unlock (&dl->lock);
Greg Kroah-Hartman
maintainerPATCH 701/1536 xfs: dont proceed with xattr repair if the live update fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 833f98b3be45bc7c6ce4c87bdc4892f546ab72ee upstream.
LOLLM observes that we ought to make one last check for failed live updates before replacing the xattr structure. Let's be cautious here.
--- fs/xfs/scrub/attr_repair.c | 3 +++ 1 file changed, 3 insertions(+)
fs/xfs/scrub/attr_repair.c +3 -0
@@ -1477,6 +1477,9 @@ xrep_xattr_rebuild_tree(if (error)return error; +if (rx->live_update_aborted) +return -EIO ; +/* * Exchange the blocks mapped by the tempfile's attr fork with the file * being repaired. The old attr blocks will then be attached to the
Greg Kroah-Hartman
maintainerPATCH 702/1536 xfs: fix skipped inode mask handling in iscan
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 63341d4af16fe850716b454fcd18990590d07d97 upstream.
xfs_highbit64() returns -1 if none of the bits in its argument are set. In this particular callsite, a totally zeroed mask means that no inodes were skipped, so executing the if-body is incorrect. Fix that.
--- fs/xfs/scrub/iscan.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/iscan.c +1 -1
@@ -545,7 +545,7 @@ xchk_iscan_finish_batch(mutex_lock (&iscan->lock); -if (iscan->__batch_ino !=NULLFSINO ) { +if (iscan->__batch_ino !=NULLFSINO && iscan->__skipped_inomask) { highest_skipped = iscan->__batch_ino +xfs_highbit64 (iscan->__skipped_inomask); iscan->__visited_ino = max(iscan->__visited_ino,
Greg Kroah-Hartman
maintainerPATCH 703/1536 xfs: dont repair fs summary counters with garbage
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 22a8a7501c0146dba4ce99b8256975ffe945125d upstream.
LOLLM noticed that if we scan the filesystem and come up with totally garbage numbers for the summary counters, we don't actually mark the scan incomplete. Because we don't do this, repair can install the garbage values into the filesystem, making things worse. Don't do that.
--- fs/xfs/scrub/fscounters.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/fscounters.c +3 -1
@@ -368,8 +368,10 @@ retry:/* Bail out if the values we compute are totally nonsense. */ if (fsc->icount < fsc->icount_min || fsc->icount > fsc->icount_max || fsc->fdblocks > mp->m_sb.sb_dblocks || - fsc->ifree > fsc->icount_max) + fsc->ifree > fsc->icount_max) { +xchk_set_incomplete (sc);return -EFSCORRUPTED ; + }/* * If ifree > icount then we probably had some perturbation in the
Greg Kroah-Hartman
maintainerPATCH 704/1536 xfs: fix lost errno returned from xfarray_foliosort
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 8c4f172c246717b1420f138a159ed15c315a58bd upstream.
LOLLM noticed that we stop the sort early but don't actually pass along the error code, which could enable repair code to continue running with an unsorted array. Fix that.
--- fs/xfs/scrub/xfarray.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/xfarray.c +3 -1
@@ -943,8 +943,10 @@ xfarray_sort(* problems, we're done. */ ret =xfarray_foliosort (si, lo, hi); -if (ret <0 ) +if (ret <0 ) { + error = ret; goto out_free; + }if (ret ==1 ) { si->stack_depth--;continue ;
Greg Kroah-Hartman
maintainerPATCH 705/1536 xfs: allow softlimit with no hardlimit in quota scrub
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 342c2e00b3a99099a7088f7b8c8f075670c603a9 upstream.
LOLLM observes that the sysadmin can set a user's soft limit to a nonzero value and the hard limit to zero, so those aren't corruptions.
--- fs/xfs/scrub/quota.c | 8 ++++---- fs/xfs/scrub/quota_repair.c | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-)
fs/xfs/scrub/quota.c +4 -4
@@ -185,21 +185,21 @@ xchk_quota_item(* suspect, which is why we flag it for review. * * Complain about corruption if the soft limit is greater than -* the hard limit. +* the hard limit and there's a hard limit set. */ if (dq->q_blk.hardlimit > mp->m_sb.sb_dblocks)xchk_fblock_set_warning (sc,XFS_DATA_FORK , offset); -if (dq->q_blk.softlimit > dq->q_blk.hardlimit) +if (dq->q_blk.hardlimit && dq->q_blk.softlimit > dq->q_blk.hardlimit)xchk_fblock_set_corrupt (sc,XFS_DATA_FORK , offset);if (dq->q_ino.hardlimit >M_IGEO (mp)->maxicount)xchk_fblock_set_warning (sc,XFS_DATA_FORK , offset); -if (dq->q_ino.softlimit > dq->q_ino.hardlimit) +if (dq->q_ino.hardlimit && dq->q_ino.softlimit > dq->q_ino.hardlimit)xchk_fblock_set_corrupt (sc,XFS_DATA_FORK , offset);if (dq->q_rtb.hardlimit > mp->m_sb.sb_rblocks)xchk_fblock_set_warning (sc,XFS_DATA_FORK , offset); -if (dq->q_rtb.softlimit > dq->q_rtb.hardlimit) +if (dq->q_rtb.hardlimit && dq->q_rtb.softlimit > dq->q_rtb.hardlimit)xchk_fblock_set_corrupt (sc,XFS_DATA_FORK , offset);/* Check the resource counts. */
fs/xfs/scrub/quota_repair.c +3 -3
@@ -197,17 +197,17 @@ xrep_quota_item(return error;/* Check the limits. */ -if (dq->q_blk.softlimit > dq->q_blk.hardlimit) { +if (dq->q_blk.hardlimit && dq->q_blk.softlimit > dq->q_blk.hardlimit) { dq->q_blk.softlimit = dq->q_blk.hardlimit; dirty = true; } -if (dq->q_ino.softlimit > dq->q_ino.hardlimit) { +if (dq->q_ino.hardlimit && dq->q_ino.softlimit > dq->q_ino.hardlimit) { dq->q_ino.softlimit = dq->q_ino.hardlimit; dirty = true; } -if (dq->q_rtb.softlimit > dq->q_rtb.hardlimit) { +if (dq->q_rtb.hardlimit && dq->q_rtb.softlimit > dq->q_rtb.hardlimit) { dq->q_rtb.softlimit = dq->q_rtb.hardlimit; dirty = true; }
Greg Kroah-Hartman
maintainerPATCH 706/1536 xfs: assign an owner to scrub_stats_fops
In reply to Greg Kroah-Hartman6.12-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
@@ -290,6 +290,7 @@ out: }static const struct file_operations scrub_stats_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = xchk_scrub_stats_read, };
@@ -317,6 +318,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 707/1536 xfs: bail out of directory tree repairs on error
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit d83ca4e7cc65dce6a02fd3427cefd174517657a3 upstream.
LOLLM complains that we ignore errors returned by xrep_dirpath_retain_parent and can set the dotdot entry to random stack garbage. Fix that by passing errors all the way out.
--- fs/xfs/scrub/dirtree_repair.c | 57 ++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 21 deletions(-)
fs/xfs/scrub/dirtree_repair.c +36 -21
@@ -94,7 +94,7 @@ xrep_dirtree_delete_all_paths( }/* Since this is the surviving path, set the dotdot entry to this value. */ -STATIC void +STATIC intxrep_dirpath_retain_parent (struct xchk_dirtree *dl,struct xchk_dirpath *path)
@@ -104,18 +104,20 @@ xrep_dirpath_retain_parent( error =xfarray_load (dl->path_steps, path->first_step, &step);if (error) -return ; +return error; dl->parent_ino =be64_to_cpu (step.pptr_rec.p_ino); +return 0 ; }/* Find the one surviving path so we know how to set dotdot. */ -STATIC void +STATIC intxrep_dirtree_find_surviving_path (struct xchk_dirtree *dl,struct xchk_dirtree_outcomes *oc) {struct xchk_dirpath *path; +int error;bool foundit = false;xchk_dirtree_for_each_path (dl, path) {
@@ -124,7 +126,10 @@ xrep_dirtree_find_surviving_path(case XCHK_DIRPATH_LOOP :case XCHK_DIRPATH_OK :if (!foundit) { -xrep_dirpath_retain_parent (dl, path); + error =xrep_dirpath_retain_parent (dl, path); +if (error) +return error; + foundit = true;continue ; }
@@ -136,16 +141,19 @@ xrep_dirtree_find_surviving_path( }ASSERT (oc->suspect + oc->good ==1 ); + +return 0 ; }/* Delete all paths except for the one good one. */ -STATIC void +STATIC intxrep_dirtree_keep_one_good_path (struct xchk_dirtree *dl,struct xchk_dirtree_outcomes *oc) {struct xchk_dirpath *path;bool foundit = false; +int error;xchk_dirtree_for_each_path (dl, path) {switch (path->outcome) {
@@ -157,7 +165,10 @@ xrep_dirtree_keep_one_good_path(break ;case XCHK_DIRPATH_OK :if (!foundit) { -xrep_dirpath_retain_parent (dl, path); + error =xrep_dirpath_retain_parent (dl, path); +if (error) +return error; + foundit = true;continue ; }
@@ -172,23 +183,28 @@ xrep_dirtree_keep_one_good_path(ASSERT (oc->suspect ==0 );ASSERT (oc->good <2 ); +return 0 ; }/* Delete all paths except for one suspect one. */ -STATIC void +STATIC intxrep_dirtree_keep_one_suspect_path (struct xchk_dirtree *dl,struct xchk_dirtree_outcomes *oc) {struct xchk_dirpath *path;bool foundit = false; +int error =0 ;xchk_dirtree_for_each_path (dl, path) {switch (path->outcome) {case XCHK_DIRPATH_CORRUPT :case XCHK_DIRPATH_LOOP :if (!foundit) { -xrep_dirpath_retain_parent (dl, path); + error =xrep_dirpath_retain_parent (dl, path); +if (error) +return error; + foundit = true;continue ; }
@@ -206,13 +222,14 @@ xrep_dirtree_keep_one_suspect_path(ASSERT (oc->suspect ==1 );ASSERT (oc->good ==0 ); +return error; }/* * Figure out what to do with the paths we tried to find. Returns -EDEADLOCK * if the scan results have become stale. */ -STATIC void +STATIC intxrep_dirtree_decide_fate (struct xchk_dirtree *dl,struct xchk_dirtree_outcomes *oc)
@@ -222,36 +239,32 @@ xrep_dirtree_decide_fate(/* Parentless directories should not have any paths at all. */ if (xchk_dirtree_parentless (dl)) {xrep_dirtree_delete_all_paths (dl, oc); -return ; +return 0 ; }/* One path is exactly the number of paths we want. */ -if (oc->good + oc->suspect ==1 ) { -xrep_dirtree_find_surviving_path (dl, oc); -return ; - } +if (oc->good + oc->suspect ==1 ) +return xrep_dirtree_find_surviving_path (dl, oc);/* Zero paths means we should reattach the subdir to the orphanage. */ if (oc->good + oc->suspect ==0 ) {if (dl->sc->orphanage) oc->needs_adoption = true; -return ; +return 0 ; }/* * Otherwise, this subdirectory has too many parents. If there's at * least one good path, keep it and delete the others. */ -if (oc->good >0 ) { -xrep_dirtree_keep_one_good_path (dl, oc); -return ; - } +if (oc->good >0 ) +return xrep_dirtree_keep_one_good_path (dl, oc);/* * There are no good paths and there are too many suspect paths. * Keep the first suspect path and delete the rest. */ -xrep_dirtree_keep_one_suspect_path (dl, oc); +return xrep_dirtree_keep_one_suspect_path (dl, oc); }/*
@@ -824,7 +837,9 @@ xrep_dirtree(* to walk again. */ if (!dl->stale) { -xrep_dirtree_decide_fate (dl, &oc); + error =xrep_dirtree_decide_fate (dl, &oc); +if (error) +break ;trace_xrep_dirtree_decided_fate (dl, &oc);
Greg Kroah-Hartman
maintainerPATCH 708/1536 xfs: fix revalidation of xchk_dquot_iter cached mappings
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 6c64d650460b455980a6023d43bc6c8859c1cfd2 upstream.
LOLLM noticed that the purpose of xchk_dquot_iter_revalidate_bmap is to revalidate the quota file mapping after we've (presumably) done something to the quota file contents. However, the "yes this is valid" code isn't quite strong enough -- the mapping must cover at least the block at fileoff, not just end after fileoff. Fix that.
--- fs/xfs/scrub/dqiterate.c | 1 + 1 file changed, 1 insertion(+)
fs/xfs/scrub/dqiterate.c +1 -0
@@ -58,6 +58,7 @@ xchk_dquot_iter_revalidate_bmap(* no need to reread the bmbt. */ if (cursor->bmap.br_startoff !=NULLFILEOFF && + cursor->bmap.br_startoff <= fileoff && cursor->if_seq == ifp->if_seq && cursor->bmap.br_startoff + cursor->bmap.br_blockcount > fileoff)return 0 ;
Greg Kroah-Hartman
maintainerPATCH 709/1536 xfs: abort dirtree repair if the live update hook dies
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 07732dea4f5d0410e1566b81a58a1154bf9dcb29 upstream.
LOLLM notices that if the live update hook for the directory tree repair code hits an error, it will set dl->aborted and stops working. If the repair code ever sees that condition, it ought to bail out immediately instead of continuing with obsolete data.
--- fs/xfs/scrub/dirtree_repair.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/xfs/scrub/dirtree_repair.c +5 -0
@@ -831,6 +831,11 @@ xrep_dirtree(*/ mutex_lock (&dl->lock); do { + if (dl->aborted) { + error = -EIO; + break; + } + /* * Decide what we're going to do, then do it. An -ESTALE * return here means the scan results are invalid and we have
Greg Kroah-Hartman
maintainerPATCH 710/1536 xfs: check fork type against dabtree block magic number
In reply to Greg Kroah-Hartman6.12-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
@@ -410,6 +410,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 ;
@@ -419,6 +423,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 ;
@@ -428,6 +436,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 711/1536 xfs: mark overfull dabtree node blocks as corrupt
In reply to Greg Kroah-Hartman6.12-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
@@ -451,6 +451,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 712/1536 xfs: jump out of xchk_bmap_check_rmap if fatal signals
In reply to Greg Kroah-Hartman6.12-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
@@ -566,6 +566,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)
@@ -597,6 +601,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 713/1536 xfs: adjust checks for cross-AG reaping issues
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 4c6668ecebc61bb0a53d4c6e95509bc960cf6bbc upstream.
While analyzing the reaping code for the previous patch, I studied the xfs_fsblock_t code to reconstruct how this code works. AGs have a superblock at the start of each AG which means that regions in the xfsb_bitmap (aka xfs_fsblock_t bitmap) cannot cross an AG boundary, so we don't need a loop here like we do for xfs_rtblock_t bitmaps.
However, the checks here are not quite right -- there can be quite a lot of reserved space in COW forks, which means that the bitmap extent actually can exceed XFS_MAX_BMBT_EXTLEN. We also don't have an explicit debugging check that we never cross AGs, so add that here.
--- fs/xfs/scrub/reap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/reap.c +1 -1
@@ -583,9 +583,9 @@ xreap_fsmeta_extent(xfs_agblock_t agbno_next = agbno + len;int error =0 ; -ASSERT (len <=XFS_MAX_BMBT_EXTLEN );ASSERT (sc->ip !=NULL );ASSERT (!sc->sa.pag); +ASSERT (agno ==XFS_FSB_TO_AGNO (sc->mp, fsbno + len -1 ));/* * We're reaping blocks after repairing file metadata, which means that
Greg Kroah-Hartman
maintainerPATCH 714/1536 xfs: fix xchk_stats_estimate_bufsize to allow for the trailing null
In reply to Greg Kroah-Hartman6.12-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
@@ -162,7 +162,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 715/1536 ALSA: usb-audio: Use the right limit for PCM OOB check
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Takashi Iwai <[email protected]>
[ Upstream commit 70b4db7d258118a7464f039112a74ddb49a95b06 ]
The recent fix commit for addressing the OOB access of PCM URB data buffer caused a regression on Behringer UMC2020HD device, resulting in choppy sound. The fix used ep->max_urb_frames for the upper limit check, and this is no right value to be referred.
Use the actual buffer size (ctx->buffer_size) as the upper limit instead, which also avoids the regression on the device above.
--- sound/usb/pcm.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
sound/usb/pcm.c +2 -1
@@ -1505,7 +1505,8 @@ static int prepare_playback_urb(struct snd_usb_substream *subs,for (i =0 ; i < ctx->packets; i++) { counts =snd_usb_endpoint_next_packet_size (ep, ctx, i, avail); -if (counts <0 || frames + counts >= ep->max_urb_frames) +if (counts <0 || + (frames + counts) * stride > ctx->buffer_size)break ;/* set up descriptor */ urb->iso_frame_desc[i].offset = frames * stride;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 716/1536 ksmbd: serialize directory emptiness checks with readdir
In reply to Greg Kroah-Hartman6.12-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
@@ -6570,6 +6570,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);
@@ -6578,9 +6579,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 717/1536 ksmbd: fix breaking_cnt leak on early return in oplock_break()
In reply to Greg Kroah-Hartman6.12-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 718/1536 EDAC/mc: Really fix error path ordering in edac_mc_alloc()
In reply to Greg Kroah-Hartman6.12-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
@@ -366,13 +366,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 719/1536 ufs: fix ufs_read_cylinder() failure handling
In reply to Greg Kroah-Hartman6.12-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 720/1536 media: usbtv: drop redundant device reference
In reply to Greg Kroah-Hartman6.12-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 721/1536 media: usbtv: fix null-pointer dereference on disconnect
In reply to Greg Kroah-Hartman6.12-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
@@ -970,5 +970,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 722/1536 xfs: reject absurdly large xattr value lengths in xchk_xattr_actor
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit fd012955641881169a9f01a00f656f6ca73842ec upstream.
LOLLM suggests that we shouldn't try to allocate absurdly large buffers for xattr value checks because that will push reclaim very hard, never succeed, and is pointless because nobody can create xattrs that large. Since the xattr repair code ignores values larger than XATTR_SIZE_MAX, we can flag the corruption and return early.
--- fs/xfs/scrub/attr.c | 6 ++++++ fs/xfs/scrub/parent_repair.c | 4 ++++ 2 files changed, 10 insertions(+)
fs/xfs/scrub/attr.c +6 -0
@@ -216,6 +216,12 @@ xchk_xattr_actor(return -ECANCELED ; } +/* Don't even try to handle a bizarrely large xattr. */ +if (valuelen >XATTR_SIZE_MAX ) { +xchk_fblock_set_corrupt (sc,XFS_ATTR_FORK , args.blkno); +return -ECANCELED ; + } +/* * Try to allocate enough memory to extract the attr value. If that * doesn't work, return -EDEADLOCK as a signal to try again with a
fs/xfs/scrub/parent_repair.c +4 -0
@@ -914,6 +914,10 @@ xrep_parent_fetch_xattr_remote( };int error; +/* Don't even try to handle a bizarrely large xattr. */ +if (valuelen >XATTR_SIZE_MAX ) +return -EFSCORRUPTED ; +/* * If we need a larger value buffer, try to allocate one. If that * fails, return with -EDEADLOCK to try harder.
Greg Kroah-Hartman
maintainerPATCH 723/1536 xfs: reject out-of-range attribute value lengths in xfs_attr_copy_value
In reply to Greg Kroah-Hartman6.12-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
@@ -582,6 +582,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 ; + +/* * Parent pointer lookups require the caller to specify the name and * value, so don't copy anything. */
Greg Kroah-Hartman
maintainerPATCH 724/1536 xfs: reject remote xattr entries with an out-of-range value length
In reply to Greg Kroah-Hartman6.12-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
@@ -296,6 +296,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 725/1536 xfs: abort directory tree repair whenever dl->aborted is set
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 4582327e7068194d55941b49dd66be211b9e3f90 upstream.
LOLLM observed that if the live update hooks for the directory tree repair code ever fail, they'll set dl->aborted, but then the main repair code path won't check it to exit early. This can cause incorrect repairs, so let's check for hook errors and abort the repair.
--- fs/xfs/scrub/dirtree_repair.c | 9 +++++++++ 1 file changed, 9 insertions(+)
fs/xfs/scrub/dirtree_repair.c +9 -0
@@ -575,6 +575,8 @@ xrep_dirtree_delete_path(if (!error && dl->stale) error = -ESTALE ; +if (!error && dl->aborted) + error = -EIO ;return error; }
@@ -720,6 +722,11 @@ xrep_dirtree_adopt( error = -ESTALE ; goto out_trans; } +if (dl->aborted) { +mutex_unlock (&dl->lock); + error = -EIO ; + goto out_trans; + } error =xrep_dirtree_create_adoption_path (dl);mutex_unlock (&dl->lock);if (error)
@@ -780,6 +787,8 @@ xrep_dirtree_move_to_orphanage(if (!error && dl->stale) error = -ESTALE ; +if (!error && dl->aborted) + error = -EIO ;return error; }
Greg Kroah-Hartman
maintainerPATCH 726/1536 xfs: always forget cached ACLs if the attr fork swap succeeds
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 41ee987f53785b9443388a756912b1a0fe3c9592 upstream.
LOLLM complains that xrep_xattr_rebuild_tree omits the xfs_forget_acl call if the attr fork swap succeeds (and hence the acls might have changed) but reaping the old attr fork fails. Fix it so that we always purge the cached acls if the swap succeeds, even if subsequent steps do not. This avoids some cache coherency problems with access controls.
--- fs/xfs/scrub/attr_repair.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
fs/xfs/scrub/attr_repair.c +3 -3
@@ -1491,7 +1491,7 @@ xrep_xattr_rebuild_tree( error =xrep_xattr_reset_tempfile_fork (sc);if (error) -return error; + goto forget_acls;/* * Roll to get a transaction without any inodes joined to it. Then we
@@ -1500,7 +1500,7 @@ xrep_xattr_rebuild_tree(*/ error =xfs_trans_roll (&sc->tp);if (error) -return error; + goto forget_acls;xrep_tempfile_iunlock (sc);xrep_tempfile_iounlock (sc);
@@ -1509,7 +1509,7 @@ forget_acls:/* Invalidate cached ACLs now that we've reloaded all the xattrs. */ xfs_forget_acl (VFS_I (sc->ip),SGI_ACL_FILE );xfs_forget_acl (VFS_I (sc->ip),SGI_ACL_DEFAULT ); -return 0 ; +return error; }/* Tear down all the incore scan stuff we created. */
Greg Kroah-Hartman
maintainerPATCH 727/1536 xfs: always report inode repair setup failures
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit ce9098338a7e1a77246684242d10779fc4d4a539 upstream.
LOLLM noticed that xchk_setup_inode silently discards errors being returned by xrep_setup_inode. Fix that, and fix the stub macro so that it actually "returns" a value.
--- fs/xfs/scrub/inode.c | 2 +- fs/xfs/scrub/repair.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)
fs/xfs/scrub/inode.c +1 -1
@@ -190,7 +190,7 @@ xchk_setup_inode(* make repairs to the ondisk inode buffer. */ if (xchk_could_repair (sc)) -xrep_setup_inode (sc, &imap); +return xrep_setup_inode (sc, &imap);return 0 ; out_cancel:
fs/xfs/scrub/repair.h +1 -1
@@ -218,7 +218,7 @@ xrep_setup_nothing(#define xrep_setup_nlinks xrep_setup_nothing#define xrep_setup_dirtree xrep_setup_nothing -#define xrep_setup_inode (sc, imap) ((void)0) +#define xrep_setup_inode (sc, imap) (0)static inline int xrep_setup_symlink (struct xfs_scrub *sc,unsigned int *x) {
Greg Kroah-Hartman
maintainerPATCH 728/1536 xfs: always report scrub errors in tracepoints
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 1ccc8f553d885d49c1bfe141ea1f331511940b3a upstream.
LOLLM complains that the error processing functions in scrub will sometimes zero out *error before recording a tracepoint. This makes diagnosing problems harder, so let's fix that.
--- fs/xfs/scrub/btree.c | 8 +++++++- fs/xfs/scrub/common.c | 7 +++++-- fs/xfs/scrub/dabtree.c | 6 +++++- 3 files changed, 17 insertions(+), 4 deletions(-)
fs/xfs/scrub/btree.c +7 -1
@@ -46,8 +46,14 @@ __xchk_btree_process_error(case -ENODATA :/* Note the badness but don't abort. */ sc->sm->sm_flags |= errflag; +if (cur->bc_ops->type ==XFS_BTREE_TYPE_INODE ) +trace_xchk_ifork_btree_op_error (sc, cur, level, + *error, ret_ip); +else +trace_xchk_btree_op_error (sc, cur, level, + *error, ret_ip); *error =0 ; - fallthrough; +break ;default :if (cur->bc_ops->type ==XFS_BTREE_TYPE_INODE ) trace_xchk_ifork_btree_op_error(sc, cur, level,
fs/xfs/scrub/common.c +5 -2
@@ -102,8 +102,9 @@ __xchk_process_error(case -ENODATA :/* Note the badness but don't abort. */ sc->sm->sm_flags |= errflag; +trace_xchk_op_error (sc, agno, bno, *error, ret_ip); *error =0 ; - fallthrough; +break ;default :trace_xchk_op_error (sc, agno, bno, *error, ret_ip);break ;
@@ -167,8 +168,10 @@ __xchk_fblock_process_error(case -ENODATA :/* Note the badness but don't abort. */ sc->sm->sm_flags |= errflag; +trace_xchk_file_op_error (sc, whichfork, offset, *error, + ret_ip); *error =0 ; - fallthrough; +break ;default :trace_xchk_file_op_error (sc, whichfork, offset, *error, ret_ip);
fs/xfs/scrub/dabtree.c +5 -1
@@ -49,8 +49,12 @@ xchk_da_process_error(case -ENODATA :/* Note the badness but don't abort. */ sc->sm->sm_flags |=XFS_SCRUB_OFLAG_CORRUPT ; +trace_xchk_file_op_error (sc, ds->dargs.whichfork, +xfs_dir2_da_to_db (ds->dargs.geo, + ds->state->path.blk[level].blkno), + *error, __return_address); *error =0 ; - fallthrough; +break ;default : trace_xchk_file_op_error(sc, ds->dargs.whichfork, xfs_dir2_da_to_db(ds->dargs.geo,
Greg Kroah-Hartman
maintainerPATCH 729/1536 xfs: always zero the whole shortform header when zeroing attr fork
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 52aa50cea408e27454d206cccecbe4f694a6c1e1 upstream.
LOLLM noticed that xrep_xattr_fork_remove can decide to reset the attr fork contents to an empty shortform header, but then fails to zero the padding byte in the header. Fix that.
--- fs/xfs/scrub/attr_repair.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/attr_repair.c +1 -1
@@ -970,7 +970,7 @@ xrep_xattr_fork_remove( ifp->if_format =XFS_DINODE_FMT_LOCAL ; hdr =xfs_idata_realloc (ip, (int )sizeof (*hdr) - ifp->if_bytes,XFS_ATTR_FORK ); - hdr->count =0 ; +memset (hdr,0 ,sizeof (*hdr)); hdr->totsize =cpu_to_be16 (sizeof (*hdr));xfs_trans_log_inode (sc->tp, ip,XFS_ILOG_CORE |XFS_ILOG_ADATA );
Greg Kroah-Hartman
maintainerPATCH 730/1536 xfs: bound da-node entry count against the correct geometry
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 3df5e5aaa3bc0913236c48ab29b7df3a785aa29f upstream.
xfs_da3_node_verify() bounds the node entry count against the larger of the directory and attribute geometries because, as a buffer verifier, it cannot tell whether the block belongs to the directory or the attribute tree. When the directory block size exceeds the fs block size (e.g. mkfs.xfs -n size=64k -b size=4k), an attribute node buffer is a single fs block that holds only m_attr_geo->node_ents entries, yet a crafted attr node may claim a count up to m_dir_geo->node_ents and still pass the verifier.
xfs_da3_node_lookup_int() then indexes btree[] up to that count during its binary search -- an out-of-bounds read via getxattr/listxattr on a mounted crafted image.
The buffer verifier is the wrong place to tighten this: it has no fork context, and the transaction-less read path used by getxattr does not run xfs_da3_node_set_type() either. xfs_da3_node_lookup_int(), on the other hand, always runs on that path and holds args->geo, the geometry of the fork actually being searched. Bound the entry count against args->geo->node_ents there, before walking the entries.
--- fs/xfs/libxfs/xfs_da_btree.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
fs/xfs/libxfs/xfs_da_btree.c +14 -0
@@ -1787,6 +1787,20 @@ xfs_da3_node_lookup_int( }else expected_level--; +/* +* The node verifier cannot tell whether this block belongs to +* the directory or the attribute tree, so it only bounds the +* entry count against the larger of the two geometries. Here +* args->geo is the geometry of the fork we are actually +* searching, so reject a count that would walk btree[] off the +* end of this node buffer. +*/ +if (nodehdr.count > args->geo->node_ents) { +xfs_buf_mark_corrupt (blk->bp); +xfs_da_mark_sick (args); +return -EFSCORRUPTED ; + } + max = nodehdr.count; blk->hashval =be32_to_cpu (btree[max -1 ].hashval);
Greg Kroah-Hartman
maintainerPATCH 731/1536 xfs: bound inode fork length against the fork size during log recovery
In reply to Greg Kroah-Hartman6.12-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
@@ -468,6 +468,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 :
@@ -507,7 +526,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 732/1536 xfs: check for fragments when full-extent sharing matches
In reply to Greg Kroah-Hartman6.12-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
@@ -174,8 +174,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 733/1536 xfs: check for termination during rmap btree walk
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 1fc241cdeab276dc6c3ec14840faa706ed7712ff upstream.
LOLLM complains that we should check for a fatal signal *every* time we walk a record in the rmap btree as part of rebuilding the free space btrees. Fix that, and improve responsiveness to ^C of xfs_scrub.
--- fs/xfs/scrub/alloc_repair.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/alloc_repair.c +4 -1
@@ -228,7 +228,10 @@ xrep_abt_walk_rmap( void *priv) {struct xrep_abt *ra = priv; -int error; +int error =0 ; + +if (xchk_should_terminate (ra->sc, &error)) +return error;/* Record all the OWN_AG blocks... */ if (rec->rm_owner ==XFS_RMAP_OWN_AG ) {
Greg Kroah-Hartman
maintainerPATCH 734/1536 xfs: clarify various parts of the bitmap API
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 00f32fdf54983371d39162efef7df693e2842ffb upstream.
LOLLM pointed out some underspecified parts of the xbitmap{32,64} API. Specifically, the behavior of set/clear/test functions when the length parameter is zero is not well defined, nor is what happens when someone tries to disunion a bitmap with itself. None of these situations are expected, but we'll define zero-length set and clear to be nops, and the rest to be checked by assertions.
--- fs/xfs/scrub/bitmap.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+)
fs/xfs/scrub/bitmap.c +20 -0
@@ -77,6 +77,9 @@ xbitmap64_clear(struct xbitmap64_node *new_bn;uint64_t last = start + len -1 ; +if (!len) +return 0 ; +while ((bn =xbitmap64_tree_iter_first (&bitmap->xb_root, start, last))) {if (bn->bn_start < start && bn->bn_last > last) {uint64_t old_last = bn->bn_last;
@@ -127,6 +130,9 @@ xbitmap64_set(uint64_t last = start + len -1 ;int error; +if (!len) +return 0 ; +/* Is this whole range already set? */ left =xbitmap64_tree_iter_first (&bitmap->xb_root, start, last);if (left && left->bn_start <= start && left->bn_last >= last)
@@ -218,6 +224,8 @@ xbitmap64_disunion(struct xbitmap64_node *bn;int error; +ASSERT (bitmap != sub); +if (xbitmap64_empty (bitmap) ||xbitmap64_empty (sub))return 0 ;
@@ -282,6 +290,8 @@ xbitmap64_test(struct xbitmap64_node *bn;uint64_t last = start + *len -1 ; +ASSERT (*len >0 ); + bn =xbitmap64_tree_iter_first (&bitmap->xb_root, start, last);if (!bn)return false;
@@ -352,6 +362,9 @@ xbitmap32_clear(struct xbitmap32_node *new_bn;uint32_t last = start + len -1 ; +if (!len) +return 0 ; +while ((bn =xbitmap32_tree_iter_first (&bitmap->xb_root, start, last))) {if (bn->bn_start < start && bn->bn_last > last) {uint32_t old_last = bn->bn_last;
@@ -402,6 +415,9 @@ xbitmap32_set(uint32_t last = start + len -1 ;int error; +if (!len) +return 0 ; +/* Is this whole range already set? */ left =xbitmap32_tree_iter_first (&bitmap->xb_root, start, last);if (left && left->bn_start <= start && left->bn_last >= last)
@@ -493,6 +509,8 @@ xbitmap32_disunion(struct xbitmap32_node *bn;int error; +ASSERT (bitmap != sub); +if (xbitmap32_empty (bitmap) ||xbitmap32_empty (sub))return 0 ;
@@ -557,6 +575,8 @@ xbitmap32_test(struct xbitmap32_node *bn;uint32_t last = start + *len -1 ; +ASSERT (*len >0 ); + bn =xbitmap32_tree_iter_first (&bitmap->xb_root, start, last);if (!bn)return false;
Greg Kroah-Hartman
maintainerPATCH 735/1536 xfs: clear set[ug]id mode bits when zapping attr fork
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit eb20a959760c21e3547cd811d0d9b0b29df98959 upstream.
LOLLM observes that zapping a file's attr fork could result in ACLs being removed from the file. Because we have no idea what we're deleting, we should clear the setuid and setgid bits in addition to the access mode bits so that nobody can access the file.
--- fs/xfs/scrub/inode_repair.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
fs/xfs/scrub/inode_repair.c +6 -1
@@ -1130,7 +1130,12 @@ xrep_dinode_zap_afork(*/ if (dip->di_format !=XFS_DINODE_FMT_BTREE ) dip->di_forkoff =0 ; - dip->di_mode =cpu_to_be16 (mode & ~0777 ); + +/* +* Zapping the attr fork could remove ACLs, so we clear suid/sgid and +* all access mode bits. +*/ + dip->di_mode =cpu_to_be16 (mode & ~(S_ISUID |S_ISGID |0777 )); dip->di_uid =0 ; dip->di_gid =0 ; }
Greg Kroah-Hartman
maintainerPATCH 736/1536 xfs: dont clear COWEXTSIZE on directories on reflink filesystems
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 3978b1f3109dfd5c648442bb040f9abd58608226 upstream.
LOLLM noticed that xrep_dinode_flags clears the COWEXTSIZE flag unnecessarily on directories on reflink filesystems. Directories just pass the hint along to new children, so it's valid to leave the flag set.
--- fs/xfs/scrub/inode_repair.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/scrub/inode_repair.c +2 -0
@@ -553,6 +553,8 @@ xrep_dinode_flags(*/ if (xfs_has_reflink (mp) &&S_ISREG (mode)) flags2 |=XFS_DIFLAG2_REFLINK ; +else if (xfs_has_reflink (mp) &&S_ISDIR (mode)) + flags2 &= ~XFS_DIFLAG2_REFLINK ;else flags2 &= ~(XFS_DIFLAG2_REFLINK |XFS_DIFLAG2_COWEXTSIZE );if (flags &XFS_DIFLAG_REALTIME )
Greg Kroah-Hartman
maintainerPATCH 737/1536 xfs: dont overrun incore inode when cleaning attr forks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit c28b4b48deac17749ed1ebe4289a4ba73541ddc6 upstream.
LOLLM noticed that xrep_dinode_check_afork doesn't check for a di_forkoff value that is so large that the attr fork would begin after the end of the inode space. This causes afork_{ptr,size} to be nonsense. What we really ought to do here is zap the attr fork.
--- fs/xfs/scrub/inode_repair.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/scrub/inode_repair.c +2 -0
@@ -1071,6 +1071,8 @@ xrep_dinode_check_afork(if (XFS_DFORK_BOFF (dip) ==0 )return dip->di_aformat !=XFS_DINODE_FMT_EXTENTS ||xfs_dfork_attr_extents (dip) !=0 ; +if (XFS_DFORK_BOFF (dip) >=XFS_LITINO (sc->mp)) +return true; afork_size =XFS_DFORK_SIZE (dip, sc->mp,XFS_ATTR_FORK ); afork_ptr =XFS_DFORK_PTR (dip,XFS_ATTR_FORK );
Greg Kroah-Hartman
maintainerPATCH 738/1536 xfs: dont rescan ifree and icount when frozen
In reply to Greg Kroah-Hartman6.12-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
@@ -379,6 +379,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 739/1536 xfs: dont subtract excess usage twice when computing agf_btreeblks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 4439b626fb5104204952aa2f169451688fb6be26 upstream.
LOLLM noticed that the free space btree repair code calculates agf_btreeblks from the number of blocks we wrote to rebuild the free space btrees (minus the roots). That's correct. However, it observes that we subtract the "excess" reservation, which is not correct. Fix this accounting problem.
--- fs/xfs/scrub/alloc_repair.c | 6 +----- fs/xfs/scrub/newbt.c | 13 ------------- fs/xfs/scrub/newbt.h | 1 - 3 files changed, 1 insertion(+), 19 deletions(-)
fs/xfs/scrub/alloc_repair.c +1 -5
@@ -663,15 +663,11 @@ xrep_abt_reset_counters(/* * Compute the contribution to agf_btreeblks for the new free space -* btrees. This is the computed btree size minus anything we didn't -* use. +* btrees. This is the computed btree size minus the root block. */ freesp_btreeblks += ra->new_bnobt.bload.nr_blocks -1 ; freesp_btreeblks += ra->new_cntbt.bload.nr_blocks -1 ; - freesp_btreeblks -=xrep_newbt_unused_blocks (&ra->new_bnobt); - freesp_btreeblks -=xrep_newbt_unused_blocks (&ra->new_cntbt); -/* * The AGF header contains extra information related to the free space * btrees, so we must update those fields here.
fs/xfs/scrub/newbt.c +0 -13
@@ -555,16 +555,3 @@ xrep_newbt_claim_block(/* Relog all the EFIs. */ return xrep_defer_finish (xnr->sc); } - -/* How many reserved blocks are unused? */ -unsigned int -xrep_newbt_unused_blocks ( -struct xrep_newbt *xnr) -{ -struct xrep_newbt_resv *resv; -unsigned int unused =0 ; - -list_for_each_entry (resv, &xnr->resv_list, list) - unused += resv->len - resv->used; -return unused; -}
fs/xfs/scrub/newbt.h +0 -1
@@ -70,6 +70,5 @@ void xrep_newbt_cancel(struct xrep_newbtint xrep_newbt_commit (struct xrep_newbt *xnr);int xrep_newbt_claim_block (struct xfs_btree_cur *cur,struct xrep_newbt *xnr,union xfs_btree_ptr *ptr); -unsigned int xrep_newbt_unused_blocks (struct xrep_newbt *xnr);#endif /* __XFS_SCRUB_NEWBT_H__ */
Greg Kroah-Hartman
maintainerPATCH 740/1536 xfs: fix correction of unwritten extents in quota file data fork
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 6f2792720673f569fa3e1f68181b9d6fd26802b5 upstream.
LOLLM noticed a couple of problems with the code that fixes unwritten mappings in the quota file's data fork: first, we should zero the ondisk contents as part of converting them to "unwritten" just in case we crash shortly after the conversion. Second, and more importantly, it noticed that we fail to resynchronize the iext tree cursor after modifying the iext tree. If the tree shape changes, we could be in a world of hurt. Third, we should force a quotacheck if we reset an ondisk dquot. Fix all issues.
--- fs/xfs/scrub/quota_repair.c | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-)
fs/xfs/scrub/quota_repair.c +23 -2
@@ -418,7 +418,9 @@ xrep_quota_data_fork(/* Check for data fork problems that apply only to quota files. */ max_dqid_off =XFS_DQ_ID_MAX / qi->qi_dqperchunk; ifp =xfs_ifork_ptr (sc->ip,XFS_DATA_FORK ); -for_each_xfs_iext (ifp, &icur, &irec) { +xfs_iext_first (ifp, &icur); + +while (xfs_iext_get_extent (ifp, &icur, &irec)) {if (isnullstartblock (irec.br_startblock)) { error = -EFSCORRUPTED ; goto out;
@@ -442,16 +444,35 @@ xrep_quota_data_fork( error =xfs_bmapi_write (sc->tp, sc->ip, irec.br_startoff, irec.br_blockcount, -XFS_BMAPI_CONVERT ,0 , &nrec, &nmap); +XFS_BMAPI_CONVERT |XFS_BMAPI_ZERO ,0 , + &nrec, &nmap);if (error) goto out;ASSERT (nrec.br_startoff == irec.br_startoff);ASSERT (nrec.br_blockcount == irec.br_blockcount); +/* +* We just zeroed the ondisk dquot, so counts could be +* wrong. Schedule a quotacheck to fix that. +*/ +xrep_force_quotacheck (sc, dqtype); error =xfs_defer_finish (&sc->tp);if (error) goto out; + +/* +* Set cursor to the next block past the extent we just +* converted because bmapi write could have merged +* records. +*/ +if (!xfs_iext_lookup_extent (sc->ip, ifp, + irec.br_startoff + irec.br_blockcount, + &icur, &irec)) +break ; +continue ; } + +xfs_iext_next (ifp, &icur); }if (!joined) {
Greg Kroah-Hartman
maintainerPATCH 741/1536 xfs: fix data fork block count check in xrep_inode_blockcounts
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 147f9f8300cb284923e08bb8a7b32ba9681c45ed upstream.
LOLLM notices that for non-reflink realtime files, the @count output of xchk_inode_count_blocks includes both the file blocks on the realtime volume and the bmap btree blocks on the data volume. Therefore, we must compare this value to rblocks + dblocks to avoid unnecessary failure.
--- fs/xfs/scrub/inode_repair.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/inode_repair.c +1 -1
@@ -1528,7 +1528,7 @@ xrep_inode_blockcounts(*/ ; }else if (XFS_IS_REALTIME_INODE (sc->ip)) { -if (count >= sc->mp->m_sb.sb_rblocks) +if (count >= sc->mp->m_sb.sb_rblocks + sc->mp->m_sb.sb_dblocks)return -EFSCORRUPTED ; }else {if (count >= sc->mp->m_sb.sb_dblocks)
Greg Kroah-Hartman
maintainerPATCH 742/1536 xfs: never reset the default quota timer
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit ddf4fe30c3fd7d37cf9bad3887ddb69984954cf4 upstream.
LOLLM notices that xrep_quota_fix_timer doesn't check the dquot id, which means that it can inadvertently reset the default quota timer when we really meant to ensure that a (non-root) quota overage timeout has a sane timestamp. Fix that.
--- fs/xfs/scrub/quota_repair.c | 3 +++ 1 file changed, 3 insertions(+)
fs/xfs/scrub/quota_repair.c +3 -0
@@ -274,6 +274,9 @@ xrep_quota_fix_timer(time64_t new_timer;uint32_t t; +/* never reset the default quota timer */ +if (ddq->d_id ==0 ) +return ;if (!soft || count <= soft || *timer !=0 )return ;
Greg Kroah-Hartman
maintainerPATCH 743/1536 xfs: only written file data blocks can be shared
In reply to Greg Kroah-Hartman6.12-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
@@ -129,6 +129,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 744/1536 xfs: opportunistically skip btree block checks
In reply to Greg Kroah-Hartman6.12-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
@@ -608,6 +608,14 @@ xchk_btree_get_block(xfs_btree_get_block (bs->cur, level, pbp);if (__xfs_btree_check_block (bs->cur, *pblock, level, *pbp)) {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 745/1536 xfs: propagate errors while checking null siblings
In reply to Greg Kroah-Hartman6.12-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
@@ -257,9 +257,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 746/1536 xfs: range-check bc_levels array access in scrub tracepoints
In reply to Greg Kroah-Hartman6.12-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
@@ -39,6 +39,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));
@@ -50,6 +53,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
@@ -565,7 +565,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; ),
@@ -606,7 +606,7 @@ TRACE_EVENT(xchk_ifork_btree_op_error, __entry->type = sc->sm->sm_type;__assign_str (name); __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;
@@ -648,7 +648,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 %sbt level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -688,7 +688,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 %sbt level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -728,7 +728,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 %sbt agno 0x%x agbno 0x%x level %d nlevels %d ptr %d", MAJOR(__entry->dev), MINOR(__entry->dev),
Greg Kroah-Hartman
maintainerPATCH 747/1536 smb: server: size directory name conversion buffer correctly
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: VeroFess <[email protected]>
commit f1f37834eaba5904103af1f18afe3510c7e9dc71 upstream.
A 2048-byte ASCII directory name needs 4098 bytes when converted to UTF-16, including the terminator. ksmbd_convert_dir_info_name() caps its allocation at PATH_MAX and writes past the end of that buffer.
Allocate space for one UTF-16 code unit per input byte plus the terminator. Use kmalloc_array() to check the size calculation.
--- fs/smb/server/misc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
fs/smb/server/misc.c +4 -4
@@ -291,12 +291,13 @@ char *ksmbd_convert_dir_info_name(struct int *conv_len) {char *conv; -int sz =min (4 * d_info->name_len,PATH_MAX ); -if (!sz) +if (d_info->name_len <=0 )return NULL ; - conv =kmalloc (sz,KSMBD_DEFAULT_GFP ); +/* One UTF-16 code unit per input byte, plus the terminating NUL. */ + conv =kmalloc_array ((size_t )d_info->name_len +1 , +sizeof (__le16),KSMBD_DEFAULT_GFP );if (!conv)return NULL ;
@@ -305,7 +306,6 @@ char *ksmbd_convert_dir_info_name(struct d_info->name_len, local_nls, 0); *conv_len *=2 ; -/* We allocate buffer twice bigger than needed. */ conv[*conv_len] =0x00 ; conv[*conv_len +1 ] =0x00 ;return conv;
Greg Kroah-Hartman
maintainerPATCH 748/1536 smb: client: dont resurrect an exiting tcon from cached dir workers
In reply to Greg Kroah-Hartman6.12-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 749/1536 smb: client: fix buffer overflow in SMB2_tcon()
In reply to Greg Kroah-Hartman6.12-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
@@ -2033,8 +2033,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) {
@@ -2065,7 +2063,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 750/1536 smb: client: fix fiemap wild read on empty truncated response
In reply to Greg Kroah-Hartman6.12-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
@@ -4205,6 +4205,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 ;
@@ -4225,10 +4234,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 751/1536 smb: client: fix slab-out-of-bounds write in id_mode_to_cifs_acl()
In reply to Greg Kroah-Hartman6.12-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
@@ -1771,12 +1771,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 752/1536 smb: client: validate NT transaction response layout and offsets
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ratnaker Gautam <[email protected]>
commit 83d0d5e0ca22233c75daf139ec0063b9d2ff1ac7 upstream.
validate_ntransact() assumes that the response uses the fixed 18-word NT transaction layout. A different WordCount makes get_bcc() locate the byte count at a different offset from pSMBr->ByteCount, allowing the subsequent bounds checks to use inconsistent response boundaries.
The function also turns the 32-bit ParameterOffset and DataOffset fields into pointers before checking their bounds. On a 32-bit client, a large offset can wrap the pointer below end_of_smb and pass the one-sided pointer comparison. The caller then dereferences the parameter pointer or copies from the data pointer.
Require the expected WordCount before reading the byte count. Check each offset and count against the received SMB length as integers before forming either pointer. Use subtraction after validating the offset so that the range checks cannot overflow.
--- fs/smb/client/cifssmb.c | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-)
fs/smb/client/cifssmb.c +19 -13
@@ -3401,9 +3401,10 @@ static intvalidate_ntransact (char *buf, char **ppparm, char **ppdata, __u32 *pparmlen, __u32 *pdatalen) { -char *end_of_smb;__u32 data_count, data_offset, parm_count, parm_offset;struct smb_com_ntransact_rsp *pSMBr; +size_t buflen; +char *end_buf;u16 bcc; *pdatalen =0 ;
@@ -3414,37 +3415,42 @@ validate_ntransact(char *buf, char **ppp pSMBr = (struct smb_com_ntransact_rsp *)buf; +if (pSMBr->hdr.WordCount !=18 ) { +cifs_dbg (FYI ,"invalid NT transaction WordCount %u\n" , + pSMBr->hdr.WordCount); +return -EINVAL ; + } + bcc =get_bcc (&pSMBr->hdr); - end_of_smb =2 /* sizeof byte count */ + bcc + - (char *)&pSMBr->ByteCount; + end_buf =2 /* sizeof byte count */ + bcc + (char *)&pSMBr->ByteCount; + buflen = end_buf - buf; data_offset =le32_to_cpu (pSMBr->DataOffset); data_count =le32_to_cpu (pSMBr->DataCount); parm_offset =le32_to_cpu (pSMBr->ParameterOffset); parm_count =le32_to_cpu (pSMBr->ParameterCount); - *ppparm = (char *)&pSMBr->hdr.Protocol + parm_offset; - *ppdata = (char *)&pSMBr->hdr.Protocol + data_offset; -/* should we also check that parm and data areas do not overlap? */ -if (*ppparm > end_of_smb) { +if (parm_offset > buflen) {cifs_dbg (FYI ,"parms start after end of smb\n" );return -EINVAL ; - }else if (parm_count + *ppparm > end_of_smb) { + }else if (parm_count > buflen - parm_offset) {cifs_dbg (FYI ,"parm end after end of smb\n" );return -EINVAL ; - }else if (*ppdata > end_of_smb) { + }else if (data_offset > buflen) {cifs_dbg (FYI ,"data starts after end of smb\n" );return -EINVAL ; - }else if (data_count + *ppdata > end_of_smb) { -cifs_dbg (FYI ,"data %p + count %d (%p) past smb end %p start %p\n" , - *ppdata, data_count, (data_count + *ppdata), - end_of_smb, pSMBr); + }else if (data_count > buflen - data_offset) { +cifs_dbg (FYI ,"data offset %u + count %u past smb length %zu\n" , + data_offset, data_count, buflen);return -EINVAL ; }else if (parm_count + data_count > bcc) {cifs_dbg (FYI ,"parm count and data count larger than SMB\n" );return -EINVAL ; } + + *ppparm = buf + parm_offset; + *ppdata = buf + data_offset; *pdatalen = data_count; *pparmlen = parm_count;return 0 ;
Greg Kroah-Hartman
maintainerPATCH 753/1536 pNFS: Fix CB_NOTIFY_DEVICEID CHANGE to consume ndc_immediate
In reply to Greg Kroah-Hartman6.12-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
@@ -316,7 +316,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 754/1536 pnfs/blocklayout: Complete a device upcall only on its own reply
In reply to Greg Kroah-Hartman6.12-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
@@ -161,11 +161,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 755/1536 pnfs/blocklayout: Complete a device upcall when the pipe is closed
In reply to Greg Kroah-Hartman6.12-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 int nfs4blocklayout_register_sb(struct super_block *sb,
Greg Kroah-Hartman
maintainerPATCH 756/1536 NFSv4.1/pnfs: suspend pNFS on NFS4ERR_TOOSMALL from LAYOUTGET
In reply to Greg Kroah-Hartman6.12-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
@@ -9888,6 +9888,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
@@ -2319,6 +2319,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 757/1536 NFSv4/filelayout: Anchor page coalescing on pattern_offset
In reply to Greg Kroah-Hartman6.12-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
@@ -796,7 +796,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 */
@@ -808,8 +808,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);
@@ -818,7 +818,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 758/1536 NFSv4/flexfiles: fail I/O to the data server once a lock is lost
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit 7fa2ad367abe6d3155daefb57331e7fce1a17afd upstream.
When a client loses a byte-range lock, because its lease expired and it may not recover the lock (nfs.recover_lost_locks=0) or because reclaim failed, it marks the lock state NFS_LOCK_LOST and fails further I/O by that lock owner. Otherwise an application that believes it holds a lock over a range is never told that the lock is gone, and can overwrite data that another client has since written under its own lock on that range.
The NFSv4 READ/WRITE and file layout I/O paths apply this in rpc_call_prepare, where nfs4_set_rw_stateid() returns -EIO for a lost lock. The flexfiles data server I/O path does not: the NFSv3 data server path never checked, and the check on the NFSv4 path was removed when the data server stateid began to be taken from the layout.
Fail read and write RPCs to the data server in rpc_call_prepare when the lock is lost. The data server path has no use for the stateid that nfs4_set_rw_stateid() selects, and selecting it looks up a delegation or open stateid on every I/O.
Instead add nfs4_lock_context_lost(), which only tests NFS_LOCK_LOST, and check it alongside the open state. Its lookup, __nfs4_lookup_lock_state(), is split out of __nfs4_find_lock_state() and takes no reference: a lock state is only unlinked from state->lock_states under state->state_lock, so one found while holding that lock cannot be freed before it is released. Use it in nfs4_copy_lock_stateid() as well, which only reads the lock state under that lock. That drops a reference get and put from stateid selection for all NFSv4 I/O without changing the stateid selected.
Terminating the RPC in rpc_call_prepare is not enough on its own. The done callback reads the -EIO as a data server connection error, forgets the device ID, and resets the I/O to pNFS (or, for an NFSv4 data server, possibly to the MDS). After a reset to pNFS a new LAYOUTGET is granted and rpc_call_prepare fails the I/O again, without end. The existing NFS_CONTEXT_BAD check does not loop, since the open state is then invalid and pnfs_update_layout() fails the reset I/O, but it still forgets the device ID.
So when an RPC that was never sent fails and the open context is bad, the open state is invalid, or the lock is lost, complete it with -EIO without error handling. An RPC that was sent and failed is handled as before, so a real data server error is still reported to the MDS.
--- fs/nfs/flexfilelayout/flexfilelayout.c | 25 +++++++++++++++++++-- fs/nfs/nfs4_fs.h | 2 + fs/nfs/nfs4state.c | 38 +++++++++++++++++++++++++++++---- 3 files changed, 59 insertions(+), 6 deletions(-)
fs/nfs/flexfilelayout/flexfilelayout.c +23 -2
@@ -1399,12 +1399,27 @@ static void ff_layout_io_track_ds_error(dprintk ("%s: err %d op %d status %u\n" , __func__, err, opnum, status); } +static bool ff_layout_io_state_lost (const struct nfs_pgio_header *hdr) +{ +struct nfs_open_context *ctx = hdr->args.context; + +return test_bit (NFS_CONTEXT_BAD , &ctx->flags) || + !nfs4_valid_open_stateid (ctx->state) || +nfs4_lock_context_lost (ctx->state, hdr->args.lock_context); +} +/* NFS_PROTO call done callback routines */ static int ff_layout_read_done_cb (struct rpc_task *task,struct nfs_pgio_header *hdr) {int err; +if (task->tk_status <0 && !RPC_WAS_SENT (task) && +ff_layout_io_state_lost (hdr)) { + task->tk_status = -EIO ; +return 0 ; + } +if (task->tk_status <0 ) { ff_layout_io_track_ds_error(hdr->lseg, hdr->pgio_mirror_idx, hdr->args.offset, hdr->args.count,
@@ -1492,7 +1507,7 @@ static void ff_layout_read_record_layoutstatic int ff_layout_read_prepare_common (struct rpc_task *task,struct nfs_pgio_header *hdr) { -if (unlikely (test_bit (NFS_CONTEXT_BAD , &hdr->args.context->flags))) { +if (unlikely (ff_layout_io_state_lost (hdr))) {rpc_exit (task, -EIO );return -EIO ; }
@@ -1576,6 +1591,12 @@ static int ff_layout_write_done_cb(strucloff_t end_offs =0 ;int err; +if (task->tk_status <0 && !RPC_WAS_SENT (task) && +ff_layout_io_state_lost (hdr)) { + task->tk_status = -EIO ; +return 0 ; + } +if (task->tk_status <0 ) { ff_layout_io_track_ds_error(hdr->lseg, hdr->pgio_mirror_idx, hdr->args.offset, hdr->args.count,
@@ -1679,7 +1700,7 @@ static void ff_layout_write_record_layoustatic int ff_layout_write_prepare_common (struct rpc_task *task,struct nfs_pgio_header *hdr) { -if (unlikely (test_bit (NFS_CONTEXT_BAD , &hdr->args.context->flags))) { +if (unlikely (ff_layout_io_state_lost (hdr))) {rpc_exit (task, -EIO );return -EIO ; }
fs/nfs/nfs4_fs.h +2 -0
@@ -520,6 +520,8 @@ extern int nfs4_select_rw_stateid(struct const struct cred **); extern bool nfs4_copy_open_stateid(nfs4_stateid *dst,struct nfs4_state *state); +extern bool nfs4_lock_context_lost (struct nfs4_state *state, +const struct nfs_lock_context *l_ctx);extern struct nfs_seqid *nfs_alloc_seqid (struct nfs_seqid_counter *counter,gfp_t gfp_mask);extern int nfs_wait_on_sequence (struct nfs_seqid *seqid,struct rpc_task *task);
fs/nfs/nfs4state.c +34 -4
@@ -864,10 +864,13 @@ void nfs4_close_sync(struct nfs4_state ** be made. Failing that, a "consistent" choice is preferable. The * consistent choice we make is to prefer the first owner, that of a * Posix lock. +* +* Called with state->state_lock held. No reference is taken: a lock +* state is freed only after it is unlinked under state->state_lock. */ static struct nfs4_lock_state * -__nfs4_find_lock_state (struct nfs4_state *state, -fl_owner_t owner,fl_owner_t owner2) +__nfs4_lookup_lock_state (struct nfs4_state *state, +fl_owner_t owner,fl_owner_t owner2) {struct nfs4_lock_state *pos, *ret =NULL ;list_for_each_entry (pos, &state->lock_states, ls_locks) {
@@ -878,6 +881,16 @@ __nfs4_find_lock_state(struct nfs4_stateif (pos->ls_owner == owner2) ret = pos; } +return ret; +} + +static struct nfs4_lock_state * +__nfs4_find_lock_state (struct nfs4_state *state, +fl_owner_t owner,fl_owner_t owner2) +{ +struct nfs4_lock_state *ret; + + ret =__nfs4_lookup_lock_state (state, owner, owner2);if (ret)refcount_inc (&ret->ls_count);return ret;
@@ -1020,7 +1033,7 @@ static int nfs4_copy_lock_stateid(nfs4_s fl_flock_owner = l_ctx->open_context->flock_owner;spin_lock (&state->state_lock); - lsp =__nfs4_find_lock_state (state, owner, fl_flock_owner); + lsp =__nfs4_lookup_lock_state (state, owner, fl_flock_owner);if (lsp &&test_bit (NFS_LOCK_LOST , &lsp->ls_flags)) ret = -EIO ;else if (lsp !=NULL &&test_bit (NFS_LOCK_INITIALIZED , &lsp->ls_flags) !=0 ) {
@@ -1028,11 +1041,28 @@ static int nfs4_copy_lock_stateid(nfs4_s ret =0 ; }spin_unlock (&state->state_lock); -nfs4_put_lock_state (lsp); out:return ret; } +bool nfs4_lock_context_lost (struct nfs4_state *state, +const struct nfs_lock_context *l_ctx) +{ +struct nfs4_lock_state *lsp; +bool ret; + +if (!test_bit (LK_STATE_IN_USE , &state->flags)) +return false; + +spin_lock (&state->state_lock); + lsp =__nfs4_lookup_lock_state (state, l_ctx->lockowner, + l_ctx->open_context->flock_owner); + ret = lsp &&test_bit (NFS_LOCK_LOST , &lsp->ls_flags); +spin_unlock (&state->state_lock); +return ret; +} +EXPORT_SYMBOL_GPL (nfs4_lock_context_lost); +bool nfs4_copy_open_stateid (nfs4_stateid *dst,struct nfs4_state *state) {bool ret;
Greg Kroah-Hartman
maintainerPATCH 759/1536 NFSD: cap the number of listeners accepted in listener_set
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeff Layton <[email protected]>
commit 9a05e5ee0a98b9550521df86936b5f825bc07ec2 upstream.
nfsd_nl_listener_set_doit() matches each requested listener against the existing set. The nested loop that does this is O(N * M), where N is the requested count and M is the existing count. The loop runs under sv_lock with bottom halves disabled. A userland request with a very large listener list can therefore spin in atomic context for a long time.
Reject a request that carries more than NFSD_NL_LISTENER_MAX (1024) entries. The check goes in nfsd_nl_validate_listeners(), before the code takes any lock. The limit is far above any realistic configuration.
This patch does not cap M. Only the message size bounded N; real sockets bound M. A listener_set result set is the requested set, so that path also holds M at the cap, but __write_ports_addxprt() adds two listeners per call and removes none, so repeated calls can push M past it. The worst case under sv_lock is therefore 1024 * M, plus 1024 nla_parse_nested() calls. Both interfaces require CAP_NET_ADMIN.
--- fs/nfsd/nfsctl.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-)
fs/nfsd/nfsctl.c +11 -5
@@ -1994,21 +1994,22 @@ err_free_msg:return err; } +/* Upper bound on the number of listeners a single request may carry. */ +#define NFSD_NL_LISTENER_MAX 1024 +/** * nfsd_nl_validate_listeners - sanity-check the listener list from userland * @info: netlink metadata and command arguments * -* Walk every NFSD_A_SERVER_SOCK_ADDR attribute and confirm that each entry -* is well-formed: it parses against the policy, carries both an address and -* a transport name, and the address is long enough for its family. Doing -* this up front lets the callers below assume every entry is valid and -* guarantees we make no changes when the request is malformed. +* Walk every NFSD_A_SERVER_SOCK_ADDR attribute and confirm that the list is +* not oversized and that each entry is well-formed. * * Return: 0 if every entry is valid, or a negative errno otherwise. */ static int nfsd_nl_validate_listeners (struct genl_info *info) {const struct nlattr *attr; +unsigned int count =0 ;int rem; nlmsg_for_each_attr_type(attr, NFSD_A_SERVER_SOCK_ADDR, info->nlhdr,
@@ -2017,6 +2018,11 @@ static int nfsd_nl_validate_listeners(ststruct sockaddr *sa;int err; +if (++count >NFSD_NL_LISTENER_MAX ) { +NL_SET_ERR_MSG (info->extack,"too many listeners" ); +return -E2BIG ; + } + err =nla_parse_nested (tb,NFSD_A_SOCK_MAX , attr, nfsd_sock_nl_policy, info->extack);if (err <0 )
Greg Kroah-Hartman
maintainerPATCH 760/1536 nfsd: clear XDR padding in GETXATTR replies
In reply to Greg Kroah-Hartman6.12-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
@@ -5414,7 +5414,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 761/1536 NFSD: copy SETXATTR data from all XDR buffer segments
In reply to Greg Kroah-Hartman6.12-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
@@ -2145,10 +2145,8 @@ static __be32 nfsd4_vbuf_from_vector(struct nfsd4_compoundargs *argp, struct xdr_buf *xdr, char **bufp, size_t buflen) { - struct page **pages = xdr->pages; struct kvec *head = xdr->head; -char *tmp, *dp; -u32 len; +char *tmp;if (buflen <= head->iov_len) {/*
@@ -2163,19 +2161,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 762/1536 NFSD: Do not send CB_RECALL_ANY to NFSv4.0 clients
In reply to Greg Kroah-Hartman6.12-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
@@ -6977,6 +6977,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 763/1536 NFSD: Dont complete a cld upcall the daemon has not read
In reply to Greg Kroah-Hartman6.12-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
@@ -728,6 +728,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;
@@ -888,6 +890,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);
@@ -896,9 +905,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 ; }
@@ -918,8 +927,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 764/1536 nfsd: dont modify a session slot when replaying its cached reply
In reply to Greg Kroah-Hartman6.12-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
@@ -4473,6 +4473,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;
@@ -4508,7 +4509,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
@@ -188,6 +188,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 765/1536 NFSD: Fail a pool_threads read whose reply does not fit
In reply to Greg Kroah-Hartman6.12-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
@@ -471,7 +471,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);
@@ -525,9 +525,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 766/1536 nfsd: Fix id-to-name cache entry leak in idtoname_parse()
In reply to Greg Kroah-Hartman6.12-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 767/1536 NFSD: Fix out-of-bounds read in the rpc_status dump
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit cbea14890783fead76f878caf0775a62a42049bf upstream.
nfsd_nl_rpc_status_get_dumpit() loads args->opcnt and args->ops separately, then walks ops[] before rechecking rq_status_counter. A COMPOUND that completes between the two loads runs nfsd4_release_compoundargs(), which zeroes opcnt and points ops back at the eight-entry inline array. A dump that already sampled an opcnt of 200 clamps it to the sixteen slots in rq_opnum, then indexes iops[0..15]. iops is the last member of struct nfsd4_compoundargs and rq_argp is allocated at exactly that size, so the walk runs off the end of the allocation. The trailing recheck discards the sampled data, but the read has already happened. NFSD_CMD_RPC_STATUS_GET carries no GENL_ADMIN_PERM, so an unprivileged local user can repeat the dump against a busy server until it lands in the window.
Sample opcnt and ops into locals, then finish the counter recheck before dereferencing ops. An unchanged counter means both came from the same COMPOUND, where opcnt cannot exceed what ops holds.
--- fs/nfsd/nfsctl.c | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-)
fs/nfsd/nfsctl.c +18 -3
@@ -1657,14 +1657,29 @@ int nfsd_nl_rpc_status_get_dumpit(struct rqstp->rq_proc == NFSPROC4_COMPOUND) {/* NFSv4 compound */ struct nfsd4_compoundargs *args; +struct nfsd4_op *ops; +u32 opcnt;int j; args = rqstp->rq_argp; - genl_rqstp.rq_opcnt =min_t (u32, args->opcnt, + opcnt =READ_ONCE (args->opcnt); + ops =READ_ONCE (args->ops); + +/* +* Finish the seqcount retry before +* dereferencing ops. An unchanged counter means +* opcnt and ops came from the same COMPOUND, +* where opcnt cannot exceed what ops holds. +*/ +smp_rmb (); +if (READ_ONCE (rqstp->rq_status_counter) != + status_counter) +continue ; + + genl_rqstp.rq_opcnt =min_t (u32, opcnt,ARRAY_SIZE (genl_rqstp.rq_opnum));for (j =0 ; j < genl_rqstp.rq_opcnt; j++) - genl_rqstp.rq_opnum[j] = - args->ops[j].opnum; + genl_rqstp.rq_opnum[j] = ops[j].opnum; }#endif /* CONFIG_NFSD_V4 */
Greg Kroah-Hartman
maintainerPATCH 768/1536 nfsd: hold cl_lock in client_has_openowners()
In reply to Greg Kroah-Hartman6.12-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
@@ -3641,12 +3641,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 769/1536 nfsd: honour client-provided attributes for NFS4_CREATE_EXCLUSIVE4_1
In reply to Greg Kroah-Hartman6.12-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
@@ -359,8 +359,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 770/1536 NFSD: map fh_verify() status codes for NFS_ACLv3 replies
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit b1eb9f1aea88a0d7ec8116a70c33b7b31ad0a3eb upstream.
The NFS_ACLv3 protocol shares its status code space with NFSv3, which has NFS3ERR_BADHANDLE but no NFSERR_NOFILEHANDLE. An NFS_ACLv3 GETACL or SETACL request that carries an empty file handle gets a reply with status 10020, a value the client cannot interpret.
Commit 1459ad57673b ("nfsd: Move error code mapping to per-version proc code.") made fh_verify() return nfserr_nofilehandle for an empty handle regardless of protocol version. The NFSv3 procedures gained nfsd3_map_status() in exchange, but the NFS_ACLv3 procedures did not, so the unmapped status reaches the encoder.
Add the same mapping to the NFS_ACLv3 procedures.
--- fs/nfsd/nfs3acl.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
fs/nfsd/nfs3acl.c +15 -0
@@ -13,6 +13,19 @@#include "xdr3.h" #include "vfs.h" +static __be32 nfsd3_map_status (__be32 status) +{ +switch (status) { +case nfserr_nofilehandle: + status = nfserr_badhandle; +break ; +case nfserr_wrongsec: + status = nfserr_acces; +break ; + } +return status; +} +/* * NULL call. */
@@ -71,6 +84,7 @@ static __be32 nfsd3_proc_getacl(struct s/* resp->acl_{access,default} are released in nfs3svc_release_getacl. */ out: + resp->status =nfsd3_map_status (resp->status);return rpc_success; fail:
@@ -124,6 +138,7 @@ out_errno: resp->status =nfserrno (error); out:/* argp->acl_{access,default} are released in nfs3svc_release_setacl. */ + resp->status =nfsd3_map_status (resp->status);return rpc_success; }
Greg Kroah-Hartman
maintainerPATCH 771/1536 nfsd: preflight SEQUENCE replies before accepting a slot
In reply to Greg Kroah-Hartman6.12-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
@@ -4384,6 +4384,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;
@@ -4393,6 +4394,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);
@@ -4465,7 +4467,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 772/1536 nfsd: propagate SETXATTR value decode errors
In reply to Greg Kroah-Hartman6.12-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
@@ -2279,7 +2279,7 @@ nfsd4_decode_setxattr(struct nfsd4_compo &setxattr->setxa_buf, size); } -return nfs_ok; +return status; } static __be32
Greg Kroah-Hartman
maintainerPATCH 773/1536 NFSD: Reject an oversized principal hash from nfsdcld
In reply to Greg Kroah-Hartman6.12-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
@@ -809,6 +809,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 774/1536 NFSD: Resolve the recall-any mask names in the trace format
In reply to Greg Kroah-Hartman6.12-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
@@ -358,6 +358,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 775/1536 NFSD: Return NFSERR_ISDIR for NFSv2 READ and WRITE on a non-regular file
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 07649099cc8c449ea8d37d0e8d6b532fecb24bf8 upstream.
Commit 0ac903d1bfdc ("NFS: NFSERR_INVAL is not defined by NFSv2") changed the status NFSD returns for an NFSv2 READ or WRITE of a symlink or other non-regular file from NFSERR_INVAL to NFSERR_IO. RFC 1094 defines neither an INVAL nor a SYMLINK status.
U-Boot's NFS client follows a symlink only when READ fails with NFSERR_ISDIR or NFSERR_INVAL. Since that commit it cannot load a boot image through a symlink exported by a Linux NFS server: the load completes with zero bytes transferred.
Solaris returns NFSERR_ISDIR when the target of an NFSv2 READ or WRITE is not a regular file. Return the same status from NFSD. Other NFSv2 procedures continue to return NFSERR_IO.
--- fs/nfsd/nfsproc.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-)
fs/nfsd/nfsproc.c +17 -2
@@ -38,6 +38,21 @@ static __be32 nfsd_map_status(__be32 stareturn status; } +/* +* Because NFSv2 does not have an NFSERR_SYMLINK, Solaris returns +* NFSERR_ISDIR when the target of a READ or WRITE is any object +* that is not a regular file. +*/ +static __be32 nfsd_map_io_status (__be32 status) +{ +switch (status) { +case nfserr_symlink: +case nfserr_wrong_type: +return nfserr_isdir; + } +return nfsd_map_status (status); +} +static __be32 nfsd_proc_null (struct svc_rqst *rqstp) {
@@ -236,7 +251,7 @@ nfsd_proc_read(struct svc_rqst *rqstp) resp->status =fh_getattr (&resp->fh, &resp->stat); else if (resp->status == nfserr_jukebox) set_bit(RQ_DROPME, &rqstp->rq_flags); - resp->status =nfsd_map_status (resp->status); + resp->status =nfsd_map_io_status (resp->status);return rpc_success; }
@@ -272,7 +287,7 @@ nfsd_proc_write(struct svc_rqst *rqstp) resp->status =fh_getattr (&resp->fh, &resp->stat); else if (resp->status == nfserr_jukebox) set_bit(RQ_DROPME, &rqstp->rq_flags); - resp->status =nfsd_map_status (resp->status); + resp->status =nfsd_map_io_status (resp->status);return rpc_success; }
Greg Kroah-Hartman
maintainerPATCH 776/1536 NFSD: Set nn->cld_net before registering the cld pipe
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 14996e662f3b734427e2d645cacffc27b779f7d1 upstream.
rpc_mkpipe_dentry() instantiates the pipe's dentry before it returns, so the cld pipe can be opened as soon as nfsd4_cld_register_net() has run. __nfsd4_init_cld_pipe() does not store the new cld_net in nn->cld_net until after that call. cld_pipe_downcall() reaches the cld_net only through that pointer and takes cn_lock without checking it, so a write() that lands in the window oopses.
Store nn->cld_net once @cn is fully initialized and before the pipe is registered, and clear it again when registration fails.
--- fs/nfsd/nfs4recover.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
fs/nfsd/nfs4recover.c +10 -4
@@ -1025,18 +1025,24 @@ __nfsd4_init_cld_pipe(struct net *net) }spin_lock_init (&cn->cn_lock);INIT_LIST_HEAD (&cn->cn_list); +#ifdef CONFIG_NFSD_LEGACY_CLIENT_TRACKING + cn->cn_has_legacy = false; +#endif + +/* +* The pipe's methods reach @cn through nn->cld_net, so set +* it before the pipe can be opened. +*/ + nn->cld_net = cn; ret =nfsd4_cld_register_net (net, cn->cn_pipe);if (unlikely (ret)) goto err_destroy_data; -#ifdef CONFIG_NFSD_LEGACY_CLIENT_TRACKING - cn->cn_has_legacy = false; -#endif - nn->cld_net = cn;return 0 ; err_destroy_data: + nn->cld_net =NULL ;rpc_destroy_pipe_data (cn->cn_pipe); err:kfree (cn);
Greg Kroah-Hartman
maintainerPATCH 777/1536 NFSD: validate transport name in listener_set before serv creation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeff Layton <[email protected]>
commit 421becdc5cf4d7d2fbda393e78ca76d25d277c0f upstream.
nfsd_nl_listener_set_doit() holds nfsd_mutex for the whole listener teardown and rebuild. The code checks NFSD_A_SOCK_TRANSPORT_NAME for presence only, and not for content. An arbitrary name therefore reaches svc_xprt_create_from_sa(). There, a name that matches no registered class calls request_module("svc%s", name). That call is a TASK_KILLABLE usermode helper upcall, and it runs under nfsd_mutex.
Check the name against the classes that NFSD can create: tcp, udp and rdma. The check goes in nfsd_nl_validate_listeners(), which runs before the code takes nfsd_mutex. The rejection names the offending attribute through extack, since -EPROTONOSUPPORT on its own does not say which entry carried the bad name.
This narrows the upcall. It does not remove it. NFSD accepts "rdma" without a condition, so on a kernel that does not build svcrdma the name still reaches request_module("svcrdma") under nfsd_mutex. That is necessary for the modular case, where the autoload is legitimate.
--- fs/nfsd/nfsctl.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+)
fs/nfsd/nfsctl.c +24 -0
@@ -2013,6 +2013,23 @@ err_free_msg:return err; } +/* +* Transport classes NFSD knows how to instantiate. Vetting the name here +* keeps a bogus string from reaching svc_xprt_create_from_sa(), where an +* unknown name triggers a request_module("svc%s", name) upcall under +* nfsd_mutex. +*/ +static bool nfsd_nl_transport_supported (const char *name) +{ +static const char *const supported[] = {"tcp" ,"udp" ,"rdma" }; +int i; + +for (i =0 ; i <ARRAY_SIZE (supported); i++) +if (!strcmp (name, supported[i])) +return true; +return false; +} +/* Upper bound on the number of listeners a single request may carry. */ #define NFSD_NL_LISTENER_MAX 1024
@@ -2050,6 +2067,13 @@ static int nfsd_nl_validate_listeners(stif (!tb[NFSD_A_SOCK_ADDR ] || !tb[NFSD_A_SOCK_TRANSPORT_NAME ])return -EINVAL ; +if (!nfsd_nl_transport_supported (nla_data (tb[NFSD_A_SOCK_TRANSPORT_NAME ]))) { +NL_SET_ERR_MSG_ATTR (info->extack, + tb[NFSD_A_SOCK_TRANSPORT_NAME ], +"unsupported transport name" ); +return -EPROTONOSUPPORT ; + } + sa =nla_data (tb[NFSD_A_SOCK_ADDR ]);if (nla_len (tb[NFSD_A_SOCK_ADDR ]) <sizeof (sa->sa_family))return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 778/1536 nfsd: zero NFSv4 COMPOUND tag padding
In reply to Greg Kroah-Hartman6.12-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
@@ -5922,8 +5922,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 779/1536 SUNRPC: Copy the deferred RPC Call from the head buffer
In reply to Greg Kroah-Hartman6.12-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
@@ -1182,13 +1182,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) {
@@ -1201,8 +1196,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 );
@@ -1216,9 +1214,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;
@@ -1241,17 +1237,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 780/1536 SUNRPC: Do not credit control-record octets to the RPC stream
In reply to Greg Kroah-Hartman6.12-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 781/1536 SUNRPC: fix oversized GSS proxy token copy
In reply to Greg Kroah-Hartman6.12-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
@@ -1085,10 +1085,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 782/1536 SUNRPC: keep the first error in svc_register()
In reply to Greg Kroah-Hartman6.12-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
@@ -1233,13 +1233,16 @@ int svc_register(const struct svc_serv *struct svc_program *progp = &serv->sv_programs[p];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 783/1536 sunrpc: pin gss module across auth_domain RCU free
In reply to Greg Kroah-Hartman6.12-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;
@@ -2003,9 +2009,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 784/1536 SUNRPC: Reject a socket that already has an svc_sock attached
In reply to Greg Kroah-Hartman6.12-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
@@ -1531,6 +1531,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 785/1536 SUNRPC: Reject a TLS alert record that is not two octets
In reply to Greg Kroah-Hartman6.12-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 *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 ) { +/* 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 ); }
Greg Kroah-Hartman
maintainerPATCH 786/1536 SUNRPC: Resume receiving after a TLS control record
In reply to Greg Kroah-Hartman6.12-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 787/1536 SUNRPC: trace an accepted transport before publishing it
In reply to Greg Kroah-Hartman6.12-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
@@ -797,8 +797,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 788/1536 sunrpc: treat empty auth.unix.gid replies as negative entries
In reply to Greg Kroah-Hartman6.12-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 789/1536 SUNRPC: Treat every TLS error alert as fatal
In reply to Greg Kroah-Hartman6.12-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 790/1536 rxrpc: Fix double IRQ enablement
In reply to Greg Kroah-Hartman6.12-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_ca {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_ca 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);
Greg Kroah-Hartman
maintainerPATCH 791/1536 rxrpc: Fix return in rxrpc_recvmsg_data() for service calls
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Howells <[email protected]>
commit 18a71e111c7505e16c2de91480561fc491f41341 upstream.
When rxrpc_recvmsg_data() gets called on a service call that has received all of the request, RXRPC_CALL_RECVMSG_READ_ALL has been set, and this causes rxrpc_recvmsg_data() to jump straight out, indicating the end of the call (ie. rxrpc_kernel_recv_data() returns 1) without waiting for the call to be processed or the reply to be transmitted.
rxperf_deliver_to_call() also has to be altered to call rxrpc_kernel_recv_data() to collect the final ACK on a service call as does afs_deliver_to_call().
--- Documentation/networking/rxrpc.rst | 13 +++++++++---- fs/afs/rxrpc.c | 4 ++-- net/rxrpc/recvmsg.c | 13 ++++++++++--- net/rxrpc/rxperf.c | 16 ++++++++++++++-- 4 files changed, 35 insertions(+), 11 deletions(-)
Documentation/networking/rxrpc.rst +9 -4
@@ -910,10 +910,15 @@ The kernel interface functions are as fo want_more should be true if further data will be required after this is satisfied and false if this is the last item of the receive phase. - There are three normal returns: 0 if the buffer was filled and want_more - was true; 1 if the buffer was filled, the last DATA packet has been - emptied and want_more was false; and -EAGAIN if the function needs to be - called again. + For client calls, there are three normal returns: 0 if the buffer was + filled and want_more was true; 1 if the buffer was filled, the last DATA + packet has been emptied and want_more was false; and -EAGAIN if the + function needs to be called again. + + For service calls, there are four normal returns: 0 and -EAGAIN are the + same as for client calls; 2 indicates that the last DATA packet of the + request has been received, want_more was false and the call is still in + progress; and 1 indicates that the call is now successfully complete. If the last DATA packet is processed but the buffer contains less than the amount requested, EBADMSG is returned. If want_more wasn't set, but
fs/afs/rxrpc.c +2 -2
@@ -544,7 +544,7 @@ static void afs_deliver_to_call(struct a &call->service_id);trace_afs_receive_data (call, &call->def_iter, false, ret); -if (ret == -EINPROGRESS || ret == -EAGAIN ) +if (ret == -EAGAIN || ret ==2 )return ;if (ret <0 || ret ==1 ) {if (ret ==1 )
@@ -945,7 +945,7 @@ int afs_extract_data(struct afs_call *careturn ret; state =READ_ONCE (call->state); -if (ret ==1 ) { +if (ret ==1 || ret ==2 ) {switch (state) {case AFS_CALL_CL_AWAIT_REPLY :afs_set_call_state (call, state,AFS_CALL_CL_PROC_REPLY );
net/rxrpc/recvmsg.c +10 -3
@@ -552,9 +552,11 @@ wait_error:* Note that we may return %-EAGAIN to drain empty packets at the end * of the data, even if we've already copied over the requested data. * -* Return: %0 if got what was asked for and there's more available, %1 -* if we got what was asked for and we're at the end of the data and -* %-EAGAIN if we need more data. +* Return: %0 if got what was asked for and there's more available, %1 if we +* got what was asked for and we're at the end of the call, %2 if a service +* call received all of the request but is still in progress and %-EAGAIN if we +* need more data. A variety of other errors can be returned if the call +* completed with failure. */ int rxrpc_kernel_recv_data(struct socket *sock, struct rxrpc_call *call, struct iov_iter *iter, size_t *_len,
@@ -593,6 +595,11 @@ int rxrpc_kernel_recv_data(struct socket read_phase_complete: ret =1 ; +if (rxrpc_is_service_call (call)) { +if (rxrpc_call_is_complete (call)) + goto call_failed; + ret =2 ; + } out:if (_service) *_service = call->dest_srx.srx_service;
net/rxrpc/rxperf.c +14 -2
@@ -292,8 +292,20 @@ static void rxperf_deliver_to_call(struc state == RXPERF_CALL_SV_AWAIT_ACK ) {if (state ==RXPERF_CALL_SV_AWAIT_ACK ) { -if (!rxrpc_kernel_check_life (rxperf_socket, call->rxcall)) +size_t len =0 ; +iov_iter_kvec (&call->iter,ITER_DEST ,NULL ,0 ,0 ); + ret =rxrpc_kernel_recv_data (rxperf_socket, + call->rxcall, &call->iter, + &len, false, &remote_abort, + &call->service_id); + +if (ret == -EAGAIN || ret ==2 ) +return ; +if (ret <0 || ret ==1 ) { +if (ret ==1 ) + ret =0 ; goto call_complete; + }return ; }
@@ -368,7 +380,7 @@ static int rxperf_extract_data(struct rxif (ret ==0 || ret == -EAGAIN )return ret; -if (ret ==1 ) { +if (ret ==1 || ret ==2 ) {switch (call->state) {case RXPERF_CALL_SV_AWAIT_REQUEST :rxperf_set_call_state (call,RXPERF_CALL_SV_REPLYING );
Greg Kroah-Hartman
maintainerPATCH 792/1536 x86/mm/pat: Fix effective RW computation in lookup_address_in_pgd_attr()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Rapoport (Microsoft) <[email protected]>
commit ebaf7c9bbb1e16523d7036e7e1225ad2dfcc6482 upstream.
lookup_address_in_pgd_attr() accumulates the effective NX and RW bits of the walked page table levels so that verify_rwx() can detect mappings that are both writable and executable.
The RW bits are folded into a bool with
rw &= pXd_flags(*pXd) & _PAGE_RW;
but _PAGE_RW is 0x2. So consider the accumulation line:
rw &= pXd_flags(*pXd) & _PAGE_RW;
where rw=0x1 and the right side evaluates down to 0x2. It'll end up doing:
rw = 0x1 & 0x2
and rw always ends up 0.
This way rw becomes false at the first level walked, regardless of the actual permissions, and verify_rwx() treats every mapping as non-writable and never reports a W^X violation.
Add double negation to the right side to normalize the _PAGE_RW flag to 0 or 1.
--- arch/x86/mm/pat/set_memory.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
arch/x86/mm/pat/set_memory.c +4 -4
@@ -682,7 +682,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *level =PG_LEVEL_512G ; *nx |=pgd_flags (*pgd) & _PAGE_NX; - *rw &=pgd_flags (*pgd) & _PAGE_RW; + *rw &= !!(pgd_flags (*pgd) & _PAGE_RW); p4d =p4d_offset (pgd, address);if (p4d_none (*p4d))
@@ -693,7 +693,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *level =PG_LEVEL_1G ; *nx |=p4d_flags (*p4d) & _PAGE_NX; - *rw &=p4d_flags (*p4d) & _PAGE_RW; + *rw &= !!(p4d_flags (*p4d) & _PAGE_RW); pud =pud_offset (p4d, address);if (pud_none (*pud))
@@ -704,7 +704,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *level =PG_LEVEL_2M ; *nx |=pud_flags (*pud) & _PAGE_NX; - *rw &=pud_flags (*pud) & _PAGE_RW; + *rw &= !!(pud_flags (*pud) & _PAGE_RW); pmd =pmd_offset (pud, address);if (pmd_none (*pmd))
@@ -715,7 +715,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *level =PG_LEVEL_4K ; *nx |=pmd_flags (*pmd) & _PAGE_NX; - *rw &=pmd_flags (*pmd) & _PAGE_RW; + *rw &= !!(pmd_flags (*pmd) & _PAGE_RW);return pte_offset_kernel (pmd, address); }
Greg Kroah-Hartman
maintainerPATCH 793/1536 KVM: SVM: Trigger new ASID allocation in both VMCBs on pCPU switch
In reply to Greg Kroah-Hartman6.12-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
@@ -1227,6 +1227,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
@@ -3713,14 +3713,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 794/1536 KVM: nSVM: Ignore EFER.LMA if EFER.LME=0 when preparing L2 state
In reply to Greg Kroah-Hartman6.12-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
@@ -588,6 +588,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 795/1536 KVM: Use goto to handle errors during memslot preparation
In reply to Greg Kroah-Hartman6.12-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
@@ -1914,21 +1914,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
@@ -1960,6 +1947,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 796/1536 KVM: x86/mmu: Bug the VM if KVM attempts to walk more levels than the MMU has
In reply to Greg Kroah-Hartman6.12-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 797/1536 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.12-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
@@ -5449,6 +5449,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 798/1536 KVM: x86/xen: Enforce 4-byte alignment of vcpu_info registration
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Woodhouse <[email protected]>
commit eacdb76c5f04956035c5d7f7e1973028f30684a2 upstream.
Xen's map_guest_area() enforces that vcpu_info is aligned to sizeof(xen_ulong_t). KVM has no such check, allowing a guest to register vcpu_info at an arbitrary byte alignment.
Enforce unconditional 4-byte alignment regardless of the current shinfo mode. This is sufficient because subsequent commits ensure that all locked atomic operations on vcpu_info fields use at most 32-bit accesses. Return -ENXIO on failure, matching Xen's map_guest_area() behaviour for unaligned requests.
Originally observed in review of an unrelated patch:
https://lore.kernel.org/all/[email protected]/
--- arch/x86/kvm/xen.c | 8 ++++++++ 1 file changed, 8 insertions(+)
arch/x86/kvm/xen.c +8 -0
@@ -878,6 +878,10 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpbreak ; } + r = -ENXIO ; +if (!IS_ALIGNED (data->u.gpa,sizeof (u32))) +break ; + r =kvm_gpc_activate (&vcpu->arch.xen.vcpu_info_cache, data->u.gpa,sizeof (struct vcpu_info )); }else {
@@ -887,6 +891,10 @@ int kvm_xen_vcpu_set_attr(struct kvm_vcpbreak ; } + r = -ENXIO ; +if (!IS_ALIGNED (data->u.hva,sizeof (u32))) +break ; + r =kvm_gpc_activate_hva (&vcpu->arch.xen.vcpu_info_cache, data->u.hva,sizeof (struct vcpu_info )); }
Greg Kroah-Hartman
maintainerPATCH 799/1536 KVM: x86/xen: Take kvm->srcu in __kvm_xen_has_interrupt()
In reply to Greg Kroah-Hartman6.12-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
@@ -665,6 +665,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 800/1536 KVM: x86: Preserve DR6.BLD (Bus Lock Detect) when delivering #DB payload
In reply to Greg Kroah-Hartman6.12-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
@@ -733,30 +733,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
@@ -765,6 +772,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 801/1536 KVM: x86: Request event processing for exception VM-Exits
In reply to Greg Kroah-Hartman6.12-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
@@ -790,6 +790,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 802/1536 KVM: x86: Take SRCU in kvm_zap_gfn_range()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chengfeng Ye <[email protected]>
commit b59a87c1ba3c347e8aec5f932eb7abf13064fd62 upstream.
kvm_zap_gfn_range() walks memslots and rmaps and may drop mmu_lock to reschedule. Callers that do not already hold kvm->srcu (or slots_lock) can race with memslot deletion: synchronize_srcu_expedited() does not wait, kvm_free_memslot() frees the old slot and its rmap, and the zap resumes on freed memory.
The VFIO noncoherent-DMA path hits this by zapping the entire GPA space without SRCU. KASAN reported:
BUG: KASAN: vmalloc-out-of-bounds in slot_rmap_walk_next+0x82/0x1c0 Read of size 8 at addr ffffc900005c1008 Call Trace: slot_rmap_walk_next+0x82/0x1c0 __kvm_rmap_zap_gfn_range+0x17a/0x280 kvm_zap_gfn_range+0x2a6/0x6a0 kvm_vfio_set_attr+0x576/0x770 kvm_device_ioctl+0x1ff/0x3b0
Take SRCU inside kvm_zap_gfn_range() so every caller is covered. Nesting with an existing kvm->srcu critical section is fine; the helper uses a local index. Drop the now-redundant SRCU pair from __kvm_set_or_clear_apicv_inhibit().
--- arch/x86/kvm/mmu/mmu.c | 2 ++ arch/x86/kvm/x86.c | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-)
arch/x86/kvm/mmu/mmu.c +2 -0
@@ -6664,6 +6664,8 @@ void kvm_zap_gfn_range(struct kvm *kvm,if (WARN_ON_ONCE (gfn_end <= gfn_start))return ; +guard (srcu)(&kvm->srcu); +write_lock (&kvm->mmu_lock);kvm_mmu_invalidate_begin (kvm);
arch/x86/kvm/x86.c +0 -2
@@ -10207,10 +10207,8 @@ void __kvm_set_or_clear_apicv_inhibit(st kvm->arch.apicv_inhibit_reasons = new;if (new) {unsigned long gfn =gpa_to_gfn (APIC_DEFAULT_PHYS_BASE ); -int idx =srcu_read_lock (&kvm->srcu);kvm_zap_gfn_range (kvm, gfn, gfn+1 ); -srcu_read_unlock (&kvm->srcu, idx); } }else { kvm->arch.apicv_inhibit_reasons = new;
Greg Kroah-Hartman
maintainerPATCH 803/1536 KVM: x86: Zero reserved synic flags when delivering message to avoid stack leak
In reply to Greg Kroah-Hartman6.12-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 804/1536 KVM: PPC: Book3S HV: Add preempt_disable() around virtual-mode HPTE bit-lock users
In reply to Greg Kroah-Hartman6.12-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
@@ -1192,9 +1192,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 ;
@@ -1814,8 +1816,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 ) {
@@ -1861,8 +1865,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 ) {