6.18.61-rc1 review
Subsystems (2)
Greg Kroah-Hartman
maintainerPATCH 694/1005 HID: wacom: Redesign shared sibling data lifecycle
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 480c9cb14ae81f8e112ff83f8778b3d7b9324dc8 upstream.
The Wacom driver coordinates state between sibling interfaces of the same physical device using a shared structure 'wacom_shared' inside 'wacom_hdev_data'. The driver kept a volatile representative pointer 'data->dev' pointing to a sibling 'hid_device' for physical path comparisons during sibling matching.
This pointer management is fragile. When the representative device is disconnected, wacom_remove_shared_data() failed to clear/update 'data->dev', leading to a Use-After-Free vulnerability when subsequent sibling probes dereference the dangling 'data->dev' pointer.
Resolve this issue by redesigning the sibling data lifecycle:
- Eliminate the volatile 'data->dev' representative pointer completely
- Redesign 'wacom_hdev_data' to store stable static copies of the required attributes upon first allocation: 'phys' path string, 'vendor', 'product' IDs and the sibling's 'device_type'
- Use these static attributes for stable sibling matching in wacom_are_sibling() and wacom_get_hdev_data()
This ensures sibling matching remains safe and stable even if individual siblings are dynamically added or removed.
To secure the lifecycle against concurrent probe/disconnect races:
- Switch kref_put() to kref_put_mutex() in wacom_remove_shared_data() to serialize refcount drops with list traversal and lookup
- Modify wacom_release_shared_data() to assume the list lock is already held
Also, do not accumulate the 'device_type' capability flag during subsequent sibling probes. Keeping only the first probed sibling's device_type exactly preserves the original sibling matching behavior without introducing side effects.
--- drivers/hid/wacom_sys.c | 70 +++++++++++++++++++++++++++++++----------------- 1 file changed, 46 insertions(+), 24 deletions(-)
drivers/hid/wacom_sys.c +46 -24
@@ -762,27 +762,47 @@ static void wacom_retrieve_hid_descriptostruct wacom_hdev_data {struct list_head list;struct kref kref; -struct hid_device *dev; +char phys[64 ]; +__u32 vendor; +__u32 product; +__u32 device_type;struct wacom_shared shared; }; +static bool wacom_compare_device_paths (struct hid_device *hdev_a, +const char *phys_b,char separator) +{ +const char *p1 =strrchr (hdev_a->phys, separator); +const char *p2 =strrchr (phys_b, separator); +int n1, n2; + +if (!p1 || !p2) +return false; + + n1 = p1 - hdev_a->phys; + n2 = p2 - phys_b; + +if (n1 != n2 || n1 <=0 || n2 <=0 ) +return false; + +return !strncmp (hdev_a->phys, phys_b, n1); +} +static LIST_HEAD (wacom_udev_list);static DEFINE_MUTEX (wacom_udev_list_lock);static bool wacom_are_sibling (struct hid_device *hdev, -struct hid_device *sibling) +struct wacom_hdev_data *data) {struct wacom *wacom =hid_get_drvdata (hdev);struct wacom_features *features = &wacom->wacom_wac.features; -struct wacom *sibling_wacom =hid_get_drvdata (sibling); -struct wacom_features *sibling_features = &sibling_wacom->wacom_wac.features;__u32 oVid = features->oVid ? features->oVid : hdev->vendor;__u32 oPid = features->oPid ? features->oPid : hdev->product;/* The defined oVid/oPid must match that of the sibling */ -if (features->oVid !=HID_ANY_ID && sibling->vendor != oVid) +if (features->oVid !=HID_ANY_ID && data->vendor != oVid)return false; -if (features->oPid !=HID_ANY_ID && sibling->product != oPid) +if (features->oPid !=HID_ANY_ID && data->product != oPid)return false;/*
@@ -790,11 +810,11 @@ static bool wacom_are_sibling(struct hid* device path, while those with different VID/PID must share * the same physical parent device path. */ -if (hdev->vendor == sibling->vendor && hdev->product == sibling->product) { -if (!hid_compare_device_paths (hdev, sibling,'/' )) +if (hdev->vendor == data->vendor && hdev->product == data->product) { +if (!wacom_compare_device_paths (hdev, data->phys,'/' ))return false; }else { -if (!hid_compare_device_paths (hdev, sibling,'.' )) +if (!wacom_compare_device_paths (hdev, data->phys,'.' ))return false; }
@@ -807,7 +827,7 @@ static bool wacom_are_sibling(struct hid* devices. */ if ((features->device_type &WACOM_DEVICETYPE_DIRECT ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + !(data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/*
@@ -815,17 +835,17 @@ static bool wacom_are_sibling(struct hid* devices. */ if (!(features->device_type &WACOM_DEVICETYPE_DIRECT ) && - (sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + (data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/* Pen devices may only be siblings of touch devices */ if ((features->device_type &WACOM_DEVICETYPE_PEN ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_TOUCH )) + !(data->device_type &WACOM_DEVICETYPE_TOUCH ))return false;/* Touch devices may only be siblings of pen devices */ if ((features->device_type &WACOM_DEVICETYPE_TOUCH ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_PEN )) + !(data->device_type &WACOM_DEVICETYPE_PEN ))return false;/*
@@ -841,7 +861,7 @@ static struct wacom_hdev_data *wacom_get/* Try to find an already-probed interface from the same device */ list_for_each_entry (data, &wacom_udev_list, list) { -if (hid_compare_device_paths (hdev, data->dev,'/' )) { +if (wacom_compare_device_paths (hdev, data->phys,'/' )) {kref_get (&data->kref);return data; }
@@ -849,7 +869,7 @@ static struct wacom_hdev_data *wacom_get/* Fallback to finding devices that appear to be "siblings" */ list_for_each_entry (data, &wacom_udev_list, list) { -if (wacom_are_sibling (hdev, data->dev)) { +if (wacom_are_sibling (hdev, data)) {kref_get (&data->kref);return data; }
@@ -863,18 +883,15 @@ static void wacom_release_shared_data(ststruct wacom_hdev_data *data = container_of(kref, struct wacom_hdev_data, kref); -mutex_lock (&wacom_udev_list_lock);list_del (&data->list); -mutex_unlock (&wacom_udev_list_lock); -kfree (data); }static void wacom_remove_shared_data (void *res) { -struct wacom *wacom = res; +struct wacom *res_wacom = res;struct wacom_hdev_data *data; -struct wacom_wac *wacom_wac = &wacom->wacom_wac; +struct wacom_wac *wacom_wac = &res_wacom->wacom_wac;if (wacom_wac->shared) { data = container_of(wacom_wac->shared, struct wacom_hdev_data,
@@ -888,17 +905,19 @@ static void wacom_remove_shared_data(voircu_dereference_protected (wacom_wac->shared->pen,lockdep_is_held (&wacom_udev_list_lock)); -if (touch == wacom->hdev) { +if (touch == res_wacom->hdev) {rcu_assign_pointer (wacom_wac->shared->touch,NULL );rcu_assign_pointer (wacom_wac->shared->touch_input,NULL ); - }else if (pen == wacom->hdev) { + }else if (pen == res_wacom->hdev) {rcu_assign_pointer (wacom_wac->shared->pen,NULL ); } }synchronize_rcu (); -kref_put (&data->kref, wacom_release_shared_data); +if (kref_put_mutex (&data->kref, wacom_release_shared_data, &wacom_udev_list_lock)) +mutex_unlock (&wacom_udev_list_lock); + wacom_wac->shared =NULL ; } }
@@ -921,7 +940,10 @@ static int wacom_add_shared_data(struct }kref_init (&data->kref); - data->dev = hdev; +strscpy (data->phys, hdev->phys,sizeof (data->phys)); + data->vendor = hdev->vendor; + data->product = hdev->product; + data->device_type = wacom_wac->features.device_type;list_add_tail (&data->list, &wacom_udev_list); }
Greg Kroah-Hartman
maintainerPATCH 695/1005 HID: wacom: Setup SW_MUTE_DEVICE according to the order of input registration
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ping Cheng <[email protected]>
commit 97ce491bcef2d231b8d51cee8e579183319a5ba4 upstream.
The refactored SW_MUTE_DEVICE code assumed that stylus will be the first regiestered input. In reality, touch can be registered before stylus, such as the Wacom Cintiq Pro 13 and 16.
This patch covers both touch-first and stylus-first cases.
--- drivers/hid/wacom_wac.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-)
drivers/hid/wacom_wac.c +30 -3
@@ -3977,10 +3977,18 @@ int wacom_setup_touch_input_capabilitiesif (features->type ==HID_GENERIC ) {hid_dbg (hdev,"generic touch setup\n" ); -if (wacom_wac->has_mute_touch_switch || - (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch))) { + +/* +* This is to setup the touch switch for those devices that report +* pen interface first. The setup can only be done here since this +* routine is only called once. When we are here, the shared +* has_mute_touch_switch has been set by the pad. + +* There are two ways of reporting inputs from firmware: stylus first +* or touch first. This path covers the stylus input first case. +*/ +if (wacom_wac->shared &&READ_ONCE (wacom_wac->shared->has_mute_touch_switch)) {input_set_capability (input_dev,EV_SW ,SW_MUTE_DEVICE ); - wacom_wac->has_mute_touch_switch = true; }/* setup has already been done */ return 0 ;
@@ -4403,7 +4411,26 @@ int wacom_setup_pad_input_capabilities(sbreak ;case INTUOSHT3_BT : +break ; +case HID_GENERIC : +if (wacom_wac->shared) { +/* +* The setup of touch switch capability can only be done +* here for those devices, such as Cintiq Pro 13 and 16, +* that have touch input registered before stylus and pad +* inputs. +* +* There are two ways of reporting inputs from firmware: +* stylus first or touch first. This path covers the touch +* input first case. +*/ +if (wacom_wac->has_mute_touch_switch && + wacom_wac->shared->touch_input) { +input_set_capability (wacom_wac->shared->touch_input, +EV_SW ,SW_MUTE_DEVICE ); + } + }break ;default :
Greg Kroah-Hartman
maintainerPATCH 696/1005 HID: wacom: Write shared touch initial status only once
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ping Cheng <[email protected]>
commit cae3031c691dff0be61a26bc64e31a6939010d5c upstream.
For consistency with how the shared has_mute_touch_switch is handled during registration, let's apply WRITE_ONCE to is_touch_on too.
--- drivers/hid/wacom_sys.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/wacom_sys.c +1 -1
@@ -2391,7 +2391,7 @@ static void wacom_set_shared_values(stru* match historic default. */ if (wacom_wac->is_soft_touch_switch) - wacom_wac->shared->is_touch_on = true; +WRITE_ONCE (wacom_wac->shared->is_touch_on, true); }if (wacom_wac->features.device_type &WACOM_DEVICETYPE_TOUCH ) {
Greg Kroah-Hartman
maintainerPATCH 697/1005 klist: avoid accesses after waking klist_remove()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit 732e3e10234cbe302d0dcbaa98c91c66628209cb upstream.
klist_remove() waits until a node is unreferenced so that its caller can free the containing object. klist_release() currently publishes waiter->woken and wakes the waiter before its final accesses to the waiter and node. klist_remove() can then return, allowing its stack waiter and the containing object to be freed or reused while klist_release() is still running. In particular, bus_remove_driver() can free drv->p while __device_attach() walks the same bus klist with bus_for_each_drv().
On an arm64 Cortex-A72 system, an unpatched 7.2.0-rc3 kernel with CONFIG_PREEMPT_RT=y and CONFIG_KASAN=y reproduced the bug through the in-tree I2C/at24 path. KASAN reported a use-after-free in klist_dec_and_del() reached from klist_next()/bus_for_each_drv() while at24 was being unregistered.
Clear n_klist and take a task reference before publishing woken. Use release/acquire accesses for that publication and wake the referenced task. The task reference keeps the waiter task alive if it returns and exits before wake_up_process().
--- lib/klist.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
lib/klist.c +12 -4
@@ -36,6 +36,7 @@#include <linux/klist.h> #include <linux/export.h> #include <linux/sched.h> +#include <linux/sched/task.h> /* * Use the lowest bit of n_klist to mark deleted nodes and exclude
@@ -187,18 +188,24 @@ static void klist_release(struct kref *kWARN_ON (!knode_dead (n));list_del (&n->n_node); +knode_set_klist (n,NULL );spin_lock (&klist_remove_lock);list_for_each_entry_safe (waiter, tmp, &klist_remove_waiters, list) { +struct task_struct *p; +if (waiter->node != n)continue ; + p = waiter->process; +get_task_struct (p);list_del (&waiter->list); - waiter->woken =1 ; +/* Publish only after the final waiter and n accesses */ +smp_store_release (&waiter->woken,1 );mb (); -wake_up_process (waiter->process); +wake_up_process (p); +put_task_struct (p); }spin_unlock (&klist_remove_lock); -knode_set_klist (n,NULL ); }static int klist_dec_and_del (struct klist_node *n)
@@ -250,7 +257,8 @@ void klist_remove(struct klist_node *n)for (;;) {set_current_state (TASK_UNINTERRUPTIBLE ); -if (waiter.woken) +/* Pairs with the release store in klist_release() */ +if (smp_load_acquire (&waiter.woken))break ;schedule (); }
Greg Kroah-Hartman
maintainerPATCH 698/1005 objtool/rust: add one more `noreturn` Rust function for Rust 1.101.0
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Miguel Ojeda <[email protected]>
commit 6b704ec9007a3f23ec5ded8f320825ac444f307d upstream.
Starting with Rust 1.101.0 (expected 2026-12-24), objtool may report:
rust/kernel.o: warning: objtool: _R..._4core6result13unwrap_failed...() falls through to next function _R..._4core6result13unwrap_failed...()
(and others) due to calls to the noreturn symbol:
core::result::unwrap_failed::unwrap_failed_inner
Rust introduced this helper when making unwrap_failed generic [1]. The existing entry for unwrap_failed does not match the new helper.
Thus add the mangled one to the list so that objtool knows it is actually noreturn.
See commit 56d680dd23c3 ("objtool/rust: list noreturn Rust functions") for more details.
--- tools/objtool/check.c | 1 + 1 file changed, 1 insertion(+)
tools/objtool/check.c +1 -0
@@ -221,6 +221,7 @@ static bool is_rust_noreturn(const strucstr_ends_with (func->name,"_4core6option13expect_failed" ) ||str_ends_with (func->name,"_4core6option13unwrap_failed" ) ||str_ends_with (func->name,"_4core6result13unwrap_failed" ) || +str_ends_with (func->name,"_4core6result13unwrap_failed19unwrap_failed_inner" ) ||str_ends_with (func->name,"_4core9panicking5panic" ) ||str_ends_with (func->name,"_4core9panicking9panic_fmt" ) || str_ends_with(func->name, "_4core9panicking14panic_explicit") ||
Greg Kroah-Hartman
maintainerPATCH 699/1005 rust: bitmap: restrict bitmap length to at most i32::MAX
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eliot Courtney <[email protected]>
commit 931790a91378f6513ba82730eb5607479c3184a0 upstream.
It is currently possible to construct a non-BitmapVec backed Bitmap using Bitmap::from_raw that is larger than i32::MAX, and it is not part of the unsafe requirements. Restricting all bitmaps (even non-BitmapVec backed ones) to a maximum size of i32::MAX simplifies a few things and matches BitmapVec::MAX_LEN. For example, copy_and_extend truncates len to u32, which is wrong for > u32::MAX size. __bitmap_set and __bitmap_clear need i32 for size and u32 for start - so they can't be run on a Bitmap with a > i32::MAX size. Rather than adding runtime checks to account for the case of a non BitmapVec backed Bitmap, just include that in the requirements for Bitmap.
Add that requirement to the unsafe requirements on Bitmap::from_raw and Bitmap::from_raw_mut, and to the invariants on Bitmap.
This also fixes u32 casts truncating in copy_and_extend, which could otherwise lead to OOB writes.
[ Added a few intra-doc links. Added backticks to C types. Capitalize
tagged comments. - Miguel ]
--- rust/kernel/bitmap.rs | 70 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 21 deletions(-)
rust/kernel/bitmap.rs +49 -21
@@ -19,24 +19,59 @@ const BITS_PER_LONG: usize = bindings::B/// # Invariants /// /// Must reference a `[c_ulong]` long enough to fit `data.len()` bits. +/// Must not be longer than [`i32::MAX`] bits, so offsets and lengths used with +/// [`Bitmap`] functions fit in the `int` and `unsigned int` arguments of the C bitmap API. +/// This also matches [`BitmapVec::MAX_LEN`]. #[cfg_attr( CONFIG_64BIT , repr(align( 8 )))] #[cfg_attr(not( CONFIG_64BIT ), repr(align( 4 )))] pub struct Bitmap { data: [()], } +macro_rules! bitmap_assert { + ($cond:expr, $($arg:tt)+) => { +#[cfg( CONFIG_RUST_BITMAP_HARDENED )] +assert! ($cond, $($arg)*); + } +} + +macro_rules! bitmap_assert_return { + ($cond:expr, $($arg:tt)+) => { +#[cfg( CONFIG_RUST_BITMAP_HARDENED )] +assert! ($cond, $($arg)*); + +#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] +if !($cond) { +pr_err! ($($arg)*); +return + } + } +} +impl Bitmap {/// Borrows a C bitmap. /// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `nbits` exceeds [`i32::MAX`]. +/// /// # Safety /// /// * `ptr` holds a non-null address of an initialized array of `unsigned long` /// that is large enough to hold `nbits` bits. +/// * `nbits` must not exceed [`i32::MAX`]. /// * the array must not be freed for the lifetime of this [`Bitmap`] /// * concurrent access only happens through atomic operations pub unsafe fn from_raw <'a>(ptr: *const usize , nbits:usize ) -> &'aBitmap { +bitmap_assert! ( + nbits <=i32 ::MAX as usize , +"`nbits` must be <= {}, was {}" , +i32 ::MAX , + nbits + );let data: *const [()] = core::ptr::slice_from_raw_parts (ptr.cast (), nbits);// INVARIANT: `data` references an initialized array that can hold `nbits` bits. +// INVARIANT: The caller guarantees that `nbits` does not exceed `i32::MAX`. // SAFETY: // The caller guarantees that `data` (derived from `ptr` and `nbits`) // points to a valid, initialized, and appropriately sized memory region
@@ -53,15 +88,27 @@ impl Bitmap {/// Borrows a C bitmap exclusively. /// +/// # Panics +/// +/// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `nbits` exceeds [`i32::MAX`]. +/// /// # Safety /// /// * `ptr` holds a non-null address of an initialized array of `unsigned long` /// that is large enough to hold `nbits` bits. +/// * `nbits` must not exceed [`i32::MAX`]. /// * the array must not be freed for the lifetime of this [`Bitmap`] /// * no concurrent access may happen. pub unsafe fn from_raw_mut <'a>(ptr: *mut usize , nbits:usize ) -> &'amut Bitmap { +bitmap_assert! ( + nbits <=i32 ::MAX as usize , +"`nbits` must be <= {}, was {}" , +i32 ::MAX , + nbits + );let data: *mut [()] = core::ptr::slice_from_raw_parts_mut (ptr.cast (), nbits);// INVARIANT: `data` references an initialized array that can hold `nbits` bits. +// INVARIANT: The caller guarantees that `nbits` does not exceed `i32::MAX`. // SAFETY: // The caller guarantees that `data` (derived from `ptr` and `nbits`) // points to a valid, initialized, and appropriately sized memory region
@@ -98,26 +145,6 @@ union BitmapRepr { ptr: NonNull<usize>, } -macro_rules! bitmap_assert { - ($cond:expr, $($arg:tt)+) => { -#[cfg( CONFIG_RUST_BITMAP_HARDENED )] -assert! ($cond, $($arg)*); - } -} - -macro_rules! bitmap_assert_return { - ($cond:expr, $($arg:tt)+) => { -#[cfg( CONFIG_RUST_BITMAP_HARDENED )] -assert! ($cond, $($arg)*); - -#[cfg(not( CONFIG_RUST_BITMAP_HARDENED ))] -if !($cond) { -pr_err! ($($arg)*); -return - } - } -} -/// Represents an owned bitmap. /// /// Wraps underlying C bitmap API. See [`Bitmap`] for available
@@ -401,7 +428,8 @@ impl Bitmap {#[inline] pub fn copy_and_extend (&mut self, src: &Bitmap ) {let len = core::cmp::min (src.len (), self.len ()); -// SAFETY: access to `self` and `src` is within bounds. +// SAFETY: Access to `self` and `src` is within bounds. Both lengths fit in `u32` +// because a `Bitmap` is at most `i32::MAX` bits, so the casts are lossless. unsafe { bindings::bitmap_copy_and_extend ( self.as_mut_ptr(),
Re: [PATCH 6.18 0699/1005] rust: bitmap: restrict bitmap length to at most i32::MAX
Quoted 2 lines · On Wed, 04 Nov 2026 16:07:12 -0500 Greg Kroah-Hartman…
+/// This also matches [
BitmapVec::MAX_LEN].
This is a broken intra-doc link -- it can be fixed with a trivial one-liner I just sent here:
https://lore.kernel.org/stable/[email protected]/
But another option (cleaner but a bigger change) is to cherry-pick:
f5535d78e126 ("rust: bitmap: add MAX_LEN and MAX_INLINE_LEN constants")
Cheers,
Miguel
Re: [PATCH 6.18 0699/1005] rust: bitmap: restrict bitmap length to at most i32::MAX
Quoted 4 lines · Miguel Ojeda
Quoted 2 lines · On Wed, 04 Nov 2026 16:07:12 -0500 Greg Kroah-Hartman…
+/// This also matches [
BitmapVec::MAX_LEN].
Quoted 8 lines
This is a broken intra-doc link -- it can be fixed with a trivial one-liner I just sent here:
https://lore.kernel.org/stable/[email protected]/
But another option (cleaner but a bigger change) is to cherry-pick:
f5535d78e126("rust: bitmap: addMAX_LENandMAX_INLINE_LENconstants")
Both options (the one-liner fix or cherry-picking f5535d78e126) look good to me.
Alice
Greg KH
maintainerRe: [PATCH 6.18 0699/1005] rust: bitmap: restrict bitmap length to at most i32::MAX
In reply to Miguel OjedaQuoted 4 lines · Miguel Ojeda
Quoted 2 lines · On Wed, 04 Nov 2026 16:07:12 -0500 Greg Kroah-Hartman…
+/// This also matches [
BitmapVec::MAX_LEN].
Quoted 8 lines
This is a broken intra-doc link -- it can be fixed with a trivial one-liner I just sent here:
https://lore.kernel.org/stable/[email protected]/
But another option (cleaner but a bigger change) is to cherry-pick:
f5535d78e126("rust: bitmap: addMAX_LENandMAX_INLINE_LENconstants")
Great, I'll do that now, thanks.
greg k-h
Sasha Levin
maintainerRe: [PATCH 6.18 0699/1005] rust: bitmap: restrict bitmap length to at most i32::MAX
In reply to Miguel OjedaQuoted 3 lines
But another option (cleaner but a bigger change) is to cherry-pick:
f5535d78e126("rust: bitmap: addMAX_LENandMAX_INLINE_LENconstants")
I took your one-liner for 6.18, since f5535d78e126 ("rust: bitmap: add MAX_LEN and MAX_INLINE_LEN constants") adds new API and is not a fix.
Signature · 2 lines
Thanks, Sasha
Greg Kroah-Hartman
maintainerPATCH 700/1005 rust: block: fix `Send` bound for `GenDisk`
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Hindborg <[email protected]>
commit e502b667ee70a7fa2a578e7722672ecd4fe0eb81 upstream.
The Send implementation for GenDisk<T> was conditioned on T: Send. This constrains the wrong type. T is the Operations implementation, which is typically a zero-sized marker type that carries no data, so `T:
Send says nothing about whether the data a GenDisk` actually owns can be moved to another thread.
A GenDisk<T> owns the queue data T::QueueData (stored as the gendisk's queuedata and dropped when the GenDisk is dropped) and an Arc<TagSet<T>>. These are the values transferred when a GenDisk is sent across a thread boundary, so the Send bound must constrain exactly them. Bound T::QueueData: Send and Arc<TagSet<T>>: Send instead.
--- rust/kernel/block/mq/gen_disk.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
rust/kernel/block/mq/gen_disk.rs +8 -2
@@ -215,8 +215,14 @@ pub struct GenDisk<T: Operations> { }// SAFETY: `GenDisk` is an owned pointer to a `struct gendisk` and an `Arc` to a -// `TagSet` It is safe to send this to other threads as long as T is Send. -unsafe impl <T :Operations +Send >Send for GenDisk <T > {} +// `TagSet`. It is safe to send this to other threads as long as these two are `Send`. +unsafe impl <T >Send for GenDisk <T > +where +T :Operations , +T ::QueueData :Send , +Arc <TagSet <T >>:Send , +{ +}impl <T :Operations >Drop for GenDisk <T > {fn drop (&mut self) {
Greg Kroah-Hartman
maintainerPATCH 701/1005 rust: block: require `Sync` for `Operations::QueueData`
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Hindborg <[email protected]>
commit 67b7a2728e4873e64405c5564fe50f7123012b71 upstream.
The queue data installed in a GenDisk is stored in the request queue and handed back to the driver as a shared borrow through the queue_rq and commit_rqs callbacks. Both callbacks obtain that borrow via ForeignOwnable::borrow and may execute concurrently on several CPUs, since the block layer runs one hardware queue per CPU. That means a shared reference to the same queue data can be live on multiple threads at once, which is only sound when the referent is Sync.
The initial GenDisk private data support omitted this bound, so a driver could install a non-Sync type as queue data and then access it concurrently from multiple CPUs without synchronization. Add a Sync bound to the QueueData associated type to rule that out.
--- rust/kernel/block/mq/operations.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/block/mq/operations.rs +1 -1
@@ -30,7 +30,7 @@ type ForeignBorrowed<'a, T> = <T as Forepub trait Operations :Sized {/// Data associated with the `struct request_queue` that is allocated for /// the `GenDisk` associated with this `Operations` implementation. -type QueueData :ForeignOwnable ; +type QueueData :ForeignOwnable +Sync ;/// Called by the kernel to queue a request with the driver. If `is_last` is /// `false`, the driver is allowed to defer committing the request.
Greg Kroah-Hartman
maintainerPATCH 702/1005 rust: configfs: fix data offset calculation for subsystem callbacks
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Hindborg <[email protected]>
commit e84c9b64df615e658e47561b835c1364dc48f0c0 upstream.
get_group_data() chooses between Group::<Parent>::container_of() and Subsystem::<Parent>::container_of() based on whether this represents the root group of a configfs subsystem. It detects this by checking (*this).cg_subsys.is_null(), but link_group() in fs/configfs/dir.c unconditionally sets cg_subsys for every config_group attached anywhere in a registered subsystem, including the subsystem's own su_group. The only config_group with a NULL cg_subsys is the configfs root, on which userspace cannot trigger callbacks. The check is therefore always false at runtime, and the Subsystem branch is dead. Subsystem-level callbacks reach the Group branch and may read data at the wrong offset.
Thus change the is_root check to correctly identify whether a group is a root group by comparing this to subsys.su_group.
--- rust/kernel/configfs.rs | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-)
rust/kernel/configfs.rs +28 -15
@@ -298,26 +298,39 @@ unsafe impl<Data> HasGroup<Data> for Gro/// /// `this` must be a valid pointer. /// -/// If `this` does not represent the root group of a configfs subsystem, -/// `this` must be a pointer to a `bindings::config_group` embedded in a -/// `Group<Parent>`. +/// If `this` is the `su_group` field of a `bindings::configfs_subsystem`, that +/// `configfs_subsystem` must be embedded in a `Subsystem<Parent>`. /// -/// Otherwise, `this` must be a pointer to a `bindings::config_group` that -/// is embedded in a `bindings::configfs_subsystem` that is embedded in a -/// `Subsystem<Parent>`. +/// Otherwise, `this` must be a pointer to a `bindings::config_group` embedded +/// in a `Group<Parent>`. unsafe fn get_group_data <'a,Parent >(this: *mut bindings::config_group ) -> &'aParent {// SAFETY: `this` is a valid pointer. -let is_root =unsafe { (*this).cg_subsys.is_null () }; +let subsys =unsafe { (*this).cg_subsys }; -if !is_root { -// SAFETY: By C API contact,`this` was returned from a call to -// `make_group`. The pointer is known to be embedded within a -// `Group<Parent>`. -unsafe { &(*Group ::<Parent >::container_of (this)).data } - }else { -// SAFETY: By C API contract, `this` is a pointer to the -// `bindings::config_group` field within a `Subsystem<Parent>`. +// `link_group()` in `fs/configfs/dir.c` assigns `cg_subsys` for every +// `config_group` attached anywhere in a registered subsystem, including +// the subsystem's own `su_group` (which gets a pointer to itself). The +// only `config_group` with a NULL `cg_subsys` is the configfs root, and +// userspace cannot trigger callbacks on it. The group is therefore the +// subsystem's `su_group` iff it equals `&cg_subsys->su_group`. +let is_root = !subsys.is_null () + && core::ptr::eq ( + this.cast_const (), +// SAFETY: For every `config_group` the configfs core dispatches a +// callback on, `cg_subsys` was set by `link_group()` at registration time +// and points to a valid `configfs_subsystem` that outlives the callback. +unsafe { &raw const (*subsys).su_group }, + ); + +if is_root { +// SAFETY: By the above, `this` is the `su_group` field of a +// `configfs_subsystem` that, by function safety requirements, is +// embedded in a `Subsystem<Parent>`. unsafe { &(*Subsystem ::container_of (this)).data } + }else { +// SAFETY: By function safety requirements, `this` is a +// `config_group` embedded in a `Group<Parent>`. +unsafe { &(*Group ::<Parent >::container_of (this)).data } } }
Greg Kroah-Hartman
maintainerPATCH 703/1005 rust: cpufreq: reject NULL from cpufreq_cpu_get()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mehmet Koseoglu <[email protected]>
commit 02c5d7bfa8724789f6620f7787532666edc891a1 upstream.
cpufreq_cpu_get() returns either a referenced policy or NULL. PolicyCpu::from_cpu() passed its return value to from_err_ptr(), which rejects ERR_PTR values but accepts NULL.
If the lookup fails, Policy::from_raw_mut() therefore constructs a mutable reference from NULL. Dropping the resulting PolicyCpu then passes the invalid pointer to cpufreq_cpu_put(), causing an oops in kobject_put().
Reject NULL with NonNull before constructing the Policy reference. Return ENODEV instead.
A KUnit negative-control run reproduced the oops with the original conversion. The same test passed with this change. The reproducer is available on request.
--- rust/kernel/cpufreq.rs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-)
rust/kernel/cpufreq.rs +16 -6
@@ -14,7 +14,13 @@ use crate::{ cpumask, device::{Bound, Device}, devres, - error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, + error::{ + code::*, + from_result, + to_result, + Result, + VTABLE_DEFAULT_ERROR, // + }, ffi::{c_char, c_ulong}, prelude::*, types::ForeignOwnable,
@@ -29,7 +35,10 @@ use core::{ marker::PhantomData, ops::{Deref, DerefMut}, pin::Pin, - ptr, + ptr::{ + self, +NonNull ,// + }, };use macros::vtable;
@@ -686,12 +695,13 @@ struct PolicyCpu<'a>(&'a mut Policy);impl <'a>PolicyCpu <'a> {fn from_cpu (cpu:CpuId ) ->Result <Self > {// SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. -let ptr =from_err_ptr (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) })?; +let ptr = +NonNull ::new (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) }).ok_or (ENODEV )?;Ok (Self ( -// SAFETY: The `ptr` is guaranteed to be valid and remains valid for the lifetime of -// the returned reference. -unsafe {Policy ::from_raw_mut (ptr) }, +// SAFETY: `ptr` is non-NULL and `cpufreq_cpu_get()` took a reference on it, so it is +// valid for writing and remains valid for the lifetime of the returned reference. +unsafe {Policy ::from_raw_mut (ptr.as_ptr ()) }, )) } }
Greg Kroah-Hartman
maintainerPATCH 704/1005 rust: rcpufreq_dt: add module alias
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Frank Zhang <[email protected]>
commit 53732733c7af437b0ed710a1df91a67a0d3dfc07 upstream.
Add the missing platform:cpufreq-dt module alias so that the driver can be automatically loaded when the platform device is registered.
--- drivers/cpufreq/rcpufreq_dt.rs | 1 + 1 file changed, 1 insertion(+)
drivers/cpufreq/rcpufreq_dt.rs +1 -0
@@ -219,4 +219,5 @@ module_platform_driver! { authors: ["Viresh Kumar <[email protected]>"], description: "Generic CPUFreq DT driver", license: "GPL v2", + alias: ["platform:cpufreq-dt"], }
Greg Kroah-Hartman
maintainerPATCH 705/1005 ALSA: control: Fix UAF in snd_ctl_elem_add() on card disconnect
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Takashi Iwai <[email protected]>
commit d4febca239be3c91498762dd0535a87d4af1eabc upstream.
A use-after-free can be triggered via SNDRV_CTL_IOCTL_ELEM_ADD when a USB audio card is disconnected while an ELEM_ADD ioctl is in flight.
The reproducer parks the ioctl thread inside copy_from_user() using userfaultfd, then tears down the USB device. Unlike every other ALSA control _user handler (ELEM_INFO, ELEM_READ, ELEM_WRITE, TLV_*), snd_ctl_elem_add_user() never calls snd_power_ref_and_wait(), so the parked thread holds no power reference. snd_card_disconnect() therefore cannot observe it via snd_power_sync_ref() and proceeds unimpeded:
1. card->shutdown is set to 1
2. device_del(&card->card_dev) drops the kobject reference on the
parent USB interface device (card->dev = &intf->dev)
3. The USB core drops its own reference and calls device_release(), freeing the struct usb_interface, including the embedded struct device that card->dev points to
When the userfaultfd is resolved and the thread resumes, snd_ctl_elem_add() acquires controls_rwsem without checking card->shutdown and calls __snd_ctl_add_replace(). Because the reproducer pre-registered the same control, the CTL_ADD_EXCLUSIVE path calls dev_err(card->dev, ...) on the freed USB interface:
KASAN: slab-use-after-free Read in __dev_printk
Add a card->shutdown guard immediately after acquiring controls_rwsem in snd_ctl_elem_add(). At that point card->shutdown is guaranteed to be stable: snd_card_disconnect() sets it before freeing the parent device, and it never transitions back to 0. A thread that acquired the lock before disconnect sees shutdown=0 and holds the write lock through the rest of the operation, preventing concurrent disconnect from proceeding past its own controls_rwsem-less shutdown=1 store (which happened earlier, outside the lock) from racing with dev_err().
--- sound/core/control.c | 2 ++ 1 file changed, 2 insertions(+)
sound/core/control.c +2 -0
@@ -1676,6 +1676,8 @@ static int snd_ctl_elem_add(struct snd_c alloc_size =compute_user_elem_size (private_size, count);guard (rwsem_write)(&card->controls_rwsem); +if (card->shutdown) +return -ENODEV ;if (check_user_elem_overflow (card, alloc_size))return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 706/1005 ALSA: emux: Fix UAF of soundfont zones at note-on
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Takashi Iwai <[email protected]>
commit 34e3e04b8a1731a773797542f0781e99ce7cd755 upstream.
snd_emux_note_on() looks up the matching zones via snd_soundfont_search_zone(), which takes sflist->lock only during the lookup and returns the raw zone pointers after releasing it. The caller then stores them in vp->zone without any protection. Meanwhile, a concurrent SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES ioctl may unlink and free those zones in snd_soundfont_remove_unlocked(); this leads to a use-after-free in snd_emux_note_on(), and later at accessing the cached vp->zone, e.g. in snd_emux_send_effect().
Fix it by holding sflist->lock in snd_emux_note_on() over the whole zone lookup and voice setup, and let snd_soundfont_search_zone() require the caller to hold the lock, instead. snd_soundfont_lock_preset() takes sflist->lock for setting presets_locked, so the removal path now syncs with the note-on finish.
--- sound/synth/emux/emux_synth.c | 3 +++ sound/synth/emux/soundfont.c | 9 ++++++--- 2 files changed, 9 insertions(+), 3 deletions(-)
sound/synth/emux/emux_synth.c +3 -0
@@ -60,6 +60,9 @@ snd_emux_note_on(void *p, int note, intreturn ; key = note;/* remember the original note */ + +/* hold sflist->lock for protecting against concurrent free */ +guard (spinlock_irqsave)(&emu->sflist->lock); nvoices =get_zone (emu, port, ¬e, vel, chan, table);if (! nvoices)return ;
sound/synth/emux/soundfont.c +6 -3
@@ -1225,6 +1225,9 @@ delete_preset(struct snd_sf_list *sflist* The found zones are stored on 'table' array. max_layers defines * the maximum number of elements in this array. * This function returns the number of found zones. 0 if not found. +* +* The caller must hold sflist->lock, and keep holding it as long as +* the returned zones are accessed. */ int snd_soundfont_search_zone(struct snd_sf_list *sflist, int *notep, int vel,
@@ -1234,11 +1237,11 @@ snd_soundfont_search_zone(struct snd_sf_ {int nvoices; -/* this function is supposed to be called atomically, -* so we check the lock. if it's busy, just returns 0 to +lockdep_assert_held (&sflist->lock); + +/* if the presets are being modified, just returns 0 to * tell the caller the busy state */ -guard (spinlock_irqsave)(&sflist->lock);if (sflist->presets_locked)return 0 ; nvoices = search_zones(sflist, notep, vel, preset, bank,
Greg Kroah-Hartman
maintainerPATCH 707/1005 ALSA: pcmtest: handle multiple wraps in random capture fill
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sung Byeongchan <[email protected]>
commit 6541871e8e63e721733cd120af4d9cd22c5ef62f upstream.
The random capture helpers assume that the data generated for one timer tick wraps the DMA ring at most once. However, b_rw describes 200 ms of audio because the timer runs at 5 Hz, so it can be several times larger than a small ring.
For 48 kHz, S16_LE, four-channel capture with a 512-frame buffer, the DMA ring is 4096 bytes while one tick generates 76800 bytes. After filling the 4096-byte tail, the existing code issues a second 72704-byte write from the ring base, writing 68608 bytes beyond the ring. Both interleaved and non-interleaved capture are affected.
KASAN reports the first write into the adjacent free page as a use-after-free in the random-byte generator. The underlying defect is an out-of-bounds write from the live DMA ring, not a stale DMA allocation.
Split each random write repeatedly at the interleaved ring or per-channel block boundary. Keep the hardware-pointer update exactly once after the complete logical write.
The issue reproduced on three of three clean boots. With this change, the same vulnerable geometry completed six times without a sanitizer finding. Boundary, pattern-fill, no-timer, open/close, and module-reload controls also completed normally.
snd-pcmtest is a test driver, and selecting random fill requires an administrator-controlled module parameter. The written values come from the kernel random generator; no privilege escalation or attacker-controlled write primitive was demonstrated.
--- sound/drivers/pcmtest.c | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-)
sound/drivers/pcmtest.c +19 -23
@@ -280,39 +280,35 @@ static void fill_block_pattern(struct pcfill_block_pattern_n (v_iter, runtime); } +static void fill_random_block (char *buf,size_t buf_size,size_t pos, +size_t count) +{ +while (count) { +size_t chunk =min (count, buf_size - pos); + +get_random_bytes (buf + pos, chunk); + count -= chunk; + pos =0 ; + } +} +static void fill_block_rand_n (struct pcmtst_buf_iter *v_iter,struct snd_pcm_runtime *runtime) {unsigned int channels = runtime->channels; -// Remaining space in all channel buffers -size_t bytes_remain = runtime->dma_bytes - v_iter->buf_pos; +size_t pos = v_iter->buf_pos / channels;unsigned int i; -for (i =0 ; i < channels; i++) { -if (v_iter->b_rw <= bytes_remain) { -//b_rw - count of bytes must be written for all channels at each timer tick -get_random_bytes (runtime->dma_area +buf_pos_n (v_iter, channels, i), - v_iter->b_rw / channels); - }else { -// Write to the end of buffer and start from the beginning of it -get_random_bytes (runtime->dma_area +buf_pos_n (v_iter, channels, i), - bytes_remain / channels); -get_random_bytes (runtime->dma_area + v_iter->chan_block * i, - (v_iter->b_rw - bytes_remain) / channels); - } - } +for (i =0 ; i < channels; i++) +fill_random_block (runtime->dma_area + v_iter->chan_block * i, + v_iter->chan_block, pos, + v_iter->b_rw / channels);inc_buf_pos (v_iter, v_iter->b_rw, runtime->dma_bytes); }static void fill_block_rand_i (struct pcmtst_buf_iter *v_iter,struct snd_pcm_runtime *runtime) { -size_t in_cur_block = runtime->dma_bytes - v_iter->buf_pos; - -if (v_iter->b_rw <= in_cur_block) { -get_random_bytes (&runtime->dma_area[v_iter->buf_pos], v_iter->b_rw); - }else { -get_random_bytes (&runtime->dma_area[v_iter->buf_pos], in_cur_block); -get_random_bytes (runtime->dma_area, v_iter->b_rw - in_cur_block); - } +fill_random_block (runtime->dma_area, runtime->dma_bytes, + v_iter->buf_pos, v_iter->b_rw);inc_buf_pos (v_iter, v_iter->b_rw, runtime->dma_bytes); }
Greg Kroah-Hartman
maintainerPATCH 708/1005 ASoC: amd: ps: fix snd_acp63_remove() teardown ordering
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit c53791d673ed4da6759d276078627ec4d0c6536b upstream.
The ACP IRQ handlers dereference the SoundWire, SoundWire DMA, and PDM child platform devices, but snd_acp63_remove() unregisters them while the interrupt is still held by devres, which frees it only after remove returns. An interrupt in this window is a use-after-free.
Mask the ACP interrupt sources and call devm_free_irq() before the first child device is unregistered. The masking goes through the new acp_hw_ops->disable_interrupts callback, keeping the remove path platform-agnostic. The interrupt line is shared, and acp_hw_deinit() clears the sources only after the children are gone, which would leave the line raised with no handler left to ack it. The window predates the tagged refactor, which only reshaped the dereferences.
devm_free_irq() waits for in-flight handlers, but not for work the hardirq has already queued: acp63_irq_handler() schedules amd_sdw_irq_thread on the SoundWire manager. Draining that work in the manager's remove path is a soundwire-side change and follows separately.
This issue was found by an in-house static analysis tool.
--- sound/soc/amd/ps/acp63.h | 8 ++++++++ sound/soc/amd/ps/pci-ps.c | 2 ++ sound/soc/amd/ps/ps-common.c | 2 ++ 3 files changed, 12 insertions(+)
sound/soc/amd/ps/acp63.h +8 -0
@@ -294,6 +294,7 @@ struct acp63_dev_data;* struct acp_hw_ops - ACP PCI driver platform specific ops * @acp_init: ACP initialization * @acp_deinit: ACP de-initialization +* @disable_interrupts: disable ACP interrupt sources * @acp_get_config: function to read the acp pin configuration * @acp_sdw_dma_irq_thread: ACP SoundWire DMA interrupt thread * acp_suspend: ACP system level suspend callback
@@ -304,6 +305,7 @@ struct acp63_dev_data;struct acp_hw_ops {int (*acp_init)(void __iomem *acp_base,struct device *dev);int (*acp_deinit)(void __iomem *acp_base,struct device *dev); +void (*disable_interrupts)(void __iomem *acp_base);void (*acp_get_config)(struct pci_dev *pci,struct acp63_dev_data *acp_data);void (*acp_sdw_dma_irq_thread)(struct acp63_dev_data *acp_data);int (*acp_suspend)(struct device *dev);
@@ -395,6 +397,12 @@ static inline int acp_hw_deinit(struct areturn -EOPNOTSUPP ; } +static inline void acp_hw_disable_interrupts (struct acp63_dev_data *adata) +{ +if (adata && adata->hw_ops && adata->hw_ops->disable_interrupts) +ACP_HW_OPS (adata, disable_interrupts)(adata->acp63_base); +} +static inline void acp_hw_get_config (struct pci_dev *pci,struct acp63_dev_data *adata) {if (adata && adata->hw_ops && adata->hw_ops->acp_get_config)
sound/soc/amd/ps/pci-ps.c +2 -0
@@ -728,6 +728,8 @@ static void snd_acp63_remove(struct pci_int ret; adata =pci_get_drvdata (pci); +acp_hw_disable_interrupts (adata); +devm_free_irq (&pci->dev, pci->irq, adata);if (adata->sdw) {amd_sdw_exit (adata);platform_device_unregister (adata->sdw_dma_dev);
sound/soc/amd/ps/ps-common.c +2 -0
@@ -248,6 +248,7 @@ void acp63_hw_init_ops(struct acp_hw_ops { hw_ops->acp_init = acp63_init; hw_ops->acp_deinit = acp63_deinit; + hw_ops->disable_interrupts = acp63_disable_interrupts; hw_ops->acp_get_config = acp63_get_config; hw_ops->acp_sdw_dma_irq_thread = acp63_sdw_dma_irq_thread; hw_ops->acp_suspend = snd_acp63_suspend;
@@ -484,6 +485,7 @@ void acp70_hw_init_ops(struct acp_hw_ops { hw_ops->acp_init = acp70_init; hw_ops->acp_deinit = acp70_deinit; + hw_ops->disable_interrupts = acp70_disable_interrupts; hw_ops->acp_get_config = acp70_get_config; hw_ops->acp_sdw_dma_irq_thread = acp70_sdw_dma_irq_thread; hw_ops->acp_suspend = snd_acp70_suspend;
Greg Kroah-Hartman
maintainerPATCH 709/1005 Bluetooth: hci_vhci: Pin module for debugfs file operations
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bui Viet Dung <[email protected]>
commit 645ee6b176c958579cff1c783413d5cff65c8197 upstream.
An open debugfs file retains its file_operations pointer in the debugfs proxy state. However, force_suspend_fops, force_wakeup_fops, aosp_capable_fops, and force_devcoredump_fops have no .owner set to THIS_MODULE. As a result, full_proxy_open_regular() calls fops_get() which succeeds without taking a reference to the hci_vhci module.
When userspace opens any of these debugfs files and later closes the /dev/vhci file descriptor (triggering vhci_release() and debugfs file removal), the open debugfs file descriptor remains valid in userspace. Because the module refcount was not incremented, the hci_vhci module can be unloaded via delete_module (rmmod hci_vhci).
When the userspace process subsequently closes the debugfs file descriptor, full_proxy_release() accesses the already unmapped file_operations structure, resulting in a kernel page fault / oops:
BUG: unable to handle page fault for address: fffffbfff846f18b #PF: supervisor read access in kernel mode #PF: error_code(0x0000) - not-present page Oops: Oops: 0000 [#1] SMP KASAN NOPTI RIP: 0010:full_proxy_release+0x8e/0x140 Call Trace: <TASK> __fput+0x39f/0xa60 fput_close_sync+0xff/0x200 __x64_sys_close+0x8c/0xf0 do_syscall_64+0xc3/0x590 entry_SYSCALL_64_after_hwframe+0x76/0x7e </TASK> Modules linked in: ... [last unloaded: hci_vhci(E)]
The issue was discovered via manual code audit of drivers/bluetooth/hci_vhci.c and verified on a Linux 7.3-rc6 test VM with CONFIG_BT_VHCI=m by keeping a debugfs file open across controller teardown and module unload.
Set .owner = THIS_MODULE on all four file_operations structures so that debugfs pins the module until all file descriptors are closed.
--- drivers/bluetooth/hci_vhci.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/bluetooth/hci_vhci.c +4 -0
@@ -155,6 +155,7 @@ static ssize_t force_suspend_write(struc }static const struct file_operations force_suspend_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = force_suspend_read, .write = force_suspend_write,
@@ -194,6 +195,7 @@ static ssize_t force_wakeup_write(struct }static const struct file_operations force_wakeup_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = force_wakeup_read, .write = force_wakeup_write,
@@ -263,6 +265,7 @@ static ssize_t aosp_capable_write(struct }static const struct file_operations aosp_capable_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = aosp_capable_read, .write = aosp_capable_write,
@@ -386,6 +389,7 @@ static ssize_t force_devcd_write(struct }static const struct file_operations force_devcoredump_fops = { + .owner =THIS_MODULE , .open = simple_open, .write = force_devcd_write, };
Greg Kroah-Hartman
maintainerPATCH 710/1005 drm/panthor: Fix TOCTOU race between GROUP_REGISTERED check and erase
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Osama Abdelkader <[email protected]>
commit 7764289d76a38c3a2f9b093bf17e193ab54acd70 upstream.
panthor_group_destroy() checks the GROUP_REGISTERED mark and then calls xa_erase() without holding the xarray lock across both. If the handle is destroyed by another thread in between, and a concurrent GROUP_CREATE reuses the freed ID, the first destroy erases and releases the new, still-initializing group, leading to a use-after-free in panthor_group_create().
Do the mark check and erase atomically under xa_lock().
--- drivers/gpu/drm/panthor/panthor_sched.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/gpu/drm/panthor/panthor_sched.c +10 -4
@@ -3664,12 +3664,18 @@ int panthor_group_destroy(struct panthorstruct panthor_group_pool *gpool = pfile->groups;struct panthor_device *ptdev = pfile->ptdev;struct panthor_scheduler *sched = ptdev->scheduler; -struct panthor_group *group; +struct panthor_group *group =NULL ; -if (!xa_get_mark (&gpool->xa, group_handle,GROUP_REGISTERED )) -return -EINVAL ; +/* +* Check the mark and erase the entry atomically, so a concurrent +* destroy + create can't make us erase a group that's still being +* initialized and happens to reuse the same handle. +*/ +xa_lock (&gpool->xa); +if (xa_get_mark (&gpool->xa, group_handle,GROUP_REGISTERED )) + group =__xa_erase (&gpool->xa, group_handle); +xa_unlock (&gpool->xa); - group =xa_erase (&gpool->xa, group_handle);if (!group)return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 711/1005 fbdev: atmel_lcdfb: Prevent FIFO work after removal
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yibo Tan <[email protected]>
commit 20b3b97cf89cb381bf07516090d99399cc9b91fd upstream.
The LCD controller IRQ schedules sinfo->task to recover from a FIFO underflow. Probe currently requests the IRQ before initializing the work, so an early interrupt can schedule an uninitialized work item.
The probe error path and remove path cancel the work before freeing the IRQ. A FIFO-underflow interrupt can schedule the work again after that cancellation. framebuffer_release() may then free sinfo while the work is still pending.
KASAN reported a use-after-free in atmel_lcdfb_task() when an underflow interrupt occurred during removal. With the IRQ freed before the work was cancelled, the same test completed without a kernel diagnostic.
Initialize the work before requesting the IRQ. In both cleanup paths, free the IRQ before cancelling the work so that it cannot be scheduled again after cancellation.
--- drivers/video/fbdev/atmel_lcdfb.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +5 -6
@@ -1148,6 +1148,9 @@ static int atmel_lcdfb_probe(struct plat/* Initialize PWM for contrast or backlight ("off") */ init_contrast (sinfo); +/* Some LCDC recovery operations require process context. */ +INIT_WORK (&sinfo->task, atmel_lcdfb_task); +/* interrupt */ ret =request_irq (sinfo->irq_base, atmel_lcdfb_interrupt,0 , pdev->name, info);if (ret) {
@@ -1155,10 +1158,6 @@ static int atmel_lcdfb_probe(struct plat goto unmap_mmio; } -/* Some operations on the LCDC might sleep and -* require a preemptible task context */ -INIT_WORK (&sinfo->task, atmel_lcdfb_task); - ret =atmel_lcdfb_init_fbinfo (sinfo);if (ret <0 ) {dev_err (dev,"init fbinfo failed: %d\n" , ret);
@@ -1194,8 +1193,8 @@ reset_drvdata:dev_set_drvdata (dev,NULL );fb_dealloc_cmap (&info->cmap); unregister_irqs: -cancel_work_sync (&sinfo->task);free_irq (sinfo->irq_base, info); +cancel_work_sync (&sinfo->task); unmap_mmio:exit_backlight (sinfo);iounmap (sinfo->mmio);
@@ -1232,6 +1231,7 @@ static void atmel_lcdfb_remove(struct plreturn ; sinfo = info->par; +free_irq (sinfo->irq_base, info);cancel_work_sync (&sinfo->task);exit_backlight (sinfo);atmel_lcdfb_power_control (sinfo,0 );
@@ -1240,7 +1240,6 @@ static void atmel_lcdfb_remove(struct plclk_put (sinfo->lcdc_clk);clk_put (sinfo->bus_clk);fb_dealloc_cmap (&info->cmap); -free_irq (sinfo->irq_base, info);iounmap (sinfo->mmio);release_mem_region (info->fix.mmio_start, info->fix.mmio_len);if (platform_get_resource (pdev,IORESOURCE_MEM ,1 )) {
Greg Kroah-Hartman
maintainerPATCH 712/1005 fbdev: udlfb: dont rebuild the mode list while the framebuffer is in use
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
commit ac9cfa552102b8e80e88c2872e80dc9cb5f07dda upstream.
dlfb_setup_modes() frees info->modelist with fb_destroy_modelist() and rebuilds it, but fbcon holds raw pointers into that list in fb_display[i].mode and nothing un-publishes them the way do_unregister_framebuffer() and store_modes() do with fbcon_delete_modelist(). The function does refuse to install a new mode while the framebuffer has users (dlfb->fb_count != 0), but only after the list is already destroyed. Reached from the 0666 "edid" sysfs attribute, an unprivileged write to /sys/class/graphics/fb0/edid therefore fails with -EINVAL and still leaves every fb_display[i].mode dangling; the next console switch reads the freed fb_videomode in fb_videomode_to_var().
Test fb_count before touching the list. fbcon takes a reference through fbcon_open(), so that condition covers exactly the states in which fb_display[] points into the list, and the errno returned to userspace is unchanged.
BUG: KASAN: slab-use-after-free in fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) Read of size 4 at addr ffff8880107b449c by task kworker/1:1/47 Workqueue: events console_callback Call Trace: fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) display_to_var (drivers/video/fbdev/core/fbcon.c:998) fbcon_switch (drivers/video/fbdev/core/fbcon.c:2182) redraw_screen (drivers/tty/vt/vt.c:994) complete_change_console (drivers/tty/vt/vt_ioctl.c:1141) console_callback (drivers/tty/vt/vt.c:3358) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) ... The buggy address is located 28 bytes inside of freed 96-byte region [ffff8880107b4480, ffff8880107b44e0)
--- drivers/video/fbdev/udlfb.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/video/fbdev/udlfb.c +5 -0
@@ -1293,6 +1293,11 @@ static int dlfb_setup_modes(struct dlfb_ goto error; } +if (dlfb->fb_count) { + result = -EINVAL ; + goto error; + } +fb_destroy_modelist (&info->modelist);memset (&info->monspecs,0 ,sizeof (info->monspecs));
Greg Kroah-Hartman
maintainerPATCH 713/1005 fs/proc/task_mmu: pin mm_users in do_pagemap_scan()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ngoc Quy <[email protected]>
commit 4fb975471717c953f912776bb60301add1ffae11 upstream.
The PAGEMAP_SCAN ioctl takes mmap_read_lock() on an mm obtained from /proc/<pid>/pagemap without holding a reference to mm_users.
proc_mem_open() deliberately grabs only mm_count, so a consumer that touches the address space has to call mmget_not_zero() first. Every other consumer in this file does -- m_start(), do_procmap_query(), show_smaps_rollup() and pagemap_read() -- but do_pagemap_scan() does not.
Without that reference the target can reach exit_mmap() concurrently, and exit_mmap() calls unmap_vmas() while holding mmap_lock only for reading, which does not exclude the scanner. For ordinary VMAs this is harmless, as free_pgtables() and remove_vma() run afterwards under mmap_write_lock. A shared hugetlb VMA is different: __hugetlb_zap_end() frees the VMA's hugetlb_vma_lock inside the read-locked phase.
walk_hugetlb_range() can therefore load vma->vm_private_data, have the lock freed underneath it, and then down_read() a freed rw_semaphore. The load happens before the freeing side clears the pointer, so this is a use-after-free and not a NULL dereference. Any unprivileged user can reach it with no huge pages configured, as hugetlb_reserve_pages() allocates the lock before the VM_NORESERVE early return.
Pin mm_users across the scan, the way the other consumers do. mmput() from the exiting task can then no longer reach exit_mmap() while a walk is in progress.
--- fs/proc/task_mmu.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
fs/proc/task_mmu.c +7 -2
@@ -3098,15 +3098,18 @@ static long do_pagemap_scan(struct mm_stsize_t n_ranges_out =0 ;int ret; +if (!mmget_not_zero (mm)) +return -ESRCH ; + ret =pagemap_scan_get_args (&p.arg, uarg);if (ret) -return ret; + goto out_mmput; p.masks_of_interest = p.arg.category_mask | p.arg.category_anyof_mask | p.arg.return_mask; ret =pagemap_scan_init_bounce_buffer (&p);if (ret) -return ret; + goto out_mmput;for (walk_start = p.arg.start; walk_start < p.arg.end; walk_start = p.arg.walk_end) {
@@ -3161,6 +3164,8 @@ static long do_pagemap_scan(struct mm_st ret = -EFAULT ;kfree (p.vec_buf); +out_mmput: +mmput (mm);return ret; }
Greg Kroah-Hartman
maintainerPATCH 714/1005 genirq: Defer kfree(irqaction) until irq_thread_dtor() finishes
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Patel <[email protected]>
commit d04adff6860587e843948b0c31174f8ae11b8dfe upstream.
When an interrupt thread exits abnormally via do_exit() (e.g. the interrupt handler oopses) without returning from irq_thread(), a concurrent call to free_irq() could free the irqaction before the irq_thread_dtor() exit task work runs.
irq thread (oopsed) free_irq()
------------------- ----------
do_exit()
exit_mm()
complete_vfork_done() -------> kthread_stop() returns
exit_files() ... kfree(action)
exit_task_work()
irq_thread_dtor()
action->... <- use-after-freeTrack the pending exit work with the IRQTF_EXIT_WORK thread flag, and have __free_irq() wait for the bit to clear before kfree().
irq_thread_dtor() only runs on irq_thread abnormal exit. If that dtor also faults, free_irq() will hang indefinitely, but double IRQ thread faults require a reboot anyways.
[ tglx: Add missing include ]
--- kernel/irq/internals.h | 2 ++ kernel/irq/manage.c | 26 ++++++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-)
kernel/irq/internals.h +2 -0
@@ -31,6 +31,7 @@ extern struct irqaction chained_action;* IRQTF_AFFINITY - irq thread is requested to adjust affinity * IRQTF_FORCED_THREAD - irq action is force threaded * IRQTF_READY - signals that irq thread is ready +* IRQTF_EXIT_WORK - irq thread exit task_work is pending */ enum {IRQTF_RUNTHREAD ,
@@ -38,6 +39,7 @@ enum {IRQTF_AFFINITY ,IRQTF_FORCED_THREAD ,IRQTF_READY , + IRQTF_EXIT_WORK, };/*
kernel/irq/manage.c +20 -6
@@ -21,6 +21,7 @@#include <linux/sched/isolation.h> #include <uapi/linux/sched/types.h> #include <linux/task_work.h> +#include <linux/wait_bit.h> #include "internals.h"
@@ -1173,17 +1174,14 @@ void wake_threads_waitq(struct irq_descwake_up (&desc->wait_for_threads); } -static void irq_thread_dtor (struct callback_head *unused) +static void __irq_thread_dtor (struct irqaction *action) {struct task_struct *tsk = current;struct irq_desc *desc; -struct irqaction *action;if (WARN_ON_ONCE (!(current->flags &PF_EXITING )))return ; - action =kthread_data (tsk); -pr_err ("exiting task \"%s\" (%d) is an active IRQ thread (irq %d)\n" , tsk->comm, tsk->pid, action->irq);
@@ -1200,6 +1198,14 @@ static void irq_thread_dtor(struct callbirq_finalize_oneshot (desc, action); } +static void irq_thread_dtor (struct callback_head *unused) +{ +struct irqaction *action =kthread_data (current); + +__irq_thread_dtor (action); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags); +} +static void irq_wake_secondary (struct irq_desc *desc,struct irqaction *action) {struct irqaction *secondary = action->secondary;
@@ -1257,6 +1263,7 @@ static int irq_thread(void *data)else handler_fn = irq_thread_fn; +set_bit (IRQTF_EXIT_WORK , &action->thread_flags);init_task_work (&on_exit_work, irq_thread_dtor);task_work_add (current, &on_exit_work,TWA_NONE );
@@ -1277,6 +1284,7 @@ static int irq_thread(void *data)* oneshot mask bit can be set. */ task_work_cancel_func (current, irq_thread_dtor); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags);return 0 ; }
@@ -1811,6 +1819,12 @@ out_mput:return ret; } +static void irq_stop_thread (struct irqaction *action) +{ +kthread_stop_put (action->thread); +wait_on_bit (&action->thread_flags,IRQTF_EXIT_WORK ,TASK_UNINTERRUPTIBLE ); +} +/* * Internal function to unregister an irqaction - used to free * regular and special interrupts that are part of the architecture.
@@ -1915,9 +1929,9 @@ static struct irqaction *__free_irq(stru* the same bit to a newly requested action. */ if (action->thread) { -kthread_stop_put (action->thread); +irq_stop_thread (action);if (action->secondary && action->secondary->thread) -kthread_stop_put (action->secondary->thread); +irq_stop_thread (action->secondary); }/* Last action releases resources */
Greg Kroah-Hartman
maintainerPATCH 715/1005 genirq: Move interrupt thread exit_work object to irqaction
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Patel <[email protected]>
commit 89a9e003a2ef73f67dff03dfd59e0a5474b56b0b upstream.
irq_thread() registers irq_thread_dtor() as exit task_work using a stack-allocated callback_head. On normal interrupt thread exit, this work gets cancelled and never runs.
On x86, an abnormal interrupt thread exit (e.g. handler oops) discards the stack, including the callback_head, while that callback_head is still pending. By the time exit_task_work() runs, the stack memory formerly backing callback_head is already clobbered.
irq_thread() <-- on_exit_work allocated
** IRQ handler faults **
oops_end()
rewind_stack_and_make_dead() <-- on_exit_work freed
make_task_dead()
do_exit(SIGSEGV)
...
exit_shm() <-- on_exit_work clobbered
...
exit_task_work() <-- stack use-after-free
exit_shm()+0x30 <-- wild jump to return addrThus, a benign threaded IRQ oops (e.g. a NULL pointer deref) is turned into a wild jump. This is caught by kernel IBT:
** first fault **
Oops: general protection fault, kernel NULL pointer dereference 0x3c0: 0000 [#1] SMP NOPTI ... ** second fault ** Missing ENDBR: exit_shm+0x30/0x1c0 kernel BUG at arch/x86/kernel/cet.c:133! ... ? task_work_run+0x5c/0x90 ? do_exit+0x209/0x460 ? rewind_stack_and_make_dead+0x16/0x20 ... note: irq/165-AudioDS[1427] exited with irqs disabled Fixing recursive fault but reboot is needed!
Fix this by storing the callback_head in struct irqaction. The irqaction is only freed once irq_thread_dtor() finishes.
--- include/linux/interrupt.h | 2 ++ kernel/irq/manage.c | 9 ++++----- 2 files changed, 6 insertions(+), 5 deletions(-)
include/linux/interrupt.h +2 -0
@@ -118,6 +118,7 @@ typedef irqreturn_t (*irq_handler_t)(int* @thread_flags: flags related to @thread * @thread_mask: bitmask for keeping track of @thread activity * @dir: pointer to the proc/irq/NN/name entry +* @thread_dtor: task_work for @thread irregular exit cleanup */ struct irqaction {irq_handler_t handler;
@@ -133,6 +134,7 @@ struct irqaction {unsigned long thread_mask;const char *name;struct proc_dir_entry *dir; +struct callback_head thread_dtor; }____cacheline_internodealigned_in_smp ;extern irqreturn_t no_action (int cpl,void *dev_id);
kernel/irq/manage.c +4 -5
@@ -1198,9 +1198,9 @@ static void __irq_thread_dtor(struct irqirq_finalize_oneshot (desc, action); } -static void irq_thread_dtor (struct callback_head *unused) +static void irq_thread_dtor (struct callback_head *work) { -struct irqaction *action =kthread_data (current); + struct irqaction *action = container_of(work, struct irqaction, thread_dtor);__irq_thread_dtor (action);clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags);
@@ -1247,7 +1247,6 @@ static void wake_up_and_wait_for_irq_thr*/ static int irq_thread (void *data) { -struct callback_head on_exit_work;struct irqaction *action = data;struct irq_desc *desc =irq_to_desc (action->irq); irqreturn_t (*handler_fn)(struct irq_desc *desc,
@@ -1264,8 +1263,8 @@ static int irq_thread(void *data) handler_fn = irq_thread_fn;set_bit (IRQTF_EXIT_WORK , &action->thread_flags); -init_task_work (&on_exit_work, irq_thread_dtor); -task_work_add (current, &on_exit_work,TWA_NONE ); +init_task_work (&action->thread_dtor, irq_thread_dtor); +task_work_add (current, &action->thread_dtor,TWA_NONE );while (!irq_wait_for_interrupt (desc, action)) {irqreturn_t action_ret;
Greg Kroah-Hartman
maintainerPATCH 716/1005 HID: hiddev: keep state alive through disconnect unlock
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yousef Alhouseen <[email protected]>
commit 03f449b5de36a25fc5eba7dabf2b4494389bdb91 upstream.
mutex_unlock() clears the mutex owner before taking its wait lock. A thread spinning in the final hiddev file release can acquire existancelock after hiddev_disconnect() clears the owner, then free hiddev before the disconnecting thread reaches the mutex wait lock. This causes a use-after-free in the mutex slow unlock path.
Give the connection and each open file an explicit reference. Drop each reference only after its existancelock critical section has completed, so neither unlock path can free the mutex while the other is still using it.
--- drivers/hid/usbhid/hiddev.c | 37 +++++++++++++++++++------------------ include/linux/hiddev.h | 2 ++ 2 files changed, 21 insertions(+), 18 deletions(-)
drivers/hid/usbhid/hiddev.c +19 -18
@@ -46,6 +46,12 @@ struct hiddev_list {struct mutex thread_lock; }; +static void hiddev_put (struct hiddev *hiddev) +{ +if (refcount_dec_and_test (&hiddev->refcount)) +kfree (hiddev); +} +/* * Find a report, given the report's type and ID. The ID can be specified * indirectly by REPORT_ID_FIRST (which returns the first report of the given
@@ -216,26 +222,21 @@ static int hiddev_fasync(int fd, structstatic int hiddev_release (struct inode * inode,struct file * file) {struct hiddev_list *list = file->private_data; +struct hiddev *hiddev = list->hiddev;unsigned long flags; -spin_lock_irqsave (&list->hiddev->list_lock, flags); +spin_lock_irqsave (&hiddev->list_lock, flags);list_del (&list->node); -spin_unlock_irqrestore (&list->hiddev->list_lock, flags); +spin_unlock_irqrestore (&hiddev->list_lock, flags); -mutex_lock (&list->hiddev->existancelock); -if (!--list->hiddev->open) { -if (list->hiddev->exist) { -hid_hw_close (list->hiddev->hid); -hid_hw_power (list->hiddev->hid,PM_HINT_NORMAL ); - }else { -mutex_unlock (&list->hiddev->existancelock); -kfree (list->hiddev); -vfree (list); -return 0 ; - } +mutex_lock (&hiddev->existancelock); +if (!--hiddev->open && hiddev->exist) { +hid_hw_close (hiddev->hid); +hid_hw_power (hiddev->hid,PM_HINT_NORMAL ); } -mutex_unlock (&list->hiddev->existancelock); +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev);vfree (list);return 0 ;
@@ -270,6 +271,7 @@ static int __hiddev_open(struct hiddev *spin_unlock_irq (&hiddev->list_lock); file->private_data = list; +refcount_inc (&hiddev->refcount);return 0 ;
@@ -897,6 +899,7 @@ int hiddev_connect(struct hid_device *hiINIT_LIST_HEAD (&hiddev->list);spin_lock_init (&hiddev->list_lock);mutex_init (&hiddev->existancelock); +refcount_set (&hiddev->refcount,1 ); hid->hiddev = hiddev; hiddev->hid = hid; hiddev->exist =1 ;
@@ -937,9 +940,7 @@ void hiddev_disconnect(struct hid_deviceif (hiddev->open) {hid_hw_close (hiddev->hid);wake_up_interruptible (&hiddev->wait); -mutex_unlock (&hiddev->existancelock); - }else { -mutex_unlock (&hiddev->existancelock); -kfree (hiddev); } +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev); }
include/linux/hiddev.h +2 -0
@@ -13,6 +13,7 @@#ifndef _HIDDEV_H#define _HIDDEV_H +#include <linux/refcount.h> #include <uapi/linux/hiddev.h>
@@ -24,6 +25,7 @@ struct hiddev {int minor;int exist;int open; +refcount_t refcount;struct mutex existancelock;wait_queue_head_t wait;struct hid_device *hid;
Greg Kroah-Hartman
maintainerPATCH 717/1005 io_uring/io-wq: save worker type before dropping its reference
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 37e425460b7c41687e51e3254b1eb1d799da9614 upstream.
io_wq_cancel_tw_create() inspects cb->func after calling io_worker_cancel_cb(). For an existing worker, that call can drop the last worker reference and wake io_worker_exit(). If the canceling task is preempted, the worker can be unlinked and freed by kfree_rcu() before the callback function is inspected. KASAN reports a slab-use-after-free read in this path.
Save whether the callback belongs to an unpublished continuation worker while its reference is still held, then use the saved result for the conditional free. This preserves the existing accounting and frees only the worker allocated for the canceled continuation.
--- io_uring/io-wq.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
io_uring/io-wq.c +5 -3
@@ -1420,14 +1420,16 @@ static void io_wq_cancel_tw_create(strucwhile ((cb =task_work_cancel_match (wq->task, io_task_work_match, wq)) !=NULL ) {struct io_worker *worker; +bool free_worker; worker = container_of(cb, struct io_worker, create_work); -io_worker_cancel_cb (worker);/* * Only the worker continuation helper has worker allocated and -* hence needs freeing. +* hence needs freeing. Save this before dropping its reference. */ -if (cb->func == create_worker_cont) + free_worker = cb->func == create_worker_cont; +io_worker_cancel_cb (worker); +if (free_worker)kfree (worker); } }
Greg Kroah-Hartman
maintainerPATCH 718/1005 iomap: dont resubmit an ioend after ->writeback_submit() failed
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Parri <[email protected]>
commit 3f517370076f1fedaa38cd8c78ceb73616b79336 upstream.
iomap_add_to_ioend() submits the pending ioend through ->writeback_submit() before allocating a new one for the current range. When the submission fails the helper completes the ioend with an error, but iomap_add_to_ioend() returns the error without clearing wpc->wb_ctx. iomap_writepages() then submits whatever wpc->wb_ctx points to, so the already completed ioend is submitted a second time.
For XFS the second bio_endio() lands in xfs_end_bio(), which list_add_tail()s the already linked ioend into ip->i_ioend_list. This corrupts the list and leaves a use-after-free/double-free window against the ioend completion worker. Reproduced with a fault-injected ->writeback_submit() failure on a reflinked XFS file with several CoW writeback ranges in flight: the unfixed kernel hits repeated "list_add double add" warnings from __list_add_valid_or_report(), the fixed kernel fails writeback cleanly.
Clear wpc->wb_ctx when ->writeback_submit() fails. The old iomap_submit_ioend() cleared the context unconditionally; that clear was lost when submission moved to iomap_ioend_writeback_submit(). The final ->writeback_submit() call in iomap_writepages() needs no equivalent fix:
it is the last thing the function does before returning, and every caller allocates its iomap_writepage_ctx on the stack for a single call, so wpc->wb_ctx is never read again afterwards.
--- fs/iomap/ioend.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
fs/iomap/ioend.c +9 -1
@@ -187,8 +187,16 @@ ssize_t iomap_add_to_ioend(struct iomap_ new_ioend:if (ioend) { error = wpc->ops->writeback_submit (wpc,0 ); -if (error) +if (error) { +/* +* ->writeback_submit() completed the ioend +* with an error, so drop the stale context; +* iomap_writepages() would otherwise submit +* it a second time. +*/ + wpc->wb_ctx =NULL ;return error; + } } wpc->wb_ctx = ioend =iomap_alloc_ioend (wpc, pos, ioend_flags); }
Greg Kroah-Hartman
maintainerPATCH 719/1005 iommu/arm-smmu-v3: Disable the impl before disabling the SMMU on shutdown
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nicolin Chen <[email protected]>
commit ab0dbf411aced59c04ce86fd8443faf13bdc9936 upstream.
arm_smmu_device_shutdown() only calls arm_smmu_device_disable(), and never the impl_ops->device_disable() hook. On tegra241-cmdqv, that hook quiesces every VINTF through tegra241_vintf_hw_deinit(), which issues a CMD_SYNC on the shared CMDQ while it is still enabled.
arm_smmu_disable_action() already runs this hook before disabling the SMMU, to cover an unbind or a probe failure, and no devres release ever follows a reboot or a kexec to run it again. Have arm_smmu_device_shutdown() call it directly, instead of reimplementing part of what it already does.
--- drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -1
@@ -4972,7 +4972,7 @@ static void arm_smmu_device_shutdown(str {struct arm_smmu_device *smmu =platform_get_drvdata (pdev); -arm_smmu_device_disable (smmu); +arm_smmu_disable_action (smmu); }static const struct of_device_id arm_smmu_of_match[] = {
Greg Kroah-Hartman
maintainerPATCH 720/1005 KVM: PPC: Book3S HV: Add SRCU protection for virtual-mode HPT hcalls
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 61a39797bb136243c48b46e2586d8a9e2cea6a89 upstream.
The virtual-mode HPT hcall handlers (H_ENTER, H_REMOVE, H_BULK_REMOVE, H_CLEAR_REF, H_CLEAR_MOD) call into book3s_hv_rm_mmu.c, which accesses memslots via kvm_memslots_raw(). kvm_memslots_raw() uses rcu_dereference_raw_check() to bypass SRCU lockdep annotation checking. This is safe in real mode because the entire guest entry/exit is wrapped in srcu_read_lock/unlock inside kvmppc_run_core() and kvmhv_run_single_vcpu().
However, since commit 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults"), these same handlers are also executed in virtual mode via kvmppc_pseries_do_hcall(), which runs after SRCU has already been released on guest exit.
A concurrent KVM_SET_USER_MEMORY_REGION deletion or move can therefore call synchronize_srcu_expedited() — which does not wait for this thread — and then kfree(slot) and vfree(slot->arch.rmap) while the hcall handler still holds a raw pointer to the memslot. lock_rmap() then writes to freed vmalloc memory, leading to use-after-free and memory corruption. Because kvm_memslots_raw() suppresses lockdep checks, this race is entirely silent.
Fix this by factoring out the 7 HPT hcall handlers (H_REMOVE, H_ENTER, H_READ, H_CLEAR_MOD, H_CLEAR_REF, H_PROTECT, H_BULK_REMOVE) into a helper function, kvmppc_pseries_do_hpt_hcall(), and wrapping its call site in srcu_read_lock(&kvm->srcu) / srcu_read_unlock(&kvm->srcu, idx). Targeting only the HPT hcalls avoids wrapping non-HPT hcalls that sleep (such as H_CONFER, H_REGISTER_VPA, H_PAGE_INIT) or handlers that already acquire SRCU internally (such as H_RTAS).
--- arch/powerpc/kvm/book3s_hv.c | 70 +++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 35 deletions(-)
arch/powerpc/kvm/book3s_hv.c +35 -35
@@ -1155,6 +1155,38 @@ static long kvmppc_h_rpt_invalidate(strureturn H_SUCCESS ; } +static long kvmppc_pseries_do_hpt_hcall (struct kvm_vcpu *vcpu,unsigned long req) +{ +switch (req) { +case H_REMOVE : +return kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_ENTER : +return kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 ), +kvmppc_get_gpr (vcpu,7 )); +case H_READ : +return kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_MOD : +return kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_CLEAR_REF : +return kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 )); +case H_PROTECT : +return kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), +kvmppc_get_gpr (vcpu,5 ), +kvmppc_get_gpr (vcpu,6 )); +case H_BULK_REMOVE : +return kvmppc_h_bulk_remove (vcpu); + } + +return H_FUNCTION ; +} +int kvmppc_pseries_do_hcall (struct kvm_vcpu *vcpu) {struct kvm *kvm = vcpu->kvm;
@@ -1170,47 +1202,15 @@ int kvmppc_pseries_do_hcall(struct kvm_vswitch (req) {case H_REMOVE : - ret =kvmppc_h_remove (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_ENTER : - ret =kvmppc_h_enter (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 ), -kvmppc_get_gpr (vcpu,7 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_READ : - ret =kvmppc_h_read (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_MOD : - ret =kvmppc_h_clear_mod (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_CLEAR_REF : - ret =kvmppc_h_clear_ref (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_PROTECT : - ret =kvmppc_h_protect (vcpu,kvmppc_get_gpr (vcpu,4 ), -kvmppc_get_gpr (vcpu,5 ), -kvmppc_get_gpr (vcpu,6 )); -if (ret ==H_TOO_HARD ) -return RESUME_HOST ; -break ;case H_BULK_REMOVE : - ret =kvmppc_h_bulk_remove (vcpu); + idx =srcu_read_lock (&kvm->srcu); + ret =kvmppc_pseries_do_hpt_hcall (vcpu, req); +srcu_read_unlock (&kvm->srcu, idx);if (ret ==H_TOO_HARD )return RESUME_HOST ;break ;
Greg Kroah-Hartman
maintainerPATCH 721/1005 media: cx23885: unregister DVB bus when SP2 CI setup fails
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 22f552ff726a82a086be4ef02ce5099a0e8624b6 upstream.
The DVBSKY S950C, DVBSKY T980C and TechnoTrend CT2-4500 CI paths register the DVB bus before attaching their SP2 CI client. If that client cannot be created, bound, or pinned, the current error path removes the I2C frontend components and only deallocates the frontend list, leaving the registered DVB adapter behind. Removing an I2C demod before unregistering the DVB bus can also expose the use-after-free ordering fixed for the normal remove path.
Unregister the DVB bus immediately when SP2 CI setup fails, before the existing I2C client cleanup. The bus helper empties the frontend list, so the later frontend deallocation has nothing left to release. Keep failures from vb2_dvb_register_bus() on the existing cleanup path. Also release an unbound SP2 client and propagate the actual I2C creation or CI registration error.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/media/pci/cx23885/cx23885-dvb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/media/pci/cx23885/cx23885-dvb.c +10 -4
@@ -1158,8 +1158,12 @@ static int dvb_register_ci_mac(struct cx info.platform_data = &sp2_config;request_module (info.type); client_ci =i2c_new_client_device (&i2c_bus->i2c_adap, &info); -if (!i2c_client_has_driver (client_ci)) +if (IS_ERR (client_ci)) +return PTR_ERR (client_ci); +if (!client_ci->dev.driver) { +i2c_unregister_device (client_ci);return -ENODEV ; + }if (!try_module_get (client_ci->dev.driver->owner)) {i2c_unregister_device (client_ci);return -ENODEV ;
@@ -1202,7 +1206,7 @@ static int dvb_register(struct cx23885_tint (*p_set_voltage)(struct dvb_frontend *fe,enum fe_sec_voltage voltage) =NULL ;int mfe_shared =0 ;/* bus not shared by default */ -int ret; +int ret = -EINVAL ;/* Get the first frontend */ fe0 =vb2_dvb_get_frontend (&port->frontends,1 );
@@ -2584,8 +2588,10 @@ static int dvb_register(struct cx23885_t goto frontend_detach; ret =dvb_register_ci_mac (port); -if (ret) +if (ret) { +vb2_dvb_unregister_bus (&port->frontends); goto frontend_detach; + }return 0 ;
@@ -2616,7 +2622,7 @@ frontend_detach: port->gate_ctrl =NULL ;vb2_dvb_dealloc_frontends (&port->frontends); -return -EINVAL ; +return ret; }int cx23885_dvb_register (struct cx23885_tsport *port)
Greg Kroah-Hartman
maintainerPATCH 722/1005 media: gspca: use vb2_video_unregister_device() on disconnect
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shuangpeng Bai <[email protected]>
commit 3dbbbc3cafa2de377d9b97af4e35b8b6b5282047 upstream.
gspca uses vb2_fop_release(), but gspca_disconnect() only unregisters the video device. If the queue owner closes the device after USB disconnect, vb2_fop_release() releases the queue and invokes gspca_stop_streaming() at that point.
gspca_stream_off() calls subdriver stop callbacks and usb_set_interface() through gspca_dev->dev. By the time the late close runs, the USB core can have freed the usb_device, resulting in a use-after-free. This was observed as a KASAN use-after-free in sd_stopN().
Use vb2_video_unregister_device() so the queue is released and streaming is stopped synchronously during disconnect, while the usb_device is still valid. Since the helper takes the queue lock, which is usb_lock, call it after dropping that lock.
--- drivers/media/usb/gspca/gspca.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/media/usb/gspca/gspca.c +1 -2
@@ -1641,9 +1641,8 @@ void gspca_disconnect(struct usb_interfa#endif v4l2_device_disconnect (&gspca_dev->v4l2_dev); -video_unregister_device (&gspca_dev->vdev); -mutex_unlock (&gspca_dev->usb_lock); +vb2_video_unregister_device (&gspca_dev->vdev);/* (this will call gspca_release() immediately or on last close) */ v4l2_device_put (&gspca_dev->v4l2_dev);
Greg Kroah-Hartman
maintainerPATCH 723/1005 media: imx-jpeg: cancel timeout worker when streaming stops
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 78fdfbf117c409273eecbfa7a528ef42358a0e38 upstream.
Each per-fd context ctx owns a delayed_work (ctx->task_timer, callback mxc_jpeg_device_run_timeout) armed via schedule_delayed_work() at the end of mxc_jpeg_device_run() to recover a stalled encode/decode job. The only existing cancellation is cancel_delayed_work() in the frame-done IRQ handler, which de-queues a pending work item but does not wait for a callback that has already started, and it only runs when a frame completes.
When the fd is closed while a job is in flight (the frame-done IRQ has not fired yet), nothing syncs the worker before mxc_jpeg_release() frees ctx with kfree() after v4l2_m2m_ctx_release(). A queued or executing mxc_jpeg_device_run_timeout() can then recover ctx through container_of(&ctx->task_timer) and dereference it (ctx->mxc_jpeg, slot_data, dev_warn) after ctx has been freed.
Cancel the worker from mxc_jpeg_stop_streaming(). The cancel cannot live in mxc_jpeg_release(): mxc_jpeg_device_run() arms the timer while holding only hw_lock, not the mxc_jpeg->lock mutex that release holds, so a cancel in release could still race a concurrent mxc_jpeg_device_run() that re-arms the timer afterwards. mxc_jpeg_stop_streaming() instead runs inside v4l2_m2m_ctx_release() -> vb2_queue_release(), i.e. after v4l2_m2m_cancel_job() has set TRANS_ABORT and waited for any in-flight job to finish (so __v4l2_m2m_try_queue() will not queue and v4l2_m2m_try_run() will not run any further job for this context, which prevents mxc_jpeg_device_run() from re-arming the timer) and before the m2m context is freed. cancel_delayed_work_sync() removes a pending work item and waits for a running callback, so the worker can no longer race with the subsequent kfree(). The cancel is placed before the buffer-release loop so a concurrently running timeout callback cannot race with it over the same buffers. If the frame-done IRQ canceled a still-pending timer, this cancel is a no-op; if the timeout callback has already started, it waits for the callback to finish. The same mxc_jpeg_stop_streaming() call is also reached from VIDIOC_STREAMOFF, which drains the worker early, although STREAMOFF itself does not free ctx -- the use-after-free arises only when the fd is later closed.
This bug was found by static analysis.
--- drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c +2 -0
@@ -1735,6 +1735,8 @@ static void mxc_jpeg_stop_streaming(strudev_dbg (ctx->mxc_jpeg->dev,"Stop streaming ctx=%p" , ctx); +cancel_delayed_work_sync (&ctx->task_timer); +/* Release all active buffers */ for (;;) {if (V4L2_TYPE_IS_OUTPUT (q->type))
Greg Kroah-Hartman
maintainerPATCH 724/1005 media: marvell: mcam: stop DMA and cancel s_bh_work before freeing DMA buffers
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 0f29f84317c1e35f6a9265277be33e60d3fc8c1c upstream.
In vmalloc mode the frame-completion IRQ queues mcam_frame_work() on cam->s_bh_work, which memcpy()s from the dma_bufs[] that mcam_free_dma_bufs() frees with dma_free_coherent(). mccic_shutdown() frees those buffers without stopping the controller, so while streaming a late frame IRQ can re-arm the work after the buffers are gone, causing a use-after-free.
Stop the controller in mccic_shutdown() when streaming is still active (gated on an open fd, which holds a runtime-PM reference, so the device is powered), cancel s_bh_work in mcam_free_dma_bufs(), and move INIT_WORK() into mccic_register() before the device can be published.
--- drivers/media/platform/marvell/mcam-core.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/media/platform/marvell/mcam-core.c +13 -1
@@ -406,6 +406,8 @@ static void mcam_free_dma_bufs(struct mc {int i; +cancel_work_sync (&cam->s_bh_work); +for (i =0 ; i < cam->nbufs; i++) {dma_free_coherent (cam->dev, cam->dma_buf_size, cam->dma_bufs[i], cam->dma_handles[i]);
@@ -1306,7 +1308,6 @@ static int mcam_setup_vb2(struct mcam_cabreak ;case B_vmalloc:#ifdef MCAM_MODE_VMALLOC -INIT_WORK (&cam->s_bh_work, mcam_frame_work); vq->ops = &mcam_vb2_ops; vq->mem_ops = &vb2_vmalloc_memops; cam->dma_setup = mcam_ctlr_dma_vmalloc;
@@ -1864,6 +1865,12 @@ int mccic_register(struct mcam_camera *c goto out; } +#ifdef MCAM_MODE_VMALLOC +/* Init before sensor bind: armed by IRQ, cancelled on probe-error paths. */ +if (cam->buffer_mode == B_vmalloc) +INIT_WORK (&cam->s_bh_work, mcam_frame_work); +#endif +mutex_init (&cam->s_mutex); cam->state =S_NOTREADY ;mcam_set_config_needed (cam,1 );
@@ -1922,10 +1929,15 @@ void mccic_shutdown(struct mcam_camera ** take it down again will wedge the machine, which is frowned * upon. */ +mutex_lock (&cam->s_mutex);if (!list_empty (&cam->vdev.fh_list)) {cam_warn (cam,"Removing a device with users!\n" ); +/* Stop so the IRQ can't re-arm s_bh_work after the buffers are freed. */ +if (cam->state ==S_STREAMING ) +mcam_ctlr_stop_dma (cam);sensor_call (cam, core, s_power,0 ); } +mutex_unlock (&cam->s_mutex);if (cam->buffer_mode == B_vmalloc)mcam_free_dma_bufs (cam);v4l2_ctrl_handler_free (&cam->ctrl_handler);
Greg Kroah-Hartman
maintainerPATCH 725/1005 media: microchip-csi2dc: fix async notifier leak on probe error path
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cong Nguyen <[email protected]>
commit c7528789244ce7329ca883170fb9315d739ae985 upstream.
csi2dc_of_parse() ends up calling csi2dc_prepare_notifier(), which registers the V4L2 async notifier with v4l2_async_nf_register(). The probe error label csi2dc_probe_cleanup_notifier is reached after csi2dc_of_parse() has already succeeded (e.g. when media entity init, csi2dc_power() or v4l2_async_register_subdev() fail), but it calls only v4l2_async_nf_cleanup() and never v4l2_async_nf_unregister().
The notifier therefore stays chained in the global notifier_list while the enclosing struct csi2dc_device is freed, leading to list corruption and a use-after-free when the list is next walked.
Unregister the notifier before cleaning it up on the error path, matching the teardown already done in csi2dc_remove().
--- drivers/media/platform/microchip/microchip-csi2dc.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/platform/microchip/microchip-csi2dc.c +1 -0
@@ -736,6 +736,7 @@ static int csi2dc_probe(struct platform_return 0 ; csi2dc_probe_cleanup_notifier: +v4l2_async_nf_unregister (&csi2dc->notifier);v4l2_async_nf_cleanup (&csi2dc->notifier); csi2dc_probe_cleanup_entity:media_entity_cleanup (&csi2dc->csi2dc_sd.entity);
Greg Kroah-Hartman
maintainerPATCH 726/1005 media: microchip-isc: take a reference on the parsed endpoints
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Balakrishnan Sambath <[email protected]>
commit f2eb2fd388bf3f1959556a326e797cacca341c86 upstream.
for_each_endpoint_of_node() drops the reference on the current node as it advances. xisc_parse_dt() and isc_parse_dt() store the node in subdev_entity->epn and release it later with of_node_put(), but never took their own reference, so the stored pointer refers to an already-released node. This underflows the refcount and can use-after-free, reachable through the camera device tree overlay.
Take a reference with of_node_get() when storing the node, and drop it in microchip_isc_subdev_cleanup() so the entities the bind loop never reaches on an early exit do not leak it.
--- drivers/media/platform/microchip/microchip-isc-base.c | 6 +++++ drivers/media/platform/microchip/microchip-sama5d2-isc.c | 17 ++++++++++----- drivers/media/platform/microchip/microchip-sama7g5-isc.c | 17 ++++++++++----- 3 files changed, 30 insertions(+), 10 deletions(-)
drivers/media/platform/microchip/microchip-isc-base.c +6 -0
@@ -1860,6 +1860,12 @@ void microchip_isc_subdev_cleanup(structlist_for_each_entry (subdev_entity, &isc->subdev_entities, list) {v4l2_async_nf_unregister (&subdev_entity->notifier);v4l2_async_nf_cleanup (&subdev_entity->notifier); +/* +* Release the endpoint reference taken while parsing. It is +* NULL for entities the bind loop already consumed, so this +* only drops the ones left over on an early exit. +*/ +of_node_put (subdev_entity->epn); }INIT_LIST_HEAD (&isc->subdev_entities);
drivers/media/platform/microchip/microchip-sama5d2-isc.c +12 -5
@@ -356,28 +356,30 @@ static int isc_parse_dt(struct device *dstruct device_node *epn;struct isc_subdev_entity *subdev_entity;unsigned int flags; +int ret;INIT_LIST_HEAD (&isc->subdev_entities);for_each_endpoint_of_node (np, epn) {struct v4l2_fwnode_endpoint v4l2_epn = { .bus_type =0 }; -int ret; ret =v4l2_fwnode_endpoint_parse (of_fwnode_handle (epn), &v4l2_epn);if (ret) { -of_node_put (epn);dev_err (dev,"Could not parse the endpoint\n" ); -return -EINVAL ; +of_node_put (epn); + ret = -EINVAL ; + goto err_cleanup; } subdev_entity =devm_kzalloc (dev,sizeof (*subdev_entity),GFP_KERNEL );if (!subdev_entity) {of_node_put (epn); -return -ENOMEM ; + ret = -ENOMEM ; + goto err_cleanup; } - subdev_entity->epn = epn; + subdev_entity->epn =of_node_get (epn); flags = v4l2_epn.bus.parallel.flags;
@@ -398,6 +400,11 @@ static int isc_parse_dt(struct device *d }return 0 ; + +err_cleanup: +list_for_each_entry (subdev_entity, &isc->subdev_entities, list) +of_node_put (subdev_entity->epn); +return ret; }static int microchip_isc_probe (struct platform_device *pdev)
drivers/media/platform/microchip/microchip-sama7g5-isc.c +12 -5
@@ -340,6 +340,7 @@ static int xisc_parse_dt(struct device *struct isc_subdev_entity *subdev_entity;unsigned int flags;bool mipi_mode; +int ret;INIT_LIST_HEAD (&isc->subdev_entities);
@@ -347,23 +348,24 @@ static int xisc_parse_dt(struct device *for_each_endpoint_of_node (np, epn) {struct v4l2_fwnode_endpoint v4l2_epn = { .bus_type =0 }; -int ret; ret =v4l2_fwnode_endpoint_parse (of_fwnode_handle (epn), &v4l2_epn);if (ret) { -of_node_put (epn);dev_err (dev,"Could not parse the endpoint\n" ); -return -EINVAL ; +of_node_put (epn); + ret = -EINVAL ; + goto err_cleanup; } subdev_entity =devm_kzalloc (dev,sizeof (*subdev_entity),GFP_KERNEL );if (!subdev_entity) {of_node_put (epn); -return -ENOMEM ; + ret = -ENOMEM ; + goto err_cleanup; } - subdev_entity->epn = epn; + subdev_entity->epn =of_node_get (epn); flags = v4l2_epn.bus.parallel.flags;
@@ -387,6 +389,11 @@ static int xisc_parse_dt(struct device * }return 0 ; + +err_cleanup: +list_for_each_entry (subdev_entity, &isc->subdev_entities, list) +of_node_put (subdev_entity->epn); +return ret; }static int microchip_xisc_probe (struct platform_device *pdev)
Greg Kroah-Hartman
maintainerPATCH 727/1005 media: redrat3: fix UAF in probe error path leaving rc device registered
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rik van Riel <[email protected]>
commit af452b9e01331b5338a1e5141624f17607239207 upstream.
redrat3 stores its device name and phys path inside the main rr3 structure, and the rc device's device_name and input_phys point into rr3. When the RC device is registered, it keeps those pointers.
KASAN: slab-use-after-free in string_nocheck lib/vsprintf.c:648 Read of size 1 at addr ffff888051fda758 by task udevd/7464 Call Trace: string_nocheck lib/vsprintf.c:648 [inline] string+0x216/0x2d0 lib/vsprintf.c:730 vsnprintf+0x74a/0xef0 lib/vsprintf.c:2945 vscnprintf+0x41/0x90 lib/vsprintf.c:3014 sysfs_emit+0x10e/0x180 fs/sysfs/file.c:761 input_dev_show_name+0x58/0x70 drivers/input/input.c:1282 Allocated by task 10: redrat3_dev_probe+0x477/0x2570 drivers/media/rc/redrat3.c:1023 Freed by task 10: redrat3_delete drivers/media/rc/redrat3.c:466 [inline] redrat3_dev_probe+0x1bf4/0x2570 drivers/media/rc/redrat3.c:1124
Syzkaller triggers this via usb probing. It probes the RedRat3 USB interface, which calls redrat3_dev_probe() in redrat3.c. That function allocates rr3, then builds an rc device whose name points into rr3 via redrat3_init_rc_dev() in redrat3.c, and registers it with rc_register_device().
When the detector enable fails after the RC device is registered, the probe jumps to the led_free path. That path unregisters the LED but does not unregister the RC device before freeing rr3 via redrat3_delete() in redrat3.c. The RC device still holds device_name = rr3->name which is now freed.
Later udevd reads /sys/.../input device name via sysfs_emit() in file.c, which calls input_dev_show_name() in input.c, which emits dev->name which is the freed rr3->name.
When the detector enable fails after the RC device is registered, the error path must not leave the RC device registered. Make the probe error path clean up the same way redrat3_dev_disconnect() does.
This change should be safe because the RC device is fully registered at this point and its teardown via rc_unregister_device() is protected by the input device mutex, and rr3 is still alive during unregister so device_name remains valid until after unregister. The URBs are killed before rc_free, so no completion can run after rc is freed. No new lock ordering is introduced.
--- drivers/media/rc/redrat3.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/redrat3.c +4 -0
@@ -977,6 +977,7 @@ static int redrat3_dev_probe(struct usb_struct device *dev = &intf->dev;struct usb_host_interface *uhi;struct redrat3_dev *rr3; +struct rc_dev *rc;struct usb_endpoint_descriptor *ep;struct usb_endpoint_descriptor *ep_narrow =NULL ;struct usb_endpoint_descriptor *ep_wide =NULL ;
@@ -1121,9 +1122,12 @@ static int redrat3_dev_probe(struct usb_return 0 ; led_free: +rc_unregister_device (rr3->rc);led_classdev_unregister (&rr3->led); redrat_free: + rc = rr3->rc;redrat3_delete (rr3, rr3->udev); +rc_free_device (rc); no_endpoints:return retval;
Greg Kroah-Hartman
maintainerPATCH 728/1005 media: s5p-mfc: use timer_shutdown_sync() for the self-rearming watchdog
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 63069b5917cba2e15b1a78b3f4ff99e45102c56f upstream.
The MFC watchdog timer (s5p_mfc_watchdog) is self-rearming: every callback re-arms itself with add_timer() and, on a timeout, schedules watchdog_work. s5p_mfc_remove() tears this down with timer_delete_sync() followed by flush_work().
timer_delete_sync() dequeues the timer and waits for a callback that is already running, but it does not prevent a subsequent re-arm. Because the watchdog callback re-arms via add_timer(), this is the wrong shutdown
primitive: once the wait returns nothing guarantees a just-queued re-arm will not fire later, dereferencing dev (clock on/off, deinit_hw, load_firmware, init_hw) after video_unregister_device(), DMA teardown and s5p_mfc_final_pm() have run, a potential use-after-free.
Use timer_shutdown_sync(), which puts the timer into a shutdown state so that any add_timer()/mod_timer() from the callback becomes a no-op and no later firing is possible. Switch flush_work() to cancel_work_sync() so any watchdog_work that was already queued before the timer was stopped is cancelled rather than allowed to run to completion against the torn-down device.
This issue was found by an in-house static analysis tool. No runtime reproducer is available.
--- drivers/media/platform/samsung/s5p-mfc/s5p_mfc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/platform/samsung/s5p-mfc/s5p_mfc.c +2 -2
@@ -1474,8 +1474,8 @@ static void s5p_mfc_remove(struct platfo }mutex_unlock (&dev->mfc_mutex); -timer_delete_sync (&dev->watchdog_timer); -flush_work (&dev->watchdog_work); +timer_shutdown_sync (&dev->watchdog_timer); +cancel_work_sync (&dev->watchdog_work);video_unregister_device (dev->vfd_enc);video_unregister_device (dev->vfd_dec);
Greg Kroah-Hartman
maintainerPATCH 729/1005 mm/slab: sample slab_state once in kmem_cache_destroy()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Imre Kaloz <[email protected]>
commit 088bfdc0d7947d623f4899b9011c866e4445074d upstream.
kmem_cache_release() tests slab_state >= FULL after kmem_cache_destroy() has dropped slab_mutex and unlinked the cache, and for a SLAB_TYPESAFE_BY_RCU cache after rcu_barrier(). If slab_late_init() runs before that test it sets slab_state to FULL but skips the unlinked cache, which never got a sysfs entry, so sysfs_slab_release() calls kobject_put() on a kobject that was never initialized:
WARNING: lib/kobject.c:734 at kobject_put+0x64/0x2c0, CPU#1: kworker/u8:3/55 kobject: '(null)' ((____ptrval____)): is not initialized, yet kobject_put() is being called. refcount_t: underflow; use-after-free. kobject_put+0x64/0x2c0 sysfs_slab_release+0xc/0x20 kmem_cache_destroy+0x104/0x1e0 bioset_exit+0x13c/0x1e0 disk_release+0x54/0x140 put_disk+0x18/0x40 floppy_async_init+0xbec/0xd10
slab_state >= FULL asks whether the cache has a kobject, which cache creation skips while slab_state <= UP. UP is the state just below FULL, so a false sample cannot skip a kobject_put() that was owed.
Seen on sparc64 at boot, where the asynchronous floppy init tears down its bio slab while the late initcalls are running.
Sample slab_state once, under slab_mutex which slab_late_init() holds when it sets FULL, and use the result for both the unlink and the release.
The history of this problem dates back to v3.2:
Commit 69cb8e6b7c29 ("slub: free slabs without holding locks") in v3.2 moved sysfs_slab_remove() outside slub_lock and introduced a race condition between kmem_cache_destroy() and slab_sysfs_init().
Commit 945cf2b6199be ("mm/sl[aou]b: Extract a common function for kmem_cache_destroy") in v3.7 accidentally closed the race while extracting a common implementation for kmem_cache_destroy().
Commit 5413dfba88d6 ("slub: drop mutex before deleting sysfs entry") in v3.8 re-opened the race by dropping slab_mutex around sysfs_slab_remove() in __kmem_cache_shutdown(), to avoid a lockdep splat between slab_mutex and the sysfs lock.
Commit 657dc2f97220 ("slab: remove synchronous rcu_barrier() call in memcg cache release path") in v4.11 shifted from synchronous rcu_barrier() to asynchronous RCU work for SLAB_TYPESAFE_BY_RCU caches. That commit, again, accidentally closed the race by moving sysfs_slab_release() to shutdown_cache(), but only for !SLAB_TYPESAFE_BY_RCU caches because destruction of SLAB_TYPESAFE_BY_RCU caches is done in an RCU work.
Commit 0495e337b703 ("mm/slab_common: Deleting kobject in kmem_cache_destroy() without holding slab_mutex/cpu_hotplug_lock") in v6.0 re-introduced the race for !SLAB_TYPESAFE_BY_RCU caches.
--- mm/slab_common.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-)
mm/slab_common.c +13 -4
@@ -498,10 +498,10 @@ EXPORT_SYMBOL(kmem_buckets_create);* and release of the kobject does not need slab_mutex or cpu_hotplug_lock * protection. So they are now done without holding those locks. */ -static void kmem_cache_release (struct kmem_cache *s) +static void kmem_cache_release (struct kmem_cache *s,bool sysfs_ready) {kfence_shutdown_cache (s); -if (__is_defined (SLAB_SUPPORTS_SYSFS ) && slab_state >=FULL ) +if (__is_defined (SLAB_SUPPORTS_SYSFS ) && sysfs_ready)sysfs_slab_release (s);else slab_kmem_cache_release (s);
@@ -516,6 +516,7 @@ void slab_kmem_cache_release(struct kmemvoid kmem_cache_destroy (struct kmem_cache *s) { +bool sysfs_ready;int err;if (unlikely (!s) || !kasan_check_byte (s))
@@ -563,10 +564,18 @@ void kmem_cache_destroy(struct kmem_cachlist_del (&s->list); +/* +* slab_late_init() sets slab_state to FULL under slab_mutex and adds +* sysfs entries only for caches still on the list. Sample the state +* here, so that a cache unlinked before that point is not handed to +* sysfs_slab_release() with an uninitialized kobject. +*/ + sysfs_ready = slab_state >=FULL ; +mutex_unlock (&slab_mutex);cpus_read_unlock (); -if (slab_state >=FULL ) +if (sysfs_ready)sysfs_slab_unlink (s);debugfs_slab_release (s);
@@ -576,7 +585,7 @@ void kmem_cache_destroy(struct kmem_cachif (s->flags &SLAB_TYPESAFE_BY_RCU )rcu_barrier (); -kmem_cache_release (s); +kmem_cache_release (s, sysfs_ready); }EXPORT_SYMBOL (kmem_cache_destroy);
Greg Kroah-Hartman
maintainerPATCH 730/1005 mm: khugepaged: fix folio is used after folio_put/unlock()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vernon Yang <[email protected]>
commit 9010383e71e6ce75fcd3c8f87133c8ce6c0e6ab4 upstream.
On the rollback path, folio_put() has already dropped the last reference of new_folio. On the success path, new_folio is already unlocked and can be freed concurrently. The trace_mm_khugepaged_collapse_file() is left with a dangling folio pointer.
So using the folio_pfn() before dropping the reference, closing use-after-free window.
--- include/trace/events/huge_memory.h | 6 +++--- mm/khugepaged.c | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-)
include/trace/events/huge_memory.h +3 -3
@@ -200,10 +200,10 @@ TRACE_EVENT(mm_khugepaged_scan_file, ); TRACE_EVENT(mm_khugepaged_collapse_file, - TP_PROTO(struct mm_struct *mm, struct folio *new_folio, pgoff_t index, + TP_PROTO(struct mm_struct *mm, unsigned long new_pfn, pgoff_t index, unsigned long addr, bool is_shmem, struct file *file, int nr, int result), - TP_ARGS(mm, new_folio, index, addr, is_shmem, file, nr, result), + TP_ARGS(mm, new_pfn, index, addr, is_shmem, file, nr, result), TP_STRUCT__entry( __field(struct mm_struct *, mm) __field(unsigned long, hpfn)
@@ -217,7 +217,7 @@ TRACE_EVENT(mm_khugepaged_collapse_file,TP_fast_assign ( __entry->mm = mm; - __entry->hpfn = new_folio ?folio_pfn (new_folio) :-1 ; + __entry->hpfn = new_pfn; __entry->index = index; __entry->addr = addr; __entry->is_shmem = is_shmem;
mm/khugepaged.c +3 -1
@@ -1861,6 +1861,7 @@ static int collapse_file(struct mm_strucstruct address_space *mapping = file->f_mapping;struct page *dst;struct folio *folio, *tmp, *new_folio; +unsigned long new_pfn =-1 ;pgoff_t index =0 , end = start +HPAGE_PMD_NR ;LIST_HEAD (pagelist);XA_STATE_ORDER (xas, &mapping->i_pages, start,HPAGE_PMD_ORDER );
@@ -1873,6 +1874,7 @@ static int collapse_file(struct mm_struc result =alloc_charge_folio (&new_folio, mm, cc);if (result !=SCAN_SUCCEED ) goto out; + new_pfn =folio_pfn (new_folio);mapping_set_update (&xas, mapping);
@@ -2292,7 +2294,7 @@ rollback:folio_put (new_folio); out:VM_BUG_ON (!list_empty (&pagelist)); -trace_mm_khugepaged_collapse_file (mm, new_folio, index, addr, is_shmem, file,HPAGE_PMD_NR , result); +trace_mm_khugepaged_collapse_file (mm, new_pfn, index, addr, is_shmem, file,HPAGE_PMD_NR , result);return result; }
Greg Kroah-Hartman
maintainerPATCH 731/1005 scsi: dc395x: sync the waiting_timer before freeing the host
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 0b1a79f2791a06f139dce5450e487307cf0e241f upstream.
The waiting_timer callback re-arms itself and takes the host lock. adapter_uninit() currently stops it with timer_delete(), which does not wait for a callback already running on another CPU. The final scsi_host_put() that frees the host (and the host lock the callback dereferences) runs right after adapter_uninit(), so a concurrent or just re-armed callback can fire after the free, leaving a potential use-after-free window.
Replace timer_delete() with timer_shutdown_sync() at the top of adapter_uninit(), before the host-lock section: the timer is dequeued, a running callback is waited for and rearming is blocked before the chip is halted, so it cannot fire at all once the adapter has ceased to function. Waiting outside the lock avoids the self-deadlock that would result from syncing a callback blocked on the lock we still hold.
No shutdown is needed for selto_timer because it has no reachable armer or callback.
This issue was found by an in-house static analysis tool.
--- drivers/scsi/dc395x.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-)
drivers/scsi/dc395x.c +4 -6
@@ -3814,13 +3814,11 @@ static void adapter_uninit_chip(struct Astatic void adapter_uninit (struct AdapterCtlBlk *acb) {unsigned long flags; -DC395x_LOCK_IO (acb->scsi_host, flags); -/* remove timers */ -if (timer_pending (&acb->waiting_timer)) -timer_delete (&acb->waiting_timer); -if (timer_pending (&acb->selto_timer)) -timer_delete (&acb->selto_timer); +/* Drain the self-rearming timer; must not run under host_lock. */ +timer_shutdown_sync (&acb->waiting_timer); + +DC395x_LOCK_IO (acb->scsi_host, flags);adapter_uninit_chip (acb);adapter_remove_and_free_all_devices (acb);
Greg Kroah-Hartman
maintainerPATCH 732/1005 serial: core: shut down initialized port on removal
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Putko <[email protected]>
commit 810d467c11f0c85107874d08dfdd11acba6aa0c0 upstream.
When a serial port configured as a console is opened and subsequently closed, tty_port_shutdown() skips invoking port->ops->shutdown() because port->console is true. As a result, tty_port_initialized() remains true and the port's interrupt handler stays registered in the irq subsystem.
If the underlying device is later unbound or removed (e.g. via sysfs driver unbind or device hot-unplug), serial_core_remove_one_port() unregisters the console, frees uport->name via kfree(), and tears down the port without shutting it down or freeing its IRQ. Consequently, the irqaction descriptor remains registered in genirq with action->name pointing to freed memory.
This triggers a use-after-free read whenever genirq accesses action->name, such as when reading /proc/interrupts:
BUG: KASAN: slab-use-after-free in string+0x476/0x570 Call Trace: string+0x476/0x570 vsnprintf+0x422/0x1300 seq_printf+0x... show_interrupts+...
Fix this by acquiring port->mutex in serial_core_remove_one_port() after console unregistration, clearing port->console under the mutex to prevent data races with concurrent tty_port_shutdown(), and invoking uart_shutdown(NULL, state) if the port remains initialized. This ensures that port->ops->shutdown() is called and the IRQ is freed before kfree(uport->name).
--- drivers/tty/serial/serial_core.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/tty/serial/serial_core.c +7 -0
@@ -3225,6 +3225,13 @@ static void serial_core_remove_one_port(if (uart_console (uport))unregister_console (uport->cons); + scoped_guard(mutex, &port->mutex) { + port->console = false; + +if (tty_port_initialized (port)) +uart_shutdown (NULL , state); + } +/* * Free the port IO and memory resources, if any. */
Greg Kroah-Hartman
maintainerPATCH 733/1005 xen-blkfront: unbind irq before tearing down ring and shadow requests
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuchao Zhang <[email protected]>
commit f3e27b7955727a4d7c0e9264a2a209fbba788bdc upstream.
In blkif_free_ring(), the driver tears down the ring's persistent grants, shadow request arrays, and shared ring structure (xenbus_teardown_ring), and only calls unbind_from_irqhandler() at the very end.
While blkif_free_ring() is freeing persistent grants and clearing the shadow array, the event channel interrupt (blkif_interrupt) is still registered and active. If an interrupt arrives from the backend during this teardown window, blkif_interrupt() reads rinfo->ring.sring and, via blkif_completion(), accesses rinfo->shadow[id].grants_used and rinfo->shadow[id].sg. blkif_free_ring() tears these structures down without holding rinfo->ring_lock, and the handler only checks info->connected at entry, so this is a real race resulting in a use-after-free or NULL pointer dereference.
Fix this by moving unbind_from_irqhandler() to the beginning of blkif_free_ring(). Calling unbind_from_irqhandler() first frees the IRQ and synchronizes with any in-flight interrupt handlers on other CPUs before ring memory and shadow request structures are deallocated, matching the teardown order in drivers/net/xen-netfront.c.
Message-ID: <[email protected]>
--- drivers/block/xen-blkfront.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/block/xen-blkfront.c +8 -4
@@ -1211,6 +1211,14 @@ static void blkif_free_ring(struct blkfrint i, j, segs;/* +* Interrupt teardown must be done ahead of freeing queue-related +* data, otherwise the interrupt handler can race with the cleanup. +*/ +if (rinfo->irq) +unbind_from_irqhandler (rinfo->irq, rinfo); + rinfo->evtchn = rinfo->irq =0 ; + +/* * Remove indirect pages, this only happens when using indirect * descriptors but not persistent grants */
@@ -1292,10 +1300,6 @@ free_shadow:/* Free resources associated with old device channel. */ xenbus_teardown_ring ((void **)&rinfo->ring.sring, info->nr_ring_pages, rinfo->ring_ref); - -if (rinfo->irq) -unbind_from_irqhandler (rinfo->irq, rinfo); - rinfo->evtchn = rinfo->irq =0 ; }static void blkif_free (struct blkfront_info *info,int suspend)
Greg Kroah-Hartman
maintainerPATCH 734/1005 wifi: ath9k: delete channel-context timers on deinit
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
commit 81394dfb9a7905472957628b560ae894eae3a30f upstream.
ath9k_deinit_channel_context() cancels chanctx_work but does not delete the offchannel and sched timers set up by ath9k_init_channel_context(). If either timer fires after deinit (e.g. during driver unload or suspend), it accesses sc->sc_ah which may already be freed by ath9k_hw_deinit(), causing a use-after-free.
Delete both timers with timer_shutdown_sync() before cancelling the work item.
--- drivers/net/wireless/ath/ath9k/channel.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/net/wireless/ath/ath9k/channel.c +2 -0
@@ -1363,6 +1363,8 @@ void ath9k_init_channel_context(struct avoid ath9k_deinit_channel_context (struct ath_softc *sc) { +timer_shutdown_sync (&sc->sched.timer); +timer_shutdown_sync (&sc->offchannel.timer);cancel_work_sync (&sc->chanctx_work); }
Greg Kroah-Hartman
maintainerPATCH 735/1005 wifi: mt76: mt7996: unlink TWT flow if the MCU rejects the agreement
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhao Li <[email protected]>
commit 022f5f8b7a0580da50fcbc34da853d03d4321fe2 upstream.
mt7996_mac_add_twt_setup() links a new flow into dev->twt_list before asking the MCU to add the agreement, but exits without unlinking the flow if the request fails. The flow-ID and table masks are only committed after MCU success, so the still-linked flow is invisible to the mask-gated teardown paths.
If the station retries the setup, the same slot is cleared and its embedded list node reinitialized while it is still linked, corrupting dev->twt_list. If the station disassociates instead, teardown skips the flow and station storage can be freed while the node remains linked. A later scheduling or debugfs twt_stats walk can then dereference the freed flow, resulting in a use-after-free.
Unlink the flow when the MCU rejects the agreement. This restores the list to its pre-request state while leaving the unchanged mask and agreement accounting untouched.
--- drivers/net/wireless/mediatek/mt76/mt7996/mac.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/net/wireless/mediatek/mt76/mt7996/mac.c +3 -1
@@ -3347,8 +3347,10 @@ void mt7996_mac_add_twt_setup(struct iee flow->tsf =le64_to_cpu (twt_agrt->twt);if (mt7996_mcu_twt_agrt_update (dev, &msta->vif->deflink, flow, -MCU_TWT_AGRT_ADD )) +MCU_TWT_AGRT_ADD )) { +list_del (&flow->list); goto unlock; + } setup_cmd =TWT_SETUP_CMD_ACCEPT ; dev->twt.table_mask |=BIT (table_id);
Greg Kroah-Hartman
maintainerPATCH 736/1005 usb: gadget: fix refcount underflow in gadgetfs_bind() error path
In reply to Greg Kroah-Hartman6.18-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
@@ -1697,6 +1697,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)
@@ -1711,7 +1713,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 737/1005 ufs: use u64 for directory size in ufs_last_byte
In reply to Greg Kroah-Hartman6.18-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
@@ -212,7 +212,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 738/1005 spi: spi-pci1xxxx: quiesce DMA engines on transfer timeout
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weibin Liu <[email protected]>
commit 0b591332a2bdc13d3f9163793131fe3651d1556a upstream.
If a DMA-mapped transfer times out waiting for DMA_TERM and neither DMA abort interrupt arrived, pci1xxxx_spi_transfer_with_dma() returns through the error label while both DMA engines are still enabled, the done/abort interrupt status is still armed and the transfer state (p->xfer, p->tx_sgl, p->rx_sgl) is still registered.
The ISRs keep firing afterwards: they reprogram the DMA engines from p->tx_sgl / p->rx_sgl and signal completion through p->xfer and p->spi_xfer_done, all of which the SPI core is free to unmap or reuse once transfer_one() has returned, which is a use-after-free. A late done interrupt can also start the next transfer queued behind the failed one.
Stop both DMA engines, drain the pending done/abort interrupt status and synchronize the DMA IRQs before dropping the in-progress state and the transfer pointers, and re-enable the engines afterwards so that subsequent transfers keep working. The engines are only turned back on once both were confirmed to have stopped: re-enabling an engine that failed to stop would cancel the pending stop request and let it keep running into buffers the SPI core is about to unmap or free, which is exactly the window this patch closes. An engine that failed to stop is left disabled, as the abort paths already do.
The DMA interrupt status and mask registers are shared between the two SPI instances, so the cleanup drains only this instance's done/abort status bits instead of masking the interrupt lines, which would also suppress the peer instance's completion interrupts.
Also make the DMA ISRs ignore interrupts while no transfer is in progress so that a stray MSI after the cleanup can no longer act on the cleared state.
No PCI1XXXX hardware was available for testing and QEMU has no model of this PCIe part, so the timeout path was exercised with a userspace replica of the timeout branch and the DMA ISRs, with the register and interrupt accesses mocked: on the unfixed code both a wedged engine that clears after the timeout and a late done interrupt touch the freed transfer state, while with this fix applied neither does and an engine that failed to stop is left disabled. The module was also loaded and unloaded in a QEMU x86_64 guest running a kernel with this fix applied.
--- drivers/spi/spi-pci1xxxx.c | 71 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+)
drivers/spi/spi-pci1xxxx.c +71 -0
@@ -542,6 +542,8 @@ static int pci1xxxx_spi_transfer_with_dmstruct pci1xxxx_spi_internal *p =spi_controller_get_devdata (spi_ctlr);struct pci1xxxx_spi *par = p->parent;dma_addr_t tx_dma_addr =0 ; +unsigned long flags; +bool engines_stopped;int ret =0 ;u32 regval;
@@ -618,12 +620,72 @@ static int pci1xxxx_spi_transfer_with_dm p->dma_aborted_wr = false; ret = -ECANCELED ; } + +/* +* A timed out transfer leaves the DMA engines running and +* the done/abort interrupt status armed with p->xfer, +* p->tx_sgl and p->rx_sgl still registered. Stop the +* engines, drain the pending status and synchronize the +* IRQs before dropping the transfer state, otherwise a +* late interrupt makes the ISRs reprogram the engines +* from or signal completion through memory which the SPI +* core is about to unmap or free. +*/ +writel (SPI_DMA_ENGINE_DIS , + par->dma_offset_bar +SPI_DMA_GLOBAL_WR_ENGINE_EN ); +writel (SPI_DMA_ENGINE_DIS , + par->dma_offset_bar +SPI_DMA_GLOBAL_RD_ENGINE_EN ); + engines_stopped = + !(readl_poll_timeout (par->dma_offset_bar + +SPI_DMA_GLOBAL_WR_ENGINE_EN , + regval, regval ==0x0 ,0 , +USEC_PER_MSEC ) || +readl_poll_timeout (par->dma_offset_bar + +SPI_DMA_GLOBAL_RD_ENGINE_EN , + regval, regval ==0x0 ,0 , +USEC_PER_MSEC )); +if (!engines_stopped) +dev_warn (&par->dev->dev, +"SPI DMA engines failed to stop\n" ); + +spin_lock_irqsave (&par->dma_wr_reg_lock, flags); +writel ((SPI_DMA_DONE_INT_MASK (p->hw_inst) | +SPI_DMA_ABORT_INT_MASK (p->hw_inst)), + par->dma_offset_bar +SPI_DMA_INTR_WR_CLR ); +spin_unlock_irqrestore (&par->dma_wr_reg_lock, flags); +spin_lock_irqsave (&par->dma_rd_reg_lock, flags); +writel ((SPI_DMA_DONE_INT_MASK (p->hw_inst) | +SPI_DMA_ABORT_INT_MASK (p->hw_inst)), + par->dma_offset_bar +SPI_DMA_INTR_RD_CLR ); +spin_unlock_irqrestore (&par->dma_rd_reg_lock, flags); + + p->spi_xfer_in_progress = false; +synchronize_irq (p->irq[1 ]); +synchronize_irq (p->irq[2 ]); + +/* +* Turn the engines back on only once both are confirmed +* to have stopped: re-enabling an engine that failed to +* stop would cancel the pending stop request and let it +* run into buffers the SPI core is about to unmap or +* free. An engine that failed to stop is left disabled, +* as the abort paths already do. +*/ +if (engines_stopped) { +writel (SPI_DMA_ENGINE_EN , + par->dma_offset_bar +SPI_DMA_GLOBAL_WR_ENGINE_EN ); +writel (SPI_DMA_ENGINE_EN , + par->dma_offset_bar +SPI_DMA_GLOBAL_RD_ENGINE_EN ); + } goto error; } ret =0 ; error: p->spi_xfer_in_progress = false; + p->xfer =NULL ; + p->tx_sgl =NULL ; + p->rx_sgl =NULL ;return ret; }
@@ -695,6 +757,9 @@ static irqreturn_t pci1xxxx_spi_isr_dma_unsigned long flags;u32 regval; +if (!p->spi_xfer_in_progress) +return IRQ_NONE ; +/* Clear the DMA RD INT and start spi xfer*/ regval =readl (p->parent->dma_offset_bar +SPI_DMA_INTR_RD_STS );if (regval) {
@@ -723,6 +788,9 @@ static irqreturn_t pci1xxxx_spi_isr_dma_unsigned long flags;u32 regval; +if (!p->spi_xfer_in_progress) +return IRQ_NONE ; +/* Clear the DMA WR INT */ regval =readl (p->parent->dma_offset_bar +SPI_DMA_INTR_WR_STS );if (regval) {
@@ -755,6 +823,9 @@ static irqreturn_t pci1xxxx_spi_isr_dma(irqreturn_t spi_int_fired =IRQ_NONE ;u32 regval; +if (!p->spi_xfer_in_progress) +return IRQ_NONE ; +/* Clear the SPI GO_BIT Interrupt */ regval =readl (p->parent->reg_base +SPI_MST_EVENT_REG_OFFSET (p->hw_inst));if (regval &SPI_INTR ) {
Greg Kroah-Hartman
maintainerPATCH 739/1005 resource: report a devm_request_resource() conflict under the lock
In reply to Greg Kroah-Hartman6.18-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
@@ -1645,10 +1645,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 740/1005 phy: core: Fix race-condition between _of_phy_get() and try_module_get()
In reply to Greg Kroah-Hartman6.18-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 ); }
@@ -602,6 +602,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)
@@ -613,11 +615,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)) {
@@ -631,8 +632,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);
@@ -656,15 +655,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);
@@ -764,6 +769,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",
@@ -774,15 +780,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);
@@ -791,6 +800,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);
@@ -939,15 +950,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);
@@ -960,6 +973,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 741/1005 power: supply: sbs-battery: disable polling before supply teardown
In reply to Greg Kroah-Hartman6.18-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
@@ -1060,6 +1060,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);
@@ -1200,6 +1207,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 742/1005 nvmem: core: Fix OOB read for bit offsets of more than one byte
In reply to Greg Kroah-Hartman6.18-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
@@ -1597,12 +1597,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 743/1005 media: rc: Ensure that rc_unregister_device() does not free input device
In reply to Greg Kroah-Hartman6.18-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 744/1005 media: rc: Ensure registered is cleared in error path
In reply to Greg Kroah-Hartman6.18-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 745/1005 media: rc: fintek-cir: process a full RX buffer instead of overflowing it
In reply to Greg Kroah-Hartman6.18-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 746/1005 media: rc: Fix race between bpf(BPG_PROG_ATTACH) and device unregister
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit b3f5daf3222999d3f92f606a4eb5e35ab90fd0e4 upstream.
Mark the device as unregistered before tearing down raw IR/bpf state, so that racing bpf(BPF_PROG_{ATTACH,DETACH,QUERY}) calls cannot slip in between ir_raw_event_unregister() completing and dev->registered being cleared.
--- drivers/media/rc/rc-main.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/media/rc/rc-main.c +6 -6
@@ -2026,18 +2026,18 @@ void rc_unregister_device(struct rc_devif (!dev)return ; +mutex_lock (&dev->lock); + dev->registered = false; +if (dev->users && dev->close) + dev->close (dev); +mutex_unlock (&dev->lock); +if (dev->driver_type ==RC_DRIVER_IR_RAW )ir_raw_event_unregister (dev);timer_delete_sync (&dev->timer_keyup);timer_delete_sync (&dev->timer_repeat); -mutex_lock (&dev->lock); -if (dev->users && dev->close) - dev->close (dev); - dev->registered = false; -mutex_unlock (&dev->lock); -rc_free_rx_device (dev);/*
Greg Kroah-Hartman
maintainerPATCH 747/1005 media: rc: mce_kbd: Fix inconsistent locking of keylock
In reply to Greg Kroah-Hartman6.18-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
@@ -219,6 +219,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)) {
@@ -319,7 +320,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 );
@@ -329,7 +330,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 748/1005 media: rc: Use after free in ir_raw_event_handle()
In reply to Greg Kroah-Hartman6.18-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
@@ -648,8 +648,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)
@@ -659,6 +664,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);timer_delete_sync (&dev->raw->edge_handle);
Greg Kroah-Hartman
maintainerPATCH 749/1005 media: rc: After rc_unregister_device() timers can be re-armed
In reply to Greg Kroah-Hartman6.18-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 750/1005 media: rc: Fix use after free in bpf progs
In reply to Greg Kroah-Hartman6.18-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
@@ -650,8 +650,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 ; }
@@ -661,9 +664,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
@@ -683,11 +683,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 751/1005 media: rc: Fix ABBA deadlock by making locks more fine grained
In reply to Greg Kroah-Hartman6.18-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
@@ -633,15 +627,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 ; }
@@ -674,16 +671,19 @@ void ir_raw_event_unregister(struct rc_dkthread_stop (dev->raw->thread);timer_delete_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); }/*
@@ -706,15 +706,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 752/1005 ocfs2/heartbeat: unlink live slots when their node is missing
In reply to Greg Kroah-Hartman6.18-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
@@ -868,8 +868,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)) {
@@ -891,7 +894,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)
@@ -1026,7 +1030,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 753/1005 ocfs2/dlm: hold a lock reference across grant AST enqueue
In reply to Greg Kroah-Hartman6.18-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 754/1005 ocfs2/dlm: hold the lookup reference across convert AST enqueue
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit 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 755/1005 ocfs2: cancel quota sync work before freeing quota info
In reply to Greg Kroah-Hartman6.18-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 756/1005 ocfs2: fix chunk number of the first chunk in a local quota file
In reply to Greg Kroah-Hartman6.18-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 757/1005 ocfs2: pin refcount trees before dropping the lookup lock
In reply to Greg Kroah-Hartman6.18-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 758/1005 ocfs2: snapshot dentry names in file and setattr traces
In reply to Greg Kroah-Hartman6.18-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 759/1005 smb: client: fix OOB last_entry pointer from unbounded LastNameOffset
In reply to Greg Kroah-Hartman6.18-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
@@ -4447,14 +4447,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 ; }
@@ -4572,7 +4575,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 760/1005 smb: client: stop processing a read response after a receive error
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weiming Shi <[email protected]>
commit 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
@@ -1312,6 +1312,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 761/1005 ovl: set OVL_WHITEOUTS before publishing the upper dir
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit cbec8610ec5aaf35df50094ff639febc23f20773 upstream.
Listing a directory while it is copied up causes a use-after-free of the readdir cache.
A merge directory must never be iterated as a real upper directory:
that mode frees the cache in OVL_I(inode)->cache without looking at its refcount, while files opened in merged mode still use it. ovl_copy_up_workdir() publishes the upper dentry before it sets OVL_WHITEOUTS, and ovl_dir_open() samples both without a lock, so an open between the two stores finds the upper directory and takes it for a real one.
With a delay between the two stores, an unprivileged process that listed a directory during its copy-up saw only "." and "..", and its next getdents freed the readdir cache of another descriptor.
Fix this by setting OVL_WHITEOUTS before ovl_inode_update(), so that ovl_dir_reset() agrees with ovl_dir_open(), and by testing OVL_TYPE_MERGE() of the path type in ovl_dir_open(), so that an open that observes the upper dentry never iterates a merge dir as a real dir, regardless of the order in which it observes the flag.
--- fs/overlayfs/copy_up.c | 2 +- fs/overlayfs/readdir.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +1 -1
@@ -843,9 +843,9 @@ static int ovl_copy_up_workdir(struct ovif (!c->metacopy)ovl_set_upperdata (inode); -ovl_inode_update (inode, temp);if (S_ISDIR (inode->i_mode))ovl_set_flag (OVL_WHITEOUTS , inode); +ovl_inode_update (inode, temp); out:ovl_end_write (c->dentry);
fs/overlayfs/readdir.c +2 -1
@@ -1053,7 +1053,8 @@ static int ovl_dir_open(struct inode *inreturn PTR_ERR (realfile); } od->realfile = realfile; - od->is_real =ovl_dir_is_real (inode); + od->is_real = !OVL_TYPE_MERGE (type) && + !ovl_test_flag (OVL_WHITEOUTS , inode); od->is_upper =OVL_TYPE_UPPER (type); file->private_data = od;
Greg Kroah-Hartman
maintainerPATCH 762/1005 ovl: take a snapshot of the name for copy up
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 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 763/1005 ovl: use the pinned upper dir in ovl_fix_origin()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 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
@@ -936,8 +936,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
@@ -559,6 +559,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 764/1005 ovl: always encode the origin fh when index is enabled
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 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 765/1005 ovl: check the casefold flag of directories only
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 1d27da7de3f74405b1de85ad26c5ea90f826114b upstream.
On an overlay over casefolded (case-insensitive) directories, every lookup of a file that is not a directory fails with EREMOTE, and the first file create triggers a kernel warning. No privilege is needed: an unprivileged user can cause both in a user namespace, with the layers on a tmpfs that they have mounted with the casefold option.
Some filesystems support casefolding, which is case-insensitive name lookup. It is enabled per directory, and the inode of a casefolded directory has the S_CASEFOLD flag.
overlayfs accepts layers on a filesystem that supports casefolding as long as casefolding is enabled on every directory of the layers, or on none. The mount records which of the two applies in ofs->casefold. ovl_lookup_single() compares the S_CASEFOLD flag of each file that it finds against ofs->casefold and returns -EREMOTE on a mismatch.
Filesystems only set S_CASEFOLD on directories, so with casefolded layers a regular file, a symlink or a special file never matches and its lookup fails.
ovl_get_inode() does the same comparison in a WARN_ON_ONCE() for each new overlay inode. A failed lookup never gets that far, so it is the first file create that trips the warning.
Reproduced on an overlay over casefolded tmpfs or ext4 directories, with stat() of a regular file, a symlink and a FIFO, and with a file create:
each stat() failed with EREMOTE. For an unprivileged user in a user namespace, on tmpfs, stat() of a regular file failed in the same way, and the file create triggered the warning.
Fix this by limiting both checks to directories.
--- fs/overlayfs/inode.c | 2 +- fs/overlayfs/namei.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-)
fs/overlayfs/inode.c +1 -1
@@ -1280,7 +1280,7 @@ struct inode *ovl_get_inode(struct super }ovl_fill_inode (inode, realinode->i_mode, realinode->i_rdev);ovl_inode_init (inode, oip, ino, fsid); -WARN_ON_ONCE (!!IS_CASEFOLDED (inode) != ofs->casefold); +WARN_ON_ONCE (is_dir && !!IS_CASEFOLDED (inode) != ofs->casefold);if (upperdentry &&ovl_is_impuredir (sb, upperdentry))ovl_set_flag (OVL_IMPURE , inode);
fs/overlayfs/namei.c +2 -1
@@ -260,7 +260,8 @@ static int ovl_lookup_single(struct dent goto out_err; } -if (ofs->casefold !=ovl_dentry_casefolded (this)) { +/* Filesystems set the casefold flag only on directories */ +if (d_is_dir (this) && ofs->casefold !=ovl_dentry_casefolded (this)) { warn ="child wrong casefold" ; err = -EREMOTE ; goto out_warn;
Greg Kroah-Hartman
maintainerPATCH 766/1005 ovl: do not copy up an xattr value that was never read
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 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 767/1005 ovl: fix a torn path in ovl_get_redirect()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 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
@@ -1007,7 +1007,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);
@@ -1020,13 +1032,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 768/1005 ovl: fortify ovl_copy_xattr() against underlying layer modifications
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit 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 769/1005 ovl: read the nlink xattr of every indexed non-dir
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 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
@@ -707,7 +707,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
@@ -795,7 +795,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 770/1005 ovl: reserve space for the casefolded name terminator
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit a65eb1808177a4381718abe563dddebf840598f9 upstream.
ovl_casefold() allocates NAME_MAX bytes and passes that capacity to utf8_casefold(), which also needs room for a terminating NUL. A valid name whose folded form is exactly NAME_MAX bytes therefore fails to fold, and ovl_fill_merge() falls back to comparing the original bytes.
For example, when two casefolded layers contain directories named with 255 uppercase and lowercase ASCII letters respectively, readdir lists both names even though lookup treats them as the same directory. The same names merge correctly at 254 bytes.
Reserve one additional byte in both the allocation and the folding capacity so that NAME_MAX-byte folded names use the canonical merge key.
--- fs/overlayfs/readdir.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/overlayfs/readdir.c +2 -2
@@ -79,13 +79,13 @@ static int ovl_casefold(struct ovl_readdif (!IS_ENABLED (CONFIG_UNICODE ) || !rdd->map ||is_dot_dotdot (str, len))return 0 ; - cf_name =kmalloc (NAME_MAX ,GFP_KERNEL ); + cf_name =kmalloc (NAME_MAX +1 ,GFP_KERNEL );if (!cf_name) { rdd->err = -ENOMEM ;return -ENOMEM ; } - cf_len =utf8_casefold (rdd->map, &qstr, cf_name,NAME_MAX ); + cf_len =utf8_casefold (rdd->map, &qstr, cf_name,NAME_MAX +1 );if (cf_len >0 ) *dst = cf_name;else
Greg Kroah-Hartman
maintainerPATCH 771/1005 ovl: set the revalidate flags after d_instantiate()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 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
@@ -295,7 +295,6 @@ static int ovl_instantiate(struct dentry };ovl_dentry_set_upper_alias (dentry); -ovl_dentry_init_reval (dentry, newdentry,NULL );if (!hardlink) {/*
@@ -326,6 +325,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 772/1005 ovl: skip copy up of empty security.capability
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
commit 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 773/1005 xfs: clear the symlink zapped flag if inline symlink is ok
In reply to Greg Kroah-Hartman6.18-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 774/1005 xfs: mark cow extents bad if theres no rmap mapping for them
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 2ffc0619c9c2881443c5fffb10db8f2bc0aa2ce8 upstream.
LOLLM noticed that we fail to mark cow staging extents as bad if there's a cow staging extent but no rmap record for the cow staging event. Close this gap.
--- fs/xfs/scrub/cow_repair.c | 84 ++++++++++++++++++++++++++++++---------------- 1 file changed, 55 insertions(+), 29 deletions(-)
fs/xfs/scrub/cow_repair.c +55 -29
@@ -199,29 +199,35 @@ xrep_cow_mark_missing_staging_rmap( void *priv) {struct xrep_cow *xc = priv; -xfs_agblock_t rec_bno; -xfs_extlen_t rec_len; -unsigned int adj; - -if (rec->rm_owner ==XFS_RMAP_OWN_COW ) -return 0 ; +const xfs_agblock_t rec_end = + rec->rm_startblock + rec->rm_blockcount; +int error =0 ; - rec_bno = rec->rm_startblock; - rec_len = rec->rm_blockcount; -if (rec_bno < xc->irec_startbno) { - adj = xc->irec_startbno - rec_bno; - rec_len -= adj; - rec_bno += adj; +/* Was there a gap since the last rmap? */ +if (xc->next_bno < rec->rm_startblock) { + error =xrep_cow_mark_file_range (xc, +xfs_gbno_to_fsb (cur->bc_group, xc->next_bno), + rec->rm_startblock - xc->next_bno); +if (error) +return error; } -if (rec_bno + rec_len > xc->irec_startbno + xc->irec.br_blockcount) { - adj = (rec_bno + rec_len) - - (xc->irec_startbno + xc->irec.br_blockcount); - rec_len -= adj; +if (rec->rm_owner !=XFS_RMAP_OWN_COW ) { +const xfs_agblock_t bad_bno = +max (xc->irec_startbno, rec->rm_startblock); +const xfs_agblock_t irec_end = + xc->irec_startbno + xc->irec.br_blockcount; +const xfs_extlen_t bad_end =min (irec_end, rec_end); + + error =xrep_cow_mark_file_range (xc, +xfs_gbno_to_fsb (cur->bc_group, bad_bno), + bad_end - bad_bno); +if (error) +return error; } -return xrep_cow_mark_file_range (xc, -xfs_gbno_to_fsb (cur->bc_group, rec_bno), rec_len); + xc->next_bno =max (xc->next_bno, rec_end); +return error; }/*
@@ -239,10 +245,12 @@ xrep_cow_find_bad(struct xfs_perag *pag;struct xfs_scrub *sc = xc->sc;xfs_agnumber_t agno; +xfs_agblock_t irec_end;int error; agno =XFS_FSB_TO_AGNO (sc->mp, xc->irec.br_startblock); xc->irec_startbno =XFS_FSB_TO_AGBNO (sc->mp, xc->irec.br_startblock); + irec_end = xc->irec_startbno + xc->irec.br_blockcount; pag =xfs_perag_get (sc->mp, agno);if (!pag)
@@ -254,7 +262,7 @@ xrep_cow_find_bad(/* Mark any CoW fork extents that are shared. */ rc_low.rc_startblock = xc->irec_startbno; - rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount -1 ; + rc_high.rc_startblock = irec_end -1 ; rc_low.rc_domain = rc_high.rc_domain =XFS_REFC_DOMAIN_SHARED ; error =xfs_refcount_query_range (sc->sa.refc_cur, &rc_low, &rc_high, xrep_cow_mark_shared_staging, xc);
@@ -263,7 +271,7 @@ xrep_cow_find_bad(/* Make sure there are CoW staging extents for the whole mapping. */ rc_low.rc_startblock = xc->irec_startbno; - rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount -1 ; + rc_high.rc_startblock = irec_end -1 ; rc_low.rc_domain = rc_high.rc_domain =XFS_REFC_DOMAIN_COW ; xc->next_bno = xc->irec_startbno; error = xfs_refcount_query_range(sc->sa.refc_cur, &rc_low, &rc_high,
@@ -271,11 +279,10 @@ xrep_cow_find_bad(if (error) goto out_sa; -if (xc->next_bno < xc->irec_startbno + xc->irec.br_blockcount) { +if (xc->next_bno < irec_end) { error =xrep_cow_mark_file_range (xc,xfs_agbno_to_fsb (pag, xc->next_bno), - xc->irec_startbno + xc->irec.br_blockcount - - xc->next_bno); + irec_end - xc->next_bno);if (error) goto out_sa; }
@@ -284,11 +291,20 @@ xrep_cow_find_bad( rm_low.rm_startblock = xc->irec_startbno;memset (&rm_high,0xFF ,sizeof (rm_high)); rm_high.rm_startblock = xc->irec_startbno + xc->irec.br_blockcount -1 ; + xc->next_bno = xc->irec_startbno; error =xfs_rmap_query_range (sc->sa.rmap_cur, &rm_low, &rm_high, xrep_cow_mark_missing_staging_rmap, xc);if (error) goto out_sa; +if (xc->next_bno < irec_end) { + error =xrep_cow_mark_file_range (xc, +xfs_agbno_to_fsb (pag, xc->next_bno), + irec_end - xc->next_bno); +if (error) + goto out_sa; + } +/* * If userspace is forcing us to rebuild the CoW fork or someone turned * on the debugging knob, replace everything in the CoW fork.
@@ -319,9 +335,11 @@ xrep_cow_find_bad_rt(struct xfs_rmap_irec rm_high = {0 };struct xfs_scrub *sc = xc->sc;struct xfs_rtgroup *rtg; +xfs_agblock_t irec_end;int error =0 ; xc->irec_startbno =xfs_rtb_to_rgbno (sc->mp, xc->irec.br_startblock); + irec_end = xc->irec_startbno + xc->irec.br_blockcount; rtg =xfs_rtgroup_get (sc->mp,xfs_rtb_to_rgno (sc->mp, xc->irec.br_startblock));
@@ -335,7 +353,7 @@ xrep_cow_find_bad_rt(/* Mark any CoW fork extents that are shared. */ rc_low.rc_startblock = xc->irec_startbno; - rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount -1 ; + rc_high.rc_startblock = irec_end -1 ; rc_low.rc_domain = rc_high.rc_domain =XFS_REFC_DOMAIN_SHARED ; error =xfs_refcount_query_range (sc->sr.refc_cur, &rc_low, &rc_high, xrep_cow_mark_shared_staging, xc);
@@ -344,7 +362,7 @@ xrep_cow_find_bad_rt(/* Make sure there are CoW staging extents for the whole mapping. */ rc_low.rc_startblock = xc->irec_startbno; - rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount -1 ; + rc_high.rc_startblock = irec_end -1 ; rc_low.rc_domain = rc_high.rc_domain =XFS_REFC_DOMAIN_COW ; xc->next_bno = xc->irec_startbno; error = xfs_refcount_query_range(sc->sr.refc_cur, &rc_low, &rc_high,
@@ -352,11 +370,10 @@ xrep_cow_find_bad_rt(if (error) goto out_sr; -if (xc->next_bno < xc->irec_startbno + xc->irec.br_blockcount) { +if (xc->next_bno < irec_end) { error =xrep_cow_mark_file_range (xc,xfs_rgbno_to_rtb (rtg, xc->next_bno), - xc->irec_startbno + xc->irec.br_blockcount - - xc->next_bno); + irec_end - xc->next_bno);if (error) goto out_sr; }
@@ -364,12 +381,21 @@ xrep_cow_find_bad_rt(/* Mark any area has an rmap that isn't a COW staging extent. */ rm_low.rm_startblock = xc->irec_startbno;memset (&rm_high,0xFF ,sizeof (rm_high)); - rm_high.rm_startblock = xc->irec_startbno + xc->irec.br_blockcount -1 ; + rm_high.rm_startblock = irec_end -1 ; + xc->next_bno = xc->irec_startbno; error =xfs_rmap_query_range (sc->sr.rmap_cur, &rm_low, &rm_high, xrep_cow_mark_missing_staging_rmap, xc);if (error) goto out_sr; +if (xc->next_bno < irec_end) { + error =xrep_cow_mark_file_range (xc, +xfs_rgbno_to_rtb (rtg, xc->next_bno), + irec_end - xc->next_bno); +if (error) + goto out_sr; + } +/* * If userspace is forcing us to rebuild the CoW fork or someone * turned on the debugging knob, replace everything in the
Greg Kroah-Hartman
maintainerPATCH 775/1005 xfs: compute the correct fdblocks/frextents for repair when theyre negative
In reply to Greg Kroah-Hartman6.18-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
@@ -541,7 +541,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 776/1005 xfs: fix ondisk symlink target validation in xrep_dinode_check_dfork
In reply to Greg Kroah-Hartman6.18-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
@@ -683,9 +683,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
@@ -1024,6 +1024,30 @@ xrep_dinode_bad_metabt_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.
@@ -1099,7 +1123,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 777/1005 xfs: fix xfs_rename_space_res for non-pptr filesystems
In reply to Greg Kroah-Hartman6.18-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 778/1005 xfs: fix missing xfs_qm_adjust_dqlimits call in quotacheck repair
In reply to Greg Kroah-Hartman6.18-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 ;
@@ -223,6 +220,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
@@ -220,7 +220,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
@@ -1341,11 +1341,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
@@ -566,11 +566,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 779/1005 xfs: fix buffer overruns in xfs_ioc_attr_list
In reply to Greg Kroah-Hartman6.18-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
@@ -431,7 +431,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 780/1005 xfs: online quotacheck must dirty dquot if enforcement adjustments needed
In reply to Greg Kroah-Hartman6.18-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 781/1005 xfs: avoid cross-rtgroup reaping after a repair
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit d7c204d4ea7ef0cf0dac908388984c2936f1f94e upstream.
LOLLM notices that the extents stored in a xrtb_bitmap (aka xfs_rtblock bitmap) can span multiple rtgroups due to two circumstances. The first is that the size of an rtgroup is an exact power of two, which means that rtgroups are adjacent in the segmented xfs_rtblock_t address space. This is fairly common to reduce the amount of multiplication and division needed to handle space on the rt volume.
The second is that (unlike in the original rtgroups design), rtgroups do not have fixed-location metadata like AGs do, which means that there's nothing to force a break between rtgroups.
Therefore, we must loop through the rtgroups in xreap_rtmeta_extent to avoid running off the end of an rtgroup while reaping.
--- fs/xfs/scrub/reap.c | 59 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 11 deletions(-)
fs/xfs/scrub/reap.c +48 -11
@@ -1080,26 +1080,23 @@ xreap_configure_rgcow_limits( XFS_RTGLOCK_RMAP | \ XFS_RTGLOCK_REFCOUNT) -/* -* Break a rt file metadata extent into sub-extents by fate (crosslinked, not -* crosslinked), and dispose of each sub-extent separately. The extent must -* be aligned to a realtime extent. -*/ -STATIC int -xreap_rtmeta_extent ( -uint64_t rtbno, +static int +xreap_rtgroup_extent ( +struct xreap_state *rs, +xfs_rtblock_t rtbno,uint64_t len, -void *priv) +xfs_rgblock_t *done) { -struct xreap_state *rs = priv;struct xfs_scrub *sc = rs->sc;xfs_rgblock_t rgbno =xfs_rtb_to_rgbno (sc->mp, rtbno); -xfs_rgblock_t rgbno_next = rgbno + len; +xfs_rgblock_t rgbno_next;int error =0 ;ASSERT (sc->ip !=NULL );ASSERT (!sc->sr.rtg); + *done =0 ; +/* * We're reaping blocks after repairing file metadata, which means that * we have to init the xchk_ag structure ourselves.
@@ -1110,6 +1107,7 @@ xreap_rtmeta_extent(xfs_rtgroup_lock (sc->sr.rtg,XREAP_RTGLOCK_ALL ); + rgbno_next = rgbno +min (len, (uint64_t )rtg_blocks (sc->sr.rtg) - rgbno);while (rgbno < rgbno_next) {xfs_extlen_t rglen;bool crosslinked;
@@ -1136,6 +1134,7 @@ xreap_rtmeta_extent( } rgbno += rglen; + *done += rglen; } out_unlock:
@@ -1146,6 +1145,44 @@ out_unlock: }/* +* Break a rt file metadata extent into sub-extents by fate (crosslinked, not +* crosslinked), and dispose of each sub-extent separately. The extent must +* be aligned to a realtime extent. +*/ +STATIC int +xreap_rtmeta_extent ( +uint64_t rtbno, +uint64_t len, +void *priv) +{ +struct xreap_state *rs = priv; +int error; + +/* +* Space from adjacent rtgroups can be stored as a single bitmap extent +* because rtgroups do not have fixed-location metadata such as a +* per-group superblock that cannot be reaped. Handle these overlaps +* by only reaping within a single rtgroup at a time. +* +* In the somewhat unlikely event that an rtgroup size is not a power +* of two, the segmented nature of xfs_rtblock_t prevents space in +* adjacent rtgroups from merging in the bitmap. +*/ +while (len >0 ) { +xfs_rgblock_t done =0 ; + + error =xreap_rtgroup_extent (rs, rtbno, len, &done); +if (error) +return error; + + rtbno += done; + len -= done; + } + +return 0 ; +} + +/* * Dispose of every block of every rt metadata extent in the bitmap. * Do not use this to dispose of the mappings in an ondisk inode fork. */
Greg Kroah-Hartman
maintainerPATCH 782/1005 xfs: actually lock the metafile reservation when adjusting after repair
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit e53c620b3670fc0c162b5f768a10a3a17d0c04f6 upstream.
LOLLM reported that xrep_reset_metafile_resv performs unlocked loads and stores to the metadata file space reservation counters and thus can race with other threads. Fix this by taking the lock.
--- fs/xfs/scrub/repair.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
fs/xfs/scrub/repair.c +12 -6
@@ -1377,12 +1377,14 @@ xrep_reset_metafile_resv( {struct xfs_mount *mp = sc->mp;int64_t delta; -int error; +int error =0 ; + +mutex_lock (&mp->m_metafile_resv_lock); delta = mp->m_metafile_resv_used + mp->m_metafile_resv_avail - mp->m_metafile_resv_target;if (delta ==0 ) -return 0 ; + goto out_resv_lock;/* * Too many blocks have been reserved, transfer some from the incore
@@ -1398,7 +1400,7 @@ xrep_reset_metafile_resv( mp->m_metafile_resv_avail -= give_back; } -return 0 ; + goto out_resv_lock; }/*
@@ -1412,14 +1414,18 @@ xrep_reset_metafile_resv(if (delta ==0 ) {xfs_warn (sc->mp,"Insufficient free space to reset metabtree reservation after repair." ); -return 0 ; + error =0 ; + goto out_resv_lock; } error =xfs_dec_fdblocks (mp, delta, true); }if (error) -return error; + goto out_resv_lock;xfs_mod_sb_delalloc (mp, delta); mp->m_metafile_resv_avail += delta; -return 0 ; + +out_resv_lock: +mutex_unlock (&mp->m_metafile_resv_lock); +return error; }
Greg Kroah-Hartman
maintainerPATCH 783/1005 xfs: fix unnecessary dapos truncation in xchk_dir_walk
In reply to Greg Kroah-Hartman6.18-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 784/1005 xfs: fix buffer overflow in corrupt inline attr structure
In reply to Greg Kroah-Hartman6.18-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 785/1005 xfs: actually report corrupt xattrs as XFAIL during cross-referencing
In reply to Greg Kroah-Hartman6.18-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
@@ -155,6 +155,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 786/1005 xfs: fix inode btree repair when a cluster is larger than a chunk
In reply to Greg Kroah-Hartman6.18-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
@@ -294,12 +294,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
@@ -320,6 +316,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 787/1005 xfs: always reset incore attr fork buffer when resetting fork
In reply to Greg Kroah-Hartman6.18-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 );
Greg Kroah-Hartman
maintainerPATCH 788/1005 xfs: dont pass iget failures up when marking ondisk inodes
In reply to Greg Kroah-Hartman6.18-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
@@ -1331,8 +1331,12 @@ xrep_iunlink_mark_ondisk_rec(*/ error =xchk_iget (ragi->sc,xfs_agino_to_ino (sc->sa.pag, agino), &ip); -if (error) +if (error == -ENOMEM ) +return error; +if (error) { + error =0 ;continue ; + }trace_xrep_iunlink_reload_ondisk (ip);
Greg Kroah-Hartman
maintainerPATCH 789/1005 xfs: zero out di_metatype when removing the metadir file iflag
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit f5b4d8c8ce16675f77c25a4ff06caaa9a2739f31 upstream.
LOLLM pointed out that we should zero di_metatype (fka di_onlink) when we're clearing the METADIR inode flag because the file is no longer a metadata file.
--- fs/xfs/scrub/inode_repair.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/inode_repair.c +3 -1
@@ -579,8 +579,10 @@ xrep_dinode_flags( fa =xfs_dinode_verify_metadir (sc->mp, dip, mode, flags, flags2); -if (fa) +if (fa) { flags2 &= ~XFS_DIFLAG2_METADATA ; + dip->di_metatype =cpu_to_be16 (XFS_METAFILE_UNKNOWN ); + } } dip->di_flags =cpu_to_be16 (flags);
Greg Kroah-Hartman
maintainerPATCH 790/1005 xfs: flag excessive delalloc rt extents as corruption
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 2b47be015a5e54f4a3d62afa636ba593de9b67f6 upstream.
LOLLM observed that we should not allow repairs to proceed if the count of delayed-allocation realtime extents exceeds the number of free rt extents because we can't install negative numbers into the superblock. It's unclear how we could end up in that state in real life, but let's at least complain loudly about it if we ever encounter it.
--- fs/xfs/scrub/fscounters.c | 7 +++++++ 1 file changed, 7 insertions(+)
fs/xfs/scrub/fscounters.c +7 -0
@@ -607,6 +607,13 @@ xchk_fscounters( try_again = true; } +if (!xfs_has_zoned (mp) && fsc->frextents < fsc->frextents_delayed) { +if (fsc->frozen) +xchk_set_incomplete (sc); +else + try_again = true; + } +if (!xfs_has_zoned (mp) && !xchk_fscount_within_range(sc, frextents, &mp->m_free[XC_FREE_RTEXTENTS].count,
Greg Kroah-Hartman
maintainerPATCH 791/1005 xfs: dont fix the directory tree if live update fails
In reply to Greg Kroah-Hartman6.18-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 792/1005 xfs: validate rc_domain in xchk_rtrefcount_mergeable
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Sandeen <[email protected]>
commit f04361fb8694bff98ec61e2e2030a1993426fdca upstream.
xchk_refcount_mergeable validates that the domains match, but this was omitted from the realtime version of the check; fix it.
--- fs/xfs/scrub/rtrefcount.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/scrub/rtrefcount.c +2 -0
@@ -380,6 +380,8 @@ xchk_rtrefcount_mergeable(if (r1->rc_blockcount ==0 )return false; +if (r1->rc_domain != r2->rc_domain) +return false;if (r1->rc_startblock + r1->rc_blockcount != r2->rc_startblock)return false;if (r1->rc_refcount != r2->rc_refcount)
Greg Kroah-Hartman
maintainerPATCH 793/1005 xfs: dont proceed with xattr repair if the live update fails
In reply to Greg Kroah-Hartman6.18-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 794/1005 xfs: fix skipped inode mask handling in iscan
In reply to Greg Kroah-Hartman6.18-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 795/1005 xfs: dont repair fs summary counters with garbage
In reply to Greg Kroah-Hartman6.18-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 796/1005 xfs: fix lost errno returned from xfarray_foliosort
In reply to Greg Kroah-Hartman6.18-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 797/1005 xfs: allow softlimit with no hardlimit in quota scrub
In reply to Greg Kroah-Hartman6.18-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 798/1005 xfs: assign an owner to scrub_stats_fops
In reply to Greg Kroah-Hartman6.18-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
@@ -294,6 +294,7 @@ out: }static const struct file_operations scrub_stats_fops = { + .owner =THIS_MODULE , .open = simple_open, .read = xchk_scrub_stats_read, };
@@ -321,6 +322,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 799/1005 xfs: bail out of directory tree repairs on error
In reply to Greg Kroah-Hartman6.18-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 800/1005 xfs: fix revalidation of xchk_dquot_iter cached mappings
In reply to Greg Kroah-Hartman6.18-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 801/1005 xfs: abort dirtree repair if the live update hook dies
In reply to Greg Kroah-Hartman6.18-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 802/1005 xfs: check fork type against dabtree block magic number
In reply to Greg Kroah-Hartman6.18-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 803/1005 xfs: mark overfull dabtree node blocks as corrupt
In reply to Greg Kroah-Hartman6.18-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 804/1005 xfs: jump out of xchk_bmap_check_rmap if fatal signals
In reply to Greg Kroah-Hartman6.18-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
@@ -626,6 +626,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)
@@ -657,6 +661,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 805/1005 xfs: cross-reference the primary superblock
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 0c61016006ab08f8346f9e7b1e38559bd4ea499e upstream.
Make sure we cross-reference the primary superblock against the rest of the AG 0 space metadata. Drop the unused @bp parameter of xchk_superblock_xref to avoid complaints about uninitialized variables.
--- fs/xfs/scrub/agheader.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-)
fs/xfs/scrub/agheader.c +7 -8
@@ -35,8 +35,7 @@ xchk_setup_agheader(/* Cross-reference with the other btrees. */ STATIC voidxchk_superblock_xref ( -struct xfs_scrub *sc, -struct xfs_buf *bp) +struct xfs_scrub *sc) {struct xfs_mount *mp = sc->mp;xfs_agnumber_t agno = sc->sm->sm_agno;
@@ -106,16 +105,12 @@ xchk_superblock(struct xfs_dsb *sb;struct xfs_perag *pag;size_t sblen; -xfs_agnumber_t agno; +xfs_agnumber_t agno = sc->sm->sm_agno;uint32_t v2_ok;__be32 features_mask;int error;__be16 vernum_mask; - agno = sc->sm->sm_agno; -if (agno ==0 ) -return 0 ; -/* * Grab an active reference to the perag structure. If we can't get * it, we're racing with something that's tearing down the AG, so
@@ -125,6 +120,9 @@ xchk_superblock(if (!pag)return -ENOENT ; +if (agno ==0 ) + goto out_xref; + error =xfs_sb_read_secondary (mp, sc->tp, agno, &bp);/* * The superblock verifier can return several different error codes
@@ -430,7 +428,8 @@ xchk_superblock(if (memchr_inv ((char *)sb + sblen,0 ,BBTOB (bp->b_length) - sblen))xchk_block_set_corrupt (sc, bp); -xchk_superblock_xref (sc, bp); +out_xref: +xchk_superblock_xref (sc); out_pag:xfs_perag_put (pag);return error;
Re: [PATCH 6.18 0805/1005] xfs: cross-reference the primary superblock
Review
Quoted 13 lines · On Wed, 04 Nov 2026 16:08:58 -0500 Greg Kroah-Hartman…
(quoted diff) +5
-0int error; + if (agno == 0) + goto out_xref; + error = xfs_sb_read_secondary(mp, sc->tp, agno, &bp); +out_xref: + xchk_superblock_xref(sc); out_pag: xfs_perag_put(pag); return error;
In loongarch64, like in 7.13.y, I am also seeing the following due to the code above:
fs/xfs/scrub/agheader.c:123:6: warning: variable 'error' is used uninitialized whenever 'if' condition is true [-Wsometimes-uninitialized]
123 | if (agno == 0)
| ^~~~~~~~~
fs/xfs/scrub/agheader.c:435:9: note: uninitialized use occurs here
435 | return error;
| ^~~~~
fs/xfs/scrub/agheader.c:123:2: note: remove the 'if' if its condition is always false
123 | if (agno == 0)
| ^~~~~~~~~~~~~~
124 | goto out_xref;
| ~~~~~~~~~~~~~
fs/xfs/scrub/agheader.c:111:13: note: initialize the variable 'error' to silence this warning
111 | int error;
| ^
| = 0It seems this happened in mainline too, but error got initialized in a later commit:
612d2e7506c3 ("xfs: read primary superblock from disk during scrub")
So something needs to be changed for stable.
Cheers,
Miguel
Greg Kroah-Hartman
maintainerPATCH 806/1005 xfs: adjust checks for cross-AG reaping issues
In reply to Greg Kroah-Hartman6.18-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
@@ -796,9 +796,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 807/1005 xfs: actually check XFS_DIFLAG2_METADATA for metadata btree data forks
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 436ae68743a6974021fefa21fd3093d9bf8e66e4 upstream.
LOLLM noticed that xrep_dinode_check_dfork doesn't require that the inode has the METADATA flag set in flags2. Add that check.
--- fs/xfs/scrub/inode_repair.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/xfs/scrub/inode_repair.c +5 -0
@@ -1014,6 +1014,11 @@ xrep_dinode_bad_metabt_fork(if (whichfork !=XFS_DATA_FORK )return true; +if (!xfs_has_metadir (sc->mp)) +return true; +if (!(dip->di_flags2 &cpu_to_be64 (XFS_DIFLAG2_METADATA ))) +return true; +switch (be16_to_cpu (dip->di_metatype)) {case XFS_METAFILE_RTRMAP :return xrep_dinode_bad_rtrmapbt_fork (sc, dip, dfork_size);
Greg Kroah-Hartman
maintainerPATCH 808/1005 xfs: fix xchk_stats_estimate_bufsize to allow for the trailing null
In reply to Greg Kroah-Hartman6.18-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
@@ -166,7 +166,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 809/1005 sched_ext: sync disable_irq_work in bpf_scx_unreg()
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Cheng <[email protected]>
[ Upstream commit 510a27055446b8f0d29487ca8b8d2033dc2b6ca6 ]
When unregistered my self-written scx scheduler, the following panic occurs.
[ 229.923133] Kernel text patching generated an invalid instruction at 0xffff80009bc2c1f8! [ 229.923146] Internal error: Oops - BRK: 00000000f2000100 [#1] SMP [ 230.077871] CPU: 48 UID: 0 PID: 1760 Comm: kworker/u583:7 Not tainted 7.0.0+ #3 PREEMPT(full) [ 230.086677] Hardware name: NVIDIA GB200 NVL/P3809-BMC, BIOS 02.05.12 20251107 [ 230.093972] Workqueue: events_unbound bpf_map_free_deferred [ 230.099675] Sched_ext: invariant_0.1.0_aarch64_unknown_linux_gnu_debug (disabling), task: runnable_at=-174ms [ 230.116843] pc : 0xffff80009bc2c1f8 [ 230.120406] lr : dequeue_task_scx+0x270/0x2d0 [ 230.217749] Call trace: [ 230.228515] 0xffff80009bc2c1f8 (P) [ 230.232077] dequeue_task+0x84/0x188 [ 230.235728] sched_change_begin+0x1dc/0x250 [ 230.240000] __set_cpus_allowed_ptr_locked+0x17c/0x240 [ 230.245250] __set_cpus_allowed_ptr+0x74/0xf0 [ 230.249701] ___migrate_enable+0x4c/0xa0 [ 230.253707] bpf_map_free_deferred+0x1a4/0x1b0 [ 230.258246] process_one_work+0x184/0x540 [ 230.262342] worker_thread+0x19c/0x348 [ 230.266170] kthread+0x13c/0x150 [ 230.269465] ret_from_fork+0x10/0x20 [ 230.281393] Code: d4202000 d4202000 d4202000 d4202000 (d4202000) [ 230.287621] ---[ end trace 0000000000000000 ]--- [ 231.160046] Kernel panic - not syncing: Oops - BRK: Fatal exception in interrupt
The root cause is that the JIT page backing ops->quiescent() is freed before all callers of that function have stopped.
The expected ordering during teardown is:
bitmap_zero(sch->has_op) + synchronize_rcu()
-> guarantees no CPU will ever call sch->ops.* again
-> only THEN free the BPF struct_ops JIT pagebpf_scx_unreg() is supposed to enforce the order, but after commit f4a6c506d118 ("sched_ext: Always bounce scx_disable() through irq_work"), disable_work is no longer queued directly, causing kthread_flush_work() to be a noop. Thus, the caller drops the struct_ops map too early and poisoned with AARCH64_BREAK_FAULT before disable_workfn ever execute.
So the subsequent dequeue_task() still sees SCX_HAS_OP(sch, quiescent) as true and calls ops.quiescent, which hit on the poisoned page and BRK panic.
Add a helper scx_flush_disable_work() so the future use cases that want to flush disable_work can use it.
Also amend the call for scx_root_enable_workfn() and scx_sub_enable_workfn() which have similar pattern in the error path.
[ 6.18.y has neither f4a6c506d118 nor sub-schedulers. Here, the flush is
a no-op when scx_disable() loses the exit claim to scx_vexit(), whose error_irq_work queues disable_work later. Sync error_irq_work instead of disable_irq_work and drop the scx_sub_enable_workfn() hunk. ]
--- kernel/sched/ext.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-)
kernel/sched/ext.c +16 -2
@@ -4207,6 +4207,20 @@ static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)kthread_queue_work (sch->helper, &sch->disable_work); } +/** +* scx_flush_disable_work - flush the disable work and wait for it to finish +* @sch: the scheduler +* +* sch->disable_work might still not queued, causing kthread_flush_work() +* as a noop. Syncing the irq_work first is required to guarantee the +* kthread work has been queued before waiting for it. +*/ +static void scx_flush_disable_work (struct scx_sched *sch) +{ +irq_work_sync (&sch->error_irq_work); +kthread_flush_work (&sch->disable_work); +} +static void dump_newline (struct seq_buf *s) {trace_sched_ext_dump ("" );
@@ -4968,7 +4982,7 @@ static void scx_root_enable_workfn(struct kthread_work *work)* completion. sch's base reference will be put by bpf_scx_unreg(). */ scx_error (sch,"scx_root_enable() failed (%d)" , ret); -kthread_flush_work (&sch->disable_work); +scx_flush_disable_work (sch); cmd->ret =0 ; }
@@ -5142,7 +5156,7 @@ static void bpf_scx_unreg(void *kdata, struct bpf_link *link)struct scx_sched *sch = ops->priv;scx_disable (sch,SCX_EXIT_UNREG ); -kthread_flush_work (&sch->disable_work); +scx_flush_disable_work (sch);kobject_put (&sch->kobj); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 810/1005 sched_ext: Fix scx_flush_disable_work() UAF race
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cheng-Yang Chou <[email protected]>
[ Upstream commit d99f7a32f09dccbe396187370ec1a74a31b73d7e ]
scx_flush_disable_work() calls irq_work_sync() followed by kthread_flush_work() to ensure that the disable kthread work has fully completed before bpf_scx_unreg() frees the SCX scheduler.
However, a concurrent scx_vexit() (e.g., triggered by a watchdog stall) creates a race window between scx_claim_exit() and irq_work_queue():
CPU A (scx_vexit (watchdog)) CPU B (bpf_scx_unreg)
---- ----
scx_claim_exit()
atomic_try_cmpxchg(NONE->kind)
stack_trace_save()
vscnprintf()
scx_disable()
scx_claim_exit() -> FAIL
scx_flush_disable_work()
irq_work_sync() // no-op: not queued yet
kthread_flush_work() // no-op: not queued yet
kobject_put(&sch->kobj) -> free %sch
irq_work_queue() -> UAF on %sch
scx_disable_irq_workfn()
kthread_queue_work() -> UAFThe root cause is that CPU B's scx_flush_disable_work() returns after syncing an irq_work that has not yet been queued, while CPU A is still executing the code between scx_claim_exit() and irq_work_queue().
Loop until exit_kind reaches SCX_EXIT_DONE or SCX_EXIT_NONE, draining disable_irq_work and disable_work in each pass. This ensures that any work queued after the previous check is caught, while also correctly handling cases where no disable was triggered (e.g., the scx_sub_enable_workfn() abort path).
--- kernel/sched/ext.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/sched/ext.c +7 -2
@@ -4217,8 +4217,13 @@ static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)*/ static void scx_flush_disable_work (struct scx_sched *sch) { -irq_work_sync (&sch->error_irq_work); -kthread_flush_work (&sch->disable_work); +int kind; + +do { +irq_work_sync (&sch->error_irq_work); +kthread_flush_work (&sch->disable_work); + kind =atomic_read (&sch->exit_kind); + }while (kind !=SCX_EXIT_NONE && kind !=SCX_EXIT_DONE ); }static void dump_newline (struct seq_buf *s)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 811/1005 netfilter: disable payload mangling in userns
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Florian Westphal <[email protected]>
[ Upstream commit 968cc2c96390f06e56ed6a43f935bfebdefed28f ]
Several parts of network stack rely on iph->ihl validation done by network stack before PRE_ROUTING.
Disable this feature for user namespaces for now.
tcp option handling is likely safe even for LOCAL_IN, so this this leaves tcp option mangling via nft_exthdr.c as-is.
I don't think these are the only means to alter packets, but these appear to be relatively prominent.
This could be relaxed later. Example:
- allow userns for ingress hook.
- allow userns if base is transport header.
Also, we should revalidate or restrict generally:
- Don't allow linklayer writes to spill into network header
- restrict ipv4 and ipv6 to 'known safe' writes, e.g. saddr/daddr/check/tos
--- net/netfilter/nfnetlink_queue.c | 6 ++++-- net/netfilter/nft_payload.c | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-)
net/netfilter/nfnetlink_queue.c +4 -2
@@ -1190,6 +1190,9 @@ nfqnl_mangle(void *data, unsigned int data_len, struct nf_queue_entry *e, int di {struct sk_buff *nskb; +if (e->state.net->user_ns != &init_user_ns) +return -EPERM ; +if (diff <0 ) {unsigned int min_len =skb_transport_offset (e->skb);
@@ -1592,8 +1595,7 @@ static int nfqnl_recv_verdict(struct sk_buff *skb, const struct nfnl_info *info,if (nfqnl_mangle (nla_data (nfqa[NFQA_PAYLOAD ]), payload_len, entry, diff) <0 ) verdict =NF_DROP ; - -if (ct && diff) +else if (ct && diff) nfnl_ct->seq_adjust (entry->skb, ct, ctinfo, diff); }
net/netfilter/nft_payload.c +3 -0
@@ -917,6 +917,9 @@ static int nft_payload_set_init(const struct nft_ctx *ctx,struct nft_payload_set *priv =nft_expr_priv (expr);int err; +if (ctx->net->user_ns != &init_user_ns) +return -EPERM ; + priv->base =ntohl (nla_get_be32 (tb[NFTA_PAYLOAD_BASE ])); priv->len =ntohl (nla_get_be32 (tb[NFTA_PAYLOAD_LEN ]));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 812/1005 ipv6: Implement limits on extension header parsing
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daniel Borkmann <[email protected]>
[ Upstream commit 3744b0964d5267c0b651bcd8f8c25db6bf4ccbac ]
ipv6_{skip_exthdr,find_hdr}() and ip6_{tnl_parse_tlv_enc_lim, protocol_deliver_rcu}() iterate over IPv6 extension headers until they find a non-extension-header protocol or run out of packet data. The loops have no iteration counter, relying solely on the packet length to bound them. For a crafted packet with 8-byte extension headers filling a 64KB jumbogram, this means a worst case of up to ~8k iterations with a skb_header_pointer call each. ipv6_skip_exthdr(), for example, is used where it parses the inner quoted packet inside an incoming ICMPv6 error:
- icmpv6_rcv
- checksum validation
- case ICMPV6_DEST_UNREACH
- icmpv6_notify
- pskb_may_pull() <- pull inner IPv6 header
- ipv6_skip_exthdr() <- iterates here
- pskb_may_pull()
- ipprot->err_handler() <- sk lookup
The per-iteration cost of ipv6_skip_exthdr itself is generally light, but skb_header_pointer becomes more costly on reassembled
packets: the first ~1232 bytes of the inner packet are in the skb's linear area, but the remaining ~63KB are in the frag_list where skb_copy_bits is needed to read data.
Initially, the idea was to add a configurable limit via a new sysctl knob with default 8, in line with knobs from commit 47d3d7ac656a ("ipv6: Implement limits on Hop-by-Hop and Destination options"), but two reasons eventually argued against it:
- It adds to UAPI that needs to be maintained forever, and upcoming work is restricting extension header ordering anyway, leaving little reason for another sysctl knob
- exthdrs_core.c is always built-in even when CONFIG_IPV6=n, where struct net has no .ipv6 member, so the read site would need an ifdef'd fallback to a constant anyway
Therefore, just use a constant (IP6_MAX_EXT_HDRS_CNT). All four extension header walking functions are now bound by this limit.
Note that the check in ip6_protocol_deliver_rcu() happens right before the goto resubmit, such that we don't have to have a test for ipv6_ext_hdr() in the fast-path.
There's an ongoing IETF draft-iurman-6man-eh-occurrences to enforce IPv6 extension headers ordering and occurrence. The latter also discusses security implications. As per RFC8200 section 4.1, the occurrence rules for extension headers provide a practical upper bound which is 8. In order to be conservative, let's define IP6_MAX_EXT_HDRS_CNT as 12 to leave enough room for quirky setups. In the unlikely event that this is still not enough, then we might need to reconsider a sysctl.
--- include/net/dropreason-core.h | 6 ++++++ include/net/ipv6.h | 3 +++ net/ipv6/exthdrs_core.c | 7 +++++++ net/ipv6/ip6_input.c | 5 +++++ net/ipv6/ip6_tunnel.c | 4 ++++ 5 files changed, 25 insertions(+)
include/net/dropreason-core.h +6 -0
@@ -101,6 +101,7 @@ FN(FRAG_TOO_FAR) \ FN(TCP_MINTTL) \ FN(IPV6_BAD_EXTHDR) \ + FN(IPV6_TOO_MANY_EXTHDRS) \ FN(IPV6_NDISC_FRAG) \ FN(IPV6_NDISC_HOP_LIMIT) \ FN(IPV6_NDISC_BAD_CODE) \
@@ -508,6 +509,11 @@ enum skb_drop_reason {SKB_DROP_REASON_TCP_MINTTL ,/** @SKB_DROP_REASON_IPV6_BAD_EXTHDR: Bad IPv6 extension header. */ SKB_DROP_REASON_IPV6_BAD_EXTHDR , +/** +* @SKB_DROP_REASON_IPV6_TOO_MANY_EXTHDRS: Number of IPv6 extension +* headers in the packet exceeds IP6_MAX_EXT_HDRS_CNT. +*/ +SKB_DROP_REASON_IPV6_TOO_MANY_EXTHDRS ,/** @SKB_DROP_REASON_IPV6_NDISC_FRAG: invalid frag (suppress_frag_ndisc). */ SKB_DROP_REASON_IPV6_NDISC_FRAG,/** @SKB_DROP_REASON_IPV6_NDISC_HOP_LIMIT: invalid hop limit. */
include/net/ipv6.h +3 -0
@@ -90,6 +90,9 @@ struct ip_tunnel_info;#define IP6_DEFAULT_MAX_DST_OPTS_LEN INT_MAX/* No limit */ #define IP6_DEFAULT_MAX_HBH_OPTS_LEN INT_MAX/* No limit */ +/* Hard limit on traversed IPv6 extension headers */ +#define IP6_MAX_EXT_HDRS_CNT 12 +/* * Addr type *
net/ipv6/exthdrs_core.c +7 -0
@@ -73,6 +73,7 @@ int ipv6_skip_exthdr(const struct sk_buff *skb, int start, u8 *nexthdrp, __be16 *frag_offp) {u8 nexthdr = *nexthdrp; +int exthdr_cnt =0 ; *frag_offp =0 ;
@@ -82,6 +83,8 @@ int ipv6_skip_exthdr(const struct sk_buff *skb, int start, u8 *nexthdrp,if (nexthdr ==NEXTHDR_NONE )return -1 ; +if (unlikely (exthdr_cnt++ >=IP6_MAX_EXT_HDRS_CNT )) +return -1 ; hp =skb_header_pointer (skb, start,sizeof (_hdr), &_hdr);if (!hp)return -1 ;
@@ -190,6 +193,7 @@ int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset, {unsigned int start =skb_network_offset (skb) +sizeof (struct ipv6hdr );u8 nexthdr =ipv6_hdr (skb)->nexthdr; +int exthdr_cnt =0 ;bool found;if (fragoff)
@@ -216,6 +220,9 @@ int ipv6_find_hdr(const struct sk_buff *skb, unsigned int *offset,return -ENOENT ; } +if (unlikely (exthdr_cnt++ >=IP6_MAX_EXT_HDRS_CNT )) +return -EBADMSG ; + hp =skb_header_pointer (skb, start,sizeof (_hdr), &_hdr);if (!hp)return -EBADMSG ;
net/ipv6/ip6_input.c +5 -0
@@ -363,6 +363,7 @@ INDIRECT_CALLABLE_DECLARE(int tcp_v6_rcv(struct sk_buff *));void ip6_protocol_deliver_rcu (struct net *net,struct sk_buff *skb,int nexthdr,bool have_final) { +int exthdr_cnt =IP6CB (skb)->flags &IP6SKB_HOPBYHOP ?1 :0 ;const struct inet6_protocol *ipprot;struct inet6_dev *idev;unsigned int nhoff;
@@ -447,6 +448,10 @@ void ip6_protocol_deliver_rcu(struct net *net, struct sk_buff *skb, int nexthdr, nexthdr = ret; goto resubmit_final; }else { +if (unlikely (exthdr_cnt++ >=IP6_MAX_EXT_HDRS_CNT )) { +SKB_DR_SET (reason,IPV6_TOO_MANY_EXTHDRS ); + goto discard; + } goto resubmit; } }else if (ret ==0 ) {
net/ipv6/ip6_tunnel.c +4 -0
@@ -400,11 +400,15 @@ __u16 ip6_tnl_parse_tlv_enc_lim(struct sk_buff *skb, __u8 *raw)unsigned int nhoff = raw - skb->data;unsigned int off = nhoff +sizeof (*ipv6h);u8 nexthdr = ipv6h->nexthdr; +int exthdr_cnt =0 ;while (ipv6_ext_hdr (nexthdr) && nexthdr !=NEXTHDR_NONE ) {struct ipv6_opt_hdr *hdr;u16 optlen; +if (unlikely (exthdr_cnt++ >=IP6_MAX_EXT_HDRS_CNT )) +break ; +if (!pskb_may_pull (skb, off +sizeof (*hdr)))break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 813/1005 netfilter: nfnetlink_queue: restrict writes to network header
In reply to Greg Kroah-Hartman6.18-stable review patch. If anyone has any objections, please let me know.
------------------
From: Florian Westphal <[email protected]>
[ Upstream commit 54f34607d184c1cc056c59a5b3d86d96dd6a515c ]
nfnetlink_queue doesn't allow selective replacements of some part of the payload, only complete replacement.
If the new data is shorter, skb is trimmed, otherwise expanded.
Add minimal validation of the new ip/ipv6 header. Check total len matches skb length. Disallow ip option modifications.
IPv6 extension headers are also disabled.
IP options and exthdrs could be allowed later after validation pass or ip option recompile.
Transport header is not checked.
Bridge modifications are rejected. Given userspace doesn't even receive L2 headers, use is limited and I don't think there are any users of bridge nfnetlink_queue, let alone users that modifiy payload.
Arp isn't supported at all.
--- net/netfilter/nfnetlink_queue.c | 170 ++++++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+)
net/netfilter/nfnetlink_queue.c +170 -0
@@ -1185,6 +1185,173 @@ nfqnl_enqueue_packet(struct nf_queue_entry *entry, unsigned int queuenum)return err; } +static bool nfqnl_validate_ipopts (const struct iphdr *iph_new, +const struct nf_queue_entry *e) +{ +const struct iphdr *iph_orig =ip_hdr (e->skb); +unsigned int ihl = iph_new->ihl *4 ; + +if (iph_new->ihl != iph_orig->ihl) +return false; +if (ihl ==sizeof (*iph_orig)) +return true; + +return memcmp (iph_new +1 ,ip_hdr (e->skb) +1 , ihl -sizeof (*iph_orig)) ==0 ; +} + +static bool nfqnl_validate_ip4 (const struct iphdr *iph,unsigned int data_len, +const struct nf_queue_entry *e) +{ +unsigned int ihl; + +if (data_len <sizeof (*iph)) +return false; + + ihl = iph->ihl *4u ; +if (ihl <sizeof (*iph) || data_len < ihl) +return false; + +if (iph->version !=4 || + ((iph->frag_off ^ip_hdr (e->skb)->frag_off) & ~htons (IP_DF )) !=0 ) +return false; + +/* BIG TCP won't work; netlink attr len is u16 */ +if (ntohs (iph->tot_len) != data_len) +return false; + +/* support for ipopts mangling would require +* recompile + skb transport header update. +*/ +return nfqnl_validate_ipopts (iph, e); +} + +static bool nfqnl_validate_one_exthdr (const u8 *data, +unsigned int data_len, +const struct nf_queue_entry *e, +int start,int hdrlen) +{ +u16 octets; + +if (data_len < hdrlen || hdrlen <2 ) +return false; + +while (hdrlen >0 ) { +if (data_len <sizeof (octets)) +return false; + data_len -=sizeof (octets); + +if (skb_copy_bits (e->skb, start, &octets,sizeof (octets))) +return false; + +if (hdrlen <sizeof (octets)) +return false; + + hdrlen -=sizeof (octets); +if (memcmp (data, &octets,sizeof (octets))) +return false; + + start +=sizeof (octets); + data +=sizeof (octets); + } + +return true; +} + +static bool nfqnl_validate_exthdr (const struct ipv6hdr *ip6_new, +unsigned int data_len, +const struct nf_queue_entry *e) +{ +const struct ipv6hdr *ip6_orig =ipv6_hdr (e->skb); +int exthdr_cnt =0 , start =sizeof (*ip6_orig); +const u8 *data = (const u8 *)ip6_new; +u8 orig_nexthdr = ip6_orig->nexthdr; +u8 new_nexthdr = ip6_new->nexthdr; + +if (new_nexthdr != orig_nexthdr) +return false; + + data +=sizeof (*ip6_new); + data_len -=sizeof (*ip6_new); + +while (ipv6_ext_hdr (orig_nexthdr)) { +const struct ipv6_opt_hdr *hp; +struct ipv6_opt_hdr _hdr; +int hdrlen; + +if (orig_nexthdr ==NEXTHDR_NONE ) +return true; + +if (unlikely (exthdr_cnt++ >=IP6_MAX_EXT_HDRS_CNT )) +return false; + + hp =skb_header_pointer (e->skb, start,sizeof (_hdr), &_hdr); +if (!hp) +return false; + +switch (orig_nexthdr) { +case NEXTHDR_FRAGMENT : + hdrlen =sizeof (struct frag_hdr ); +break ; +case NEXTHDR_AUTH : + hdrlen =ipv6_authlen (hp); +break ; +default : + hdrlen =ipv6_optlen (hp); +break ; + } + +if (!nfqnl_validate_one_exthdr (data, data_len, e, + start, hdrlen)) +return false; + + orig_nexthdr = hp->nexthdr; + hp = (const void *)data; + new_nexthdr = hp->nexthdr; + +if (new_nexthdr != orig_nexthdr) +return false; + + data_len -= hdrlen; + start += hdrlen; + data += hdrlen; + } + +return true; +} + +static bool nfqnl_validate_ip6 (const struct ipv6hdr *ip6,unsigned int data_len, +const struct nf_queue_entry *e) +{ +if (data_len <sizeof (*ip6)) +return false; + +/* BIG TCP/jumbograms won't work; netlink attr len is u16 */ +if (ntohs (ip6->payload_len) != data_len -sizeof (*ip6)) +return false; + +if (ip6->version !=6 ) +return false; + +return nfqnl_validate_exthdr (ip6, data_len, e); +} + +static bool nfqnl_validate_write (const void *data,unsigned int data_len, +const struct nf_queue_entry *e) +{ +switch (e->state.pf) { +case NFPROTO_IPV4 : +return nfqnl_validate_ip4 (data, data_len, e); +case NFPROTO_IPV6 : +return nfqnl_validate_ip6 (data, data_len, e) && + !(IP6CB (e->skb)->flags &IP6SKB_JUMBOGRAM ); +case NFPROTO_BRIDGE : +/* No write support. Bridge is dubious: userspace doesn't even see L2 header */ +return false; + } + +return false; +} +static int nfqnl_mangle (void *data,unsigned int data_len,struct nf_queue_entry *e,int diff) {
@@ -1193,6 +1360,9 @@ nfqnl_mangle(void *data, unsigned int data_len, struct nf_queue_entry *e, int diif (e->state.net->user_ns != &init_user_ns)return -EPERM ; +if (!nfqnl_validate_write (data, data_len, e)) +return -EINVAL ; +if (diff <0 ) {unsigned int min_len =skb_transport_offset (e->skb);
Signature · 1 line
2.53.0