Skip to contentSkip to conversation

mm: process/cgroup ksm support

PATCH Superseded Stefan Roesch 5 participants 17 messages Feb 24, 2023 – Mar 9, 2023

Subsystems (6)

v3 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#0 lore raw

v3 cover mm: process/cgroup ksm support

So far KSM can only be enabled by calling madvise for memory regions. To be able to use KSM for more workloads, KSM needs to have the ability to be enabled / disabled at the process / cgroup level.

Use case 1:
The madvise call is not available in the programming language. An example for this are programs with forked workloads using a garbage collected language without pointers. In such a language madvise cannot be made available.

In addition the addresses of objects get moved around as they are garbage collected. KSM sharing needs to be enabled "from the outside" for these type of workloads.

Use case 2:
The same interpreter can also be used for workloads where KSM brings no benefit or even has overhead. We'd like to be able to enable KSM on a workload by workload basis.

Use case 3:
With the madvise call sharing opportunities are only enabled for the current
process: it is a workload-local decision. A considerable number of sharing opportuniites may exist across multiple workloads or jobs. Only a higler level entity like a job scheduler or container can know for certain if its running one or more instances of a job. That job scheduler however doesn't have the necessary internal worklaod knowledge to make targeted madvise calls.

Security concerns:
In previous discussions security concerns have been brought up. The problem is that an individual workload does not have the knowledge about what else is running on a machine. Therefore it has to be very conservative in what memory areas can be shared or not. However, if the system is dedicated to running multiple jobs within the same security domain, its the job scheduler that has the knowledge that sharing can be safely enabled and is even desirable.

Performance:
Experiments with using UKSM have shown a capacity increase of around 20%.

1. New options for prctl system command
This patch series adds two new options to the prctl system call. The first one allows to enable KSM at the process level and the second one to query the setting.

The setting will be inherited by child processes.

With the above setting, KSM can be enabled for the seed process of a cgroup and all processes in the cgroup will inherit the setting.

2. Changes to KSM processing
When KSM is enabled at the process level, the KSM code will iterate over all the VMA's and enable KSM for the eligible VMA's.

When forking a process that has KSM enabled, the setting will be inherited by the new child process.

In addition when KSM is disabled for a process, KSM will be disabled for the VMA's where KSM has been enabled.

3. Add general_profit metric
The general_profit metric of KSM is specified in the documentation, but not calculated. This adds the general profit metric to /sys/kernel/debug/mm/ksm.

4. Add more metrics to ksm_stat
This adds the process profit and ksm type metric to /proc/<pid>/ksm_stat.

5. Add more tests to ksm_tests
This adds an option to specify the merge type to the ksm_tests. This allows to test madvise and prctl KSM. It also adds a new option to query if prctl KSM has been enabled. It adds a fork test to verify that the KSM process setting is inherited by client processes.

Changes:
- V3:
- folded patch 1 - 6
- folded patch 7 - 14
- folded patch 15 - 19
- Expanded on the use cases in the cover letter
- Added a section on security concerns to the cover letter

- V2:
- Added use cases to the cover letter
- Removed the tracing patch from the patch series and posted it as an individual patch
- Refreshed repo

Stefan Roesch (3):
mm: add new api to enable ksm per process
mm: add new KSM process and sysfs knobs
selftests/mm: add new selftests for KSM

 Documentation/ABI/testing/sysfs-kernel-mm-ksm |   8 +
 Documentation/admin-guide/mm/ksm.rst          |   8 +-
 fs/proc/base.c                                |   5 +
 include/linux/ksm.h                           |  19 +-
 include/linux/sched/coredump.h                |   1 +
 include/uapi/linux/prctl.h                    |   2 +
 kernel/sys.c                                  |  29 ++
 mm/ksm.c                                      | 114 +++++++-
 tools/include/uapi/linux/prctl.h              |   2 +
 tools/testing/selftests/mm/Makefile           |   3 +-
 tools/testing/selftests/mm/ksm_tests.c        | 254 +++++++++++++++---
 11 files changed, 389 insertions(+), 56 deletions(-)

base-commit: 234a68e24b120b98875a8b6e17a9dead277be16a

Signature · 1 line
2.30.2
#1 lore raw

PATCH v3 1/3 mm: add new api to enable ksm per process

This adds a new prctl to API to enable and disable KSM on a per process basis instead of only at the VMA basis (with madvise).

1) Introduce new MMF_VM_MERGE_ANY flag

This introduces the new flag MMF_VM_MERGE_ANY flag. When this flag is set, kernel samepage merging (ksm) gets enabled for all vma's of a process.

2) add flag to __ksm_enter

This change adds the flag parameter to __ksm_enter. This allows to distinguish if ksm was called by prctl or madvise.

3) add flag to __ksm_exit call

This adds the flag parameter to the __ksm_exit() call. This allows to distinguish if this call is for an prctl or madvise invocation.

4) invoke madvise for all vmas in scan_get_next_rmap_item

If the new flag MMF_VM_MERGE_ANY has been set for a process, iterate over all the vmas and enable ksm if possible. For the vmas that can be ksm enabled this is only done once.

5) support disabling of ksm for a process

This adds the ability to disable ksm for a process if ksm has been enabled for the process.

6) add new prctl option to get and set ksm for a process

This adds two new options to the prctl system call
- enable ksm for all vmas of a process (if the vmas support it).
- query if ksm has been enabled for a process.

---
 include/linux/ksm.h            | 14 ++++---
 include/linux/sched/coredump.h |  1 +
 include/uapi/linux/prctl.h     |  2 +
 kernel/sys.c                   | 29 +++++++++++++++
 mm/ksm.c                       | 67 ++++++++++++++++++++++++++++++----
 5 files changed, 101 insertions(+), 12 deletions(-)
include/linux/ksm.h +9 -5
index 7e232ba59b86..d38a05a36298 100644
@@ -18,20 +18,24 @@
 #ifdef CONFIG_KSM
 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
 		unsigned long end, int advice, unsigned long *vm_flags);
-int __ksm_enter(struct mm_struct *mm);
-void __ksm_exit(struct mm_struct *mm);
+int __ksm_enter(struct mm_struct *mm, int flag);
+void __ksm_exit(struct mm_struct *mm, int flag);
 
 static inline int ksm_fork(struct mm_struct *mm, struct mm_struct *oldmm)
 {
+	if (test_bit(MMF_VM_MERGE_ANY, &oldmm->flags))
+		return __ksm_enter(mm, MMF_VM_MERGE_ANY);
 	if (test_bit(MMF_VM_MERGEABLE, &oldmm->flags))
-		return __ksm_enter(mm);
+		return __ksm_enter(mm, MMF_VM_MERGEABLE);
 	return 0;
 }
 
 static inline void ksm_exit(struct mm_struct *mm)
 {
-	if (test_bit(MMF_VM_MERGEABLE, &mm->flags))
-		__ksm_exit(mm);
+	if (test_bit(MMF_VM_MERGE_ANY, &mm->flags))
+		__ksm_exit(mm, MMF_VM_MERGE_ANY);
+	else if (test_bit(MMF_VM_MERGEABLE, &mm->flags))
+		__ksm_exit(mm, MMF_VM_MERGEABLE);
 }
 
 /*
include/linux/sched/coredump.h +1 -0
index 0e17ae7fbfd3..0ee96ea7a0e9 100644
@@ -90,4 +90,5 @@ static inline int get_dumpable(struct mm_struct *mm)
 #define MMF_INIT_MASK		(MMF_DUMPABLE_MASK | MMF_DUMP_FILTER_MASK |\
 				 MMF_DISABLE_THP_MASK | MMF_HAS_MDWE_MASK)
 
+#define MMF_VM_MERGE_ANY	29
 #endif /* _LINUX_SCHED_COREDUMP_H */
