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