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