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