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