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>
37 #include <asm/tlbflush.h>
41 * A few notes about the KSM scanning process,
42 * to make it easier to understand the data structures below:
44 * In order to reduce excessive scanning, KSM sorts the memory pages by their
45 * contents into a data structure that holds pointers to the pages' locations.
47 * Since the contents of the pages may change at any moment, KSM cannot just
48 * insert the pages into a normal sorted tree and expect it to find anything.
49 * Therefore KSM uses two data structures - the stable and the unstable tree.
51 * The stable tree holds pointers to all the merged pages (ksm pages), sorted
52 * by their contents. Because each such page is write-protected, searching on
53 * this tree is fully assured to be working (except when pages are unmapped),
54 * and therefore this tree is called the stable tree.
56 * In addition to the stable tree, KSM uses a second data structure called the
57 * unstable tree: this tree holds pointers to pages which have been found to
58 * be "unchanged for a period of time". The unstable tree sorts these pages
59 * by their contents, but since they are not write-protected, KSM cannot rely
60 * upon the unstable tree to work correctly - the unstable tree is liable to
61 * be corrupted as its contents are modified, and so it is called unstable.
63 * KSM solves this problem by several techniques:
65 * 1) The unstable tree is flushed every time KSM completes scanning all
66 * memory areas, and then the tree is rebuilt again from the beginning.
67 * 2) KSM will only insert into the unstable tree, pages whose hash value
68 * has not changed since the previous scan of all memory areas.
69 * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
70 * colors of the nodes and not on their contents, assuring that even when
71 * the tree gets "corrupted" it won't get out of balance, so scanning time
72 * remains the same (also, searching and inserting nodes in an rbtree uses
73 * the same algorithm, so we have no overhead when we flush and rebuild).
74 * 4) KSM never flushes the stable tree, which means that even if it were to
75 * take 10 attempts to find a page in the unstable tree, once it is found,
76 * it is secured in the stable tree. (When we scan a new page, we first
77 * compare it against the stable tree, and then against the unstable tree.)
81 * struct mm_slot - ksm information per mm that is being scanned
82 * @link: link to the mm_slots hash list
83 * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
84 * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
85 * @mm: the mm that this information is valid for
88 struct hlist_node link
;
89 struct list_head mm_list
;
90 struct rmap_item
*rmap_list
;
95 * struct ksm_scan - cursor for scanning
96 * @mm_slot: the current mm_slot we are scanning
97 * @address: the next address inside that to be scanned
98 * @rmap_list: link to the next rmap to be scanned in the rmap_list
99 * @seqnr: count of completed full scans (needed when removing unstable node)
101 * There is only the one ksm_scan instance of this cursor structure.
104 struct mm_slot
*mm_slot
;
105 unsigned long address
;
106 struct rmap_item
**rmap_list
;
111 * struct stable_node - node of the stable rbtree
112 * @node: rb node of this ksm page in the stable tree
113 * @hlist: hlist head of rmap_items using this ksm page
114 * @kpfn: page frame number of this ksm page
118 struct hlist_head hlist
;
123 * struct rmap_item - reverse mapping item for virtual addresses
124 * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
125 * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
126 * @mm: the memory structure this rmap_item is pointing into
127 * @address: the virtual address this rmap_item tracks (+ flags in low bits)
128 * @oldchecksum: previous checksum of the page at that virtual address
129 * @node: rb node of this rmap_item in the unstable tree
130 * @head: pointer to stable_node heading this list in the stable tree
131 * @hlist: link into hlist of rmap_items hanging off that stable_node
134 struct rmap_item
*rmap_list
;
135 struct anon_vma
*anon_vma
; /* when stable */
136 struct mm_struct
*mm
;
137 unsigned long address
; /* + low bits used for flags below */
138 unsigned int oldchecksum
; /* when unstable */
140 struct rb_node node
; /* when node of unstable tree */
141 struct { /* when listed from stable tree */
142 struct stable_node
*head
;
143 struct hlist_node hlist
;
148 #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
149 #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
150 #define STABLE_FLAG 0x200 /* is listed from the stable tree */
152 /* The stable and unstable tree heads */
153 static struct rb_root root_stable_tree
= RB_ROOT
;
154 static struct rb_root root_unstable_tree
= RB_ROOT
;
156 #define MM_SLOTS_HASH_HEADS 1024
157 static struct hlist_head
*mm_slots_hash
;
159 static struct mm_slot ksm_mm_head
= {
160 .mm_list
= LIST_HEAD_INIT(ksm_mm_head
.mm_list
),
162 static struct ksm_scan ksm_scan
= {
163 .mm_slot
= &ksm_mm_head
,
166 static struct kmem_cache
*rmap_item_cache
;
167 static struct kmem_cache
*stable_node_cache
;
168 static struct kmem_cache
*mm_slot_cache
;
170 /* The number of nodes in the stable tree */
171 static unsigned long ksm_pages_shared
;
173 /* The number of page slots additionally sharing those nodes */
174 static unsigned long ksm_pages_sharing
;
176 /* The number of nodes in the unstable tree */
177 static unsigned long ksm_pages_unshared
;
179 /* The number of rmap_items in use: to calculate pages_volatile */
180 static unsigned long ksm_rmap_items
;
182 /* Number of pages ksmd should scan in one batch */
183 static unsigned int ksm_thread_pages_to_scan
= 100;
185 /* Milliseconds ksmd should sleep between batches */
186 static unsigned int ksm_thread_sleep_millisecs
= 20;
188 #define KSM_RUN_STOP 0
189 #define KSM_RUN_MERGE 1
190 #define KSM_RUN_UNMERGE 2
191 static unsigned int ksm_run
= KSM_RUN_STOP
;
193 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait
);
194 static DEFINE_MUTEX(ksm_thread_mutex
);
195 static DEFINE_SPINLOCK(ksm_mmlist_lock
);
197 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
198 sizeof(struct __struct), __alignof__(struct __struct),\
201 static int __init
ksm_slab_init(void)
203 rmap_item_cache
= KSM_KMEM_CACHE(rmap_item
, 0);
204 if (!rmap_item_cache
)
207 stable_node_cache
= KSM_KMEM_CACHE(stable_node
, 0);
208 if (!stable_node_cache
)
211 mm_slot_cache
= KSM_KMEM_CACHE(mm_slot
, 0);
218 kmem_cache_destroy(stable_node_cache
);
220 kmem_cache_destroy(rmap_item_cache
);
225 static void __init
ksm_slab_free(void)
227 kmem_cache_destroy(mm_slot_cache
);
228 kmem_cache_destroy(stable_node_cache
);
229 kmem_cache_destroy(rmap_item_cache
);
230 mm_slot_cache
= NULL
;
233 static inline struct rmap_item
*alloc_rmap_item(void)
235 struct rmap_item
*rmap_item
;
237 rmap_item
= kmem_cache_zalloc(rmap_item_cache
, GFP_KERNEL
);
243 static inline void free_rmap_item(struct rmap_item
*rmap_item
)
246 rmap_item
->mm
= NULL
; /* debug safety */
247 kmem_cache_free(rmap_item_cache
, rmap_item
);
250 static inline struct stable_node
*alloc_stable_node(void)
252 return kmem_cache_alloc(stable_node_cache
, GFP_KERNEL
);
255 static inline void free_stable_node(struct stable_node
*stable_node
)
257 kmem_cache_free(stable_node_cache
, stable_node
);
260 static inline struct mm_slot
*alloc_mm_slot(void)
262 if (!mm_slot_cache
) /* initialization failed */
264 return kmem_cache_zalloc(mm_slot_cache
, GFP_KERNEL
);
267 static inline void free_mm_slot(struct mm_slot
*mm_slot
)
269 kmem_cache_free(mm_slot_cache
, mm_slot
);
272 static int __init
mm_slots_hash_init(void)
274 mm_slots_hash
= kzalloc(MM_SLOTS_HASH_HEADS
* sizeof(struct hlist_head
),
281 static void __init
mm_slots_hash_free(void)
283 kfree(mm_slots_hash
);
286 static struct mm_slot
*get_mm_slot(struct mm_struct
*mm
)
288 struct mm_slot
*mm_slot
;
289 struct hlist_head
*bucket
;
290 struct hlist_node
*node
;
292 bucket
= &mm_slots_hash
[((unsigned long)mm
/ sizeof(struct mm_struct
))
293 % MM_SLOTS_HASH_HEADS
];
294 hlist_for_each_entry(mm_slot
, node
, bucket
, link
) {
295 if (mm
== mm_slot
->mm
)
301 static void insert_to_mm_slots_hash(struct mm_struct
*mm
,
302 struct mm_slot
*mm_slot
)
304 struct hlist_head
*bucket
;
306 bucket
= &mm_slots_hash
[((unsigned long)mm
/ sizeof(struct mm_struct
))
307 % MM_SLOTS_HASH_HEADS
];
309 hlist_add_head(&mm_slot
->link
, bucket
);
312 static inline int in_stable_tree(struct rmap_item
*rmap_item
)
314 return rmap_item
->address
& STABLE_FLAG
;
317 static void hold_anon_vma(struct rmap_item
*rmap_item
,
318 struct anon_vma
*anon_vma
)
320 rmap_item
->anon_vma
= anon_vma
;
321 atomic_inc(&anon_vma
->ksm_refcount
);
324 static void drop_anon_vma(struct rmap_item
*rmap_item
)
326 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
328 if (atomic_dec_and_lock(&anon_vma
->ksm_refcount
, &anon_vma
->lock
)) {
329 int empty
= list_empty(&anon_vma
->head
);
330 spin_unlock(&anon_vma
->lock
);
332 anon_vma_free(anon_vma
);
337 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
338 * page tables after it has passed through ksm_exit() - which, if necessary,
339 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
340 * a special flag: they can just back out as soon as mm_users goes to zero.
341 * ksm_test_exit() is used throughout to make this test for exit: in some
342 * places for correctness, in some places just to avoid unnecessary work.
344 static inline bool ksm_test_exit(struct mm_struct
*mm
)
346 return atomic_read(&mm
->mm_users
) == 0;
350 * We use break_ksm to break COW on a ksm page: it's a stripped down
352 * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
355 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
356 * in case the application has unmapped and remapped mm,addr meanwhile.
357 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
358 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
360 static int break_ksm(struct vm_area_struct
*vma
, unsigned long addr
)
367 page
= follow_page(vma
, addr
, FOLL_GET
);
368 if (IS_ERR_OR_NULL(page
))
371 ret
= handle_mm_fault(vma
->vm_mm
, vma
, addr
,
374 ret
= VM_FAULT_WRITE
;
376 } while (!(ret
& (VM_FAULT_WRITE
| VM_FAULT_SIGBUS
| VM_FAULT_OOM
)));
378 * We must loop because handle_mm_fault() may back out if there's
379 * any difficulty e.g. if pte accessed bit gets updated concurrently.
381 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
382 * COW has been broken, even if the vma does not permit VM_WRITE;
383 * but note that a concurrent fault might break PageKsm for us.
385 * VM_FAULT_SIGBUS could occur if we race with truncation of the
386 * backing file, which also invalidates anonymous pages: that's
387 * okay, that truncation will have unmapped the PageKsm for us.
389 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
390 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
391 * current task has TIF_MEMDIE set, and will be OOM killed on return
392 * to user; and ksmd, having no mm, would never be chosen for that.
394 * But if the mm is in a limited mem_cgroup, then the fault may fail
395 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
396 * even ksmd can fail in this way - though it's usually breaking ksm
397 * just to undo a merge it made a moment before, so unlikely to oom.
399 * That's a pity: we might therefore have more kernel pages allocated
400 * than we're counting as nodes in the stable tree; but ksm_do_scan
401 * will retry to break_cow on each pass, so should recover the page
402 * in due course. The important thing is to not let VM_MERGEABLE
403 * be cleared while any such pages might remain in the area.
405 return (ret
& VM_FAULT_OOM
) ? -ENOMEM
: 0;
408 static void break_cow(struct rmap_item
*rmap_item
)
410 struct mm_struct
*mm
= rmap_item
->mm
;
411 unsigned long addr
= rmap_item
->address
;
412 struct vm_area_struct
*vma
;
415 * It is not an accident that whenever we want to break COW
416 * to undo, we also need to drop a reference to the anon_vma.
418 drop_anon_vma(rmap_item
);
420 down_read(&mm
->mmap_sem
);
421 if (ksm_test_exit(mm
))
423 vma
= find_vma(mm
, addr
);
424 if (!vma
|| vma
->vm_start
> addr
)
426 if (!(vma
->vm_flags
& VM_MERGEABLE
) || !vma
->anon_vma
)
428 break_ksm(vma
, addr
);
430 up_read(&mm
->mmap_sem
);
433 static struct page
*get_mergeable_page(struct rmap_item
*rmap_item
)
435 struct mm_struct
*mm
= rmap_item
->mm
;
436 unsigned long addr
= rmap_item
->address
;
437 struct vm_area_struct
*vma
;
440 down_read(&mm
->mmap_sem
);
441 if (ksm_test_exit(mm
))
443 vma
= find_vma(mm
, addr
);
444 if (!vma
|| vma
->vm_start
> addr
)
446 if (!(vma
->vm_flags
& VM_MERGEABLE
) || !vma
->anon_vma
)
449 page
= follow_page(vma
, addr
, FOLL_GET
);
450 if (IS_ERR_OR_NULL(page
))
452 if (PageAnon(page
)) {
453 flush_anon_page(vma
, page
, addr
);
454 flush_dcache_page(page
);
459 up_read(&mm
->mmap_sem
);
463 static void remove_node_from_stable_tree(struct stable_node
*stable_node
)
465 struct rmap_item
*rmap_item
;
466 struct hlist_node
*hlist
;
468 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
469 if (rmap_item
->hlist
.next
)
473 drop_anon_vma(rmap_item
);
474 rmap_item
->address
&= PAGE_MASK
;
478 rb_erase(&stable_node
->node
, &root_stable_tree
);
479 free_stable_node(stable_node
);
483 * get_ksm_page: checks if the page indicated by the stable node
484 * is still its ksm page, despite having held no reference to it.
485 * In which case we can trust the content of the page, and it
486 * returns the gotten page; but if the page has now been zapped,
487 * remove the stale node from the stable tree and return NULL.
489 * You would expect the stable_node to hold a reference to the ksm page.
490 * But if it increments the page's count, swapping out has to wait for
491 * ksmd to come around again before it can free the page, which may take
492 * seconds or even minutes: much too unresponsive. So instead we use a
493 * "keyhole reference": access to the ksm page from the stable node peeps
494 * out through its keyhole to see if that page still holds the right key,
495 * pointing back to this stable node. This relies on freeing a PageAnon
496 * page to reset its page->mapping to NULL, and relies on no other use of
497 * a page to put something that might look like our key in page->mapping.
499 * include/linux/pagemap.h page_cache_get_speculative() is a good reference,
500 * but this is different - made simpler by ksm_thread_mutex being held, but
501 * interesting for assuming that no other use of the struct page could ever
502 * put our expected_mapping into page->mapping (or a field of the union which
503 * coincides with page->mapping). The RCU calls are not for KSM at all, but
504 * to keep the page_count protocol described with page_cache_get_speculative.
506 * Note: it is possible that get_ksm_page() will return NULL one moment,
507 * then page the next, if the page is in between page_freeze_refs() and
508 * page_unfreeze_refs(): this shouldn't be a problem anywhere, the page
509 * is on its way to being freed; but it is an anomaly to bear in mind.
511 static struct page
*get_ksm_page(struct stable_node
*stable_node
)
514 void *expected_mapping
;
516 page
= pfn_to_page(stable_node
->kpfn
);
517 expected_mapping
= (void *)stable_node
+
518 (PAGE_MAPPING_ANON
| PAGE_MAPPING_KSM
);
520 if (page
->mapping
!= expected_mapping
)
522 if (!get_page_unless_zero(page
))
524 if (page
->mapping
!= expected_mapping
) {
532 remove_node_from_stable_tree(stable_node
);
537 * Removing rmap_item from stable or unstable tree.
538 * This function will clean the information from the stable/unstable tree.
540 static void remove_rmap_item_from_tree(struct rmap_item
*rmap_item
)
542 if (rmap_item
->address
& STABLE_FLAG
) {
543 struct stable_node
*stable_node
;
546 stable_node
= rmap_item
->head
;
547 page
= get_ksm_page(stable_node
);
552 hlist_del(&rmap_item
->hlist
);
556 if (stable_node
->hlist
.first
)
561 drop_anon_vma(rmap_item
);
562 rmap_item
->address
&= PAGE_MASK
;
564 } else if (rmap_item
->address
& UNSTABLE_FLAG
) {
567 * Usually ksmd can and must skip the rb_erase, because
568 * root_unstable_tree was already reset to RB_ROOT.
569 * But be careful when an mm is exiting: do the rb_erase
570 * if this rmap_item was inserted by this scan, rather
571 * than left over from before.
573 age
= (unsigned char)(ksm_scan
.seqnr
- rmap_item
->address
);
576 rb_erase(&rmap_item
->node
, &root_unstable_tree
);
578 ksm_pages_unshared
--;
579 rmap_item
->address
&= PAGE_MASK
;
582 cond_resched(); /* we're called from many long loops */
585 static void remove_trailing_rmap_items(struct mm_slot
*mm_slot
,
586 struct rmap_item
**rmap_list
)
589 struct rmap_item
*rmap_item
= *rmap_list
;
590 *rmap_list
= rmap_item
->rmap_list
;
591 remove_rmap_item_from_tree(rmap_item
);
592 free_rmap_item(rmap_item
);
597 * Though it's very tempting to unmerge in_stable_tree(rmap_item)s rather
598 * than check every pte of a given vma, the locking doesn't quite work for
599 * that - an rmap_item is assigned to the stable tree after inserting ksm
600 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
601 * rmap_items from parent to child at fork time (so as not to waste time
602 * if exit comes before the next scan reaches it).
604 * Similarly, although we'd like to remove rmap_items (so updating counts
605 * and freeing memory) when unmerging an area, it's easier to leave that
606 * to the next pass of ksmd - consider, for example, how ksmd might be
607 * in cmp_and_merge_page on one of the rmap_items we would be removing.
609 static int unmerge_ksm_pages(struct vm_area_struct
*vma
,
610 unsigned long start
, unsigned long end
)
615 for (addr
= start
; addr
< end
&& !err
; addr
+= PAGE_SIZE
) {
616 if (ksm_test_exit(vma
->vm_mm
))
618 if (signal_pending(current
))
621 err
= break_ksm(vma
, addr
);
628 * Only called through the sysfs control interface:
630 static int unmerge_and_remove_all_rmap_items(void)
632 struct mm_slot
*mm_slot
;
633 struct mm_struct
*mm
;
634 struct vm_area_struct
*vma
;
637 spin_lock(&ksm_mmlist_lock
);
638 ksm_scan
.mm_slot
= list_entry(ksm_mm_head
.mm_list
.next
,
639 struct mm_slot
, mm_list
);
640 spin_unlock(&ksm_mmlist_lock
);
642 for (mm_slot
= ksm_scan
.mm_slot
;
643 mm_slot
!= &ksm_mm_head
; mm_slot
= ksm_scan
.mm_slot
) {
645 down_read(&mm
->mmap_sem
);
646 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
647 if (ksm_test_exit(mm
))
649 if (!(vma
->vm_flags
& VM_MERGEABLE
) || !vma
->anon_vma
)
651 err
= unmerge_ksm_pages(vma
,
652 vma
->vm_start
, vma
->vm_end
);
657 remove_trailing_rmap_items(mm_slot
, &mm_slot
->rmap_list
);
659 spin_lock(&ksm_mmlist_lock
);
660 ksm_scan
.mm_slot
= list_entry(mm_slot
->mm_list
.next
,
661 struct mm_slot
, mm_list
);
662 if (ksm_test_exit(mm
)) {
663 hlist_del(&mm_slot
->link
);
664 list_del(&mm_slot
->mm_list
);
665 spin_unlock(&ksm_mmlist_lock
);
667 free_mm_slot(mm_slot
);
668 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
669 up_read(&mm
->mmap_sem
);
672 spin_unlock(&ksm_mmlist_lock
);
673 up_read(&mm
->mmap_sem
);
681 up_read(&mm
->mmap_sem
);
682 spin_lock(&ksm_mmlist_lock
);
683 ksm_scan
.mm_slot
= &ksm_mm_head
;
684 spin_unlock(&ksm_mmlist_lock
);
687 #endif /* CONFIG_SYSFS */
689 static u32
calc_checksum(struct page
*page
)
692 void *addr
= kmap_atomic(page
, KM_USER0
);
693 checksum
= jhash2(addr
, PAGE_SIZE
/ 4, 17);
694 kunmap_atomic(addr
, KM_USER0
);
698 static int memcmp_pages(struct page
*page1
, struct page
*page2
)
703 addr1
= kmap_atomic(page1
, KM_USER0
);
704 addr2
= kmap_atomic(page2
, KM_USER1
);
705 ret
= memcmp(addr1
, addr2
, PAGE_SIZE
);
706 kunmap_atomic(addr2
, KM_USER1
);
707 kunmap_atomic(addr1
, KM_USER0
);
711 static inline int pages_identical(struct page
*page1
, struct page
*page2
)
713 return !memcmp_pages(page1
, page2
);
716 static int write_protect_page(struct vm_area_struct
*vma
, struct page
*page
,
719 struct mm_struct
*mm
= vma
->vm_mm
;
726 addr
= page_address_in_vma(page
, vma
);
730 ptep
= page_check_address(page
, mm
, addr
, &ptl
, 0);
734 if (pte_write(*ptep
)) {
737 swapped
= PageSwapCache(page
);
738 flush_cache_page(vma
, addr
, page_to_pfn(page
));
740 * Ok this is tricky, when get_user_pages_fast() run it doesnt
741 * take any lock, therefore the check that we are going to make
742 * with the pagecount against the mapcount is racey and
743 * O_DIRECT can happen right after the check.
744 * So we clear the pte and flush the tlb before the check
745 * this assure us that no O_DIRECT can happen after the check
746 * or in the middle of the check.
748 entry
= ptep_clear_flush(vma
, addr
, ptep
);
750 * Check that no O_DIRECT or similar I/O is in progress on the
753 if (page_mapcount(page
) + 1 + swapped
!= page_count(page
)) {
754 set_pte_at(mm
, addr
, ptep
, entry
);
757 entry
= pte_wrprotect(entry
);
758 set_pte_at_notify(mm
, addr
, ptep
, entry
);
764 pte_unmap_unlock(ptep
, ptl
);
770 * replace_page - replace page in vma by new ksm page
771 * @vma: vma that holds the pte pointing to page
772 * @page: the page we are replacing by kpage
773 * @kpage: the ksm page we replace page by
774 * @orig_pte: the original value of the pte
776 * Returns 0 on success, -EFAULT on failure.
778 static int replace_page(struct vm_area_struct
*vma
, struct page
*page
,
779 struct page
*kpage
, pte_t orig_pte
)
781 struct mm_struct
*mm
= vma
->vm_mm
;
790 addr
= page_address_in_vma(page
, vma
);
794 pgd
= pgd_offset(mm
, addr
);
795 if (!pgd_present(*pgd
))
798 pud
= pud_offset(pgd
, addr
);
799 if (!pud_present(*pud
))
802 pmd
= pmd_offset(pud
, addr
);
803 if (!pmd_present(*pmd
))
806 ptep
= pte_offset_map_lock(mm
, pmd
, addr
, &ptl
);
807 if (!pte_same(*ptep
, orig_pte
)) {
808 pte_unmap_unlock(ptep
, ptl
);
813 page_add_anon_rmap(kpage
, vma
, addr
);
815 flush_cache_page(vma
, addr
, pte_pfn(*ptep
));
816 ptep_clear_flush(vma
, addr
, ptep
);
817 set_pte_at_notify(mm
, addr
, ptep
, mk_pte(kpage
, vma
->vm_page_prot
));
819 page_remove_rmap(page
);
822 pte_unmap_unlock(ptep
, ptl
);
829 * try_to_merge_one_page - take two pages and merge them into one
830 * @vma: the vma that holds the pte pointing to page
831 * @page: the PageAnon page that we want to replace with kpage
832 * @kpage: the PageKsm page that we want to map instead of page,
833 * or NULL the first time when we want to use page as kpage.
835 * This function returns 0 if the pages were merged, -EFAULT otherwise.
837 static int try_to_merge_one_page(struct vm_area_struct
*vma
,
838 struct page
*page
, struct page
*kpage
)
840 pte_t orig_pte
= __pte(0);
843 if (page
== kpage
) /* ksm page forked */
846 if (!(vma
->vm_flags
& VM_MERGEABLE
))
852 * We need the page lock to read a stable PageSwapCache in
853 * write_protect_page(). We use trylock_page() instead of
854 * lock_page() because we don't want to wait here - we
855 * prefer to continue scanning and merging different pages,
856 * then come back to this page when it is unlocked.
858 if (!trylock_page(page
))
861 * If this anonymous page is mapped only here, its pte may need
862 * to be write-protected. If it's mapped elsewhere, all of its
863 * ptes are necessarily already write-protected. But in either
864 * case, we need to lock and check page_count is not raised.
866 if (write_protect_page(vma
, page
, &orig_pte
) == 0) {
869 * While we hold page lock, upgrade page from
870 * PageAnon+anon_vma to PageKsm+NULL stable_node:
871 * stable_tree_insert() will update stable_node.
873 set_page_stable_node(page
, NULL
);
874 mark_page_accessed(page
);
876 } else if (pages_identical(page
, kpage
))
877 err
= replace_page(vma
, page
, kpage
, orig_pte
);
880 if ((vma
->vm_flags
& VM_LOCKED
) && kpage
&& !err
) {
881 munlock_vma_page(page
);
882 if (!PageMlocked(kpage
)) {
885 mlock_vma_page(kpage
);
886 page
= kpage
; /* for final unlock */
896 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
897 * but no new kernel page is allocated: kpage must already be a ksm page.
899 * This function returns 0 if the pages were merged, -EFAULT otherwise.
901 static int try_to_merge_with_ksm_page(struct rmap_item
*rmap_item
,
902 struct page
*page
, struct page
*kpage
)
904 struct mm_struct
*mm
= rmap_item
->mm
;
905 struct vm_area_struct
*vma
;
908 down_read(&mm
->mmap_sem
);
909 if (ksm_test_exit(mm
))
911 vma
= find_vma(mm
, rmap_item
->address
);
912 if (!vma
|| vma
->vm_start
> rmap_item
->address
)
915 err
= try_to_merge_one_page(vma
, page
, kpage
);
919 /* Must get reference to anon_vma while still holding mmap_sem */
920 hold_anon_vma(rmap_item
, vma
->anon_vma
);
922 up_read(&mm
->mmap_sem
);
927 * try_to_merge_two_pages - take two identical pages and prepare them
928 * to be merged into one page.
930 * This function returns the kpage if we successfully merged two identical
931 * pages into one ksm page, NULL otherwise.
933 * Note that this function upgrades page to ksm page: if one of the pages
934 * is already a ksm page, try_to_merge_with_ksm_page should be used.
936 static struct page
*try_to_merge_two_pages(struct rmap_item
*rmap_item
,
938 struct rmap_item
*tree_rmap_item
,
939 struct page
*tree_page
)
943 err
= try_to_merge_with_ksm_page(rmap_item
, page
, NULL
);
945 err
= try_to_merge_with_ksm_page(tree_rmap_item
,
948 * If that fails, we have a ksm page with only one pte
949 * pointing to it: so break it.
952 break_cow(rmap_item
);
954 return err
? NULL
: page
;
958 * stable_tree_search - search for page inside the stable tree
960 * This function checks if there is a page inside the stable tree
961 * with identical content to the page that we are scanning right now.
963 * This function returns the stable tree node of identical content if found,
966 static struct page
*stable_tree_search(struct page
*page
)
968 struct rb_node
*node
= root_stable_tree
.rb_node
;
969 struct stable_node
*stable_node
;
971 stable_node
= page_stable_node(page
);
972 if (stable_node
) { /* ksm page forked */
978 struct page
*tree_page
;
982 stable_node
= rb_entry(node
, struct stable_node
, node
);
983 tree_page
= get_ksm_page(stable_node
);
987 ret
= memcmp_pages(page
, tree_page
);
991 node
= node
->rb_left
;
992 } else if (ret
> 0) {
994 node
= node
->rb_right
;
1003 * stable_tree_insert - insert rmap_item pointing to new ksm page
1004 * into the stable tree.
1006 * This function returns the stable tree node just allocated on success,
1009 static struct stable_node
*stable_tree_insert(struct page
*kpage
)
1011 struct rb_node
**new = &root_stable_tree
.rb_node
;
1012 struct rb_node
*parent
= NULL
;
1013 struct stable_node
*stable_node
;
1016 struct page
*tree_page
;
1020 stable_node
= rb_entry(*new, struct stable_node
, node
);
1021 tree_page
= get_ksm_page(stable_node
);
1025 ret
= memcmp_pages(kpage
, tree_page
);
1026 put_page(tree_page
);
1030 new = &parent
->rb_left
;
1032 new = &parent
->rb_right
;
1035 * It is not a bug that stable_tree_search() didn't
1036 * find this node: because at that time our page was
1037 * not yet write-protected, so may have changed since.
1043 stable_node
= alloc_stable_node();
1047 rb_link_node(&stable_node
->node
, parent
, new);
1048 rb_insert_color(&stable_node
->node
, &root_stable_tree
);
1050 INIT_HLIST_HEAD(&stable_node
->hlist
);
1052 stable_node
->kpfn
= page_to_pfn(kpage
);
1053 set_page_stable_node(kpage
, stable_node
);
1059 * unstable_tree_search_insert - search for identical page,
1060 * else insert rmap_item into the unstable tree.
1062 * This function searches for a page in the unstable tree identical to the
1063 * page currently being scanned; and if no identical page is found in the
1064 * tree, we insert rmap_item as a new object into the unstable tree.
1066 * This function returns pointer to rmap_item found to be identical
1067 * to the currently scanned page, NULL otherwise.
1069 * This function does both searching and inserting, because they share
1070 * the same walking algorithm in an rbtree.
1073 struct rmap_item
*unstable_tree_search_insert(struct rmap_item
*rmap_item
,
1075 struct page
**tree_pagep
)
1078 struct rb_node
**new = &root_unstable_tree
.rb_node
;
1079 struct rb_node
*parent
= NULL
;
1082 struct rmap_item
*tree_rmap_item
;
1083 struct page
*tree_page
;
1087 tree_rmap_item
= rb_entry(*new, struct rmap_item
, node
);
1088 tree_page
= get_mergeable_page(tree_rmap_item
);
1089 if (IS_ERR_OR_NULL(tree_page
))
1093 * Don't substitute a ksm page for a forked page.
1095 if (page
== tree_page
) {
1096 put_page(tree_page
);
1100 ret
= memcmp_pages(page
, tree_page
);
1104 put_page(tree_page
);
1105 new = &parent
->rb_left
;
1106 } else if (ret
> 0) {
1107 put_page(tree_page
);
1108 new = &parent
->rb_right
;
1110 *tree_pagep
= tree_page
;
1111 return tree_rmap_item
;
1115 rmap_item
->address
|= UNSTABLE_FLAG
;
1116 rmap_item
->address
|= (ksm_scan
.seqnr
& SEQNR_MASK
);
1117 rb_link_node(&rmap_item
->node
, parent
, new);
1118 rb_insert_color(&rmap_item
->node
, &root_unstable_tree
);
1120 ksm_pages_unshared
++;
1125 * stable_tree_append - add another rmap_item to the linked list of
1126 * rmap_items hanging off a given node of the stable tree, all sharing
1127 * the same ksm page.
1129 static void stable_tree_append(struct rmap_item
*rmap_item
,
1130 struct stable_node
*stable_node
)
1132 rmap_item
->head
= stable_node
;
1133 rmap_item
->address
|= STABLE_FLAG
;
1134 hlist_add_head(&rmap_item
->hlist
, &stable_node
->hlist
);
1136 if (rmap_item
->hlist
.next
)
1137 ksm_pages_sharing
++;
1143 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1144 * if not, compare checksum to previous and if it's the same, see if page can
1145 * be inserted into the unstable tree, or merged with a page already there and
1146 * both transferred to the stable tree.
1148 * @page: the page that we are searching identical page to.
1149 * @rmap_item: the reverse mapping into the virtual address of this page
1151 static void cmp_and_merge_page(struct page
*page
, struct rmap_item
*rmap_item
)
1153 struct rmap_item
*tree_rmap_item
;
1154 struct page
*tree_page
= NULL
;
1155 struct stable_node
*stable_node
;
1157 unsigned int checksum
;
1160 remove_rmap_item_from_tree(rmap_item
);
1162 /* We first start with searching the page inside the stable tree */
1163 kpage
= stable_tree_search(page
);
1165 err
= try_to_merge_with_ksm_page(rmap_item
, page
, kpage
);
1168 * The page was successfully merged:
1169 * add its rmap_item to the stable tree.
1172 stable_tree_append(rmap_item
, page_stable_node(kpage
));
1180 * If the hash value of the page has changed from the last time
1181 * we calculated it, this page is changing frequently: therefore we
1182 * don't want to insert it in the unstable tree, and we don't want
1183 * to waste our time searching for something identical to it there.
1185 checksum
= calc_checksum(page
);
1186 if (rmap_item
->oldchecksum
!= checksum
) {
1187 rmap_item
->oldchecksum
= checksum
;
1192 unstable_tree_search_insert(rmap_item
, page
, &tree_page
);
1193 if (tree_rmap_item
) {
1194 kpage
= try_to_merge_two_pages(rmap_item
, page
,
1195 tree_rmap_item
, tree_page
);
1196 put_page(tree_page
);
1198 * As soon as we merge this page, we want to remove the
1199 * rmap_item of the page we have merged with from the unstable
1200 * tree, and insert it instead as new node in the stable tree.
1203 remove_rmap_item_from_tree(tree_rmap_item
);
1206 stable_node
= stable_tree_insert(kpage
);
1208 stable_tree_append(tree_rmap_item
, stable_node
);
1209 stable_tree_append(rmap_item
, stable_node
);
1214 * If we fail to insert the page into the stable tree,
1215 * we will have 2 virtual addresses that are pointing
1216 * to a ksm page left outside the stable tree,
1217 * in which case we need to break_cow on both.
1220 break_cow(tree_rmap_item
);
1221 break_cow(rmap_item
);
1227 static struct rmap_item
*get_next_rmap_item(struct mm_slot
*mm_slot
,
1228 struct rmap_item
**rmap_list
,
1231 struct rmap_item
*rmap_item
;
1233 while (*rmap_list
) {
1234 rmap_item
= *rmap_list
;
1235 if ((rmap_item
->address
& PAGE_MASK
) == addr
)
1237 if (rmap_item
->address
> addr
)
1239 *rmap_list
= rmap_item
->rmap_list
;
1240 remove_rmap_item_from_tree(rmap_item
);
1241 free_rmap_item(rmap_item
);
1244 rmap_item
= alloc_rmap_item();
1246 /* It has already been zeroed */
1247 rmap_item
->mm
= mm_slot
->mm
;
1248 rmap_item
->address
= addr
;
1249 rmap_item
->rmap_list
= *rmap_list
;
1250 *rmap_list
= rmap_item
;
1255 static struct rmap_item
*scan_get_next_rmap_item(struct page
**page
)
1257 struct mm_struct
*mm
;
1258 struct mm_slot
*slot
;
1259 struct vm_area_struct
*vma
;
1260 struct rmap_item
*rmap_item
;
1262 if (list_empty(&ksm_mm_head
.mm_list
))
1265 slot
= ksm_scan
.mm_slot
;
1266 if (slot
== &ksm_mm_head
) {
1267 root_unstable_tree
= RB_ROOT
;
1269 spin_lock(&ksm_mmlist_lock
);
1270 slot
= list_entry(slot
->mm_list
.next
, struct mm_slot
, mm_list
);
1271 ksm_scan
.mm_slot
= slot
;
1272 spin_unlock(&ksm_mmlist_lock
);
1274 * Although we tested list_empty() above, a racing __ksm_exit
1275 * of the last mm on the list may have removed it since then.
1277 if (slot
== &ksm_mm_head
)
1280 ksm_scan
.address
= 0;
1281 ksm_scan
.rmap_list
= &slot
->rmap_list
;
1285 down_read(&mm
->mmap_sem
);
1286 if (ksm_test_exit(mm
))
1289 vma
= find_vma(mm
, ksm_scan
.address
);
1291 for (; vma
; vma
= vma
->vm_next
) {
1292 if (!(vma
->vm_flags
& VM_MERGEABLE
))
1294 if (ksm_scan
.address
< vma
->vm_start
)
1295 ksm_scan
.address
= vma
->vm_start
;
1297 ksm_scan
.address
= vma
->vm_end
;
1299 while (ksm_scan
.address
< vma
->vm_end
) {
1300 if (ksm_test_exit(mm
))
1302 *page
= follow_page(vma
, ksm_scan
.address
, FOLL_GET
);
1303 if (!IS_ERR_OR_NULL(*page
) && PageAnon(*page
)) {
1304 flush_anon_page(vma
, *page
, ksm_scan
.address
);
1305 flush_dcache_page(*page
);
1306 rmap_item
= get_next_rmap_item(slot
,
1307 ksm_scan
.rmap_list
, ksm_scan
.address
);
1309 ksm_scan
.rmap_list
=
1310 &rmap_item
->rmap_list
;
1311 ksm_scan
.address
+= PAGE_SIZE
;
1314 up_read(&mm
->mmap_sem
);
1317 if (!IS_ERR_OR_NULL(*page
))
1319 ksm_scan
.address
+= PAGE_SIZE
;
1324 if (ksm_test_exit(mm
)) {
1325 ksm_scan
.address
= 0;
1326 ksm_scan
.rmap_list
= &slot
->rmap_list
;
1329 * Nuke all the rmap_items that are above this current rmap:
1330 * because there were no VM_MERGEABLE vmas with such addresses.
1332 remove_trailing_rmap_items(slot
, ksm_scan
.rmap_list
);
1334 spin_lock(&ksm_mmlist_lock
);
1335 ksm_scan
.mm_slot
= list_entry(slot
->mm_list
.next
,
1336 struct mm_slot
, mm_list
);
1337 if (ksm_scan
.address
== 0) {
1339 * We've completed a full scan of all vmas, holding mmap_sem
1340 * throughout, and found no VM_MERGEABLE: so do the same as
1341 * __ksm_exit does to remove this mm from all our lists now.
1342 * This applies either when cleaning up after __ksm_exit
1343 * (but beware: we can reach here even before __ksm_exit),
1344 * or when all VM_MERGEABLE areas have been unmapped (and
1345 * mmap_sem then protects against race with MADV_MERGEABLE).
1347 hlist_del(&slot
->link
);
1348 list_del(&slot
->mm_list
);
1349 spin_unlock(&ksm_mmlist_lock
);
1352 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
1353 up_read(&mm
->mmap_sem
);
1356 spin_unlock(&ksm_mmlist_lock
);
1357 up_read(&mm
->mmap_sem
);
1360 /* Repeat until we've completed scanning the whole list */
1361 slot
= ksm_scan
.mm_slot
;
1362 if (slot
!= &ksm_mm_head
)
1370 * ksm_do_scan - the ksm scanner main worker function.
1371 * @scan_npages - number of pages we want to scan before we return.
1373 static void ksm_do_scan(unsigned int scan_npages
)
1375 struct rmap_item
*rmap_item
;
1376 struct page
*uninitialized_var(page
);
1378 while (scan_npages
--) {
1380 rmap_item
= scan_get_next_rmap_item(&page
);
1383 if (!PageKsm(page
) || !in_stable_tree(rmap_item
))
1384 cmp_and_merge_page(page
, rmap_item
);
1389 static int ksmd_should_run(void)
1391 return (ksm_run
& KSM_RUN_MERGE
) && !list_empty(&ksm_mm_head
.mm_list
);
1394 static int ksm_scan_thread(void *nothing
)
1396 set_user_nice(current
, 5);
1398 while (!kthread_should_stop()) {
1399 mutex_lock(&ksm_thread_mutex
);
1400 if (ksmd_should_run())
1401 ksm_do_scan(ksm_thread_pages_to_scan
);
1402 mutex_unlock(&ksm_thread_mutex
);
1404 if (ksmd_should_run()) {
1405 schedule_timeout_interruptible(
1406 msecs_to_jiffies(ksm_thread_sleep_millisecs
));
1408 wait_event_interruptible(ksm_thread_wait
,
1409 ksmd_should_run() || kthread_should_stop());
1415 int ksm_madvise(struct vm_area_struct
*vma
, unsigned long start
,
1416 unsigned long end
, int advice
, unsigned long *vm_flags
)
1418 struct mm_struct
*mm
= vma
->vm_mm
;
1422 case MADV_MERGEABLE
:
1424 * Be somewhat over-protective for now!
1426 if (*vm_flags
& (VM_MERGEABLE
| VM_SHARED
| VM_MAYSHARE
|
1427 VM_PFNMAP
| VM_IO
| VM_DONTEXPAND
|
1428 VM_RESERVED
| VM_HUGETLB
| VM_INSERTPAGE
|
1429 VM_NONLINEAR
| VM_MIXEDMAP
| VM_SAO
))
1430 return 0; /* just ignore the advice */
1432 if (!test_bit(MMF_VM_MERGEABLE
, &mm
->flags
)) {
1433 err
= __ksm_enter(mm
);
1438 *vm_flags
|= VM_MERGEABLE
;
1441 case MADV_UNMERGEABLE
:
1442 if (!(*vm_flags
& VM_MERGEABLE
))
1443 return 0; /* just ignore the advice */
1445 if (vma
->anon_vma
) {
1446 err
= unmerge_ksm_pages(vma
, start
, end
);
1451 *vm_flags
&= ~VM_MERGEABLE
;
1458 int __ksm_enter(struct mm_struct
*mm
)
1460 struct mm_slot
*mm_slot
;
1463 mm_slot
= alloc_mm_slot();
1467 /* Check ksm_run too? Would need tighter locking */
1468 needs_wakeup
= list_empty(&ksm_mm_head
.mm_list
);
1470 spin_lock(&ksm_mmlist_lock
);
1471 insert_to_mm_slots_hash(mm
, mm_slot
);
1473 * Insert just behind the scanning cursor, to let the area settle
1474 * down a little; when fork is followed by immediate exec, we don't
1475 * want ksmd to waste time setting up and tearing down an rmap_list.
1477 list_add_tail(&mm_slot
->mm_list
, &ksm_scan
.mm_slot
->mm_list
);
1478 spin_unlock(&ksm_mmlist_lock
);
1480 set_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
1481 atomic_inc(&mm
->mm_count
);
1484 wake_up_interruptible(&ksm_thread_wait
);
1489 void __ksm_exit(struct mm_struct
*mm
)
1491 struct mm_slot
*mm_slot
;
1492 int easy_to_free
= 0;
1495 * This process is exiting: if it's straightforward (as is the
1496 * case when ksmd was never running), free mm_slot immediately.
1497 * But if it's at the cursor or has rmap_items linked to it, use
1498 * mmap_sem to synchronize with any break_cows before pagetables
1499 * are freed, and leave the mm_slot on the list for ksmd to free.
1500 * Beware: ksm may already have noticed it exiting and freed the slot.
1503 spin_lock(&ksm_mmlist_lock
);
1504 mm_slot
= get_mm_slot(mm
);
1505 if (mm_slot
&& ksm_scan
.mm_slot
!= mm_slot
) {
1506 if (!mm_slot
->rmap_list
) {
1507 hlist_del(&mm_slot
->link
);
1508 list_del(&mm_slot
->mm_list
);
1511 list_move(&mm_slot
->mm_list
,
1512 &ksm_scan
.mm_slot
->mm_list
);
1515 spin_unlock(&ksm_mmlist_lock
);
1518 free_mm_slot(mm_slot
);
1519 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
1521 } else if (mm_slot
) {
1522 down_write(&mm
->mmap_sem
);
1523 up_write(&mm
->mmap_sem
);
1527 struct page
*ksm_does_need_to_copy(struct page
*page
,
1528 struct vm_area_struct
*vma
, unsigned long address
)
1530 struct page
*new_page
;
1532 unlock_page(page
); /* any racers will COW it, not modify it */
1534 new_page
= alloc_page_vma(GFP_HIGHUSER_MOVABLE
, vma
, address
);
1536 copy_user_highpage(new_page
, page
, address
, vma
);
1538 SetPageDirty(new_page
);
1539 __SetPageUptodate(new_page
);
1540 SetPageSwapBacked(new_page
);
1541 __set_page_locked(new_page
);
1543 if (page_evictable(new_page
, vma
))
1544 lru_cache_add_lru(new_page
, LRU_ACTIVE_ANON
);
1546 add_page_to_unevictable_list(new_page
);
1549 page_cache_release(page
);
1553 int page_referenced_ksm(struct page
*page
, struct mem_cgroup
*memcg
,
1554 unsigned long *vm_flags
)
1556 struct stable_node
*stable_node
;
1557 struct rmap_item
*rmap_item
;
1558 struct hlist_node
*hlist
;
1559 unsigned int mapcount
= page_mapcount(page
);
1561 int search_new_forks
= 0;
1563 VM_BUG_ON(!PageKsm(page
));
1564 VM_BUG_ON(!PageLocked(page
));
1566 stable_node
= page_stable_node(page
);
1570 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
1571 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
1572 struct anon_vma_chain
*vmac
;
1573 struct vm_area_struct
*vma
;
1575 spin_lock(&anon_vma
->lock
);
1576 list_for_each_entry(vmac
, &anon_vma
->head
, same_anon_vma
) {
1578 if (rmap_item
->address
< vma
->vm_start
||
1579 rmap_item
->address
>= vma
->vm_end
)
1582 * Initially we examine only the vma which covers this
1583 * rmap_item; but later, if there is still work to do,
1584 * we examine covering vmas in other mms: in case they
1585 * were forked from the original since ksmd passed.
1587 if ((rmap_item
->mm
== vma
->vm_mm
) == search_new_forks
)
1590 if (memcg
&& !mm_match_cgroup(vma
->vm_mm
, memcg
))
1593 referenced
+= page_referenced_one(page
, vma
,
1594 rmap_item
->address
, &mapcount
, vm_flags
);
1595 if (!search_new_forks
|| !mapcount
)
1598 spin_unlock(&anon_vma
->lock
);
1602 if (!search_new_forks
++)
1608 int try_to_unmap_ksm(struct page
*page
, enum ttu_flags flags
)
1610 struct stable_node
*stable_node
;
1611 struct hlist_node
*hlist
;
1612 struct rmap_item
*rmap_item
;
1613 int ret
= SWAP_AGAIN
;
1614 int search_new_forks
= 0;
1616 VM_BUG_ON(!PageKsm(page
));
1617 VM_BUG_ON(!PageLocked(page
));
1619 stable_node
= page_stable_node(page
);
1623 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
1624 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
1625 struct anon_vma_chain
*vmac
;
1626 struct vm_area_struct
*vma
;
1628 spin_lock(&anon_vma
->lock
);
1629 list_for_each_entry(vmac
, &anon_vma
->head
, same_anon_vma
) {
1631 if (rmap_item
->address
< vma
->vm_start
||
1632 rmap_item
->address
>= vma
->vm_end
)
1635 * Initially we examine only the vma which covers this
1636 * rmap_item; but later, if there is still work to do,
1637 * we examine covering vmas in other mms: in case they
1638 * were forked from the original since ksmd passed.
1640 if ((rmap_item
->mm
== vma
->vm_mm
) == search_new_forks
)
1643 ret
= try_to_unmap_one(page
, vma
,
1644 rmap_item
->address
, flags
);
1645 if (ret
!= SWAP_AGAIN
|| !page_mapped(page
)) {
1646 spin_unlock(&anon_vma
->lock
);
1650 spin_unlock(&anon_vma
->lock
);
1652 if (!search_new_forks
++)
1658 #ifdef CONFIG_MIGRATION
1659 int rmap_walk_ksm(struct page
*page
, int (*rmap_one
)(struct page
*,
1660 struct vm_area_struct
*, unsigned long, void *), void *arg
)
1662 struct stable_node
*stable_node
;
1663 struct hlist_node
*hlist
;
1664 struct rmap_item
*rmap_item
;
1665 int ret
= SWAP_AGAIN
;
1666 int search_new_forks
= 0;
1668 VM_BUG_ON(!PageKsm(page
));
1669 VM_BUG_ON(!PageLocked(page
));
1671 stable_node
= page_stable_node(page
);
1675 hlist_for_each_entry(rmap_item
, hlist
, &stable_node
->hlist
, hlist
) {
1676 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
1677 struct anon_vma_chain
*vmac
;
1678 struct vm_area_struct
*vma
;
1680 spin_lock(&anon_vma
->lock
);
1681 list_for_each_entry(vmac
, &anon_vma
->head
, same_anon_vma
) {
1683 if (rmap_item
->address
< vma
->vm_start
||
1684 rmap_item
->address
>= vma
->vm_end
)
1687 * Initially we examine only the vma which covers this
1688 * rmap_item; but later, if there is still work to do,
1689 * we examine covering vmas in other mms: in case they
1690 * were forked from the original since ksmd passed.
1692 if ((rmap_item
->mm
== vma
->vm_mm
) == search_new_forks
)
1695 ret
= rmap_one(page
, vma
, rmap_item
->address
, arg
);
1696 if (ret
!= SWAP_AGAIN
) {
1697 spin_unlock(&anon_vma
->lock
);
1701 spin_unlock(&anon_vma
->lock
);
1703 if (!search_new_forks
++)
1709 void ksm_migrate_page(struct page
*newpage
, struct page
*oldpage
)
1711 struct stable_node
*stable_node
;
1713 VM_BUG_ON(!PageLocked(oldpage
));
1714 VM_BUG_ON(!PageLocked(newpage
));
1715 VM_BUG_ON(newpage
->mapping
!= oldpage
->mapping
);
1717 stable_node
= page_stable_node(newpage
);
1719 VM_BUG_ON(stable_node
->kpfn
!= page_to_pfn(oldpage
));
1720 stable_node
->kpfn
= page_to_pfn(newpage
);
1723 #endif /* CONFIG_MIGRATION */
1725 #ifdef CONFIG_MEMORY_HOTREMOVE
1726 static struct stable_node
*ksm_check_stable_tree(unsigned long start_pfn
,
1727 unsigned long end_pfn
)
1729 struct rb_node
*node
;
1731 for (node
= rb_first(&root_stable_tree
); node
; node
= rb_next(node
)) {
1732 struct stable_node
*stable_node
;
1734 stable_node
= rb_entry(node
, struct stable_node
, node
);
1735 if (stable_node
->kpfn
>= start_pfn
&&
1736 stable_node
->kpfn
< end_pfn
)
1742 static int ksm_memory_callback(struct notifier_block
*self
,
1743 unsigned long action
, void *arg
)
1745 struct memory_notify
*mn
= arg
;
1746 struct stable_node
*stable_node
;
1749 case MEM_GOING_OFFLINE
:
1751 * Keep it very simple for now: just lock out ksmd and
1752 * MADV_UNMERGEABLE while any memory is going offline.
1754 mutex_lock(&ksm_thread_mutex
);
1759 * Most of the work is done by page migration; but there might
1760 * be a few stable_nodes left over, still pointing to struct
1761 * pages which have been offlined: prune those from the tree.
1763 while ((stable_node
= ksm_check_stable_tree(mn
->start_pfn
,
1764 mn
->start_pfn
+ mn
->nr_pages
)) != NULL
)
1765 remove_node_from_stable_tree(stable_node
);
1768 case MEM_CANCEL_OFFLINE
:
1769 mutex_unlock(&ksm_thread_mutex
);
1774 #endif /* CONFIG_MEMORY_HOTREMOVE */
1778 * This all compiles without CONFIG_SYSFS, but is a waste of space.
1781 #define KSM_ATTR_RO(_name) \
1782 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
1783 #define KSM_ATTR(_name) \
1784 static struct kobj_attribute _name##_attr = \
1785 __ATTR(_name, 0644, _name##_show, _name##_store)
1787 static ssize_t
sleep_millisecs_show(struct kobject
*kobj
,
1788 struct kobj_attribute
*attr
, char *buf
)
1790 return sprintf(buf
, "%u\n", ksm_thread_sleep_millisecs
);
1793 static ssize_t
sleep_millisecs_store(struct kobject
*kobj
,
1794 struct kobj_attribute
*attr
,
1795 const char *buf
, size_t count
)
1797 unsigned long msecs
;
1800 err
= strict_strtoul(buf
, 10, &msecs
);
1801 if (err
|| msecs
> UINT_MAX
)
1804 ksm_thread_sleep_millisecs
= msecs
;
1808 KSM_ATTR(sleep_millisecs
);
1810 static ssize_t
pages_to_scan_show(struct kobject
*kobj
,
1811 struct kobj_attribute
*attr
, char *buf
)
1813 return sprintf(buf
, "%u\n", ksm_thread_pages_to_scan
);
1816 static ssize_t
pages_to_scan_store(struct kobject
*kobj
,
1817 struct kobj_attribute
*attr
,
1818 const char *buf
, size_t count
)
1821 unsigned long nr_pages
;
1823 err
= strict_strtoul(buf
, 10, &nr_pages
);
1824 if (err
|| nr_pages
> UINT_MAX
)
1827 ksm_thread_pages_to_scan
= nr_pages
;
1831 KSM_ATTR(pages_to_scan
);
1833 static ssize_t
run_show(struct kobject
*kobj
, struct kobj_attribute
*attr
,
1836 return sprintf(buf
, "%u\n", ksm_run
);
1839 static ssize_t
run_store(struct kobject
*kobj
, struct kobj_attribute
*attr
,
1840 const char *buf
, size_t count
)
1843 unsigned long flags
;
1845 err
= strict_strtoul(buf
, 10, &flags
);
1846 if (err
|| flags
> UINT_MAX
)
1848 if (flags
> KSM_RUN_UNMERGE
)
1852 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
1853 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
1854 * breaking COW to free the pages_shared (but leaves mm_slots
1855 * on the list for when ksmd may be set running again).
1858 mutex_lock(&ksm_thread_mutex
);
1859 if (ksm_run
!= flags
) {
1861 if (flags
& KSM_RUN_UNMERGE
) {
1862 current
->flags
|= PF_OOM_ORIGIN
;
1863 err
= unmerge_and_remove_all_rmap_items();
1864 current
->flags
&= ~PF_OOM_ORIGIN
;
1866 ksm_run
= KSM_RUN_STOP
;
1871 mutex_unlock(&ksm_thread_mutex
);
1873 if (flags
& KSM_RUN_MERGE
)
1874 wake_up_interruptible(&ksm_thread_wait
);
1880 static ssize_t
pages_shared_show(struct kobject
*kobj
,
1881 struct kobj_attribute
*attr
, char *buf
)
1883 return sprintf(buf
, "%lu\n", ksm_pages_shared
);
1885 KSM_ATTR_RO(pages_shared
);
1887 static ssize_t
pages_sharing_show(struct kobject
*kobj
,
1888 struct kobj_attribute
*attr
, char *buf
)
1890 return sprintf(buf
, "%lu\n", ksm_pages_sharing
);
1892 KSM_ATTR_RO(pages_sharing
);
1894 static ssize_t
pages_unshared_show(struct kobject
*kobj
,
1895 struct kobj_attribute
*attr
, char *buf
)
1897 return sprintf(buf
, "%lu\n", ksm_pages_unshared
);
1899 KSM_ATTR_RO(pages_unshared
);
1901 static ssize_t
pages_volatile_show(struct kobject
*kobj
,
1902 struct kobj_attribute
*attr
, char *buf
)
1904 long ksm_pages_volatile
;
1906 ksm_pages_volatile
= ksm_rmap_items
- ksm_pages_shared
1907 - ksm_pages_sharing
- ksm_pages_unshared
;
1909 * It was not worth any locking to calculate that statistic,
1910 * but it might therefore sometimes be negative: conceal that.
1912 if (ksm_pages_volatile
< 0)
1913 ksm_pages_volatile
= 0;
1914 return sprintf(buf
, "%ld\n", ksm_pages_volatile
);
1916 KSM_ATTR_RO(pages_volatile
);
1918 static ssize_t
full_scans_show(struct kobject
*kobj
,
1919 struct kobj_attribute
*attr
, char *buf
)
1921 return sprintf(buf
, "%lu\n", ksm_scan
.seqnr
);
1923 KSM_ATTR_RO(full_scans
);
1925 static struct attribute
*ksm_attrs
[] = {
1926 &sleep_millisecs_attr
.attr
,
1927 &pages_to_scan_attr
.attr
,
1929 &pages_shared_attr
.attr
,
1930 &pages_sharing_attr
.attr
,
1931 &pages_unshared_attr
.attr
,
1932 &pages_volatile_attr
.attr
,
1933 &full_scans_attr
.attr
,
1937 static struct attribute_group ksm_attr_group
= {
1941 #endif /* CONFIG_SYSFS */
1943 static int __init
ksm_init(void)
1945 struct task_struct
*ksm_thread
;
1948 err
= ksm_slab_init();
1952 err
= mm_slots_hash_init();
1956 ksm_thread
= kthread_run(ksm_scan_thread
, NULL
, "ksmd");
1957 if (IS_ERR(ksm_thread
)) {
1958 printk(KERN_ERR
"ksm: creating kthread failed\n");
1959 err
= PTR_ERR(ksm_thread
);
1964 err
= sysfs_create_group(mm_kobj
, &ksm_attr_group
);
1966 printk(KERN_ERR
"ksm: register sysfs failed\n");
1967 kthread_stop(ksm_thread
);
1971 ksm_run
= KSM_RUN_MERGE
; /* no way for user to start it */
1973 #endif /* CONFIG_SYSFS */
1975 #ifdef CONFIG_MEMORY_HOTREMOVE
1977 * Choose a high priority since the callback takes ksm_thread_mutex:
1978 * later callbacks could only be taking locks which nest within that.
1980 hotplug_memory_notifier(ksm_memory_callback
, 100);
1985 mm_slots_hash_free();
1991 module_init(ksm_init
)