mm/damon: hardware-sampled access reports
Subsystems (4)
v4 cover mm/damon: hardware-sampled access reports
This series lets DAMON monitor a hardware-sampled data attribute -- the addresses a PMU saw accessed -- through the data attributes monitoring (probe) interface, and run DAMOS schemes on it in data attributes-only mode. Patches 3, 5, and 6 are co-developed with Akinobu Mita, building on his earlier perf-event proposal [3].
This v4 follows v3 by only a few days, which breaks the usual practice of waiting for review before respinning. I am sending it now so that it addresses the sashiko review of v3 and the questions Kunwu Chan raised on it before the DAMON nano-conference at LPC; it supersedes v3.
The scope has been narrowed from v2 [1] based on SJ's feedback; the changes are described in the "Changes from v2" section below. What remains is the perf-event probe substrate and its consumers.
The sysfs surface has been reshaped against the milestone-1 probes/preps interface [2], as the v2 cover letter said it would be. A perf-event probe is configured through the probe's preps/N/ directory using the perf_event prep action. This is the first concrete implementation of a hardware-sampled data attribute on the milestone-2 path SJ described in [2].
The series is based on damon/next at the base-commit below, which moves, so the tree it was built and tested from is also on
https://github.com/ravis-opensrc/linux/tree/damon/perf-rfc-v4-send-2026-10-04
It is posted as an RFC for design feedback on the substrate and on where it belongs in the roadmap for extending DAMON beyond the pte-accessed bit [2]. That roadmap's second milestone, now open, is a first data attribute monitored through damon_report_access(), and that is what a sampling PMU is here. So this series keeps that function as the reporting entry point and replaces its body: the reporting path a hardware sampler needs cannot take a mutex, and the drain has to reach a virtual-address context as well as a physical one. The shape of the ring, the drain and the sysfs surface are what is most useful to review.
The series builds cleanly at every commit and passes all KUnit tests; checkpatch reports only false positives. It runs end to end on the hardware described below. I expect it to be rebased onto the milestone 2 work once that lands; patch 8 does not depend on the rest and could be taken on its own.
Why a unified perf-event substrate
==================================
DAMON derives its access information from the PTE Accessed bit. A sampling PMU carries what that bit cannot: which addresses the hardware went to, and how often it went there. Many machines already have such a unit, and more than one kind of it, so what this series is after is letting DAMON's regions be tuned from whichever perf-based hardware source a machine offers rather than from the Accessed bit alone. A sampler does not arrive on a kdamond's terms, though: it delivers an address when the hardware decides to, in NMI context, with no relation to the sampling interval and no mm to walk.
The alternative is a backend per PMU vendor, each owning its own configuration, sysfs knobs and lifecycle. The perf-event direction [3] avoids that: let DAMON register kernel-counter perf events and consume samples from any sampling PMU the perf core already knows about. This series follows it, adding one substrate below the ops sets rather than an ops set per PMU -- a per-context report ring that the perf-event overflow handler pushes into through damon_report_access(), and a drain that folds those reports into region probe hits on the kdamond's own sampling interval. What running it across vendors needed on top of that direction is:
- per-CPU lockless rings between the NMI sample handler and the kdamond drain, one set per context, so each context drains only the reports of the events it armed,
- per-CPU events that follow CPU hotplug, armed when the context is set up and released when the kdamond stops,
- a per-PMU owner, so two contexts cannot claim the same PMU type,
- whichever address a PMU does report carried on the report and matched against the context's own address space, so one source serves a paddr or a vaddr context without a backend per address space.
This is tested with PEBS on Intel and IBS on AMD, both configured as perf_event attributes on a probe and using the perf core's event plumbing rather than per-vendor MSR code. A third source has already been written against damon_report_access(): Kunwu Chan's ARM SPE backend [5], which reaches it through an AUX buffer drained in process context instead of an overflow callback, and which the roadmap [2] places in its third milestone.
What the series adds
====================
1. mm/damon/paddr: remove page_fault access check primitive -- removes damon_pa_prepare_access_checks_faults() and its helpers, and damon_report_page_fault() and its caller do_damon_page() in mm/memory.c. Both predate this series; removed here because they are the only producer into the report buffer that patch 2 replaces.
2. mm/damon/core: replace the access report buffer with per-context rings -- the substrate. Per-CPU SPSC rings, one set per context, that an NMI-context source can publish into, replacing the global mutex-protected buffer, plus the kdamond-side drain that matches each report to a region by binary search over a per-target snapshot and adds it to that region's probe hits, at most once per sampling interval. The reports are data attribute samples and do not change nr_accesses. The address space of the target selects which address of a report is matched, and pid targets are filtered by thread group id.
3. mm/damon: add perf-event overflow handler feeding the report ring -- an ops-agnostic perf-event source whose overflow handler turns a PMU sample into a page-aligned report routed to the ring of the context that armed the event. It sets each address field the PMU reported as valid, so a PMU that reports a virtual address only can drive a virtual-address context, one that reports a physical address a physical-address context, and the same source serves either without a backend per address space. Per-CPU events are armed and released through cpuhp callbacks, a CPU whose counter cannot be created is left unsampled with a warning, and a per-PMU owner keeps two contexts from claiming the same PMU type.
4. mm/damon/ops-common: use probe-weighted score when probe weights are set -- lets a scheme's frequency subscore come from the probe hits, weighted per probe, so in data attributes-only mode what the sampler reported reaches the DAMOS priority score. With no weights set the subscore comes from the access rate as before.
5. mm/damon: add perf_event prep type, core lifecycle, and PMU arm/disarm -- the event lifecycle: a perf_event prep action carrying the PMU type, the event config and the sample attributes per probe, with per-CPU arming or, through a single_instance flag, one counter for a system-wide PMU. A single-instance counter is pinned to one online CPU and is not migrated if that CPU goes offline. A commit keeps a probe's running event when its perf attributes and list position are unchanged, so a weight-only commit leaves it untouched.
6. mm/damon/sysfs: expose perf_event prep attributes -- wires the perf_event prep attributes through the DAMON sysfs interface, exposing type, config, config1, config2, freq, sample_period, sample_freq, wakeup_events, precise_ip, sample_phys_addr, sample_weight_struct, exclude_kernel, exclude_hv and single_instance under the probe's preps/N/ directory. sample_weight_struct only requests the weight in each sample; DAMON does not use it yet. A perf_event probe cannot have probe filters.
7. mm/damon/tests/drain-kunit: kunit for report rings and ring drain -- unit tests for the rings and the drain: inject and drain, overflow on wrap, a report without an owning context dropped, per-context isolation, probe-index crediting, thread-group filtering, the address-space match, ring-full accounting, and reports counted as at most one probe hit per sampling interval with nr_accesses left unchanged, with and without probe weights. The sysfs checks of patch 6 are not covered by kunit.
8. mm/damon/core: cap the region merge threshold per target -- on the regular merge pass, also caps each target's threshold at a tenth of that target's own maximum merge score, so a high-traffic target cannot merge away the hot/cold boundary of a low-traffic target in the same context. The passes that bring the region count under max_nr_regions keep the escalated threshold.
9. mm/damon/core: apply probe_hits_wsum filters to node_eligible_mem_bp -- counts a region as eligible memory only if it also passes the scheme's probe_hits_wsum filters (SJ's DAMOS core filter), decided as core filters are but among those filters only, so the quota goal follows the regions a scheme selects in data attributes-only mode, where the access pattern cannot select them.
Patches 2-5 are the substrate; 6 is its sysfs surface; 7 covers them; 9 lets the node_eligible_mem_bp quota goal use what they monitor. Patch 8 applies on damon/next independently and could be taken on its own. Patch 1 applies on its own too, but is only needed with patch 2. Documentation is left out of this RFC, to follow once the design is
settled: the perf_event preparation action and its sysfs files, how its samples are counted, the node_eligible_mem_bp change, and marking the page fault based access check unsupported in the design document.
How the samples are counted
===========================
A perf_event probe follows the data attributes monitoring design. A region's probe hit count rises by one for each sampling interval in which the PMU sampled an access in it, the same per-interval bound a probe hit has for the samples DAMON takes itself, so the count stays within the samples per aggregation. Where DAMON's own probe tests one address per region, a perf hit means that at least one PMU sample landed somewhere in the region. No sample changes nr_accesses, which stays with the access check primitives. To act on the samples, a context sets a probe weight, which turns on data attributes-only monitoring:
DAMON merges regions and ages them by the weighted probe hits, and DAMOS schemes select regions with SJ's probe_hits_wsum filters. Patch 9 makes the node_eligible_mem_bp quota goal count the regions those filters select. The runs below use that mode.
Changes from v3
===============
In v3 [11] I made the drain raise a region's nr_accesses for each sample, so that a region the PMU sampled more often read as hotter. Kunwu Chan pointed out that this gives nr_accesses a scale that depends on the PMU and its sampling settings [10]. The data attributes monitoring design already has the place for such samples: a PMU sample is a data attribute sample, so v4 counts it as a probe hit, at most once per region per sampling interval, and leaves nr_accesses to the access check primitives.
The sashiko review of v3 is addressed as well, including bounds in the drain and in probe arming, the probe-weighted subscore computed in 64 bits, PERF_SAMPLE_DATA_SRC gating, sysfs locking and the CONFIG_DAMON_PERF_SOURCE=n case. Pid targets are now matched by the thread group id of the target task, probe_hits[] keeps its base width, and v3 patch 9 is dropped, since data attributes-only mode already turns the access checks off.
Changes from v2
===============
Following SJ's feedback on v2 [1]:
- The page-fault primitive is out of scope. The vaddr page-fault primitive, the global page-fault report ring and the partitioning of reports into probe classes are dropped; there is a single class of report ring, per context, fed only by perf-event probes.
- The CPU-number and folio-lock fixes (v2 patches 2 and 3) are dropped with the page-fault path they belonged to.
- The damos_node_eligible_mem_bp tracepoint (v2 patch 4) has been
decoupled from this series and sent separately against mm-new:
Message-ID: <[email protected]>
Link: https://lore.kernel.org/all/[email protected]/- Per-CPU rings are kept; SJ wrote "feel free to keep the per-CPU rings. As long as it is an RFC, please feel free to implement it in an easy-to-implement way."
As in v3, one point differs from what the v2 thread discussed. It scoped milestone 2 to physical addresses only, with the virtual-address parts deferred to phase 3. This version keeps virtual-address support, for the following reason: the concern that made the page-fault path a poor fit for milestone 2 is that it reaches into other mm code (the fault handler and mprotect). The virtual-address support here does not. It is confined to the DAMON report path: the overflow handler records the virtual address the PMU reports, and the drain matches it against the regions of the target whose thread group reported it. Nothing outside mm/damon/ changes for it, and in vaddr.c it only makes the software prep and apply paths skip event-driven probes. It is also what makes a PMU that reports only virtual addresses to the overflow handler, such as Intel PEBS, usable, and what lets a context scope tiering to a set of processes. If milestone 2 should stay physical-address only regardless, the vaddr handling can be taken out without affecting the physical-address path, and I am happy to do that in the next revision.
Patch 8 is new since v2 and was in v3. It keeps region merging from erasing the hot/cold boundary of a low-traffic target when the same context also monitors a high-traffic one, as configuration B below does. Patch 9 is new in this version; it is what configuration A below steers by in data attributes-only mode.
Changes from v1
===============
v2 [1] moved the series onto the data attributes monitoring (probe) infrastructure that had landed in mm-new after v1 [12]: a PMU became one more probe on a context, with its own weight and probe hits, instead of a mechanism of its own beside the ops set.
Build qualification
===================
Tested with CONFIG_DAMON_PERF_SOURCE and CONFIG_DAMON_KUNIT_TEST enabled; the series also builds with CONFIG_DAMON_PERF_SOURCE disabled.
Patch 1 removes the only code that sets MM_CP_DAMON (defined in include/linux/mm.h).
The check for it in mm/mprotect.c is left for a separate cleanup.
Userspace setup model
=====================
The runs were driven by an auto_tier subcommand added to damo on the branch below, which reads achieved bandwidth from resctrl MBM [6]. That tooling is not part of this posting; it is on
https://github.com/ravis-opensrc/damo/tree/damo/auto-tier-bw-2026-10-04
Configuration A: AMD IBS Op, paddr ops, system-wide
---------------------------------------------------
```
$ sudo mount -t resctrl resctrl /sys/fs/resctrl
$ sudo python3 tools/damon_tier_gen.py --hotness ibs \
--near_node 0 --far_node 4 \
--cold_demote --cold_demote_mode proactive \
-o tier.yaml
$ sudo damo auto_tier tier.yaml --bw_source resctrl --verbose
``` - Scope is the machine, not a process set. The distribution is steered through node_eligible_mem_bp [8] quota goals over each node's own physical ranges, which the generator reads from /proc/iomem.
- AMD Turin, DRAM on node 0 and a CXL node. IBS Op at a sample_period of 262144 with sample_phys_addr set.
- damo detects convergence of each step in this mode from the damos_node_eligible_mem_bp tracepoint, which has been sent separately against mm-new (<[email protected]>) and is not part of this series. The runs below were taken with it applied. Without it damo falls back to a coarser convergence check.
- Workload: multiload drives the hot set; a second process allocates 32 GiB on the near node, touches all of it once and then only a 64 MiB part, leaving the rest idle to age out for the demotion scheme to find.
Configuration B: Intel PEBS L3-miss, vaddr ops, per-PID
-------------------------------------------------------
```
$ sudo mount -t resctrl resctrl /sys/fs/resctrl
$ sudo python3 tools/damon_tier_gen.py --hotness pebs \
--pid $HOT_PID --pid $COLD_PID \
--near_node 0 --far_node 1 \
--cold_demote --cold_demote_mode proactive \
-o tier.yaml
$ sudo damo auto_tier tier.yaml --bw_source resctrl --verbose
``` - Scope is the named processes. Distribution steered through the hot scheme's DamosDest weights [9].
- Intel Granite Rapids, DRAM on node 0 and CXL on node 1. PEBS L3-miss at sample_freq 5003 with precise_ip 2.
- Same workload shape.
Both configurations run in data attributes-only mode, with probe weight 1, so DAMON adjusts and ages regions by the probe hits. The hot scheme selects regions with at least one weighted probe hit through a probe_hits_wsum filter. The cold scheme selects regions with none, and demotes those that have stayed so for its minimum age: a region that receives no perf-event samples keeps a zero weighted hit sum, so its age keeps growing.
- --bw_source resctrl reads achieved bandwidth from an MBM monitoring group; --verbose logs each step.
- Everything else -- intervals, schemes, filters, the probe's perf_event attributes -- is written by the generator from the command line shown: 5 ms sampling, 100 ms aggregation, 1 s ops update.
- Both configurations select proactive demotion.
- The hot-spread-only runs below use the same commands without the --cold_demote options and, in configuration B, without the idle process's --pid.
- The search is the algorithm described in [4].
What the runs show
==================
Per-node reference, each figure measured by binding the same workload to one node:
```
Granite Rapids, 64 threads x 8 GiB
node 0 1.0 TB DRAM DRAM only 269,574 MB/s
node 1 2.0 TB CXL CXL only 249,045 MB/s
Turin, 32 threads x 4 GiB
node 0 386 GB DRAM DRAM only 113,288 MB/s
node 4 1.0 TB CXL CXL only 39,280 MB/s
```Configuration B, virtual-address mode (PEBS, hot spread only):
--------------------------------------------------------------
```
MB/s climb
460k | * * * * * *
440k | *
420k | *
400k | *
380k | *
360k | *
340k | *
320k | *
300k | * *
280k |
260k | * *
+--+-----+-----+-----+-----+-----+-----+-----+-----+--
1 3 5 7 9 11 13 15 17
100 88 80 72 64 56 48 52 52
decision index, near-node share (%)
settled 52% near, 463,151 MB/s, after 16 decisions
```- Converges unattended from no given target to a distribution that beats either node on its own.
Configuration B, virtual-address mode (PEBS, cold demotion):
------------------------------------------------------------
- Cold demotion from PEBS aging alone (no page-fault primitive):
32,655 MB of the idle process's 32 GiB moved to the far node in 600 s. Regions that receive no samples keep a zero weighted hit sum, so they age, and the age-gated demotion scheme moves them.
Configuration A, physical-address mode (IBS, hot spread):
---------------------------------------------------------
```
MB/s climb
136k | *
134k | * * *
132k | * *
130k |
128k | *
126k |
124k |
122k | *
120k | *
118k |
+--+---+---+---+---+---+---+---+---+---
1 2 3 4 5 6 7 8 9
100 92 88 84 80 76 78 80 78
decision index, near-node share (%)
settled 78% near, 134,738 MB/s, after 8 decisions
```- 8 decisions to settle at 78%, from a start with almost everything on the near node.
Configuration A, physical-address mode (IBS, cold demotion):
------------------------------------------------------------
- Cold demotion from IBS aging alone: with the idle process as the only workload and only the demotion scheme configured, it moved all of its 32 GiB to the CXL node, 98% of it within the first minute.
What the runs establish
=======================
- A controller reading achieved bandwidth converges unattended, from a configuration naming no target, to a distribution that beats either node on its own, and holds it once found.
- Sampling-based aging (regions that receive no samples keep a zero weighted hit sum and age) identifies cold pages and a demotion scheme moves them, with PEBS and with IBS, without the page-fault primitive.
- One code path does both, steering node_eligible_mem_bp over physical ranges system-wide on one machine and DamosDest weights over a named process group on the other.
Beyond a CPU PMU
================
Nothing above is specific to PEBS or IBS. A source qualifies if it can report an accessed address to the ring. A CXL device's Hotness Monitoring Unit [7] or a custom monitoring unit on an accelerator reports exactly that, and a backend delivering those reports through a perf event reaches the same drain, the same probe hits and the same schemes already in the tree.
References
==========
[1] v2 of this series
https://lore.kernel.org/linux-mm/[email protected]/ [2] Roadmap for extending DAMON beyond pte-accessed bit https://lore.kernel.org/damon/[email protected]/ [3] mm/damon: introduce perf event based access check https://lore.kernel.org/damon/[email protected]/
[4] B. Tabatabai, R. Jonnalagadda et al., "Bandwidth Speaks, We Listen:
Dynamic Memory Interleaving for Tiering", ISMM 2026.
https://dl.acm.org/doi/10.1145/3814942.3816137
[5] mm/damon/perf: add ARM SPE AUX backend
https://lore.kernel.org/damon/[email protected]/
[6] A platform-independent subsystem for bandwidth information, and resctrl as that source
https://lore.kernel.org/linux-mm/[email protected]/
[7] CXL Hotness Monitoring Unit perf driver
https://lore.kernel.org/linux-mm/[email protected]/ [8] mm/damon: add node_eligible_mem_bp goal metric, merged for v7.2 https://lore.kernel.org/linux-mm/[email protected]/
[9] mm/damon/vaddr: allow interleaving in migrate_{hot,cold} actions, merged for v6.17
https://lore.kernel.org/linux-mm/[email protected]/
[10] Kunwu Chan on the nr_accesses scale of hardware-sampled reports (v3)
https://lore.kernel.org/all/[email protected]/ [11] v3 of this series https://lore.kernel.org/all/20261003-damon-perf-rfc-v3-send-2026-10-03-v3-0-0f00417b41bc@gmail.com/ [12] v1 of this series https://lore.kernel.org/damon/[email protected]/
---
- Link to v3: https://patch.msgid.link/20261003-damon-perf-rfc-v3-send-2026-10-03-v3-0-0f00417b41bc@gmail.com
---
Ravi Jonnalagadda (9):
mm/damon/paddr: remove page_fault access check primitive mm/damon/core: replace the access report buffer with per-context rings mm/damon: add perf-event overflow handler feeding the report ring mm/damon/ops-common: use probe-weighted score when probe weights are set mm/damon: add perf_event prep type, core lifecycle, and PMU arm/disarm mm/damon/sysfs: expose perf_event prep attributes mm/damon/tests/drain-kunit: kunit for report rings and ring drain mm/damon/core: cap the region merge threshold per target mm/damon/core: apply probe_hits_wsum filters to node_eligible_mem_bp
include/linux/damon.h | 145 +++++++- mm/damon/Kconfig | 19 + mm/damon/Makefile | 1 + mm/damon/core.c | 851 +++++++++++++++++++++++++++++++++++++------ mm/damon/ops-common.c | 19 +- mm/damon/paddr.c | 72 +--- mm/damon/perf_source.c | 429 ++++++++++++++++++++++ mm/damon/perf_source.h | 55 +++ mm/damon/sysfs-sample.c | 7 +- mm/damon/sysfs.c | 304 +++++++++++++++- mm/damon/tests/core-kunit.h | 2 +- mm/damon/tests/drain-kunit.h | 786 +++++++++++++++++++++++++++++++++++++++ mm/damon/tests/perf-kunit.h | 133 +++++++ mm/damon/vaddr.c | 15 +- mm/memory.c | 53 --- 15 files changed, 2625 insertions(+), 266 deletions(-)
---
base-commit: 9f1c290342ea4f24dc1be639ff3055716f829376
change-id: 20261003-damon-perf-rfc-v3-send-2026-10-03-b94adf49eb90
Best regards,
Signature · 1 line
Ravi Jonnalagadda <[email protected]>
RFC PATCH v4 1/9 mm/damon/paddr: remove page_fault access check primitive
The page_fault access check primitive reports faults through damon_report_page_fault() into the global, mutex-protected damon_access_reports[] buffer. A later patch in this series replaces that buffer with per-context rings fed only by perf-event probes, which leaves the page-fault producer with nowhere to report. Remove the producer here so no report is silently dropped.
Remove damon_pa_prepare_access_checks_faults() and its supporting damon_pa_change_protection()/damon_pa_change_protection_one() helpers, and the page_fault dispatch in damon_pa_prepare_access_checks(). Remove damon_report_page_fault() and its sole caller, do_damon_page(), along with the two page-fault-handler dispatch sites in mm/memory.c that selected it over the ordinary NUMA-hinting fault path.
Writing Y to the sysfs page_fault file now returns -EOPNOTSUPP, and core validation rejects a context with page_fault set, so a configuration cannot select a primitive that no longer reports and have every region read as cold. With page_fault gone, page_table is the only access check primitive left, so a context must enable it. This leaves MM_CP_DAMON with no user that sets it; its check in mm/mprotect.c is left for a separate cleanup.
--- include/linux/damon.h | 12 +---------- mm/damon/core.c | 24 +++------------------ mm/damon/paddr.c | 57 ------------------------------------------------- mm/damon/sysfs-sample.c | 7 +++--- mm/memory.c | 53 --------------------------------------------- 5 files changed, 8 insertions(+), 145 deletions(-)
include/linux/damon.h +1 -11
@@ -930,7 +930,7 @@ struct damon_attrs {* struct damon_primitives_enabled - Enablement of access sampling primitives. * * @page_table: Page table Accessed bits scanning. -* @page_fault: Page faults monitoring. +* @page_fault: Page faults monitoring. Not supported; must be false. * * Read &struct damon_sample_control for more details. */
@@ -1299,13 +1299,6 @@ int damon_call(struct damon_ctx *ctx, struct damon_call_control *control);int damos_walk (struct damon_ctx *ctx,struct damos_walk_control *control);void damon_report_access (struct damon_access_report *report); -#ifdef CONFIG_MMU -void damon_report_page_fault (struct vm_fault *vmf,bool huge_pmd); -#else -static inline void damon_report_page_fault (struct vm_fault *vmf,bool huge_pmd) -{ -} -#endif int damon_set_region_system_rams_default(struct damon_target *t, unsigned long *start, unsigned long *end,
@@ -1323,9 +1316,6 @@ unsigned long damon_alloced_bytes(void);static inline void damon_report_access (struct damon_access_report *report) { } -static inline void damon_report_page_fault (struct vm_fault *vmf,bool huge_pmd) -{ -}#endif /* CONFIG_DAMON */
mm/damon/core.c +3 -21
@@ -2087,7 +2087,9 @@ static int damon_commit_sample_filters(struct damon_sample_control *dst,static bool damon_primitives_enabled_invalid (struct damon_primitives_enabled *config) { -return config->page_table == config->page_fault; +if (config->page_fault) +return true; +return !config->page_table; } static int damon_commit_sample_control(
@@ -2544,26 +2546,6 @@ void damon_report_access(struct damon_access_report *report)mutex_unlock (&damon_access_reports_lock); } -#ifdef CONFIG_MMU -void damon_report_page_fault (struct vm_fault *vmf,bool huge_pmd) -{ -struct damon_access_report access_report = { - .vaddr = vmf->address, - .size =1 ,/* todo: set appripriately */ - .cpu =smp_processor_id (), - .tid =task_pid_vnr (current), - .is_write = vmf->flags &FAULT_FLAG_WRITE , - }; - -if (huge_pmd) - access_report.paddr =PFN_PHYS (pmd_pfn (vmf->orig_pmd)); -else - access_report.paddr =PFN_PHYS (pte_pfn (vmf->orig_pte)); - -damon_report_access (&access_report); -} -#endif -/* * Reset the aggregated monitoring results ('nr_accesses' of each region). */
mm/damon/paddr.c +0 -57
67 lines not on this page · raw message
mm/damon/sysfs-sample.c +4 -3
@@ -421,7 +421,9 @@ static ssize_t page_fault_store(struct kobject *kobj,if (err)return err; - primitives->page_fault = enable; +if (enable) +return -EOPNOTSUPP ; + primitives->page_fault = false;return count; }
@@ -590,8 +592,7 @@ int damon_sysfs_set_sample_control( { control->primitives_enabled.page_table = sysfs_sample->primitives->page_table; - control->primitives_enabled.page_fault = - sysfs_sample->primitives->page_fault; + control->primitives_enabled.page_fault = false;return damon_sysfs_set_sample_filters (control, sysfs_sample->filters);
mm/memory.c +0 -53
71 lines not on this page · raw message
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 1/9] mm/damon/paddr: remove page_fault access check primitive
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 22 lines
The
page_faultaccess check primitive reports faults throughdamon_report_page_fault()into the global, mutex-protected damon_access_reports[] buffer. A later patch in this series replaces that buffer with per-context rings fed only by perf-event probes, which leaves the page-fault producer with nowhere to report. Remove the producer here so no report is silently dropped.Remove
damon_pa_prepare_access_checks_faults()and its supporting damon_pa_change_protection()/damon_pa_change_protection_one() helpers, and thepage_faultdispatch indamon_pa_prepare_access_checks(). Removedamon_report_page_fault()and its sole caller,do_damon_page(), along with the two page-fault-handler dispatch sites inmm/memory.cthat selected it over the ordinary NUMA-hinting fault path.Writing Y to the sysfs
page_faultfile now returns-EOPNOTSUPP, and core validation rejects a context withpage_faultset, so a configuration cannot select a primitive that no longer reports and have every region read as cold. Withpage_faultgone,page_tableis the only access check primitive left, so a context must enable it. This leavesMM_CP_DAMONwith no user that sets it; its check inmm/mprotect.cis left for a separate cleanup.
Quoted 1 line
Signed-off-by Ravi Jonnalagadda <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=1
RFC PATCH v4 2/9 mm/damon/core: replace the access report buffer with per-context rings
In reply to Ravi Jonnalagaddadamon_report_access() queues reports into the global damon_access_reports[] buffer under a mutex, and kdamond applies them from there. A perf-event overflow handler runs in NMI context and cannot take that mutex, and the buffer has no other producer.
Replace the buffer with a per-context, per-CPU SPSC report ring (ctx->perf_rings) that an NMI-context producer can publish into, and a kdamond drain that credits regions from each ring's pending reports.
NMI safety: the producer uses a busy counter to drop re-entrant reports on the same CPU, publishes with smp_wmb() before advancing the head, and sets a pending-CPU bitmask with smp_mb__before_atomic() so the consumer catches any report published between the bit-clear and the READ_ONCE(head). The consumer publishes the tail with smp_store_release() after reading the entries, and the producer reads it with smp_load_acquire(), so a slot is not reused while it is still being read. A source allocates the ring before it arms its first perf event for the context, and damon_destroy_ctx() frees it after the events are released, so no in-flight NMI can reach freed storage. Per-CPU counters count the reports dropped because a ring was full or its busy guard was held, the reports drained into a region and those that matched none; the damon_get_*() accessors read them for the kunit tests.
The drain matches each report to a region by binary search over a per-target region snapshot built in ar.start order, the region-list invariant damon_credit_report_bsearch() relies on. Pid targets are matched by the thread group id of the target's task, so a target named by any of its threads matches, compared as the global pid number, since a producer may run in any pid namespace. Each drained report adds one to the region's probe_hits[] slot for its probe, at most once per sampling interval, the same bound a probe hit has for the samples DAMON takes itself; that keeps probe_hits[] within the samples per aggregation, as the code that splits, merges and rescales it assumes. A physical address is matched in the context's address unit. The reports are data attribute samples, so the drain does not change nr_accesses, which stays with the access check primitives. That leaves the access_reported flag and kdamond_apply_zero_access_report(), which served only the page fault primitive's reports, with no user; remove them.
--- include/linux/damon.h | 102 ++++++++- mm/damon/core.c | 591 ++++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 605 insertions(+), 88 deletions(-)
include/linux/damon.h +99 -3
@@ -17,9 +17,19 @@#define DAMON_MIN_REGION_SZ PAGE_SIZE/* Maximum number of monitoring probes. */ #define DAMON_MAX_PROBES (4) +/* +* Sentinel value for damon_access_report.probe_idx: 0 means no probe +* attribution (matches zero-init of struct damon_access_report on the stack). +* Perf-event probe indices start at 1. +*/ +#define DAMON_PROBE_IDX_NONE 0/* Max priority score for DAMON-based operation schemes */ #define DAMOS_MAX_SCORE (99) +/* Per-CPU SPSC ring: size must be a power of two. */ +#define DAMON_REPORT_RING_SIZE 256 +#define DAMON_REPORT_RING_MASK (DAMON_REPORT_RING_SIZE - 1) +/** * struct damon_addr_range - Represents an address region of [@start, @end). * @start: Start address of the region (inclusive).
@@ -74,7 +84,9 @@ struct damon_region {/* for age calculation. */ unsigned int last_nr_accesses;unsigned char last_probe_hits[DAMON_MAX_PROBES ]; -bool access_reported; +/* probes already credited in sampling interval probes_reported_sis */ +unsigned long probes_reported_sis; +unsigned char probes_reported; };/**
@@ -110,7 +122,18 @@ struct damon_target {* @size: The size of the accessed address range. * @cpu: The id of the CPU that made the access. * @tid: The task id of the task that made the access. +* @tgid: The thread group id of the task that made the access, in +* the initial pid namespace. A monitoring target created +* for a process is matched against it. * @is_write: Whether the access is write. +* @probe_idx: 1-based index of the reporting probe; the drain credits +* probe_hits[@probe_idx - 1]. Set by the reporting +* source, so the drain needs no list walk. +* 0 is reserved (no probe attribution; matches zero-init); +* perf-event probe indices start at 1. +* @ctx: Context whose report ring receives the report; set by +* the reporting source. A report with no context is +* dropped by damon_report_access(). * * Any DAMON API callers that notified access events can report the information * to DAMON using damon_report_access(). This struct contains the reporting
@@ -122,11 +145,49 @@ struct damon_access_report {unsigned long size;unsigned int cpu;pid_t tid; +pid_t tgid;bool is_write; +int probe_idx; +struct damon_ctx *ctx;/* private: */ unsigned long report_jiffies;/* when this report is made */ }; +/** +* struct damon_report_ring - Per-CPU SPSC ring for NMI-safe access reports. +* +* @head: Write index; updated by the NMI producer. +* @tail: Read index; updated by the kdamond consumer. +* @entries: Ring buffer entries. +* +* One ring per CPU, per context with a perf-event probe. The producer +* (NMI overflow handler) writes to @head; the consumer (kdamond) reads +* from @tail. Both indices are unsigned and wrap modulo +* DAMON_REPORT_RING_SIZE. +*/ +struct damon_report_ring { +unsigned int head;/* written by producer (NMI) */ +unsigned int tail/* written by consumer (kdamond) */ +____cacheline_aligned_in_smp ; +struct damon_access_report entries[DAMON_REPORT_RING_SIZE ] +____cacheline_aligned_in_smp ; +}; + +/* +* struct damon_target_lookup - Cached, sorted region snapshot for one target. +* @regions: Array of region pointers, sorted by ar.start (address order). +* @nr_regions: Number of entries in @regions. +* @tgid: Thread group id of a pid target's task; 0 if it has none. +* +* Built once per drain by damon_build_target_lookup() so the ring drain can +* binary-search a target's regions instead of walking the list. +*/ +struct damon_target_lookup { +struct damon_region **regions; +unsigned int nr_regions; +pid_t tgid; +}; +/** * enum damos_action - Represents an action of a Data Access Monitoring-based * Operation Scheme.
@@ -871,9 +932,12 @@ struct damon_filter {* struct damon_probe - Data region attribute probe. * * @weight: Relative priority of the attribute for this probe. +* @event_driven: Whether the probe's hits arrive through the report ring +* drain rather than the apply_probes callback. */ struct damon_probe {unsigned int weight; +bool event_driven;/* private: */ /* Preparation actions to apply to each probing memory. */ struct list_head preps;
@@ -1091,6 +1155,29 @@ struct damon_ctx {/* @rnd_state: Per-ctx PRNG state for damon_rand(). */ struct rnd_state rnd_state; + +/* Reusable drain-loop snapshot buffer (avoids per-tick kmalloc). */ +struct { +struct damon_target_lookup *lookups; +unsigned int nr_lookups; +struct damon_region **region_buf; +unsigned int region_buf_cap; + } drain_snapshot; + +/* +* Per-context perf-event report ring. A perf overflow handler carries +* a pointer to the ctx that armed it (damon_access_report.ctx), so its +* reports route to this ring and two perf-driven ctxs never share one. +* +* A source allocates it with damon_ctx_alloc_perf_ring() before it +* arms the first perf event of the ctx, and damon_destroy_ctx() frees +* it after the events are released, so no in-flight NMI can reach +* freed storage. +* While perf_rings is NULL, every perf report for the ctx is dropped. +*/ +struct damon_report_ring __percpu *perf_rings; +int __percpu *perf_ring_busy; +cpumask_t perf_pending; };/* Get a random number in [@l, @r) using @ctx's lockless PRNG. */
@@ -1209,6 +1296,7 @@ void damon_destroy_filter(struct damon_filter *f);struct damon_probe *damon_new_probe (void );void damon_add_probe (struct damon_ctx *ctx,struct damon_probe *probe); +bool damon_has_event_driven_probes (struct damon_ctx *ctx);struct damon_region *damon_new_region (unsigned long start,unsigned long end); unsigned int damon_nr_accesses_mvsum(struct damon_region *r,
@@ -1298,13 +1386,20 @@ int damon_kdamond_pid(struct damon_ctx *ctx);int damon_call (struct damon_ctx *ctx,struct damon_call_control *control);int damos_walk (struct damon_ctx *ctx,struct damos_walk_control *control); -void damon_report_access (struct damon_access_report *report); +bool damon_report_access (struct damon_access_report *report); +int damon_ctx_alloc_perf_ring (struct damon_ctx *ctx);int damon_set_region_system_rams_default (struct damon_target *t,unsigned long *start,unsigned long *end,unsigned long addr_unit,unsigned long min_region_sz); +unsigned long damon_get_report_overflow (void ); +unsigned long damon_get_report_ring_full (void ); +unsigned long damon_get_report_busy_drop (void ); +unsigned long damon_get_samples_drained (void ); +unsigned long damon_get_samples_no_region (void ); +#ifdef CONFIG_ACMA unsigned long damon_alloced_bytes (void );
@@ -1313,8 +1408,9 @@ unsigned long damon_alloced_bytes(void);#else /* CONFIG_DAMON */ -static inline void damon_report_access (struct damon_access_report *report) +static inline bool damon_report_access (struct damon_access_report *report) { +return false; }#endif /* CONFIG_DAMON */
mm/damon/core.c +506 -85
665 lines not on this page · raw message
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 2/9] mm/damon/core: replace the access report buffer with per-context rings
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 20 lines
damon_report_access()queues reports into the global damon_access_reports[] buffer under a mutex, and kdamond applies them from there. A perf-event overflow handler runs in NMI context and cannot take that mutex, and the buffer has no other producer.Replace the buffer with a per-context, per-CPU SPSC report ring (
ctx->perf_rings) that an NMI-context producer can publish into, and a kdamond drain that credits regions from each ring's pending reports.NMI safety: the producer uses a busy counter to drop re-entrant reports on the same CPU, publishes with
smp_wmb()before advancing the head, and sets a pending-CPU bitmask withsmp_mb__before_atomic()so the consumer catches any report published between the bit-clear and theREAD_ONCE(head). The consumer publishes the tail withsmp_store_release()after reading the entries, and the producer reads it withsmp_load_acquire(), so a slot is [ ... ]
theaccess_reportedflag andkdamond_apply_zero_access_report(), which served only the page fault primitive's reports, with no user; remove them.
Quoted 1 line
Signed-off-by Ravi Jonnalagadda <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=2
RFC PATCH v4 3/9 mm/damon: add perf-event overflow handler feeding the report ring
In reply to Ravi JonnalagaddaAdd mm/damon/perf_source.c, an ops-agnostic perf-event source that turns PMU overflow samples into DAMON access reports. The overflow handler runs in NMI context and reports through damon_report_access(), so it works with either paddr or vaddr ops.
Each armed event carries its owning context, set when the probe is set up, and the handler routes every report to that context's perf ring. Setup allocates the ring before arming the first counter, so the handler always finds one. Teardown clears the event's context with a release store before releasing the counters, and the handler reads it with a matching acquire load, so an overflow racing teardown drops its sample instead of reporting into a context that is going away.
The handler sets whichever address fields the PMU provides: paddr when PERF_SAMPLE_PHYS_ADDR is set, vaddr when PERF_SAMPLE_ADDR is set, plus the CPU it runs on. Both addresses are page aligned, matching the PAGE_SIZE report size, so a sample that lands in the last page of a region is not rejected by the drain as straddling the region end. The drain matches on whichever address the context's targets use. The handler reports both the thread id and the thread group id, because a VA-only PMU samples whichever thread of a process happened to access memory while the drain matches a target created for that process. The thread group id is the global one, which is what the drain compares the target's pid with.
Per-CPU perf events are armed and released through cpuhp callbacks, so a CPU coming online while a probe is armed gets a counter and a CPU going offline releases its own. A CPU on which the counter cannot be created is left unsampled with a warning, since failing the online callback would block the CPU from coming online.
A probe with event_driven set has its hits credited through the report-ring drain rather than the apply_probes vtable. Both ops sets honour that flag in their probe vtables: an event-driven probe has no software prep action, and is skipped in the apply_probes loop, so the drain is the only thing that credits its probe_hits[]. When no probe of the context is sampled by DAMON itself, the apply_probes vtable also skips the per-region folio lookup or page table walk.
damon_perf_probe_setup() computes probe_idx by walking ctx->probes, assigning 1-based indices because 0 is the zero-init sentinel DAMON_PROBE_IDX_NONE, and the overflow handler warns once if it sees 0.
A refcounted per-PMU owner tracks which context owns each PMU type: a second context claiming the same type gets -EBUSY, and ownership is released when the last probe for that type is torn down.
--- include/linux/damon.h | 1 + mm/damon/Kconfig | 19 +++ mm/damon/Makefile | 1 + mm/damon/core.c | 18 +++ mm/damon/paddr.c | 15 +- mm/damon/perf_source.c | 378 +++++++++++++++++++++++++++++++++++++++++++++++++ mm/damon/perf_source.h | 25 ++++ mm/damon/vaddr.c | 15 +- 8 files changed, 469 insertions(+), 3 deletions(-)
include/linux/damon.h +1 -0
@@ -1297,6 +1297,7 @@ void damon_destroy_filter(struct damon_filter *f);struct damon_probe *damon_new_probe (void );void damon_add_probe (struct damon_ctx *ctx,struct damon_probe *probe);bool damon_has_event_driven_probes (struct damon_ctx *ctx); +bool damon_has_sampling_probes (struct damon_ctx *ctx);struct damon_region *damon_new_region (unsigned long start,unsigned long end); unsigned int damon_nr_accesses_mvsum(struct damon_region *r,
mm/damon/Kconfig +19 -0
@@ -64,6 +64,25 @@ config DAMON_PADDR This builds the default data access monitoring operations for DAMON that works for the physical address space. +config DAMON_PERF_SOURCE + bool "perf-event source for DAMON probes" + depends on DAMON && PERF_EVENTS + help + Provides a PMU-agnostic perf-event overflow handler that feeds + physical-address and virtual-address access reports into DAMON via + damon_report_access(). Needed for DAMON probes backed by an + address-sampling PMU. + + The overflow handler is NMI-safe: it writes to a per-CPU SPSC + ring rather than taking any lock. The PMU is selected at probe + creation time via perf_event_attr (e.g. AMD IBS Op, Intel PEBS). + + A given PMU type may be driven by at most one DAMON context at a + time; damon_perf_probe_setup() returns -EBUSY if another context + already owns that PMU type. Distinct contexts may each drive + different PMUs concurrently, each draining its own per-context + report ring. + config DAMON_VADDR_KUNIT_TEST bool "Test for DAMON operations" if !KUNIT_ALL_TESTS depends on DAMON_VADDR && KUNIT=y
mm/damon/Makefile +1 -0
@@ -9,3 +9,4 @@ obj-$(CONFIG_DAMON_RECLAIM) += modules-common.o reclaim.o obj-$(CONFIG_DAMON_LRU_SORT) += modules-common.o lru_sort.o obj-$(CONFIG_DAMON_STAT) += modules-common.o stat.o obj-$(CONFIG_DAMON_ACMA) += modules-common.o acma.o +obj-$(CONFIG_DAMON_PERF_SOURCE) += perf_source.o
mm/damon/core.c +18 -0
@@ -364,6 +364,24 @@ bool damon_has_event_driven_probes(struct damon_ctx *ctx)return false; } +/** +* damon_has_sampling_probes() - return true if @ctx has a probe that DAMON +* samples itself, that is, one that is not event-driven. +* @ctx: the DAMON context whose probes are inspected. +* +* Return: true if @ctx has a probe that is not event-driven. +*/ +bool damon_has_sampling_probes (struct damon_ctx *ctx) +{ +struct damon_probe *p; + +damon_for_each_probe (p, ctx) { +if (!p->event_driven) +return true; + } +return false; +} +/* Does @ctx drain a perf report ring? */ static bool damon_drains_ring_perf (struct damon_ctx *ctx) {
mm/damon/paddr.c +14 -1
@@ -118,6 +118,10 @@ static void damon_pa_prep_probes_region(struct damon_region *r, {struct damon_prep *p; +/* event-driven probes have no software prep */ +if (probe->event_driven) +return ; +damon_for_each_prep (p, probe) {switch (p->action) {case DAMON_PREP_SET_PGIDLE :
@@ -193,6 +197,7 @@ static unsigned int damon_pa_apply_probes(struct damon_ctx *ctx,struct damon_region *r;struct damon_probe *p;unsigned int max_wsum =0 ; +bool sampling =damon_has_sampling_probes (ctx);damon_for_each_target (t, ctx) {damon_for_each_region (r, t) {
@@ -203,16 +208,24 @@ static unsigned int damon_pa_apply_probes(struct damon_ctx *ctx,if (set_samples) r->sampling_addr =damon_rand (ctx, r->ar.start, r->ar.end); +if (!sampling) + goto wsum; pa =damon_pa_phys_addr (r->sampling_addr, ctx->addr_unit); folio =damon_get_folio (PHYS_PFN (pa));damon_for_each_probe (p, ctx) { -if (damon_pa_filter_pass (folio, p)) +/* +* Event-driven probes are credited by the ring +* drain; only sampling-based probes are here. +*/ +if (!p->event_driven && +damon_pa_filter_pass (folio, p)) r->probe_hits[i]++; i++; }if (folio)folio_put (folio); +wsum:if (return_max_wsum) max_wsum =max (damon_probe_hits_wsum (r, false, false, ctx), max_wsum);
mm/damon/perf_source.c new file +378 -0
378 lines not on this page · raw message
mm/damon/perf_source.h new file +25 -0
@@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* DAMON perf-event source - public interface +* +* Callers that register perf-event probes include this header. +*/ + +#ifndef _DAMON_PERF_SOURCE_H +#define _DAMON_PERF_SOURCE_H + +#ifdef CONFIG_DAMON_PERF_SOURCE + +#include <linux/damon.h> +#include <linux/perf_event.h> + +struct damon_perf_probe_event ; + +int damon_perf_probe_setup (struct damon_ctx *ctx, +struct damon_probe *probe, +struct damon_perf_probe_event *event); +void damon_perf_probe_teardown (struct damon_ctx *ctx, +struct damon_perf_probe_event *event); + +#endif /* CONFIG_DAMON_PERF_SOURCE */ +#endif /* _DAMON_PERF_SOURCE_H */
mm/damon/vaddr.c +13 -2
@@ -490,6 +490,10 @@ static void damon_va_prep_probe_region(struct damon_ctx *ctx, {struct damon_prep *p; +/* event-driven probes have no software prep */ +if (probe->event_driven) +return ; +damon_for_each_prep (p, probe) {switch (p->action) {case DAMON_PREP_SET_PGIDLE :
@@ -594,7 +598,12 @@ static void damon_va_probe_folio(struct damon_ctx *ctx,int i =0 ;damon_for_each_probe (probe, ctx) { -if (damon_va_filter_pass (folio, probe, pte, pmd, mm, +/* +* Event-driven probes are credited by the ring drain; only +* sampling-based probes are here. +*/ +if (!probe->event_driven && +damon_va_filter_pass (folio, probe, pte, pmd, mm, r->sampling_addr)) r->probe_hits[i]++; i++;
@@ -703,6 +712,7 @@ static unsigned int damon_va_apply_probes(struct damon_ctx *ctx,struct mm_struct *mm;struct damon_region *r;unsigned int max_wsum =0 ; +bool sampling =damon_has_sampling_probes (ctx);damon_for_each_target (t, ctx) { mm =damon_get_mm (t);
@@ -710,7 +720,8 @@ static unsigned int damon_va_apply_probes(struct damon_ctx *ctx,if (set_samples) r->sampling_addr =damon_rand (ctx, r->ar.start, r->ar.end); -__damon_va_apply_probes (ctx, mm, r); +if (sampling) +__damon_va_apply_probes (ctx, mm, r);if (return_max_wsum) max_wsum =max (damon_probe_hits_wsum (r, false, false, ctx), max_wsum);
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 3/9] mm/damon: add perf-event overflow handler feeding the report ring
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] mm: damon-perf drops valid memory accesses at physical or virtual page 0 - [Medium] mm: damon-perf…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] mm: damon-perf drops valid memory accesses at physical or virtual page 0
- [Medium] mm: damon-perf setup silently succeeds even if PMU event creation fails on all CPUs --
commit 8f5b12d04ef4011765be3438258e3b2a5a8d8eb7
Author: Ravi Jonnalagadda <[email protected]>
mm/damon: add perf-event overflow handler feeding the report ring
This patch adds a PMU-agnostic perf-event overflow handler for DAMON. It routes physical and virtual address access samples from a perf-event into a per-context report ring.
Quoted 5 lines
mm/damon/perf_source.c new file +0
-0
[ ... ]
Quoted 4 lines
mm/damon/perf_source.c new file +4
-0+static void damon_perf_overflow (struct perf_event *perf_event, +struct perf_sample_data *data, +struct pt_regs *regs) +{
[ ... ]
mm/damon/perf_source.c line 93
Quoted 7 lines
mm/damon/perf_source.c new file +7
-0+if (data->sample_flags &PERF_SAMPLE_PHYS_ADDR ) + report.paddr = data->phys_addr &PAGE_MASK ; +if (data->sample_flags &PERF_SAMPLE_ADDR ) + report.vaddr = data->addr &PAGE_MASK ; + +if (!report.paddr && !report.vaddr) +return ;
[Severity: High]
Does this check mistakenly drop legitimate accesses to physical or virtual page 0? If only PERF_SAMPLE_PHYS_ADDR is requested, accesses to the first physical page will have report.paddr == 0 and report.vaddr == 0, causing this logic to silently discard valid memory accesses.
Quoted 2 lines
mm/damon/perf_source.c new file +2
-0+ +if (data->sample_flags &PERF_SAMPLE_DATA_SRC )
[ ... ]
Quoted 2 lines
mm/damon/perf_source.c new file +2
-0+static int damon_perf_cpu_online (unsigned int cpu,struct hlist_node *node) +{
[ ... ]
Quoted 13 lines
mm/damon/perf_source.c new file +13
-0+ perf_event =perf_event_create_kernel_counter (&attr, cpu,NULL , + damon_perf_overflow, + event); +if (IS_ERR (perf_event)) { +pr_warn_ratelimited ("damon-perf: cpu %u event create failed: %ld\n" , + cpu,PTR_ERR (perf_event)); +return 0 ; + } +per_cpu (*perf->event, cpu) = perf_event; + +perf_event_enable (perf_event); +return 0 ; +}
[ ... ]
Quoted 4 lines
mm/damon/perf_source.c new file +4
-0+int damon_perf_probe_setup (struct damon_ctx *ctx, +struct damon_probe *probe, +struct damon_perf_probe_event *event) +{
[ ... ]
mm/damon/perf_source.c line 301
Quoted 6 lines
mm/damon/perf_source.c new file +6
-0+ err =cpuhp_state_add_instance (damon_perf_cpuhp_state, + &event->hlist_node); +if (err) + goto free_event; + +return 0 ;
[Severity: Medium]
Could this setup silently succeed even if PMU event creation fails on all CPUs?
In damon_perf_cpu_online(), when perf_event_create_kernel_counter() returns an error, it rightly returns 0 to avoid breaking CPU hotplug. However, damon_perf_probe_setup() relies on the return value of cpuhp_state_add_instance().
If a user provides an invalid PMU configuration, event creation will fail everywhere, but the setup will succeed without error, leaving DAMON running without any armed counters. Should there be a check to verify that at least one counter was successfully created?
Quoted 3 lines
mm/damon/perf_source.c new file +3
-0+ +free_event: +free_percpu (perf->event);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=3
RFC PATCH v4 4/9 mm/damon/ops-common: use probe-weighted score when probe weights are set
In reply to Ravi JonnalagaddaWhen probe weights are configured (damon_has_probe_weights()), use damon_probe_hits_wsum() for the frequency subscore in damon_hot_score() instead of damon_nr_accesses_mvsum(). This routes the probe hits of a perf-event probe into the DAMOS priority score.
Make damon_has_probe_weights() non-static and declare it in damon.h so ops-common.c can call it.
Scale the weighted-hit sum in 64 bits and clamp the result to DAMON_MAX_SUBSCORE, so a large sum cannot overflow the subscore range.
--- include/linux/damon.h | 1 + mm/damon/core.c | 2 +- mm/damon/ops-common.c | 19 ++++++++++++++++--- 3 files changed, 18 insertions(+), 4 deletions(-)
include/linux/damon.h +1 -0
@@ -1306,6 +1306,7 @@ unsigned char damon_probe_hits_mvsum(int probe_idx, struct damon_region *r, struct damon_ctx *ctx);unsigned int damon_probe_hits_wsum (struct damon_region *r,bool last,bool mv,struct damon_ctx *ctx); +bool damon_has_probe_weights (struct damon_ctx *c);int damon_set_regions (struct damon_target *t,struct damon_addr_range *ranges,unsigned int nr_ranges,unsigned long min_region_sz);
mm/damon/core.c +1 -1
@@ -331,7 +331,7 @@ static struct damon_probe *damon_nth_probe(int n, struct damon_ctx *ctx)return NULL ; } -static bool damon_has_probe_weights (struct damon_ctx *c) +bool damon_has_probe_weights (struct damon_ctx *c) {struct damon_probe *p;
mm/damon/ops-common.c +16 -3
@@ -172,9 +172,22 @@ int damon_hot_score(struct damon_ctx *c, struct damon_region *r,unsigned int age_weight = s->quota.weight_age;int hotness; - freq_subscore =mult_frac (damon_nr_accesses_mvsum (r, c), -DAMON_MAX_SUBSCORE , -damon_nr_samples_per_aggr (&c->attrs)); +if (damon_has_probe_weights (c)) { +unsigned int wsum =damon_probe_hits_wsum (r, false, true, c); +u64 subscore =div_u64 ((u64 )wsum *DAMON_MAX_SUBSCORE , +damon_nr_samples_per_aggr (&c->attrs)); + +/* +* Score by the weighted probe hits. Clamp to +* DAMON_MAX_SUBSCORE so a large weighted-hit sum cannot +* overflow the subscore range. +*/ + freq_subscore =min_t (u64, subscore,DAMON_MAX_SUBSCORE ); + }else { + freq_subscore =mult_frac (damon_nr_accesses_mvsum (r, c), +DAMON_MAX_SUBSCORE , +damon_nr_samples_per_aggr (&c->attrs)); + } age_in_sec =div_u64 ((u64 )r->age * c->attrs.aggr_interval,USEC_PER_SEC );
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 4/9] mm/damon/ops-common: use probe-weighted score when probe weights are set
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 5 lines
When probe weights are configured (
damon_has_probe_weights()), usedamon_probe_hits_wsum()for the frequency subscore indamon_hot_score()instead ofdamon_nr_accesses_mvsum(). This routes the probe hits of a perf-event probe into the DAMOS priority score.
Quoted 7 lines
Make
damon_has_probe_weights()non-static and declare it indamon.hsoops-common.ccan call it.Scale the weighted-hit sum in 64 bits and clamp the result to
DAMON_MAX_SUBSCORE, so a large sum cannot overflow the subscore range.Signed-off-by Ravi Jonnalagadda <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=4
RFC PATCH v4 5/9 mm/damon: add perf_event prep type, core lifecycle, and PMU arm/disarm
In reply to Ravi JonnalagaddaThe prep interface exposes a single preparation action, set_pgidle, which arms the page-idle scan used by the software access check. There is no way for user space to configure a probe whose access information comes from a hardware PMU sampling facility, even though the perf-event source (CONFIG_DAMON_PERF_SOURCE) already provides the NMI-safe overflow handler, the report ring, and the probe setup/teardown lifecycle to consume such samples.
Add a DAMON_PREP_PERF_EVENT prep action carrying a subset of perf_event_attr (type, config, config1, config2, sampling period or frequency, wakeup_events, precise_ip, sample_phys_addr, sample_weight_struct, exclude_kernel, exclude_hv), and wire it through include/linux/damon.h, mm/damon/perf_source.h and mm/damon/core.c. A probe built with a perf_event prep is to be event driven, which the sysfs patch that follows sets: DAMON does not walk it in the apply_probes vtable; instead the PMU samples memory accesses and feeds region hit counters through the report ring.
The prep also carries how many counters the PMU needs. A per-CPU PMU is armed by adding a cpuhp instance, which opens one kernel counter on every online CPU. A system-wide PMU is a single hardware unit served by exactly one counter, so a single_instance flag opens one kernel counter pinned to a fixed online CPU and bypasses the cpuhp fan-out. The pin names an online CPU because a kernel counter with no task must be bound to one.
The PMU is only armed when building the context that will actually run. A param_ctx built for a commit carries the attributes but defers arming, because arming a throwaway context would collide with the running context's per-PMU ownership, and a commit_live flag distinguishes the dry-run validation pass from the real commit. The commit path hands the armed event between the running probe and the committed source probe, keeping the running event untouched on the common weight-only commit and re-arming only when the perf attributes change or the probe's list position no longer matches the position its running event's probe_idx was computed for; a probe reorder with unchanged attributes still needs a re-arm, or the event keeps crediting probe_hits[] at its old index.
The armed event is released both when monitoring is turned off, from kdamond_fn()'s exit path after damon_destroy_targets(), and when the context is destroyed. Turning monitoring back on through sysfs builds a fresh context, which arms a new event from the probe attributes. The teardown barrier the overflow handler pairs with, a release store of event->ctx = NULL, covers the single-instance path as well as the per-CPU one. damon_perf_probe_teardown() also frees the event descriptor, which the probe owns from the time the descriptor is attached to it.
__damon_commit_ctx() and damon_commit_probes() gain the commit_live flag described above, false for the validation and test-context passes and true for the real commit; its one existing kunit call site in mm/damon/tests/core-kunit.h is updated to pass false. Wiring these attributes through sysfs is a separate, following commit.
--- include/linux/damon.h | 29 ++++++++ mm/damon/core.c | 154 ++++++++++++++++++++++++++++++++++++++++--- mm/damon/perf_source.c | 157 +++++++++++++++++++++++++++++--------------- mm/damon/perf_source.h | 32 ++++++++- mm/damon/tests/core-kunit.h | 2 +- 5 files changed, 310 insertions(+), 64 deletions(-)
include/linux/damon.h +29 -0
@@ -868,18 +868,44 @@ struct damon_intervals_goal {* enum damon_prep_action - DAMON probing preparation action. * * @DAMON_PREP_SET_PGIDLE: Set the probing memory as idle page. +* @DAMON_PREP_PERF_EVENT: Back the probe with a perf event. */ enum damon_prep_action {DAMON_PREP_SET_PGIDLE , +DAMON_PREP_PERF_EVENT , };/** * struct damon_prep - DAMON probing preparation request. * * @action: Action to do to the probing memory for the preparation. +* @perf: perf_event_attr subset selecting the PMU and sampling +* parameters. Only valid when @action is DAMON_PREP_PERF_EVENT. +* +* A DAMON_PREP_PERF_EVENT prep turns the containing &struct damon_probe into +* an event-driven probe: a kernel perf event (e.g. AMD IBS Op, Intel PEBS) +* samples memory accesses and feeds them into the probe hit counters via the +* report ring. The @perf fields are copied into a perf_event_attr when the +* kdamond is turned on, or when a commit changes them. */ struct damon_prep {enum damon_prep_action action; +struct { +u32 type; +u64 config; +u64 config1; +u64 config2; +u64 sample_period; +u64 sample_freq; +u32 wakeup_events; +u32 precise_ip; +bool sample_phys_addr; +bool sample_weight_struct; +bool exclude_kernel; +bool exclude_hv; +bool freq; +bool single_instance; + } perf;/* private: */ /* siblings list. */ struct list_head list;
@@ -934,10 +960,13 @@ struct damon_filter {* @weight: Relative priority of the attribute for this probe. * @event_driven: Whether the probe's hits arrive through the report ring * drain rather than the apply_probes callback. +* @perf_priv: Perf-event state of an event-driven probe, released by +* damon_perf_probe_teardown(). */ struct damon_probe {unsigned int weight;bool event_driven; +void *perf_priv;/* private: */ /* Preparation actions to apply to each probing memory. */ struct list_head preps;
mm/damon/core.c +145 -9
252 lines not on this page · raw message
mm/damon/perf_source.c +104 -53
203 lines not on this page · raw message
mm/damon/perf_source.h +31 -1
@@ -13,7 +13,37 @@#include <linux/damon.h> #include <linux/perf_event.h> -struct damon_perf_probe_event ; +/* +* PMU event attributes for a perf-event probe. A subset of perf_event_attr +* chosen at probe creation time to select the PMU (AMD IBS, Intel PEBS, ...) +* and its sampling parameters. +*/ +struct damon_perf_event_attr { +u32 type; +u64 config; +u64 config1; +u64 config2; +bool sample_phys_addr; +bool sample_weight_struct; +bool exclude_kernel; +bool exclude_hv; +bool freq; +/* system-wide PMU: open one counter, not one per CPU */ +bool single_instance; +u64 sample_freq; +u64 sample_period; +u32 wakeup_events; +u32 precise_ip; +}; + +struct damon_perf_probe_event { +struct damon_perf_event_attr attr; +struct damon_ctx *ctx;/* owning ctx for ring routing; set at setup */ +void *priv;/* struct damon_perf_probe_state * */ +struct hlist_node hlist_node; +/* 1-based probe index for probe_hits[]; set at registration */ +int probe_idx; +}; int damon_perf_probe_setup(struct damon_ctx *ctx, struct damon_probe *probe,
mm/damon/tests/core-kunit.h +1 -1
@@ -1590,7 +1590,7 @@ static void damon_test_commit_probes_for(struct kunit *test,kunit_skip (test,"src alloc fail" ); } - err =damon_commit_probes (dst, src); + err =damon_commit_probes (dst, src, false);KUNIT_EXPECT_EQ (test, err,0 );if (err) goto out;
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 5/9] mm/damon: add perf_event prep type, core lifecycle, and PMU arm/disarm
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] mm/damon: PMU configuration bypasses perf_event_open security checks - [Medium] mm/damon…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] mm/damon: PMU configuration bypasses perf_event_open security checks
- [Medium] mm/damon: perf_priv is permanently lost on kdamond stop
- [Low] mm/damon: uninitialized heap garbage in newly added damon_prep objects --
commit bb2fe5a24d18d1ea5740c8beef1d58359ce0c535
Author: Ravi Jonnalagadda <[email protected]>
Subject: mm/damon: add perf_event prep type, core lifecycle, and PMU arm/disarm
This patch adds a new DAMON_PREP_PERF_EVENT preparation action to allow DAMON probes to be event-driven via a hardware PMU. It updates the core lifecycle to manage PMU arming/disarming and handles both per-CPU and single-instance models.
mm/damon/core.c static int damon_commit_targets( · line 2044
Quoted 10 lines
mm/damon/core.c +1
-0@@ -2016,6 +2040,7 @@ static int damon_commit_targets(static void damon_commit_prep (struct damon_prep *dst,struct damon_prep *src) { dst->action = src->action; + dst->perf = src->perf; }
[Severity: Low]
Does this commit path properly initialize new damon_prep objects?
While the above handles updating existing prep objects, damon_commit_preps() adds newly allocated prep objects for any new entries:
new_prep = damon_new_prep(src_prep->action); if (!new_prep) return -ENOMEM; damon_add_prep(dst, new_prep);
Since damon_new_prep() uses kmalloc_obj() without zero-initialization, the newly allocated object will contain uninitialized heap garbage in its perf struct because the src_prep->perf values are never copied into new_prep.
[ ... ]
Quoted 6 lines
mm/damon/core.c +2
-0@@ -4913,6 +5032,23 @@ static int kdamond_fn(void *data) done:damon_destroy_targets (ctx); +#ifdef CONFIG_DAMON_PERF_SOURCE +/*
mm/damon/core.c static int kdamond_fn(void *data) · line 5046
Quoted 10 lines
mm/damon/core.c +10
-0+* Release perf-event probes here so a stopped kdamond leaves no event +* firing overflows into its report ring, and holds no PMU ownership. +*/ + { +struct damon_probe *p, *next_p; + +damon_for_each_probe_safe (p, next_p, ctx) { +if (p->perf_priv) { +damon_perf_probe_teardown (ctx, p->perf_priv); + p->perf_priv =NULL ;
[Severity: Medium]
Can a stopped DAMON context ever be safely restarted?
When kdamond stops, this teardown path permanently nulls out p->perf_priv. If a core API user subsequently restarts the context via damon_start(), the context is left without its PMU configuration and will silently fail to monitor any events.
While sysfs users aren't affected because they rebuild the context entirely on restart, this breaks the core API's ability to reuse stopped contexts.
[ ... ]
Quoted 22 lines
mm/damon/perf_source.c +14
-0@@ -285,12 +269,51 @@ int damon_perf_probe_setup(struct damon_ctx *ctx, perf =kzalloc_obj (*perf,GFP_KERNEL );if (!perf) goto release_owner; + event->priv = perf; + +/* +* A system-wide PMU is a single hardware unit rather than a per-CPU +* counter, so it needs exactly one counter: the cpuhp fan-out below +* would run one redundant sampler per CPU against the one device and +* corrupt its shared state. Pin that counter to a fixed online CPU +* and bypass cpuhp. +* +* A kernel counter with no task must name a CPU. If that CPU goes +* offline the counter stops and is not migrated. +*/ +if (event->attr.single_instance) { +struct perf_event_attr attr;
mm/damon/perf_source.c int damon_perf_probe_setup(struct damon_ctx *ctx, · line 295
Quoted 10 lines
mm/damon/perf_source.c +10
-0+int cpu =cpumask_first (cpu_online_mask); + +damon_perf_event_init_attr (event, &attr); +/* +* Pass @event as the overflow context, as the per-CPU path +* (damon_perf_cpu_online()) does: damon_perf_overflow() reads +* event->ctx via smp_load_acquire() for the teardown barrier. +*/ + perf->single_event =perf_event_create_kernel_counter (&attr, + cpu,NULL , damon_perf_overflow, event);
[Severity: High]
Does this allow userspace to bypass perf_event security policies?
The attributes copied in damon_perf_event_init_attr() (such as type, config, and exclude_kernel) originate directly from user sysfs inputs.
By passing these raw user-supplied attributes directly into perf_event_create_kernel_counter(), standard perf security checks like perf_event_paranoid and LSM hooks are bypassed.
This could allow a user with sysfs write access to configure arbitrary PMU counters and monitor kernel memory accesses.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=5
RFC PATCH v4 6/9 mm/damon/sysfs: expose perf_event prep attributes
In reply to Ravi JonnalagaddaWire the DAMON_PREP_PERF_EVENT prep type added to core.c and perf_source.h into sysfs, so user space can configure a PMU-backed probe entirely through the preps/N/ directory: type, config, config1, config2, freq, sample_period, sample_freq, wakeup_events, precise_ip, sample_phys_addr, sample_weight_struct, exclude_kernel, exclude_hv and single_instance.
For example:
echo perf_event > .../probes/0/preps/0/prep_action
echo 8 > .../probes/0/preps/0/type echo 0x100 > .../probes/0/preps/0/sample_period echo 1 > .../probes/0/preps/0/sample_phys_addr
damon_sysfs_set_perf_probe() builds the damon_perf_probe_event from the prep's stored attributes and, when arming, calls damon_perf_probe_setup() to open the PMU counter(s) immediately; deferred (non-arming) builds carry the attributes for a later commit to arm, per the commit_live distinction in the previous commit.
damon_sysfs_set_preps() validates a DAMON_PREP_PERF_EVENT prep before it can reach the PMU. freq selects which one of sample_freq and sample_period carries the sampling rate, so the selected one must be set and the other zero, since the counter would otherwise be armed with a zero period and take no samples. precise_ip is a 2-bit bitfield in perf_event_attr, so a value above 3 is rejected. A second DAMON_PREP_PERF_EVENT prep on the same probe is rejected, since a probe is backed by one PMU counter.
A probe with a perf_event prep cannot have probe filters, since the drain does not apply them to its samples. With CONFIG_DAMON_PERF_SOURCE disabled, a perf_event prep is rejected with -EOPNOTSUPP. The prep attribute stores take damon_sysfs_lock with mutex_trylock(), as the other DAMON sysfs stores do, and return -EBUSY while it is held, so a commit reads a consistent set of values.
--- mm/damon/sysfs.c | 304 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 290 insertions(+), 14 deletions(-)
mm/damon/sysfs.c +290 -14
@@ -7,6 +7,7 @@#include <linux/slab.h> #include "sysfs-common.h" +#include "perf_source.h" /* * init region directory
@@ -756,6 +757,21 @@ static const struct kobj_type damon_sysfs_intervals_ktype = {struct damon_sysfs_prep {struct kobject kobj;enum damon_prep_action action; +/* perf_event_attr subset; valid when action == DAMON_PREP_PERF_EVENT */ +u32 perf_type; +u64 config; +u64 config1; +u64 config2; +u64 sample_period; +u64 sample_freq; +u32 wakeup_events; +u32 precise_ip; +bool sample_phys_addr; +bool sample_weight_struct; +bool exclude_kernel; +bool exclude_hv; +bool freq; +bool single_instance; };static struct damon_sysfs_prep *damon_sysfs_prep_alloc (void )
@@ -780,6 +796,10 @@ damon_sysfs_prep_action_names[] = { .action = DAMON_PREP_SET_PGIDLE, .name = "set_pgidle", }, + { + .action = DAMON_PREP_PERF_EVENT, + .name = "perf_event", + }, }; static ssize_t prep_action_show(struct kobject *kobj,
@@ -834,8 +854,132 @@ static void damon_sysfs_prep_release(struct kobject *kobj)static struct kobj_attribute damon_sysfs_prep_prep_action_attr =__ATTR_RW_MODE (prep_action,0600 ); +/* +* perf_event configuration attributes. These mirror a subset of +* perf_event_attr and are only meaningful when prep_action is "perf_event". +* They select the PMU (via type/config) and its sampling parameters, and are +* copied into the perf-event probe when DAMON is turned on or the inputs are +* committed. +* +* The sysfs file names stay bare (type, config, ...) while the backing C +* symbols are prefixed to avoid clashing with identically named attributes +* elsewhere in this file. +*/ +#define DAMON_SYSFS_PREP_PERF_U32 (name, field) \ +static ssize_t damon_sysfs_prep_##name##_show(struct kobject *kobj, \ + struct kobj_attribute *attr, char *buf) \ +{ \ + struct damon_sysfs_prep *prep = container_of(kobj, \ + struct damon_sysfs_prep, kobj); \ + return sysfs_emit(buf, "%u\n", prep->field); \ +} \ +static ssize_t damon_sysfs_prep_##name##_store(struct kobject *kobj, \ + struct kobj_attribute *attr, const char *buf, \ + size_t count) \ +{ \ + struct damon_sysfs_prep *prep = container_of(kobj, \ + struct damon_sysfs_prep, kobj); \ + u32 v; \ + int err = kstrtou32(buf, 0, &v); \ + if (err) \ + return err; \ + if (!mutex_trylock(&damon_sysfs_lock)) \ + return -EBUSY; \ + prep->field = v; \ + mutex_unlock(&damon_sysfs_lock); \ + return count; \ +} \ +static struct kobj_attribute damon_sysfs_prep_##name##_attr = __ATTR(name, \ + 0600, damon_sysfs_prep_##name##_show, \ + damon_sysfs_prep_##name##_store) + +#define DAMON_SYSFS_PREP_PERF_U64 (name, field) \ +static ssize_t damon_sysfs_prep_##name##_show(struct kobject *kobj, \ + struct kobj_attribute *attr, char *buf) \ +{ \ + struct damon_sysfs_prep *prep = container_of(kobj, \ + struct damon_sysfs_prep, kobj); \ + return sysfs_emit(buf, "%llu\n", prep->field); \ +} \ +static ssize_t damon_sysfs_prep_##name##_store(struct kobject *kobj, \ + struct kobj_attribute *attr, const char *buf, \ + size_t count) \ +{ \ + struct damon_sysfs_prep *prep = container_of(kobj, \ + struct damon_sysfs_prep, kobj); \ + u64 v; \ + int err = kstrtou64(buf, 0, &v); \ + if (err) \ + return err; \ + if (!mutex_trylock(&damon_sysfs_lock)) \ + return -EBUSY; \ + prep->field = v; \ + mutex_unlock(&damon_sysfs_lock); \ + return count; \ +} \ +static struct kobj_attribute damon_sysfs_prep_##name##_attr = __ATTR(name, \ + 0600, damon_sysfs_prep_##name##_show, \ + damon_sysfs_prep_##name##_store) + +#define DAMON_SYSFS_PREP_PERF_BOOL (name, field) \ +static ssize_t damon_sysfs_prep_##name##_show(struct kobject *kobj, \ + struct kobj_attribute *attr, char *buf) \ +{ \ + struct damon_sysfs_prep *prep = container_of(kobj, \ + struct damon_sysfs_prep, kobj); \ + return sysfs_emit(buf, "%u\n", prep->field); \ +} \ +static ssize_t damon_sysfs_prep_##name##_store(struct kobject *kobj, \ + struct kobj_attribute *attr, const char *buf, \ + size_t count) \ +{ \ + struct damon_sysfs_prep *prep = container_of(kobj, \ + struct damon_sysfs_prep, kobj); \ + bool v; \ + int err = kstrtobool(buf, &v); \ + if (err) \ + return err; \ + if (!mutex_trylock(&damon_sysfs_lock)) \ + return -EBUSY; \ + prep->field = v; \ + mutex_unlock(&damon_sysfs_lock); \ + return count; \ +} \ +static struct kobj_attribute damon_sysfs_prep_##name##_attr = __ATTR(name, \ + 0600, damon_sysfs_prep_##name##_show, \ + damon_sysfs_prep_##name##_store) + +DAMON_SYSFS_PREP_PERF_U32 (type, perf_type); +DAMON_SYSFS_PREP_PERF_U64 (config, config); +DAMON_SYSFS_PREP_PERF_U64 (config1, config1); +DAMON_SYSFS_PREP_PERF_U64 (config2, config2); +DAMON_SYSFS_PREP_PERF_U64 (sample_period, sample_period); +DAMON_SYSFS_PREP_PERF_U64 (sample_freq, sample_freq); +DAMON_SYSFS_PREP_PERF_U32 (wakeup_events, wakeup_events); +DAMON_SYSFS_PREP_PERF_U32 (precise_ip, precise_ip); +DAMON_SYSFS_PREP_PERF_BOOL (sample_phys_addr, sample_phys_addr); +DAMON_SYSFS_PREP_PERF_BOOL (sample_weight_struct, sample_weight_struct); +DAMON_SYSFS_PREP_PERF_BOOL (exclude_kernel, exclude_kernel); +DAMON_SYSFS_PREP_PERF_BOOL (exclude_hv, exclude_hv); +DAMON_SYSFS_PREP_PERF_BOOL (freq, freq); +DAMON_SYSFS_PREP_PERF_BOOL (single_instance, single_instance); +static struct attribute *damon_sysfs_prep_attrs[] = { &damon_sysfs_prep_prep_action_attr.attr, + &damon_sysfs_prep_type_attr.attr, + &damon_sysfs_prep_config_attr.attr, + &damon_sysfs_prep_config1_attr.attr, + &damon_sysfs_prep_config2_attr.attr, + &damon_sysfs_prep_sample_period_attr.attr, + &damon_sysfs_prep_sample_freq_attr.attr, + &damon_sysfs_prep_wakeup_events_attr.attr, + &damon_sysfs_prep_precise_ip_attr.attr, + &damon_sysfs_prep_sample_phys_addr_attr.attr, + &damon_sysfs_prep_sample_weight_struct_attr.attr, + &damon_sysfs_prep_exclude_kernel_attr.attr, + &damon_sysfs_prep_exclude_hv_attr.attr, + &damon_sysfs_prep_freq_attr.attr, + &damon_sysfs_prep_single_instance_attr.attr,NULL , };ATTRIBUTE_GROUPS (damon_sysfs_prep);
@@ -2261,14 +2405,60 @@ static int damon_sysfs_set_preps(struct damon_probe *probe, struct damon_sysfs_preps *sys_preps) {int i; +bool seen_perf_prep = false;for (i =0 ; i < sys_preps->nr; i++) {struct damon_sysfs_prep *sys_prep = sys_preps->preps_arr[i];struct damon_prep *prep; +#ifndef CONFIG_DAMON_PERF_SOURCE +if (sys_prep->action ==DAMON_PREP_PERF_EVENT ) +return -EOPNOTSUPP ; +#endif + +/* freq selects which of sample_freq and sample_period is set */ +if (sys_prep->action ==DAMON_PREP_PERF_EVENT && + (sys_prep->freq ? + !sys_prep->sample_freq || sys_prep->sample_period : + !sys_prep->sample_period || sys_prep->sample_freq)) +return -EINVAL ; +/* precise_ip is a 2-bit bitfield in perf_event_attr */ +if (sys_prep->action ==DAMON_PREP_PERF_EVENT && + sys_prep->precise_ip >3 ) +return -EINVAL ; +/* At most one perf-event prep per probe. */ +if (sys_prep->action ==DAMON_PREP_PERF_EVENT && seen_perf_prep) +return -EINVAL ; +if (sys_prep->action ==DAMON_PREP_PERF_EVENT ) + seen_perf_prep = true; + prep =damon_new_prep (sys_prep->action);if (!prep)return -ENOMEM ; +if (sys_prep->action ==DAMON_PREP_PERF_EVENT ) { +/* +* damon_new_prep() does not zero prep->perf; clear it +* so any field not assigned below starts from a known +* zero rather than kmalloc garbage. +*/ +memset (&prep->perf,0 ,sizeof (prep->perf)); + prep->perf.type = sys_prep->perf_type; + prep->perf.config = sys_prep->config; + prep->perf.config1 = sys_prep->config1; + prep->perf.config2 = sys_prep->config2; + prep->perf.sample_period = sys_prep->sample_period; + prep->perf.sample_freq = sys_prep->sample_freq; + prep->perf.wakeup_events = sys_prep->wakeup_events; + prep->perf.precise_ip = sys_prep->precise_ip; + prep->perf.sample_phys_addr = + sys_prep->sample_phys_addr; + prep->perf.sample_weight_struct = + sys_prep->sample_weight_struct; + prep->perf.exclude_kernel = sys_prep->exclude_kernel; + prep->perf.exclude_hv = sys_prep->exclude_hv; + prep->perf.freq = sys_prep->freq; + prep->perf.single_instance = sys_prep->single_instance; + }damon_add_prep (probe, prep); }return 0 ;
@@ -2308,8 +2498,81 @@ static int damon_sysfs_set_filters(struct damon_probe *probe,return 0 ; } -static int damon_sysfs_set_probe (struct damon_probe *probe, -struct damon_sysfs_probe *sys_probe) +#ifdef CONFIG_DAMON_PERF_SOURCE +/* +* Build a perf-event probe descriptor from the probe's DAMON_PREP_PERF_EVENT +* prep and attach it to @probe. The descriptor is always carried (so the ring +* drain and the commit hand-off recognise the probe as event-driven), but the +* PMU counters are only armed when @arm is set. +* +* @arm is true when building the context that will actually run (turn-on +* path); it is false when building a param_ctx for a commit, which is +* discarded after validation. Arming a param_ctx would collide with the +* running context's perf-probe ownership and return -EBUSY, so the commit path +* defers arming to damon_commit_perf_probe(). +*/ +static int damon_sysfs_set_perf_probe (struct damon_ctx *ctx, +struct damon_probe *probe,bool arm) +{ +struct damon_prep *prep; + +damon_for_each_prep (prep, probe) { +struct damon_perf_probe_event *event; +int err; + +if (prep->action !=DAMON_PREP_PERF_EVENT ) +continue ; + + event =kzalloc_obj (*event,GFP_KERNEL ); +if (!event) +return -ENOMEM ; + event->attr.type = prep->perf.type; + event->attr.config = prep->perf.config; + event->attr.config1 = prep->perf.config1; + event->attr.config2 = prep->perf.config2; + event->attr.sample_period = prep->perf.sample_period; + event->attr.sample_freq = prep->perf.sample_freq; + event->attr.wakeup_events = prep->perf.wakeup_events; + event->attr.precise_ip = prep->perf.precise_ip; + event->attr.sample_phys_addr = prep->perf.sample_phys_addr; + event->attr.sample_weight_struct = + prep->perf.sample_weight_struct; + event->attr.exclude_kernel = prep->perf.exclude_kernel; + event->attr.exclude_hv = prep->perf.exclude_hv; + event->attr.freq = prep->perf.freq; + event->attr.single_instance = prep->perf.single_instance; + + probe->perf_priv = event; + probe->event_driven = true; +if (arm) { + err =damon_perf_probe_setup (ctx, probe, event); +if (err) { + probe->perf_priv =NULL ; +kfree (event); +return err; + } + } +/* At most one perf-event prep per probe. */ +break ; + } +return 0 ; +} +#endif /* CONFIG_DAMON_PERF_SOURCE */ + +static bool damon_sysfs_probe_has_perf_prep (struct damon_probe *probe) +{ +struct damon_prep *prep; + +damon_for_each_prep (prep, probe) { +if (prep->action ==DAMON_PREP_PERF_EVENT ) +return true; + } +return false; +} + +static int damon_sysfs_set_probe (struct damon_ctx *ctx, +struct damon_probe *probe, +struct damon_sysfs_probe *sys_probe,bool arm) {struct damon_sysfs_filters *sys_filters;struct damon_sysfs_preps *sys_preps;
@@ -2322,13 +2585,25 @@ static int damon_sysfs_set_probe(struct damon_probe *probe,return err; } sys_filters = sys_probe->filters; -if (!sys_filters) -return 0 ; -return damon_sysfs_set_filters (probe, sys_filters); +/* the drain does not apply probe filters to perf_event samples */ +if (sys_filters && sys_filters->nr && +damon_sysfs_probe_has_perf_prep (probe)) +return -EINVAL ; +if (sys_filters) { + err =damon_sysfs_set_filters (probe, sys_filters); +if (err) +return err; + } +#ifdef CONFIG_DAMON_PERF_SOURCE + err =damon_sysfs_set_perf_probe (ctx, probe, arm); +if (err) +return err; +#endif +return 0 ; }static int damon_sysfs_set_probes (struct damon_ctx *ctx, -struct damon_sysfs_probes *sys_probes) +struct damon_sysfs_probes *sys_probes,bool arm) {int i, err;
@@ -2342,7 +2617,7 @@ static int damon_sysfs_set_probes(struct damon_ctx *ctx,damon_add_probe (ctx, p); sys_probe = sys_probes->probes_arr[i]; p->weight = sys_probe->weight; - err =damon_sysfs_set_probe (p, sys_probe); + err =damon_sysfs_set_probe (ctx, p, sys_probe, arm);if (err)return err; }
@@ -2443,7 +2718,7 @@ static inline bool damon_sysfs_kdamond_running( }static int damon_sysfs_apply_inputs (struct damon_ctx *ctx, -struct damon_sysfs_context *sys_ctx) +struct damon_sysfs_context *sys_ctx,bool arm) {enum damon_ops_id ops_id;int err;
@@ -2461,7 +2736,7 @@ static int damon_sysfs_apply_inputs(struct damon_ctx *ctx, err =damon_sysfs_set_attrs (ctx, sys_ctx->attrs);if (err)return err; - err =damon_sysfs_set_probes (ctx, sys_ctx->attrs->probes); + err =damon_sysfs_set_probes (ctx, sys_ctx->attrs->probes, arm);if (err)return err; err = damon_sysfs_set_sample_control(&ctx->sample_control,
@@ -2475,7 +2750,7 @@ static int damon_sysfs_apply_inputs(struct damon_ctx *ctx, }static struct damon_ctx *damon_sysfs_build_ctx ( -struct damon_sysfs_context *sys_ctx); +struct damon_sysfs_context *sys_ctx,bool arm);/* * damon_sysfs_commit_input() - Commit user inputs to a running kdamond.
@@ -2495,7 +2770,8 @@ static int damon_sysfs_commit_input(void *data)if (kdamond->contexts->nr !=1 )return -EINVAL ; - param_ctx =damon_sysfs_build_ctx (kdamond->contexts->contexts_arr[0 ]); + param_ctx =damon_sysfs_build_ctx (kdamond->contexts->contexts_arr[0 ], + false);if (IS_ERR (param_ctx))return PTR_ERR (param_ctx); err =damon_commit_ctx (kdamond->damon_ctx, param_ctx);
@@ -2553,7 +2829,7 @@ static int damon_sysfs_upd_tuned_intervals(void *data) }static struct damon_ctx *damon_sysfs_build_ctx ( -struct damon_sysfs_context *sys_ctx) +struct damon_sysfs_context *sys_ctx,bool arm) {struct damon_ctx *ctx =damon_new_ctx ();int err;
@@ -2561,7 +2837,7 @@ static struct damon_ctx *damon_sysfs_build_ctx(if (!ctx)return ERR_PTR (-ENOMEM ); - err =damon_sysfs_apply_inputs (ctx, sys_ctx); + err =damon_sysfs_apply_inputs (ctx, sys_ctx, arm);if (err) {damon_destroy_ctx (ctx);return ERR_PTR (err);
@@ -2613,7 +2889,7 @@ static int damon_sysfs_turn_damon_on(struct damon_sysfs_kdamond *kdamond)if (!repeat_call_control)return -ENOMEM ; - ctx =damon_sysfs_build_ctx (kdamond->contexts->contexts_arr[0 ]); + ctx =damon_sysfs_build_ctx (kdamond->contexts->contexts_arr[0 ], true);if (IS_ERR (ctx)) {kfree (repeat_call_control);return PTR_ERR (ctx);
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 6/9] mm/damon/sysfs: expose perf_event prep attributes
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines
Wire the
DAMON_PREP_PERF_EVENTprep type added tocore.candperf_source.hinto sysfs, so user space can configure a PMU-backed probe entirely through the preps/N/ directory: type, config, config1, config2, freq,sample_period,sample_freq,wakeup_events,precise_ip,sample_phys_addr,sample_weight_struct,exclude_kernel,exclude_hvandsingle_instance.For example:
echo
perf_event> .../probes/0/preps/0/prep_actionecho 8 > .../probes/0/preps/0/type echo 0x100 > .../probes/0/preps/0/sample_period echo 1 > .../probes/0/preps/0/sample_phys_addr
Quoted 7 lines
damon_sysfs_set_perf_probe()builds thedamon_perf_probe_eventfrom the [ ... ]
commit reads a consistent set of values.Co-developed-by Akinobu Mita <[email protected]>Signed-off-by Akinobu Mita <[email protected]>Signed-off-by Ravi Jonnalagadda <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=6
RFC PATCH v4 7/9 mm/damon/tests/drain-kunit: kunit for report rings and ring drain
In reply to Ravi JonnalagaddaAdd kunit coverage for the per-context perf report rings and the drain that credits regions from them. Wire the suites into core.c (included after the drain and its counters are defined) so CONFIG_DAMON_KUNIT_TEST=y builds them.
perf-kunit.h covers the ring itself: reports injected and accepted, overflow safety on wrap, and a report that carries no owning context being dropped.
drain-kunit.h covers the drain and the damon_report_access() producer:
- a vaddr report credited to the region holding its address, and not credited when its thread group id does not match the target
- a paddr report credited with no thread-group filtering
- a perf report credited to the probe hits of its probe index
- reports adding at most one probe hit per sampling interval and none changing nr_accesses, with and without a probe weight set
- per-context isolation: a report reaches only its own context's ring
- the producer's return value, and a full ring counted in the ring-full counter and freed again by a drain
- the address-space match: a report whose virtual address falls inside a region of a physical-address target, and whose physical address falls outside it, is not credited
--- mm/damon/core.c | 2 + mm/damon/tests/drain-kunit.h | 786 +++++++++++++++++++++++++++++++++++++++++++ mm/damon/tests/perf-kunit.h | 133 ++++++++ 3 files changed, 921 insertions(+)
mm/damon/core.c +2 -0
@@ -5208,3 +5208,5 @@ struct damon_region *damon_search(unsigned long addr, struct pid *pid)subsys_initcall (damon_init);#include "tests/core-kunit.h" +#include "tests/drain-kunit.h" +#include "tests/perf-kunit.h"
mm/damon/tests/drain-kunit.h new file +786 -0
786 lines not on this page · raw message
mm/damon/tests/perf-kunit.h new file +133 -0
133 lines not on this page · raw message
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 7/9] mm/damon/tests/drain-kunit: kunit for report rings and ring drain
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Medium] mm: kunit test fails on architectures with PAGE_SIZE > 4KB - [Medium] mm: kunit test flaky due…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] mm: kunit test fails on architectures with PAGE_SIZE > 4KB
- [Medium] mm: kunit test flaky due to short staleness timeout
- [Low] mm: kunit test flaky due to hardcoded magic TGID 9999
- [Low] mm: kunit test flaky due to assertion on global state
--
commit 00b2c09e452d8dccc585f63512e7c9dee88a28fd
Author: Ravi Jonnalagadda <[email protected]>
mm/damon/tests/drain-kunit: kunit for report rings and ring drain
Add kunit coverage for the per-context perf report rings and the drain that credits regions from them. Wire the suites into core.c so CONFIG_DAMON_KUNIT_TEST=y builds them.
Quoted 4 lines
mm/damon/tests/drain-kunit.h new file +0
-0
[ ... ]
Quoted 15 lines
mm/damon/tests/drain-kunit.h new file +15
-0+static void damon_test_unified_vaddr_match (struct kunit *test) +{ +struct damon_ctx *ctx; +struct damon_target *t; +struct damon_region *r; +struct damon_access_report rep = { + .paddr =0 , + .vaddr =0x1500 , + .probe_idx =1 , + .size =PAGE_SIZE , + }; +unsigned long before, after; +int hits; + + ctx =damon_new_ctx ();
[ ... ]
mm/damon/tests/drain-kunit.h line 109
Quoted 6 lines
mm/damon/tests/drain-kunit.h new file +6
-0+/* +* Region must fully contain the report [vaddr, vaddr + size): a report +* straddling the region end is rejected by the drain. With +* vaddr=0x1500 and size=PAGE_SIZE the region must reach >= 0x2500. +*/ + r =damon_new_region (0x1000 ,0x3000 );
[Severity: Medium]
Will this test fail deterministically on architectures where PAGE_SIZE exceeds 4KB (such as ARM64 with 64KB pages)?
The injected report size is PAGE_SIZE starting at 0x1500. If PAGE_SIZE is larger than 6.75KB, the report will straddle the hardcoded 8KB region boundary ending at 0x3000, causing the drain logic to reject it and fail the test.
mm/damon/tests/drain-kunit.h line 122
Quoted 13 lines
mm/damon/tests/drain-kunit.h new file +13
-0+if (!r) { +put_pid (t->pid); +damon_free_target (t); +damon_destroy_ctx (ctx); +kunit_skip (test,"region alloc failed" ); + } +damon_add_region (r, t); +damon_add_target (ctx, t); + + rep.report_jiffies = jiffies; + before =damon_get_samples_drained (); +damon_report_access (&rep); +kdamond_check_reported_accesses (ctx);
[Severity: Medium]
Could this test be flaky under CPU load or preemption?
If execution is delayed by just a few ticks between capturing jiffies and evaluating the drain:
rep.report_jiffies = jiffies; before = damon_get_samples_drained(); damon_report_access(&rep); <-- execution delayed by preemption here kdamond_check_reported_accesses(ctx);
Couldn't the drain logic in __kdamond_drain_ring() drop the report as stale since the default sample_interval is 5ms?
[ ... ]
mm/damon/tests/drain-kunit.h line 153
Quoted 12 lines
mm/damon/tests/drain-kunit.h new file +12
-0+static void damon_test_unified_vaddr_tgid_mismatch (struct kunit *test) +{ +struct damon_ctx *ctx; +struct damon_target *t; +struct damon_region *r; +struct damon_access_report rep = { + .paddr =0 , + .vaddr =0x1500 , + .tgid =9999 ,/* matches no target */ + .probe_idx =1 , + .size =PAGE_SIZE , + };
[Severity: Low]
Could this intermittently fail if the test runner thread happens to be assigned PID 9999 by the OS?
If that occurs, the TGIDs would match, erroneously crediting the report and causing the test assertion to fail.
[ ... ]
Quoted 11 lines
mm/damon/tests/drain-kunit.h new file +11
-0+static void damon_test_report_return_value (struct kunit *test) +{ +struct damon_ctx *ctx; +struct damon_access_report rep = { + .paddr =0x15000 , .probe_idx =1 , .size =PAGE_SIZE , + }; +unsigned long full_before, busy_before; +unsigned int queued =0 , dropped =0 ; +int i; + + ctx =damon_new_ctx ();
[ ... ]
Quoted 6 lines
mm/damon/tests/drain-kunit.h new file +6
-0+ busy_before =damon_get_report_busy_drop (); + +/* One past capacity, so the last iteration must be a drop. */ +for (i =0 ; i <DAMON_REPORT_RING_SIZE ; i++) { +if (damon_report_access (&rep)) + queued++;
mm/damon/tests/drain-kunit.h line 598
Quoted 10 lines
mm/damon/tests/drain-kunit.h new file +10
-0+else + dropped++; + } +preempt_enable (); + +KUNIT_EXPECT_EQ (test, queued, (unsigned int )DAMON_REPORT_RING_SIZE -1 ); +KUNIT_EXPECT_EQ (test, dropped,1u ); +/* No NMI nests here, so the drop must be the full ring. */ +KUNIT_EXPECT_GT (test,damon_get_report_ring_full (), full_before); +KUNIT_EXPECT_EQ (test,damon_get_report_busy_drop (), busy_before);
[Severity: Low]
Is it safe to assert that this global counter remains completely unchanged during the test's execution?
Since damon_get_report_busy_drop() aggregates the damon_report_busy_drop_perf counter across all CPUs, wouldn't concurrent perf NMI activity in other DAMON contexts on different CPUs increment this counter and cause the test assertion to fail?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=7
RFC PATCH v4 8/9 mm/damon/core: cap the region merge threshold per target
In reply to Ravi Jonnalagaddakdamond_merge_regions() applies one context-wide threshold, the highest merge score across all targets divided by 10, to every target. When a high-traffic target and a low-traffic target share a context, the high-traffic target sets a threshold permissive enough to erase the hot/cold boundary in the low-traffic one: a region with nr_accesses=1 next to one with nr_accesses=0 merges because 1 <= threshold, even though that difference is the only signal the cold scheme has to admit it.
On the regular merge pass, cap the threshold for each target by a tenth of that target's own maximum merge score. The score is the one damon_merge_regions_of() compares, so a probe-weighted context is capped by its weighted hit sums.
The passes that follow the regular one exist only to bring the region count under max_nr_regions by escalating the threshold. They keep using the escalated threshold uncapped, so that bound still holds.
In a probe-weighted context the merge score is a weighted hit sum, which can exceed max_thres, the samples-per-aggregation ceiling the escalating passes stop at, when the probe weights sum above 1. Raise max_thres to ten times the initial threshold there, so those passes still run.
--- mm/damon/core.c | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-)
mm/damon/core.c +29 -1
@@ -4167,12 +4167,40 @@ static noinline_for_stack void kdamond_merge_regions(struct damon_ctx *c,unsigned int nr_regions;unsigned int max_thres;bool count_age = true; +bool use_probe_hits =damon_has_probe_weights (c); max_thres =damon_nr_samples_per_aggr (&c->attrs); +/* weighted scores can exceed max_thres; threshold is max score / 10 */ +if (use_probe_hits) + max_thres =max (threshold *10 , max_thres);while (true) { nr_regions =0 ;damon_for_each_target (t, c) { -damon_merge_regions_of (t, threshold, sz_limit, c, +struct damon_region *r; +unsigned int t_max =0 , t_thres = threshold; + +/* +* On the regular pass, cap the threshold at a tenth of +* this target's maximum merge score. A high-traffic +* target in the same context must not set a threshold +* so permissive that a low-traffic target's hot/cold +* boundary merges away before the cold scheme can act +* on it. The score is the one damon_merge_regions_of() +* compares, so probe-weighted contexts are capped by +* their weighted hit sums. +* +* The passes that follow exist only to bring the region +* count under max_nr_regions, so they use the escalated +* threshold as is. +*/ +if (count_age) { +damon_for_each_region (r, t) + t_max =max (t_max, +damon_merge_score (r, false, c, + use_probe_hits)); + t_thres =min (threshold, t_max /10 ); + } +damon_merge_regions_of (t, t_thres, sz_limit, c, count_age); nr_regions +=damon_nr_regions (t); }
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 8/9] mm/damon/core: cap the region merge threshold per target
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] mm/damon: integer truncation in max_thres bounds calculation --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] mm/damon: integer truncation in max_thres bounds calculation
--
commit a10e8369d2fd5c44226b6327f0cddd983be70366
Author: Ravi Jonnalagadda <[email protected]>
mm/damon/core: cap the region merge threshold per target
This commit modifies kdamond_merge_regions to cap the merge threshold for each target individually during the regular merge pass. It also adjusts the maximum threshold for probe-weighted contexts to ensure escalation passes continue to run even when weighted hits exceed the normal maximum threshold.
[ ... ]
Quoted 5 lines
mm/damon/core.c +0
-0
mm/damon/core.c static noinline_for_stack void kdamond_merge_regions(struct damon_ctx *c, · line 4175
Quoted 9 lines
mm/damon/core.c +4
-0@@ -4167,12 +4167,40 @@ static noinline_for_stack void kdamond_merge_regions(struct damon_ctx *c,unsigned int nr_regions;unsigned int max_thres;bool count_age = true; +bool use_probe_hits =damon_has_probe_weights (c); max_thres =damon_nr_samples_per_aggr (&c->attrs); +/* weighted scores can exceed max_thres; threshold is max score / 10 */ +if (use_probe_hits) + max_thres =max (threshold *10 , max_thres);
[Severity: Medium]
When the true maximum merge score is not a multiple of 10, does this calculation cause max_nr_regions to be violated?
Because kdamond_fn() calculates the initial threshold by dividing max_merge_score by 10, the remainder is discarded:
mm/damon/core.c:kdamond_fn() {
...
kdamond_merge_regions(ctx, max_merge_score / 10, sz_limit);
...
}When kdamond_merge_regions() attempts to restore the max_thres ceiling via threshold * 10, it loses the remainder (e.g., a max score of 29 yields threshold 2, restoring a ceiling of 20 instead of 29).
Will the escalation loop then terminate prematurely when it reaches 20, leaving regions with score differences up to 29 unmerged and the total region count above the configured limit?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=8
RFC PATCH v4 9/9 mm/damon/core: apply probe_hits_wsum filters to node_eligible_mem_bp
In reply to Ravi Jonnalagaddanode_eligible_mem_bp is the share of a scheme's eligible memory that is on a given node, and memory is eligible when its region matches the scheme's access pattern. In data attributes-only monitoring nr_accesses is not updated, so the access pattern cannot tell which regions the scheme is for; its probe_hits_wsum filters do.
Count a region as eligible only if it also passes the scheme's probe_hits_wsum filters, decided as the scheme's core filters are: the first matching one decides, and if none matches, the region passes unless the last of them is an allow filter and the scheme has no ops filters. The address and target filters stay out of the metric, as before, since they scope where the scheme acts rather than which memory it is for.
--- mm/damon/core.c | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-)
mm/damon/core.c +31 -3
@@ -3609,6 +3609,31 @@ static unsigned long damos_get_node_memcg_used_bp( }#ifdef CONFIG_DAMON_PADDR +/* +* Whether @r passes the probe_hits_wsum filters of @s, decided as the core +* filters of a scheme are, with the other filter types left out: the first +* matching filter decides, and if none matches, @r passes unless the last of +* them is an allow filter and @s has no ops filters. These filters select +* regions by their data attributes, so they are part of what makes memory +* eligible for the scheme, unlike its address and target filters. +*/ +static bool damos_probe_filters_pass (struct damon_ctx *c, +struct damon_target *t,struct damon_region *r,struct damos *s) +{ +struct damos_filter *filter; +bool pass = true; + +damos_for_each_core_filter (filter, s) { +if (filter->type !=DAMOS_FILTER_TYPE_PROBE_HITS_WSUM ) +continue ; +if (damos_filter_match (c, t, r, filter, c->min_region_sz)) +return filter->allow; + pass = !filter->allow; + } +/* as damos_set_filters_default_reject(): ops filters decide the rest */ +return pass || !list_empty (&s->ops_filters); +} +/* * damos_calc_eligible_bytes() - Calculate raw eligible bytes per node. * @c: The DAMON context.
@@ -3616,9 +3641,10 @@ static unsigned long damos_get_node_memcg_used_bp(* @nid: The target NUMA node id. * @total: Output for total eligible bytes across all nodes. * -* Iterates through each folio in eligible regions to accurately determine -* which node the memory resides on. Returns eligible bytes on the specified -* node and sets *total to the sum across all nodes. +* A region is eligible if it matches the access pattern of @s and passes its +* probe_hits_wsum filters. Iterates through each folio in eligible regions to +* accurately determine which node the memory resides on. Returns eligible bytes +* on the specified node and sets *total to the sum across all nodes. * * Note: This function requires damon_get_folio() from ops-common.c, which is * only available when CONFIG_DAMON_PADDR is enabled. It also requires the
@@ -3638,6 +3664,8 @@ static phys_addr_t damos_calc_eligible_bytes(struct damon_ctx *c,if (!__damos_valid_target (r, s, c))continue ; +if (!damos_probe_filters_pass (c, t, r, s)) +continue ;/* Convert from core address units to physical bytes */ addr = (phys_addr_t )r->ar.start * c->addr_unit;
Signature · 1 line
Git-157)
[email protected]
AI reviewRe: [RFC PATCH v4 9/9] mm/damon/core: apply probe_hits_wsum filters to node_eligible_mem_bp
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 14 lines
node_eligible_mem_bpis the share of a scheme's eligible memory that is on a given node, and memory is eligible when its region matches the scheme's access pattern. In data attributes-only monitoringnr_accessesis not updated, so the access pattern cannot tell which regions the scheme is for; itsprobe_hits_wsumfilters do.Count a region as eligible only if it also passes the scheme's
probe_hits_wsumfilters, decided as the scheme's core filters are: the first matching one decides, and if none matches, the region passes unless the last of them is an allow filter and the scheme has no ops filters. The address and target filters stay out of the metric, as before, since they scope where the scheme acts rather than which memory it is for.
Quoted 1 line
Signed-off-by Ravi Jonnalagadda <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/20261005-damon-perf-rfc-v3-send-2026-10-03-v4-0-b03452e137f3@gmail.com?part=9
SJ Park
maintainerHi Ravi,
Quoted 5 lines · On Mon, 05 Oct 2026 01:46:44 -0700 Ravi Jonnalagadda <[email protected]>…
This series lets DAMON monitor a hardware-sampled data attribute -- the addresses a PMU saw accessed -- through the data attributes monitoring (probe) interface, and run DAMOS schemes on it in data attributes-only mode. Patches 3, 5, and 6 are co-developed with Akinobu Mita, building on his earlier perf-event proposal [3].
Thank you for this series! I'm in travel, so it would take time to review this in depth, though. Hopefully I will get get some bandwidth starting from next week. Feel free to send new versions meanwhile, if you think those are needed. I will review the latest version when I get the bandwidth.
Thanks,
SJ
[...]
v4 cover mm/damon: hardware-sampled access reports
In reply to Ravi JonnalagaddaHi Ravi,
TLDR
====
I have noticed that there might have an issue with this patch or my CPU. I am not sure. I have provided some details below.
Quoted 6 lines · On Mon, 05 Oct 2026 01:46:44 -0700 Ravi Jonnalagadda <[email protected]>…
This series lets DAMON monitor a hardware-sampled data attribute -- the addresses a PMU saw accessed -- through the data attributes monitoring (probe) interface, and run DAMOS schemes on it in data attributes-only mode. Patches 3, 5, and 6 are co-developed with Akinobu Mita, building on his earlier perf-event proposal [3].
I expected it to monitor regions in the same way as PTE sampling, that is, if the system has hot memory, DAMON should be able to detect it, or at least with some probability. However, it is not always work like that. After I starting DAMON about 10 minutes, the DAMON cannot found any hot page, even when I am running 'stress-ng --vm 6 --vm-bytes 6G':
snapshot time: [0 ns, 100 ms] (100 ms)
|0000000000000000000000000000000000000000| size 1.461 GiB access 0 age 3 m 3.200 s
|000000000| size 1.465 GiB access 0 age 3 m 1 s
|00| size 2.922 GiB access 0 age 3 m 0.500 s
|0000000000000000000| size 1.471 GiB access 0 age 3 m 1.700 s
|000000000000000000000000| size 1.462 GiB access 0 age 3 m 2.100 s
|00| size 1.470 GiB access 0 age 3 m 0.500 s
|0| size 2.926 GiB access 0 age 3 m 0.400 s
|00| size 1.544 GiB access 0 age 3 m 0.500 s
memory bw estimate: 0 B per second
total size: 14.722 GiB
record DAMON intervals: sample 5 ms, aggr 100 ms
Note that this is my own fork of damo [1].To ensure this was not a bug in my damo fork [1], I adding a tracing statistic [2] to DAMON to confirm whether this was indeed a DAMON issue.
TLDR for new tracing statsistic: 'seen' means how many times damon_perf_overflow() was called.
Later, I noticed that about 10 minutes after starting DAMON, the 'seen' stopped increasing:
I am running 'stress-ng --vm 6 --vm-bytes 6G' during recording this statistic.
Start Time: 19:25:42 | End Time: 19:42:18
Time Unit: 1 step = 1.81 minutes
Seen (Delta)
^
|
100k | *
36k | *
18k | * *
17k | *
15k | *
4k | *
453 | *
106 | *
0 | *
+--+---+---+---+---+---+---+---+---+---+---> Step
1 2 3 4 5 6 7 8 9 10
Note: Zero delta from 19:42:18 (step 10) till 20:00:00 (I close my machine after that).
My DAMON Perf Config
====================
K=/sys/kernel/mm/damon/admin/kdamonds/0
C=$K/contexts/0
P=$C/monitoring_attrs/probes
echo 1 > $P/0/preps/nr_preps
echo perf_event > $P/0/preps/0/prep_action
cat /sys/bus/event_source/devices/ibs_op/type > $P/0/preps/0/type
echo 0 > $P/0/preps/0/config
echo 0 > $P/0/preps/0/config2
echo 0 > $P/0/preps/0/sample_freq
echo 100000 > $P/0/preps/0/sample_period
echo 1 > $P/0/preps/0/sample_phys_addr
echo 0 > $P/0/preps/0/exclude_kernel
echo 0 > $P/0/preps/0/exclude_hv
echo 1 > $P/0/weight
Note that this issue can also reproduce even when
'kernel.perf_cpu_time_max_percent=100'.My CPU Specification
====================
CPU(s): 12
On-line CPU(s) list: 0-11
Vendor ID: AuthenticAMD
Model name: AMD Ryzen 5 5600H with Radeon Graphics
CPU family: 25
Model: 80
Thread(s) per core: 2
Core(s) per socket: 6
Socket(s): 1
Stepping: 0
Microcode version: 0xa500012
Frequency boost: enabled
CPU(s) scaling MHz: 48%
CPU max MHz: 4280.9849
CPU min MHz: 412.6250
BogoMIPS: 6587.34I am trying to figure out if this is a CPU issue, or if there is an issue with this patch. I would be happy to provide more information.
[...]
[1] https://github.com/aethernet65535/damo/tree/probe
[2] Trace patch diff
'''
include/trace/events/damon.h +17 -0
@@ -199,6 +199,23 @@ TRACE_EVENT(damon_aggregated, __entry->nr_accesses, __entry->age) ); +TRACE_EVENT (damon_perf_source_stats, + + TP_PROTO(unsigned long seen), + +TP_ARGS (seen), + +TP_STRUCT__entry ( + __field(unsigned long, seen) + ), + +TP_fast_assign ( + __entry->seen = seen; + ), + +TP_printk ("seen=%lu" , __entry->seen) +) +#endif /* _TRACE_DAMON_H */ /* This part must be outside protection */
mm/damon/core.c +2 -0
@@ -4927,6 +4927,8 @@ static void kdamond_check_reported_accesses(struct damon_ctx *ctx)if (damon_drains_ring_perf (ctx))__kdamond_drain_ring (ctx, tbl, ctx->perf_rings, &ctx->perf_pending); + +trace_damon_perf_source_stats (damon_get_perf_seen ()); }/*
mm/damon/perf_source.c +14 -0
@@ -27,6 +27,8 @@ struct damon_perf_probe_state {struct perf_event *single_event; }; +static DEFINE_PER_CPU(unsigned long, damon_perf_seen); +static void damon_perf_overflow (struct perf_event *perf_event,struct perf_sample_data *data,struct pt_regs *regs)
@@ -40,6 +42,8 @@ static void damon_perf_overflow(struct perf_event *perf_event, .cpu = smp_processor_id(), }; +this_cpu_inc (damon_perf_seen); +/* * Teardown NULLs event->ctx (with a release barrier) before releasing * the per-CPU perf events, so an in-flight overflow racing the
@@ -84,6 +88,16 @@ static void damon_perf_overflow(struct perf_event *perf_event,damon_report_access (&report); } +unsigned long damon_get_perf_seen (void ) +{ +unsigned long sum =0 ; +int cpu; + +for_each_possible_cpu (cpu) + sum +=per_cpu (damon_perf_seen, cpu); +return sum; +} +static enum cpuhp_state damon_perf_cpuhp_state;/*
mm/damon/perf_source.h +1 -0
@@ -50,6 +50,7 @@ int damon_perf_probe_setup(struct damon_ctx *ctx, struct damon_perf_probe_event *event);void damon_perf_probe_teardown (struct damon_ctx *ctx,struct damon_perf_probe_event *event); +unsigned long damon_get_perf_seen (void );#endif /* CONFIG_DAMON_PERF_SOURCE */ #endif /* _DAMON_PERF_SOURCE_H */
'''
Best regards,
Rui Yan
v4 cover mm/damon: hardware-sampled access reports
Quoted 214 lines · On Sat, 17 Oct 2026 15:11:18 +0800 Liew Rui Yan <[email protected]>…
Hi Ravi,
TLDR
====I have noticed that there might have an issue with this patch or my CPU. I am not sure. I have provided some details below.
Quoted 6 lines · On Mon, 05 Oct 2026 01:46:44 -0700 Ravi Jonnalagadda <[email protected]>…
This series lets DAMON monitor a hardware-sampled data attribute -- the addresses a PMU saw accessed -- through the data attributes monitoring (probe) interface, and run DAMOS schemes on it in data attributes-only mode. Patches 3, 5, and 6 are co-developed with Akinobu Mita, building on his earlier perf-event proposal [3].
I expected it to monitor regions in the same way as PTE sampling, that is, if the system has hot memory, DAMON should be able to detect it, or at least with some probability. However, it is not always work like that. After I starting DAMON about 10 minutes, the DAMON cannot found any hot page, even when I am running 'stress-ng --vm 6 --vm-bytes 6G':
snapshot time: [0 ns, 100 ms] (100 ms) |0000000000000000000000000000000000000000| size 1.461 GiB access 0 age 3 m 3.200 s |000000000| size 1.465 GiB access 0 age 3 m 1 s |00| size 2.922 GiB access 0 age 3 m 0.500 s |0000000000000000000| size 1.471 GiB access 0 age 3 m 1.700 s |000000000000000000000000| size 1.462 GiB access 0 age 3 m 2.100 s |00| size 1.470 GiB access 0 age 3 m 0.500 s |0| size 2.926 GiB access 0 age 3 m 0.400 s |00| size 1.544 GiB access 0 age 3 m 0.500 s memory bw estimate: 0 B per second total size: 14.722 GiB record DAMON intervals: sample 5 ms, aggr 100 ms Note that this is my own fork of damo [1].To ensure this was not a bug in my damo fork [1], I adding a tracing statistic [2] to DAMON to confirm whether this was indeed a DAMON issue.
TLDR for new tracing statsistic: 'seen' means how many times
damon_perf_overflow()was called.Later, I noticed that about 10 minutes after starting DAMON, the 'seen' stopped increasing:
I am running 'stress-ng --vm 6 --vm-bytes 6G' during recording this statistic.
Start Time: 19:25:42 | End Time: 19:42:18
Time Unit: 1 step = 1.81 minutesSeen (Delta)
^
|
100k | *
36k | *
18k | * *
17k | *
15k | *
4k | *
453 | *
106 | *
0 | *
+--+---+---+---+---+---+---+---+---+---+---> Step
1 2 3 4 5 6 7 8 9 10Note: Zero delta from 19:42:18 (step 10) till 20:00:00 (I close my machine after that).
My DAMON Perf Config
====================K=/sys/kernel/mm/damon/admin/kdamonds/0 C=$K/contexts/0 P=$C/monitoring_attrs/probes echo 1 > $P/0/preps/nr_preps echo perf_event > $P/0/preps/0/prep_action cat /sys/bus/event_source/devices/ibs_op/type > $P/0/preps/0/type echo 0 > $P/0/preps/0/config echo 0 > $P/0/preps/0/config2 echo 0 > $P/0/preps/0/sample_freq echo 100000 > $P/0/preps/0/sample_period echo 1 > $P/0/preps/0/sample_phys_addr echo 0 > $P/0/preps/0/exclude_kernel echo 0 > $P/0/preps/0/exclude_hv echo 1 > $P/0/weight Note that this issue can also reproduce even when 'kernel.perf_cpu_time_max_percent=100'.My CPU Specification
====================CPU(s): 12 On-line CPU(s) list: 0-11 Vendor ID: AuthenticAMD Model name: AMD Ryzen 5 5600H with Radeon Graphics CPU family: 25 Model: 80 Thread(s) per core: 2 Core(s) per socket: 6 Socket(s): 1 Stepping: 0 Microcode version: 0xa500012 Frequency boost: enabled CPU(s) scaling MHz: 48% CPU max MHz: 4280.9849 CPU min MHz: 412.6250 BogoMIPS: 6587.34I am trying to figure out if this is a CPU issue, or if there is an issue with this patch. I would be happy to provide more information.
[...]
[1] https://github.com/aethernet65535/damo/tree/probe
[2] Trace patch diff
'''include/trace/events/damon.h +17
-0@@ -199,6 +199,23 @@ TRACE_EVENT(damon_aggregated, __entry->nr_accesses, __entry->age) ); +TRACE_EVENT (damon_perf_source_stats, + + TP_PROTO(unsigned long seen), + +TP_ARGS (seen), + +TP_STRUCT__entry ( + __field(unsigned long, seen) + ), + +TP_fast_assign ( + __entry->seen = seen; + ), + +TP_printk ("seen=%lu" , __entry->seen) +) +#endif /* _TRACE_DAMON_H */ /* This part must be outside protection */ mm/damon/core.c +2
-0@@ -4927,6 +4927,8 @@ static void kdamond_check_reported_accesses(struct damon_ctx *ctx)if (damon_drains_ring_perf (ctx))__kdamond_drain_ring (ctx, tbl, ctx->perf_rings, &ctx->perf_pending); + +trace_damon_perf_source_stats (damon_get_perf_seen ()); }/* mm/damon/perf_source.c +14
-0@@ -27,6 +27,8 @@ struct damon_perf_probe_state {struct perf_event *single_event; }; +static DEFINE_PER_CPU(unsigned long, damon_perf_seen); +static void damon_perf_overflow (struct perf_event *perf_event,struct perf_sample_data *data,struct pt_regs *regs)@@ -40,6 +42,8 @@ static void damon_perf_overflow(struct perf_event *perf_event, .cpu = smp_processor_id(), }; +this_cpu_inc (damon_perf_seen); +/* * Teardown NULLs event->ctx (with a release barrier) before releasing * the per-CPU perf events, so an in-flight overflow racing the @@ -84,6 +88,16 @@ static void damon_perf_overflow(struct perf_event *perf_event,damon_report_access (&report); } +unsigned long damon_get_perf_seen (void ) +{ +unsigned long sum =0 ; +int cpu; + +for_each_possible_cpu (cpu) + sum +=per_cpu (damon_perf_seen, cpu); +return sum; +} +static enum cpuhp_state damon_perf_cpuhp_state;/* mm/damon/perf_source.h +1
-0@@ -50,6 +50,7 @@ int damon_perf_probe_setup(struct damon_ctx *ctx, struct damon_perf_probe_event *event);void damon_perf_probe_teardown (struct damon_ctx *ctx,struct damon_perf_probe_event *event); +unsigned long damon_get_perf_seen (void );#endif /* CONFIG_DAMON_PERF_SOURCE */ #endif /* _DAMON_PERF_SOURCE_H */
Quoted 1 line
'''
I found that if I enable the kernel NMI watchdog, this issue can be fixed. So I think this is not issue of this patch. What do you think?
[...]
Best regards,
Rui Yan
Hi Rui Yan,
Quoted 1 line · On Sun, 18 Oct 2026 05:16:13 +0800 Liew Rui Yan <[email protected]>…
On Sat, 17 Oct 2026 15:11:18 +0800 Liew Rui Yan <[email protected]> wrote:
[...]
Quoted 2 lines
Quoted 2 lines
Later, I noticed that about 10 minutes after starting DAMON, the 'seen' stopped increasing:
[...]
Quoted 2 lines
I found that if I enable the kernel NMI watchdog, this issue can be fixed. So I think this is not issue of this patch. What do you think?
Thanks for testing the series!
Agreed, this is an AMD IBS / x86 NMI quirk rather than an issue in this patchset.
On AMD IBS, when a counter overflows it sets IbsOpVal in MSR_AMD64_IBSOPCTL, stops counting, and sends a single edge-triggered NMI. If that NMI edge is lost (e.g., across C-state transitions), IbsOpVal stays set and the counter remains frozen on that CPU until perf_ibs_handle_irq() clears it and re-arms the MSR. That also explains why the sample count in your graph stepped down gradually over time (100k -> 36k -> 18k -> 4k -> 0), as individual CPUs got stuck one by one. When the NMI watchdog is enabled, its periodic NMI walks all NMI_LOCAL handlers (including perf_ibs_nmi_handler()), which spots the pending IbsOpVal bit and re-arms IBS.
For ibs_op, a larger period such as sample_period=262144 (as used in the cover letter) or setting config=0x80000 (cnt_ctl=1, dispatched micro-ops instead of clock cycles) also helps reduce the NMI rate on the CPU.
Also, if it helps for testing, the damo branch in the cover letter [1] already has sysfs read/write support for the perf_event prep attributes (commit 1178ccb) and tools/damon_tier_gen.py for generating IBS/PEBS configs. Your probe_hits_wsum support in 'damo report access' on your branch is a nice addition as well.
[1] https://github.com/ravis-opensrc/damo/tree/damo/auto-tier-bw-2026-10-04
Thanks,
Ravi