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