Skip to contentSkip to conversation

ksm - dynamic page sharing driver for linux v4

PATCH In review Izik Eidus 7 participants 19 messages Apr 20, 2009 – May 14, 2009

Subsystems (6)
lore
Share & tools
lore

Izik Eidus

author
#0 lore raw

cover ksm - dynamic page sharing driver for linux v4

Introduction:
KSM is a linux driver that allows dynamicly sharing identical memory pages between one or more processes.

Unlike tradtional page sharing that is made at the allocation of the memory, ksm do it dynamicly after the memory was created. Memory is periodically scanned; identical pages are identified and merged.

The sharing is made in a transparent way to the procsess that use it.

Ksm is highly important for hypervisors (kvm), where in production enviorments there might be many copys of the same data data among the host memory.
This kind of data can be:
similar kernels, librarys, cache, and so on.

Even that ksm was wrote for kvm, any userspace application that want to use it to share its data can try it.

Ksm may be useful for any application that might have similar (page aligment) data strctures among the memory, ksm will find this data merge it to one copy, and even if it will be changed and thereforew copy on writed, ksm will merge it again as soon as it will be identical again.

Another reason to consider using ksm is the fact that it might simplify alot the userspace code of application that want to use shared private data, instead that the application will mange shared area, ksm will do this for the application, and even write to this data will be allowed without any synchinization acts from the application.

Ksm was desgiend to be a loadable module that doesnt change the VM code of linux.

Quoted 1 line

From v3 - v4:

1) Mostly fixes of coding styles, and few bugs that Andrew found.
* get_user_pages return value check - we now check == 1.
* protecting the vma under the mmap_sem() while checking its fields.
* kthread_* renaming into ksm_thread_*
* const to the file_operations strctures.

(The only thing i didnt change from your comments, is the number
of pages we are allocating for the hash table, this is performence critical for ksm)

2) Changed get_pte() to be linux generic function avaible for other users.

Description of the ksm interface:

Ksm interface is splited into two areas;
Administration sysfs interface - interface that is avaible thanks to sysfs to control the ksm cpu timing, maximum allocation of kernel pages and statics.

This interface is avaible at /sys/kernel/mm/ksm/ and its fields are:

kernel_pages_allocated - information about how many kernel pagesksm have allocated, this pages are not swappabke, and each page like that is used by ksm to share pages with identical content.

pages_shared - how many pages were shared by ksm

run - set to 1 when you want ksm to run, 0 when no

max_kernel_pages - set the maximum amount of kernel pages to be allocated by ksm, set 0 for unlimited.

pages_to_scan - how many pages to scan before ksm will sleep

sleep - how much usecs ksm will sleep.

The interface for applications that want its memory to be scanned by ksm:
This interface is built around ioctls when application want its memory to be scanned it will do something like that:

static int ksm_register_memory(unsigned long phys_ram_size,
unsigned long phys_ram_base)

{
    int fd;
    int ksm_fd;
    int r = 1;
    struct ksm_memory_region ksm_region;

    fd = open("/dev/ksm", O_RDWR | O_TRUNC, (mode_t)0600);
    if (fd == -1)
        goto out;

    ksm_fd = ioctl(fd, KSM_CREATE_SHARED_MEMORY_AREA);
    if (ksm_fd == -1)
        goto out_free;

    ksm_region.npages = phys_ram_size / TARGET_PAGE_SIZE;
    ksm_region.addr = phys_ram_base;
    r = ioctl(ksm_fd, KSM_REGISTER_MEMORY_REGION, &ksm_region);
    if (r)
        goto out_free1;

    return r;

out_free1:

    close(ksm_fd);
out_free:
    close(fd);
out:
    return r;
}

This ioctls are:

KSM_GET_API_VERSION:
Give the userspace the api version of the module.

KSM_CREATE_SHARED_MEMORY_AREA:
Create shared memory reagion fd, that latter allow the user to register the memory region to scan by using:
KSM_REGISTER_MEMORY_REGION and KSM_REMOVE_MEMORY_REGION

KSM_REGISTER_MEMORY_REGION:
Register userspace virtual address range to be scanned by ksm. This ioctl is using the ksm_memory_region structure:
ksm_memory_region:
__u32 npages;
number of pages to share inside this memory region.
__u32 pad;
__u64 addr:
the begining of the virtual address of this region.
__u64 reserved_bits;
reserved bits for future usage.

KSM_REMOVE_MEMORY_REGION:
Remove memory region from ksm.

Testing ksm:
Considering the fact that i got some mails asking me how to use this, I guess it wasnt explined good in the last posts, i will try to improve this:

The following steps should allow you to test ksm and play with it:

1) First patch your kernel with this patchs.

2) Patch avi kvm-git tree:
(git.kernel.org/pub/scm/linux/kernel/git/avi/kvm.git) with the patchs from:
http://lkml.org/lkml/2009/3/30/534

3) Patch kvm-userspace tree:
git.kernel.org/pub/scm/virt/kvm/kvm-userspace.git with the patchs from:
http://lkml.org/lkml/2009/3/30/538

4) try to do:
echo 300 > /sys/kernel/mm/ksm/pages_to_scan
echo 10000 > /sys/kernel/mm/ksm/sleep
echo 1 > /sys/kernel/mm/ksm/run
(Or any other numbers...)

Ok, you are ready :-)

(Just remember, memory that is swapped, isnt scanned by ksm until it
come back to memory, so dont try to raise alot of VMS togather)