include/uapi/linux/prctl.h +2 -0
index 1312a137f7fb..759b3f53e53f 100644
@@ -290,4 +290,6 @@ struct prctl_mm_map {
 #define PR_SET_VMA		0x53564d41
 # define PR_SET_VMA_ANON_NAME		0
 
+#define PR_SET_MEMORY_MERGE		67
+#define PR_GET_MEMORY_MERGE		68
 #endif /* _LINUX_PRCTL_H */
kernel/sys.c +29 -0
index b3cab94545ed..495bab3ed2ad 100644
@@ -15,6 +15,7 @@
 #include <linux/highuid.h>
 #include <linux/fs.h>
 #include <linux/kmod.h>
+#include <linux/ksm.h>
 #include <linux/perf_event.h>
 #include <linux/resource.h>
 #include <linux/kernel.h>
@@ -2659,6 +2660,34 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 	case PR_SET_VMA:
 		error = prctl_set_vma(arg2, arg3, arg4, arg5);
 		break;
+#ifdef CONFIG_KSM
+	case PR_SET_MEMORY_MERGE:
+		if (!capable(CAP_SYS_RESOURCE))
+			return -EPERM;
+
+		if (arg2) {
+			if (mmap_write_lock_killable(me->mm))
+				return -EINTR;
+
+			if (test_bit(MMF_VM_MERGEABLE, &me->mm->flags))
+				error = -EINVAL;
+			else if (!test_bit(MMF_VM_MERGE_ANY, &me->mm->flags))
+				error = __ksm_enter(me->mm, MMF_VM_MERGE_ANY);
+			mmap_write_unlock(me->mm);
+		} else {
+			__ksm_exit(me->mm, MMF_VM_MERGE_ANY);
+		}
+		break;
+	case PR_GET_MEMORY_MERGE:
+		if (!capable(CAP_SYS_RESOURCE))
+			return -EPERM;
+
+		if (arg2 || arg3 || arg4 || arg5)
+			return -EINVAL;
+
+		error = !!test_bit(MMF_VM_MERGE_ANY, &me->mm->flags);
+		break;
+#endif
 	default:
 		error = -EINVAL;
 		break;
mm/ksm.c +60 -7

127 lines not on this page · raw message

Signature · 1 line
2.30.2
#2 lore raw

Re: [PATCH v3 1/3] mm: add new api to enable ksm per process

Quoted 30 lines · Stefan Roesch

This adds a new prctl to API to enable and disable KSM on a per process basis instead of only at the VMA basis (with madvise).

1) Introduce new MMF_VM_MERGE_ANY flag

This introduces the new flag MMF_VM_MERGE_ANY flag. When this flag is set, kernel samepage merging (ksm) gets enabled for all vma's of a process.

2) add flag to __ksm_enter

This change adds the flag parameter to __ksm_enter. This allows to distinguish if ksm was called by prctl or madvise.

3) add flag to __ksm_exit call

This adds the flag parameter to the __ksm_exit() call. This allows to distinguish if this call is for an prctl or madvise invocation.

4) invoke madvise for all vmas in scan_get_next_rmap_item

If the new flag MMF_VM_MERGE_ANY has been set for a process, iterate over all the vmas and enable ksm if possible. For the vmas that can be ksm enabled this is only done once.

5) support disabling of ksm for a process

This adds the ability to disable ksm for a process if ksm has been enabled for the process.

Quoted 7 lines

6) add new prctl option to get and set ksm for a process

This adds two new options to the prctl system call
- enable ksm for all vmas of a process (if the vmas support it).
- query if ksm has been enabled for a process.

Hey Stefan, thanks for merging the patches into one. I found it much easier to review.

Overall this looks straight-forward to me. A few comments below:

Quoted 5 lines
kernel/sys.c +1 -0
@@ -2659,6 +2660,34 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 	case PR_SET_VMA:
 		error = prctl_set_vma(arg2, arg3, arg4, arg5);
 		break;
+#ifdef CONFIG_KSM

kernel/sys.c SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3, · line 2673

Quoted 10 lines
kernel/sys.c +10 -0
+	case PR_SET_MEMORY_MERGE:
+		if (!capable(CAP_SYS_RESOURCE))
+			return -EPERM;
+
+		if (arg2) {
+			if (mmap_write_lock_killable(me->mm))
+				return -EINTR;
+
+			if (test_bit(MMF_VM_MERGEABLE, &me->mm->flags))
+				error = -EINVAL;

So if the workload has already madvised specific VMAs the process-enablement will fail. Why is that? Shouldn't it be possible to override a local decision from an outside context that has more perspective on both sharing opportunities and security aspects?

If there is a good reason for it, the -EINVAL should be addressed in the manpage. And maybe add a comment here as well.

Quoted 51 lines
kernel/sys.c +17 -0
+			else if (!test_bit(MMF_VM_MERGE_ANY, &me->mm->flags))
+				error = __ksm_enter(me->mm, MMF_VM_MERGE_ANY);
+			mmap_write_unlock(me->mm);
+		} else {
+			__ksm_exit(me->mm, MMF_VM_MERGE_ANY);
+		}
+		break;
+	case PR_GET_MEMORY_MERGE:
+		if (!capable(CAP_SYS_RESOURCE))
+			return -EPERM;
+
+		if (arg2 || arg3 || arg4 || arg5)
+			return -EINVAL;
+
+		error = !!test_bit(MMF_VM_MERGE_ANY, &me->mm->flags);
+		break;
+#endif
 	default:
 		error = -EINVAL;
 		break;
mm/ksm.c +12 -0
index 56808e3bfd19..23d6944f78ad 100644
@@ -1063,6 +1063,7 @@ static int unmerge_and_remove_all_rmap_items(void)
 
 			mm_slot_free(mm_slot_cache, mm_slot);
 			clear_bit(MMF_VM_MERGEABLE, &mm->flags);
+			clear_bit(MMF_VM_MERGE_ANY, &mm->flags);
 			mmdrop(mm);
 		} else
 			spin_unlock(&ksm_mmlist_lock);
@@ -2329,6 +2330,17 @@ static struct ksm_rmap_item *get_next_rmap_item(struct ksm_mm_slot *mm_slot,
 	return rmap_item;
 }
 
