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