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;
256 /* Zeroed when merging across nodes is not allowed */
257 static unsigned int ksm_merge_across_nodes = 1;
258 static int ksm_nr_node_ids = 1;
260 #define ksm_merge_across_nodes 1U
261 #define ksm_nr_node_ids 1
264 #define KSM_RUN_STOP 0
265 #define KSM_RUN_MERGE 1
266 #define KSM_RUN_UNMERGE 2
267 #define KSM_RUN_OFFLINE 4
268 static unsigned long ksm_run = KSM_RUN_STOP;
269 static void wait_while_offlining(void);
271 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
272 static DEFINE_MUTEX(ksm_thread_mutex);
273 static DEFINE_SPINLOCK(ksm_mmlist_lock);
275 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
276 sizeof(struct __struct), __alignof__(struct __struct),\
279 static int __init ksm_slab_init(void)
281 rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
282 if (!rmap_item_cache)
285 stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
286 if (!stable_node_cache)
289 mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
296 kmem_cache_destroy(stable_node_cache);
298 kmem_cache_destroy(rmap_item_cache);
303 static void __init ksm_slab_free(void)
305 kmem_cache_destroy(mm_slot_cache);
306 kmem_cache_destroy(stable_node_cache);
307 kmem_cache_destroy(rmap_item_cache);
308 mm_slot_cache = NULL;
311 static __always_inline bool is_stable_node_chain(struct stable_node *chain)
313 return chain->rmap_hlist_len == STABLE_NODE_CHAIN;
316 static __always_inline bool is_stable_node_dup(struct stable_node *dup)
318 return dup->head == STABLE_NODE_DUP_HEAD;
321 static inline void stable_node_chain_add_dup(struct stable_node *dup,
322 struct stable_node *chain)
324 VM_BUG_ON(is_stable_node_dup(dup));
325 dup->head = STABLE_NODE_DUP_HEAD;
326 VM_BUG_ON(!is_stable_node_chain(chain));
327 hlist_add_head(&dup->hlist_dup, &chain->hlist);
328 ksm_stable_node_dups++;
331 static inline void __stable_node_dup_del(struct stable_node *dup)
333 hlist_del(&dup->hlist_dup);
334 ksm_stable_node_dups--;
337 static inline void stable_node_dup_del(struct stable_node *dup)
339 VM_BUG_ON(is_stable_node_chain(dup));
340 if (is_stable_node_dup(dup))
341 __stable_node_dup_del(dup);
343 rb_erase(&dup->node, root_stable_tree + NUMA(dup->nid));
344 #ifdef CONFIG_DEBUG_VM
349 static inline struct rmap_item *alloc_rmap_item(void)
351 struct rmap_item *rmap_item;
353 rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL);
359 static inline void free_rmap_item(struct rmap_item *rmap_item)
362 rmap_item->mm = NULL; /* debug safety */
363 kmem_cache_free(rmap_item_cache, rmap_item);
366 static inline struct stable_node *alloc_stable_node(void)
368 return kmem_cache_alloc(stable_node_cache, GFP_KERNEL);
371 static inline void free_stable_node(struct stable_node *stable_node)
373 VM_BUG_ON(stable_node->rmap_hlist_len &&
374 !is_stable_node_chain(stable_node));
375 kmem_cache_free(stable_node_cache, stable_node);
378 static inline struct mm_slot *alloc_mm_slot(void)
380 if (!mm_slot_cache) /* initialization failed */
382 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
385 static inline void free_mm_slot(struct mm_slot *mm_slot)
387 kmem_cache_free(mm_slot_cache, mm_slot);
390 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
392 struct mm_slot *slot;
394 hash_for_each_possible(mm_slots_hash, slot, link, (unsigned long)mm)
401 static void insert_to_mm_slots_hash(struct mm_struct *mm,
402 struct mm_slot *mm_slot)
405 hash_add(mm_slots_hash, &mm_slot->link, (unsigned long)mm);
409 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
410 * page tables after it has passed through ksm_exit() - which, if necessary,
411 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
412 * a special flag: they can just back out as soon as mm_users goes to zero.
413 * ksm_test_exit() is used throughout to make this test for exit: in some
414 * places for correctness, in some places just to avoid unnecessary work.
416 static inline bool ksm_test_exit(struct mm_struct *mm)
418 return atomic_read(&mm->mm_users) == 0;
422 * We use break_ksm to break COW on a ksm page: it's a stripped down
424 * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
427 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
428 * in case the application has unmapped and remapped mm,addr meanwhile.
429 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
430 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
432 static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
439 page = follow_page(vma, addr, FOLL_GET | FOLL_MIGRATION);
440 if (IS_ERR_OR_NULL(page))
443 ret = handle_mm_fault(vma->vm_mm, vma, addr,
446 ret = VM_FAULT_WRITE;
448 } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
450 * We must loop because handle_mm_fault() may back out if there's
451 * any difficulty e.g. if pte accessed bit gets updated concurrently.
453 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
454 * COW has been broken, even if the vma does not permit VM_WRITE;
455 * but note that a concurrent fault might break PageKsm for us.
457 * VM_FAULT_SIGBUS could occur if we race with truncation of the
458 * backing file, which also invalidates anonymous pages: that's
459 * okay, that truncation will have unmapped the PageKsm for us.
461 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
462 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
463 * current task has TIF_MEMDIE set, and will be OOM killed on return
464 * to user; and ksmd, having no mm, would never be chosen for that.
466 * But if the mm is in a limited mem_cgroup, then the fault may fail
467 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
468 * even ksmd can fail in this way - though it's usually breaking ksm
469 * just to undo a merge it made a moment before, so unlikely to oom.
471 * That's a pity: we might therefore have more kernel pages allocated
472 * than we're counting as nodes in the stable tree; but ksm_do_scan
473 * will retry to break_cow on each pass, so should recover the page
474 * in due course. The important thing is to not let VM_MERGEABLE
475 * be cleared while any such pages might remain in the area.
477 return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
480 static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
483 struct vm_area_struct *vma;
484 if (ksm_test_exit(mm))
486 vma = find_vma(mm, addr);
487 if (!vma || vma->vm_start > addr)
489 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
494 static void break_cow(struct rmap_item *rmap_item)
496 struct mm_struct *mm = rmap_item->mm;
497 unsigned long addr = rmap_item->address;
498 struct vm_area_struct *vma;
501 * It is not an accident that whenever we want to break COW
502 * to undo, we also need to drop a reference to the anon_vma.
504 put_anon_vma(rmap_item->anon_vma);
506 down_read(&mm->mmap_sem);
507 vma = find_mergeable_vma(mm, addr);
509 break_ksm(vma, addr);
510 up_read(&mm->mmap_sem);
513 static struct page *get_mergeable_page(struct rmap_item *rmap_item)
515 struct mm_struct *mm = rmap_item->mm;
516 unsigned long addr = rmap_item->address;
517 struct vm_area_struct *vma;
520 down_read(&mm->mmap_sem);
521 vma = find_mergeable_vma(mm, addr);
525 page = follow_page(vma, addr, FOLL_GET);
526 if (IS_ERR_OR_NULL(page))
528 if (PageAnon(page)) {
529 flush_anon_page(vma, page, addr);
530 flush_dcache_page(page);
536 up_read(&mm->mmap_sem);
541 * This helper is used for getting right index into array of tree roots.
542 * When merge_across_nodes knob is set to 1, there are only two rb-trees for
543 * stable and unstable pages from all nodes with roots in index 0. Otherwise,
544 * every node has its own stable and unstable tree.
546 static inline int get_kpfn_nid(unsigned long kpfn)
548 return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
551 static struct stable_node *alloc_stable_node_chain(struct stable_node *dup,
552 struct rb_root *root)
554 struct stable_node *chain = alloc_stable_node();
555 VM_BUG_ON(is_stable_node_chain(dup));
557 INIT_HLIST_HEAD(&chain->hlist);
558 chain->chain_prune_time = jiffies;
559 chain->rmap_hlist_len = STABLE_NODE_CHAIN;
560 #if defined (CONFIG_DEBUG_VM) && defined(CONFIG_NUMA)
561 chain->nid = -1; /* debug */
563 ksm_stable_node_chains++;
566 * Put the stable node chain in the first dimension of
567 * the stable tree and at the same time remove the old
570 rb_replace_node(&dup->node, &chain->node, root);
573 * Move the old stable node to the second dimension
574 * queued in the hlist_dup. The invariant is that all
575 * dup stable_nodes in the chain->hlist point to pages
576 * that are wrprotected and have the exact same
579 stable_node_chain_add_dup(dup, chain);
584 static inline void free_stable_node_chain(struct stable_node *chain,
585 struct rb_root *root)
587 rb_erase(&chain->node, root);
588 free_stable_node(chain);
589 ksm_stable_node_chains--;
592 static void remove_node_from_stable_tree(struct stable_node *stable_node)
594 struct rmap_item *rmap_item;
596 /* check it's not STABLE_NODE_CHAIN or negative */
597 BUG_ON(stable_node->rmap_hlist_len < 0);
599 hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
600 if (rmap_item->hlist.next)
604 VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
605 stable_node->rmap_hlist_len--;
606 put_anon_vma(rmap_item->anon_vma);
607 rmap_item->address &= PAGE_MASK;
612 * We need the second aligned pointer of the migrate_nodes
613 * list_head to stay clear from the rb_parent_color union
614 * (aligned and different than any node) and also different
615 * from &migrate_nodes. This will verify that future list.h changes
616 * don't break STABLE_NODE_DUP_HEAD.
618 #if GCC_VERSION >= 40903 /* only recent gcc can handle it */
619 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD <= &migrate_nodes);
620 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD >= &migrate_nodes + 1);
623 if (stable_node->head == &migrate_nodes)
624 list_del(&stable_node->list);
626 stable_node_dup_del(stable_node);
627 free_stable_node(stable_node);
631 * get_ksm_page: checks if the page indicated by the stable node
632 * is still its ksm page, despite having held no reference to it.
633 * In which case we can trust the content of the page, and it
634 * returns the gotten page; but if the page has now been zapped,
635 * remove the stale node from the stable tree and return NULL.
636 * But beware, the stable node's page might be being migrated.
638 * You would expect the stable_node to hold a reference to the ksm page.
639 * But if it increments the page's count, swapping out has to wait for
640 * ksmd to come around again before it can free the page, which may take
641 * seconds or even minutes: much too unresponsive. So instead we use a
642 * "keyhole reference": access to the ksm page from the stable node peeps
643 * out through its keyhole to see if that page still holds the right key,
644 * pointing back to this stable node. This relies on freeing a PageAnon
645 * page to reset its page->mapping to NULL, and relies on no other use of
646 * a page to put something that might look like our key in page->mapping.
647 * is on its way to being freed; but it is an anomaly to bear in mind.
649 static struct page *get_ksm_page(struct stable_node *stable_node, bool lock_it)
652 void *expected_mapping;
655 expected_mapping = (void *)stable_node +
656 (PAGE_MAPPING_ANON | PAGE_MAPPING_KSM);
658 kpfn = READ_ONCE(stable_node->kpfn);
659 page = pfn_to_page(kpfn);
662 * page is computed from kpfn, so on most architectures reading
663 * page->mapping is naturally ordered after reading node->kpfn,
664 * but on Alpha we need to be more careful.
666 smp_read_barrier_depends();
667 if (READ_ONCE(page->mapping) != expected_mapping)
671 * We cannot do anything with the page while its refcount is 0.
672 * Usually 0 means free, or tail of a higher-order page: in which
673 * case this node is no longer referenced, and should be freed;
674 * however, it might mean that the page is under page_freeze_refs().
675 * The __remove_mapping() case is easy, again the node is now stale;
676 * but if page is swapcache in migrate_page_move_mapping(), it might
677 * still be our page, in which case it's essential to keep the node.
679 while (!get_page_unless_zero(page)) {
681 * Another check for page->mapping != expected_mapping would
682 * work here too. We have chosen the !PageSwapCache test to
683 * optimize the common case, when the page is or is about to
684 * be freed: PageSwapCache is cleared (under spin_lock_irq)
685 * in the freeze_refs section of __remove_mapping(); but Anon
686 * page->mapping reset to NULL later, in free_pages_prepare().
688 if (!PageSwapCache(page))
693 if (READ_ONCE(page->mapping) != expected_mapping) {
700 if (READ_ONCE(page->mapping) != expected_mapping) {
710 * We come here from above when page->mapping or !PageSwapCache
711 * suggests that the node is stale; but it might be under migration.
712 * We need smp_rmb(), matching the smp_wmb() in ksm_migrate_page(),
713 * before checking whether node->kpfn has been changed.
716 if (READ_ONCE(stable_node->kpfn) != kpfn)
718 remove_node_from_stable_tree(stable_node);
723 * Removing rmap_item from stable or unstable tree.
724 * This function will clean the information from the stable/unstable tree.
726 static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
728 if (rmap_item->address & STABLE_FLAG) {
729 struct stable_node *stable_node;
732 stable_node = rmap_item->head;
733 page = get_ksm_page(stable_node, true);
737 hlist_del(&rmap_item->hlist);
741 if (!hlist_empty(&stable_node->hlist))
745 VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
746 stable_node->rmap_hlist_len--;
748 put_anon_vma(rmap_item->anon_vma);
749 rmap_item->address &= PAGE_MASK;
751 } else if (rmap_item->address & UNSTABLE_FLAG) {
754 * Usually ksmd can and must skip the rb_erase, because
755 * root_unstable_tree was already reset to RB_ROOT.
756 * But be careful when an mm is exiting: do the rb_erase
757 * if this rmap_item was inserted by this scan, rather
758 * than left over from before.
760 age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
763 rb_erase(&rmap_item->node,
764 root_unstable_tree + NUMA(rmap_item->nid));
765 ksm_pages_unshared--;
766 rmap_item->address &= PAGE_MASK;
769 cond_resched(); /* we're called from many long loops */
772 static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
773 struct rmap_item **rmap_list)
776 struct rmap_item *rmap_item = *rmap_list;
777 *rmap_list = rmap_item->rmap_list;
778 remove_rmap_item_from_tree(rmap_item);
779 free_rmap_item(rmap_item);
784 * Though it's very tempting to unmerge rmap_items from stable tree rather
785 * than check every pte of a given vma, the locking doesn't quite work for
786 * that - an rmap_item is assigned to the stable tree after inserting ksm
787 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
788 * rmap_items from parent to child at fork time (so as not to waste time
789 * if exit comes before the next scan reaches it).
791 * Similarly, although we'd like to remove rmap_items (so updating counts
792 * and freeing memory) when unmerging an area, it's easier to leave that
793 * to the next pass of ksmd - consider, for example, how ksmd might be
794 * in cmp_and_merge_page on one of the rmap_items we would be removing.
796 static int unmerge_ksm_pages(struct vm_area_struct *vma,
797 unsigned long start, unsigned long end)
802 for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
803 if (ksm_test_exit(vma->vm_mm))
805 if (signal_pending(current))
808 err = break_ksm(vma, addr);
815 * Only called through the sysfs control interface:
817 static int remove_stable_node(struct stable_node *stable_node)
822 page = get_ksm_page(stable_node, true);
825 * get_ksm_page did remove_node_from_stable_tree itself.
830 if (WARN_ON_ONCE(page_mapped(page))) {
832 * This should not happen: but if it does, just refuse to let
833 * merge_across_nodes be switched - there is no need to panic.
838 * The stable node did not yet appear stale to get_ksm_page(),
839 * since that allows for an unmapped ksm page to be recognized
840 * right up until it is freed; but the node is safe to remove.
841 * This page might be in a pagevec waiting to be freed,
842 * or it might be PageSwapCache (perhaps under writeback),
843 * or it might have been removed from swapcache a moment ago.
845 set_page_stable_node(page, NULL);
846 remove_node_from_stable_tree(stable_node);
855 static int remove_stable_node_chain(struct stable_node *stable_node,
856 struct rb_root *root)
858 struct stable_node *dup;
859 struct hlist_node *hlist_safe;
861 if (!is_stable_node_chain(stable_node)) {
862 VM_BUG_ON(is_stable_node_dup(stable_node));
863 if (remove_stable_node(stable_node))
869 hlist_for_each_entry_safe(dup, hlist_safe,
870 &stable_node->hlist, hlist_dup) {
871 VM_BUG_ON(!is_stable_node_dup(dup));
872 if (remove_stable_node(dup))
875 BUG_ON(!hlist_empty(&stable_node->hlist));
876 free_stable_node_chain(stable_node, root);
880 static int remove_all_stable_nodes(void)
882 struct stable_node *stable_node, *next;
886 for (nid = 0; nid < ksm_nr_node_ids; nid++) {
887 while (root_stable_tree[nid].rb_node) {
888 stable_node = rb_entry(root_stable_tree[nid].rb_node,
889 struct stable_node, node);
890 if (remove_stable_node_chain(stable_node,
891 root_stable_tree + nid)) {
893 break; /* proceed to next nid */
898 list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
899 if (remove_stable_node(stable_node))
906 static int unmerge_and_remove_all_rmap_items(void)
908 struct mm_slot *mm_slot;
909 struct mm_struct *mm;
910 struct vm_area_struct *vma;
913 spin_lock(&ksm_mmlist_lock);
914 ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
915 struct mm_slot, mm_list);
916 spin_unlock(&ksm_mmlist_lock);
918 for (mm_slot = ksm_scan.mm_slot;
919 mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
921 down_read(&mm->mmap_sem);
922 for (vma = mm->mmap; vma; vma = vma->vm_next) {
923 if (ksm_test_exit(mm))
925 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
927 err = unmerge_ksm_pages(vma,
928 vma->vm_start, vma->vm_end);
933 remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
935 spin_lock(&ksm_mmlist_lock);
936 ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
937 struct mm_slot, mm_list);
938 if (ksm_test_exit(mm)) {
939 hash_del(&mm_slot->link);
940 list_del(&mm_slot->mm_list);
941 spin_unlock(&ksm_mmlist_lock);
943 free_mm_slot(mm_slot);
944 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
945 up_read(&mm->mmap_sem);
948 spin_unlock(&ksm_mmlist_lock);
949 up_read(&mm->mmap_sem);
953 /* Clean up stable nodes, but don't worry if some are still busy */
954 remove_all_stable_nodes();
959 up_read(&mm->mmap_sem);
960 spin_lock(&ksm_mmlist_lock);
961 ksm_scan.mm_slot = &ksm_mm_head;
962 spin_unlock(&ksm_mmlist_lock);
965 #endif /* CONFIG_SYSFS */
967 static u32 calc_checksum(struct page *page)
970 void *addr = kmap_atomic(page);
971 checksum = jhash2(addr, PAGE_SIZE / 4, 17);
976 static int memcmp_pages(struct page *page1, struct page *page2)
981 addr1 = kmap_atomic(page1);
982 addr2 = kmap_atomic(page2);
983 ret = memcmp(addr1, addr2, PAGE_SIZE);
984 kunmap_atomic(addr2);
985 kunmap_atomic(addr1);
989 static inline int pages_identical(struct page *page1, struct page *page2)
991 return !memcmp_pages(page1, page2);
994 static int write_protect_page(struct vm_area_struct *vma, struct page *page,
997 struct mm_struct *mm = vma->vm_mm;
1003 unsigned long mmun_start; /* For mmu_notifiers */
1004 unsigned long mmun_end; /* For mmu_notifiers */
1006 addr = page_address_in_vma(page, vma);
1007 if (addr == -EFAULT)
1010 BUG_ON(PageTransCompound(page));
1013 mmun_end = addr + PAGE_SIZE;
1014 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1016 ptep = page_check_address(page, mm, addr, &ptl, 0);
1020 if (pte_write(*ptep) || pte_dirty(*ptep)) {
1023 swapped = PageSwapCache(page);
1024 flush_cache_page(vma, addr, page_to_pfn(page));
1026 * Ok this is tricky, when get_user_pages_fast() run it doesn't
1027 * take any lock, therefore the check that we are going to make
1028 * with the pagecount against the mapcount is racey and
1029 * O_DIRECT can happen right after the check.
1030 * So we clear the pte and flush the tlb before the check
1031 * this assure us that no O_DIRECT can happen after the check
1032 * or in the middle of the check.
1034 entry = ptep_clear_flush_notify(vma, addr, ptep);
1036 * Check that no O_DIRECT or similar I/O is in progress on the
1039 if (page_mapcount(page) + 1 + swapped != page_count(page)) {
1040 set_pte_at(mm, addr, ptep, entry);
1043 if (pte_dirty(entry))
1044 set_page_dirty(page);
1045 entry = pte_mkclean(pte_wrprotect(entry));
1046 set_pte_at_notify(mm, addr, ptep, entry);
1052 pte_unmap_unlock(ptep, ptl);
1054 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1060 * replace_page - replace page in vma by new ksm page
1061 * @vma: vma that holds the pte pointing to page
1062 * @page: the page we are replacing by kpage
1063 * @kpage: the ksm page we replace page by
1064 * @orig_pte: the original value of the pte
1066 * Returns 0 on success, -EFAULT on failure.
1068 static int replace_page(struct vm_area_struct *vma, struct page *page,
1069 struct page *kpage, pte_t orig_pte)
1071 struct mm_struct *mm = vma->vm_mm;
1077 unsigned long mmun_start; /* For mmu_notifiers */
1078 unsigned long mmun_end; /* For mmu_notifiers */
1080 addr = page_address_in_vma(page, vma);
1081 if (addr == -EFAULT)
1084 pmd = mm_find_pmd(mm, addr);
1089 mmun_end = addr + PAGE_SIZE;
1090 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1092 ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
1093 if (!pte_same(*ptep, orig_pte)) {
1094 pte_unmap_unlock(ptep, ptl);
1099 page_add_anon_rmap(kpage, vma, addr, false);
1101 flush_cache_page(vma, addr, pte_pfn(*ptep));
1102 ptep_clear_flush_notify(vma, addr, ptep);
1103 set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
1105 page_remove_rmap(page, false);
1106 if (!page_mapped(page))
1107 try_to_free_swap(page);
1110 pte_unmap_unlock(ptep, ptl);
1113 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
1119 * try_to_merge_one_page - take two pages and merge them into one
1120 * @vma: the vma that holds the pte pointing to page
1121 * @page: the PageAnon page that we want to replace with kpage
1122 * @kpage: the PageKsm page that we want to map instead of page,
1123 * or NULL the first time when we want to use page as kpage.
1125 * This function returns 0 if the pages were merged, -EFAULT otherwise.
1127 static int try_to_merge_one_page(struct vm_area_struct *vma,
1128 struct page *page, struct page *kpage)
1130 pte_t orig_pte = __pte(0);
1133 if (page == kpage) /* ksm page forked */
1136 if (!PageAnon(page))
1140 * We need the page lock to read a stable PageSwapCache in
1141 * write_protect_page(). We use trylock_page() instead of
1142 * lock_page() because we don't want to wait here - we
1143 * prefer to continue scanning and merging different pages,
1144 * then come back to this page when it is unlocked.
1146 if (!trylock_page(page))
1149 if (PageTransCompound(page)) {
1150 err = split_huge_page(page);
1156 * If this anonymous page is mapped only here, its pte may need
1157 * to be write-protected. If it's mapped elsewhere, all of its
1158 * ptes are necessarily already write-protected. But in either
1159 * case, we need to lock and check page_count is not raised.
1161 if (write_protect_page(vma, page, &orig_pte) == 0) {
1164 * While we hold page lock, upgrade page from
1165 * PageAnon+anon_vma to PageKsm+NULL stable_node:
1166 * stable_tree_insert() will update stable_node.
1168 set_page_stable_node(page, NULL);
1169 mark_page_accessed(page);
1171 * Page reclaim just frees a clean page with no dirty
1172 * ptes: make sure that the ksm page would be swapped.
1174 if (!PageDirty(page))
1177 } else if (pages_identical(page, kpage))
1178 err = replace_page(vma, page, kpage, orig_pte);
1181 if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
1182 munlock_vma_page(page);
1183 if (!PageMlocked(kpage)) {
1186 mlock_vma_page(kpage);
1187 page = kpage; /* for final unlock */
1198 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
1199 * but no new kernel page is allocated: kpage must already be a ksm page.
1201 * This function returns 0 if the pages were merged, -EFAULT otherwise.
1203 static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
1204 struct page *page, struct page *kpage)
1206 struct mm_struct *mm = rmap_item->mm;
1207 struct vm_area_struct *vma;
1210 down_read(&mm->mmap_sem);
1211 vma = find_mergeable_vma(mm, rmap_item->address);
1215 err = try_to_merge_one_page(vma, page, kpage);
1219 /* Unstable nid is in union with stable anon_vma: remove first */
1220 remove_rmap_item_from_tree(rmap_item);
1222 /* Must get reference to anon_vma while still holding mmap_sem */
1223 rmap_item->anon_vma = vma->anon_vma;
1224 get_anon_vma(vma->anon_vma);
1226 up_read(&mm->mmap_sem);
1231 * try_to_merge_two_pages - take two identical pages and prepare them
1232 * to be merged into one page.
1234 * This function returns the kpage if we successfully merged two identical
1235 * pages into one ksm page, NULL otherwise.
1237 * Note that this function upgrades page to ksm page: if one of the pages
1238 * is already a ksm page, try_to_merge_with_ksm_page should be used.
1240 static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
1242 struct rmap_item *tree_rmap_item,
1243 struct page *tree_page)
1247 err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
1249 err = try_to_merge_with_ksm_page(tree_rmap_item,
1252 * If that fails, we have a ksm page with only one pte
1253 * pointing to it: so break it.
1256 break_cow(rmap_item);
1258 return err ? NULL : page;
1261 static __always_inline
1262 bool __is_page_sharing_candidate(struct stable_node *stable_node, int offset)
1264 VM_BUG_ON(stable_node->rmap_hlist_len < 0);
1266 * Check that at least one mapping still exists, otherwise
1267 * there's no much point to merge and share with this
1268 * stable_node, as the underlying tree_page of the other
1269 * sharer is going to be freed soon.
1271 return stable_node->rmap_hlist_len &&
1272 stable_node->rmap_hlist_len + offset < ksm_max_page_sharing;
1275 static __always_inline
1276 bool is_page_sharing_candidate(struct stable_node *stable_node)
1278 return __is_page_sharing_candidate(stable_node, 0);
1281 static struct stable_node *stable_node_dup(struct stable_node *stable_node,
1282 struct page **tree_page,
1283 struct rb_root *root,
1284 bool prune_stale_stable_nodes)
1286 struct stable_node *dup, *found = NULL;
1287 struct hlist_node *hlist_safe;
1288 struct page *_tree_page;
1290 int found_rmap_hlist_len;
1292 if (!prune_stale_stable_nodes ||
1293 time_before(jiffies, stable_node->chain_prune_time +
1295 ksm_stable_node_chains_prune_millisecs)))
1296 prune_stale_stable_nodes = false;
1298 stable_node->chain_prune_time = jiffies;
1300 hlist_for_each_entry_safe(dup, hlist_safe,
1301 &stable_node->hlist, hlist_dup) {
1304 * We must walk all stable_node_dup to prune the stale
1305 * stable nodes during lookup.
1307 * get_ksm_page can drop the nodes from the
1308 * stable_node->hlist if they point to freed pages
1309 * (that's why we do a _safe walk). The "dup"
1310 * stable_node parameter itself will be freed from
1311 * under us if it returns NULL.
1313 _tree_page = get_ksm_page(dup, false);
1317 if (is_page_sharing_candidate(dup)) {
1319 dup->rmap_hlist_len > found_rmap_hlist_len) {
1321 put_page(*tree_page);
1323 found_rmap_hlist_len = found->rmap_hlist_len;
1324 *tree_page = _tree_page;
1326 if (!prune_stale_stable_nodes)
1332 put_page(_tree_page);
1336 * nr is relevant only if prune_stale_stable_nodes is true,
1337 * otherwise we may break the loop at nr == 1 even if there
1338 * are multiple entries.
1340 if (prune_stale_stable_nodes && found) {
1343 * If there's not just one entry it would
1344 * corrupt memory, better BUG_ON. In KSM
1345 * context with no lock held it's not even
1348 BUG_ON(stable_node->hlist.first->next);
1351 * There's just one entry and it is below the
1352 * deduplication limit so drop the chain.
1354 rb_replace_node(&stable_node->node, &found->node,
1356 free_stable_node(stable_node);
1357 ksm_stable_node_chains--;
1358 ksm_stable_node_dups--;
1359 } else if (__is_page_sharing_candidate(found, 1)) {
1361 * Refile our candidate at the head
1362 * after the prune if our candidate
1363 * can accept one more future sharing
1364 * in addition to the one underway.
1366 hlist_del(&found->hlist_dup);
1367 hlist_add_head(&found->hlist_dup,
1368 &stable_node->hlist);
1375 static struct stable_node *stable_node_dup_any(struct stable_node *stable_node,
1376 struct rb_root *root)
1378 if (!is_stable_node_chain(stable_node))
1380 if (hlist_empty(&stable_node->hlist)) {
1381 free_stable_node_chain(stable_node, root);
1384 return hlist_entry(stable_node->hlist.first,
1385 typeof(*stable_node), hlist_dup);
1388 static struct stable_node *__stable_node_chain(struct stable_node *stable_node,
1389 struct page **tree_page,
1390 struct rb_root *root,
1391 bool prune_stale_stable_nodes)
1393 if (!is_stable_node_chain(stable_node)) {
1394 if (is_page_sharing_candidate(stable_node)) {
1395 *tree_page = get_ksm_page(stable_node, false);
1400 return stable_node_dup(stable_node, tree_page, root,
1401 prune_stale_stable_nodes);
1404 static __always_inline struct stable_node *chain_prune(struct stable_node *s_n,
1406 struct rb_root *root)
1408 return __stable_node_chain(s_n, t_p, root, true);
1411 static __always_inline struct stable_node *chain(struct stable_node *s_n,
1413 struct rb_root *root)
1415 return __stable_node_chain(s_n, t_p, root, false);
1419 * stable_tree_search - search for page inside the stable tree
1421 * This function checks if there is a page inside the stable tree
1422 * with identical content to the page that we are scanning right now.
1424 * This function returns the stable tree node of identical content if found,
1427 static struct page *stable_tree_search(struct page *page)
1430 struct rb_root *root;
1431 struct rb_node **new;
1432 struct rb_node *parent;
1433 struct stable_node *stable_node, *stable_node_dup, *stable_node_any;
1434 struct stable_node *page_node;
1436 page_node = page_stable_node(page);
1437 if (page_node && page_node->head != &migrate_nodes) {
1438 /* ksm page forked */
1443 nid = get_kpfn_nid(page_to_pfn(page));
1444 root = root_stable_tree + nid;
1446 new = &root->rb_node;
1450 struct page *tree_page;
1454 stable_node = rb_entry(*new, struct stable_node, node);
1455 stable_node_any = NULL;
1456 stable_node_dup = chain_prune(stable_node, &tree_page, root);
1457 if (!stable_node_dup) {
1459 * Either all stable_node dups were full in
1460 * this stable_node chain, or this chain was
1461 * empty and should be rb_erased.
1463 stable_node_any = stable_node_dup_any(stable_node,
1465 if (!stable_node_any) {
1466 /* rb_erase just run */
1470 * Take any of the stable_node dups page of
1471 * this stable_node chain to let the tree walk
1472 * continue. All KSM pages belonging to the
1473 * stable_node dups in a stable_node chain
1474 * have the same content and they're
1475 * wrprotected at all times. Any will work
1476 * fine to continue the walk.
1478 tree_page = get_ksm_page(stable_node_any, false);
1480 VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
1483 * If we walked over a stale stable_node,
1484 * get_ksm_page() will call rb_erase() and it
1485 * may rebalance the tree from under us. So
1486 * restart the search from scratch. Returning
1487 * NULL would be safe too, but we'd generate
1488 * false negative insertions just because some
1489 * stable_node was stale.
1494 ret = memcmp_pages(page, tree_page);
1495 put_page(tree_page);
1499 new = &parent->rb_left;
1501 new = &parent->rb_right;
1504 VM_BUG_ON(page_node->head != &migrate_nodes);
1506 * Test if the migrated page should be merged
1507 * into a stable node dup. If the mapcount is
1508 * 1 we can migrate it with another KSM page
1509 * without adding it to the chain.
1511 if (page_mapcount(page) > 1)
1515 if (!stable_node_dup) {
1517 * If the stable_node is a chain and
1518 * we got a payload match in memcmp
1519 * but we cannot merge the scanned
1520 * page in any of the existing
1521 * stable_node dups because they're
1522 * all full, we need to wait the
1523 * scanned page to find itself a match
1524 * in the unstable tree to create a
1525 * brand new KSM page to add later to
1526 * the dups of this stable_node.
1532 * Lock and unlock the stable_node's page (which
1533 * might already have been migrated) so that page
1534 * migration is sure to notice its raised count.
1535 * It would be more elegant to return stable_node
1536 * than kpage, but that involves more changes.
1538 tree_page = get_ksm_page(stable_node_dup, true);
1539 if (unlikely(!tree_page))
1541 * The tree may have been rebalanced,
1542 * so re-evaluate parent and new.
1545 unlock_page(tree_page);
1547 if (get_kpfn_nid(stable_node_dup->kpfn) !=
1548 NUMA(stable_node_dup->nid)) {
1549 put_page(tree_page);
1559 list_del(&page_node->list);
1560 DO_NUMA(page_node->nid = nid);
1561 rb_link_node(&page_node->node, parent, new);
1562 rb_insert_color(&page_node->node, root);
1564 if (is_page_sharing_candidate(page_node)) {
1571 if (stable_node_dup == stable_node) {
1572 /* there is no chain */
1574 VM_BUG_ON(page_node->head != &migrate_nodes);
1575 list_del(&page_node->list);
1576 DO_NUMA(page_node->nid = nid);
1577 rb_replace_node(&stable_node->node, &page_node->node,
1579 if (is_page_sharing_candidate(page_node))
1584 rb_erase(&stable_node->node, root);
1588 VM_BUG_ON(!is_stable_node_chain(stable_node));
1589 __stable_node_dup_del(stable_node_dup);
1591 VM_BUG_ON(page_node->head != &migrate_nodes);
1592 list_del(&page_node->list);
1593 DO_NUMA(page_node->nid = nid);
1594 stable_node_chain_add_dup(page_node, stable_node);
1595 if (is_page_sharing_candidate(page_node))
1603 stable_node_dup->head = &migrate_nodes;
1604 list_add(&stable_node_dup->list, stable_node_dup->head);
1608 /* stable_node_dup could be null if it reached the limit */
1609 if (!stable_node_dup)
1610 stable_node_dup = stable_node_any;
1611 if (stable_node_dup == stable_node) {
1612 /* chain is missing so create it */
1613 stable_node = alloc_stable_node_chain(stable_node_dup,
1619 * Add this stable_node dup that was
1620 * migrated to the stable_node chain
1621 * of the current nid for this page
1624 VM_BUG_ON(page_node->head != &migrate_nodes);
1625 list_del(&page_node->list);
1626 DO_NUMA(page_node->nid = nid);
1627 stable_node_chain_add_dup(page_node, stable_node);
1632 * stable_tree_insert - insert stable tree node pointing to new ksm page
1633 * into the stable tree.
1635 * This function returns the stable tree node just allocated on success,
1638 static struct stable_node *stable_tree_insert(struct page *kpage)
1642 struct rb_root *root;
1643 struct rb_node **new;
1644 struct rb_node *parent;
1645 struct stable_node *stable_node, *stable_node_dup, *stable_node_any;
1646 bool need_chain = false;
1648 kpfn = page_to_pfn(kpage);
1649 nid = get_kpfn_nid(kpfn);
1650 root = root_stable_tree + nid;
1653 new = &root->rb_node;
1656 struct page *tree_page;
1660 stable_node = rb_entry(*new, struct stable_node, node);
1661 stable_node_any = NULL;
1662 stable_node_dup = chain(stable_node, &tree_page, root);
1663 if (!stable_node_dup) {
1665 * Either all stable_node dups were full in
1666 * this stable_node chain, or this chain was
1667 * empty and should be rb_erased.
1669 stable_node_any = stable_node_dup_any(stable_node,
1671 if (!stable_node_any) {
1672 /* rb_erase just run */
1676 * Take any of the stable_node dups page of
1677 * this stable_node chain to let the tree walk
1678 * continue. All KSM pages belonging to the
1679 * stable_node dups in a stable_node chain
1680 * have the same content and they're
1681 * wrprotected at all times. Any will work
1682 * fine to continue the walk.
1684 tree_page = get_ksm_page(stable_node_any, false);
1686 VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
1689 * If we walked over a stale stable_node,
1690 * get_ksm_page() will call rb_erase() and it
1691 * may rebalance the tree from under us. So
1692 * restart the search from scratch. Returning
1693 * NULL would be safe too, but we'd generate
1694 * false negative insertions just because some
1695 * stable_node was stale.
1700 ret = memcmp_pages(kpage, tree_page);
1701 put_page(tree_page);
1705 new = &parent->rb_left;
1707 new = &parent->rb_right;
1714 stable_node_dup = alloc_stable_node();
1715 if (!stable_node_dup)
1718 INIT_HLIST_HEAD(&stable_node_dup->hlist);
1719 stable_node_dup->kpfn = kpfn;
1720 set_page_stable_node(kpage, stable_node_dup);
1721 stable_node_dup->rmap_hlist_len = 0;
1722 DO_NUMA(stable_node_dup->nid = nid);
1724 rb_link_node(&stable_node_dup->node, parent, new);
1725 rb_insert_color(&stable_node_dup->node, root);
1727 if (!is_stable_node_chain(stable_node)) {
1728 struct stable_node *orig = stable_node;
1729 /* chain is missing so create it */
1730 stable_node = alloc_stable_node_chain(orig, root);
1732 free_stable_node(stable_node_dup);
1736 stable_node_chain_add_dup(stable_node_dup, stable_node);
1739 return stable_node_dup;
1743 * unstable_tree_search_insert - search for identical page,
1744 * else insert rmap_item into the unstable tree.
1746 * This function searches for a page in the unstable tree identical to the
1747 * page currently being scanned; and if no identical page is found in the
1748 * tree, we insert rmap_item as a new object into the unstable tree.
1750 * This function returns pointer to rmap_item found to be identical
1751 * to the currently scanned page, NULL otherwise.
1753 * This function does both searching and inserting, because they share
1754 * the same walking algorithm in an rbtree.
1757 struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
1759 struct page **tree_pagep)
1761 struct rb_node **new;
1762 struct rb_root *root;
1763 struct rb_node *parent = NULL;
1766 nid = get_kpfn_nid(page_to_pfn(page));
1767 root = root_unstable_tree + nid;
1768 new = &root->rb_node;
1771 struct rmap_item *tree_rmap_item;
1772 struct page *tree_page;
1776 tree_rmap_item = rb_entry(*new, struct rmap_item, node);
1777 tree_page = get_mergeable_page(tree_rmap_item);
1782 * Don't substitute a ksm page for a forked page.
1784 if (page == tree_page) {
1785 put_page(tree_page);
1789 ret = memcmp_pages(page, tree_page);
1793 put_page(tree_page);
1794 new = &parent->rb_left;
1795 } else if (ret > 0) {
1796 put_page(tree_page);
1797 new = &parent->rb_right;
1798 } else if (!ksm_merge_across_nodes &&
1799 page_to_nid(tree_page) != nid) {
1801 * If tree_page has been migrated to another NUMA node,
1802 * it will be flushed out and put in the right unstable
1803 * tree next time: only merge with it when across_nodes.
1805 put_page(tree_page);
1808 *tree_pagep = tree_page;
1809 return tree_rmap_item;
1813 rmap_item->address |= UNSTABLE_FLAG;
1814 rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
1815 DO_NUMA(rmap_item->nid = nid);
1816 rb_link_node(&rmap_item->node, parent, new);
1817 rb_insert_color(&rmap_item->node, root);
1819 ksm_pages_unshared++;
1824 * stable_tree_append - add another rmap_item to the linked list of
1825 * rmap_items hanging off a given node of the stable tree, all sharing
1826 * the same ksm page.
1828 static void stable_tree_append(struct rmap_item *rmap_item,
1829 struct stable_node *stable_node,
1830 bool max_page_sharing_bypass)
1833 * rmap won't find this mapping if we don't insert the
1834 * rmap_item in the right stable_node
1835 * duplicate. page_migration could break later if rmap breaks,
1836 * so we can as well crash here. We really need to check for
1837 * rmap_hlist_len == STABLE_NODE_CHAIN, but we can as well check
1838 * for other negative values as an undeflow if detected here
1839 * for the first time (and not when decreasing rmap_hlist_len)
1840 * would be sign of memory corruption in the stable_node.
1842 BUG_ON(stable_node->rmap_hlist_len < 0);
1844 stable_node->rmap_hlist_len++;
1845 if (!max_page_sharing_bypass)
1846 /* possibly non fatal but unexpected overflow, only warn */
1847 WARN_ON_ONCE(stable_node->rmap_hlist_len >
1848 ksm_max_page_sharing);
1850 rmap_item->head = stable_node;
1851 rmap_item->address |= STABLE_FLAG;
1852 hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
1854 if (rmap_item->hlist.next)
1855 ksm_pages_sharing++;
1861 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1862 * if not, compare checksum to previous and if it's the same, see if page can
1863 * be inserted into the unstable tree, or merged with a page already there and
1864 * both transferred to the stable tree.
1866 * @page: the page that we are searching identical page to.
1867 * @rmap_item: the reverse mapping into the virtual address of this page
1869 static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
1871 struct rmap_item *tree_rmap_item;
1872 struct page *tree_page = NULL;
1873 struct stable_node *stable_node;
1875 unsigned int checksum;
1877 bool max_page_sharing_bypass = false;
1879 stable_node = page_stable_node(page);
1881 if (stable_node->head != &migrate_nodes &&
1882 get_kpfn_nid(READ_ONCE(stable_node->kpfn)) !=
1883 NUMA(stable_node->nid)) {
1884 stable_node_dup_del(stable_node);
1885 stable_node->head = &migrate_nodes;
1886 list_add(&stable_node->list, stable_node->head);
1888 if (stable_node->head != &migrate_nodes &&
1889 rmap_item->head == stable_node)
1892 * If it's a KSM fork, allow it to go over the sharing limit
1895 if (!is_page_sharing_candidate(stable_node))
1896 max_page_sharing_bypass = true;
1899 /* We first start with searching the page inside the stable tree */
1900 kpage = stable_tree_search(page);
1901 if (kpage == page && rmap_item->head == stable_node) {
1906 remove_rmap_item_from_tree(rmap_item);
1909 err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
1912 * The page was successfully merged:
1913 * add its rmap_item to the stable tree.
1916 stable_tree_append(rmap_item, page_stable_node(kpage),
1917 max_page_sharing_bypass);
1925 * If the hash value of the page has changed from the last time
1926 * we calculated it, this page is changing frequently: therefore we
1927 * don't want to insert it in the unstable tree, and we don't want
1928 * to waste our time searching for something identical to it there.
1930 checksum = calc_checksum(page);
1931 if (rmap_item->oldchecksum != checksum) {
1932 rmap_item->oldchecksum = checksum;
1937 unstable_tree_search_insert(rmap_item, page, &tree_page);
1938 if (tree_rmap_item) {
1939 kpage = try_to_merge_two_pages(rmap_item, page,
1940 tree_rmap_item, tree_page);
1941 put_page(tree_page);
1944 * The pages were successfully merged: insert new
1945 * node in the stable tree and add both rmap_items.
1948 stable_node = stable_tree_insert(kpage);
1950 stable_tree_append(tree_rmap_item, stable_node,
1952 stable_tree_append(rmap_item, stable_node,
1958 * If we fail to insert the page into the stable tree,
1959 * we will have 2 virtual addresses that are pointing
1960 * to a ksm page left outside the stable tree,
1961 * in which case we need to break_cow on both.
1964 break_cow(tree_rmap_item);
1965 break_cow(rmap_item);
1971 static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
1972 struct rmap_item **rmap_list,
1975 struct rmap_item *rmap_item;
1977 while (*rmap_list) {
1978 rmap_item = *rmap_list;
1979 if ((rmap_item->address & PAGE_MASK) == addr)
1981 if (rmap_item->address > addr)
1983 *rmap_list = rmap_item->rmap_list;
1984 remove_rmap_item_from_tree(rmap_item);
1985 free_rmap_item(rmap_item);
1988 rmap_item = alloc_rmap_item();
1990 /* It has already been zeroed */
1991 rmap_item->mm = mm_slot->mm;
1992 rmap_item->address = addr;
1993 rmap_item->rmap_list = *rmap_list;
1994 *rmap_list = rmap_item;
1999 static struct rmap_item *scan_get_next_rmap_item(struct page **page)
2001 struct mm_struct *mm;
2002 struct mm_slot *slot;
2003 struct vm_area_struct *vma;
2004 struct rmap_item *rmap_item;
2007 if (list_empty(&ksm_mm_head.mm_list))
2010 slot = ksm_scan.mm_slot;
2011 if (slot == &ksm_mm_head) {
2013 * A number of pages can hang around indefinitely on per-cpu
2014 * pagevecs, raised page count preventing write_protect_page
2015 * from merging them. Though it doesn't really matter much,
2016 * it is puzzling to see some stuck in pages_volatile until
2017 * other activity jostles them out, and they also prevented
2018 * LTP's KSM test from succeeding deterministically; so drain
2019 * them here (here rather than on entry to ksm_do_scan(),
2020 * so we don't IPI too often when pages_to_scan is set low).
2022 lru_add_drain_all();
2025 * Whereas stale stable_nodes on the stable_tree itself
2026 * get pruned in the regular course of stable_tree_search(),
2027 * those moved out to the migrate_nodes list can accumulate:
2028 * so prune them once before each full scan.
2030 if (!ksm_merge_across_nodes) {
2031 struct stable_node *stable_node, *next;
2034 list_for_each_entry_safe(stable_node, next,
2035 &migrate_nodes, list) {
2036 page = get_ksm_page(stable_node, false);
2043 for (nid = 0; nid < ksm_nr_node_ids; nid++)
2044 root_unstable_tree[nid] = RB_ROOT;
2046 spin_lock(&ksm_mmlist_lock);
2047 slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
2048 ksm_scan.mm_slot = slot;
2049 spin_unlock(&ksm_mmlist_lock);
2051 * Although we tested list_empty() above, a racing __ksm_exit
2052 * of the last mm on the list may have removed it since then.
2054 if (slot == &ksm_mm_head)
2057 ksm_scan.address = 0;
2058 ksm_scan.rmap_list = &slot->rmap_list;
2062 down_read(&mm->mmap_sem);
2063 if (ksm_test_exit(mm))
2066 vma = find_vma(mm, ksm_scan.address);
2068 for (; vma; vma = vma->vm_next) {
2069 if (!(vma->vm_flags & VM_MERGEABLE))
2071 if (ksm_scan.address < vma->vm_start)
2072 ksm_scan.address = vma->vm_start;
2074 ksm_scan.address = vma->vm_end;
2076 while (ksm_scan.address < vma->vm_end) {
2077 if (ksm_test_exit(mm))
2079 *page = follow_page(vma, ksm_scan.address, FOLL_GET);
2080 if (IS_ERR_OR_NULL(*page)) {
2081 ksm_scan.address += PAGE_SIZE;
2085 if (PageAnon(*page)) {
2086 flush_anon_page(vma, *page, ksm_scan.address);
2087 flush_dcache_page(*page);
2088 rmap_item = get_next_rmap_item(slot,
2089 ksm_scan.rmap_list, ksm_scan.address);
2091 ksm_scan.rmap_list =
2092 &rmap_item->rmap_list;
2093 ksm_scan.address += PAGE_SIZE;
2096 up_read(&mm->mmap_sem);
2100 ksm_scan.address += PAGE_SIZE;
2105 if (ksm_test_exit(mm)) {
2106 ksm_scan.address = 0;
2107 ksm_scan.rmap_list = &slot->rmap_list;
2110 * Nuke all the rmap_items that are above this current rmap:
2111 * because there were no VM_MERGEABLE vmas with such addresses.
2113 remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
2115 spin_lock(&ksm_mmlist_lock);
2116 ksm_scan.mm_slot = list_entry(slot->mm_list.next,
2117 struct mm_slot, mm_list);
2118 if (ksm_scan.address == 0) {
2120 * We've completed a full scan of all vmas, holding mmap_sem
2121 * throughout, and found no VM_MERGEABLE: so do the same as
2122 * __ksm_exit does to remove this mm from all our lists now.
2123 * This applies either when cleaning up after __ksm_exit
2124 * (but beware: we can reach here even before __ksm_exit),
2125 * or when all VM_MERGEABLE areas have been unmapped (and
2126 * mmap_sem then protects against race with MADV_MERGEABLE).
2128 hash_del(&slot->link);
2129 list_del(&slot->mm_list);
2130 spin_unlock(&ksm_mmlist_lock);
2133 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
2134 up_read(&mm->mmap_sem);
2137 spin_unlock(&ksm_mmlist_lock);
2138 up_read(&mm->mmap_sem);
2141 /* Repeat until we've completed scanning the whole list */
2142 slot = ksm_scan.mm_slot;
2143 if (slot != &ksm_mm_head)
2151 * ksm_do_scan - the ksm scanner main worker function.
2152 * @scan_npages - number of pages we want to scan before we return.
2154 static void ksm_do_scan(unsigned int scan_npages)
2156 struct rmap_item *rmap_item;
2157 struct page *uninitialized_var(page);
2159 while (scan_npages-- && likely(!freezing(current))) {
2161 rmap_item = scan_get_next_rmap_item(&page);
2164 cmp_and_merge_page(page, rmap_item);
2169 static int ksmd_should_run(void)
2171 return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
2174 static int ksm_scan_thread(void *nothing)
2177 set_user_nice(current, 5);
2179 while (!kthread_should_stop()) {
2180 mutex_lock(&ksm_thread_mutex);
2181 wait_while_offlining();
2182 if (ksmd_should_run())
2183 ksm_do_scan(ksm_thread_pages_to_scan);
2184 mutex_unlock(&ksm_thread_mutex);
2188 if (ksmd_should_run()) {
2189 schedule_timeout_interruptible(
2190 msecs_to_jiffies(ksm_thread_sleep_millisecs));
2192 wait_event_freezable(ksm_thread_wait,
2193 ksmd_should_run() || kthread_should_stop());
2199 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
2200 unsigned long end, int advice, unsigned long *vm_flags)
2202 struct mm_struct *mm = vma->vm_mm;
2206 case MADV_MERGEABLE:
2208 * Be somewhat over-protective for now!
2210 if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
2211 VM_PFNMAP | VM_IO | VM_DONTEXPAND |
2212 VM_HUGETLB | VM_MIXEDMAP))
2213 return 0; /* just ignore the advice */
2216 if (*vm_flags & VM_SAO)
2220 if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
2221 err = __ksm_enter(mm);
2226 *vm_flags |= VM_MERGEABLE;
2229 case MADV_UNMERGEABLE:
2230 if (!(*vm_flags & VM_MERGEABLE))
2231 return 0; /* just ignore the advice */
2233 if (vma->anon_vma) {
2234 err = unmerge_ksm_pages(vma, start, end);
2239 *vm_flags &= ~VM_MERGEABLE;
2246 int __ksm_enter(struct mm_struct *mm)
2248 struct mm_slot *mm_slot;
2251 mm_slot = alloc_mm_slot();
2255 /* Check ksm_run too? Would need tighter locking */
2256 needs_wakeup = list_empty(&ksm_mm_head.mm_list);
2258 spin_lock(&ksm_mmlist_lock);
2259 insert_to_mm_slots_hash(mm, mm_slot);
2261 * When KSM_RUN_MERGE (or KSM_RUN_STOP),
2262 * insert just behind the scanning cursor, to let the area settle
2263 * down a little; when fork is followed by immediate exec, we don't
2264 * want ksmd to waste time setting up and tearing down an rmap_list.
2266 * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
2267 * scanning cursor, otherwise KSM pages in newly forked mms will be
2268 * missed: then we might as well insert at the end of the list.
2270 if (ksm_run & KSM_RUN_UNMERGE)
2271 list_add_tail(&mm_slot->mm_list, &ksm_mm_head.mm_list);
2273 list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
2274 spin_unlock(&ksm_mmlist_lock);
2276 set_bit(MMF_VM_MERGEABLE, &mm->flags);
2277 atomic_inc(&mm->mm_count);
2280 wake_up_interruptible(&ksm_thread_wait);
2285 void __ksm_exit(struct mm_struct *mm)
2287 struct mm_slot *mm_slot;
2288 int easy_to_free = 0;
2291 * This process is exiting: if it's straightforward (as is the
2292 * case when ksmd was never running), free mm_slot immediately.
2293 * But if it's at the cursor or has rmap_items linked to it, use
2294 * mmap_sem to synchronize with any break_cows before pagetables
2295 * are freed, and leave the mm_slot on the list for ksmd to free.
2296 * Beware: ksm may already have noticed it exiting and freed the slot.
2299 spin_lock(&ksm_mmlist_lock);
2300 mm_slot = get_mm_slot(mm);
2301 if (mm_slot && ksm_scan.mm_slot != mm_slot) {
2302 if (!mm_slot->rmap_list) {
2303 hash_del(&mm_slot->link);
2304 list_del(&mm_slot->mm_list);
2307 list_move(&mm_slot->mm_list,
2308 &ksm_scan.mm_slot->mm_list);
2311 spin_unlock(&ksm_mmlist_lock);
2314 free_mm_slot(mm_slot);
2315 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
2317 } else if (mm_slot) {
2318 down_write(&mm->mmap_sem);
2319 up_write(&mm->mmap_sem);
2323 struct page *ksm_might_need_to_copy(struct page *page,
2324 struct vm_area_struct *vma, unsigned long address)
2326 struct anon_vma *anon_vma = page_anon_vma(page);
2327 struct page *new_page;
2329 if (PageKsm(page)) {
2330 if (page_stable_node(page) &&
2331 !(ksm_run & KSM_RUN_UNMERGE))
2332 return page; /* no need to copy it */
2333 } else if (!anon_vma) {
2334 return page; /* no need to copy it */
2335 } else if (anon_vma->root == vma->anon_vma->root &&
2336 page->index == linear_page_index(vma, address)) {
2337 return page; /* still no need to copy it */
2339 if (!PageUptodate(page))
2340 return page; /* let do_swap_page report the error */
2342 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
2344 copy_user_highpage(new_page, page, address, vma);
2346 SetPageDirty(new_page);
2347 __SetPageUptodate(new_page);
2348 __SetPageLocked(new_page);
2354 int rmap_walk_ksm(struct page *page, struct rmap_walk_control *rwc)
2356 struct stable_node *stable_node;
2357 struct rmap_item *rmap_item;
2358 int ret = SWAP_AGAIN;
2359 int search_new_forks = 0;
2361 VM_BUG_ON_PAGE(!PageKsm(page), page);
2364 * Rely on the page lock to protect against concurrent modifications
2365 * to that page's node of the stable tree.
2367 VM_BUG_ON_PAGE(!PageLocked(page), page);
2369 stable_node = page_stable_node(page);
2373 hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
2374 struct anon_vma *anon_vma = rmap_item->anon_vma;
2375 struct anon_vma_chain *vmac;
2376 struct vm_area_struct *vma;
2379 anon_vma_lock_read(anon_vma);
2380 anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
2384 if (rmap_item->address < vma->vm_start ||
2385 rmap_item->address >= vma->vm_end)
2388 * Initially we examine only the vma which covers this
2389 * rmap_item; but later, if there is still work to do,
2390 * we examine covering vmas in other mms: in case they
2391 * were forked from the original since ksmd passed.
2393 if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
2396 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2399 ret = rwc->rmap_one(page, vma,
2400 rmap_item->address, rwc->arg);
2401 if (ret != SWAP_AGAIN) {
2402 anon_vma_unlock_read(anon_vma);
2405 if (rwc->done && rwc->done(page)) {
2406 anon_vma_unlock_read(anon_vma);
2410 anon_vma_unlock_read(anon_vma);
2412 if (!search_new_forks++)
2418 #ifdef CONFIG_MIGRATION
2419 void ksm_migrate_page(struct page *newpage, struct page *oldpage)
2421 struct stable_node *stable_node;
2423 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
2424 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
2425 VM_BUG_ON_PAGE(newpage->mapping != oldpage->mapping, newpage);
2427 stable_node = page_stable_node(newpage);
2429 VM_BUG_ON_PAGE(stable_node->kpfn != page_to_pfn(oldpage), oldpage);
2430 stable_node->kpfn = page_to_pfn(newpage);
2432 * newpage->mapping was set in advance; now we need smp_wmb()
2433 * to make sure that the new stable_node->kpfn is visible
2434 * to get_ksm_page() before it can see that oldpage->mapping
2435 * has gone stale (or that PageSwapCache has been cleared).
2438 set_page_stable_node(oldpage, NULL);
2441 #endif /* CONFIG_MIGRATION */
2443 #ifdef CONFIG_MEMORY_HOTREMOVE
2444 static void wait_while_offlining(void)
2446 while (ksm_run & KSM_RUN_OFFLINE) {
2447 mutex_unlock(&ksm_thread_mutex);
2448 wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
2449 TASK_UNINTERRUPTIBLE);
2450 mutex_lock(&ksm_thread_mutex);
2454 static bool stable_node_dup_remove_range(struct stable_node *stable_node,
2455 unsigned long start_pfn,
2456 unsigned long end_pfn)
2458 if (stable_node->kpfn >= start_pfn &&
2459 stable_node->kpfn < end_pfn) {
2461 * Don't get_ksm_page, page has already gone:
2462 * which is why we keep kpfn instead of page*
2464 remove_node_from_stable_tree(stable_node);
2470 static bool stable_node_chain_remove_range(struct stable_node *stable_node,
2471 unsigned long start_pfn,
2472 unsigned long end_pfn,
2473 struct rb_root *root)
2475 struct stable_node *dup;
2476 struct hlist_node *hlist_safe;
2478 if (!is_stable_node_chain(stable_node)) {
2479 VM_BUG_ON(is_stable_node_dup(stable_node));
2480 return stable_node_dup_remove_range(stable_node, start_pfn,
2484 hlist_for_each_entry_safe(dup, hlist_safe,
2485 &stable_node->hlist, hlist_dup) {
2486 VM_BUG_ON(!is_stable_node_dup(dup));
2487 stable_node_dup_remove_range(dup, start_pfn, end_pfn);
2489 if (hlist_empty(&stable_node->hlist)) {
2490 free_stable_node_chain(stable_node, root);
2491 return true; /* notify caller that tree was rebalanced */
2496 static void ksm_check_stable_tree(unsigned long start_pfn,
2497 unsigned long end_pfn)
2499 struct stable_node *stable_node, *next;
2500 struct rb_node *node;
2503 for (nid = 0; nid < ksm_nr_node_ids; nid++) {
2504 node = rb_first(root_stable_tree + nid);
2506 stable_node = rb_entry(node, struct stable_node, node);
2507 if (stable_node_chain_remove_range(stable_node,
2511 node = rb_first(root_stable_tree + nid);
2513 node = rb_next(node);
2517 list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
2518 if (stable_node->kpfn >= start_pfn &&
2519 stable_node->kpfn < end_pfn)
2520 remove_node_from_stable_tree(stable_node);
2525 static int ksm_memory_callback(struct notifier_block *self,
2526 unsigned long action, void *arg)
2528 struct memory_notify *mn = arg;
2531 case MEM_GOING_OFFLINE:
2533 * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
2534 * and remove_all_stable_nodes() while memory is going offline:
2535 * it is unsafe for them to touch the stable tree at this time.
2536 * But unmerge_ksm_pages(), rmap lookups and other entry points
2537 * which do not need the ksm_thread_mutex are all safe.
2539 mutex_lock(&ksm_thread_mutex);
2540 ksm_run |= KSM_RUN_OFFLINE;
2541 mutex_unlock(&ksm_thread_mutex);
2546 * Most of the work is done by page migration; but there might
2547 * be a few stable_nodes left over, still pointing to struct
2548 * pages which have been offlined: prune those from the tree,
2549 * otherwise get_ksm_page() might later try to access a
2550 * non-existent struct page.
2552 ksm_check_stable_tree(mn->start_pfn,
2553 mn->start_pfn + mn->nr_pages);
2556 case MEM_CANCEL_OFFLINE:
2557 mutex_lock(&ksm_thread_mutex);
2558 ksm_run &= ~KSM_RUN_OFFLINE;
2559 mutex_unlock(&ksm_thread_mutex);
2561 smp_mb(); /* wake_up_bit advises this */
2562 wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
2568 static void wait_while_offlining(void)
2571 #endif /* CONFIG_MEMORY_HOTREMOVE */
2575 * This all compiles without CONFIG_SYSFS, but is a waste of space.
2578 #define KSM_ATTR_RO(_name) \
2579 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2580 #define KSM_ATTR(_name) \
2581 static struct kobj_attribute _name##_attr = \
2582 __ATTR(_name, 0644, _name##_show, _name##_store)
2584 static ssize_t sleep_millisecs_show(struct kobject *kobj,
2585 struct kobj_attribute *attr, char *buf)
2587 return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
2590 static ssize_t sleep_millisecs_store(struct kobject *kobj,
2591 struct kobj_attribute *attr,
2592 const char *buf, size_t count)
2594 unsigned long msecs;
2597 err = kstrtoul(buf, 10, &msecs);
2598 if (err || msecs > UINT_MAX)
2601 ksm_thread_sleep_millisecs = msecs;
2605 KSM_ATTR(sleep_millisecs);
2607 static ssize_t pages_to_scan_show(struct kobject *kobj,
2608 struct kobj_attribute *attr, char *buf)
2610 return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
2613 static ssize_t pages_to_scan_store(struct kobject *kobj,
2614 struct kobj_attribute *attr,
2615 const char *buf, size_t count)
2618 unsigned long nr_pages;
2620 err = kstrtoul(buf, 10, &nr_pages);
2621 if (err || nr_pages > UINT_MAX)
2624 ksm_thread_pages_to_scan = nr_pages;
2628 KSM_ATTR(pages_to_scan);
2630 static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
2633 return sprintf(buf, "%lu\n", ksm_run);
2636 static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
2637 const char *buf, size_t count)
2640 unsigned long flags;
2642 err = kstrtoul(buf, 10, &flags);
2643 if (err || flags > UINT_MAX)
2645 if (flags > KSM_RUN_UNMERGE)
2649 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
2650 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
2651 * breaking COW to free the pages_shared (but leaves mm_slots
2652 * on the list for when ksmd may be set running again).
2655 mutex_lock(&ksm_thread_mutex);
2656 wait_while_offlining();
2657 if (ksm_run != flags) {
2659 if (flags & KSM_RUN_UNMERGE) {
2660 set_current_oom_origin();
2661 err = unmerge_and_remove_all_rmap_items();
2662 clear_current_oom_origin();
2664 ksm_run = KSM_RUN_STOP;
2669 mutex_unlock(&ksm_thread_mutex);
2671 if (flags & KSM_RUN_MERGE)
2672 wake_up_interruptible(&ksm_thread_wait);
2679 static ssize_t merge_across_nodes_show(struct kobject *kobj,
2680 struct kobj_attribute *attr, char *buf)
2682 return sprintf(buf, "%u\n", ksm_merge_across_nodes);
2685 static ssize_t merge_across_nodes_store(struct kobject *kobj,
2686 struct kobj_attribute *attr,
2687 const char *buf, size_t count)
2692 err = kstrtoul(buf, 10, &knob);
2698 mutex_lock(&ksm_thread_mutex);
2699 wait_while_offlining();
2700 if (ksm_merge_across_nodes != knob) {
2701 if (ksm_pages_shared || remove_all_stable_nodes())
2703 else if (root_stable_tree == one_stable_tree) {
2704 struct rb_root *buf;
2706 * This is the first time that we switch away from the
2707 * default of merging across nodes: must now allocate
2708 * a buffer to hold as many roots as may be needed.
2709 * Allocate stable and unstable together:
2710 * MAXSMP NODES_SHIFT 10 will use 16kB.
2712 buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf),
2714 /* Let us assume that RB_ROOT is NULL is zero */
2718 root_stable_tree = buf;
2719 root_unstable_tree = buf + nr_node_ids;
2720 /* Stable tree is empty but not the unstable */
2721 root_unstable_tree[0] = one_unstable_tree[0];
2725 ksm_merge_across_nodes = knob;
2726 ksm_nr_node_ids = knob ? 1 : nr_node_ids;
2729 mutex_unlock(&ksm_thread_mutex);
2731 return err ? err : count;
2733 KSM_ATTR(merge_across_nodes);
2736 static ssize_t max_page_sharing_show(struct kobject *kobj,
2737 struct kobj_attribute *attr, char *buf)
2739 return sprintf(buf, "%u\n", ksm_max_page_sharing);
2742 static ssize_t max_page_sharing_store(struct kobject *kobj,
2743 struct kobj_attribute *attr,
2744 const char *buf, size_t count)
2749 err = kstrtoint(buf, 10, &knob);
2753 * When a KSM page is created it is shared by 2 mappings. This
2754 * being a signed comparison, it implicitly verifies it's not
2760 if (READ_ONCE(ksm_max_page_sharing) == knob)
2763 mutex_lock(&ksm_thread_mutex);
2764 wait_while_offlining();
2765 if (ksm_max_page_sharing != knob) {
2766 if (ksm_pages_shared || remove_all_stable_nodes())
2769 ksm_max_page_sharing = knob;
2771 mutex_unlock(&ksm_thread_mutex);
2773 return err ? err : count;
2775 KSM_ATTR(max_page_sharing);
2777 static ssize_t pages_shared_show(struct kobject *kobj,
2778 struct kobj_attribute *attr, char *buf)
2780 return sprintf(buf, "%lu\n", ksm_pages_shared);
2782 KSM_ATTR_RO(pages_shared);
2784 static ssize_t pages_sharing_show(struct kobject *kobj,
2785 struct kobj_attribute *attr, char *buf)
2787 return sprintf(buf, "%lu\n", ksm_pages_sharing);
2789 KSM_ATTR_RO(pages_sharing);
2791 static ssize_t pages_unshared_show(struct kobject *kobj,
2792 struct kobj_attribute *attr, char *buf)
2794 return sprintf(buf, "%lu\n", ksm_pages_unshared);
2796 KSM_ATTR_RO(pages_unshared);
2798 static ssize_t pages_volatile_show(struct kobject *kobj,
2799 struct kobj_attribute *attr, char *buf)
2801 long ksm_pages_volatile;
2803 ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
2804 - ksm_pages_sharing - ksm_pages_unshared;
2806 * It was not worth any locking to calculate that statistic,
2807 * but it might therefore sometimes be negative: conceal that.
2809 if (ksm_pages_volatile < 0)
2810 ksm_pages_volatile = 0;
2811 return sprintf(buf, "%ld\n", ksm_pages_volatile);
2813 KSM_ATTR_RO(pages_volatile);
2815 static ssize_t stable_node_dups_show(struct kobject *kobj,
2816 struct kobj_attribute *attr, char *buf)
2818 return sprintf(buf, "%lu\n", ksm_stable_node_dups);
2820 KSM_ATTR_RO(stable_node_dups);
2822 static ssize_t stable_node_chains_show(struct kobject *kobj,
2823 struct kobj_attribute *attr, char *buf)
2825 return sprintf(buf, "%lu\n", ksm_stable_node_chains);
2827 KSM_ATTR_RO(stable_node_chains);
2830 stable_node_chains_prune_millisecs_show(struct kobject *kobj,
2831 struct kobj_attribute *attr,
2834 return sprintf(buf, "%u\n", ksm_stable_node_chains_prune_millisecs);
2838 stable_node_chains_prune_millisecs_store(struct kobject *kobj,
2839 struct kobj_attribute *attr,
2840 const char *buf, size_t count)
2842 unsigned long msecs;
2845 err = kstrtoul(buf, 10, &msecs);
2846 if (err || msecs > UINT_MAX)
2849 ksm_stable_node_chains_prune_millisecs = msecs;
2853 KSM_ATTR(stable_node_chains_prune_millisecs);
2855 static ssize_t full_scans_show(struct kobject *kobj,
2856 struct kobj_attribute *attr, char *buf)
2858 return sprintf(buf, "%lu\n", ksm_scan.seqnr);
2860 KSM_ATTR_RO(full_scans);
2862 static struct attribute *ksm_attrs[] = {
2863 &sleep_millisecs_attr.attr,
2864 &pages_to_scan_attr.attr,
2866 &pages_shared_attr.attr,
2867 &pages_sharing_attr.attr,
2868 &pages_unshared_attr.attr,
2869 &pages_volatile_attr.attr,
2870 &full_scans_attr.attr,
2872 &merge_across_nodes_attr.attr,
2874 &max_page_sharing_attr.attr,
2875 &stable_node_chains_attr.attr,
2876 &stable_node_dups_attr.attr,
2877 &stable_node_chains_prune_millisecs_attr.attr,
2881 static struct attribute_group ksm_attr_group = {
2885 #endif /* CONFIG_SYSFS */
2887 static int __init ksm_init(void)
2889 struct task_struct *ksm_thread;
2892 err = ksm_slab_init();
2896 ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
2897 if (IS_ERR(ksm_thread)) {
2898 pr_err("ksm: creating kthread failed\n");
2899 err = PTR_ERR(ksm_thread);
2904 err = sysfs_create_group(mm_kobj, &ksm_attr_group);
2906 pr_err("ksm: register sysfs failed\n");
2907 kthread_stop(ksm_thread);
2911 ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
2913 #endif /* CONFIG_SYSFS */
2915 #ifdef CONFIG_MEMORY_HOTREMOVE
2916 /* There is no significance to this priority 100 */
2917 hotplug_memory_notifier(ksm_memory_callback, 100);
2926 subsys_initcall(ksm_init);