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