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