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