1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
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 *
8 * Copyright (C) 2008-2009 Red Hat, Inc.
9 * Authors:
10 * Izik Eidus
11 * Andrea Arcangeli
12 * Chris Wright
13 * Hugh Dickins
14 */
15
16 #include <linux/errno.h>
17 #include <linux/mm.h>
18 #include <linux/mm_inline.h>
19 #include <linux/fs.h>
20 #include <linux/mman.h>
21 #include <linux/sched.h>
22 #include <linux/sched/mm.h>
23 #include <linux/sched/cputime.h>
24 #include <linux/rwsem.h>
25 #include <linux/pagemap.h>
26 #include <linux/rmap.h>
27 #include <linux/spinlock.h>
28 #include <linux/xxhash.h>
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>
34 #include <linux/memory.h>
35 #include <linux/mmu_notifier.h>
36 #include <linux/swap.h>
37 #include <linux/ksm.h>
38 #include <linux/hashtable.h>
39 #include <linux/freezer.h>
40 #include <linux/oom.h>
41 #include <linux/numa.h>
42 #include <linux/pagewalk.h>
43
44 #include <asm/tlbflush.h>
45 #include "internal.h"
46 #include "mm_slot.h"
47
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/ksm.h>
50
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
59 typedef u8 rmap_age_t;
60
61 /**
62 * DOC: Overview
63 *
64 * A few notes about the KSM scanning process,
65 * to make it easier to understand the data structures below:
66 *
67 * In order to reduce excessive scanning, KSM sorts the memory pages by their
68 * contents into a data structure that holds pointers to the pages' locations.
69 *
70 * Since the contents of the pages may change at any moment, KSM cannot just
71 * insert the pages into a normal sorted tree and expect it to find anything.
72 * Therefore KSM uses two data structures - the stable and the unstable tree.
73 *
74 * The stable tree holds pointers to all the merged pages (ksm pages), sorted
75 * by their contents. Because each such page is write-protected, searching on
76 * this tree is fully assured to be working (except when pages are unmapped),
77 * and therefore this tree is called the stable tree.
78 *
79 * The stable tree node includes information required for reverse
80 * mapping from a KSM page to virtual addresses that map this page.
81 *
82 * In order to avoid large latencies of the rmap walks on KSM pages,
83 * KSM maintains two types of nodes in the stable tree:
84 *
85 * * the regular nodes that keep the reverse mapping structures in a
86 * linked list
87 * * the "chains" that link nodes ("dups") that represent the same
88 * write protected memory content, but each "dup" corresponds to a
89 * different KSM page copy of that content
90 *
91 * Internally, the regular nodes, "dups" and "chains" are represented
92 * using the same struct ksm_stable_node structure.
93 *
94 * In addition to the stable tree, KSM uses a second data structure called the
95 * unstable tree: this tree holds pointers to pages which have been found to
96 * be "unchanged for a period of time". The unstable tree sorts these pages
97 * by their contents, but since they are not write-protected, KSM cannot rely
98 * upon the unstable tree to work correctly - the unstable tree is liable to
99 * be corrupted as its contents are modified, and so it is called unstable.
100 *
101 * KSM solves this problem by several techniques:
102 *
103 * 1) The unstable tree is flushed every time KSM completes scanning all
104 * memory areas, and then the tree is rebuilt again from the beginning.
105 * 2) KSM will only insert into the unstable tree, pages whose hash value
106 * has not changed since the previous scan of all memory areas.
107 * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
108 * colors of the nodes and not on their contents, assuring that even when
109 * the tree gets "corrupted" it won't get out of balance, so scanning time
110 * remains the same (also, searching and inserting nodes in an rbtree uses
111 * the same algorithm, so we have no overhead when we flush and rebuild).
112 * 4) KSM never flushes the stable tree, which means that even if it were to
113 * take 10 attempts to find a page in the unstable tree, once it is found,
114 * it is secured in the stable tree. (When we scan a new page, we first
115 * compare it against the stable tree, and then against the unstable tree.)
116 *
117 * If the merge_across_nodes tunable is unset, then KSM maintains multiple
118 * stable trees and multiple unstable trees: one of each for each NUMA node.
119 */
120
121 /**
122 * struct ksm_mm_slot - ksm information per mm that is being scanned
123 * @slot: hash lookup from mm to mm_slot
124 * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
125 */
126 struct ksm_mm_slot {
127 struct mm_slot slot;
128 struct ksm_rmap_item *rmap_list;
129 };
130
131 /**
132 * struct ksm_scan - cursor for scanning
133 * @mm_slot: the current mm_slot we are scanning
134 * @address: the next address inside that to be scanned
135 * @rmap_list: link to the next rmap to be scanned in the rmap_list
136 * @seqnr: count of completed full scans (needed when removing unstable node)
137 *
138 * There is only the one ksm_scan instance of this cursor structure.
139 */
140 struct ksm_scan {
141 struct ksm_mm_slot *mm_slot;
142 unsigned long address;
143 struct ksm_rmap_item **rmap_list;
144 unsigned long seqnr;
145 };
146
147 /**
148 * struct ksm_stable_node - node of the stable rbtree
149 * @node: rb node of this ksm page in the stable tree
150 * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
151 * @hlist_dup: linked into the stable_node->hlist with a stable_node chain
152 * @list: linked into migrate_nodes, pending placement in the proper node tree
153 * @hlist: hlist head of rmap_items using this ksm page
154 * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
155 * @chain_prune_time: time of the last full garbage collection
156 * @rmap_hlist_len: number of rmap_item entries in hlist or STABLE_NODE_CHAIN
157 * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
158 */
159 struct ksm_stable_node {
160 union {
161 struct rb_node node; /* when node of stable tree */
162 struct { /* when listed for migration */
163 struct list_head *head;
164 struct {
165 struct hlist_node hlist_dup;
166 struct list_head list;
167 };
168 };
169 };
170 struct hlist_head hlist;
171 union {
172 unsigned long kpfn;
173 unsigned long chain_prune_time;
174 };
175 /*
176 * STABLE_NODE_CHAIN can be any negative number in
177 * rmap_hlist_len negative range, but better not -1 to be able
178 * to reliably detect underflows.
179 */
180 #define STABLE_NODE_CHAIN -1024
181 int rmap_hlist_len;
182 #ifdef CONFIG_NUMA
183 int nid;
184 #endif
185 };
186
187 /**
188 * struct ksm_rmap_item - reverse mapping item for virtual addresses
189 * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
190 * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
191 * @nid: NUMA node id of unstable tree in which linked (may not match page)
192 * @mm: the memory structure this rmap_item is pointing into
193 * @address: the virtual address this rmap_item tracks (+ flags in low bits)
194 * @oldchecksum: previous checksum of the page at that virtual address
195 * @node: rb node of this rmap_item in the unstable tree
196 * @head: pointer to stable_node heading this list in the stable tree
197 * @hlist: link into hlist of rmap_items hanging off that stable_node
198 * @age: number of scan iterations since creation
199 * @remaining_skips: how many scans to skip
200 */
201 struct ksm_rmap_item {
202 struct ksm_rmap_item *rmap_list;
203 union {
204 struct anon_vma *anon_vma; /* when stable */
205 #ifdef CONFIG_NUMA
206 int nid; /* when node of unstable tree */
207 #endif
208 };
209 struct mm_struct *mm;
210 unsigned long address; /* + low bits used for flags below */
211 unsigned int oldchecksum; /* when unstable */
212 rmap_age_t age;
213 rmap_age_t remaining_skips;
214 union {
215 struct rb_node node; /* when node of unstable tree */
216 struct { /* when listed from stable tree */
217 struct ksm_stable_node *head;
218 struct hlist_node hlist;
219 };
220 };
221 };
222
223 #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
224 #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
225 #define STABLE_FLAG 0x200 /* is listed from the stable tree */
226
227 /* The stable and unstable tree heads */
228 static struct rb_root one_stable_tree[1] = { RB_ROOT };
229 static struct rb_root one_unstable_tree[1] = { RB_ROOT };
230 static struct rb_root *root_stable_tree = one_stable_tree;
231 static struct rb_root *root_unstable_tree = one_unstable_tree;
232
233 /* Recently migrated nodes of stable tree, pending proper placement */
234 static LIST_HEAD(migrate_nodes);
235 #define STABLE_NODE_DUP_HEAD ((struct list_head *)&migrate_nodes.prev)
236
237 #define MM_SLOTS_HASH_BITS 10
238 static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
239
240 static struct ksm_mm_slot ksm_mm_head = {
241 .slot.mm_node = LIST_HEAD_INIT(ksm_mm_head.slot.mm_node),
242 };
243 static struct ksm_scan ksm_scan = {
244 .mm_slot = &ksm_mm_head,
245 };
246
247 static struct kmem_cache *rmap_item_cache;
248 static struct kmem_cache *stable_node_cache;
249 static struct kmem_cache *mm_slot_cache;
250
251 /* Default number of pages to scan per batch */
252 #define DEFAULT_PAGES_TO_SCAN 100
253
254 /* The number of pages scanned */
255 static unsigned long ksm_pages_scanned;
256
257 /* The number of nodes in the stable tree */
258 static unsigned long ksm_pages_shared;
259
260 /* The number of page slots additionally sharing those nodes */
261 static unsigned long ksm_pages_sharing;
262
263 /* The number of nodes in the unstable tree */
264 static unsigned long ksm_pages_unshared;
265
266 /* The number of rmap_items in use: to calculate pages_volatile */
267 static unsigned long ksm_rmap_items;
268
269 /* The number of stable_node chains */
270 static unsigned long ksm_stable_node_chains;
271
272 /* The number of stable_node dups linked to the stable_node chains */
273 static unsigned long ksm_stable_node_dups;
274
275 /* Delay in pruning stale stable_node_dups in the stable_node_chains */
276 static unsigned int ksm_stable_node_chains_prune_millisecs = 2000;
277
278 /* Maximum number of page slots sharing a stable node */
279 static int ksm_max_page_sharing = 256;
280
281 /* Number of pages ksmd should scan in one batch */
282 static unsigned int ksm_thread_pages_to_scan = DEFAULT_PAGES_TO_SCAN;
283
284 /* Milliseconds ksmd should sleep between batches */
285 static unsigned int ksm_thread_sleep_millisecs = 20;
286
287 /* Checksum of an empty (zeroed) page */
288 static unsigned int zero_checksum __read_mostly;
289
290 /* Whether to merge empty (zeroed) pages with actual zero pages */
291 static bool ksm_use_zero_pages __read_mostly;
292
293 /* Skip pages that couldn't be de-duplicated previously */
294 /* Default to true at least temporarily, for testing */
295 static bool ksm_smart_scan = true;
296
297 /* The number of zero pages which is placed by KSM */
298 atomic_long_t ksm_zero_pages = ATOMIC_LONG_INIT(0);
299
300 /* The number of pages that have been skipped due to "smart scanning" */
301 static unsigned long ksm_pages_skipped;
302
303 /* Don't scan more than max pages per batch. */
304 static unsigned long ksm_advisor_max_pages_to_scan = 30000;
305
306 /* Min CPU for scanning pages per scan */
307 #define KSM_ADVISOR_MIN_CPU 10
308
309 /* Max CPU for scanning pages per scan */
310 static unsigned int ksm_advisor_max_cpu = 70;
311
312 /* Target scan time in seconds to analyze all KSM candidate pages. */
313 static unsigned long ksm_advisor_target_scan_time = 200;
314
315 /* Exponentially weighted moving average. */
316 #define EWMA_WEIGHT 30
317
318 /**
319 * struct advisor_ctx - metadata for KSM advisor
320 * @start_scan: start time of the current scan
321 * @scan_time: scan time of previous scan
322 * @change: change in percent to pages_to_scan parameter
323 * @cpu_time: cpu time consumed by the ksmd thread in the previous scan
324 */
325 struct advisor_ctx {
326 ktime_t start_scan;
327 unsigned long scan_time;
328 unsigned long change;
329 unsigned long long cpu_time;
330 };
331 static struct advisor_ctx advisor_ctx;
332
333 /* Define different advisor's */
334 enum ksm_advisor_type {
335 KSM_ADVISOR_NONE,
336 KSM_ADVISOR_SCAN_TIME,
337 };
338 static enum ksm_advisor_type ksm_advisor;
339
340 #ifdef CONFIG_SYSFS
341 /*
342 * Only called through the sysfs control interface:
343 */
344
345 /* At least scan this many pages per batch. */
346 static unsigned long ksm_advisor_min_pages_to_scan = 500;
347
set_advisor_defaults(void)348 static void set_advisor_defaults(void)
349 {
350 if (ksm_advisor == KSM_ADVISOR_NONE) {
351 ksm_thread_pages_to_scan = DEFAULT_PAGES_TO_SCAN;
352 } else if (ksm_advisor == KSM_ADVISOR_SCAN_TIME) {
353 advisor_ctx = (const struct advisor_ctx){ 0 };
354 ksm_thread_pages_to_scan = ksm_advisor_min_pages_to_scan;
355 }
356 }
357 #endif /* CONFIG_SYSFS */
358
advisor_start_scan(void)359 static inline void advisor_start_scan(void)
360 {
361 if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
362 advisor_ctx.start_scan = ktime_get();
363 }
364
365 /*
366 * Use previous scan time if available, otherwise use current scan time as an
367 * approximation for the previous scan time.
368 */
prev_scan_time(struct advisor_ctx * ctx,unsigned long scan_time)369 static inline unsigned long prev_scan_time(struct advisor_ctx *ctx,
370 unsigned long scan_time)
371 {
372 return ctx->scan_time ? ctx->scan_time : scan_time;
373 }
374
375 /* Calculate exponential weighted moving average */
ewma(unsigned long prev,unsigned long curr)376 static unsigned long ewma(unsigned long prev, unsigned long curr)
377 {
378 return ((100 - EWMA_WEIGHT) * prev + EWMA_WEIGHT * curr) / 100;
379 }
380
381 /*
382 * The scan time advisor is based on the current scan rate and the target
383 * scan rate.
384 *
385 * new_pages_to_scan = pages_to_scan * (scan_time / target_scan_time)
386 *
387 * To avoid perturbations it calculates a change factor of previous changes.
388 * A new change factor is calculated for each iteration and it uses an
389 * exponentially weighted moving average. The new pages_to_scan value is
390 * multiplied with that change factor:
391 *
392 * new_pages_to_scan *= change factor
393 *
394 * The new_pages_to_scan value is limited by the cpu min and max values. It
395 * calculates the cpu percent for the last scan and calculates the new
396 * estimated cpu percent cost for the next scan. That value is capped by the
397 * cpu min and max setting.
398 *
399 * In addition the new pages_to_scan value is capped by the max and min
400 * limits.
401 */
scan_time_advisor(void)402 static void scan_time_advisor(void)
403 {
404 unsigned int cpu_percent;
405 unsigned long cpu_time;
406 unsigned long cpu_time_diff;
407 unsigned long cpu_time_diff_ms;
408 unsigned long pages;
409 unsigned long per_page_cost;
410 unsigned long factor;
411 unsigned long change;
412 unsigned long last_scan_time;
413 unsigned long scan_time;
414
415 /* Convert scan time to seconds */
416 scan_time = div_s64(ktime_ms_delta(ktime_get(), advisor_ctx.start_scan),
417 MSEC_PER_SEC);
418 scan_time = scan_time ? scan_time : 1;
419
420 /* Calculate CPU consumption of ksmd background thread */
421 cpu_time = task_sched_runtime(current);
422 cpu_time_diff = cpu_time - advisor_ctx.cpu_time;
423 cpu_time_diff_ms = cpu_time_diff / 1000 / 1000;
424
425 cpu_percent = (cpu_time_diff_ms * 100) / (scan_time * 1000);
426 cpu_percent = cpu_percent ? cpu_percent : 1;
427 last_scan_time = prev_scan_time(&advisor_ctx, scan_time);
428
429 /* Calculate scan time as percentage of target scan time */
430 factor = ksm_advisor_target_scan_time * 100 / scan_time;
431 factor = factor ? factor : 1;
432
433 /*
434 * Calculate scan time as percentage of last scan time and use
435 * exponentially weighted average to smooth it
436 */
437 change = scan_time * 100 / last_scan_time;
438 change = change ? change : 1;
439 change = ewma(advisor_ctx.change, change);
440
441 /* Calculate new scan rate based on target scan rate. */
442 pages = ksm_thread_pages_to_scan * 100 / factor;
443 /* Update pages_to_scan by weighted change percentage. */
444 pages = pages * change / 100;
445
446 /* Cap new pages_to_scan value */
447 per_page_cost = ksm_thread_pages_to_scan / cpu_percent;
448 per_page_cost = per_page_cost ? per_page_cost : 1;
449
450 pages = min(pages, per_page_cost * ksm_advisor_max_cpu);
451 pages = max(pages, per_page_cost * KSM_ADVISOR_MIN_CPU);
452 pages = min(pages, ksm_advisor_max_pages_to_scan);
453
454 /* Update advisor context */
455 advisor_ctx.change = change;
456 advisor_ctx.scan_time = scan_time;
457 advisor_ctx.cpu_time = cpu_time;
458
459 ksm_thread_pages_to_scan = pages;
460 trace_ksm_advisor(scan_time, pages, cpu_percent);
461 }
462
advisor_stop_scan(void)463 static void advisor_stop_scan(void)
464 {
465 if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
466 scan_time_advisor();
467 }
468
469 #ifdef CONFIG_NUMA
470 /* Zeroed when merging across nodes is not allowed */
471 static unsigned int ksm_merge_across_nodes = 1;
472 static int ksm_nr_node_ids = 1;
473 #else
474 #define ksm_merge_across_nodes 1U
475 #define ksm_nr_node_ids 1
476 #endif
477
478 #define KSM_RUN_STOP 0
479 #define KSM_RUN_MERGE 1
480 #define KSM_RUN_UNMERGE 2
481 #define KSM_RUN_OFFLINE 4
482 static unsigned long ksm_run = KSM_RUN_STOP;
483 static void wait_while_offlining(void);
484
485 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
486 static DECLARE_WAIT_QUEUE_HEAD(ksm_iter_wait);
487 static DEFINE_MUTEX(ksm_thread_mutex);
488 static DEFINE_SPINLOCK(ksm_mmlist_lock);
489
ksm_slab_init(void)490 static int __init ksm_slab_init(void)
491 {
492 rmap_item_cache = KMEM_CACHE(ksm_rmap_item, 0);
493 if (!rmap_item_cache)
494 goto out;
495
496 stable_node_cache = KMEM_CACHE(ksm_stable_node, 0);
497 if (!stable_node_cache)
498 goto out_free1;
499
500 mm_slot_cache = KMEM_CACHE(ksm_mm_slot, 0);
501 if (!mm_slot_cache)
502 goto out_free2;
503
504 return 0;
505
506 out_free2:
507 kmem_cache_destroy(stable_node_cache);
508 out_free1:
509 kmem_cache_destroy(rmap_item_cache);
510 out:
511 return -ENOMEM;
512 }
513
ksm_slab_free(void)514 static void __init ksm_slab_free(void)
515 {
516 kmem_cache_destroy(mm_slot_cache);
517 kmem_cache_destroy(stable_node_cache);
518 kmem_cache_destroy(rmap_item_cache);
519 mm_slot_cache = NULL;
520 }
521
is_stable_node_chain(struct ksm_stable_node * chain)522 static __always_inline bool is_stable_node_chain(struct ksm_stable_node *chain)
523 {
524 return chain->rmap_hlist_len == STABLE_NODE_CHAIN;
525 }
526
is_stable_node_dup(struct ksm_stable_node * dup)527 static __always_inline bool is_stable_node_dup(struct ksm_stable_node *dup)
528 {
529 return dup->head == STABLE_NODE_DUP_HEAD;
530 }
531
stable_node_chain_add_dup(struct ksm_stable_node * dup,struct ksm_stable_node * chain)532 static inline void stable_node_chain_add_dup(struct ksm_stable_node *dup,
533 struct ksm_stable_node *chain)
534 {
535 VM_BUG_ON(is_stable_node_dup(dup));
536 dup->head = STABLE_NODE_DUP_HEAD;
537 VM_BUG_ON(!is_stable_node_chain(chain));
538 hlist_add_head(&dup->hlist_dup, &chain->hlist);
539 ksm_stable_node_dups++;
540 }
541
__stable_node_dup_del(struct ksm_stable_node * dup)542 static inline void __stable_node_dup_del(struct ksm_stable_node *dup)
543 {
544 VM_BUG_ON(!is_stable_node_dup(dup));
545 hlist_del(&dup->hlist_dup);
546 ksm_stable_node_dups--;
547 }
548
stable_node_dup_del(struct ksm_stable_node * dup)549 static inline void stable_node_dup_del(struct ksm_stable_node *dup)
550 {
551 VM_BUG_ON(is_stable_node_chain(dup));
552 if (is_stable_node_dup(dup))
553 __stable_node_dup_del(dup);
554 else
555 rb_erase(&dup->node, root_stable_tree + NUMA(dup->nid));
556 #ifdef CONFIG_DEBUG_VM
557 dup->head = NULL;
558 #endif
559 }
560
alloc_rmap_item(void)561 static inline struct ksm_rmap_item *alloc_rmap_item(void)
562 {
563 struct ksm_rmap_item *rmap_item;
564
565 rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL |
566 __GFP_NORETRY | __GFP_NOWARN);
567 if (rmap_item)
568 ksm_rmap_items++;
569 return rmap_item;
570 }
571
free_rmap_item(struct ksm_rmap_item * rmap_item)572 static inline void free_rmap_item(struct ksm_rmap_item *rmap_item)
573 {
574 ksm_rmap_items--;
575 rmap_item->mm->ksm_rmap_items--;
576 rmap_item->mm = NULL; /* debug safety */
577 kmem_cache_free(rmap_item_cache, rmap_item);
578 }
579
alloc_stable_node(void)580 static inline struct ksm_stable_node *alloc_stable_node(void)
581 {
582 /*
583 * The allocation can take too long with GFP_KERNEL when memory is under
584 * pressure, which may lead to hung task warnings. Adding __GFP_HIGH
585 * grants access to memory reserves, helping to avoid this problem.
586 */
587 return kmem_cache_alloc(stable_node_cache, GFP_KERNEL | __GFP_HIGH);
588 }
589
free_stable_node(struct ksm_stable_node * stable_node)590 static inline void free_stable_node(struct ksm_stable_node *stable_node)
591 {
592 VM_BUG_ON(stable_node->rmap_hlist_len &&
593 !is_stable_node_chain(stable_node));
594 kmem_cache_free(stable_node_cache, stable_node);
595 }
596
597 /*
598 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
599 * page tables after it has passed through ksm_exit() - which, if necessary,
600 * takes mmap_lock briefly to serialize against them. ksm_exit() does not set
601 * a special flag: they can just back out as soon as mm_users goes to zero.
602 * ksm_test_exit() is used throughout to make this test for exit: in some
603 * places for correctness, in some places just to avoid unnecessary work.
604 */
ksm_test_exit(struct mm_struct * mm)605 static inline bool ksm_test_exit(struct mm_struct *mm)
606 {
607 return atomic_read(&mm->mm_users) == 0;
608 }
609
break_ksm_pmd_entry(pmd_t * pmdp,unsigned long addr,unsigned long end,struct mm_walk * walk)610 static int break_ksm_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long end,
611 struct mm_walk *walk)
612 {
613 unsigned long *found_addr = (unsigned long *) walk->private;
614 struct mm_struct *mm = walk->mm;
615 pte_t *start_ptep, *ptep;
616 spinlock_t *ptl;
617 int found = 0;
618
619 if (ksm_test_exit(walk->mm))
620 return 0;
621 if (signal_pending(current))
622 return -ERESTARTSYS;
623
624 start_ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
625 if (!start_ptep)
626 return 0;
627
628 for (ptep = start_ptep; addr < end; ptep++, addr += PAGE_SIZE) {
629 pte_t pte = ptep_get(ptep);
630 struct folio *folio = NULL;
631
632 if (pte_present(pte)) {
633 folio = vm_normal_folio(walk->vma, addr, pte);
634 } else if (!pte_none(pte)) {
635 const softleaf_t entry = softleaf_from_pte(pte);
636
637 /*
638 * As KSM pages remain KSM pages until freed, no need to wait
639 * here for migration to end.
640 */
641 if (softleaf_is_migration(entry))
642 folio = softleaf_to_folio(entry);
643 }
644 /* return 1 if the page is an normal ksm page or KSM-placed zero page */
645 found = (folio && folio_test_ksm(folio)) ||
646 (pte_present(pte) && is_ksm_zero_pte(pte));
647 if (found) {
648 *found_addr = addr;
649 goto out_unlock;
650 }
651 }
652 out_unlock:
653 pte_unmap_unlock(start_ptep, ptl);
654 return found;
655 }
656
657 static const struct mm_walk_ops break_ksm_ops = {
658 .pmd_entry = break_ksm_pmd_entry,
659 .walk_lock = PGWALK_RDLOCK,
660 };
661
662 static const struct mm_walk_ops break_ksm_lock_vma_ops = {
663 .pmd_entry = break_ksm_pmd_entry,
664 .walk_lock = PGWALK_WRLOCK,
665 };
666
667 /*
668 * Though it's very tempting to unmerge rmap_items from stable tree rather
669 * than check every pte of a given vma, the locking doesn't quite work for
670 * that - an rmap_item is assigned to the stable tree after inserting ksm
671 * page and upping mmap_lock. Nor does it fit with the way we skip dup'ing
672 * rmap_items from parent to child at fork time (so as not to waste time
673 * if exit comes before the next scan reaches it).
674 *
675 * Similarly, although we'd like to remove rmap_items (so updating counts
676 * and freeing memory) when unmerging an area, it's easier to leave that
677 * to the next pass of ksmd - consider, for example, how ksmd might be
678 * in cmp_and_merge_page on one of the rmap_items we would be removing.
679 *
680 * We use break_ksm to break COW on a ksm page by triggering unsharing,
681 * such that the ksm page will get replaced by an exclusive anonymous page.
682 *
683 * We take great care only to touch a ksm page, in a VM_MERGEABLE vma,
684 * in case the application has unmapped and remapped mm,addr meanwhile.
685 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
686 * mmap of /dev/mem, where we would not want to touch it.
687 *
688 * FAULT_FLAG_REMOTE/FOLL_REMOTE are because we do this outside the context
689 * of the process that owns 'vma'. We also do not want to enforce
690 * protection keys here anyway.
691 */
break_ksm(struct vm_area_struct * vma,unsigned long addr,unsigned long end,bool lock_vma)692 static int break_ksm(struct vm_area_struct *vma, unsigned long addr,
693 unsigned long end, bool lock_vma)
694 {
695 vm_fault_t ret = 0;
696 const struct mm_walk_ops *ops = lock_vma ?
697 &break_ksm_lock_vma_ops : &break_ksm_ops;
698
699 do {
700 int ksm_page;
701
702 cond_resched();
703 ksm_page = walk_page_range_vma(vma, addr, end, ops, &addr);
704 if (ksm_page <= 0)
705 return ksm_page;
706 ret = handle_mm_fault(vma, addr,
707 FAULT_FLAG_UNSHARE | FAULT_FLAG_REMOTE,
708 NULL);
709 } while (!(ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
710 /*
711 * We must loop until we no longer find a KSM page because
712 * handle_mm_fault() may back out if there's any difficulty e.g. if
713 * pte accessed bit gets updated concurrently.
714 *
715 * VM_FAULT_SIGBUS could occur if we race with truncation of the
716 * backing file, which also invalidates anonymous pages: that's
717 * okay, that truncation will have unmapped the KSM page for us.
718 *
719 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
720 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
721 * current task has TIF_MEMDIE set, and will be OOM killed on return
722 * to user; and ksmd, having no mm, would never be chosen for that.
723 *
724 * But if the mm is in a limited mem_cgroup, then the fault may fail
725 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
726 * even ksmd can fail in this way - though it's usually breaking ksm
727 * just to undo a merge it made a moment before, so unlikely to oom.
728 *
729 * That's a pity: we might therefore have more kernel pages allocated
730 * than we're counting as nodes in the stable tree; but ksm_do_scan
731 * will retry to break_cow on each pass, so should recover the page
732 * in due course. The important thing is to not let VM_MERGEABLE
733 * be cleared while any such pages might remain in the area.
734 */
735 return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
736 }
737
ksm_compatible(const struct file * file,vma_flags_t vma_flags)738 static bool ksm_compatible(const struct file *file, vma_flags_t vma_flags)
739 {
740 /* Just ignore the advice. */
741 if (vma_flags_test_any(&vma_flags, VMA_SHARED_BIT, VMA_MAYSHARE_BIT,
742 VMA_HUGETLB_BIT))
743 return false;
744 if (vma_flags_test_single_mask(&vma_flags, VMA_DROPPABLE))
745 return false;
746 if (vma_flags_test_any_mask(&vma_flags, VMA_SPECIAL_FLAGS))
747 return false;
748 if (file_is_dax(file))
749 return false;
750 #ifdef VM_SAO
751 if (vma_flags_test(&vma_flags, VMA_SAO_BIT))
752 return false;
753 #endif
754 #ifdef VM_SPARC_ADI
755 if (vma_flags_test(&vma_flags, VMA_SPARC_ADI_BIT))
756 return false;
757 #endif
758
759 return true;
760 }
761
vma_ksm_compatible(struct vm_area_struct * vma)762 static bool vma_ksm_compatible(struct vm_area_struct *vma)
763 {
764 return ksm_compatible(vma->vm_file, vma->flags);
765 }
766
find_mergeable_vma(struct mm_struct * mm,unsigned long addr)767 static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
768 unsigned long addr)
769 {
770 struct vm_area_struct *vma;
771 if (ksm_test_exit(mm))
772 return NULL;
773 vma = vma_lookup(mm, addr);
774 if (!vma || !(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
775 return NULL;
776 return vma;
777 }
778
break_cow(struct ksm_rmap_item * rmap_item)779 static void break_cow(struct ksm_rmap_item *rmap_item)
780 {
781 struct mm_struct *mm = rmap_item->mm;
782 unsigned long addr = rmap_item->address;
783 struct vm_area_struct *vma;
784
785 /*
786 * It is not an accident that whenever we want to break COW
787 * to undo, we also need to drop a reference to the anon_vma.
788 */
789 put_anon_vma(rmap_item->anon_vma);
790
791 mmap_read_lock(mm);
792 vma = find_mergeable_vma(mm, addr);
793 if (vma)
794 break_ksm(vma, addr, addr + PAGE_SIZE, false);
795 mmap_read_unlock(mm);
796 }
797
get_mergeable_page(struct ksm_rmap_item * rmap_item)798 static struct page *get_mergeable_page(struct ksm_rmap_item *rmap_item)
799 {
800 struct mm_struct *mm = rmap_item->mm;
801 unsigned long addr = rmap_item->address;
802 struct vm_area_struct *vma;
803 struct page *page = NULL;
804 struct folio_walk fw;
805 struct folio *folio;
806
807 mmap_read_lock(mm);
808 vma = find_mergeable_vma(mm, addr);
809 if (!vma)
810 goto out;
811
812 folio = folio_walk_start(&fw, vma, addr, 0);
813 if (folio) {
814 if (!folio_is_zone_device(folio) &&
815 folio_test_anon(folio)) {
816 folio_get(folio);
817 page = fw.page;
818 }
819 folio_walk_end(&fw, vma);
820 }
821 out:
822 if (page) {
823 flush_anon_page(vma, page, addr);
824 flush_dcache_page(page);
825 }
826 mmap_read_unlock(mm);
827 return page;
828 }
829
830 /*
831 * This helper is used for getting right index into array of tree roots.
832 * When merge_across_nodes knob is set to 1, there are only two rb-trees for
833 * stable and unstable pages from all nodes with roots in index 0. Otherwise,
834 * every node has its own stable and unstable tree.
835 */
get_kpfn_nid(unsigned long kpfn)836 static inline int get_kpfn_nid(unsigned long kpfn)
837 {
838 return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
839 }
840
alloc_stable_node_chain(struct ksm_stable_node * dup,struct rb_root * root)841 static struct ksm_stable_node *alloc_stable_node_chain(struct ksm_stable_node *dup,
842 struct rb_root *root)
843 {
844 struct ksm_stable_node *chain = alloc_stable_node();
845 VM_BUG_ON(is_stable_node_chain(dup));
846 if (likely(chain)) {
847 INIT_HLIST_HEAD(&chain->hlist);
848 chain->chain_prune_time = jiffies;
849 chain->rmap_hlist_len = STABLE_NODE_CHAIN;
850 #if defined (CONFIG_DEBUG_VM) && defined(CONFIG_NUMA)
851 chain->nid = NUMA_NO_NODE; /* debug */
852 #endif
853 ksm_stable_node_chains++;
854
855 /*
856 * Put the stable node chain in the first dimension of
857 * the stable tree and at the same time remove the old
858 * stable node.
859 */
860 rb_replace_node(&dup->node, &chain->node, root);
861
862 /*
863 * Move the old stable node to the second dimension
864 * queued in the hlist_dup. The invariant is that all
865 * dup stable_nodes in the chain->hlist point to pages
866 * that are write protected and have the exact same
867 * content.
868 */
869 stable_node_chain_add_dup(dup, chain);
870 }
871 return chain;
872 }
873
free_stable_node_chain(struct ksm_stable_node * chain,struct rb_root * root)874 static inline void free_stable_node_chain(struct ksm_stable_node *chain,
875 struct rb_root *root)
876 {
877 rb_erase(&chain->node, root);
878 free_stable_node(chain);
879 ksm_stable_node_chains--;
880 }
881
remove_node_from_stable_tree(struct ksm_stable_node * stable_node)882 static void remove_node_from_stable_tree(struct ksm_stable_node *stable_node)
883 {
884 struct ksm_rmap_item *rmap_item;
885
886 /* check it's not STABLE_NODE_CHAIN or negative */
887 BUG_ON(stable_node->rmap_hlist_len < 0);
888
889 hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
890 if (rmap_item->hlist.next) {
891 ksm_pages_sharing--;
892 trace_ksm_remove_rmap_item(stable_node->kpfn, rmap_item, rmap_item->mm);
893 } else {
894 ksm_pages_shared--;
895 }
896
897 rmap_item->mm->ksm_merging_pages--;
898
899 VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
900 stable_node->rmap_hlist_len--;
901 put_anon_vma(rmap_item->anon_vma);
902 rmap_item->address &= PAGE_MASK;
903 cond_resched();
904 }
905
906 /*
907 * We need the second aligned pointer of the migrate_nodes
908 * list_head to stay clear from the rb_parent_color union
909 * (aligned and different than any node) and also different
910 * from &migrate_nodes. This will verify that future list.h changes
911 * don't break STABLE_NODE_DUP_HEAD. Only recent gcc can handle it.
912 */
913 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD <= &migrate_nodes);
914 BUILD_BUG_ON(STABLE_NODE_DUP_HEAD >= &migrate_nodes + 1);
915
916 trace_ksm_remove_ksm_page(stable_node->kpfn);
917 if (stable_node->head == &migrate_nodes)
918 list_del(&stable_node->list);
919 else
920 stable_node_dup_del(stable_node);
921 free_stable_node(stable_node);
922 }
923
924 enum ksm_get_folio_flags {
925 KSM_GET_FOLIO_NOLOCK,
926 KSM_GET_FOLIO_LOCK,
927 KSM_GET_FOLIO_TRYLOCK
928 };
929
930 /*
931 * ksm_get_folio: checks if the page indicated by the stable node
932 * is still its ksm page, despite having held no reference to it.
933 * In which case we can trust the content of the page, and it
934 * returns the gotten page; but if the page has now been zapped,
935 * remove the stale node from the stable tree and return NULL.
936 * But beware, the stable node's page might be being migrated.
937 *
938 * You would expect the stable_node to hold a reference to the ksm page.
939 * But if it increments the page's count, swapping out has to wait for
940 * ksmd to come around again before it can free the page, which may take
941 * seconds or even minutes: much too unresponsive. So instead we use a
942 * "keyhole reference": access to the ksm page from the stable node peeps
943 * out through its keyhole to see if that page still holds the right key,
944 * pointing back to this stable node. This relies on freeing a PageAnon
945 * page to reset its page->mapping to NULL, and relies on no other use of
946 * a page to put something that might look like our key in page->mapping.
947 * is on its way to being freed; but it is an anomaly to bear in mind.
948 */
ksm_get_folio(struct ksm_stable_node * stable_node,enum ksm_get_folio_flags flags)949 static struct folio *ksm_get_folio(struct ksm_stable_node *stable_node,
950 enum ksm_get_folio_flags flags)
951 {
952 struct folio *folio;
953 void *expected_mapping;
954 unsigned long kpfn;
955
956 expected_mapping = (void *)((unsigned long)stable_node |
957 FOLIO_MAPPING_KSM);
958 again:
959 kpfn = READ_ONCE(stable_node->kpfn); /* Address dependency. */
960 folio = pfn_folio(kpfn);
961 if (READ_ONCE(folio->mapping) != expected_mapping)
962 goto stale;
963
964 /*
965 * We cannot do anything with the page while its refcount is 0.
966 * Usually 0 means free, or tail of a higher-order page: in which
967 * case this node is no longer referenced, and should be freed;
968 * however, it might mean that the page is under page_ref_freeze().
969 * The __remove_mapping() case is easy, again the node is now stale;
970 * the same is in reuse_ksm_page() case; but if page is swapcache
971 * in folio_migrate_mapping(), it might still be our page,
972 * in which case it's essential to keep the node.
973 */
974 while (!folio_try_get(folio)) {
975 /*
976 * Another check for folio->mapping != expected_mapping
977 * would work here too. We have chosen to test the
978 * swapcache flag to optimize the common case, when the
979 * folio is or is about to be freed: the swapcache flag
980 * is cleared (under spin_lock_irq) in the ref_freeze
981 * section of __remove_mapping(); but anon folio->mapping
982 * is reset to NULL later, in free_pages_prepare().
983 */
984 if (!folio_test_swapcache(folio))
985 goto stale;
986 cpu_relax();
987 }
988
989 if (READ_ONCE(folio->mapping) != expected_mapping) {
990 folio_put(folio);
991 goto stale;
992 }
993
994 if (flags == KSM_GET_FOLIO_TRYLOCK) {
995 if (!folio_trylock(folio)) {
996 folio_put(folio);
997 return ERR_PTR(-EBUSY);
998 }
999 } else if (flags == KSM_GET_FOLIO_LOCK)
1000 folio_lock(folio);
1001
1002 if (flags != KSM_GET_FOLIO_NOLOCK) {
1003 if (READ_ONCE(folio->mapping) != expected_mapping) {
1004 folio_unlock(folio);
1005 folio_put(folio);
1006 goto stale;
1007 }
1008 }
1009 return folio;
1010
1011 stale:
1012 /*
1013 * We come here from above when folio->mapping or the swapcache flag
1014 * suggests that the node is stale; but it might be under migration.
1015 * We need smp_rmb(), matching the smp_wmb() in folio_migrate_ksm(),
1016 * before checking whether node->kpfn has been changed.
1017 */
1018 smp_rmb();
1019 if (READ_ONCE(stable_node->kpfn) != kpfn)
1020 goto again;
1021 remove_node_from_stable_tree(stable_node);
1022 return NULL;
1023 }
1024
1025 /*
1026 * Removing rmap_item from stable or unstable tree.
1027 * This function will clean the information from the stable/unstable tree.
1028 */
remove_rmap_item_from_tree(struct ksm_rmap_item * rmap_item)1029 static void remove_rmap_item_from_tree(struct ksm_rmap_item *rmap_item)
1030 {
1031 if (rmap_item->address & STABLE_FLAG) {
1032 struct ksm_stable_node *stable_node;
1033 struct folio *folio;
1034
1035 stable_node = rmap_item->head;
1036 folio = ksm_get_folio(stable_node, KSM_GET_FOLIO_LOCK);
1037 if (!folio)
1038 goto out;
1039
1040 hlist_del(&rmap_item->hlist);
1041 folio_unlock(folio);
1042 folio_put(folio);
1043
1044 if (!hlist_empty(&stable_node->hlist))
1045 ksm_pages_sharing--;
1046 else
1047 ksm_pages_shared--;
1048
1049 rmap_item->mm->ksm_merging_pages--;
1050
1051 VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
1052 stable_node->rmap_hlist_len--;
1053
1054 put_anon_vma(rmap_item->anon_vma);
1055 rmap_item->head = NULL;
1056 rmap_item->address &= PAGE_MASK;
1057
1058 } else if (rmap_item->address & UNSTABLE_FLAG) {
1059 unsigned char age;
1060 /*
1061 * Usually ksmd can and must skip the rb_erase, because
1062 * root_unstable_tree was already reset to RB_ROOT.
1063 * But be careful when an mm is exiting: do the rb_erase
1064 * if this rmap_item was inserted by this scan, rather
1065 * than left over from before.
1066 */
1067 age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
1068 BUG_ON(age > 1);
1069 if (!age)
1070 rb_erase(&rmap_item->node,
1071 root_unstable_tree + NUMA(rmap_item->nid));
1072 ksm_pages_unshared--;
1073 rmap_item->address &= PAGE_MASK;
1074 }
1075 out:
1076 cond_resched(); /* we're called from many long loops */
1077 }
1078
remove_trailing_rmap_items(struct ksm_rmap_item ** rmap_list)1079 static void remove_trailing_rmap_items(struct ksm_rmap_item **rmap_list)
1080 {
1081 while (*rmap_list) {
1082 struct ksm_rmap_item *rmap_item = *rmap_list;
1083 *rmap_list = rmap_item->rmap_list;
1084 remove_rmap_item_from_tree(rmap_item);
1085 free_rmap_item(rmap_item);
1086 }
1087 }
1088
1089 static inline
folio_stable_node(const struct folio * folio)1090 struct ksm_stable_node *folio_stable_node(const struct folio *folio)
1091 {
1092 return folio_test_ksm(folio) ? folio_raw_mapping(folio) : NULL;
1093 }
1094
folio_set_stable_node(struct folio * folio,struct ksm_stable_node * stable_node)1095 static inline void folio_set_stable_node(struct folio *folio,
1096 struct ksm_stable_node *stable_node)
1097 {
1098 VM_WARN_ON_FOLIO(folio_test_anon(folio) && PageAnonExclusive(&folio->page), folio);
1099 folio->mapping = (void *)((unsigned long)stable_node | FOLIO_MAPPING_KSM);
1100 }
1101
1102 #ifdef CONFIG_SYSFS
1103 /*
1104 * Only called through the sysfs control interface:
1105 */
remove_stable_node(struct ksm_stable_node * stable_node)1106 static int remove_stable_node(struct ksm_stable_node *stable_node)
1107 {
1108 struct folio *folio;
1109 int err;
1110
1111 folio = ksm_get_folio(stable_node, KSM_GET_FOLIO_LOCK);
1112 if (!folio) {
1113 /*
1114 * ksm_get_folio did remove_node_from_stable_tree itself.
1115 */
1116 return 0;
1117 }
1118
1119 /*
1120 * Page could be still mapped if this races with __mmput() running in
1121 * between ksm_exit() and exit_mmap(). Just refuse to let
1122 * merge_across_nodes/max_page_sharing be switched.
1123 */
1124 err = -EBUSY;
1125 if (!folio_mapped(folio)) {
1126 /*
1127 * The stable node did not yet appear stale to ksm_get_folio(),
1128 * since that allows for an unmapped ksm folio to be recognized
1129 * right up until it is freed; but the node is safe to remove.
1130 * This folio might be in an LRU cache waiting to be freed,
1131 * or it might be in the swapcache (perhaps under writeback),
1132 * or it might have been removed from swapcache a moment ago.
1133 */
1134 folio_set_stable_node(folio, NULL);
1135 remove_node_from_stable_tree(stable_node);
1136 err = 0;
1137 }
1138
1139 folio_unlock(folio);
1140 folio_put(folio);
1141 return err;
1142 }
1143
remove_stable_node_chain(struct ksm_stable_node * stable_node,struct rb_root * root)1144 static int remove_stable_node_chain(struct ksm_stable_node *stable_node,
1145 struct rb_root *root)
1146 {
1147 struct ksm_stable_node *dup;
1148 struct hlist_node *hlist_safe;
1149
1150 if (!is_stable_node_chain(stable_node)) {
1151 VM_BUG_ON(is_stable_node_dup(stable_node));
1152 if (remove_stable_node(stable_node))
1153 return true;
1154 else
1155 return false;
1156 }
1157
1158 hlist_for_each_entry_safe(dup, hlist_safe,
1159 &stable_node->hlist, hlist_dup) {
1160 VM_BUG_ON(!is_stable_node_dup(dup));
1161 if (remove_stable_node(dup))
1162 return true;
1163 }
1164 BUG_ON(!hlist_empty(&stable_node->hlist));
1165 free_stable_node_chain(stable_node, root);
1166 return false;
1167 }
1168
remove_all_stable_nodes(void)1169 static int remove_all_stable_nodes(void)
1170 {
1171 struct ksm_stable_node *stable_node, *next;
1172 int nid;
1173 int err = 0;
1174
1175 for (nid = 0; nid < ksm_nr_node_ids; nid++) {
1176 while (root_stable_tree[nid].rb_node) {
1177 stable_node = rb_entry(root_stable_tree[nid].rb_node,
1178 struct ksm_stable_node, node);
1179 if (remove_stable_node_chain(stable_node,
1180 root_stable_tree + nid)) {
1181 err = -EBUSY;
1182 break; /* proceed to next nid */
1183 }
1184 cond_resched();
1185 }
1186 }
1187 list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
1188 if (remove_stable_node(stable_node))
1189 err = -EBUSY;
1190 cond_resched();
1191 }
1192 return err;
1193 }
1194
unmerge_and_remove_all_rmap_items(void)1195 static int unmerge_and_remove_all_rmap_items(void)
1196 {
1197 struct ksm_mm_slot *mm_slot;
1198 struct mm_slot *slot;
1199 struct mm_struct *mm;
1200 struct vm_area_struct *vma;
1201 int err = 0;
1202
1203 spin_lock(&ksm_mmlist_lock);
1204 slot = list_entry(ksm_mm_head.slot.mm_node.next,
1205 struct mm_slot, mm_node);
1206 ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
1207 spin_unlock(&ksm_mmlist_lock);
1208
1209 for (mm_slot = ksm_scan.mm_slot; mm_slot != &ksm_mm_head;
1210 mm_slot = ksm_scan.mm_slot) {
1211 VMA_ITERATOR(vmi, mm_slot->slot.mm, 0);
1212
1213 mm = mm_slot->slot.mm;
1214 mmap_read_lock(mm);
1215
1216 /*
1217 * Exit right away if mm is exiting to avoid lockdep issue in
1218 * the maple tree
1219 */
1220 if (ksm_test_exit(mm))
1221 goto mm_exiting;
1222
1223 for_each_vma(vmi, vma) {
1224 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
1225 continue;
1226 err = break_ksm(vma, vma->vm_start, vma->vm_end, false);
1227 if (err)
1228 goto error;
1229 }
1230
1231 mm_exiting:
1232 remove_trailing_rmap_items(&mm_slot->rmap_list);
1233 mmap_read_unlock(mm);
1234
1235 spin_lock(&ksm_mmlist_lock);
1236 slot = list_entry(mm_slot->slot.mm_node.next,
1237 struct mm_slot, mm_node);
1238 ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
1239 if (ksm_test_exit(mm)) {
1240 hash_del(&mm_slot->slot.hash);
1241 list_del(&mm_slot->slot.mm_node);
1242 spin_unlock(&ksm_mmlist_lock);
1243
1244 mm_slot_free(mm_slot_cache, mm_slot);
1245 mm_flags_clear(MMF_VM_MERGEABLE, mm);
1246 mm_flags_clear(MMF_VM_MERGE_ANY, mm);
1247 mmdrop(mm);
1248 } else
1249 spin_unlock(&ksm_mmlist_lock);
1250 }
1251
1252 /* Clean up stable nodes, but don't worry if some are still busy */
1253 remove_all_stable_nodes();
1254 ksm_scan.seqnr = 0;
1255 return 0;
1256
1257 error:
1258 mmap_read_unlock(mm);
1259 spin_lock(&ksm_mmlist_lock);
1260 ksm_scan.mm_slot = &ksm_mm_head;
1261 spin_unlock(&ksm_mmlist_lock);
1262 return err;
1263 }
1264 #endif /* CONFIG_SYSFS */
1265
calc_checksum(struct page * page)1266 static u32 calc_checksum(struct page *page)
1267 {
1268 u32 checksum;
1269 void *addr = kmap_local_page(page);
1270 checksum = xxhash(addr, PAGE_SIZE, 0);
1271 kunmap_local(addr);
1272 return checksum;
1273 }
1274
write_protect_page(struct vm_area_struct * vma,struct folio * folio,pte_t * orig_pte)1275 static int write_protect_page(struct vm_area_struct *vma, struct folio *folio,
1276 pte_t *orig_pte)
1277 {
1278 struct mm_struct *mm = vma->vm_mm;
1279 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, 0, 0);
1280 int swapped;
1281 int err = -EFAULT;
1282 struct mmu_notifier_range range;
1283 bool anon_exclusive;
1284 pte_t entry;
1285
1286 if (WARN_ON_ONCE(folio_test_large(folio)))
1287 return err;
1288
1289 pvmw.address = page_address_in_vma(folio, folio_page(folio, 0), vma);
1290 if (pvmw.address == -EFAULT)
1291 goto out;
1292
1293 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, pvmw.address,
1294 pvmw.address + PAGE_SIZE);
1295 mmu_notifier_invalidate_range_start(&range);
1296
1297 if (!page_vma_mapped_walk(&pvmw))
1298 goto out_mn;
1299 if (WARN_ONCE(!pvmw.pte, "Unexpected PMD mapping?"))
1300 goto out_unlock;
1301
1302 entry = ptep_get(pvmw.pte);
1303 /*
1304 * Handle PFN swap PTEs, such as device-exclusive ones, that actually
1305 * map pages: give up just like the next folio_walk would.
1306 */
1307 if (unlikely(!pte_present(entry)))
1308 goto out_unlock;
1309
1310 anon_exclusive = PageAnonExclusive(&folio->page);
1311 if (pte_write(entry) || pte_dirty(entry) ||
1312 anon_exclusive || mm_tlb_flush_pending(mm)) {
1313 swapped = folio_test_swapcache(folio);
1314 flush_cache_page(vma, pvmw.address, folio_pfn(folio));
1315 /*
1316 * Ok this is tricky, when get_user_pages_fast() run it doesn't
1317 * take any lock, therefore the check that we are going to make
1318 * with the pagecount against the mapcount is racy and
1319 * O_DIRECT can happen right after the check.
1320 * So we clear the pte and flush the tlb before the check
1321 * this assure us that no O_DIRECT can happen after the check
1322 * or in the middle of the check.
1323 *
1324 * No need to notify as we are downgrading page table to read
1325 * only not changing it to point to a new page.
1326 *
1327 * See Documentation/mm/mmu_notifier.rst
1328 */
1329 entry = ptep_clear_flush(vma, pvmw.address, pvmw.pte);
1330 /*
1331 * Check that no O_DIRECT or similar I/O is in progress on the
1332 * page
1333 */
1334 if (folio_mapcount(folio) + 1 + swapped != folio_ref_count(folio)) {
1335 set_pte_at(mm, pvmw.address, pvmw.pte, entry);
1336 goto out_unlock;
1337 }
1338
1339 /* See folio_try_share_anon_rmap_pte(): clear PTE first. */
1340 if (anon_exclusive &&
1341 folio_try_share_anon_rmap_pte(folio, &folio->page)) {
1342 set_pte_at(mm, pvmw.address, pvmw.pte, entry);
1343 goto out_unlock;
1344 }
1345
1346 if (pte_dirty(entry))
1347 folio_mark_dirty(folio);
1348 entry = pte_mkclean(entry);
1349
1350 if (pte_write(entry))
1351 entry = pte_wrprotect(entry);
1352
1353 set_pte_at(mm, pvmw.address, pvmw.pte, entry);
1354 }
1355 *orig_pte = entry;
1356 err = 0;
1357
1358 out_unlock:
1359 page_vma_mapped_walk_done(&pvmw);
1360 out_mn:
1361 mmu_notifier_invalidate_range_end(&range);
1362 out:
1363 return err;
1364 }
1365
1366 /**
1367 * replace_page - replace page in vma by new ksm page
1368 * @vma: vma that holds the pte pointing to page
1369 * @page: the page we are replacing by kpage
1370 * @kpage: the ksm page we replace page by
1371 * @orig_pte: the original value of the pte
1372 *
1373 * Returns 0 on success, -EFAULT on failure.
1374 */
replace_page(struct vm_area_struct * vma,struct page * page,struct page * kpage,pte_t orig_pte)1375 static int replace_page(struct vm_area_struct *vma, struct page *page,
1376 struct page *kpage, pte_t orig_pte)
1377 {
1378 struct folio *kfolio = page_folio(kpage);
1379 struct mm_struct *mm = vma->vm_mm;
1380 struct folio *folio = page_folio(page);
1381 pmd_t *pmd;
1382 pmd_t pmde;
1383 pte_t *ptep;
1384 pte_t newpte;
1385 spinlock_t *ptl;
1386 unsigned long addr;
1387 int err = -EFAULT;
1388 struct mmu_notifier_range range;
1389
1390 addr = page_address_in_vma(folio, page, vma);
1391 if (addr == -EFAULT)
1392 goto out;
1393
1394 pmd = mm_find_pmd(mm, addr);
1395 if (!pmd)
1396 goto out;
1397 /*
1398 * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
1399 * without holding anon_vma lock for write. So when looking for a
1400 * genuine pmde (in which to find pte), test present and !THP together.
1401 */
1402 pmde = pmdp_get_lockless(pmd);
1403 if (!pmd_present(pmde) || pmd_trans_huge(pmde))
1404 goto out;
1405
1406 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, addr,
1407 addr + PAGE_SIZE);
1408 mmu_notifier_invalidate_range_start(&range);
1409
1410 ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
1411 if (!ptep)
1412 goto out_mn;
1413 if (!pte_same(ptep_get(ptep), orig_pte)) {
1414 pte_unmap_unlock(ptep, ptl);
1415 goto out_mn;
1416 }
1417 VM_BUG_ON_PAGE(PageAnonExclusive(page), page);
1418 VM_BUG_ON_FOLIO(folio_test_anon(kfolio) && PageAnonExclusive(kpage),
1419 kfolio);
1420
1421 /*
1422 * No need to check ksm_use_zero_pages here: we can only have a
1423 * zero_page here if ksm_use_zero_pages was enabled already.
1424 */
1425 if (!is_zero_pfn(page_to_pfn(kpage))) {
1426 folio_get(kfolio);
1427 folio_add_anon_rmap_pte(kfolio, kpage, vma, addr, RMAP_NONE);
1428 newpte = mk_pte(kpage, vma->vm_page_prot);
1429 } else {
1430 /*
1431 * Use pte_mkdirty to mark the zero page mapped by KSM, and then
1432 * we can easily track all KSM-placed zero pages by checking if
1433 * the dirty bit in zero page's PTE is set.
1434 */
1435 newpte = pte_mkdirty(pte_mkspecial(pfn_pte(page_to_pfn(kpage), vma->vm_page_prot)));
1436 ksm_map_zero_page(mm);
1437 /*
1438 * We're replacing an anonymous page with a zero page, which is
1439 * not anonymous. We need to do proper accounting otherwise we
1440 * will get wrong values in /proc, and a BUG message in dmesg
1441 * when tearing down the mm.
1442 */
1443 dec_mm_counter(mm, MM_ANONPAGES);
1444 }
1445
1446 flush_cache_page(vma, addr, pte_pfn(ptep_get(ptep)));
1447 /*
1448 * No need to notify as we are replacing a read only page with another
1449 * read only page with the same content.
1450 *
1451 * See Documentation/mm/mmu_notifier.rst
1452 */
1453 ptep_clear_flush(vma, addr, ptep);
1454 set_pte_at(mm, addr, ptep, newpte);
1455
1456 folio_remove_rmap_pte(folio, page, vma);
1457 if (!folio_mapped(folio))
1458 folio_free_swap(folio);
1459 folio_put(folio);
1460
1461 pte_unmap_unlock(ptep, ptl);
1462 err = 0;
1463 out_mn:
1464 mmu_notifier_invalidate_range_end(&range);
1465 out:
1466 return err;
1467 }
1468
1469 /*
1470 * try_to_merge_one_page - take two pages and merge them into one
1471 * @vma: the vma that holds the pte pointing to page
1472 * @page: the PageAnon page that we want to replace with kpage
1473 * @kpage: the KSM page that we want to map instead of page,
1474 * or NULL the first time when we want to use page as kpage.
1475 *
1476 * This function returns 0 if the pages were merged, -EFAULT otherwise.
1477 */
try_to_merge_one_page(struct vm_area_struct * vma,struct page * page,struct page * kpage)1478 static int try_to_merge_one_page(struct vm_area_struct *vma,
1479 struct page *page, struct page *kpage)
1480 {
1481 struct folio *folio = page_folio(page);
1482 pte_t orig_pte = __pte(0);
1483 int err = -EFAULT;
1484
1485 if (page == kpage) /* ksm page forked */
1486 return 0;
1487
1488 if (!folio_test_anon(folio))
1489 goto out;
1490
1491 /*
1492 * We need the folio lock to read a stable swapcache flag in
1493 * write_protect_page(). We trylock because we don't want to wait
1494 * here - we prefer to continue scanning and merging different
1495 * pages, then come back to this page when it is unlocked.
1496 */
1497 if (!folio_trylock(folio))
1498 goto out;
1499
1500 if (folio_test_large(folio)) {
1501 if (split_huge_page(page))
1502 goto out_unlock;
1503 folio = page_folio(page);
1504 }
1505
1506 /*
1507 * If this anonymous page is mapped only here, its pte may need
1508 * to be write-protected. If it's mapped elsewhere, all of its
1509 * ptes are necessarily already write-protected. But in either
1510 * case, we need to lock and check page_count is not raised.
1511 */
1512 if (write_protect_page(vma, folio, &orig_pte) == 0) {
1513 if (!kpage) {
1514 /*
1515 * While we hold folio lock, upgrade folio from
1516 * anon to a NULL stable_node with the KSM flag set:
1517 * stable_tree_insert() will update stable_node.
1518 */
1519 folio_set_stable_node(folio, NULL);
1520 folio_mark_accessed(folio);
1521 /*
1522 * Page reclaim just frees a clean folio with no dirty
1523 * ptes: make sure that the ksm page would be swapped.
1524 */
1525 if (!folio_test_dirty(folio))
1526 folio_mark_dirty(folio);
1527 err = 0;
1528 } else if (pages_identical(page, kpage))
1529 err = replace_page(vma, page, kpage, orig_pte);
1530 }
1531
1532 out_unlock:
1533 folio_unlock(folio);
1534 out:
1535 return err;
1536 }
1537
1538 /*
1539 * This function returns 0 if the pages were merged or if they are
1540 * no longer merging candidates (e.g., VMA stale), -EFAULT otherwise.
1541 */
try_to_merge_with_zero_page(struct ksm_rmap_item * rmap_item,struct page * page)1542 static int try_to_merge_with_zero_page(struct ksm_rmap_item *rmap_item,
1543 struct page *page)
1544 {
1545 struct mm_struct *mm = rmap_item->mm;
1546 int err = -EFAULT;
1547
1548 /*
1549 * Same checksum as an empty page. We attempt to merge it with the
1550 * appropriate zero page if the user enabled this via sysfs.
1551 */
1552 if (ksm_use_zero_pages && (rmap_item->oldchecksum == zero_checksum)) {
1553 struct vm_area_struct *vma;
1554
1555 mmap_read_lock(mm);
1556 vma = find_mergeable_vma(mm, rmap_item->address);
1557 if (vma) {
1558 err = try_to_merge_one_page(vma, page,
1559 ZERO_PAGE(rmap_item->address));
1560 trace_ksm_merge_one_page(
1561 page_to_pfn(ZERO_PAGE(rmap_item->address)),
1562 rmap_item, mm, err);
1563 } else {
1564 /*
1565 * If the vma is out of date, we do not need to
1566 * continue.
1567 */
1568 err = 0;
1569 }
1570 mmap_read_unlock(mm);
1571 }
1572
1573 return err;
1574 }
1575
1576 /*
1577 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
1578 * but no new kernel page is allocated: kpage must already be a ksm page.
1579 *
1580 * This function returns 0 if the pages were merged, -EFAULT otherwise.
1581 */
try_to_merge_with_ksm_page(struct ksm_rmap_item * rmap_item,struct page * page,struct page * kpage)1582 static int try_to_merge_with_ksm_page(struct ksm_rmap_item *rmap_item,
1583 struct page *page, struct page *kpage)
1584 {
1585 struct mm_struct *mm = rmap_item->mm;
1586 struct vm_area_struct *vma;
1587 int err = -EFAULT;
1588
1589 mmap_read_lock(mm);
1590 vma = find_mergeable_vma(mm, rmap_item->address);
1591 if (!vma)
1592 goto out;
1593
1594 err = try_to_merge_one_page(vma, page, kpage);
1595 if (err)
1596 goto out;
1597
1598 /* Unstable nid is in union with stable anon_vma: remove first */
1599 remove_rmap_item_from_tree(rmap_item);
1600
1601 /* Must get reference to anon_vma while still holding mmap_lock */
1602 rmap_item->anon_vma = vma->anon_vma;
1603 get_anon_vma(vma->anon_vma);
1604 out:
1605 mmap_read_unlock(mm);
1606 trace_ksm_merge_with_ksm_page(kpage, page_to_pfn(kpage ? kpage : page),
1607 rmap_item, mm, err);
1608 return err;
1609 }
1610
1611 /*
1612 * try_to_merge_two_pages - take two identical pages and prepare them
1613 * to be merged into one page.
1614 *
1615 * This function returns the kpage if we successfully merged two identical
1616 * pages into one ksm page, NULL otherwise.
1617 *
1618 * Note that this function upgrades page to ksm page: if one of the pages
1619 * is already a ksm page, try_to_merge_with_ksm_page should be used.
1620 */
try_to_merge_two_pages(struct ksm_rmap_item * rmap_item,struct page * page,struct ksm_rmap_item * tree_rmap_item,struct page * tree_page)1621 static struct folio *try_to_merge_two_pages(struct ksm_rmap_item *rmap_item,
1622 struct page *page,
1623 struct ksm_rmap_item *tree_rmap_item,
1624 struct page *tree_page)
1625 {
1626 int err;
1627
1628 err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
1629 if (!err) {
1630 err = try_to_merge_with_ksm_page(tree_rmap_item,
1631 tree_page, page);
1632 /*
1633 * If that fails, we have a ksm page with only one pte
1634 * pointing to it: so break it.
1635 */
1636 if (err)
1637 break_cow(rmap_item);
1638 }
1639 return err ? NULL : page_folio(page);
1640 }
1641
1642 static __always_inline
__is_page_sharing_candidate(struct ksm_stable_node * stable_node,int offset)1643 bool __is_page_sharing_candidate(struct ksm_stable_node *stable_node, int offset)
1644 {
1645 VM_BUG_ON(stable_node->rmap_hlist_len < 0);
1646 /*
1647 * Check that at least one mapping still exists, otherwise
1648 * there's no much point to merge and share with this
1649 * stable_node, as the underlying tree_page of the other
1650 * sharer is going to be freed soon.
1651 */
1652 return stable_node->rmap_hlist_len &&
1653 stable_node->rmap_hlist_len + offset < ksm_max_page_sharing;
1654 }
1655
1656 static __always_inline
is_page_sharing_candidate(struct ksm_stable_node * stable_node)1657 bool is_page_sharing_candidate(struct ksm_stable_node *stable_node)
1658 {
1659 return __is_page_sharing_candidate(stable_node, 0);
1660 }
1661
stable_node_dup(struct ksm_stable_node ** _stable_node_dup,struct ksm_stable_node ** _stable_node,struct rb_root * root,bool prune_stale_stable_nodes)1662 static struct folio *stable_node_dup(struct ksm_stable_node **_stable_node_dup,
1663 struct ksm_stable_node **_stable_node,
1664 struct rb_root *root,
1665 bool prune_stale_stable_nodes)
1666 {
1667 struct ksm_stable_node *dup, *found = NULL, *stable_node = *_stable_node;
1668 struct hlist_node *hlist_safe;
1669 struct folio *folio, *tree_folio = NULL;
1670 int found_rmap_hlist_len;
1671
1672 if (!prune_stale_stable_nodes ||
1673 time_before(jiffies, stable_node->chain_prune_time +
1674 msecs_to_jiffies(
1675 ksm_stable_node_chains_prune_millisecs)))
1676 prune_stale_stable_nodes = false;
1677 else
1678 stable_node->chain_prune_time = jiffies;
1679
1680 hlist_for_each_entry_safe(dup, hlist_safe,
1681 &stable_node->hlist, hlist_dup) {
1682 cond_resched();
1683 /*
1684 * We must walk all stable_node_dup to prune the stale
1685 * stable nodes during lookup.
1686 *
1687 * ksm_get_folio can drop the nodes from the
1688 * stable_node->hlist if they point to freed pages
1689 * (that's why we do a _safe walk). The "dup"
1690 * stable_node parameter itself will be freed from
1691 * under us if it returns NULL.
1692 */
1693 folio = ksm_get_folio(dup, KSM_GET_FOLIO_NOLOCK);
1694 if (!folio)
1695 continue;
1696 /* Pick the best candidate if possible. */
1697 if (!found || (is_page_sharing_candidate(dup) &&
1698 (!is_page_sharing_candidate(found) ||
1699 dup->rmap_hlist_len > found_rmap_hlist_len))) {
1700 if (found)
1701 folio_put(tree_folio);
1702 found = dup;
1703 found_rmap_hlist_len = found->rmap_hlist_len;
1704 tree_folio = folio;
1705 /* skip put_page for found candidate */
1706 if (!prune_stale_stable_nodes &&
1707 is_page_sharing_candidate(found))
1708 break;
1709 continue;
1710 }
1711 folio_put(folio);
1712 }
1713
1714 if (found) {
1715 if (hlist_is_singular_node(&found->hlist_dup, &stable_node->hlist)) {
1716 /*
1717 * If there's not just one entry it would
1718 * corrupt memory, better BUG_ON. In KSM
1719 * context with no lock held it's not even
1720 * fatal.
1721 */
1722 BUG_ON(stable_node->hlist.first->next);
1723
1724 /*
1725 * There's just one entry and it is below the
1726 * deduplication limit so drop the chain.
1727 */
1728 rb_replace_node(&stable_node->node, &found->node,
1729 root);
1730 free_stable_node(stable_node);
1731 ksm_stable_node_chains--;
1732 ksm_stable_node_dups--;
1733 /*
1734 * NOTE: the caller depends on the stable_node
1735 * to be equal to stable_node_dup if the chain
1736 * was collapsed.
1737 */
1738 *_stable_node = found;
1739 /*
1740 * Just for robustness, as stable_node is
1741 * otherwise left as a stable pointer, the
1742 * compiler shall optimize it away at build
1743 * time.
1744 */
1745 stable_node = NULL;
1746 } else if (stable_node->hlist.first != &found->hlist_dup &&
1747 __is_page_sharing_candidate(found, 1)) {
1748 /*
1749 * If the found stable_node dup can accept one
1750 * more future merge (in addition to the one
1751 * that is underway) and is not at the head of
1752 * the chain, put it there so next search will
1753 * be quicker in the !prune_stale_stable_nodes
1754 * case.
1755 *
1756 * NOTE: it would be inaccurate to use nr > 1
1757 * instead of checking the hlist.first pointer
1758 * directly, because in the
1759 * prune_stale_stable_nodes case "nr" isn't
1760 * the position of the found dup in the chain,
1761 * but the total number of dups in the chain.
1762 */
1763 hlist_del(&found->hlist_dup);
1764 hlist_add_head(&found->hlist_dup,
1765 &stable_node->hlist);
1766 }
1767 } else {
1768 /* Its hlist must be empty if no one found. */
1769 free_stable_node_chain(stable_node, root);
1770 }
1771
1772 *_stable_node_dup = found;
1773 return tree_folio;
1774 }
1775
1776 /*
1777 * Like for ksm_get_folio, this function can free the *_stable_node and
1778 * *_stable_node_dup if the returned tree_page is NULL.
1779 *
1780 * It can also free and overwrite *_stable_node with the found
1781 * stable_node_dup if the chain is collapsed (in which case
1782 * *_stable_node will be equal to *_stable_node_dup like if the chain
1783 * never existed). It's up to the caller to verify tree_page is not
1784 * NULL before dereferencing *_stable_node or *_stable_node_dup.
1785 *
1786 * *_stable_node_dup is really a second output parameter of this
1787 * function and will be overwritten in all cases, the caller doesn't
1788 * need to initialize it.
1789 */
__stable_node_chain(struct ksm_stable_node ** _stable_node_dup,struct ksm_stable_node ** _stable_node,struct rb_root * root,bool prune_stale_stable_nodes)1790 static struct folio *__stable_node_chain(struct ksm_stable_node **_stable_node_dup,
1791 struct ksm_stable_node **_stable_node,
1792 struct rb_root *root,
1793 bool prune_stale_stable_nodes)
1794 {
1795 struct ksm_stable_node *stable_node = *_stable_node;
1796
1797 if (!is_stable_node_chain(stable_node)) {
1798 *_stable_node_dup = stable_node;
1799 return ksm_get_folio(stable_node, KSM_GET_FOLIO_NOLOCK);
1800 }
1801 return stable_node_dup(_stable_node_dup, _stable_node, root,
1802 prune_stale_stable_nodes);
1803 }
1804
chain_prune(struct ksm_stable_node ** s_n_d,struct ksm_stable_node ** s_n,struct rb_root * root)1805 static __always_inline struct folio *chain_prune(struct ksm_stable_node **s_n_d,
1806 struct ksm_stable_node **s_n,
1807 struct rb_root *root)
1808 {
1809 return __stable_node_chain(s_n_d, s_n, root, true);
1810 }
1811
chain(struct ksm_stable_node ** s_n_d,struct ksm_stable_node ** s_n,struct rb_root * root)1812 static __always_inline struct folio *chain(struct ksm_stable_node **s_n_d,
1813 struct ksm_stable_node **s_n,
1814 struct rb_root *root)
1815 {
1816 return __stable_node_chain(s_n_d, s_n, root, false);
1817 }
1818
1819 /*
1820 * stable_tree_search - search for page inside the stable tree
1821 *
1822 * This function checks if there is a page inside the stable tree
1823 * with identical content to the page that we are scanning right now.
1824 *
1825 * This function returns the stable tree node of identical content if found,
1826 * -EBUSY if the stable node's page is being migrated, NULL otherwise.
1827 */
stable_tree_search(struct page * page)1828 static struct folio *stable_tree_search(struct page *page)
1829 {
1830 int nid;
1831 struct rb_root *root;
1832 struct rb_node **new;
1833 struct rb_node *parent;
1834 struct ksm_stable_node *stable_node, *stable_node_dup;
1835 struct ksm_stable_node *page_node;
1836 struct folio *folio;
1837
1838 folio = page_folio(page);
1839 page_node = folio_stable_node(folio);
1840 if (page_node && page_node->head != &migrate_nodes) {
1841 /* ksm page forked */
1842 folio_get(folio);
1843 return folio;
1844 }
1845
1846 nid = get_kpfn_nid(folio_pfn(folio));
1847 root = root_stable_tree + nid;
1848 again:
1849 new = &root->rb_node;
1850 parent = NULL;
1851
1852 while (*new) {
1853 struct folio *tree_folio;
1854 int ret;
1855
1856 cond_resched();
1857 stable_node = rb_entry(*new, struct ksm_stable_node, node);
1858 tree_folio = chain_prune(&stable_node_dup, &stable_node, root);
1859 if (!tree_folio) {
1860 /*
1861 * If we walked over a stale stable_node,
1862 * ksm_get_folio() will call rb_erase() and it
1863 * may rebalance the tree from under us. So
1864 * restart the search from scratch. Returning
1865 * NULL would be safe too, but we'd generate
1866 * false negative insertions just because some
1867 * stable_node was stale.
1868 */
1869 goto again;
1870 }
1871
1872 ret = memcmp_pages(page, &tree_folio->page);
1873 folio_put(tree_folio);
1874
1875 parent = *new;
1876 if (ret < 0)
1877 new = &parent->rb_left;
1878 else if (ret > 0)
1879 new = &parent->rb_right;
1880 else {
1881 if (page_node) {
1882 VM_BUG_ON(page_node->head != &migrate_nodes);
1883 /*
1884 * If the mapcount of our migrated KSM folio is
1885 * at most 1, we can merge it with another
1886 * KSM folio where we know that we have space
1887 * for one more mapping without exceeding the
1888 * ksm_max_page_sharing limit: see
1889 * chain_prune(). This way, we can avoid adding
1890 * this stable node to the chain.
1891 */
1892 if (folio_mapcount(folio) > 1)
1893 goto chain_append;
1894 }
1895
1896 if (!is_page_sharing_candidate(stable_node_dup)) {
1897 /*
1898 * If the stable_node is a chain and
1899 * we got a payload match in memcmp
1900 * but we cannot merge the scanned
1901 * page in any of the existing
1902 * stable_node dups because they're
1903 * all full, we need to wait the
1904 * scanned page to find itself a match
1905 * in the unstable tree to create a
1906 * brand new KSM page to add later to
1907 * the dups of this stable_node.
1908 */
1909 return NULL;
1910 }
1911
1912 /*
1913 * Lock and unlock the stable_node's page (which
1914 * might already have been migrated) so that page
1915 * migration is sure to notice its raised count.
1916 * It would be more elegant to return stable_node
1917 * than kpage, but that involves more changes.
1918 */
1919 tree_folio = ksm_get_folio(stable_node_dup,
1920 KSM_GET_FOLIO_TRYLOCK);
1921
1922 if (PTR_ERR(tree_folio) == -EBUSY)
1923 return ERR_PTR(-EBUSY);
1924
1925 if (unlikely(!tree_folio))
1926 /*
1927 * The tree may have been rebalanced,
1928 * so re-evaluate parent and new.
1929 */
1930 goto again;
1931 folio_unlock(tree_folio);
1932
1933 if (get_kpfn_nid(stable_node_dup->kpfn) !=
1934 NUMA(stable_node_dup->nid)) {
1935 folio_put(tree_folio);
1936 goto replace;
1937 }
1938 return tree_folio;
1939 }
1940 }
1941
1942 if (!page_node)
1943 return NULL;
1944
1945 list_del(&page_node->list);
1946 DO_NUMA(page_node->nid = nid);
1947 rb_link_node(&page_node->node, parent, new);
1948 rb_insert_color(&page_node->node, root);
1949 out:
1950 if (is_page_sharing_candidate(page_node)) {
1951 folio_get(folio);
1952 return folio;
1953 } else
1954 return NULL;
1955
1956 replace:
1957 /*
1958 * If stable_node was a chain and chain_prune collapsed it,
1959 * stable_node has been updated to be the new regular
1960 * stable_node. A collapse of the chain is indistinguishable
1961 * from the case there was no chain in the stable
1962 * rbtree. Otherwise stable_node is the chain and
1963 * stable_node_dup is the dup to replace.
1964 */
1965 if (stable_node_dup == stable_node) {
1966 VM_BUG_ON(is_stable_node_chain(stable_node_dup));
1967 VM_BUG_ON(is_stable_node_dup(stable_node_dup));
1968 /* there is no chain */
1969 if (page_node) {
1970 VM_BUG_ON(page_node->head != &migrate_nodes);
1971 list_del(&page_node->list);
1972 DO_NUMA(page_node->nid = nid);
1973 rb_replace_node(&stable_node_dup->node,
1974 &page_node->node,
1975 root);
1976 if (is_page_sharing_candidate(page_node))
1977 folio_get(folio);
1978 else
1979 folio = NULL;
1980 } else {
1981 rb_erase(&stable_node_dup->node, root);
1982 folio = NULL;
1983 }
1984 } else {
1985 VM_BUG_ON(!is_stable_node_chain(stable_node));
1986 __stable_node_dup_del(stable_node_dup);
1987 if (page_node) {
1988 VM_BUG_ON(page_node->head != &migrate_nodes);
1989 list_del(&page_node->list);
1990 DO_NUMA(page_node->nid = nid);
1991 stable_node_chain_add_dup(page_node, stable_node);
1992 if (is_page_sharing_candidate(page_node))
1993 folio_get(folio);
1994 else
1995 folio = NULL;
1996 } else {
1997 folio = NULL;
1998 }
1999 }
2000 stable_node_dup->head = &migrate_nodes;
2001 list_add(&stable_node_dup->list, stable_node_dup->head);
2002 return folio;
2003
2004 chain_append:
2005 /*
2006 * If stable_node was a chain and chain_prune collapsed it,
2007 * stable_node has been updated to be the new regular
2008 * stable_node. A collapse of the chain is indistinguishable
2009 * from the case there was no chain in the stable
2010 * rbtree. Otherwise stable_node is the chain and
2011 * stable_node_dup is the dup to replace.
2012 */
2013 if (stable_node_dup == stable_node) {
2014 VM_BUG_ON(is_stable_node_dup(stable_node_dup));
2015 /* chain is missing so create it */
2016 stable_node = alloc_stable_node_chain(stable_node_dup,
2017 root);
2018 if (!stable_node)
2019 return NULL;
2020 }
2021 /*
2022 * Add this stable_node dup that was
2023 * migrated to the stable_node chain
2024 * of the current nid for this page
2025 * content.
2026 */
2027 VM_BUG_ON(!is_stable_node_dup(stable_node_dup));
2028 VM_BUG_ON(page_node->head != &migrate_nodes);
2029 list_del(&page_node->list);
2030 DO_NUMA(page_node->nid = nid);
2031 stable_node_chain_add_dup(page_node, stable_node);
2032 goto out;
2033 }
2034
2035 /*
2036 * stable_tree_insert - insert stable tree node pointing to new ksm page
2037 * into the stable tree.
2038 *
2039 * This function returns the stable tree node just allocated on success,
2040 * NULL otherwise.
2041 */
stable_tree_insert(struct folio * kfolio)2042 static struct ksm_stable_node *stable_tree_insert(struct folio *kfolio)
2043 {
2044 int nid;
2045 unsigned long kpfn;
2046 struct rb_root *root;
2047 struct rb_node **new;
2048 struct rb_node *parent;
2049 struct ksm_stable_node *stable_node, *stable_node_dup;
2050 bool need_chain = false;
2051
2052 kpfn = folio_pfn(kfolio);
2053 nid = get_kpfn_nid(kpfn);
2054 root = root_stable_tree + nid;
2055 again:
2056 parent = NULL;
2057 new = &root->rb_node;
2058
2059 while (*new) {
2060 struct folio *tree_folio;
2061 int ret;
2062
2063 cond_resched();
2064 stable_node = rb_entry(*new, struct ksm_stable_node, node);
2065 tree_folio = chain(&stable_node_dup, &stable_node, root);
2066 if (!tree_folio) {
2067 /*
2068 * If we walked over a stale stable_node,
2069 * ksm_get_folio() will call rb_erase() and it
2070 * may rebalance the tree from under us. So
2071 * restart the search from scratch. Returning
2072 * NULL would be safe too, but we'd generate
2073 * false negative insertions just because some
2074 * stable_node was stale.
2075 */
2076 goto again;
2077 }
2078
2079 ret = memcmp_pages(&kfolio->page, &tree_folio->page);
2080 folio_put(tree_folio);
2081
2082 parent = *new;
2083 if (ret < 0)
2084 new = &parent->rb_left;
2085 else if (ret > 0)
2086 new = &parent->rb_right;
2087 else {
2088 need_chain = true;
2089 break;
2090 }
2091 }
2092
2093 stable_node_dup = alloc_stable_node();
2094 if (!stable_node_dup)
2095 return NULL;
2096
2097 INIT_HLIST_HEAD(&stable_node_dup->hlist);
2098 stable_node_dup->kpfn = kpfn;
2099 stable_node_dup->rmap_hlist_len = 0;
2100 DO_NUMA(stable_node_dup->nid = nid);
2101 if (!need_chain) {
2102 rb_link_node(&stable_node_dup->node, parent, new);
2103 rb_insert_color(&stable_node_dup->node, root);
2104 } else {
2105 if (!is_stable_node_chain(stable_node)) {
2106 struct ksm_stable_node *orig = stable_node;
2107 /* chain is missing so create it */
2108 stable_node = alloc_stable_node_chain(orig, root);
2109 if (!stable_node) {
2110 free_stable_node(stable_node_dup);
2111 return NULL;
2112 }
2113 }
2114 stable_node_chain_add_dup(stable_node_dup, stable_node);
2115 }
2116
2117 folio_set_stable_node(kfolio, stable_node_dup);
2118
2119 return stable_node_dup;
2120 }
2121
2122 /*
2123 * unstable_tree_search_insert - search for identical page,
2124 * else insert rmap_item into the unstable tree.
2125 *
2126 * This function searches for a page in the unstable tree identical to the
2127 * page currently being scanned; and if no identical page is found in the
2128 * tree, we insert rmap_item as a new object into the unstable tree.
2129 *
2130 * This function returns pointer to rmap_item found to be identical
2131 * to the currently scanned page, NULL otherwise.
2132 *
2133 * This function does both searching and inserting, because they share
2134 * the same walking algorithm in an rbtree.
2135 */
2136 static
unstable_tree_search_insert(struct ksm_rmap_item * rmap_item,struct page * page,struct page ** tree_pagep)2137 struct ksm_rmap_item *unstable_tree_search_insert(struct ksm_rmap_item *rmap_item,
2138 struct page *page,
2139 struct page **tree_pagep)
2140 {
2141 struct rb_node **new;
2142 struct rb_root *root;
2143 struct rb_node *parent = NULL;
2144 int nid;
2145
2146 nid = get_kpfn_nid(page_to_pfn(page));
2147 root = root_unstable_tree + nid;
2148 new = &root->rb_node;
2149
2150 while (*new) {
2151 struct ksm_rmap_item *tree_rmap_item;
2152 struct page *tree_page;
2153 int ret;
2154
2155 cond_resched();
2156 tree_rmap_item = rb_entry(*new, struct ksm_rmap_item, node);
2157 tree_page = get_mergeable_page(tree_rmap_item);
2158 if (!tree_page)
2159 return NULL;
2160
2161 /*
2162 * Don't substitute a ksm page for a forked page.
2163 */
2164 if (page == tree_page) {
2165 put_page(tree_page);
2166 return NULL;
2167 }
2168
2169 ret = memcmp_pages(page, tree_page);
2170
2171 parent = *new;
2172 if (ret < 0) {
2173 put_page(tree_page);
2174 new = &parent->rb_left;
2175 } else if (ret > 0) {
2176 put_page(tree_page);
2177 new = &parent->rb_right;
2178 } else if (!ksm_merge_across_nodes &&
2179 page_to_nid(tree_page) != nid) {
2180 /*
2181 * If tree_page has been migrated to another NUMA node,
2182 * it will be flushed out and put in the right unstable
2183 * tree next time: only merge with it when across_nodes.
2184 */
2185 put_page(tree_page);
2186 return NULL;
2187 } else {
2188 *tree_pagep = tree_page;
2189 return tree_rmap_item;
2190 }
2191 }
2192
2193 rmap_item->address |= UNSTABLE_FLAG;
2194 rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
2195 DO_NUMA(rmap_item->nid = nid);
2196 rb_link_node(&rmap_item->node, parent, new);
2197 rb_insert_color(&rmap_item->node, root);
2198
2199 ksm_pages_unshared++;
2200 return NULL;
2201 }
2202
2203 /*
2204 * stable_tree_append - add another rmap_item to the linked list of
2205 * rmap_items hanging off a given node of the stable tree, all sharing
2206 * the same ksm page.
2207 */
stable_tree_append(struct ksm_rmap_item * rmap_item,struct ksm_stable_node * stable_node,bool max_page_sharing_bypass)2208 static void stable_tree_append(struct ksm_rmap_item *rmap_item,
2209 struct ksm_stable_node *stable_node,
2210 bool max_page_sharing_bypass)
2211 {
2212 /*
2213 * rmap won't find this mapping if we don't insert the
2214 * rmap_item in the right stable_node
2215 * duplicate. page_migration could break later if rmap breaks,
2216 * so we can as well crash here. We really need to check for
2217 * rmap_hlist_len == STABLE_NODE_CHAIN, but we can as well check
2218 * for other negative values as an underflow if detected here
2219 * for the first time (and not when decreasing rmap_hlist_len)
2220 * would be sign of memory corruption in the stable_node.
2221 */
2222 BUG_ON(stable_node->rmap_hlist_len < 0);
2223
2224 stable_node->rmap_hlist_len++;
2225 if (!max_page_sharing_bypass)
2226 /* possibly non fatal but unexpected overflow, only warn */
2227 WARN_ON_ONCE(stable_node->rmap_hlist_len >
2228 ksm_max_page_sharing);
2229
2230 rmap_item->head = stable_node;
2231 rmap_item->address |= STABLE_FLAG;
2232 hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
2233
2234 if (rmap_item->hlist.next)
2235 ksm_pages_sharing++;
2236 else
2237 ksm_pages_shared++;
2238
2239 rmap_item->mm->ksm_merging_pages++;
2240 }
2241
2242 /*
2243 * cmp_and_merge_page - first see if page can be merged into the stable tree;
2244 * if not, compare checksum to previous and if it's the same, see if page can
2245 * be inserted into the unstable tree, or merged with a page already there and
2246 * both transferred to the stable tree.
2247 *
2248 * @page: the page that we are searching identical page to.
2249 * @rmap_item: the reverse mapping into the virtual address of this page
2250 */
cmp_and_merge_page(struct page * page,struct ksm_rmap_item * rmap_item)2251 static void cmp_and_merge_page(struct page *page, struct ksm_rmap_item *rmap_item)
2252 {
2253 struct folio *folio = page_folio(page);
2254 struct ksm_rmap_item *tree_rmap_item;
2255 struct page *tree_page = NULL;
2256 struct ksm_stable_node *stable_node;
2257 struct folio *kfolio;
2258 unsigned int checksum;
2259 int err;
2260 bool max_page_sharing_bypass = false;
2261
2262 stable_node = folio_stable_node(folio);
2263 if (stable_node) {
2264 if (stable_node->head != &migrate_nodes &&
2265 get_kpfn_nid(READ_ONCE(stable_node->kpfn)) !=
2266 NUMA(stable_node->nid)) {
2267 stable_node_dup_del(stable_node);
2268 stable_node->head = &migrate_nodes;
2269 list_add(&stable_node->list, stable_node->head);
2270 }
2271 if (stable_node->head != &migrate_nodes &&
2272 rmap_item->head == stable_node)
2273 return;
2274 /*
2275 * If it's a KSM fork, allow it to go over the sharing limit
2276 * without warnings.
2277 */
2278 if (!is_page_sharing_candidate(stable_node))
2279 max_page_sharing_bypass = true;
2280 } else {
2281 remove_rmap_item_from_tree(rmap_item);
2282
2283 /*
2284 * If the hash value of the page has changed from the last time
2285 * we calculated it, this page is changing frequently: therefore we
2286 * don't want to insert it in the unstable tree, and we don't want
2287 * to waste our time searching for something identical to it there.
2288 */
2289 checksum = calc_checksum(page);
2290 if (rmap_item->oldchecksum != checksum) {
2291 rmap_item->oldchecksum = checksum;
2292 return;
2293 }
2294
2295 if (!try_to_merge_with_zero_page(rmap_item, page))
2296 return;
2297 }
2298
2299 /* Start by searching for the folio in the stable tree */
2300 kfolio = stable_tree_search(page);
2301 if (kfolio == folio && rmap_item->head == stable_node) {
2302 folio_put(kfolio);
2303 return;
2304 }
2305
2306 remove_rmap_item_from_tree(rmap_item);
2307
2308 if (kfolio) {
2309 if (kfolio == ERR_PTR(-EBUSY))
2310 return;
2311
2312 err = try_to_merge_with_ksm_page(rmap_item, page, &kfolio->page);
2313 if (!err) {
2314 /*
2315 * The page was successfully merged:
2316 * add its rmap_item to the stable tree.
2317 */
2318 folio_lock(kfolio);
2319 stable_tree_append(rmap_item, folio_stable_node(kfolio),
2320 max_page_sharing_bypass);
2321 folio_unlock(kfolio);
2322 }
2323 folio_put(kfolio);
2324 return;
2325 }
2326
2327 tree_rmap_item =
2328 unstable_tree_search_insert(rmap_item, page, &tree_page);
2329 if (tree_rmap_item) {
2330 bool split;
2331
2332 kfolio = try_to_merge_two_pages(rmap_item, page,
2333 tree_rmap_item, tree_page);
2334 /*
2335 * If both pages we tried to merge belong to the same compound
2336 * page, then we actually ended up increasing the reference
2337 * count of the same compound page twice, and split_huge_page
2338 * failed.
2339 * Here we set a flag if that happened, and we use it later to
2340 * try split_huge_page again. Since we call put_page right
2341 * afterwards, the reference count will be correct and
2342 * split_huge_page should succeed.
2343 */
2344 split = PageTransCompound(page)
2345 && compound_head(page) == compound_head(tree_page);
2346 put_page(tree_page);
2347 if (kfolio) {
2348 /*
2349 * The pages were successfully merged: insert new
2350 * node in the stable tree and add both rmap_items.
2351 */
2352 folio_lock(kfolio);
2353 stable_node = stable_tree_insert(kfolio);
2354 if (stable_node) {
2355 stable_tree_append(tree_rmap_item, stable_node,
2356 false);
2357 stable_tree_append(rmap_item, stable_node,
2358 false);
2359 }
2360 folio_unlock(kfolio);
2361
2362 /*
2363 * If we fail to insert the page into the stable tree,
2364 * we will have 2 virtual addresses that are pointing
2365 * to a ksm page left outside the stable tree,
2366 * in which case we need to break_cow on both.
2367 */
2368 if (!stable_node) {
2369 break_cow(tree_rmap_item);
2370 break_cow(rmap_item);
2371 }
2372 } else if (split) {
2373 /*
2374 * We are here if we tried to merge two pages and
2375 * failed because they both belonged to the same
2376 * compound page. We will split the page now, but no
2377 * merging will take place.
2378 * We do not want to add the cost of a full lock; if
2379 * the page is locked, it is better to skip it and
2380 * perhaps try again later.
2381 */
2382 if (!folio_trylock(folio))
2383 return;
2384 split_huge_page(page);
2385 folio = page_folio(page);
2386 folio_unlock(folio);
2387 }
2388 }
2389 }
2390
get_next_rmap_item(struct ksm_mm_slot * mm_slot,struct ksm_rmap_item ** rmap_list,unsigned long addr)2391 static struct ksm_rmap_item *get_next_rmap_item(struct ksm_mm_slot *mm_slot,
2392 struct ksm_rmap_item **rmap_list,
2393 unsigned long addr)
2394 {
2395 struct ksm_rmap_item *rmap_item;
2396
2397 while (*rmap_list) {
2398 rmap_item = *rmap_list;
2399 if ((rmap_item->address & PAGE_MASK) == addr)
2400 return rmap_item;
2401 if (rmap_item->address > addr)
2402 break;
2403 *rmap_list = rmap_item->rmap_list;
2404 remove_rmap_item_from_tree(rmap_item);
2405 free_rmap_item(rmap_item);
2406 }
2407
2408 rmap_item = alloc_rmap_item();
2409 if (rmap_item) {
2410 /* It has already been zeroed */
2411 rmap_item->mm = mm_slot->slot.mm;
2412 rmap_item->mm->ksm_rmap_items++;
2413 rmap_item->address = addr;
2414 rmap_item->rmap_list = *rmap_list;
2415 *rmap_list = rmap_item;
2416 }
2417 return rmap_item;
2418 }
2419
2420 /*
2421 * Calculate skip age for the ksm page age. The age determines how often
2422 * de-duplicating has already been tried unsuccessfully. If the age is
2423 * smaller, the scanning of this page is skipped for less scans.
2424 *
2425 * @age: rmap_item age of page
2426 */
skip_age(rmap_age_t age)2427 static unsigned int skip_age(rmap_age_t age)
2428 {
2429 if (age <= 3)
2430 return 1;
2431 if (age <= 5)
2432 return 2;
2433 if (age <= 8)
2434 return 4;
2435
2436 return 8;
2437 }
2438
2439 /*
2440 * Determines if a page should be skipped for the current scan.
2441 *
2442 * @folio: folio containing the page to check
2443 * @rmap_item: associated rmap_item of page
2444 */
should_skip_rmap_item(struct folio * folio,struct ksm_rmap_item * rmap_item)2445 static bool should_skip_rmap_item(struct folio *folio,
2446 struct ksm_rmap_item *rmap_item)
2447 {
2448 rmap_age_t age;
2449
2450 if (!ksm_smart_scan)
2451 return false;
2452
2453 /*
2454 * Never skip pages that are already KSM; pages cmp_and_merge_page()
2455 * will essentially ignore them, but we still have to process them
2456 * properly.
2457 */
2458 if (folio_test_ksm(folio))
2459 return false;
2460
2461 age = rmap_item->age;
2462 if (age != U8_MAX)
2463 rmap_item->age++;
2464
2465 /*
2466 * Smaller ages are not skipped, they need to get a chance to go
2467 * through the different phases of the KSM merging.
2468 */
2469 if (age < 3)
2470 return false;
2471
2472 /*
2473 * Are we still allowed to skip? If not, then don't skip it
2474 * and determine how much more often we are allowed to skip next.
2475 */
2476 if (!rmap_item->remaining_skips) {
2477 rmap_item->remaining_skips = skip_age(age);
2478 return false;
2479 }
2480
2481 /* Skip this page */
2482 ksm_pages_skipped++;
2483 rmap_item->remaining_skips--;
2484 remove_rmap_item_from_tree(rmap_item);
2485 return true;
2486 }
2487
2488 struct ksm_next_page_arg {
2489 struct folio *folio;
2490 struct page *page;
2491 unsigned long addr;
2492 };
2493
ksm_next_page_pmd_entry(pmd_t * pmdp,unsigned long addr,unsigned long end,struct mm_walk * walk)2494 static int ksm_next_page_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long end,
2495 struct mm_walk *walk)
2496 {
2497 struct ksm_next_page_arg *private = walk->private;
2498 struct vm_area_struct *vma = walk->vma;
2499 pte_t *start_ptep = NULL, *ptep, pte;
2500 struct mm_struct *mm = walk->mm;
2501 struct folio *folio;
2502 struct page *page;
2503 spinlock_t *ptl;
2504 pmd_t pmd;
2505
2506 if (ksm_test_exit(mm))
2507 return 0;
2508
2509 cond_resched();
2510
2511 pmd = pmdp_get_lockless(pmdp);
2512 if (!pmd_present(pmd))
2513 return 0;
2514
2515 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && pmd_leaf(pmd)) {
2516 ptl = pmd_lock(mm, pmdp);
2517 pmd = pmdp_get(pmdp);
2518
2519 if (!pmd_present(pmd)) {
2520 goto not_found_unlock;
2521 } else if (pmd_leaf(pmd)) {
2522 page = vm_normal_page_pmd(vma, addr, pmd);
2523 if (!page)
2524 goto not_found_unlock;
2525 folio = page_folio(page);
2526
2527 if (folio_is_zone_device(folio) || !folio_test_anon(folio))
2528 goto not_found_unlock;
2529
2530 page += ((addr & (PMD_SIZE - 1)) >> PAGE_SHIFT);
2531 goto found_unlock;
2532 }
2533 spin_unlock(ptl);
2534 }
2535
2536 start_ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
2537 if (!start_ptep)
2538 return 0;
2539
2540 for (ptep = start_ptep; addr < end; ptep++, addr += PAGE_SIZE) {
2541 pte = ptep_get(ptep);
2542
2543 if (!pte_present(pte))
2544 continue;
2545
2546 page = vm_normal_page(vma, addr, pte);
2547 if (!page)
2548 continue;
2549 folio = page_folio(page);
2550
2551 if (folio_is_zone_device(folio) || !folio_test_anon(folio))
2552 continue;
2553 goto found_unlock;
2554 }
2555
2556 not_found_unlock:
2557 spin_unlock(ptl);
2558 if (start_ptep)
2559 pte_unmap(start_ptep);
2560 return 0;
2561 found_unlock:
2562 folio_get(folio);
2563 spin_unlock(ptl);
2564 if (start_ptep)
2565 pte_unmap(start_ptep);
2566 private->page = page;
2567 private->folio = folio;
2568 private->addr = addr;
2569 return 1;
2570 }
2571
2572 static struct mm_walk_ops ksm_next_page_ops = {
2573 .pmd_entry = ksm_next_page_pmd_entry,
2574 .walk_lock = PGWALK_RDLOCK,
2575 };
2576
scan_get_next_rmap_item(struct page ** page)2577 static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
2578 {
2579 struct mm_struct *mm;
2580 struct ksm_mm_slot *mm_slot;
2581 struct mm_slot *slot;
2582 struct vm_area_struct *vma;
2583 struct ksm_rmap_item *rmap_item;
2584 struct vma_iterator vmi;
2585 int nid;
2586
2587 if (list_empty(&ksm_mm_head.slot.mm_node))
2588 return NULL;
2589
2590 mm_slot = ksm_scan.mm_slot;
2591 if (mm_slot == &ksm_mm_head) {
2592 advisor_start_scan();
2593 trace_ksm_start_scan(ksm_scan.seqnr, ksm_rmap_items);
2594
2595 /*
2596 * A number of pages can hang around indefinitely in per-cpu
2597 * LRU cache, raised page count preventing write_protect_page
2598 * from merging them. Though it doesn't really matter much,
2599 * it is puzzling to see some stuck in pages_volatile until
2600 * other activity jostles them out, and they also prevented
2601 * LTP's KSM test from succeeding deterministically; so drain
2602 * them here (here rather than on entry to ksm_do_scan(),
2603 * so we don't IPI too often when pages_to_scan is set low).
2604 */
2605 lru_add_drain_all();
2606
2607 /*
2608 * Whereas stale stable_nodes on the stable_tree itself
2609 * get pruned in the regular course of stable_tree_search(),
2610 * those moved out to the migrate_nodes list can accumulate:
2611 * so prune them once before each full scan.
2612 */
2613 if (!ksm_merge_across_nodes) {
2614 struct ksm_stable_node *stable_node, *next;
2615 struct folio *folio;
2616
2617 list_for_each_entry_safe(stable_node, next,
2618 &migrate_nodes, list) {
2619 folio = ksm_get_folio(stable_node,
2620 KSM_GET_FOLIO_NOLOCK);
2621 if (folio)
2622 folio_put(folio);
2623 cond_resched();
2624 }
2625 }
2626
2627 for (nid = 0; nid < ksm_nr_node_ids; nid++)
2628 root_unstable_tree[nid] = RB_ROOT;
2629
2630 spin_lock(&ksm_mmlist_lock);
2631 slot = list_entry(mm_slot->slot.mm_node.next,
2632 struct mm_slot, mm_node);
2633 mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
2634 ksm_scan.mm_slot = mm_slot;
2635 spin_unlock(&ksm_mmlist_lock);
2636 /*
2637 * Although we tested list_empty() above, a racing __ksm_exit
2638 * of the last mm on the list may have removed it since then.
2639 */
2640 if (mm_slot == &ksm_mm_head)
2641 return NULL;
2642 next_mm:
2643 ksm_scan.address = 0;
2644 ksm_scan.rmap_list = &mm_slot->rmap_list;
2645 }
2646
2647 slot = &mm_slot->slot;
2648 mm = slot->mm;
2649 vma_iter_init(&vmi, mm, ksm_scan.address);
2650
2651 mmap_read_lock(mm);
2652 if (ksm_test_exit(mm))
2653 goto no_vmas;
2654
2655 for_each_vma(vmi, vma) {
2656 if (!(vma->vm_flags & VM_MERGEABLE))
2657 continue;
2658 if (ksm_scan.address < vma->vm_start)
2659 ksm_scan.address = vma->vm_start;
2660 if (!vma->anon_vma)
2661 ksm_scan.address = vma->vm_end;
2662
2663 while (ksm_scan.address < vma->vm_end) {
2664 struct ksm_next_page_arg ksm_next_page_arg;
2665 struct page *tmp_page = NULL;
2666 struct folio *folio;
2667
2668 if (ksm_test_exit(mm))
2669 break;
2670
2671 int found;
2672
2673 found = walk_page_range_vma(vma, ksm_scan.address,
2674 vma->vm_end,
2675 &ksm_next_page_ops,
2676 &ksm_next_page_arg);
2677
2678 if (found > 0) {
2679 folio = ksm_next_page_arg.folio;
2680 tmp_page = ksm_next_page_arg.page;
2681 ksm_scan.address = ksm_next_page_arg.addr;
2682 } else {
2683 VM_WARN_ON_ONCE(found < 0);
2684 ksm_scan.address = vma->vm_end - PAGE_SIZE;
2685 }
2686
2687 if (tmp_page) {
2688 flush_anon_page(vma, tmp_page, ksm_scan.address);
2689 flush_dcache_page(tmp_page);
2690 rmap_item = get_next_rmap_item(mm_slot,
2691 ksm_scan.rmap_list, ksm_scan.address);
2692 if (rmap_item) {
2693 ksm_scan.rmap_list =
2694 &rmap_item->rmap_list;
2695
2696 if (should_skip_rmap_item(folio, rmap_item)) {
2697 folio_put(folio);
2698 goto next_page;
2699 }
2700
2701 ksm_scan.address += PAGE_SIZE;
2702 *page = tmp_page;
2703 } else {
2704 folio_put(folio);
2705 }
2706 mmap_read_unlock(mm);
2707 return rmap_item;
2708 }
2709 next_page:
2710 ksm_scan.address += PAGE_SIZE;
2711 cond_resched();
2712 }
2713 }
2714
2715 if (ksm_test_exit(mm)) {
2716 no_vmas:
2717 ksm_scan.address = 0;
2718 ksm_scan.rmap_list = &mm_slot->rmap_list;
2719 }
2720 /*
2721 * Nuke all the rmap_items that are above this current rmap:
2722 * because there were no VM_MERGEABLE vmas with such addresses.
2723 */
2724 remove_trailing_rmap_items(ksm_scan.rmap_list);
2725
2726 spin_lock(&ksm_mmlist_lock);
2727 slot = list_entry(mm_slot->slot.mm_node.next,
2728 struct mm_slot, mm_node);
2729 ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
2730 if (ksm_scan.address == 0) {
2731 /*
2732 * We've completed a full scan of all vmas, holding mmap_lock
2733 * throughout, and found no VM_MERGEABLE: so do the same as
2734 * __ksm_exit does to remove this mm from all our lists now.
2735 * This applies either when cleaning up after __ksm_exit
2736 * (but beware: we can reach here even before __ksm_exit),
2737 * or when all VM_MERGEABLE areas have been unmapped (and
2738 * mmap_lock then protects against race with MADV_MERGEABLE).
2739 */
2740 hash_del(&mm_slot->slot.hash);
2741 list_del(&mm_slot->slot.mm_node);
2742 spin_unlock(&ksm_mmlist_lock);
2743
2744 mm_slot_free(mm_slot_cache, mm_slot);
2745 /*
2746 * Only clear MMF_VM_MERGEABLE. We must not clear
2747 * MMF_VM_MERGE_ANY, because for those MMF_VM_MERGE_ANY process,
2748 * perhaps their mm_struct has just been added to ksm_mm_slot
2749 * list, and its process has not yet officially started running
2750 * or has not yet performed mmap/brk to allocate anonymous VMAS.
2751 */
2752 mm_flags_clear(MMF_VM_MERGEABLE, mm);
2753 mmap_read_unlock(mm);
2754 mmdrop(mm);
2755 } else {
2756 mmap_read_unlock(mm);
2757 /*
2758 * mmap_read_unlock(mm) first because after
2759 * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
2760 * already have been freed under us by __ksm_exit()
2761 * because the "mm_slot" is still hashed and
2762 * ksm_scan.mm_slot doesn't point to it anymore.
2763 */
2764 spin_unlock(&ksm_mmlist_lock);
2765 }
2766
2767 /* Repeat until we've completed scanning the whole list */
2768 mm_slot = ksm_scan.mm_slot;
2769 if (mm_slot != &ksm_mm_head)
2770 goto next_mm;
2771
2772 advisor_stop_scan();
2773
2774 trace_ksm_stop_scan(ksm_scan.seqnr, ksm_rmap_items);
2775 ksm_scan.seqnr++;
2776 return NULL;
2777 }
2778
2779 /**
2780 * ksm_do_scan - the ksm scanner main worker function.
2781 * @scan_npages: number of pages we want to scan before we return.
2782 */
ksm_do_scan(unsigned int scan_npages)2783 static void ksm_do_scan(unsigned int scan_npages)
2784 {
2785 struct ksm_rmap_item *rmap_item;
2786 struct page *page;
2787
2788 while (scan_npages-- && likely(!freezing(current))) {
2789 cond_resched();
2790 rmap_item = scan_get_next_rmap_item(&page);
2791 if (!rmap_item)
2792 return;
2793 cmp_and_merge_page(page, rmap_item);
2794 put_page(page);
2795 ksm_pages_scanned++;
2796 }
2797 }
2798
ksmd_should_run(void)2799 static int ksmd_should_run(void)
2800 {
2801 return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.slot.mm_node);
2802 }
2803
ksm_scan_thread(void * nothing)2804 static int ksm_scan_thread(void *nothing)
2805 {
2806 unsigned int sleep_ms;
2807
2808 set_freezable();
2809 set_user_nice(current, 5);
2810
2811 while (!kthread_should_stop()) {
2812 mutex_lock(&ksm_thread_mutex);
2813 wait_while_offlining();
2814 if (ksmd_should_run())
2815 ksm_do_scan(ksm_thread_pages_to_scan);
2816 mutex_unlock(&ksm_thread_mutex);
2817
2818 if (ksmd_should_run()) {
2819 sleep_ms = READ_ONCE(ksm_thread_sleep_millisecs);
2820 wait_event_freezable_timeout(ksm_iter_wait,
2821 sleep_ms != READ_ONCE(ksm_thread_sleep_millisecs),
2822 msecs_to_jiffies(sleep_ms));
2823 } else {
2824 wait_event_freezable(ksm_thread_wait,
2825 ksmd_should_run() || kthread_should_stop());
2826 }
2827 }
2828 return 0;
2829 }
2830
__ksm_should_add_vma(const struct file * file,vma_flags_t vma_flags)2831 static bool __ksm_should_add_vma(const struct file *file, vma_flags_t vma_flags)
2832 {
2833 if (vma_flags_test(&vma_flags, VMA_MERGEABLE_BIT))
2834 return false;
2835
2836 return ksm_compatible(file, vma_flags);
2837 }
2838
__ksm_add_vma(struct vm_area_struct * vma)2839 static void __ksm_add_vma(struct vm_area_struct *vma)
2840 {
2841 if (__ksm_should_add_vma(vma->vm_file, vma->flags))
2842 vm_flags_set(vma, VM_MERGEABLE);
2843 }
2844
__ksm_del_vma(struct vm_area_struct * vma)2845 static int __ksm_del_vma(struct vm_area_struct *vma)
2846 {
2847 int err;
2848
2849 if (!(vma->vm_flags & VM_MERGEABLE))
2850 return 0;
2851
2852 if (vma->anon_vma) {
2853 err = break_ksm(vma, vma->vm_start, vma->vm_end, true);
2854 if (err)
2855 return err;
2856 }
2857
2858 vm_flags_clear(vma, VM_MERGEABLE);
2859 return 0;
2860 }
2861 /**
2862 * ksm_vma_flags - Update VMA flags to mark as mergeable if compatible
2863 *
2864 * @mm: Proposed VMA's mm_struct
2865 * @file: Proposed VMA's file-backed mapping, if any.
2866 * @vma_flags: Proposed VMA"s flags.
2867 *
2868 * Returns: @vma_flags possibly updated to mark mergeable.
2869 */
ksm_vma_flags(struct mm_struct * mm,const struct file * file,vma_flags_t vma_flags)2870 vma_flags_t ksm_vma_flags(struct mm_struct *mm, const struct file *file,
2871 vma_flags_t vma_flags)
2872 {
2873 if (mm_flags_test(MMF_VM_MERGE_ANY, mm) &&
2874 __ksm_should_add_vma(file, vma_flags)) {
2875 vma_flags_set(&vma_flags, VMA_MERGEABLE_BIT);
2876 /*
2877 * Generally, the flags here always include MMF_VM_MERGEABLE.
2878 * However, in rare cases, this flag may be cleared by ksmd who
2879 * scans a cycle without finding any mergeable vma.
2880 */
2881 if (unlikely(!mm_flags_test(MMF_VM_MERGEABLE, mm)))
2882 __ksm_enter(mm);
2883 }
2884
2885 return vma_flags;
2886 }
2887
ksm_add_vmas(struct mm_struct * mm)2888 static void ksm_add_vmas(struct mm_struct *mm)
2889 {
2890 struct vm_area_struct *vma;
2891
2892 VMA_ITERATOR(vmi, mm, 0);
2893 for_each_vma(vmi, vma)
2894 __ksm_add_vma(vma);
2895 }
2896
ksm_del_vmas(struct mm_struct * mm)2897 static int ksm_del_vmas(struct mm_struct *mm)
2898 {
2899 struct vm_area_struct *vma;
2900 int err;
2901
2902 VMA_ITERATOR(vmi, mm, 0);
2903 for_each_vma(vmi, vma) {
2904 err = __ksm_del_vma(vma);
2905 if (err)
2906 return err;
2907 }
2908 return 0;
2909 }
2910
2911 /**
2912 * ksm_enable_merge_any - Add mm to mm ksm list and enable merging on all
2913 * compatible VMA's
2914 *
2915 * @mm: Pointer to mm
2916 *
2917 * Returns 0 on success, otherwise error code
2918 */
ksm_enable_merge_any(struct mm_struct * mm)2919 int ksm_enable_merge_any(struct mm_struct *mm)
2920 {
2921 int err;
2922
2923 if (mm_flags_test(MMF_VM_MERGE_ANY, mm))
2924 return 0;
2925
2926 if (!mm_flags_test(MMF_VM_MERGEABLE, mm)) {
2927 err = __ksm_enter(mm);
2928 if (err)
2929 return err;
2930 }
2931
2932 mm_flags_set(MMF_VM_MERGE_ANY, mm);
2933 ksm_add_vmas(mm);
2934
2935 return 0;
2936 }
2937
2938 /**
2939 * ksm_disable_merge_any - Disable merging on all compatible VMA's of the mm,
2940 * previously enabled via ksm_enable_merge_any().
2941 *
2942 * Disabling merging implies unmerging any merged pages, like setting
2943 * MADV_UNMERGEABLE would. If unmerging fails, the whole operation fails and
2944 * merging on all compatible VMA's remains enabled.
2945 *
2946 * @mm: Pointer to mm
2947 *
2948 * Returns 0 on success, otherwise error code
2949 */
ksm_disable_merge_any(struct mm_struct * mm)2950 int ksm_disable_merge_any(struct mm_struct *mm)
2951 {
2952 int err;
2953
2954 if (!mm_flags_test(MMF_VM_MERGE_ANY, mm))
2955 return 0;
2956
2957 err = ksm_del_vmas(mm);
2958 if (err) {
2959 ksm_add_vmas(mm);
2960 return err;
2961 }
2962
2963 mm_flags_clear(MMF_VM_MERGE_ANY, mm);
2964 return 0;
2965 }
2966
ksm_disable(struct mm_struct * mm)2967 int ksm_disable(struct mm_struct *mm)
2968 {
2969 mmap_assert_write_locked(mm);
2970
2971 if (!mm_flags_test(MMF_VM_MERGEABLE, mm))
2972 return 0;
2973 if (mm_flags_test(MMF_VM_MERGE_ANY, mm))
2974 return ksm_disable_merge_any(mm);
2975 return ksm_del_vmas(mm);
2976 }
2977
ksm_madvise(struct vm_area_struct * vma,unsigned long start,unsigned long end,int advice,vm_flags_t * vm_flags)2978 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
2979 unsigned long end, int advice, vm_flags_t *vm_flags)
2980 {
2981 struct mm_struct *mm = vma->vm_mm;
2982 int err;
2983
2984 switch (advice) {
2985 case MADV_MERGEABLE:
2986 if (vma->vm_flags & VM_MERGEABLE)
2987 return 0;
2988 if (!vma_ksm_compatible(vma))
2989 return 0;
2990
2991 if (!mm_flags_test(MMF_VM_MERGEABLE, mm)) {
2992 err = __ksm_enter(mm);
2993 if (err)
2994 return err;
2995 }
2996
2997 *vm_flags |= VM_MERGEABLE;
2998 break;
2999
3000 case MADV_UNMERGEABLE:
3001 if (!(*vm_flags & VM_MERGEABLE))
3002 return 0; /* just ignore the advice */
3003
3004 if (vma->anon_vma) {
3005 err = break_ksm(vma, start, end, true);
3006 if (err)
3007 return err;
3008 }
3009
3010 *vm_flags &= ~VM_MERGEABLE;
3011 break;
3012 }
3013
3014 return 0;
3015 }
3016 EXPORT_SYMBOL_GPL(ksm_madvise);
3017
__ksm_enter(struct mm_struct * mm)3018 int __ksm_enter(struct mm_struct *mm)
3019 {
3020 struct ksm_mm_slot *mm_slot;
3021 struct mm_slot *slot;
3022 int needs_wakeup;
3023
3024 mm_slot = mm_slot_alloc(mm_slot_cache);
3025 if (!mm_slot)
3026 return -ENOMEM;
3027
3028 slot = &mm_slot->slot;
3029
3030 /* Check ksm_run too? Would need tighter locking */
3031 needs_wakeup = list_empty(&ksm_mm_head.slot.mm_node);
3032
3033 spin_lock(&ksm_mmlist_lock);
3034 mm_slot_insert(mm_slots_hash, mm, slot);
3035 /*
3036 * When KSM_RUN_MERGE (or KSM_RUN_STOP),
3037 * insert just behind the scanning cursor, to let the area settle
3038 * down a little; when fork is followed by immediate exec, we don't
3039 * want ksmd to waste time setting up and tearing down an rmap_list.
3040 *
3041 * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
3042 * scanning cursor, otherwise KSM pages in newly forked mms will be
3043 * missed: then we might as well insert at the end of the list.
3044 */
3045 if (ksm_run & KSM_RUN_UNMERGE)
3046 list_add_tail(&slot->mm_node, &ksm_mm_head.slot.mm_node);
3047 else
3048 list_add_tail(&slot->mm_node, &ksm_scan.mm_slot->slot.mm_node);
3049 spin_unlock(&ksm_mmlist_lock);
3050
3051 mm_flags_set(MMF_VM_MERGEABLE, mm);
3052 mmgrab(mm);
3053
3054 if (needs_wakeup)
3055 wake_up_interruptible(&ksm_thread_wait);
3056
3057 trace_ksm_enter(mm);
3058 return 0;
3059 }
3060
__ksm_exit(struct mm_struct * mm)3061 void __ksm_exit(struct mm_struct *mm)
3062 {
3063 struct ksm_mm_slot *mm_slot = NULL;
3064 struct mm_slot *slot;
3065 int easy_to_free = 0;
3066
3067 /*
3068 * This process is exiting: if it's straightforward (as is the
3069 * case when ksmd was never running), free mm_slot immediately.
3070 * But if it's at the cursor or has rmap_items linked to it, use
3071 * mmap_lock to synchronize with any break_cows before pagetables
3072 * are freed, and leave the mm_slot on the list for ksmd to free.
3073 * Beware: ksm may already have noticed it exiting and freed the slot.
3074 */
3075
3076 spin_lock(&ksm_mmlist_lock);
3077 slot = mm_slot_lookup(mm_slots_hash, mm);
3078 if (!slot)
3079 goto unlock;
3080 mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
3081 if (ksm_scan.mm_slot == mm_slot)
3082 goto unlock;
3083 if (!mm_slot->rmap_list) {
3084 hash_del(&slot->hash);
3085 list_del(&slot->mm_node);
3086 easy_to_free = 1;
3087 } else {
3088 list_move(&slot->mm_node,
3089 &ksm_scan.mm_slot->slot.mm_node);
3090 }
3091 unlock:
3092 spin_unlock(&ksm_mmlist_lock);
3093
3094 if (easy_to_free) {
3095 mm_slot_free(mm_slot_cache, mm_slot);
3096 mm_flags_clear(MMF_VM_MERGE_ANY, mm);
3097 mm_flags_clear(MMF_VM_MERGEABLE, mm);
3098 mmdrop(mm);
3099 } else if (mm_slot) {
3100 mmap_write_lock(mm);
3101 mmap_write_unlock(mm);
3102 }
3103
3104 trace_ksm_exit(mm);
3105 }
3106
ksm_might_need_to_copy(struct folio * folio,struct vm_area_struct * vma,unsigned long addr)3107 struct folio *ksm_might_need_to_copy(struct folio *folio,
3108 struct vm_area_struct *vma, unsigned long addr)
3109 {
3110 struct page *page = folio_page(folio, 0);
3111 struct anon_vma *anon_vma = folio_anon_vma(folio);
3112 struct folio *new_folio;
3113
3114 if (folio_test_large(folio))
3115 return folio;
3116
3117 if (folio_test_ksm(folio)) {
3118 if (folio_stable_node(folio) &&
3119 !(ksm_run & KSM_RUN_UNMERGE))
3120 return folio; /* no need to copy it */
3121 } else if (!anon_vma) {
3122 return folio; /* no need to copy it */
3123 } else if (folio->index == linear_page_index(vma, addr) &&
3124 anon_vma->root == vma->anon_vma->root) {
3125 return folio; /* still no need to copy it */
3126 }
3127 if (PageHWPoison(page))
3128 return ERR_PTR(-EHWPOISON);
3129 if (!folio_test_uptodate(folio))
3130 return folio; /* let do_swap_page report the error */
3131
3132 new_folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, addr);
3133 if (new_folio &&
3134 mem_cgroup_charge(new_folio, vma->vm_mm, GFP_KERNEL)) {
3135 folio_put(new_folio);
3136 new_folio = NULL;
3137 }
3138 if (new_folio) {
3139 if (copy_mc_user_highpage(folio_page(new_folio, 0), page,
3140 addr, vma)) {
3141 folio_put(new_folio);
3142 return ERR_PTR(-EHWPOISON);
3143 }
3144 folio_set_dirty(new_folio);
3145 __folio_mark_uptodate(new_folio);
3146 __folio_set_locked(new_folio);
3147 #ifdef CONFIG_SWAP
3148 count_vm_event(KSM_SWPIN_COPY);
3149 #endif
3150 }
3151
3152 return new_folio;
3153 }
3154
rmap_walk_ksm(struct folio * folio,struct rmap_walk_control * rwc)3155 void rmap_walk_ksm(struct folio *folio, struct rmap_walk_control *rwc)
3156 {
3157 struct ksm_stable_node *stable_node;
3158 struct ksm_rmap_item *rmap_item;
3159 int search_new_forks = 0;
3160
3161 VM_BUG_ON_FOLIO(!folio_test_ksm(folio), folio);
3162
3163 /*
3164 * Rely on the page lock to protect against concurrent modifications
3165 * to that page's node of the stable tree.
3166 */
3167 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
3168
3169 stable_node = folio_stable_node(folio);
3170 if (!stable_node)
3171 return;
3172 again:
3173 hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
3174 /* Ignore the stable/unstable/sqnr flags */
3175 const unsigned long addr = rmap_item->address & PAGE_MASK;
3176 struct anon_vma *anon_vma = rmap_item->anon_vma;
3177 struct anon_vma_chain *vmac;
3178 struct vm_area_struct *vma;
3179
3180 cond_resched();
3181 if (!anon_vma_trylock_read(anon_vma)) {
3182 if (rwc->try_lock) {
3183 rwc->contended = true;
3184 return;
3185 }
3186 anon_vma_lock_read(anon_vma);
3187 }
3188
3189 anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
3190 0, ULONG_MAX) {
3191
3192 cond_resched();
3193 vma = vmac->vma;
3194
3195 if (addr < vma->vm_start || addr >= vma->vm_end)
3196 continue;
3197 /*
3198 * Initially we examine only the vma which covers this
3199 * rmap_item; but later, if there is still work to do,
3200 * we examine covering vmas in other mms: in case they
3201 * were forked from the original since ksmd passed.
3202 */
3203 if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
3204 continue;
3205
3206 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
3207 continue;
3208
3209 if (!rwc->rmap_one(folio, vma, addr, rwc->arg)) {
3210 anon_vma_unlock_read(anon_vma);
3211 return;
3212 }
3213 if (rwc->done && rwc->done(folio)) {
3214 anon_vma_unlock_read(anon_vma);
3215 return;
3216 }
3217 }
3218 anon_vma_unlock_read(anon_vma);
3219 }
3220 if (!search_new_forks++)
3221 goto again;
3222 }
3223
3224 #ifdef CONFIG_MEMORY_FAILURE
3225 /*
3226 * Collect processes when the error hit an ksm page.
3227 */
collect_procs_ksm(const struct folio * folio,const struct page * page,struct list_head * to_kill,int force_early)3228 void collect_procs_ksm(const struct folio *folio, const struct page *page,
3229 struct list_head *to_kill, int force_early)
3230 {
3231 struct ksm_stable_node *stable_node;
3232 struct ksm_rmap_item *rmap_item;
3233 struct vm_area_struct *vma;
3234 struct task_struct *tsk;
3235
3236 stable_node = folio_stable_node(folio);
3237 if (!stable_node)
3238 return;
3239 hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
3240 struct anon_vma *av = rmap_item->anon_vma;
3241
3242 anon_vma_lock_read(av);
3243 rcu_read_lock();
3244 for_each_process(tsk) {
3245 struct anon_vma_chain *vmac;
3246 unsigned long addr;
3247 struct task_struct *t =
3248 task_early_kill(tsk, force_early);
3249 if (!t)
3250 continue;
3251 anon_vma_interval_tree_foreach(vmac, &av->rb_root, 0,
3252 ULONG_MAX)
3253 {
3254 vma = vmac->vma;
3255 if (vma->vm_mm == t->mm) {
3256 addr = rmap_item->address & PAGE_MASK;
3257 add_to_kill_ksm(t, page, vma, to_kill,
3258 addr);
3259 }
3260 }
3261 }
3262 rcu_read_unlock();
3263 anon_vma_unlock_read(av);
3264 }
3265 }
3266 #endif
3267
3268 #ifdef CONFIG_MIGRATION
folio_migrate_ksm(struct folio * newfolio,struct folio * folio)3269 void folio_migrate_ksm(struct folio *newfolio, struct folio *folio)
3270 {
3271 struct ksm_stable_node *stable_node;
3272
3273 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
3274 VM_BUG_ON_FOLIO(!folio_test_locked(newfolio), newfolio);
3275 VM_BUG_ON_FOLIO(newfolio->mapping != folio->mapping, newfolio);
3276
3277 stable_node = folio_stable_node(folio);
3278 if (stable_node) {
3279 VM_BUG_ON_FOLIO(stable_node->kpfn != folio_pfn(folio), folio);
3280 stable_node->kpfn = folio_pfn(newfolio);
3281 /*
3282 * newfolio->mapping was set in advance; now we need smp_wmb()
3283 * to make sure that the new stable_node->kpfn is visible
3284 * to ksm_get_folio() before it can see that folio->mapping
3285 * has gone stale (or that the swapcache flag has been cleared).
3286 */
3287 smp_wmb();
3288 folio_set_stable_node(folio, NULL);
3289 }
3290 }
3291 #endif /* CONFIG_MIGRATION */
3292
3293 #ifdef CONFIG_MEMORY_HOTREMOVE
wait_while_offlining(void)3294 static void wait_while_offlining(void)
3295 {
3296 while (ksm_run & KSM_RUN_OFFLINE) {
3297 mutex_unlock(&ksm_thread_mutex);
3298 wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
3299 TASK_UNINTERRUPTIBLE);
3300 mutex_lock(&ksm_thread_mutex);
3301 }
3302 }
3303
stable_node_dup_remove_range(struct ksm_stable_node * stable_node,unsigned long start_pfn,unsigned long end_pfn)3304 static bool stable_node_dup_remove_range(struct ksm_stable_node *stable_node,
3305 unsigned long start_pfn,
3306 unsigned long end_pfn)
3307 {
3308 if (stable_node->kpfn >= start_pfn &&
3309 stable_node->kpfn < end_pfn) {
3310 /*
3311 * Don't ksm_get_folio, page has already gone:
3312 * which is why we keep kpfn instead of page*
3313 */
3314 remove_node_from_stable_tree(stable_node);
3315 return true;
3316 }
3317 return false;
3318 }
3319
stable_node_chain_remove_range(struct ksm_stable_node * stable_node,unsigned long start_pfn,unsigned long end_pfn,struct rb_root * root)3320 static bool stable_node_chain_remove_range(struct ksm_stable_node *stable_node,
3321 unsigned long start_pfn,
3322 unsigned long end_pfn,
3323 struct rb_root *root)
3324 {
3325 struct ksm_stable_node *dup;
3326 struct hlist_node *hlist_safe;
3327
3328 if (!is_stable_node_chain(stable_node)) {
3329 VM_BUG_ON(is_stable_node_dup(stable_node));
3330 return stable_node_dup_remove_range(stable_node, start_pfn,
3331 end_pfn);
3332 }
3333
3334 hlist_for_each_entry_safe(dup, hlist_safe,
3335 &stable_node->hlist, hlist_dup) {
3336 VM_BUG_ON(!is_stable_node_dup(dup));
3337 stable_node_dup_remove_range(dup, start_pfn, end_pfn);
3338 }
3339 if (hlist_empty(&stable_node->hlist)) {
3340 free_stable_node_chain(stable_node, root);
3341 return true; /* notify caller that tree was rebalanced */
3342 } else
3343 return false;
3344 }
3345
ksm_check_stable_tree(unsigned long start_pfn,unsigned long end_pfn)3346 static void ksm_check_stable_tree(unsigned long start_pfn,
3347 unsigned long end_pfn)
3348 {
3349 struct ksm_stable_node *stable_node, *next;
3350 struct rb_node *node;
3351 int nid;
3352
3353 for (nid = 0; nid < ksm_nr_node_ids; nid++) {
3354 node = rb_first(root_stable_tree + nid);
3355 while (node) {
3356 stable_node = rb_entry(node, struct ksm_stable_node, node);
3357 if (stable_node_chain_remove_range(stable_node,
3358 start_pfn, end_pfn,
3359 root_stable_tree +
3360 nid))
3361 node = rb_first(root_stable_tree + nid);
3362 else
3363 node = rb_next(node);
3364 cond_resched();
3365 }
3366 }
3367 list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
3368 if (stable_node->kpfn >= start_pfn &&
3369 stable_node->kpfn < end_pfn)
3370 remove_node_from_stable_tree(stable_node);
3371 cond_resched();
3372 }
3373 }
3374
ksm_memory_callback(struct notifier_block * self,unsigned long action,void * arg)3375 static int ksm_memory_callback(struct notifier_block *self,
3376 unsigned long action, void *arg)
3377 {
3378 struct memory_notify *mn = arg;
3379
3380 switch (action) {
3381 case MEM_GOING_OFFLINE:
3382 /*
3383 * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
3384 * and remove_all_stable_nodes() while memory is going offline:
3385 * it is unsafe for them to touch the stable tree at this time.
3386 * But break_ksm(), rmap lookups and other entry points
3387 * which do not need the ksm_thread_mutex are all safe.
3388 */
3389 mutex_lock(&ksm_thread_mutex);
3390 ksm_run |= KSM_RUN_OFFLINE;
3391 mutex_unlock(&ksm_thread_mutex);
3392 break;
3393
3394 case MEM_OFFLINE:
3395 /*
3396 * Most of the work is done by page migration; but there might
3397 * be a few stable_nodes left over, still pointing to struct
3398 * pages which have been offlined: prune those from the tree,
3399 * otherwise ksm_get_folio() might later try to access a
3400 * non-existent struct page.
3401 */
3402 ksm_check_stable_tree(mn->start_pfn,
3403 mn->start_pfn + mn->nr_pages);
3404 fallthrough;
3405 case MEM_CANCEL_OFFLINE:
3406 mutex_lock(&ksm_thread_mutex);
3407 ksm_run &= ~KSM_RUN_OFFLINE;
3408 mutex_unlock(&ksm_thread_mutex);
3409
3410 smp_mb(); /* wake_up_bit advises this */
3411 wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
3412 break;
3413 }
3414 return NOTIFY_OK;
3415 }
3416 #else
wait_while_offlining(void)3417 static void wait_while_offlining(void)
3418 {
3419 }
3420 #endif /* CONFIG_MEMORY_HOTREMOVE */
3421
3422 #ifdef CONFIG_PROC_FS
3423 /*
3424 * The process is mergeable only if any VMA is currently
3425 * applicable to KSM.
3426 *
3427 * The mmap lock must be held in read mode.
3428 */
ksm_process_mergeable(struct mm_struct * mm)3429 bool ksm_process_mergeable(struct mm_struct *mm)
3430 {
3431 struct vm_area_struct *vma;
3432
3433 mmap_assert_locked(mm);
3434 VMA_ITERATOR(vmi, mm, 0);
3435 for_each_vma(vmi, vma)
3436 if (vma->vm_flags & VM_MERGEABLE)
3437 return true;
3438
3439 return false;
3440 }
3441
ksm_process_profit(struct mm_struct * mm)3442 long ksm_process_profit(struct mm_struct *mm)
3443 {
3444 return (long)(mm->ksm_merging_pages + mm_ksm_zero_pages(mm)) * PAGE_SIZE -
3445 mm->ksm_rmap_items * sizeof(struct ksm_rmap_item);
3446 }
3447 #endif /* CONFIG_PROC_FS */
3448
3449 #ifdef CONFIG_SYSFS
3450 /*
3451 * This all compiles without CONFIG_SYSFS, but is a waste of space.
3452 */
3453
3454 #define KSM_ATTR_RO(_name) \
3455 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
3456 #define KSM_ATTR(_name) \
3457 static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
3458
sleep_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3459 static ssize_t sleep_millisecs_show(struct kobject *kobj,
3460 struct kobj_attribute *attr, char *buf)
3461 {
3462 return sysfs_emit(buf, "%u\n", ksm_thread_sleep_millisecs);
3463 }
3464
sleep_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3465 static ssize_t sleep_millisecs_store(struct kobject *kobj,
3466 struct kobj_attribute *attr,
3467 const char *buf, size_t count)
3468 {
3469 unsigned int msecs;
3470 int err;
3471
3472 err = kstrtouint(buf, 10, &msecs);
3473 if (err)
3474 return -EINVAL;
3475
3476 ksm_thread_sleep_millisecs = msecs;
3477 wake_up_interruptible(&ksm_iter_wait);
3478
3479 return count;
3480 }
3481 KSM_ATTR(sleep_millisecs);
3482
pages_to_scan_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3483 static ssize_t pages_to_scan_show(struct kobject *kobj,
3484 struct kobj_attribute *attr, char *buf)
3485 {
3486 return sysfs_emit(buf, "%u\n", ksm_thread_pages_to_scan);
3487 }
3488
pages_to_scan_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3489 static ssize_t pages_to_scan_store(struct kobject *kobj,
3490 struct kobj_attribute *attr,
3491 const char *buf, size_t count)
3492 {
3493 unsigned int nr_pages;
3494 int err;
3495
3496 if (ksm_advisor != KSM_ADVISOR_NONE)
3497 return -EINVAL;
3498
3499 err = kstrtouint(buf, 10, &nr_pages);
3500 if (err)
3501 return -EINVAL;
3502
3503 ksm_thread_pages_to_scan = nr_pages;
3504
3505 return count;
3506 }
3507 KSM_ATTR(pages_to_scan);
3508
run_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3509 static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
3510 char *buf)
3511 {
3512 return sysfs_emit(buf, "%lu\n", ksm_run);
3513 }
3514
run_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3515 static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
3516 const char *buf, size_t count)
3517 {
3518 unsigned int flags;
3519 int err;
3520
3521 err = kstrtouint(buf, 10, &flags);
3522 if (err)
3523 return -EINVAL;
3524 if (flags > KSM_RUN_UNMERGE)
3525 return -EINVAL;
3526
3527 /*
3528 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
3529 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
3530 * breaking COW to free the pages_shared (but leaves mm_slots
3531 * on the list for when ksmd may be set running again).
3532 */
3533
3534 mutex_lock(&ksm_thread_mutex);
3535 wait_while_offlining();
3536 if (ksm_run != flags) {
3537 ksm_run = flags;
3538 if (flags & KSM_RUN_UNMERGE) {
3539 set_current_oom_origin();
3540 err = unmerge_and_remove_all_rmap_items();
3541 clear_current_oom_origin();
3542 if (err) {
3543 ksm_run = KSM_RUN_STOP;
3544 count = err;
3545 }
3546 }
3547 }
3548 mutex_unlock(&ksm_thread_mutex);
3549
3550 if (flags & KSM_RUN_MERGE)
3551 wake_up_interruptible(&ksm_thread_wait);
3552
3553 return count;
3554 }
3555 KSM_ATTR(run);
3556
3557 #ifdef CONFIG_NUMA
merge_across_nodes_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3558 static ssize_t merge_across_nodes_show(struct kobject *kobj,
3559 struct kobj_attribute *attr, char *buf)
3560 {
3561 return sysfs_emit(buf, "%u\n", ksm_merge_across_nodes);
3562 }
3563
merge_across_nodes_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3564 static ssize_t merge_across_nodes_store(struct kobject *kobj,
3565 struct kobj_attribute *attr,
3566 const char *buf, size_t count)
3567 {
3568 int err;
3569 unsigned long knob;
3570
3571 err = kstrtoul(buf, 10, &knob);
3572 if (err)
3573 return err;
3574 if (knob > 1)
3575 return -EINVAL;
3576
3577 mutex_lock(&ksm_thread_mutex);
3578 wait_while_offlining();
3579 if (ksm_merge_across_nodes != knob) {
3580 if (ksm_pages_shared || remove_all_stable_nodes())
3581 err = -EBUSY;
3582 else if (root_stable_tree == one_stable_tree) {
3583 struct rb_root *buf;
3584 /*
3585 * This is the first time that we switch away from the
3586 * default of merging across nodes: must now allocate
3587 * a buffer to hold as many roots as may be needed.
3588 * Allocate stable and unstable together:
3589 * MAXSMP NODES_SHIFT 10 will use 16kB.
3590 */
3591 buf = kzalloc_objs(*buf, nr_node_ids + nr_node_ids);
3592 /* Let us assume that RB_ROOT is NULL is zero */
3593 if (!buf)
3594 err = -ENOMEM;
3595 else {
3596 root_stable_tree = buf;
3597 root_unstable_tree = buf + nr_node_ids;
3598 /* Stable tree is empty but not the unstable */
3599 root_unstable_tree[0] = one_unstable_tree[0];
3600 }
3601 }
3602 if (!err) {
3603 ksm_merge_across_nodes = knob;
3604 ksm_nr_node_ids = knob ? 1 : nr_node_ids;
3605 }
3606 }
3607 mutex_unlock(&ksm_thread_mutex);
3608
3609 return err ? err : count;
3610 }
3611 KSM_ATTR(merge_across_nodes);
3612 #endif
3613
use_zero_pages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3614 static ssize_t use_zero_pages_show(struct kobject *kobj,
3615 struct kobj_attribute *attr, char *buf)
3616 {
3617 return sysfs_emit(buf, "%u\n", ksm_use_zero_pages);
3618 }
use_zero_pages_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3619 static ssize_t use_zero_pages_store(struct kobject *kobj,
3620 struct kobj_attribute *attr,
3621 const char *buf, size_t count)
3622 {
3623 int err;
3624 bool value;
3625
3626 err = kstrtobool(buf, &value);
3627 if (err)
3628 return -EINVAL;
3629
3630 ksm_use_zero_pages = value;
3631
3632 return count;
3633 }
3634 KSM_ATTR(use_zero_pages);
3635
max_page_sharing_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3636 static ssize_t max_page_sharing_show(struct kobject *kobj,
3637 struct kobj_attribute *attr, char *buf)
3638 {
3639 return sysfs_emit(buf, "%u\n", ksm_max_page_sharing);
3640 }
3641
max_page_sharing_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3642 static ssize_t max_page_sharing_store(struct kobject *kobj,
3643 struct kobj_attribute *attr,
3644 const char *buf, size_t count)
3645 {
3646 int err;
3647 int knob;
3648
3649 err = kstrtoint(buf, 10, &knob);
3650 if (err)
3651 return err;
3652 /*
3653 * When a KSM page is created it is shared by 2 mappings. This
3654 * being a signed comparison, it implicitly verifies it's not
3655 * negative.
3656 */
3657 if (knob < 2)
3658 return -EINVAL;
3659
3660 if (READ_ONCE(ksm_max_page_sharing) == knob)
3661 return count;
3662
3663 mutex_lock(&ksm_thread_mutex);
3664 wait_while_offlining();
3665 if (ksm_max_page_sharing != knob) {
3666 if (ksm_pages_shared || remove_all_stable_nodes())
3667 err = -EBUSY;
3668 else
3669 ksm_max_page_sharing = knob;
3670 }
3671 mutex_unlock(&ksm_thread_mutex);
3672
3673 return err ? err : count;
3674 }
3675 KSM_ATTR(max_page_sharing);
3676
pages_scanned_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3677 static ssize_t pages_scanned_show(struct kobject *kobj,
3678 struct kobj_attribute *attr, char *buf)
3679 {
3680 return sysfs_emit(buf, "%lu\n", ksm_pages_scanned);
3681 }
3682 KSM_ATTR_RO(pages_scanned);
3683
pages_shared_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3684 static ssize_t pages_shared_show(struct kobject *kobj,
3685 struct kobj_attribute *attr, char *buf)
3686 {
3687 return sysfs_emit(buf, "%lu\n", ksm_pages_shared);
3688 }
3689 KSM_ATTR_RO(pages_shared);
3690
pages_sharing_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3691 static ssize_t pages_sharing_show(struct kobject *kobj,
3692 struct kobj_attribute *attr, char *buf)
3693 {
3694 return sysfs_emit(buf, "%lu\n", ksm_pages_sharing);
3695 }
3696 KSM_ATTR_RO(pages_sharing);
3697
pages_unshared_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3698 static ssize_t pages_unshared_show(struct kobject *kobj,
3699 struct kobj_attribute *attr, char *buf)
3700 {
3701 return sysfs_emit(buf, "%lu\n", ksm_pages_unshared);
3702 }
3703 KSM_ATTR_RO(pages_unshared);
3704
pages_volatile_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3705 static ssize_t pages_volatile_show(struct kobject *kobj,
3706 struct kobj_attribute *attr, char *buf)
3707 {
3708 long ksm_pages_volatile;
3709
3710 ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
3711 - ksm_pages_sharing - ksm_pages_unshared;
3712 /*
3713 * It was not worth any locking to calculate that statistic,
3714 * but it might therefore sometimes be negative: conceal that.
3715 */
3716 if (ksm_pages_volatile < 0)
3717 ksm_pages_volatile = 0;
3718 return sysfs_emit(buf, "%ld\n", ksm_pages_volatile);
3719 }
3720 KSM_ATTR_RO(pages_volatile);
3721
pages_skipped_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3722 static ssize_t pages_skipped_show(struct kobject *kobj,
3723 struct kobj_attribute *attr, char *buf)
3724 {
3725 return sysfs_emit(buf, "%lu\n", ksm_pages_skipped);
3726 }
3727 KSM_ATTR_RO(pages_skipped);
3728
ksm_zero_pages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3729 static ssize_t ksm_zero_pages_show(struct kobject *kobj,
3730 struct kobj_attribute *attr, char *buf)
3731 {
3732 return sysfs_emit(buf, "%ld\n", atomic_long_read(&ksm_zero_pages));
3733 }
3734 KSM_ATTR_RO(ksm_zero_pages);
3735
general_profit_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3736 static ssize_t general_profit_show(struct kobject *kobj,
3737 struct kobj_attribute *attr, char *buf)
3738 {
3739 long general_profit;
3740
3741 general_profit = (ksm_pages_sharing + atomic_long_read(&ksm_zero_pages)) * PAGE_SIZE -
3742 ksm_rmap_items * sizeof(struct ksm_rmap_item);
3743
3744 return sysfs_emit(buf, "%ld\n", general_profit);
3745 }
3746 KSM_ATTR_RO(general_profit);
3747
stable_node_dups_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3748 static ssize_t stable_node_dups_show(struct kobject *kobj,
3749 struct kobj_attribute *attr, char *buf)
3750 {
3751 return sysfs_emit(buf, "%lu\n", ksm_stable_node_dups);
3752 }
3753 KSM_ATTR_RO(stable_node_dups);
3754
stable_node_chains_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3755 static ssize_t stable_node_chains_show(struct kobject *kobj,
3756 struct kobj_attribute *attr, char *buf)
3757 {
3758 return sysfs_emit(buf, "%lu\n", ksm_stable_node_chains);
3759 }
3760 KSM_ATTR_RO(stable_node_chains);
3761
3762 static ssize_t
stable_node_chains_prune_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3763 stable_node_chains_prune_millisecs_show(struct kobject *kobj,
3764 struct kobj_attribute *attr,
3765 char *buf)
3766 {
3767 return sysfs_emit(buf, "%u\n", ksm_stable_node_chains_prune_millisecs);
3768 }
3769
3770 static ssize_t
stable_node_chains_prune_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3771 stable_node_chains_prune_millisecs_store(struct kobject *kobj,
3772 struct kobj_attribute *attr,
3773 const char *buf, size_t count)
3774 {
3775 unsigned int msecs;
3776 int err;
3777
3778 err = kstrtouint(buf, 10, &msecs);
3779 if (err)
3780 return -EINVAL;
3781
3782 ksm_stable_node_chains_prune_millisecs = msecs;
3783
3784 return count;
3785 }
3786 KSM_ATTR(stable_node_chains_prune_millisecs);
3787
full_scans_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3788 static ssize_t full_scans_show(struct kobject *kobj,
3789 struct kobj_attribute *attr, char *buf)
3790 {
3791 return sysfs_emit(buf, "%lu\n", ksm_scan.seqnr);
3792 }
3793 KSM_ATTR_RO(full_scans);
3794
smart_scan_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3795 static ssize_t smart_scan_show(struct kobject *kobj,
3796 struct kobj_attribute *attr, char *buf)
3797 {
3798 return sysfs_emit(buf, "%u\n", ksm_smart_scan);
3799 }
3800
smart_scan_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3801 static ssize_t smart_scan_store(struct kobject *kobj,
3802 struct kobj_attribute *attr,
3803 const char *buf, size_t count)
3804 {
3805 int err;
3806 bool value;
3807
3808 err = kstrtobool(buf, &value);
3809 if (err)
3810 return -EINVAL;
3811
3812 ksm_smart_scan = value;
3813 return count;
3814 }
3815 KSM_ATTR(smart_scan);
3816
advisor_mode_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3817 static ssize_t advisor_mode_show(struct kobject *kobj,
3818 struct kobj_attribute *attr, char *buf)
3819 {
3820 const char *output;
3821
3822 if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
3823 output = "none [scan-time]";
3824 else
3825 output = "[none] scan-time";
3826
3827 return sysfs_emit(buf, "%s\n", output);
3828 }
3829
advisor_mode_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3830 static ssize_t advisor_mode_store(struct kobject *kobj,
3831 struct kobj_attribute *attr, const char *buf,
3832 size_t count)
3833 {
3834 enum ksm_advisor_type curr_advisor = ksm_advisor;
3835
3836 if (sysfs_streq("scan-time", buf))
3837 ksm_advisor = KSM_ADVISOR_SCAN_TIME;
3838 else if (sysfs_streq("none", buf))
3839 ksm_advisor = KSM_ADVISOR_NONE;
3840 else
3841 return -EINVAL;
3842
3843 /* Set advisor default values */
3844 if (curr_advisor != ksm_advisor)
3845 set_advisor_defaults();
3846
3847 return count;
3848 }
3849 KSM_ATTR(advisor_mode);
3850
advisor_max_cpu_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3851 static ssize_t advisor_max_cpu_show(struct kobject *kobj,
3852 struct kobj_attribute *attr, char *buf)
3853 {
3854 return sysfs_emit(buf, "%u\n", ksm_advisor_max_cpu);
3855 }
3856
advisor_max_cpu_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3857 static ssize_t advisor_max_cpu_store(struct kobject *kobj,
3858 struct kobj_attribute *attr,
3859 const char *buf, size_t count)
3860 {
3861 int err;
3862 unsigned long value;
3863
3864 err = kstrtoul(buf, 10, &value);
3865 if (err)
3866 return -EINVAL;
3867
3868 ksm_advisor_max_cpu = value;
3869 return count;
3870 }
3871 KSM_ATTR(advisor_max_cpu);
3872
advisor_min_pages_to_scan_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3873 static ssize_t advisor_min_pages_to_scan_show(struct kobject *kobj,
3874 struct kobj_attribute *attr, char *buf)
3875 {
3876 return sysfs_emit(buf, "%lu\n", ksm_advisor_min_pages_to_scan);
3877 }
3878
advisor_min_pages_to_scan_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3879 static ssize_t advisor_min_pages_to_scan_store(struct kobject *kobj,
3880 struct kobj_attribute *attr,
3881 const char *buf, size_t count)
3882 {
3883 int err;
3884 unsigned long value;
3885
3886 err = kstrtoul(buf, 10, &value);
3887 if (err)
3888 return -EINVAL;
3889
3890 ksm_advisor_min_pages_to_scan = value;
3891 return count;
3892 }
3893 KSM_ATTR(advisor_min_pages_to_scan);
3894
advisor_max_pages_to_scan_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3895 static ssize_t advisor_max_pages_to_scan_show(struct kobject *kobj,
3896 struct kobj_attribute *attr, char *buf)
3897 {
3898 return sysfs_emit(buf, "%lu\n", ksm_advisor_max_pages_to_scan);
3899 }
3900
advisor_max_pages_to_scan_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3901 static ssize_t advisor_max_pages_to_scan_store(struct kobject *kobj,
3902 struct kobj_attribute *attr,
3903 const char *buf, size_t count)
3904 {
3905 int err;
3906 unsigned long value;
3907
3908 err = kstrtoul(buf, 10, &value);
3909 if (err)
3910 return -EINVAL;
3911
3912 ksm_advisor_max_pages_to_scan = value;
3913 return count;
3914 }
3915 KSM_ATTR(advisor_max_pages_to_scan);
3916
advisor_target_scan_time_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3917 static ssize_t advisor_target_scan_time_show(struct kobject *kobj,
3918 struct kobj_attribute *attr, char *buf)
3919 {
3920 return sysfs_emit(buf, "%lu\n", ksm_advisor_target_scan_time);
3921 }
3922
advisor_target_scan_time_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3923 static ssize_t advisor_target_scan_time_store(struct kobject *kobj,
3924 struct kobj_attribute *attr,
3925 const char *buf, size_t count)
3926 {
3927 int err;
3928 unsigned long value;
3929
3930 err = kstrtoul(buf, 10, &value);
3931 if (err)
3932 return -EINVAL;
3933 if (value < 1)
3934 return -EINVAL;
3935
3936 ksm_advisor_target_scan_time = value;
3937 return count;
3938 }
3939 KSM_ATTR(advisor_target_scan_time);
3940
3941 static struct attribute *ksm_attrs[] = {
3942 &sleep_millisecs_attr.attr,
3943 &pages_to_scan_attr.attr,
3944 &run_attr.attr,
3945 &pages_scanned_attr.attr,
3946 &pages_shared_attr.attr,
3947 &pages_sharing_attr.attr,
3948 &pages_unshared_attr.attr,
3949 &pages_volatile_attr.attr,
3950 &pages_skipped_attr.attr,
3951 &ksm_zero_pages_attr.attr,
3952 &full_scans_attr.attr,
3953 #ifdef CONFIG_NUMA
3954 &merge_across_nodes_attr.attr,
3955 #endif
3956 &max_page_sharing_attr.attr,
3957 &stable_node_chains_attr.attr,
3958 &stable_node_dups_attr.attr,
3959 &stable_node_chains_prune_millisecs_attr.attr,
3960 &use_zero_pages_attr.attr,
3961 &general_profit_attr.attr,
3962 &smart_scan_attr.attr,
3963 &advisor_mode_attr.attr,
3964 &advisor_max_cpu_attr.attr,
3965 &advisor_min_pages_to_scan_attr.attr,
3966 &advisor_max_pages_to_scan_attr.attr,
3967 &advisor_target_scan_time_attr.attr,
3968 NULL,
3969 };
3970
3971 static const struct attribute_group ksm_attr_group = {
3972 .attrs = ksm_attrs,
3973 .name = "ksm",
3974 };
3975 #endif /* CONFIG_SYSFS */
3976
ksm_init(void)3977 static int __init ksm_init(void)
3978 {
3979 struct task_struct *ksm_thread;
3980 int err;
3981
3982 /* The correct value depends on page size and endianness */
3983 zero_checksum = calc_checksum(ZERO_PAGE(0));
3984 /* Default to false for backwards compatibility */
3985 ksm_use_zero_pages = false;
3986
3987 err = ksm_slab_init();
3988 if (err)
3989 goto out;
3990
3991 ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
3992 if (IS_ERR(ksm_thread)) {
3993 pr_err("ksm: creating kthread failed\n");
3994 err = PTR_ERR(ksm_thread);
3995 goto out_free;
3996 }
3997
3998 #ifdef CONFIG_SYSFS
3999 err = sysfs_create_group(mm_kobj, &ksm_attr_group);
4000 if (err) {
4001 pr_err("ksm: register sysfs failed\n");
4002 kthread_stop(ksm_thread);
4003 goto out_free;
4004 }
4005 #else
4006 ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
4007
4008 #endif /* CONFIG_SYSFS */
4009
4010 #ifdef CONFIG_MEMORY_HOTREMOVE
4011 /* There is no significance to this priority 100 */
4012 hotplug_memory_notifier(ksm_memory_callback, KSM_CALLBACK_PRI);
4013 #endif
4014 return 0;
4015
4016 out_free:
4017 ksm_slab_free();
4018 out:
4019 return err;
4020 }
4021 subsys_initcall(ksm_init);
4022