+static bool vma_ksm_mergeable(struct vm_area_struct *vma)
+{
+	if (vma->vm_flags & VM_MERGEABLE)
+		return true;
+
+	if (test_bit(MMF_VM_MERGE_ANY, &vma->vm_mm->flags))
+		return true;
+
+	return false;
+}
+
 static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 {
 	struct mm_struct *mm;

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2422

Quoted 7 lines
mm/ksm.c +2 -1
@@ -2405,8 +2417,20 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 		goto no_vmas;
 
 	for_each_vma(vmi, vma) {
-		if (!(vma->vm_flags & VM_MERGEABLE))
+		if (!vma_ksm_mergeable(vma))
 			continue;
+		if (!(vma->vm_flags & VM_MERGEABLE)) {

IMO, the helper obscures the interaction between the vma flag and the per-process flag here. How about:

		if (!(vma->vm_flags & VM_MERGEABLE)) {
			if (!test_bit(MMF_VM_MERGE_ANY, &vma->vm_mm->flags))
				continue;

			/*
			 * With per-process merging enabled, have the MM scan
			 * enroll any existing and new VMAs on the fly.
			 * 
			ksm_madvise();
		}

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2432

Quoted 10 lines
mm/ksm.c +10 -0
+			unsigned long flags = vma->vm_flags;
+
+			/* madvise failed, use next vma */
+			if (ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &flags))
+				continue;
+			/* vma, not supported as being mergeable */
+			if (!(flags & VM_MERGEABLE))
+				continue;
+
+			vm_flags_set(vma, VM_MERGEABLE);

I don't understand the local flags. Can't it pass &vma->vm_flags to ksm_madvise()? It'll set VM_MERGEABLE on success. And you know it wasn't set before because the whole thing is inside the !set branch. The return value doesn't seem super useful, it's only the flag setting that matters:

			ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &vma->vm_flags);
			/* madvise can fail, and will skip special vmas (pfnmaps and such) */
			if (!(vma->vm_flags & VM_MERGEABLE))
				continue;
Quoted 24 lines
mm/ksm.c +8 -1
+		}
 		if (ksm_scan.address < vma->vm_start)
 			ksm_scan.address = vma->vm_start;
 		if (!vma->anon_vma)
@@ -2491,6 +2515,7 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 
 		mm_slot_free(mm_slot_cache, mm_slot);
 		clear_bit(MMF_VM_MERGEABLE, &mm->flags);
+		clear_bit(MMF_VM_MERGE_ANY, &mm->flags);
 		mmap_read_unlock(mm);
 		mmdrop(mm);
 	} else {
@@ -2664,12 +2690,39 @@ int __ksm_enter(struct mm_struct *mm)
 	return 0;
 }
 
-void __ksm_exit(struct mm_struct *mm)
+static void unmerge_vmas(struct mm_struct *mm)
+{
+	struct vm_area_struct *vma;
+	struct vma_iterator vmi;
+
+	vma_iter_init(&vmi, mm, 0);

mm/ksm.c int __ksm_enter(struct mm_struct *mm) · line 2708

Quoted 10 lines
mm/ksm.c +10 -0
+
+	mmap_read_lock(mm);
+	for_each_vma(vmi, vma) {
+		if (vma->vm_flags & VM_MERGEABLE) {
+			unsigned long flags = vma->vm_flags;
+
+			if (ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_UNMERGEABLE, &flags))
+				continue;
+
+			vm_flags_clear(vma, VM_MERGEABLE);

ksm_madvise() tests and clears VM_MERGEABLE, so AFAICS

	for_each_vma(vmi, vma)
		ksm_madvise();

should do it...

Quoted 5 lines
mm/ksm.c +5 -0
+		}
+	}
+	mmap_read_unlock(mm);
+}
+

mm/ksm.c int __ksm_enter(struct mm_struct *mm) · line 2723

Quoted 10 lines
mm/ksm.c +5 -0
+void __ksm_exit(struct mm_struct *mm, int flag)
 {
 	struct ksm_mm_slot *mm_slot;
 	struct mm_slot *slot;
 	int easy_to_free = 0;
 
+	if (!(current->flags & PF_EXITING) && flag == MMF_VM_MERGE_ANY &&
+		test_bit(MMF_VM_MERGE_ANY, &mm->flags)) {
+		clear_bit(MMF_VM_MERGE_ANY, &mm->flags);
+		unmerge_vmas(mm);

...and then it's short enough to just open-code it here and drop the unmerge_vmas() helper.

#3 lore raw

Re: [PATCH v3 1/3] mm: add new api to enable ksm per process

Quoted 65 lines · Johannes Weiner
Quoted 30 lines · Stefan Roesch

This adds a new prctl to API to enable and disable KSM on a per process basis instead of only at the VMA basis (with madvise).

1) Introduce new MMF_VM_MERGE_ANY flag

This introduces the new flag MMF_VM_MERGE_ANY flag. When this flag is set, kernel samepage merging (ksm) gets enabled for all vma's of a process.

2) add flag to __ksm_enter

This change adds the flag parameter to __ksm_enter. This allows to distinguish if ksm was called by prctl or madvise.

3) add flag to __ksm_exit call

This adds the flag parameter to the __ksm_exit() call. This allows to distinguish if this call is for an prctl or madvise invocation.

4) invoke madvise for all vmas in scan_get_next_rmap_item

If the new flag MMF_VM_MERGE_ANY has been set for a process, iterate over all the vmas and enable ksm if possible. For the vmas that can be ksm enabled this is only done once.

5) support disabling of ksm for a process

This adds the ability to disable ksm for a process if ksm has been enabled for the process.

Quoted 7 lines

6) add new prctl option to get and set ksm for a process

This adds two new options to the prctl system call
- enable ksm for all vmas of a process (if the vmas support it).
- query if ksm has been enabled for a process.

Hey Stefan, thanks for merging the patches into one. I found it much easier to review.

Overall this looks straight-forward to me. A few comments below:

Quoted 5 lines
kernel/sys.c +1 -0
@@ -2659,6 +2660,34 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 	case PR_SET_VMA:
 		error = prctl_set_vma(arg2, arg3, arg4, arg5);
 		break;
+#ifdef CONFIG_KSM

kernel/sys.c SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3, · line 2673

Quoted 10 lines
kernel/sys.c +10 -0
+	case PR_SET_MEMORY_MERGE:
+		if (!capable(CAP_SYS_RESOURCE))
+			return -EPERM;
+
+		if (arg2) {
+			if (mmap_write_lock_killable(me->mm))
+				return -EINTR;
+
+			if (test_bit(MMF_VM_MERGEABLE, &me->mm->flags))
+				error = -EINVAL;

So if the workload has already madvised specific VMAs the process-enablement will fail. Why is that? Shouldn't it be possible to override a local decision from an outside context that has more perspective on both sharing opportunities and security aspects?

Quoted 3 lines

If there is a good reason for it, the -EINVAL should be addressed in the manpage. And maybe add a comment here as well.

This makes sense, I'll remove the check above.

Quoted 90 lines
Quoted 51 lines
kernel/sys.c +17 -0
+			else if (!test_bit(MMF_VM_MERGE_ANY, &me->mm->flags))
+				error = __ksm_enter(me->mm, MMF_VM_MERGE_ANY);
+			mmap_write_unlock(me->mm);
+		} else {
+			__ksm_exit(me->mm, MMF_VM_MERGE_ANY);
+		}
+		break;
+	case PR_GET_MEMORY_MERGE:
+		if (!capable(CAP_SYS_RESOURCE))
+			return -EPERM;
+
+		if (arg2 || arg3 || arg4 || arg5)
+			return -EINVAL;
+
+		error = !!test_bit(MMF_VM_MERGE_ANY, &me->mm->flags);
+		break;
+#endif
 	default:
 		error = -EINVAL;
 		break;
mm/ksm.c +12 -0
index 56808e3bfd19..23d6944f78ad 100644
@@ -1063,6 +1063,7 @@ static int unmerge_and_remove_all_rmap_items(void)
 
 			mm_slot_free(mm_slot_cache, mm_slot);
 			clear_bit(MMF_VM_MERGEABLE, &mm->flags);
+			clear_bit(MMF_VM_MERGE_ANY, &mm->flags);
 			mmdrop(mm);
 		} else
 			spin_unlock(&ksm_mmlist_lock);
@@ -2329,6 +2330,17 @@ static struct ksm_rmap_item *get_next_rmap_item(struct ksm_mm_slot *mm_slot,
 	return rmap_item;
 }
 
