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