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