[PATCH 3/4] mm/damon/sysfs: check contexts->nr in update_schemes_tried_regions

Josh Law posted 4 patches 2 weeks, 3 days ago
[PATCH 3/4] mm/damon/sysfs: check contexts->nr in update_schemes_tried_regions
Posted by Josh Law 2 weeks, 3 days ago
damon_sysfs_update_schemes_tried_regions() and its callback
damon_sysfs_schemes_tried_regions_upd_one() access contexts_arr[0]
without verifying nr_contexts >= 1. This can NULL deref if damon_ctx is
non-NULL (preserved after stop) but nr_contexts has been set to 0. Add
the missing check.

Signed-off-by: Josh Law <objecting@objecting.org>
---
 mm/damon/sysfs.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/mm/damon/sysfs.c b/mm/damon/sysfs.c
index 36ad2e8956c9..ddcdc4e35b27 100644
--- a/mm/damon/sysfs.c
+++ b/mm/damon/sysfs.c
@@ -1731,6 +1731,8 @@ static int damon_sysfs_update_schemes_tried_regions(
 
 	if (!ctx)
 		return -EINVAL;
+	if (sysfs_kdamond->contexts->nr != 1)
+		return -EINVAL;
 
 	damon_sysfs_schemes_clear_regions(
 			sysfs_kdamond->contexts->contexts_arr[0]->schemes);
-- 
2.34.1
Re: [PATCH 3/4] mm/damon/sysfs: check contexts->nr in update_schemes_tried_regions
Posted by SeongJae Park 2 weeks, 3 days ago
On Thu, 19 Mar 2026 15:57:41 +0000 Josh Law <objecting@objecting.org> wrote:

> damon_sysfs_update_schemes_tried_regions() and its callback
> damon_sysfs_schemes_tried_regions_upd_one() access contexts_arr[0]
> without verifying nr_contexts >= 1. This can NULL deref if damon_ctx is
> non-NULL (preserved after stop) but nr_contexts has been set to 0. Add
> the missing check.

Nice catch.  This can be triggered by privileged users.

    # cd /sys/kernel/mm/damon/admin/kdamonds/
    # echo 1 > nr_kdamonds
    # echo 1 > contexts/nr_contexts
    # echo on > state
    # echo off > state
    # echo 0 > contexts/nr_contexts
    # echo update_schemes_tried_regions > state
    # dmesg
    [...]
    [  222.362338] BUG: kernel NULL pointer dereference, address: 0000000000000000
    [...]

Weird sequence of commands, but even privileged users can make mistakes.  So I
think this deserves Fixes: and Cc: stable.

But, this is just another instance of a class of bugs that I mentioned on the
reply to the second patch of this series.  I'd suggest fixing all bugs of the
class with single fix, as I also mentioned on the second patch thread.  Let's
discuss on the thread.


Thanks,
SJ

[...]