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