Staging: comedi: fix build on arches that don't want comedi drivers
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / ksm.c
blobbef1af4f77e36186503c9fe2f91530954a456f3f
1 /*
2 * Memory merging support.
4 * This code enables dynamic sharing of identical pages found in different
5 * memory areas, even if they are not shared by fork()
7 * Copyright (C) 2008-2009 Red Hat, Inc.
8 * Authors:
9 * Izik Eidus
10 * Andrea Arcangeli
11 * Chris Wright
12 * Hugh Dickins
14 * This work is licensed under the terms of the GNU GPL, version 2.
17 #include <linux/errno.h>
18 #include <linux/mm.h>
19 #include <linux/fs.h>
20 #include <linux/mman.h>
21 #include <linux/sched.h>
22 #include <linux/rwsem.h>
23 #include <linux/pagemap.h>
24 #include <linux/rmap.h>
25 #include <linux/spinlock.h>
26 #include <linux/jhash.h>
27 #include <linux/delay.h>
28 #include <linux/kthread.h>
29 #include <linux/wait.h>
30 #include <linux/slab.h>
31 #include <linux/rbtree.h>
32 #include <linux/mmu_notifier.h>
33 #include <linux/swap.h>
34 #include <linux/ksm.h>
36 #include <asm/tlbflush.h>
39 * A few notes about the KSM scanning process,
40 * to make it easier to understand the data structures below:
42 * In order to reduce excessive scanning, KSM sorts the memory pages by their
43 * contents into a data structure that holds pointers to the pages' locations.
45 * Since the contents of the pages may change at any moment, KSM cannot just
46 * insert the pages into a normal sorted tree and expect it to find anything.
47 * Therefore KSM uses two data structures - the stable and the unstable tree.
49 * The stable tree holds pointers to all the merged pages (ksm pages), sorted
50 * by their contents. Because each such page is write-protected, searching on
51 * this tree is fully assured to be working (except when pages are unmapped),
52 * and therefore this tree is called the stable tree.
54 * In addition to the stable tree, KSM uses a second data structure called the
55 * unstable tree: this tree holds pointers to pages which have been found to
56 * be "unchanged for a period of time". The unstable tree sorts these pages
57 * by their contents, but since they are not write-protected, KSM cannot rely
58 * upon the unstable tree to work correctly - the unstable tree is liable to
59 * be corrupted as its contents are modified, and so it is called unstable.
61 * KSM solves this problem by several techniques:
63 * 1) The unstable tree is flushed every time KSM completes scanning all
64 * memory areas, and then the tree is rebuilt again from the beginning.
65 * 2) KSM will only insert into the unstable tree, pages whose hash value
66 * has not changed since the previous scan of all memory areas.
67 * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
68 * colors of the nodes and not on their contents, assuring that even when
69 * the tree gets "corrupted" it won't get out of balance, so scanning time
70 * remains the same (also, searching and inserting nodes in an rbtree uses
71 * the same algorithm, so we have no overhead when we flush and rebuild).
72 * 4) KSM never flushes the stable tree, which means that even if it were to
73 * take 10 attempts to find a page in the unstable tree, once it is found,
74 * it is secured in the stable tree. (When we scan a new page, we first
75 * compare it against the stable tree, and then against the unstable tree.)
78 /**
79 * struct mm_slot - ksm information per mm that is being scanned
80 * @link: link to the mm_slots hash list
81 * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
82 * @rmap_list: head for this mm_slot's list of rmap_items
83 * @mm: the mm that this information is valid for
85 struct mm_slot {
86 struct hlist_node link;
87 struct list_head mm_list;
88 struct list_head rmap_list;
89 struct mm_struct *mm;
92 /**
93 * struct ksm_scan - cursor for scanning
94 * @mm_slot: the current mm_slot we are scanning
95 * @address: the next address inside that to be scanned
96 * @rmap_item: the current rmap that we are scanning inside the rmap_list
97 * @seqnr: count of completed full scans (needed when removing unstable node)
99 * There is only the one ksm_scan instance of this cursor structure.
101 struct ksm_scan {
102 struct mm_slot *mm_slot;
103 unsigned long address;
104 struct rmap_item *rmap_item;
105 unsigned long seqnr;
109 * struct rmap_item - reverse mapping item for virtual addresses
110 * @link: link into mm_slot's rmap_list (rmap_list is per mm)
111 * @mm: the memory structure this rmap_item is pointing into
112 * @address: the virtual address this rmap_item tracks (+ flags in low bits)
113 * @oldchecksum: previous checksum of the page at that virtual address
114 * @node: rb_node of this rmap_item in either unstable or stable tree
115 * @next: next rmap_item hanging off the same node of the stable tree
116 * @prev: previous rmap_item hanging off the same node of the stable tree
118 struct rmap_item {
119 struct list_head link;
120 struct mm_struct *mm;
121 unsigned long address; /* + low bits used for flags below */
122 union {
123 unsigned int oldchecksum; /* when unstable */
124 struct rmap_item *next; /* when stable */
126 union {
127 struct rb_node node; /* when tree node */
128 struct rmap_item *prev; /* in stable list */
132 #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
133 #define NODE_FLAG 0x100 /* is a node of unstable or stable tree */
134 #define STABLE_FLAG 0x200 /* is a node or list item of stable tree */
136 /* The stable and unstable tree heads */
137 static struct rb_root root_stable_tree = RB_ROOT;
138 static struct rb_root root_unstable_tree = RB_ROOT;
140 #define MM_SLOTS_HASH_HEADS 1024
141 static struct hlist_head *mm_slots_hash;
143 static struct mm_slot ksm_mm_head = {
144 .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
146 static struct ksm_scan ksm_scan = {
147 .mm_slot = &ksm_mm_head,
150 static struct kmem_cache *rmap_item_cache;
151 static struct kmem_cache *mm_slot_cache;
153 /* The number of nodes in the stable tree */
154 static unsigned long ksm_pages_shared;
156 /* The number of page slots additionally sharing those nodes */
157 static unsigned long ksm_pages_sharing;
159 /* The number of nodes in the unstable tree */
160 static unsigned long ksm_pages_unshared;
162 /* The number of rmap_items in use: to calculate pages_volatile */
163 static unsigned long ksm_rmap_items;
165 /* Limit on the number of unswappable pages used */
166 static unsigned long ksm_max_kernel_pages;
168 /* Number of pages ksmd should scan in one batch */
169 static unsigned int ksm_thread_pages_to_scan = 100;
171 /* Milliseconds ksmd should sleep between batches */
172 static unsigned int ksm_thread_sleep_millisecs = 20;
174 #define KSM_RUN_STOP 0
175 #define KSM_RUN_MERGE 1
176 #define KSM_RUN_UNMERGE 2
177 static unsigned int ksm_run = KSM_RUN_STOP;
179 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
180 static DEFINE_MUTEX(ksm_thread_mutex);
181 static DEFINE_SPINLOCK(ksm_mmlist_lock);
183 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
184 sizeof(struct __struct), __alignof__(struct __struct),\
185 (__flags), NULL)
187 static int __init ksm_slab_init(void)
189 rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
190 if (!rmap_item_cache)
191 goto out;
193 mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
194 if (!mm_slot_cache)
195 goto out_free;
197 return 0;
199 out_free:
200 kmem_cache_destroy(rmap_item_cache);
201 out:
202 return -ENOMEM;
205 static void __init ksm_slab_free(void)
207 kmem_cache_destroy(mm_slot_cache);
208 kmem_cache_destroy(rmap_item_cache);
209 mm_slot_cache = NULL;
212 static inline struct rmap_item *alloc_rmap_item(void)
214 struct rmap_item *rmap_item;
216 rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL);
217 if (rmap_item)
218 ksm_rmap_items++;
219 return rmap_item;
222 static inline void free_rmap_item(struct rmap_item *rmap_item)
224 ksm_rmap_items--;
225 rmap_item->mm = NULL; /* debug safety */
226 kmem_cache_free(rmap_item_cache, rmap_item);
229 static inline struct mm_slot *alloc_mm_slot(void)
231 if (!mm_slot_cache) /* initialization failed */
232 return NULL;
233 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
236 static inline void free_mm_slot(struct mm_slot *mm_slot)
238 kmem_cache_free(mm_slot_cache, mm_slot);
241 static int __init mm_slots_hash_init(void)
243 mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
244 GFP_KERNEL);
245 if (!mm_slots_hash)
246 return -ENOMEM;
247 return 0;
250 static void __init mm_slots_hash_free(void)
252 kfree(mm_slots_hash);
255 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
257 struct mm_slot *mm_slot;
258 struct hlist_head *bucket;
259 struct hlist_node *node;
261 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
262 % MM_SLOTS_HASH_HEADS];
263 hlist_for_each_entry(mm_slot, node, bucket, link) {
264 if (mm == mm_slot->mm)
265 return mm_slot;
267 return NULL;
270 static void insert_to_mm_slots_hash(struct mm_struct *mm,
271 struct mm_slot *mm_slot)
273 struct hlist_head *bucket;
275 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
276 % MM_SLOTS_HASH_HEADS];
277 mm_slot->mm = mm;
278 INIT_LIST_HEAD(&mm_slot->rmap_list);
279 hlist_add_head(&mm_slot->link, bucket);
282 static inline int in_stable_tree(struct rmap_item *rmap_item)
284 return rmap_item->address & STABLE_FLAG;
288 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
289 * page tables after it has passed through ksm_exit() - which, if necessary,
290 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
291 * a special flag: they can just back out as soon as mm_users goes to zero.
292 * ksm_test_exit() is used throughout to make this test for exit: in some
293 * places for correctness, in some places just to avoid unnecessary work.
295 static inline bool ksm_test_exit(struct mm_struct *mm)
297 return atomic_read(&mm->mm_users) == 0;
301 * We use break_ksm to break COW on a ksm page: it's a stripped down
303 * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
304 * put_page(page);
306 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
307 * in case the application has unmapped and remapped mm,addr meanwhile.
308 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
309 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
311 static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
313 struct page *page;
314 int ret = 0;
316 do {
317 cond_resched();
318 page = follow_page(vma, addr, FOLL_GET);
319 if (!page)
320 break;
321 if (PageKsm(page))
322 ret = handle_mm_fault(vma->vm_mm, vma, addr,
323 FAULT_FLAG_WRITE);
324 else
325 ret = VM_FAULT_WRITE;
326 put_page(page);
327 } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_OOM)));
329 * We must loop because handle_mm_fault() may back out if there's
330 * any difficulty e.g. if pte accessed bit gets updated concurrently.
332 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
333 * COW has been broken, even if the vma does not permit VM_WRITE;
334 * but note that a concurrent fault might break PageKsm for us.
336 * VM_FAULT_SIGBUS could occur if we race with truncation of the
337 * backing file, which also invalidates anonymous pages: that's
338 * okay, that truncation will have unmapped the PageKsm for us.
340 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
341 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
342 * current task has TIF_MEMDIE set, and will be OOM killed on return
343 * to user; and ksmd, having no mm, would never be chosen for that.
345 * But if the mm is in a limited mem_cgroup, then the fault may fail
346 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
347 * even ksmd can fail in this way - though it's usually breaking ksm
348 * just to undo a merge it made a moment before, so unlikely to oom.
350 * That's a pity: we might therefore have more kernel pages allocated
351 * than we're counting as nodes in the stable tree; but ksm_do_scan
352 * will retry to break_cow on each pass, so should recover the page
353 * in due course. The important thing is to not let VM_MERGEABLE
354 * be cleared while any such pages might remain in the area.
356 return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
359 static void break_cow(struct mm_struct *mm, unsigned long addr)
361 struct vm_area_struct *vma;
363 down_read(&mm->mmap_sem);
364 if (ksm_test_exit(mm))
365 goto out;
366 vma = find_vma(mm, addr);
367 if (!vma || vma->vm_start > addr)
368 goto out;
369 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
370 goto out;
371 break_ksm(vma, addr);
372 out:
373 up_read(&mm->mmap_sem);
376 static struct page *get_mergeable_page(struct rmap_item *rmap_item)
378 struct mm_struct *mm = rmap_item->mm;
379 unsigned long addr = rmap_item->address;
380 struct vm_area_struct *vma;
381 struct page *page;
383 down_read(&mm->mmap_sem);
384 if (ksm_test_exit(mm))
385 goto out;
386 vma = find_vma(mm, addr);
387 if (!vma || vma->vm_start > addr)
388 goto out;
389 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
390 goto out;
392 page = follow_page(vma, addr, FOLL_GET);
393 if (!page)
394 goto out;
395 if (PageAnon(page)) {
396 flush_anon_page(vma, page, addr);
397 flush_dcache_page(page);
398 } else {
399 put_page(page);
400 out: page = NULL;
402 up_read(&mm->mmap_sem);
403 return page;
407 * get_ksm_page: checks if the page at the virtual address in rmap_item
408 * is still PageKsm, in which case we can trust the content of the page,
409 * and it returns the gotten page; but NULL if the page has been zapped.
411 static struct page *get_ksm_page(struct rmap_item *rmap_item)
413 struct page *page;
415 page = get_mergeable_page(rmap_item);
416 if (page && !PageKsm(page)) {
417 put_page(page);
418 page = NULL;
420 return page;
424 * Removing rmap_item from stable or unstable tree.
425 * This function will clean the information from the stable/unstable tree.
427 static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
429 if (in_stable_tree(rmap_item)) {
430 struct rmap_item *next_item = rmap_item->next;
432 if (rmap_item->address & NODE_FLAG) {
433 if (next_item) {
434 rb_replace_node(&rmap_item->node,
435 &next_item->node,
436 &root_stable_tree);
437 next_item->address |= NODE_FLAG;
438 ksm_pages_sharing--;
439 } else {
440 rb_erase(&rmap_item->node, &root_stable_tree);
441 ksm_pages_shared--;
443 } else {
444 struct rmap_item *prev_item = rmap_item->prev;
446 BUG_ON(prev_item->next != rmap_item);
447 prev_item->next = next_item;
448 if (next_item) {
449 BUG_ON(next_item->prev != rmap_item);
450 next_item->prev = rmap_item->prev;
452 ksm_pages_sharing--;
455 rmap_item->next = NULL;
457 } else if (rmap_item->address & NODE_FLAG) {
458 unsigned char age;
460 * Usually ksmd can and must skip the rb_erase, because
461 * root_unstable_tree was already reset to RB_ROOT.
462 * But be careful when an mm is exiting: do the rb_erase
463 * if this rmap_item was inserted by this scan, rather
464 * than left over from before.
466 age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
467 BUG_ON(age > 1);
468 if (!age)
469 rb_erase(&rmap_item->node, &root_unstable_tree);
470 ksm_pages_unshared--;
473 rmap_item->address &= PAGE_MASK;
475 cond_resched(); /* we're called from many long loops */
478 static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
479 struct list_head *cur)
481 struct rmap_item *rmap_item;
483 while (cur != &mm_slot->rmap_list) {
484 rmap_item = list_entry(cur, struct rmap_item, link);
485 cur = cur->next;
486 remove_rmap_item_from_tree(rmap_item);
487 list_del(&rmap_item->link);
488 free_rmap_item(rmap_item);
493 * Though it's very tempting to unmerge in_stable_tree(rmap_item)s rather
494 * than check every pte of a given vma, the locking doesn't quite work for
495 * that - an rmap_item is assigned to the stable tree after inserting ksm
496 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
497 * rmap_items from parent to child at fork time (so as not to waste time
498 * if exit comes before the next scan reaches it).
500 * Similarly, although we'd like to remove rmap_items (so updating counts
501 * and freeing memory) when unmerging an area, it's easier to leave that
502 * to the next pass of ksmd - consider, for example, how ksmd might be
503 * in cmp_and_merge_page on one of the rmap_items we would be removing.
505 static int unmerge_ksm_pages(struct vm_area_struct *vma,
506 unsigned long start, unsigned long end)
508 unsigned long addr;
509 int err = 0;
511 for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
512 if (ksm_test_exit(vma->vm_mm))
513 break;
514 if (signal_pending(current))
515 err = -ERESTARTSYS;
516 else
517 err = break_ksm(vma, addr);
519 return err;
522 #ifdef CONFIG_SYSFS
524 * Only called through the sysfs control interface:
526 static int unmerge_and_remove_all_rmap_items(void)
528 struct mm_slot *mm_slot;
529 struct mm_struct *mm;
530 struct vm_area_struct *vma;
531 int err = 0;
533 spin_lock(&ksm_mmlist_lock);
534 ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
535 struct mm_slot, mm_list);
536 spin_unlock(&ksm_mmlist_lock);
538 for (mm_slot = ksm_scan.mm_slot;
539 mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
540 mm = mm_slot->mm;
541 down_read(&mm->mmap_sem);
542 for (vma = mm->mmap; vma; vma = vma->vm_next) {
543 if (ksm_test_exit(mm))
544 break;
545 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
546 continue;
547 err = unmerge_ksm_pages(vma,
548 vma->vm_start, vma->vm_end);
549 if (err)
550 goto error;
553 remove_trailing_rmap_items(mm_slot, mm_slot->rmap_list.next);
555 spin_lock(&ksm_mmlist_lock);
556 ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
557 struct mm_slot, mm_list);
558 if (ksm_test_exit(mm)) {
559 hlist_del(&mm_slot->link);
560 list_del(&mm_slot->mm_list);
561 spin_unlock(&ksm_mmlist_lock);
563 free_mm_slot(mm_slot);
564 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
565 up_read(&mm->mmap_sem);
566 mmdrop(mm);
567 } else {
568 spin_unlock(&ksm_mmlist_lock);
569 up_read(&mm->mmap_sem);
573 ksm_scan.seqnr = 0;
574 return 0;
576 error:
577 up_read(&mm->mmap_sem);
578 spin_lock(&ksm_mmlist_lock);
579 ksm_scan.mm_slot = &ksm_mm_head;
580 spin_unlock(&ksm_mmlist_lock);
581 return err;
583 #endif /* CONFIG_SYSFS */
585 static u32 calc_checksum(struct page *page)
587 u32 checksum;
588 void *addr = kmap_atomic(page, KM_USER0);
589 checksum = jhash2(addr, PAGE_SIZE / 4, 17);
590 kunmap_atomic(addr, KM_USER0);
591 return checksum;
594 static int memcmp_pages(struct page *page1, struct page *page2)
596 char *addr1, *addr2;
597 int ret;
599 addr1 = kmap_atomic(page1, KM_USER0);
600 addr2 = kmap_atomic(page2, KM_USER1);
601 ret = memcmp(addr1, addr2, PAGE_SIZE);
602 kunmap_atomic(addr2, KM_USER1);
603 kunmap_atomic(addr1, KM_USER0);
604 return ret;
607 static inline int pages_identical(struct page *page1, struct page *page2)
609 return !memcmp_pages(page1, page2);
612 static int write_protect_page(struct vm_area_struct *vma, struct page *page,
613 pte_t *orig_pte)
615 struct mm_struct *mm = vma->vm_mm;
616 unsigned long addr;
617 pte_t *ptep;
618 spinlock_t *ptl;
619 int swapped;
620 int err = -EFAULT;
622 addr = page_address_in_vma(page, vma);
623 if (addr == -EFAULT)
624 goto out;
626 ptep = page_check_address(page, mm, addr, &ptl, 0);
627 if (!ptep)
628 goto out;
630 if (pte_write(*ptep)) {
631 pte_t entry;
633 swapped = PageSwapCache(page);
634 flush_cache_page(vma, addr, page_to_pfn(page));
636 * Ok this is tricky, when get_user_pages_fast() run it doesnt
637 * take any lock, therefore the check that we are going to make
638 * with the pagecount against the mapcount is racey and
639 * O_DIRECT can happen right after the check.
640 * So we clear the pte and flush the tlb before the check
641 * this assure us that no O_DIRECT can happen after the check
642 * or in the middle of the check.
644 entry = ptep_clear_flush(vma, addr, ptep);
646 * Check that no O_DIRECT or similar I/O is in progress on the
647 * page
649 if ((page_mapcount(page) + 2 + swapped) != page_count(page)) {
650 set_pte_at_notify(mm, addr, ptep, entry);
651 goto out_unlock;
653 entry = pte_wrprotect(entry);
654 set_pte_at_notify(mm, addr, ptep, entry);
656 *orig_pte = *ptep;
657 err = 0;
659 out_unlock:
660 pte_unmap_unlock(ptep, ptl);
661 out:
662 return err;
666 * replace_page - replace page in vma by new ksm page
667 * @vma: vma that holds the pte pointing to oldpage
668 * @oldpage: the page we are replacing by newpage
669 * @newpage: the ksm page we replace oldpage by
670 * @orig_pte: the original value of the pte
672 * Returns 0 on success, -EFAULT on failure.
674 static int replace_page(struct vm_area_struct *vma, struct page *oldpage,
675 struct page *newpage, pte_t orig_pte)
677 struct mm_struct *mm = vma->vm_mm;
678 pgd_t *pgd;
679 pud_t *pud;
680 pmd_t *pmd;
681 pte_t *ptep;
682 spinlock_t *ptl;
683 unsigned long addr;
684 pgprot_t prot;
685 int err = -EFAULT;
687 prot = vm_get_page_prot(vma->vm_flags & ~VM_WRITE);
689 addr = page_address_in_vma(oldpage, vma);
690 if (addr == -EFAULT)
691 goto out;
693 pgd = pgd_offset(mm, addr);
694 if (!pgd_present(*pgd))
695 goto out;
697 pud = pud_offset(pgd, addr);
698 if (!pud_present(*pud))
699 goto out;
701 pmd = pmd_offset(pud, addr);
702 if (!pmd_present(*pmd))
703 goto out;
705 ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
706 if (!pte_same(*ptep, orig_pte)) {
707 pte_unmap_unlock(ptep, ptl);
708 goto out;
711 get_page(newpage);
712 page_add_ksm_rmap(newpage);
714 flush_cache_page(vma, addr, pte_pfn(*ptep));
715 ptep_clear_flush(vma, addr, ptep);
716 set_pte_at_notify(mm, addr, ptep, mk_pte(newpage, prot));
718 page_remove_rmap(oldpage);
719 put_page(oldpage);
721 pte_unmap_unlock(ptep, ptl);
722 err = 0;
723 out:
724 return err;
728 * try_to_merge_one_page - take two pages and merge them into one
729 * @vma: the vma that hold the pte pointing into oldpage
730 * @oldpage: the page that we want to replace with newpage
731 * @newpage: the page that we want to map instead of oldpage
733 * Note:
734 * oldpage should be a PageAnon page, while newpage should be a PageKsm page,
735 * or a newly allocated kernel page which page_add_ksm_rmap will make PageKsm.
737 * This function returns 0 if the pages were merged, -EFAULT otherwise.
739 static int try_to_merge_one_page(struct vm_area_struct *vma,
740 struct page *oldpage,
741 struct page *newpage)
743 pte_t orig_pte = __pte(0);
744 int err = -EFAULT;
746 if (!(vma->vm_flags & VM_MERGEABLE))
747 goto out;
749 if (!PageAnon(oldpage))
750 goto out;
752 get_page(newpage);
753 get_page(oldpage);
756 * We need the page lock to read a stable PageSwapCache in
757 * write_protect_page(). We use trylock_page() instead of
758 * lock_page() because we don't want to wait here - we
759 * prefer to continue scanning and merging different pages,
760 * then come back to this page when it is unlocked.
762 if (!trylock_page(oldpage))
763 goto out_putpage;
765 * If this anonymous page is mapped only here, its pte may need
766 * to be write-protected. If it's mapped elsewhere, all of its
767 * ptes are necessarily already write-protected. But in either
768 * case, we need to lock and check page_count is not raised.
770 if (write_protect_page(vma, oldpage, &orig_pte)) {
771 unlock_page(oldpage);
772 goto out_putpage;
774 unlock_page(oldpage);
776 if (pages_identical(oldpage, newpage))
777 err = replace_page(vma, oldpage, newpage, orig_pte);
779 out_putpage:
780 put_page(oldpage);
781 put_page(newpage);
782 out:
783 return err;
787 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
788 * but no new kernel page is allocated: kpage must already be a ksm page.
790 static int try_to_merge_with_ksm_page(struct mm_struct *mm1,
791 unsigned long addr1,
792 struct page *page1,
793 struct page *kpage)
795 struct vm_area_struct *vma;
796 int err = -EFAULT;
798 down_read(&mm1->mmap_sem);
799 if (ksm_test_exit(mm1))
800 goto out;
802 vma = find_vma(mm1, addr1);
803 if (!vma || vma->vm_start > addr1)
804 goto out;
806 err = try_to_merge_one_page(vma, page1, kpage);
807 out:
808 up_read(&mm1->mmap_sem);
809 return err;
813 * try_to_merge_two_pages - take two identical pages and prepare them
814 * to be merged into one page.
816 * This function returns 0 if we successfully mapped two identical pages
817 * into one page, -EFAULT otherwise.
819 * Note that this function allocates a new kernel page: if one of the pages
820 * is already a ksm page, try_to_merge_with_ksm_page should be used.
822 static int try_to_merge_two_pages(struct mm_struct *mm1, unsigned long addr1,
823 struct page *page1, struct mm_struct *mm2,
824 unsigned long addr2, struct page *page2)
826 struct vm_area_struct *vma;
827 struct page *kpage;
828 int err = -EFAULT;
831 * The number of nodes in the stable tree
832 * is the number of kernel pages that we hold.
834 if (ksm_max_kernel_pages &&
835 ksm_max_kernel_pages <= ksm_pages_shared)
836 return err;
838 kpage = alloc_page(GFP_HIGHUSER);
839 if (!kpage)
840 return err;
842 down_read(&mm1->mmap_sem);
843 if (ksm_test_exit(mm1)) {
844 up_read(&mm1->mmap_sem);
845 goto out;
847 vma = find_vma(mm1, addr1);
848 if (!vma || vma->vm_start > addr1) {
849 up_read(&mm1->mmap_sem);
850 goto out;
853 copy_user_highpage(kpage, page1, addr1, vma);
854 err = try_to_merge_one_page(vma, page1, kpage);
855 up_read(&mm1->mmap_sem);
857 if (!err) {
858 err = try_to_merge_with_ksm_page(mm2, addr2, page2, kpage);
860 * If that fails, we have a ksm page with only one pte
861 * pointing to it: so break it.
863 if (err)
864 break_cow(mm1, addr1);
866 out:
867 put_page(kpage);
868 return err;
872 * stable_tree_search - search page inside the stable tree
873 * @page: the page that we are searching identical pages to.
874 * @page2: pointer into identical page that we are holding inside the stable
875 * tree that we have found.
876 * @rmap_item: the reverse mapping item
878 * This function checks if there is a page inside the stable tree
879 * with identical content to the page that we are scanning right now.
881 * This function return rmap_item pointer to the identical item if found,
882 * NULL otherwise.
884 static struct rmap_item *stable_tree_search(struct page *page,
885 struct page **page2,
886 struct rmap_item *rmap_item)
888 struct rb_node *node = root_stable_tree.rb_node;
890 while (node) {
891 struct rmap_item *tree_rmap_item, *next_rmap_item;
892 int ret;
894 tree_rmap_item = rb_entry(node, struct rmap_item, node);
895 while (tree_rmap_item) {
896 BUG_ON(!in_stable_tree(tree_rmap_item));
897 cond_resched();
898 page2[0] = get_ksm_page(tree_rmap_item);
899 if (page2[0])
900 break;
901 next_rmap_item = tree_rmap_item->next;
902 remove_rmap_item_from_tree(tree_rmap_item);
903 tree_rmap_item = next_rmap_item;
905 if (!tree_rmap_item)
906 return NULL;
908 ret = memcmp_pages(page, page2[0]);
910 if (ret < 0) {
911 put_page(page2[0]);
912 node = node->rb_left;
913 } else if (ret > 0) {
914 put_page(page2[0]);
915 node = node->rb_right;
916 } else {
917 return tree_rmap_item;
921 return NULL;
925 * stable_tree_insert - insert rmap_item pointing to new ksm page
926 * into the stable tree.
928 * @page: the page that we are searching identical page to inside the stable
929 * tree.
930 * @rmap_item: pointer to the reverse mapping item.
932 * This function returns rmap_item if success, NULL otherwise.
934 static struct rmap_item *stable_tree_insert(struct page *page,
935 struct rmap_item *rmap_item)
937 struct rb_node **new = &root_stable_tree.rb_node;
938 struct rb_node *parent = NULL;
940 while (*new) {
941 struct rmap_item *tree_rmap_item, *next_rmap_item;
942 struct page *tree_page;
943 int ret;
945 tree_rmap_item = rb_entry(*new, struct rmap_item, node);
946 while (tree_rmap_item) {
947 BUG_ON(!in_stable_tree(tree_rmap_item));
948 cond_resched();
949 tree_page = get_ksm_page(tree_rmap_item);
950 if (tree_page)
951 break;
952 next_rmap_item = tree_rmap_item->next;
953 remove_rmap_item_from_tree(tree_rmap_item);
954 tree_rmap_item = next_rmap_item;
956 if (!tree_rmap_item)
957 return NULL;
959 ret = memcmp_pages(page, tree_page);
960 put_page(tree_page);
962 parent = *new;
963 if (ret < 0)
964 new = &parent->rb_left;
965 else if (ret > 0)
966 new = &parent->rb_right;
967 else {
969 * It is not a bug that stable_tree_search() didn't
970 * find this node: because at that time our page was
971 * not yet write-protected, so may have changed since.
973 return NULL;
977 rmap_item->address |= NODE_FLAG | STABLE_FLAG;
978 rmap_item->next = NULL;
979 rb_link_node(&rmap_item->node, parent, new);
980 rb_insert_color(&rmap_item->node, &root_stable_tree);
982 ksm_pages_shared++;
983 return rmap_item;
987 * unstable_tree_search_insert - search and insert items into the unstable tree.
989 * @page: the page that we are going to search for identical page or to insert
990 * into the unstable tree
991 * @page2: pointer into identical page that was found inside the unstable tree
992 * @rmap_item: the reverse mapping item of page
994 * This function searches for a page in the unstable tree identical to the
995 * page currently being scanned; and if no identical page is found in the
996 * tree, we insert rmap_item as a new object into the unstable tree.
998 * This function returns pointer to rmap_item found to be identical
999 * to the currently scanned page, NULL otherwise.
1001 * This function does both searching and inserting, because they share
1002 * the same walking algorithm in an rbtree.
1004 static struct rmap_item *unstable_tree_search_insert(struct page *page,
1005 struct page **page2,
1006 struct rmap_item *rmap_item)
1008 struct rb_node **new = &root_unstable_tree.rb_node;
1009 struct rb_node *parent = NULL;
1011 while (*new) {
1012 struct rmap_item *tree_rmap_item;
1013 int ret;
1015 tree_rmap_item = rb_entry(*new, struct rmap_item, node);
1016 page2[0] = get_mergeable_page(tree_rmap_item);
1017 if (!page2[0])
1018 return NULL;
1021 * Don't substitute an unswappable ksm page
1022 * just for one good swappable forked page.
1024 if (page == page2[0]) {
1025 put_page(page2[0]);
1026 return NULL;
1029 ret = memcmp_pages(page, page2[0]);
1031 parent = *new;
1032 if (ret < 0) {
1033 put_page(page2[0]);
1034 new = &parent->rb_left;
1035 } else if (ret > 0) {
1036 put_page(page2[0]);
1037 new = &parent->rb_right;
1038 } else {
1039 return tree_rmap_item;
1043 rmap_item->address |= NODE_FLAG;
1044 rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
1045 rb_link_node(&rmap_item->node, parent, new);
1046 rb_insert_color(&rmap_item->node, &root_unstable_tree);
1048 ksm_pages_unshared++;
1049 return NULL;
1053 * stable_tree_append - add another rmap_item to the linked list of
1054 * rmap_items hanging off a given node of the stable tree, all sharing
1055 * the same ksm page.
1057 static void stable_tree_append(struct rmap_item *rmap_item,
1058 struct rmap_item *tree_rmap_item)
1060 rmap_item->next = tree_rmap_item->next;
1061 rmap_item->prev = tree_rmap_item;
1063 if (tree_rmap_item->next)
1064 tree_rmap_item->next->prev = rmap_item;
1066 tree_rmap_item->next = rmap_item;
1067 rmap_item->address |= STABLE_FLAG;
1069 ksm_pages_sharing++;
1073 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1074 * if not, compare checksum to previous and if it's the same, see if page can
1075 * be inserted into the unstable tree, or merged with a page already there and
1076 * both transferred to the stable tree.
1078 * @page: the page that we are searching identical page to.
1079 * @rmap_item: the reverse mapping into the virtual address of this page
1081 static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
1083 struct page *page2[1];
1084 struct rmap_item *tree_rmap_item;
1085 unsigned int checksum;
1086 int err;
1088 if (in_stable_tree(rmap_item))
1089 remove_rmap_item_from_tree(rmap_item);
1091 /* We first start with searching the page inside the stable tree */
1092 tree_rmap_item = stable_tree_search(page, page2, rmap_item);
1093 if (tree_rmap_item) {
1094 if (page == page2[0]) /* forked */
1095 err = 0;
1096 else
1097 err = try_to_merge_with_ksm_page(rmap_item->mm,
1098 rmap_item->address,
1099 page, page2[0]);
1100 put_page(page2[0]);
1102 if (!err) {
1104 * The page was successfully merged:
1105 * add its rmap_item to the stable tree.
1107 stable_tree_append(rmap_item, tree_rmap_item);
1109 return;
1113 * A ksm page might have got here by fork, but its other
1114 * references have already been removed from the stable tree.
1115 * Or it might be left over from a break_ksm which failed
1116 * when the mem_cgroup had reached its limit: try again now.
1118 if (PageKsm(page))
1119 break_cow(rmap_item->mm, rmap_item->address);
1122 * In case the hash value of the page was changed from the last time we
1123 * have calculated it, this page to be changed frequely, therefore we
1124 * don't want to insert it to the unstable tree, and we don't want to
1125 * waste our time to search if there is something identical to it there.
1127 checksum = calc_checksum(page);
1128 if (rmap_item->oldchecksum != checksum) {
1129 rmap_item->oldchecksum = checksum;
1130 return;
1133 tree_rmap_item = unstable_tree_search_insert(page, page2, rmap_item);
1134 if (tree_rmap_item) {
1135 err = try_to_merge_two_pages(rmap_item->mm,
1136 rmap_item->address, page,
1137 tree_rmap_item->mm,
1138 tree_rmap_item->address, page2[0]);
1140 * As soon as we merge this page, we want to remove the
1141 * rmap_item of the page we have merged with from the unstable
1142 * tree, and insert it instead as new node in the stable tree.
1144 if (!err) {
1145 rb_erase(&tree_rmap_item->node, &root_unstable_tree);
1146 tree_rmap_item->address &= ~NODE_FLAG;
1147 ksm_pages_unshared--;
1150 * If we fail to insert the page into the stable tree,
1151 * we will have 2 virtual addresses that are pointing
1152 * to a ksm page left outside the stable tree,
1153 * in which case we need to break_cow on both.
1155 if (stable_tree_insert(page2[0], tree_rmap_item))
1156 stable_tree_append(rmap_item, tree_rmap_item);
1157 else {
1158 break_cow(tree_rmap_item->mm,
1159 tree_rmap_item->address);
1160 break_cow(rmap_item->mm, rmap_item->address);
1164 put_page(page2[0]);
1168 static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
1169 struct list_head *cur,
1170 unsigned long addr)
1172 struct rmap_item *rmap_item;
1174 while (cur != &mm_slot->rmap_list) {
1175 rmap_item = list_entry(cur, struct rmap_item, link);
1176 if ((rmap_item->address & PAGE_MASK) == addr) {
1177 if (!in_stable_tree(rmap_item))
1178 remove_rmap_item_from_tree(rmap_item);
1179 return rmap_item;
1181 if (rmap_item->address > addr)
1182 break;
1183 cur = cur->next;
1184 remove_rmap_item_from_tree(rmap_item);
1185 list_del(&rmap_item->link);
1186 free_rmap_item(rmap_item);
1189 rmap_item = alloc_rmap_item();
1190 if (rmap_item) {
1191 /* It has already been zeroed */
1192 rmap_item->mm = mm_slot->mm;
1193 rmap_item->address = addr;
1194 list_add_tail(&rmap_item->link, cur);
1196 return rmap_item;
1199 static struct rmap_item *scan_get_next_rmap_item(struct page **page)
1201 struct mm_struct *mm;
1202 struct mm_slot *slot;
1203 struct vm_area_struct *vma;
1204 struct rmap_item *rmap_item;
1206 if (list_empty(&ksm_mm_head.mm_list))
1207 return NULL;
1209 slot = ksm_scan.mm_slot;
1210 if (slot == &ksm_mm_head) {
1211 root_unstable_tree = RB_ROOT;
1213 spin_lock(&ksm_mmlist_lock);
1214 slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
1215 ksm_scan.mm_slot = slot;
1216 spin_unlock(&ksm_mmlist_lock);
1217 next_mm:
1218 ksm_scan.address = 0;
1219 ksm_scan.rmap_item = list_entry(&slot->rmap_list,
1220 struct rmap_item, link);
1223 mm = slot->mm;
1224 down_read(&mm->mmap_sem);
1225 if (ksm_test_exit(mm))
1226 vma = NULL;
1227 else
1228 vma = find_vma(mm, ksm_scan.address);
1230 for (; vma; vma = vma->vm_next) {
1231 if (!(vma->vm_flags & VM_MERGEABLE))
1232 continue;
1233 if (ksm_scan.address < vma->vm_start)
1234 ksm_scan.address = vma->vm_start;
1235 if (!vma->anon_vma)
1236 ksm_scan.address = vma->vm_end;
1238 while (ksm_scan.address < vma->vm_end) {
1239 if (ksm_test_exit(mm))
1240 break;
1241 *page = follow_page(vma, ksm_scan.address, FOLL_GET);
1242 if (*page && PageAnon(*page)) {
1243 flush_anon_page(vma, *page, ksm_scan.address);
1244 flush_dcache_page(*page);
1245 rmap_item = get_next_rmap_item(slot,
1246 ksm_scan.rmap_item->link.next,
1247 ksm_scan.address);
1248 if (rmap_item) {
1249 ksm_scan.rmap_item = rmap_item;
1250 ksm_scan.address += PAGE_SIZE;
1251 } else
1252 put_page(*page);
1253 up_read(&mm->mmap_sem);
1254 return rmap_item;
1256 if (*page)
1257 put_page(*page);
1258 ksm_scan.address += PAGE_SIZE;
1259 cond_resched();
1263 if (ksm_test_exit(mm)) {
1264 ksm_scan.address = 0;
1265 ksm_scan.rmap_item = list_entry(&slot->rmap_list,
1266 struct rmap_item, link);
1269 * Nuke all the rmap_items that are above this current rmap:
1270 * because there were no VM_MERGEABLE vmas with such addresses.
1272 remove_trailing_rmap_items(slot, ksm_scan.rmap_item->link.next);
1274 spin_lock(&ksm_mmlist_lock);
1275 ksm_scan.mm_slot = list_entry(slot->mm_list.next,
1276 struct mm_slot, mm_list);
1277 if (ksm_scan.address == 0) {
1279 * We've completed a full scan of all vmas, holding mmap_sem
1280 * throughout, and found no VM_MERGEABLE: so do the same as
1281 * __ksm_exit does to remove this mm from all our lists now.
1282 * This applies either when cleaning up after __ksm_exit
1283 * (but beware: we can reach here even before __ksm_exit),
1284 * or when all VM_MERGEABLE areas have been unmapped (and
1285 * mmap_sem then protects against race with MADV_MERGEABLE).
1287 hlist_del(&slot->link);
1288 list_del(&slot->mm_list);
1289 spin_unlock(&ksm_mmlist_lock);
1291 free_mm_slot(slot);
1292 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1293 up_read(&mm->mmap_sem);
1294 mmdrop(mm);
1295 } else {
1296 spin_unlock(&ksm_mmlist_lock);
1297 up_read(&mm->mmap_sem);
1300 /* Repeat until we've completed scanning the whole list */
1301 slot = ksm_scan.mm_slot;
1302 if (slot != &ksm_mm_head)
1303 goto next_mm;
1305 ksm_scan.seqnr++;
1306 return NULL;
1310 * ksm_do_scan - the ksm scanner main worker function.
1311 * @scan_npages - number of pages we want to scan before we return.
1313 static void ksm_do_scan(unsigned int scan_npages)
1315 struct rmap_item *rmap_item;
1316 struct page *page;
1318 while (scan_npages--) {
1319 cond_resched();
1320 rmap_item = scan_get_next_rmap_item(&page);
1321 if (!rmap_item)
1322 return;
1323 if (!PageKsm(page) || !in_stable_tree(rmap_item))
1324 cmp_and_merge_page(page, rmap_item);
1325 else if (page_mapcount(page) == 1) {
1327 * Replace now-unshared ksm page by ordinary page.
1329 break_cow(rmap_item->mm, rmap_item->address);
1330 remove_rmap_item_from_tree(rmap_item);
1331 rmap_item->oldchecksum = calc_checksum(page);
1333 put_page(page);
1337 static int ksmd_should_run(void)
1339 return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
1342 static int ksm_scan_thread(void *nothing)
1344 set_user_nice(current, 5);
1346 while (!kthread_should_stop()) {
1347 mutex_lock(&ksm_thread_mutex);
1348 if (ksmd_should_run())
1349 ksm_do_scan(ksm_thread_pages_to_scan);
1350 mutex_unlock(&ksm_thread_mutex);
1352 if (ksmd_should_run()) {
1353 schedule_timeout_interruptible(
1354 msecs_to_jiffies(ksm_thread_sleep_millisecs));
1355 } else {
1356 wait_event_interruptible(ksm_thread_wait,
1357 ksmd_should_run() || kthread_should_stop());
1360 return 0;
1363 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
1364 unsigned long end, int advice, unsigned long *vm_flags)
1366 struct mm_struct *mm = vma->vm_mm;
1367 int err;
1369 switch (advice) {
1370 case MADV_MERGEABLE:
1372 * Be somewhat over-protective for now!
1374 if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
1375 VM_PFNMAP | VM_IO | VM_DONTEXPAND |
1376 VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
1377 VM_MIXEDMAP | VM_SAO))
1378 return 0; /* just ignore the advice */
1380 if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
1381 err = __ksm_enter(mm);
1382 if (err)
1383 return err;
1386 *vm_flags |= VM_MERGEABLE;
1387 break;
1389 case MADV_UNMERGEABLE:
1390 if (!(*vm_flags & VM_MERGEABLE))
1391 return 0; /* just ignore the advice */
1393 if (vma->anon_vma) {
1394 err = unmerge_ksm_pages(vma, start, end);
1395 if (err)
1396 return err;
1399 *vm_flags &= ~VM_MERGEABLE;
1400 break;
1403 return 0;
1406 int __ksm_enter(struct mm_struct *mm)
1408 struct mm_slot *mm_slot;
1409 int needs_wakeup;
1411 mm_slot = alloc_mm_slot();
1412 if (!mm_slot)
1413 return -ENOMEM;
1415 /* Check ksm_run too? Would need tighter locking */
1416 needs_wakeup = list_empty(&ksm_mm_head.mm_list);
1418 spin_lock(&ksm_mmlist_lock);
1419 insert_to_mm_slots_hash(mm, mm_slot);
1421 * Insert just behind the scanning cursor, to let the area settle
1422 * down a little; when fork is followed by immediate exec, we don't
1423 * want ksmd to waste time setting up and tearing down an rmap_list.
1425 list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
1426 spin_unlock(&ksm_mmlist_lock);
1428 set_bit(MMF_VM_MERGEABLE, &mm->flags);
1429 atomic_inc(&mm->mm_count);
1431 if (needs_wakeup)
1432 wake_up_interruptible(&ksm_thread_wait);
1434 return 0;
1437 void __ksm_exit(struct mm_struct *mm)
1439 struct mm_slot *mm_slot;
1440 int easy_to_free = 0;
1443 * This process is exiting: if it's straightforward (as is the
1444 * case when ksmd was never running), free mm_slot immediately.
1445 * But if it's at the cursor or has rmap_items linked to it, use
1446 * mmap_sem to synchronize with any break_cows before pagetables
1447 * are freed, and leave the mm_slot on the list for ksmd to free.
1448 * Beware: ksm may already have noticed it exiting and freed the slot.
1451 spin_lock(&ksm_mmlist_lock);
1452 mm_slot = get_mm_slot(mm);
1453 if (mm_slot && ksm_scan.mm_slot != mm_slot) {
1454 if (list_empty(&mm_slot->rmap_list)) {
1455 hlist_del(&mm_slot->link);
1456 list_del(&mm_slot->mm_list);
1457 easy_to_free = 1;
1458 } else {
1459 list_move(&mm_slot->mm_list,
1460 &ksm_scan.mm_slot->mm_list);
1463 spin_unlock(&ksm_mmlist_lock);
1465 if (easy_to_free) {
1466 free_mm_slot(mm_slot);
1467 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1468 mmdrop(mm);
1469 } else if (mm_slot) {
1470 down_write(&mm->mmap_sem);
1471 up_write(&mm->mmap_sem);
1475 #ifdef CONFIG_SYSFS
1477 * This all compiles without CONFIG_SYSFS, but is a waste of space.
1480 #define KSM_ATTR_RO(_name) \
1481 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
1482 #define KSM_ATTR(_name) \
1483 static struct kobj_attribute _name##_attr = \
1484 __ATTR(_name, 0644, _name##_show, _name##_store)
1486 static ssize_t sleep_millisecs_show(struct kobject *kobj,
1487 struct kobj_attribute *attr, char *buf)
1489 return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
1492 static ssize_t sleep_millisecs_store(struct kobject *kobj,
1493 struct kobj_attribute *attr,
1494 const char *buf, size_t count)
1496 unsigned long msecs;
1497 int err;
1499 err = strict_strtoul(buf, 10, &msecs);
1500 if (err || msecs > UINT_MAX)
1501 return -EINVAL;
1503 ksm_thread_sleep_millisecs = msecs;
1505 return count;
1507 KSM_ATTR(sleep_millisecs);
1509 static ssize_t pages_to_scan_show(struct kobject *kobj,
1510 struct kobj_attribute *attr, char *buf)
1512 return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
1515 static ssize_t pages_to_scan_store(struct kobject *kobj,
1516 struct kobj_attribute *attr,
1517 const char *buf, size_t count)
1519 int err;
1520 unsigned long nr_pages;
1522 err = strict_strtoul(buf, 10, &nr_pages);
1523 if (err || nr_pages > UINT_MAX)
1524 return -EINVAL;
1526 ksm_thread_pages_to_scan = nr_pages;
1528 return count;
1530 KSM_ATTR(pages_to_scan);
1532 static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
1533 char *buf)
1535 return sprintf(buf, "%u\n", ksm_run);
1538 static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
1539 const char *buf, size_t count)
1541 int err;
1542 unsigned long flags;
1544 err = strict_strtoul(buf, 10, &flags);
1545 if (err || flags > UINT_MAX)
1546 return -EINVAL;
1547 if (flags > KSM_RUN_UNMERGE)
1548 return -EINVAL;
1551 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
1552 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
1553 * breaking COW to free the unswappable pages_shared (but leaves
1554 * mm_slots on the list for when ksmd may be set running again).
1557 mutex_lock(&ksm_thread_mutex);
1558 if (ksm_run != flags) {
1559 ksm_run = flags;
1560 if (flags & KSM_RUN_UNMERGE) {
1561 current->flags |= PF_OOM_ORIGIN;
1562 err = unmerge_and_remove_all_rmap_items();
1563 current->flags &= ~PF_OOM_ORIGIN;
1564 if (err) {
1565 ksm_run = KSM_RUN_STOP;
1566 count = err;
1570 mutex_unlock(&ksm_thread_mutex);
1572 if (flags & KSM_RUN_MERGE)
1573 wake_up_interruptible(&ksm_thread_wait);
1575 return count;
1577 KSM_ATTR(run);
1579 static ssize_t max_kernel_pages_store(struct kobject *kobj,
1580 struct kobj_attribute *attr,
1581 const char *buf, size_t count)
1583 int err;
1584 unsigned long nr_pages;
1586 err = strict_strtoul(buf, 10, &nr_pages);
1587 if (err)
1588 return -EINVAL;
1590 ksm_max_kernel_pages = nr_pages;
1592 return count;
1595 static ssize_t max_kernel_pages_show(struct kobject *kobj,
1596 struct kobj_attribute *attr, char *buf)
1598 return sprintf(buf, "%lu\n", ksm_max_kernel_pages);
1600 KSM_ATTR(max_kernel_pages);
1602 static ssize_t pages_shared_show(struct kobject *kobj,
1603 struct kobj_attribute *attr, char *buf)
1605 return sprintf(buf, "%lu\n", ksm_pages_shared);
1607 KSM_ATTR_RO(pages_shared);
1609 static ssize_t pages_sharing_show(struct kobject *kobj,
1610 struct kobj_attribute *attr, char *buf)
1612 return sprintf(buf, "%lu\n", ksm_pages_sharing);
1614 KSM_ATTR_RO(pages_sharing);
1616 static ssize_t pages_unshared_show(struct kobject *kobj,
1617 struct kobj_attribute *attr, char *buf)
1619 return sprintf(buf, "%lu\n", ksm_pages_unshared);
1621 KSM_ATTR_RO(pages_unshared);
1623 static ssize_t pages_volatile_show(struct kobject *kobj,
1624 struct kobj_attribute *attr, char *buf)
1626 long ksm_pages_volatile;
1628 ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
1629 - ksm_pages_sharing - ksm_pages_unshared;
1631 * It was not worth any locking to calculate that statistic,
1632 * but it might therefore sometimes be negative: conceal that.
1634 if (ksm_pages_volatile < 0)
1635 ksm_pages_volatile = 0;
1636 return sprintf(buf, "%ld\n", ksm_pages_volatile);
1638 KSM_ATTR_RO(pages_volatile);
1640 static ssize_t full_scans_show(struct kobject *kobj,
1641 struct kobj_attribute *attr, char *buf)
1643 return sprintf(buf, "%lu\n", ksm_scan.seqnr);
1645 KSM_ATTR_RO(full_scans);
1647 static struct attribute *ksm_attrs[] = {
1648 &sleep_millisecs_attr.attr,
1649 &pages_to_scan_attr.attr,
1650 &run_attr.attr,
1651 &max_kernel_pages_attr.attr,
1652 &pages_shared_attr.attr,
1653 &pages_sharing_attr.attr,
1654 &pages_unshared_attr.attr,
1655 &pages_volatile_attr.attr,
1656 &full_scans_attr.attr,
1657 NULL,
1660 static struct attribute_group ksm_attr_group = {
1661 .attrs = ksm_attrs,
1662 .name = "ksm",
1664 #endif /* CONFIG_SYSFS */
1666 static int __init ksm_init(void)
1668 struct task_struct *ksm_thread;
1669 int err;
1671 ksm_max_kernel_pages = totalram_pages / 4;
1673 err = ksm_slab_init();
1674 if (err)
1675 goto out;
1677 err = mm_slots_hash_init();
1678 if (err)
1679 goto out_free1;
1681 ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
1682 if (IS_ERR(ksm_thread)) {
1683 printk(KERN_ERR "ksm: creating kthread failed\n");
1684 err = PTR_ERR(ksm_thread);
1685 goto out_free2;
1688 #ifdef CONFIG_SYSFS
1689 err = sysfs_create_group(mm_kobj, &ksm_attr_group);
1690 if (err) {
1691 printk(KERN_ERR "ksm: register sysfs failed\n");
1692 kthread_stop(ksm_thread);
1693 goto out_free2;
1695 #else
1696 ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
1698 #endif /* CONFIG_SYSFS */
1700 return 0;
1702 out_free2:
1703 mm_slots_hash_free();
1704 out_free1:
1705 ksm_slab_free();
1706 out:
1707 return err;
1709 module_init(ksm_init)