Skip to contentSkip to conversation

mm: workingset reporting

PATCH In review Yuanchu Xie 6 participants 21 messages Nov 27, 2024 – Jan 30, 2025

Subsystems (14)
lore
Share & tools
lore

Yuanchu Xie

author reviewer
#0 lore raw

v4 cover mm: workingset reporting

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references. However, the concept of workingset applies generically to all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

Use cases
==========
Job scheduling
On overcommitted hosts, workingset information improves efficiency and reliability by allowing the job scheduler to have better stats on the exact memory requirements of each job. This can manifest in efficiency by landing more jobs on the same host or NUMA node. On the other hand, the job scheduler can also ensure each node has a sufficient amount of memory and does not enter direct reclaim or the kernel OOM path. With workingset information and job priority, the userspace OOM killing or proactive reclaim policy can kick in before the system is under memory pressure. If the job shape is very different from the machine shape, knowing the workingset per-node can also help inform page allocation policies.

Proactive reclaim
Workingset information allows the a container manager to proactively reclaim memory while not impacting a job's performance. While PSI may provide a reactive measure of when a proactive reclaim has reclaimed too much, workingset reporting allows the policy to be more accurate and flexible.

Ballooning (similar to proactive reclaim)
The last patch of the series extends the virtio-balloon device to report the guest workingset.
Balloon policies benefit from workingset to more precisely determine the size of the memory balloon. On end-user devices where memory is scarce and overcommitted, the balloon sizing in multiple VMs running on the same device can be orchestrated with workingset reports from each one. On the server side, workingset reporting allows the balloon controller to inflate the balloon without causing too much file cache to be reclaimed in the guest.

Promotion/Demotion
If different mechanisms are used for promition and demotion, workingset information can help connect the two and avoid pages being migrated back and forth.
For example, given a promotion hot page threshold defined in reaccess distance of N seconds (promote pages accessed more often than every N seconds). The threshold N should be set so that ~80% (e.g.) of pages on the fast memory node passes the threshold. This calculation can be done with workingset reports.
To be directly useful for promotion policies, the workingset report interfaces need to be extended to report hotness and gather hotness information from the devices[1].

[1]
https://www.opencompute.org/documents/ocp-cms-hotness-tracking-requirements-white-paper-pdf-1

Sysfs and Cgroup Interfaces
==========
The interfaces are detailed in the patches that introduce them. The main idea here is we break down the workingset per-node per-memcg into time intervals (ms), e.g.

1000 anon=137368 file=24530
20000 anon=34342 file=0
30000 anon=353232 file=333608
40000 anon=407198 file=206052
9223372036854775807 anon=4925624 file=892892

Implementation
==========
The reporting of user pages is based off of MGLRU, and therefore requires CONFIG_LRU_GEN=y. We would benefit from more MGLRU generations for a more fine-grained workingset report, but we can already gather a lot of data with just four generations. The workingset reporting mechanism is gated behind CONFIG_WORKINGSET_REPORT, and the aging thread is behind CONFIG_WORKINGSET_REPORT_AGING.

Benchmarks
==========
Ghait Ouled Amar Ben Cheikh has implemented a simple policy and ran Linux compile and redis benchmarks from openbenchmarking.org. The policy and runner is referred to as WMO (Workload Memory Optimization). The results were based on v3 of the series, but v4 doesn't change the core of the working set reporting and just adds the ballooning counterpart.

The timed Linux kernel compilation benchmark shows improvements in peak memory usage with a policy of "swap out all bytes colder than 10 seconds every 40 seconds". A swapfile is configured on SSD.
--------------------------------------------
peak memory usage (with WMO): 4982.61328 MiB
peak memory usage (control): 9569.1367 MiB
peak memory reduction: 47.9%
--------------------------------------------

Benchmark                                           | Experimental     |Control         | Experimental_Std_Dev | Control_Std_Dev
Timed Linux Kernel Compilation - allmodconfig (sec) | 708.486 (95.91%) | 679.499 (100%) | 0.6%                 | 0.1%

--------------------------------------------
Seconds, fewer is better

The redis benchmark shows employs the same policy:
--------------------------------------------
peak memory usage (with WMO): 375.9023 MiB peak memory usage (control): 509.765 MiB peak memory reduction: 26%
--------------------------------------------

Benchmark               | Experimental     | Control          | Experimental_Std_Dev | Control_Std_Dev
Redis - LPOP (Reqs/sec) | 2023130 (98.22%) | 2059849 (100%)   | 1.2%                 | 2%
Redis - SADD (Reqs/sec) | 2539662 (98.63%) | 2574811 (100%)   | 2.3%                 | 1.4%
Redis - LPUSH (Reqs/sec)| 2024880 (100%)   | 2000884 (98.81%) | 1.1%                 | 0.8%
Redis - GET (Reqs/sec)  | 2835764 (100%)   | 2763722 (97.46%) | 2.7%                 | 1.6%
Redis - SET (Reqs/sec)  | 2340723 (100%)   | 2327372 (99.43%) | 2.4%                 | 1.8%

--------------------------------------------
Reqs/sec, more is better

The detailed report and benchmarking results are in Ghait's repo:
https://github.com/miloudi98/WMO

Changelog
==========

Changes from PATCH v3 -> v4:
- Added documentation for cgroup-v2 (Waiman Long)
- Fixed types in documentation
(Randy Dunlap)
- Added implementation for the ballooning use case
- Added detailed description of benchmark results (Andrew Morton)

Changes from PATCH v2 -> v3:
- Fixed typos in commit messages and documentation (Lance Yang, Randy Dunlap)
- Split out the force_scan patch to be reviewed separately
- Added benchmarks from Ghait Ouled Amar Ben Cheikh
- Fixed reported compile error without CONFIG_MEMCG

Changes from PATCH v1 -> v2:
- Updated selftest to use ksft_test_result_code instead of switch-case (Muhammad Usama Anjum)
- Included more use cases in the cover letter
(Huang, Ying)
- Added documentation for sysfs and memcg interfaces
- Added an aging-specific struct lru_gen_mm_walk in struct pglist_data to avoid allocating for each lruvec.

[v1] https://lore.kernel.org/linux-mm/[email protected]/
[v2] https://lore.kernel.org/linux-mm/[email protected]/
[v3] https://lore.kernel.org/linux-mm/[email protected]/

Yuanchu Xie (9):
mm: aggregate workingset information into histograms
mm: use refresh interval to rate-limit workingset report aggregation
mm: report workingset during memory pressure driven scanning
mm: extend workingset reporting to memcgs
mm: add kernel aging thread for workingset reporting
selftest: test system-wide workingset reporting Docs/admin-guide/mm/workingset_report: document sysfs and memcg
interfaces
Docs/admin-guide/cgroup-v2: document workingset reporting
virtio-balloon: add workingset reporting

 Documentation/admin-guide/cgroup-v2.rst       |  35 +
 Documentation/admin-guide/mm/index.rst        |   1 +
 .../admin-guide/mm/workingset_report.rst      | 105 +++
 drivers/base/node.c                           |   6 +
 drivers/virtio/virtio_balloon.c               | 390 ++++++++++-
 include/linux/balloon_compaction.h            |   1 +
 include/linux/memcontrol.h                    |  21 +
 include/linux/mmzone.h                        |  13 +
 include/linux/workingset_report.h             | 167 +++++
 include/uapi/linux/virtio_balloon.h           |  30 +
 mm/Kconfig                                    |  15 +
 mm/Makefile                                   |   2 +
 mm/internal.h                                 |  19 +
 mm/memcontrol.c                               | 162 ++++-
 mm/mm_init.c                                  |   2 +
 mm/mmzone.c                                   |   2 +
 mm/vmscan.c                                   |  56 +-
 mm/workingset_report.c                        | 653 ++++++++++++++++++
 mm/workingset_report_aging.c                  | 127 ++++
 tools/testing/selftests/mm/.gitignore         |   1 +
 tools/testing/selftests/mm/Makefile           |   3 +
 tools/testing/selftests/mm/run_vmtests.sh     |   5 +
 .../testing/selftests/mm/workingset_report.c  | 306 ++++++++
 .../testing/selftests/mm/workingset_report.h  |  39 ++
 .../selftests/mm/workingset_report_test.c     | 330 +++++++++
 25 files changed, 2482 insertions(+), 9 deletions(-)
 create mode 100644 Documentation/admin-guide/mm/workingset_report.rst
 create mode 100644 include/linux/workingset_report.h
 create mode 100644 mm/workingset_report.c
 create mode 100644 mm/workingset_report_aging.c
 create mode 100644 tools/testing/selftests/mm/workingset_report.c
 create mode 100644 tools/testing/selftests/mm/workingset_report.h
 create mode 100644 tools/testing/selftests/mm/workingset_report_test.c
Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#1 lore raw

PATCH v4 1/9 mm: aggregate workingset information into histograms

Hierarchically aggregate all memcgs' MGLRU generations and their page counts into working set page age histograms.
The histograms break down the system's workingset per-node, per-anon/file.

The sysfs interfaces are as follows:
/sys/devices/system/node/nodeX/workingset_report/page_age
A per-node page age histogram, showing an aggregate of the node's lruvecs. The information is extracted from MGLRU's per-generation page counters. Reading this file causes a hierarchical aging of all lruvecs, scanning pages and creates a new generation in each lruvec.
For example:
1000 anon=0 file=0
2000 anon=0 file=0
100000 anon=5533696 file=5566464 18446744073709551615 anon=0 file=0

/sys/devices/system/node/nodeX/workingset_report/page_age_interval
A comma separated list of time in milliseconds that configures what the page age histogram uses for aggregation.

---
 drivers/base/node.c               |   6 +
 include/linux/mmzone.h            |   9 +
 include/linux/workingset_report.h |  79 ++++++
 mm/Kconfig                        |   9 +
 mm/Makefile                       |   1 +
 mm/internal.h                     |   5 +
 mm/memcontrol.c                   |   2 +
 mm/mm_init.c                      |   2 +
 mm/mmzone.c                       |   2 +
 mm/vmscan.c                       |  10 +-
 mm/workingset_report.c            | 451 ++++++++++++++++++++++++++++++
 11 files changed, 572 insertions(+), 4 deletions(-)
 create mode 100644 include/linux/workingset_report.h
 create mode 100644 mm/workingset_report.c
drivers/base/node.c +6 -0
index eb72580288e6..ba5b8720dbfa 100644
@@ -20,6 +20,8 @@
 #include <linux/pm_runtime.h>
 #include <linux/swap.h>
 #include <linux/slab.h>
+#include <linux/memcontrol.h>
+#include <linux/workingset_report.h>
 
 static const struct bus_type node_subsys = {
 	.name = "node",
@@ -626,6 +628,7 @@ static int register_node(struct node *node, int num)
 	} else {
 		hugetlb_register_node(node);
 		compaction_register_node(node);
+		wsr_init_sysfs(node);
 	}
 
 	return error;
