]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blame - mm/ksm.c
ksm: introduce ksm_max_page_sharing per page deduplication limit
[mirror_ubuntu-zesty-kernel.git] / mm / ksm.c
CommitLineData
f8af4da3 1/*
31dbd01f
IE
2 * Memory merging support.
3 *
4 * This code enables dynamic sharing of identical pages found in different
5 * memory areas, even if they are not shared by fork()
6 *
36b2528d 7 * Copyright (C) 2008-2009 Red Hat, Inc.
31dbd01f
IE
8 * Authors:
9 * Izik Eidus
10 * Andrea Arcangeli
11 * Chris Wright
36b2528d 12 * Hugh Dickins
31dbd01f
IE
13 *
14 * This work is licensed under the terms of the GNU GPL, version 2.
f8af4da3
HD
15 */
16
17#include <linux/errno.h>
31dbd01f
IE
18#include <linux/mm.h>
19#include <linux/fs.h>
f8af4da3 20#include <linux/mman.h>
31dbd01f
IE
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>
62b61f61 32#include <linux/memory.h>
31dbd01f 33#include <linux/mmu_notifier.h>
2c6854fd 34#include <linux/swap.h>
f8af4da3 35#include <linux/ksm.h>
4ca3a69b 36#include <linux/hashtable.h>
878aee7d 37#include <linux/freezer.h>
72788c38 38#include <linux/oom.h>
90bd6fd3 39#include <linux/numa.h>
f8af4da3 40
31dbd01f 41#include <asm/tlbflush.h>
73848b46 42#include "internal.h"
31dbd01f 43
e850dcf5
HD
44#ifdef CONFIG_NUMA
45#define NUMA(x) (x)
46#define DO_NUMA(x) do { (x); } while (0)
47#else
48#define NUMA(x) (0)
49#define DO_NUMA(x) do { } while (0)
50#endif
51
31dbd01f
IE
52/*
53 * A few notes about the KSM scanning process,
54 * to make it easier to understand the data structures below:
55 *
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.
58 *
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.
62 *
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.
67 *
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.
74 *
75 * KSM solves this problem by several techniques:
76 *
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.)
8fdb3dbf
HD
90 *
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.
31dbd01f
IE
93 */
94
95/**
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
6514d511 99 * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
31dbd01f
IE
100 * @mm: the mm that this information is valid for
101 */
102struct mm_slot {
103 struct hlist_node link;
104 struct list_head mm_list;
6514d511 105 struct rmap_item *rmap_list;
31dbd01f
IE
106 struct mm_struct *mm;
107};
108
109/**
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
6514d511 113 * @rmap_list: link to the next rmap to be scanned in the rmap_list
31dbd01f
IE
114 * @seqnr: count of completed full scans (needed when removing unstable node)
115 *
116 * There is only the one ksm_scan instance of this cursor structure.
117 */
118struct ksm_scan {
119 struct mm_slot *mm_slot;
120 unsigned long address;
6514d511 121 struct rmap_item **rmap_list;
31dbd01f
IE
122 unsigned long seqnr;
123};
124
7b6ba2c7
HD
125/**
126 * struct stable_node - node of the stable rbtree
127 * @node: rb node of this ksm page in the stable tree
4146d2d6 128 * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
7253473c 129 * @hlist_dup: linked into the stable_node->hlist with a stable_node chain
4146d2d6 130 * @list: linked into migrate_nodes, pending placement in the proper node tree
7b6ba2c7 131 * @hlist: hlist head of rmap_items using this ksm page
4146d2d6 132 * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
7253473c
AA
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
4146d2d6 135 * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
7b6ba2c7
HD
136 */
137struct stable_node {
4146d2d6
HD
138 union {
139 struct rb_node node; /* when node of stable tree */
140 struct { /* when listed for migration */
141 struct list_head *head;
7253473c
AA
142 struct {
143 struct hlist_node hlist_dup;
144 struct list_head list;
145 };
4146d2d6
HD
146 };
147 };
7b6ba2c7 148 struct hlist_head hlist;
7253473c
AA
149 union {
150 unsigned long kpfn;
151 unsigned long chain_prune_time;
152 };
153 /*
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.
157 */
158#define STABLE_NODE_CHAIN -1024
159 int rmap_hlist_len;
4146d2d6
HD
160#ifdef CONFIG_NUMA
161 int nid;
162#endif
7b6ba2c7
HD
163};
164
31dbd01f
IE
165/**
166 * struct rmap_item - reverse mapping item for virtual addresses
6514d511 167 * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
db114b83 168 * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
bc56620b 169 * @nid: NUMA node id of unstable tree in which linked (may not match page)
31dbd01f
IE
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
7b6ba2c7
HD
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
31dbd01f
IE
176 */
177struct rmap_item {
6514d511 178 struct rmap_item *rmap_list;
bc56620b
HD
179 union {
180 struct anon_vma *anon_vma; /* when stable */
181#ifdef CONFIG_NUMA
182 int nid; /* when node of unstable tree */
183#endif
184 };
31dbd01f
IE
185 struct mm_struct *mm;
186 unsigned long address; /* + low bits used for flags below */
7b6ba2c7 187 unsigned int oldchecksum; /* when unstable */
31dbd01f 188 union {
7b6ba2c7
HD
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;
193 };
31dbd01f
IE
194 };
195};
196
197#define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
7b6ba2c7
HD
198#define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
199#define STABLE_FLAG 0x200 /* is listed from the stable tree */
31dbd01f
IE
200
201/* The stable and unstable tree heads */
ef53d16c
HD
202static struct rb_root one_stable_tree[1] = { RB_ROOT };
203static struct rb_root one_unstable_tree[1] = { RB_ROOT };
204static struct rb_root *root_stable_tree = one_stable_tree;
205static struct rb_root *root_unstable_tree = one_unstable_tree;
31dbd01f 206
4146d2d6
HD
207/* Recently migrated nodes of stable tree, pending proper placement */
208static LIST_HEAD(migrate_nodes);
7253473c 209#define STABLE_NODE_DUP_HEAD ((struct list_head *)&migrate_nodes.prev)
4146d2d6 210
4ca3a69b
SL
211#define MM_SLOTS_HASH_BITS 10
212static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
31dbd01f
IE
213
214static struct mm_slot ksm_mm_head = {
215 .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
216};
217static struct ksm_scan ksm_scan = {
218 .mm_slot = &ksm_mm_head,
219};
220
221static struct kmem_cache *rmap_item_cache;
7b6ba2c7 222static struct kmem_cache *stable_node_cache;
31dbd01f
IE
223static struct kmem_cache *mm_slot_cache;
224
225/* The number of nodes in the stable tree */
b4028260 226static unsigned long ksm_pages_shared;
31dbd01f 227
e178dfde 228/* The number of page slots additionally sharing those nodes */
b4028260 229static unsigned long ksm_pages_sharing;
31dbd01f 230
473b0ce4
HD
231/* The number of nodes in the unstable tree */
232static unsigned long ksm_pages_unshared;
233
234/* The number of rmap_items in use: to calculate pages_volatile */
235static unsigned long ksm_rmap_items;
236
7253473c
AA
237/* The number of stable_node chains */
238static unsigned long ksm_stable_node_chains;
239
240/* The number of stable_node dups linked to the stable_node chains */
241static unsigned long ksm_stable_node_dups;
242
243/* Delay in pruning stale stable_node_dups in the stable_node_chains */
244static int ksm_stable_node_chains_prune_millisecs = 2000;
245
246/* Maximum number of page slots sharing a stable node */
247static int ksm_max_page_sharing = 256;
248
31dbd01f 249/* Number of pages ksmd should scan in one batch */
2c6854fd 250static unsigned int ksm_thread_pages_to_scan = 100;
31dbd01f
IE
251
252/* Milliseconds ksmd should sleep between batches */
2ffd8679 253static unsigned int ksm_thread_sleep_millisecs = 20;
31dbd01f 254
fa2aa0fc
CI
255/* Checksum of an empty (zeroed) page */
256static unsigned int zero_checksum __read_mostly;
257
258/* Whether to merge empty (zeroed) pages with actual zero pages */
259static bool ksm_use_zero_pages __read_mostly;
260
e850dcf5 261#ifdef CONFIG_NUMA
90bd6fd3
PH
262/* Zeroed when merging across nodes is not allowed */
263static unsigned int ksm_merge_across_nodes = 1;
ef53d16c 264static int ksm_nr_node_ids = 1;
e850dcf5
HD
265#else
266#define ksm_merge_across_nodes 1U
ef53d16c 267#define ksm_nr_node_ids 1
e850dcf5 268#endif
90bd6fd3 269
31dbd01f
IE
270#define KSM_RUN_STOP 0
271#define KSM_RUN_MERGE 1
272#define KSM_RUN_UNMERGE 2
ef4d43a8
HD
273#define KSM_RUN_OFFLINE 4
274static unsigned long ksm_run = KSM_RUN_STOP;
275static void wait_while_offlining(void);
31dbd01f
IE
276
277static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
278static DEFINE_MUTEX(ksm_thread_mutex);
279static DEFINE_SPINLOCK(ksm_mmlist_lock);
280
281#define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
282 sizeof(struct __struct), __alignof__(struct __struct),\
283 (__flags), NULL)
284
285static int __init ksm_slab_init(void)
286{
287 rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
288 if (!rmap_item_cache)
289 goto out;
290
7b6ba2c7
HD
291 stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
292 if (!stable_node_cache)
293 goto out_free1;
294
31dbd01f
IE
295 mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
296 if (!mm_slot_cache)
7b6ba2c7 297 goto out_free2;
31dbd01f
IE
298
299 return 0;
300
7b6ba2c7
HD
301out_free2:
302 kmem_cache_destroy(stable_node_cache);
303out_free1:
31dbd01f
IE
304 kmem_cache_destroy(rmap_item_cache);
305out:
306 return -ENOMEM;
307}
308
309static void __init ksm_slab_free(void)
310{
311 kmem_cache_destroy(mm_slot_cache);
7b6ba2c7 312 kmem_cache_destroy(stable_node_cache);
31dbd01f
IE
313 kmem_cache_destroy(rmap_item_cache);
314 mm_slot_cache = NULL;
315}
316
7253473c
AA
317static __always_inline bool is_stable_node_chain(struct stable_node *chain)
318{
319 return chain->rmap_hlist_len == STABLE_NODE_CHAIN;
320}
321
322static __always_inline bool is_stable_node_dup(struct stable_node *dup)
323{
324 return dup->head == STABLE_NODE_DUP_HEAD;
325}
326
327static inline void stable_node_chain_add_dup(struct stable_node *dup,
328 struct stable_node *chain)
329{
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++;
335}
336
337static inline void __stable_node_dup_del(struct stable_node *dup)
338{
339 hlist_del(&dup->hlist_dup);
340 ksm_stable_node_dups--;
341}
342
343static inline void stable_node_dup_del(struct stable_node *dup)
344{
345 VM_BUG_ON(is_stable_node_chain(dup));
346 if (is_stable_node_dup(dup))
347 __stable_node_dup_del(dup);
348 else
349 rb_erase(&dup->node, root_stable_tree + NUMA(dup->nid));
350#ifdef CONFIG_DEBUG_VM
351 dup->head = NULL;
352#endif
353}
354
31dbd01f
IE
355static inline struct rmap_item *alloc_rmap_item(void)
356{
473b0ce4
HD
357 struct rmap_item *rmap_item;
358
5b398e41 359 rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL |
360 __GFP_NORETRY | __GFP_NOWARN);
473b0ce4
HD
361 if (rmap_item)
362 ksm_rmap_items++;
363 return rmap_item;
31dbd01f
IE
364}
365
366static inline void free_rmap_item(struct rmap_item *rmap_item)
367{
473b0ce4 368 ksm_rmap_items--;
31dbd01f
IE
369 rmap_item->mm = NULL; /* debug safety */
370 kmem_cache_free(rmap_item_cache, rmap_item);
371}
372
7b6ba2c7
HD
373static inline struct stable_node *alloc_stable_node(void)
374{
6213055f 375 /*
376 * The allocation can take too long with GFP_KERNEL when memory is under
377 * pressure, which may lead to hung task warnings. Adding __GFP_HIGH
378 * grants access to memory reserves, helping to avoid this problem.
379 */
380 return kmem_cache_alloc(stable_node_cache, GFP_KERNEL | __GFP_HIGH);
7b6ba2c7
HD
381}
382
383static inline void free_stable_node(struct stable_node *stable_node)
384{
7253473c
AA
385 VM_BUG_ON(stable_node->rmap_hlist_len &&
386 !is_stable_node_chain(stable_node));
7b6ba2c7
HD
387 kmem_cache_free(stable_node_cache, stable_node);
388}
389
31dbd01f
IE
390static inline struct mm_slot *alloc_mm_slot(void)
391{
392 if (!mm_slot_cache) /* initialization failed */
393 return NULL;
394 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
395}
396
397static inline void free_mm_slot(struct mm_slot *mm_slot)
398{
399 kmem_cache_free(mm_slot_cache, mm_slot);
400}
401
31dbd01f
IE
402static struct mm_slot *get_mm_slot(struct mm_struct *mm)
403{
4ca3a69b
SL
404 struct mm_slot *slot;
405
b67bfe0d 406 hash_for_each_possible(mm_slots_hash, slot, link, (unsigned long)mm)
4ca3a69b
SL
407 if (slot->mm == mm)
408 return slot;
31dbd01f 409
31dbd01f
IE
410 return NULL;
411}
412
413static void insert_to_mm_slots_hash(struct mm_struct *mm,
414 struct mm_slot *mm_slot)
415{
31dbd01f 416 mm_slot->mm = mm;
4ca3a69b 417 hash_add(mm_slots_hash, &mm_slot->link, (unsigned long)mm);
31dbd01f
IE
418}
419
a913e182
HD
420/*
421 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
422 * page tables after it has passed through ksm_exit() - which, if necessary,
423 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
424 * a special flag: they can just back out as soon as mm_users goes to zero.
425 * ksm_test_exit() is used throughout to make this test for exit: in some
426 * places for correctness, in some places just to avoid unnecessary work.
427 */
428static inline bool ksm_test_exit(struct mm_struct *mm)
429{
430 return atomic_read(&mm->mm_users) == 0;
431}
432
31dbd01f
IE
433/*
434 * We use break_ksm to break COW on a ksm page: it's a stripped down
435 *
d4edcf0d 436 * if (get_user_pages(addr, 1, 1, 1, &page, NULL) == 1)
31dbd01f
IE
437 * put_page(page);
438 *
439 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
440 * in case the application has unmapped and remapped mm,addr meanwhile.
441 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
442 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
1b2ee126
DH
443 *
444 * FAULT_FLAG/FOLL_REMOTE are because we do this outside the context
445 * of the process that owns 'vma'. We also do not want to enforce
446 * protection keys here anyway.
31dbd01f 447 */
d952b791 448static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
31dbd01f
IE
449{
450 struct page *page;
d952b791 451 int ret = 0;
31dbd01f
IE
452
453 do {
454 cond_resched();
1b2ee126
DH
455 page = follow_page(vma, addr,
456 FOLL_GET | FOLL_MIGRATION | FOLL_REMOTE);
22eccdd7 457 if (IS_ERR_OR_NULL(page))
31dbd01f
IE
458 break;
459 if (PageKsm(page))
dcddffd4
KS
460 ret = handle_mm_fault(vma, addr,
461 FAULT_FLAG_WRITE | FAULT_FLAG_REMOTE);
31dbd01f
IE
462 else
463 ret = VM_FAULT_WRITE;
464 put_page(page);
33692f27 465 } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
d952b791
HD
466 /*
467 * We must loop because handle_mm_fault() may back out if there's
468 * any difficulty e.g. if pte accessed bit gets updated concurrently.
469 *
470 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
471 * COW has been broken, even if the vma does not permit VM_WRITE;
472 * but note that a concurrent fault might break PageKsm for us.
473 *
474 * VM_FAULT_SIGBUS could occur if we race with truncation of the
475 * backing file, which also invalidates anonymous pages: that's
476 * okay, that truncation will have unmapped the PageKsm for us.
477 *
478 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
479 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
480 * current task has TIF_MEMDIE set, and will be OOM killed on return
481 * to user; and ksmd, having no mm, would never be chosen for that.
482 *
483 * But if the mm is in a limited mem_cgroup, then the fault may fail
484 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
485 * even ksmd can fail in this way - though it's usually breaking ksm
486 * just to undo a merge it made a moment before, so unlikely to oom.
487 *
488 * That's a pity: we might therefore have more kernel pages allocated
489 * than we're counting as nodes in the stable tree; but ksm_do_scan
490 * will retry to break_cow on each pass, so should recover the page
491 * in due course. The important thing is to not let VM_MERGEABLE
492 * be cleared while any such pages might remain in the area.
493 */
494 return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
31dbd01f
IE
495}
496
ef694222
BL
497static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
498 unsigned long addr)
499{
500 struct vm_area_struct *vma;
501 if (ksm_test_exit(mm))
502 return NULL;
503 vma = find_vma(mm, addr);
504 if (!vma || vma->vm_start > addr)
505 return NULL;
506 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
507 return NULL;
508 return vma;
509}
510
8dd3557a 511static void break_cow(struct rmap_item *rmap_item)
31dbd01f 512{
8dd3557a
HD
513 struct mm_struct *mm = rmap_item->mm;
514 unsigned long addr = rmap_item->address;
31dbd01f
IE
515 struct vm_area_struct *vma;
516
4035c07a
HD
517 /*
518 * It is not an accident that whenever we want to break COW
519 * to undo, we also need to drop a reference to the anon_vma.
520 */
9e60109f 521 put_anon_vma(rmap_item->anon_vma);
4035c07a 522
81464e30 523 down_read(&mm->mmap_sem);
ef694222
BL
524 vma = find_mergeable_vma(mm, addr);
525 if (vma)
526 break_ksm(vma, addr);
31dbd01f
IE
527 up_read(&mm->mmap_sem);
528}
529
530static struct page *get_mergeable_page(struct rmap_item *rmap_item)
531{
532 struct mm_struct *mm = rmap_item->mm;
533 unsigned long addr = rmap_item->address;
534 struct vm_area_struct *vma;
535 struct page *page;
536
537 down_read(&mm->mmap_sem);
ef694222
BL
538 vma = find_mergeable_vma(mm, addr);
539 if (!vma)
31dbd01f
IE
540 goto out;
541
542 page = follow_page(vma, addr, FOLL_GET);
22eccdd7 543 if (IS_ERR_OR_NULL(page))
31dbd01f 544 goto out;
f765f540 545 if (PageAnon(page)) {
31dbd01f
IE
546 flush_anon_page(vma, page, addr);
547 flush_dcache_page(page);
548 } else {
549 put_page(page);
c8f95ed1
AA
550out:
551 page = NULL;
31dbd01f
IE
552 }
553 up_read(&mm->mmap_sem);
554 return page;
555}
556
90bd6fd3
PH
557/*
558 * This helper is used for getting right index into array of tree roots.
559 * When merge_across_nodes knob is set to 1, there are only two rb-trees for
560 * stable and unstable pages from all nodes with roots in index 0. Otherwise,
561 * every node has its own stable and unstable tree.
562 */
563static inline int get_kpfn_nid(unsigned long kpfn)
564{
d8fc16a8 565 return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
90bd6fd3
PH
566}
567
7253473c
AA
568static struct stable_node *alloc_stable_node_chain(struct stable_node *dup,
569 struct rb_root *root)
570{
571 struct stable_node *chain = alloc_stable_node();
572 VM_BUG_ON(is_stable_node_chain(dup));
573 if (likely(chain)) {
574 INIT_HLIST_HEAD(&chain->hlist);
575 chain->chain_prune_time = jiffies;
576 chain->rmap_hlist_len = STABLE_NODE_CHAIN;
577#if defined (CONFIG_DEBUG_VM) && defined(CONFIG_NUMA)
578 chain->nid = -1; /* debug */
579#endif
580 ksm_stable_node_chains++;
581
582 /*
583 * Put the stable node chain in the first dimension of
584 * the stable tree and at the same time remove the old
585 * stable node.
586 */
587 rb_replace_node(&dup->node, &chain->node, root);
588
589 /*
590 * Move the old stable node to the second dimension
591 * queued in the hlist_dup. The invariant is that all
592 * dup stable_nodes in the chain->hlist point to pages
593 * that are wrprotected and have the exact same
594 * content.
595 */
596 stable_node_chain_add_dup(dup, chain);
597 }
598 return chain;
599}
600
601static inline void free_stable_node_chain(struct stable_node *chain,
602 struct rb_root *root)
603{
604 rb_erase(&chain->node, root);
605 free_stable_node(chain);
606 ksm_stable_node_chains--;
607}
608
4035c07a
HD
609static void remove_node_from_stable_tree(struct stable_node *stable_node)
610{
611 struct rmap_item *rmap_item;
4035c07a 612
7253473c
AA
613 /* check it's not STABLE_NODE_CHAIN or negative */
614 BUG_ON(stable_node->rmap_hlist_len < 0);
615
b67bfe0d 616 hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
4035c07a
HD
617 if (rmap_item->hlist.next)
618 ksm_pages_sharing--;
619 else
620 ksm_pages_shared--;
7253473c
AA
621 VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
622 stable_node->rmap_hlist_len--;
9e60109f 623 put_anon_vma(rmap_item->anon_vma);
4035c07a
HD
624 rmap_item->address &= PAGE_MASK;
625 cond_resched();
626 }
627
7253473c
AA
628 /*
629 * We need the second aligned pointer of the migrate_nodes
630 * list_head to stay clear from the rb_parent_color union
631 * (aligned and different than any node) and also different
632 * from &migrate_nodes. This will verify that future list.h changes
633 * don't break STABLE_NODE_DUP_HEAD.
634 */
635#if GCC_VERSION >= 40903 /* only recent gcc can handle it */
636 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD <= &migrate_nodes);
637 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD >= &migrate_nodes + 1);
638#endif
639
4146d2d6
HD
640 if (stable_node->head == &migrate_nodes)
641 list_del(&stable_node->list);
642 else
7253473c 643 stable_node_dup_del(stable_node);
4035c07a
HD
644 free_stable_node(stable_node);
645}
646
647/*
648 * get_ksm_page: checks if the page indicated by the stable node
649 * is still its ksm page, despite having held no reference to it.
650 * In which case we can trust the content of the page, and it
651 * returns the gotten page; but if the page has now been zapped,
652 * remove the stale node from the stable tree and return NULL.
c8d6553b 653 * But beware, the stable node's page might be being migrated.
4035c07a
HD
654 *
655 * You would expect the stable_node to hold a reference to the ksm page.
656 * But if it increments the page's count, swapping out has to wait for
657 * ksmd to come around again before it can free the page, which may take
658 * seconds or even minutes: much too unresponsive. So instead we use a
659 * "keyhole reference": access to the ksm page from the stable node peeps
660 * out through its keyhole to see if that page still holds the right key,
661 * pointing back to this stable node. This relies on freeing a PageAnon
662 * page to reset its page->mapping to NULL, and relies on no other use of
663 * a page to put something that might look like our key in page->mapping.
4035c07a
HD
664 * is on its way to being freed; but it is an anomaly to bear in mind.
665 */
8fdb3dbf 666static struct page *get_ksm_page(struct stable_node *stable_node, bool lock_it)
4035c07a
HD
667{
668 struct page *page;
669 void *expected_mapping;
c8d6553b 670 unsigned long kpfn;
4035c07a 671
bda807d4
MK
672 expected_mapping = (void *)((unsigned long)stable_node |
673 PAGE_MAPPING_KSM);
c8d6553b 674again:
4db0c3c2 675 kpfn = READ_ONCE(stable_node->kpfn);
c8d6553b
HD
676 page = pfn_to_page(kpfn);
677
678 /*
679 * page is computed from kpfn, so on most architectures reading
680 * page->mapping is naturally ordered after reading node->kpfn,
681 * but on Alpha we need to be more careful.
682 */
683 smp_read_barrier_depends();
4db0c3c2 684 if (READ_ONCE(page->mapping) != expected_mapping)
4035c07a 685 goto stale;
c8d6553b
HD
686
687 /*
688 * We cannot do anything with the page while its refcount is 0.
689 * Usually 0 means free, or tail of a higher-order page: in which
690 * case this node is no longer referenced, and should be freed;
691 * however, it might mean that the page is under page_freeze_refs().
692 * The __remove_mapping() case is easy, again the node is now stale;
693 * but if page is swapcache in migrate_page_move_mapping(), it might
694 * still be our page, in which case it's essential to keep the node.
695 */
696 while (!get_page_unless_zero(page)) {
697 /*
698 * Another check for page->mapping != expected_mapping would
699 * work here too. We have chosen the !PageSwapCache test to
700 * optimize the common case, when the page is or is about to
701 * be freed: PageSwapCache is cleared (under spin_lock_irq)
702 * in the freeze_refs section of __remove_mapping(); but Anon
703 * page->mapping reset to NULL later, in free_pages_prepare().
704 */
705 if (!PageSwapCache(page))
706 goto stale;
707 cpu_relax();
708 }
709
4db0c3c2 710 if (READ_ONCE(page->mapping) != expected_mapping) {
4035c07a
HD
711 put_page(page);
712 goto stale;
713 }
c8d6553b 714
8fdb3dbf 715 if (lock_it) {
8aafa6a4 716 lock_page(page);
4db0c3c2 717 if (READ_ONCE(page->mapping) != expected_mapping) {
8aafa6a4
HD
718 unlock_page(page);
719 put_page(page);
720 goto stale;
721 }
722 }
4035c07a 723 return page;
c8d6553b 724
4035c07a 725stale:
c8d6553b
HD
726 /*
727 * We come here from above when page->mapping or !PageSwapCache
728 * suggests that the node is stale; but it might be under migration.
729 * We need smp_rmb(), matching the smp_wmb() in ksm_migrate_page(),
730 * before checking whether node->kpfn has been changed.
731 */
732 smp_rmb();
4db0c3c2 733 if (READ_ONCE(stable_node->kpfn) != kpfn)
c8d6553b 734 goto again;
4035c07a
HD
735 remove_node_from_stable_tree(stable_node);
736 return NULL;
737}
738
31dbd01f
IE
739/*
740 * Removing rmap_item from stable or unstable tree.
741 * This function will clean the information from the stable/unstable tree.
742 */
743static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
744{
7b6ba2c7
HD
745 if (rmap_item->address & STABLE_FLAG) {
746 struct stable_node *stable_node;
5ad64688 747 struct page *page;
31dbd01f 748
7b6ba2c7 749 stable_node = rmap_item->head;
8aafa6a4 750 page = get_ksm_page(stable_node, true);
4035c07a
HD
751 if (!page)
752 goto out;
5ad64688 753
7b6ba2c7 754 hlist_del(&rmap_item->hlist);
4035c07a
HD
755 unlock_page(page);
756 put_page(page);
08beca44 757
98666f8a 758 if (!hlist_empty(&stable_node->hlist))
4035c07a
HD
759 ksm_pages_sharing--;
760 else
7b6ba2c7 761 ksm_pages_shared--;
7253473c
AA
762 VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
763 stable_node->rmap_hlist_len--;
31dbd01f 764
9e60109f 765 put_anon_vma(rmap_item->anon_vma);
93d17715 766 rmap_item->address &= PAGE_MASK;
31dbd01f 767
7b6ba2c7 768 } else if (rmap_item->address & UNSTABLE_FLAG) {
31dbd01f
IE
769 unsigned char age;
770 /*
9ba69294 771 * Usually ksmd can and must skip the rb_erase, because
31dbd01f 772 * root_unstable_tree was already reset to RB_ROOT.
9ba69294
HD
773 * But be careful when an mm is exiting: do the rb_erase
774 * if this rmap_item was inserted by this scan, rather
775 * than left over from before.
31dbd01f
IE
776 */
777 age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
cd551f97 778 BUG_ON(age > 1);
31dbd01f 779 if (!age)
90bd6fd3 780 rb_erase(&rmap_item->node,
ef53d16c 781 root_unstable_tree + NUMA(rmap_item->nid));
473b0ce4 782 ksm_pages_unshared--;
93d17715 783 rmap_item->address &= PAGE_MASK;
31dbd01f 784 }
4035c07a 785out:
31dbd01f
IE
786 cond_resched(); /* we're called from many long loops */
787}
788
31dbd01f 789static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
6514d511 790 struct rmap_item **rmap_list)
31dbd01f 791{
6514d511
HD
792 while (*rmap_list) {
793 struct rmap_item *rmap_item = *rmap_list;
794 *rmap_list = rmap_item->rmap_list;
31dbd01f 795 remove_rmap_item_from_tree(rmap_item);
31dbd01f
IE
796 free_rmap_item(rmap_item);
797 }
798}
799
800/*
e850dcf5 801 * Though it's very tempting to unmerge rmap_items from stable tree rather
31dbd01f
IE
802 * than check every pte of a given vma, the locking doesn't quite work for
803 * that - an rmap_item is assigned to the stable tree after inserting ksm
804 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
805 * rmap_items from parent to child at fork time (so as not to waste time
806 * if exit comes before the next scan reaches it).
81464e30
HD
807 *
808 * Similarly, although we'd like to remove rmap_items (so updating counts
809 * and freeing memory) when unmerging an area, it's easier to leave that
810 * to the next pass of ksmd - consider, for example, how ksmd might be
811 * in cmp_and_merge_page on one of the rmap_items we would be removing.
31dbd01f 812 */
d952b791
HD
813static int unmerge_ksm_pages(struct vm_area_struct *vma,
814 unsigned long start, unsigned long end)
31dbd01f
IE
815{
816 unsigned long addr;
d952b791 817 int err = 0;
31dbd01f 818
d952b791 819 for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
9ba69294
HD
820 if (ksm_test_exit(vma->vm_mm))
821 break;
d952b791
HD
822 if (signal_pending(current))
823 err = -ERESTARTSYS;
824 else
825 err = break_ksm(vma, addr);
826 }
827 return err;
31dbd01f
IE
828}
829
2ffd8679
HD
830#ifdef CONFIG_SYSFS
831/*
832 * Only called through the sysfs control interface:
833 */
cbf86cfe
HD
834static int remove_stable_node(struct stable_node *stable_node)
835{
836 struct page *page;
837 int err;
838
839 page = get_ksm_page(stable_node, true);
840 if (!page) {
841 /*
842 * get_ksm_page did remove_node_from_stable_tree itself.
843 */
844 return 0;
845 }
846
8fdb3dbf
HD
847 if (WARN_ON_ONCE(page_mapped(page))) {
848 /*
849 * This should not happen: but if it does, just refuse to let
850 * merge_across_nodes be switched - there is no need to panic.
851 */
cbf86cfe 852 err = -EBUSY;
8fdb3dbf 853 } else {
cbf86cfe 854 /*
8fdb3dbf
HD
855 * The stable node did not yet appear stale to get_ksm_page(),
856 * since that allows for an unmapped ksm page to be recognized
857 * right up until it is freed; but the node is safe to remove.
cbf86cfe
HD
858 * This page might be in a pagevec waiting to be freed,
859 * or it might be PageSwapCache (perhaps under writeback),
860 * or it might have been removed from swapcache a moment ago.
861 */
862 set_page_stable_node(page, NULL);
863 remove_node_from_stable_tree(stable_node);
864 err = 0;
865 }
866
867 unlock_page(page);
868 put_page(page);
869 return err;
870}
871
7253473c
AA
872static int remove_stable_node_chain(struct stable_node *stable_node,
873 struct rb_root *root)
874{
875 struct stable_node *dup;
876 struct hlist_node *hlist_safe;
877
878 if (!is_stable_node_chain(stable_node)) {
879 VM_BUG_ON(is_stable_node_dup(stable_node));
880 if (remove_stable_node(stable_node))
881 return true;
882 else
883 return false;
884 }
885
886 hlist_for_each_entry_safe(dup, hlist_safe,
887 &stable_node->hlist, hlist_dup) {
888 VM_BUG_ON(!is_stable_node_dup(dup));
889 if (remove_stable_node(dup))
890 return true;
891 }
892 BUG_ON(!hlist_empty(&stable_node->hlist));
893 free_stable_node_chain(stable_node, root);
894 return false;
895}
896
cbf86cfe
HD
897static int remove_all_stable_nodes(void)
898{
03640418 899 struct stable_node *stable_node, *next;
cbf86cfe
HD
900 int nid;
901 int err = 0;
902
ef53d16c 903 for (nid = 0; nid < ksm_nr_node_ids; nid++) {
cbf86cfe
HD
904 while (root_stable_tree[nid].rb_node) {
905 stable_node = rb_entry(root_stable_tree[nid].rb_node,
906 struct stable_node, node);
7253473c
AA
907 if (remove_stable_node_chain(stable_node,
908 root_stable_tree + nid)) {
cbf86cfe
HD
909 err = -EBUSY;
910 break; /* proceed to next nid */
911 }
912 cond_resched();
913 }
914 }
03640418 915 list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
4146d2d6
HD
916 if (remove_stable_node(stable_node))
917 err = -EBUSY;
918 cond_resched();
919 }
cbf86cfe
HD
920 return err;
921}
922
d952b791 923static int unmerge_and_remove_all_rmap_items(void)
31dbd01f
IE
924{
925 struct mm_slot *mm_slot;
926 struct mm_struct *mm;
927 struct vm_area_struct *vma;
d952b791
HD
928 int err = 0;
929
930 spin_lock(&ksm_mmlist_lock);
9ba69294 931 ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
d952b791
HD
932 struct mm_slot, mm_list);
933 spin_unlock(&ksm_mmlist_lock);
31dbd01f 934
9ba69294
HD
935 for (mm_slot = ksm_scan.mm_slot;
936 mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
31dbd01f
IE
937 mm = mm_slot->mm;
938 down_read(&mm->mmap_sem);
939 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9ba69294
HD
940 if (ksm_test_exit(mm))
941 break;
31dbd01f
IE
942 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
943 continue;
d952b791
HD
944 err = unmerge_ksm_pages(vma,
945 vma->vm_start, vma->vm_end);
9ba69294
HD
946 if (err)
947 goto error;
31dbd01f 948 }
9ba69294 949
6514d511 950 remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
7496fea9 951 up_read(&mm->mmap_sem);
d952b791
HD
952
953 spin_lock(&ksm_mmlist_lock);
9ba69294 954 ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
d952b791 955 struct mm_slot, mm_list);
9ba69294 956 if (ksm_test_exit(mm)) {
4ca3a69b 957 hash_del(&mm_slot->link);
9ba69294
HD
958 list_del(&mm_slot->mm_list);
959 spin_unlock(&ksm_mmlist_lock);
960
961 free_mm_slot(mm_slot);
962 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
9ba69294 963 mmdrop(mm);
7496fea9 964 } else
9ba69294 965 spin_unlock(&ksm_mmlist_lock);
31dbd01f
IE
966 }
967
cbf86cfe
HD
968 /* Clean up stable nodes, but don't worry if some are still busy */
969 remove_all_stable_nodes();
d952b791 970 ksm_scan.seqnr = 0;
9ba69294
HD
971 return 0;
972
973error:
974 up_read(&mm->mmap_sem);
31dbd01f 975 spin_lock(&ksm_mmlist_lock);
d952b791 976 ksm_scan.mm_slot = &ksm_mm_head;
31dbd01f 977 spin_unlock(&ksm_mmlist_lock);
d952b791 978 return err;
31dbd01f 979}
2ffd8679 980#endif /* CONFIG_SYSFS */
31dbd01f 981
31dbd01f
IE
982static u32 calc_checksum(struct page *page)
983{
984 u32 checksum;
9b04c5fe 985 void *addr = kmap_atomic(page);
31dbd01f 986 checksum = jhash2(addr, PAGE_SIZE / 4, 17);
9b04c5fe 987 kunmap_atomic(addr);
31dbd01f
IE
988 return checksum;
989}
990
991static int memcmp_pages(struct page *page1, struct page *page2)
992{
993 char *addr1, *addr2;
994 int ret;
995
9b04c5fe
CW
996 addr1 = kmap_atomic(page1);
997 addr2 = kmap_atomic(page2);
31dbd01f 998 ret = memcmp(addr1, addr2, PAGE_SIZE);
9b04c5fe
CW
999 kunmap_atomic(addr2);
1000 kunmap_atomic(addr1);
31dbd01f
IE
1001 return ret;
1002}
1003
1004static inline int pages_identical(struct page *page1, struct page *page2)
1005{
1006 return !memcmp_pages(page1, page2);
1007}
1008
1009static int write_protect_page(struct vm_area_struct *vma, struct page *page,
1010 pte_t *orig_pte)
1011{
1012 struct mm_struct *mm = vma->vm_mm;
421ec457
SF
1013 unsigned long addr;
1014 pte_t *ptep;
1015 spinlock_t *ptl;
31dbd01f
IE
1016 int swapped;
1017 int err = -EFAULT;
6bdb913f
HE
1018 unsigned long mmun_start; /* For mmu_notifiers */
1019 unsigned long mmun_end; /* For mmu_notifiers */
31dbd01f 1020
421ec457
SF
1021 addr = page_address_in_vma(page, vma);
1022 if (addr == -EFAULT)
31dbd01f
IE
1023 goto out;
1024
29ad768c 1025 BUG_ON(PageTransCompound(page));
6bdb913f 1026
421ec457
SF
1027 mmun_start = addr;
1028 mmun_end = addr + PAGE_SIZE;
6bdb913f
HE
1029 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1030
421ec457
SF
1031 ptep = page_check_address(page, mm, addr, &ptl, 0);
1032 if (!ptep)
6bdb913f 1033 goto out_mn;
31dbd01f 1034
737f3a90
AK
1035 if (pte_write(*ptep) || pte_dirty(*ptep) ||
1036 (pte_protnone(*ptep) && pte_savedwrite(*ptep))) {
31dbd01f
IE
1037 pte_t entry;
1038
1039 swapped = PageSwapCache(page);
421ec457 1040 flush_cache_page(vma, addr, page_to_pfn(page));
31dbd01f 1041 /*
25985edc 1042 * Ok this is tricky, when get_user_pages_fast() run it doesn't
31dbd01f
IE
1043 * take any lock, therefore the check that we are going to make
1044 * with the pagecount against the mapcount is racey and
1045 * O_DIRECT can happen right after the check.
1046 * So we clear the pte and flush the tlb before the check
1047 * this assure us that no O_DIRECT can happen after the check
1048 * or in the middle of the check.
1049 */
421ec457 1050 entry = ptep_clear_flush_notify(vma, addr, ptep);
31dbd01f
IE
1051 /*
1052 * Check that no O_DIRECT or similar I/O is in progress on the
1053 * page
1054 */
31e855ea 1055 if (page_mapcount(page) + 1 + swapped != page_count(page)) {
421ec457 1056 set_pte_at(mm, addr, ptep, entry);
31dbd01f
IE
1057 goto out_unlock;
1058 }
4e31635c
HD
1059 if (pte_dirty(entry))
1060 set_page_dirty(page);
737f3a90
AK
1061
1062 if (pte_protnone(entry))
1063 entry = pte_mkclean(pte_clear_savedwrite(entry));
1064 else
1065 entry = pte_mkclean(pte_wrprotect(entry));
421ec457 1066 set_pte_at_notify(mm, addr, ptep, entry);
31dbd01f 1067 }
421ec457 1068 *orig_pte = *ptep;
31dbd01f
IE
1069 err = 0;
1070
1071out_unlock:
421ec457 1072 pte_unmap_unlock(ptep, ptl);
6bdb913f
HE
1073out_mn:
1074 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
31dbd01f
IE
1075out:
1076 return err;
1077}
1078
1079/**
1080 * replace_page - replace page in vma by new ksm page
8dd3557a
HD
1081 * @vma: vma that holds the pte pointing to page
1082 * @page: the page we are replacing by kpage
1083 * @kpage: the ksm page we replace page by
31dbd01f
IE
1084 * @orig_pte: the original value of the pte
1085 *
1086 * Returns 0 on success, -EFAULT on failure.
1087 */
8dd3557a
HD
1088static int replace_page(struct vm_area_struct *vma, struct page *page,
1089 struct page *kpage, pte_t orig_pte)
31dbd01f
IE
1090{
1091 struct mm_struct *mm = vma->vm_mm;
31dbd01f
IE
1092 pmd_t *pmd;
1093 pte_t *ptep;
fa2aa0fc 1094 pte_t newpte;
31dbd01f
IE
1095 spinlock_t *ptl;
1096 unsigned long addr;
31dbd01f 1097 int err = -EFAULT;
6bdb913f
HE
1098 unsigned long mmun_start; /* For mmu_notifiers */
1099 unsigned long mmun_end; /* For mmu_notifiers */
31dbd01f 1100
8dd3557a 1101 addr = page_address_in_vma(page, vma);
31dbd01f
IE
1102 if (addr == -EFAULT)
1103 goto out;
1104
6219049a
BL
1105 pmd = mm_find_pmd(mm, addr);
1106 if (!pmd)
31dbd01f 1107 goto out;
31dbd01f 1108
6bdb913f
HE
1109 mmun_start = addr;
1110 mmun_end = addr + PAGE_SIZE;
1111 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
1112
31dbd01f
IE
1113 ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
1114 if (!pte_same(*ptep, orig_pte)) {
1115 pte_unmap_unlock(ptep, ptl);
6bdb913f 1116 goto out_mn;
31dbd01f
IE
1117 }
1118
fa2aa0fc
CI
1119 /*
1120 * No need to check ksm_use_zero_pages here: we can only have a
1121 * zero_page here if ksm_use_zero_pages was enabled alreaady.
1122 */
1123 if (!is_zero_pfn(page_to_pfn(kpage))) {
1124 get_page(kpage);
1125 page_add_anon_rmap(kpage, vma, addr, false);
1126 newpte = mk_pte(kpage, vma->vm_page_prot);
1127 } else {
1128 newpte = pte_mkspecial(pfn_pte(page_to_pfn(kpage),
1129 vma->vm_page_prot));
1130 }
31dbd01f
IE
1131
1132 flush_cache_page(vma, addr, pte_pfn(*ptep));
34ee645e 1133 ptep_clear_flush_notify(vma, addr, ptep);
fa2aa0fc 1134 set_pte_at_notify(mm, addr, ptep, newpte);
31dbd01f 1135
d281ee61 1136 page_remove_rmap(page, false);
ae52a2ad
HD
1137 if (!page_mapped(page))
1138 try_to_free_swap(page);
8dd3557a 1139 put_page(page);
31dbd01f
IE
1140
1141 pte_unmap_unlock(ptep, ptl);
1142 err = 0;
6bdb913f
HE
1143out_mn:
1144 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
31dbd01f
IE
1145out:
1146 return err;
1147}
1148
1149/*
1150 * try_to_merge_one_page - take two pages and merge them into one
8dd3557a
HD
1151 * @vma: the vma that holds the pte pointing to page
1152 * @page: the PageAnon page that we want to replace with kpage
80e14822
HD
1153 * @kpage: the PageKsm page that we want to map instead of page,
1154 * or NULL the first time when we want to use page as kpage.
31dbd01f
IE
1155 *
1156 * This function returns 0 if the pages were merged, -EFAULT otherwise.
1157 */
1158static int try_to_merge_one_page(struct vm_area_struct *vma,
8dd3557a 1159 struct page *page, struct page *kpage)
31dbd01f
IE
1160{
1161 pte_t orig_pte = __pte(0);
1162 int err = -EFAULT;
1163
db114b83
HD
1164 if (page == kpage) /* ksm page forked */
1165 return 0;
1166
8dd3557a 1167 if (!PageAnon(page))
31dbd01f
IE
1168 goto out;
1169
31dbd01f
IE
1170 /*
1171 * We need the page lock to read a stable PageSwapCache in
1172 * write_protect_page(). We use trylock_page() instead of
1173 * lock_page() because we don't want to wait here - we
1174 * prefer to continue scanning and merging different pages,
1175 * then come back to this page when it is unlocked.
1176 */
8dd3557a 1177 if (!trylock_page(page))
31e855ea 1178 goto out;
f765f540
KS
1179
1180 if (PageTransCompound(page)) {
1181 err = split_huge_page(page);
1182 if (err)
1183 goto out_unlock;
1184 }
1185
31dbd01f
IE
1186 /*
1187 * If this anonymous page is mapped only here, its pte may need
1188 * to be write-protected. If it's mapped elsewhere, all of its
1189 * ptes are necessarily already write-protected. But in either
1190 * case, we need to lock and check page_count is not raised.
1191 */
80e14822
HD
1192 if (write_protect_page(vma, page, &orig_pte) == 0) {
1193 if (!kpage) {
1194 /*
1195 * While we hold page lock, upgrade page from
1196 * PageAnon+anon_vma to PageKsm+NULL stable_node:
1197 * stable_tree_insert() will update stable_node.
1198 */
1199 set_page_stable_node(page, NULL);
1200 mark_page_accessed(page);
337ed7eb
MK
1201 /*
1202 * Page reclaim just frees a clean page with no dirty
1203 * ptes: make sure that the ksm page would be swapped.
1204 */
1205 if (!PageDirty(page))
1206 SetPageDirty(page);
80e14822
HD
1207 err = 0;
1208 } else if (pages_identical(page, kpage))
1209 err = replace_page(vma, page, kpage, orig_pte);
1210 }
31dbd01f 1211
80e14822 1212 if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
73848b46 1213 munlock_vma_page(page);
5ad64688
HD
1214 if (!PageMlocked(kpage)) {
1215 unlock_page(page);
5ad64688
HD
1216 lock_page(kpage);
1217 mlock_vma_page(kpage);
1218 page = kpage; /* for final unlock */
1219 }
1220 }
73848b46 1221
f765f540 1222out_unlock:
8dd3557a 1223 unlock_page(page);
31dbd01f
IE
1224out:
1225 return err;
1226}
1227
81464e30
HD
1228/*
1229 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
1230 * but no new kernel page is allocated: kpage must already be a ksm page.
8dd3557a
HD
1231 *
1232 * This function returns 0 if the pages were merged, -EFAULT otherwise.
81464e30 1233 */
8dd3557a
HD
1234static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
1235 struct page *page, struct page *kpage)
81464e30 1236{
8dd3557a 1237 struct mm_struct *mm = rmap_item->mm;
81464e30
HD
1238 struct vm_area_struct *vma;
1239 int err = -EFAULT;
1240
8dd3557a 1241 down_read(&mm->mmap_sem);
85c6e8dd
AA
1242 vma = find_mergeable_vma(mm, rmap_item->address);
1243 if (!vma)
81464e30
HD
1244 goto out;
1245
8dd3557a 1246 err = try_to_merge_one_page(vma, page, kpage);
db114b83
HD
1247 if (err)
1248 goto out;
1249
bc56620b
HD
1250 /* Unstable nid is in union with stable anon_vma: remove first */
1251 remove_rmap_item_from_tree(rmap_item);
1252
db114b83 1253 /* Must get reference to anon_vma while still holding mmap_sem */
9e60109f
PZ
1254 rmap_item->anon_vma = vma->anon_vma;
1255 get_anon_vma(vma->anon_vma);
81464e30 1256out:
8dd3557a 1257 up_read(&mm->mmap_sem);
81464e30
HD
1258 return err;
1259}
1260
31dbd01f
IE
1261/*
1262 * try_to_merge_two_pages - take two identical pages and prepare them
1263 * to be merged into one page.
1264 *
8dd3557a
HD
1265 * This function returns the kpage if we successfully merged two identical
1266 * pages into one ksm page, NULL otherwise.
31dbd01f 1267 *
80e14822 1268 * Note that this function upgrades page to ksm page: if one of the pages
31dbd01f
IE
1269 * is already a ksm page, try_to_merge_with_ksm_page should be used.
1270 */
8dd3557a
HD
1271static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
1272 struct page *page,
1273 struct rmap_item *tree_rmap_item,
1274 struct page *tree_page)
31dbd01f 1275{
80e14822 1276 int err;
31dbd01f 1277
80e14822 1278 err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
31dbd01f 1279 if (!err) {
8dd3557a 1280 err = try_to_merge_with_ksm_page(tree_rmap_item,
80e14822 1281 tree_page, page);
31dbd01f 1282 /*
81464e30
HD
1283 * If that fails, we have a ksm page with only one pte
1284 * pointing to it: so break it.
31dbd01f 1285 */
4035c07a 1286 if (err)
8dd3557a 1287 break_cow(rmap_item);
31dbd01f 1288 }
80e14822 1289 return err ? NULL : page;
31dbd01f
IE
1290}
1291
7253473c
AA
1292static __always_inline
1293bool __is_page_sharing_candidate(struct stable_node *stable_node, int offset)
1294{
1295 VM_BUG_ON(stable_node->rmap_hlist_len < 0);
1296 /*
1297 * Check that at least one mapping still exists, otherwise
1298 * there's no much point to merge and share with this
1299 * stable_node, as the underlying tree_page of the other
1300 * sharer is going to be freed soon.
1301 */
1302 return stable_node->rmap_hlist_len &&
1303 stable_node->rmap_hlist_len + offset < ksm_max_page_sharing;
1304}
1305
1306static __always_inline
1307bool is_page_sharing_candidate(struct stable_node *stable_node)
1308{
1309 return __is_page_sharing_candidate(stable_node, 0);
1310}
1311
1312static struct stable_node *stable_node_dup(struct stable_node *stable_node,
1313 struct page **tree_page,
1314 struct rb_root *root,
1315 bool prune_stale_stable_nodes)
1316{
1317 struct stable_node *dup, *found = NULL;
1318 struct hlist_node *hlist_safe;
1319 struct page *_tree_page;
1320 int nr = 0;
1321 int found_rmap_hlist_len;
1322
1323 if (!prune_stale_stable_nodes ||
1324 time_before(jiffies, stable_node->chain_prune_time +
1325 msecs_to_jiffies(
1326 ksm_stable_node_chains_prune_millisecs)))
1327 prune_stale_stable_nodes = false;
1328 else
1329 stable_node->chain_prune_time = jiffies;
1330
1331 hlist_for_each_entry_safe(dup, hlist_safe,
1332 &stable_node->hlist, hlist_dup) {
1333 cond_resched();
1334 /*
1335 * We must walk all stable_node_dup to prune the stale
1336 * stable nodes during lookup.
1337 *
1338 * get_ksm_page can drop the nodes from the
1339 * stable_node->hlist if they point to freed pages
1340 * (that's why we do a _safe walk). The "dup"
1341 * stable_node parameter itself will be freed from
1342 * under us if it returns NULL.
1343 */
1344 _tree_page = get_ksm_page(dup, false);
1345 if (!_tree_page)
1346 continue;
1347 nr += 1;
1348 if (is_page_sharing_candidate(dup)) {
1349 if (!found ||
1350 dup->rmap_hlist_len > found_rmap_hlist_len) {
1351 if (found)
1352 put_page(*tree_page);
1353 found = dup;
1354 found_rmap_hlist_len = found->rmap_hlist_len;
1355 *tree_page = _tree_page;
1356
1357 if (!prune_stale_stable_nodes)
1358 break;
1359 /* skip put_page */
1360 continue;
1361 }
1362 }
1363 put_page(_tree_page);
1364 }
1365
1366 /*
1367 * nr is relevant only if prune_stale_stable_nodes is true,
1368 * otherwise we may break the loop at nr == 1 even if there
1369 * are multiple entries.
1370 */
1371 if (prune_stale_stable_nodes && found) {
1372 if (nr == 1) {
1373 /*
1374 * If there's not just one entry it would
1375 * corrupt memory, better BUG_ON. In KSM
1376 * context with no lock held it's not even
1377 * fatal.
1378 */
1379 BUG_ON(stable_node->hlist.first->next);
1380
1381 /*
1382 * There's just one entry and it is below the
1383 * deduplication limit so drop the chain.
1384 */
1385 rb_replace_node(&stable_node->node, &found->node,
1386 root);
1387 free_stable_node(stable_node);
1388 ksm_stable_node_chains--;
1389 ksm_stable_node_dups--;
1390 } else if (__is_page_sharing_candidate(found, 1)) {
1391 /*
1392 * Refile our candidate at the head
1393 * after the prune if our candidate
1394 * can accept one more future sharing
1395 * in addition to the one underway.
1396 */
1397 hlist_del(&found->hlist_dup);
1398 hlist_add_head(&found->hlist_dup,
1399 &stable_node->hlist);
1400 }
1401 }
1402
1403 return found;
1404}
1405
1406static struct stable_node *stable_node_dup_any(struct stable_node *stable_node,
1407 struct rb_root *root)
1408{
1409 if (!is_stable_node_chain(stable_node))
1410 return stable_node;
1411 if (hlist_empty(&stable_node->hlist)) {
1412 free_stable_node_chain(stable_node, root);
1413 return NULL;
1414 }
1415 return hlist_entry(stable_node->hlist.first,
1416 typeof(*stable_node), hlist_dup);
1417}
1418
1419static struct stable_node *__stable_node_chain(struct stable_node *stable_node,
1420 struct page **tree_page,
1421 struct rb_root *root,
1422 bool prune_stale_stable_nodes)
1423{
1424 if (!is_stable_node_chain(stable_node)) {
1425 if (is_page_sharing_candidate(stable_node)) {
1426 *tree_page = get_ksm_page(stable_node, false);
1427 return stable_node;
1428 }
1429 return NULL;
1430 }
1431 return stable_node_dup(stable_node, tree_page, root,
1432 prune_stale_stable_nodes);
1433}
1434
1435static __always_inline struct stable_node *chain_prune(struct stable_node *s_n,
1436 struct page **t_p,
1437 struct rb_root *root)
1438{
1439 return __stable_node_chain(s_n, t_p, root, true);
1440}
1441
1442static __always_inline struct stable_node *chain(struct stable_node *s_n,
1443 struct page **t_p,
1444 struct rb_root *root)
1445{
1446 return __stable_node_chain(s_n, t_p, root, false);
1447}
1448
31dbd01f 1449/*
8dd3557a 1450 * stable_tree_search - search for page inside the stable tree
31dbd01f
IE
1451 *
1452 * This function checks if there is a page inside the stable tree
1453 * with identical content to the page that we are scanning right now.
1454 *
7b6ba2c7 1455 * This function returns the stable tree node of identical content if found,
31dbd01f
IE
1456 * NULL otherwise.
1457 */
62b61f61 1458static struct page *stable_tree_search(struct page *page)
31dbd01f 1459{
90bd6fd3 1460 int nid;
ef53d16c 1461 struct rb_root *root;
4146d2d6
HD
1462 struct rb_node **new;
1463 struct rb_node *parent;
7253473c 1464 struct stable_node *stable_node, *stable_node_dup, *stable_node_any;
4146d2d6 1465 struct stable_node *page_node;
31dbd01f 1466
4146d2d6
HD
1467 page_node = page_stable_node(page);
1468 if (page_node && page_node->head != &migrate_nodes) {
1469 /* ksm page forked */
08beca44 1470 get_page(page);
62b61f61 1471 return page;
08beca44
HD
1472 }
1473
90bd6fd3 1474 nid = get_kpfn_nid(page_to_pfn(page));
ef53d16c 1475 root = root_stable_tree + nid;
4146d2d6 1476again:
ef53d16c 1477 new = &root->rb_node;
4146d2d6 1478 parent = NULL;
90bd6fd3 1479
4146d2d6 1480 while (*new) {
4035c07a 1481 struct page *tree_page;
31dbd01f
IE
1482 int ret;
1483
08beca44 1484 cond_resched();
4146d2d6 1485 stable_node = rb_entry(*new, struct stable_node, node);
7253473c
AA
1486 stable_node_any = NULL;
1487 stable_node_dup = chain_prune(stable_node, &tree_page, root);
1488 if (!stable_node_dup) {
1489 /*
1490 * Either all stable_node dups were full in
1491 * this stable_node chain, or this chain was
1492 * empty and should be rb_erased.
1493 */
1494 stable_node_any = stable_node_dup_any(stable_node,
1495 root);
1496 if (!stable_node_any) {
1497 /* rb_erase just run */
1498 goto again;
1499 }
1500 /*
1501 * Take any of the stable_node dups page of
1502 * this stable_node chain to let the tree walk
1503 * continue. All KSM pages belonging to the
1504 * stable_node dups in a stable_node chain
1505 * have the same content and they're
1506 * wrprotected at all times. Any will work
1507 * fine to continue the walk.
1508 */
1509 tree_page = get_ksm_page(stable_node_any, false);
1510 }
1511 VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
f2e5ff85
AA
1512 if (!tree_page) {
1513 /*
1514 * If we walked over a stale stable_node,
1515 * get_ksm_page() will call rb_erase() and it
1516 * may rebalance the tree from under us. So
1517 * restart the search from scratch. Returning
1518 * NULL would be safe too, but we'd generate
1519 * false negative insertions just because some
1520 * stable_node was stale.
1521 */
1522 goto again;
1523 }
31dbd01f 1524
4035c07a 1525 ret = memcmp_pages(page, tree_page);
c8d6553b 1526 put_page(tree_page);
31dbd01f 1527
4146d2d6 1528 parent = *new;
c8d6553b 1529 if (ret < 0)
4146d2d6 1530 new = &parent->rb_left;
c8d6553b 1531 else if (ret > 0)
4146d2d6 1532 new = &parent->rb_right;
c8d6553b 1533 else {
7253473c
AA
1534 if (page_node) {
1535 VM_BUG_ON(page_node->head != &migrate_nodes);
1536 /*
1537 * Test if the migrated page should be merged
1538 * into a stable node dup. If the mapcount is
1539 * 1 we can migrate it with another KSM page
1540 * without adding it to the chain.
1541 */
1542 if (page_mapcount(page) > 1)
1543 goto chain_append;
1544 }
1545
1546 if (!stable_node_dup) {
1547 /*
1548 * If the stable_node is a chain and
1549 * we got a payload match in memcmp
1550 * but we cannot merge the scanned
1551 * page in any of the existing
1552 * stable_node dups because they're
1553 * all full, we need to wait the
1554 * scanned page to find itself a match
1555 * in the unstable tree to create a
1556 * brand new KSM page to add later to
1557 * the dups of this stable_node.
1558 */
1559 return NULL;
1560 }
1561
c8d6553b
HD
1562 /*
1563 * Lock and unlock the stable_node's page (which
1564 * might already have been migrated) so that page
1565 * migration is sure to notice its raised count.
1566 * It would be more elegant to return stable_node
1567 * than kpage, but that involves more changes.
1568 */
7253473c
AA
1569 tree_page = get_ksm_page(stable_node_dup, true);
1570 if (unlikely(!tree_page))
1571 /*
1572 * The tree may have been rebalanced,
1573 * so re-evaluate parent and new.
1574 */
4146d2d6 1575 goto again;
7253473c
AA
1576 unlock_page(tree_page);
1577
1578 if (get_kpfn_nid(stable_node_dup->kpfn) !=
1579 NUMA(stable_node_dup->nid)) {
1580 put_page(tree_page);
1581 goto replace;
1582 }
1583 return tree_page;
c8d6553b 1584 }
31dbd01f
IE
1585 }
1586
4146d2d6
HD
1587 if (!page_node)
1588 return NULL;
1589
1590 list_del(&page_node->list);
1591 DO_NUMA(page_node->nid = nid);
1592 rb_link_node(&page_node->node, parent, new);
ef53d16c 1593 rb_insert_color(&page_node->node, root);
7253473c
AA
1594out:
1595 if (is_page_sharing_candidate(page_node)) {
1596 get_page(page);
1597 return page;
1598 } else
1599 return NULL;
4146d2d6
HD
1600
1601replace:
7253473c
AA
1602 if (stable_node_dup == stable_node) {
1603 /* there is no chain */
1604 if (page_node) {
1605 VM_BUG_ON(page_node->head != &migrate_nodes);
1606 list_del(&page_node->list);
1607 DO_NUMA(page_node->nid = nid);
1608 rb_replace_node(&stable_node->node, &page_node->node,
1609 root);
1610 if (is_page_sharing_candidate(page_node))
1611 get_page(page);
1612 else
1613 page = NULL;
1614 } else {
1615 rb_erase(&stable_node->node, root);
1616 page = NULL;
1617 }
4146d2d6 1618 } else {
7253473c
AA
1619 VM_BUG_ON(!is_stable_node_chain(stable_node));
1620 __stable_node_dup_del(stable_node_dup);
1621 if (page_node) {
1622 VM_BUG_ON(page_node->head != &migrate_nodes);
1623 list_del(&page_node->list);
1624 DO_NUMA(page_node->nid = nid);
1625 stable_node_chain_add_dup(page_node, stable_node);
1626 if (is_page_sharing_candidate(page_node))
1627 get_page(page);
1628 else
1629 page = NULL;
1630 } else {
1631 page = NULL;
1632 }
4146d2d6 1633 }
7253473c
AA
1634 stable_node_dup->head = &migrate_nodes;
1635 list_add(&stable_node_dup->list, stable_node_dup->head);
4146d2d6 1636 return page;
7253473c
AA
1637
1638chain_append:
1639 /* stable_node_dup could be null if it reached the limit */
1640 if (!stable_node_dup)
1641 stable_node_dup = stable_node_any;
1642 if (stable_node_dup == stable_node) {
1643 /* chain is missing so create it */
1644 stable_node = alloc_stable_node_chain(stable_node_dup,
1645 root);
1646 if (!stable_node)
1647 return NULL;
1648 }
1649 /*
1650 * Add this stable_node dup that was
1651 * migrated to the stable_node chain
1652 * of the current nid for this page
1653 * content.
1654 */
1655 VM_BUG_ON(page_node->head != &migrate_nodes);
1656 list_del(&page_node->list);
1657 DO_NUMA(page_node->nid = nid);
1658 stable_node_chain_add_dup(page_node, stable_node);
1659 goto out;
31dbd01f
IE
1660}
1661
1662/*
e850dcf5 1663 * stable_tree_insert - insert stable tree node pointing to new ksm page
31dbd01f
IE
1664 * into the stable tree.
1665 *
7b6ba2c7
HD
1666 * This function returns the stable tree node just allocated on success,
1667 * NULL otherwise.
31dbd01f 1668 */
7b6ba2c7 1669static struct stable_node *stable_tree_insert(struct page *kpage)
31dbd01f 1670{
90bd6fd3
PH
1671 int nid;
1672 unsigned long kpfn;
ef53d16c 1673 struct rb_root *root;
90bd6fd3 1674 struct rb_node **new;
f2e5ff85 1675 struct rb_node *parent;
7253473c
AA
1676 struct stable_node *stable_node, *stable_node_dup, *stable_node_any;
1677 bool need_chain = false;
31dbd01f 1678
90bd6fd3
PH
1679 kpfn = page_to_pfn(kpage);
1680 nid = get_kpfn_nid(kpfn);
ef53d16c 1681 root = root_stable_tree + nid;
f2e5ff85
AA
1682again:
1683 parent = NULL;
ef53d16c 1684 new = &root->rb_node;
90bd6fd3 1685
31dbd01f 1686 while (*new) {
4035c07a 1687 struct page *tree_page;
31dbd01f
IE
1688 int ret;
1689
08beca44 1690 cond_resched();
7b6ba2c7 1691 stable_node = rb_entry(*new, struct stable_node, node);
7253473c
AA
1692 stable_node_any = NULL;
1693 stable_node_dup = chain(stable_node, &tree_page, root);
1694 if (!stable_node_dup) {
1695 /*
1696 * Either all stable_node dups were full in
1697 * this stable_node chain, or this chain was
1698 * empty and should be rb_erased.
1699 */
1700 stable_node_any = stable_node_dup_any(stable_node,
1701 root);
1702 if (!stable_node_any) {
1703 /* rb_erase just run */
1704 goto again;
1705 }
1706 /*
1707 * Take any of the stable_node dups page of
1708 * this stable_node chain to let the tree walk
1709 * continue. All KSM pages belonging to the
1710 * stable_node dups in a stable_node chain
1711 * have the same content and they're
1712 * wrprotected at all times. Any will work
1713 * fine to continue the walk.
1714 */
1715 tree_page = get_ksm_page(stable_node_any, false);
1716 }
1717 VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
f2e5ff85
AA
1718 if (!tree_page) {
1719 /*
1720 * If we walked over a stale stable_node,
1721 * get_ksm_page() will call rb_erase() and it
1722 * may rebalance the tree from under us. So
1723 * restart the search from scratch. Returning
1724 * NULL would be safe too, but we'd generate
1725 * false negative insertions just because some
1726 * stable_node was stale.
1727 */
1728 goto again;
1729 }
31dbd01f 1730
4035c07a
HD
1731 ret = memcmp_pages(kpage, tree_page);
1732 put_page(tree_page);
31dbd01f
IE
1733
1734 parent = *new;
1735 if (ret < 0)
1736 new = &parent->rb_left;
1737 else if (ret > 0)
1738 new = &parent->rb_right;
1739 else {
7253473c
AA
1740 need_chain = true;
1741 break;
31dbd01f
IE
1742 }
1743 }
1744
7253473c
AA
1745 stable_node_dup = alloc_stable_node();
1746 if (!stable_node_dup)
7b6ba2c7 1747 return NULL;
31dbd01f 1748
7253473c
AA
1749 INIT_HLIST_HEAD(&stable_node_dup->hlist);
1750 stable_node_dup->kpfn = kpfn;
1751 set_page_stable_node(kpage, stable_node_dup);
1752 stable_node_dup->rmap_hlist_len = 0;
1753 DO_NUMA(stable_node_dup->nid = nid);
1754 if (!need_chain) {
1755 rb_link_node(&stable_node_dup->node, parent, new);
1756 rb_insert_color(&stable_node_dup->node, root);
1757 } else {
1758 if (!is_stable_node_chain(stable_node)) {
1759 struct stable_node *orig = stable_node;
1760 /* chain is missing so create it */
1761 stable_node = alloc_stable_node_chain(orig, root);
1762 if (!stable_node) {
1763 free_stable_node(stable_node_dup);
1764 return NULL;
1765 }
1766 }
1767 stable_node_chain_add_dup(stable_node_dup, stable_node);
1768 }
08beca44 1769
7253473c 1770 return stable_node_dup;
31dbd01f
IE
1771}
1772
1773/*
8dd3557a
HD
1774 * unstable_tree_search_insert - search for identical page,
1775 * else insert rmap_item into the unstable tree.
31dbd01f
IE
1776 *
1777 * This function searches for a page in the unstable tree identical to the
1778 * page currently being scanned; and if no identical page is found in the
1779 * tree, we insert rmap_item as a new object into the unstable tree.
1780 *
1781 * This function returns pointer to rmap_item found to be identical
1782 * to the currently scanned page, NULL otherwise.
1783 *
1784 * This function does both searching and inserting, because they share
1785 * the same walking algorithm in an rbtree.
1786 */
8dd3557a
HD
1787static
1788struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
1789 struct page *page,
1790 struct page **tree_pagep)
31dbd01f 1791{
90bd6fd3
PH
1792 struct rb_node **new;
1793 struct rb_root *root;
31dbd01f 1794 struct rb_node *parent = NULL;
90bd6fd3
PH
1795 int nid;
1796
1797 nid = get_kpfn_nid(page_to_pfn(page));
ef53d16c 1798 root = root_unstable_tree + nid;
90bd6fd3 1799 new = &root->rb_node;
31dbd01f
IE
1800
1801 while (*new) {
1802 struct rmap_item *tree_rmap_item;
8dd3557a 1803 struct page *tree_page;
31dbd01f
IE
1804 int ret;
1805
d178f27f 1806 cond_resched();
31dbd01f 1807 tree_rmap_item = rb_entry(*new, struct rmap_item, node);
8dd3557a 1808 tree_page = get_mergeable_page(tree_rmap_item);
c8f95ed1 1809 if (!tree_page)
31dbd01f
IE
1810 return NULL;
1811
1812 /*
8dd3557a 1813 * Don't substitute a ksm page for a forked page.
31dbd01f 1814 */
8dd3557a
HD
1815 if (page == tree_page) {
1816 put_page(tree_page);
31dbd01f
IE
1817 return NULL;
1818 }
1819
8dd3557a 1820 ret = memcmp_pages(page, tree_page);
31dbd01f
IE
1821
1822 parent = *new;
1823 if (ret < 0) {
8dd3557a 1824 put_page(tree_page);
31dbd01f
IE
1825 new = &parent->rb_left;
1826 } else if (ret > 0) {
8dd3557a 1827 put_page(tree_page);
31dbd01f 1828 new = &parent->rb_right;
b599cbdf
HD
1829 } else if (!ksm_merge_across_nodes &&
1830 page_to_nid(tree_page) != nid) {
1831 /*
1832 * If tree_page has been migrated to another NUMA node,
1833 * it will be flushed out and put in the right unstable
1834 * tree next time: only merge with it when across_nodes.
1835 */
1836 put_page(tree_page);
1837 return NULL;
31dbd01f 1838 } else {
8dd3557a 1839 *tree_pagep = tree_page;
31dbd01f
IE
1840 return tree_rmap_item;
1841 }
1842 }
1843
7b6ba2c7 1844 rmap_item->address |= UNSTABLE_FLAG;
31dbd01f 1845 rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
e850dcf5 1846 DO_NUMA(rmap_item->nid = nid);
31dbd01f 1847 rb_link_node(&rmap_item->node, parent, new);
90bd6fd3 1848 rb_insert_color(&rmap_item->node, root);
31dbd01f 1849
473b0ce4 1850 ksm_pages_unshared++;
31dbd01f
IE
1851 return NULL;
1852}
1853
1854/*
1855 * stable_tree_append - add another rmap_item to the linked list of
1856 * rmap_items hanging off a given node of the stable tree, all sharing
1857 * the same ksm page.
1858 */
1859static void stable_tree_append(struct rmap_item *rmap_item,
7253473c
AA
1860 struct stable_node *stable_node,
1861 bool max_page_sharing_bypass)
31dbd01f 1862{
7253473c
AA
1863 /*
1864 * rmap won't find this mapping if we don't insert the
1865 * rmap_item in the right stable_node
1866 * duplicate. page_migration could break later if rmap breaks,
1867 * so we can as well crash here. We really need to check for
1868 * rmap_hlist_len == STABLE_NODE_CHAIN, but we can as well check
1869 * for other negative values as an undeflow if detected here
1870 * for the first time (and not when decreasing rmap_hlist_len)
1871 * would be sign of memory corruption in the stable_node.
1872 */
1873 BUG_ON(stable_node->rmap_hlist_len < 0);
1874
1875 stable_node->rmap_hlist_len++;
1876 if (!max_page_sharing_bypass)
1877 /* possibly non fatal but unexpected overflow, only warn */
1878 WARN_ON_ONCE(stable_node->rmap_hlist_len >
1879 ksm_max_page_sharing);
1880
7b6ba2c7 1881 rmap_item->head = stable_node;
31dbd01f 1882 rmap_item->address |= STABLE_FLAG;
7b6ba2c7 1883 hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
e178dfde 1884
7b6ba2c7
HD
1885 if (rmap_item->hlist.next)
1886 ksm_pages_sharing++;
1887 else
1888 ksm_pages_shared++;
31dbd01f
IE
1889}
1890
1891/*
81464e30
HD
1892 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1893 * if not, compare checksum to previous and if it's the same, see if page can
1894 * be inserted into the unstable tree, or merged with a page already there and
1895 * both transferred to the stable tree.
31dbd01f
IE
1896 *
1897 * @page: the page that we are searching identical page to.
1898 * @rmap_item: the reverse mapping into the virtual address of this page
1899 */
1900static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
1901{
31dbd01f 1902 struct rmap_item *tree_rmap_item;
8dd3557a 1903 struct page *tree_page = NULL;
7b6ba2c7 1904 struct stable_node *stable_node;
8dd3557a 1905 struct page *kpage;
31dbd01f
IE
1906 unsigned int checksum;
1907 int err;
7253473c 1908 bool max_page_sharing_bypass = false;
31dbd01f 1909
4146d2d6
HD
1910 stable_node = page_stable_node(page);
1911 if (stable_node) {
1912 if (stable_node->head != &migrate_nodes &&
7253473c
AA
1913 get_kpfn_nid(READ_ONCE(stable_node->kpfn)) !=
1914 NUMA(stable_node->nid)) {
1915 stable_node_dup_del(stable_node);
4146d2d6
HD
1916 stable_node->head = &migrate_nodes;
1917 list_add(&stable_node->list, stable_node->head);
1918 }
1919 if (stable_node->head != &migrate_nodes &&
1920 rmap_item->head == stable_node)
1921 return;
7253473c
AA
1922 /*
1923 * If it's a KSM fork, allow it to go over the sharing limit
1924 * without warnings.
1925 */
1926 if (!is_page_sharing_candidate(stable_node))
1927 max_page_sharing_bypass = true;
4146d2d6 1928 }
31dbd01f
IE
1929
1930 /* We first start with searching the page inside the stable tree */
62b61f61 1931 kpage = stable_tree_search(page);
4146d2d6
HD
1932 if (kpage == page && rmap_item->head == stable_node) {
1933 put_page(kpage);
1934 return;
1935 }
1936
1937 remove_rmap_item_from_tree(rmap_item);
1938
62b61f61 1939 if (kpage) {
08beca44 1940 err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
31dbd01f
IE
1941 if (!err) {
1942 /*
1943 * The page was successfully merged:
1944 * add its rmap_item to the stable tree.
1945 */
5ad64688 1946 lock_page(kpage);
7253473c
AA
1947 stable_tree_append(rmap_item, page_stable_node(kpage),
1948 max_page_sharing_bypass);
5ad64688 1949 unlock_page(kpage);
31dbd01f 1950 }
8dd3557a 1951 put_page(kpage);
31dbd01f
IE
1952 return;
1953 }
1954
1955 /*
4035c07a
HD
1956 * If the hash value of the page has changed from the last time
1957 * we calculated it, this page is changing frequently: therefore we
1958 * don't want to insert it in the unstable tree, and we don't want
1959 * to waste our time searching for something identical to it there.
31dbd01f
IE
1960 */
1961 checksum = calc_checksum(page);
1962 if (rmap_item->oldchecksum != checksum) {
1963 rmap_item->oldchecksum = checksum;
1964 return;
1965 }
1966
fa2aa0fc
CI
1967 /*
1968 * Same checksum as an empty page. We attempt to merge it with the
1969 * appropriate zero page if the user enabled this via sysfs.
1970 */
1971 if (ksm_use_zero_pages && (checksum == zero_checksum)) {
1972 struct vm_area_struct *vma;
1973
1974 vma = find_mergeable_vma(rmap_item->mm, rmap_item->address);
1975 err = try_to_merge_one_page(vma, page,
1976 ZERO_PAGE(rmap_item->address));
1977 /*
1978 * In case of failure, the page was not really empty, so we
1979 * need to continue. Otherwise we're done.
1980 */
1981 if (!err)
1982 return;
1983 }
8dd3557a
HD
1984 tree_rmap_item =
1985 unstable_tree_search_insert(rmap_item, page, &tree_page);
31dbd01f 1986 if (tree_rmap_item) {
8dd3557a
HD
1987 kpage = try_to_merge_two_pages(rmap_item, page,
1988 tree_rmap_item, tree_page);
1989 put_page(tree_page);
8dd3557a 1990 if (kpage) {
bc56620b
HD
1991 /*
1992 * The pages were successfully merged: insert new
1993 * node in the stable tree and add both rmap_items.
1994 */
5ad64688 1995 lock_page(kpage);
7b6ba2c7
HD
1996 stable_node = stable_tree_insert(kpage);
1997 if (stable_node) {
7253473c
AA
1998 stable_tree_append(tree_rmap_item, stable_node,
1999 false);
2000 stable_tree_append(rmap_item, stable_node,
2001 false);
7b6ba2c7 2002 }
5ad64688 2003 unlock_page(kpage);
7b6ba2c7 2004
31dbd01f
IE
2005 /*
2006 * If we fail to insert the page into the stable tree,
2007 * we will have 2 virtual addresses that are pointing
2008 * to a ksm page left outside the stable tree,
2009 * in which case we need to break_cow on both.
2010 */
7b6ba2c7 2011 if (!stable_node) {
8dd3557a
HD
2012 break_cow(tree_rmap_item);
2013 break_cow(rmap_item);
31dbd01f
IE
2014 }
2015 }
31dbd01f
IE
2016 }
2017}
2018
2019static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
6514d511 2020 struct rmap_item **rmap_list,
31dbd01f
IE
2021 unsigned long addr)
2022{
2023 struct rmap_item *rmap_item;
2024
6514d511
HD
2025 while (*rmap_list) {
2026 rmap_item = *rmap_list;
93d17715 2027 if ((rmap_item->address & PAGE_MASK) == addr)
31dbd01f 2028 return rmap_item;
31dbd01f
IE
2029 if (rmap_item->address > addr)
2030 break;
6514d511 2031 *rmap_list = rmap_item->rmap_list;
31dbd01f 2032 remove_rmap_item_from_tree(rmap_item);
31dbd01f
IE
2033 free_rmap_item(rmap_item);
2034 }
2035
2036 rmap_item = alloc_rmap_item();
2037 if (rmap_item) {
2038 /* It has already been zeroed */
2039 rmap_item->mm = mm_slot->mm;
2040 rmap_item->address = addr;
6514d511
HD
2041 rmap_item->rmap_list = *rmap_list;
2042 *rmap_list = rmap_item;
31dbd01f
IE
2043 }
2044 return rmap_item;
2045}
2046
2047static struct rmap_item *scan_get_next_rmap_item(struct page **page)
2048{
2049 struct mm_struct *mm;
2050 struct mm_slot *slot;
2051 struct vm_area_struct *vma;
2052 struct rmap_item *rmap_item;
90bd6fd3 2053 int nid;
31dbd01f
IE
2054
2055 if (list_empty(&ksm_mm_head.mm_list))
2056 return NULL;
2057
2058 slot = ksm_scan.mm_slot;
2059 if (slot == &ksm_mm_head) {
2919bfd0
HD
2060 /*
2061 * A number of pages can hang around indefinitely on per-cpu
2062 * pagevecs, raised page count preventing write_protect_page
2063 * from merging them. Though it doesn't really matter much,
2064 * it is puzzling to see some stuck in pages_volatile until
2065 * other activity jostles them out, and they also prevented
2066 * LTP's KSM test from succeeding deterministically; so drain
2067 * them here (here rather than on entry to ksm_do_scan(),
2068 * so we don't IPI too often when pages_to_scan is set low).
2069 */
2070 lru_add_drain_all();
2071
4146d2d6
HD
2072 /*
2073 * Whereas stale stable_nodes on the stable_tree itself
2074 * get pruned in the regular course of stable_tree_search(),
2075 * those moved out to the migrate_nodes list can accumulate:
2076 * so prune them once before each full scan.
2077 */
2078 if (!ksm_merge_across_nodes) {
03640418 2079 struct stable_node *stable_node, *next;
4146d2d6
HD
2080 struct page *page;
2081
03640418
GT
2082 list_for_each_entry_safe(stable_node, next,
2083 &migrate_nodes, list) {
4146d2d6
HD
2084 page = get_ksm_page(stable_node, false);
2085 if (page)
2086 put_page(page);
2087 cond_resched();
2088 }
2089 }
2090
ef53d16c 2091 for (nid = 0; nid < ksm_nr_node_ids; nid++)
90bd6fd3 2092 root_unstable_tree[nid] = RB_ROOT;
31dbd01f
IE
2093
2094 spin_lock(&ksm_mmlist_lock);
2095 slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
2096 ksm_scan.mm_slot = slot;
2097 spin_unlock(&ksm_mmlist_lock);
2b472611
HD
2098 /*
2099 * Although we tested list_empty() above, a racing __ksm_exit
2100 * of the last mm on the list may have removed it since then.
2101 */
2102 if (slot == &ksm_mm_head)
2103 return NULL;
31dbd01f
IE
2104next_mm:
2105 ksm_scan.address = 0;
6514d511 2106 ksm_scan.rmap_list = &slot->rmap_list;
31dbd01f
IE
2107 }
2108
2109 mm = slot->mm;
2110 down_read(&mm->mmap_sem);
9ba69294
HD
2111 if (ksm_test_exit(mm))
2112 vma = NULL;
2113 else
2114 vma = find_vma(mm, ksm_scan.address);
2115
2116 for (; vma; vma = vma->vm_next) {
31dbd01f
IE
2117 if (!(vma->vm_flags & VM_MERGEABLE))
2118 continue;
2119 if (ksm_scan.address < vma->vm_start)
2120 ksm_scan.address = vma->vm_start;
2121 if (!vma->anon_vma)
2122 ksm_scan.address = vma->vm_end;
2123
2124 while (ksm_scan.address < vma->vm_end) {
9ba69294
HD
2125 if (ksm_test_exit(mm))
2126 break;
31dbd01f 2127 *page = follow_page(vma, ksm_scan.address, FOLL_GET);
21ae5b01
AA
2128 if (IS_ERR_OR_NULL(*page)) {
2129 ksm_scan.address += PAGE_SIZE;
2130 cond_resched();
2131 continue;
2132 }
f765f540 2133 if (PageAnon(*page)) {
31dbd01f
IE
2134 flush_anon_page(vma, *page, ksm_scan.address);
2135 flush_dcache_page(*page);
2136 rmap_item = get_next_rmap_item(slot,
6514d511 2137 ksm_scan.rmap_list, ksm_scan.address);
31dbd01f 2138 if (rmap_item) {
6514d511
HD
2139 ksm_scan.rmap_list =
2140 &rmap_item->rmap_list;
31dbd01f
IE
2141 ksm_scan.address += PAGE_SIZE;
2142 } else
2143 put_page(*page);
2144 up_read(&mm->mmap_sem);
2145 return rmap_item;
2146 }
21ae5b01 2147 put_page(*page);
31dbd01f
IE
2148 ksm_scan.address += PAGE_SIZE;
2149 cond_resched();
2150 }
2151 }
2152
9ba69294
HD
2153 if (ksm_test_exit(mm)) {
2154 ksm_scan.address = 0;
6514d511 2155 ksm_scan.rmap_list = &slot->rmap_list;
9ba69294 2156 }
31dbd01f
IE
2157 /*
2158 * Nuke all the rmap_items that are above this current rmap:
2159 * because there were no VM_MERGEABLE vmas with such addresses.
2160 */
6514d511 2161 remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
31dbd01f
IE
2162
2163 spin_lock(&ksm_mmlist_lock);
cd551f97
HD
2164 ksm_scan.mm_slot = list_entry(slot->mm_list.next,
2165 struct mm_slot, mm_list);
2166 if (ksm_scan.address == 0) {
2167 /*
2168 * We've completed a full scan of all vmas, holding mmap_sem
2169 * throughout, and found no VM_MERGEABLE: so do the same as
2170 * __ksm_exit does to remove this mm from all our lists now.
9ba69294
HD
2171 * This applies either when cleaning up after __ksm_exit
2172 * (but beware: we can reach here even before __ksm_exit),
2173 * or when all VM_MERGEABLE areas have been unmapped (and
2174 * mmap_sem then protects against race with MADV_MERGEABLE).
cd551f97 2175 */
4ca3a69b 2176 hash_del(&slot->link);
cd551f97 2177 list_del(&slot->mm_list);
9ba69294
HD
2178 spin_unlock(&ksm_mmlist_lock);
2179
cd551f97
HD
2180 free_mm_slot(slot);
2181 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
9ba69294
HD
2182 up_read(&mm->mmap_sem);
2183 mmdrop(mm);
2184 } else {
9ba69294 2185 up_read(&mm->mmap_sem);
7496fea9
ZC
2186 /*
2187 * up_read(&mm->mmap_sem) first because after
2188 * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
2189 * already have been freed under us by __ksm_exit()
2190 * because the "mm_slot" is still hashed and
2191 * ksm_scan.mm_slot doesn't point to it anymore.
2192 */
2193 spin_unlock(&ksm_mmlist_lock);
cd551f97 2194 }
31dbd01f
IE
2195
2196 /* Repeat until we've completed scanning the whole list */
cd551f97 2197 slot = ksm_scan.mm_slot;
31dbd01f
IE
2198 if (slot != &ksm_mm_head)
2199 goto next_mm;
2200
31dbd01f
IE
2201 ksm_scan.seqnr++;
2202 return NULL;
2203}
2204
2205/**
2206 * ksm_do_scan - the ksm scanner main worker function.
2207 * @scan_npages - number of pages we want to scan before we return.
2208 */
2209static void ksm_do_scan(unsigned int scan_npages)
2210{
2211 struct rmap_item *rmap_item;
22eccdd7 2212 struct page *uninitialized_var(page);
31dbd01f 2213
878aee7d 2214 while (scan_npages-- && likely(!freezing(current))) {
31dbd01f
IE
2215 cond_resched();
2216 rmap_item = scan_get_next_rmap_item(&page);
2217 if (!rmap_item)
2218 return;
4146d2d6 2219 cmp_and_merge_page(page, rmap_item);
31dbd01f
IE
2220 put_page(page);
2221 }
2222}
2223
6e158384
HD
2224static int ksmd_should_run(void)
2225{
2226 return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
2227}
2228
31dbd01f
IE
2229static int ksm_scan_thread(void *nothing)
2230{
878aee7d 2231 set_freezable();
339aa624 2232 set_user_nice(current, 5);
31dbd01f
IE
2233
2234 while (!kthread_should_stop()) {
6e158384 2235 mutex_lock(&ksm_thread_mutex);
ef4d43a8 2236 wait_while_offlining();
6e158384 2237 if (ksmd_should_run())
31dbd01f 2238 ksm_do_scan(ksm_thread_pages_to_scan);
6e158384
HD
2239 mutex_unlock(&ksm_thread_mutex);
2240
878aee7d
AA
2241 try_to_freeze();
2242
6e158384 2243 if (ksmd_should_run()) {
23519606
AV
2244 if (ksm_thread_sleep_millisecs >= 1000)
2245 schedule_timeout_interruptible(
2246 msecs_to_jiffies(round_jiffies_relative(ksm_thread_sleep_millisecs)));
2247 else
2248 schedule_timeout_interruptible(
2249 msecs_to_jiffies(ksm_thread_sleep_millisecs));
31dbd01f 2250 } else {
878aee7d 2251 wait_event_freezable(ksm_thread_wait,
6e158384 2252 ksmd_should_run() || kthread_should_stop());
31dbd01f
IE
2253 }
2254 }
2255 return 0;
2256}
2257
f8af4da3
HD
2258int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
2259 unsigned long end, int advice, unsigned long *vm_flags)
2260{
2261 struct mm_struct *mm = vma->vm_mm;
d952b791 2262 int err;
f8af4da3
HD
2263
2264 switch (advice) {
2265 case MADV_MERGEABLE:
2266 /*
2267 * Be somewhat over-protective for now!
2268 */
2269 if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
2270 VM_PFNMAP | VM_IO | VM_DONTEXPAND |
0661a336 2271 VM_HUGETLB | VM_MIXEDMAP))
f8af4da3
HD
2272 return 0; /* just ignore the advice */
2273
cc2383ec
KK
2274#ifdef VM_SAO
2275 if (*vm_flags & VM_SAO)
2276 return 0;
2277#endif
2278
d952b791
HD
2279 if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
2280 err = __ksm_enter(mm);
2281 if (err)
2282 return err;
2283 }
f8af4da3
HD
2284
2285 *vm_flags |= VM_MERGEABLE;
2286 break;
2287
2288 case MADV_UNMERGEABLE:
2289 if (!(*vm_flags & VM_MERGEABLE))
2290 return 0; /* just ignore the advice */
2291
d952b791
HD
2292 if (vma->anon_vma) {
2293 err = unmerge_ksm_pages(vma, start, end);
2294 if (err)
2295 return err;
2296 }
f8af4da3
HD
2297
2298 *vm_flags &= ~VM_MERGEABLE;
2299 break;
2300 }
2301
2302 return 0;
2303}
2304
2305int __ksm_enter(struct mm_struct *mm)
2306{
6e158384
HD
2307 struct mm_slot *mm_slot;
2308 int needs_wakeup;
2309
2310 mm_slot = alloc_mm_slot();
31dbd01f
IE
2311 if (!mm_slot)
2312 return -ENOMEM;
2313
6e158384
HD
2314 /* Check ksm_run too? Would need tighter locking */
2315 needs_wakeup = list_empty(&ksm_mm_head.mm_list);
2316
31dbd01f
IE
2317 spin_lock(&ksm_mmlist_lock);
2318 insert_to_mm_slots_hash(mm, mm_slot);
2319 /*
cbf86cfe
HD
2320 * When KSM_RUN_MERGE (or KSM_RUN_STOP),
2321 * insert just behind the scanning cursor, to let the area settle
31dbd01f
IE
2322 * down a little; when fork is followed by immediate exec, we don't
2323 * want ksmd to waste time setting up and tearing down an rmap_list.
cbf86cfe
HD
2324 *
2325 * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
2326 * scanning cursor, otherwise KSM pages in newly forked mms will be
2327 * missed: then we might as well insert at the end of the list.
31dbd01f 2328 */
cbf86cfe
HD
2329 if (ksm_run & KSM_RUN_UNMERGE)
2330 list_add_tail(&mm_slot->mm_list, &ksm_mm_head.mm_list);
2331 else
2332 list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
31dbd01f
IE
2333 spin_unlock(&ksm_mmlist_lock);
2334
f8af4da3 2335 set_bit(MMF_VM_MERGEABLE, &mm->flags);
9ba69294 2336 atomic_inc(&mm->mm_count);
6e158384
HD
2337
2338 if (needs_wakeup)
2339 wake_up_interruptible(&ksm_thread_wait);
2340
f8af4da3
HD
2341 return 0;
2342}
2343
1c2fb7a4 2344void __ksm_exit(struct mm_struct *mm)
f8af4da3 2345{
cd551f97 2346 struct mm_slot *mm_slot;
9ba69294 2347 int easy_to_free = 0;
cd551f97 2348
31dbd01f 2349 /*
9ba69294
HD
2350 * This process is exiting: if it's straightforward (as is the
2351 * case when ksmd was never running), free mm_slot immediately.
2352 * But if it's at the cursor or has rmap_items linked to it, use
2353 * mmap_sem to synchronize with any break_cows before pagetables
2354 * are freed, and leave the mm_slot on the list for ksmd to free.
2355 * Beware: ksm may already have noticed it exiting and freed the slot.
31dbd01f 2356 */
9ba69294 2357
cd551f97
HD
2358 spin_lock(&ksm_mmlist_lock);
2359 mm_slot = get_mm_slot(mm);
9ba69294 2360 if (mm_slot && ksm_scan.mm_slot != mm_slot) {
6514d511 2361 if (!mm_slot->rmap_list) {
4ca3a69b 2362 hash_del(&mm_slot->link);
9ba69294
HD
2363 list_del(&mm_slot->mm_list);
2364 easy_to_free = 1;
2365 } else {
2366 list_move(&mm_slot->mm_list,
2367 &ksm_scan.mm_slot->mm_list);
2368 }
cd551f97 2369 }
cd551f97
HD
2370 spin_unlock(&ksm_mmlist_lock);
2371
9ba69294
HD
2372 if (easy_to_free) {
2373 free_mm_slot(mm_slot);
2374 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
2375 mmdrop(mm);
2376 } else if (mm_slot) {
9ba69294
HD
2377 down_write(&mm->mmap_sem);
2378 up_write(&mm->mmap_sem);
9ba69294 2379 }
31dbd01f
IE
2380}
2381
cbf86cfe 2382struct page *ksm_might_need_to_copy(struct page *page,
5ad64688
HD
2383 struct vm_area_struct *vma, unsigned long address)
2384{
cbf86cfe 2385 struct anon_vma *anon_vma = page_anon_vma(page);
5ad64688
HD
2386 struct page *new_page;
2387
cbf86cfe
HD
2388 if (PageKsm(page)) {
2389 if (page_stable_node(page) &&
2390 !(ksm_run & KSM_RUN_UNMERGE))
2391 return page; /* no need to copy it */
2392 } else if (!anon_vma) {
2393 return page; /* no need to copy it */
2394 } else if (anon_vma->root == vma->anon_vma->root &&
2395 page->index == linear_page_index(vma, address)) {
2396 return page; /* still no need to copy it */
2397 }
2398 if (!PageUptodate(page))
2399 return page; /* let do_swap_page report the error */
2400
5ad64688
HD
2401 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
2402 if (new_page) {
2403 copy_user_highpage(new_page, page, address, vma);
2404
2405 SetPageDirty(new_page);
2406 __SetPageUptodate(new_page);
48c935ad 2407 __SetPageLocked(new_page);
5ad64688
HD
2408 }
2409
5ad64688
HD
2410 return new_page;
2411}
2412
051ac83a 2413int rmap_walk_ksm(struct page *page, struct rmap_walk_control *rwc)
e9995ef9
HD
2414{
2415 struct stable_node *stable_node;
e9995ef9
HD
2416 struct rmap_item *rmap_item;
2417 int ret = SWAP_AGAIN;
2418 int search_new_forks = 0;
2419
309381fe 2420 VM_BUG_ON_PAGE(!PageKsm(page), page);
9f32624b
JK
2421
2422 /*
2423 * Rely on the page lock to protect against concurrent modifications
2424 * to that page's node of the stable tree.
2425 */
309381fe 2426 VM_BUG_ON_PAGE(!PageLocked(page), page);
e9995ef9
HD
2427
2428 stable_node = page_stable_node(page);
2429 if (!stable_node)
2430 return ret;
2431again:
b67bfe0d 2432 hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
e9995ef9 2433 struct anon_vma *anon_vma = rmap_item->anon_vma;
5beb4930 2434 struct anon_vma_chain *vmac;
e9995ef9
HD
2435 struct vm_area_struct *vma;
2436
ad12695f 2437 cond_resched();
b6b19f25 2438 anon_vma_lock_read(anon_vma);
bf181b9f
ML
2439 anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
2440 0, ULONG_MAX) {
ad12695f 2441 cond_resched();
5beb4930 2442 vma = vmac->vma;
e9995ef9
HD
2443 if (rmap_item->address < vma->vm_start ||
2444 rmap_item->address >= vma->vm_end)
2445 continue;
2446 /*
2447 * Initially we examine only the vma which covers this
2448 * rmap_item; but later, if there is still work to do,
2449 * we examine covering vmas in other mms: in case they
2450 * were forked from the original since ksmd passed.
2451 */
2452 if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
2453 continue;
2454
0dd1c7bb
JK
2455 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2456 continue;
2457
051ac83a
JK
2458 ret = rwc->rmap_one(page, vma,
2459 rmap_item->address, rwc->arg);
e9995ef9 2460 if (ret != SWAP_AGAIN) {
b6b19f25 2461 anon_vma_unlock_read(anon_vma);
e9995ef9
HD
2462 goto out;
2463 }
0dd1c7bb
JK
2464 if (rwc->done && rwc->done(page)) {
2465 anon_vma_unlock_read(anon_vma);
2466 goto out;
2467 }
e9995ef9 2468 }
b6b19f25 2469 anon_vma_unlock_read(anon_vma);
e9995ef9
HD
2470 }
2471 if (!search_new_forks++)
2472 goto again;
2473out:
2474 return ret;
2475}
2476
52629506 2477#ifdef CONFIG_MIGRATION
e9995ef9
HD
2478void ksm_migrate_page(struct page *newpage, struct page *oldpage)
2479{
2480 struct stable_node *stable_node;
2481
309381fe
SL
2482 VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
2483 VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
2484 VM_BUG_ON_PAGE(newpage->mapping != oldpage->mapping, newpage);
e9995ef9
HD
2485
2486 stable_node = page_stable_node(newpage);
2487 if (stable_node) {
309381fe 2488 VM_BUG_ON_PAGE(stable_node->kpfn != page_to_pfn(oldpage), oldpage);
62b61f61 2489 stable_node->kpfn = page_to_pfn(newpage);
c8d6553b
HD
2490 /*
2491 * newpage->mapping was set in advance; now we need smp_wmb()
2492 * to make sure that the new stable_node->kpfn is visible
2493 * to get_ksm_page() before it can see that oldpage->mapping
2494 * has gone stale (or that PageSwapCache has been cleared).
2495 */
2496 smp_wmb();
2497 set_page_stable_node(oldpage, NULL);
e9995ef9
HD
2498 }
2499}
2500#endif /* CONFIG_MIGRATION */
2501
62b61f61 2502#ifdef CONFIG_MEMORY_HOTREMOVE
ef4d43a8
HD
2503static void wait_while_offlining(void)
2504{
2505 while (ksm_run & KSM_RUN_OFFLINE) {
2506 mutex_unlock(&ksm_thread_mutex);
2507 wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
74316201 2508 TASK_UNINTERRUPTIBLE);
ef4d43a8
HD
2509 mutex_lock(&ksm_thread_mutex);
2510 }
2511}
2512
7253473c
AA
2513static bool stable_node_dup_remove_range(struct stable_node *stable_node,
2514 unsigned long start_pfn,
2515 unsigned long end_pfn)
2516{
2517 if (stable_node->kpfn >= start_pfn &&
2518 stable_node->kpfn < end_pfn) {
2519 /*
2520 * Don't get_ksm_page, page has already gone:
2521 * which is why we keep kpfn instead of page*
2522 */
2523 remove_node_from_stable_tree(stable_node);
2524 return true;
2525 }
2526 return false;
2527}
2528
2529static bool stable_node_chain_remove_range(struct stable_node *stable_node,
2530 unsigned long start_pfn,
2531 unsigned long end_pfn,
2532 struct rb_root *root)
2533{
2534 struct stable_node *dup;
2535 struct hlist_node *hlist_safe;
2536
2537 if (!is_stable_node_chain(stable_node)) {
2538 VM_BUG_ON(is_stable_node_dup(stable_node));
2539 return stable_node_dup_remove_range(stable_node, start_pfn,
2540 end_pfn);
2541 }
2542
2543 hlist_for_each_entry_safe(dup, hlist_safe,
2544 &stable_node->hlist, hlist_dup) {
2545 VM_BUG_ON(!is_stable_node_dup(dup));
2546 stable_node_dup_remove_range(dup, start_pfn, end_pfn);
2547 }
2548 if (hlist_empty(&stable_node->hlist)) {
2549 free_stable_node_chain(stable_node, root);
2550 return true; /* notify caller that tree was rebalanced */
2551 } else
2552 return false;
2553}
2554
ee0ea59c
HD
2555static void ksm_check_stable_tree(unsigned long start_pfn,
2556 unsigned long end_pfn)
62b61f61 2557{
03640418 2558 struct stable_node *stable_node, *next;
62b61f61 2559 struct rb_node *node;
90bd6fd3 2560 int nid;
62b61f61 2561
ef53d16c
HD
2562 for (nid = 0; nid < ksm_nr_node_ids; nid++) {
2563 node = rb_first(root_stable_tree + nid);
ee0ea59c 2564 while (node) {
90bd6fd3 2565 stable_node = rb_entry(node, struct stable_node, node);
7253473c
AA
2566 if (stable_node_chain_remove_range(stable_node,
2567 start_pfn, end_pfn,
2568 root_stable_tree +
2569 nid))
ef53d16c 2570 node = rb_first(root_stable_tree + nid);
7253473c 2571 else
ee0ea59c
HD
2572 node = rb_next(node);
2573 cond_resched();
90bd6fd3 2574 }
ee0ea59c 2575 }
03640418 2576 list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
4146d2d6
HD
2577 if (stable_node->kpfn >= start_pfn &&
2578 stable_node->kpfn < end_pfn)
2579 remove_node_from_stable_tree(stable_node);
2580 cond_resched();
2581 }
62b61f61
HD
2582}
2583
2584static int ksm_memory_callback(struct notifier_block *self,
2585 unsigned long action, void *arg)
2586{
2587 struct memory_notify *mn = arg;
62b61f61
HD
2588
2589 switch (action) {
2590 case MEM_GOING_OFFLINE:
2591 /*
ef4d43a8
HD
2592 * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
2593 * and remove_all_stable_nodes() while memory is going offline:
2594 * it is unsafe for them to touch the stable tree at this time.
2595 * But unmerge_ksm_pages(), rmap lookups and other entry points
2596 * which do not need the ksm_thread_mutex are all safe.
62b61f61 2597 */
ef4d43a8
HD
2598 mutex_lock(&ksm_thread_mutex);
2599 ksm_run |= KSM_RUN_OFFLINE;
2600 mutex_unlock(&ksm_thread_mutex);
62b61f61
HD
2601 break;
2602
2603 case MEM_OFFLINE:
2604 /*
2605 * Most of the work is done by page migration; but there might
2606 * be a few stable_nodes left over, still pointing to struct
ee0ea59c
HD
2607 * pages which have been offlined: prune those from the tree,
2608 * otherwise get_ksm_page() might later try to access a
2609 * non-existent struct page.
62b61f61 2610 */
ee0ea59c
HD
2611 ksm_check_stable_tree(mn->start_pfn,
2612 mn->start_pfn + mn->nr_pages);
62b61f61
HD
2613 /* fallthrough */
2614
2615 case MEM_CANCEL_OFFLINE:
ef4d43a8
HD
2616 mutex_lock(&ksm_thread_mutex);
2617 ksm_run &= ~KSM_RUN_OFFLINE;
62b61f61 2618 mutex_unlock(&ksm_thread_mutex);
ef4d43a8
HD
2619
2620 smp_mb(); /* wake_up_bit advises this */
2621 wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
62b61f61
HD
2622 break;
2623 }
2624 return NOTIFY_OK;
2625}
ef4d43a8
HD
2626#else
2627static void wait_while_offlining(void)
2628{
2629}
62b61f61
HD
2630#endif /* CONFIG_MEMORY_HOTREMOVE */
2631
2ffd8679
HD
2632#ifdef CONFIG_SYSFS
2633/*
2634 * This all compiles without CONFIG_SYSFS, but is a waste of space.
2635 */
2636
31dbd01f
IE
2637#define KSM_ATTR_RO(_name) \
2638 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2639#define KSM_ATTR(_name) \
2640 static struct kobj_attribute _name##_attr = \
2641 __ATTR(_name, 0644, _name##_show, _name##_store)
2642
2643static ssize_t sleep_millisecs_show(struct kobject *kobj,
2644 struct kobj_attribute *attr, char *buf)
2645{
2646 return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
2647}
2648
2649static ssize_t sleep_millisecs_store(struct kobject *kobj,
2650 struct kobj_attribute *attr,
2651 const char *buf, size_t count)
2652{
2653 unsigned long msecs;
2654 int err;
2655
3dbb95f7 2656 err = kstrtoul(buf, 10, &msecs);
31dbd01f
IE
2657 if (err || msecs > UINT_MAX)
2658 return -EINVAL;
2659
2660 ksm_thread_sleep_millisecs = msecs;
2661
2662 return count;
2663}
2664KSM_ATTR(sleep_millisecs);
2665
2666static ssize_t pages_to_scan_show(struct kobject *kobj,
2667 struct kobj_attribute *attr, char *buf)
2668{
2669 return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
2670}
2671
2672static ssize_t pages_to_scan_store(struct kobject *kobj,
2673 struct kobj_attribute *attr,
2674 const char *buf, size_t count)
2675{
2676 int err;
2677 unsigned long nr_pages;
2678
3dbb95f7 2679 err = kstrtoul(buf, 10, &nr_pages);
31dbd01f
IE
2680 if (err || nr_pages > UINT_MAX)
2681 return -EINVAL;
2682
2683 ksm_thread_pages_to_scan = nr_pages;
2684
2685 return count;
2686}
2687KSM_ATTR(pages_to_scan);
2688
2689static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
2690 char *buf)
2691{
ef4d43a8 2692 return sprintf(buf, "%lu\n", ksm_run);
31dbd01f
IE
2693}
2694
2695static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
2696 const char *buf, size_t count)
2697{
2698 int err;
2699 unsigned long flags;
2700
3dbb95f7 2701 err = kstrtoul(buf, 10, &flags);
31dbd01f
IE
2702 if (err || flags > UINT_MAX)
2703 return -EINVAL;
2704 if (flags > KSM_RUN_UNMERGE)
2705 return -EINVAL;
2706
2707 /*
2708 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
2709 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
d0f209f6
HD
2710 * breaking COW to free the pages_shared (but leaves mm_slots
2711 * on the list for when ksmd may be set running again).
31dbd01f
IE
2712 */
2713
2714 mutex_lock(&ksm_thread_mutex);
ef4d43a8 2715 wait_while_offlining();
31dbd01f
IE
2716 if (ksm_run != flags) {
2717 ksm_run = flags;
d952b791 2718 if (flags & KSM_RUN_UNMERGE) {
e1e12d2f 2719 set_current_oom_origin();
d952b791 2720 err = unmerge_and_remove_all_rmap_items();
e1e12d2f 2721 clear_current_oom_origin();
d952b791
HD
2722 if (err) {
2723 ksm_run = KSM_RUN_STOP;
2724 count = err;
2725 }
2726 }
31dbd01f
IE
2727 }
2728 mutex_unlock(&ksm_thread_mutex);
2729
2730 if (flags & KSM_RUN_MERGE)
2731 wake_up_interruptible(&ksm_thread_wait);
2732
2733 return count;
2734}
2735KSM_ATTR(run);
2736
90bd6fd3
PH
2737#ifdef CONFIG_NUMA
2738static ssize_t merge_across_nodes_show(struct kobject *kobj,
2739 struct kobj_attribute *attr, char *buf)
2740{
2741 return sprintf(buf, "%u\n", ksm_merge_across_nodes);
2742}
2743
2744static ssize_t merge_across_nodes_store(struct kobject *kobj,
2745 struct kobj_attribute *attr,
2746 const char *buf, size_t count)
2747{
2748 int err;
2749 unsigned long knob;
2750
2751 err = kstrtoul(buf, 10, &knob);
2752 if (err)
2753 return err;
2754 if (knob > 1)
2755 return -EINVAL;
2756
2757 mutex_lock(&ksm_thread_mutex);
ef4d43a8 2758 wait_while_offlining();
90bd6fd3 2759 if (ksm_merge_across_nodes != knob) {
cbf86cfe 2760 if (ksm_pages_shared || remove_all_stable_nodes())
90bd6fd3 2761 err = -EBUSY;
ef53d16c
HD
2762 else if (root_stable_tree == one_stable_tree) {
2763 struct rb_root *buf;
2764 /*
2765 * This is the first time that we switch away from the
2766 * default of merging across nodes: must now allocate
2767 * a buffer to hold as many roots as may be needed.
2768 * Allocate stable and unstable together:
2769 * MAXSMP NODES_SHIFT 10 will use 16kB.
2770 */
bafe1e14
JP
2771 buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf),
2772 GFP_KERNEL);
ef53d16c
HD
2773 /* Let us assume that RB_ROOT is NULL is zero */
2774 if (!buf)
2775 err = -ENOMEM;
2776 else {
2777 root_stable_tree = buf;
2778 root_unstable_tree = buf + nr_node_ids;
2779 /* Stable tree is empty but not the unstable */
2780 root_unstable_tree[0] = one_unstable_tree[0];
2781 }
2782 }
2783 if (!err) {
90bd6fd3 2784 ksm_merge_across_nodes = knob;
ef53d16c
HD
2785 ksm_nr_node_ids = knob ? 1 : nr_node_ids;
2786 }
90bd6fd3
PH
2787 }
2788 mutex_unlock(&ksm_thread_mutex);
2789
2790 return err ? err : count;
2791}
2792KSM_ATTR(merge_across_nodes);
2793#endif
2794
fa2aa0fc
CI
2795static ssize_t use_zero_pages_show(struct kobject *kobj,
2796 struct kobj_attribute *attr, char *buf)
2797{
2798 return sprintf(buf, "%u\n", ksm_use_zero_pages);
2799}
2800static ssize_t use_zero_pages_store(struct kobject *kobj,
2801 struct kobj_attribute *attr,
2802 const char *buf, size_t count)
2803{
2804 int err;
2805 bool value;
2806
2807 err = kstrtobool(buf, &value);
2808 if (err)
2809 return -EINVAL;
2810
2811 ksm_use_zero_pages = value;
2812
2813 return count;
2814}
2815KSM_ATTR(use_zero_pages);
2816
7253473c
AA
2817static ssize_t max_page_sharing_show(struct kobject *kobj,
2818 struct kobj_attribute *attr, char *buf)
2819{
2820 return sprintf(buf, "%u\n", ksm_max_page_sharing);
2821}
2822
2823static ssize_t max_page_sharing_store(struct kobject *kobj,
2824 struct kobj_attribute *attr,
2825 const char *buf, size_t count)
2826{
2827 int err;
2828 int knob;
2829
2830 err = kstrtoint(buf, 10, &knob);
2831 if (err)
2832 return err;
2833 /*
2834 * When a KSM page is created it is shared by 2 mappings. This
2835 * being a signed comparison, it implicitly verifies it's not
2836 * negative.
2837 */
2838 if (knob < 2)
2839 return -EINVAL;
2840
2841 if (READ_ONCE(ksm_max_page_sharing) == knob)
2842 return count;
2843
2844 mutex_lock(&ksm_thread_mutex);
2845 wait_while_offlining();
2846 if (ksm_max_page_sharing != knob) {
2847 if (ksm_pages_shared || remove_all_stable_nodes())
2848 err = -EBUSY;
2849 else
2850 ksm_max_page_sharing = knob;
2851 }
2852 mutex_unlock(&ksm_thread_mutex);
2853
2854 return err ? err : count;
2855}
2856KSM_ATTR(max_page_sharing);
2857
b4028260
HD
2858static ssize_t pages_shared_show(struct kobject *kobj,
2859 struct kobj_attribute *attr, char *buf)
2860{
2861 return sprintf(buf, "%lu\n", ksm_pages_shared);
2862}
2863KSM_ATTR_RO(pages_shared);
2864
2865static ssize_t pages_sharing_show(struct kobject *kobj,
2866 struct kobj_attribute *attr, char *buf)
2867{
e178dfde 2868 return sprintf(buf, "%lu\n", ksm_pages_sharing);
b4028260
HD
2869}
2870KSM_ATTR_RO(pages_sharing);
2871
473b0ce4
HD
2872static ssize_t pages_unshared_show(struct kobject *kobj,
2873 struct kobj_attribute *attr, char *buf)
2874{
2875 return sprintf(buf, "%lu\n", ksm_pages_unshared);
2876}
2877KSM_ATTR_RO(pages_unshared);
2878
2879static ssize_t pages_volatile_show(struct kobject *kobj,
2880 struct kobj_attribute *attr, char *buf)
2881{
2882 long ksm_pages_volatile;
2883
2884 ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
2885 - ksm_pages_sharing - ksm_pages_unshared;
2886 /*
2887 * It was not worth any locking to calculate that statistic,
2888 * but it might therefore sometimes be negative: conceal that.
2889 */
2890 if (ksm_pages_volatile < 0)
2891 ksm_pages_volatile = 0;
2892 return sprintf(buf, "%ld\n", ksm_pages_volatile);
2893}
2894KSM_ATTR_RO(pages_volatile);
2895
7253473c
AA
2896static ssize_t stable_node_dups_show(struct kobject *kobj,
2897 struct kobj_attribute *attr, char *buf)
2898{
2899 return sprintf(buf, "%lu\n", ksm_stable_node_dups);
2900}
2901KSM_ATTR_RO(stable_node_dups);
2902
2903static ssize_t stable_node_chains_show(struct kobject *kobj,
2904 struct kobj_attribute *attr, char *buf)
2905{
2906 return sprintf(buf, "%lu\n", ksm_stable_node_chains);
2907}
2908KSM_ATTR_RO(stable_node_chains);
2909
2910static ssize_t
2911stable_node_chains_prune_millisecs_show(struct kobject *kobj,
2912 struct kobj_attribute *attr,
2913 char *buf)
2914{
2915 return sprintf(buf, "%u\n", ksm_stable_node_chains_prune_millisecs);
2916}
2917
2918static ssize_t
2919stable_node_chains_prune_millisecs_store(struct kobject *kobj,
2920 struct kobj_attribute *attr,
2921 const char *buf, size_t count)
2922{
2923 unsigned long msecs;
2924 int err;
2925
2926 err = kstrtoul(buf, 10, &msecs);
2927 if (err || msecs > UINT_MAX)
2928 return -EINVAL;
2929
2930 ksm_stable_node_chains_prune_millisecs = msecs;
2931
2932 return count;
2933}
2934KSM_ATTR(stable_node_chains_prune_millisecs);
2935
473b0ce4
HD
2936static ssize_t full_scans_show(struct kobject *kobj,
2937 struct kobj_attribute *attr, char *buf)
2938{
2939 return sprintf(buf, "%lu\n", ksm_scan.seqnr);
2940}
2941KSM_ATTR_RO(full_scans);
2942
31dbd01f
IE
2943static struct attribute *ksm_attrs[] = {
2944 &sleep_millisecs_attr.attr,
2945 &pages_to_scan_attr.attr,
2946 &run_attr.attr,
b4028260
HD
2947 &pages_shared_attr.attr,
2948 &pages_sharing_attr.attr,
473b0ce4
HD
2949 &pages_unshared_attr.attr,
2950 &pages_volatile_attr.attr,
2951 &full_scans_attr.attr,
90bd6fd3
PH
2952#ifdef CONFIG_NUMA
2953 &merge_across_nodes_attr.attr,
2954#endif
7253473c
AA
2955 &max_page_sharing_attr.attr,
2956 &stable_node_chains_attr.attr,
2957 &stable_node_dups_attr.attr,
2958 &stable_node_chains_prune_millisecs_attr.attr,
fa2aa0fc 2959 &use_zero_pages_attr.attr,
31dbd01f
IE
2960 NULL,
2961};
2962
2963static struct attribute_group ksm_attr_group = {
2964 .attrs = ksm_attrs,
2965 .name = "ksm",
2966};
2ffd8679 2967#endif /* CONFIG_SYSFS */
31dbd01f
IE
2968
2969static int __init ksm_init(void)
2970{
2971 struct task_struct *ksm_thread;
2972 int err;
2973
fa2aa0fc
CI
2974 /* The correct value depends on page size and endianness */
2975 zero_checksum = calc_checksum(ZERO_PAGE(0));
2976 /* Default to false for backwards compatibility */
2977 ksm_use_zero_pages = false;
2978
31dbd01f
IE
2979 err = ksm_slab_init();
2980 if (err)
2981 goto out;
2982
31dbd01f
IE
2983 ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
2984 if (IS_ERR(ksm_thread)) {
25acde31 2985 pr_err("ksm: creating kthread failed\n");
31dbd01f 2986 err = PTR_ERR(ksm_thread);
d9f8984c 2987 goto out_free;
31dbd01f
IE
2988 }
2989
2ffd8679 2990#ifdef CONFIG_SYSFS
31dbd01f
IE
2991 err = sysfs_create_group(mm_kobj, &ksm_attr_group);
2992 if (err) {
25acde31 2993 pr_err("ksm: register sysfs failed\n");
2ffd8679 2994 kthread_stop(ksm_thread);
d9f8984c 2995 goto out_free;
31dbd01f 2996 }
c73602ad
HD
2997#else
2998 ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
2999
2ffd8679 3000#endif /* CONFIG_SYSFS */
31dbd01f 3001
62b61f61 3002#ifdef CONFIG_MEMORY_HOTREMOVE
ef4d43a8 3003 /* There is no significance to this priority 100 */
62b61f61
HD
3004 hotplug_memory_notifier(ksm_memory_callback, 100);
3005#endif
31dbd01f
IE
3006 return 0;
3007
d9f8984c 3008out_free:
31dbd01f
IE
3009 ksm_slab_free();
3010out:
3011 return err;
f8af4da3 3012}
a64fb3cd 3013subsys_initcall(ksm_init);