Skip to contentSkip to conversation

DAMON: Support Physical Memory Address Space Monitoring

RFC Superseded SeongJae Park 3 participants 15 messages Jul 7, 2020 – Jul 20, 2020

Subsystems (7)

v5 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

v5 cover DAMON: Support Physical Memory Address Space Monitoring

From: SeongJae Park <[email protected]>

DAMON[1] programming interface users can extend DAMON for any address space by configuring the address-space specific low level primitives with appropriate ones including their own implementations. However, because the implementation for the virtual address space is only available now, the users should implement their own for other address spaces. Worse yet, the user space users who rely on the debugfs interface and user space tool, cannot implement their own.

This patchset implements another reference implementation of the low level primitives for the physical memory address space. With this change, hence, the kernel space users can monitor both the virtual and the physical address spaces by simply changing the configuration in the runtime. Further, this patchset links the implementation to the debugfs interface and the user space tool for the user space users.

Note that the implementation supports only the user memory, as same to the idle page access tracking feature.

[1] https://lore.kernel.org/linux-mm/[email protected]/

Baseline and Complete Git Trees
===============================

The patches are based on the v5.7 plus DAMON v17 patchset[1] and DAMOS RFC v13 patchset[2]. You can also clone the complete git tree:

    $ git clone git://github.com/sjp38/linux -b cdamon/rfc/v5

The web is also available:
https://github.com/sjp38/linux/releases/tag/cdamon/rfc/v5

