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