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