+static bool vma_ksm_mergeable(struct vm_area_struct *vma)
+{
+	if (vma->vm_flags & VM_MERGEABLE)
+		return true;
+
+	if (test_bit(MMF_VM_MERGE_ANY, &vma->vm_mm->flags))
+		return true;
+
+	return false;
+}
+
 static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 {
 	struct mm_struct *mm;

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2422

Quoted 7 lines
mm/ksm.c +2 -1
@@ -2405,8 +2417,20 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 		goto no_vmas;
 
 	for_each_vma(vmi, vma) {
-		if (!(vma->vm_flags & VM_MERGEABLE))
+		if (!vma_ksm_mergeable(vma))
 			continue;
+		if (!(vma->vm_flags & VM_MERGEABLE)) {

IMO, the helper obscures the interaction between the vma flag and the per-process flag here. How about:

		if (!(vma->vm_flags & VM_MERGEABLE)) {
			if (!test_bit(MMF_VM_MERGE_ANY, &vma->vm_mm->flags))
				continue;

			/*
			 * With per-process merging enabled, have the MM scan
			 * enroll any existing and new VMAs on the fly.
			 *
			ksm_madvise();
		}

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2432

Quoted 10 lines
mm/ksm.c +10 -0
+			unsigned long flags = vma->vm_flags;
+
+			/* madvise failed, use next vma */
+			if (ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &flags))
+				continue;
+			/* vma, not supported as being mergeable */
+			if (!(flags & VM_MERGEABLE))
+				continue;
+
+			vm_flags_set(vma, VM_MERGEABLE);

I don't understand the local flags. Can't it pass &vma->vm_flags to ksm_madvise()? It'll set VM_MERGEABLE on success. And you know it wasn't set before because the whole thing is inside the !set branch. The return value doesn't seem super useful, it's only the flag setting that matters:

Quoted 5 lines
			ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &vma->vm_flags);
			/* madvise can fail, and will skip special vmas (pfnmaps and such) */
			if (!(vma->vm_flags & VM_MERGEABLE))
				continue;

vm_flags is defined as const. I cannot pass it directly inside the function, this is the reason, I'm using a local variable for it.

Quoted 37 lines
Quoted 24 lines
mm/ksm.c +8 -1
+		}
 		if (ksm_scan.address < vma->vm_start)
 			ksm_scan.address = vma->vm_start;
 		if (!vma->anon_vma)
@@ -2491,6 +2515,7 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 
 		mm_slot_free(mm_slot_cache, mm_slot);
 		clear_bit(MMF_VM_MERGEABLE, &mm->flags);
+		clear_bit(MMF_VM_MERGE_ANY, &mm->flags);
 		mmap_read_unlock(mm);
 		mmdrop(mm);
 	} else {
@@ -2664,12 +2690,39 @@ int __ksm_enter(struct mm_struct *mm)
 	return 0;
 }
 
-void __ksm_exit(struct mm_struct *mm)
+static void unmerge_vmas(struct mm_struct *mm)
+{
+	struct vm_area_struct *vma;
+	struct vma_iterator vmi;
+
+	vma_iter_init(&vmi, mm, 0);

mm/ksm.c int __ksm_enter(struct mm_struct *mm) · line 2708

Quoted 10 lines
mm/ksm.c +10 -0
+
+	mmap_read_lock(mm);
+	for_each_vma(vmi, vma) {
+		if (vma->vm_flags & VM_MERGEABLE) {
+			unsigned long flags = vma->vm_flags;
+
+			if (ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_UNMERGEABLE, &flags))
+				continue;
+
+			vm_flags_clear(vma, VM_MERGEABLE);

ksm_madvise() tests and clears VM_MERGEABLE, so AFAICS

Quoted 5 lines
	for_each_vma(vmi, vma)
		ksm_madvise();

should do it...

This is the same problem. vma->vm_flags is defined as const.

+ if (vma->vm_flags & VM_MERGEABLE) {
This will be removed.

Quoted 18 lines
Quoted 5 lines
mm/ksm.c +5 -0
+		}
+	}
+	mmap_read_unlock(mm);
+}
+

mm/ksm.c int __ksm_enter(struct mm_struct *mm) · line 2723

Quoted 10 lines
mm/ksm.c +5 -0
+void __ksm_exit(struct mm_struct *mm, int flag)
 {
 	struct ksm_mm_slot *mm_slot;
 	struct mm_slot *slot;
 	int easy_to_free = 0;
 
+	if (!(current->flags & PF_EXITING) && flag == MMF_VM_MERGE_ANY &&
+		test_bit(MMF_VM_MERGE_ANY, &mm->flags)) {
+		clear_bit(MMF_VM_MERGE_ANY, &mm->flags);
+		unmerge_vmas(mm);

...and then it's short enough to just open-code it here and drop the unmerge_vmas() helper.

#4 lore raw

Re: [PATCH v3 1/3] mm: add new api to enable ksm per process

Quoted 42 lines · Stefan Roesch
Quoted 41 lines · Johannes Weiner

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2422

Quoted 8 lines · Stefan Roesch
mm/ksm.c +2 -1
@@ -2405,8 +2417,20 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 		goto no_vmas;
 
 	for_each_vma(vmi, vma) {
-		if (!(vma->vm_flags & VM_MERGEABLE))
+		if (!vma_ksm_mergeable(vma))
 			continue;
+		if (!(vma->vm_flags & VM_MERGEABLE)) {

IMO, the helper obscures the interaction between the vma flag and the per-process flag here. How about:

		if (!(vma->vm_flags & VM_MERGEABLE)) {
			if (!test_bit(MMF_VM_MERGE_ANY, &vma->vm_mm->flags))
				continue;

			/*
			 * With per-process merging enabled, have the MM scan
			 * enroll any existing and new VMAs on the fly.
			 *
			ksm_madvise();
		}

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2432

Quoted 10 lines
mm/ksm.c +10 -0
+			unsigned long flags = vma->vm_flags;
+
+			/* madvise failed, use next vma */
+			if (ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &flags))
+				continue;
+			/* vma, not supported as being mergeable */
+			if (!(flags & VM_MERGEABLE))
+				continue;
+
+			vm_flags_set(vma, VM_MERGEABLE);

I don't understand the local flags. Can't it pass &vma->vm_flags to ksm_madvise()? It'll set VM_MERGEABLE on success. And you know it wasn't set before because the whole thing is inside the !set branch. The return value doesn't seem super useful, it's only the flag setting that matters:

Quoted 8 lines
Quoted 5 lines
			ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &vma->vm_flags);
			/* madvise can fail, and will skip special vmas (pfnmaps and such) */
			if (!(vma->vm_flags & VM_MERGEABLE))
				continue;

vm_flags is defined as const. I cannot pass it directly inside the function, this is the reason, I'm using a local variable for it.

Oops, good catch.

However, while looking at the flag helpers, I'm also realizing that modifications requires the mmap_sem in write mode, which this code doesn't. This function might potentially scan the entire process address space, so you can't just change the lock mode, either.

Staring more at this, do you actually need to set VM_MERGEABLE on the individual vmas? There are only a few places that check VM_MERGEABLE, and AFAICS they can all just check for MMF_VM_MERGE_ANY also.

You'd need to factor out the vma compatibility checks from ksm_madvise(), and skip over special vmas during the mm scan. But those tests are all stable under the read lock, so that's fine.

The other thing ksm_madvise() does is ksm_enter() - but that's obviously not needed from inside the loop over ksm_enter'd mms. :)

#5 lore raw

Re: [PATCH v3 1/3] mm: add new api to enable ksm per process

Quoted 63 lines · Johannes Weiner
Quoted 42 lines · Stefan Roesch
Quoted 41 lines · Johannes Weiner

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2422

Quoted 8 lines · Stefan Roesch
mm/ksm.c +2 -1
@@ -2405,8 +2417,20 @@ static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
 		goto no_vmas;
 
 	for_each_vma(vmi, vma) {
-		if (!(vma->vm_flags & VM_MERGEABLE))
+		if (!vma_ksm_mergeable(vma))
 			continue;
+		if (!(vma->vm_flags & VM_MERGEABLE)) {

IMO, the helper obscures the interaction between the vma flag and the per-process flag here. How about:

		if (!(vma->vm_flags & VM_MERGEABLE)) {
			if (!test_bit(MMF_VM_MERGE_ANY, &vma->vm_mm->flags))
				continue;

			/*
			 * With per-process merging enabled, have the MM scan
			 * enroll any existing and new VMAs on the fly.
			 *
			ksm_madvise();
		}

mm/ksm.c static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page) · line 2432

Quoted 10 lines
mm/ksm.c +10 -0
+			unsigned long flags = vma->vm_flags;
+
+			/* madvise failed, use next vma */
+			if (ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &flags))
+				continue;
+			/* vma, not supported as being mergeable */
+			if (!(flags & VM_MERGEABLE))
+				continue;
+
+			vm_flags_set(vma, VM_MERGEABLE);

I don't understand the local flags. Can't it pass &vma->vm_flags to ksm_madvise()? It'll set VM_MERGEABLE on success. And you know it wasn't set before because the whole thing is inside the !set branch. The return value doesn't seem super useful, it's only the flag setting that matters:

Quoted 8 lines
Quoted 5 lines
			ksm_madvise(vma, vma->vm_start, vma->vm_end, MADV_MERGEABLE, &vma->vm_flags);
			/* madvise can fail, and will skip special vmas (pfnmaps and such) */
			if (!(vma->vm_flags & VM_MERGEABLE))
				continue;

vm_flags is defined as const. I cannot pass it directly inside the function, this is the reason, I'm using a local variable for it.

Oops, good catch.

However, while looking at the flag helpers, I'm also realizing that modifications requires the mmap_sem in write mode, which this code doesn't. This function might potentially scan the entire process address space, so you can't just change the lock mode, either.

Staring more at this, do you actually need to set VM_MERGEABLE on the individual vmas? There are only a few places that check VM_MERGEABLE, and AFAICS they can all just check for MMF_VM_MERGE_ANY also.

Quoted 6 lines

You'd need to factor out the vma compatibility checks from ksm_madvise(), and skip over special vmas during the mm scan. But those tests are all stable under the read lock, so that's fine.

The other thing ksm_madvise() does is ksm_enter() - but that's obviously not needed from inside the loop over ksm_enter'd mms. :)

The check alone for MMF_VM_MERGE_ANY is not sufficient. We also need to check if the respective VMA is mergeable. I'll split off the checks in ksm_madvise to its own function, so it can be called from where VM_MERGEABLE is currently checked.

With the above change, the function unmerge_vmas is no longer needed.

#6 lore raw

PATCH v3 2/3 mm: add new KSM process and sysfs knobs

In reply to Stefan Roesch

This adds the general_profit KSM sysfs knob and the process profit metric and process merge type knobs to ksm_stat.

1) split off pages_volatile function

This splits off the pages_volatile function. The next patch will use this function.

2) expose general_profit metric

The documentation mentions a general profit metric, however this metric is not calculated. In addition the formula depends on the size of internal structures, which makes it more difficult for an administrator to make the calculation. Adding the metric for a better user experience.

3) document general_profit sysfs knob