[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://lore.kernel.org/linux-mm/[email protected]/

Sequence of Patches
===================

The sequence of patches is as follow.

The first 5 patches allow the user space users manually set the monitoring regions. The 1st and 2nd patches implements the features in the debugfs interface and the user space tool . Following two patches each implement unittests (the 3rd patch) and selftests (the 4th patch) for the new feature. Finally, the 5th patch documents this new feature.

Following 6 patches implement the physical memory monitoring. The 6th patch exports rmap essential functions to GPL modules as those will be used by the DAMON's implementation of the low level primitives for the physical memory address space. The 7th patch implements the low level primitives. The 8th and the 9th patches links the feature to the debugfs and the user space tool, respectively. The 10th patch further implement a handy NUMA specific memory monitoring feature on the user space tool. Finally, the 11th patch documents this new features.

Patch History
=============

Changes from RFC v4
(https://lore.kernel.org/linux-mm/[email protected]/)
- Support NUMA specific physical memory monitoring

Changes from RFC v3
(https://lore.kernel.org/linux-mm/[email protected]/)
- Export rmap functions
- Reorganize for physical memory monitoring support only
- Clean up debugfs code

Changes from RFC v2
(https://lore.kernel.org/linux-mm/[email protected]/)
- Support the physical memory monitoring with the user space tool
- Use 'pfn_to_online_page()' (David Hildenbrand)
- Document more detail on random 'pfn' and its safeness (David Hildenbrand)

Changes from RFC v1
(https://lore.kernel.org/linux-mm/[email protected]/)
- Provide the reference primitive implementations for the physical memory
- Connect the extensions with the debugfs interface

SeongJae Park (11):
mm/damon/debugfs: Allow users to set initial monitoring target regions tools/damon: Support init target regions specification mm/damon-test: Add more unit tests for 'init_regions' selftests/damon/_chk_record: Do not check number of gaps Docs/damon: Document 'initial_regions' feature
mm/rmap: Export essential functions for rmap_run
mm/damon: Implement callbacks for physical memory monitoring mm/damon/debugfs: Support physical memory monitoring tools/damon/record: Support physical memory monitoring tools/damon/record: Support NUMA specific recording Docs/damon: Document physical memory monitoring support

 Documentation/admin-guide/mm/damon/faq.rst    |   7 +-
 Documentation/admin-guide/mm/damon/index.rst  |   1 -
 .../admin-guide/mm/damon/mechanisms.rst       |  29 +-
 Documentation/admin-guide/mm/damon/plans.rst  |   7 -
 Documentation/admin-guide/mm/damon/usage.rst  |  80 +++-
 include/linux/damon.h                         |   5 +
 mm/damon-test.h                               |  53 +++
 mm/damon.c                                    | 374 +++++++++++++++++-
 mm/rmap.c                                     |   2 +
 mm/util.c                                     |   1 +
 tools/damon/_damon.py                         |  41 ++
 tools/damon/_paddr_layout.py                  | 158 ++++++++
 tools/damon/heats.py                          |   2 +-
 tools/damon/record.py                         |  60 ++-
 tools/damon/schemes.py                        |  12 +-
 tools/testing/selftests/damon/_chk_record.py  |   6 -
 16 files changed, 783 insertions(+), 55 deletions(-)
 delete mode 100644 Documentation/admin-guide/mm/damon/plans.rst
 create mode 100644 tools/damon/_paddr_layout.py
Signature · 1 line
2.17.1
#1 lore raw

RFC v5 1/11 mm/damon/debugfs: Allow users to set initial monitoring target regions

From: SeongJae Park <[email protected]>

Some users would want to monitor only a part of the entire virtual memory address space. The '->init_target_regions' callback is therefore provided, but only programming interface can use it.

For the reason, this commit introduces a new debugfs file, 'init_region'. Users can specify which initial monitoring target address regions they want by writing special input to the file. The input should describe each region in each line in below form:

<pid> <start address> <end address>

This commit also makes the default '->init_target_regions' callback, 'kdamon_init_vm_regions()' to do nothing if the user has set the initial target regions already.

Note that the regions will be updated to cover entire memory mapped regions after 'regions update interval'. If you want the regions to not be updated after the initial setting, you could set the interval as a very long time, say, a few decades.

---
 mm/damon.c | 156 +++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 152 insertions(+), 4 deletions(-)
mm/damon.c +152 -4
index 937b6bccb7b8..3aecdef4c841 100644
@@ -1800,6 +1800,147 @@ static ssize_t debugfs_record_write(struct file *file,
 	return ret;
 }
 
+static ssize_t sprint_init_regions(struct damon_ctx *c, char *buf, ssize_t len)
+{
+	struct damon_task *t;
+	struct damon_region *r;
+	int written = 0;
+	int rc;
+
+	damon_for_each_task(t, c) {
+		damon_for_each_region(r, t) {
+			rc = snprintf(&buf[written], len - written,
+					"%d %lu %lu\n",
+					t->pid, r->ar.start, r->ar.end);
+			if (!rc)
+				return -ENOMEM;
+			written += rc;
+		}
+	}
+	return written;
+}
+
+static ssize_t debugfs_init_regions_read(struct file *file, char __user *buf,
+		size_t count, loff_t *ppos)
+{
+	struct damon_ctx *ctx = &damon_user_ctx;
+	char *kbuf;
+	ssize_t len;
+
+	kbuf = kmalloc(count, GFP_KERNEL);
+	if (!kbuf)
+		return -ENOMEM;
+
+	mutex_lock(&ctx->kdamond_lock);
+	if (ctx->kdamond) {
+		mutex_unlock(&ctx->kdamond_lock);
+		return -EBUSY;
+	}
+
+	len = sprint_init_regions(ctx, kbuf, count);
+	mutex_unlock(&ctx->kdamond_lock);
+	if (len < 0)
+		goto out;
+	len = simple_read_from_buffer(buf, count, ppos, kbuf, len);
+
+out:
+	kfree(kbuf);
+	return len;
+}
+
+static int add_init_region(struct damon_ctx *c,
+			 int pid, struct damon_addr_range *ar)
+{
+	struct damon_task *t;
+	struct damon_region *r, *prev;
+	int rc = -EINVAL;
+
+	if (ar->start >= ar->end)
+		return -EINVAL;
+
+	damon_for_each_task(t, c) {
+		if (t->pid == pid) {
+			r = damon_new_region(ar->start, ar->end);
+			if (!r)
+				return -ENOMEM;
+			damon_add_region(r, t);
+			if (nr_damon_regions(t) > 1) {
+				prev = damon_prev_region(r);
+				if (prev->ar.end > r->ar.start) {
+					damon_destroy_region(r);
+					return -EINVAL;
+				}
+			}
+			rc = 0;
+		}
+	}
+	return rc;
+}
+
+static int set_init_regions(struct damon_ctx *c, const char *str, ssize_t len)
+{
+	struct damon_task *t;
+	struct damon_region *r, *next;
+	int pos = 0, parsed, ret;
+	int pid;
+	struct damon_addr_range ar;
+	int err;
+
+	damon_for_each_task(t, c) {
+		damon_for_each_region_safe(r, next, t)
+			damon_destroy_region(r);
+	}
+
+	while (pos < len) {
+		ret = sscanf(&str[pos], "%d %lu %lu%n",
+				&pid, &ar.start, &ar.end, &parsed);
+		if (ret != 3)
+			break;
+		err = add_init_region(c, pid, &ar);
+		if (err)
+			goto fail;
+		pos += parsed;
+	}
+
+	return 0;
+
+fail:
+	damon_for_each_task(t, c) {
+		damon_for_each_region_safe(r, next, t)
+			damon_destroy_region(r);
+	}
+	return err;
+}
+
+static ssize_t debugfs_init_regions_write(struct file *file,
+					  const char __user *buf, size_t count,
+					  loff_t *ppos)
+{
+	struct damon_ctx *ctx = &damon_user_ctx;
+	char *kbuf;
+	ssize_t ret = count;
+	int err;
+
+	kbuf = user_input_str(buf, count, ppos);
+	if (IS_ERR(kbuf))
+		return PTR_ERR(kbuf);
+
+	mutex_lock(&ctx->kdamond_lock);
+	if (ctx->kdamond) {
+		ret = -EBUSY;
+		goto unlock_out;
+	}
+
+	err = set_init_regions(ctx, kbuf, ret);
+	if (err)
+		ret = err;
+
+unlock_out:
+	mutex_unlock(&ctx->kdamond_lock);
+	kfree(kbuf);
+	return ret;
+}
+
 static ssize_t debugfs_attrs_read(struct file *file,
 		char __user *buf, size_t count, loff_t *ppos)
 {
@@ -1876,6 +2017,12 @@ static const struct file_operations record_fops = {
 	.write = debugfs_record_write,
 };
 
+static const struct file_operations init_regions_fops = {
+	.owner = THIS_MODULE,
+	.read = debugfs_init_regions_read,
+	.write = debugfs_init_regions_write,
+};
+
 static const struct file_operations attrs_fops = {
 	.owner = THIS_MODULE,
 	.read = debugfs_attrs_read,
@@ -1886,10 +2033,11 @@ static struct dentry *debugfs_root;
 
 static int __init damon_debugfs_init(void)
 {
-	const char * const file_names[] = {"attrs", "record", "schemes",
-		"pids", "monitor_on"};
-	const struct file_operations *fops[] = {&attrs_fops, &record_fops,
-		&schemes_fops, &pids_fops, &monitor_on_fops};
+	const char * const file_names[] = {"attrs", "init_regions", "record",
+		"schemes", "pids", "monitor_on"};
+	const struct file_operations *fops[] = {&attrs_fops,
+		&init_regions_fops, &record_fops, &schemes_fops, &pids_fops,
+		&monitor_on_fops};
 	int i;
 
 	debugfs_root = debugfs_create_dir("damon", NULL);
Signature · 1 line
2.17.1
#2 lore raw

RFC v5 2/11 tools/damon: Support init target regions specification

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit updates the damon user space tool to support the initial monitoring target regions specification.

---
 tools/damon/_damon.py  | 39 +++++++++++++++++++++++++++++++++++++++
 tools/damon/record.py  | 12 +++++++-----
 tools/damon/schemes.py | 12 +++++++-----
 3 files changed, 53 insertions(+), 10 deletions(-)
tools/damon/_damon.py +39 -0
index 3620ef12a5ea..ad476cc61421 100644
@@ -12,12 +12,25 @@ debugfs_attrs = None
 debugfs_record = None
 debugfs_schemes = None
 debugfs_pids = None
+debugfs_init_regions = None
 debugfs_monitor_on = None
 
 def set_target_pid(pid):
     return subprocess.call('echo %s > %s' % (pid, debugfs_pids), shell=True,
             executable='/bin/bash')
 
+def set_target(pid, init_regions=[]):
+    rc = set_target_pid(pid)
+    if rc:
+        return rc
+
+    if not os.path.exists(debugfs_init_regions):
+        return 0
+
+    string = ' '.join(['%s %d %d' % (pid, r[0], r[1]) for r in init_regions])
+    return subprocess.call('echo "%s" > %s' % (string, debugfs_init_regions),
+            shell=True, executable='/bin/bash')
+
 def turn_damon(on_off):
     return subprocess.call("echo %s > %s" % (on_off, debugfs_monitor_on),
             shell=True, executable="/bin/bash")
@@ -97,6 +110,7 @@ def chk_update_debugfs(debugfs):
     global debugfs_record
     global debugfs_schemes
     global debugfs_pids
+    global debugfs_init_regions
     global debugfs_monitor_on
 
     debugfs_damon = os.path.join(debugfs, 'damon')
@@ -104,6 +118,7 @@ def chk_update_debugfs(debugfs):
     debugfs_record = os.path.join(debugfs_damon, 'record')
     debugfs_schemes = os.path.join(debugfs_damon, 'schemes')
     debugfs_pids = os.path.join(debugfs_damon, 'pids')
+    debugfs_init_regions = os.path.join(debugfs_damon, 'init_regions')
     debugfs_monitor_on = os.path.join(debugfs_damon, 'monitor_on')
 
     if not os.path.isdir(debugfs_damon):
@@ -131,6 +146,26 @@ def cmd_args_to_attrs(args):
     return Attrs(sample_interval, aggr_interval, regions_update_interval,
             min_nr_regions, max_nr_regions, rbuf_len, rfile_path, schemes)
 
+def cmd_args_to_init_regions(args):
+    regions = []
+    for arg in args.regions.split():
+        addrs = arg.split('-')
+        try:
+            if len(addrs) != 2:
+                raise Exception('two addresses not given')
+            start = int(addrs[0])
+            end = int(addrs[1])
+            if start >= end:
+                raise Exception('start >= end')
+            if regions and regions[-1][1] > start:
+                raise Exception('regions overlap')
+        except Exception as e:
+            print('Wrong \'--regions\' argument (%s)' % e)
+            exit(1)
+
+        regions.append([start, end])
+    return regions
+
 def set_attrs_argparser(parser):
     parser.add_argument('-d', '--debugfs', metavar='<debugfs>', type=str,
             default='/sys/kernel/debug', help='debugfs mounted path')
@@ -144,3 +179,7 @@ def set_attrs_argparser(parser):
             default=10, help='minimal number of regions')
     parser.add_argument('-m', '--maxr', metavar='<# regions>', type=int,
             default=1000, help='maximum number of regions')
+
+def set_init_regions_argparser(parser):
+    parser.add_argument('-r', '--regions', metavar='"<start>-<end> ..."',
+            type=str, default='', help='monitoring target address regions')
tools/damon/record.py +7 -5
index 44fa3a12af35..6ce8721d782a 100644
@@ -13,7 +13,7 @@ import time
 
 import _damon
 
-def do_record(target, is_target_cmd, attrs, old_attrs):
+def do_record(target, is_target_cmd, init_regions, attrs, old_attrs):
     if os.path.isfile(attrs.rfile_path):
         os.rename(attrs.rfile_path, attrs.rfile_path + '.old')
 
@@ -24,8 +24,8 @@ def do_record(target, is_target_cmd, attrs, old_attrs):
     if is_target_cmd:
         p = subprocess.Popen(target, shell=True, executable='/bin/bash')
         target = p.pid
-    if _damon.set_target_pid(target):
-        print('pid setting (%s) failed' % target)
+    if _damon.set_target(target, init_regions):
+        print('target setting (%s, %s) failed' % (target, init_regions))
         cleanup_exit(old_attrs, -2)
     if _damon.turn_damon('on'):
         print('could not turn on damon' % target)
@@ -65,6 +65,7 @@ def chk_permission():
 
 def set_argparser(parser):
     _damon.set_attrs_argparser(parser)
+    _damon.set_init_regions_argparser(parser)
     parser.add_argument('target', type=str, metavar='<target>',
             help='the target command or the pid to record')
     parser.add_argument('-l', '--rbuf', metavar='<len>', type=int,
@@ -88,19 +89,20 @@ def main(args=None):
 
     args.schemes = ''
     new_attrs = _damon.cmd_args_to_attrs(args)
+    init_regions = _damon.cmd_args_to_init_regions(args)
     target = args.target
 
     target_fields = target.split()
     if not subprocess.call('which %s > /dev/null' % target_fields[0],
             shell=True, executable='/bin/bash'):
-        do_record(target, True, new_attrs, orig_attrs)
+        do_record(target, True, init_regions, new_attrs, orig_attrs)
     else:
         try:
             pid = int(target)
         except:
             print('target \'%s\' is neither a command, nor a pid' % target)
             exit(1)
-        do_record(target, False, new_attrs, orig_attrs)
+        do_record(target, False, init_regions, new_attrs, orig_attrs)
 
 if __name__ == '__main__':
     main()
tools/damon/schemes.py +7 -5
index 9f369db7d12e..49968fb947f1 100644
@@ -14,7 +14,7 @@ import time
 import _convert_damos
 import _damon
 
-def run_damon(target, is_target_cmd, attrs, old_attrs):
+def run_damon(target, is_target_cmd, init_regions, attrs, old_attrs):
     if os.path.isfile(attrs.rfile_path):
         os.rename(attrs.rfile_path, attrs.rfile_path + '.old')
 
@@ -27,8 +27,8 @@ def run_damon(target, is_target_cmd, attrs, old_attrs):
     if is_target_cmd:
         p = subprocess.Popen(target, shell=True, executable='/bin/bash')
         target = p.pid
-    if _damon.set_target_pid(target):
-        print('pid setting (%s) failed' % target)
+    if _damon.set_target(target, init_regions):
+        print('target setting (%s, %s) failed' % (target, init_regions))
         cleanup_exit(old_attrs, -2)
     if _damon.turn_damon('on'):
         print('could not turn on damon' % target)
@@ -68,6 +68,7 @@ def chk_permission():
 
 def set_argparser(parser):
     _damon.set_attrs_argparser(parser)
+    _damon.set_init_regions_argparser(parser)
     parser.add_argument('target', type=str, metavar='<target>',
             help='the target command or the pid to record')
     parser.add_argument('-c', '--schemes', metavar='<file>', type=str,
@@ -92,19 +93,20 @@ def main(args=None):
     args.out = 'null'
     args.schemes = _convert_damos.convert(args.schemes, args.sample, args.aggr)
     new_attrs = _damon.cmd_args_to_attrs(args)
+    init_regions = _damon.cmd_args_to_init_regions(args)
     target = args.target
 
     target_fields = target.split()
     if not subprocess.call('which %s > /dev/null' % target_fields[0],
             shell=True, executable='/bin/bash'):
-        run_damon(target, True, new_attrs, orig_attrs)
+        run_damon(target, True, init_regions, new_attrs, orig_attrs)
     else:
         try:
             pid = int(target)
         except:
             print('target \'%s\' is neither a command, nor a pid' % target)
             exit(1)
-        run_damon(target, False, new_attrs, orig_attrs)
+        run_damon(target, False, init_regions, new_attrs, orig_attrs)
 
 if __name__ == '__main__':
     main()
Signature · 1 line
2.17.1
#3 lore raw

RFC v5 3/11 mm/damon-test: Add more unit tests for 'init_regions'

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit adds more test cases for the new feature, 'init_regions'.

---
 mm/damon-test.h | 53 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 53 insertions(+)
mm/damon-test.h +53 -0
index b31c7fe913ca..716594342ff1 100644
@@ -152,6 +152,58 @@ static void damon_test_set_recording(struct kunit *test)
 	KUNIT_EXPECT_STREQ(test, ctx->rfile_path, "foo");
 }
 
+static void damon_test_set_init_regions(struct kunit *test)
+{
+	struct damon_ctx *ctx = &damon_user_ctx;
+	int pids[] = {1, 2, 3};
+	/* Each line represents one region in ``<pid> <start> <end>`` */
+	char * const valid_inputs[] = {"2 10 20\n 2   20 30\n2 35 45",
+		"2 10 20\n",
+		"2 10 20\n1 39 59\n1 70 134\n  2  20 25\n",
+		""};
+	/* Reading the file again will show sorted, clean output */
+	char * const valid_expects[] = {"2 10 20\n2 20 30\n2 35 45\n",
+		"2 10 20\n",
+		"1 39 59\n1 70 134\n2 10 20\n2 20 25\n",
+		""};
+	char * const invalid_inputs[] = {"4 10 20\n",	/* pid not exists */
+		"2 10 20\n 2 14 26\n",		/* regions overlap */
+		"1 10 20\n2 30 40\n 1 5 8"};	/* not sorted by address */
+	char *input, *expect;
+	int i, rc;
+	char buf[256];
+
+	damon_set_pids(ctx, pids, 3);
+
+	/* Put valid inputs and check the results */
+	for (i = 0; i < ARRAY_SIZE(valid_inputs); i++) {
+		input = valid_inputs[i];
+		expect = valid_expects[i];
+
+		rc = set_init_regions(ctx, input, strnlen(input, 256));
+		KUNIT_EXPECT_EQ(test, rc, 0);
+
+		memset(buf, 0, 256);
+		sprint_init_regions(ctx, buf, 256);
+
+		KUNIT_EXPECT_STREQ(test, (char *)buf, expect);
+	}
+	/* Put invlid inputs and check the return error code */
+	for (i = 0; i < ARRAY_SIZE(invalid_inputs); i++) {
+		input = invalid_inputs[i];
+		pr_info("input: %s\n", input);
+		rc = set_init_regions(ctx, input, strnlen(input, 256));
+		KUNIT_EXPECT_EQ(test, rc, -EINVAL);
+
+		memset(buf, 0, 256);
+		sprint_init_regions(ctx, buf, 256);
+
+		KUNIT_EXPECT_STREQ(test, (char *)buf, "");
+	}
+
+	damon_set_pids(ctx, NULL, 0);
+}
+
 static void __link_vmas(struct vm_area_struct *vmas, ssize_t nr_vmas)
 {
 	int i, j;
@@ -635,6 +687,7 @@ static struct kunit_case damon_test_cases[] = {
 	KUNIT_CASE(damon_test_regions),
 	KUNIT_CASE(damon_test_set_pids),
 	KUNIT_CASE(damon_test_set_recording),
+	KUNIT_CASE(damon_test_set_init_regions),
 	KUNIT_CASE(damon_test_three_regions_in_vmas),
 	KUNIT_CASE(damon_test_aggregate),
 	KUNIT_CASE(damon_test_write_rbuf),
Signature · 1 line
2.17.1
#5 lore raw

RFC v5 4/11 selftests/damon/_chk_record: Do not check number of gaps

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

Now the regions can be explicitly set as users want. Therefore checking the number of gaps doesn't make sense. Remove the condition.

---
 tools/testing/selftests/damon/_chk_record.py | 6 ------
 1 file changed, 6 deletions(-)
tools/testing/selftests/damon/_chk_record.py +0 -6
index 5cfcf4161404..ef28d4f7aca1 100644
@@ -36,12 +36,9 @@ def chk_task_info(f):
         print('too many regions: %d > %d' % (nr_regions, max_nr_regions))
         exit(1)
 
-    nr_gaps = 0
     eaddr = 0
     for r in range(nr_regions):
         saddr = struct.unpack('L', f.read(8))[0]
-        if eaddr and saddr != eaddr:
-            nr_gaps += 1
         eaddr = struct.unpack('L', f.read(8))[0]
         nr_accesses = struct.unpack('I', f.read(4))[0]
 
@@ -55,9 +52,6 @@ def chk_task_info(f):
                 print('too high nr_access: expected %d but %d' %
                         (max_nr_accesses, nr_accesses))
                 exit(1)
-    if nr_gaps != 2:
-        print('number of gaps are not two but %d' % nr_gaps)
-        exit(1)
 
 def parse_time_us(bindat):
     sec = struct.unpack('l', bindat[0:8])[0]
Signature · 1 line
2.17.1
#6 lore raw

RFC v5 5/11 Docs/damon: Document 'initial_regions' feature

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit documents the 'initial_regions' feature.

---
 Documentation/admin-guide/mm/damon/usage.rst | 35 ++++++++++++++++++++
 1 file changed, 35 insertions(+)
Documentation/admin-guide/mm/damon/usage.rst +35 -0
index 153f07da9368..573fcb4c57a7 100644
@@ -315,6 +315,41 @@ having pids 42 and 4242 as the processes to be monitored and check it again::
 Note that setting the pids doesn't start the monitoring.
 
 
+Initial Monitoring Target Regions
+---------------------------------
+
+In case of the debugfs based monitoring, DAMON automatically sets and updates
+the monitoring target regions so that entire memory mappings of target
+processes can be covered. However, users might want to limit the monitoring
+region to specific address ranges, such as the heap, the stack, or specific
+file-mapped area. Or, some users might know the initial access pattern of their
+workloads and therefore want to set optimal initial regions for the 'adaptive
+regions adjustment'.
+
+In such cases, users can explicitly set the initial monitoring target regions
+as they want, by writing proper values to the ``init_regions`` file.  Each line
+of the input should represent one region in below form.::
+
+    <pid> <start address> <end address>
+
+The ``pid`` should already in ``pids`` file, and the regions should be
+passed in address order.  For example, below commands will set a couple of
+address ranges, ``1-100`` and ``100-200`` as the initial monitoring target
+region of process 42, and another couple of address ranges, ``20-40`` and
+``50-100`` as that of process 4242.::
+
+    # cd <debugfs>/damon
+    # echo "42   1       100
+            42   100     200
+            4242 20      40
+            4242 50      100" > init_regions
+
+Note that this sets the initial monitoring target regions only.  DAMON will
+automatically updates the boundary of the regions after one ``regions update
+interval``.  Therefore, users should set the ``regions update interval`` large
+enough.
+
+
 Record
 ------
 
Signature · 1 line
2.17.1
#7 lore raw

RFC v5 6/11 mm/rmap: Export essential functions for rmap_run

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit exports the three essential functions for ramp walk, 'page_lock_anon_vma_read()', 'rmap_walk()', and 'page_rmapping()', to GPL modules. Those will be used by DAMON for the physical memory address based access monitoring in the following commit.

---
 mm/rmap.c | 2 ++
 mm/util.c | 1 +
 2 files changed, 3 insertions(+)
mm/rmap.c +2 -0
index f79a206b271a..20ac37b27a7d 100644
@@ -579,6 +579,7 @@ struct anon_vma *page_lock_anon_vma_read(struct page *page)
 	rcu_read_unlock();
 	return anon_vma;
 }
+EXPORT_SYMBOL_GPL(page_lock_anon_vma_read);
 
 void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
 {
@@ -1934,6 +1935,7 @@ void rmap_walk(struct page *page, struct rmap_walk_control *rwc)
 	else
 		rmap_walk_file(page, rwc, false);
 }
+EXPORT_SYMBOL_GPL(rmap_walk);
 
 /* Like rmap_walk, but caller holds relevant rmap lock */
 void rmap_walk_locked(struct page *page, struct rmap_walk_control *rwc)
mm/util.c +1 -0
index 988d11e6c17c..1df32546fe28 100644
@@ -620,6 +620,7 @@ void *page_rmapping(struct page *page)
 	page = compound_head(page);
 	return __page_rmapping(page);
 }
+EXPORT_SYMBOL_GPL(page_rmapping);
 
 /*
  * Return true if this page is mapped into pagetables.
Signature · 1 line
2.17.1
#8 lore raw

RFC v5 7/11 mm/damon: Implement callbacks for physical memory monitoring

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit implements the four callbacks (->init_target_regions, ->update_target_regions, ->prepare_access_check, and ->check_accesses) for the basic access monitoring of the physical memory address space. By setting the callback pointers to point those, users can easily monitor the accesses to the physical memory.

Internally, it uses the PTE Accessed bit, as similar to that of the virtual memory support. Also, it supports only user memory pages, as idle page tracking also does, for the same reason. If the monitoring target physical memory address range contains non-user memory pages, access check of the pages will do nothing but simply treat the pages as not accessed.

Users who want to use other access check primitives and/or monitor the non-user memory regions could implement and use their own callbacks.

---
 include/linux/damon.h |   5 ++
 mm/damon.c            | 201 ++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 206 insertions(+)
include/linux/damon.h +5 -0
index f176a2b6e67c..eb7a5595b616 100644
@@ -227,6 +227,11 @@ void kdamond_update_vm_regions(struct damon_ctx *ctx);
 void kdamond_prepare_vm_access_checks(struct damon_ctx *ctx);
 unsigned int kdamond_check_vm_accesses(struct damon_ctx *ctx);
 
+void kdamond_init_phys_regions(struct damon_ctx *ctx);
+void kdamond_update_phys_regions(struct damon_ctx *ctx);
+void kdamond_prepare_phys_access_checks(struct damon_ctx *ctx);
+unsigned int kdamond_check_phys_accesses(struct damon_ctx *ctx);
+
 int damon_set_pids(struct damon_ctx *ctx, int *pids, ssize_t nr_pids);
 int damon_set_attrs(struct damon_ctx *ctx, unsigned long sample_int,
 		unsigned long aggr_int, unsigned long regions_update_int,
mm/damon.c +201 -0

229 lines not on this page · raw message

Signature · 1 line
2.17.1
#9 lore raw

RFC v5 8/11 mm/damon/debugfs: Support physical memory monitoring

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit makes the debugfs interface to support the physical memory monitoring, in addition to the virtual memory monitoring.

Users can do the physical memory monitoring by writing a special keyword, 'paddr\n' to the 'pids' debugfs file. Then, DAMON will check the special keyword and configure the callbacks of the monitoring context for the debugfs user for physical memory. This will internally add one fake monitoring target process, which has pid as -1.

Unlike the virtual memory monitoring, DAMON debugfs will not automatically set the monitoring target region. Therefore, users should also set the monitoring target address region using the 'init_regions' debugfs file. While doing this, the 'pid' in the input should be '-1'.

Finally, the physical memory monitoring will not automatically terminated because it has fake monitoring target process. The user should explicitly turn off the monitoring by writing 'off' to the 'monitor_on' debugfs file.

---
 mm/damon.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
mm/damon.c +17 -0
index fb533b2ee4bf..34c418ef4e5f 100644
@@ -1928,6 +1928,23 @@ static ssize_t debugfs_pids_write(struct file *file,
 	if (IS_ERR(kbuf))
 		return PTR_ERR(kbuf);
 
+	if (!strncmp(kbuf, "paddr\n", count)) {
+		/* Configure the context for physical memory monitoring */
+		ctx->init_target_regions = kdamond_init_phys_regions;
+		ctx->update_target_regions = kdamond_update_phys_regions;
+		ctx->prepare_access_checks = kdamond_prepare_phys_access_checks;
+		ctx->check_accesses = kdamond_check_phys_accesses;
+
+		/* Set the fake target task pid as -1 */
+		snprintf(kbuf, count, "-1    ");
+	} else {
+		/* Configure the context for virtual memory monitoring */
+		ctx->init_target_regions = kdamond_init_vm_regions;
+		ctx->update_target_regions = kdamond_update_vm_regions;
+		ctx->prepare_access_checks = kdamond_prepare_vm_access_checks;
+		ctx->check_accesses = kdamond_check_vm_accesses;
+	}
+
 	targets = str_to_pids(kbuf, ret, &nr_targets);
 	if (!targets) {
 		ret = -ENOMEM;
Signature · 1 line
2.17.1
#10 lore raw

RFC v5 9/11 tools/damon/record: Support physical memory monitoring

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit allows users to record the data accesses on physical memory address space by passing 'paddr' as target to 'damo-record'. If the init regions are given, the regions will be monitored. Else, it will monitor biggest conitguous 'System RAM' region in '/proc/iomem' and monitor the region.

---
 tools/damon/_damon.py |  2 ++
 tools/damon/heats.py  |  2 +-
 tools/damon/record.py | 29 ++++++++++++++++++++++++++++-
 3 files changed, 31 insertions(+), 2 deletions(-)
tools/damon/_damon.py +2 -0
index ad476cc61421..95d23c2ab6ee 100644
@@ -27,6 +27,8 @@ def set_target(pid, init_regions=[]):
     if not os.path.exists(debugfs_init_regions):
         return 0
 
+    if pid == 'paddr':
+        pid = -1
     string = ' '.join(['%s %d %d' % (pid, r[0], r[1]) for r in init_regions])
     return subprocess.call('echo "%s" > %s' % (string, debugfs_init_regions),
             shell=True, executable='/bin/bash')
tools/damon/heats.py +1 -1
index 99837083874e..34dbcf1a839d 100644
@@ -307,7 +307,7 @@ def plot_heatmap(data_file, output_file):
     set xrange [0:];
     set yrange [0:];
     set xlabel 'Time (ns)';
-    set ylabel 'Virtual Address (bytes)';
+    set ylabel 'Address (bytes)';
     plot '%s' using 1:2:3 with image;""" % (terminal, output_file, data_file)
     subprocess.call(['gnuplot', '-e', gnuplot_cmd])
     os.remove(data_file)
tools/damon/record.py +28 -1
index 6ce8721d782a..416dca940c1d 100644
@@ -73,6 +73,29 @@ def set_argparser(parser):
     parser.add_argument('-o', '--out', metavar='<file path>', type=str,
             default='damon.data', help='output file path')
 
+def default_paddr_region():
+    "Largest System RAM region becomes the default"
+    ret = []
+    with open('/proc/iomem', 'r') as f:
+        # example of the line: '100000000-42b201fff : System RAM'
+        for line in f:
+            fields = line.split(':')
+            if len(fields) != 2:
+                continue
+            name = fields[1].strip()
+            if name != 'System RAM':
+                continue
+            addrs = fields[0].split('-')
+            if len(addrs) != 2:
+                continue
+            start = int(addrs[0], 16)
+            end = int(addrs[1], 16)
+
+            sz_region = end - start
+            if not ret or sz_region > (ret[1] - ret[0]):
+                ret = [start, end]
+    return ret
+
 def main(args=None):
     global orig_attrs
     if not args:
@@ -93,7 +116,11 @@ def main(args=None):
     target = args.target
 
     target_fields = target.split()
-    if not subprocess.call('which %s > /dev/null' % target_fields[0],
+    if target == 'paddr':   # physical memory address space
+        if not init_regions:
+            init_regions = [default_paddr_region()]
+        do_record(target, False, init_regions, new_attrs, orig_attrs)
+    elif not subprocess.call('which %s > /dev/null' % target_fields[0],
             shell=True, executable='/bin/bash'):
         do_record(target, True, init_regions, new_attrs, orig_attrs)
     else:
Signature · 1 line
2.17.1
#11 lore raw

RFC v5 10/11 tools/damon/record: Support NUMA specific recording

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit updates the DAMON user space tool (damo-record) for NUMA specific physical memory monitoring. With this change, users can monitor accesses to physical memory of specific NUMA node.

---
 tools/damon/_paddr_layout.py | 158 +++++++++++++++++++++++++++++++++++
 tools/damon/record.py        |  21 ++++-
 2 files changed, 178 insertions(+), 1 deletion(-)
 create mode 100644 tools/damon/_paddr_layout.py
tools/damon/_paddr_layout.py new file +158 -0
new file mode 100644
index 000000000000..10056172db21
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+import os
+
+class PaddrRange:
+    start = None
+    end = None
+    nid = None
+    state = None
+    name = None
+
+    def __init__(self, start, end, nid, state, name):
+        self.start = start
+        self.end = end
+        self.nid = nid
+        self.state = state
+        self.name = name
+
+    def interleaved(self, prange):
+        if self.end <= prange.start:
+            return None
+        if prange.end <= self.start:
+            return None
+        return [max(self.start, prange.start), min(self.end, prange.end)]
+
+    def __str__(self):
+        return '%x-%x, nid %s, state %s, name %s' % (self.start, self.end,
+                self.nid, self.state, self.name)
+
+class MemBlock:
+    nid = None
+    index = None
+    state = None
+
+    def __init__(self, nid, index, state):
+        self.nid = nid
+        self.index = index
+        self.state = state
+
+    def __str__(self):
+        return '%d (%s)' % (self.index, self.state)
+
+    def __repr__(self):
+        return self.__str__()
+
+def readfile(file_path):
+    with open(file_path, 'r') as f:
+        return f.read()
+
+def collapse_ranges(ranges):
+    ranges = sorted(ranges, key=lambda x: x.start)
+    merged = []
+    for r in ranges:
+        if not merged:
+            merged.append(r)
+            continue
+        last = merged[-1]
+        if last.end != r.start or last.nid != r.nid or last.state != r.state:
+            merged.append(r)
+        else:
+            last.end = r.end
+    return merged
+
+def memblocks_to_ranges(blocks, block_size):
+    ranges = []
+    for b in blocks:
+        ranges.append(PaddrRange(b.index * block_size,
+            (b.index + 1) * block_size, b.nid, b.state, None))
+
+    return collapse_ranges(ranges)
+
+def memblock_ranges():
+    SYSFS='/sys/devices/system/node'
+    sz_block = int(readfile('/sys/devices/system/memory/block_size_bytes'), 16)
+    sys_nodes = [x for x in os.listdir(SYSFS) if x.startswith('node')]
+
+    blocks = []
+    for sys_node in sys_nodes:
+        nid = int(sys_node[4:])
+
+        sys_node_files = os.listdir(os.path.join(SYSFS, sys_node))
+        for f in sys_node_files:
+            if not f.startswith('memory'):
+                continue
+            index = int(f[6:])
+            sys_state = os.path.join(SYSFS, sys_node, f, 'state')
+            state = readfile(sys_state).strip()
+
+            blocks.append(MemBlock(nid, index, state))
+
+    return memblocks_to_ranges(blocks, sz_block)
+
+def iomem_ranges():
+    ranges = []
+
+    with open('/proc/iomem', 'r') as f:
+        # example of the line: '100000000-42b201fff : System RAM'
+        for line in f:
+            fields = line.split(':')
+            if len(fields) < 2:
+                continue
+            name = ':'.join(fields[1:]).strip()
+            addrs = fields[0].split('-')
+            if len(addrs) != 2:
+                continue
+            start = int(addrs[0], 16)
+            end = int(addrs[1], 16) + 1
+            ranges.append(PaddrRange(start, end, None, None, name))
+
+    return ranges
+
+def paddr_ranges():
+    ranges1 = memblock_ranges()
+    ranges2 = iomem_ranges()
+    merged = []
+
+    for r in ranges1:
+        subsets = []
+        for r2 in ranges2:
+            interleaved = r.interleaved(r2)
+            if interleaved == None:
+                continue
+
+            start, end = interleaved
+            left = None
+            if start > r.start:
+                left = PaddrRange(r.start, start, r.nid, r.state, r.name)
+                subsets.append(left)
+
+            middle = PaddrRange(start, end, r.nid, r.state, r.name)
+            if r2.nid:
+                middle.nid = r2.nid
+            if r2.state:
+                middle.state = r2.state
+            if r2.name:
+                middle.name = r2.name
+            subsets.append(middle)
+            r.start = end
+        if r.start < r.end:
+            subsets = [r]
+
+        merged += subsets
+    return merged
+
+def pr_ranges(ranges):
+    print('#%12s %13s\tnode\tstate\tresource\tsize' % ('start', 'end'))
+    for r in ranges:
+        print('%13d %13d\t%s\t%s\t%s\t%d' % (r.start, r.end, r.nid,
+            r.state, r.name, r.end - r.start))
+
+def main():
+    ranges = paddr_ranges()
+
+    pr_ranges(ranges)
+
+if __name__ == '__main__':
+    main()
tools/damon/record.py +20 -1
index 416dca940c1d..8440a9818810 100644
@@ -12,6 +12,7 @@ import subprocess
 import time
 
 import _damon
+import _paddr_layout
 
 def do_record(target, is_target_cmd, init_regions, attrs, old_attrs):
     if os.path.isfile(attrs.rfile_path):
@@ -70,6 +71,8 @@ def set_argparser(parser):
             help='the target command or the pid to record')
     parser.add_argument('-l', '--rbuf', metavar='<len>', type=int,
             default=1024*1024, help='length of record result buffer')
+    parser.add_argument('--numa_node', metavar='<node id>', type=int,
+            help='if target is \'paddr\', limit it to the numa node')
     parser.add_argument('-o', '--out', metavar='<file path>', type=str,
             default='damon.data', help='output file path')
 
@@ -96,6 +99,18 @@ def default_paddr_region():
                 ret = [start, end]
     return ret
 
+def paddr_region_of(numa_node):
+    regions = []
+    default_region = default_paddr_region()
+    paddr_ranges = _paddr_layout.paddr_ranges()
+    for r in paddr_ranges:
+        if r.end <= default_region[0] or default_region[1] <= r.start:
+            continue
+        if r.nid == numa_node and r.name == 'System RAM':
+            regions.append([r.start, r.end])
+
+    return regions
+
 def main(args=None):
     global orig_attrs
     if not args:
@@ -113,12 +128,16 @@ def main(args=None):
     args.schemes = ''
     new_attrs = _damon.cmd_args_to_attrs(args)
     init_regions = _damon.cmd_args_to_init_regions(args)
+    numa_node = args.numa_node
     target = args.target
 
     target_fields = target.split()
     if target == 'paddr':   # physical memory address space
         if not init_regions:
-            init_regions = [default_paddr_region()]
+            if numa_node:
+                init_regions = paddr_region_of(numa_node)
+            else:
+                init_regions = [default_paddr_region()]
         do_record(target, False, init_regions, new_attrs, orig_attrs)
     elif not subprocess.call('which %s > /dev/null' % target_fields[0],
             shell=True, executable='/bin/bash'):
Signature · 1 line
2.17.1
#12 lore raw

RE: [RFC v5 10/11] tools/damon/record: Support NUMA specific recording

Quoted 147 lines

-----Original Message-----
From: [email protected] <[email protected]> On Behalf Of SeongJae Park
Sent: Tuesday, July 7, 2020 10:46 PM
To: [email protected]
Cc: SeongJae Park <[email protected]>; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; Huang, Ying <[email protected]>; [email protected]; [email protected]; [email protected]; [email protected]
Subject: [RFC v5 10/11] tools/damon/record: Support NUMA specific recording

From: SeongJae Park <[email protected]>

This commit updates the DAMON user space tool (damo-record) for NUMA specific physical memory monitoring. With this change, users can monitor accesses to physical memory of specific NUMA node.

---
tools/damon/_paddr_layout.py | 158
+++++++++++++++++++++++++++++++++++
tools/damon/record.py | 21 ++++-

2 files changed, 178 insertions(+), 1 deletion(-)

create mode 100644 tools/damon/_paddr_layout.py

tools/damon/_paddr_layout.py new file +75 -0
new file mode 100644
index 000000000000..10056172db21
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+import os
+
+class PaddrRange:
+    start = None
+    end = None
+    nid = None
+    state = None
+    name = None
+
+    def __init__(self, start, end, nid, state, name):
+        self.start = start
+        self.end = end
+        self.nid = nid
+        self.state = state
+        self.name = name
+
+    def interleaved(self, prange):
+        if self.end <= prange.start:
+            return None
+        if prange.end <= self.start:
+            return None
+        return [max(self.start, prange.start), min(self.end, prange.end)]
+
+    def __str__(self):
+        return '%x-%x, nid %s, state %s, name %s' % (self.start, self.end,
+                self.nid, self.state, self.name)
+
+class MemBlock:
+    nid = None
+    index = None
+    state = None
+
+    def __init__(self, nid, index, state):
+        self.nid = nid
+        self.index = index
+        self.state = state
+
+    def __str__(self):
+        return '%d (%s)' % (self.index, self.state)
+
+    def __repr__(self):
+        return self.__str__()
+
+def readfile(file_path):
+    with open(file_path, 'r') as f:
+        return f.read()
+
+def collapse_ranges(ranges):
+    ranges = sorted(ranges, key=lambda x: x.start)
+    merged = []
+    for r in ranges:
+        if not merged:
+            merged.append(r)
+            continue
+        last = merged[-1]
+        if last.end != r.start or last.nid != r.nid or last.state != r.state:
+            merged.append(r)
+        else:
+            last.end = r.end
+    return merged
+
+def memblocks_to_ranges(blocks, block_size):
+    ranges = []
+    for b in blocks:
+        ranges.append(PaddrRange(b.index * block_size,
+            (b.index + 1) * block_size, b.nid, b.state, None))
+
+    return collapse_ranges(ranges)
+
+def memblock_ranges():
+    SYSFS='/sys/devices/system/node'
+    sz_block = int(readfile('/sys/devices/system/memory/block_size_bytes'),

16)

tools/damon/_paddr_layout.py new file +26 -0
+    sys_nodes = [x for x in os.listdir(SYSFS) if x.startswith('node')]
+
+    blocks = []
+    for sys_node in sys_nodes:
+        nid = int(sys_node[4:])
+
+        sys_node_files = os.listdir(os.path.join(SYSFS, sys_node))
+        for f in sys_node_files:
+            if not f.startswith('memory'):
+                continue
+            index = int(f[6:])
+            sys_state = os.path.join(SYSFS, sys_node, f, 'state')
+            state = readfile(sys_state).strip()
+
+            blocks.append(MemBlock(nid, index, state))
+
+    return memblocks_to_ranges(blocks, sz_block)
+
+def iomem_ranges():
+    ranges = []
+
+    with open('/proc/iomem', 'r') as f:
+        # example of the line: '100000000-42b201fff : System RAM'
+        for line in f:
+            fields = line.split(':')
+            if len(fields) < 2:

tools/damon/_paddr_layout.py line 111

Quoted 10 lines
tools/damon/_paddr_layout.py new file +10 -0
+                continue
+            name = ':'.join(fields[1:]).strip()
+            addrs = fields[0].split('-')
+            if len(addrs) != 2:
+                continue
+            start = int(addrs[0], 16)
+            end = int(addrs[1], 16) + 1
+            ranges.append(PaddrRange(start, end, None, None, name))
+
+    return ranges

Hi SeongJae

Here on system with persistent memory, user can plug {all or portion of }persistent memory into buddy system with drivers from patchset[1] implemented. The persistent memory in this setup will be treated as normal system RAM, and have valid full-fledged page structure as well.

For example, here is what /proc/iomem looks like in system with such configuration on my testbed.

1840000000-963fffffff : Persistent Memory
1840000000-18be1fffff : namespace0.0
18c0000000-37bfffffff : dax0.0
18c0000000-37bfffffff : System RAM <- first 128G of persistent memory corresponding to node 2

# numactl  -H
available: 3 nodes (0-2)
node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
node 0 size: 95447 MB
node 0 free: 92391 MB
node 1 cpus: 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
node 1 size: 96733 MB
node 1 free: 95670 MB
node 2 cpus:
node 2 size: 126976 MB
node 2 free: 126935 MB
node distances:
node   0   1   2
  0:  10  21  17
  1:  21  10  28
  2:  17  28  10

So here we have two ranges:
1840000000-963fffffff : Persistent Memory
18c0000000-37bfffffff : System RAM

[1]:
https://patchwork.kernel.org/cover/10829019/

Quoted 15 lines
tools/damon/_paddr_layout.py new file +15 -0
+def paddr_ranges():
+    ranges1 = memblock_ranges()
+    ranges2 = iomem_ranges()
+    merged = []
+
+    for r in ranges1:
+        subsets = []
+        for r2 in ranges2:
+            interleaved = r.interleaved(r2)
+            if interleaved == None:
+                continue
+
+            start, end = interleaved
+            left = None
+            if start > r.start:

tools/damon/_paddr_layout.py line 137

Quoted 10 lines
tools/damon/_paddr_layout.py new file +10 -0
+                left = PaddrRange(r.start, start, r.nid, r.state, r.name)
+                subsets.append(left)
+
+            middle = PaddrRange(start, end, r.nid, r.state, r.name)
+            if r2.nid:
+                middle.nid = r2.nid
+            if r2.state:
+                middle.state = r2.state
+            if r2.name:
+                middle.name = r2.name

Memory block from numa node 2 will match with range "1840000000-963fffffff : Persistent Memory" But take the name "Persistent memory", expected "System RAM" here.

Quoted 45 lines
tools/damon/_paddr_layout.py new file +21 -0
+            subsets.append(middle)
+            r.start = end
+        if r.start < r.end:
+            subsets = [r]
+
+        merged += subsets
+    return merged
+
+def pr_ranges(ranges):
+    print('#%12s %13s\tnode\tstate\tresource\tsize' % ('start', 'end'))
+    for r in ranges:
+        print('%13d %13d\t%s\t%s\t%s\t%d' % (r.start, r.end, r.nid,
+            r.state, r.name, r.end - r.start))
+
+def main():
+    ranges = paddr_ranges()
+
+    pr_ranges(ranges)
+
+if __name__ == '__main__':
+    main()
tools/damon/record.py +0 -0
index 416dca940c1d..8440a9818810 100644
@@ -12,6 +12,7 @@ import subprocess

import time

import _damon
+import _paddr_layout

def do_record(target, is_target_cmd, init_regions, attrs, old_attrs):
if os.path.isfile(attrs.rfile_path):

tools/damon/record.py +2 -0
@@ -70,6 +71,8 @@ def set_argparser(parser):
            help='the target command or the pid to record')
    parser.add_argument('-l', '--rbuf', metavar='<len>', type=int,
            default=1024*1024, help='length of record result buffer')
+    parser.add_argument('--numa_node', metavar='<node id>', type=int,
+            help='if target is \'paddr\', limit it to the numa node')
    parser.add_argument('-o', '--out', metavar='<file path>', type=str,
            default='damon.data', help='output file path')
 
@@ -96,6 +99,18 @@ def default_paddr_region():
                ret = [start, end]
    return ret

tools/damon/record.py def default_paddr_region(): · line 110

Quoted 10 lines
tools/damon/record.py +9 -0
 
+def paddr_region_of(numa_node):
+    regions = []
+    default_region = default_paddr_region()
+    paddr_ranges = _paddr_layout.paddr_ranges()
+    for r in paddr_ranges:
+        if r.end <= default_region[0] or default_region[1] <= r.start:
+            continue
+        if r.nid == numa_node and r.name == 'System RAM':
+            regions.append([r.start, r.end])

To profile physical address for numa node 2, above checking will not return valid node 2 range i.e., 18c0000000-37bfffffff : System RAM, but empty ones.

I tweaked the checking to match "Persistent Memory" also, it looks physical address monitoring with numa node specified works from first glance.

I'm willing to give it a try once you posted next updated version.

Quoted 26 lines
tools/damon/record.py +2 -0
+    return regions
+

def main(args=None):
global orig_attrs
if not args:

tools/damon/record.py +5 -2
@@ -113,12 +128,16 @@ def main(args=None):
    args.schemes = ''
    new_attrs = _damon.cmd_args_to_attrs(args)
    init_regions = _damon.cmd_args_to_init_regions(args)
+    numa_node = args.numa_node
    target = args.target
 
    target_fields = target.split()
    if target == 'paddr':   # physical memory address space
        if not init_regions:
-            init_regions = [default_paddr_region()]
+            if numa_node:
+                init_regions = paddr_region_of(numa_node)
+            else:
+                init_regions = [default_paddr_region()]
        do_record(target, False, init_regions, new_attrs, orig_attrs)
    elif not subprocess.call('which %s > /dev/null' % target_fields[0],
            shell=True, executable='/bin/bash'):
--

2.17.1

#13 lore raw

Re: RE: [RFC v5 10/11] tools/damon/record: Support NUMA specific recording

On Mon, 20 Jul 2020 06:53:14 +0000 "Du, Fan" <[email protected]> wrote:

[...]
From: SeongJae Park <[email protected]>

Quoted 134 lines
Quoted 121 lines

This commit updates the DAMON user space tool (damo-record) for NUMA specific physical memory monitoring. With this change, users can monitor accesses to physical memory of specific NUMA node.

---
tools/damon/_paddr_layout.py | 158
+++++++++++++++++++++++++++++++++++
tools/damon/record.py | 21 ++++-

2 files changed, 178 insertions(+), 1 deletion(-)

create mode 100644 tools/damon/_paddr_layout.py

tools/damon/_paddr_layout.py new file +75 -0
new file mode 100644
index 000000000000..10056172db21
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+
+import os
+
+class PaddrRange:
+    start = None
+    end = None
+    nid = None
+    state = None
+    name = None
+
+    def __init__(self, start, end, nid, state, name):
+        self.start = start
+        self.end = end
+        self.nid = nid
+        self.state = state
+        self.name = name
+
+    def interleaved(self, prange):
+        if self.end <= prange.start:
+            return None
+        if prange.end <= self.start:
+            return None
+        return [max(self.start, prange.start), min(self.end, prange.end)]
+
+    def __str__(self):
+        return '%x-%x, nid %s, state %s, name %s' % (self.start, self.end,
+                self.nid, self.state, self.name)
+
+class MemBlock:
+    nid = None
+    index = None
+    state = None
+
+    def __init__(self, nid, index, state):
+        self.nid = nid
+        self.index = index
+        self.state = state
+
+    def __str__(self):
+        return '%d (%s)' % (self.index, self.state)
+
+    def __repr__(self):
+        return self.__str__()
+
+def readfile(file_path):
+    with open(file_path, 'r') as f:
+        return f.read()
+
+def collapse_ranges(ranges):
+    ranges = sorted(ranges, key=lambda x: x.start)
+    merged = []
+    for r in ranges:
+        if not merged:
+            merged.append(r)
+            continue
+        last = merged[-1]
+        if last.end != r.start or last.nid != r.nid or last.state != r.state:
+            merged.append(r)
+        else:
+            last.end = r.end
+    return merged
+
+def memblocks_to_ranges(blocks, block_size):
+    ranges = []
+    for b in blocks:
+        ranges.append(PaddrRange(b.index * block_size,
+            (b.index + 1) * block_size, b.nid, b.state, None))
+
+    return collapse_ranges(ranges)
+
+def memblock_ranges():
+    SYSFS='/sys/devices/system/node'
+    sz_block = int(readfile('/sys/devices/system/memory/block_size_bytes'),

16)

tools/damon/_paddr_layout.py new file +26 -0
+    sys_nodes = [x for x in os.listdir(SYSFS) if x.startswith('node')]
+
+    blocks = []
+    for sys_node in sys_nodes:
+        nid = int(sys_node[4:])
+
+        sys_node_files = os.listdir(os.path.join(SYSFS, sys_node))
+        for f in sys_node_files:
+            if not f.startswith('memory'):
+                continue
+            index = int(f[6:])
+            sys_state = os.path.join(SYSFS, sys_node, f, 'state')
+            state = readfile(sys_state).strip()
+
+            blocks.append(MemBlock(nid, index, state))
+
+    return memblocks_to_ranges(blocks, sz_block)
+
+def iomem_ranges():
+    ranges = []
+
+    with open('/proc/iomem', 'r') as f:
+        # example of the line: '100000000-42b201fff : System RAM'
+        for line in f:
+            fields = line.split(':')
+            if len(fields) < 2:

tools/damon/_paddr_layout.py line 111

Quoted 10 lines
tools/damon/_paddr_layout.py new file +10 -0
+                continue
+            name = ':'.join(fields[1:]).strip()
+            addrs = fields[0].split('-')
+            if len(addrs) != 2:
+                continue
+            start = int(addrs[0], 16)
+            end = int(addrs[1], 16) + 1
+            ranges.append(PaddrRange(start, end, None, None, name))
+
+    return ranges

Hi SeongJae

Quoted 3 lines

Here on system with persistent memory, user can plug {all or portion of }persistent memory into buddy system with drivers from patchset[1] implemented. The persistent memory in this setup will be treated as normal system RAM, and have valid full-fledged page structure as well.

Cool! I didn't read the patchset in detail yet. I will take a look soon!

Quoted 53 lines

For example, here is what /proc/iomem looks like in system with such configuration on my testbed.

1840000000-963fffffff : Persistent Memory
1840000000-18be1fffff : namespace0.0
18c0000000-37bfffffff : dax0.0
18c0000000-37bfffffff : System RAM <- first 128G of persistent memory corresponding to node 2

# numactl  -H
available: 3 nodes (0-2)
node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
node 0 size: 95447 MB
node 0 free: 92391 MB
node 1 cpus: 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
node 1 size: 96733 MB
node 1 free: 95670 MB
node 2 cpus:
node 2 size: 126976 MB
node 2 free: 126935 MB
node distances:
node   0   1   2
  0:  10  21  17
  1:  21  10  28
  2:  17  28  10

So here we have two ranges:
1840000000-963fffffff : Persistent Memory
18c0000000-37bfffffff : System RAM

[1]:
https://patchwork.kernel.org/cover/10829019/

Quoted 20 lines
tools/damon/_paddr_layout.py new file +20 -0
+def paddr_ranges():
+    ranges1 = memblock_ranges()
+    ranges2 = iomem_ranges()
+    merged = []
+
+    for r in ranges1:
+        subsets = []
+        for r2 in ranges2:
+            interleaved = r.interleaved(r2)
+            if interleaved == None:
+                continue
+
+            start, end = interleaved
+            left = None
+            if start > r.start:
+                left = PaddrRange(r.start, start, r.nid, r.state, r.name)
+                subsets.append(left)
+
+            middle = PaddrRange(start, end, r.nid, r.state, r.name)
+            if r2.nid:
Quoted 8 lines

tools/damon/_paddr_layout.py line 137

Quoted 5 lines
tools/damon/_paddr_layout.py new file +5 -0
+                middle.nid = r2.nid
+            if r2.state:
+                middle.state = r2.state
+            if r2.name:
+                middle.name = r2.name

Memory block from numa node 2 will match with range "1840000000-963fffffff : Persistent Memory" But take the name "Persistent memory", expected "System RAM" here.

You're right, current code cares only the outermost regions. I will fix this in the next spin.

Quoted 60 lines
Quoted 46 lines
tools/damon/_paddr_layout.py new file +21 -0
+            subsets.append(middle)
+            r.start = end
+        if r.start < r.end:
+            subsets = [r]
+
+        merged += subsets
+    return merged
+
+def pr_ranges(ranges):
+    print('#%12s %13s\tnode\tstate\tresource\tsize' % ('start', 'end'))
+    for r in ranges:
+        print('%13d %13d\t%s\t%s\t%s\t%d' % (r.start, r.end, r.nid,
+            r.state, r.name, r.end - r.start))
+
+def main():
+    ranges = paddr_ranges()
+
+    pr_ranges(ranges)
+
+if __name__ == '__main__':
+    main()
tools/damon/record.py +0 -0
index 416dca940c1d..8440a9818810 100644
@@ -12,6 +12,7 @@ import subprocess

import time

import _damon
+import _paddr_layout

def do_record(target, is_target_cmd, init_regions, attrs, old_attrs):
if os.path.isfile(attrs.rfile_path):

tools/damon/record.py +2 -0
@@ -70,6 +71,8 @@ def set_argparser(parser):
            help='the target command or the pid to record')
    parser.add_argument('-l', '--rbuf', metavar='<len>', type=int,
            default=1024*1024, help='length of record result buffer')
+    parser.add_argument('--numa_node', metavar='<node id>', type=int,
+            help='if target is \'paddr\', limit it to the numa node')
    parser.add_argument('-o', '--out', metavar='<file path>', type=str,
            default='damon.data', help='output file path')
 
@@ -96,6 +99,18 @@ def default_paddr_region():
                ret = [start, end]
    return ret

tools/damon/record.py def default_paddr_region(): · line 110

Quoted 10 lines
tools/damon/record.py +9 -0
 
+def paddr_region_of(numa_node):
+    regions = []
+    default_region = default_paddr_region()
+    paddr_ranges = _paddr_layout.paddr_ranges()
+    for r in paddr_ranges:
+        if r.end <= default_region[0] or default_region[1] <= r.start:
+            continue
+        if r.nid == numa_node and r.name == 'System RAM':
+            regions.append([r.start, r.end])

To profile physical address for numa node 2, above checking will not return valid node 2 range i.e., 18c0000000-37bfffffff : System RAM, but empty ones.

Quoted 4 lines

I tweaked the checking to match "Persistent Memory" also, it looks physical address monitoring with numa node specified works from first glance.

I'm willing to give it a try once you posted next updated version.

So glad to hear that! Hope to get your feedback again!

Quoted 13 lines
Quoted 13 lines
tools/damon/record.py +2 -0
+    return regions
+

def main(args=None):
global orig_attrs
if not args:

tools/damon/record.py +1 -0
@@ -113,12 +128,16 @@ def main(args=None):
    args.schemes = ''
    new_attrs = _damon.cmd_args_to_attrs(args)
    init_regions = _damon.cmd_args_to_init_regions(args)
+    numa_node = args.numa_node
    target = args.target
 
Quoted 4 lines

tools/damon/record.py def main(args=None): · line 121

Quoted 4 lines
tools/damon/record.py +0 -1
    target_fields = target.split()
    if target == 'paddr':   # physical memory address space
        if not init_regions:
-            init_regions = [default_paddr_region()]

BTW, until the next spin, you would be able to use the your tweak or directly set the address ranges using '--regions' option.

Thanks,
SeongJae Park

Quoted 11 lines
Quoted 10 lines
tools/damon/record.py +4 -1
+            if numa_node:
+                init_regions = paddr_region_of(numa_node)
+            else:
+                init_regions = [default_paddr_region()]
        do_record(target, False, init_regions, new_attrs, orig_attrs)
    elif not subprocess.call('which %s > /dev/null' % target_fields[0],
            shell=True, executable='/bin/bash'):
--

2.17.1

#14 lore raw

RFC v5 11/11 Docs/damon: Document physical memory monitoring support

In reply to SeongJae Park

From: SeongJae Park <[email protected]>

This commit adds description for the physical memory monitoring usage in the DAMON document.

---
 Documentation/admin-guide/mm/damon/faq.rst    |  7 ++-
 Documentation/admin-guide/mm/damon/index.rst  |  1 -
 .../admin-guide/mm/damon/mechanisms.rst       | 29 +++++-----
 Documentation/admin-guide/mm/damon/plans.rst  |  7 ---
 Documentation/admin-guide/mm/damon/usage.rst  | 53 ++++++++++++++-----
 5 files changed, 60 insertions(+), 37 deletions(-)
 delete mode 100644 Documentation/admin-guide/mm/damon/plans.rst
Documentation/admin-guide/mm/damon/faq.rst +3 -4
index f55d1d719999..ff630cf5fce1 100644
@@ -44,10 +44,9 @@ constructions and actual access checks can be implemented and configured on the
 DAMON core by the users.  In this way, DAMON users can monitor any address
 space with any access check technique.
 
-Nonetheless, DAMON provides a vma tracking and PTE Accessed bit check based
-implementation of the address space dependent functions for the virtual memory
-by default, for a reference and convenient use.  In near future, we will also
-provide that for physical memory address space.
+Nonetheless, DAMON provides vma/rmap tracking and PTE Accessed bit check based
+implementations of the address space dependent functions for the virtual memory
+and the physical memory by default, for a reference and convenient use.
 
 
 Can I simply monitor page granularity?
Documentation/admin-guide/mm/damon/index.rst +0 -1
index c6e657f8e90c..6e36149053fa 100644
@@ -32,4 +32,3 @@ workloads and systems.
    faq
    mechanisms
    eval
-   plans
Documentation/admin-guide/mm/damon/mechanisms.rst +17 -12
index 16066477bb2c..fb33d8d8a09c 100644
@@ -25,9 +25,11 @@ files, and backing devices would be supportable.  Also, if some architectures
 or kernel module support special access check primitives for specific address
 space, those will be easily configurable.
 
-DAMON currently provides an implementation of the primitives for the virtual
-address space.  It uses VMA for the target address range identification and PTE
-Accessed bit for the access check.
+DAMON currently provides an implementation of the primitives for the physical
+and virtual address spaces.  The implementation for the physical address space
+ask users to manually set the monitoring target address ranges while the
+implementation for the virtual address space uses VMA for the target address
+range identification.  Both uses PTE Accessed bit for the access check.
 
 Below four sections describe the address independent core mechanisms and the
 five knobs for tuning, that is, ``sampling interval``, ``aggregation
@@ -113,26 +115,29 @@ memory mapping changes and applies it to the abstracted target area only for
 each of a user-specified time interval (``regions update interval``).
 
 
-Virtual Address Space Specific Low Primitives
-=============================================
+Address Space Specific Low Primitives
+=====================================
 
-This is for the DAMON's reference implementation of the virtual memory address
-specific low level primitive only.
+This is for the DAMON's reference implementation of the address space specific
+low level primitive only.
 
 
 PTE Accessed-bit Based Access Check
 -----------------------------------
 
-The implementation uses PTE Accessed-bit for basic access checks.  That is, it
-clears the bit for next sampling target page and checks whether it set again
-after one sampling period.  To avoid disturbing other Accessed bit users such
-as the reclamation logic, this implementation adjusts the ``PG_Idle`` and
-``PG_Young`` appropriately, as same to the 'Idle Page Tracking'.
+Both of the implementations for physical and virtual address spaces use PTE
+Accessed-bit for basic access checks.  That is, those clears the bit for next
+sampling target page and checks whether it set again after one sampling period.
+To avoid disturbing other Accessed bit users such as the reclamation logic, the
+implementations adjust the ``PG_Idle`` and ``PG_Young`` appropriately, as same
+to the 'Idle Page Tracking'.
 
 
 VMA-based Target Address Range Construction
 -------------------------------------------
 
+This is for the virtual address space specific primitives implementation.
+
 Only small parts in the super-huge virtual address space of the processes are
 mapped to the physical memory and accessed.  Thus, tracking the unmapped
 address regions is just wasteful.  However, because DAMON can deal with some
Documentation/admin-guide/mm/damon/plans.rst deleted +0 -7
deleted file mode 100644
index 765344f02eb3..000000000000
@@ -1,7 +0,0 @@
-.. SPDX-License-Identifier: GPL-2.0
-
-============
-Future Plans
-============
-
-TBD.
Documentation/admin-guide/mm/damon/usage.rst +40 -13

101 lines not on this page · raw message

Signature · 1 line
2.17.1