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