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/memory.h>
33 #include <linux/mmu_notifier.h>
34 #include <linux/swap.h>
35 #include <linux/ksm.h>
36 #include <linux/hashtable.h>
37 #include <linux/freezer.h>
38 #include <linux/oom.h>
39 #include <linux/numa.h>
41 #include <asm/tlbflush.h>
45 * A few notes about the KSM scanning process,
46 * to make it easier to understand the data structures below:
48 * In order to reduce excessive scanning, KSM sorts the memory pages by their
49 * contents into a data structure that holds pointers to the pages' locations.
51 * Since the contents of the pages may change at any moment, KSM cannot just
52 * insert the pages into a normal sorted tree and expect it to find anything.
53 * Therefore KSM uses two data structures - the stable and the unstable tree.
55 * The stable tree holds pointers to all the merged pages (ksm pages), sorted
56 * by their contents. Because each such page is write-protected, searching on
57 * this tree is fully assured to be working (except when pages are unmapped),
58 * and therefore this tree is called the stable tree.
60 * In addition to the stable tree, KSM uses a second data structure called the
61 * unstable tree: this tree holds pointers to pages which have been found to
62 * be "unchanged for a period of time". The unstable tree sorts these pages
63 * by their contents, but since they are not write-protected, KSM cannot rely
64 * upon the unstable tree to work correctly - the unstable tree is liable to
65 * be corrupted as its contents are modified, and so it is called unstable.
67 * KSM solves this problem by several techniques:
69 * 1) The unstable tree is flushed every time KSM completes scanning all
70 * memory areas, and then the tree is rebuilt again from the beginning.
71 * 2) KSM will only insert into the unstable tree, pages whose hash value
72 * has not changed since the previous scan of all memory areas.
73 * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
74 * colors of the nodes and not on their contents, assuring that even when
75 * the tree gets "corrupted" it won't get out of balance, so scanning time
76 * remains the same (also, searching and inserting nodes in an rbtree uses
77 * the same algorithm, so we have no overhead when we flush and rebuild).
78 * 4) KSM never flushes the stable tree, which means that even if it were to
79 * take 10 attempts to find a page in the unstable tree, once it is found,
80 * it is secured in the stable tree. (When we scan a new page, we first
81 * compare it against the stable tree, and then against the unstable tree.)
85 * struct mm_slot - ksm information per mm that is being scanned
86 * @link: link to the mm_slots hash list
87 * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
88 * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
89 * @mm: the mm that this information is valid for
92 struct hlist_node link
;
93 struct list_head mm_list
;
94 struct rmap_item
*rmap_list
;
99 * struct ksm_scan - cursor for scanning
100 * @mm_slot: the current mm_slot we are scanning
101 * @address: the next address inside that to be scanned
102 * @rmap_list: link to the next rmap to be scanned in the rmap_list
103 * @seqnr: count of completed full scans (needed when removing unstable node)
105 * There is only the one ksm_scan instance of this cursor structure.
108 struct mm_slot
*mm_slot
;
109 unsigned long address
;
110 struct rmap_item
**rmap_list
;
115 * struct stable_node - node of the stable rbtree
116 * @node: rb node of this ksm page in the stable tree
117 * @hlist: hlist head of rmap_items using this ksm page
118 * @kpfn: page frame number of this ksm page
122 struct hlist_head hlist
;
127 * struct rmap_item - reverse mapping item for virtual addresses
128 * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
129 * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
130 * @mm: the memory structure this rmap_item is pointing into
131 * @address: the virtual address this rmap_item tracks (+ flags in low bits)
132 * @oldchecksum: previous checksum of the page at that virtual address
133 * @node: rb node of this rmap_item in the unstable tree
134 * @head: pointer to stable_node heading this list in the stable tree
135 * @hlist: link into hlist of rmap_items hanging off that stable_node
138 struct rmap_item
*rmap_list
;
139 struct anon_vma
*anon_vma
; /* when stable */
140 struct mm_struct
*mm
;
141 unsigned long address
; /* + low bits used for flags below */
142 unsigned int oldchecksum
; /* when unstable */
147 struct rb_node node
; /* when node of unstable tree */
148 struct { /* when listed from stable tree */
149 struct stable_node
*head
;
150 struct hlist_node hlist
;
155 #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
156 #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
157 #define STABLE_FLAG 0x200 /* is listed from the stable tree */
159 /* The stable and unstable tree heads */
160 static struct rb_root root_unstable_tree
[MAX_NUMNODES
];
161 static struct rb_root root_stable_tree
[MAX_NUMNODES
];
163 #define MM_SLOTS_HASH_BITS 10
164 static DEFINE_HASHTABLE(mm_slots_hash
, MM_SLOTS_HASH_BITS
);
166 static struct mm_slot ksm_mm_head
= {
167 .mm_list
= LIST_HEAD_INIT(ksm_mm_head
.mm_list
),
169 static struct ksm_scan ksm_scan
= {
170 .mm_slot
= &ksm_mm_head
,
173 static struct kmem_cache
*rmap_item_cache
;
174 static struct kmem_cache
*stable_node_cache
;
175 static struct kmem_cache
*mm_slot_cache
;
177 /* The number of nodes in the stable tree */
178 static unsigned long ksm_pages_shared
;
180 /* The number of page slots additionally sharing those nodes */
181 static unsigned long ksm_pages_sharing
;
183 /* The number of nodes in the unstable tree */
184 static unsigned long ksm_pages_unshared
;
186 /* The number of rmap_items in use: to calculate pages_volatile */
187 static unsigned long ksm_rmap_items
;
189 /* Number of pages ksmd should scan in one batch */
190 static unsigned int ksm_thread_pages_to_scan
= 100;
192 /* Milliseconds ksmd should sleep between batches */
193 static unsigned int ksm_thread_sleep_millisecs
= 20;
195 /* Zeroed when merging across nodes is not allowed */
196 static unsigned int ksm_merge_across_nodes
= 1;
198 #define KSM_RUN_STOP 0
199 #define KSM_RUN_MERGE 1
200 #define KSM_RUN_UNMERGE 2
201 static unsigned int ksm_run
= KSM_RUN_STOP
;
203 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait
);
204 static DEFINE_MUTEX(ksm_thread_mutex
);
205 static DEFINE_SPINLOCK(ksm_mmlist_lock
);
207 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
208 sizeof(struct __struct), __alignof__(struct __struct),\
211 static int __init
ksm_slab_init(void)
213 rmap_item_cache
= KSM_KMEM_CACHE(rmap_item
, 0);
214 if (!rmap_item_cache
)
217 stable_node_cache
= KSM_KMEM_CACHE(stable_node
, 0);
218 if (!stable_node_cache
)
221 mm_slot_cache
= KSM_KMEM_CACHE(mm_slot
, 0);
228 kmem_cache_destroy(stable_node_cache
);
230 kmem_cache_destroy(rmap_item_cache
);
235 static void __init
ksm_slab_free(void)
237 kmem_cache_destroy(mm_slot_cache
);
238 kmem_cache_destroy(stable_node_cache
);
239 kmem_cache_destroy(rmap_item_cache
);
240 mm_slot_cache
= NULL
;
243 static inline struct rmap_item
*alloc_rmap_item(void)
245 struct rmap_item
*rmap_item
;
247 rmap_item
= kmem_cache_zalloc(rmap_item_cache
, GFP_KERNEL
);
253 static inline void free_rmap_item(struct rmap_item
*rmap_item
)
256 rmap_item
->mm
= NULL
; /* debug safety */
257 kmem_cache_free(rmap_item_cache
, rmap_item
);
260 static inline struct stable_node
*alloc_stable_node(void)
262 return kmem_cache_alloc(stable_node_cache
, GFP_KERNEL
);
265 static inline void free_stable_node(struct stable_node
*stable_node
)
267 kmem_cache_free(stable_node_cache
, stable_node
);
270 static inline struct mm_slot
*alloc_mm_slot(void)
272 if (!mm_slot_cache
) /* initialization failed */
274 return kmem_cache_zalloc(mm_slot_cache
, GFP_KERNEL
);
277 static inline void free_mm_slot(struct mm_slot
*mm_slot
)
279 kmem_cache_free(mm_slot_cache
, mm_slot
);
282 static struct mm_slot
*get_mm_slot(struct mm_struct
*mm
)
284 struct hlist_node
*node
;
285 struct mm_slot
*slot
;
287 hash_for_each_possible(mm_slots_hash
, slot
, node
, link
, (unsigned long)mm
)
294 static void insert_to_mm_slots_hash(struct mm_struct
*mm
,
295 struct mm_slot
*mm_slot
)
298 hash_add(mm_slots_hash
, &mm_slot
->link
, (unsigned long)mm
);
301 static inline int in_stable_tree(struct rmap_item
*rmap_item
)
303 return rmap_item
->address
& STABLE_FLAG
;
307 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
308 * page tables after it has passed through ksm_exit() - which, if necessary,
309 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
310 * a special flag: they can just back out as soon as mm_users goes to zero.
311 * ksm_test_exit() is used throughout to make this test for exit: in some
312 * places for correctness, in some places just to avoid unnecessary work.
314 static inline bool ksm_test_exit(struct mm_struct
*mm
)
316 return atomic_read(&mm
->mm_users
) == 0;
320 * We use break_ksm to break COW on a ksm page: it's a stripped down
322 * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
325 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
326 * in case the application has unmapped and remapped mm,addr meanwhile.
327 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
328 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
330 static int break_ksm(struct vm_area_struct
*vma
, unsigned long addr
)
337 page
= follow_page(vma
, addr
, FOLL_GET
);
338 if (IS_ERR_OR_NULL(page
))
341 ret
= handle_mm_fault(vma
->vm_mm
, vma
, addr
,
344 ret
= VM_FAULT_WRITE
;
346 } while (!(ret
& (VM_FAULT_WRITE
| VM_FAULT_SIGBUS
| VM_FAULT_OOM
)));
348 * We must loop because handle_mm_fault() may back out if there's
349 * any difficulty e.g. if pte accessed bit gets updated concurrently.
351 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
352 * COW has been broken, even if the vma does not permit VM_WRITE;
353 * but note that a concurrent fault might break PageKsm for us.
355 * VM_FAULT_SIGBUS could occur if we race with truncation of the
356 * backing file, which also invalidates anonymous pages: that's
357 * okay, that truncation will have unmapped the PageKsm for us.
359 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
360 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
361 * current task has TIF_MEMDIE set, and will be OOM killed on return
362 * to user; and ksmd, having no mm, would never be chosen for that.
364 * But if the mm is in a limited mem_cgroup, then the fault may fail
365 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
366 * even ksmd can fail in this way - though it's usually breaking ksm
367 * just to undo a merge it made a moment before, so unlikely to oom.
369 * That's a pity: we might therefore have more kernel pages allocated
370 * than we're counting as nodes in the stable tree; but ksm_do_scan
371 * will retry to break_cow on each pass, so should recover the page
372 * in due course. The important thing is to not let VM_MERGEABLE
373 * be cleared while any such pages might remain in the area.
375 return (ret
& VM_FAULT_OOM
) ? -ENOMEM
: 0;
378 static struct vm_area_struct
*find_mergeable_vma(struct mm_struct
*mm
,
381 struct vm_area_struct
*vma
;
382 if (ksm_test_exit(mm
))
384 vma
= find_vma(mm
, addr
);
385 if (!vma
|| vma
->vm_start
> addr
)
387 if (!(vma
->vm_flags
& VM_MERGEABLE
) || !vma
->anon_vma
)
392 static void break_cow(struct rmap_item
*rmap_item
)
394 struct mm_struct
*mm
= rmap_item
->mm
;
395 unsigned long addr
= rmap_item
->address
;
396 struct vm_area_struct
*vma
;
399 * It is not an accident that whenever we want to break COW
400 * to undo, we also need to drop a reference to the anon_vma.
402 put_anon_vma(rmap_item
->anon_vma
);
404 down_read(&mm
->mmap_sem
);
405 vma
= find_mergeable_vma(mm
, addr
);
407 break_ksm(vma
, addr
);
408 up_read(&mm
->mmap_sem
);
411 static struct page
*page_trans_compound_anon(struct page
*page
)
413 if (PageTransCompound(page
)) {
414 struct page
*head
= compound_trans_head(page
);
416 * head may actually be splitted and freed from under
417 * us but it's ok here.
425 static struct page
*get_mergeable_page(struct rmap_item
*rmap_item
)
427 struct mm_struct
*mm
= rmap_item
->mm
;
428 unsigned long addr
= rmap_item
->address
;
429 struct vm_area_struct
*vma
;
432 down_read(&mm
->mmap_sem
);
433 vma
= find_mergeable_vma(mm
, addr
);
437 page
= follow_page(vma
, addr
, FOLL_GET
);
438 if (IS_ERR_OR_NULL(page
))
440 if (PageAnon(page
) || page_trans_compound_anon(page
)) {
441 flush_anon_page(vma
, page
, addr
);
442 flush_dcache_page(page
);
447 up_read(&mm
->mmap_sem
);
452 * This helper is used for getting right index into array of tree roots.
453 * When merge_across_nodes knob is set to 1, there are only two rb-trees for
454 * stable and unstable pages from all nodes with roots in index 0. Otherwise,
455 * every node has its own stable and unstable tree.
457 static inline int get_kpfn_nid(unsigned long kpfn
)
459 if (ksm_merge_across_nodes
)
462 return pfn_to_nid(kpfn
);
465 static void remove_node_from_stable_tree(struct stable_node
*stable_node
)
467 struct rmap_item
*rmap_item
;
468 struct hlist_node
*hlist
;
471 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
472 if (rmap_item
->hlist
.next
)
476 put_anon_vma(rmap_item
->anon_vma
);
477 rmap_item
->address
&= PAGE_MASK
;
481 nid
= get_kpfn_nid(stable_node
->kpfn
);
483 rb_erase(&stable_node
->node
, &root_stable_tree
[nid
]);
484 free_stable_node(stable_node
);
488 * get_ksm_page: checks if the page indicated by the stable node
489 * is still its ksm page, despite having held no reference to it.
490 * In which case we can trust the content of the page, and it
491 * returns the gotten page; but if the page has now been zapped,
492 * remove the stale node from the stable tree and return NULL.
494 * You would expect the stable_node to hold a reference to the ksm page.
495 * But if it increments the page's count, swapping out has to wait for
496 * ksmd to come around again before it can free the page, which may take
497 * seconds or even minutes: much too unresponsive. So instead we use a
498 * "keyhole reference": access to the ksm page from the stable node peeps
499 * out through its keyhole to see if that page still holds the right key,
500 * pointing back to this stable node. This relies on freeing a PageAnon
501 * page to reset its page->mapping to NULL, and relies on no other use of
502 * a page to put something that might look like our key in page->mapping.
504 * include/linux/pagemap.h page_cache_get_speculative() is a good reference,
505 * but this is different - made simpler by ksm_thread_mutex being held, but
506 * interesting for assuming that no other use of the struct page could ever
507 * put our expected_mapping into page->mapping (or a field of the union which
508 * coincides with page->mapping). The RCU calls are not for KSM at all, but
509 * to keep the page_count protocol described with page_cache_get_speculative.
511 * Note: it is possible that get_ksm_page() will return NULL one moment,
512 * then page the next, if the page is in between page_freeze_refs() and
513 * page_unfreeze_refs(): this shouldn't be a problem anywhere, the page
514 * is on its way to being freed; but it is an anomaly to bear in mind.
516 static struct page
*get_ksm_page(struct stable_node
*stable_node
)
519 void *expected_mapping
;
521 page
= pfn_to_page(stable_node
->kpfn
);
522 expected_mapping
= (void *)stable_node
+
523 (PAGE_MAPPING_ANON
| PAGE_MAPPING_KSM
);
525 if (page
->mapping
!= expected_mapping
)
527 if (!get_page_unless_zero(page
))
529 if (page
->mapping
!= expected_mapping
) {
537 remove_node_from_stable_tree(stable_node
);
542 * Removing rmap_item from stable or unstable tree.
543 * This function will clean the information from the stable/unstable tree.
545 static void remove_rmap_item_from_tree(struct rmap_item
*rmap_item
)
547 if (rmap_item
->address
& STABLE_FLAG
) {
548 struct stable_node
*stable_node
;
551 stable_node
= rmap_item
->head
;
552 page
= get_ksm_page(stable_node
);
557 hlist_del(&rmap_item
->hlist
);
561 if (stable_node
->hlist
.first
)
566 put_anon_vma(rmap_item
->anon_vma
);
567 rmap_item
->address
&= PAGE_MASK
;
569 } else if (rmap_item
->address
& UNSTABLE_FLAG
) {
572 * Usually ksmd can and must skip the rb_erase, because
573 * root_unstable_tree was already reset to RB_ROOT.
574 * But be careful when an mm is exiting: do the rb_erase
575 * if this rmap_item was inserted by this scan, rather
576 * than left over from before.
578 age
= (unsigned char)(ksm_scan
.seqnr
- rmap_item
->address
);
582 rb_erase(&rmap_item
->node
,
583 &root_unstable_tree
[rmap_item
->nid
]);
585 rb_erase(&rmap_item
->node
, &root_unstable_tree
[0]);
588 ksm_pages_unshared
--;
589 rmap_item
->address
&= PAGE_MASK
;
592 cond_resched(); /* we're called from many long loops */
595 static void remove_trailing_rmap_items(struct mm_slot
*mm_slot
,
596 struct rmap_item
**rmap_list
)
599 struct rmap_item
*rmap_item
= *rmap_list
;
600 *rmap_list
= rmap_item
->rmap_list
;
601 remove_rmap_item_from_tree(rmap_item
);
602 free_rmap_item(rmap_item
);
607 * Though it's very tempting to unmerge in_stable_tree(rmap_item)s rather
608 * than check every pte of a given vma, the locking doesn't quite work for
609 * that - an rmap_item is assigned to the stable tree after inserting ksm
610 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
611 * rmap_items from parent to child at fork time (so as not to waste time
612 * if exit comes before the next scan reaches it).
614 * Similarly, although we'd like to remove rmap_items (so updating counts
615 * and freeing memory) when unmerging an area, it's easier to leave that
616 * to the next pass of ksmd - consider, for example, how ksmd might be
617 * in cmp_and_merge_page on one of the rmap_items we would be removing.
619 static int unmerge_ksm_pages(struct vm_area_struct
*vma
,
620 unsigned long start
, unsigned long end
)
625 for (addr
= start
; addr
< end
&& !err
; addr
+= PAGE_SIZE
) {
626 if (ksm_test_exit(vma
->vm_mm
))
628 if (signal_pending(current
))
631 err
= break_ksm(vma
, addr
);
638 * Only called through the sysfs control interface:
640 static int unmerge_and_remove_all_rmap_items(void)
642 struct mm_slot
*mm_slot
;
643 struct mm_struct
*mm
;
644 struct vm_area_struct
*vma
;
647 spin_lock(&ksm_mmlist_lock
);
648 ksm_scan
.mm_slot
= list_entry(ksm_mm_head
.mm_list
.next
,
649 struct mm_slot
, mm_list
);
650 spin_unlock(&ksm_mmlist_lock
);
652 for (mm_slot
= ksm_scan
.mm_slot
;
653 mm_slot
!= &ksm_mm_head
; mm_slot
= ksm_scan
.mm_slot
) {
655 down_read(&mm
->mmap_sem
);
656 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
657 if (ksm_test_exit(mm
))
659 if (!(vma
->vm_flags
& VM_MERGEABLE
) || !vma
->anon_vma
)
661 err
= unmerge_ksm_pages(vma
,
662 vma
->vm_start
, vma
->vm_end
);
667 remove_trailing_rmap_items(mm_slot
, &mm_slot
->rmap_list
);
669 spin_lock(&ksm_mmlist_lock
);
670 ksm_scan
.mm_slot
= list_entry(mm_slot
->mm_list
.next
,
671 struct mm_slot
, mm_list
);
672 if (ksm_test_exit(mm
)) {
673 hash_del(&mm_slot
->link
);
674 list_del(&mm_slot
->mm_list
);
675 spin_unlock(&ksm_mmlist_lock
);
677 free_mm_slot(mm_slot
);
678 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
679 up_read(&mm
->mmap_sem
);
682 spin_unlock(&ksm_mmlist_lock
);
683 up_read(&mm
->mmap_sem
);
691 up_read(&mm
->mmap_sem
);
692 spin_lock(&ksm_mmlist_lock
);
693 ksm_scan
.mm_slot
= &ksm_mm_head
;
694 spin_unlock(&ksm_mmlist_lock
);
697 #endif /* CONFIG_SYSFS */
699 static u32
calc_checksum(struct page
*page
)
702 void *addr
= kmap_atomic(page
);
703 checksum
= jhash2(addr
, PAGE_SIZE
/ 4, 17);
708 static int memcmp_pages(struct page
*page1
, struct page
*page2
)
713 addr1
= kmap_atomic(page1
);
714 addr2
= kmap_atomic(page2
);
715 ret
= memcmp(addr1
, addr2
, PAGE_SIZE
);
716 kunmap_atomic(addr2
);
717 kunmap_atomic(addr1
);
721 static inline int pages_identical(struct page
*page1
, struct page
*page2
)
723 return !memcmp_pages(page1
, page2
);
726 static int write_protect_page(struct vm_area_struct
*vma
, struct page
*page
,
729 struct mm_struct
*mm
= vma
->vm_mm
;
735 unsigned long mmun_start
; /* For mmu_notifiers */
736 unsigned long mmun_end
; /* For mmu_notifiers */
738 addr
= page_address_in_vma(page
, vma
);
742 BUG_ON(PageTransCompound(page
));
745 mmun_end
= addr
+ PAGE_SIZE
;
746 mmu_notifier_invalidate_range_start(mm
, mmun_start
, mmun_end
);
748 ptep
= page_check_address(page
, mm
, addr
, &ptl
, 0);
752 if (pte_write(*ptep
) || pte_dirty(*ptep
)) {
755 swapped
= PageSwapCache(page
);
756 flush_cache_page(vma
, addr
, page_to_pfn(page
));
758 * Ok this is tricky, when get_user_pages_fast() run it doesn't
759 * take any lock, therefore the check that we are going to make
760 * with the pagecount against the mapcount is racey and
761 * O_DIRECT can happen right after the check.
762 * So we clear the pte and flush the tlb before the check
763 * this assure us that no O_DIRECT can happen after the check
764 * or in the middle of the check.
766 entry
= ptep_clear_flush(vma
, addr
, ptep
);
768 * Check that no O_DIRECT or similar I/O is in progress on the
771 if (page_mapcount(page
) + 1 + swapped
!= page_count(page
)) {
772 set_pte_at(mm
, addr
, ptep
, entry
);
775 if (pte_dirty(entry
))
776 set_page_dirty(page
);
777 entry
= pte_mkclean(pte_wrprotect(entry
));
778 set_pte_at_notify(mm
, addr
, ptep
, entry
);
784 pte_unmap_unlock(ptep
, ptl
);
786 mmu_notifier_invalidate_range_end(mm
, mmun_start
, mmun_end
);
792 * replace_page - replace page in vma by new ksm page
793 * @vma: vma that holds the pte pointing to page
794 * @page: the page we are replacing by kpage
795 * @kpage: the ksm page we replace page by
796 * @orig_pte: the original value of the pte
798 * Returns 0 on success, -EFAULT on failure.
800 static int replace_page(struct vm_area_struct
*vma
, struct page
*page
,
801 struct page
*kpage
, pte_t orig_pte
)
803 struct mm_struct
*mm
= vma
->vm_mm
;
809 unsigned long mmun_start
; /* For mmu_notifiers */
810 unsigned long mmun_end
; /* For mmu_notifiers */
812 addr
= page_address_in_vma(page
, vma
);
816 pmd
= mm_find_pmd(mm
, addr
);
819 BUG_ON(pmd_trans_huge(*pmd
));
822 mmun_end
= addr
+ PAGE_SIZE
;
823 mmu_notifier_invalidate_range_start(mm
, mmun_start
, mmun_end
);
825 ptep
= pte_offset_map_lock(mm
, pmd
, addr
, &ptl
);
826 if (!pte_same(*ptep
, orig_pte
)) {
827 pte_unmap_unlock(ptep
, ptl
);
832 page_add_anon_rmap(kpage
, vma
, addr
);
834 flush_cache_page(vma
, addr
, pte_pfn(*ptep
));
835 ptep_clear_flush(vma
, addr
, ptep
);
836 set_pte_at_notify(mm
, addr
, ptep
, mk_pte(kpage
, vma
->vm_page_prot
));
838 page_remove_rmap(page
);
839 if (!page_mapped(page
))
840 try_to_free_swap(page
);
843 pte_unmap_unlock(ptep
, ptl
);
846 mmu_notifier_invalidate_range_end(mm
, mmun_start
, mmun_end
);
851 static int page_trans_compound_anon_split(struct page
*page
)
854 struct page
*transhuge_head
= page_trans_compound_anon(page
);
855 if (transhuge_head
) {
856 /* Get the reference on the head to split it. */
857 if (get_page_unless_zero(transhuge_head
)) {
859 * Recheck we got the reference while the head
860 * was still anonymous.
862 if (PageAnon(transhuge_head
))
863 ret
= split_huge_page(transhuge_head
);
866 * Retry later if split_huge_page run
870 put_page(transhuge_head
);
872 /* Retry later if split_huge_page run from under us. */
879 * try_to_merge_one_page - take two pages and merge them into one
880 * @vma: the vma that holds the pte pointing to page
881 * @page: the PageAnon page that we want to replace with kpage
882 * @kpage: the PageKsm page that we want to map instead of page,
883 * or NULL the first time when we want to use page as kpage.
885 * This function returns 0 if the pages were merged, -EFAULT otherwise.
887 static int try_to_merge_one_page(struct vm_area_struct
*vma
,
888 struct page
*page
, struct page
*kpage
)
890 pte_t orig_pte
= __pte(0);
893 if (page
== kpage
) /* ksm page forked */
896 if (!(vma
->vm_flags
& VM_MERGEABLE
))
898 if (PageTransCompound(page
) && page_trans_compound_anon_split(page
))
900 BUG_ON(PageTransCompound(page
));
905 * We need the page lock to read a stable PageSwapCache in
906 * write_protect_page(). We use trylock_page() instead of
907 * lock_page() because we don't want to wait here - we
908 * prefer to continue scanning and merging different pages,
909 * then come back to this page when it is unlocked.
911 if (!trylock_page(page
))
914 * If this anonymous page is mapped only here, its pte may need
915 * to be write-protected. If it's mapped elsewhere, all of its
916 * ptes are necessarily already write-protected. But in either
917 * case, we need to lock and check page_count is not raised.
919 if (write_protect_page(vma
, page
, &orig_pte
) == 0) {
922 * While we hold page lock, upgrade page from
923 * PageAnon+anon_vma to PageKsm+NULL stable_node:
924 * stable_tree_insert() will update stable_node.
926 set_page_stable_node(page
, NULL
);
927 mark_page_accessed(page
);
929 } else if (pages_identical(page
, kpage
))
930 err
= replace_page(vma
, page
, kpage
, orig_pte
);
933 if ((vma
->vm_flags
& VM_LOCKED
) && kpage
&& !err
) {
934 munlock_vma_page(page
);
935 if (!PageMlocked(kpage
)) {
938 mlock_vma_page(kpage
);
939 page
= kpage
; /* for final unlock */
949 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
950 * but no new kernel page is allocated: kpage must already be a ksm page.
952 * This function returns 0 if the pages were merged, -EFAULT otherwise.
954 static int try_to_merge_with_ksm_page(struct rmap_item
*rmap_item
,
955 struct page
*page
, struct page
*kpage
)
957 struct mm_struct
*mm
= rmap_item
->mm
;
958 struct vm_area_struct
*vma
;
961 down_read(&mm
->mmap_sem
);
962 if (ksm_test_exit(mm
))
964 vma
= find_vma(mm
, rmap_item
->address
);
965 if (!vma
|| vma
->vm_start
> rmap_item
->address
)
968 err
= try_to_merge_one_page(vma
, page
, kpage
);
972 /* Must get reference to anon_vma while still holding mmap_sem */
973 rmap_item
->anon_vma
= vma
->anon_vma
;
974 get_anon_vma(vma
->anon_vma
);
976 up_read(&mm
->mmap_sem
);
981 * try_to_merge_two_pages - take two identical pages and prepare them
982 * to be merged into one page.
984 * This function returns the kpage if we successfully merged two identical
985 * pages into one ksm page, NULL otherwise.
987 * Note that this function upgrades page to ksm page: if one of the pages
988 * is already a ksm page, try_to_merge_with_ksm_page should be used.
990 static struct page
*try_to_merge_two_pages(struct rmap_item
*rmap_item
,
992 struct rmap_item
*tree_rmap_item
,
993 struct page
*tree_page
)
997 err
= try_to_merge_with_ksm_page(rmap_item
, page
, NULL
);
999 err
= try_to_merge_with_ksm_page(tree_rmap_item
,
1002 * If that fails, we have a ksm page with only one pte
1003 * pointing to it: so break it.
1006 break_cow(rmap_item
);
1008 return err
? NULL
: page
;
1012 * stable_tree_search - search for page inside the stable tree
1014 * This function checks if there is a page inside the stable tree
1015 * with identical content to the page that we are scanning right now.
1017 * This function returns the stable tree node of identical content if found,
1020 static struct page
*stable_tree_search(struct page
*page
)
1022 struct rb_node
*node
;
1023 struct stable_node
*stable_node
;
1026 stable_node
= page_stable_node(page
);
1027 if (stable_node
) { /* ksm page forked */
1032 nid
= get_kpfn_nid(page_to_pfn(page
));
1033 node
= root_stable_tree
[nid
].rb_node
;
1036 struct page
*tree_page
;
1040 stable_node
= rb_entry(node
, struct stable_node
, node
);
1041 tree_page
= get_ksm_page(stable_node
);
1045 ret
= memcmp_pages(page
, tree_page
);
1048 put_page(tree_page
);
1049 node
= node
->rb_left
;
1050 } else if (ret
> 0) {
1051 put_page(tree_page
);
1052 node
= node
->rb_right
;
1061 * stable_tree_insert - insert rmap_item pointing to new ksm page
1062 * into the stable tree.
1064 * This function returns the stable tree node just allocated on success,
1067 static struct stable_node
*stable_tree_insert(struct page
*kpage
)
1071 struct rb_node
**new;
1072 struct rb_node
*parent
= NULL
;
1073 struct stable_node
*stable_node
;
1075 kpfn
= page_to_pfn(kpage
);
1076 nid
= get_kpfn_nid(kpfn
);
1077 new = &root_stable_tree
[nid
].rb_node
;
1080 struct page
*tree_page
;
1084 stable_node
= rb_entry(*new, struct stable_node
, node
);
1085 tree_page
= get_ksm_page(stable_node
);
1089 ret
= memcmp_pages(kpage
, tree_page
);
1090 put_page(tree_page
);
1094 new = &parent
->rb_left
;
1096 new = &parent
->rb_right
;
1099 * It is not a bug that stable_tree_search() didn't
1100 * find this node: because at that time our page was
1101 * not yet write-protected, so may have changed since.
1107 stable_node
= alloc_stable_node();
1111 rb_link_node(&stable_node
->node
, parent
, new);
1112 rb_insert_color(&stable_node
->node
, &root_stable_tree
[nid
]);
1114 INIT_HLIST_HEAD(&stable_node
->hlist
);
1116 stable_node
->kpfn
= kpfn
;
1117 set_page_stable_node(kpage
, stable_node
);
1123 * unstable_tree_search_insert - search for identical page,
1124 * else insert rmap_item into the unstable tree.
1126 * This function searches for a page in the unstable tree identical to the
1127 * page currently being scanned; and if no identical page is found in the
1128 * tree, we insert rmap_item as a new object into the unstable tree.
1130 * This function returns pointer to rmap_item found to be identical
1131 * to the currently scanned page, NULL otherwise.
1133 * This function does both searching and inserting, because they share
1134 * the same walking algorithm in an rbtree.
1137 struct rmap_item
*unstable_tree_search_insert(struct rmap_item
*rmap_item
,
1139 struct page
**tree_pagep
)
1141 struct rb_node
**new;
1142 struct rb_root
*root
;
1143 struct rb_node
*parent
= NULL
;
1146 nid
= get_kpfn_nid(page_to_pfn(page
));
1147 root
= &root_unstable_tree
[nid
];
1148 new = &root
->rb_node
;
1151 struct rmap_item
*tree_rmap_item
;
1152 struct page
*tree_page
;
1156 tree_rmap_item
= rb_entry(*new, struct rmap_item
, node
);
1157 tree_page
= get_mergeable_page(tree_rmap_item
);
1158 if (IS_ERR_OR_NULL(tree_page
))
1162 * Don't substitute a ksm page for a forked page.
1164 if (page
== tree_page
) {
1165 put_page(tree_page
);
1170 * If tree_page has been migrated to another NUMA node, it
1171 * will be flushed out and put into the right unstable tree
1172 * next time: only merge with it if merge_across_nodes.
1173 * Just notice, we don't have similar problem for PageKsm
1174 * because their migration is disabled now. (62b61f611e)
1176 if (!ksm_merge_across_nodes
&& page_to_nid(tree_page
) != nid
) {
1177 put_page(tree_page
);
1181 ret
= memcmp_pages(page
, tree_page
);
1185 put_page(tree_page
);
1186 new = &parent
->rb_left
;
1187 } else if (ret
> 0) {
1188 put_page(tree_page
);
1189 new = &parent
->rb_right
;
1191 *tree_pagep
= tree_page
;
1192 return tree_rmap_item
;
1196 rmap_item
->address
|= UNSTABLE_FLAG
;
1197 rmap_item
->address
|= (ksm_scan
.seqnr
& SEQNR_MASK
);
1199 rmap_item
->nid
= nid
;
1201 rb_link_node(&rmap_item
->node
, parent
, new);
1202 rb_insert_color(&rmap_item
->node
, root
);
1204 ksm_pages_unshared
++;
1209 * stable_tree_append - add another rmap_item to the linked list of
1210 * rmap_items hanging off a given node of the stable tree, all sharing
1211 * the same ksm page.
1213 static void stable_tree_append(struct rmap_item
*rmap_item
,
1214 struct stable_node
*stable_node
)
1218 * Usually rmap_item->nid is already set correctly,
1219 * but it may be wrong after switching merge_across_nodes.
1221 rmap_item
->nid
= get_kpfn_nid(stable_node
->kpfn
);
1223 rmap_item
->head
= stable_node
;
1224 rmap_item
->address
|= STABLE_FLAG
;
1225 hlist_add_head(&rmap_item
->hlist
, &stable_node
->hlist
);
1227 if (rmap_item
->hlist
.next
)
1228 ksm_pages_sharing
++;
1234 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1235 * if not, compare checksum to previous and if it's the same, see if page can
1236 * be inserted into the unstable tree, or merged with a page already there and
1237 * both transferred to the stable tree.
1239 * @page: the page that we are searching identical page to.
1240 * @rmap_item: the reverse mapping into the virtual address of this page
1242 static void cmp_and_merge_page(struct page
*page
, struct rmap_item
*rmap_item
)
1244 struct rmap_item
*tree_rmap_item
;
1245 struct page
*tree_page
= NULL
;
1246 struct stable_node
*stable_node
;
1248 unsigned int checksum
;
1251 remove_rmap_item_from_tree(rmap_item
);
1253 /* We first start with searching the page inside the stable tree */
1254 kpage
= stable_tree_search(page
);
1256 err
= try_to_merge_with_ksm_page(rmap_item
, page
, kpage
);
1259 * The page was successfully merged:
1260 * add its rmap_item to the stable tree.
1263 stable_tree_append(rmap_item
, page_stable_node(kpage
));
1271 * If the hash value of the page has changed from the last time
1272 * we calculated it, this page is changing frequently: therefore we
1273 * don't want to insert it in the unstable tree, and we don't want
1274 * to waste our time searching for something identical to it there.
1276 checksum
= calc_checksum(page
);
1277 if (rmap_item
->oldchecksum
!= checksum
) {
1278 rmap_item
->oldchecksum
= checksum
;
1283 unstable_tree_search_insert(rmap_item
, page
, &tree_page
);
1284 if (tree_rmap_item
) {
1285 kpage
= try_to_merge_two_pages(rmap_item
, page
,
1286 tree_rmap_item
, tree_page
);
1287 put_page(tree_page
);
1289 * As soon as we merge this page, we want to remove the
1290 * rmap_item of the page we have merged with from the unstable
1291 * tree, and insert it instead as new node in the stable tree.
1294 remove_rmap_item_from_tree(tree_rmap_item
);
1297 stable_node
= stable_tree_insert(kpage
);
1299 stable_tree_append(tree_rmap_item
, stable_node
);
1300 stable_tree_append(rmap_item
, stable_node
);
1305 * If we fail to insert the page into the stable tree,
1306 * we will have 2 virtual addresses that are pointing
1307 * to a ksm page left outside the stable tree,
1308 * in which case we need to break_cow on both.
1311 break_cow(tree_rmap_item
);
1312 break_cow(rmap_item
);
1318 static struct rmap_item
*get_next_rmap_item(struct mm_slot
*mm_slot
,
1319 struct rmap_item
**rmap_list
,
1322 struct rmap_item
*rmap_item
;
1324 while (*rmap_list
) {
1325 rmap_item
= *rmap_list
;
1326 if ((rmap_item
->address
& PAGE_MASK
) == addr
)
1328 if (rmap_item
->address
> addr
)
1330 *rmap_list
= rmap_item
->rmap_list
;
1331 remove_rmap_item_from_tree(rmap_item
);
1332 free_rmap_item(rmap_item
);
1335 rmap_item
= alloc_rmap_item();
1337 /* It has already been zeroed */
1338 rmap_item
->mm
= mm_slot
->mm
;
1339 rmap_item
->address
= addr
;
1340 rmap_item
->rmap_list
= *rmap_list
;
1341 *rmap_list
= rmap_item
;
1346 static struct rmap_item
*scan_get_next_rmap_item(struct page
**page
)
1348 struct mm_struct
*mm
;
1349 struct mm_slot
*slot
;
1350 struct vm_area_struct
*vma
;
1351 struct rmap_item
*rmap_item
;
1354 if (list_empty(&ksm_mm_head
.mm_list
))
1357 slot
= ksm_scan
.mm_slot
;
1358 if (slot
== &ksm_mm_head
) {
1360 * A number of pages can hang around indefinitely on per-cpu
1361 * pagevecs, raised page count preventing write_protect_page
1362 * from merging them. Though it doesn't really matter much,
1363 * it is puzzling to see some stuck in pages_volatile until
1364 * other activity jostles them out, and they also prevented
1365 * LTP's KSM test from succeeding deterministically; so drain
1366 * them here (here rather than on entry to ksm_do_scan(),
1367 * so we don't IPI too often when pages_to_scan is set low).
1369 lru_add_drain_all();
1371 for (nid
= 0; nid
< nr_node_ids
; nid
++)
1372 root_unstable_tree
[nid
] = RB_ROOT
;
1374 spin_lock(&ksm_mmlist_lock
);
1375 slot
= list_entry(slot
->mm_list
.next
, struct mm_slot
, mm_list
);
1376 ksm_scan
.mm_slot
= slot
;
1377 spin_unlock(&ksm_mmlist_lock
);
1379 * Although we tested list_empty() above, a racing __ksm_exit
1380 * of the last mm on the list may have removed it since then.
1382 if (slot
== &ksm_mm_head
)
1385 ksm_scan
.address
= 0;
1386 ksm_scan
.rmap_list
= &slot
->rmap_list
;
1390 down_read(&mm
->mmap_sem
);
1391 if (ksm_test_exit(mm
))
1394 vma
= find_vma(mm
, ksm_scan
.address
);
1396 for (; vma
; vma
= vma
->vm_next
) {
1397 if (!(vma
->vm_flags
& VM_MERGEABLE
))
1399 if (ksm_scan
.address
< vma
->vm_start
)
1400 ksm_scan
.address
= vma
->vm_start
;
1402 ksm_scan
.address
= vma
->vm_end
;
1404 while (ksm_scan
.address
< vma
->vm_end
) {
1405 if (ksm_test_exit(mm
))
1407 *page
= follow_page(vma
, ksm_scan
.address
, FOLL_GET
);
1408 if (IS_ERR_OR_NULL(*page
)) {
1409 ksm_scan
.address
+= PAGE_SIZE
;
1413 if (PageAnon(*page
) ||
1414 page_trans_compound_anon(*page
)) {
1415 flush_anon_page(vma
, *page
, ksm_scan
.address
);
1416 flush_dcache_page(*page
);
1417 rmap_item
= get_next_rmap_item(slot
,
1418 ksm_scan
.rmap_list
, ksm_scan
.address
);
1420 ksm_scan
.rmap_list
=
1421 &rmap_item
->rmap_list
;
1422 ksm_scan
.address
+= PAGE_SIZE
;
1425 up_read(&mm
->mmap_sem
);
1429 ksm_scan
.address
+= PAGE_SIZE
;
1434 if (ksm_test_exit(mm
)) {
1435 ksm_scan
.address
= 0;
1436 ksm_scan
.rmap_list
= &slot
->rmap_list
;
1439 * Nuke all the rmap_items that are above this current rmap:
1440 * because there were no VM_MERGEABLE vmas with such addresses.
1442 remove_trailing_rmap_items(slot
, ksm_scan
.rmap_list
);
1444 spin_lock(&ksm_mmlist_lock
);
1445 ksm_scan
.mm_slot
= list_entry(slot
->mm_list
.next
,
1446 struct mm_slot
, mm_list
);
1447 if (ksm_scan
.address
== 0) {
1449 * We've completed a full scan of all vmas, holding mmap_sem
1450 * throughout, and found no VM_MERGEABLE: so do the same as
1451 * __ksm_exit does to remove this mm from all our lists now.
1452 * This applies either when cleaning up after __ksm_exit
1453 * (but beware: we can reach here even before __ksm_exit),
1454 * or when all VM_MERGEABLE areas have been unmapped (and
1455 * mmap_sem then protects against race with MADV_MERGEABLE).
1457 hash_del(&slot
->link
);
1458 list_del(&slot
->mm_list
);
1459 spin_unlock(&ksm_mmlist_lock
);
1462 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
1463 up_read(&mm
->mmap_sem
);
1466 spin_unlock(&ksm_mmlist_lock
);
1467 up_read(&mm
->mmap_sem
);
1470 /* Repeat until we've completed scanning the whole list */
1471 slot
= ksm_scan
.mm_slot
;
1472 if (slot
!= &ksm_mm_head
)
1480 * ksm_do_scan - the ksm scanner main worker function.
1481 * @scan_npages - number of pages we want to scan before we return.
1483 static void ksm_do_scan(unsigned int scan_npages
)
1485 struct rmap_item
*rmap_item
;
1486 struct page
*uninitialized_var(page
);
1488 while (scan_npages
-- && likely(!freezing(current
))) {
1490 rmap_item
= scan_get_next_rmap_item(&page
);
1493 if (!PageKsm(page
) || !in_stable_tree(rmap_item
))
1494 cmp_and_merge_page(page
, rmap_item
);
1499 static int ksmd_should_run(void)
1501 return (ksm_run
& KSM_RUN_MERGE
) && !list_empty(&ksm_mm_head
.mm_list
);
1504 static int ksm_scan_thread(void *nothing
)
1507 set_user_nice(current
, 5);
1509 while (!kthread_should_stop()) {
1510 mutex_lock(&ksm_thread_mutex
);
1511 if (ksmd_should_run())
1512 ksm_do_scan(ksm_thread_pages_to_scan
);
1513 mutex_unlock(&ksm_thread_mutex
);
1517 if (ksmd_should_run()) {
1518 schedule_timeout_interruptible(
1519 msecs_to_jiffies(ksm_thread_sleep_millisecs
));
1521 wait_event_freezable(ksm_thread_wait
,
1522 ksmd_should_run() || kthread_should_stop());
1528 int ksm_madvise(struct vm_area_struct
*vma
, unsigned long start
,
1529 unsigned long end
, int advice
, unsigned long *vm_flags
)
1531 struct mm_struct
*mm
= vma
->vm_mm
;
1535 case MADV_MERGEABLE
:
1537 * Be somewhat over-protective for now!
1539 if (*vm_flags
& (VM_MERGEABLE
| VM_SHARED
| VM_MAYSHARE
|
1540 VM_PFNMAP
| VM_IO
| VM_DONTEXPAND
|
1541 VM_HUGETLB
| VM_NONLINEAR
| VM_MIXEDMAP
))
1542 return 0; /* just ignore the advice */
1545 if (*vm_flags
& VM_SAO
)
1549 if (!test_bit(MMF_VM_MERGEABLE
, &mm
->flags
)) {
1550 err
= __ksm_enter(mm
);
1555 *vm_flags
|= VM_MERGEABLE
;
1558 case MADV_UNMERGEABLE
:
1559 if (!(*vm_flags
& VM_MERGEABLE
))
1560 return 0; /* just ignore the advice */
1562 if (vma
->anon_vma
) {
1563 err
= unmerge_ksm_pages(vma
, start
, end
);
1568 *vm_flags
&= ~VM_MERGEABLE
;
1575 int __ksm_enter(struct mm_struct
*mm
)
1577 struct mm_slot
*mm_slot
;
1580 mm_slot
= alloc_mm_slot();
1584 /* Check ksm_run too? Would need tighter locking */
1585 needs_wakeup
= list_empty(&ksm_mm_head
.mm_list
);
1587 spin_lock(&ksm_mmlist_lock
);
1588 insert_to_mm_slots_hash(mm
, mm_slot
);
1590 * Insert just behind the scanning cursor, to let the area settle
1591 * down a little; when fork is followed by immediate exec, we don't
1592 * want ksmd to waste time setting up and tearing down an rmap_list.
1594 list_add_tail(&mm_slot
->mm_list
, &ksm_scan
.mm_slot
->mm_list
);
1595 spin_unlock(&ksm_mmlist_lock
);
1597 set_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
1598 atomic_inc(&mm
->mm_count
);
1601 wake_up_interruptible(&ksm_thread_wait
);
1606 void __ksm_exit(struct mm_struct
*mm
)
1608 struct mm_slot
*mm_slot
;
1609 int easy_to_free
= 0;
1612 * This process is exiting: if it's straightforward (as is the
1613 * case when ksmd was never running), free mm_slot immediately.
1614 * But if it's at the cursor or has rmap_items linked to it, use
1615 * mmap_sem to synchronize with any break_cows before pagetables
1616 * are freed, and leave the mm_slot on the list for ksmd to free.
1617 * Beware: ksm may already have noticed it exiting and freed the slot.
1620 spin_lock(&ksm_mmlist_lock
);
1621 mm_slot
= get_mm_slot(mm
);
1622 if (mm_slot
&& ksm_scan
.mm_slot
!= mm_slot
) {
1623 if (!mm_slot
->rmap_list
) {
1624 hash_del(&mm_slot
->link
);
1625 list_del(&mm_slot
->mm_list
);
1628 list_move(&mm_slot
->mm_list
,
1629 &ksm_scan
.mm_slot
->mm_list
);
1632 spin_unlock(&ksm_mmlist_lock
);
1635 free_mm_slot(mm_slot
);
1636 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
1638 } else if (mm_slot
) {
1639 down_write(&mm
->mmap_sem
);
1640 up_write(&mm
->mmap_sem
);
1644 struct page
*ksm_does_need_to_copy(struct page
*page
,
1645 struct vm_area_struct
*vma
, unsigned long address
)
1647 struct page
*new_page
;
1649 new_page
= alloc_page_vma(GFP_HIGHUSER_MOVABLE
, vma
, address
);
1651 copy_user_highpage(new_page
, page
, address
, vma
);
1653 SetPageDirty(new_page
);
1654 __SetPageUptodate(new_page
);
1655 __set_page_locked(new_page
);
1661 int page_referenced_ksm(struct page
*page
, struct mem_cgroup
*memcg
,
1662 unsigned long *vm_flags
)
1664 struct stable_node
*stable_node
;
1665 struct rmap_item
*rmap_item
;
1666 struct hlist_node
*hlist
;
1667 unsigned int mapcount
= page_mapcount(page
);
1669 int search_new_forks
= 0;
1671 VM_BUG_ON(!PageKsm(page
));
1672 VM_BUG_ON(!PageLocked(page
));
1674 stable_node
= page_stable_node(page
);
1678 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
1679 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
1680 struct anon_vma_chain
*vmac
;
1681 struct vm_area_struct
*vma
;
1683 anon_vma_lock_read(anon_vma
);
1684 anon_vma_interval_tree_foreach(vmac
, &anon_vma
->rb_root
,
1687 if (rmap_item
->address
< vma
->vm_start
||
1688 rmap_item
->address
>= vma
->vm_end
)
1691 * Initially we examine only the vma which covers this
1692 * rmap_item; but later, if there is still work to do,
1693 * we examine covering vmas in other mms: in case they
1694 * were forked from the original since ksmd passed.
1696 if ((rmap_item
->mm
== vma
->vm_mm
) == search_new_forks
)
1699 if (memcg
&& !mm_match_cgroup(vma
->vm_mm
, memcg
))
1702 referenced
+= page_referenced_one(page
, vma
,
1703 rmap_item
->address
, &mapcount
, vm_flags
);
1704 if (!search_new_forks
|| !mapcount
)
1707 anon_vma_unlock_read(anon_vma
);
1711 if (!search_new_forks
++)
1717 int try_to_unmap_ksm(struct page
*page
, enum ttu_flags flags
)
1719 struct stable_node
*stable_node
;
1720 struct hlist_node
*hlist
;
1721 struct rmap_item
*rmap_item
;
1722 int ret
= SWAP_AGAIN
;
1723 int search_new_forks
= 0;
1725 VM_BUG_ON(!PageKsm(page
));
1726 VM_BUG_ON(!PageLocked(page
));
1728 stable_node
= page_stable_node(page
);
1732 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
1733 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
1734 struct anon_vma_chain
*vmac
;
1735 struct vm_area_struct
*vma
;
1737 anon_vma_lock_read(anon_vma
);
1738 anon_vma_interval_tree_foreach(vmac
, &anon_vma
->rb_root
,
1741 if (rmap_item
->address
< vma
->vm_start
||
1742 rmap_item
->address
>= vma
->vm_end
)
1745 * Initially we examine only the vma which covers this
1746 * rmap_item; but later, if there is still work to do,
1747 * we examine covering vmas in other mms: in case they
1748 * were forked from the original since ksmd passed.
1750 if ((rmap_item
->mm
== vma
->vm_mm
) == search_new_forks
)
1753 ret
= try_to_unmap_one(page
, vma
,
1754 rmap_item
->address
, flags
);
1755 if (ret
!= SWAP_AGAIN
|| !page_mapped(page
)) {
1756 anon_vma_unlock_read(anon_vma
);
1760 anon_vma_unlock_read(anon_vma
);
1762 if (!search_new_forks
++)
1768 #ifdef CONFIG_MIGRATION
1769 int rmap_walk_ksm(struct page
*page
, int (*rmap_one
)(struct page
*,
1770 struct vm_area_struct
*, unsigned long, void *), void *arg
)
1772 struct stable_node
*stable_node
;
1773 struct hlist_node
*hlist
;
1774 struct rmap_item
*rmap_item
;
1775 int ret
= SWAP_AGAIN
;
1776 int search_new_forks
= 0;
1778 VM_BUG_ON(!PageKsm(page
));
1779 VM_BUG_ON(!PageLocked(page
));
1781 stable_node
= page_stable_node(page
);
1785 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
1786 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
1787 struct anon_vma_chain
*vmac
;
1788 struct vm_area_struct
*vma
;
1790 anon_vma_lock_read(anon_vma
);
1791 anon_vma_interval_tree_foreach(vmac
, &anon_vma
->rb_root
,
1794 if (rmap_item
->address
< vma
->vm_start
||
1795 rmap_item
->address
>= vma
->vm_end
)
1798 * Initially we examine only the vma which covers this
1799 * rmap_item; but later, if there is still work to do,
1800 * we examine covering vmas in other mms: in case they
1801 * were forked from the original since ksmd passed.
1803 if ((rmap_item
->mm
== vma
->vm_mm
) == search_new_forks
)
1806 ret
= rmap_one(page
, vma
, rmap_item
->address
, arg
);
1807 if (ret
!= SWAP_AGAIN
) {
1808 anon_vma_unlock_read(anon_vma
);
1812 anon_vma_unlock_read(anon_vma
);
1814 if (!search_new_forks
++)
1820 void ksm_migrate_page(struct page
*newpage
, struct page
*oldpage
)
1822 struct stable_node
*stable_node
;
1824 VM_BUG_ON(!PageLocked(oldpage
));
1825 VM_BUG_ON(!PageLocked(newpage
));
1826 VM_BUG_ON(newpage
->mapping
!= oldpage
->mapping
);
1828 stable_node
= page_stable_node(newpage
);
1830 VM_BUG_ON(stable_node
->kpfn
!= page_to_pfn(oldpage
));
1831 stable_node
->kpfn
= page_to_pfn(newpage
);
1834 #endif /* CONFIG_MIGRATION */
1836 #ifdef CONFIG_MEMORY_HOTREMOVE
1837 static struct stable_node
*ksm_check_stable_tree(unsigned long start_pfn
,
1838 unsigned long end_pfn
)
1840 struct rb_node
*node
;
1843 for (nid
= 0; nid
< nr_node_ids
; nid
++)
1844 for (node
= rb_first(&root_stable_tree
[nid
]); node
;
1845 node
= rb_next(node
)) {
1846 struct stable_node
*stable_node
;
1848 stable_node
= rb_entry(node
, struct stable_node
, node
);
1849 if (stable_node
->kpfn
>= start_pfn
&&
1850 stable_node
->kpfn
< end_pfn
)
1857 static int ksm_memory_callback(struct notifier_block
*self
,
1858 unsigned long action
, void *arg
)
1860 struct memory_notify
*mn
= arg
;
1861 struct stable_node
*stable_node
;
1864 case MEM_GOING_OFFLINE
:
1866 * Keep it very simple for now: just lock out ksmd and
1867 * MADV_UNMERGEABLE while any memory is going offline.
1868 * mutex_lock_nested() is necessary because lockdep was alarmed
1869 * that here we take ksm_thread_mutex inside notifier chain
1870 * mutex, and later take notifier chain mutex inside
1871 * ksm_thread_mutex to unlock it. But that's safe because both
1872 * are inside mem_hotplug_mutex.
1874 mutex_lock_nested(&ksm_thread_mutex
, SINGLE_DEPTH_NESTING
);
1879 * Most of the work is done by page migration; but there might
1880 * be a few stable_nodes left over, still pointing to struct
1881 * pages which have been offlined: prune those from the tree.
1883 while ((stable_node
= ksm_check_stable_tree(mn
->start_pfn
,
1884 mn
->start_pfn
+ mn
->nr_pages
)) != NULL
)
1885 remove_node_from_stable_tree(stable_node
);
1888 case MEM_CANCEL_OFFLINE
:
1889 mutex_unlock(&ksm_thread_mutex
);
1894 #endif /* CONFIG_MEMORY_HOTREMOVE */
1898 * This all compiles without CONFIG_SYSFS, but is a waste of space.
1901 #define KSM_ATTR_RO(_name) \
1902 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
1903 #define KSM_ATTR(_name) \
1904 static struct kobj_attribute _name##_attr = \
1905 __ATTR(_name, 0644, _name##_show, _name##_store)
1907 static ssize_t
sleep_millisecs_show(struct kobject
*kobj
,
1908 struct kobj_attribute
*attr
, char *buf
)
1910 return sprintf(buf
, "%u\n", ksm_thread_sleep_millisecs
);
1913 static ssize_t
sleep_millisecs_store(struct kobject
*kobj
,
1914 struct kobj_attribute
*attr
,
1915 const char *buf
, size_t count
)
1917 unsigned long msecs
;
1920 err
= strict_strtoul(buf
, 10, &msecs
);
1921 if (err
|| msecs
> UINT_MAX
)
1924 ksm_thread_sleep_millisecs
= msecs
;
1928 KSM_ATTR(sleep_millisecs
);
1930 static ssize_t
pages_to_scan_show(struct kobject
*kobj
,
1931 struct kobj_attribute
*attr
, char *buf
)
1933 return sprintf(buf
, "%u\n", ksm_thread_pages_to_scan
);
1936 static ssize_t
pages_to_scan_store(struct kobject
*kobj
,
1937 struct kobj_attribute
*attr
,
1938 const char *buf
, size_t count
)
1941 unsigned long nr_pages
;
1943 err
= strict_strtoul(buf
, 10, &nr_pages
);
1944 if (err
|| nr_pages
> UINT_MAX
)
1947 ksm_thread_pages_to_scan
= nr_pages
;
1951 KSM_ATTR(pages_to_scan
);
1953 static ssize_t
run_show(struct kobject
*kobj
, struct kobj_attribute
*attr
,
1956 return sprintf(buf
, "%u\n", ksm_run
);
1959 static ssize_t
run_store(struct kobject
*kobj
, struct kobj_attribute
*attr
,
1960 const char *buf
, size_t count
)
1963 unsigned long flags
;
1965 err
= strict_strtoul(buf
, 10, &flags
);
1966 if (err
|| flags
> UINT_MAX
)
1968 if (flags
> KSM_RUN_UNMERGE
)
1972 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
1973 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
1974 * breaking COW to free the pages_shared (but leaves mm_slots
1975 * on the list for when ksmd may be set running again).
1978 mutex_lock(&ksm_thread_mutex
);
1979 if (ksm_run
!= flags
) {
1981 if (flags
& KSM_RUN_UNMERGE
) {
1982 set_current_oom_origin();
1983 err
= unmerge_and_remove_all_rmap_items();
1984 clear_current_oom_origin();
1986 ksm_run
= KSM_RUN_STOP
;
1991 mutex_unlock(&ksm_thread_mutex
);
1993 if (flags
& KSM_RUN_MERGE
)
1994 wake_up_interruptible(&ksm_thread_wait
);
2001 static ssize_t
merge_across_nodes_show(struct kobject
*kobj
,
2002 struct kobj_attribute
*attr
, char *buf
)
2004 return sprintf(buf
, "%u\n", ksm_merge_across_nodes
);
2007 static ssize_t
merge_across_nodes_store(struct kobject
*kobj
,
2008 struct kobj_attribute
*attr
,
2009 const char *buf
, size_t count
)
2014 err
= kstrtoul(buf
, 10, &knob
);
2020 mutex_lock(&ksm_thread_mutex
);
2021 if (ksm_merge_across_nodes
!= knob
) {
2022 if (ksm_pages_shared
)
2025 ksm_merge_across_nodes
= knob
;
2027 mutex_unlock(&ksm_thread_mutex
);
2029 return err
? err
: count
;
2031 KSM_ATTR(merge_across_nodes
);
2034 static ssize_t
pages_shared_show(struct kobject
*kobj
,
2035 struct kobj_attribute
*attr
, char *buf
)
2037 return sprintf(buf
, "%lu\n", ksm_pages_shared
);
2039 KSM_ATTR_RO(pages_shared
);
2041 static ssize_t
pages_sharing_show(struct kobject
*kobj
,
2042 struct kobj_attribute
*attr
, char *buf
)
2044 return sprintf(buf
, "%lu\n", ksm_pages_sharing
);
2046 KSM_ATTR_RO(pages_sharing
);
2048 static ssize_t
pages_unshared_show(struct kobject
*kobj
,
2049 struct kobj_attribute
*attr
, char *buf
)
2051 return sprintf(buf
, "%lu\n", ksm_pages_unshared
);
2053 KSM_ATTR_RO(pages_unshared
);
2055 static ssize_t
pages_volatile_show(struct kobject
*kobj
,
2056 struct kobj_attribute
*attr
, char *buf
)
2058 long ksm_pages_volatile
;
2060 ksm_pages_volatile
= ksm_rmap_items
- ksm_pages_shared
2061 - ksm_pages_sharing
- ksm_pages_unshared
;
2063 * It was not worth any locking to calculate that statistic,
2064 * but it might therefore sometimes be negative: conceal that.
2066 if (ksm_pages_volatile
< 0)
2067 ksm_pages_volatile
= 0;
2068 return sprintf(buf
, "%ld\n", ksm_pages_volatile
);
2070 KSM_ATTR_RO(pages_volatile
);
2072 static ssize_t
full_scans_show(struct kobject
*kobj
,
2073 struct kobj_attribute
*attr
, char *buf
)
2075 return sprintf(buf
, "%lu\n", ksm_scan
.seqnr
);
2077 KSM_ATTR_RO(full_scans
);
2079 static struct attribute
*ksm_attrs
[] = {
2080 &sleep_millisecs_attr
.attr
,
2081 &pages_to_scan_attr
.attr
,
2083 &pages_shared_attr
.attr
,
2084 &pages_sharing_attr
.attr
,
2085 &pages_unshared_attr
.attr
,
2086 &pages_volatile_attr
.attr
,
2087 &full_scans_attr
.attr
,
2089 &merge_across_nodes_attr
.attr
,
2094 static struct attribute_group ksm_attr_group
= {
2098 #endif /* CONFIG_SYSFS */
2100 static int __init
ksm_init(void)
2102 struct task_struct
*ksm_thread
;
2106 err
= ksm_slab_init();
2110 for (nid
= 0; nid
< nr_node_ids
; nid
++)
2111 root_stable_tree
[nid
] = RB_ROOT
;
2113 ksm_thread
= kthread_run(ksm_scan_thread
, NULL
, "ksmd");
2114 if (IS_ERR(ksm_thread
)) {
2115 printk(KERN_ERR
"ksm: creating kthread failed\n");
2116 err
= PTR_ERR(ksm_thread
);
2121 err
= sysfs_create_group(mm_kobj
, &ksm_attr_group
);
2123 printk(KERN_ERR
"ksm: register sysfs failed\n");
2124 kthread_stop(ksm_thread
);
2128 ksm_run
= KSM_RUN_MERGE
; /* no way for user to start it */
2130 #endif /* CONFIG_SYSFS */
2132 #ifdef CONFIG_MEMORY_HOTREMOVE
2134 * Choose a high priority since the callback takes ksm_thread_mutex:
2135 * later callbacks could only be taking locks which nest within that.
2137 hotplug_memory_notifier(ksm_memory_callback
, 100);
2146 module_init(ksm_init
)