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