oom: remove child->mm check from oom_kill_process()
[linux-2.6/x86.git] / mm / ksm.c
blob9f2acc998a37d0f293eb52e6efdccefc17dfa272
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/memory.h>
33 #include <linux/mmu_notifier.h>
34 #include <linux/swap.h>
35 #include <linux/ksm.h>
37 #include <asm/tlbflush.h>
38 #include "internal.h"
41 * A few notes about the KSM scanning process,
42 * to make it easier to understand the data structures below:
44 * In order to reduce excessive scanning, KSM sorts the memory pages by their
45 * contents into a data structure that holds pointers to the pages' locations.
47 * Since the contents of the pages may change at any moment, KSM cannot just
48 * insert the pages into a normal sorted tree and expect it to find anything.
49 * Therefore KSM uses two data structures - the stable and the unstable tree.
51 * The stable tree holds pointers to all the merged pages (ksm pages), sorted
52 * by their contents. Because each such page is write-protected, searching on
53 * this tree is fully assured to be working (except when pages are unmapped),
54 * and therefore this tree is called the stable tree.
56 * In addition to the stable tree, KSM uses a second data structure called the
57 * unstable tree: this tree holds pointers to pages which have been found to
58 * be "unchanged for a period of time". The unstable tree sorts these pages
59 * by their contents, but since they are not write-protected, KSM cannot rely
60 * upon the unstable tree to work correctly - the unstable tree is liable to
61 * be corrupted as its contents are modified, and so it is called unstable.
63 * KSM solves this problem by several techniques:
65 * 1) The unstable tree is flushed every time KSM completes scanning all
66 * memory areas, and then the tree is rebuilt again from the beginning.
67 * 2) KSM will only insert into the unstable tree, pages whose hash value
68 * has not changed since the previous scan of all memory areas.
69 * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
70 * colors of the nodes and not on their contents, assuring that even when
71 * the tree gets "corrupted" it won't get out of balance, so scanning time
72 * remains the same (also, searching and inserting nodes in an rbtree uses
73 * the same algorithm, so we have no overhead when we flush and rebuild).
74 * 4) KSM never flushes the stable tree, which means that even if it were to
75 * take 10 attempts to find a page in the unstable tree, once it is found,
76 * it is secured in the stable tree. (When we scan a new page, we first
77 * compare it against the stable tree, and then against the unstable tree.)
80 /**
81 * struct mm_slot - ksm information per mm that is being scanned
82 * @link: link to the mm_slots hash list
83 * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
84 * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
85 * @mm: the mm that this information is valid for
87 struct mm_slot {
88 struct hlist_node link;
89 struct list_head mm_list;
90 struct rmap_item *rmap_list;
91 struct mm_struct *mm;
94 /**
95 * struct ksm_scan - cursor for scanning
96 * @mm_slot: the current mm_slot we are scanning
97 * @address: the next address inside that to be scanned
98 * @rmap_list: link to the next rmap to be scanned in the rmap_list
99 * @seqnr: count of completed full scans (needed when removing unstable node)
101 * There is only the one ksm_scan instance of this cursor structure.
103 struct ksm_scan {
104 struct mm_slot *mm_slot;
105 unsigned long address;
106 struct rmap_item **rmap_list;
107 unsigned long seqnr;
111 * struct stable_node - node of the stable rbtree
112 * @node: rb node of this ksm page in the stable tree
113 * @hlist: hlist head of rmap_items using this ksm page
114 * @kpfn: page frame number of this ksm page
116 struct stable_node {
117 struct rb_node node;
118 struct hlist_head hlist;
119 unsigned long kpfn;
123 * struct rmap_item - reverse mapping item for virtual addresses
124 * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
125 * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
126 * @mm: the memory structure this rmap_item is pointing into
127 * @address: the virtual address this rmap_item tracks (+ flags in low bits)
128 * @oldchecksum: previous checksum of the page at that virtual address
129 * @node: rb node of this rmap_item in the unstable tree
130 * @head: pointer to stable_node heading this list in the stable tree
131 * @hlist: link into hlist of rmap_items hanging off that stable_node
133 struct rmap_item {
134 struct rmap_item *rmap_list;
135 struct anon_vma *anon_vma; /* when stable */
136 struct mm_struct *mm;
137 unsigned long address; /* + low bits used for flags below */
138 unsigned int oldchecksum; /* when unstable */
139 union {
140 struct rb_node node; /* when node of unstable tree */
141 struct { /* when listed from stable tree */
142 struct stable_node *head;
143 struct hlist_node hlist;
148 #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
149 #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
150 #define STABLE_FLAG 0x200 /* is listed from the stable tree */
152 /* The stable and unstable tree heads */
153 static struct rb_root root_stable_tree = RB_ROOT;
154 static struct rb_root root_unstable_tree = RB_ROOT;
156 #define MM_SLOTS_HASH_HEADS 1024
157 static struct hlist_head *mm_slots_hash;
159 static struct mm_slot ksm_mm_head = {
160 .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
162 static struct ksm_scan ksm_scan = {
163 .mm_slot = &ksm_mm_head,
166 static struct kmem_cache *rmap_item_cache;
167 static struct kmem_cache *stable_node_cache;
168 static struct kmem_cache *mm_slot_cache;
170 /* The number of nodes in the stable tree */
171 static unsigned long ksm_pages_shared;
173 /* The number of page slots additionally sharing those nodes */
174 static unsigned long ksm_pages_sharing;
176 /* The number of nodes in the unstable tree */
177 static unsigned long ksm_pages_unshared;
179 /* The number of rmap_items in use: to calculate pages_volatile */
180 static unsigned long ksm_rmap_items;
182 /* Number of pages ksmd should scan in one batch */
183 static unsigned int ksm_thread_pages_to_scan = 100;
185 /* Milliseconds ksmd should sleep between batches */
186 static unsigned int ksm_thread_sleep_millisecs = 20;
188 #define KSM_RUN_STOP 0
189 #define KSM_RUN_MERGE 1
190 #define KSM_RUN_UNMERGE 2
191 static unsigned int ksm_run = KSM_RUN_STOP;
193 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
194 static DEFINE_MUTEX(ksm_thread_mutex);
195 static DEFINE_SPINLOCK(ksm_mmlist_lock);
197 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
198 sizeof(struct __struct), __alignof__(struct __struct),\
199 (__flags), NULL)
201 static int __init ksm_slab_init(void)
203 rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
204 if (!rmap_item_cache)
205 goto out;
207 stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
208 if (!stable_node_cache)
209 goto out_free1;
211 mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
212 if (!mm_slot_cache)
213 goto out_free2;
215 return 0;
217 out_free2:
218 kmem_cache_destroy(stable_node_cache);
219 out_free1:
220 kmem_cache_destroy(rmap_item_cache);
221 out:
222 return -ENOMEM;
225 static void __init ksm_slab_free(void)
227 kmem_cache_destroy(mm_slot_cache);
228 kmem_cache_destroy(stable_node_cache);
229 kmem_cache_destroy(rmap_item_cache);
230 mm_slot_cache = NULL;
233 static inline struct rmap_item *alloc_rmap_item(void)
235 struct rmap_item *rmap_item;
237 rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL);
238 if (rmap_item)
239 ksm_rmap_items++;
240 return rmap_item;
243 static inline void free_rmap_item(struct rmap_item *rmap_item)
245 ksm_rmap_items--;
246 rmap_item->mm = NULL; /* debug safety */
247 kmem_cache_free(rmap_item_cache, rmap_item);
250 static inline struct stable_node *alloc_stable_node(void)
252 return kmem_cache_alloc(stable_node_cache, GFP_KERNEL);
255 static inline void free_stable_node(struct stable_node *stable_node)
257 kmem_cache_free(stable_node_cache, stable_node);
260 static inline struct mm_slot *alloc_mm_slot(void)
262 if (!mm_slot_cache) /* initialization failed */
263 return NULL;
264 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
267 static inline void free_mm_slot(struct mm_slot *mm_slot)
269 kmem_cache_free(mm_slot_cache, mm_slot);
272 static int __init mm_slots_hash_init(void)
274 mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
275 GFP_KERNEL);
276 if (!mm_slots_hash)
277 return -ENOMEM;
278 return 0;
281 static void __init mm_slots_hash_free(void)
283 kfree(mm_slots_hash);
286 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
288 struct mm_slot *mm_slot;
289 struct hlist_head *bucket;
290 struct hlist_node *node;
292 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
293 % MM_SLOTS_HASH_HEADS];
294 hlist_for_each_entry(mm_slot, node, bucket, link) {
295 if (mm == mm_slot->mm)
296 return mm_slot;
298 return NULL;
301 static void insert_to_mm_slots_hash(struct mm_struct *mm,
302 struct mm_slot *mm_slot)
304 struct hlist_head *bucket;
306 bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
307 % MM_SLOTS_HASH_HEADS];
308 mm_slot->mm = mm;
309 hlist_add_head(&mm_slot->link, bucket);
312 static inline int in_stable_tree(struct rmap_item *rmap_item)
314 return rmap_item->address & STABLE_FLAG;
317 static void hold_anon_vma(struct rmap_item *rmap_item,
318 struct anon_vma *anon_vma)
320 rmap_item->anon_vma = anon_vma;
321 get_anon_vma(anon_vma);
324 static void ksm_drop_anon_vma(struct rmap_item *rmap_item)
326 struct anon_vma *anon_vma = rmap_item->anon_vma;
328 drop_anon_vma(anon_vma);
332 * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
333 * page tables after it has passed through ksm_exit() - which, if necessary,
334 * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
335 * a special flag: they can just back out as soon as mm_users goes to zero.
336 * ksm_test_exit() is used throughout to make this test for exit: in some
337 * places for correctness, in some places just to avoid unnecessary work.
339 static inline bool ksm_test_exit(struct mm_struct *mm)
341 return atomic_read(&mm->mm_users) == 0;
345 * We use break_ksm to break COW on a ksm page: it's a stripped down
347 * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
348 * put_page(page);
350 * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
351 * in case the application has unmapped and remapped mm,addr meanwhile.
352 * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
353 * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
355 static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
357 struct page *page;
358 int ret = 0;
360 do {
361 cond_resched();
362 page = follow_page(vma, addr, FOLL_GET);
363 if (IS_ERR_OR_NULL(page))
364 break;
365 if (PageKsm(page))
366 ret = handle_mm_fault(vma->vm_mm, vma, addr,
367 FAULT_FLAG_WRITE);
368 else
369 ret = VM_FAULT_WRITE;
370 put_page(page);
371 } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_OOM)));
373 * We must loop because handle_mm_fault() may back out if there's
374 * any difficulty e.g. if pte accessed bit gets updated concurrently.
376 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
377 * COW has been broken, even if the vma does not permit VM_WRITE;
378 * but note that a concurrent fault might break PageKsm for us.
380 * VM_FAULT_SIGBUS could occur if we race with truncation of the
381 * backing file, which also invalidates anonymous pages: that's
382 * okay, that truncation will have unmapped the PageKsm for us.
384 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
385 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
386 * current task has TIF_MEMDIE set, and will be OOM killed on return
387 * to user; and ksmd, having no mm, would never be chosen for that.
389 * But if the mm is in a limited mem_cgroup, then the fault may fail
390 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
391 * even ksmd can fail in this way - though it's usually breaking ksm
392 * just to undo a merge it made a moment before, so unlikely to oom.
394 * That's a pity: we might therefore have more kernel pages allocated
395 * than we're counting as nodes in the stable tree; but ksm_do_scan
396 * will retry to break_cow on each pass, so should recover the page
397 * in due course. The important thing is to not let VM_MERGEABLE
398 * be cleared while any such pages might remain in the area.
400 return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
403 static void break_cow(struct rmap_item *rmap_item)
405 struct mm_struct *mm = rmap_item->mm;
406 unsigned long addr = rmap_item->address;
407 struct vm_area_struct *vma;
410 * It is not an accident that whenever we want to break COW
411 * to undo, we also need to drop a reference to the anon_vma.
413 ksm_drop_anon_vma(rmap_item);
415 down_read(&mm->mmap_sem);
416 if (ksm_test_exit(mm))
417 goto out;
418 vma = find_vma(mm, addr);
419 if (!vma || vma->vm_start > addr)
420 goto out;
421 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
422 goto out;
423 break_ksm(vma, addr);
424 out:
425 up_read(&mm->mmap_sem);
428 static struct page *get_mergeable_page(struct rmap_item *rmap_item)
430 struct mm_struct *mm = rmap_item->mm;
431 unsigned long addr = rmap_item->address;
432 struct vm_area_struct *vma;
433 struct page *page;
435 down_read(&mm->mmap_sem);
436 if (ksm_test_exit(mm))
437 goto out;
438 vma = find_vma(mm, addr);
439 if (!vma || vma->vm_start > addr)
440 goto out;
441 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
442 goto out;
444 page = follow_page(vma, addr, FOLL_GET);
445 if (IS_ERR_OR_NULL(page))
446 goto out;
447 if (PageAnon(page)) {
448 flush_anon_page(vma, page, addr);
449 flush_dcache_page(page);
450 } else {
451 put_page(page);
452 out: page = NULL;
454 up_read(&mm->mmap_sem);
455 return page;
458 static void remove_node_from_stable_tree(struct stable_node *stable_node)
460 struct rmap_item *rmap_item;
461 struct hlist_node *hlist;
463 hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
464 if (rmap_item->hlist.next)
465 ksm_pages_sharing--;
466 else
467 ksm_pages_shared--;
468 ksm_drop_anon_vma(rmap_item);
469 rmap_item->address &= PAGE_MASK;
470 cond_resched();
473 rb_erase(&stable_node->node, &root_stable_tree);
474 free_stable_node(stable_node);
478 * get_ksm_page: checks if the page indicated by the stable node
479 * is still its ksm page, despite having held no reference to it.
480 * In which case we can trust the content of the page, and it
481 * returns the gotten page; but if the page has now been zapped,
482 * remove the stale node from the stable tree and return NULL.
484 * You would expect the stable_node to hold a reference to the ksm page.
485 * But if it increments the page's count, swapping out has to wait for
486 * ksmd to come around again before it can free the page, which may take
487 * seconds or even minutes: much too unresponsive. So instead we use a
488 * "keyhole reference": access to the ksm page from the stable node peeps
489 * out through its keyhole to see if that page still holds the right key,
490 * pointing back to this stable node. This relies on freeing a PageAnon
491 * page to reset its page->mapping to NULL, and relies on no other use of
492 * a page to put something that might look like our key in page->mapping.
494 * include/linux/pagemap.h page_cache_get_speculative() is a good reference,
495 * but this is different - made simpler by ksm_thread_mutex being held, but
496 * interesting for assuming that no other use of the struct page could ever
497 * put our expected_mapping into page->mapping (or a field of the union which
498 * coincides with page->mapping). The RCU calls are not for KSM at all, but
499 * to keep the page_count protocol described with page_cache_get_speculative.
501 * Note: it is possible that get_ksm_page() will return NULL one moment,
502 * then page the next, if the page is in between page_freeze_refs() and
503 * page_unfreeze_refs(): this shouldn't be a problem anywhere, the page
504 * is on its way to being freed; but it is an anomaly to bear in mind.
506 static struct page *get_ksm_page(struct stable_node *stable_node)
508 struct page *page;
509 void *expected_mapping;
511 page = pfn_to_page(stable_node->kpfn);
512 expected_mapping = (void *)stable_node +
513 (PAGE_MAPPING_ANON | PAGE_MAPPING_KSM);
514 rcu_read_lock();
515 if (page->mapping != expected_mapping)
516 goto stale;
517 if (!get_page_unless_zero(page))
518 goto stale;
519 if (page->mapping != expected_mapping) {
520 put_page(page);
521 goto stale;
523 rcu_read_unlock();
524 return page;
525 stale:
526 rcu_read_unlock();
527 remove_node_from_stable_tree(stable_node);
528 return NULL;
532 * Removing rmap_item from stable or unstable tree.
533 * This function will clean the information from the stable/unstable tree.
535 static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
537 if (rmap_item->address & STABLE_FLAG) {
538 struct stable_node *stable_node;
539 struct page *page;
541 stable_node = rmap_item->head;
542 page = get_ksm_page(stable_node);
543 if (!page)
544 goto out;
546 lock_page(page);
547 hlist_del(&rmap_item->hlist);
548 unlock_page(page);
549 put_page(page);
551 if (stable_node->hlist.first)
552 ksm_pages_sharing--;
553 else
554 ksm_pages_shared--;
556 ksm_drop_anon_vma(rmap_item);
557 rmap_item->address &= PAGE_MASK;
559 } else if (rmap_item->address & UNSTABLE_FLAG) {
560 unsigned char age;
562 * Usually ksmd can and must skip the rb_erase, because
563 * root_unstable_tree was already reset to RB_ROOT.
564 * But be careful when an mm is exiting: do the rb_erase
565 * if this rmap_item was inserted by this scan, rather
566 * than left over from before.
568 age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
569 BUG_ON(age > 1);
570 if (!age)
571 rb_erase(&rmap_item->node, &root_unstable_tree);
573 ksm_pages_unshared--;
574 rmap_item->address &= PAGE_MASK;
576 out:
577 cond_resched(); /* we're called from many long loops */
580 static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
581 struct rmap_item **rmap_list)
583 while (*rmap_list) {
584 struct rmap_item *rmap_item = *rmap_list;
585 *rmap_list = rmap_item->rmap_list;
586 remove_rmap_item_from_tree(rmap_item);
587 free_rmap_item(rmap_item);
592 * Though it's very tempting to unmerge in_stable_tree(rmap_item)s rather
593 * than check every pte of a given vma, the locking doesn't quite work for
594 * that - an rmap_item is assigned to the stable tree after inserting ksm
595 * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
596 * rmap_items from parent to child at fork time (so as not to waste time
597 * if exit comes before the next scan reaches it).
599 * Similarly, although we'd like to remove rmap_items (so updating counts
600 * and freeing memory) when unmerging an area, it's easier to leave that
601 * to the next pass of ksmd - consider, for example, how ksmd might be
602 * in cmp_and_merge_page on one of the rmap_items we would be removing.
604 static int unmerge_ksm_pages(struct vm_area_struct *vma,
605 unsigned long start, unsigned long end)
607 unsigned long addr;
608 int err = 0;
610 for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
611 if (ksm_test_exit(vma->vm_mm))
612 break;
613 if (signal_pending(current))
614 err = -ERESTARTSYS;
615 else
616 err = break_ksm(vma, addr);
618 return err;
621 #ifdef CONFIG_SYSFS
623 * Only called through the sysfs control interface:
625 static int unmerge_and_remove_all_rmap_items(void)
627 struct mm_slot *mm_slot;
628 struct mm_struct *mm;
629 struct vm_area_struct *vma;
630 int err = 0;
632 spin_lock(&ksm_mmlist_lock);
633 ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
634 struct mm_slot, mm_list);
635 spin_unlock(&ksm_mmlist_lock);
637 for (mm_slot = ksm_scan.mm_slot;
638 mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
639 mm = mm_slot->mm;
640 down_read(&mm->mmap_sem);
641 for (vma = mm->mmap; vma; vma = vma->vm_next) {
642 if (ksm_test_exit(mm))
643 break;
644 if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
645 continue;
646 err = unmerge_ksm_pages(vma,
647 vma->vm_start, vma->vm_end);
648 if (err)
649 goto error;
652 remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
654 spin_lock(&ksm_mmlist_lock);
655 ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
656 struct mm_slot, mm_list);
657 if (ksm_test_exit(mm)) {
658 hlist_del(&mm_slot->link);
659 list_del(&mm_slot->mm_list);
660 spin_unlock(&ksm_mmlist_lock);
662 free_mm_slot(mm_slot);
663 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
664 up_read(&mm->mmap_sem);
665 mmdrop(mm);
666 } else {
667 spin_unlock(&ksm_mmlist_lock);
668 up_read(&mm->mmap_sem);
672 ksm_scan.seqnr = 0;
673 return 0;
675 error:
676 up_read(&mm->mmap_sem);
677 spin_lock(&ksm_mmlist_lock);
678 ksm_scan.mm_slot = &ksm_mm_head;
679 spin_unlock(&ksm_mmlist_lock);
680 return err;
682 #endif /* CONFIG_SYSFS */
684 static u32 calc_checksum(struct page *page)
686 u32 checksum;
687 void *addr = kmap_atomic(page, KM_USER0);
688 checksum = jhash2(addr, PAGE_SIZE / 4, 17);
689 kunmap_atomic(addr, KM_USER0);
690 return checksum;
693 static int memcmp_pages(struct page *page1, struct page *page2)
695 char *addr1, *addr2;
696 int ret;
698 addr1 = kmap_atomic(page1, KM_USER0);
699 addr2 = kmap_atomic(page2, KM_USER1);
700 ret = memcmp(addr1, addr2, PAGE_SIZE);
701 kunmap_atomic(addr2, KM_USER1);
702 kunmap_atomic(addr1, KM_USER0);
703 return ret;
706 static inline int pages_identical(struct page *page1, struct page *page2)
708 return !memcmp_pages(page1, page2);
711 static int write_protect_page(struct vm_area_struct *vma, struct page *page,
712 pte_t *orig_pte)
714 struct mm_struct *mm = vma->vm_mm;
715 unsigned long addr;
716 pte_t *ptep;
717 spinlock_t *ptl;
718 int swapped;
719 int err = -EFAULT;
721 addr = page_address_in_vma(page, vma);
722 if (addr == -EFAULT)
723 goto out;
725 ptep = page_check_address(page, mm, addr, &ptl, 0);
726 if (!ptep)
727 goto out;
729 if (pte_write(*ptep)) {
730 pte_t entry;
732 swapped = PageSwapCache(page);
733 flush_cache_page(vma, addr, page_to_pfn(page));
735 * Ok this is tricky, when get_user_pages_fast() run it doesnt
736 * take any lock, therefore the check that we are going to make
737 * with the pagecount against the mapcount is racey and
738 * O_DIRECT can happen right after the check.
739 * So we clear the pte and flush the tlb before the check
740 * this assure us that no O_DIRECT can happen after the check
741 * or in the middle of the check.
743 entry = ptep_clear_flush(vma, addr, ptep);
745 * Check that no O_DIRECT or similar I/O is in progress on the
746 * page
748 if (page_mapcount(page) + 1 + swapped != page_count(page)) {
749 set_pte_at(mm, addr, ptep, entry);
750 goto out_unlock;
752 entry = pte_wrprotect(entry);
753 set_pte_at_notify(mm, addr, ptep, entry);
755 *orig_pte = *ptep;
756 err = 0;
758 out_unlock:
759 pte_unmap_unlock(ptep, ptl);
760 out:
761 return err;
765 * replace_page - replace page in vma by new ksm page
766 * @vma: vma that holds the pte pointing to page
767 * @page: the page we are replacing by kpage
768 * @kpage: the ksm page we replace page by
769 * @orig_pte: the original value of the pte
771 * Returns 0 on success, -EFAULT on failure.
773 static int replace_page(struct vm_area_struct *vma, struct page *page,
774 struct page *kpage, pte_t orig_pte)
776 struct mm_struct *mm = vma->vm_mm;
777 pgd_t *pgd;
778 pud_t *pud;
779 pmd_t *pmd;
780 pte_t *ptep;
781 spinlock_t *ptl;
782 unsigned long addr;
783 int err = -EFAULT;
785 addr = page_address_in_vma(page, vma);
786 if (addr == -EFAULT)
787 goto out;
789 pgd = pgd_offset(mm, addr);
790 if (!pgd_present(*pgd))
791 goto out;
793 pud = pud_offset(pgd, addr);
794 if (!pud_present(*pud))
795 goto out;
797 pmd = pmd_offset(pud, addr);
798 if (!pmd_present(*pmd))
799 goto out;
801 ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
802 if (!pte_same(*ptep, orig_pte)) {
803 pte_unmap_unlock(ptep, ptl);
804 goto out;
807 get_page(kpage);
808 page_add_anon_rmap(kpage, vma, addr);
810 flush_cache_page(vma, addr, pte_pfn(*ptep));
811 ptep_clear_flush(vma, addr, ptep);
812 set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
814 page_remove_rmap(page);
815 put_page(page);
817 pte_unmap_unlock(ptep, ptl);
818 err = 0;
819 out:
820 return err;
824 * try_to_merge_one_page - take two pages and merge them into one
825 * @vma: the vma that holds the pte pointing to page
826 * @page: the PageAnon page that we want to replace with kpage
827 * @kpage: the PageKsm page that we want to map instead of page,
828 * or NULL the first time when we want to use page as kpage.
830 * This function returns 0 if the pages were merged, -EFAULT otherwise.
832 static int try_to_merge_one_page(struct vm_area_struct *vma,
833 struct page *page, struct page *kpage)
835 pte_t orig_pte = __pte(0);
836 int err = -EFAULT;
838 if (page == kpage) /* ksm page forked */
839 return 0;
841 if (!(vma->vm_flags & VM_MERGEABLE))
842 goto out;
843 if (!PageAnon(page))
844 goto out;
847 * We need the page lock to read a stable PageSwapCache in
848 * write_protect_page(). We use trylock_page() instead of
849 * lock_page() because we don't want to wait here - we
850 * prefer to continue scanning and merging different pages,
851 * then come back to this page when it is unlocked.
853 if (!trylock_page(page))
854 goto out;
856 * If this anonymous page is mapped only here, its pte may need
857 * to be write-protected. If it's mapped elsewhere, all of its
858 * ptes are necessarily already write-protected. But in either
859 * case, we need to lock and check page_count is not raised.
861 if (write_protect_page(vma, page, &orig_pte) == 0) {
862 if (!kpage) {
864 * While we hold page lock, upgrade page from
865 * PageAnon+anon_vma to PageKsm+NULL stable_node:
866 * stable_tree_insert() will update stable_node.
868 set_page_stable_node(page, NULL);
869 mark_page_accessed(page);
870 err = 0;
871 } else if (pages_identical(page, kpage))
872 err = replace_page(vma, page, kpage, orig_pte);
875 if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
876 munlock_vma_page(page);
877 if (!PageMlocked(kpage)) {
878 unlock_page(page);
879 lock_page(kpage);
880 mlock_vma_page(kpage);
881 page = kpage; /* for final unlock */
885 unlock_page(page);
886 out:
887 return err;
891 * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
892 * but no new kernel page is allocated: kpage must already be a ksm page.
894 * This function returns 0 if the pages were merged, -EFAULT otherwise.
896 static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
897 struct page *page, struct page *kpage)
899 struct mm_struct *mm = rmap_item->mm;
900 struct vm_area_struct *vma;
901 int err = -EFAULT;
903 down_read(&mm->mmap_sem);
904 if (ksm_test_exit(mm))
905 goto out;
906 vma = find_vma(mm, rmap_item->address);
907 if (!vma || vma->vm_start > rmap_item->address)
908 goto out;
910 err = try_to_merge_one_page(vma, page, kpage);
911 if (err)
912 goto out;
914 /* Must get reference to anon_vma while still holding mmap_sem */
915 hold_anon_vma(rmap_item, vma->anon_vma);
916 out:
917 up_read(&mm->mmap_sem);
918 return err;
922 * try_to_merge_two_pages - take two identical pages and prepare them
923 * to be merged into one page.
925 * This function returns the kpage if we successfully merged two identical
926 * pages into one ksm page, NULL otherwise.
928 * Note that this function upgrades page to ksm page: if one of the pages
929 * is already a ksm page, try_to_merge_with_ksm_page should be used.
931 static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
932 struct page *page,
933 struct rmap_item *tree_rmap_item,
934 struct page *tree_page)
936 int err;
938 err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
939 if (!err) {
940 err = try_to_merge_with_ksm_page(tree_rmap_item,
941 tree_page, page);
943 * If that fails, we have a ksm page with only one pte
944 * pointing to it: so break it.
946 if (err)
947 break_cow(rmap_item);
949 return err ? NULL : page;
953 * stable_tree_search - search for page inside the stable tree
955 * This function checks if there is a page inside the stable tree
956 * with identical content to the page that we are scanning right now.
958 * This function returns the stable tree node of identical content if found,
959 * NULL otherwise.
961 static struct page *stable_tree_search(struct page *page)
963 struct rb_node *node = root_stable_tree.rb_node;
964 struct stable_node *stable_node;
966 stable_node = page_stable_node(page);
967 if (stable_node) { /* ksm page forked */
968 get_page(page);
969 return page;
972 while (node) {
973 struct page *tree_page;
974 int ret;
976 cond_resched();
977 stable_node = rb_entry(node, struct stable_node, node);
978 tree_page = get_ksm_page(stable_node);
979 if (!tree_page)
980 return NULL;
982 ret = memcmp_pages(page, tree_page);
984 if (ret < 0) {
985 put_page(tree_page);
986 node = node->rb_left;
987 } else if (ret > 0) {
988 put_page(tree_page);
989 node = node->rb_right;
990 } else
991 return tree_page;
994 return NULL;
998 * stable_tree_insert - insert rmap_item pointing to new ksm page
999 * into the stable tree.
1001 * This function returns the stable tree node just allocated on success,
1002 * NULL otherwise.
1004 static struct stable_node *stable_tree_insert(struct page *kpage)
1006 struct rb_node **new = &root_stable_tree.rb_node;
1007 struct rb_node *parent = NULL;
1008 struct stable_node *stable_node;
1010 while (*new) {
1011 struct page *tree_page;
1012 int ret;
1014 cond_resched();
1015 stable_node = rb_entry(*new, struct stable_node, node);
1016 tree_page = get_ksm_page(stable_node);
1017 if (!tree_page)
1018 return NULL;
1020 ret = memcmp_pages(kpage, tree_page);
1021 put_page(tree_page);
1023 parent = *new;
1024 if (ret < 0)
1025 new = &parent->rb_left;
1026 else if (ret > 0)
1027 new = &parent->rb_right;
1028 else {
1030 * It is not a bug that stable_tree_search() didn't
1031 * find this node: because at that time our page was
1032 * not yet write-protected, so may have changed since.
1034 return NULL;
1038 stable_node = alloc_stable_node();
1039 if (!stable_node)
1040 return NULL;
1042 rb_link_node(&stable_node->node, parent, new);
1043 rb_insert_color(&stable_node->node, &root_stable_tree);
1045 INIT_HLIST_HEAD(&stable_node->hlist);
1047 stable_node->kpfn = page_to_pfn(kpage);
1048 set_page_stable_node(kpage, stable_node);
1050 return stable_node;
1054 * unstable_tree_search_insert - search for identical page,
1055 * else insert rmap_item into the unstable tree.
1057 * This function searches for a page in the unstable tree identical to the
1058 * page currently being scanned; and if no identical page is found in the
1059 * tree, we insert rmap_item as a new object into the unstable tree.
1061 * This function returns pointer to rmap_item found to be identical
1062 * to the currently scanned page, NULL otherwise.
1064 * This function does both searching and inserting, because they share
1065 * the same walking algorithm in an rbtree.
1067 static
1068 struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
1069 struct page *page,
1070 struct page **tree_pagep)
1073 struct rb_node **new = &root_unstable_tree.rb_node;
1074 struct rb_node *parent = NULL;
1076 while (*new) {
1077 struct rmap_item *tree_rmap_item;
1078 struct page *tree_page;
1079 int ret;
1081 cond_resched();
1082 tree_rmap_item = rb_entry(*new, struct rmap_item, node);
1083 tree_page = get_mergeable_page(tree_rmap_item);
1084 if (IS_ERR_OR_NULL(tree_page))
1085 return NULL;
1088 * Don't substitute a ksm page for a forked page.
1090 if (page == tree_page) {
1091 put_page(tree_page);
1092 return NULL;
1095 ret = memcmp_pages(page, tree_page);
1097 parent = *new;
1098 if (ret < 0) {
1099 put_page(tree_page);
1100 new = &parent->rb_left;
1101 } else if (ret > 0) {
1102 put_page(tree_page);
1103 new = &parent->rb_right;
1104 } else {
1105 *tree_pagep = tree_page;
1106 return tree_rmap_item;
1110 rmap_item->address |= UNSTABLE_FLAG;
1111 rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
1112 rb_link_node(&rmap_item->node, parent, new);
1113 rb_insert_color(&rmap_item->node, &root_unstable_tree);
1115 ksm_pages_unshared++;
1116 return NULL;
1120 * stable_tree_append - add another rmap_item to the linked list of
1121 * rmap_items hanging off a given node of the stable tree, all sharing
1122 * the same ksm page.
1124 static void stable_tree_append(struct rmap_item *rmap_item,
1125 struct stable_node *stable_node)
1127 rmap_item->head = stable_node;
1128 rmap_item->address |= STABLE_FLAG;
1129 hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
1131 if (rmap_item->hlist.next)
1132 ksm_pages_sharing++;
1133 else
1134 ksm_pages_shared++;
1138 * cmp_and_merge_page - first see if page can be merged into the stable tree;
1139 * if not, compare checksum to previous and if it's the same, see if page can
1140 * be inserted into the unstable tree, or merged with a page already there and
1141 * both transferred to the stable tree.
1143 * @page: the page that we are searching identical page to.
1144 * @rmap_item: the reverse mapping into the virtual address of this page
1146 static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
1148 struct rmap_item *tree_rmap_item;
1149 struct page *tree_page = NULL;
1150 struct stable_node *stable_node;
1151 struct page *kpage;
1152 unsigned int checksum;
1153 int err;
1155 remove_rmap_item_from_tree(rmap_item);
1157 /* We first start with searching the page inside the stable tree */
1158 kpage = stable_tree_search(page);
1159 if (kpage) {
1160 err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
1161 if (!err) {
1163 * The page was successfully merged:
1164 * add its rmap_item to the stable tree.
1166 lock_page(kpage);
1167 stable_tree_append(rmap_item, page_stable_node(kpage));
1168 unlock_page(kpage);
1170 put_page(kpage);
1171 return;
1175 * If the hash value of the page has changed from the last time
1176 * we calculated it, this page is changing frequently: therefore we
1177 * don't want to insert it in the unstable tree, and we don't want
1178 * to waste our time searching for something identical to it there.
1180 checksum = calc_checksum(page);
1181 if (rmap_item->oldchecksum != checksum) {
1182 rmap_item->oldchecksum = checksum;
1183 return;
1186 tree_rmap_item =
1187 unstable_tree_search_insert(rmap_item, page, &tree_page);
1188 if (tree_rmap_item) {
1189 kpage = try_to_merge_two_pages(rmap_item, page,
1190 tree_rmap_item, tree_page);
1191 put_page(tree_page);
1193 * As soon as we merge this page, we want to remove the
1194 * rmap_item of the page we have merged with from the unstable
1195 * tree, and insert it instead as new node in the stable tree.
1197 if (kpage) {
1198 remove_rmap_item_from_tree(tree_rmap_item);
1200 lock_page(kpage);
1201 stable_node = stable_tree_insert(kpage);
1202 if (stable_node) {
1203 stable_tree_append(tree_rmap_item, stable_node);
1204 stable_tree_append(rmap_item, stable_node);
1206 unlock_page(kpage);
1209 * If we fail to insert the page into the stable tree,
1210 * we will have 2 virtual addresses that are pointing
1211 * to a ksm page left outside the stable tree,
1212 * in which case we need to break_cow on both.
1214 if (!stable_node) {
1215 break_cow(tree_rmap_item);
1216 break_cow(rmap_item);
1222 static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
1223 struct rmap_item **rmap_list,
1224 unsigned long addr)
1226 struct rmap_item *rmap_item;
1228 while (*rmap_list) {
1229 rmap_item = *rmap_list;
1230 if ((rmap_item->address & PAGE_MASK) == addr)
1231 return rmap_item;
1232 if (rmap_item->address > addr)
1233 break;
1234 *rmap_list = rmap_item->rmap_list;
1235 remove_rmap_item_from_tree(rmap_item);
1236 free_rmap_item(rmap_item);
1239 rmap_item = alloc_rmap_item();
1240 if (rmap_item) {
1241 /* It has already been zeroed */
1242 rmap_item->mm = mm_slot->mm;
1243 rmap_item->address = addr;
1244 rmap_item->rmap_list = *rmap_list;
1245 *rmap_list = rmap_item;
1247 return rmap_item;
1250 static struct rmap_item *scan_get_next_rmap_item(struct page **page)
1252 struct mm_struct *mm;
1253 struct mm_slot *slot;
1254 struct vm_area_struct *vma;
1255 struct rmap_item *rmap_item;
1257 if (list_empty(&ksm_mm_head.mm_list))
1258 return NULL;
1260 slot = ksm_scan.mm_slot;
1261 if (slot == &ksm_mm_head) {
1262 root_unstable_tree = RB_ROOT;
1264 spin_lock(&ksm_mmlist_lock);
1265 slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
1266 ksm_scan.mm_slot = slot;
1267 spin_unlock(&ksm_mmlist_lock);
1268 next_mm:
1269 ksm_scan.address = 0;
1270 ksm_scan.rmap_list = &slot->rmap_list;
1273 mm = slot->mm;
1274 down_read(&mm->mmap_sem);
1275 if (ksm_test_exit(mm))
1276 vma = NULL;
1277 else
1278 vma = find_vma(mm, ksm_scan.address);
1280 for (; vma; vma = vma->vm_next) {
1281 if (!(vma->vm_flags & VM_MERGEABLE))
1282 continue;
1283 if (ksm_scan.address < vma->vm_start)
1284 ksm_scan.address = vma->vm_start;
1285 if (!vma->anon_vma)
1286 ksm_scan.address = vma->vm_end;
1288 while (ksm_scan.address < vma->vm_end) {
1289 if (ksm_test_exit(mm))
1290 break;
1291 *page = follow_page(vma, ksm_scan.address, FOLL_GET);
1292 if (!IS_ERR_OR_NULL(*page) && PageAnon(*page)) {
1293 flush_anon_page(vma, *page, ksm_scan.address);
1294 flush_dcache_page(*page);
1295 rmap_item = get_next_rmap_item(slot,
1296 ksm_scan.rmap_list, ksm_scan.address);
1297 if (rmap_item) {
1298 ksm_scan.rmap_list =
1299 &rmap_item->rmap_list;
1300 ksm_scan.address += PAGE_SIZE;
1301 } else
1302 put_page(*page);
1303 up_read(&mm->mmap_sem);
1304 return rmap_item;
1306 if (!IS_ERR_OR_NULL(*page))
1307 put_page(*page);
1308 ksm_scan.address += PAGE_SIZE;
1309 cond_resched();
1313 if (ksm_test_exit(mm)) {
1314 ksm_scan.address = 0;
1315 ksm_scan.rmap_list = &slot->rmap_list;
1318 * Nuke all the rmap_items that are above this current rmap:
1319 * because there were no VM_MERGEABLE vmas with such addresses.
1321 remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
1323 spin_lock(&ksm_mmlist_lock);
1324 ksm_scan.mm_slot = list_entry(slot->mm_list.next,
1325 struct mm_slot, mm_list);
1326 if (ksm_scan.address == 0) {
1328 * We've completed a full scan of all vmas, holding mmap_sem
1329 * throughout, and found no VM_MERGEABLE: so do the same as
1330 * __ksm_exit does to remove this mm from all our lists now.
1331 * This applies either when cleaning up after __ksm_exit
1332 * (but beware: we can reach here even before __ksm_exit),
1333 * or when all VM_MERGEABLE areas have been unmapped (and
1334 * mmap_sem then protects against race with MADV_MERGEABLE).
1336 hlist_del(&slot->link);
1337 list_del(&slot->mm_list);
1338 spin_unlock(&ksm_mmlist_lock);
1340 free_mm_slot(slot);
1341 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1342 up_read(&mm->mmap_sem);
1343 mmdrop(mm);
1344 } else {
1345 spin_unlock(&ksm_mmlist_lock);
1346 up_read(&mm->mmap_sem);
1349 /* Repeat until we've completed scanning the whole list */
1350 slot = ksm_scan.mm_slot;
1351 if (slot != &ksm_mm_head)
1352 goto next_mm;
1354 ksm_scan.seqnr++;
1355 return NULL;
1359 * ksm_do_scan - the ksm scanner main worker function.
1360 * @scan_npages - number of pages we want to scan before we return.
1362 static void ksm_do_scan(unsigned int scan_npages)
1364 struct rmap_item *rmap_item;
1365 struct page *uninitialized_var(page);
1367 while (scan_npages--) {
1368 cond_resched();
1369 rmap_item = scan_get_next_rmap_item(&page);
1370 if (!rmap_item)
1371 return;
1372 if (!PageKsm(page) || !in_stable_tree(rmap_item))
1373 cmp_and_merge_page(page, rmap_item);
1374 put_page(page);
1378 static int ksmd_should_run(void)
1380 return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
1383 static int ksm_scan_thread(void *nothing)
1385 set_user_nice(current, 5);
1387 while (!kthread_should_stop()) {
1388 mutex_lock(&ksm_thread_mutex);
1389 if (ksmd_should_run())
1390 ksm_do_scan(ksm_thread_pages_to_scan);
1391 mutex_unlock(&ksm_thread_mutex);
1393 if (ksmd_should_run()) {
1394 schedule_timeout_interruptible(
1395 msecs_to_jiffies(ksm_thread_sleep_millisecs));
1396 } else {
1397 wait_event_interruptible(ksm_thread_wait,
1398 ksmd_should_run() || kthread_should_stop());
1401 return 0;
1404 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
1405 unsigned long end, int advice, unsigned long *vm_flags)
1407 struct mm_struct *mm = vma->vm_mm;
1408 int err;
1410 switch (advice) {
1411 case MADV_MERGEABLE:
1413 * Be somewhat over-protective for now!
1415 if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
1416 VM_PFNMAP | VM_IO | VM_DONTEXPAND |
1417 VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
1418 VM_NONLINEAR | VM_MIXEDMAP | VM_SAO))
1419 return 0; /* just ignore the advice */
1421 if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
1422 err = __ksm_enter(mm);
1423 if (err)
1424 return err;
1427 *vm_flags |= VM_MERGEABLE;
1428 break;
1430 case MADV_UNMERGEABLE:
1431 if (!(*vm_flags & VM_MERGEABLE))
1432 return 0; /* just ignore the advice */
1434 if (vma->anon_vma) {
1435 err = unmerge_ksm_pages(vma, start, end);
1436 if (err)
1437 return err;
1440 *vm_flags &= ~VM_MERGEABLE;
1441 break;
1444 return 0;
1447 int __ksm_enter(struct mm_struct *mm)
1449 struct mm_slot *mm_slot;
1450 int needs_wakeup;
1452 mm_slot = alloc_mm_slot();
1453 if (!mm_slot)
1454 return -ENOMEM;
1456 /* Check ksm_run too? Would need tighter locking */
1457 needs_wakeup = list_empty(&ksm_mm_head.mm_list);
1459 spin_lock(&ksm_mmlist_lock);
1460 insert_to_mm_slots_hash(mm, mm_slot);
1462 * Insert just behind the scanning cursor, to let the area settle
1463 * down a little; when fork is followed by immediate exec, we don't
1464 * want ksmd to waste time setting up and tearing down an rmap_list.
1466 list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
1467 spin_unlock(&ksm_mmlist_lock);
1469 set_bit(MMF_VM_MERGEABLE, &mm->flags);
1470 atomic_inc(&mm->mm_count);
1472 if (needs_wakeup)
1473 wake_up_interruptible(&ksm_thread_wait);
1475 return 0;
1478 void __ksm_exit(struct mm_struct *mm)
1480 struct mm_slot *mm_slot;
1481 int easy_to_free = 0;
1484 * This process is exiting: if it's straightforward (as is the
1485 * case when ksmd was never running), free mm_slot immediately.
1486 * But if it's at the cursor or has rmap_items linked to it, use
1487 * mmap_sem to synchronize with any break_cows before pagetables
1488 * are freed, and leave the mm_slot on the list for ksmd to free.
1489 * Beware: ksm may already have noticed it exiting and freed the slot.
1492 spin_lock(&ksm_mmlist_lock);
1493 mm_slot = get_mm_slot(mm);
1494 if (mm_slot && ksm_scan.mm_slot != mm_slot) {
1495 if (!mm_slot->rmap_list) {
1496 hlist_del(&mm_slot->link);
1497 list_del(&mm_slot->mm_list);
1498 easy_to_free = 1;
1499 } else {
1500 list_move(&mm_slot->mm_list,
1501 &ksm_scan.mm_slot->mm_list);
1504 spin_unlock(&ksm_mmlist_lock);
1506 if (easy_to_free) {
1507 free_mm_slot(mm_slot);
1508 clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1509 mmdrop(mm);
1510 } else if (mm_slot) {
1511 down_write(&mm->mmap_sem);
1512 up_write(&mm->mmap_sem);
1516 struct page *ksm_does_need_to_copy(struct page *page,
1517 struct vm_area_struct *vma, unsigned long address)
1519 struct page *new_page;
1521 unlock_page(page); /* any racers will COW it, not modify it */
1523 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
1524 if (new_page) {
1525 copy_user_highpage(new_page, page, address, vma);
1527 SetPageDirty(new_page);
1528 __SetPageUptodate(new_page);
1529 SetPageSwapBacked(new_page);
1530 __set_page_locked(new_page);
1532 if (page_evictable(new_page, vma))
1533 lru_cache_add_lru(new_page, LRU_ACTIVE_ANON);
1534 else
1535 add_page_to_unevictable_list(new_page);
1538 page_cache_release(page);
1539 return new_page;
1542 int page_referenced_ksm(struct page *page, struct mem_cgroup *memcg,
1543 unsigned long *vm_flags)
1545 struct stable_node *stable_node;
1546 struct rmap_item *rmap_item;
1547 struct hlist_node *hlist;
1548 unsigned int mapcount = page_mapcount(page);
1549 int referenced = 0;
1550 int search_new_forks = 0;
1552 VM_BUG_ON(!PageKsm(page));
1553 VM_BUG_ON(!PageLocked(page));
1555 stable_node = page_stable_node(page);
1556 if (!stable_node)
1557 return 0;
1558 again:
1559 hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
1560 struct anon_vma *anon_vma = rmap_item->anon_vma;
1561 struct anon_vma_chain *vmac;
1562 struct vm_area_struct *vma;
1564 anon_vma_lock(anon_vma);
1565 list_for_each_entry(vmac, &anon_vma->head, same_anon_vma) {
1566 vma = vmac->vma;
1567 if (rmap_item->address < vma->vm_start ||
1568 rmap_item->address >= vma->vm_end)
1569 continue;
1571 * Initially we examine only the vma which covers this
1572 * rmap_item; but later, if there is still work to do,
1573 * we examine covering vmas in other mms: in case they
1574 * were forked from the original since ksmd passed.
1576 if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
1577 continue;
1579 if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
1580 continue;
1582 referenced += page_referenced_one(page, vma,
1583 rmap_item->address, &mapcount, vm_flags);
1584 if (!search_new_forks || !mapcount)
1585 break;
1587 anon_vma_unlock(anon_vma);
1588 if (!mapcount)
1589 goto out;
1591 if (!search_new_forks++)
1592 goto again;
1593 out:
1594 return referenced;
1597 int try_to_unmap_ksm(struct page *page, enum ttu_flags flags)
1599 struct stable_node *stable_node;
1600 struct hlist_node *hlist;
1601 struct rmap_item *rmap_item;
1602 int ret = SWAP_AGAIN;
1603 int search_new_forks = 0;
1605 VM_BUG_ON(!PageKsm(page));
1606 VM_BUG_ON(!PageLocked(page));
1608 stable_node = page_stable_node(page);
1609 if (!stable_node)
1610 return SWAP_FAIL;
1611 again:
1612 hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
1613 struct anon_vma *anon_vma = rmap_item->anon_vma;
1614 struct anon_vma_chain *vmac;
1615 struct vm_area_struct *vma;
1617 anon_vma_lock(anon_vma);
1618 list_for_each_entry(vmac, &anon_vma->head, same_anon_vma) {
1619 vma = vmac->vma;
1620 if (rmap_item->address < vma->vm_start ||
1621 rmap_item->address >= vma->vm_end)
1622 continue;
1624 * Initially we examine only the vma which covers this
1625 * rmap_item; but later, if there is still work to do,
1626 * we examine covering vmas in other mms: in case they
1627 * were forked from the original since ksmd passed.
1629 if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
1630 continue;
1632 ret = try_to_unmap_one(page, vma,
1633 rmap_item->address, flags);
1634 if (ret != SWAP_AGAIN || !page_mapped(page)) {
1635 anon_vma_unlock(anon_vma);
1636 goto out;
1639 anon_vma_unlock(anon_vma);
1641 if (!search_new_forks++)
1642 goto again;
1643 out:
1644 return ret;
1647 #ifdef CONFIG_MIGRATION
1648 int rmap_walk_ksm(struct page *page, int (*rmap_one)(struct page *,
1649 struct vm_area_struct *, unsigned long, void *), void *arg)
1651 struct stable_node *stable_node;
1652 struct hlist_node *hlist;
1653 struct rmap_item *rmap_item;
1654 int ret = SWAP_AGAIN;
1655 int search_new_forks = 0;
1657 VM_BUG_ON(!PageKsm(page));
1658 VM_BUG_ON(!PageLocked(page));
1660 stable_node = page_stable_node(page);
1661 if (!stable_node)
1662 return ret;
1663 again:
1664 hlist_for_each_entry(rmap_item, hlist, &stable_node->hlist, hlist) {
1665 struct anon_vma *anon_vma = rmap_item->anon_vma;
1666 struct anon_vma_chain *vmac;
1667 struct vm_area_struct *vma;
1669 anon_vma_lock(anon_vma);
1670 list_for_each_entry(vmac, &anon_vma->head, same_anon_vma) {
1671 vma = vmac->vma;
1672 if (rmap_item->address < vma->vm_start ||
1673 rmap_item->address >= vma->vm_end)
1674 continue;
1676 * Initially we examine only the vma which covers this
1677 * rmap_item; but later, if there is still work to do,
1678 * we examine covering vmas in other mms: in case they
1679 * were forked from the original since ksmd passed.
1681 if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
1682 continue;
1684 ret = rmap_one(page, vma, rmap_item->address, arg);
1685 if (ret != SWAP_AGAIN) {
1686 anon_vma_unlock(anon_vma);
1687 goto out;
1690 anon_vma_unlock(anon_vma);
1692 if (!search_new_forks++)
1693 goto again;
1694 out:
1695 return ret;
1698 void ksm_migrate_page(struct page *newpage, struct page *oldpage)
1700 struct stable_node *stable_node;
1702 VM_BUG_ON(!PageLocked(oldpage));
1703 VM_BUG_ON(!PageLocked(newpage));
1704 VM_BUG_ON(newpage->mapping != oldpage->mapping);
1706 stable_node = page_stable_node(newpage);
1707 if (stable_node) {
1708 VM_BUG_ON(stable_node->kpfn != page_to_pfn(oldpage));
1709 stable_node->kpfn = page_to_pfn(newpage);
1712 #endif /* CONFIG_MIGRATION */
1714 #ifdef CONFIG_MEMORY_HOTREMOVE
1715 static struct stable_node *ksm_check_stable_tree(unsigned long start_pfn,
1716 unsigned long end_pfn)
1718 struct rb_node *node;
1720 for (node = rb_first(&root_stable_tree); node; node = rb_next(node)) {
1721 struct stable_node *stable_node;
1723 stable_node = rb_entry(node, struct stable_node, node);
1724 if (stable_node->kpfn >= start_pfn &&
1725 stable_node->kpfn < end_pfn)
1726 return stable_node;
1728 return NULL;
1731 static int ksm_memory_callback(struct notifier_block *self,
1732 unsigned long action, void *arg)
1734 struct memory_notify *mn = arg;
1735 struct stable_node *stable_node;
1737 switch (action) {
1738 case MEM_GOING_OFFLINE:
1740 * Keep it very simple for now: just lock out ksmd and
1741 * MADV_UNMERGEABLE while any memory is going offline.
1743 mutex_lock(&ksm_thread_mutex);
1744 break;
1746 case MEM_OFFLINE:
1748 * Most of the work is done by page migration; but there might
1749 * be a few stable_nodes left over, still pointing to struct
1750 * pages which have been offlined: prune those from the tree.
1752 while ((stable_node = ksm_check_stable_tree(mn->start_pfn,
1753 mn->start_pfn + mn->nr_pages)) != NULL)
1754 remove_node_from_stable_tree(stable_node);
1755 /* fallthrough */
1757 case MEM_CANCEL_OFFLINE:
1758 mutex_unlock(&ksm_thread_mutex);
1759 break;
1761 return NOTIFY_OK;
1763 #endif /* CONFIG_MEMORY_HOTREMOVE */
1765 #ifdef CONFIG_SYSFS
1767 * This all compiles without CONFIG_SYSFS, but is a waste of space.
1770 #define KSM_ATTR_RO(_name) \
1771 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
1772 #define KSM_ATTR(_name) \
1773 static struct kobj_attribute _name##_attr = \
1774 __ATTR(_name, 0644, _name##_show, _name##_store)
1776 static ssize_t sleep_millisecs_show(struct kobject *kobj,
1777 struct kobj_attribute *attr, char *buf)
1779 return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
1782 static ssize_t sleep_millisecs_store(struct kobject *kobj,
1783 struct kobj_attribute *attr,
1784 const char *buf, size_t count)
1786 unsigned long msecs;
1787 int err;
1789 err = strict_strtoul(buf, 10, &msecs);
1790 if (err || msecs > UINT_MAX)
1791 return -EINVAL;
1793 ksm_thread_sleep_millisecs = msecs;
1795 return count;
1797 KSM_ATTR(sleep_millisecs);
1799 static ssize_t pages_to_scan_show(struct kobject *kobj,
1800 struct kobj_attribute *attr, char *buf)
1802 return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
1805 static ssize_t pages_to_scan_store(struct kobject *kobj,
1806 struct kobj_attribute *attr,
1807 const char *buf, size_t count)
1809 int err;
1810 unsigned long nr_pages;
1812 err = strict_strtoul(buf, 10, &nr_pages);
1813 if (err || nr_pages > UINT_MAX)
1814 return -EINVAL;
1816 ksm_thread_pages_to_scan = nr_pages;
1818 return count;
1820 KSM_ATTR(pages_to_scan);
1822 static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
1823 char *buf)
1825 return sprintf(buf, "%u\n", ksm_run);
1828 static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
1829 const char *buf, size_t count)
1831 int err;
1832 unsigned long flags;
1834 err = strict_strtoul(buf, 10, &flags);
1835 if (err || flags > UINT_MAX)
1836 return -EINVAL;
1837 if (flags > KSM_RUN_UNMERGE)
1838 return -EINVAL;
1841 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
1842 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
1843 * breaking COW to free the pages_shared (but leaves mm_slots
1844 * on the list for when ksmd may be set running again).
1847 mutex_lock(&ksm_thread_mutex);
1848 if (ksm_run != flags) {
1849 ksm_run = flags;
1850 if (flags & KSM_RUN_UNMERGE) {
1851 current->flags |= PF_OOM_ORIGIN;
1852 err = unmerge_and_remove_all_rmap_items();
1853 current->flags &= ~PF_OOM_ORIGIN;
1854 if (err) {
1855 ksm_run = KSM_RUN_STOP;
1856 count = err;
1860 mutex_unlock(&ksm_thread_mutex);
1862 if (flags & KSM_RUN_MERGE)
1863 wake_up_interruptible(&ksm_thread_wait);
1865 return count;
1867 KSM_ATTR(run);
1869 static ssize_t pages_shared_show(struct kobject *kobj,
1870 struct kobj_attribute *attr, char *buf)
1872 return sprintf(buf, "%lu\n", ksm_pages_shared);
1874 KSM_ATTR_RO(pages_shared);
1876 static ssize_t pages_sharing_show(struct kobject *kobj,
1877 struct kobj_attribute *attr, char *buf)
1879 return sprintf(buf, "%lu\n", ksm_pages_sharing);
1881 KSM_ATTR_RO(pages_sharing);
1883 static ssize_t pages_unshared_show(struct kobject *kobj,
1884 struct kobj_attribute *attr, char *buf)
1886 return sprintf(buf, "%lu\n", ksm_pages_unshared);
1888 KSM_ATTR_RO(pages_unshared);
1890 static ssize_t pages_volatile_show(struct kobject *kobj,
1891 struct kobj_attribute *attr, char *buf)
1893 long ksm_pages_volatile;
1895 ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
1896 - ksm_pages_sharing - ksm_pages_unshared;
1898 * It was not worth any locking to calculate that statistic,
1899 * but it might therefore sometimes be negative: conceal that.
1901 if (ksm_pages_volatile < 0)
1902 ksm_pages_volatile = 0;
1903 return sprintf(buf, "%ld\n", ksm_pages_volatile);
1905 KSM_ATTR_RO(pages_volatile);
1907 static ssize_t full_scans_show(struct kobject *kobj,
1908 struct kobj_attribute *attr, char *buf)
1910 return sprintf(buf, "%lu\n", ksm_scan.seqnr);
1912 KSM_ATTR_RO(full_scans);
1914 static struct attribute *ksm_attrs[] = {
1915 &sleep_millisecs_attr.attr,
1916 &pages_to_scan_attr.attr,
1917 &run_attr.attr,
1918 &pages_shared_attr.attr,
1919 &pages_sharing_attr.attr,
1920 &pages_unshared_attr.attr,
1921 &pages_volatile_attr.attr,
1922 &full_scans_attr.attr,
1923 NULL,
1926 static struct attribute_group ksm_attr_group = {
1927 .attrs = ksm_attrs,
1928 .name = "ksm",
1930 #endif /* CONFIG_SYSFS */
1932 static int __init ksm_init(void)
1934 struct task_struct *ksm_thread;
1935 int err;
1937 err = ksm_slab_init();
1938 if (err)
1939 goto out;
1941 err = mm_slots_hash_init();
1942 if (err)
1943 goto out_free1;
1945 ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
1946 if (IS_ERR(ksm_thread)) {
1947 printk(KERN_ERR "ksm: creating kthread failed\n");
1948 err = PTR_ERR(ksm_thread);
1949 goto out_free2;
1952 #ifdef CONFIG_SYSFS
1953 err = sysfs_create_group(mm_kobj, &ksm_attr_group);
1954 if (err) {
1955 printk(KERN_ERR "ksm: register sysfs failed\n");
1956 kthread_stop(ksm_thread);
1957 goto out_free2;
1959 #else
1960 ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
1962 #endif /* CONFIG_SYSFS */
1964 #ifdef CONFIG_MEMORY_HOTREMOVE
1966 * Choose a high priority since the callback takes ksm_thread_mutex:
1967 * later callbacks could only be taking locks which nest within that.
1969 hotplug_memory_notifier(ksm_memory_callback, 100);
1970 #endif
1971 return 0;
1973 out_free2:
1974 mm_slots_hash_free();
1975 out_free1:
1976 ksm_slab_free();
1977 out:
1978 return err;
1980 module_init(ksm_init)