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