Thanks.

Izik Eidus (5):
MMU_NOTIFIERS: add set_pte_at_notify()
add get_pte(): helper function: fetching pte for va add page_wrprotect(): write protecting page. add replace_page(): change the page pte is pointing to. add ksm kernel shared memory driver.

 include/linux/ksm.h          |   48 ++
 include/linux/miscdevice.h   |    1 +
 include/linux/mm.h           |   29 +
 include/linux/mmu_notifier.h |   34 +
 include/linux/rmap.h         |   11 +
 mm/Kconfig                   |    6 +
 mm/Makefile                  |    1 +
 mm/ksm.c                     | 1675 ++++++++++++++++++++++++++++++++++++++++++
 mm/memory.c                  |   90 +++-
 mm/mmu_notifier.c            |   20 +
 mm/rmap.c                    |  139 ++++
 11 files changed, 2052 insertions(+), 2 deletions(-)
 create mode 100644 include/linux/ksm.h
 create mode 100644 mm/ksm.c
author
#1 lore raw

PATCH 1/5 MMU_NOTIFIERS: add set_pte_at_notify()

this macro allow setting the pte in the shadow page tables directly instead of flushing the shadow page table entry and then get vmexit in order to set it.

This function is optimzation for kvm/users of mmu_notifiers for COW pages, it is useful for kvm when ksm is used beacuse it allow kvm not to have to recive VMEXIT and only then map the shared page into the mmu shadow pages, but instead map it directly at the same time linux map the page into the host page table.

this mmu notifer macro is working by calling to callback that will map directly the physical page into the shadow page tables.

(users of mmu_notifiers that didnt implement the set_pte_at_notify() call back will just recive the mmu_notifier_invalidate_page callback)

---
 include/linux/mmu_notifier.h |   34 ++++++++++++++++++++++++++++++++++
 mm/memory.c                  |   10 ++++++++--
 mm/mmu_notifier.c            |   20 ++++++++++++++++++++
 3 files changed, 62 insertions(+), 2 deletions(-)
include/linux/mmu_notifier.h +34 -0
index b77486d..8bb245f 100644
@@ -61,6 +61,15 @@ struct mmu_notifier_ops {
 				 struct mm_struct *mm,
 				 unsigned long address);
 
+	/* 
+	* change_pte is called in cases that pte mapping into page is changed
+	* for example when ksm mapped pte to point into a new shared page.
+	*/
+	void (*change_pte)(struct mmu_notifier *mn,
+			   struct mm_struct *mm,
+			   unsigned long address,
+			   pte_t pte);
+
 	/*
 	 * Before this is invoked any secondary MMU is still ok to
 	 * read/write to the page previously pointed to by the Linux
@@ -154,6 +163,8 @@ extern void __mmu_notifier_mm_destroy(struct mm_struct *mm);
 extern void __mmu_notifier_release(struct mm_struct *mm);
 extern int __mmu_notifier_clear_flush_young(struct mm_struct *mm,
 					  unsigned long address);
+extern void __mmu_notifier_change_pte(struct mm_struct *mm, 
+				      unsigned long address, pte_t pte);
 extern void __mmu_notifier_invalidate_page(struct mm_struct *mm,
 					  unsigned long address);
 extern void __mmu_notifier_invalidate_range_start(struct mm_struct *mm,
@@ -175,6 +186,13 @@ static inline int mmu_notifier_clear_flush_young(struct mm_struct *mm,
 	return 0;
 }
 
+static inline void mmu_notifier_change_pte(struct mm_struct *mm,
+					   unsigned long address, pte_t pte)
+{
+	if (mm_has_notifiers(mm))
+		__mmu_notifier_change_pte(mm, address, pte);
+}
+
 static inline void mmu_notifier_invalidate_page(struct mm_struct *mm,
 					  unsigned long address)
 {
@@ -236,6 +254,16 @@ static inline void mmu_notifier_mm_destroy(struct mm_struct *mm)
 	__young;							\
 })
 
+#define set_pte_at_notify(__mm, __address, __ptep, __pte)		\
+({									\
+	struct mm_struct *___mm = __mm;					\
+	unsigned long ___address = __address;				\
+	pte_t ___pte = __pte;						\
+									\
+	set_pte_at(__mm, __address, __ptep, ___pte);			\
+	mmu_notifier_change_pte(___mm, ___address, ___pte);		\
+})
+
 #else /* CONFIG_MMU_NOTIFIER */
 
 static inline void mmu_notifier_release(struct mm_struct *mm)
@@ -248,6 +276,11 @@ static inline int mmu_notifier_clear_flush_young(struct mm_struct *mm,
 	return 0;
 }
 