4) calculate ksm process profit metric

The ksm documentation mentions the process profit metric and how to calculate it. This adds the calculation of the metric.

5) add ksm_merge_type() function

This adds the ksm_merge_type function. The function returns the merge type for the process. For madvise it returns "madvise", for prctl it returns "process" and otherwise it returns "none".

6) mm: expose ksm process profit metric and merge type in ksm_stat

This exposes the ksm process profit metric in /proc/<pid>/ksm_stat. The documentation mentions the formula for the ksm process profit metric, however it does not calculate it. In addition the formula depends on the size of internal structures. So it makes sense to expose it.

This exposes the ksm process type in /proc/<pid>/ksm_stat. The name of the value is ksm_merge_type.

7) document new procfs ksm knobs

---
 Documentation/ABI/testing/sysfs-kernel-mm-ksm |  8 ++++
 Documentation/admin-guide/mm/ksm.rst          |  8 +++-
 fs/proc/base.c                                |  5 ++
 include/linux/ksm.h                           |  5 ++
 mm/ksm.c                                      | 47 +++++++++++++++++--
 5 files changed, 69 insertions(+), 4 deletions(-)
Documentation/ABI/testing/sysfs-kernel-mm-ksm +8 -0
index d244674a9480..7768e90f7a8f 100644
@@ -51,3 +51,11 @@ Description:	Control merging pages across different NUMA nodes.
 
 		When it is set to 0 only pages from the same node are merged,
 		otherwise pages from all nodes can be merged together (default).
+
+What:		/sys/kernel/mm/ksm/general_profit
+Date:		January 2023
+KernelVersion:  6.1
+Contact:	Linux memory management mailing list <[email protected]>
+Description:	Measure how effective KSM is.
+		general_profit: how effective is KSM. The formula for the
+		calculation is in Documentation/admin-guide/mm/ksm.rst.
Documentation/admin-guide/mm/ksm.rst +7 -1
index f160f9487a90..34f1d0396eee 100644
@@ -159,6 +159,8 @@ stable_node_chains_prune_millisecs
 
 The effectiveness of KSM and MADV_MERGEABLE is shown in ``/sys/kernel/mm/ksm/``:
 
+general_profit
+        how effective is KSM. The calculation is explained below.
 pages_shared
         how many shared pages are being used
 pages_sharing
@@ -216,7 +218,8 @@ several times, which are unprofitable memory consumed.
 			  ksm_rmap_items * sizeof(rmap_item).
 
    where ksm_merging_pages is shown under the directory ``/proc/<pid>/``,
-   and ksm_rmap_items is shown in ``/proc/<pid>/ksm_stat``.
+   and ksm_rmap_items is shown in ``/proc/<pid>/ksm_stat``. The process profit
+   is also shown in ``/proc/<pid>/ksm_stat`` as ksm_process_profit.
 
 From the perspective of application, a high ratio of ``ksm_rmap_items`` to
 ``ksm_merging_pages`` means a bad madvise-applied policy, so developers or
@@ -227,6 +230,9 @@ so if the ``ksm_rmap_items/ksm_merging_pages`` ratio exceeds 64 on 64-bit CPU
 or exceeds 128 on 32-bit CPU, then the app's madvise policy should be dropped,
 because the ksm profit is approximately zero or negative.
 
+The ksm_merge_type in ``/proc/<pid>/ksm_stat`` shows the merge type of the
+process. Valid values are ``none``, ``madvise`` and ``process``.
+
 Monitoring KSM events
 =====================
 
fs/proc/base.c +5 -0
index ac9ebe972be0..45749051e53b 100644
@@ -96,6 +96,7 @@
 #include <linux/time_namespace.h>
 #include <linux/resctrl.h>
 #include <linux/cn_proc.h>
+#include <linux/ksm.h>
 #include <trace/events/oom.h>
 #include "internal.h"
 #include "fd.h"
@@ -3199,6 +3200,7 @@ static int proc_pid_ksm_merging_pages(struct seq_file *m, struct pid_namespace *
 
 	return 0;
 }