@@ -642,6 +645,9 @@ void unregister_node(struct node *node)
 {
 	hugetlb_unregister_node(node);
 	compaction_unregister_node(node);
+	wsr_remove_sysfs(node);
+	wsr_destroy_lruvec(mem_cgroup_lruvec(NULL, NODE_DATA(node->dev.id)));
+	wsr_destroy_pgdat(NODE_DATA(node->dev.id));
 	node_remove_accesses(node);
 	node_remove_caches(node);
 	device_unregister(&node->dev);
include/linux/mmzone.h +9 -0
index 80bc5640bb60..ee728c0c5a3b 100644
@@ -24,6 +24,7 @@
 #include <linux/local_lock.h>
 #include <linux/zswap.h>
 #include <asm/page.h>
+#include <linux/workingset_report.h>
 
 /* Free memory management - zoned buddy allocator.  */
 #ifndef CONFIG_ARCH_FORCE_MAX_ORDER
@@ -630,6 +631,9 @@ struct lruvec {
 	struct lru_gen_mm_state		mm_state;
 #endif
 #endif /* CONFIG_LRU_GEN */
+#ifdef CONFIG_WORKINGSET_REPORT
+	struct wsr_state	wsr;
+#endif /* CONFIG_WORKINGSET_REPORT */
 #ifdef CONFIG_MEMCG
 	struct pglist_data *pgdat;
 #endif
@@ -1424,6 +1428,11 @@ typedef struct pglist_data {
 	struct lru_gen_memcg memcg_lru;
 #endif
 
+#ifdef CONFIG_WORKINGSET_REPORT
+	struct mutex wsr_update_mutex;
+	struct wsr_report_bins __rcu *wsr_page_age_bins;
+#endif
+
 	CACHELINE_PADDING(_pad2_);
 
 	/* Per-node vmstats */
include/linux/workingset_report.h new file +79 -0

79 lines not on this page · raw message

mm/Kconfig +9 -0
index 84000b016808..be949786796d 100644
@@ -1301,6 +1301,15 @@ config ARCH_HAS_USER_SHADOW_STACK
 	  The architecture has hardware support for userspace shadow call
           stacks (eg, x86 CET, arm64 GCS or RISC-V Zicfiss).
 
+config WORKINGSET_REPORT
+	bool "Working set reporting"
+	depends on LRU_GEN && SYSFS
+	help
+	  Report system and per-memcg working set to userspace.
+
+	  This option exports stats and events giving the user more insight
+	  into its memory working set.
+
 source "mm/damon/Kconfig"
 
 endmenu
mm/Makefile +1 -0
index d5639b036166..f5ef0768253a 100644
@@ -98,6 +98,7 @@ obj-$(CONFIG_TRANSPARENT_HUGEPAGE) += huge_memory.o khugepaged.o
 obj-$(CONFIG_PAGE_COUNTER) += page_counter.o
 obj-$(CONFIG_MEMCG_V1) += memcontrol-v1.o
 obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o
+obj-$(CONFIG_WORKINGSET_REPORT) += workingset_report.o
 ifdef CONFIG_SWAP
 obj-$(CONFIG_MEMCG) += swap_cgroup.o
 endif
mm/internal.h +5 -0
index 64c2eb0b160e..bbd3c1501bac 100644
@@ -470,9 +470,14 @@ extern unsigned long highest_memmap_pfn;
 /*
  * in mm/vmscan.c:
  */
+struct scan_control;
+bool isolate_lru_page(struct page *page);
 bool folio_isolate_lru(struct folio *folio);
 void folio_putback_lru(struct folio *folio);
 extern void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason);
+bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq, bool can_swap,
+			bool force_scan);
+void set_task_reclaim_state(struct task_struct *task, struct reclaim_state *rs);
 
 /*
  * in mm/rmap.c:
mm/memcontrol.c +2 -0
index 53db98d2c4a1..096856b35fbc 100644
@@ -63,6 +63,7 @@
 #include <linux/seq_buf.h>
 #include <linux/sched/isolation.h>
 #include <linux/kmemleak.h>
+#include <linux/workingset_report.h>
 #include "internal.h"
 #include <net/sock.h>
 #include <net/ip.h>
@@ -3453,6 +3454,7 @@ static void free_mem_cgroup_per_node_info(struct mem_cgroup *memcg, int node)
 	if (!pn)
 		return;
 
+	wsr_destroy_lruvec(&pn->lruvec);
 	free_percpu(pn->lruvec_stats_percpu);
 	kfree(pn->lruvec_stats);
 	kfree(pn);
mm/mm_init.c +2 -0
index 4ba5607aaf19..b4f7c904ce33 100644
@@ -30,6 +30,7 @@
 #include <linux/crash_dump.h>
 #include <linux/execmem.h>
 #include <linux/vmstat.h>
+#include <linux/workingset_report.h>
 #include "internal.h"
 #include "slab.h"
 #include "shuffle.h"
@@ -1378,6 +1379,7 @@ static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
 
 	pgdat_page_ext_init(pgdat);
 	lruvec_init(&pgdat->__lruvec);
+	wsr_init_pgdat(pgdat);
 }
 
 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
mm/mmzone.c +2 -0
index f9baa8882fbf..0352a2018067 100644
@@ -90,6 +90,8 @@ void lruvec_init(struct lruvec *lruvec)
 	 */
 	list_del(&lruvec->lists[LRU_UNEVICTABLE]);
 
+	wsr_init_lruvec(lruvec);
+
 	lru_gen_init_lruvec(lruvec);
 }
 
mm/vmscan.c +6 -4
index 28ba2b06fc7d..89da4d8dfb5f 100644
@@ -57,6 +57,7 @@
 #include <linux/rculist_nulls.h>
 #include <linux/random.h>
 #include <linux/mmu_notifier.h>
+#include <linux/workingset_report.h>
 
 #include <asm/tlbflush.h>
 #include <asm/div64.h>
@@ -271,8 +272,7 @@ static int sc_swappiness(struct scan_control *sc, struct mem_cgroup *memcg)
 }
 #endif
 
