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