+
 static int proc_pid_ksm_stat(struct seq_file *m, struct pid_namespace *ns,
 				struct pid *pid, struct task_struct *task)
 {
@@ -3208,6 +3210,9 @@ static int proc_pid_ksm_stat(struct seq_file *m, struct pid_namespace *ns,
 	if (mm) {
 		seq_printf(m, "ksm_rmap_items %lu\n", mm->ksm_rmap_items);
 		seq_printf(m, "zero_pages_sharing %lu\n", mm->ksm_zero_pages_sharing);
+		seq_printf(m, "ksm_merging_pages %lu\n", mm->ksm_merging_pages);
+		seq_printf(m, "ksm_merge_type %s\n", ksm_merge_type(mm));
+		seq_printf(m, "ksm_process_profit %ld\n", ksm_process_profit(mm));
 		mmput(mm);
 	}
 
include/linux/ksm.h +5 -0
index d38a05a36298..d5f69f18ee5a 100644
@@ -55,6 +55,11 @@ struct page *ksm_might_need_to_copy(struct page *page,
 void rmap_walk_ksm(struct folio *folio, struct rmap_walk_control *rwc);
 void folio_migrate_ksm(struct folio *newfolio, struct folio *folio);
 
+#ifdef CONFIG_PROC_FS
+long ksm_process_profit(struct mm_struct *);
+const char *ksm_merge_type(struct mm_struct *mm);
+#endif /* CONFIG_PROC_FS */
+
 #else  /* !CONFIG_KSM */
 
 static inline int ksm_fork(struct mm_struct *mm, struct mm_struct *oldmm)
mm/ksm.c +44 -3

77 lines not on this page · raw message

Signature · 1 line
2.30.2
#7 lore raw

PATCH v3 3/3 selftests/mm: add new selftests for KSM

In reply to Stefan Roesch

This adds three new tests to the selftests for KSM. These tests use the new prctl API's to enable and disable KSM.

1) add new prctl flags to prctl header file in tools dir

This adds the new prctl flags to the include file prct.h in the tools directory. This makes sure they are available for testing.

2) add KSM prctl merge test

This adds the -t option to the ksm_tests program. The -t flag allows to specify if it should use madvise or prctl ksm merging.

3) add KSM get merge type test

This adds the -G flag to the ksm_tests program to query the KSM status with prctl after KSM has been enabled with prctl.

4) add KSM fork test

Add fork test to verify that the MMF_VM_MERGE_ANY flag is inherited by the child process.

5) add two functions for debugging merge outcome

This adds two functions to report the metrics in /proc/self/ksm_stat and /sys/kernel/debug/mm/ksm.

The debugging can be enabled with the following command line:
make -C tools/testing/selftests TARGETS="vm" --keep-going \
EXTRA_CFLAGS=-DDEBUG=1

---
 tools/include/uapi/linux/prctl.h       |   2 +
 tools/testing/selftests/mm/Makefile    |   3 +-
 tools/testing/selftests/mm/ksm_tests.c | 254 +++++++++++++++++++++----
 3 files changed, 219 insertions(+), 40 deletions(-)