+static inline void mmu_notifier_change_pte(struct mm_struct *mm,
+					   unsigned long address, pte_t pte)
+{
+}
+
 static inline void mmu_notifier_invalidate_page(struct mm_struct *mm,
 					  unsigned long address)
 {
@@ -273,6 +306,7 @@ static inline void mmu_notifier_mm_destroy(struct mm_struct *mm)
 
 #define ptep_clear_flush_young_notify ptep_clear_flush_young
 #define ptep_clear_flush_notify ptep_clear_flush
+#define set_pte_at_notify set_pte_at
 
 #endif /* CONFIG_MMU_NOTIFIER */
 
mm/memory.c +8 -2
index cf6873e..1e1a14b 100644
@@ -2051,9 +2051,15 @@ gotten:
 		 * seen in the presence of one thread doing SMC and another
 		 * thread doing COW.
 		 */
-		ptep_clear_flush_notify(vma, address, page_table);
+		ptep_clear_flush(vma, address, page_table);
 		page_add_new_anon_rmap(new_page, vma, address);
-		set_pte_at(mm, address, page_table, entry);
+		/*
+		 * We call here the notify macro beacuse in cases of using
+		 * secondary mmu page table like kvm shadow page, tables we want
+		 * the new page to be mapped directly into the secondary page
+		 * table
+		 */
+		set_pte_at_notify(mm, address, page_table, entry);
 		update_mmu_cache(vma, address, entry);
 		if (old_page) {
 			/*
mm/mmu_notifier.c +20 -0
index 5f4ef02..c3e8779 100644
@@ -99,6 +99,26 @@ int __mmu_notifier_clear_flush_young(struct mm_struct *mm,
 	return young;
 }
 
+void __mmu_notifier_change_pte(struct mm_struct *mm, unsigned long address,
+			       pte_t pte)
+{
+	struct mmu_notifier *mn;
+	struct hlist_node *n;
+
+	rcu_read_lock();
+	hlist_for_each_entry_rcu(mn, n, &mm->mmu_notifier_mm->list, hlist) {
+		if (mn->ops->change_pte)
+			mn->ops->change_pte(mn, mm, address, pte);
+		/* 
+		 * some drivers dont have change_pte and therefor we must call
+		 * for invalidate_page in that case
+		 */
+		else if (mn->ops->invalidate_page)
+			mn->ops->invalidate_page(mn, mm, address);
+	}
+	rcu_read_unlock();
+}
+
 void __mmu_notifier_invalidate_page(struct mm_struct *mm,
 					  unsigned long address)
 {
Signature · 1 line
1.5.6.5
author
#2 lore raw

PATCH 2/5 add get_pte(): helper function: fetching pte for va

get_pte() receive mm_struct of a task, and a virtual address and return the pte corresponding to it.

this function return NULL in case it couldnt fetch the pte.

---
 include/linux/mm.h |   24 ++++++++++++++++++++++++
 1 files changed, 24 insertions(+), 0 deletions(-)
include/linux/mm.h +24 -0
index bff1f0d..9a34109 100644
@@ -894,6 +894,30 @@ int vma_wants_writenotify(struct vm_area_struct *vma);
 
 extern pte_t *get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl);
 
+static inline pte_t *get_pte(struct mm_struct *mm, unsigned long addr)
+{
+	pgd_t *pgd;
+	pud_t *pud;
+	pmd_t *pmd;
+	pte_t *ptep = NULL;
+
+	pgd = pgd_offset(mm, addr);
+	if (!pgd_present(*pgd))
+		goto out;
+
+	pud = pud_offset(pgd, addr);
+	if (!pud_present(*pud))
+		goto out;
+
+	pmd = pmd_offset(pud, addr);
+	if (!pmd_present(*pmd))
+		goto out;
+
+	ptep = pte_offset_map(pmd, addr);
+out:
+	return ptep;
+}
+
 #ifdef __PAGETABLE_PUD_FOLDED
 static inline int __pud_alloc(struct mm_struct *mm, pgd_t *pgd,
 						unsigned long address)
Signature · 7 lines
1.5.6.5

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
author
#3 lore raw

PATCH 3/5 add page_wrprotect(): write protecting page.

this patch add new function called page_wrprotect(), page_wrprotect() is used to take a page and mark all the pte that point into it as readonly.

The function is working by walking the rmap of the page, and setting each pte realted to the page as readonly.

The odirect_sync parameter is used to protect against possible races with odirect while we are marking the pte as readonly,
as noted by Andrea Arcanglei:

"While thinking at get_user_pages_fast I figured another worse way things can go wrong with ksm and o_direct: think a thread writing constantly to the last 512bytes of a page, while another thread read and writes to/from the first 512bytes of the page. We can lose O_DIRECT reads, the very moment we mark any pte wrprotected..."

---
 include/linux/rmap.h |   11 ++++
 mm/rmap.c            |  139 ++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 150 insertions(+), 0 deletions(-)
include/linux/rmap.h +11 -0
index b35bc0e..469376d 100644
@@ -118,6 +118,10 @@ static inline int try_to_munlock(struct page *page)
 }
 #endif
 
+#if defined(CONFIG_KSM) || defined(CONFIG_KSM_MODULE)
+int page_wrprotect(struct page *page, int *odirect_sync, int count_offset);
+#endif
+
 #else	/* !CONFIG_MMU */
 
 #define anon_vma_init()		do {} while (0)
@@ -132,6 +136,13 @@ static inline int page_mkclean(struct page *page)
 	return 0;
 }
 
+#if defined(CONFIG_KSM) || defined(CONFIG_KSM_MODULE)
+static inline int page_wrprotect(struct page *page, int *odirect_sync,
+				 int count_offset)
+{
+	return 0;
+}
+#endif
 
 #endif	/* CONFIG_MMU */
 
mm/rmap.c +139 -0

145 lines not on this page · raw message

Signature · 7 lines
1.5.6.5

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
author
#4 lore raw

PATCH 4/5 add replace_page(): change the page pte is pointing to.

replace_page() allow changing the mapping of pte from one physical page into diffrent physical page.

this function is working by removing oldpage from the rmap and calling put_page on it, and by setting the pte to point into newpage and by inserting it to the rmap using page_add_file_rmap().

