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>
46 #define DO_NUMA(x) do { (x); } while (0)
49 #define DO_NUMA(x) do { } while (0)
53 * A few notes about the KSM scanning process,
54 * to make it easier to understand the data structures below:
56 * In order to reduce excessive scanning, KSM sorts the memory pages by their
57 * contents into a data structure that holds pointers to the pages' locations.
59 * Since the contents of the pages may change at any moment, KSM cannot just
60 * insert the pages into a normal sorted tree and expect it to find anything.
61 * Therefore KSM uses two data structures - the stable and the unstable tree.
63 * The stable tree holds pointers to all the merged pages (ksm pages), sorted
64 * by their contents. Because each such page is write-protected, searching on
65 * this tree is fully assured to be working (except when pages are unmapped),
66 * and therefore this tree is called the stable tree.
68 * In addition to the stable tree, KSM uses a second data structure called the
69 * unstable tree: this tree holds pointers to pages which have been found to
70 * be "unchanged for a period of time". The unstable tree sorts these pages
71 * by their contents, but since they are not write-protected, KSM cannot rely
72 * upon the unstable tree to work correctly - the unstable tree is liable to
73 * be corrupted as its contents are modified, and so it is called unstable.
75 * KSM solves this problem by several techniques:
77 * 1) The unstable tree is flushed every time KSM completes scanning all
78 * memory areas, and then the tree is rebuilt again from the beginning.
79 * 2) KSM will only insert into the unstable tree, pages whose hash value
80 * has not changed since the previous scan of all memory areas.
81 * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
82 * colors of the nodes and not on their contents, assuring that even when
83 * the tree gets "corrupted" it won't get out of balance, so scanning time
84 * remains the same (also, searching and inserting nodes in an rbtree uses
85 * the same algorithm, so we have no overhead when we flush and rebuild).
86 * 4) KSM never flushes the stable tree, which means that even if it were to
87 * take 10 attempts to find a page in the unstable tree, once it is found,
88 * it is secured in the stable tree. (When we scan a new page, we first
89 * compare it against the stable tree, and then against the unstable tree.)
91 * If the merge_across_nodes tunable is unset, then KSM maintains multiple
92 * stable trees and multiple unstable trees: one of each for each NUMA node.
96 * struct mm_slot - ksm information per mm that is being scanned
97 * @link: link to the mm_slots hash list
98 * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
99 * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
100 * @mm: the mm that this information is valid for
103 struct hlist_node link
;
104 struct list_head mm_list
;
105 struct rmap_item
*rmap_list
;
106 struct mm_struct
*mm
;
110 * struct ksm_scan - cursor for scanning
111 * @mm_slot: the current mm_slot we are scanning
112 * @address: the next address inside that to be scanned
113 * @rmap_list: link to the next rmap to be scanned in the rmap_list
114 * @seqnr: count of completed full scans (needed when removing unstable node)
116 * There is only the one ksm_scan instance of this cursor structure.
119 struct mm_slot
*mm_slot
;
120 unsigned long address
;
121 struct rmap_item
**rmap_list
;
126 * struct stable_node - node of the stable rbtree
127 * @node: rb node of this ksm page in the stable tree
128 * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
129 * @hlist_dup: linked into the stable_node->hlist with a stable_node chain
130 * @list: linked into migrate_nodes, pending placement in the proper node tree
131 * @hlist: hlist head of rmap_items using this ksm page
132 * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
133 * @chain_prune_time: time of the last full garbage collection
134 * @rmap_hlist_len: number of rmap_item entries in hlist or STABLE_NODE_CHAIN
135 * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
139 struct rb_node node
; /* when node of stable tree */
140 struct { /* when listed for migration */
141 struct list_head
*head
;
143 struct hlist_node hlist_dup
;
144 struct list_head list
;
148 struct hlist_head hlist
;
151 unsigned long chain_prune_time
;
154 * STABLE_NODE_CHAIN can be any negative number in
155 * rmap_hlist_len negative range, but better not -1 to be able
156 * to reliably detect underflows.
158 #define STABLE_NODE_CHAIN -1024
166 * struct rmap_item - reverse mapping item for virtual addresses
167 * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
168 * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
169 * @nid: NUMA node id of unstable tree in which linked (may not match page)
170 * @mm: the memory structure this rmap_item is pointing into
171 * @address: the virtual address this rmap_item tracks (+ flags in low bits)
172 * @oldchecksum: previous checksum of the page at that virtual address
173 * @node: rb node of this rmap_item in the unstable tree
174 * @head: pointer to stable_node heading this list in the stable tree
175 * @hlist: link into hlist of rmap_items hanging off that stable_node
178 struct rmap_item
*rmap_list
;
180 struct anon_vma
*anon_vma
; /* when stable */
182 int nid
; /* when node of unstable tree */
185 struct mm_struct
*mm
;
186 unsigned long address
; /* + low bits used for flags below */
187 unsigned int oldchecksum
; /* when unstable */
189 struct rb_node node
; /* when node of unstable tree */
190 struct { /* when listed from stable tree */
191 struct stable_node
*head
;
192 struct hlist_node hlist
;
197 #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
198 #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
199 #define STABLE_FLAG 0x200 /* is listed from the stable tree */
201 /* The stable and unstable tree heads */
202 static struct rb_root one_stable_tree
[1] = { RB_ROOT
};
203 static struct rb_root one_unstable_tree
[1] = { RB_ROOT
};
204 static struct rb_root
*root_stable_tree
= one_stable_tree
;
205 static struct rb_root
*root_unstable_tree
= one_unstable_tree
;
207 /* Recently migrated nodes of stable tree, pending proper placement */
208 static LIST_HEAD(migrate_nodes
);
209 #define STABLE_NODE_DUP_HEAD ((struct list_head *)&migrate_nodes.prev)
211 #define MM_SLOTS_HASH_BITS 10
212 static DEFINE_HASHTABLE(mm_slots_hash
, MM_SLOTS_HASH_BITS
);
214 static struct mm_slot ksm_mm_head
= {
215 .mm_list
= LIST_HEAD_INIT(ksm_mm_head
.mm_list
),
217 static struct ksm_scan ksm_scan
= {
218 .mm_slot
= &ksm_mm_head
,
221 static struct kmem_cache
*rmap_item_cache
;
222 static struct kmem_cache
*stable_node_cache
;
223 static struct kmem_cache
*mm_slot_cache
;
225 /* The number of nodes in the stable tree */
226 static unsigned long ksm_pages_shared
;
228 /* The number of page slots additionally sharing those nodes */
229 static unsigned long ksm_pages_sharing
;
231 /* The number of nodes in the unstable tree */
232 static unsigned long ksm_pages_unshared
;
234 /* The number of rmap_items in use: to calculate pages_volatile */
235 static unsigned long ksm_rmap_items
;
237 /* The number of stable_node chains */
238 static unsigned long ksm_stable_node_chains
;
240 /* The number of stable_node dups linked to the stable_node chains */
241 static unsigned long ksm_stable_node_dups
;
243 /* Delay in pruning stale stable_node_dups in the stable_node_chains */
244 static int ksm_stable_node_chains_prune_millisecs
= 2000;
246 /* Maximum number of page slots sharing a stable node */
247 static int ksm_max_page_sharing
= 256;
249 /* Number of pages ksmd should scan in one batch */
250 static unsigned int ksm_thread_pages_to_scan
= 100;
252 /* Milliseconds ksmd should sleep between batches */
253 static unsigned int ksm_thread_sleep_millisecs
= 20;
255 /* Checksum of an empty (zeroed) page */
256 static unsigned int zero_checksum __read_mostly
;
258 /* Whether to merge empty (zeroed) pages with actual zero pages */
259 static bool ksm_use_zero_pages __read_mostly
;
262 /* Zeroed when merging across nodes is not allowed */
263 static unsigned int ksm_merge_across_nodes
= 1;
264 static int ksm_nr_node_ids
= 1;
266 #define ksm_merge_across_nodes 1U
267 #define ksm_nr_node_ids 1
270 #define KSM_RUN_STOP 0
271 #define KSM_RUN_MERGE 1
272 #define KSM_RUN_UNMERGE 2
273 #define KSM_RUN_OFFLINE 4
274 static unsigned long ksm_run
= KSM_RUN_STOP
;
275 static void wait_while_offlining(void);
277 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait
);
278 static DEFINE_MUTEX(ksm_thread_mutex
);
279 static DEFINE_SPINLOCK(ksm_mmlist_lock
);
281 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
282 sizeof(struct __struct), __alignof__(struct __struct),\
285 static int __init
ksm_slab_init(void)
287 rmap_item_cache
= KSM_KMEM_CACHE(rmap_item
, 0);
288 if (!rmap_item_cache
)
291 stable_node_cache
= KSM_KMEM_CACHE(stable_node
, 0);
292 if (!stable_node_cache
)
295 mm_slot_cache
= KSM_KMEM_CACHE(mm_slot
, 0);
302 kmem_cache_destroy(stable_node_cache
);
304 kmem_cache_destroy(rmap_item_cache
);
309 static void __init
ksm_slab_free(void)
311 kmem_cache_destroy(mm_slot_cache
);
312 kmem_cache_destroy(stable_node_cache
);
313 kmem_cache_destroy(rmap_item_cache
);
314 mm_slot_cache
= NULL
;
317 static __always_inline
bool is_stable_node_chain(struct stable_node
*chain
)
319 return chain
->rmap_hlist_len
== STABLE_NODE_CHAIN
;
322 static __always_inline
bool is_stable_node_dup(struct stable_node
*dup
)
324 return dup
->head
== STABLE_NODE_DUP_HEAD
;
327 static inline void stable_node_chain_add_dup(struct stable_node
*dup
,
328 struct stable_node
*chain
)
330 VM_BUG_ON(is_stable_node_dup(dup
));
331 dup
->head
= STABLE_NODE_DUP_HEAD
;
332 VM_BUG_ON(!is_stable_node_chain(chain
));
333 hlist_add_head(&dup
->hlist_dup
, &chain
->hlist
);
334 ksm_stable_node_dups
++;
337 static inline void __stable_node_dup_del(struct stable_node
*dup
)
339 VM_BUG_ON(!is_stable_node_dup(dup
));
340 hlist_del(&dup
->hlist_dup
);
341 ksm_stable_node_dups
--;
344 static inline void stable_node_dup_del(struct stable_node
*dup
)
346 VM_BUG_ON(is_stable_node_chain(dup
));
347 if (is_stable_node_dup(dup
))
348 __stable_node_dup_del(dup
);
350 rb_erase(&dup
->node
, root_stable_tree
+ NUMA(dup
->nid
));
351 #ifdef CONFIG_DEBUG_VM
356 static inline struct rmap_item
*alloc_rmap_item(void)
358 struct rmap_item
*rmap_item
;
360 rmap_item
= kmem_cache_zalloc(rmap_item_cache
, GFP_KERNEL
|
361 __GFP_NORETRY
| __GFP_NOWARN
);
367 static inline void free_rmap_item(struct rmap_item
*rmap_item
)
370 rmap_item
->mm
= NULL
; /* debug safety */
371 kmem_cache_free(rmap_item_cache
, rmap_item
);
374 static inline struct stable_node
*alloc_stable_node(void)
377 * The allocation can take too long with GFP_KERNEL when memory is under
378 * pressure, which may lead to hung task warnings. Adding __GFP_HIGH
379 * grants access to memory reserves, helping to avoid this problem.
381 return kmem_cache_alloc(stable_node_cache
, GFP_KERNEL
| __GFP_HIGH
);
384 static inline void free_stable_node(struct stable_node
*stable_node
)
386 VM_BUG_ON(stable_node
->rmap_hlist_len
&&
387 !is_stable_node_chain(stable_node
));
388 kmem_cache_free(stable_node_cache
, stable_node
);
391 static inline struct mm_slot
*alloc_mm_slot(void)
393 if (!mm_slot_cache
) /* initialization failed */
395 return kmem_cache_zalloc(mm_slot_cache
, GFP_KERNEL
);
398 static inline void free_mm_slot(struct mm_slot
*mm_slot
)
400 kmem_cache_free(mm_slot_cache
, mm_slot
);
403 static struct mm_slot
*get_mm_slot(struct mm_struct
*mm
)
405 struct mm_slot
*slot
;
407 hash_for_each_possible(mm_slots_hash
, slot
, link
, (unsigned long)mm
)
414 static void insert_to_mm_slots_hash(struct mm_struct
*mm
,
415 struct mm_slot
*mm_slot
)
418 hash_add(mm_slots_hash
, &mm_slot
->link
, (unsigned long)mm
);
422 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
423 * page tables after it has passed through ksm_exit() - which, if necessary,
424 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
425 * a special flag: they can just back out as soon as mm_users goes to zero.
426 * ksm_test_exit() is used throughout to make this test for exit: in some
427 * places for correctness, in some places just to avoid unnecessary work.
429 static inline bool ksm_test_exit(struct mm_struct
*mm
)
431 return atomic_read(&mm
->mm_users
) == 0;
435 * We use break_ksm to break COW on a ksm page: it's a stripped down
437 * if (get_user_pages(addr, 1, 1, 1, &page, NULL) == 1)
440 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
441 * in case the application has unmapped and remapped mm,addr meanwhile.
442 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
443 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
445 * FAULT_FLAG/FOLL_REMOTE are because we do this outside the context
446 * of the process that owns 'vma'. We also do not want to enforce
447 * protection keys here anyway.
449 static int break_ksm(struct vm_area_struct
*vma
, unsigned long addr
)
456 page
= follow_page(vma
, addr
,
457 FOLL_GET
| FOLL_MIGRATION
| FOLL_REMOTE
);
458 if (IS_ERR_OR_NULL(page
))
461 ret
= handle_mm_fault(vma
, addr
,
462 FAULT_FLAG_WRITE
| FAULT_FLAG_REMOTE
);
464 ret
= VM_FAULT_WRITE
;
466 } while (!(ret
& (VM_FAULT_WRITE
| VM_FAULT_SIGBUS
| VM_FAULT_SIGSEGV
| VM_FAULT_OOM
)));
468 * We must loop because handle_mm_fault() may back out if there's
469 * any difficulty e.g. if pte accessed bit gets updated concurrently.
471 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
472 * COW has been broken, even if the vma does not permit VM_WRITE;
473 * but note that a concurrent fault might break PageKsm for us.
475 * VM_FAULT_SIGBUS could occur if we race with truncation of the
476 * backing file, which also invalidates anonymous pages: that's
477 * okay, that truncation will have unmapped the PageKsm for us.
479 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
480 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
481 * current task has TIF_MEMDIE set, and will be OOM killed on return
482 * to user; and ksmd, having no mm, would never be chosen for that.
484 * But if the mm is in a limited mem_cgroup, then the fault may fail
485 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
486 * even ksmd can fail in this way - though it's usually breaking ksm
487 * just to undo a merge it made a moment before, so unlikely to oom.
489 * That's a pity: we might therefore have more kernel pages allocated
490 * than we're counting as nodes in the stable tree; but ksm_do_scan
491 * will retry to break_cow on each pass, so should recover the page
492 * in due course. The important thing is to not let VM_MERGEABLE
493 * be cleared while any such pages might remain in the area.
495 return (ret
& VM_FAULT_OOM
) ? -ENOMEM
: 0;
498 static struct vm_area_struct
*find_mergeable_vma(struct mm_struct
*mm
,
501 struct vm_area_struct
*vma
;
502 if (ksm_test_exit(mm
))
504 vma
= find_vma(mm
, addr
);
505 if (!vma
|| vma
->vm_start
> addr
)
507 if (!(vma
->vm_flags
& VM_MERGEABLE
) || !vma
->anon_vma
)
512 static void break_cow(struct rmap_item
*rmap_item
)
514 struct mm_struct
*mm
= rmap_item
->mm
;
515 unsigned long addr
= rmap_item
->address
;
516 struct vm_area_struct
*vma
;
519 * It is not an accident that whenever we want to break COW
520 * to undo, we also need to drop a reference to the anon_vma.
522 put_anon_vma(rmap_item
->anon_vma
);
524 down_read(&mm
->mmap_sem
);
525 vma
= find_mergeable_vma(mm
, addr
);
527 break_ksm(vma
, addr
);
528 up_read(&mm
->mmap_sem
);
531 static struct page
*get_mergeable_page(struct rmap_item
*rmap_item
)
533 struct mm_struct
*mm
= rmap_item
->mm
;
534 unsigned long addr
= rmap_item
->address
;
535 struct vm_area_struct
*vma
;
538 down_read(&mm
->mmap_sem
);
539 vma
= find_mergeable_vma(mm
, addr
);
543 page
= follow_page(vma
, addr
, FOLL_GET
);
544 if (IS_ERR_OR_NULL(page
))
546 if (PageAnon(page
)) {
547 flush_anon_page(vma
, page
, addr
);
548 flush_dcache_page(page
);
554 up_read(&mm
->mmap_sem
);
559 * This helper is used for getting right index into array of tree roots.
560 * When merge_across_nodes knob is set to 1, there are only two rb-trees for
561 * stable and unstable pages from all nodes with roots in index 0. Otherwise,
562 * every node has its own stable and unstable tree.
564 static inline int get_kpfn_nid(unsigned long kpfn
)
566 return ksm_merge_across_nodes
? 0 : NUMA(pfn_to_nid(kpfn
));
569 static struct stable_node
*alloc_stable_node_chain(struct stable_node
*dup
,
570 struct rb_root
*root
)
572 struct stable_node
*chain
= alloc_stable_node();
573 VM_BUG_ON(is_stable_node_chain(dup
));
575 INIT_HLIST_HEAD(&chain
->hlist
);
576 chain
->chain_prune_time
= jiffies
;
577 chain
->rmap_hlist_len
= STABLE_NODE_CHAIN
;
578 #if defined (CONFIG_DEBUG_VM) && defined(CONFIG_NUMA)
579 chain
->nid
= -1; /* debug */
581 ksm_stable_node_chains
++;
584 * Put the stable node chain in the first dimension of
585 * the stable tree and at the same time remove the old
588 rb_replace_node(&dup
->node
, &chain
->node
, root
);
591 * Move the old stable node to the second dimension
592 * queued in the hlist_dup. The invariant is that all
593 * dup stable_nodes in the chain->hlist point to pages
594 * that are wrprotected and have the exact same
597 stable_node_chain_add_dup(dup
, chain
);
602 static inline void free_stable_node_chain(struct stable_node
*chain
,
603 struct rb_root
*root
)
605 rb_erase(&chain
->node
, root
);
606 free_stable_node(chain
);
607 ksm_stable_node_chains
--;
610 static void remove_node_from_stable_tree(struct stable_node
*stable_node
)
612 struct rmap_item
*rmap_item
;
614 /* check it's not STABLE_NODE_CHAIN or negative */
615 BUG_ON(stable_node
->rmap_hlist_len
< 0);
617 hlist_for_each_entry(rmap_item
, &stable_node
->hlist
, hlist
) {
618 if (rmap_item
->hlist
.next
)
622 VM_BUG_ON(stable_node
->rmap_hlist_len
<= 0);
623 stable_node
->rmap_hlist_len
--;
624 put_anon_vma(rmap_item
->anon_vma
);
625 rmap_item
->address
&= PAGE_MASK
;
630 * We need the second aligned pointer of the migrate_nodes
631 * list_head to stay clear from the rb_parent_color union
632 * (aligned and different than any node) and also different
633 * from &migrate_nodes. This will verify that future list.h changes
634 * don't break STABLE_NODE_DUP_HEAD.
636 #if GCC_VERSION >= 40903 /* only recent gcc can handle it */
637 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD
<= &migrate_nodes
);
638 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD
>= &migrate_nodes
+ 1);
641 if (stable_node
->head
== &migrate_nodes
)
642 list_del(&stable_node
->list
);
644 stable_node_dup_del(stable_node
);
645 free_stable_node(stable_node
);
649 * get_ksm_page: checks if the page indicated by the stable node
650 * is still its ksm page, despite having held no reference to it.
651 * In which case we can trust the content of the page, and it
652 * returns the gotten page; but if the page has now been zapped,
653 * remove the stale node from the stable tree and return NULL.
654 * But beware, the stable node's page might be being migrated.
656 * You would expect the stable_node to hold a reference to the ksm page.
657 * But if it increments the page's count, swapping out has to wait for
658 * ksmd to come around again before it can free the page, which may take
659 * seconds or even minutes: much too unresponsive. So instead we use a
660 * "keyhole reference": access to the ksm page from the stable node peeps
661 * out through its keyhole to see if that page still holds the right key,
662 * pointing back to this stable node. This relies on freeing a PageAnon
663 * page to reset its page->mapping to NULL, and relies on no other use of
664 * a page to put something that might look like our key in page->mapping.
665 * is on its way to being freed; but it is an anomaly to bear in mind.
667 static struct page
*get_ksm_page(struct stable_node
*stable_node
, bool lock_it
)
670 void *expected_mapping
;
673 expected_mapping
= (void *)((unsigned long)stable_node
|
676 kpfn
= READ_ONCE(stable_node
->kpfn
);
677 page
= pfn_to_page(kpfn
);
680 * page is computed from kpfn, so on most architectures reading
681 * page->mapping is naturally ordered after reading node->kpfn,
682 * but on Alpha we need to be more careful.
684 smp_read_barrier_depends();
685 if (READ_ONCE(page
->mapping
) != expected_mapping
)
689 * We cannot do anything with the page while its refcount is 0.
690 * Usually 0 means free, or tail of a higher-order page: in which
691 * case this node is no longer referenced, and should be freed;
692 * however, it might mean that the page is under page_freeze_refs().
693 * The __remove_mapping() case is easy, again the node is now stale;
694 * but if page is swapcache in migrate_page_move_mapping(), it might
695 * still be our page, in which case it's essential to keep the node.
697 while (!get_page_unless_zero(page
)) {
699 * Another check for page->mapping != expected_mapping would
700 * work here too. We have chosen the !PageSwapCache test to
701 * optimize the common case, when the page is or is about to
702 * be freed: PageSwapCache is cleared (under spin_lock_irq)
703 * in the freeze_refs section of __remove_mapping(); but Anon
704 * page->mapping reset to NULL later, in free_pages_prepare().
706 if (!PageSwapCache(page
))
711 if (READ_ONCE(page
->mapping
) != expected_mapping
) {
718 if (READ_ONCE(page
->mapping
) != expected_mapping
) {
728 * We come here from above when page->mapping or !PageSwapCache
729 * suggests that the node is stale; but it might be under migration.
730 * We need smp_rmb(), matching the smp_wmb() in ksm_migrate_page(),
731 * before checking whether node->kpfn has been changed.
734 if (READ_ONCE(stable_node
->kpfn
) != kpfn
)
736 remove_node_from_stable_tree(stable_node
);
741 * Removing rmap_item from stable or unstable tree.
742 * This function will clean the information from the stable/unstable tree.
744 static void remove_rmap_item_from_tree(struct rmap_item
*rmap_item
)
746 if (rmap_item
->address
& STABLE_FLAG
) {
747 struct stable_node
*stable_node
;
750 stable_node
= rmap_item
->head
;
751 page
= get_ksm_page(stable_node
, true);
755 hlist_del(&rmap_item
->hlist
);
759 if (!hlist_empty(&stable_node
->hlist
))
763 VM_BUG_ON(stable_node
->rmap_hlist_len
<= 0);
764 stable_node
->rmap_hlist_len
--;
766 put_anon_vma(rmap_item
->anon_vma
);
767 rmap_item
->address
&= PAGE_MASK
;
769 } else if (rmap_item
->address
& UNSTABLE_FLAG
) {
772 * Usually ksmd can and must skip the rb_erase, because
773 * root_unstable_tree was already reset to RB_ROOT.
774 * But be careful when an mm is exiting: do the rb_erase
775 * if this rmap_item was inserted by this scan, rather
776 * than left over from before.
778 age
= (unsigned char)(ksm_scan
.seqnr
- rmap_item
->address
);
781 rb_erase(&rmap_item
->node
,
782 root_unstable_tree
+ NUMA(rmap_item
->nid
));
783 ksm_pages_unshared
--;
784 rmap_item
->address
&= PAGE_MASK
;
787 cond_resched(); /* we're called from many long loops */
790 static void remove_trailing_rmap_items(struct mm_slot
*mm_slot
,
791 struct rmap_item
**rmap_list
)
794 struct rmap_item
*rmap_item
= *rmap_list
;
795 *rmap_list
= rmap_item
->rmap_list
;
796 remove_rmap_item_from_tree(rmap_item
);
797 free_rmap_item(rmap_item
);
802 * Though it's very tempting to unmerge rmap_items from stable tree rather
803 * than check every pte of a given vma, the locking doesn't quite work for
804 * that - an rmap_item is assigned to the stable tree after inserting ksm
805 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
806 * rmap_items from parent to child at fork time (so as not to waste time
807 * if exit comes before the next scan reaches it).
809 * Similarly, although we'd like to remove rmap_items (so updating counts
810 * and freeing memory) when unmerging an area, it's easier to leave that
811 * to the next pass of ksmd - consider, for example, how ksmd might be
812 * in cmp_and_merge_page on one of the rmap_items we would be removing.
814 static int unmerge_ksm_pages(struct vm_area_struct
*vma
,
815 unsigned long start
, unsigned long end
)
820 for (addr
= start
; addr
< end
&& !err
; addr
+= PAGE_SIZE
) {
821 if (ksm_test_exit(vma
->vm_mm
))
823 if (signal_pending(current
))
826 err
= break_ksm(vma
, addr
);
833 * Only called through the sysfs control interface:
835 static int remove_stable_node(struct stable_node
*stable_node
)
840 page
= get_ksm_page(stable_node
, true);
843 * get_ksm_page did remove_node_from_stable_tree itself.
848 if (WARN_ON_ONCE(page_mapped(page
))) {
850 * This should not happen: but if it does, just refuse to let
851 * merge_across_nodes be switched - there is no need to panic.
856 * The stable node did not yet appear stale to get_ksm_page(),
857 * since that allows for an unmapped ksm page to be recognized
858 * right up until it is freed; but the node is safe to remove.
859 * This page might be in a pagevec waiting to be freed,
860 * or it might be PageSwapCache (perhaps under writeback),
861 * or it might have been removed from swapcache a moment ago.
863 set_page_stable_node(page
, NULL
);
864 remove_node_from_stable_tree(stable_node
);
873 static int remove_stable_node_chain(struct stable_node
*stable_node
,
874 struct rb_root
*root
)
876 struct stable_node
*dup
;
877 struct hlist_node
*hlist_safe
;
879 if (!is_stable_node_chain(stable_node
)) {
880 VM_BUG_ON(is_stable_node_dup(stable_node
));
881 if (remove_stable_node(stable_node
))
887 hlist_for_each_entry_safe(dup
, hlist_safe
,
888 &stable_node
->hlist
, hlist_dup
) {
889 VM_BUG_ON(!is_stable_node_dup(dup
));
890 if (remove_stable_node(dup
))
893 BUG_ON(!hlist_empty(&stable_node
->hlist
));
894 free_stable_node_chain(stable_node
, root
);
898 static int remove_all_stable_nodes(void)
900 struct stable_node
*stable_node
, *next
;
904 for (nid
= 0; nid
< ksm_nr_node_ids
; nid
++) {
905 while (root_stable_tree
[nid
].rb_node
) {
906 stable_node
= rb_entry(root_stable_tree
[nid
].rb_node
,
907 struct stable_node
, node
);
908 if (remove_stable_node_chain(stable_node
,
909 root_stable_tree
+ nid
)) {
911 break; /* proceed to next nid */
916 list_for_each_entry_safe(stable_node
, next
, &migrate_nodes
, list
) {
917 if (remove_stable_node(stable_node
))
924 static int unmerge_and_remove_all_rmap_items(void)
926 struct mm_slot
*mm_slot
;
927 struct mm_struct
*mm
;
928 struct vm_area_struct
*vma
;
931 spin_lock(&ksm_mmlist_lock
);
932 ksm_scan
.mm_slot
= list_entry(ksm_mm_head
.mm_list
.next
,
933 struct mm_slot
, mm_list
);
934 spin_unlock(&ksm_mmlist_lock
);
936 for (mm_slot
= ksm_scan
.mm_slot
;
937 mm_slot
!= &ksm_mm_head
; mm_slot
= ksm_scan
.mm_slot
) {
939 down_read(&mm
->mmap_sem
);
940 for (vma
= mm
->mmap
; vma
; vma
= vma
->vm_next
) {
941 if (ksm_test_exit(mm
))
943 if (!(vma
->vm_flags
& VM_MERGEABLE
) || !vma
->anon_vma
)
945 err
= unmerge_ksm_pages(vma
,
946 vma
->vm_start
, vma
->vm_end
);
951 remove_trailing_rmap_items(mm_slot
, &mm_slot
->rmap_list
);
952 up_read(&mm
->mmap_sem
);
954 spin_lock(&ksm_mmlist_lock
);
955 ksm_scan
.mm_slot
= list_entry(mm_slot
->mm_list
.next
,
956 struct mm_slot
, mm_list
);
957 if (ksm_test_exit(mm
)) {
958 hash_del(&mm_slot
->link
);
959 list_del(&mm_slot
->mm_list
);
960 spin_unlock(&ksm_mmlist_lock
);
962 free_mm_slot(mm_slot
);
963 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
966 spin_unlock(&ksm_mmlist_lock
);
969 /* Clean up stable nodes, but don't worry if some are still busy */
970 remove_all_stable_nodes();
975 up_read(&mm
->mmap_sem
);
976 spin_lock(&ksm_mmlist_lock
);
977 ksm_scan
.mm_slot
= &ksm_mm_head
;
978 spin_unlock(&ksm_mmlist_lock
);
981 #endif /* CONFIG_SYSFS */
983 static u32
calc_checksum(struct page
*page
)
986 void *addr
= kmap_atomic(page
);
987 checksum
= jhash2(addr
, PAGE_SIZE
/ 4, 17);
992 static int memcmp_pages(struct page
*page1
, struct page
*page2
)
997 addr1
= kmap_atomic(page1
);
998 addr2
= kmap_atomic(page2
);
999 ret
= memcmp(addr1
, addr2
, PAGE_SIZE
);
1000 kunmap_atomic(addr2
);
1001 kunmap_atomic(addr1
);
1005 static inline int pages_identical(struct page
*page1
, struct page
*page2
)
1007 return !memcmp_pages(page1
, page2
);
1010 static int write_protect_page(struct vm_area_struct
*vma
, struct page
*page
,
1013 struct mm_struct
*mm
= vma
->vm_mm
;
1019 unsigned long mmun_start
; /* For mmu_notifiers */
1020 unsigned long mmun_end
; /* For mmu_notifiers */
1022 addr
= page_address_in_vma(page
, vma
);
1023 if (addr
== -EFAULT
)
1026 BUG_ON(PageTransCompound(page
));
1029 mmun_end
= addr
+ PAGE_SIZE
;
1030 mmu_notifier_invalidate_range_start(mm
, mmun_start
, mmun_end
);
1032 ptep
= page_check_address(page
, mm
, addr
, &ptl
, 0);
1036 if (pte_write(*ptep
) || pte_dirty(*ptep
) ||
1037 (pte_protnone(*ptep
) && pte_savedwrite(*ptep
))) {
1040 swapped
= PageSwapCache(page
);
1041 flush_cache_page(vma
, addr
, page_to_pfn(page
));
1043 * Ok this is tricky, when get_user_pages_fast() run it doesn't
1044 * take any lock, therefore the check that we are going to make
1045 * with the pagecount against the mapcount is racey and
1046 * O_DIRECT can happen right after the check.
1047 * So we clear the pte and flush the tlb before the check
1048 * this assure us that no O_DIRECT can happen after the check
1049 * or in the middle of the check.
1051 entry
= ptep_clear_flush_notify(vma
, addr
, ptep
);
1053 * Check that no O_DIRECT or similar I/O is in progress on the
1056 if (page_mapcount(page
) + 1 + swapped
!= page_count(page
)) {
1057 set_pte_at(mm
, addr
, ptep
, entry
);
1060 if (pte_dirty(entry
))
1061 set_page_dirty(page
);
1063 if (pte_protnone(entry
))
1064 entry
= pte_mkclean(pte_clear_savedwrite(entry
));
1066 entry
= pte_mkclean(pte_wrprotect(entry
));
1067 set_pte_at_notify(mm
, addr
, ptep
, entry
);
1073 pte_unmap_unlock(ptep
, ptl
);
1075 mmu_notifier_invalidate_range_end(mm
, mmun_start
, mmun_end
);
1081 * replace_page - replace page in vma by new ksm page
1082 * @vma: vma that holds the pte pointing to page
1083 * @page: the page we are replacing by kpage
1084 * @kpage: the ksm page we replace page by
1085 * @orig_pte: the original value of the pte
1087 * Returns 0 on success, -EFAULT on failure.
1089 static int replace_page(struct vm_area_struct
*vma
, struct page
*page
,
1090 struct page
*kpage
, pte_t orig_pte
)
1092 struct mm_struct
*mm
= vma
->vm_mm
;
1099 unsigned long mmun_start
; /* For mmu_notifiers */
1100 unsigned long mmun_end
; /* For mmu_notifiers */
1102 addr
= page_address_in_vma(page
, vma
);
1103 if (addr
== -EFAULT
)
1106 pmd
= mm_find_pmd(mm
, addr
);
1111 mmun_end
= addr
+ PAGE_SIZE
;
1112 mmu_notifier_invalidate_range_start(mm
, mmun_start
, mmun_end
);
1114 ptep
= pte_offset_map_lock(mm
, pmd
, addr
, &ptl
);
1115 if (!pte_same(*ptep
, orig_pte
)) {
1116 pte_unmap_unlock(ptep
, ptl
);
1121 * No need to check ksm_use_zero_pages here: we can only have a
1122 * zero_page here if ksm_use_zero_pages was enabled alreaady.
1124 if (!is_zero_pfn(page_to_pfn(kpage
))) {
1126 page_add_anon_rmap(kpage
, vma
, addr
, false);
1127 newpte
= mk_pte(kpage
, vma
->vm_page_prot
);
1129 newpte
= pte_mkspecial(pfn_pte(page_to_pfn(kpage
),
1130 vma
->vm_page_prot
));
1133 flush_cache_page(vma
, addr
, pte_pfn(*ptep
));
1134 ptep_clear_flush_notify(vma
, addr
, ptep
);
1135 set_pte_at_notify(mm
, addr
, ptep
, newpte
);
1137 page_remove_rmap(page
, false);
1138 if (!page_mapped(page
))
1139 try_to_free_swap(page
);
1142 pte_unmap_unlock(ptep
, ptl
);
1145 mmu_notifier_invalidate_range_end(mm
, mmun_start
, mmun_end
);
1151 * try_to_merge_one_page - take two pages and merge them into one
1152 * @vma: the vma that holds the pte pointing to page
1153 * @page: the PageAnon page that we want to replace with kpage
1154 * @kpage: the PageKsm page that we want to map instead of page,
1155 * or NULL the first time when we want to use page as kpage.
1157 * This function returns 0 if the pages were merged, -EFAULT otherwise.
1159 static int try_to_merge_one_page(struct vm_area_struct
*vma
,
1160 struct page
*page
, struct page
*kpage
)
1162 pte_t orig_pte
= __pte(0);
1165 if (page
== kpage
) /* ksm page forked */
1168 if (!PageAnon(page
))
1172 * We need the page lock to read a stable PageSwapCache in
1173 * write_protect_page(). We use trylock_page() instead of
1174 * lock_page() because we don't want to wait here - we
1175 * prefer to continue scanning and merging different pages,
1176 * then come back to this page when it is unlocked.
1178 if (!trylock_page(page
))
1181 if (PageTransCompound(page
)) {
1182 err
= split_huge_page(page
);
1188 * If this anonymous page is mapped only here, its pte may need
1189 * to be write-protected. If it's mapped elsewhere, all of its
1190 * ptes are necessarily already write-protected. But in either
1191 * case, we need to lock and check page_count is not raised.
1193 if (write_protect_page(vma
, page
, &orig_pte
) == 0) {
1196 * While we hold page lock, upgrade page from
1197 * PageAnon+anon_vma to PageKsm+NULL stable_node:
1198 * stable_tree_insert() will update stable_node.
1200 set_page_stable_node(page
, NULL
);
1201 mark_page_accessed(page
);
1203 * Page reclaim just frees a clean page with no dirty
1204 * ptes: make sure that the ksm page would be swapped.
1206 if (!PageDirty(page
))
1209 } else if (pages_identical(page
, kpage
))
1210 err
= replace_page(vma
, page
, kpage
, orig_pte
);
1213 if ((vma
->vm_flags
& VM_LOCKED
) && kpage
&& !err
) {
1214 munlock_vma_page(page
);
1215 if (!PageMlocked(kpage
)) {
1218 mlock_vma_page(kpage
);
1219 page
= kpage
; /* for final unlock */
1230 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
1231 * but no new kernel page is allocated: kpage must already be a ksm page.
1233 * This function returns 0 if the pages were merged, -EFAULT otherwise.
1235 static int try_to_merge_with_ksm_page(struct rmap_item
*rmap_item
,
1236 struct page
*page
, struct page
*kpage
)
1238 struct mm_struct
*mm
= rmap_item
->mm
;
1239 struct vm_area_struct
*vma
;
1242 down_read(&mm
->mmap_sem
);
1243 vma
= find_mergeable_vma(mm
, rmap_item
->address
);
1247 err
= try_to_merge_one_page(vma
, page
, kpage
);
1251 /* Unstable nid is in union with stable anon_vma: remove first */
1252 remove_rmap_item_from_tree(rmap_item
);
1254 /* Must get reference to anon_vma while still holding mmap_sem */
1255 rmap_item
->anon_vma
= vma
->anon_vma
;
1256 get_anon_vma(vma
->anon_vma
);
1258 up_read(&mm
->mmap_sem
);
1263 * try_to_merge_two_pages - take two identical pages and prepare them
1264 * to be merged into one page.
1266 * This function returns the kpage if we successfully merged two identical
1267 * pages into one ksm page, NULL otherwise.
1269 * Note that this function upgrades page to ksm page: if one of the pages
1270 * is already a ksm page, try_to_merge_with_ksm_page should be used.
1272 static struct page
*try_to_merge_two_pages(struct rmap_item
*rmap_item
,
1274 struct rmap_item
*tree_rmap_item
,
1275 struct page
*tree_page
)
1279 err
= try_to_merge_with_ksm_page(rmap_item
, page
, NULL
);
1281 err
= try_to_merge_with_ksm_page(tree_rmap_item
,
1284 * If that fails, we have a ksm page with only one pte
1285 * pointing to it: so break it.
1288 break_cow(rmap_item
);
1290 return err
? NULL
: page
;
1293 static __always_inline
1294 bool __is_page_sharing_candidate(struct stable_node
*stable_node
, int offset
)
1296 VM_BUG_ON(stable_node
->rmap_hlist_len
< 0);
1298 * Check that at least one mapping still exists, otherwise
1299 * there's no much point to merge and share with this
1300 * stable_node, as the underlying tree_page of the other
1301 * sharer is going to be freed soon.
1303 return stable_node
->rmap_hlist_len
&&
1304 stable_node
->rmap_hlist_len
+ offset
< ksm_max_page_sharing
;
1307 static __always_inline
1308 bool is_page_sharing_candidate(struct stable_node
*stable_node
)
1310 return __is_page_sharing_candidate(stable_node
, 0);
1313 static struct stable_node
*stable_node_dup(struct stable_node
**_stable_node
,
1314 struct page
**tree_page
,
1315 struct rb_root
*root
,
1316 bool prune_stale_stable_nodes
)
1318 struct stable_node
*dup
, *found
= NULL
, *stable_node
= *_stable_node
;
1319 struct hlist_node
*hlist_safe
;
1320 struct page
*_tree_page
;
1322 int found_rmap_hlist_len
;
1324 if (!prune_stale_stable_nodes
||
1325 time_before(jiffies
, stable_node
->chain_prune_time
+
1327 ksm_stable_node_chains_prune_millisecs
)))
1328 prune_stale_stable_nodes
= false;
1330 stable_node
->chain_prune_time
= jiffies
;
1332 hlist_for_each_entry_safe(dup
, hlist_safe
,
1333 &stable_node
->hlist
, hlist_dup
) {
1336 * We must walk all stable_node_dup to prune the stale
1337 * stable nodes during lookup.
1339 * get_ksm_page can drop the nodes from the
1340 * stable_node->hlist if they point to freed pages
1341 * (that's why we do a _safe walk). The "dup"
1342 * stable_node parameter itself will be freed from
1343 * under us if it returns NULL.
1345 _tree_page
= get_ksm_page(dup
, false);
1349 if (is_page_sharing_candidate(dup
)) {
1351 dup
->rmap_hlist_len
> found_rmap_hlist_len
) {
1353 put_page(*tree_page
);
1355 found_rmap_hlist_len
= found
->rmap_hlist_len
;
1356 *tree_page
= _tree_page
;
1358 if (!prune_stale_stable_nodes
)
1364 put_page(_tree_page
);
1368 * nr is relevant only if prune_stale_stable_nodes is true,
1369 * otherwise we may break the loop at nr == 1 even if there
1370 * are multiple entries.
1372 if (prune_stale_stable_nodes
&& found
) {
1375 * If there's not just one entry it would
1376 * corrupt memory, better BUG_ON. In KSM
1377 * context with no lock held it's not even
1380 BUG_ON(stable_node
->hlist
.first
->next
);
1383 * There's just one entry and it is below the
1384 * deduplication limit so drop the chain.
1386 rb_replace_node(&stable_node
->node
, &found
->node
,
1388 free_stable_node(stable_node
);
1389 ksm_stable_node_chains
--;
1390 ksm_stable_node_dups
--;
1392 * NOTE: the caller depends on the
1393 * *_stable_node to become NULL if the chain
1394 * was collapsed. Enforce that if anything
1395 * uses a stale (freed) stable_node chain a
1396 * visible crash will materialize (instead of
1397 * an use after free).
1399 *_stable_node
= stable_node
= NULL
;
1400 } else if (__is_page_sharing_candidate(found
, 1)) {
1402 * Refile our candidate at the head
1403 * after the prune if our candidate
1404 * can accept one more future sharing
1405 * in addition to the one underway.
1407 hlist_del(&found
->hlist_dup
);
1408 hlist_add_head(&found
->hlist_dup
,
1409 &stable_node
->hlist
);
1416 static struct stable_node
*stable_node_dup_any(struct stable_node
*stable_node
,
1417 struct rb_root
*root
)
1419 if (!is_stable_node_chain(stable_node
))
1421 if (hlist_empty(&stable_node
->hlist
)) {
1422 free_stable_node_chain(stable_node
, root
);
1425 return hlist_entry(stable_node
->hlist
.first
,
1426 typeof(*stable_node
), hlist_dup
);
1429 static struct stable_node
*__stable_node_chain(struct stable_node
**_stable_node
,
1430 struct page
**tree_page
,
1431 struct rb_root
*root
,
1432 bool prune_stale_stable_nodes
)
1434 struct stable_node
*stable_node
= *_stable_node
;
1435 if (!is_stable_node_chain(stable_node
)) {
1436 if (is_page_sharing_candidate(stable_node
)) {
1437 *tree_page
= get_ksm_page(stable_node
, false);
1442 return stable_node_dup(_stable_node
, tree_page
, root
,
1443 prune_stale_stable_nodes
);
1446 static __always_inline
struct stable_node
*chain_prune(struct stable_node
**s_n
,
1448 struct rb_root
*root
)
1450 return __stable_node_chain(s_n
, t_p
, root
, true);
1453 static __always_inline
struct stable_node
*chain(struct stable_node
*s_n
,
1455 struct rb_root
*root
)
1457 return __stable_node_chain(&s_n
, t_p
, root
, false);
1461 * stable_tree_search - search for page inside the stable tree
1463 * This function checks if there is a page inside the stable tree
1464 * with identical content to the page that we are scanning right now.
1466 * This function returns the stable tree node of identical content if found,
1469 static struct page
*stable_tree_search(struct page
*page
)
1472 struct rb_root
*root
;
1473 struct rb_node
**new;
1474 struct rb_node
*parent
;
1475 struct stable_node
*stable_node
, *stable_node_dup
, *stable_node_any
;
1476 struct stable_node
*page_node
;
1478 page_node
= page_stable_node(page
);
1479 if (page_node
&& page_node
->head
!= &migrate_nodes
) {
1480 /* ksm page forked */
1485 nid
= get_kpfn_nid(page_to_pfn(page
));
1486 root
= root_stable_tree
+ nid
;
1488 new = &root
->rb_node
;
1492 struct page
*tree_page
;
1496 stable_node
= rb_entry(*new, struct stable_node
, node
);
1497 stable_node_any
= NULL
;
1498 stable_node_dup
= chain_prune(&stable_node
, &tree_page
, root
);
1500 * NOTE: stable_node may have been freed by
1501 * chain_prune() if the returned stable_node_dup is
1502 * not NULL. stable_node_dup may have been inserted in
1503 * the rbtree instead as a regular stable_node (in
1504 * order to collapse the stable_node chain if a single
1505 * stable_node dup was found in it).
1507 if (!stable_node_dup
) {
1509 * Either all stable_node dups were full in
1510 * this stable_node chain, or this chain was
1511 * empty and should be rb_erased.
1513 stable_node_any
= stable_node_dup_any(stable_node
,
1515 if (!stable_node_any
) {
1516 /* rb_erase just run */
1520 * Take any of the stable_node dups page of
1521 * this stable_node chain to let the tree walk
1522 * continue. All KSM pages belonging to the
1523 * stable_node dups in a stable_node chain
1524 * have the same content and they're
1525 * wrprotected at all times. Any will work
1526 * fine to continue the walk.
1528 tree_page
= get_ksm_page(stable_node_any
, false);
1530 VM_BUG_ON(!stable_node_dup
^ !!stable_node_any
);
1533 * If we walked over a stale stable_node,
1534 * get_ksm_page() will call rb_erase() and it
1535 * may rebalance the tree from under us. So
1536 * restart the search from scratch. Returning
1537 * NULL would be safe too, but we'd generate
1538 * false negative insertions just because some
1539 * stable_node was stale.
1544 ret
= memcmp_pages(page
, tree_page
);
1545 put_page(tree_page
);
1549 new = &parent
->rb_left
;
1551 new = &parent
->rb_right
;
1554 VM_BUG_ON(page_node
->head
!= &migrate_nodes
);
1556 * Test if the migrated page should be merged
1557 * into a stable node dup. If the mapcount is
1558 * 1 we can migrate it with another KSM page
1559 * without adding it to the chain.
1561 if (page_mapcount(page
) > 1)
1565 if (!stable_node_dup
) {
1567 * If the stable_node is a chain and
1568 * we got a payload match in memcmp
1569 * but we cannot merge the scanned
1570 * page in any of the existing
1571 * stable_node dups because they're
1572 * all full, we need to wait the
1573 * scanned page to find itself a match
1574 * in the unstable tree to create a
1575 * brand new KSM page to add later to
1576 * the dups of this stable_node.
1582 * Lock and unlock the stable_node's page (which
1583 * might already have been migrated) so that page
1584 * migration is sure to notice its raised count.
1585 * It would be more elegant to return stable_node
1586 * than kpage, but that involves more changes.
1588 tree_page
= get_ksm_page(stable_node_dup
, true);
1589 if (unlikely(!tree_page
))
1591 * The tree may have been rebalanced,
1592 * so re-evaluate parent and new.
1595 unlock_page(tree_page
);
1597 if (get_kpfn_nid(stable_node_dup
->kpfn
) !=
1598 NUMA(stable_node_dup
->nid
)) {
1599 put_page(tree_page
);
1609 list_del(&page_node
->list
);
1610 DO_NUMA(page_node
->nid
= nid
);
1611 rb_link_node(&page_node
->node
, parent
, new);
1612 rb_insert_color(&page_node
->node
, root
);
1614 if (is_page_sharing_candidate(page_node
)) {
1622 * If stable_node was a chain and chain_prune collapsed it,
1623 * stable_node will be NULL here. In that case the
1624 * stable_node_dup is the regular stable_node that has
1625 * replaced the chain. If stable_node is not NULL and equal to
1626 * stable_node_dup there was no chain and stable_node_dup is
1627 * the regular stable_node in the stable rbtree. Otherwise
1628 * stable_node is the chain and stable_node_dup is the dup to
1631 if (!stable_node
|| stable_node_dup
== stable_node
) {
1632 VM_BUG_ON(is_stable_node_chain(stable_node_dup
));
1633 VM_BUG_ON(is_stable_node_dup(stable_node_dup
));
1634 /* there is no chain */
1636 VM_BUG_ON(page_node
->head
!= &migrate_nodes
);
1637 list_del(&page_node
->list
);
1638 DO_NUMA(page_node
->nid
= nid
);
1639 rb_replace_node(&stable_node_dup
->node
,
1642 if (is_page_sharing_candidate(page_node
))
1647 rb_erase(&stable_node_dup
->node
, root
);
1651 VM_BUG_ON(!is_stable_node_chain(stable_node
));
1652 __stable_node_dup_del(stable_node_dup
);
1654 VM_BUG_ON(page_node
->head
!= &migrate_nodes
);
1655 list_del(&page_node
->list
);
1656 DO_NUMA(page_node
->nid
= nid
);
1657 stable_node_chain_add_dup(page_node
, stable_node
);
1658 if (is_page_sharing_candidate(page_node
))
1666 stable_node_dup
->head
= &migrate_nodes
;
1667 list_add(&stable_node_dup
->list
, stable_node_dup
->head
);
1671 /* stable_node_dup could be null if it reached the limit */
1672 if (!stable_node_dup
)
1673 stable_node_dup
= stable_node_any
;
1675 * If stable_node was a chain and chain_prune collapsed it,
1676 * stable_node will be NULL here. In that case the
1677 * stable_node_dup is the regular stable_node that has
1678 * replaced the chain. If stable_node is not NULL and equal to
1679 * stable_node_dup there was no chain and stable_node_dup is
1680 * the regular stable_node in the stable rbtree.
1682 if (!stable_node
|| stable_node_dup
== stable_node
) {
1683 VM_BUG_ON(is_stable_node_chain(stable_node_dup
));
1684 VM_BUG_ON(is_stable_node_dup(stable_node_dup
));
1685 /* chain is missing so create it */
1686 stable_node
= alloc_stable_node_chain(stable_node_dup
,
1692 * Add this stable_node dup that was
1693 * migrated to the stable_node chain
1694 * of the current nid for this page
1697 VM_BUG_ON(!is_stable_node_chain(stable_node
));
1698 VM_BUG_ON(!is_stable_node_dup(stable_node_dup
));
1699 VM_BUG_ON(page_node
->head
!= &migrate_nodes
);
1700 list_del(&page_node
->list
);
1701 DO_NUMA(page_node
->nid
= nid
);
1702 stable_node_chain_add_dup(page_node
, stable_node
);
1707 * stable_tree_insert - insert stable tree node pointing to new ksm page
1708 * into the stable tree.
1710 * This function returns the stable tree node just allocated on success,
1713 static struct stable_node
*stable_tree_insert(struct page
*kpage
)
1717 struct rb_root
*root
;
1718 struct rb_node
**new;
1719 struct rb_node
*parent
;
1720 struct stable_node
*stable_node
, *stable_node_dup
, *stable_node_any
;
1721 bool need_chain
= false;
1723 kpfn
= page_to_pfn(kpage
);
1724 nid
= get_kpfn_nid(kpfn
);
1725 root
= root_stable_tree
+ nid
;
1728 new = &root
->rb_node
;
1731 struct page
*tree_page
;
1735 stable_node
= rb_entry(*new, struct stable_node
, node
);
1736 stable_node_any
= NULL
;
1737 stable_node_dup
= chain(stable_node
, &tree_page
, root
);
1738 if (!stable_node_dup
) {
1740 * Either all stable_node dups were full in
1741 * this stable_node chain, or this chain was
1742 * empty and should be rb_erased.
1744 stable_node_any
= stable_node_dup_any(stable_node
,
1746 if (!stable_node_any
) {
1747 /* rb_erase just run */
1751 * Take any of the stable_node dups page of
1752 * this stable_node chain to let the tree walk
1753 * continue. All KSM pages belonging to the
1754 * stable_node dups in a stable_node chain
1755 * have the same content and they're
1756 * wrprotected at all times. Any will work
1757 * fine to continue the walk.
1759 tree_page
= get_ksm_page(stable_node_any
, false);
1761 VM_BUG_ON(!stable_node_dup
^ !!stable_node_any
);
1764 * If we walked over a stale stable_node,
1765 * get_ksm_page() will call rb_erase() and it
1766 * may rebalance the tree from under us. So
1767 * restart the search from scratch. Returning
1768 * NULL would be safe too, but we'd generate
1769 * false negative insertions just because some
1770 * stable_node was stale.
1775 ret
= memcmp_pages(kpage
, tree_page
);
1776 put_page(tree_page
);
1780 new = &parent
->rb_left
;
1782 new = &parent
->rb_right
;
1789 stable_node_dup
= alloc_stable_node();
1790 if (!stable_node_dup
)
1793 INIT_HLIST_HEAD(&stable_node_dup
->hlist
);
1794 stable_node_dup
->kpfn
= kpfn
;
1795 set_page_stable_node(kpage
, stable_node_dup
);
1796 stable_node_dup
->rmap_hlist_len
= 0;
1797 DO_NUMA(stable_node_dup
->nid
= nid
);
1799 rb_link_node(&stable_node_dup
->node
, parent
, new);
1800 rb_insert_color(&stable_node_dup
->node
, root
);
1802 if (!is_stable_node_chain(stable_node
)) {
1803 struct stable_node
*orig
= stable_node
;
1804 /* chain is missing so create it */
1805 stable_node
= alloc_stable_node_chain(orig
, root
);
1807 free_stable_node(stable_node_dup
);
1811 stable_node_chain_add_dup(stable_node_dup
, stable_node
);
1814 return stable_node_dup
;
1818 * unstable_tree_search_insert - search for identical page,
1819 * else insert rmap_item into the unstable tree.
1821 * This function searches for a page in the unstable tree identical to the
1822 * page currently being scanned; and if no identical page is found in the
1823 * tree, we insert rmap_item as a new object into the unstable tree.
1825 * This function returns pointer to rmap_item found to be identical
1826 * to the currently scanned page, NULL otherwise.
1828 * This function does both searching and inserting, because they share
1829 * the same walking algorithm in an rbtree.
1832 struct rmap_item
*unstable_tree_search_insert(struct rmap_item
*rmap_item
,
1834 struct page
**tree_pagep
)
1836 struct rb_node
**new;
1837 struct rb_root
*root
;
1838 struct rb_node
*parent
= NULL
;
1841 nid
= get_kpfn_nid(page_to_pfn(page
));
1842 root
= root_unstable_tree
+ nid
;
1843 new = &root
->rb_node
;
1846 struct rmap_item
*tree_rmap_item
;
1847 struct page
*tree_page
;
1851 tree_rmap_item
= rb_entry(*new, struct rmap_item
, node
);
1852 tree_page
= get_mergeable_page(tree_rmap_item
);
1857 * Don't substitute a ksm page for a forked page.
1859 if (page
== tree_page
) {
1860 put_page(tree_page
);
1864 ret
= memcmp_pages(page
, tree_page
);
1868 put_page(tree_page
);
1869 new = &parent
->rb_left
;
1870 } else if (ret
> 0) {
1871 put_page(tree_page
);
1872 new = &parent
->rb_right
;
1873 } else if (!ksm_merge_across_nodes
&&
1874 page_to_nid(tree_page
) != nid
) {
1876 * If tree_page has been migrated to another NUMA node,
1877 * it will be flushed out and put in the right unstable
1878 * tree next time: only merge with it when across_nodes.
1880 put_page(tree_page
);
1883 *tree_pagep
= tree_page
;
1884 return tree_rmap_item
;
1888 rmap_item
->address
|= UNSTABLE_FLAG
;
1889 rmap_item
->address
|= (ksm_scan
.seqnr
& SEQNR_MASK
);
1890 DO_NUMA(rmap_item
->nid
= nid
);
1891 rb_link_node(&rmap_item
->node
, parent
, new);
1892 rb_insert_color(&rmap_item
->node
, root
);
1894 ksm_pages_unshared
++;
1899 * stable_tree_append - add another rmap_item to the linked list of
1900 * rmap_items hanging off a given node of the stable tree, all sharing
1901 * the same ksm page.
1903 static void stable_tree_append(struct rmap_item
*rmap_item
,
1904 struct stable_node
*stable_node
,
1905 bool max_page_sharing_bypass
)
1908 * rmap won't find this mapping if we don't insert the
1909 * rmap_item in the right stable_node
1910 * duplicate. page_migration could break later if rmap breaks,
1911 * so we can as well crash here. We really need to check for
1912 * rmap_hlist_len == STABLE_NODE_CHAIN, but we can as well check
1913 * for other negative values as an undeflow if detected here
1914 * for the first time (and not when decreasing rmap_hlist_len)
1915 * would be sign of memory corruption in the stable_node.
1917 BUG_ON(stable_node
->rmap_hlist_len
< 0);
1919 stable_node
->rmap_hlist_len
++;
1920 if (!max_page_sharing_bypass
)
1921 /* possibly non fatal but unexpected overflow, only warn */
1922 WARN_ON_ONCE(stable_node
->rmap_hlist_len
>
1923 ksm_max_page_sharing
);
1925 rmap_item
->head
= stable_node
;
1926 rmap_item
->address
|= STABLE_FLAG
;
1927 hlist_add_head(&rmap_item
->hlist
, &stable_node
->hlist
);
1929 if (rmap_item
->hlist
.next
)
1930 ksm_pages_sharing
++;
1936 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1937 * if not, compare checksum to previous and if it's the same, see if page can
1938 * be inserted into the unstable tree, or merged with a page already there and
1939 * both transferred to the stable tree.
1941 * @page: the page that we are searching identical page to.
1942 * @rmap_item: the reverse mapping into the virtual address of this page
1944 static void cmp_and_merge_page(struct page
*page
, struct rmap_item
*rmap_item
)
1946 struct rmap_item
*tree_rmap_item
;
1947 struct page
*tree_page
= NULL
;
1948 struct stable_node
*stable_node
;
1950 unsigned int checksum
;
1952 bool max_page_sharing_bypass
= false;
1954 stable_node
= page_stable_node(page
);
1956 if (stable_node
->head
!= &migrate_nodes
&&
1957 get_kpfn_nid(READ_ONCE(stable_node
->kpfn
)) !=
1958 NUMA(stable_node
->nid
)) {
1959 stable_node_dup_del(stable_node
);
1960 stable_node
->head
= &migrate_nodes
;
1961 list_add(&stable_node
->list
, stable_node
->head
);
1963 if (stable_node
->head
!= &migrate_nodes
&&
1964 rmap_item
->head
== stable_node
)
1967 * If it's a KSM fork, allow it to go over the sharing limit
1970 if (!is_page_sharing_candidate(stable_node
))
1971 max_page_sharing_bypass
= true;
1974 /* We first start with searching the page inside the stable tree */
1975 kpage
= stable_tree_search(page
);
1976 if (kpage
== page
&& rmap_item
->head
== stable_node
) {
1981 remove_rmap_item_from_tree(rmap_item
);
1984 err
= try_to_merge_with_ksm_page(rmap_item
, page
, kpage
);
1987 * The page was successfully merged:
1988 * add its rmap_item to the stable tree.
1991 stable_tree_append(rmap_item
, page_stable_node(kpage
),
1992 max_page_sharing_bypass
);
2000 * If the hash value of the page has changed from the last time
2001 * we calculated it, this page is changing frequently: therefore we
2002 * don't want to insert it in the unstable tree, and we don't want
2003 * to waste our time searching for something identical to it there.
2005 checksum
= calc_checksum(page
);
2006 if (rmap_item
->oldchecksum
!= checksum
) {
2007 rmap_item
->oldchecksum
= checksum
;
2012 * Same checksum as an empty page. We attempt to merge it with the
2013 * appropriate zero page if the user enabled this via sysfs.
2015 if (ksm_use_zero_pages
&& (checksum
== zero_checksum
)) {
2016 struct vm_area_struct
*vma
;
2018 vma
= find_mergeable_vma(rmap_item
->mm
, rmap_item
->address
);
2019 err
= try_to_merge_one_page(vma
, page
,
2020 ZERO_PAGE(rmap_item
->address
));
2022 * In case of failure, the page was not really empty, so we
2023 * need to continue. Otherwise we're done.
2029 unstable_tree_search_insert(rmap_item
, page
, &tree_page
);
2030 if (tree_rmap_item
) {
2031 kpage
= try_to_merge_two_pages(rmap_item
, page
,
2032 tree_rmap_item
, tree_page
);
2033 put_page(tree_page
);
2036 * The pages were successfully merged: insert new
2037 * node in the stable tree and add both rmap_items.
2040 stable_node
= stable_tree_insert(kpage
);
2042 stable_tree_append(tree_rmap_item
, stable_node
,
2044 stable_tree_append(rmap_item
, stable_node
,
2050 * If we fail to insert the page into the stable tree,
2051 * we will have 2 virtual addresses that are pointing
2052 * to a ksm page left outside the stable tree,
2053 * in which case we need to break_cow on both.
2056 break_cow(tree_rmap_item
);
2057 break_cow(rmap_item
);
2063 static struct rmap_item
*get_next_rmap_item(struct mm_slot
*mm_slot
,
2064 struct rmap_item
**rmap_list
,
2067 struct rmap_item
*rmap_item
;
2069 while (*rmap_list
) {
2070 rmap_item
= *rmap_list
;
2071 if ((rmap_item
->address
& PAGE_MASK
) == addr
)
2073 if (rmap_item
->address
> addr
)
2075 *rmap_list
= rmap_item
->rmap_list
;
2076 remove_rmap_item_from_tree(rmap_item
);
2077 free_rmap_item(rmap_item
);
2080 rmap_item
= alloc_rmap_item();
2082 /* It has already been zeroed */
2083 rmap_item
->mm
= mm_slot
->mm
;
2084 rmap_item
->address
= addr
;
2085 rmap_item
->rmap_list
= *rmap_list
;
2086 *rmap_list
= rmap_item
;
2091 static struct rmap_item
*scan_get_next_rmap_item(struct page
**page
)
2093 struct mm_struct
*mm
;
2094 struct mm_slot
*slot
;
2095 struct vm_area_struct
*vma
;
2096 struct rmap_item
*rmap_item
;
2099 if (list_empty(&ksm_mm_head
.mm_list
))
2102 slot
= ksm_scan
.mm_slot
;
2103 if (slot
== &ksm_mm_head
) {
2105 * A number of pages can hang around indefinitely on per-cpu
2106 * pagevecs, raised page count preventing write_protect_page
2107 * from merging them. Though it doesn't really matter much,
2108 * it is puzzling to see some stuck in pages_volatile until
2109 * other activity jostles them out, and they also prevented
2110 * LTP's KSM test from succeeding deterministically; so drain
2111 * them here (here rather than on entry to ksm_do_scan(),
2112 * so we don't IPI too often when pages_to_scan is set low).
2114 lru_add_drain_all();
2117 * Whereas stale stable_nodes on the stable_tree itself
2118 * get pruned in the regular course of stable_tree_search(),
2119 * those moved out to the migrate_nodes list can accumulate:
2120 * so prune them once before each full scan.
2122 if (!ksm_merge_across_nodes
) {
2123 struct stable_node
*stable_node
, *next
;
2126 list_for_each_entry_safe(stable_node
, next
,
2127 &migrate_nodes
, list
) {
2128 page
= get_ksm_page(stable_node
, false);
2135 for (nid
= 0; nid
< ksm_nr_node_ids
; nid
++)
2136 root_unstable_tree
[nid
] = RB_ROOT
;
2138 spin_lock(&ksm_mmlist_lock
);
2139 slot
= list_entry(slot
->mm_list
.next
, struct mm_slot
, mm_list
);
2140 ksm_scan
.mm_slot
= slot
;
2141 spin_unlock(&ksm_mmlist_lock
);
2143 * Although we tested list_empty() above, a racing __ksm_exit
2144 * of the last mm on the list may have removed it since then.
2146 if (slot
== &ksm_mm_head
)
2149 ksm_scan
.address
= 0;
2150 ksm_scan
.rmap_list
= &slot
->rmap_list
;
2154 down_read(&mm
->mmap_sem
);
2155 if (ksm_test_exit(mm
))
2158 vma
= find_vma(mm
, ksm_scan
.address
);
2160 for (; vma
; vma
= vma
->vm_next
) {
2161 if (!(vma
->vm_flags
& VM_MERGEABLE
))
2163 if (ksm_scan
.address
< vma
->vm_start
)
2164 ksm_scan
.address
= vma
->vm_start
;
2166 ksm_scan
.address
= vma
->vm_end
;
2168 while (ksm_scan
.address
< vma
->vm_end
) {
2169 if (ksm_test_exit(mm
))
2171 *page
= follow_page(vma
, ksm_scan
.address
, FOLL_GET
);
2172 if (IS_ERR_OR_NULL(*page
)) {
2173 ksm_scan
.address
+= PAGE_SIZE
;
2177 if (PageAnon(*page
)) {
2178 flush_anon_page(vma
, *page
, ksm_scan
.address
);
2179 flush_dcache_page(*page
);
2180 rmap_item
= get_next_rmap_item(slot
,
2181 ksm_scan
.rmap_list
, ksm_scan
.address
);
2183 ksm_scan
.rmap_list
=
2184 &rmap_item
->rmap_list
;
2185 ksm_scan
.address
+= PAGE_SIZE
;
2188 up_read(&mm
->mmap_sem
);
2192 ksm_scan
.address
+= PAGE_SIZE
;
2197 if (ksm_test_exit(mm
)) {
2198 ksm_scan
.address
= 0;
2199 ksm_scan
.rmap_list
= &slot
->rmap_list
;
2202 * Nuke all the rmap_items that are above this current rmap:
2203 * because there were no VM_MERGEABLE vmas with such addresses.
2205 remove_trailing_rmap_items(slot
, ksm_scan
.rmap_list
);
2207 spin_lock(&ksm_mmlist_lock
);
2208 ksm_scan
.mm_slot
= list_entry(slot
->mm_list
.next
,
2209 struct mm_slot
, mm_list
);
2210 if (ksm_scan
.address
== 0) {
2212 * We've completed a full scan of all vmas, holding mmap_sem
2213 * throughout, and found no VM_MERGEABLE: so do the same as
2214 * __ksm_exit does to remove this mm from all our lists now.
2215 * This applies either when cleaning up after __ksm_exit
2216 * (but beware: we can reach here even before __ksm_exit),
2217 * or when all VM_MERGEABLE areas have been unmapped (and
2218 * mmap_sem then protects against race with MADV_MERGEABLE).
2220 hash_del(&slot
->link
);
2221 list_del(&slot
->mm_list
);
2222 spin_unlock(&ksm_mmlist_lock
);
2225 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
2226 up_read(&mm
->mmap_sem
);
2229 up_read(&mm
->mmap_sem
);
2231 * up_read(&mm->mmap_sem) first because after
2232 * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
2233 * already have been freed under us by __ksm_exit()
2234 * because the "mm_slot" is still hashed and
2235 * ksm_scan.mm_slot doesn't point to it anymore.
2237 spin_unlock(&ksm_mmlist_lock
);
2240 /* Repeat until we've completed scanning the whole list */
2241 slot
= ksm_scan
.mm_slot
;
2242 if (slot
!= &ksm_mm_head
)
2250 * ksm_do_scan - the ksm scanner main worker function.
2251 * @scan_npages - number of pages we want to scan before we return.
2253 static void ksm_do_scan(unsigned int scan_npages
)
2255 struct rmap_item
*rmap_item
;
2256 struct page
*uninitialized_var(page
);
2258 while (scan_npages
-- && likely(!freezing(current
))) {
2260 rmap_item
= scan_get_next_rmap_item(&page
);
2263 cmp_and_merge_page(page
, rmap_item
);
2268 static int ksmd_should_run(void)
2270 return (ksm_run
& KSM_RUN_MERGE
) && !list_empty(&ksm_mm_head
.mm_list
);
2273 static int ksm_scan_thread(void *nothing
)
2276 set_user_nice(current
, 5);
2278 while (!kthread_should_stop()) {
2279 mutex_lock(&ksm_thread_mutex
);
2280 wait_while_offlining();
2281 if (ksmd_should_run())
2282 ksm_do_scan(ksm_thread_pages_to_scan
);
2283 mutex_unlock(&ksm_thread_mutex
);
2287 if (ksmd_should_run()) {
2288 if (ksm_thread_sleep_millisecs
>= 1000)
2289 schedule_timeout_interruptible(
2290 msecs_to_jiffies(round_jiffies_relative(ksm_thread_sleep_millisecs
)));
2292 schedule_timeout_interruptible(
2293 msecs_to_jiffies(ksm_thread_sleep_millisecs
));
2295 wait_event_freezable(ksm_thread_wait
,
2296 ksmd_should_run() || kthread_should_stop());
2302 int ksm_madvise(struct vm_area_struct
*vma
, unsigned long start
,
2303 unsigned long end
, int advice
, unsigned long *vm_flags
)
2305 struct mm_struct
*mm
= vma
->vm_mm
;
2309 case MADV_MERGEABLE
:
2311 * Be somewhat over-protective for now!
2313 if (*vm_flags
& (VM_MERGEABLE
| VM_SHARED
| VM_MAYSHARE
|
2314 VM_PFNMAP
| VM_IO
| VM_DONTEXPAND
|
2315 VM_HUGETLB
| VM_MIXEDMAP
))
2316 return 0; /* just ignore the advice */
2319 if (*vm_flags
& VM_SAO
)
2323 if (!test_bit(MMF_VM_MERGEABLE
, &mm
->flags
)) {
2324 err
= __ksm_enter(mm
);
2329 *vm_flags
|= VM_MERGEABLE
;
2332 case MADV_UNMERGEABLE
:
2333 if (!(*vm_flags
& VM_MERGEABLE
))
2334 return 0; /* just ignore the advice */
2336 if (vma
->anon_vma
) {
2337 err
= unmerge_ksm_pages(vma
, start
, end
);
2342 *vm_flags
&= ~VM_MERGEABLE
;
2349 int __ksm_enter(struct mm_struct
*mm
)
2351 struct mm_slot
*mm_slot
;
2354 mm_slot
= alloc_mm_slot();
2358 /* Check ksm_run too? Would need tighter locking */
2359 needs_wakeup
= list_empty(&ksm_mm_head
.mm_list
);
2361 spin_lock(&ksm_mmlist_lock
);
2362 insert_to_mm_slots_hash(mm
, mm_slot
);
2364 * When KSM_RUN_MERGE (or KSM_RUN_STOP),
2365 * insert just behind the scanning cursor, to let the area settle
2366 * down a little; when fork is followed by immediate exec, we don't
2367 * want ksmd to waste time setting up and tearing down an rmap_list.
2369 * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
2370 * scanning cursor, otherwise KSM pages in newly forked mms will be
2371 * missed: then we might as well insert at the end of the list.
2373 if (ksm_run
& KSM_RUN_UNMERGE
)
2374 list_add_tail(&mm_slot
->mm_list
, &ksm_mm_head
.mm_list
);
2376 list_add_tail(&mm_slot
->mm_list
, &ksm_scan
.mm_slot
->mm_list
);
2377 spin_unlock(&ksm_mmlist_lock
);
2379 set_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
2380 atomic_inc(&mm
->mm_count
);
2383 wake_up_interruptible(&ksm_thread_wait
);
2388 void __ksm_exit(struct mm_struct
*mm
)
2390 struct mm_slot
*mm_slot
;
2391 int easy_to_free
= 0;
2394 * This process is exiting: if it's straightforward (as is the
2395 * case when ksmd was never running), free mm_slot immediately.
2396 * But if it's at the cursor or has rmap_items linked to it, use
2397 * mmap_sem to synchronize with any break_cows before pagetables
2398 * are freed, and leave the mm_slot on the list for ksmd to free.
2399 * Beware: ksm may already have noticed it exiting and freed the slot.
2402 spin_lock(&ksm_mmlist_lock
);
2403 mm_slot
= get_mm_slot(mm
);
2404 if (mm_slot
&& ksm_scan
.mm_slot
!= mm_slot
) {
2405 if (!mm_slot
->rmap_list
) {
2406 hash_del(&mm_slot
->link
);
2407 list_del(&mm_slot
->mm_list
);
2410 list_move(&mm_slot
->mm_list
,
2411 &ksm_scan
.mm_slot
->mm_list
);
2414 spin_unlock(&ksm_mmlist_lock
);
2417 free_mm_slot(mm_slot
);
2418 clear_bit(MMF_VM_MERGEABLE
, &mm
->flags
);
2420 } else if (mm_slot
) {
2421 down_write(&mm
->mmap_sem
);
2422 up_write(&mm
->mmap_sem
);
2426 struct page
*ksm_might_need_to_copy(struct page
*page
,
2427 struct vm_area_struct
*vma
, unsigned long address
)
2429 struct anon_vma
*anon_vma
= page_anon_vma(page
);
2430 struct page
*new_page
;
2432 if (PageKsm(page
)) {
2433 if (page_stable_node(page
) &&
2434 !(ksm_run
& KSM_RUN_UNMERGE
))
2435 return page
; /* no need to copy it */
2436 } else if (!anon_vma
) {
2437 return page
; /* no need to copy it */
2438 } else if (anon_vma
->root
== vma
->anon_vma
->root
&&
2439 page
->index
== linear_page_index(vma
, address
)) {
2440 return page
; /* still no need to copy it */
2442 if (!PageUptodate(page
))
2443 return page
; /* let do_swap_page report the error */
2445 new_page
= alloc_page_vma(GFP_HIGHUSER_MOVABLE
, vma
, address
);
2447 copy_user_highpage(new_page
, page
, address
, vma
);
2449 SetPageDirty(new_page
);
2450 __SetPageUptodate(new_page
);
2451 __SetPageLocked(new_page
);
2457 int rmap_walk_ksm(struct page
*page
, struct rmap_walk_control
*rwc
)
2459 struct stable_node
*stable_node
;
2460 struct rmap_item
*rmap_item
;
2461 int ret
= SWAP_AGAIN
;
2462 int search_new_forks
= 0;
2464 VM_BUG_ON_PAGE(!PageKsm(page
), page
);
2467 * Rely on the page lock to protect against concurrent modifications
2468 * to that page's node of the stable tree.
2470 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
2472 stable_node
= page_stable_node(page
);
2476 hlist_for_each_entry(rmap_item
, &stable_node
->hlist
, hlist
) {
2477 struct anon_vma
*anon_vma
= rmap_item
->anon_vma
;
2478 struct anon_vma_chain
*vmac
;
2479 struct vm_area_struct
*vma
;
2482 anon_vma_lock_read(anon_vma
);
2483 anon_vma_interval_tree_foreach(vmac
, &anon_vma
->rb_root
,
2487 if (rmap_item
->address
< vma
->vm_start
||
2488 rmap_item
->address
>= vma
->vm_end
)
2491 * Initially we examine only the vma which covers this
2492 * rmap_item; but later, if there is still work to do,
2493 * we examine covering vmas in other mms: in case they
2494 * were forked from the original since ksmd passed.
2496 if ((rmap_item
->mm
== vma
->vm_mm
) == search_new_forks
)
2499 if (rwc
->invalid_vma
&& rwc
->invalid_vma(vma
, rwc
->arg
))
2502 ret
= rwc
->rmap_one(page
, vma
,
2503 rmap_item
->address
, rwc
->arg
);
2504 if (ret
!= SWAP_AGAIN
) {
2505 anon_vma_unlock_read(anon_vma
);
2508 if (rwc
->done
&& rwc
->done(page
)) {
2509 anon_vma_unlock_read(anon_vma
);
2513 anon_vma_unlock_read(anon_vma
);
2515 if (!search_new_forks
++)
2521 #ifdef CONFIG_MIGRATION
2522 void ksm_migrate_page(struct page
*newpage
, struct page
*oldpage
)
2524 struct stable_node
*stable_node
;
2526 VM_BUG_ON_PAGE(!PageLocked(oldpage
), oldpage
);
2527 VM_BUG_ON_PAGE(!PageLocked(newpage
), newpage
);
2528 VM_BUG_ON_PAGE(newpage
->mapping
!= oldpage
->mapping
, newpage
);
2530 stable_node
= page_stable_node(newpage
);
2532 VM_BUG_ON_PAGE(stable_node
->kpfn
!= page_to_pfn(oldpage
), oldpage
);
2533 stable_node
->kpfn
= page_to_pfn(newpage
);
2535 * newpage->mapping was set in advance; now we need smp_wmb()
2536 * to make sure that the new stable_node->kpfn is visible
2537 * to get_ksm_page() before it can see that oldpage->mapping
2538 * has gone stale (or that PageSwapCache has been cleared).
2541 set_page_stable_node(oldpage
, NULL
);
2544 #endif /* CONFIG_MIGRATION */
2546 #ifdef CONFIG_MEMORY_HOTREMOVE
2547 static void wait_while_offlining(void)
2549 while (ksm_run
& KSM_RUN_OFFLINE
) {
2550 mutex_unlock(&ksm_thread_mutex
);
2551 wait_on_bit(&ksm_run
, ilog2(KSM_RUN_OFFLINE
),
2552 TASK_UNINTERRUPTIBLE
);
2553 mutex_lock(&ksm_thread_mutex
);
2557 static bool stable_node_dup_remove_range(struct stable_node
*stable_node
,
2558 unsigned long start_pfn
,
2559 unsigned long end_pfn
)
2561 if (stable_node
->kpfn
>= start_pfn
&&
2562 stable_node
->kpfn
< end_pfn
) {
2564 * Don't get_ksm_page, page has already gone:
2565 * which is why we keep kpfn instead of page*
2567 remove_node_from_stable_tree(stable_node
);
2573 static bool stable_node_chain_remove_range(struct stable_node
*stable_node
,
2574 unsigned long start_pfn
,
2575 unsigned long end_pfn
,
2576 struct rb_root
*root
)
2578 struct stable_node
*dup
;
2579 struct hlist_node
*hlist_safe
;
2581 if (!is_stable_node_chain(stable_node
)) {
2582 VM_BUG_ON(is_stable_node_dup(stable_node
));
2583 return stable_node_dup_remove_range(stable_node
, start_pfn
,
2587 hlist_for_each_entry_safe(dup
, hlist_safe
,
2588 &stable_node
->hlist
, hlist_dup
) {
2589 VM_BUG_ON(!is_stable_node_dup(dup
));
2590 stable_node_dup_remove_range(dup
, start_pfn
, end_pfn
);
2592 if (hlist_empty(&stable_node
->hlist
)) {
2593 free_stable_node_chain(stable_node
, root
);
2594 return true; /* notify caller that tree was rebalanced */
2599 static void ksm_check_stable_tree(unsigned long start_pfn
,
2600 unsigned long end_pfn
)
2602 struct stable_node
*stable_node
, *next
;
2603 struct rb_node
*node
;
2606 for (nid
= 0; nid
< ksm_nr_node_ids
; nid
++) {
2607 node
= rb_first(root_stable_tree
+ nid
);
2609 stable_node
= rb_entry(node
, struct stable_node
, node
);
2610 if (stable_node_chain_remove_range(stable_node
,
2614 node
= rb_first(root_stable_tree
+ nid
);
2616 node
= rb_next(node
);
2620 list_for_each_entry_safe(stable_node
, next
, &migrate_nodes
, list
) {
2621 if (stable_node
->kpfn
>= start_pfn
&&
2622 stable_node
->kpfn
< end_pfn
)
2623 remove_node_from_stable_tree(stable_node
);
2628 static int ksm_memory_callback(struct notifier_block
*self
,
2629 unsigned long action
, void *arg
)
2631 struct memory_notify
*mn
= arg
;
2634 case MEM_GOING_OFFLINE
:
2636 * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
2637 * and remove_all_stable_nodes() while memory is going offline:
2638 * it is unsafe for them to touch the stable tree at this time.
2639 * But unmerge_ksm_pages(), rmap lookups and other entry points
2640 * which do not need the ksm_thread_mutex are all safe.
2642 mutex_lock(&ksm_thread_mutex
);
2643 ksm_run
|= KSM_RUN_OFFLINE
;
2644 mutex_unlock(&ksm_thread_mutex
);
2649 * Most of the work is done by page migration; but there might
2650 * be a few stable_nodes left over, still pointing to struct
2651 * pages which have been offlined: prune those from the tree,
2652 * otherwise get_ksm_page() might later try to access a
2653 * non-existent struct page.
2655 ksm_check_stable_tree(mn
->start_pfn
,
2656 mn
->start_pfn
+ mn
->nr_pages
);
2659 case MEM_CANCEL_OFFLINE
:
2660 mutex_lock(&ksm_thread_mutex
);
2661 ksm_run
&= ~KSM_RUN_OFFLINE
;
2662 mutex_unlock(&ksm_thread_mutex
);
2664 smp_mb(); /* wake_up_bit advises this */
2665 wake_up_bit(&ksm_run
, ilog2(KSM_RUN_OFFLINE
));
2671 static void wait_while_offlining(void)
2674 #endif /* CONFIG_MEMORY_HOTREMOVE */
2678 * This all compiles without CONFIG_SYSFS, but is a waste of space.
2681 #define KSM_ATTR_RO(_name) \
2682 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2683 #define KSM_ATTR(_name) \
2684 static struct kobj_attribute _name##_attr = \
2685 __ATTR(_name, 0644, _name##_show, _name##_store)
2687 static ssize_t
sleep_millisecs_show(struct kobject
*kobj
,
2688 struct kobj_attribute
*attr
, char *buf
)
2690 return sprintf(buf
, "%u\n", ksm_thread_sleep_millisecs
);
2693 static ssize_t
sleep_millisecs_store(struct kobject
*kobj
,
2694 struct kobj_attribute
*attr
,
2695 const char *buf
, size_t count
)
2697 unsigned long msecs
;
2700 err
= kstrtoul(buf
, 10, &msecs
);
2701 if (err
|| msecs
> UINT_MAX
)
2704 ksm_thread_sleep_millisecs
= msecs
;
2708 KSM_ATTR(sleep_millisecs
);
2710 static ssize_t
pages_to_scan_show(struct kobject
*kobj
,
2711 struct kobj_attribute
*attr
, char *buf
)
2713 return sprintf(buf
, "%u\n", ksm_thread_pages_to_scan
);
2716 static ssize_t
pages_to_scan_store(struct kobject
*kobj
,
2717 struct kobj_attribute
*attr
,
2718 const char *buf
, size_t count
)
2721 unsigned long nr_pages
;
2723 err
= kstrtoul(buf
, 10, &nr_pages
);
2724 if (err
|| nr_pages
> UINT_MAX
)
2727 ksm_thread_pages_to_scan
= nr_pages
;
2731 KSM_ATTR(pages_to_scan
);
2733 static ssize_t
run_show(struct kobject
*kobj
, struct kobj_attribute
*attr
,
2736 return sprintf(buf
, "%lu\n", ksm_run
);
2739 static ssize_t
run_store(struct kobject
*kobj
, struct kobj_attribute
*attr
,
2740 const char *buf
, size_t count
)
2743 unsigned long flags
;
2745 err
= kstrtoul(buf
, 10, &flags
);
2746 if (err
|| flags
> UINT_MAX
)
2748 if (flags
> KSM_RUN_UNMERGE
)
2752 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
2753 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
2754 * breaking COW to free the pages_shared (but leaves mm_slots
2755 * on the list for when ksmd may be set running again).
2758 mutex_lock(&ksm_thread_mutex
);
2759 wait_while_offlining();
2760 if (ksm_run
!= flags
) {
2762 if (flags
& KSM_RUN_UNMERGE
) {
2763 set_current_oom_origin();
2764 err
= unmerge_and_remove_all_rmap_items();
2765 clear_current_oom_origin();
2767 ksm_run
= KSM_RUN_STOP
;
2772 mutex_unlock(&ksm_thread_mutex
);
2774 if (flags
& KSM_RUN_MERGE
)
2775 wake_up_interruptible(&ksm_thread_wait
);
2782 static ssize_t
merge_across_nodes_show(struct kobject
*kobj
,
2783 struct kobj_attribute
*attr
, char *buf
)
2785 return sprintf(buf
, "%u\n", ksm_merge_across_nodes
);
2788 static ssize_t
merge_across_nodes_store(struct kobject
*kobj
,
2789 struct kobj_attribute
*attr
,
2790 const char *buf
, size_t count
)
2795 err
= kstrtoul(buf
, 10, &knob
);
2801 mutex_lock(&ksm_thread_mutex
);
2802 wait_while_offlining();
2803 if (ksm_merge_across_nodes
!= knob
) {
2804 if (ksm_pages_shared
|| remove_all_stable_nodes())
2806 else if (root_stable_tree
== one_stable_tree
) {
2807 struct rb_root
*buf
;
2809 * This is the first time that we switch away from the
2810 * default of merging across nodes: must now allocate
2811 * a buffer to hold as many roots as may be needed.
2812 * Allocate stable and unstable together:
2813 * MAXSMP NODES_SHIFT 10 will use 16kB.
2815 buf
= kcalloc(nr_node_ids
+ nr_node_ids
, sizeof(*buf
),
2817 /* Let us assume that RB_ROOT is NULL is zero */
2821 root_stable_tree
= buf
;
2822 root_unstable_tree
= buf
+ nr_node_ids
;
2823 /* Stable tree is empty but not the unstable */
2824 root_unstable_tree
[0] = one_unstable_tree
[0];
2828 ksm_merge_across_nodes
= knob
;
2829 ksm_nr_node_ids
= knob
? 1 : nr_node_ids
;
2832 mutex_unlock(&ksm_thread_mutex
);
2834 return err
? err
: count
;
2836 KSM_ATTR(merge_across_nodes
);
2839 static ssize_t
use_zero_pages_show(struct kobject
*kobj
,
2840 struct kobj_attribute
*attr
, char *buf
)
2842 return sprintf(buf
, "%u\n", ksm_use_zero_pages
);
2844 static ssize_t
use_zero_pages_store(struct kobject
*kobj
,
2845 struct kobj_attribute
*attr
,
2846 const char *buf
, size_t count
)
2851 err
= kstrtobool(buf
, &value
);
2855 ksm_use_zero_pages
= value
;
2859 KSM_ATTR(use_zero_pages
);
2861 static ssize_t
max_page_sharing_show(struct kobject
*kobj
,
2862 struct kobj_attribute
*attr
, char *buf
)
2864 return sprintf(buf
, "%u\n", ksm_max_page_sharing
);
2867 static ssize_t
max_page_sharing_store(struct kobject
*kobj
,
2868 struct kobj_attribute
*attr
,
2869 const char *buf
, size_t count
)
2874 err
= kstrtoint(buf
, 10, &knob
);
2878 * When a KSM page is created it is shared by 2 mappings. This
2879 * being a signed comparison, it implicitly verifies it's not
2885 if (READ_ONCE(ksm_max_page_sharing
) == knob
)
2888 mutex_lock(&ksm_thread_mutex
);
2889 wait_while_offlining();
2890 if (ksm_max_page_sharing
!= knob
) {
2891 if (ksm_pages_shared
|| remove_all_stable_nodes())
2894 ksm_max_page_sharing
= knob
;
2896 mutex_unlock(&ksm_thread_mutex
);
2898 return err
? err
: count
;
2900 KSM_ATTR(max_page_sharing
);
2902 static ssize_t
pages_shared_show(struct kobject
*kobj
,
2903 struct kobj_attribute
*attr
, char *buf
)
2905 return sprintf(buf
, "%lu\n", ksm_pages_shared
);
2907 KSM_ATTR_RO(pages_shared
);
2909 static ssize_t
pages_sharing_show(struct kobject
*kobj
,
2910 struct kobj_attribute
*attr
, char *buf
)
2912 return sprintf(buf
, "%lu\n", ksm_pages_sharing
);
2914 KSM_ATTR_RO(pages_sharing
);
2916 static ssize_t
pages_unshared_show(struct kobject
*kobj
,
2917 struct kobj_attribute
*attr
, char *buf
)
2919 return sprintf(buf
, "%lu\n", ksm_pages_unshared
);
2921 KSM_ATTR_RO(pages_unshared
);
2923 static ssize_t
pages_volatile_show(struct kobject
*kobj
,
2924 struct kobj_attribute
*attr
, char *buf
)
2926 long ksm_pages_volatile
;
2928 ksm_pages_volatile
= ksm_rmap_items
- ksm_pages_shared
2929 - ksm_pages_sharing
- ksm_pages_unshared
;
2931 * It was not worth any locking to calculate that statistic,
2932 * but it might therefore sometimes be negative: conceal that.
2934 if (ksm_pages_volatile
< 0)
2935 ksm_pages_volatile
= 0;
2936 return sprintf(buf
, "%ld\n", ksm_pages_volatile
);
2938 KSM_ATTR_RO(pages_volatile
);
2940 static ssize_t
stable_node_dups_show(struct kobject
*kobj
,
2941 struct kobj_attribute
*attr
, char *buf
)
2943 return sprintf(buf
, "%lu\n", ksm_stable_node_dups
);
2945 KSM_ATTR_RO(stable_node_dups
);
2947 static ssize_t
stable_node_chains_show(struct kobject
*kobj
,
2948 struct kobj_attribute
*attr
, char *buf
)
2950 return sprintf(buf
, "%lu\n", ksm_stable_node_chains
);
2952 KSM_ATTR_RO(stable_node_chains
);
2955 stable_node_chains_prune_millisecs_show(struct kobject
*kobj
,
2956 struct kobj_attribute
*attr
,
2959 return sprintf(buf
, "%u\n", ksm_stable_node_chains_prune_millisecs
);
2963 stable_node_chains_prune_millisecs_store(struct kobject
*kobj
,
2964 struct kobj_attribute
*attr
,
2965 const char *buf
, size_t count
)
2967 unsigned long msecs
;
2970 err
= kstrtoul(buf
, 10, &msecs
);
2971 if (err
|| msecs
> UINT_MAX
)
2974 ksm_stable_node_chains_prune_millisecs
= msecs
;
2978 KSM_ATTR(stable_node_chains_prune_millisecs
);
2980 static ssize_t
full_scans_show(struct kobject
*kobj
,
2981 struct kobj_attribute
*attr
, char *buf
)
2983 return sprintf(buf
, "%lu\n", ksm_scan
.seqnr
);
2985 KSM_ATTR_RO(full_scans
);
2987 static struct attribute
*ksm_attrs
[] = {
2988 &sleep_millisecs_attr
.attr
,
2989 &pages_to_scan_attr
.attr
,
2991 &pages_shared_attr
.attr
,
2992 &pages_sharing_attr
.attr
,
2993 &pages_unshared_attr
.attr
,
2994 &pages_volatile_attr
.attr
,
2995 &full_scans_attr
.attr
,
2997 &merge_across_nodes_attr
.attr
,
2999 &max_page_sharing_attr
.attr
,
3000 &stable_node_chains_attr
.attr
,
3001 &stable_node_dups_attr
.attr
,
3002 &stable_node_chains_prune_millisecs_attr
.attr
,
3003 &use_zero_pages_attr
.attr
,
3007 static struct attribute_group ksm_attr_group
= {
3011 #endif /* CONFIG_SYSFS */
3013 static int __init
ksm_init(void)
3015 struct task_struct
*ksm_thread
;
3018 /* The correct value depends on page size and endianness */
3019 zero_checksum
= calc_checksum(ZERO_PAGE(0));
3020 /* Default to false for backwards compatibility */
3021 ksm_use_zero_pages
= false;
3023 err
= ksm_slab_init();
3027 ksm_thread
= kthread_run(ksm_scan_thread
, NULL
, "ksmd");
3028 if (IS_ERR(ksm_thread
)) {
3029 pr_err("ksm: creating kthread failed\n");
3030 err
= PTR_ERR(ksm_thread
);
3035 err
= sysfs_create_group(mm_kobj
, &ksm_attr_group
);
3037 pr_err("ksm: register sysfs failed\n");
3038 kthread_stop(ksm_thread
);
3042 ksm_run
= KSM_RUN_MERGE
; /* no way for user to start it */
3044 #endif /* CONFIG_SYSFS */
3046 #ifdef CONFIG_MEMORY_HOTREMOVE
3047 /* There is no significance to this priority 100 */
3048 hotplug_memory_notifier(ksm_memory_callback
, 100);
3057 subsys_initcall(ksm_init
);