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