note: newpage must be non anonymous page, the reason for this is:
replace_page() is built to allow mapping one page into more than one virtual addresses, the mapping of this page can happen in diffrent offsets inside each vma, and therefore we cannot trust the page->index anymore.

the side effect of this issue is that newpage cannot be anything but kernel allocated page that is not swappable.

---
 include/linux/mm.h |    5 +++
 mm/memory.c        |   80 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 85 insertions(+), 0 deletions(-)
include/linux/mm.h +5 -0
index 9a34109..a0ddfb5 100644
@@ -1264,6 +1264,11 @@ int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
 			unsigned long pfn);
 
+#if defined(CONFIG_KSM) || defined(CONFIG_KSM_MODULE)
+int replace_page(struct vm_area_struct *vma, struct page *oldpage,
+		 struct page *newpage, pte_t orig_pte, pgprot_t prot);
+#endif
+
 struct page *follow_page(struct vm_area_struct *, unsigned long address,
 			unsigned int foll_flags);
 #define FOLL_WRITE	0x01	/* check pte is writable */
mm/memory.c +80 -0

86 lines not on this page · raw message

Signature · 7 lines
1.5.6.5

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
author
#5 lore raw

PATCH 5/5 add ksm kernel shared memory driver.

Ksm is driver that allow merging identical pages between one or more applications in way unvisible to the application that use it. Pages that are merged are marked as readonly and are COWed when any application try to change them.

Ksm is used for cases where using fork() is not suitable, one of this cases is where the pages of the application keep changing dynamicly and the application cannot know in advance what pages are going to be identical.

Ksm works by walking over the memory pages of the applications it scan in order to find identical pages.
It uses a two sorted data strctures called stable and unstable trees to find in effective way the identical pages.

When ksm finds two identical pages, it marks them as readonly and merges them into single one page,
after the pages are marked as readonly and merged into one page, linux will treat this pages as normal copy_on_write pages and will fork them when write access will happen to them.

Ksm scan just memory areas that were registred to be scanned by it.

---
 include/linux/ksm.h        |   48 ++
 include/linux/miscdevice.h |    1 +
 mm/Kconfig                 |    6 +
 mm/Makefile                |    1 +
 mm/ksm.c                   | 1675 ++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 1731 insertions(+), 0 deletions(-)
 create mode 100644 include/linux/ksm.h
 create mode 100644 mm/ksm.c
include/linux/ksm.h new file +48 -0
new file mode 100644
index 0000000..2c11e9a
@@ -0,0 +1,48 @@
+#ifndef __LINUX_KSM_H
+#define __LINUX_KSM_H
+
+/*
+ * Userspace interface for /dev/ksm - kvm shared memory
+ */
+
+#include <linux/types.h>
+#include <linux/ioctl.h>
+
+#include <asm/types.h>
+
+#define KSM_API_VERSION 1
+
+#define ksm_control_flags_run 1
+
+/* for KSM_REGISTER_MEMORY_REGION */
+struct ksm_memory_region {
+	__u32 npages; /* number of pages to share */
+	__u32 pad;
+	__u64 addr; /* the begining of the virtual address */
+        __u64 reserved_bits;
+};
+
+#define KSMIO 0xAB
+
+/* ioctls for /dev/ksm */
+
+#define KSM_GET_API_VERSION              _IO(KSMIO,   0x00)
+/*
+ * KSM_CREATE_SHARED_MEMORY_AREA - create the shared memory reagion fd
+ */
+#define KSM_CREATE_SHARED_MEMORY_AREA    _IO(KSMIO,   0x01) /* return SMA fd */
+
+/* ioctls for SMA fds */
+
+/*
+ * KSM_REGISTER_MEMORY_REGION - register virtual address memory area to be
+ * scanned by kvm.
+ */
+#define KSM_REGISTER_MEMORY_REGION       _IOW(KSMIO,  0x20,\
+					      struct ksm_memory_region)
+/*
+ * KSM_REMOVE_MEMORY_REGION - remove virtual address memory area from ksm.
+ */
+#define KSM_REMOVE_MEMORY_REGION         _IO(KSMIO,   0x21)
+
+#endif
include/linux/miscdevice.h +1 -0
index beb6ec9..297c0bb 100644
@@ -30,6 +30,7 @@
 #define HPET_MINOR		228
 #define FUSE_MINOR		229
 #define KVM_MINOR		232
+#define KSM_MINOR		233
 #define MISC_DYNAMIC_MINOR	255
 
 struct device;
mm/Kconfig +6 -0
index 57971d2..fb8ac63 100644
@@ -225,3 +225,9 @@ config HAVE_MLOCKED_PAGE_BIT
 
 config MMU_NOTIFIER
 	bool
+
+config KSM
+	tristate "Enable KSM for page sharing"
+	help
+	  Enable the KSM kernel module to allow page sharing of equal pages
+	  among different tasks.
mm/Makefile +1 -0
index ec73c68..b885513 100644
@@ -24,6 +24,7 @@ obj-$(CONFIG_SPARSEMEM_VMEMMAP) += sparse-vmemmap.o
 obj-$(CONFIG_TMPFS_POSIX_ACL) += shmem_acl.o
 obj-$(CONFIG_SLOB) += slob.o
 obj-$(CONFIG_MMU_NOTIFIER) += mmu_notifier.o
+obj-$(CONFIG_KSM) += ksm.o
 obj-$(CONFIG_PAGE_POISONING) += debug-pagealloc.o
 obj-$(CONFIG_SLAB) += slab.o
 obj-$(CONFIG_SLUB) += slub.o
