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