-static void set_task_reclaim_state(struct task_struct *task,
-				   struct reclaim_state *rs)
+void set_task_reclaim_state(struct task_struct *task, struct reclaim_state *rs)
 {
 	/* Check for an overwrite */
 	WARN_ON_ONCE(rs && task->reclaim_state);
@@ -3861,8 +3861,8 @@ static bool inc_max_seq(struct lruvec *lruvec, unsigned long seq,
 	return success;
 }
 
-static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq,
-			       bool can_swap, bool force_scan)
+bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq, bool can_swap,
+			bool force_scan)
 {
 	bool success;
 	struct lru_gen_mm_walk *walk;
@@ -5640,6 +5640,8 @@ static int __init init_lru_gen(void)
 	if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
 		pr_err("lru_gen: failed to create sysfs group\n");
 
+	wsr_init_sysfs(NULL);
+
 	debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
 	debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
 
mm/workingset_report.c new file +451 -0

451 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
#2 lore raw

Re: [PATCH v4 1/9] mm: aggregate workingset information into histograms

mm/internal.h extern unsigned long highest_memmap_pfn; · line 474

Quoted 10 lines · Yuanchu Xie
mm/internal.h +2 -0
index 64c2eb0b160e..bbd3c1501bac 100644
@@ -470,9 +470,14 @@ extern unsigned long highest_memmap_pfn;
 /*
  * in mm/vmscan.c:
  */
+struct scan_control;
+bool isolate_lru_page(struct page *page);

Is this a mismerge? It doesn't exist any more.

author reviewer
#3 lore raw

Re: [PATCH v4 1/9] mm: aggregate workingset information into histograms

Quoted 14 lines · Matthew Wilcox

mm/internal.h extern unsigned long highest_memmap_pfn; · line 474

Quoted 10 lines · Yuanchu Xie
mm/internal.h +2 -0
index 64c2eb0b160e..bbd3c1501bac 100644
@@ -470,9 +470,14 @@ extern unsigned long highest_memmap_pfn;
 /*
  * in mm/vmscan.c:
  */
+struct scan_control;
+bool isolate_lru_page(struct page *page);

Is this a mismerge? It doesn't exist any more.

Yes this is a mismerge. I'll fix it in the next version.

author reviewer
#4 lore raw

PATCH v4 2/9 mm: use refresh interval to rate-limit workingset report aggregation

In reply to Yuanchu Xie

The refresh interval is a rate limiting factor to workingset page age histogram reads. When a workingset report is generated, the oldest timestamp of all the lruvecs is stored as the timestamp of the report. The same report will be read until the report expires beyond the refresh interval, at which point a new report is generated.

Sysfs interface /sys/devices/system/node/nodeX/workingset_report/refresh_interval
time in milliseconds specifying how long the report is valid for

---
 include/linux/workingset_report.h |   1 +
 mm/workingset_report.c            | 101 ++++++++++++++++++++++++------
 2 files changed, 83 insertions(+), 19 deletions(-)
include/linux/workingset_report.h +1 -0
index d7c2ee14ec87..8bae6a600410 100644
@@ -37,6 +37,7 @@ struct wsr_page_age_histo {
 };
 
 struct wsr_state {
+	unsigned long refresh_interval;
 	/* breakdown of workingset by page age */
 	struct mutex page_age_lock;
 	struct wsr_page_age_histo *page_age;
mm/workingset_report.c +82 -19

174 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#5 lore raw

PATCH v4 3/9 mm: report workingset during memory pressure driven scanning

In reply to Yuanchu Xie

When a node reaches its low watermarks and wakes up kswapd, notify all userspace programs waiting on the workingset page age histogram of the memory pressure, so a userspace agent can read the workingset report in time and make policy decisions, such as logging, oom-killing, or migration.

Sysfs interface:
/sys/devices/system/node/nodeX/workingset_report/report_threshold
time in milliseconds that specifies how often the userspace agent can be notified for node memory pressure.

---
 include/linux/workingset_report.h |  4 +++
 mm/internal.h                     | 12 ++++++++
 mm/vmscan.c                       | 46 +++++++++++++++++++++++++++++++
 mm/workingset_report.c            | 43 ++++++++++++++++++++++++++++-
 4 files changed, 104 insertions(+), 1 deletion(-)
include/linux/workingset_report.h +4 -0
index 8bae6a600410..2ec8b927b200 100644
@@ -37,7 +37,11 @@ struct wsr_page_age_histo {
 };
 
 struct wsr_state {
+	unsigned long report_threshold;
 	unsigned long refresh_interval;
+
+	struct kernfs_node *page_age_sys_file;
+
 	/* breakdown of workingset by page age */
 	struct mutex page_age_lock;
 	struct wsr_page_age_histo *page_age;
mm/internal.h +12 -0
index bbd3c1501bac..508b7d9937d6 100644
@@ -479,6 +479,18 @@ bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long seq, bool can_swap,
 			bool force_scan);
 void set_task_reclaim_state(struct task_struct *task, struct reclaim_state *rs);
 
+#ifdef CONFIG_WORKINGSET_REPORT
+/*
+ * in mm/wsr.c
+ */
+void notify_workingset(struct mem_cgroup *memcg, struct pglist_data *pgdat);
+#else
+static inline void notify_workingset(struct mem_cgroup *memcg,
+				     struct pglist_data *pgdat)
+{
+}
+#endif
+
 /*
  * in mm/rmap.c:
  */
mm/vmscan.c +46 -0

70 lines not on this page · raw message

mm/workingset_report.c +42 -1

68 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#6 lore raw

PATCH v4 4/9 mm: extend workingset reporting to memcgs

In reply to Yuanchu Xie

Break down the system-wide workingset report into per-memcg reports, which aggregages its children hierarchically.

The per-node workingset reporting histograms and refresh/report threshold files are presented as memcg files, showing a report containing all the nodes.

The per-node page age interval is configurable in sysfs and not available per-memcg, while the refresh interval and report threshold are configured per-memcg.

Memcg interface:
/sys/fs/cgroup/.../memory.workingset.page_age

	The memcg equivalent of the sysfs workingset page age histogram
	breaks down the workingset of this memcg and its children into
	page age intervals. Each node is prefixed with a node header and
	a newline. Non-proactive direct reclaim on this memcg can also
	wake up userspace agents that are waiting on this file.
	e.g.
	N0
	1000 anon=0 file=0
	2000 anon=0 file=0
	3000 anon=0 file=0
	4000 anon=0 file=0
	5000 anon=0 file=0
	18446744073709551615 anon=0 file=0

/sys/fs/cgroup/.../memory.workingset.refresh_interval
The memcg equivalent of the sysfs refresh interval. A per-node number of how much time a page age histogram is valid for, in milliseconds.
e.g.
echo N0=2000 > memory.workingset.refresh_interval

/sys/fs/cgroup/.../memory.workingset.report_threshold
The memcg equivalent of the sysfs report threshold. A per-node number of how often userspace agent waiting on the page age histogram can be woken up, in milliseconds.
e.g.
echo N0=1000 > memory.workingset.report_threshold

---
 include/linux/memcontrol.h        |  21 ++++
 include/linux/workingset_report.h |  15 ++-
 mm/internal.h                     |   2 +
 mm/memcontrol.c                   | 160 +++++++++++++++++++++++++++++-
 mm/workingset_report.c            |  50 +++++++---
 5 files changed, 230 insertions(+), 18 deletions(-)
include/linux/memcontrol.h +21 -0
index e1b41554a5fb..fd595b33a54d 100644
@@ -323,6 +323,11 @@ struct mem_cgroup {
 	spinlock_t event_list_lock;
 #endif /* CONFIG_MEMCG_V1 */
 
+#ifdef CONFIG_WORKINGSET_REPORT
+	/* memory.workingset.page_age file */
+	struct cgroup_file workingset_page_age_file;
+#endif
+
 	struct mem_cgroup_per_node *nodeinfo[];
 };
 
@@ -1094,6 +1099,16 @@ static inline void memcg_memory_event_mm(struct mm_struct *mm,
 
 void split_page_memcg(struct page *head, int old_order, int new_order);
 
+static inline struct cgroup_file *
+mem_cgroup_page_age_file(struct mem_cgroup *memcg)
+{
+#ifdef CONFIG_WORKINGSET_REPORT
+	return &memcg->workingset_page_age_file;
+#else
+	return NULL;
+#endif
+}
+
 #else /* CONFIG_MEMCG */
 
 #define MEM_CGROUP_ID_SHIFT	0
@@ -1511,6 +1526,12 @@ void count_memcg_event_mm(struct mm_struct *mm, enum vm_event_item idx)
 static inline void split_page_memcg(struct page *head, int old_order, int new_order)
 {
 }
+
+static inline struct cgroup_file *
+mem_cgroup_page_age_file(struct mem_cgroup *memcg)
+{
+	return NULL;
+}
 #endif /* CONFIG_MEMCG */
 
 /*
include/linux/workingset_report.h +14 -1
index 2ec8b927b200..616be6469768 100644
@@ -9,6 +9,8 @@ struct mem_cgroup;
 struct pglist_data;
 struct node;
 struct lruvec;
+struct cgroup_file;
+struct wsr_state;
 
 #ifdef CONFIG_WORKINGSET_REPORT
 
@@ -40,7 +42,10 @@ struct wsr_state {
 	unsigned long report_threshold;
 	unsigned long refresh_interval;
 
-	struct kernfs_node *page_age_sys_file;
+	union {
+		struct kernfs_node *page_age_sys_file;
+		struct cgroup_file *page_age_cgroup_file;
+	};
 
 	/* breakdown of workingset by page age */
 	struct mutex page_age_lock;
@@ -60,6 +65,9 @@ void wsr_remove_sysfs(struct node *node);
  */
 bool wsr_refresh_report(struct wsr_state *wsr, struct mem_cgroup *root,
 			struct pglist_data *pgdat);
+
+int wsr_set_refresh_interval(struct wsr_state *wsr,
+			     unsigned long refresh_interval);
 #else
 static inline void wsr_init_lruvec(struct lruvec *lruvec)
 {
@@ -79,6 +87,11 @@ static inline void wsr_init_sysfs(struct node *node)
 static inline void wsr_remove_sysfs(struct node *node)
 {
 }
+static inline int wsr_set_refresh_interval(struct wsr_state *wsr,
+					   unsigned long refresh_interval)
+{
+	return 0;
+}
 #endif /* CONFIG_WORKINGSET_REPORT */
 
 #endif /* _LINUX_WORKINGSET_REPORT_H */
mm/internal.h +2 -0
index 508b7d9937d6..50ca0c6e651c 100644
@@ -484,6 +484,8 @@ void set_task_reclaim_state(struct task_struct *task, struct reclaim_state *rs);
  * in mm/wsr.c
  */
 void notify_workingset(struct mem_cgroup *memcg, struct pglist_data *pgdat);
+int workingset_report_intervals_parse(char *src,
+				      struct wsr_report_bins *bins);
 #else
 static inline void notify_workingset(struct mem_cgroup *memcg,
 				     struct pglist_data *pgdat)
mm/memcontrol.c +159 -1

172 lines not on this page · raw message

mm/workingset_report.c +34 -16

92 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#7 lore raw

PATCH v4 5/9 mm: add kernel aging thread for workingset reporting

In reply to Yuanchu Xie

For reliable and timely aging on memcgs, one has to read the page age histograms on time. A kernel thread makes it easier by aging memcgs with valid refresh_interval when they can be refreshed, and also reduces the latency of any userspace consumers of the page age histogram.

The kerne aging thread is gated behind CONFIG_WORKINGSET_REPORT_AGING. Debugging stats may be added in the future for when aging cannot keep up with the configured refresh_interval.

---
 include/linux/workingset_report.h |  10 ++-
 mm/Kconfig                        |   6 ++
 mm/Makefile                       |   1 +
 mm/memcontrol.c                   |   2 +-
 mm/workingset_report.c            |  13 ++-
 mm/workingset_report_aging.c      | 127 ++++++++++++++++++++++++++++++
 6 files changed, 154 insertions(+), 5 deletions(-)
 create mode 100644 mm/workingset_report_aging.c
include/linux/workingset_report.h +9 -1
index 616be6469768..f6bbde2a04c3 100644
@@ -64,7 +64,15 @@ void wsr_remove_sysfs(struct node *node);
  * The next refresh time is stored in refresh_time.
  */
 bool wsr_refresh_report(struct wsr_state *wsr, struct mem_cgroup *root,
-			struct pglist_data *pgdat);
+			struct pglist_data *pgdat, unsigned long *refresh_time);
+
+#ifdef CONFIG_WORKINGSET_REPORT_AGING
+void wsr_wakeup_aging_thread(void);
+#else /* CONFIG_WORKINGSET_REPORT_AGING */
+static inline void wsr_wakeup_aging_thread(void)
+{
+}
+#endif /* CONFIG_WORKINGSET_REPORT_AGING */
 
 int wsr_set_refresh_interval(struct wsr_state *wsr,
 			     unsigned long refresh_interval);
mm/Kconfig +6 -0
index be949786796d..a8def8c65610 100644
@@ -1310,6 +1310,12 @@ config WORKINGSET_REPORT
 	  This option exports stats and events giving the user more insight
 	  into its memory working set.
 
+config WORKINGSET_REPORT_AGING
+	bool "Workingset report kernel aging thread"
+	depends on WORKINGSET_REPORT
+	help
+	  Performs aging on memcgs with their configured refresh intervals.
+
 source "mm/damon/Kconfig"
 
 endmenu
mm/Makefile +1 -0
index f5ef0768253a..3a282510f960 100644
@@ -99,6 +99,7 @@ obj-$(CONFIG_PAGE_COUNTER) += page_counter.o
 obj-$(CONFIG_MEMCG_V1) += memcontrol-v1.o
 obj-$(CONFIG_MEMCG) += memcontrol.o vmpressure.o
 obj-$(CONFIG_WORKINGSET_REPORT) += workingset_report.o
+obj-$(CONFIG_WORKINGSET_REPORT_AGING) += workingset_report_aging.o
 ifdef CONFIG_SWAP
 obj-$(CONFIG_MEMCG) += swap_cgroup.o
 endif
mm/memcontrol.c +1 -1
index d1032c6efc66..ea83f10b22a1 100644
@@ -4462,7 +4462,7 @@ static int memory_ws_page_age_show(struct seq_file *m, void *v)
 		if (!READ_ONCE(wsr->page_age))
 			continue;
 
-		wsr_refresh_report(wsr, memcg, NODE_DATA(nid));
+		wsr_refresh_report(wsr, memcg, NODE_DATA(nid), NULL);
 		mutex_lock(&wsr->page_age_lock);
 		if (!wsr->page_age)
 			goto unlock;
mm/workingset_report.c +10 -3
index 1e1bdb8bf75b..dad539e602bb 100644
@@ -283,7 +283,7 @@ static void copy_node_bins(struct pglist_data *pgdat,
 }
 
 bool wsr_refresh_report(struct wsr_state *wsr, struct mem_cgroup *root,
-			struct pglist_data *pgdat)
+			struct pglist_data *pgdat, unsigned long *refresh_time)
 {
 	struct wsr_page_age_histo *page_age;
 	unsigned long refresh_interval = READ_ONCE(wsr->refresh_interval);
@@ -300,10 +300,14 @@ bool wsr_refresh_report(struct wsr_state *wsr, struct mem_cgroup *root,
 		goto unlock;
 	if (page_age->timestamp &&
 	    time_is_after_jiffies(page_age->timestamp + refresh_interval))
-		goto unlock;
+		goto time;
 	refresh_scan(wsr, root, pgdat, refresh_interval);
 	copy_node_bins(pgdat, page_age);
 	refresh_aggregate(page_age, root, pgdat);
+
+time:
+	if (refresh_time)
+		*refresh_time = page_age->timestamp + refresh_interval;
 unlock:
 	mutex_unlock(&wsr->page_age_lock);
 	return !!page_age;
@@ -386,6 +390,9 @@ int wsr_set_refresh_interval(struct wsr_state *wsr,
 	WRITE_ONCE(wsr->refresh_interval, msecs_to_jiffies(refresh_interval));
 unlock:
 	mutex_unlock(&wsr->page_age_lock);
+	if (!err && refresh_interval &&
+	    (!old_interval || jiffies_to_msecs(old_interval) > refresh_interval))
+		wsr_wakeup_aging_thread();
 	return err;
 }
 
@@ -491,7 +498,7 @@ static ssize_t page_age_show(struct kobject *kobj, struct kobj_attribute *attr,
 	int ret = 0;
 	struct wsr_state *wsr = kobj_to_wsr(kobj);
 
-	wsr_refresh_report(wsr, NULL, kobj_to_pgdat(kobj));
+	wsr_refresh_report(wsr, NULL, kobj_to_pgdat(kobj), NULL);
 
 	mutex_lock(&wsr->page_age_lock);
 	if (!wsr->page_age)
mm/workingset_report_aging.c new file +127 -0

127 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#8 lore raw

PATCH v4 6/9 selftest: test system-wide workingset reporting

In reply to Yuanchu Xie

A basic test that verifies the working set size of a simple memory accessor. It should work with or without the aging thread.

When running tests with run_vmtests.sh, file workingset report testing requires an environment variable WORKINGSET_REPORT_TEST_FILE_PATH to store a temporary file, which is passed into the test invocation as a parameter.

---
 tools/testing/selftests/mm/.gitignore         |   1 +
 tools/testing/selftests/mm/Makefile           |   3 +
 tools/testing/selftests/mm/run_vmtests.sh     |   5 +
 .../testing/selftests/mm/workingset_report.c  | 306 ++++++++++++++++
 .../testing/selftests/mm/workingset_report.h  |  39 +++
 .../selftests/mm/workingset_report_test.c     | 330 ++++++++++++++++++
 6 files changed, 684 insertions(+)
 create mode 100644 tools/testing/selftests/mm/workingset_report.c
 create mode 100644 tools/testing/selftests/mm/workingset_report.h
 create mode 100644 tools/testing/selftests/mm/workingset_report_test.c
tools/testing/selftests/mm/.gitignore +1 -0
index da030b43e43b..e5cd0085ab74 100644
@@ -51,3 +51,4 @@ hugetlb_madv_vs_map
 mseal_test
 seal_elf
 droppable
+workingset_report_test
tools/testing/selftests/mm/Makefile +3 -0
index 0f8c110e0805..5c6a7464da6e 100644
@@ -79,6 +79,7 @@ TEST_GEN_FILES += hugetlb_fault_after_madv
 TEST_GEN_FILES += hugetlb_madv_vs_map
 TEST_GEN_FILES += hugetlb_dio
 TEST_GEN_FILES += droppable
+TEST_GEN_FILES += workingset_report_test
 
 ifneq ($(ARCH),arm64)
 TEST_GEN_FILES += soft-dirty
@@ -138,6 +139,8 @@ $(TEST_GEN_FILES): vm_util.c thp_settings.c
 $(OUTPUT)/uffd-stress: uffd-common.c
 $(OUTPUT)/uffd-unit-tests: uffd-common.c
 
+$(OUTPUT)/workingset_report_test: workingset_report.c
+
 ifeq ($(ARCH),x86_64)
 BINARIES_32 := $(patsubst %,$(OUTPUT)/%,$(BINARIES_32))
 BINARIES_64 := $(patsubst %,$(OUTPUT)/%,$(BINARIES_64))
tools/testing/selftests/mm/run_vmtests.sh +5 -0
index c5797ad1d37b..63782667381a 100755
@@ -75,6 +75,8 @@ separated by spaces:
 	read-only VMAs
 - mdwe
 	test prctl(PR_SET_MDWE, ...)
+- workingset_report
+	test workingset reporting
 
 example: ./run_vmtests.sh -t "hmm mmap ksm"
 EOF
@@ -456,6 +458,9 @@ CATEGORY="mkdirty" run_test ./mkdirty
 
 CATEGORY="mdwe" run_test ./mdwe_test
 
+CATEGORY="workingset_report" run_test ./workingset_report_test \
+  "${WORKINGSET_REPORT_TEST_FILE_PATH}"
+
 echo "SUMMARY: PASS=${count_pass} SKIP=${count_skip} FAIL=${count_fail}" | tap_prefix
 echo "1..${count_total}" | tap_output
 
tools/testing/selftests/mm/workingset_report.c new file +306 -0

306 lines not on this page · raw message

tools/testing/selftests/mm/workingset_report.h new file +39 -0
new file mode 100644
index 000000000000..c5c281e4069b
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef WORKINGSET_REPORT_H_
+#define WORKINGSET_REPORT_H_
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+#define PAGETYPE_ANON 0
+#define PAGETYPE_FILE 1
+#define ANON_AND_FILE 2
+
+int get_nr_nodes(void);
+int drop_pagecache(void);
+
+long sysfs_get_refresh_interval(int nid);
+int sysfs_set_refresh_interval(int nid, long interval);
+
+int sysfs_get_page_age_intervals_str(int nid, char *buf, int len);
+int sysfs_set_page_age_intervals_str(int nid, const char *buf, int len);
+
+int sysfs_set_page_age_intervals(int nid, const char *const intervals[],
+				 int nr_intervals);
+
+char *page_age_split_node(char *buf, int nid, char **next);
+ssize_t sysfs_page_age_read(int nid, char *buf, size_t len);
+ssize_t page_age_read(const char *buf, const char *interval, int pagetype);
+
+int alloc_file_workingset(void *arg);
+void cleanup_file_workingset(void);
+int alloc_anon_workingset(void *arg);
+
+#endif /* WORKINGSET_REPORT_H_ */
tools/testing/selftests/mm/workingset_report_test.c new file +330 -0

330 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#9 lore raw

PATCH v4 7/9 Docs/admin-guide/mm/workingset_report: document sysfs and memcg interfaces

In reply to Yuanchu Xie

Add workingset reporting documentation for better discoverability of its sysfs and memcg interfaces. Also document the required kernel config to enable workingset reporting.

---
 Documentation/admin-guide/mm/index.rst        |   1 +
 .../admin-guide/mm/workingset_report.rst      | 105 ++++++++++++++++++
 2 files changed, 106 insertions(+)
 create mode 100644 Documentation/admin-guide/mm/workingset_report.rst
Documentation/admin-guide/mm/index.rst +1 -0
index 8b35795b664b..61a2a347fc91 100644
@@ -41,4 +41,5 @@ the Linux memory management.
    swap_numa
    transhuge
    userfaultfd
+   workingset_report
    zswap
Documentation/admin-guide/mm/workingset_report.rst new file +105 -0

105 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#10 lore raw

PATCH v4 8/9 Docs/admin-guide/cgroup-v2: document workingset reporting

In reply to Yuanchu Xie

Add workingset reporting documentation for better discoverability of its memcg interfaces. Point the memcg documentation to Documentation/admin-guide/mm/workingset_report.rst for more details.

---
 Documentation/admin-guide/cgroup-v2.rst | 35 +++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
Documentation/admin-guide/cgroup-v2.rst +35 -0
index 2cb58daf3089..67a183f08245 100644
@@ -1784,6 +1784,41 @@ The following nested keys are defined.
 	Shows pressure stall information for memory. See
 	:ref:`Documentation/accounting/psi.rst <psi>` for details.
 
+  memory.workingset.page_age
+	A read-only histogram which exists on non-root cgroups.
+
+	This breaks down the cgroup's memory footprint into different
+	types of memory and groups them per-node into user-defined coldness
+	bins.
+
+	The output format of memory.workingset.page_age is::
+
+	  N0
+	  <interval 0 of node 0> type=<type bytes in interval 0 of node 0>
+	  <interval 1 of node 0> type=<type bytes in interval 1 of node 0>
+	  ...
+	  18446744073709551615 type=<the rest of type bytes of node 0>
+
+	The type of memory can be anon, file, or new types added later.
+	Don't rely on the types remaining fixed.  See
+	:ref:`Documentation/admin-guide/mm/workingset_report.rst <workingset_report>`
+	for details.
+
+  memory.workingset.refresh_interval
+	A read-write nested-keyed file which exists on non-root cgroups.
+
+	Setting it to a non-zero value for any node enables working set
+	reporting for that node.  The default is 0 for each node.   See
+	:ref:`Documentation/admin-guide/mm/workingset_report.rst <workingset_report>`
+	for details.
+
+  memory.workingset.report_threshold
+	A read-write nested-keyed file which exists on non-root cgroups.
+
+	The amount of milliseconds to wait before reporting the working
+	set again.  The default is 0 for each node.  See
+	:ref:`Documentation/admin-guide/mm/workingset_report.rst <workingset_report>`
+	for details.
 
 Usage Guidelines
 ~~~~~~~~~~~~~~~~
Signature · 1 line
2.47.0.338.g60cca15819-goog
author reviewer
#11 lore raw

PATCH v4 9/9 virtio-balloon: add workingset reporting

In reply to Yuanchu Xie

Ballooning is a way to dynamically size a VM, and it requires guest collaboration. The amount to balloon without adversely affecting guest performance is hard to compute without clear metrics from the guest.

Workingset reporting can provide guidance to the host to allow better collaborative ballooning, such that the host balloon controller can properly gauge the amount of memory the guest is actively using, i.e., the working set.

A draft QEMU series [1] is being worked on. Currently it is able to configure the workingset reporting bins, refresh_interval, and report threshold. Through QMP or HMP, a balloon controller can request a workingset report. There is also a script [2] exercising the QMP interface with a visual breakdown of the guest's workingset size.

According to the OASIS VIRTIO v1.3, there's a new balloon device in the works and this one I'm adding to is the "traditional" balloon. If the existing balloon device is not the right place for new features. I'm more than happy to add it to the new one as well.

For technical details, this patch adds the a generic mechanism into workingset reporting infrastructure to allow other parts of the kernel to receive workingset reports. Two virtqueues are added to the virtio-balloon device, notification_vq and report_vq. The notification virtqueue allows the host to configure the guest workingset reporting parameters and request a report. The report virtqueue sends a working set report to the host when one is requested or due to memory pressure.

The workingset reporting feature is gated by the compilation flag CONFIG_WORKINGSET_REPORT and the balloon feature flag VIRTIO_BALLOON_F_WS_REPORTING.

[1] https://github.com/Dummyc0m/qemu/tree/wsr
[2] https://gist.github.com/Dummyc0m/d45b4e1b0dda8f2bc6cd8cfb37cc7e34

---
 drivers/virtio/virtio_balloon.c     | 390 +++++++++++++++++++++++++++-
 include/linux/balloon_compaction.h  |   1 +
 include/linux/mmzone.h              |   4 +
 include/linux/workingset_report.h   |  66 ++++-
 include/uapi/linux/virtio_balloon.h |  30 +++
 mm/workingset_report.c              |  89 ++++++-
 6 files changed, 566 insertions(+), 14 deletions(-)
drivers/virtio/virtio_balloon.c +386 -4
index b36d2803674e..8eb300653dd8 100644
@@ -18,6 +18,7 @@
 #include <linux/wait.h>
 #include <linux/mm.h>
 #include <linux/page_reporting.h>
+#include <linux/workingset_report.h>
 
 /*
  * Balloon device works in 4K page units.  So each page is pointed to by
@@ -45,6 +46,8 @@ enum virtio_balloon_vq {
 	VIRTIO_BALLOON_VQ_STATS,
 	VIRTIO_BALLOON_VQ_FREE_PAGE,
 	VIRTIO_BALLOON_VQ_REPORTING,
+	VIRTIO_BALLOON_VQ_WORKING_SET,
+	VIRTIO_BALLOON_VQ_NOTIFY,
 	VIRTIO_BALLOON_VQ_MAX
 };
 
@@ -124,6 +127,23 @@ struct virtio_balloon {
 	spinlock_t wakeup_lock;
 	bool processing_wakeup_event;
 	u32 wakeup_signal_mask;
+
+#ifdef CONFIG_WORKINGSET_REPORT
+	struct virtqueue *working_set_vq, *notification_vq;
+
+	/* Protects node_id, wsr_receiver, and report_buf */
+	struct mutex wsr_report_lock;
+	int wsr_node_id;
+	struct wsr_receiver wsr_receiver;
+	/* Buffer to report to host */
+	struct virtio_balloon_working_set_report *report_buf;
+
+	/* Buffer to hold incoming notification from the host. */
+	struct virtio_balloon_working_set_notify *notify_buf;
+
+	struct work_struct update_balloon_working_set_work;
+	struct work_struct update_balloon_notification_work;
+#endif
 };
 
 #define VIRTIO_BALLOON_WAKEUP_SIGNAL_ADJUST (1 << 0)
@@ -339,8 +359,352 @@ static unsigned int leak_balloon(struct virtio_balloon *vb, size_t num)
 	return num_freed_pages;
 }
 
-static inline void update_stat(struct virtio_balloon *vb, int idx,
-			       u16 tag, u64 val)
+#ifdef CONFIG_WORKINGSET_REPORT
+static bool wsr_is_configured(struct virtio_balloon *vb)
+{
+	if (node_online(READ_ONCE(vb->wsr_node_id)) &&
+	    READ_ONCE(vb->wsr_receiver.wsr.refresh_interval) > 0 &&
+	    READ_ONCE(vb->wsr_receiver.wsr.page_age) != NULL)
+		return true;
+	return false;
+}
+
+/* wsr_receiver callback */
+static void wsr_receiver_notify(struct wsr_receiver *receiver)
+{
+	int bin;
+	struct virtio_balloon *vb =
+		container_of(receiver, struct virtio_balloon, wsr_receiver);
+
+	/* if we fail to acquire the locks, send stale report */
+	if (!mutex_trylock(&vb->wsr_report_lock))
+		goto out;
+	if (!mutex_trylock(&receiver->wsr.page_age_lock))
+		goto out_unlock_report_buf;
+	if (!READ_ONCE(receiver->wsr.page_age))
+		goto out_unlock_page_age;
+
+	vb->report_buf->error = cpu_to_le32(0);
+	vb->report_buf->node_id = cpu_to_le32(vb->wsr_node_id);
+	for (bin = 0; bin < WORKINGSET_REPORT_MAX_NR_BINS; ++bin) {
+		struct virtio_balloon_working_set_report_bin *dest =
+			&vb->report_buf->bins[bin];
+		struct wsr_report_bin *src = &receiver->wsr.page_age->bins[bin];
+
+		dest->anon_bytes =
+			cpu_to_le64(src->nr_pages[LRU_GEN_ANON] * PAGE_SIZE);
+		dest->file_bytes =
+			cpu_to_le64(src->nr_pages[LRU_GEN_FILE] * PAGE_SIZE);
+		if (src->idle_age == WORKINGSET_INTERVAL_MAX) {
+			dest->idle_age = cpu_to_le64(WORKINGSET_INTERVAL_MAX);
+			break;
+		}
+		dest->idle_age = cpu_to_le64(jiffies_to_msecs(src->idle_age));
+	}
+
+out_unlock_page_age:
+	mutex_unlock(&receiver->wsr.page_age_lock);
+out_unlock_report_buf:
+	mutex_unlock(&vb->wsr_report_lock);
+out:
+	/* Send the working set report to the device. */
+	spin_lock(&vb->stop_update_lock);
+	if (!vb->stop_update)
+		queue_work(system_freezable_wq, &vb->update_balloon_working_set_work);
+	spin_unlock(&vb->stop_update_lock);
+}
+
+static void virtio_balloon_working_set_request(struct virtio_balloon *vb,
+					       int nid)
+{
+	int err = 0;
+
+	if (!node_online(nid)) {
+		err = -EINVAL;
+		goto error;
+	}
+
+	err = wsr_refresh_receiver_report(NODE_DATA(nid));
+	if (err)
+		goto error;
+
+	return;
+error:
+	mutex_lock(&vb->wsr_report_lock);
+	vb->report_buf->error = cpu_to_le16(err);
+	vb->report_buf->node_id = cpu_to_le32(nid);
+	mutex_unlock(&vb->wsr_report_lock);
+	spin_lock(&vb->stop_update_lock);
+	if (!vb->stop_update)
+		queue_work(system_freezable_wq,
+			   &vb->update_balloon_working_set_work);
+	spin_unlock(&vb->stop_update_lock);
+}
+
+static void notification_receive(struct virtqueue *vq)
+{
+	struct virtio_balloon *vb = vq->vdev->priv;
+
+	spin_lock(&vb->stop_update_lock);
+	if (!vb->stop_update)
+		queue_work(system_freezable_wq, &vb->update_balloon_notification_work);
+	spin_unlock(&vb->stop_update_lock);
+}
+
+static int
+virtio_balloon_register_working_set_receiver(struct virtio_balloon *vb)
+{
+	struct pglist_data *pgdat;
+	struct wsr_report_bins *bins = NULL, __rcu *old;
+	int nid, bin, err = 0, old_nid = vb->wsr_node_id;
+	struct virtio_balloon_working_set_notify *notify = vb->notify_buf;
+
+	nid = le16_to_cpu(notify->node_id);
+	if (!node_online(nid)) {
+		dev_warn(&vb->vdev->dev, "node not online %d\n", nid);
+		return -EINVAL;
+	}
+
+	pgdat = NODE_DATA(nid);
+	bins = kzalloc(sizeof(struct wsr_report_bins), GFP_KERNEL);
+
+	if (!bins)
+		return -ENOMEM;
+
+	for (bin = 0; bin < WORKINGSET_REPORT_MAX_NR_BINS; ++bin) {
+		u32 age_msecs = le32_to_cpu(notify->idle_age[bin]);
+		unsigned long age = msecs_to_jiffies(age_msecs);
+
+		/*
+		 * A correct idle_age array should end in
+		 * WORKINGSET_INTERVAL_MAX.
+		 */
+		if (age_msecs == (u32)WORKINGSET_INTERVAL_MAX) {
+			bins->idle_age[bin] = WORKINGSET_INTERVAL_MAX;
+			break;
+		}
+		bins->idle_age[bin] = age;
+		if (bin > 0 && bins->idle_age[bin] <= bins->idle_age[bin - 1]) {
+			dev_warn(&vb->vdev->dev, "bins not increasing\n");
+			err = -EINVAL;
+			goto error;
+		}
+	}
+	if (bin < WORKINGSET_REPORT_MIN_NR_BINS - 1 ||
+	    bin == WORKINGSET_REPORT_MAX_NR_BINS) {
+		err = -ERANGE;
+		goto error;
+	}
+	bins->nr_bins = bin;
+
+	mutex_lock(&vb->wsr_report_lock);
+	err = wsr_set_refresh_interval(
+		&vb->wsr_receiver.wsr,
+		le32_to_cpu(notify->refresh_interval));
+	if (err) {
+		mutex_unlock(&vb->wsr_report_lock);
+		goto error;
+	}
+	if (old_nid != NUMA_NO_NODE)
+		wsr_remove_receiver(&vb->wsr_receiver, NODE_DATA(old_nid));
+	WRITE_ONCE(vb->wsr_node_id, nid);
+	WRITE_ONCE(vb->wsr_receiver.wsr.report_threshold,
+		   msecs_to_jiffies(le32_to_cpu(notify->report_threshold)));
+	WRITE_ONCE(vb->wsr_receiver.notify, wsr_receiver_notify);
+	mutex_unlock(&vb->wsr_report_lock);
+
+	/* update the bins for target node */
+	mutex_lock(&pgdat->wsr_update_mutex);
+	old = rcu_replace_pointer(pgdat->wsr_page_age_bins, bins,
+				  lockdep_is_held(&pgdat->wsr_update_mutex));
+	mutex_unlock(&pgdat->wsr_update_mutex);
+	kfree_rcu(old, rcu);
+
+	wsr_register_receiver(&vb->wsr_receiver, pgdat);
+
+	return 0;
+error:
+	kfree(bins);
+	return err;
+}
+
+static void update_balloon_notification_func(struct work_struct *work)
+{
+	unsigned int len, op;
+	int err;
+	struct virtio_balloon *vb;
+	struct scatterlist sg_in;
+
+	vb = container_of(work, struct virtio_balloon,
+			  update_balloon_notification_work);
+	op = le16_to_cpu(vb->notify_buf->op);
+
+	switch (op) {
+	case VIRTIO_BALLOON_WS_OP_REQUEST:
+		virtio_balloon_working_set_request(vb,
+						   READ_ONCE(vb->wsr_node_id));
+		break;
+	case VIRTIO_BALLOON_WS_OP_CONFIG:
+		err = virtio_balloon_register_working_set_receiver(vb);
+		if (err)
+			dev_warn(&vb->vdev->dev,
+				 "Error configuring working set, %d\n", err);
+		break;
+	default:
+		dev_warn(&vb->vdev->dev, "Received invalid notification, %u\n",
+			 op);
+		break;
+	}
+
+	/* Detach all the used buffers from the vq */
+	while (virtqueue_get_buf(vb->notification_vq, &len))
+		;
+	/* Add a new notification buffer for device to fill. */
+	sg_init_one(&sg_in, vb->notify_buf, sizeof(*vb->notify_buf));
+	virtqueue_add_inbuf(vb->notification_vq, &sg_in, 1, vb, GFP_KERNEL);
+	virtqueue_kick(vb->notification_vq);
+}
+
+static void update_balloon_ws_func(struct work_struct *work)
+{
+	struct virtio_balloon *vb;
+
+	vb = container_of(work, struct virtio_balloon,
+			  update_balloon_working_set_work);
+
+	if (wsr_is_configured(vb)) {
+		struct scatterlist sg_out;
+		int unused;
+		int err;
+
+		/* Detach all the used buffers from the vq */
+		while (virtqueue_get_buf(vb->working_set_vq, &unused))
+			;
+		sg_init_one(&sg_out, vb->report_buf, sizeof(*vb->report_buf));
+		err = virtqueue_add_outbuf(vb->working_set_vq, &sg_out, 1, vb, GFP_KERNEL);
+		if (unlikely(err))
+			dev_err(&vb->vdev->dev,
+				"Failed to send working set report err = %d\n",
+				err);
+		else
+			virtqueue_kick(vb->working_set_vq);
+
+	} else {
+		dev_warn(&vb->vdev->dev, "Working Set not initialized.");
+	}
+}
+
+static void wsr_init_vqs_info(struct virtio_balloon *vb,
+			      struct virtqueue_info vqs_info[])
+{
+	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_WS_REPORTING)) {
+		vqs_info[VIRTIO_BALLOON_VQ_WORKING_SET].name = "ws";
+		vqs_info[VIRTIO_BALLOON_VQ_WORKING_SET].callback = NULL;
+		vqs_info[VIRTIO_BALLOON_VQ_NOTIFY].name = "notify";
+		vqs_info[VIRTIO_BALLOON_VQ_NOTIFY].callback = notification_receive;
+	}
+}
+
+static int wsr_init_vq(struct virtio_balloon *vb, struct virtqueue *vqs[])
+{
+	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_WS_REPORTING)) {
+		struct scatterlist sg;
+		int err;
+
+		vb->working_set_vq = vqs[VIRTIO_BALLOON_VQ_WORKING_SET];
+		vb->notification_vq = vqs[VIRTIO_BALLOON_VQ_NOTIFY];
+
+		/* Prime the notification virtqueue for the device to fill. */
+		sg_init_one(&sg, vb->notify_buf, sizeof(*vb->notify_buf));
+		err = virtqueue_add_inbuf(vb->notification_vq, &sg, 1, vb, GFP_KERNEL);
+		if (unlikely(err)) {
+			dev_err(&vb->vdev->dev,
+				"Failed to prepare notifications, err = %d\n", err);
+			return err;
+		}
+		virtqueue_kick(vb->notification_vq);
+	}
+	return 0;
+}
+
+static void wsr_init_work(struct virtio_balloon *vb)
+{
+	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_WS_REPORTING)) {
+		INIT_WORK(&vb->update_balloon_working_set_work,
+			  update_balloon_ws_func);
+		INIT_WORK(&vb->update_balloon_notification_work,
+			  update_balloon_notification_func);
+	}
+}
+
+static int wsr_init(struct virtio_balloon *vb)
+{
+	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_WS_REPORTING)) {
+		vb->report_buf = kzalloc(sizeof(*vb->report_buf), GFP_KERNEL);
+		if (!vb->report_buf)
+			return -ENOMEM;
+
+		vb->notify_buf = kzalloc(sizeof(*vb->notify_buf), GFP_KERNEL);
+		if (!vb->notify_buf) {
+			kfree(vb->report_buf);
+			vb->report_buf = NULL;
+			return -ENOMEM;
+		}
+
+		wsr_init_state(&vb->wsr_receiver.wsr);
+		vb->wsr_node_id = NUMA_NO_NODE;
+		vb->report_buf->bins[0].idle_age = WORKINGSET_INTERVAL_MAX;
+	}
+	return 0;
+}
+
+static void wsr_remove(struct virtio_balloon *vb)
+{
+	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_WS_REPORTING) &&
+	    vb->wsr_node_id != NUMA_NO_NODE) {
+		wsr_remove_receiver(&vb->wsr_receiver, NODE_DATA(vb->wsr_node_id));
+		wsr_destroy_state(&vb->wsr_receiver.wsr);
+	}
+
+	kfree(vb->report_buf);
+	kfree(vb->notify_buf);
+	mutex_destroy(&vb->wsr_report_lock);
+}
+
+static void wsr_cancel_work(struct virtio_balloon *vb)
+{
+	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_WS_REPORTING)) {
+		cancel_work_sync(&vb->update_balloon_working_set_work);
+		cancel_work_sync(&vb->update_balloon_notification_work);
+	}
+}
+#else
+static inline void wsr_init_vqs_info(struct virtio_balloon *vb,
+				     struct virtqueue_info vqs_info[])
+{
+}
+static inline int wsr_init_vq(struct virtio_balloon *vb,
+			      struct virtqueue *vqs[])
+{
+	return 0;
+}
+static inline void wsr_init_work(struct virtio_balloon *vb)
+{
+}
+static inline int wsr_init(struct virtio_balloon *vb)
+{
+	return 0;
+}
+static inline void wsr_remove(struct virtio_balloon *vb)
+{
+}
+static inline void wsr_cancel_work(struct virtio_balloon *vb)
+{
+}
+#endif
+
+static inline void update_stat(struct virtio_balloon *vb, int idx, u16 tag,
+			       u64 val)
 {
 	BUG_ON(idx >= VIRTIO_BALLOON_S_NR);
 	vb->stats[idx].tag = cpu_to_virtio16(vb->vdev, tag);
@@ -605,6 +969,8 @@ static int init_vqs(struct virtio_balloon *vb)
 		vqs_info[VIRTIO_BALLOON_VQ_REPORTING].callback = balloon_ack;
 	}
 