mm/ksm.c new file +1675 -0

1,675 lines not on this page · raw message

Signature · 7 lines
1.5.6.5

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#6 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

The minor number you are using already belongs to another project.

10,234 is free but it would be good to know what device naming is proposed. I imagine other folks would like to know why you aren't using sysfs or similar or extending /dev/kvm ?

Alan

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#7 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 6 lines · Alan Cox

The minor number you are using already belongs to another project.

10,234 is free but it would be good to know what device naming is proposed. I imagine other folks would like to know why you aren't using sysfs or similar or extending /dev/kvm ?

ksm was deliberately made independent of kvm. While there may or may not be uses of ksm without kvm (you could run ordinary qemu, but no one would do this in a production deployment), keeping them separate helps avoid unnecessary interdependencies. For example all tlb flushes are mediated through mmu notifiers instead of ksm hooking directly into kvm.

Signature · 7 lines
error compiling committee.c: too many arguments to function

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
author
#8 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 10 lines · Avi Kivity
Quoted 6 lines · Alan Cox

The minor number you are using already belongs to another project.

10,234 is free but it would be good to know what device naming is proposed. I imagine other folks would like to know why you aren't using sysfs or similar or extending /dev/kvm ?

ksm was deliberately made independent of kvm. While there may or may not be uses of ksm without kvm (you could run ordinary qemu, but no one would do this in a production deployment), keeping them separate helps avoid unnecessary interdependencies. For example all tlb flushes are mediated through mmu notifiers instead of ksm hooking directly into kvm.

Yes, beside, I do use sysfs for controlling the ksm behavior, Ioctls are provided as easier way for application to register its memory.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

maintainer
#9 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

In reply to Izik Eidus
Quoted 4 lines · On Mon, 20 Apr 2009 04:36:06 +0300 Izik Eidus <[email protected]> wrote:

Ksm is driver that allow merging identical pages between one or more applications in way unvisible to the application that use it. Pages that are merged are marked as readonly and are COWed when any application try to change them.

Breaks sparc64 and probably lots of other architectures:

mm/ksm.c: In function `try_to_merge_two_pages_alloc':
mm/ksm.c:697: error: `_PAGE_RW' undeclared (first use in this function)

there should be an official arch-independent way of manipulating vma->vm_page_prot, but I'm not immediately finding it.

An alternative (and quite inferior) "fix" would be to disable ksm on architectures which don't implement _PAGE_RW. That's most of them.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

author
#10 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 10 lines · Andrew Morton
Quoted 5 lines · On Mon, 20 Apr 2009 04:36:06 +0300 Izik Eidus <[email protected]> wrote:

Ksm is driver that allow merging identical pages between one or more applications in way unvisible to the application that use it. Pages that are merged are marked as readonly and are COWed when any application try to change them.

Quoted 8 lines

Breaks sparc64 and probably lots of other architectures:

mm/ksm.c: In function `try_to_merge_two_pages_alloc':
mm/ksm.c:697: error: `_PAGE_RW' undeclared (first use in this function)

there should be an official arch-independent way of manipulating vma->vm_page_prot, but I'm not immediately finding it.

Hi,

vm_get_page_prot() will probably do the work.

I will send you patch that fix it,
but first i am waiting for Andrea and Chris to say they are happy with small changes that i made to the api after conversation i had with them (about checking if this api is robust enough so we wont have to change it later)

When i will get their acks, i will send you patch against this togather with the api (until then it is ok to just leave it only for x86)

changes are:
1) limiting the number of memory regions registered per file descriptor - so while (1){ (ioctl(KSM_REGISTER_MEMORY_REGION()) ) wont omm the host

2) checking if memory is overlap in registration (more effective to ignore such cases)

3) allow removing specific memoy regions inside fd.

Thanks.

Quoted 4 lines

An alternative (and quite inferior) "fix" would be to disable ksm on architectures which don't implement _PAGE_RW. That's most of them.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

author
#11 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 31 lines · On Tue, 28 Apr 2009 02:12:00 +0300 Izik Eidus <[email protected]> wrote:
Quoted 9 lines · Andrew Morton

Breaks sparc64 and probably lots of other architectures:

mm/ksm.c: In function `try_to_merge_two_pages_alloc':
mm/ksm.c:697: error: `_PAGE_RW' undeclared (first use in this function)

there should be an official arch-independent way of manipulating vma->vm_page_prot, but I'm not immediately finding it.

Hi,

vm_get_page_prot() will probably do the work.

I will send you patch that fix it,
but first i am waiting for Andrea and Chris to say they are happy with small changes that i made to the api after conversation i had with them (about checking if this api is robust enough so we wont have to change it later)

When i will get their acks, i will send you patch against this togather with the api (until then it is ok to just leave it only for x86)

changes are:
1) limiting the number of memory regions registered per file descriptor
- so while (1){ (ioctl(KSM_REGISTER_MEMORY_REGION()) ) wont omm the host

Quoted 7 lines

2) checking if memory is overlap in registration (more effective to ignore such cases)

3) allow removing specific memoy regions inside fd.

Thanks.

Hi,

Following patchs change the api to be more robust, the result change of the api came after conversation i had with Andrea and Chris about how to make the api as stable as we can,

In addition i hope this patchset fix the cross compilation problems, i compiled it on itanium (doesnt have _PAGE_RW) and it seems to work.

