2 * Memory merging support.
4 * This code enables dynamic sharing of identical pages found in different
5 * memory areas, even if they are not shared by fork()
7 * Copyright (C) 2008-2009 Red Hat, Inc.
14 * This work is licensed under the terms of the GNU GPL, version 2.
17 #include <linux/errno.h>
20 #include <linux/mman.h>
21 #include <linux/sched.h>
22 #include <linux/rwsem.h>
23 #include <linux/pagemap.h>
24 #include <linux/rmap.h>
25 #include <linux/spinlock.h>
26 #include <linux/jhash.h>
27 #include <linux/delay.h>
28 #include <linux/kthread.h>
29 #include <linux/wait.h>
30 #include <linux/slab.h>
31 #include <linux/rbtree.h>
32 #include <linux/mmu_notifier.h>
33 #include <linux/swap.h>
34 #include <linux/ksm.h>
36 #include <asm/tlbflush.h>
39 * A few notes about the KSM scanning process,
40 * to make it easier to understand the data structures below:
42 * In order to reduce excessive scanning, KSM sorts the memory pages by their
43 * contents into a data structure that holds pointers to the pages' locations.
45 * Since the contents of the pages may change at any moment, KSM cannot just
46 * insert the pages into a normal sorted tree and expect it to find anything.
47 * Therefore KSM uses two data structures - the stable and the unstable tree.
49 * The stable tree holds pointers to all the merged pages (ksm pages), sorted
50 * by their contents. Because each such page is write-protected, searching on
51 * this tree is fully assured to be working (except when pages are unmapped),
52 * and therefore this tree is called the stable tree.
54 * In addition to the stable tree, KSM uses a second data structure called the
55 * unstable tree: this tree holds pointers to pages which have been found to
56 * be "unchanged for a period of time". The unstable tree sorts these pages
57 * by their contents, but since they are not write-protected, KSM cannot rely
58 * upon the unstable tree to work correctly - the unstable tree is liable to
59 * be corrupted as its contents are modified, and so it is called unstable.
61 * KSM solves this problem by several techniques:
63 * 1) The unstable tree is flushed every time KSM completes scanning all
64 * memory areas, and then the tree is rebuilt again from the beginning.
65 * 2) KSM will only insert into the unstable tree, pages whose hash value
66 * has not changed since the previous scan of all memory areas.
67 * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
68 * colors of the nodes and not on their contents, assuring that even when
69 * the tree gets "corrupted" it won't get out of balance, so scanning time
70 * remains the same (also, searching and inserting nodes in an rbtree uses
71 * the same algorithm, so we have no overhead when we flush and rebuild).
72 * 4) KSM never flushes the stable tree, which means that even if it were to
73 * take 10 attempts to find a page in the unstable tree, once it is found,
74 * it is secured in the stable tree. (When we scan a new page, we first
75 * compare it against the stable tree, and then against the unstable tree.)
79 * struct mm_slot - ksm information per mm that is being scanned
80 * @link: link to the mm_slots hash list
81 * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
82 * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
83 * @mm: the mm that this information is valid for
86 struct hlist_node link;
87 struct list_head mm_list;
88 struct rmap_item *rmap_list;
93 * struct ksm_scan - cursor for scanning
94 * @mm_slot: the current mm_slot we are scanning
95 * @address: the next address inside that to be scanned
96 * @rmap_list: link to the next rmap to be scanned in the rmap_list
97 * @seqnr: count of completed full scans (needed when removing unstable node)
99 * There is only the one ksm_scan instance of this cursor structure.
102 struct mm_slot *mm_slot;
103 unsigned long address;
104 struct rmap_item **rmap_list;
109 * struct stable_node - node of the stable rbtree
110 * @node: rb node of this ksm page in the stable tree
111 * @hlist: hlist head of rmap_items using this ksm page
115 struct hlist_head hlist;
119 * struct rmap_item - reverse mapping item for virtual addresses
120 * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
121 * @filler: unused space we're making available in this patch
122 * @mm: the memory structure this rmap_item is pointing into
123 * @address: the virtual address this rmap_item tracks (+ flags in low bits)
124 * @oldchecksum: previous checksum of the page at that virtual address
125 * @node: rb node of this rmap_item in the unstable tree
126 * @head: pointer to stable_node heading this list in the stable tree
127 * @hlist: link into hlist of rmap_items hanging off that stable_node
130 struct rmap_item *rmap_list;
131 unsigned long filler;
132 struct mm_struct *mm;
133 unsigned long address; /* + low bits used for flags below */
134 unsigned int oldchecksum; /* when unstable */
136 struct rb_node node; /* when node of unstable tree */
137 struct { /* when listed from stable tree */
138 struct stable_node *head;
139 struct hlist_node hlist;
144 #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
145 #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
146 #define STABLE_FLAG 0x200 /* is listed from the stable tree */
148 /* The stable and unstable tree heads */
149 static struct rb_root root_stable_tree = RB_ROOT;
150 static struct rb_root root_unstable_tree = RB_ROOT;
152 #define MM_SLOTS_HASH_HEADS 1024
153 static struct hlist_head *mm_slots_hash;
155 static struct mm_slot ksm_mm_head = {
156 .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
158 static struct ksm_scan ksm_scan = {
159 .mm_slot = &ksm_mm_head,
162 static struct kmem_cache *rmap_item_cache;
163 static struct kmem_cache *stable_node_cache;
164 static struct kmem_cache *mm_slot_cache;
166 /* The number of nodes in the stable tree */
167 static unsigned long ksm_pages_shared;
169 /* The number of page slots additionally sharing those nodes */
170 static unsigned long ksm_pages_sharing;
172 /* The number of nodes in the unstable tree */
173 static unsigned long ksm_pages_unshared;
175 /* The number of rmap_items in use: to calculate pages_volatile */
176 static unsigned long ksm_rmap_items;
178 /* Limit on the number of unswappable pages used */
179 static unsigned long ksm_max_kernel_pages;
181 /* Number of pages ksmd should scan in one batch */
182 static unsigned int ksm_thread_pages_to_scan = 100;
184 /* Milliseconds ksmd should sleep between batches */
185 static unsigned int ksm_thread_sleep_millisecs = 20;
187 #define KSM_RUN_STOP 0
188 #define KSM_RUN_MERGE 1
189 #define KSM_RUN_UNMERGE 2
190 static unsigned int ksm_run = KSM_RUN_STOP;
192 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
193 static DEFINE_MUTEX(ksm_thread_mutex);
194 static DEFINE_SPINLOCK(ksm_mmlist_lock);
196 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
197 sizeof(struct __struct), __alignof__(struct __struct),\
200 static int __init ksm_slab_init(void)
202 rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
203 if (!rmap_item_cache)
206 stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
207 if (!stable_node_cache)
210 mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
217 kmem_cache_destroy(stable_node_cache);
219 kmem_cache_destroy(rmap_item_cache);
224 static void __init ksm_slab_free(void)
226 kmem_cache_destroy(mm_slot_cache);
227 kmem_cache_destroy(stable_node_cache);
228 kmem_cache_destroy(rmap_item_cache);
229 mm_slot_cache = NULL;
232 static inline struct rmap_item *alloc_rmap_item(void)
234 struct rmap_item *rmap_item;
236 rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL);
242 static inline void free_rmap_item(struct rmap_item *rmap_item)
245 rmap_item->mm = NULL; /* debug safety */
246 kmem_cache_free(rmap_item_cache, rmap_item);
249 static inline struct stable_node *alloc_stable_node(void)
251 return kmem_cache_alloc(stable_node_cache, GFP_KERNEL);
254 static inline void free_stable_node(struct stable_node *stable_node)
256 kmem_cache_free(stable_node_cache, stable_node);
259 static inline struct mm_slot *alloc_mm_slot(void)
261 if (!mm_slot_cache) /* initialization failed */
263 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
266 static inline void free_mm_slot(struct mm_slot *mm_slot)
268 kmem_cache_free(mm_slot_cache, mm_slot);
271 static int __init mm_slots_hash_init(void)
273 mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
280 static void __init mm_slots_hash_free(void)
282 kfree(mm_slots_hash);
285 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
287 struct mm_slot *mm_slot;
288 struct hlist_head *bucket;
289 struct hlist_node *node;
291 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
292 % MM_SLOTS_HASH_HEADS];
293 hlist_for_each_entry(mm_slot, node, bucket, link) {
294 if (mm == mm_slot->mm)
300 static void insert_to_mm_slots_hash(struct mm_struct *mm,
301 struct mm_slot *mm_slot)
303 struct hlist_head *bucket;
305 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
306 % MM_SLOTS_HASH_HEADS];
308 hlist_add_head(&mm_slot->link, bucket);
311 static inline int in_stable_tree(struct rmap_item *rmap_item)
313 return rmap_item->address & STABLE_FLAG;
317 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
318 * page tables after it has passed through ksm_exit() - which, if necessary,
319 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
320 * a special flag: they can just back out as soon as mm_users goes to zero.
321 * ksm_test_exit() is used throughout to make this test for exit: in some
322 * places for correctness, in some places just to avoid unnecessary work.
324 static inline bool ksm_test_exit(struct mm_struct *mm)
326 return atomic_read(&mm->mm_users) == 0;
330 * We use break_ksm to break COW on a ksm page: it's a stripped down
332 * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
335 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
336 * in case the application has unmapped and remapped mm,addr meanwhile.
337 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
338 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
340 static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
347 page = follow_page(vma, addr, FOLL_GET);
351 ret = handle_mm_fault(vma->vm_mm, vma, addr,
354 ret = VM_FAULT_WRITE;
356 } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_OOM)));
358 * We must loop because handle_mm_fault() may back out if there's
359 * any difficulty e.g. if pte accessed bit gets updated concurrently.
361 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
362 * COW has been broken, even if the vma does not permit VM_WRITE;
363 * but note that a concurrent fault might break PageKsm for us.
365 * VM_FAULT_SIGBUS could occur if we race with truncation of the
366 * backing file, which also invalidates anonymous pages: that's
367 * okay, that truncation will have unmapped the PageKsm for us.
369 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
370 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
371 * current task has TIF_MEMDIE set, and will be OOM killed on return
372 * to user; and ksmd, having no mm, would never be chosen for that.
374 * But if the mm is in a limited mem_cgroup, then the fault may fail
375 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
376 * even ksmd can fail in this way - though it's usually breaking ksm
377 * just to undo a merge it made a moment before, so unlikely to oom.
379 * That's a pity: we might therefore have more kernel pages allocated
380 * than we're counting as nodes in the stable tree; but ksm_do_scan
381 * will retry to break_cow on each pass, so should recover the page
382 * in due course. The important thing is to not let VM_MERGEABLE
383 * be cleared while any such pages might remain in the area.
385 return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
388 static void break_cow(struct rmap_item *rmap_item)
390 struct mm_struct *mm = rmap_item->mm;
391 unsigned long addr = rmap_item->address;
392 struct vm_area_struct *vma;
394 down_read(&mm->mmap_sem);
395 if (ksm_test_exit(mm))
397 vma = find_vma(mm, addr);
398 if (!vma || vma->vm_start > addr)
400 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
402 break_ksm(vma, addr);
404 up_read(&mm->mmap_sem);
407 static struct page *get_mergeable_page(struct rmap_item *rmap_item)
409 struct mm_struct *mm = rmap_item->mm;
410 unsigned long addr = rmap_item->address;
411 struct vm_area_struct *vma;
414 down_read(&mm->mmap_sem);
415 if (ksm_test_exit(mm))
417 vma = find_vma(mm, addr);
418 if (!vma || vma->vm_start > addr)
420 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
423 page = follow_page(vma, addr, FOLL_GET);
426 if (PageAnon(page)) {
427 flush_anon_page(vma, page, addr);
428 flush_dcache_page(page);
433 up_read(&mm->mmap_sem);
438 * get_ksm_page: checks if the page at the virtual address in rmap_item
439 * is still PageKsm, in which case we can trust the content of the page,
440 * and it returns the gotten page; but NULL if the page has been zapped.
442 static struct page *get_ksm_page(struct rmap_item *rmap_item)
446 page = get_mergeable_page(rmap_item);
447 if (page && !PageKsm(page)) {
455 * Removing rmap_item from stable or unstable tree.
456 * This function will clean the information from the stable/unstable tree.
458 static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
460 if (rmap_item->address & STABLE_FLAG) {
461 struct stable_node *stable_node;
463 stable_node = rmap_item->head;
464 hlist_del(&rmap_item->hlist);
465 if (stable_node->hlist.first)
468 rb_erase(&stable_node->node, &root_stable_tree);
469 free_stable_node(stable_node);
473 rmap_item->address &= PAGE_MASK;
475 } else if (rmap_item->address & UNSTABLE_FLAG) {
478 * Usually ksmd can and must skip the rb_erase, because
479 * root_unstable_tree was already reset to RB_ROOT.
480 * But be careful when an mm is exiting: do the rb_erase
481 * if this rmap_item was inserted by this scan, rather
482 * than left over from before.
484 age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
487 rb_erase(&rmap_item->node, &root_unstable_tree);
489 ksm_pages_unshared--;
490 rmap_item->address &= PAGE_MASK;
493 cond_resched(); /* we're called from many long loops */
496 static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
497 struct rmap_item **rmap_list)
500 struct rmap_item *rmap_item = *rmap_list;
501 *rmap_list = rmap_item->rmap_list;
502 remove_rmap_item_from_tree(rmap_item);
503 free_rmap_item(rmap_item);
508 * Though it's very tempting to unmerge in_stable_tree(rmap_item)s rather
509 * than check every pte of a given vma, the locking doesn't quite work for
510 * that - an rmap_item is assigned to the stable tree after inserting ksm
511 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
512 * rmap_items from parent to child at fork time (so as not to waste time
513 * if exit comes before the next scan reaches it).
515 * Similarly, although we'd like to remove rmap_items (so updating counts
516 * and freeing memory) when unmerging an area, it's easier to leave that
517 * to the next pass of ksmd - consider, for example, how ksmd might be
518 * in cmp_and_merge_page on one of the rmap_items we would be removing.
520 static int unmerge_ksm_pages(struct vm_area_struct *vma,
521 unsigned long start, unsigned long end)
526 for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
527 if (ksm_test_exit(vma->vm_mm))
529 if (signal_pending(current))
532 err = break_ksm(vma, addr);
539 * Only called through the sysfs control interface:
541 static int unmerge_and_remove_all_rmap_items(void)
543 struct mm_slot *mm_slot;
544 struct mm_struct *mm;
545 struct vm_area_struct *vma;
548 spin_lock(&ksm_mmlist_lock);
549 ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
550 struct mm_slot, mm_list);
551 spin_unlock(&ksm_mmlist_lock);
553 for (mm_slot = ksm_scan.mm_slot;
554 mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
556 down_read(&mm->mmap_sem);
557 for (vma = mm->mmap; vma; vma = vma->vm_next) {
558 if (ksm_test_exit(mm))
560 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
562 err = unmerge_ksm_pages(vma,
563 vma->vm_start, vma->vm_end);
568 remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
570 spin_lock(&ksm_mmlist_lock);
571 ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
572 struct mm_slot, mm_list);
573 if (ksm_test_exit(mm)) {
574 hlist_del(&mm_slot->link);
575 list_del(&mm_slot->mm_list);
576 spin_unlock(&ksm_mmlist_lock);
578 free_mm_slot(mm_slot);
579 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
580 up_read(&mm->mmap_sem);
583 spin_unlock(&ksm_mmlist_lock);
584 up_read(&mm->mmap_sem);
592 up_read(&mm->mmap_sem);
593 spin_lock(&ksm_mmlist_lock);
594 ksm_scan.mm_slot = &ksm_mm_head;
595 spin_unlock(&ksm_mmlist_lock);
598 #endif /* CONFIG_SYSFS */
600 static u32 calc_checksum(struct page *page)
603 void *addr = kmap_atomic(page, KM_USER0);
604 checksum = jhash2(addr, PAGE_SIZE / 4, 17);
605 kunmap_atomic(addr, KM_USER0);
609 static int memcmp_pages(struct page *page1, struct page *page2)
614 addr1 = kmap_atomic(page1, KM_USER0);
615 addr2 = kmap_atomic(page2, KM_USER1);
616 ret = memcmp(addr1, addr2, PAGE_SIZE);
617 kunmap_atomic(addr2, KM_USER1);
618 kunmap_atomic(addr1, KM_USER0);
622 static inline int pages_identical(struct page *page1, struct page *page2)
624 return !memcmp_pages(page1, page2);
627 static int write_protect_page(struct vm_area_struct *vma, struct page *page,
630 struct mm_struct *mm = vma->vm_mm;
637 addr = page_address_in_vma(page, vma);
641 ptep = page_check_address(page, mm, addr, &ptl, 0);
645 if (pte_write(*ptep)) {
648 swapped = PageSwapCache(page);
649 flush_cache_page(vma, addr, page_to_pfn(page));
651 * Ok this is tricky, when get_user_pages_fast() run it doesnt
652 * take any lock, therefore the check that we are going to make
653 * with the pagecount against the mapcount is racey and
654 * O_DIRECT can happen right after the check.
655 * So we clear the pte and flush the tlb before the check
656 * this assure us that no O_DIRECT can happen after the check
657 * or in the middle of the check.
659 entry = ptep_clear_flush(vma, addr, ptep);
661 * Check that no O_DIRECT or similar I/O is in progress on the
664 if (page_mapcount(page) + 1 + swapped != page_count(page)) {
665 set_pte_at_notify(mm, addr, ptep, entry);
668 entry = pte_wrprotect(entry);
669 set_pte_at_notify(mm, addr, ptep, entry);
675 pte_unmap_unlock(ptep, ptl);
681 * replace_page - replace page in vma by new ksm page
682 * @vma: vma that holds the pte pointing to page
683 * @page: the page we are replacing by kpage
684 * @kpage: the ksm page we replace page by
685 * @orig_pte: the original value of the pte
687 * Returns 0 on success, -EFAULT on failure.
689 static int replace_page(struct vm_area_struct *vma, struct page *page,
690 struct page *kpage, pte_t orig_pte)
692 struct mm_struct *mm = vma->vm_mm;
701 addr = page_address_in_vma(page, vma);
705 pgd = pgd_offset(mm, addr);
706 if (!pgd_present(*pgd))
709 pud = pud_offset(pgd, addr);
710 if (!pud_present(*pud))
713 pmd = pmd_offset(pud, addr);
714 if (!pmd_present(*pmd))
717 ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
718 if (!pte_same(*ptep, orig_pte)) {
719 pte_unmap_unlock(ptep, ptl);
724 page_add_ksm_rmap(kpage);
726 flush_cache_page(vma, addr, pte_pfn(*ptep));
727 ptep_clear_flush(vma, addr, ptep);
728 set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
730 page_remove_rmap(page);
733 pte_unmap_unlock(ptep, ptl);
740 * try_to_merge_one_page - take two pages and merge them into one
741 * @vma: the vma that holds the pte pointing to page
742 * @page: the PageAnon page that we want to replace with kpage
743 * @kpage: the PageKsm page (or newly allocated page which page_add_ksm_rmap
744 * will make PageKsm) that we want to map instead of page
746 * This function returns 0 if the pages were merged, -EFAULT otherwise.
748 static int try_to_merge_one_page(struct vm_area_struct *vma,
749 struct page *page, struct page *kpage)
751 pte_t orig_pte = __pte(0);
754 if (!(vma->vm_flags & VM_MERGEABLE))
760 * We need the page lock to read a stable PageSwapCache in
761 * write_protect_page(). We use trylock_page() instead of
762 * lock_page() because we don't want to wait here - we
763 * prefer to continue scanning and merging different pages,
764 * then come back to this page when it is unlocked.
766 if (!trylock_page(page))
769 * If this anonymous page is mapped only here, its pte may need
770 * to be write-protected. If it's mapped elsewhere, all of its
771 * ptes are necessarily already write-protected. But in either
772 * case, we need to lock and check page_count is not raised.
774 if (write_protect_page(vma, page, &orig_pte) == 0 &&
775 pages_identical(page, kpage))
776 err = replace_page(vma, page, kpage, orig_pte);
784 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
785 * but no new kernel page is allocated: kpage must already be a ksm page.
787 * This function returns 0 if the pages were merged, -EFAULT otherwise.
789 static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
790 struct page *page, struct page *kpage)
792 struct mm_struct *mm = rmap_item->mm;
793 struct vm_area_struct *vma;
796 down_read(&mm->mmap_sem);
797 if (ksm_test_exit(mm))
799 vma = find_vma(mm, rmap_item->address);
800 if (!vma || vma->vm_start > rmap_item->address)
803 err = try_to_merge_one_page(vma, page, kpage);
805 up_read(&mm->mmap_sem);
810 * try_to_merge_two_pages - take two identical pages and prepare them
811 * to be merged into one page.
813 * This function returns the kpage if we successfully merged two identical
814 * pages into one ksm page, NULL otherwise.
816 * Note that this function allocates a new kernel page: if one of the pages
817 * is already a ksm page, try_to_merge_with_ksm_page should be used.
819 static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
821 struct rmap_item *tree_rmap_item,
822 struct page *tree_page)
824 struct mm_struct *mm = rmap_item->mm;
825 struct vm_area_struct *vma;
830 * The number of nodes in the stable tree
831 * is the number of kernel pages that we hold.
833 if (ksm_max_kernel_pages &&
834 ksm_max_kernel_pages <= ksm_pages_shared)
837 kpage = alloc_page(GFP_HIGHUSER);
841 down_read(&mm->mmap_sem);
842 if (ksm_test_exit(mm))
844 vma = find_vma(mm, rmap_item->address);
845 if (!vma || vma->vm_start > rmap_item->address)
848 copy_user_highpage(kpage, page, rmap_item->address, vma);
849 err = try_to_merge_one_page(vma, page, kpage);
851 up_read(&mm->mmap_sem);
854 err = try_to_merge_with_ksm_page(tree_rmap_item,
857 * If that fails, we have a ksm page with only one pte
858 * pointing to it: so break it.
861 break_cow(rmap_item);
871 * stable_tree_search - search for page inside the stable tree
873 * This function checks if there is a page inside the stable tree
874 * with identical content to the page that we are scanning right now.
876 * This function returns the stable tree node of identical content if found,
879 static struct stable_node *stable_tree_search(struct page *page,
880 struct page **tree_pagep)
882 struct rb_node *node = root_stable_tree.rb_node;
883 struct stable_node *stable_node;
886 struct hlist_node *hlist, *hnext;
887 struct rmap_item *tree_rmap_item;
888 struct page *tree_page;
891 stable_node = rb_entry(node, struct stable_node, node);
892 hlist_for_each_entry_safe(tree_rmap_item, hlist, hnext,
893 &stable_node->hlist, hlist) {
894 BUG_ON(!in_stable_tree(tree_rmap_item));
896 tree_page = get_ksm_page(tree_rmap_item);
899 remove_rmap_item_from_tree(tree_rmap_item);
904 ret = memcmp_pages(page, tree_page);
908 node = node->rb_left;
909 } else if (ret > 0) {
911 node = node->rb_right;
913 *tree_pagep = tree_page;
922 * stable_tree_insert - insert rmap_item pointing to new ksm page
923 * into the stable tree.
925 * This function returns the stable tree node just allocated on success,
928 static struct stable_node *stable_tree_insert(struct page *kpage)
930 struct rb_node **new = &root_stable_tree.rb_node;
931 struct rb_node *parent = NULL;
932 struct stable_node *stable_node;
935 struct hlist_node *hlist, *hnext;
936 struct rmap_item *tree_rmap_item;
937 struct page *tree_page;
940 stable_node = rb_entry(*new, struct stable_node, node);
941 hlist_for_each_entry_safe(tree_rmap_item, hlist, hnext,
942 &stable_node->hlist, hlist) {
943 BUG_ON(!in_stable_tree(tree_rmap_item));
945 tree_page = get_ksm_page(tree_rmap_item);
948 remove_rmap_item_from_tree(tree_rmap_item);
953 ret = memcmp_pages(kpage, tree_page);
958 new = &parent->rb_left;
960 new = &parent->rb_right;
963 * It is not a bug that stable_tree_search() didn't
964 * find this node: because at that time our page was
965 * not yet write-protected, so may have changed since.
971 stable_node = alloc_stable_node();
975 rb_link_node(&stable_node->node, parent, new);
976 rb_insert_color(&stable_node->node, &root_stable_tree);
978 INIT_HLIST_HEAD(&stable_node->hlist);
984 * unstable_tree_search_insert - search for identical page,
985 * else insert rmap_item into the unstable tree.
987 * This function searches for a page in the unstable tree identical to the
988 * page currently being scanned; and if no identical page is found in the
989 * tree, we insert rmap_item as a new object into the unstable tree.
991 * This function returns pointer to rmap_item found to be identical
992 * to the currently scanned page, NULL otherwise.
994 * This function does both searching and inserting, because they share
995 * the same walking algorithm in an rbtree.
998 struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
1000 struct page **tree_pagep)
1003 struct rb_node **new = &root_unstable_tree.rb_node;
1004 struct rb_node *parent = NULL;
1007 struct rmap_item *tree_rmap_item;
1008 struct page *tree_page;
1012 tree_rmap_item = rb_entry(*new, struct rmap_item, node);
1013 tree_page = get_mergeable_page(tree_rmap_item);
1018 * Don't substitute a ksm page for a forked page.
1020 if (page == tree_page) {
1021 put_page(tree_page);
1025 ret = memcmp_pages(page, tree_page);
1029 put_page(tree_page);
1030 new = &parent->rb_left;
1031 } else if (ret > 0) {
1032 put_page(tree_page);
1033 new = &parent->rb_right;
1035 *tree_pagep = tree_page;
1036 return tree_rmap_item;
1040 rmap_item->address |= UNSTABLE_FLAG;
1041 rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
1042 rb_link_node(&rmap_item->node, parent, new);
1043 rb_insert_color(&rmap_item->node, &root_unstable_tree);
1045 ksm_pages_unshared++;
1050 * stable_tree_append - add another rmap_item to the linked list of
1051 * rmap_items hanging off a given node of the stable tree, all sharing
1052 * the same ksm page.
1054 static void stable_tree_append(struct rmap_item *rmap_item,
1055 struct stable_node *stable_node)
1057 rmap_item->head = stable_node;
1058 rmap_item->address |= STABLE_FLAG;
1059 hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
1061 if (rmap_item->hlist.next)
1062 ksm_pages_sharing++;
1068 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1069 * if not, compare checksum to previous and if it's the same, see if page can
1070 * be inserted into the unstable tree, or merged with a page already there and
1071 * both transferred to the stable tree.
1073 * @page: the page that we are searching identical page to.
1074 * @rmap_item: the reverse mapping into the virtual address of this page
1076 static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
1078 struct rmap_item *tree_rmap_item;
1079 struct page *tree_page = NULL;
1080 struct stable_node *stable_node;
1082 unsigned int checksum;
1085 remove_rmap_item_from_tree(rmap_item);
1087 /* We first start with searching the page inside the stable tree */
1088 stable_node = stable_tree_search(page, &tree_page);
1091 if (page == kpage) /* forked */
1094 err = try_to_merge_with_ksm_page(rmap_item,
1098 * The page was successfully merged:
1099 * add its rmap_item to the stable tree.
1101 stable_tree_append(rmap_item, stable_node);
1108 * A ksm page might have got here by fork, but its other
1109 * references have already been removed from the stable tree.
1110 * Or it might be left over from a break_ksm which failed
1111 * when the mem_cgroup had reached its limit: try again now.
1114 break_cow(rmap_item);
1117 * In case the hash value of the page was changed from the last time we
1118 * have calculated it, this page to be changed frequely, therefore we
1119 * don't want to insert it to the unstable tree, and we don't want to
1120 * waste our time to search if there is something identical to it there.
1122 checksum = calc_checksum(page);
1123 if (rmap_item->oldchecksum != checksum) {
1124 rmap_item->oldchecksum = checksum;
1129 unstable_tree_search_insert(rmap_item, page, &tree_page);
1130 if (tree_rmap_item) {
1131 kpage = try_to_merge_two_pages(rmap_item, page,
1132 tree_rmap_item, tree_page);
1133 put_page(tree_page);
1135 * As soon as we merge this page, we want to remove the
1136 * rmap_item of the page we have merged with from the unstable
1137 * tree, and insert it instead as new node in the stable tree.
1140 remove_rmap_item_from_tree(tree_rmap_item);
1142 stable_node = stable_tree_insert(kpage);
1144 stable_tree_append(tree_rmap_item, stable_node);
1145 stable_tree_append(rmap_item, stable_node);
1150 * If we fail to insert the page into the stable tree,
1151 * we will have 2 virtual addresses that are pointing
1152 * to a ksm page left outside the stable tree,
1153 * in which case we need to break_cow on both.
1156 break_cow(tree_rmap_item);
1157 break_cow(rmap_item);
1163 static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
1164 struct rmap_item **rmap_list,
1167 struct rmap_item *rmap_item;
1169 while (*rmap_list) {
1170 rmap_item = *rmap_list;
1171 if ((rmap_item->address & PAGE_MASK) == addr)
1173 if (rmap_item->address > addr)
1175 *rmap_list = rmap_item->rmap_list;
1176 remove_rmap_item_from_tree(rmap_item);
1177 free_rmap_item(rmap_item);
1180 rmap_item = alloc_rmap_item();
1182 /* It has already been zeroed */
1183 rmap_item->mm = mm_slot->mm;
1184 rmap_item->address = addr;
1185 rmap_item->rmap_list = *rmap_list;
1186 *rmap_list = rmap_item;
1191 static struct rmap_item *scan_get_next_rmap_item(struct page **page)
1193 struct mm_struct *mm;
1194 struct mm_slot *slot;
1195 struct vm_area_struct *vma;
1196 struct rmap_item *rmap_item;
1198 if (list_empty(&ksm_mm_head.mm_list))
1201 slot = ksm_scan.mm_slot;
1202 if (slot == &ksm_mm_head) {
1203 root_unstable_tree = RB_ROOT;
1205 spin_lock(&ksm_mmlist_lock);
1206 slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
1207 ksm_scan.mm_slot = slot;
1208 spin_unlock(&ksm_mmlist_lock);
1210 ksm_scan.address = 0;
1211 ksm_scan.rmap_list = &slot->rmap_list;
1215 down_read(&mm->mmap_sem);
1216 if (ksm_test_exit(mm))
1219 vma = find_vma(mm, ksm_scan.address);
1221 for (; vma; vma = vma->vm_next) {
1222 if (!(vma->vm_flags & VM_MERGEABLE))
1224 if (ksm_scan.address < vma->vm_start)
1225 ksm_scan.address = vma->vm_start;
1227 ksm_scan.address = vma->vm_end;
1229 while (ksm_scan.address < vma->vm_end) {
1230 if (ksm_test_exit(mm))
1232 *page = follow_page(vma, ksm_scan.address, FOLL_GET);
1233 if (*page && PageAnon(*page)) {
1234 flush_anon_page(vma, *page, ksm_scan.address);
1235 flush_dcache_page(*page);
1236 rmap_item = get_next_rmap_item(slot,
1237 ksm_scan.rmap_list, ksm_scan.address);
1239 ksm_scan.rmap_list =
1240 &rmap_item->rmap_list;
1241 ksm_scan.address += PAGE_SIZE;
1244 up_read(&mm->mmap_sem);
1249 ksm_scan.address += PAGE_SIZE;
1254 if (ksm_test_exit(mm)) {
1255 ksm_scan.address = 0;
1256 ksm_scan.rmap_list = &slot->rmap_list;
1259 * Nuke all the rmap_items that are above this current rmap:
1260 * because there were no VM_MERGEABLE vmas with such addresses.
1262 remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
1264 spin_lock(&ksm_mmlist_lock);
1265 ksm_scan.mm_slot = list_entry(slot->mm_list.next,
1266 struct mm_slot, mm_list);
1267 if (ksm_scan.address == 0) {
1269 * We've completed a full scan of all vmas, holding mmap_sem
1270 * throughout, and found no VM_MERGEABLE: so do the same as
1271 * __ksm_exit does to remove this mm from all our lists now.
1272 * This applies either when cleaning up after __ksm_exit
1273 * (but beware: we can reach here even before __ksm_exit),
1274 * or when all VM_MERGEABLE areas have been unmapped (and
1275 * mmap_sem then protects against race with MADV_MERGEABLE).
1277 hlist_del(&slot->link);
1278 list_del(&slot->mm_list);
1279 spin_unlock(&ksm_mmlist_lock);
1282 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1283 up_read(&mm->mmap_sem);
1286 spin_unlock(&ksm_mmlist_lock);
1287 up_read(&mm->mmap_sem);
1290 /* Repeat until we've completed scanning the whole list */
1291 slot = ksm_scan.mm_slot;
1292 if (slot != &ksm_mm_head)
1300 * ksm_do_scan - the ksm scanner main worker function.
1301 * @scan_npages - number of pages we want to scan before we return.
1303 static void ksm_do_scan(unsigned int scan_npages)
1305 struct rmap_item *rmap_item;
1308 while (scan_npages--) {
1310 rmap_item = scan_get_next_rmap_item(&page);
1313 if (!PageKsm(page) || !in_stable_tree(rmap_item))
1314 cmp_and_merge_page(page, rmap_item);
1315 else if (page_mapcount(page) == 1) {
1317 * Replace now-unshared ksm page by ordinary page.
1319 break_cow(rmap_item);
1320 remove_rmap_item_from_tree(rmap_item);
1321 rmap_item->oldchecksum = calc_checksum(page);
1327 static int ksmd_should_run(void)
1329 return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
1332 static int ksm_scan_thread(void *nothing)
1334 set_user_nice(current, 5);
1336 while (!kthread_should_stop()) {
1337 mutex_lock(&ksm_thread_mutex);
1338 if (ksmd_should_run())
1339 ksm_do_scan(ksm_thread_pages_to_scan);
1340 mutex_unlock(&ksm_thread_mutex);
1342 if (ksmd_should_run()) {
1343 schedule_timeout_interruptible(
1344 msecs_to_jiffies(ksm_thread_sleep_millisecs));
1346 wait_event_interruptible(ksm_thread_wait,
1347 ksmd_should_run() || kthread_should_stop());
1353 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
1354 unsigned long end, int advice, unsigned long *vm_flags)
1356 struct mm_struct *mm = vma->vm_mm;
1360 case MADV_MERGEABLE:
1362 * Be somewhat over-protective for now!
1364 if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
1365 VM_PFNMAP | VM_IO | VM_DONTEXPAND |
1366 VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
1367 VM_MIXEDMAP | VM_SAO))
1368 return 0; /* just ignore the advice */
1370 if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
1371 err = __ksm_enter(mm);
1376 *vm_flags |= VM_MERGEABLE;
1379 case MADV_UNMERGEABLE:
1380 if (!(*vm_flags & VM_MERGEABLE))
1381 return 0; /* just ignore the advice */
1383 if (vma->anon_vma) {
1384 err = unmerge_ksm_pages(vma, start, end);
1389 *vm_flags &= ~VM_MERGEABLE;
1396 int __ksm_enter(struct mm_struct *mm)
1398 struct mm_slot *mm_slot;
1401 mm_slot = alloc_mm_slot();
1405 /* Check ksm_run too? Would need tighter locking */
1406 needs_wakeup = list_empty(&ksm_mm_head.mm_list);
1408 spin_lock(&ksm_mmlist_lock);
1409 insert_to_mm_slots_hash(mm, mm_slot);
1411 * Insert just behind the scanning cursor, to let the area settle
1412 * down a little; when fork is followed by immediate exec, we don't
1413 * want ksmd to waste time setting up and tearing down an rmap_list.
1415 list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
1416 spin_unlock(&ksm_mmlist_lock);
1418 set_bit(MMF_VM_MERGEABLE, &mm->flags);
1419 atomic_inc(&mm->mm_count);
1422 wake_up_interruptible(&ksm_thread_wait);
1427 void __ksm_exit(struct mm_struct *mm)
1429 struct mm_slot *mm_slot;
1430 int easy_to_free = 0;
1433 * This process is exiting: if it's straightforward (as is the
1434 * case when ksmd was never running), free mm_slot immediately.
1435 * But if it's at the cursor or has rmap_items linked to it, use
1436 * mmap_sem to synchronize with any break_cows before pagetables
1437 * are freed, and leave the mm_slot on the list for ksmd to free.
1438 * Beware: ksm may already have noticed it exiting and freed the slot.
1441 spin_lock(&ksm_mmlist_lock);
1442 mm_slot = get_mm_slot(mm);
1443 if (mm_slot && ksm_scan.mm_slot != mm_slot) {
1444 if (!mm_slot->rmap_list) {
1445 hlist_del(&mm_slot->link);
1446 list_del(&mm_slot->mm_list);
1449 list_move(&mm_slot->mm_list,
1450 &ksm_scan.mm_slot->mm_list);
1453 spin_unlock(&ksm_mmlist_lock);
1456 free_mm_slot(mm_slot);
1457 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1459 } else if (mm_slot) {
1460 down_write(&mm->mmap_sem);
1461 up_write(&mm->mmap_sem);
1467 * This all compiles without CONFIG_SYSFS, but is a waste of space.
1470 #define KSM_ATTR_RO(_name) \
1471 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
1472 #define KSM_ATTR(_name) \
1473 static struct kobj_attribute _name##_attr = \
1474 __ATTR(_name, 0644, _name##_show, _name##_store)
1476 static ssize_t sleep_millisecs_show(struct kobject *kobj,
1477 struct kobj_attribute *attr, char *buf)
1479 return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
1482 static ssize_t sleep_millisecs_store(struct kobject *kobj,
1483 struct kobj_attribute *attr,
1484 const char *buf, size_t count)
1486 unsigned long msecs;
1489 err = strict_strtoul(buf, 10, &msecs);
1490 if (err || msecs > UINT_MAX)
1493 ksm_thread_sleep_millisecs = msecs;
1497 KSM_ATTR(sleep_millisecs);
1499 static ssize_t pages_to_scan_show(struct kobject *kobj,
1500 struct kobj_attribute *attr, char *buf)
1502 return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
1505 static ssize_t pages_to_scan_store(struct kobject *kobj,
1506 struct kobj_attribute *attr,
1507 const char *buf, size_t count)
1510 unsigned long nr_pages;
1512 err = strict_strtoul(buf, 10, &nr_pages);
1513 if (err || nr_pages > UINT_MAX)
1516 ksm_thread_pages_to_scan = nr_pages;
1520 KSM_ATTR(pages_to_scan);
1522 static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
1525 return sprintf(buf, "%u\n", ksm_run);
1528 static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
1529 const char *buf, size_t count)
1532 unsigned long flags;
1534 err = strict_strtoul(buf, 10, &flags);
1535 if (err || flags > UINT_MAX)
1537 if (flags > KSM_RUN_UNMERGE)
1541 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
1542 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
1543 * breaking COW to free the unswappable pages_shared (but leaves
1544 * mm_slots on the list for when ksmd may be set running again).
1547 mutex_lock(&ksm_thread_mutex);
1548 if (ksm_run != flags) {
1550 if (flags & KSM_RUN_UNMERGE) {
1551 current->flags |= PF_OOM_ORIGIN;
1552 err = unmerge_and_remove_all_rmap_items();
1553 current->flags &= ~PF_OOM_ORIGIN;
1555 ksm_run = KSM_RUN_STOP;
1560 mutex_unlock(&ksm_thread_mutex);
1562 if (flags & KSM_RUN_MERGE)
1563 wake_up_interruptible(&ksm_thread_wait);
1569 static ssize_t max_kernel_pages_store(struct kobject *kobj,
1570 struct kobj_attribute *attr,
1571 const char *buf, size_t count)
1574 unsigned long nr_pages;
1576 err = strict_strtoul(buf, 10, &nr_pages);
1580 ksm_max_kernel_pages = nr_pages;
1585 static ssize_t max_kernel_pages_show(struct kobject *kobj,
1586 struct kobj_attribute *attr, char *buf)
1588 return sprintf(buf, "%lu\n", ksm_max_kernel_pages);
1590 KSM_ATTR(max_kernel_pages);
1592 static ssize_t pages_shared_show(struct kobject *kobj,
1593 struct kobj_attribute *attr, char *buf)
1595 return sprintf(buf, "%lu\n", ksm_pages_shared);
1597 KSM_ATTR_RO(pages_shared);
1599 static ssize_t pages_sharing_show(struct kobject *kobj,
1600 struct kobj_attribute *attr, char *buf)
1602 return sprintf(buf, "%lu\n", ksm_pages_sharing);
1604 KSM_ATTR_RO(pages_sharing);
1606 static ssize_t pages_unshared_show(struct kobject *kobj,
1607 struct kobj_attribute *attr, char *buf)
1609 return sprintf(buf, "%lu\n", ksm_pages_unshared);
1611 KSM_ATTR_RO(pages_unshared);
1613 static ssize_t pages_volatile_show(struct kobject *kobj,
1614 struct kobj_attribute *attr, char *buf)
1616 long ksm_pages_volatile;
1618 ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
1619 - ksm_pages_sharing - ksm_pages_unshared;
1621 * It was not worth any locking to calculate that statistic,
1622 * but it might therefore sometimes be negative: conceal that.
1624 if (ksm_pages_volatile < 0)
1625 ksm_pages_volatile = 0;
1626 return sprintf(buf, "%ld\n", ksm_pages_volatile);
1628 KSM_ATTR_RO(pages_volatile);
1630 static ssize_t full_scans_show(struct kobject *kobj,
1631 struct kobj_attribute *attr, char *buf)
1633 return sprintf(buf, "%lu\n", ksm_scan.seqnr);
1635 KSM_ATTR_RO(full_scans);
1637 static struct attribute *ksm_attrs[] = {
1638 &sleep_millisecs_attr.attr,
1639 &pages_to_scan_attr.attr,
1641 &max_kernel_pages_attr.attr,
1642 &pages_shared_attr.attr,
1643 &pages_sharing_attr.attr,
1644 &pages_unshared_attr.attr,
1645 &pages_volatile_attr.attr,
1646 &full_scans_attr.attr,
1650 static struct attribute_group ksm_attr_group = {
1654 #endif /* CONFIG_SYSFS */
1656 static int __init ksm_init(void)
1658 struct task_struct *ksm_thread;
1661 ksm_max_kernel_pages = totalram_pages / 4;
1663 err = ksm_slab_init();
1667 err = mm_slots_hash_init();
1671 ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
1672 if (IS_ERR(ksm_thread)) {
1673 printk(KERN_ERR "ksm: creating kthread failed\n");
1674 err = PTR_ERR(ksm_thread);
1679 err = sysfs_create_group(mm_kobj, &ksm_attr_group);
1681 printk(KERN_ERR "ksm: register sysfs failed\n");
1682 kthread_stop(ksm_thread);
1686 ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
1688 #endif /* CONFIG_SYSFS */
1693 mm_slots_hash_free();
1699 module_init(ksm_init)