+	wsr_init_vqs_info(vb, vqs_info);
+
 	err = virtio_find_vqs(vb->vdev, VIRTIO_BALLOON_VQ_MAX, vqs,
 			      vqs_info, NULL);
 	if (err)
@@ -615,6 +981,7 @@ static int init_vqs(struct virtio_balloon *vb)
 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ)) {
 		struct scatterlist sg;
 		unsigned int num_stats;
+
 		vb->stats_vq = vqs[VIRTIO_BALLOON_VQ_STATS];
 
 		/*
@@ -640,6 +1007,11 @@ static int init_vqs(struct virtio_balloon *vb)
 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING))
 		vb->reporting_vq = vqs[VIRTIO_BALLOON_VQ_REPORTING];
 
+	err = wsr_init_vq(vb, vqs);
+
+	if (err)
+		return err;
+
 	return 0;
 }
 
@@ -961,15 +1333,21 @@ static int virtballoon_probe(struct virtio_device *vdev)
 		goto out;
 	}
 
+	vb->vdev = vdev;
+
 	INIT_WORK(&vb->update_balloon_stats_work, update_balloon_stats_func);
 	INIT_WORK(&vb->update_balloon_size_work, update_balloon_size_func);
+	wsr_init_work(vb);
 	spin_lock_init(&vb->stop_update_lock);
 	mutex_init(&vb->balloon_lock);
 	init_waitqueue_head(&vb->acked);
-	vb->vdev = vdev;
 
 	balloon_devinfo_init(&vb->vb_dev_info);
 
+	err = wsr_init(vb);
+	if (err)
+		goto out_remove_wsr;
+
 	err = init_vqs(vb);
 	if (err)
 		goto out_free_vb;
@@ -1085,7 +1463,6 @@ static int virtballoon_probe(struct virtio_device *vdev)
 	if (towards_target(vb))
 		virtballoon_changed(vdev);
 	return 0;
-
 out_unregister_oom:
 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
 		unregister_oom_notifier(&vb->oom_nb);
@@ -1099,6 +1476,8 @@ static int virtballoon_probe(struct virtio_device *vdev)
 	vdev->config->del_vqs(vdev);
 out_free_vb:
 	kfree(vb);
+out_remove_wsr:
+	wsr_remove(vb);
 out:
 	return err;
 }
@@ -1130,11 +1509,13 @@ static void virtballoon_remove(struct virtio_device *vdev)
 		unregister_oom_notifier(&vb->oom_nb);
 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
 		virtio_balloon_unregister_shrinker(vb);
+	wsr_remove(vb);
 	spin_lock_irq(&vb->stop_update_lock);
 	vb->stop_update = true;
 	spin_unlock_irq(&vb->stop_update_lock);
 	cancel_work_sync(&vb->update_balloon_size_work);
 	cancel_work_sync(&vb->update_balloon_stats_work);
+	wsr_cancel_work(vb);
 
 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
 		cancel_work_sync(&vb->report_free_page_work);
@@ -1200,6 +1581,7 @@ static unsigned int features[] = {
 	VIRTIO_BALLOON_F_FREE_PAGE_HINT,
 	VIRTIO_BALLOON_F_PAGE_POISON,
 	VIRTIO_BALLOON_F_REPORTING,
+	VIRTIO_BALLOON_F_WS_REPORTING,
 };
 
 static struct virtio_driver virtio_balloon_driver = {
include/linux/balloon_compaction.h +1 -0
index 5ca2d5699620..d92b8337dbcf 100644
@@ -43,6 +43,7 @@
 #include <linux/err.h>
 #include <linux/fs.h>
 #include <linux/list.h>
+#include <linux/workingset_report.h>
 
 /*
  * Balloon device information descriptor.
include/linux/mmzone.h +4 -0
index ee728c0c5a3b..9a2dc506779d 100644
@@ -1429,8 +1429,12 @@ typedef struct pglist_data {
 #endif
 
 #ifdef CONFIG_WORKINGSET_REPORT
+	/* protects wsr_page_age_bins */
 	struct mutex wsr_update_mutex;
 	struct wsr_report_bins __rcu *wsr_page_age_bins;
+	/* protects wsr_receiver_lost */
+	struct mutex wsr_receiver_mutex;
+	struct list_head wsr_receiver_list;
 #endif
 
 	CACHELINE_PADDING(_pad2_);
include/linux/workingset_report.h +64 -2

101 lines not on this page · raw message

include/uapi/linux/virtio_balloon.h +30 -0
index ee35a372805d..668eaa39c85b 100644
@@ -25,6 +25,7 @@
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE. */
+#include "linux/workingset_report.h"
 #include <linux/types.h>
 #include <linux/virtio_types.h>
 #include <linux/virtio_ids.h>
@@ -37,6 +38,7 @@
 #define VIRTIO_BALLOON_F_FREE_PAGE_HINT	3 /* VQ to report free pages */
 #define VIRTIO_BALLOON_F_PAGE_POISON	4 /* Guest is using page poisoning */
 #define VIRTIO_BALLOON_F_REPORTING	5 /* Page reporting virtqueue */
+#define VIRTIO_BALLOON_F_WS_REPORTING	6 /* Working Set Size reporting */
 
 /* Size of a PFN in the balloon interface. */
 #define VIRTIO_BALLOON_PFN_SHIFT 12
@@ -128,4 +130,32 @@ struct virtio_balloon_stat {
 	__virtio64 val;
 } __attribute__((packed));
 
+/* Operations from the device */
+#define VIRTIO_BALLOON_WS_OP_REQUEST 1
+#define VIRTIO_BALLOON_WS_OP_CONFIG 2
+
+struct virtio_balloon_working_set_notify {
+	/* REQUEST or CONFIG */
+	__le16 op;
+	__le16 node_id;
+	/* the following fields valid iff op=CONFIG */
+	__le32 report_threshold;
+	__le32 refresh_interval;
+	__le32 idle_age[WORKINGSET_REPORT_MAX_NR_BINS];
+};
+
+struct virtio_balloon_working_set_report_bin {
+	__le64 idle_age;
+	/* bytes in this bucket for anon and file */
+	__le64 anon_bytes;
+	__le64 file_bytes;
+};
+
+struct virtio_balloon_working_set_report {
+	__le32 error;
+	__le32 node_id;
+	struct virtio_balloon_working_set_report_bin
+		bins[WORKINGSET_REPORT_MAX_NR_BINS];
+};
+
 #endif /* _LINUX_VIRTIO_BALLOON_H */
mm/workingset_report.c +81 -8

135 lines not on this page · raw message

Signature · 1 line
2.47.0.338.g60cca15819-goog
#12 lore raw

Re: [PATCH v4 9/9] virtio-balloon: add workingset reporting

On Tue, Nov 26, 2024 at 7:00 PM Yuanchu Xie <[email protected]> wrote:
[...]

Quoted 4 lines
include/linux/workingset_report.h +0 -0
index f6bbde2a04c3..1074b89035e9 100644

[...]

include/uapi/linux/virtio_balloon.h line 31

Quoted 12 lines
include/uapi/linux/virtio_balloon.h +1 -0
index ee35a372805d..668eaa39c85b 100644
@@ -25,6 +25,7 @@
  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE. */
+#include "linux/workingset_report.h"
 #include <linux/types.h>
 #include <linux/virtio_types.h>
 #include <linux/virtio_ids.h>

This seems to be including a non-uapi header (include/linux/workingset_report.h) from a uapi header (include/uapi/linux/virtio_balloon.h), which won't compile outside the kernel. Does anything in the uapi actually need declarations from workingset_report.h?

Quoted 31 lines
include/uapi/linux/virtio_balloon.h +20 -0
@@ -37,6 +38,7 @@
 #define VIRTIO_BALLOON_F_FREE_PAGE_HINT        3 /* VQ to report free pages */
 #define VIRTIO_BALLOON_F_PAGE_POISON   4 /* Guest is using page poisoning */
 #define VIRTIO_BALLOON_F_REPORTING     5 /* Page reporting virtqueue */
+#define VIRTIO_BALLOON_F_WS_REPORTING  6 /* Working Set Size reporting */
 
 /* Size of a PFN in the balloon interface. */
 #define VIRTIO_BALLOON_PFN_SHIFT 12
@@ -128,4 +130,32 @@ struct virtio_balloon_stat {
        __virtio64 val;
 } __attribute__((packed));
 
+/* Operations from the device */
+#define VIRTIO_BALLOON_WS_OP_REQUEST 1
+#define VIRTIO_BALLOON_WS_OP_CONFIG 2
+
+struct virtio_balloon_working_set_notify {
+       /* REQUEST or CONFIG */
+       __le16 op;
+       __le16 node_id;
+       /* the following fields valid iff op=CONFIG */
+       __le32 report_threshold;
+       __le32 refresh_interval;
+       __le32 idle_age[WORKINGSET_REPORT_MAX_NR_BINS];
+};
+
+struct virtio_balloon_working_set_report_bin {
+       __le64 idle_age;
+       /* bytes in this bucket for anon and file */
+       __le64 anon_bytes;
+       __le64 file_bytes;

include/uapi/linux/virtio_balloon.h struct virtio_balloon_stat { · line 161

Quoted 10 lines
include/uapi/linux/virtio_balloon.h +9 -0
+};
+
+struct virtio_balloon_working_set_report {
+       __le32 error;
+       __le32 node_id;
+       struct virtio_balloon_working_set_report_bin
+               bins[WORKINGSET_REPORT_MAX_NR_BINS];
+};
+
 #endif /* _LINUX_VIRTIO_BALLOON_H */

Have the spec changes been discussed in the virtio TC?

Thanks,
-- Daniel

author reviewer
#13 lore raw

Re: [PATCH v4 9/9] virtio-balloon: add workingset reporting

Quoted 8 lines · Daniel Verkamp
Quoted 7 lines

* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. */
+#include "linux/workingset_report.h"
#include <linux/types.h>
#include <linux/virtio_types.h>
#include <linux/virtio_ids.h>

Quoted 5 lines

This seems to be including a non-uapi header (include/linux/workingset_report.h) from a uapi header (include/uapi/linux/virtio_balloon.h), which won't compile outside the kernel. Does anything in the uapi actually need declarations from workingset_report.h?

Good point. I should move the relevant constants over.

Quoted 20 lines
Quoted 20 lines
include/uapi/linux/virtio_balloon.h +20 -0
+
+struct virtio_balloon_working_set_notify {
+       /* REQUEST or CONFIG */
+       __le16 op;
+       __le16 node_id;
+       /* the following fields valid iff op=CONFIG */
+       __le32 report_threshold;
+       __le32 refresh_interval;
+       __le32 idle_age[WORKINGSET_REPORT_MAX_NR_BINS];
+};
+
+struct virtio_balloon_working_set_report_bin {
+       __le64 idle_age;
+       /* bytes in this bucket for anon and file */
+       __le64 anon_bytes;
+       __le64 file_bytes;
+};
+
+struct virtio_balloon_working_set_report {
+       __le32 error;
Quoted 8 lines

include/uapi/linux/virtio_balloon.h struct virtio_balloon_stat { · line 161

Quoted 6 lines
include/uapi/linux/virtio_balloon.h +5 -0
+       __le32 node_id;
+       struct virtio_balloon_working_set_report_bin
+               bins[WORKINGSET_REPORT_MAX_NR_BINS];
+};
+
 #endif /* _LINUX_VIRTIO_BALLOON_H */

Have the spec changes been discussed in the virtio TC?

They have not. Thanks for bringing this up. I'll post in the VIRTIO TC.

Thanks,
Yuanchu

maintainer
#14 lore raw
In reply to Yuanchu Xie
Quoted 5 lines · Yuanchu Xie

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references. However, the concept of workingset applies generically to all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might

Quoted 8 lines

come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

Doesn't DAMON already provide this information?

CCing SJ.

Quoted 14 lines

Use cases
==========
Job scheduling
On overcommitted hosts, workingset information improves efficiency and reliability by allowing the job scheduler to have better stats on the exact memory requirements of each job. This can manifest in efficiency by landing more jobs on the same host or NUMA node. On the other hand, the job scheduler can also ensure each node has a sufficient amount of memory and does not enter direct reclaim or the kernel OOM path. With workingset information and job priority, the userspace OOM killing or proactive reclaim policy can kick in before the system is under memory pressure. If the job shape is very different from the machine shape, knowing the workingset per-node can also help inform page allocation policies.

Quoted 6 lines

Proactive reclaim
Workingset information allows the a container manager to proactively reclaim memory while not impacting a job's performance. While PSI may provide a reactive measure of when a proactive reclaim has reclaimed too much, workingset reporting allows the policy to be more accurate and flexible.

I'm not sure about more accurate.

Access frequency is only half the picture. Whether you need to keep memory with a given frequency resident depends on the speed of the backing device.

There is memory compression; there is swap on flash; swap on crappy flash; swapfiles that share IOPS with co-located filesystems. There is zswap+writeback, where avg refault speed can vary dramatically.

You can of course offload much more to a fast zswap backend than to a swapfile on a struggling flashdrive, with comparable app performance.

So I think you'd be hard pressed to achieve a high level of accuracy in the usecases you list without taking the (often highly dynamic) cost of paging / memory transfer into account.

There is a more detailed discussion of this in a paper we wrote on proactive reclaim/offloading - in 2.5 Hardware Heterogeneity:

https://www.cs.cmu.edu/~dskarlat/publications/tmo_asplos22.pdf

Quoted 64 lines

Ballooning (similar to proactive reclaim)
The last patch of the series extends the virtio-balloon device to report the guest workingset.
Balloon policies benefit from workingset to more precisely determine the size of the memory balloon. On end-user devices where memory is scarce and overcommitted, the balloon sizing in multiple VMs running on the same device can be orchestrated with workingset reports from each one. On the server side, workingset reporting allows the balloon controller to inflate the balloon without causing too much file cache to be reclaimed in the guest.

Promotion/Demotion
If different mechanisms are used for promition and demotion, workingset information can help connect the two and avoid pages being migrated back and forth.
For example, given a promotion hot page threshold defined in reaccess distance of N seconds (promote pages accessed more often than every N seconds). The threshold N should be set so that ~80% (e.g.) of pages on the fast memory node passes the threshold. This calculation can be done with workingset reports.
To be directly useful for promotion policies, the workingset report interfaces need to be extended to report hotness and gather hotness information from the devices[1].

[1]
https://www.opencompute.org/documents/ocp-cms-hotness-tracking-requirements-white-paper-pdf-1

Sysfs and Cgroup Interfaces
==========
The interfaces are detailed in the patches that introduce them. The main idea here is we break down the workingset per-node per-memcg into time intervals (ms), e.g.

1000 anon=137368 file=24530
20000 anon=34342 file=0
30000 anon=353232 file=333608
40000 anon=407198 file=206052
9223372036854775807 anon=4925624 file=892892

Implementation
==========
The reporting of user pages is based off of MGLRU, and therefore requires CONFIG_LRU_GEN=y. We would benefit from more MGLRU generations for a more fine-grained workingset report, but we can already gather a lot of data with just four generations. The workingset reporting mechanism is gated behind CONFIG_WORKINGSET_REPORT, and the aging thread is behind CONFIG_WORKINGSET_REPORT_AGING.

Benchmarks
==========
Ghait Ouled Amar Ben Cheikh has implemented a simple policy and ran Linux compile and redis benchmarks from openbenchmarking.org. The policy and runner is referred to as WMO (Workload Memory Optimization). The results were based on v3 of the series, but v4 doesn't change the core of the working set reporting and just adds the ballooning counterpart.

The timed Linux kernel compilation benchmark shows improvements in peak memory usage with a policy of "swap out all bytes colder than 10 seconds every 40 seconds". A swapfile is configured on SSD.
--------------------------------------------
peak memory usage (with WMO): 4982.61328 MiB
peak memory usage (control): 9569.1367 MiB
peak memory reduction: 47.9%
--------------------------------------------

Quoted 4 lines
Benchmark                                           | Experimental     |Control         | Experimental_Std_Dev | Control_Std_Dev
Timed Linux Kernel Compilation - allmodconfig (sec) | 708.486 (95.91%) | 679.499 (100%) | 0.6%                 | 0.1%

--------------------------------------------
Seconds, fewer is better

You can do this with a recent (>2018) upstream kernel and ~100 lines of python [1]. It also works on both LRU implementations.

[1] https://github.com/facebookincubator/senpai

We use this approach in virtually the entire Meta fleet, to offload unneeded memory, estimate available capacity for job scheduling, plan future capacity needs, and provide accurate memory usage feedback to application developers.

It works over a wide variety of CPU and storage configurations with no specific tuning.

The paper I referenced above provides a detailed breakdown of how it all works together.

I would be curious to see a more in-depth comparison to the prior art in this space. At first glance, your proposal seems more complex and less robust/versatile, at least for offloading and capacity gauging.

It does provide more detailed insight into userspace memory behavior, which could be helpful when trying to make sense of applications that sit on a rich layer of libraries and complicated runtimes. But here a comparison to DAMON would be helpful.

Quoted 8 lines
 25 files changed, 2482 insertions(+), 9 deletions(-)
 create mode 100644 Documentation/admin-guide/mm/workingset_report.rst
 create mode 100644 include/linux/workingset_report.h
 create mode 100644 mm/workingset_report.c
 create mode 100644 mm/workingset_report_aging.c
 create mode 100644 tools/testing/selftests/mm/workingset_report.c
 create mode 100644 tools/testing/selftests/mm/workingset_report.h
 create mode 100644 tools/testing/selftests/mm/workingset_report_test.c
maintainer
#15 lore raw

+ [email protected]

I haven't thoroughly read any version of this patch series due to my laziness, sorry. So I may saying something completely wrong. My apology in advance, and please correct me in the case.

Quoted 4 lines · Yuanchu Xie
Quoted 3 lines

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references.

DAMON provides data access patterns of user pages. It is not exactly named as workingset but a superset of the information. Users can therefore get the workingset from DAMON-provided raw data. So I feel I have to ask if DAMON can be used for, or help at achieving the purpose of this patch series.

Depending on the detailed definition of workingset, of course, the workingset we can get from DAMON might not be technically same to what this patch series aim to provide, and the difference could be somewhat that makes DAMON unable to be used or help here. But I cannot know if this is the case with only this cover letter.

Quoted 11 lines
Quoted 11 lines

However, the concept of workingset applies generically to
all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

This again sounds similar to what DAMON aims to provide, to me. DAMON is designed to be easy to extend for vairous use cases and internal mechanisms. Specifically, it separates access check mechanisms and core logic into different layers, and provides an interface to use for implementing extending DAMON with new mechanisms. DAMON's two access check mechanisms for virtual address spaces and the physical address space are made using the interface, indeed. Also there were RFC patch series extending DAMON for NUMA-specific and write-only access monitoring using NUMA hinting fault and soft-dirty PTEs as the internal mechanisms.

My humble understanding of the major difference between DAMON and workingset reporting is the internal mechanism. Workingset reporting uses MGLRU as the access check mechanism, while current access check mechanisms for DAMON are using page table accessed bits checking as the major mechanism. I think DAMON can be extended to use MGLRU as its another internal access check mechanism, but I understand that there could be many things that I overseeing.

Yuanchu, I think it would help me and other reviewers better understand this patch series if you could share that. And I will also be more than happy to help you and others better understanding what DAMON can do or not with the discussion.

Quoted 4 lines

Doesn't DAMON already provide this information?

CCing SJ.

Thank you for adding me, Johannes :)

[...]

Quoted 4 lines

It does provide more detailed insight into userspace memory behavior, which could be helpful when trying to make sense of applications that sit on a rich layer of libraries and complicated runtimes. But here a comparison to DAMON would be helpful.

100% agree.

Thanks,
SJ

[...]

#16 lore raw
In reply to Johannes Weiner
Quoted 16 lines · Johannes Weiner
Quoted 5 lines · Yuanchu Xie

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references. However, the concept of workingset applies generically to all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might

Quoted 8 lines

come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

Quoted 1 line

Doesn't DAMON already provide this information?

Yuanchu might be able to answer this question a lot better than I do, since he studied DAMON and tried to leverage it in our fleet.

My impression is that there are some fundamental differences in access detection and accounting mechanisms between the two, i.e., sampling vs scanning-based detection and non-lruvec vs lruvec-based accounting.

Quoted 16 lines

CCing SJ.

Quoted 14 lines

Use cases
==========
Job scheduling
On overcommitted hosts, workingset information improves efficiency and reliability by allowing the job scheduler to have better stats on the exact memory requirements of each job. This can manifest in efficiency by landing more jobs on the same host or NUMA node. On the other hand, the job scheduler can also ensure each node has a sufficient amount of memory and does not enter direct reclaim or the kernel OOM path. With workingset information and job priority, the userspace OOM killing or proactive reclaim policy can kick in before the system is under memory pressure. If the job shape is very different from the machine shape, knowing the workingset per-node can also help inform page allocation policies.

Quoted 8 lines
Quoted 6 lines

Proactive reclaim
Workingset information allows the a container manager to proactively reclaim memory while not impacting a job's performance. While PSI may provide a reactive measure of when a proactive reclaim has reclaimed too much, workingset reporting allows the policy to be more accurate and flexible.

I'm not sure about more accurate.

Agreed. This is a (very) poor argument, unless there are facts to back this up.

Quoted 3 lines

Access frequency is only half the picture. Whether you need to keep memory with a given frequency resident depends on the speed of the backing device.

Along a similar line, we also need to consider use cases that don't involve backing storage, e.g., far memory (remote node). More details below.

Quoted 90 lines

There is memory compression; there is swap on flash; swap on crappy flash; swapfiles that share IOPS with co-located filesystems. There is zswap+writeback, where avg refault speed can vary dramatically.

You can of course offload much more to a fast zswap backend than to a swapfile on a struggling flashdrive, with comparable app performance.

So I think you'd be hard pressed to achieve a high level of accuracy in the usecases you list without taking the (often highly dynamic) cost of paging / memory transfer into account.

There is a more detailed discussion of this in a paper we wrote on proactive reclaim/offloading - in 2.5 Hardware Heterogeneity:

https://www.cs.cmu.edu/~dskarlat/publications/tmo_asplos22.pdf

Quoted 64 lines

Ballooning (similar to proactive reclaim)
The last patch of the series extends the virtio-balloon device to report the guest workingset.
Balloon policies benefit from workingset to more precisely determine the size of the memory balloon. On end-user devices where memory is scarce and overcommitted, the balloon sizing in multiple VMs running on the same device can be orchestrated with workingset reports from each one. On the server side, workingset reporting allows the balloon controller to inflate the balloon without causing too much file cache to be reclaimed in the guest.

Promotion/Demotion
If different mechanisms are used for promition and demotion, workingset information can help connect the two and avoid pages being migrated back and forth.
For example, given a promotion hot page threshold defined in reaccess distance of N seconds (promote pages accessed more often than every N seconds). The threshold N should be set so that ~80% (e.g.) of pages on the fast memory node passes the threshold. This calculation can be done with workingset reports.
To be directly useful for promotion policies, the workingset report interfaces need to be extended to report hotness and gather hotness information from the devices[1].

[1]
https://www.opencompute.org/documents/ocp-cms-hotness-tracking-requirements-white-paper-pdf-1

Sysfs and Cgroup Interfaces
==========
The interfaces are detailed in the patches that introduce them. The main idea here is we break down the workingset per-node per-memcg into time intervals (ms), e.g.

1000 anon=137368 file=24530
20000 anon=34342 file=0
30000 anon=353232 file=333608
40000 anon=407198 file=206052
9223372036854775807 anon=4925624 file=892892

Implementation
==========
The reporting of user pages is based off of MGLRU, and therefore requires CONFIG_LRU_GEN=y. We would benefit from more MGLRU generations for a more fine-grained workingset report, but we can already gather a lot of data with just four generations. The workingset reporting mechanism is gated behind CONFIG_WORKINGSET_REPORT, and the aging thread is behind CONFIG_WORKINGSET_REPORT_AGING.

Benchmarks
==========
Ghait Ouled Amar Ben Cheikh has implemented a simple policy and ran Linux compile and redis benchmarks from openbenchmarking.org. The policy and runner is referred to as WMO (Workload Memory Optimization). The results were based on v3 of the series, but v4 doesn't change the core of the working set reporting and just adds the ballooning counterpart.

The timed Linux kernel compilation benchmark shows improvements in peak memory usage with a policy of "swap out all bytes colder than 10 seconds every 40 seconds". A swapfile is configured on SSD.
--------------------------------------------
peak memory usage (with WMO): 4982.61328 MiB
peak memory usage (control): 9569.1367 MiB
peak memory reduction: 47.9%
--------------------------------------------

Quoted 4 lines
Benchmark                                           | Experimental     |Control         | Experimental_Std_Dev | Control_Std_Dev
Timed Linux Kernel Compilation - allmodconfig (sec) | 708.486 (95.91%) | 679.499 (100%) | 0.6%                 | 0.1%

--------------------------------------------
Seconds, fewer is better

You can do this with a recent (>2018) upstream kernel and ~100 lines of python [1]. It also works on both LRU implementations.

[1] https://github.com/facebookincubator/senpai

Quoted 7 lines

We use this approach in virtually the entire Meta fleet, to offload unneeded memory, estimate available capacity for job scheduling, plan future capacity needs, and provide accurate memory usage feedback to application developers.

It works over a wide variety of CPU and storage configurations with no specific tuning.

How would Senpai work for use cases that don't have local storage, i.e., all memory is mapped by either the fast or the slow tier? (>95% memory usage in our fleet is mapped and local storage for non-storage servers is only scratch space.)

My current understanding is that its approach would not be able to form a feedback loop because there are currently no refaults from the slow tier (because it's also mapped), and that's where I think this proposal or something similar can help.

Also this proposal reports histograms, not scalars. So in theory, userspace can see the projections of its potential actions, rather than solely rely on trial and error. Of course, this needs to be backed with data. So yes, some comparisons from real-world use cases would be very helpful to demonstrate the value of this proposal.

author reviewer
#17 lore raw
In reply to Johannes Weiner

Thanks for the response Johannes. Some replies inline.

Quoted 16 lines · Johannes Weiner
Quoted 5 lines · Yuanchu Xie

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references. However, the concept of workingset applies generically to all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might

Quoted 8 lines

come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

Quoted 3 lines

Doesn't DAMON already provide this information?

CCing SJ.

Thanks for the CC. DAMON was really good at visualizing the memory access frequencies last time I tried it out! For server use cases, DAMON would benefit from integrations with cgroups. The key then would be a standard interface for exporting a cgroup's working set to the user. It would be good to have something that will work for different backing implementations, DAMON, MGLRU, or active/inactive LRU.

Quoted 35 lines
Quoted 15 lines

Use cases
==========
Job scheduling
On overcommitted hosts, workingset information improves efficiency and reliability by allowing the job scheduler to have better stats on the exact memory requirements of each job. This can manifest in efficiency by landing more jobs on the same host or NUMA node. On the other hand, the job scheduler can also ensure each node has a sufficient amount of memory and does not enter direct reclaim or the kernel OOM path. With workingset information and job priority, the userspace OOM killing or proactive reclaim policy can kick in before the system is under memory pressure. If the job shape is very different from the machine shape, knowing the workingset per-node can also help inform page allocation policies.

Quoted 6 lines

Proactive reclaim
Workingset information allows the a container manager to proactively reclaim memory while not impacting a job's performance. While PSI may provide a reactive measure of when a proactive reclaim has reclaimed too much, workingset reporting allows the policy to be more accurate and flexible.

I'm not sure about more accurate.

Access frequency is only half the picture. Whether you need to keep memory with a given frequency resident depends on the speed of the backing device.

There is memory compression; there is swap on flash; swap on crappy flash; swapfiles that share IOPS with co-located filesystems. There is zswap+writeback, where avg refault speed can vary dramatically.

You can of course offload much more to a fast zswap backend than to a swapfile on a struggling flashdrive, with comparable app performance.

Quoted 9 lines

So I think you'd be hard pressed to achieve a high level of accuracy in the usecases you list without taking the (often highly dynamic) cost of paging / memory transfer into account.

There is a more detailed discussion of this in a paper we wrote on proactive reclaim/offloading - in 2.5 Hardware Heterogeneity:

https://www.cs.cmu.edu/~dskarlat/publications/tmo_asplos22.pdf

Yes, PSI takes into account the paging cost. I'm not claiming that Workingset reporting provides a superset of information, but rather it can complement PSI. Sorry for the bad wording here.

Quoted 10 lines
Quoted 10 lines

Ballooning (similar to proactive reclaim)
The last patch of the series extends the virtio-balloon device to report the guest workingset.
Balloon policies benefit from workingset to more precisely determine the size of the memory balloon. On end-user devices where memory is scarce and overcommitted, the balloon sizing in multiple VMs running on the same device can be orchestrated with workingset reports from each one. On the server side, workingset reporting allows the balloon controller to inflate the balloon without causing too much file cache to be reclaimed in the guest.

The ballooning use case is an important one. Having working set information would allow us to inflate a balloon of the right size in the guest.

Quoted 49 lines
Quoted 31 lines

Promotion/Demotion
If different mechanisms are used for promition and demotion, workingset information can help connect the two and avoid pages being migrated back and forth.
For example, given a promotion hot page threshold defined in reaccess distance of N seconds (promote pages accessed more often than every N seconds). The threshold N should be set so that ~80% (e.g.) of pages on the fast memory node passes the threshold. This calculation can be done with workingset reports.
To be directly useful for promotion policies, the workingset report interfaces need to be extended to report hotness and gather hotness information from the devices[1].
...

Benchmarks
==========
Ghait Ouled Amar Ben Cheikh has implemented a simple policy and ran Linux compile and redis benchmarks from openbenchmarking.org. The policy and runner is referred to as WMO (Workload Memory Optimization). The results were based on v3 of the series, but v4 doesn't change the core of the working set reporting and just adds the ballooning counterpart.

The timed Linux kernel compilation benchmark shows improvements in peak memory usage with a policy of "swap out all bytes colder than 10 seconds every 40 seconds". A swapfile is configured on SSD.
--------------------------------------------
peak memory usage (with WMO): 4982.61328 MiB
peak memory usage (control): 9569.1367 MiB
peak memory reduction: 47.9%
--------------------------------------------

Quoted 4 lines
Benchmark                                           | Experimental     |Control         | Experimental_Std_Dev | Control_Std_Dev
Timed Linux Kernel Compilation - allmodconfig (sec) | 708.486 (95.91%) | 679.499 (100%) | 0.6%                 | 0.1%

--------------------------------------------
Seconds, fewer is better

You can do this with a recent (>2018) upstream kernel and ~100 lines of python [1]. It also works on both LRU implementations.

[1] https://github.com/facebookincubator/senpai

We use this approach in virtually the entire Meta fleet, to offload unneeded memory, estimate available capacity for job scheduling, plan future capacity needs, and provide accurate memory usage feedback to application developers.

It works over a wide variety of CPU and storage configurations with no specific tuning.

Quoted 6 lines

The paper I referenced above provides a detailed breakdown of how it all works together.

I would be curious to see a more in-depth comparison to the prior art in this space. At first glance, your proposal seems more complex and less robust/versatile, at least for offloading and capacity gauging.

We have implemented TMO PSI-based proactive reclaim and compared it to a kstaled-based reclaimer (reclaiming based on 2 minute working set and refaults). The PSI-based reclaimer was able to save more memory, but it also caused spikes of refaults and a lot higher decompressions/second. Overall the test workloads had better performance with the kstaled-based reclaimer. The conclusion was that it was a trade-off. Since we have some app classes that we don't want to induce pressure but still want to proactively reclaim from, there's a missing piece. I do agree there's not a good in-depth comparison with prior art though.

maintainer
#18 lore raw
Quoted 19 lines · On Fri, 6 Dec 2024 11:57:55 -0800 Yuanchu Xie <[email protected]> wrote:

Thanks for the response Johannes. Some replies inline.

Quoted 16 lines · On Tue, Nov 26, 2024 at 11:26\u202fPM Johannes Weiner <[email protected]>…
Quoted 13 lines · Yuanchu Xie

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references. However, the concept of workingset applies generically to all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

Quoted 5 lines
Quoted 3 lines

Doesn't DAMON already provide this information?

CCing SJ.

Thanks for the CC. DAMON was really good at visualizing the memory access frequencies last time I tried it out!

Thank you for this kind acknowledgement, Yuanchu!

Quoted 3 lines

For server use cases,
DAMON would benefit from integrations with cgroups. The key then would be a standard interface for exporting a cgroup's working set to the user.

I show two ways to make DAMON supports cgroups for now. First way is making another DAMON operations set implementation for cgroups. I shared a rough idea for this before, probably on kernel summit. But I haven't had a chance to prioritize this so far. Please let me know if you need more details. The second way is extending DAMOS filter to provide more detailed statistics per DAMON-region, and adding another DAMOS action that does nothing but only accounting the detailed statistics. Using the new DAMOS action, users will be able to know how much of specific DAMON-found regions are filtered out by the given filter. Because we have DAMOS filter type for cgroups, we can know how much of workingset (or, warm memory) belongs to specific groups. This can be applied to not only cgroups, but for any DAMOS filter types that exist (e.g., anonymous page, young page).

I believe the second way is simpler to implement while providing information that sufficient for most possible use cases. I was anyway planning to do this.

Quoted 2 lines

It would be good to have something that will work for different backing implementations, DAMON, MGLRU, or active/inactive LRU.

I think we can do this using the filter statistics, with new filter types. For example, we can add new DAMOS filter that filters pages if it is for specific range of MGLRU-gen of the page, or whether the page belongs to active or inactive LRU lists.

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines

Use cases
==========

[...]

Quoted 3 lines
Quoted 3 lines

Access frequency is only half the picture. Whether you need to keep memory with a given frequency resident depends on the speed of the backing device.

[...]

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines

Benchmarks
==========
Ghait Ouled Amar Ben Cheikh has implemented a simple policy and ran Linux compile and redis benchmarks from openbenchmarking.org. The policy and runner is referred to as WMO (Workload Memory Optimization). The results were based on v3 of the series, but v4 doesn't change the core of the working set reporting and just adds the ballooning counterpart.

The timed Linux kernel compilation benchmark shows improvements in peak memory usage with a policy of "swap out all bytes colder than 10 seconds every 40 seconds". A swapfile is configured on SSD.

[...]

Quoted 19 lines
Quoted 13 lines

You can do this with a recent (>2018) upstream kernel and ~100 lines of python [1]. It also works on both LRU implementations.

[1] https://github.com/facebookincubator/senpai

We use this approach in virtually the entire Meta fleet, to offload unneeded memory, estimate available capacity for job scheduling, plan future capacity needs, and provide accurate memory usage feedback to application developers.

It works over a wide variety of CPU and storage configurations with no specific tuning.

Quoted 6 lines

The paper I referenced above provides a detailed breakdown of how it all works together.

I would be curious to see a more in-depth comparison to the prior art in this space. At first glance, your proposal seems more complex and less robust/versatile, at least for offloading and capacity gauging.

Quoted 7 lines

We have implemented TMO PSI-based proactive reclaim and compared it to a kstaled-based reclaimer (reclaiming based on 2 minute working set and refaults). The PSI-based reclaimer was able to save more memory, but it also caused spikes of refaults and a lot higher decompressions/second. Overall the test workloads had better performance with the kstaled-based reclaimer. The conclusion was that it was a trade-off.

I agree it is only half of the picture, and there could be tradeoff. Motivated by those previous works, DAMOS provides PSI-based aggressiveness auto-tuning to use both ways.

Quoted 2 lines

I do agree there's not a good in-depth comparison
with prior art though.

I would be more than happy to help the comparison work agains DAMON of current implementation and future plans, and any possible collaborations.

Thanks,
SJ

author reviewer
#19 lore raw
Quoted 47 lines · SeongJae Park
Quoted 19 lines · On Fri, 6 Dec 2024 11:57:55 -0800 Yuanchu Xie <[email protected]> wrote:

Thanks for the response Johannes. Some replies inline.

Quoted 16 lines · On Tue, Nov 26, 2024 at 11:26\u202fPM Johannes Weiner <[email protected]>…
Quoted 13 lines · Yuanchu Xie

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references. However, the concept of workingset applies generically to all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

Quoted 5 lines
Quoted 3 lines

Doesn't DAMON already provide this information?

CCing SJ.

Thanks for the CC. DAMON was really good at visualizing the memory access frequencies last time I tried it out!

Thank you for this kind acknowledgement, Yuanchu!

Quoted 3 lines

For server use cases,
DAMON would benefit from integrations with cgroups. The key then would be a standard interface for exporting a cgroup's working set to the user.

I show two ways to make DAMON supports cgroups for now. First way is making another DAMON operations set implementation for cgroups. I shared a rough idea for this before, probably on kernel summit. But I haven't had a chance to prioritize this so far. Please let me know if you need more details. The second way is extending DAMOS filter to provide more detailed statistics per DAMON-region, and adding another DAMOS action that does nothing but only accounting the detailed statistics. Using the new DAMOS action, users will be able to know how much of specific DAMON-found regions are filtered out by the given filter. Because we have DAMOS filter type for cgroups, we can know how much of workingset (or, warm memory) belongs to specific groups. This can be applied to not only cgroups, but for any DAMOS filter types that exist (e.g., anonymous page, young page).

Quoted 2 lines

I believe the second way is simpler to implement while providing information that sufficient for most possible use cases. I was anyway planning to do this.

For a container orchestrator like kubernetes, the node agents need to be able to gather the working set stats at a per-job level. Some jobs can create sub-hierarchies as well, so it's important that we have hierarchical stats.

Do you think it's a good idea to integrate DAMON to provide some aggregate stats in a memory controller file? With the DAMOS cgroup filter, there can be some kind of interface that a DAMOS action or the damo tool could call into. I feel that would be a straightforward and integrated way to support cgroups.

Yuanchu

maintainer
#20 lore raw

Hi Yuanchu,

Quoted 48 lines · On Wed, 29 Jan 2025 18:02:26 -0800 Yuanchu Xie <[email protected]> wrote:
Quoted 47 lines · SeongJae Park
Quoted 19 lines · On Fri, 6 Dec 2024 11:57:55 -0800 Yuanchu Xie <[email protected]> wrote:

Thanks for the response Johannes. Some replies inline.

Quoted 16 lines · On Tue, Nov 26, 2024 at 11:26\u202fPM Johannes Weiner <[email protected]>…
Quoted 13 lines · Yuanchu Xie

This patch series provides workingset reporting of user pages in lruvecs, of which coldness can be tracked by accessed bits and fd references. However, the concept of workingset applies generically to all types of memory, which could be kernel slab caches, discardable userspace caches (databases), or CXL.mem. Therefore, data sources might come from slab shrinkers, device drivers, or the userspace. Another interesting idea might be hugepage workingset, so that we can measure the proportion of hugepages backing cold memory. However, with architectures like arm, there may be too many hugepage sizes leading to a combinatorial explosion when exporting stats to the userspace. Nonetheless, the kernel should provide a set of workingset interfaces that is generic enough to accommodate the various use cases, and extensible to potential future use cases.

Quoted 5 lines
Quoted 3 lines

Doesn't DAMON already provide this information?

CCing SJ.

Thanks for the CC. DAMON was really good at visualizing the memory access frequencies last time I tried it out!

Thank you for this kind acknowledgement, Yuanchu!

Quoted 3 lines

For server use cases,
DAMON would benefit from integrations with cgroups. The key then would be a standard interface for exporting a cgroup's working set to the user.

I show two ways to make DAMON supports cgroups for now. First way is making another DAMON operations set implementation for cgroups. I shared a rough idea for this before, probably on kernel summit. But I haven't had a chance to prioritize this so far. Please let me know if you need more details. The second way is extending DAMOS filter to provide more detailed statistics per DAMON-region, and adding another DAMOS action that does nothing but only accounting the detailed statistics. Using the new DAMOS action, users will be able to know how much of specific DAMON-found regions are filtered out by the given filter. Because we have DAMOS filter type for cgroups, we can know how much of workingset (or, warm memory) belongs to specific groups. This can be applied to not only cgroups, but for any DAMOS filter types that exist (e.g., anonymous page, young page).

Quoted 2 lines
Quoted 2 lines

I believe the second way is simpler to implement while providing information that sufficient for most possible use cases. I was anyway planning to do this.

I implemented the feature for the second approach I mentioned above. The initial version of the feature has recently merged[1] into the mainline as a part of 6.14-rc1 MM pull request. DAMON user-space tool (damo) is also updated for baisc support of it. I forgot updating that on this thread, sorry.

Quoted 4 lines

For a container orchestrator like kubernetes, the node agents need to be able to gather the working set stats at a per-job level. Some jobs can create sub-hierarchies as well, so it's important that we have hierarchical stats.

This makes sense to me. And yes, I believe DAMOS filters for memcg could also be used for this use case, since we can install and use multiple DAMOS filters in combinations.

The documentation of the feature is not that good and there are many rooms to improve. You might not be able to get what you want in a perfect way with the current implementation. But we will continue improving it, and I believe we can make it faster if efforts are gathered. Of course, I could be wrong, and whether to use it or not is up to each person :)

Anyway, please feel free to ask me questions or any help about the feature if you want.

Quoted 6 lines

Do you think it's a good idea to integrate DAMON to provide some aggregate stats in a memory controller file? With the DAMOS cgroup filter, there can be some kind of interface that a DAMOS action or the damo tool could call into. I feel that would be a straightforward and integrated way to support cgroups.

DAMON basically exposes its internal information via DAMON sysfs, and DAMON user-space tool (damo) uses it. In this case, per-memcg working set could also be retrieved in the way (directly from DAMON sysfs or indirectly from damo).

But, yes, I think we could make new and optimized ABIs for exposing the information to user-space in more efficient way depending on the use case, if needed. DAMON modules such as DAMON_RECLAIM and DAMON_LRU_SORT provides their own ABIs that simplified and optimized for their usages.

[1] https://git.kernel.org/torvalds/c/626ffabe67c2

Thanks,
SJ

[...]