Thanks.
From 108b720636d1e679e8d5378469fa1220ce1e6963 Mon Sep 17 00:00:00 2001
From: Izik Eidus <[email protected]>
Date: Thu, 30 Apr 2009 20:36:57 +0300
Subject: [PATCH 09/13] ksm: limiting the num of mem regions user can register per fd.

Right now user can open /dev/ksm fd and register unlimited number of regions, such behavior may allocate unlimited amount of kernel memory and get the whole host into out of memory situation.

---
 mm/ksm.c |   15 +++++++++++++++
 1 files changed, 15 insertions(+), 0 deletions(-)
mm/ksm.c +15 -0
index 6165276..d58db6b 100644
@@ -48,6 +48,9 @@ static int rmap_hash_size;
 module_param(rmap_hash_size, int, 0);
 MODULE_PARM_DESC(rmap_hash_size, "Hash table size for the reverse mapping");
 
+static int regions_per_fd;
+module_param(regions_per_fd, int, 0);
+
 /*
  * ksm_mem_slot - hold information for an userspace scanning range
  * (the scanning for this region will be from addr untill addr +
@@ -67,6 +70,7 @@ struct ksm_mem_slot {
  */
 struct ksm_sma {
 	struct list_head sma_slots;
+	int nregions;
 };
 
 /**
@@ -453,6 +457,11 @@ static int ksm_sma_ioctl_register_memory_region(struct ksm_sma *ksm_sma,
 	struct ksm_mem_slot *slot;
 	int ret = -EPERM;
 
+	if ((ksm_sma->nregions + 1) > regions_per_fd) {
+		ret = -EBUSY;
+		goto out;
+	}
+
 	slot = kzalloc(sizeof(struct ksm_mem_slot), GFP_KERNEL);
 	if (!slot) {
 		ret = -ENOMEM;
@@ -473,6 +482,7 @@ static int ksm_sma_ioctl_register_memory_region(struct ksm_sma *ksm_sma,
 
 	list_add_tail(&slot->link, &slots);
 	list_add_tail(&slot->sma_link, &ksm_sma->sma_slots);
+	ksm_sma->nregions++;
 
 	up_write(&slots_lock);
 	return 0;
@@ -511,6 +521,7 @@ static int ksm_sma_ioctl_remove_memory_region(struct ksm_sma *ksm_sma)
 		mmput(slot->mm);
 		list_del(&slot->sma_link);
 		kfree(slot);
+		ksm_sma->nregions--;
 	}
 	up_write(&slots_lock);
 	return 0;
@@ -1389,6 +1400,7 @@ static int ksm_dev_ioctl_create_shared_memory_area(void)
 	}
 
 	INIT_LIST_HEAD(&ksm_sma->sma_slots);
+	ksm_sma->nregions = 0;
 
 	fd = anon_inode_getfd("ksm-sma", &ksm_sma_fops, ksm_sma, 0);
 	if (fd < 0)
@@ -1631,6 +1643,9 @@ static int __init ksm_init(void)
 	if (r)
 		goto out_free1;
 
+	if (!regions_per_fd)
+		regions_per_fd = 1024;
+
 	ksm_thread = kthread_run(ksm_scan_thread, NULL, "kksmd");
 	if (IS_ERR(ksm_thread)) {
 		printk(KERN_ERR "ksm: creating kthread failed\n");
Signature · 13 lines
1.5.6.5

From f24a9aa8c049c951a33613909951d115be5f84cd Mon Sep 17 00:00:00 2001
From: Izik Eidus <[email protected]>
Date: Thu, 30 Apr 2009 20:37:17 +0300
Subject: [PATCH 10/13] ksm: dont allow overlap memory addresses registrations.

subjects say it all.

Signed-off-by: Izik Eidus <[email protected]>
---
 mm/ksm.c |   58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 54 insertions(+), 4 deletions(-)
mm/ksm.c +54 -4

89 lines not on this page · raw message

Signature · 27 lines
1.5.6.5

From 57807f89d1f2842de69511e10643a48976ebc22e Mon Sep 17 00:00:00 2001
From: Izik Eidus <[email protected]>
Date: Thu, 30 Apr 2009 20:37:39 +0300
Subject: [PATCH 11/13] ksm: change the KSM_REMOVE_MEMORY_REGION ioctl.

This patch change the KSM_REMOVE_MEMORY_REGION ioctl to be specific per
memory region (instead of flushing all the registred memory regions inside
the file descriptor like it happen now)

The previoes api was:
user register memory regions using KSM_REGISTER_MEMORY_REGION inside the fd,
and then when he wanted to remove just one memory region, he had to remove them
all using KSM_REMOVE_MEMORY_REGION.

This patch change this beahivor by chaning the KSM_REMOVE_MEMORY_REGION
ioctl to recive another paramter that it is the begining of the virtual
address that is wanted to be removed.

(user can still remove all the memory regions all at once, by just closing
the file descriptor)

Signed-off-by: Izik Eidus <[email protected]>
---
 mm/ksm.c |   31 +++++++++++++++++++++----------
 1 files changed, 21 insertions(+), 10 deletions(-)
mm/ksm.c +21 -10
index 982dfff..c14019f 100644
@@ -561,17 +561,20 @@ static void remove_mm_from_hash_and_tree(struct mm_struct *mm)
 	list_del(&slot->link);
 }
 
-static int ksm_sma_ioctl_remove_memory_region(struct ksm_sma *ksm_sma)
+static int ksm_sma_ioctl_remove_memory_region(struct ksm_sma *ksm_sma,
+					      unsigned long addr)
 {
 	struct ksm_mem_slot *slot, *node;
 
 	down_write(&slots_lock);
 	list_for_each_entry_safe(slot, node, &ksm_sma->sma_slots, sma_link) {
-		remove_mm_from_hash_and_tree(slot->mm);
-		mmput(slot->mm);
-		list_del(&slot->sma_link);
-		kfree(slot);
-		ksm_sma->nregions--;
+		if (addr == slot->addr) {
+			remove_mm_from_hash_and_tree(slot->mm);
+			mmput(slot->mm);
+			list_del(&slot->sma_link);
+			kfree(slot);
+			ksm_sma->nregions--;
+		}
 	}
 	up_write(&slots_lock);
 	return 0;
@@ -579,12 +582,20 @@ static int ksm_sma_ioctl_remove_memory_region(struct ksm_sma *ksm_sma)
 
 static int ksm_sma_release(struct inode *inode, struct file *filp)
 {
+	struct ksm_mem_slot *slot, *node;
 	struct ksm_sma *ksm_sma = filp->private_data;
-	int r;
 
-	r = ksm_sma_ioctl_remove_memory_region(ksm_sma);
+	down_write(&slots_lock);
+	list_for_each_entry_safe(slot, node, &ksm_sma->sma_slots, sma_link) {
+		remove_mm_from_hash_and_tree(slot->mm);
+		mmput(slot->mm);
+		list_del(&slot->sma_link);
+		kfree(slot);
+	}
+	up_write(&slots_lock);
+
 	kfree(ksm_sma);
-	return r;
+	return 0;
 }
 
 static long ksm_sma_ioctl(struct file *filp,
@@ -607,7 +618,7 @@ static long ksm_sma_ioctl(struct file *filp,
 		break;
 	}
 	case KSM_REMOVE_MEMORY_REGION:
-		r = ksm_sma_ioctl_remove_memory_region(sma);
+		r = ksm_sma_ioctl_remove_memory_region(sma, arg);
 		break;
 	}
 
Signature · 13 lines
1.5.6.5

From 146ecd222f59460548dafbd3c322030251c33b8d Mon Sep 17 00:00:00 2001
From: Izik Eidus <[email protected]>
Date: Thu, 30 Apr 2009 20:38:05 +0300
Subject: [PATCH 12/13] ksm: change the prot handling to use the generic helper functions

This is needed to avoid breaking some architectures.

Signed-off-by: Izik Eidus <[email protected]>
---
 mm/ksm.c |   12 ++++++------
 1 files changed, 6 insertions(+), 6 deletions(-)
mm/ksm.c +6 -6
index c14019f..bfbbe1d 100644
@@ -766,8 +766,8 @@ static int try_to_merge_two_pages_alloc(struct mm_struct *mm1,
 		up_read(&mm1->mmap_sem);
 		return ret;
 	}
-	prot = vma->vm_page_prot;
-	pgprot_val(prot) &= ~_PAGE_RW;
+
+	prot = vm_get_page_prot(vma->vm_flags & ~VM_WRITE);
 
 	copy_user_highpage(kpage, page1, addr1, vma);
 	ret = try_to_merge_one_page(mm1, vma, page1, kpage, prot);
@@ -784,8 +784,7 @@ static int try_to_merge_two_pages_alloc(struct mm_struct *mm1,
 			return ret;
 		}
 
-		prot = vma->vm_page_prot;
-		pgprot_val(prot) &= ~_PAGE_RW;
+		prot = vm_get_page_prot(vma->vm_flags & ~VM_WRITE);
 
 		ret = try_to_merge_one_page(mm2, vma, page2, kpage,
 					    prot);
@@ -831,8 +830,9 @@ static int try_to_merge_two_pages_noalloc(struct mm_struct *mm1,
 		up_read(&mm1->mmap_sem);
 		return ret;
 	}
-	prot = vma->vm_page_prot;
-	pgprot_val(prot) &= ~_PAGE_RW;
+
+	prot = vm_get_page_prot(vma->vm_flags & ~VM_WRITE);
+
 	ret = try_to_merge_one_page(mm1, vma, page1, page2, prot);
 	up_read(&mm1->mmap_sem);
 	if (!ret)
Signature · 14 lines
1.5.6.5

From 3b437cac1890999191cca6c76da5e71ceec487e4 Mon Sep 17 00:00:00 2001
From: Izik Eidus <[email protected]>
Date: Thu, 30 Apr 2009 20:38:33 +0300
Subject: [PATCH 13/13] ksm: build system make it compile for all archs

The known issues with cross platform support were fixed,
so we return it back to compile on all archs.

Signed-off-by: Izik Eidus <[email protected]>
---
 mm/Kconfig |    1 -
 1 files changed, 0 insertions(+), 1 deletions(-)
mm/Kconfig +0 -1
index f59b1e4..fb8ac63 100644
@@ -228,7 +228,6 @@ config MMU_NOTIFIER
 
 config KSM
 	tristate "Enable KSM for page sharing"
-	depends on X86
 	help
 	  Enable the KSM kernel module to allow page sharing of equal pages
 	  among different tasks.
Signature · 9 lines
1.5.6.5



--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
maintainer
#12 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 6 lines · On Thu, 30 Apr 2009 20:46:24 +0300 Izik Eidus <[email protected]> wrote:

Following patchs change the api to be more robust, the result change of the api came after conversation i had with Andrea and Chris about how to make the api as stable as we can,

In addition i hope this patchset fix the cross compilation problems, i compiled it on itanium (doesnt have _PAGE_RW) and it seems to work.

eek, please don't send multiple patches per email - it's surprisingly disruptive to everything.

What is the relationship between these patches and the ones I merged the other day?

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

maintainer
#13 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

In reply to Izik Eidus
Quoted 24 lines · On Mon, 20 Apr 2009 04:36:06 +0300 Izik Eidus <[email protected]> wrote:

Ksm is driver that allow merging identical pages between one or more applications in way unvisible to the application that use it. Pages that are merged are marked as readonly and are COWed when any application try to change them.

Ksm is used for cases where using fork() is not suitable, one of this cases is where the pages of the application keep changing dynamicly and the application cannot know in advance what pages are going to be identical.

Ksm works by walking over the memory pages of the applications it scan in order to find identical pages.
It uses a two sorted data strctures called stable and unstable trees to find in effective way the identical pages.

When ksm finds two identical pages, it marks them as readonly and merges them into single one page,
after the pages are marked as readonly and merged into one page, linux will treat this pages as normal copy_on_write pages and will fork them when write access will happen to them.

Ksm scan just memory areas that were registred to be scanned by it.

...

mm/ksm.c line 700

Quoted 2 lines
mm/ksm.c new file +1 -0
+	copy_user_highpage(kpage, page1, addr1, vma);
...

Breaks ppc64 allmodcofnig because that architecture doesn't export its copy_user_page() to modules.

Architectures are inconsistent about this. x86 _does_ export it, because it bounces it to the exported copy_page().

So can I ask that you sit down and work out upon which architectures it really makes sense to offer KSM? Disallow the others in Kconfig and arrange for copy_user_highpage() to be available on the allowed architectures?

Thanks.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#14 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 2 lines · * Andrew Morton ([email protected]) wrote:

Breaks ppc64 allmodcofnig because that architecture doesn't export its copy_user_page() to modules.

Things like this and updating to use madvise() I think all point towards s/tristate/bool/. I don't think CONFIG_KSM=M has huge benefit.

thanks,
-chris

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#15 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 9 lines · Chris Wright
Quoted 3 lines · * Andrew Morton ([email protected]) wrote:

Breaks ppc64 allmodcofnig because that architecture doesn't export its copy_user_page() to modules.

Things like this and updating to use madvise() I think all point towards s/tristate/bool/. I don't think CONFIG_KSM=M has huge benefit.

I agree.

Regards,

Anthony Liguori

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

author
#16 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 7 lines · Anthony Liguori
Quoted 6 lines · Chris Wright
Quoted 3 lines · * Andrew Morton ([email protected]) wrote:

Breaks ppc64 allmodcofnig because that architecture doesn't export its copy_user_page() to modules.

Quoted 5 lines
Quoted 3 lines

Things like this and updating to use madvise() I think all point towards s/tristate/bool/. I don't think CONFIG_KSM=M has huge benefit.

I agree.

I am sending in one sec, the madvise patch that will kick it away from being module anyway...

Quoted 5 lines

Regards,

Anthony Liguori

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

author
#17 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

In reply to Andrew Morton
Quoted 35 lines · Andrew Morton
Quoted 25 lines · On Mon, 20 Apr 2009 04:36:06 +0300 Izik Eidus <[email protected]> wrote:

Ksm is driver that allow merging identical pages between one or more applications in way unvisible to the application that use it. Pages that are merged are marked as readonly and are COWed when any application try to change them.

Ksm is used for cases where using fork() is not suitable, one of this cases is where the pages of the application keep changing dynamicly and the application cannot know in advance what pages are going to be identical.

Ksm works by walking over the memory pages of the applications it scan in order to find identical pages.
It uses a two sorted data strctures called stable and unstable trees to find in effective way the identical pages.

When ksm finds two identical pages, it marks them as readonly and merges them into single one page,
after the pages are marked as readonly and merged into one page, linux will treat this pages as normal copy_on_write pages and will fork them when write access will happen to them.

Ksm scan just memory areas that were registred to be scanned by it.

...

mm/ksm.c line 700

Quoted 2 lines
mm/ksm.c new file +1 -0
+	copy_user_highpage(kpage, page1, addr1, vma);
...

Breaks ppc64 allmodcofnig because that architecture doesn't export its copy_user_page() to modules.

Quoted 7 lines

Architectures are inconsistent about this. x86 _does_ export it, because it bounces it to the exported copy_page().

So can I ask that you sit down and work out upon which architectures it really makes sense to offer KSM? Disallow the others in Kconfig and arrange for copy_user_highpage() to be available on the allowed architectures?

Hi

There is some way (script) that i can run that will allow compile this code for every possible arch?

(I dont mind to allow it just for archs that support virtualization - x86, ia64, powerpc, s390, but is it the right thing to do ?)

Quoted 2 lines

Thanks.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#18 lore raw

Re: [PATCH 5/5] add ksm kernel shared memory driver.

Quoted 4 lines · Izik Eidus

Hi

There is some way (script) that i can run that will allow compile this code for every possible arch?

Segher Boessenkool has a tool for builing cross toolchains and the kernel at git://git.infradead.org/users/segher/buildall.git You can save yourself some time (and pain) and use the built toolchains at:
http://bakeyournoodle.com/cross

If there is any interest I can get these toolchains hosted on a faster machine (say kernel.org)

Yours Tony

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>