tools/include/uapi/linux/prctl.h +2 -0
index a5e06dcbba13..e4c629c1f1b0 100644
@@ -284,4 +284,6 @@ struct prctl_mm_map {
 #define PR_SET_VMA		0x53564d41
 # define PR_SET_VMA_ANON_NAME		0
 
+#define PR_SET_MEMORY_MERGE		67
+#define PR_GET_MEMORY_MERGE		68
 #endif /* _LINUX_PRCTL_H */
tools/testing/selftests/mm/Makefile +2 -1
index d90cdc06aa59..507cb22bdebd 100644
@@ -29,7 +29,8 @@ MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p
 # LDLIBS.
 MAKEFLAGS += --no-builtin-rules
 
-CFLAGS = -Wall -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
+CFLAGS = -Wall -I $(top_srcdir)/tools/include/uapi
+CFLAGS += -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
 LDLIBS = -lrt -lpthread
 TEST_GEN_FILES = cow
 TEST_GEN_FILES += compaction_test
tools/testing/selftests/mm/ksm_tests.c +215 -39

466 lines not on this page · raw message

Signature · 1 line
2.30.2
maintainer
#8 lore raw

Re: [PATCH v3 3/3] selftests/mm: add new selftests for KSM

Quoted 10 lines · On Thu, 23 Feb 2023 20:40:00 -0800 Stefan Roesch <[email protected]> wrote:

This adds three new tests to the selftests for KSM. These tests use the new prctl API's to enable and disable KSM.

...

tools/testing/selftests/mm/Makefile +0 -0
index d90cdc06aa59..507cb22bdebd 100644

tools/testing/selftests/mm/Makefile MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p · line 36

Quoted 9 lines
tools/testing/selftests/mm/Makefile +2 -1
@@ -29,7 +29,8 @@ MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p
 # LDLIBS.
 MAKEFLAGS += --no-builtin-rules
 
-CFLAGS = -Wall -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
+CFLAGS = -Wall -I $(top_srcdir)/tools/include/uapi
+CFLAGS += -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
 LDLIBS = -lrt -lpthread
 TEST_GEN_FILES = cow
 TEST_GEN_FILES += compaction_test

This change runs afoul of the recently merged 8eb3751c73bec ("selftests: vm: Fix incorrect kernel headers search path").

I did this:

tools/testing/selftests/mm/Makefile renamed from tools/testing/selftests/mm/Makefile~selftests-mm-add-new-selftests-for-ksm +1 -1
@@ -29,7 +29,7 @@ MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p
 # LDLIBS.
 MAKEFLAGS += --no-builtin-rules
 
-CFLAGS = -Wall -I $(top_srcdir) $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
+CFLAGS = -Wall -I $(top_srcdir) -I $(top_srcdir)/tools/include/uapi $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
 LDLIBS = -lrt -lpthread
 TEST_GEN_FILES = cow
 TEST_GEN_FILES += compaction_test

_

But I expect it's a bit wrong. Please check?

#9 lore raw

Re: [PATCH v3 3/3] selftests/mm: add new selftests for KSM

Quoted 40 lines · Andrew Morton
Quoted 10 lines · On Thu, 23 Feb 2023 20:40:00 -0800 Stefan Roesch <[email protected]> wrote:

This adds three new tests to the selftests for KSM. These tests use the new prctl API's to enable and disable KSM.

...

tools/testing/selftests/mm/Makefile +0 -0
index d90cdc06aa59..507cb22bdebd 100644

tools/testing/selftests/mm/Makefile MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p · line 36

Quoted 9 lines
tools/testing/selftests/mm/Makefile +2 -1
@@ -29,7 +29,8 @@ MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p
 # LDLIBS.
 MAKEFLAGS += --no-builtin-rules
 
-CFLAGS = -Wall -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
+CFLAGS = -Wall -I $(top_srcdir)/tools/include/uapi
+CFLAGS += -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
 LDLIBS = -lrt -lpthread
 TEST_GEN_FILES = cow
 TEST_GEN_FILES += compaction_test

This change runs afoul of the recently merged 8eb3751c73bec ("selftests: vm: Fix incorrect kernel headers search path").

I did this:

tools/testing/selftests/mm/Makefile renamed from tools/testing/selftests/mm/Makefile~selftests-mm-add-new-selftests-for-ksm +1 -1
@@ -29,7 +29,7 @@ MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p
 # LDLIBS.
 MAKEFLAGS += --no-builtin-rules
 
-CFLAGS = -Wall -I $(top_srcdir) $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
+CFLAGS = -Wall -I $(top_srcdir) -I $(top_srcdir)/tools/include/uapi $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
 LDLIBS = -lrt -lpthread
 TEST_GEN_FILES = cow
 TEST_GEN_FILES += compaction_test

_

Quoted 1 line

But I expect it's a bit wrong. Please check?

This change looks good.

#10 lore raw

Re: [PATCH v3 3/3] selftests/mm: add new selftests for KSM

Quoted 43 lines · Stefan Roesch
Quoted 40 lines · Andrew Morton
Quoted 10 lines · On Thu, 23 Feb 2023 20:40:00 -0800 Stefan Roesch <[email protected]> wrote:

This adds three new tests to the selftests for KSM. These tests use the new prctl API's to enable and disable KSM.

...

tools/testing/selftests/mm/Makefile +0 -0
index d90cdc06aa59..507cb22bdebd 100644

tools/testing/selftests/mm/Makefile MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p · line 36

Quoted 9 lines
tools/testing/selftests/mm/Makefile +2 -1
@@ -29,7 +29,8 @@ MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p
  # LDLIBS.
  MAKEFLAGS += --no-builtin-rules
 
-CFLAGS = -Wall -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
+CFLAGS = -Wall -I $(top_srcdir)/tools/include/uapi
+CFLAGS += -I $(top_srcdir) -I $(top_srcdir)/usr/include $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
  LDLIBS = -lrt -lpthread
  TEST_GEN_FILES = cow
  TEST_GEN_FILES += compaction_test

This change runs afoul of the recently merged 8eb3751c73bec ("selftests: vm: Fix incorrect kernel headers search path").

I did this:

tools/testing/selftests/mm/Makefile renamed from tools/testing/selftests/mm/Makefile~selftests-mm-add-new-selftests-for-ksm +1 -1
@@ -29,7 +29,7 @@ MACHINE ?= $(shell echo $(uname_M) | sed -e 's/aarch64.*/arm64/' -e 's/ppc64.*/p
  # LDLIBS.
  MAKEFLAGS += --no-builtin-rules
 
-CFLAGS = -Wall -I $(top_srcdir) $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
+CFLAGS = -Wall -I $(top_srcdir) -I $(top_srcdir)/tools/include/uapi $(EXTRA_CFLAGS) $(KHDR_INCLUDES)
  LDLIBS = -lrt -lpthread
  TEST_GEN_FILES = cow
  TEST_GEN_FILES += compaction_test

_

Quoted 2 lines
Quoted 1 line

But I expect it's a bit wrong. Please check?

This change looks good.

As the content of tools/include/uapi is indeed part of the kernel sources and not generated as the result of 'make headers' in an output directory which can be overridden by O=<...>, referring to it from $(top_srcdir) seems appropriate.

lgtm

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer
#11 lore raw
In reply to Stefan Roesch
Quoted 3 lines · On Thu, 23 Feb 2023 20:39:57 -0800 Stefan Roesch <[email protected]> wrote:

So far KSM can only be enabled by calling madvise for memory regions. To be able to use KSM for more workloads, KSM needs to have the ability to be enabled / disabled at the process / cgroup level.

I'll toss this in for integration and testing, but I'd like to see reviewer input before proceeding further.

Please plan on adding suitable user-facing documentation? Presumably a patch for the prctl manpage?

#12 lore raw
Quoted 11 lines · Andrew Morton
Quoted 3 lines · On Thu, 23 Feb 2023 20:39:57 -0800 Stefan Roesch <[email protected]> wrote:

So far KSM can only be enabled by calling madvise for memory regions. To be able to use KSM for more workloads, KSM needs to have the ability to be enabled / disabled at the process / cgroup level.

I'll toss this in for integration and testing, but I'd like to see reviewer input before proceeding further.

Please plan on adding suitable user-facing documentation? Presumably a patch for the prctl manpage?

I'll work on a patch for the prctl manpage.

#13 lore raw
In reply to Andrew Morton
Quoted 11 lines · Andrew Morton
Quoted 3 lines · On Thu, 23 Feb 2023 20:39:57 -0800 Stefan Roesch <[email protected]> wrote:

So far KSM can only be enabled by calling madvise for memory regions. To be able to use KSM for more workloads, KSM needs to have the ability to be enabled / disabled at the process / cgroup level.

I'll toss this in for integration and testing, but I'd like to see reviewer input before proceeding further.

Please plan on adding suitable user-facing documentation? Presumably a patch for the prctl manpage?

The doc patch has been posted:
https://lore.kernel.org/linux-man/[email protected]/

#14 lore raw
In reply to Stefan Roesch

For some reason gmail thought it would be a good ideas to move this into the SPAM folder, so I only saw the recent replies just now.

I'm going to have a look at this soonish.

One point that popped up in the past and that I raised on the last RFC: we should think about letting processes *opt out/disable* KSM on their own. Either completely, or for selected VMAs.

Reasoning is, that if you have an application that really doesn't want some memory regions to be applicable to KSM (memory de-duplication attacks? Knowing that KSM on some regions will be counter-productive)

For example, remembering if MADV_UNMERGEABLE was called and not only clearing the VMA flag. So even if KSM would be force-enabled by some tooling after the process started, such regions would not get considered for KSM.

It would a bit like how we handle THP.

Quoted 26 lines · Stefan Roesch

So far KSM can only be enabled by calling madvise for memory regions. To be able to use KSM for more workloads, KSM needs to have the ability to be enabled / disabled at the process / cgroup level.

Use case 1:
The madvise call is not available in the programming language. An example for this are programs with forked workloads using a garbage collected language without pointers. In such a language madvise cannot be made available.

In addition the addresses of objects get moved around as they are garbage collected. KSM sharing needs to be enabled "from the outside" for these type of workloads.

Use case 2:
The same interpreter can also be used for workloads where KSM brings no benefit or even has overhead. We'd like to be able to enable KSM on a workload by workload basis.

Use case 3:
With the madvise call sharing opportunities are only enabled for the current
process: it is a workload-local decision. A considerable number of sharing opportuniites may exist across multiple workloads or jobs. Only a higler level entity like a job scheduler or container can know for certain if its running one or more instances of a job. That job scheduler however doesn't have the necessary internal worklaod knowledge to make targeted madvise calls.

Quoted 7 lines

Security concerns:
In previous discussions security concerns have been brought up. The problem is that an individual workload does not have the knowledge about what else is running on a machine. Therefore it has to be very conservative in what memory areas can be shared or not. However, if the system is dedicated to running multiple jobs within the same security domain, its the job scheduler that has the knowledge that sharing can be safely enabled and is even desirable.

Note that there are some papers about why limiting memory deduplciation attacks to single security domains is not sufficient. Especially, the remote deduplication attacks fall into that category IIRC.

Signature · 3 lines
Thanks,

David / dhildenb
#15 lore raw

Hey David,

Quoted 4 lines · David Hildenbrand

For some reason gmail thought it would be a good ideas to move this into the SPAM folder, so I only saw the recent replies just now.

I'm going to have a look at this soonish.

Thanks! More eyes are always helpful.

Quoted 8 lines

One point that popped up in the past and that I raised on the last RFC: we should think about letting processes *opt out/disable* KSM on their own. Either completely, or for selected VMAs.

Reasoning is, that if you have an application that really doesn't want some memory regions to be applicable to KSM (memory de-duplication attacks? Knowing that KSM on some regions will be counter-productive)

Quoted 5 lines

For example, remembering if MADV_UNMERGEABLE was called and not only clearing the VMA flag. So even if KSM would be force-enabled by some tooling after the process started, such regions would not get considered for KSM.

It would a bit like how we handle THP.

I'm not sure the THP comparison is apt. THP is truly a local optimization that depends on the workload's access patterns. The environment isn't a true factor. It makes some sense that if there is a global policy to generally use THP the workload be able to opt out based on known sparse access patterns. At least until THP allocation strategy inside the kernel becomes smarter!

Merging opportunities and security questions are trickier. The application might know which data is sensitive, but it doesn't know whether its environment is safe or subject do memory attacks, so it cannot make that decision purely from inside.

There is a conceivable usecase where multiple instances of the same job are running inside a safe shared security domain and using the same sensitive data.

There is a conceivable usecase where the system and the workload collaborate to merge insensitive data across security domains.

I'm honestly not sure which usecase is more likely. My gut feeling is the first one, simply because of broader concerns of multiple security domains sharing kernel instances or physical hardware.

Quoted 35 lines · Stefan Roesch
Quoted 26 lines

So far KSM can only be enabled by calling madvise for memory regions. To be able to use KSM for more workloads, KSM needs to have the ability to be enabled / disabled at the process / cgroup level.

Use case 1:
The madvise call is not available in the programming language. An example for this are programs with forked workloads using a garbage collected language without pointers. In such a language madvise cannot be made available.

In addition the addresses of objects get moved around as they are garbage collected. KSM sharing needs to be enabled "from the outside" for these type of workloads.

Use case 2:
The same interpreter can also be used for workloads where KSM brings no benefit or even has overhead. We'd like to be able to enable KSM on a workload by workload basis.

Use case 3:
With the madvise call sharing opportunities are only enabled for the current
process: it is a workload-local decision. A considerable number of sharing opportuniites may exist across multiple workloads or jobs. Only a higler level entity like a job scheduler or container can know for certain if its running one or more instances of a job. That job scheduler however doesn't have the necessary internal worklaod knowledge to make targeted madvise calls.

Quoted 7 lines

Security concerns:
In previous discussions security concerns have been brought up. The problem is that an individual workload does not have the knowledge about what else is running on a machine. Therefore it has to be very conservative in what memory areas can be shared or not. However, if the system is dedicated to running multiple jobs within the same security domain, its the job scheduler that has the knowledge that sharing can be safely enabled and is even desirable.

Quoted 3 lines

Note that there are some papers about why limiting memory deduplciation attacks to single security domains is not sufficient. Especially, the remote deduplication attacks fall into that category IIRC.

I think it would be good to elaborate on that and include any caveats in the documentation.

Ultimately, the bar isn't whether there are attack vectors on a subset of possible usecases, but whether there are usecases where this can be used safely, which is obviously true.

#16 lore raw
Quoted 13 lines
Quoted 13 lines

One point that popped up in the past and that I raised on the last RFC: we should think about letting processes *opt out/disable* KSM on their own. Either completely, or for selected VMAs.

Reasoning is, that if you have an application that really doesn't want some memory regions to be applicable to KSM (memory de-duplication attacks? Knowing that KSM on some regions will be counter-productive)

For example, remembering if MADV_UNMERGEABLE was called and not only clearing the VMA flag. So even if KSM would be force-enabled by some tooling after the process started, such regions would not get considered for KSM.

Quoted 8 lines
Quoted 1 line

It would a bit like how we handle THP.

I'm not sure the THP comparison is apt. THP is truly a local optimization that depends on the workload's access patterns. The environment isn't a true factor. It makes some sense that if there is a global policy to generally use THP the workload be able to opt out based on known sparse access patterns. At least until THP allocation strategy inside the kernel becomes smarter!

Yes, and some features really don't want THP, at least for some period of time (e.g., userfaultfd), because they are to some degree incompatible with the idea of THP populating more memory than was accessed.

Page pinning + KSM was one of the remaining cases where force-enabling KSM could have made a real difference (IOW buggy) that we discussed the last time this was proposed. That should be fixed now. I guess besides that, most features should be compatible with KSM nowadays. So force-enabling it should not result in actual issues I guess.

Quoted 5 lines

Merging opportunities and security questions are trickier. The application might know which data is sensitive, but it doesn't know whether its environment is safe or subject do memory attacks, so it cannot make that decision purely from inside.

I agree regarding security. Regarding merging opportunities, I am not so sure. There are certainly examples where an application knows best that memory deduplication is mostly a lost bet (if a lot of randomization or pointers are involved most probably).

Quoted 4 lines

There is a conceivable usecase where multiple instances of the same job are running inside a safe shared security domain and using the same sensitive data.

Yes. IMHO, such special applications could just enable KSM manually, though, instead of enabling it for each and every last piece of anonymous memory that doesn't make sense to get deduplciated :)

But of course, I see the simplicity in just enabling it globally.

Quoted 8 lines

There is a conceivable usecase where the system and the workload collaborate to merge insensitive data across security domains.

I'm honestly not sure which usecase is more likely. My gut feeling is the first one, simply because of broader concerns of multiple security domains sharing kernel instances or physical hardware.

See my side note below.

Quoted 35 lines
Quoted 35 lines · Stefan Roesch
Quoted 33 lines

So far KSM can only be enabled by calling madvise for memory regions. To be able to use KSM for more workloads, KSM needs to have the ability to be enabled / disabled at the process / cgroup level.

Use case 1:
The madvise call is not available in the programming language. An example for this are programs with forked workloads using a garbage collected language without pointers. In such a language madvise cannot be made available.

In addition the addresses of objects get moved around as they are garbage collected. KSM sharing needs to be enabled "from the outside" for these type of workloads.

Use case 2:
The same interpreter can also be used for workloads where KSM brings no benefit or even has overhead. We'd like to be able to enable KSM on a workload by workload basis.

Use case 3:
With the madvise call sharing opportunities are only enabled for the current
process: it is a workload-local decision. A considerable number of sharing opportuniites may exist across multiple workloads or jobs. Only a higler level entity like a job scheduler or container can know for certain if its running one or more instances of a job. That job scheduler however doesn't have the necessary internal worklaod knowledge to make targeted madvise calls.

Security concerns:
In previous discussions security concerns have been brought up. The problem is that an individual workload does not have the knowledge about what else is running on a machine. Therefore it has to be very conservative in what memory areas can be shared or not. However, if the system is dedicated to running multiple jobs within the same security domain, its the job scheduler that has the knowledge that sharing can be safely enabled and is even desirable.

Quoted 6 lines
Quoted 3 lines

Note that there are some papers about why limiting memory deduplciation attacks to single security domains is not sufficient. Especially, the remote deduplication attacks fall into that category IIRC.

I think it would be good to elaborate on that and include any caveats in the documentation.

Yes. The main point I would make is that we should encourage eventual users to think twice instead of blindly enabling this feature. Good documentation is certainly helpful.

Quoted 4 lines

Ultimately, the bar isn't whether there are attack vectors on a subset of possible usecases, but whether there are usecases where this can be used safely, which is obviously true.

I agree. But still I have to raise that the security implications might be rather subtle and surprising (e.g., single security domain). Sure, there are setups that certainly don't care, I totally agree.

Side note:

Of course, I wonder how many workloads would place identical data into anonymous memory where it would have to get deduplicated instead, say, mmaping a file instead.

In the VM world it all makes sense to me, because the kernel, libraries, ...executables may be identical and loaded into guest memory (-> anonymous memory) where we'd just wish to deduplciate them. In ordinary process, I'm not so sure how much deduplication potential there really is once pointers etc. are involved and memory allocators go crazy on placing unrelated data into the same page. There is one prime example, though, that might be different, which is the shared zeropage I guess.

I'd be curious which data the mentioned 20% actually deduplicate: according to [1], some workloads mostly only deduplicate the shared zeropage (in their Microsoft Edge scenario, 84% -- 93% of all deduplicated pages are zeropage). Deduplicating the shared zeropage is obviously "less security" relevant and one could optimize KSM easily to only try deduplicating that and avoid a lot of unstable nodes.

Of course, just a thought on memory deduplication on process level.

[1] https://ieeexplore.ieee.org/document/7546546

Signature · 3 lines
Thanks,

David / dhildenb