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