]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - mm/ksm.c
migrate: don't account swapcache as shmem
[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
37 #include <asm/tlbflush.h>
38 #include "internal.h"
39
40 /*
41  * A few notes about the KSM scanning process,
42  * to make it easier to understand the data structures below:
43  *
44  * In order to reduce excessive scanning, KSM sorts the memory pages by their
45  * contents into a data structure that holds pointers to the pages' locations.
46  *
47  * Since the contents of the pages may change at any moment, KSM cannot just
48  * insert the pages into a normal sorted tree and expect it to find anything.
49  * Therefore KSM uses two data structures - the stable and the unstable tree.
50  *
51  * The stable tree holds pointers to all the merged pages (ksm pages), sorted
52  * by their contents.  Because each such page is write-protected, searching on
53  * this tree is fully assured to be working (except when pages are unmapped),
54  * and therefore this tree is called the stable tree.
55  *
56  * In addition to the stable tree, KSM uses a second data structure called the
57  * unstable tree: this tree holds pointers to pages which have been found to
58  * be "unchanged for a period of time".  The unstable tree sorts these pages
59  * by their contents, but since they are not write-protected, KSM cannot rely
60  * upon the unstable tree to work correctly - the unstable tree is liable to
61  * be corrupted as its contents are modified, and so it is called unstable.
62  *
63  * KSM solves this problem by several techniques:
64  *
65  * 1) The unstable tree is flushed every time KSM completes scanning all
66  *    memory areas, and then the tree is rebuilt again from the beginning.
67  * 2) KSM will only insert into the unstable tree, pages whose hash value
68  *    has not changed since the previous scan of all memory areas.
69  * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
70  *    colors of the nodes and not on their contents, assuring that even when
71  *    the tree gets "corrupted" it won't get out of balance, so scanning time
72  *    remains the same (also, searching and inserting nodes in an rbtree uses
73  *    the same algorithm, so we have no overhead when we flush and rebuild).
74  * 4) KSM never flushes the stable tree, which means that even if it were to
75  *    take 10 attempts to find a page in the unstable tree, once it is found,
76  *    it is secured in the stable tree.  (When we scan a new page, we first
77  *    compare it against the stable tree, and then against the unstable tree.)
78  */
79
80 /**
81  * struct mm_slot - ksm information per mm that is being scanned
82  * @link: link to the mm_slots hash list
83  * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
84  * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
85  * @mm: the mm that this information is valid for
86  */
87 struct mm_slot {
88         struct hlist_node link;
89         struct list_head mm_list;
90         struct rmap_item *rmap_list;
91         struct mm_struct *mm;
92 };
93
94 /**
95  * struct ksm_scan - cursor for scanning
96  * @mm_slot: the current mm_slot we are scanning
97  * @address: the next address inside that to be scanned
98  * @rmap_list: link to the next rmap to be scanned in the rmap_list
99  * @seqnr: count of completed full scans (needed when removing unstable node)
100  *
101  * There is only the one ksm_scan instance of this cursor structure.
102  */
103 struct ksm_scan {
104         struct mm_slot *mm_slot;
105         unsigned long address;
106         struct rmap_item **rmap_list;
107         unsigned long seqnr;
108 };
109
110 /**
111  * struct stable_node - node of the stable rbtree
112  * @node: rb node of this ksm page in the stable tree
113  * @hlist: hlist head of rmap_items using this ksm page
114  * @kpfn: page frame number of this ksm page
115  */
116 struct stable_node {
117         struct rb_node node;
118         struct hlist_head hlist;
119         unsigned long kpfn;
120 };
121
122 /**
123  * struct rmap_item - reverse mapping item for virtual addresses
124  * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
125  * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
126  * @mm: the memory structure this rmap_item is pointing into
127  * @address: the virtual address this rmap_item tracks (+ flags in low bits)
128  * @oldchecksum: previous checksum of the page at that virtual address
129  * @node: rb node of this rmap_item in the unstable tree
130  * @head: pointer to stable_node heading this list in the stable tree
131  * @hlist: link into hlist of rmap_items hanging off that stable_node
132  */
133 struct rmap_item {
134         struct rmap_item *rmap_list;
135         struct anon_vma *anon_vma;      /* when stable */
136         struct mm_struct *mm;
137         unsigned long address;          /* + low bits used for flags below */
138         unsigned int oldchecksum;       /* when unstable */
139         union {
140                 struct rb_node node;    /* when node of unstable tree */
141                 struct {                /* when listed from stable tree */
142                         struct stable_node *head;
143                         struct hlist_node hlist;
144                 };
145         };
146 };
147
148 #define SEQNR_MASK      0x0ff   /* low bits of unstable tree seqnr */
149 #define UNSTABLE_FLAG   0x100   /* is a node of the unstable tree */
150 #define STABLE_FLAG     0x200   /* is listed from the stable tree */
151
152 /* The stable and unstable tree heads */
153 static struct rb_root root_stable_tree = RB_ROOT;
154 static struct rb_root root_unstable_tree = RB_ROOT;
155
156 #define MM_SLOTS_HASH_HEADS 1024
157 static struct hlist_head *mm_slots_hash;
158
159 static struct mm_slot ksm_mm_head = {
160         .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
161 };
162 static struct ksm_scan ksm_scan = {
163         .mm_slot = &ksm_mm_head,
164 };
165
166 static struct kmem_cache *rmap_item_cache;
167 static struct kmem_cache *stable_node_cache;
168 static struct kmem_cache *mm_slot_cache;
169
170 /* The number of nodes in the stable tree */
171 static unsigned long ksm_pages_shared;
172
173 /* The number of page slots additionally sharing those nodes */
174 static unsigned long ksm_pages_sharing;
175
176 /* The number of nodes in the unstable tree */
177 static unsigned long ksm_pages_unshared;
178
179 /* The number of rmap_items in use: to calculate pages_volatile */
180 static unsigned long ksm_rmap_items;
181
182 /* Number of pages ksmd should scan in one batch */
183 static unsigned int ksm_thread_pages_to_scan = 100;
184
185 /* Milliseconds ksmd should sleep between batches */
186 static unsigned int ksm_thread_sleep_millisecs = 20;
187
188 #define KSM_RUN_STOP    0
189 #define KSM_RUN_MERGE   1
190 #define KSM_RUN_UNMERGE 2
191 static unsigned int ksm_run = KSM_RUN_STOP;
192
193 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
194 static DEFINE_MUTEX(ksm_thread_mutex);
195 static DEFINE_SPINLOCK(ksm_mmlist_lock);
196
197 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
198                 sizeof(struct __struct), __alignof__(struct __struct),\
199                 (__flags), NULL)
200
201 static int __init ksm_slab_init(void)
202 {
203         rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
204         if (!rmap_item_cache)
205                 goto out;
206
207         stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
208         if (!stable_node_cache)
209                 goto out_free1;
210
211         mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
212         if (!mm_slot_cache)
213                 goto out_free2;
214
215         return 0;
216
217 out_free2:
218         kmem_cache_destroy(stable_node_cache);
219 out_free1:
220         kmem_cache_destroy(rmap_item_cache);
221 out:
222         return -ENOMEM;
223 }
224
225 static void __init ksm_slab_free(void)
226 {
227         kmem_cache_destroy(mm_slot_cache);
228         kmem_cache_destroy(stable_node_cache);
229         kmem_cache_destroy(rmap_item_cache);
230         mm_slot_cache = NULL;
231 }
232
233 static inline struct rmap_item *alloc_rmap_item(void)
234 {
235         struct rmap_item *rmap_item;
236
237         rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL);
238         if (rmap_item)
239                 ksm_rmap_items++;
240         return rmap_item;
241 }
242
243 static inline void free_rmap_item(struct rmap_item *rmap_item)
244 {
245         ksm_rmap_items--;
246         rmap_item->mm = NULL;   /* debug safety */
247         kmem_cache_free(rmap_item_cache, rmap_item);
248 }
249
250 static inline struct stable_node *alloc_stable_node(void)
251 {
252         return kmem_cache_alloc(stable_node_cache, GFP_KERNEL);
253 }
254
255 static inline void free_stable_node(struct stable_node *stable_node)
256 {
257         kmem_cache_free(stable_node_cache, stable_node);
258 }
259
260 static inline struct mm_slot *alloc_mm_slot(void)
261 {
262         if (!mm_slot_cache)     /* initialization failed */
263                 return NULL;
264         return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
265 }
266
267 static inline void free_mm_slot(struct mm_slot *mm_slot)
268 {
269         kmem_cache_free(mm_slot_cache, mm_slot);
270 }
271
272 static int __init mm_slots_hash_init(void)
273 {
274         mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
275                                 GFP_KERNEL);
276         if (!mm_slots_hash)
277                 return -ENOMEM;
278         return 0;
279 }
280
281 static void __init mm_slots_hash_free(void)
282 {
283         kfree(mm_slots_hash);
284 }
285
286 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
287 {
288         struct mm_slot *mm_slot;
289         struct hlist_head *bucket;
290         struct hlist_node *node;
291
292         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
293                                 % MM_SLOTS_HASH_HEADS];
294         hlist_for_each_entry(mm_slot, node, bucket, link) {
295                 if (mm == mm_slot->mm)
296                         return mm_slot;
297         }
298         return NULL;
299 }
300
301 static void insert_to_mm_slots_hash(struct mm_struct *mm,
302                                     struct mm_slot *mm_slot)
303 {
304         struct hlist_head *bucket;
305
306         bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
307                                 % MM_SLOTS_HASH_HEADS];
308         mm_slot->mm = mm;
309         hlist_add_head(&mm_slot->link, bucket);
310 }
311
312 static inline int in_stable_tree(struct rmap_item *rmap_item)
313 {
314         return rmap_item->address & STABLE_FLAG;
315 }
316
317 static void hold_anon_vma(struct rmap_item *rmap_item,
318                           struct anon_vma *anon_vma)
319 {
320         rmap_item->anon_vma = anon_vma;
321         atomic_inc(&anon_vma->external_refcount);
322 }
323
324 static void drop_anon_vma(struct rmap_item *rmap_item)
325 {
326         struct anon_vma *anon_vma = rmap_item->anon_vma;
327
328         if (atomic_dec_and_lock(&anon_vma->external_refcount, &anon_vma->lock)) {
329                 int empty = list_empty(&anon_vma->head);
330                 spin_unlock(&anon_vma->lock);
331                 if (empty)
332                         anon_vma_free(anon_vma);
333         }
334 }
335
336 /*
337  * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
338  * page tables after it has passed through ksm_exit() - which, if necessary,
339  * takes mmap_sem briefly to serialize against them.  ksm_exit() does not set
340  * a special flag: they can just back out as soon as mm_users goes to zero.
341  * ksm_test_exit() is used throughout to make this test for exit: in some
342  * places for correctness, in some places just to avoid unnecessary work.
343  */
344 static inline bool ksm_test_exit(struct mm_struct *mm)
345 {
346         return atomic_read(&mm->mm_users) == 0;
347 }
348
349 /*
350  * We use break_ksm to break COW on a ksm page: it's a stripped down
351  *
352  *      if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
353  *              put_page(page);
354  *
355  * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
356  * in case the application has unmapped and remapped mm,addr meanwhile.
357  * Could a ksm page appear anywhere else?  Actually yes, in a VM_PFNMAP
358  * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
359  */
360 static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
361 {
362         struct page *page;
363         int ret = 0;
364
365         do {
366                 cond_resched();
367                 page = follow_page(vma, addr, FOLL_GET);
368                 if (IS_ERR_OR_NULL(page))
369                         break;
370                 if (PageKsm(page))
371                         ret = handle_mm_fault(vma->vm_mm, vma, addr,
372                                                         FAULT_FLAG_WRITE);
373                 else
374                         ret = VM_FAULT_WRITE;
375                 put_page(page);
376         } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_OOM)));
377         /*
378          * We must loop because handle_mm_fault() may back out if there's
379          * any difficulty e.g. if pte accessed bit gets updated concurrently.
380          *
381          * VM_FAULT_WRITE is what we have been hoping for: it indicates that
382          * COW has been broken, even if the vma does not permit VM_WRITE;
383          * but note that a concurrent fault might break PageKsm for us.
384          *
385          * VM_FAULT_SIGBUS could occur if we race with truncation of the
386          * backing file, which also invalidates anonymous pages: that's
387          * okay, that truncation will have unmapped the PageKsm for us.
388          *
389          * VM_FAULT_OOM: at the time of writing (late July 2009), setting
390          * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
391          * current task has TIF_MEMDIE set, and will be OOM killed on return
392          * to user; and ksmd, having no mm, would never be chosen for that.
393          *
394          * But if the mm is in a limited mem_cgroup, then the fault may fail
395          * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
396          * even ksmd can fail in this way - though it's usually breaking ksm
397          * just to undo a merge it made a moment before, so unlikely to oom.
398          *
399          * That's a pity: we might therefore have more kernel pages allocated
400          * than we're counting as nodes in the stable tree; but ksm_do_scan
401          * will retry to break_cow on each pass, so should recover the page
402          * in due course.  The important thing is to not let VM_MERGEABLE
403          * be cleared while any such pages might remain in the area.
404          */
405         return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
406 }
407
408 static void break_cow(struct rmap_item *rmap_item)
409 {
410         struct mm_struct *mm = rmap_item->mm;
411         unsigned long addr = rmap_item->address;
412         struct vm_area_struct *vma;
413
414         /*
415          * It is not an accident that whenever we want to break COW
416          * to undo, we also need to drop a reference to the anon_vma.
417          */
418         drop_anon_vma(rmap_item);
419
420         down_read(&mm->mmap_sem);
421         if (ksm_test_exit(mm))
422                 goto out;
423         vma = find_vma(mm, addr);
424         if (!vma || vma->vm_start > addr)
425                 goto out;
426         if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
427                 goto out;
428         break_ksm(vma, addr);
429 out:
430         up_read(&mm->mmap_sem);
431 }
432
433 static struct page *get_mergeable_page(struct rmap_item *rmap_item)
434 {
435         struct mm_struct *mm = rmap_item->mm;
436         unsigned long addr = rmap_item->address;
437         struct vm_area_struct *vma;
438         struct page *page;
439
440         down_read(&mm->mmap_sem);
441         if (ksm_test_exit(mm))
442                 goto out;
443         vma = find_vma(mm, addr);
444         if (!vma || vma->vm_start > addr)
445                 goto out;
446         if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
447                 goto out;
448
449         page = follow_page(vma, addr, FOLL_GET);
450         if (IS_ERR_OR_NULL(page))
451                 goto out;
452         if (PageAnon(page)) {
453                 flush_anon_page(vma, page, addr);
454                 flush_dcache_page(page);
455         } else {
456                 put_page(page);
457 out:            page = NULL;
458         }
459         up_read(&mm->mmap_sem);
460         return page;
461 }
462
463 static void remove_node_from_stable_tree(struct stable_node *stable_node)
464 {
465         struct rmap_item *rmap_item;
466         struct hlist_node *hlist;
467
468         hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
469                 if (rmap_item->hlist.next)
470                         ksm_pages_sharing--;
471                 else
472                         ksm_pages_shared--;
473                 drop_anon_vma(rmap_item);
474                 rmap_item->address &= PAGE_MASK;
475                 cond_resched();
476         }
477
478         rb_erase(&stable_node->node, &root_stable_tree);
479         free_stable_node(stable_node);
480 }
481
482 /*
483  * get_ksm_page: checks if the page indicated by the stable node
484  * is still its ksm page, despite having held no reference to it.
485  * In which case we can trust the content of the page, and it
486  * returns the gotten page; but if the page has now been zapped,
487  * remove the stale node from the stable tree and return NULL.
488  *
489  * You would expect the stable_node to hold a reference to the ksm page.
490  * But if it increments the page's count, swapping out has to wait for
491  * ksmd to come around again before it can free the page, which may take
492  * seconds or even minutes: much too unresponsive.  So instead we use a
493  * "keyhole reference": access to the ksm page from the stable node peeps
494  * out through its keyhole to see if that page still holds the right key,
495  * pointing back to this stable node.  This relies on freeing a PageAnon
496  * page to reset its page->mapping to NULL, and relies on no other use of
497  * a page to put something that might look like our key in page->mapping.
498  *
499  * include/linux/pagemap.h page_cache_get_speculative() is a good reference,
500  * but this is different - made simpler by ksm_thread_mutex being held, but
501  * interesting for assuming that no other use of the struct page could ever
502  * put our expected_mapping into page->mapping (or a field of the union which
503  * coincides with page->mapping).  The RCU calls are not for KSM at all, but
504  * to keep the page_count protocol described with page_cache_get_speculative.
505  *
506  * Note: it is possible that get_ksm_page() will return NULL one moment,
507  * then page the next, if the page is in between page_freeze_refs() and
508  * page_unfreeze_refs(): this shouldn't be a problem anywhere, the page
509  * is on its way to being freed; but it is an anomaly to bear in mind.
510  */
511 static struct page *get_ksm_page(struct stable_node *stable_node)
512 {
513         struct page *page;
514         void *expected_mapping;
515
516         page = pfn_to_page(stable_node->kpfn);
517         expected_mapping = (void *)stable_node +
518                                 (PAGE_MAPPING_ANON | PAGE_MAPPING_KSM);
519         rcu_read_lock();
520         if (page->mapping != expected_mapping)
521                 goto stale;
522         if (!get_page_unless_zero(page))
523                 goto stale;
524         if (page->mapping != expected_mapping) {
525                 put_page(page);
526                 goto stale;
527         }
528         rcu_read_unlock();
529         return page;
530 stale:
531         rcu_read_unlock();
532         remove_node_from_stable_tree(stable_node);
533         return NULL;
534 }
535
536 /*
537  * Removing rmap_item from stable or unstable tree.
538  * This function will clean the information from the stable/unstable tree.
539  */
540 static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
541 {
542         if (rmap_item->address & STABLE_FLAG) {
543                 struct stable_node *stable_node;
544                 struct page *page;
545
546                 stable_node = rmap_item->head;
547                 page = get_ksm_page(stable_node);
548                 if (!page)
549                         goto out;
550
551                 lock_page(page);
552                 hlist_del(&rmap_item->hlist);
553                 unlock_page(page);
554                 put_page(page);
555
556                 if (stable_node->hlist.first)
557                         ksm_pages_sharing--;
558                 else
559                         ksm_pages_shared--;
560
561                 drop_anon_vma(rmap_item);
562                 rmap_item->address &= PAGE_MASK;
563
564         } else if (rmap_item->address & UNSTABLE_FLAG) {
565                 unsigned char age;
566                 /*
567                  * Usually ksmd can and must skip the rb_erase, because
568                  * root_unstable_tree was already reset to RB_ROOT.
569                  * But be careful when an mm is exiting: do the rb_erase
570                  * if this rmap_item was inserted by this scan, rather
571                  * than left over from before.
572                  */
573                 age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
574                 BUG_ON(age > 1);
575                 if (!age)
576                         rb_erase(&rmap_item->node, &root_unstable_tree);
577
578                 ksm_pages_unshared--;
579                 rmap_item->address &= PAGE_MASK;
580         }
581 out:
582         cond_resched();         /* we're called from many long loops */
583 }
584
585 static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
586                                        struct rmap_item **rmap_list)
587 {
588         while (*rmap_list) {
589                 struct rmap_item *rmap_item = *rmap_list;
590                 *rmap_list = rmap_item->rmap_list;
591                 remove_rmap_item_from_tree(rmap_item);
592                 free_rmap_item(rmap_item);
593         }
594 }
595
596 /*
597  * Though it's very tempting to unmerge in_stable_tree(rmap_item)s rather
598  * than check every pte of a given vma, the locking doesn't quite work for
599  * that - an rmap_item is assigned to the stable tree after inserting ksm
600  * page and upping mmap_sem.  Nor does it fit with the way we skip dup'ing
601  * rmap_items from parent to child at fork time (so as not to waste time
602  * if exit comes before the next scan reaches it).
603  *
604  * Similarly, although we'd like to remove rmap_items (so updating counts
605  * and freeing memory) when unmerging an area, it's easier to leave that
606  * to the next pass of ksmd - consider, for example, how ksmd might be
607  * in cmp_and_merge_page on one of the rmap_items we would be removing.
608  */
609 static int unmerge_ksm_pages(struct vm_area_struct *vma,
610                              unsigned long start, unsigned long end)
611 {
612         unsigned long addr;
613         int err = 0;
614
615         for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
616                 if (ksm_test_exit(vma->vm_mm))
617                         break;
618                 if (signal_pending(current))
619                         err = -ERESTARTSYS;
620                 else
621                         err = break_ksm(vma, addr);
622         }
623         return err;
624 }
625
626 #ifdef CONFIG_SYSFS
627 /*
628  * Only called through the sysfs control interface:
629  */
630 static int unmerge_and_remove_all_rmap_items(void)
631 {
632         struct mm_slot *mm_slot;
633         struct mm_struct *mm;
634         struct vm_area_struct *vma;
635         int err = 0;
636
637         spin_lock(&ksm_mmlist_lock);
638         ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
639                                                 struct mm_slot, mm_list);
640         spin_unlock(&ksm_mmlist_lock);
641
642         for (mm_slot = ksm_scan.mm_slot;
643                         mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
644                 mm = mm_slot->mm;
645                 down_read(&mm->mmap_sem);
646                 for (vma = mm->mmap; vma; vma = vma->vm_next) {
647                         if (ksm_test_exit(mm))
648                                 break;
649                         if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
650                                 continue;
651                         err = unmerge_ksm_pages(vma,
652                                                 vma->vm_start, vma->vm_end);
653                         if (err)
654                                 goto error;
655                 }
656
657                 remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
658
659                 spin_lock(&ksm_mmlist_lock);
660                 ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
661                                                 struct mm_slot, mm_list);
662                 if (ksm_test_exit(mm)) {
663                         hlist_del(&mm_slot->link);
664                         list_del(&mm_slot->mm_list);
665                         spin_unlock(&ksm_mmlist_lock);
666
667                         free_mm_slot(mm_slot);
668                         clear_bit(MMF_VM_MERGEABLE, &mm->flags);
669                         up_read(&mm->mmap_sem);
670                         mmdrop(mm);
671                 } else {
672                         spin_unlock(&ksm_mmlist_lock);
673                         up_read(&mm->mmap_sem);
674                 }
675         }
676
677         ksm_scan.seqnr = 0;
678         return 0;
679
680 error:
681         up_read(&mm->mmap_sem);
682         spin_lock(&ksm_mmlist_lock);
683         ksm_scan.mm_slot = &ksm_mm_head;
684         spin_unlock(&ksm_mmlist_lock);
685         return err;
686 }
687 #endif /* CONFIG_SYSFS */
688
689 static u32 calc_checksum(struct page *page)
690 {
691         u32 checksum;
692         void *addr = kmap_atomic(page, KM_USER0);
693         checksum = jhash2(addr, PAGE_SIZE / 4, 17);
694         kunmap_atomic(addr, KM_USER0);
695         return checksum;
696 }
697
698 static int memcmp_pages(struct page *page1, struct page *page2)
699 {
700         char *addr1, *addr2;
701         int ret;
702
703         addr1 = kmap_atomic(page1, KM_USER0);
704         addr2 = kmap_atomic(page2, KM_USER1);
705         ret = memcmp(addr1, addr2, PAGE_SIZE);
706         kunmap_atomic(addr2, KM_USER1);
707         kunmap_atomic(addr1, KM_USER0);
708         return ret;
709 }
710
711 static inline int pages_identical(struct page *page1, struct page *page2)
712 {
713         return !memcmp_pages(page1, page2);
714 }
715
716 static int write_protect_page(struct vm_area_struct *vma, struct page *page,
717                               pte_t *orig_pte)
718 {
719         struct mm_struct *mm = vma->vm_mm;
720         unsigned long addr;
721         pte_t *ptep;
722         spinlock_t *ptl;
723         int swapped;
724         int err = -EFAULT;
725
726         addr = page_address_in_vma(page, vma);
727         if (addr == -EFAULT)
728                 goto out;
729
730         ptep = page_check_address(page, mm, addr, &ptl, 0);
731         if (!ptep)
732                 goto out;
733
734         if (pte_write(*ptep) || pte_dirty(*ptep)) {
735                 pte_t entry;
736
737                 swapped = PageSwapCache(page);
738                 flush_cache_page(vma, addr, page_to_pfn(page));
739                 /*
740                  * Ok this is tricky, when get_user_pages_fast() run it doesnt
741                  * take any lock, therefore the check that we are going to make
742                  * with the pagecount against the mapcount is racey and
743                  * O_DIRECT can happen right after the check.
744                  * So we clear the pte and flush the tlb before the check
745                  * this assure us that no O_DIRECT can happen after the check
746                  * or in the middle of the check.
747                  */
748                 entry = ptep_clear_flush(vma, addr, ptep);
749                 /*
750                  * Check that no O_DIRECT or similar I/O is in progress on the
751                  * page
752                  */
753                 if (page_mapcount(page) + 1 + swapped != page_count(page)) {
754                         set_pte_at(mm, addr, ptep, entry);
755                         goto out_unlock;
756                 }
757                 if (pte_dirty(entry))
758                         set_page_dirty(page);
759                 entry = pte_mkclean(pte_wrprotect(entry));
760                 set_pte_at_notify(mm, addr, ptep, entry);
761         }
762         *orig_pte = *ptep;
763         err = 0;
764
765 out_unlock:
766         pte_unmap_unlock(ptep, ptl);
767 out:
768         return err;
769 }
770
771 /**
772  * replace_page - replace page in vma by new ksm page
773  * @vma:      vma that holds the pte pointing to page
774  * @page:     the page we are replacing by kpage
775  * @kpage:    the ksm page we replace page by
776  * @orig_pte: the original value of the pte
777  *
778  * Returns 0 on success, -EFAULT on failure.
779  */
780 static int replace_page(struct vm_area_struct *vma, struct page *page,
781                         struct page *kpage, pte_t orig_pte)
782 {
783         struct mm_struct *mm = vma->vm_mm;
784         pgd_t *pgd;
785         pud_t *pud;
786         pmd_t *pmd;
787         pte_t *ptep;
788         spinlock_t *ptl;
789         unsigned long addr;
790         int err = -EFAULT;
791
792         addr = page_address_in_vma(page, vma);
793         if (addr == -EFAULT)
794                 goto out;
795
796         pgd = pgd_offset(mm, addr);
797         if (!pgd_present(*pgd))
798                 goto out;
799
800         pud = pud_offset(pgd, addr);
801         if (!pud_present(*pud))
802                 goto out;
803
804         pmd = pmd_offset(pud, addr);
805         if (!pmd_present(*pmd))
806                 goto out;
807
808         ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
809         if (!pte_same(*ptep, orig_pte)) {
810                 pte_unmap_unlock(ptep, ptl);
811                 goto out;
812         }
813
814         get_page(kpage);
815         page_add_anon_rmap(kpage, vma, addr);
816
817         flush_cache_page(vma, addr, pte_pfn(*ptep));
818         ptep_clear_flush(vma, addr, ptep);
819         set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
820
821         page_remove_rmap(page);
822         put_page(page);
823
824         pte_unmap_unlock(ptep, ptl);
825         err = 0;
826 out:
827         return err;
828 }
829
830 /*
831  * try_to_merge_one_page - take two pages and merge them into one
832  * @vma: the vma that holds the pte pointing to page
833  * @page: the PageAnon page that we want to replace with kpage
834  * @kpage: the PageKsm page that we want to map instead of page,
835  *         or NULL the first time when we want to use page as kpage.
836  *
837  * This function returns 0 if the pages were merged, -EFAULT otherwise.
838  */
839 static int try_to_merge_one_page(struct vm_area_struct *vma,
840                                  struct page *page, struct page *kpage)
841 {
842         pte_t orig_pte = __pte(0);
843         int err = -EFAULT;
844
845         if (page == kpage)                      /* ksm page forked */
846                 return 0;
847
848         if (!(vma->vm_flags & VM_MERGEABLE))
849                 goto out;
850         if (!PageAnon(page))
851                 goto out;
852
853         /*
854          * We need the page lock to read a stable PageSwapCache in
855          * write_protect_page().  We use trylock_page() instead of
856          * lock_page() because we don't want to wait here - we
857          * prefer to continue scanning and merging different pages,
858          * then come back to this page when it is unlocked.
859          */
860         if (!trylock_page(page))
861                 goto out;
862         /*
863          * If this anonymous page is mapped only here, its pte may need
864          * to be write-protected.  If it's mapped elsewhere, all of its
865          * ptes are necessarily already write-protected.  But in either
866          * case, we need to lock and check page_count is not raised.
867          */
868         if (write_protect_page(vma, page, &orig_pte) == 0) {
869                 if (!kpage) {
870                         /*
871                          * While we hold page lock, upgrade page from
872                          * PageAnon+anon_vma to PageKsm+NULL stable_node:
873                          * stable_tree_insert() will update stable_node.
874                          */
875                         set_page_stable_node(page, NULL);
876                         mark_page_accessed(page);
877                         err = 0;
878                 } else if (pages_identical(page, kpage))
879                         err = replace_page(vma, page, kpage, orig_pte);
880         }
881
882         if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
883                 munlock_vma_page(page);
884                 if (!PageMlocked(kpage)) {
885                         unlock_page(page);
886                         lock_page(kpage);
887                         mlock_vma_page(kpage);
888                         page = kpage;           /* for final unlock */
889                 }
890         }
891
892         unlock_page(page);
893 out:
894         return err;
895 }
896
897 /*
898  * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
899  * but no new kernel page is allocated: kpage must already be a ksm page.
900  *
901  * This function returns 0 if the pages were merged, -EFAULT otherwise.
902  */
903 static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
904                                       struct page *page, struct page *kpage)
905 {
906         struct mm_struct *mm = rmap_item->mm;
907         struct vm_area_struct *vma;
908         int err = -EFAULT;
909
910         down_read(&mm->mmap_sem);
911         if (ksm_test_exit(mm))
912                 goto out;
913         vma = find_vma(mm, rmap_item->address);
914         if (!vma || vma->vm_start > rmap_item->address)
915                 goto out;
916
917         err = try_to_merge_one_page(vma, page, kpage);
918         if (err)
919                 goto out;
920
921         /* Must get reference to anon_vma while still holding mmap_sem */
922         hold_anon_vma(rmap_item, vma->anon_vma);
923 out:
924         up_read(&mm->mmap_sem);
925         return err;
926 }
927
928 /*
929  * try_to_merge_two_pages - take two identical pages and prepare them
930  * to be merged into one page.
931  *
932  * This function returns the kpage if we successfully merged two identical
933  * pages into one ksm page, NULL otherwise.
934  *
935  * Note that this function upgrades page to ksm page: if one of the pages
936  * is already a ksm page, try_to_merge_with_ksm_page should be used.
937  */
938 static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
939                                            struct page *page,
940                                            struct rmap_item *tree_rmap_item,
941                                            struct page *tree_page)
942 {
943         int err;
944
945         err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
946         if (!err) {
947                 err = try_to_merge_with_ksm_page(tree_rmap_item,
948                                                         tree_page, page);
949                 /*
950                  * If that fails, we have a ksm page with only one pte
951                  * pointing to it: so break it.
952                  */
953                 if (err)
954                         break_cow(rmap_item);
955         }
956         return err ? NULL : page;
957 }
958
959 /*
960  * stable_tree_search - search for page inside the stable tree
961  *
962  * This function checks if there is a page inside the stable tree
963  * with identical content to the page that we are scanning right now.
964  *
965  * This function returns the stable tree node of identical content if found,
966  * NULL otherwise.
967  */
968 static struct page *stable_tree_search(struct page *page)
969 {
970         struct rb_node *node = root_stable_tree.rb_node;
971         struct stable_node *stable_node;
972
973         stable_node = page_stable_node(page);
974         if (stable_node) {                      /* ksm page forked */
975                 get_page(page);
976                 return page;
977         }
978
979         while (node) {
980                 struct page *tree_page;
981                 int ret;
982
983                 cond_resched();
984                 stable_node = rb_entry(node, struct stable_node, node);
985                 tree_page = get_ksm_page(stable_node);
986                 if (!tree_page)
987                         return NULL;
988
989                 ret = memcmp_pages(page, tree_page);
990
991                 if (ret < 0) {
992                         put_page(tree_page);
993                         node = node->rb_left;
994                 } else if (ret > 0) {
995                         put_page(tree_page);
996                         node = node->rb_right;
997                 } else
998                         return tree_page;
999         }
1000
1001         return NULL;
1002 }
1003
1004 /*
1005  * stable_tree_insert - insert rmap_item pointing to new ksm page
1006  * into the stable tree.
1007  *
1008  * This function returns the stable tree node just allocated on success,
1009  * NULL otherwise.
1010  */
1011 static struct stable_node *stable_tree_insert(struct page *kpage)
1012 {
1013         struct rb_node **new = &root_stable_tree.rb_node;
1014         struct rb_node *parent = NULL;
1015         struct stable_node *stable_node;
1016
1017         while (*new) {
1018                 struct page *tree_page;
1019                 int ret;
1020
1021                 cond_resched();
1022                 stable_node = rb_entry(*new, struct stable_node, node);
1023                 tree_page = get_ksm_page(stable_node);
1024                 if (!tree_page)
1025                         return NULL;
1026
1027                 ret = memcmp_pages(kpage, tree_page);
1028                 put_page(tree_page);
1029
1030                 parent = *new;
1031                 if (ret < 0)
1032                         new = &parent->rb_left;
1033                 else if (ret > 0)
1034                         new = &parent->rb_right;
1035                 else {
1036                         /*
1037                          * It is not a bug that stable_tree_search() didn't
1038                          * find this node: because at that time our page was
1039                          * not yet write-protected, so may have changed since.
1040                          */
1041                         return NULL;
1042                 }
1043         }
1044
1045         stable_node = alloc_stable_node();
1046         if (!stable_node)
1047                 return NULL;
1048
1049         rb_link_node(&stable_node->node, parent, new);
1050         rb_insert_color(&stable_node->node, &root_stable_tree);
1051
1052         INIT_HLIST_HEAD(&stable_node->hlist);
1053
1054         stable_node->kpfn = page_to_pfn(kpage);
1055         set_page_stable_node(kpage, stable_node);
1056
1057         return stable_node;
1058 }
1059
1060 /*
1061  * unstable_tree_search_insert - search for identical page,
1062  * else insert rmap_item into the unstable tree.
1063  *
1064  * This function searches for a page in the unstable tree identical to the
1065  * page currently being scanned; and if no identical page is found in the
1066  * tree, we insert rmap_item as a new object into the unstable tree.
1067  *
1068  * This function returns pointer to rmap_item found to be identical
1069  * to the currently scanned page, NULL otherwise.
1070  *
1071  * This function does both searching and inserting, because they share
1072  * the same walking algorithm in an rbtree.
1073  */
1074 static
1075 struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
1076                                               struct page *page,
1077                                               struct page **tree_pagep)
1078
1079 {
1080         struct rb_node **new = &root_unstable_tree.rb_node;
1081         struct rb_node *parent = NULL;
1082
1083         while (*new) {
1084                 struct rmap_item *tree_rmap_item;
1085                 struct page *tree_page;
1086                 int ret;
1087
1088                 cond_resched();
1089                 tree_rmap_item = rb_entry(*new, struct rmap_item, node);
1090                 tree_page = get_mergeable_page(tree_rmap_item);
1091                 if (IS_ERR_OR_NULL(tree_page))
1092                         return NULL;
1093
1094                 /*
1095                  * Don't substitute a ksm page for a forked page.
1096                  */
1097                 if (page == tree_page) {
1098                         put_page(tree_page);
1099                         return NULL;
1100                 }
1101
1102                 ret = memcmp_pages(page, tree_page);
1103
1104                 parent = *new;
1105                 if (ret < 0) {
1106                         put_page(tree_page);
1107                         new = &parent->rb_left;
1108                 } else if (ret > 0) {
1109                         put_page(tree_page);
1110                         new = &parent->rb_right;
1111                 } else {
1112                         *tree_pagep = tree_page;
1113                         return tree_rmap_item;
1114                 }
1115         }
1116
1117         rmap_item->address |= UNSTABLE_FLAG;
1118         rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
1119         rb_link_node(&rmap_item->node, parent, new);
1120         rb_insert_color(&rmap_item->node, &root_unstable_tree);
1121
1122         ksm_pages_unshared++;
1123         return NULL;
1124 }
1125
1126 /*
1127  * stable_tree_append - add another rmap_item to the linked list of
1128  * rmap_items hanging off a given node of the stable tree, all sharing
1129  * the same ksm page.
1130  */
1131 static void stable_tree_append(struct rmap_item *rmap_item,
1132                                struct stable_node *stable_node)
1133 {
1134         rmap_item->head = stable_node;
1135         rmap_item->address |= STABLE_FLAG;
1136         hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
1137
1138         if (rmap_item->hlist.next)
1139                 ksm_pages_sharing++;
1140         else
1141                 ksm_pages_shared++;
1142 }
1143
1144 /*
1145  * cmp_and_merge_page - first see if page can be merged into the stable tree;
1146  * if not, compare checksum to previous and if it's the same, see if page can
1147  * be inserted into the unstable tree, or merged with a page already there and
1148  * both transferred to the stable tree.
1149  *
1150  * @page: the page that we are searching identical page to.
1151  * @rmap_item: the reverse mapping into the virtual address of this page
1152  */
1153 static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
1154 {
1155         struct rmap_item *tree_rmap_item;
1156         struct page *tree_page = NULL;
1157         struct stable_node *stable_node;
1158         struct page *kpage;
1159         unsigned int checksum;
1160         int err;
1161
1162         remove_rmap_item_from_tree(rmap_item);
1163
1164         /* We first start with searching the page inside the stable tree */
1165         kpage = stable_tree_search(page);
1166         if (kpage) {
1167                 err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
1168                 if (!err) {
1169                         /*
1170                          * The page was successfully merged:
1171                          * add its rmap_item to the stable tree.
1172                          */
1173                         lock_page(kpage);
1174                         stable_tree_append(rmap_item, page_stable_node(kpage));
1175                         unlock_page(kpage);
1176                 }
1177                 put_page(kpage);
1178                 return;
1179         }
1180
1181         /*
1182          * If the hash value of the page has changed from the last time
1183          * we calculated it, this page is changing frequently: therefore we
1184          * don't want to insert it in the unstable tree, and we don't want
1185          * to waste our time searching for something identical to it there.
1186          */
1187         checksum = calc_checksum(page);
1188         if (rmap_item->oldchecksum != checksum) {
1189                 rmap_item->oldchecksum = checksum;
1190                 return;
1191         }
1192
1193         tree_rmap_item =
1194                 unstable_tree_search_insert(rmap_item, page, &tree_page);
1195         if (tree_rmap_item) {
1196                 kpage = try_to_merge_two_pages(rmap_item, page,
1197                                                 tree_rmap_item, tree_page);
1198                 put_page(tree_page);
1199                 /*
1200                  * As soon as we merge this page, we want to remove the
1201                  * rmap_item of the page we have merged with from the unstable
1202                  * tree, and insert it instead as new node in the stable tree.
1203                  */
1204                 if (kpage) {
1205                         remove_rmap_item_from_tree(tree_rmap_item);
1206
1207                         lock_page(kpage);
1208                         stable_node = stable_tree_insert(kpage);
1209                         if (stable_node) {
1210                                 stable_tree_append(tree_rmap_item, stable_node);
1211                                 stable_tree_append(rmap_item, stable_node);
1212                         }
1213                         unlock_page(kpage);
1214
1215                         /*
1216                          * If we fail to insert the page into the stable tree,
1217                          * we will have 2 virtual addresses that are pointing
1218                          * to a ksm page left outside the stable tree,
1219                          * in which case we need to break_cow on both.
1220                          */
1221                         if (!stable_node) {
1222                                 break_cow(tree_rmap_item);
1223                                 break_cow(rmap_item);
1224                         }
1225                 }
1226         }
1227 }
1228
1229 static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
1230                                             struct rmap_item **rmap_list,
1231                                             unsigned long addr)
1232 {
1233         struct rmap_item *rmap_item;
1234
1235         while (*rmap_list) {
1236                 rmap_item = *rmap_list;
1237                 if ((rmap_item->address & PAGE_MASK) == addr)
1238                         return rmap_item;
1239                 if (rmap_item->address > addr)
1240                         break;
1241                 *rmap_list = rmap_item->rmap_list;
1242                 remove_rmap_item_from_tree(rmap_item);
1243                 free_rmap_item(rmap_item);
1244         }
1245
1246         rmap_item = alloc_rmap_item();
1247         if (rmap_item) {
1248                 /* It has already been zeroed */
1249                 rmap_item->mm = mm_slot->mm;
1250                 rmap_item->address = addr;
1251                 rmap_item->rmap_list = *rmap_list;
1252                 *rmap_list = rmap_item;
1253         }
1254         return rmap_item;
1255 }
1256
1257 static struct rmap_item *scan_get_next_rmap_item(struct page **page)
1258 {
1259         struct mm_struct *mm;
1260         struct mm_slot *slot;
1261         struct vm_area_struct *vma;
1262         struct rmap_item *rmap_item;
1263
1264         if (list_empty(&ksm_mm_head.mm_list))
1265                 return NULL;
1266
1267         slot = ksm_scan.mm_slot;
1268         if (slot == &ksm_mm_head) {
1269                 root_unstable_tree = RB_ROOT;
1270
1271                 spin_lock(&ksm_mmlist_lock);
1272                 slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
1273                 ksm_scan.mm_slot = slot;
1274                 spin_unlock(&ksm_mmlist_lock);
1275                 /*
1276                  * Although we tested list_empty() above, a racing __ksm_exit
1277                  * of the last mm on the list may have removed it since then.
1278                  */
1279                 if (slot == &ksm_mm_head)
1280                         return NULL;
1281 next_mm:
1282                 ksm_scan.address = 0;
1283                 ksm_scan.rmap_list = &slot->rmap_list;
1284         }
1285
1286         mm = slot->mm;
1287         down_read(&mm->mmap_sem);
1288         if (ksm_test_exit(mm))
1289                 vma = NULL;
1290         else
1291                 vma = find_vma(mm, ksm_scan.address);
1292
1293         for (; vma; vma = vma->vm_next) {
1294                 if (!(vma->vm_flags & VM_MERGEABLE))
1295                         continue;
1296                 if (ksm_scan.address < vma->vm_start)
1297                         ksm_scan.address = vma->vm_start;
1298                 if (!vma->anon_vma)
1299                         ksm_scan.address = vma->vm_end;
1300
1301                 while (ksm_scan.address < vma->vm_end) {
1302                         if (ksm_test_exit(mm))
1303                                 break;
1304                         *page = follow_page(vma, ksm_scan.address, FOLL_GET);
1305                         if (!IS_ERR_OR_NULL(*page) && PageAnon(*page)) {
1306                                 flush_anon_page(vma, *page, ksm_scan.address);
1307                                 flush_dcache_page(*page);
1308                                 rmap_item = get_next_rmap_item(slot,
1309                                         ksm_scan.rmap_list, ksm_scan.address);
1310                                 if (rmap_item) {
1311                                         ksm_scan.rmap_list =
1312                                                         &rmap_item->rmap_list;
1313                                         ksm_scan.address += PAGE_SIZE;
1314                                 } else
1315                                         put_page(*page);
1316                                 up_read(&mm->mmap_sem);
1317                                 return rmap_item;
1318                         }
1319                         if (!IS_ERR_OR_NULL(*page))
1320                                 put_page(*page);
1321                         ksm_scan.address += PAGE_SIZE;
1322                         cond_resched();
1323                 }
1324         }
1325
1326         if (ksm_test_exit(mm)) {
1327                 ksm_scan.address = 0;
1328                 ksm_scan.rmap_list = &slot->rmap_list;
1329         }
1330         /*
1331          * Nuke all the rmap_items that are above this current rmap:
1332          * because there were no VM_MERGEABLE vmas with such addresses.
1333          */
1334         remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
1335
1336         spin_lock(&ksm_mmlist_lock);
1337         ksm_scan.mm_slot = list_entry(slot->mm_list.next,
1338                                                 struct mm_slot, mm_list);
1339         if (ksm_scan.address == 0) {
1340                 /*
1341                  * We've completed a full scan of all vmas, holding mmap_sem
1342                  * throughout, and found no VM_MERGEABLE: so do the same as
1343                  * __ksm_exit does to remove this mm from all our lists now.
1344                  * This applies either when cleaning up after __ksm_exit
1345                  * (but beware: we can reach here even before __ksm_exit),
1346                  * or when all VM_MERGEABLE areas have been unmapped (and
1347                  * mmap_sem then protects against race with MADV_MERGEABLE).
1348                  */
1349                 hlist_del(&slot->link);
1350                 list_del(&slot->mm_list);
1351                 spin_unlock(&ksm_mmlist_lock);
1352
1353                 free_mm_slot(slot);
1354                 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1355                 up_read(&mm->mmap_sem);
1356                 mmdrop(mm);
1357         } else {
1358                 spin_unlock(&ksm_mmlist_lock);
1359                 up_read(&mm->mmap_sem);
1360         }
1361
1362         /* Repeat until we've completed scanning the whole list */
1363         slot = ksm_scan.mm_slot;
1364         if (slot != &ksm_mm_head)
1365                 goto next_mm;
1366
1367         ksm_scan.seqnr++;
1368         return NULL;
1369 }
1370
1371 /**
1372  * ksm_do_scan  - the ksm scanner main worker function.
1373  * @scan_npages - number of pages we want to scan before we return.
1374  */
1375 static void ksm_do_scan(unsigned int scan_npages)
1376 {
1377         struct rmap_item *rmap_item;
1378         struct page *uninitialized_var(page);
1379
1380         while (scan_npages--) {
1381                 cond_resched();
1382                 rmap_item = scan_get_next_rmap_item(&page);
1383                 if (!rmap_item)
1384                         return;
1385                 if (!PageKsm(page) || !in_stable_tree(rmap_item))
1386                         cmp_and_merge_page(page, rmap_item);
1387                 put_page(page);
1388         }
1389 }
1390
1391 static int ksmd_should_run(void)
1392 {
1393         return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
1394 }
1395
1396 static int ksm_scan_thread(void *nothing)
1397 {
1398         set_user_nice(current, 5);
1399
1400         while (!kthread_should_stop()) {
1401                 mutex_lock(&ksm_thread_mutex);
1402                 if (ksmd_should_run())
1403                         ksm_do_scan(ksm_thread_pages_to_scan);
1404                 mutex_unlock(&ksm_thread_mutex);
1405
1406                 if (ksmd_should_run()) {
1407                         schedule_timeout_interruptible(
1408                                 msecs_to_jiffies(ksm_thread_sleep_millisecs));
1409                 } else {
1410                         wait_event_interruptible(ksm_thread_wait,
1411                                 ksmd_should_run() || kthread_should_stop());
1412                 }
1413         }
1414         return 0;
1415 }
1416
1417 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
1418                 unsigned long end, int advice, unsigned long *vm_flags)
1419 {
1420         struct mm_struct *mm = vma->vm_mm;
1421         int err;
1422
1423         switch (advice) {
1424         case MADV_MERGEABLE:
1425                 /*
1426                  * Be somewhat over-protective for now!
1427                  */
1428                 if (*vm_flags & (VM_MERGEABLE | VM_SHARED  | VM_MAYSHARE   |
1429                                  VM_PFNMAP    | VM_IO      | VM_DONTEXPAND |
1430                                  VM_RESERVED  | VM_HUGETLB | VM_INSERTPAGE |
1431                                  VM_NONLINEAR | VM_MIXEDMAP | VM_SAO))
1432                         return 0;               /* just ignore the advice */
1433
1434                 if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
1435                         err = __ksm_enter(mm);
1436                         if (err)
1437                                 return err;
1438                 }
1439
1440                 *vm_flags |= VM_MERGEABLE;
1441                 break;
1442
1443         case MADV_UNMERGEABLE:
1444                 if (!(*vm_flags & VM_MERGEABLE))
1445                         return 0;               /* just ignore the advice */
1446
1447                 if (vma->anon_vma) {
1448                         err = unmerge_ksm_pages(vma, start, end);
1449                         if (err)
1450                                 return err;
1451                 }
1452
1453                 *vm_flags &= ~VM_MERGEABLE;
1454                 break;
1455         }
1456
1457         return 0;
1458 }
1459
1460 int __ksm_enter(struct mm_struct *mm)
1461 {
1462         struct mm_slot *mm_slot;
1463         int needs_wakeup;
1464
1465         mm_slot = alloc_mm_slot();
1466         if (!mm_slot)
1467                 return -ENOMEM;
1468
1469         /* Check ksm_run too?  Would need tighter locking */
1470         needs_wakeup = list_empty(&ksm_mm_head.mm_list);
1471
1472         spin_lock(&ksm_mmlist_lock);
1473         insert_to_mm_slots_hash(mm, mm_slot);
1474         /*
1475          * Insert just behind the scanning cursor, to let the area settle
1476          * down a little; when fork is followed by immediate exec, we don't
1477          * want ksmd to waste time setting up and tearing down an rmap_list.
1478          */
1479         list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
1480         spin_unlock(&ksm_mmlist_lock);
1481
1482         set_bit(MMF_VM_MERGEABLE, &mm->flags);
1483         atomic_inc(&mm->mm_count);
1484
1485         if (needs_wakeup)
1486                 wake_up_interruptible(&ksm_thread_wait);
1487
1488         return 0;
1489 }
1490
1491 void __ksm_exit(struct mm_struct *mm)
1492 {
1493         struct mm_slot *mm_slot;
1494         int easy_to_free = 0;
1495
1496         /*
1497          * This process is exiting: if it's straightforward (as is the
1498          * case when ksmd was never running), free mm_slot immediately.
1499          * But if it's at the cursor or has rmap_items linked to it, use
1500          * mmap_sem to synchronize with any break_cows before pagetables
1501          * are freed, and leave the mm_slot on the list for ksmd to free.
1502          * Beware: ksm may already have noticed it exiting and freed the slot.
1503          */
1504
1505         spin_lock(&ksm_mmlist_lock);
1506         mm_slot = get_mm_slot(mm);
1507         if (mm_slot && ksm_scan.mm_slot != mm_slot) {
1508                 if (!mm_slot->rmap_list) {
1509                         hlist_del(&mm_slot->link);
1510                         list_del(&mm_slot->mm_list);
1511                         easy_to_free = 1;
1512                 } else {
1513                         list_move(&mm_slot->mm_list,
1514                                   &ksm_scan.mm_slot->mm_list);
1515                 }
1516         }
1517         spin_unlock(&ksm_mmlist_lock);
1518
1519         if (easy_to_free) {
1520                 free_mm_slot(mm_slot);
1521                 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1522                 mmdrop(mm);
1523         } else if (mm_slot) {
1524                 down_write(&mm->mmap_sem);
1525                 up_write(&mm->mmap_sem);
1526         }
1527 }
1528
1529 struct page *ksm_does_need_to_copy(struct page *page,
1530                         struct vm_area_struct *vma, unsigned long address)
1531 {
1532         struct page *new_page;
1533
1534         new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
1535         if (new_page) {
1536                 copy_user_highpage(new_page, page, address, vma);
1537
1538                 SetPageDirty(new_page);
1539                 __SetPageUptodate(new_page);
1540                 SetPageSwapBacked(new_page);
1541                 __set_page_locked(new_page);
1542
1543                 if (page_evictable(new_page, vma))
1544                         lru_cache_add_lru(new_page, LRU_ACTIVE_ANON);
1545                 else
1546                         add_page_to_unevictable_list(new_page);
1547         }
1548
1549         return new_page;
1550 }
1551
1552 int page_referenced_ksm(struct page *page, struct mem_cgroup *memcg,
1553                         unsigned long *vm_flags)
1554 {
1555         struct stable_node *stable_node;
1556         struct rmap_item *rmap_item;
1557         struct hlist_node *hlist;
1558         unsigned int mapcount = page_mapcount(page);
1559         int referenced = 0;
1560         int search_new_forks = 0;
1561
1562         VM_BUG_ON(!PageKsm(page));
1563         VM_BUG_ON(!PageLocked(page));
1564
1565         stable_node = page_stable_node(page);
1566         if (!stable_node)
1567                 return 0;
1568 again:
1569         hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
1570                 struct anon_vma *anon_vma = rmap_item->anon_vma;
1571                 struct anon_vma_chain *vmac;
1572                 struct vm_area_struct *vma;
1573
1574                 spin_lock(&anon_vma->lock);
1575                 list_for_each_entry(vmac, &anon_vma->head, same_anon_vma) {
1576                         vma = vmac->vma;
1577                         if (rmap_item->address < vma->vm_start ||
1578                             rmap_item->address >= vma->vm_end)
1579                                 continue;
1580                         /*
1581                          * Initially we examine only the vma which covers this
1582                          * rmap_item; but later, if there is still work to do,
1583                          * we examine covering vmas in other mms: in case they
1584                          * were forked from the original since ksmd passed.
1585                          */
1586                         if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
1587                                 continue;
1588
1589                         if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
1590                                 continue;
1591
1592                         referenced += page_referenced_one(page, vma,
1593                                 rmap_item->address, &mapcount, vm_flags);
1594                         if (!search_new_forks || !mapcount)
1595                                 break;
1596                 }
1597                 spin_unlock(&anon_vma->lock);
1598                 if (!mapcount)
1599                         goto out;
1600         }
1601         if (!search_new_forks++)
1602                 goto again;
1603 out:
1604         return referenced;
1605 }
1606
1607 int try_to_unmap_ksm(struct page *page, enum ttu_flags flags)
1608 {
1609         struct stable_node *stable_node;
1610         struct hlist_node *hlist;
1611         struct rmap_item *rmap_item;
1612         int ret = SWAP_AGAIN;
1613         int search_new_forks = 0;
1614
1615         VM_BUG_ON(!PageKsm(page));
1616         VM_BUG_ON(!PageLocked(page));
1617
1618         stable_node = page_stable_node(page);
1619         if (!stable_node)
1620                 return SWAP_FAIL;
1621 again:
1622         hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
1623                 struct anon_vma *anon_vma = rmap_item->anon_vma;
1624                 struct anon_vma_chain *vmac;
1625                 struct vm_area_struct *vma;
1626
1627                 spin_lock(&anon_vma->lock);
1628                 list_for_each_entry(vmac, &anon_vma->head, same_anon_vma) {
1629                         vma = vmac->vma;
1630                         if (rmap_item->address < vma->vm_start ||
1631                             rmap_item->address >= vma->vm_end)
1632                                 continue;
1633                         /*
1634                          * Initially we examine only the vma which covers this
1635                          * rmap_item; but later, if there is still work to do,
1636                          * we examine covering vmas in other mms: in case they
1637                          * were forked from the original since ksmd passed.
1638                          */
1639                         if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
1640                                 continue;
1641
1642                         ret = try_to_unmap_one(page, vma,
1643                                         rmap_item->address, flags);
1644                         if (ret != SWAP_AGAIN || !page_mapped(page)) {
1645                                 spin_unlock(&anon_vma->lock);
1646                                 goto out;
1647                         }
1648                 }
1649                 spin_unlock(&anon_vma->lock);
1650         }
1651         if (!search_new_forks++)
1652                 goto again;
1653 out:
1654         return ret;
1655 }
1656
1657 #ifdef CONFIG_MIGRATION
1658 int rmap_walk_ksm(struct page *page, int (*rmap_one)(struct page *,
1659                   struct vm_area_struct *, unsigned long, void *), void *arg)
1660 {
1661         struct stable_node *stable_node;
1662         struct hlist_node *hlist;
1663         struct rmap_item *rmap_item;
1664         int ret = SWAP_AGAIN;
1665         int search_new_forks = 0;
1666
1667         VM_BUG_ON(!PageKsm(page));
1668         VM_BUG_ON(!PageLocked(page));
1669
1670         stable_node = page_stable_node(page);
1671         if (!stable_node)
1672                 return ret;
1673 again:
1674         hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
1675                 struct anon_vma *anon_vma = rmap_item->anon_vma;
1676                 struct anon_vma_chain *vmac;
1677                 struct vm_area_struct *vma;
1678
1679                 spin_lock(&anon_vma->lock);
1680                 list_for_each_entry(vmac, &anon_vma->head, same_anon_vma) {
1681                         vma = vmac->vma;
1682                         if (rmap_item->address < vma->vm_start ||
1683                             rmap_item->address >= vma->vm_end)
1684                                 continue;
1685                         /*
1686                          * Initially we examine only the vma which covers this
1687                          * rmap_item; but later, if there is still work to do,
1688                          * we examine covering vmas in other mms: in case they
1689                          * were forked from the original since ksmd passed.
1690                          */
1691                         if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
1692                                 continue;
1693
1694                         ret = rmap_one(page, vma, rmap_item->address, arg);
1695                         if (ret != SWAP_AGAIN) {
1696                                 spin_unlock(&anon_vma->lock);
1697                                 goto out;
1698                         }
1699                 }
1700                 spin_unlock(&anon_vma->lock);
1701         }
1702         if (!search_new_forks++)
1703                 goto again;
1704 out:
1705         return ret;
1706 }
1707
1708 void ksm_migrate_page(struct page *newpage, struct page *oldpage)
1709 {
1710         struct stable_node *stable_node;
1711
1712         VM_BUG_ON(!PageLocked(oldpage));
1713         VM_BUG_ON(!PageLocked(newpage));
1714         VM_BUG_ON(newpage->mapping != oldpage->mapping);
1715
1716         stable_node = page_stable_node(newpage);
1717         if (stable_node) {
1718                 VM_BUG_ON(stable_node->kpfn != page_to_pfn(oldpage));
1719                 stable_node->kpfn = page_to_pfn(newpage);
1720         }
1721 }
1722 #endif /* CONFIG_MIGRATION */
1723
1724 #ifdef CONFIG_MEMORY_HOTREMOVE
1725 static struct stable_node *ksm_check_stable_tree(unsigned long start_pfn,
1726                                                  unsigned long end_pfn)
1727 {
1728         struct rb_node *node;
1729
1730         for (node = rb_first(&root_stable_tree); node; node = rb_next(node)) {
1731                 struct stable_node *stable_node;
1732
1733                 stable_node = rb_entry(node, struct stable_node, node);
1734                 if (stable_node->kpfn >= start_pfn &&
1735                     stable_node->kpfn < end_pfn)
1736                         return stable_node;
1737         }
1738         return NULL;
1739 }
1740
1741 static int ksm_memory_callback(struct notifier_block *self,
1742                                unsigned long action, void *arg)
1743 {
1744         struct memory_notify *mn = arg;
1745         struct stable_node *stable_node;
1746
1747         switch (action) {
1748         case MEM_GOING_OFFLINE:
1749                 /*
1750                  * Keep it very simple for now: just lock out ksmd and
1751                  * MADV_UNMERGEABLE while any memory is going offline.
1752                  */
1753                 mutex_lock(&ksm_thread_mutex);
1754                 break;
1755
1756         case MEM_OFFLINE:
1757                 /*
1758                  * Most of the work is done by page migration; but there might
1759                  * be a few stable_nodes left over, still pointing to struct
1760                  * pages which have been offlined: prune those from the tree.
1761                  */
1762                 while ((stable_node = ksm_check_stable_tree(mn->start_pfn,
1763                                         mn->start_pfn + mn->nr_pages)) != NULL)
1764                         remove_node_from_stable_tree(stable_node);
1765                 /* fallthrough */
1766
1767         case MEM_CANCEL_OFFLINE:
1768                 mutex_unlock(&ksm_thread_mutex);
1769                 break;
1770         }
1771         return NOTIFY_OK;
1772 }
1773 #endif /* CONFIG_MEMORY_HOTREMOVE */
1774
1775 #ifdef CONFIG_SYSFS
1776 /*
1777  * This all compiles without CONFIG_SYSFS, but is a waste of space.
1778  */
1779
1780 #define KSM_ATTR_RO(_name) \
1781         static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
1782 #define KSM_ATTR(_name) \
1783         static struct kobj_attribute _name##_attr = \
1784                 __ATTR(_name, 0644, _name##_show, _name##_store)
1785
1786 static ssize_t sleep_millisecs_show(struct kobject *kobj,
1787                                     struct kobj_attribute *attr, char *buf)
1788 {
1789         return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
1790 }
1791
1792 static ssize_t sleep_millisecs_store(struct kobject *kobj,
1793                                      struct kobj_attribute *attr,
1794                                      const char *buf, size_t count)
1795 {
1796         unsigned long msecs;
1797         int err;
1798
1799         err = strict_strtoul(buf, 10, &msecs);
1800         if (err || msecs > UINT_MAX)
1801                 return -EINVAL;
1802
1803         ksm_thread_sleep_millisecs = msecs;
1804
1805         return count;
1806 }
1807 KSM_ATTR(sleep_millisecs);
1808
1809 static ssize_t pages_to_scan_show(struct kobject *kobj,
1810                                   struct kobj_attribute *attr, char *buf)
1811 {
1812         return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
1813 }
1814
1815 static ssize_t pages_to_scan_store(struct kobject *kobj,
1816                                    struct kobj_attribute *attr,
1817                                    const char *buf, size_t count)
1818 {
1819         int err;
1820         unsigned long nr_pages;
1821
1822         err = strict_strtoul(buf, 10, &nr_pages);
1823         if (err || nr_pages > UINT_MAX)
1824                 return -EINVAL;
1825
1826         ksm_thread_pages_to_scan = nr_pages;
1827
1828         return count;
1829 }
1830 KSM_ATTR(pages_to_scan);
1831
1832 static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
1833                         char *buf)
1834 {
1835         return sprintf(buf, "%u\n", ksm_run);
1836 }
1837
1838 static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
1839                          const char *buf, size_t count)
1840 {
1841         int err;
1842         unsigned long flags;
1843
1844         err = strict_strtoul(buf, 10, &flags);
1845         if (err || flags > UINT_MAX)
1846                 return -EINVAL;
1847         if (flags > KSM_RUN_UNMERGE)
1848                 return -EINVAL;
1849
1850         /*
1851          * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
1852          * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
1853          * breaking COW to free the pages_shared (but leaves mm_slots
1854          * on the list for when ksmd may be set running again).
1855          */
1856
1857         mutex_lock(&ksm_thread_mutex);
1858         if (ksm_run != flags) {
1859                 ksm_run = flags;
1860                 if (flags & KSM_RUN_UNMERGE) {
1861                         current->flags |= PF_OOM_ORIGIN;
1862                         err = unmerge_and_remove_all_rmap_items();
1863                         current->flags &= ~PF_OOM_ORIGIN;
1864                         if (err) {
1865                                 ksm_run = KSM_RUN_STOP;
1866                                 count = err;
1867                         }
1868                 }
1869         }
1870         mutex_unlock(&ksm_thread_mutex);
1871
1872         if (flags & KSM_RUN_MERGE)
1873                 wake_up_interruptible(&ksm_thread_wait);
1874
1875         return count;
1876 }
1877 KSM_ATTR(run);
1878
1879 static ssize_t pages_shared_show(struct kobject *kobj,
1880                                  struct kobj_attribute *attr, char *buf)
1881 {
1882         return sprintf(buf, "%lu\n", ksm_pages_shared);
1883 }
1884 KSM_ATTR_RO(pages_shared);
1885
1886 static ssize_t pages_sharing_show(struct kobject *kobj,
1887                                   struct kobj_attribute *attr, char *buf)
1888 {
1889         return sprintf(buf, "%lu\n", ksm_pages_sharing);
1890 }
1891 KSM_ATTR_RO(pages_sharing);
1892
1893 static ssize_t pages_unshared_show(struct kobject *kobj,
1894                                    struct kobj_attribute *attr, char *buf)
1895 {
1896         return sprintf(buf, "%lu\n", ksm_pages_unshared);
1897 }
1898 KSM_ATTR_RO(pages_unshared);
1899
1900 static ssize_t pages_volatile_show(struct kobject *kobj,
1901                                    struct kobj_attribute *attr, char *buf)
1902 {
1903         long ksm_pages_volatile;
1904
1905         ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
1906                                 - ksm_pages_sharing - ksm_pages_unshared;
1907         /*
1908          * It was not worth any locking to calculate that statistic,
1909          * but it might therefore sometimes be negative: conceal that.
1910          */
1911         if (ksm_pages_volatile < 0)
1912                 ksm_pages_volatile = 0;
1913         return sprintf(buf, "%ld\n", ksm_pages_volatile);
1914 }
1915 KSM_ATTR_RO(pages_volatile);
1916
1917 static ssize_t full_scans_show(struct kobject *kobj,
1918                                struct kobj_attribute *attr, char *buf)
1919 {
1920         return sprintf(buf, "%lu\n", ksm_scan.seqnr);
1921 }
1922 KSM_ATTR_RO(full_scans);
1923
1924 static struct attribute *ksm_attrs[] = {
1925         &sleep_millisecs_attr.attr,
1926         &pages_to_scan_attr.attr,
1927         &run_attr.attr,
1928         &pages_shared_attr.attr,
1929         &pages_sharing_attr.attr,
1930         &pages_unshared_attr.attr,
1931         &pages_volatile_attr.attr,
1932         &full_scans_attr.attr,
1933         NULL,
1934 };
1935
1936 static struct attribute_group ksm_attr_group = {
1937         .attrs = ksm_attrs,
1938         .name = "ksm",
1939 };
1940 #endif /* CONFIG_SYSFS */
1941
1942 static int __init ksm_init(void)
1943 {
1944         struct task_struct *ksm_thread;
1945         int err;
1946
1947         err = ksm_slab_init();
1948         if (err)
1949                 goto out;
1950
1951         err = mm_slots_hash_init();
1952         if (err)
1953                 goto out_free1;
1954
1955         ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
1956         if (IS_ERR(ksm_thread)) {
1957                 printk(KERN_ERR "ksm: creating kthread failed\n");
1958                 err = PTR_ERR(ksm_thread);
1959                 goto out_free2;
1960         }
1961
1962 #ifdef CONFIG_SYSFS
1963         err = sysfs_create_group(mm_kobj, &ksm_attr_group);
1964         if (err) {
1965                 printk(KERN_ERR "ksm: register sysfs failed\n");
1966                 kthread_stop(ksm_thread);
1967                 goto out_free2;
1968         }
1969 #else
1970         ksm_run = KSM_RUN_MERGE;        /* no way for user to start it */
1971
1972 #endif /* CONFIG_SYSFS */
1973
1974 #ifdef CONFIG_MEMORY_HOTREMOVE
1975         /*
1976          * Choose a high priority since the callback takes ksm_thread_mutex:
1977          * later callbacks could only be taking locks which nest within that.
1978          */
1979         hotplug_memory_notifier(ksm_memory_callback, 100);
1980 #endif
1981         return 0;
1982
1983 out_free2:
1984         mm_slots_hash_free();
1985 out_free1:
1986         ksm_slab_free();
1987 out:
1988         return err;
1989 }
1990 module_init(ksm_init)