• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Memory merging support.
4  *
5  * This code enables dynamic sharing of identical pages found in different
6  * memory areas, even if they are not shared by fork()
7  *
8  * Copyright (C) 2008-2009 Red Hat, Inc.
9  * Authors:
10  *	Izik Eidus
11  *	Andrea Arcangeli
12  *	Chris Wright
13  *	Hugh Dickins
14  */
15 
16 #include <linux/errno.h>
17 #include <linux/mm.h>
18 #include <linux/fs.h>
19 #include <linux/mman.h>
20 #include <linux/sched.h>
21 #include <linux/sched/mm.h>
22 #include <linux/sched/coredump.h>
23 #include <linux/rwsem.h>
24 #include <linux/pagemap.h>
25 #include <linux/rmap.h>
26 #include <linux/spinlock.h>
27 #include <linux/xxhash.h>
28 #include <linux/delay.h>
29 #include <linux/kthread.h>
30 #include <linux/wait.h>
31 #include <linux/slab.h>
32 #include <linux/rbtree.h>
33 #include <linux/memory.h>
34 #include <linux/mmu_notifier.h>
35 #include <linux/swap.h>
36 #include <linux/ksm.h>
37 #include <linux/hashtable.h>
38 #include <linux/freezer.h>
39 #include <linux/oom.h>
40 #include <linux/numa.h>
41 
42 #include <asm/tlbflush.h>
43 #include "internal.h"
44 #include <linux/xpm.h>
45 
46 #ifdef CONFIG_NUMA
47 #define NUMA(x)		(x)
48 #define DO_NUMA(x)	do { (x); } while (0)
49 #else
50 #define NUMA(x)		(0)
51 #define DO_NUMA(x)	do { } while (0)
52 #endif
53 
54 /**
55  * DOC: Overview
56  *
57  * A few notes about the KSM scanning process,
58  * to make it easier to understand the data structures below:
59  *
60  * In order to reduce excessive scanning, KSM sorts the memory pages by their
61  * contents into a data structure that holds pointers to the pages' locations.
62  *
63  * Since the contents of the pages may change at any moment, KSM cannot just
64  * insert the pages into a normal sorted tree and expect it to find anything.
65  * Therefore KSM uses two data structures - the stable and the unstable tree.
66  *
67  * The stable tree holds pointers to all the merged pages (ksm pages), sorted
68  * by their contents.  Because each such page is write-protected, searching on
69  * this tree is fully assured to be working (except when pages are unmapped),
70  * and therefore this tree is called the stable tree.
71  *
72  * The stable tree node includes information required for reverse
73  * mapping from a KSM page to virtual addresses that map this page.
74  *
75  * In order to avoid large latencies of the rmap walks on KSM pages,
76  * KSM maintains two types of nodes in the stable tree:
77  *
78  * * the regular nodes that keep the reverse mapping structures in a
79  *   linked list
80  * * the "chains" that link nodes ("dups") that represent the same
81  *   write protected memory content, but each "dup" corresponds to a
82  *   different KSM page copy of that content
83  *
84  * Internally, the regular nodes, "dups" and "chains" are represented
85  * using the same struct stable_node structure.
86  *
87  * In addition to the stable tree, KSM uses a second data structure called the
88  * unstable tree: this tree holds pointers to pages which have been found to
89  * be "unchanged for a period of time".  The unstable tree sorts these pages
90  * by their contents, but since they are not write-protected, KSM cannot rely
91  * upon the unstable tree to work correctly - the unstable tree is liable to
92  * be corrupted as its contents are modified, and so it is called unstable.
93  *
94  * KSM solves this problem by several techniques:
95  *
96  * 1) The unstable tree is flushed every time KSM completes scanning all
97  *    memory areas, and then the tree is rebuilt again from the beginning.
98  * 2) KSM will only insert into the unstable tree, pages whose hash value
99  *    has not changed since the previous scan of all memory areas.
100  * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
101  *    colors of the nodes and not on their contents, assuring that even when
102  *    the tree gets "corrupted" it won't get out of balance, so scanning time
103  *    remains the same (also, searching and inserting nodes in an rbtree uses
104  *    the same algorithm, so we have no overhead when we flush and rebuild).
105  * 4) KSM never flushes the stable tree, which means that even if it were to
106  *    take 10 attempts to find a page in the unstable tree, once it is found,
107  *    it is secured in the stable tree.  (When we scan a new page, we first
108  *    compare it against the stable tree, and then against the unstable tree.)
109  *
110  * If the merge_across_nodes tunable is unset, then KSM maintains multiple
111  * stable trees and multiple unstable trees: one of each for each NUMA node.
112  */
113 
114 /**
115  * struct mm_slot - ksm information per mm that is being scanned
116  * @link: link to the mm_slots hash list
117  * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
118  * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
119  * @mm: the mm that this information is valid for
120  */
121 struct mm_slot {
122 	struct hlist_node link;
123 	struct list_head mm_list;
124 	struct rmap_item *rmap_list;
125 	struct mm_struct *mm;
126 };
127 
128 /**
129  * struct ksm_scan - cursor for scanning
130  * @mm_slot: the current mm_slot we are scanning
131  * @address: the next address inside that to be scanned
132  * @rmap_list: link to the next rmap to be scanned in the rmap_list
133  * @seqnr: count of completed full scans (needed when removing unstable node)
134  *
135  * There is only the one ksm_scan instance of this cursor structure.
136  */
137 struct ksm_scan {
138 	struct mm_slot *mm_slot;
139 	unsigned long address;
140 	struct rmap_item **rmap_list;
141 	unsigned long seqnr;
142 };
143 
144 /**
145  * struct stable_node - node of the stable rbtree
146  * @node: rb node of this ksm page in the stable tree
147  * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
148  * @hlist_dup: linked into the stable_node->hlist with a stable_node chain
149  * @list: linked into migrate_nodes, pending placement in the proper node tree
150  * @hlist: hlist head of rmap_items using this ksm page
151  * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
152  * @chain_prune_time: time of the last full garbage collection
153  * @rmap_hlist_len: number of rmap_item entries in hlist or STABLE_NODE_CHAIN
154  * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
155  */
156 struct stable_node {
157 	union {
158 		struct rb_node node;	/* when node of stable tree */
159 		struct {		/* when listed for migration */
160 			struct list_head *head;
161 			struct {
162 				struct hlist_node hlist_dup;
163 				struct list_head list;
164 			};
165 		};
166 	};
167 	struct hlist_head hlist;
168 	union {
169 		unsigned long kpfn;
170 		unsigned long chain_prune_time;
171 	};
172 	/*
173 	 * STABLE_NODE_CHAIN can be any negative number in
174 	 * rmap_hlist_len negative range, but better not -1 to be able
175 	 * to reliably detect underflows.
176 	 */
177 #define STABLE_NODE_CHAIN -1024
178 	int rmap_hlist_len;
179 #ifdef CONFIG_NUMA
180 	int nid;
181 #endif
182 };
183 
184 /**
185  * struct rmap_item - reverse mapping item for virtual addresses
186  * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
187  * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
188  * @nid: NUMA node id of unstable tree in which linked (may not match page)
189  * @mm: the memory structure this rmap_item is pointing into
190  * @address: the virtual address this rmap_item tracks (+ flags in low bits)
191  * @oldchecksum: previous checksum of the page at that virtual address
192  * @node: rb node of this rmap_item in the unstable tree
193  * @head: pointer to stable_node heading this list in the stable tree
194  * @hlist: link into hlist of rmap_items hanging off that stable_node
195  */
196 struct rmap_item {
197 	struct rmap_item *rmap_list;
198 	union {
199 		struct anon_vma *anon_vma;	/* when stable */
200 #ifdef CONFIG_NUMA
201 		int nid;		/* when node of unstable tree */
202 #endif
203 	};
204 	struct mm_struct *mm;
205 	unsigned long address;		/* + low bits used for flags below */
206 	unsigned int oldchecksum;	/* when unstable */
207 	union {
208 		struct rb_node node;	/* when node of unstable tree */
209 		struct {		/* when listed from stable tree */
210 			struct stable_node *head;
211 			struct hlist_node hlist;
212 		};
213 	};
214 };
215 
216 #define SEQNR_MASK	0x0ff	/* low bits of unstable tree seqnr */
217 #define UNSTABLE_FLAG	0x100	/* is a node of the unstable tree */
218 #define STABLE_FLAG	0x200	/* is listed from the stable tree */
219 #define KSM_FLAG_MASK	(SEQNR_MASK|UNSTABLE_FLAG|STABLE_FLAG)
220 				/* to mask all the flags */
221 
222 /* The stable and unstable tree heads */
223 static struct rb_root one_stable_tree[1] = { RB_ROOT };
224 static struct rb_root one_unstable_tree[1] = { RB_ROOT };
225 static struct rb_root *root_stable_tree = one_stable_tree;
226 static struct rb_root *root_unstable_tree = one_unstable_tree;
227 
228 /* Recently migrated nodes of stable tree, pending proper placement */
229 static LIST_HEAD(migrate_nodes);
230 #define STABLE_NODE_DUP_HEAD ((struct list_head *)&migrate_nodes.prev)
231 
232 #define MM_SLOTS_HASH_BITS 10
233 static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
234 
235 static struct mm_slot ksm_mm_head = {
236 	.mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
237 };
238 static struct ksm_scan ksm_scan = {
239 	.mm_slot = &ksm_mm_head,
240 };
241 
242 static struct kmem_cache *rmap_item_cache;
243 static struct kmem_cache *stable_node_cache;
244 static struct kmem_cache *mm_slot_cache;
245 
246 /* The number of nodes in the stable tree */
247 static unsigned long ksm_pages_shared;
248 
249 /* The number of page slots additionally sharing those nodes */
250 static unsigned long ksm_pages_sharing;
251 
252 /* The number of nodes in the unstable tree */
253 static unsigned long ksm_pages_unshared;
254 
255 /* The number of rmap_items in use: to calculate pages_volatile */
256 static unsigned long ksm_rmap_items;
257 
258 /* The number of stable_node chains */
259 static unsigned long ksm_stable_node_chains;
260 
261 /* The number of stable_node dups linked to the stable_node chains */
262 static unsigned long ksm_stable_node_dups;
263 
264 /* Delay in pruning stale stable_node_dups in the stable_node_chains */
265 static int ksm_stable_node_chains_prune_millisecs = 2000;
266 
267 /* Maximum number of page slots sharing a stable node */
268 static int ksm_max_page_sharing = 256;
269 
270 /* Number of pages ksmd should scan in one batch */
271 static unsigned int ksm_thread_pages_to_scan = 100;
272 
273 /* Milliseconds ksmd should sleep between batches */
274 static unsigned int ksm_thread_sleep_millisecs = 20;
275 
276 /* Checksum of an empty (zeroed) page */
277 static unsigned int zero_checksum __read_mostly;
278 
279 /* Whether to merge empty (zeroed) pages with actual zero pages */
280 static bool ksm_use_zero_pages __read_mostly;
281 
282 #ifdef CONFIG_NUMA
283 /* Zeroed when merging across nodes is not allowed */
284 static unsigned int ksm_merge_across_nodes = 1;
285 static int ksm_nr_node_ids = 1;
286 #else
287 #define ksm_merge_across_nodes	1U
288 #define ksm_nr_node_ids		1
289 #endif
290 
291 #define KSM_RUN_STOP	0
292 #define KSM_RUN_MERGE	1
293 #define KSM_RUN_UNMERGE	2
294 #define KSM_RUN_OFFLINE	4
295 static unsigned long ksm_run = KSM_RUN_STOP;
296 static void wait_while_offlining(void);
297 
298 static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
299 static DECLARE_WAIT_QUEUE_HEAD(ksm_iter_wait);
300 static DEFINE_MUTEX(ksm_thread_mutex);
301 static DEFINE_SPINLOCK(ksm_mmlist_lock);
302 
303 #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
304 		sizeof(struct __struct), __alignof__(struct __struct),\
305 		(__flags), NULL)
306 
ksm_slab_init(void)307 static int __init ksm_slab_init(void)
308 {
309 	rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
310 	if (!rmap_item_cache)
311 		goto out;
312 
313 	stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
314 	if (!stable_node_cache)
315 		goto out_free1;
316 
317 	mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
318 	if (!mm_slot_cache)
319 		goto out_free2;
320 
321 	return 0;
322 
323 out_free2:
324 	kmem_cache_destroy(stable_node_cache);
325 out_free1:
326 	kmem_cache_destroy(rmap_item_cache);
327 out:
328 	return -ENOMEM;
329 }
330 
ksm_slab_free(void)331 static void __init ksm_slab_free(void)
332 {
333 	kmem_cache_destroy(mm_slot_cache);
334 	kmem_cache_destroy(stable_node_cache);
335 	kmem_cache_destroy(rmap_item_cache);
336 	mm_slot_cache = NULL;
337 }
338 
is_stable_node_chain(struct stable_node * chain)339 static __always_inline bool is_stable_node_chain(struct stable_node *chain)
340 {
341 	return chain->rmap_hlist_len == STABLE_NODE_CHAIN;
342 }
343 
is_stable_node_dup(struct stable_node * dup)344 static __always_inline bool is_stable_node_dup(struct stable_node *dup)
345 {
346 	return dup->head == STABLE_NODE_DUP_HEAD;
347 }
348 
stable_node_chain_add_dup(struct stable_node * dup,struct stable_node * chain)349 static inline void stable_node_chain_add_dup(struct stable_node *dup,
350 					     struct stable_node *chain)
351 {
352 	VM_BUG_ON(is_stable_node_dup(dup));
353 	dup->head = STABLE_NODE_DUP_HEAD;
354 	VM_BUG_ON(!is_stable_node_chain(chain));
355 	hlist_add_head(&dup->hlist_dup, &chain->hlist);
356 	ksm_stable_node_dups++;
357 }
358 
__stable_node_dup_del(struct stable_node * dup)359 static inline void __stable_node_dup_del(struct stable_node *dup)
360 {
361 	VM_BUG_ON(!is_stable_node_dup(dup));
362 	hlist_del(&dup->hlist_dup);
363 	ksm_stable_node_dups--;
364 }
365 
stable_node_dup_del(struct stable_node * dup)366 static inline void stable_node_dup_del(struct stable_node *dup)
367 {
368 	VM_BUG_ON(is_stable_node_chain(dup));
369 	if (is_stable_node_dup(dup))
370 		__stable_node_dup_del(dup);
371 	else
372 		rb_erase(&dup->node, root_stable_tree + NUMA(dup->nid));
373 #ifdef CONFIG_DEBUG_VM
374 	dup->head = NULL;
375 #endif
376 }
377 
alloc_rmap_item(void)378 static inline struct rmap_item *alloc_rmap_item(void)
379 {
380 	struct rmap_item *rmap_item;
381 
382 	rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL |
383 						__GFP_NORETRY | __GFP_NOWARN);
384 	if (rmap_item)
385 		ksm_rmap_items++;
386 	return rmap_item;
387 }
388 
free_rmap_item(struct rmap_item * rmap_item)389 static inline void free_rmap_item(struct rmap_item *rmap_item)
390 {
391 	ksm_rmap_items--;
392 	rmap_item->mm = NULL;	/* debug safety */
393 	kmem_cache_free(rmap_item_cache, rmap_item);
394 }
395 
alloc_stable_node(void)396 static inline struct stable_node *alloc_stable_node(void)
397 {
398 	/*
399 	 * The allocation can take too long with GFP_KERNEL when memory is under
400 	 * pressure, which may lead to hung task warnings.  Adding __GFP_HIGH
401 	 * grants access to memory reserves, helping to avoid this problem.
402 	 */
403 	return kmem_cache_alloc(stable_node_cache, GFP_KERNEL | __GFP_HIGH);
404 }
405 
free_stable_node(struct stable_node * stable_node)406 static inline void free_stable_node(struct stable_node *stable_node)
407 {
408 	VM_BUG_ON(stable_node->rmap_hlist_len &&
409 		  !is_stable_node_chain(stable_node));
410 	kmem_cache_free(stable_node_cache, stable_node);
411 }
412 
alloc_mm_slot(void)413 static inline struct mm_slot *alloc_mm_slot(void)
414 {
415 	if (!mm_slot_cache)	/* initialization failed */
416 		return NULL;
417 	return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
418 }
419 
free_mm_slot(struct mm_slot * mm_slot)420 static inline void free_mm_slot(struct mm_slot *mm_slot)
421 {
422 	kmem_cache_free(mm_slot_cache, mm_slot);
423 }
424 
get_mm_slot(struct mm_struct * mm)425 static struct mm_slot *get_mm_slot(struct mm_struct *mm)
426 {
427 	struct mm_slot *slot;
428 
429 	hash_for_each_possible(mm_slots_hash, slot, link, (unsigned long)mm)
430 		if (slot->mm == mm)
431 			return slot;
432 
433 	return NULL;
434 }
435 
insert_to_mm_slots_hash(struct mm_struct * mm,struct mm_slot * mm_slot)436 static void insert_to_mm_slots_hash(struct mm_struct *mm,
437 				    struct mm_slot *mm_slot)
438 {
439 	mm_slot->mm = mm;
440 	hash_add(mm_slots_hash, &mm_slot->link, (unsigned long)mm);
441 }
442 
443 /*
444  * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
445  * page tables after it has passed through ksm_exit() - which, if necessary,
446  * takes mmap_lock briefly to serialize against them.  ksm_exit() does not set
447  * a special flag: they can just back out as soon as mm_users goes to zero.
448  * ksm_test_exit() is used throughout to make this test for exit: in some
449  * places for correctness, in some places just to avoid unnecessary work.
450  */
ksm_test_exit(struct mm_struct * mm)451 static inline bool ksm_test_exit(struct mm_struct *mm)
452 {
453 	return atomic_read(&mm->mm_users) == 0;
454 }
455 
456 /*
457  * We use break_ksm to break COW on a ksm page: it's a stripped down
458  *
459  *	if (get_user_pages(addr, 1, FOLL_WRITE, &page, NULL) == 1)
460  *		put_page(page);
461  *
462  * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
463  * in case the application has unmapped and remapped mm,addr meanwhile.
464  * Could a ksm page appear anywhere else?  Actually yes, in a VM_PFNMAP
465  * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
466  *
467  * FAULT_FLAG/FOLL_REMOTE are because we do this outside the context
468  * of the process that owns 'vma'.  We also do not want to enforce
469  * protection keys here anyway.
470  */
break_ksm(struct vm_area_struct * vma,unsigned long addr)471 static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
472 {
473 	struct page *page;
474 	vm_fault_t ret = 0;
475 
476 	do {
477 		cond_resched();
478 		page = follow_page(vma, addr,
479 				FOLL_GET | FOLL_MIGRATION | FOLL_REMOTE);
480 		if (IS_ERR_OR_NULL(page))
481 			break;
482 		if (PageKsm(page))
483 			ret = handle_mm_fault(vma, addr,
484 					      FAULT_FLAG_WRITE | FAULT_FLAG_REMOTE,
485 					      NULL);
486 		else
487 			ret = VM_FAULT_WRITE;
488 		put_page(page);
489 	} while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
490 	/*
491 	 * We must loop because handle_mm_fault() may back out if there's
492 	 * any difficulty e.g. if pte accessed bit gets updated concurrently.
493 	 *
494 	 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
495 	 * COW has been broken, even if the vma does not permit VM_WRITE;
496 	 * but note that a concurrent fault might break PageKsm for us.
497 	 *
498 	 * VM_FAULT_SIGBUS could occur if we race with truncation of the
499 	 * backing file, which also invalidates anonymous pages: that's
500 	 * okay, that truncation will have unmapped the PageKsm for us.
501 	 *
502 	 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
503 	 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
504 	 * current task has TIF_MEMDIE set, and will be OOM killed on return
505 	 * to user; and ksmd, having no mm, would never be chosen for that.
506 	 *
507 	 * But if the mm is in a limited mem_cgroup, then the fault may fail
508 	 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
509 	 * even ksmd can fail in this way - though it's usually breaking ksm
510 	 * just to undo a merge it made a moment before, so unlikely to oom.
511 	 *
512 	 * That's a pity: we might therefore have more kernel pages allocated
513 	 * than we're counting as nodes in the stable tree; but ksm_do_scan
514 	 * will retry to break_cow on each pass, so should recover the page
515 	 * in due course.  The important thing is to not let VM_MERGEABLE
516 	 * be cleared while any such pages might remain in the area.
517 	 */
518 	return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
519 }
520 
find_mergeable_vma(struct mm_struct * mm,unsigned long addr)521 static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
522 		unsigned long addr)
523 {
524 	struct vm_area_struct *vma;
525 	if (ksm_test_exit(mm))
526 		return NULL;
527 	vma = find_vma(mm, addr);
528 	if (!vma || vma->vm_start > addr)
529 		return NULL;
530 	if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
531 		return NULL;
532 	return vma;
533 }
534 
break_cow(struct rmap_item * rmap_item)535 static void break_cow(struct rmap_item *rmap_item)
536 {
537 	struct mm_struct *mm = rmap_item->mm;
538 	unsigned long addr = rmap_item->address;
539 	struct vm_area_struct *vma;
540 
541 	/*
542 	 * It is not an accident that whenever we want to break COW
543 	 * to undo, we also need to drop a reference to the anon_vma.
544 	 */
545 	put_anon_vma(rmap_item->anon_vma);
546 
547 	mmap_read_lock(mm);
548 	vma = find_mergeable_vma(mm, addr);
549 	if (vma)
550 		break_ksm(vma, addr);
551 	mmap_read_unlock(mm);
552 }
553 
get_mergeable_page(struct rmap_item * rmap_item)554 static struct page *get_mergeable_page(struct rmap_item *rmap_item)
555 {
556 	struct mm_struct *mm = rmap_item->mm;
557 	unsigned long addr = rmap_item->address;
558 	struct vm_area_struct *vma;
559 	struct page *page;
560 
561 	mmap_read_lock(mm);
562 	vma = find_mergeable_vma(mm, addr);
563 	if (!vma)
564 		goto out;
565 
566 	page = follow_page(vma, addr, FOLL_GET);
567 	if (IS_ERR_OR_NULL(page))
568 		goto out;
569 	if (PageAnon(page)) {
570 		flush_anon_page(vma, page, addr);
571 		flush_dcache_page(page);
572 	} else {
573 		put_page(page);
574 out:
575 		page = NULL;
576 	}
577 	mmap_read_unlock(mm);
578 	return page;
579 }
580 
581 /*
582  * This helper is used for getting right index into array of tree roots.
583  * When merge_across_nodes knob is set to 1, there are only two rb-trees for
584  * stable and unstable pages from all nodes with roots in index 0. Otherwise,
585  * every node has its own stable and unstable tree.
586  */
get_kpfn_nid(unsigned long kpfn)587 static inline int get_kpfn_nid(unsigned long kpfn)
588 {
589 	return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
590 }
591 
alloc_stable_node_chain(struct stable_node * dup,struct rb_root * root)592 static struct stable_node *alloc_stable_node_chain(struct stable_node *dup,
593 						   struct rb_root *root)
594 {
595 	struct stable_node *chain = alloc_stable_node();
596 	VM_BUG_ON(is_stable_node_chain(dup));
597 	if (likely(chain)) {
598 		INIT_HLIST_HEAD(&chain->hlist);
599 		chain->chain_prune_time = jiffies;
600 		chain->rmap_hlist_len = STABLE_NODE_CHAIN;
601 #if defined (CONFIG_DEBUG_VM) && defined(CONFIG_NUMA)
602 		chain->nid = NUMA_NO_NODE; /* debug */
603 #endif
604 		ksm_stable_node_chains++;
605 
606 		/*
607 		 * Put the stable node chain in the first dimension of
608 		 * the stable tree and at the same time remove the old
609 		 * stable node.
610 		 */
611 		rb_replace_node(&dup->node, &chain->node, root);
612 
613 		/*
614 		 * Move the old stable node to the second dimension
615 		 * queued in the hlist_dup. The invariant is that all
616 		 * dup stable_nodes in the chain->hlist point to pages
617 		 * that are write protected and have the exact same
618 		 * content.
619 		 */
620 		stable_node_chain_add_dup(dup, chain);
621 	}
622 	return chain;
623 }
624 
free_stable_node_chain(struct stable_node * chain,struct rb_root * root)625 static inline void free_stable_node_chain(struct stable_node *chain,
626 					  struct rb_root *root)
627 {
628 	rb_erase(&chain->node, root);
629 	free_stable_node(chain);
630 	ksm_stable_node_chains--;
631 }
632 
remove_node_from_stable_tree(struct stable_node * stable_node)633 static void remove_node_from_stable_tree(struct stable_node *stable_node)
634 {
635 	struct rmap_item *rmap_item;
636 
637 	/* check it's not STABLE_NODE_CHAIN or negative */
638 	BUG_ON(stable_node->rmap_hlist_len < 0);
639 
640 	hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
641 		if (rmap_item->hlist.next)
642 			ksm_pages_sharing--;
643 		else
644 			ksm_pages_shared--;
645 		VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
646 		stable_node->rmap_hlist_len--;
647 		put_anon_vma(rmap_item->anon_vma);
648 		rmap_item->address &= PAGE_MASK;
649 		cond_resched();
650 	}
651 
652 	/*
653 	 * We need the second aligned pointer of the migrate_nodes
654 	 * list_head to stay clear from the rb_parent_color union
655 	 * (aligned and different than any node) and also different
656 	 * from &migrate_nodes. This will verify that future list.h changes
657 	 * don't break STABLE_NODE_DUP_HEAD. Only recent gcc can handle it.
658 	 */
659 #if defined(GCC_VERSION) && GCC_VERSION >= 40903
660 	BUILD_BUG_ON(STABLE_NODE_DUP_HEAD <= &migrate_nodes);
661 	BUILD_BUG_ON(STABLE_NODE_DUP_HEAD >= &migrate_nodes + 1);
662 #endif
663 
664 	if (stable_node->head == &migrate_nodes)
665 		list_del(&stable_node->list);
666 	else
667 		stable_node_dup_del(stable_node);
668 	free_stable_node(stable_node);
669 }
670 
671 enum get_ksm_page_flags {
672 	GET_KSM_PAGE_NOLOCK,
673 	GET_KSM_PAGE_LOCK,
674 	GET_KSM_PAGE_TRYLOCK
675 };
676 
677 /*
678  * get_ksm_page: checks if the page indicated by the stable node
679  * is still its ksm page, despite having held no reference to it.
680  * In which case we can trust the content of the page, and it
681  * returns the gotten page; but if the page has now been zapped,
682  * remove the stale node from the stable tree and return NULL.
683  * But beware, the stable node's page might be being migrated.
684  *
685  * You would expect the stable_node to hold a reference to the ksm page.
686  * But if it increments the page's count, swapping out has to wait for
687  * ksmd to come around again before it can free the page, which may take
688  * seconds or even minutes: much too unresponsive.  So instead we use a
689  * "keyhole reference": access to the ksm page from the stable node peeps
690  * out through its keyhole to see if that page still holds the right key,
691  * pointing back to this stable node.  This relies on freeing a PageAnon
692  * page to reset its page->mapping to NULL, and relies on no other use of
693  * a page to put something that might look like our key in page->mapping.
694  * is on its way to being freed; but it is an anomaly to bear in mind.
695  */
get_ksm_page(struct stable_node * stable_node,enum get_ksm_page_flags flags)696 static struct page *get_ksm_page(struct stable_node *stable_node,
697 				 enum get_ksm_page_flags flags)
698 {
699 	struct page *page;
700 	void *expected_mapping;
701 	unsigned long kpfn;
702 
703 	expected_mapping = (void *)((unsigned long)stable_node |
704 					PAGE_MAPPING_KSM);
705 again:
706 	kpfn = READ_ONCE(stable_node->kpfn); /* Address dependency. */
707 	page = pfn_to_page(kpfn);
708 	if (READ_ONCE(page->mapping) != expected_mapping)
709 		goto stale;
710 
711 	/*
712 	 * We cannot do anything with the page while its refcount is 0.
713 	 * Usually 0 means free, or tail of a higher-order page: in which
714 	 * case this node is no longer referenced, and should be freed;
715 	 * however, it might mean that the page is under page_ref_freeze().
716 	 * The __remove_mapping() case is easy, again the node is now stale;
717 	 * the same is in reuse_ksm_page() case; but if page is swapcache
718 	 * in migrate_page_move_mapping(), it might still be our page,
719 	 * in which case it's essential to keep the node.
720 	 */
721 	while (!get_page_unless_zero(page)) {
722 		/*
723 		 * Another check for page->mapping != expected_mapping would
724 		 * work here too.  We have chosen the !PageSwapCache test to
725 		 * optimize the common case, when the page is or is about to
726 		 * be freed: PageSwapCache is cleared (under spin_lock_irq)
727 		 * in the ref_freeze section of __remove_mapping(); but Anon
728 		 * page->mapping reset to NULL later, in free_pages_prepare().
729 		 */
730 		if (!PageSwapCache(page))
731 			goto stale;
732 		cpu_relax();
733 	}
734 
735 	if (READ_ONCE(page->mapping) != expected_mapping) {
736 		put_page(page);
737 		goto stale;
738 	}
739 
740 	if (flags == GET_KSM_PAGE_TRYLOCK) {
741 		if (!trylock_page(page)) {
742 			put_page(page);
743 			return ERR_PTR(-EBUSY);
744 		}
745 	} else if (flags == GET_KSM_PAGE_LOCK)
746 		lock_page(page);
747 
748 	if (flags != GET_KSM_PAGE_NOLOCK) {
749 		if (READ_ONCE(page->mapping) != expected_mapping) {
750 			unlock_page(page);
751 			put_page(page);
752 			goto stale;
753 		}
754 	}
755 	return page;
756 
757 stale:
758 	/*
759 	 * We come here from above when page->mapping or !PageSwapCache
760 	 * suggests that the node is stale; but it might be under migration.
761 	 * We need smp_rmb(), matching the smp_wmb() in ksm_migrate_page(),
762 	 * before checking whether node->kpfn has been changed.
763 	 */
764 	smp_rmb();
765 	if (READ_ONCE(stable_node->kpfn) != kpfn)
766 		goto again;
767 	remove_node_from_stable_tree(stable_node);
768 	return NULL;
769 }
770 
771 /*
772  * Removing rmap_item from stable or unstable tree.
773  * This function will clean the information from the stable/unstable tree.
774  */
remove_rmap_item_from_tree(struct rmap_item * rmap_item)775 static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
776 {
777 	if (rmap_item->address & STABLE_FLAG) {
778 		struct stable_node *stable_node;
779 		struct page *page;
780 
781 		stable_node = rmap_item->head;
782 		page = get_ksm_page(stable_node, GET_KSM_PAGE_LOCK);
783 		if (!page)
784 			goto out;
785 
786 		hlist_del(&rmap_item->hlist);
787 		unlock_page(page);
788 		put_page(page);
789 
790 		if (!hlist_empty(&stable_node->hlist))
791 			ksm_pages_sharing--;
792 		else
793 			ksm_pages_shared--;
794 		VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
795 		stable_node->rmap_hlist_len--;
796 
797 		put_anon_vma(rmap_item->anon_vma);
798 		rmap_item->head = NULL;
799 		rmap_item->address &= PAGE_MASK;
800 
801 	} else if (rmap_item->address & UNSTABLE_FLAG) {
802 		unsigned char age;
803 		/*
804 		 * Usually ksmd can and must skip the rb_erase, because
805 		 * root_unstable_tree was already reset to RB_ROOT.
806 		 * But be careful when an mm is exiting: do the rb_erase
807 		 * if this rmap_item was inserted by this scan, rather
808 		 * than left over from before.
809 		 */
810 		age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
811 		BUG_ON(age > 1);
812 		if (!age)
813 			rb_erase(&rmap_item->node,
814 				 root_unstable_tree + NUMA(rmap_item->nid));
815 		ksm_pages_unshared--;
816 		rmap_item->address &= PAGE_MASK;
817 	}
818 out:
819 	cond_resched();		/* we're called from many long loops */
820 }
821 
remove_trailing_rmap_items(struct mm_slot * mm_slot,struct rmap_item ** rmap_list)822 static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
823 				       struct rmap_item **rmap_list)
824 {
825 	while (*rmap_list) {
826 		struct rmap_item *rmap_item = *rmap_list;
827 		*rmap_list = rmap_item->rmap_list;
828 		remove_rmap_item_from_tree(rmap_item);
829 		free_rmap_item(rmap_item);
830 	}
831 }
832 
833 /*
834  * Though it's very tempting to unmerge rmap_items from stable tree rather
835  * than check every pte of a given vma, the locking doesn't quite work for
836  * that - an rmap_item is assigned to the stable tree after inserting ksm
837  * page and upping mmap_lock.  Nor does it fit with the way we skip dup'ing
838  * rmap_items from parent to child at fork time (so as not to waste time
839  * if exit comes before the next scan reaches it).
840  *
841  * Similarly, although we'd like to remove rmap_items (so updating counts
842  * and freeing memory) when unmerging an area, it's easier to leave that
843  * to the next pass of ksmd - consider, for example, how ksmd might be
844  * in cmp_and_merge_page on one of the rmap_items we would be removing.
845  */
unmerge_ksm_pages(struct vm_area_struct * vma,unsigned long start,unsigned long end)846 static int unmerge_ksm_pages(struct vm_area_struct *vma,
847 			     unsigned long start, unsigned long end)
848 {
849 	unsigned long addr;
850 	int err = 0;
851 
852 	for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
853 		if (ksm_test_exit(vma->vm_mm))
854 			break;
855 		if (signal_pending(current))
856 			err = -ERESTARTSYS;
857 		else
858 			err = break_ksm(vma, addr);
859 	}
860 	return err;
861 }
862 
page_stable_node(struct page * page)863 static inline struct stable_node *page_stable_node(struct page *page)
864 {
865 	return PageKsm(page) ? page_rmapping(page) : NULL;
866 }
867 
set_page_stable_node(struct page * page,struct stable_node * stable_node)868 static inline void set_page_stable_node(struct page *page,
869 					struct stable_node *stable_node)
870 {
871 	page->mapping = (void *)((unsigned long)stable_node | PAGE_MAPPING_KSM);
872 }
873 
874 #ifdef CONFIG_SYSFS
875 /*
876  * Only called through the sysfs control interface:
877  */
remove_stable_node(struct stable_node * stable_node)878 static int remove_stable_node(struct stable_node *stable_node)
879 {
880 	struct page *page;
881 	int err;
882 
883 	page = get_ksm_page(stable_node, GET_KSM_PAGE_LOCK);
884 	if (!page) {
885 		/*
886 		 * get_ksm_page did remove_node_from_stable_tree itself.
887 		 */
888 		return 0;
889 	}
890 
891 	/*
892 	 * Page could be still mapped if this races with __mmput() running in
893 	 * between ksm_exit() and exit_mmap(). Just refuse to let
894 	 * merge_across_nodes/max_page_sharing be switched.
895 	 */
896 	err = -EBUSY;
897 	if (!page_mapped(page)) {
898 		/*
899 		 * The stable node did not yet appear stale to get_ksm_page(),
900 		 * since that allows for an unmapped ksm page to be recognized
901 		 * right up until it is freed; but the node is safe to remove.
902 		 * This page might be in a pagevec waiting to be freed,
903 		 * or it might be PageSwapCache (perhaps under writeback),
904 		 * or it might have been removed from swapcache a moment ago.
905 		 */
906 		set_page_stable_node(page, NULL);
907 		remove_node_from_stable_tree(stable_node);
908 		err = 0;
909 	}
910 
911 	unlock_page(page);
912 	put_page(page);
913 	return err;
914 }
915 
remove_stable_node_chain(struct stable_node * stable_node,struct rb_root * root)916 static int remove_stable_node_chain(struct stable_node *stable_node,
917 				    struct rb_root *root)
918 {
919 	struct stable_node *dup;
920 	struct hlist_node *hlist_safe;
921 
922 	if (!is_stable_node_chain(stable_node)) {
923 		VM_BUG_ON(is_stable_node_dup(stable_node));
924 		if (remove_stable_node(stable_node))
925 			return true;
926 		else
927 			return false;
928 	}
929 
930 	hlist_for_each_entry_safe(dup, hlist_safe,
931 				  &stable_node->hlist, hlist_dup) {
932 		VM_BUG_ON(!is_stable_node_dup(dup));
933 		if (remove_stable_node(dup))
934 			return true;
935 	}
936 	BUG_ON(!hlist_empty(&stable_node->hlist));
937 	free_stable_node_chain(stable_node, root);
938 	return false;
939 }
940 
remove_all_stable_nodes(void)941 static int remove_all_stable_nodes(void)
942 {
943 	struct stable_node *stable_node, *next;
944 	int nid;
945 	int err = 0;
946 
947 	for (nid = 0; nid < ksm_nr_node_ids; nid++) {
948 		while (root_stable_tree[nid].rb_node) {
949 			stable_node = rb_entry(root_stable_tree[nid].rb_node,
950 						struct stable_node, node);
951 			if (remove_stable_node_chain(stable_node,
952 						     root_stable_tree + nid)) {
953 				err = -EBUSY;
954 				break;	/* proceed to next nid */
955 			}
956 			cond_resched();
957 		}
958 	}
959 	list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
960 		if (remove_stable_node(stable_node))
961 			err = -EBUSY;
962 		cond_resched();
963 	}
964 	return err;
965 }
966 
unmerge_and_remove_all_rmap_items(void)967 static int unmerge_and_remove_all_rmap_items(void)
968 {
969 	struct mm_slot *mm_slot;
970 	struct mm_struct *mm;
971 	struct vm_area_struct *vma;
972 	int err = 0;
973 
974 	spin_lock(&ksm_mmlist_lock);
975 	ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
976 						struct mm_slot, mm_list);
977 	spin_unlock(&ksm_mmlist_lock);
978 
979 	for (mm_slot = ksm_scan.mm_slot;
980 			mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
981 		mm = mm_slot->mm;
982 		mmap_read_lock(mm);
983 		for (vma = mm->mmap; vma; vma = vma->vm_next) {
984 			if (ksm_test_exit(mm))
985 				break;
986 			if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
987 				continue;
988 			err = unmerge_ksm_pages(vma,
989 						vma->vm_start, vma->vm_end);
990 			if (err)
991 				goto error;
992 		}
993 
994 		remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
995 		mmap_read_unlock(mm);
996 
997 		spin_lock(&ksm_mmlist_lock);
998 		ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
999 						struct mm_slot, mm_list);
1000 		if (ksm_test_exit(mm)) {
1001 			hash_del(&mm_slot->link);
1002 			list_del(&mm_slot->mm_list);
1003 			spin_unlock(&ksm_mmlist_lock);
1004 
1005 			free_mm_slot(mm_slot);
1006 			clear_bit(MMF_VM_MERGEABLE, &mm->flags);
1007 			mmdrop(mm);
1008 		} else
1009 			spin_unlock(&ksm_mmlist_lock);
1010 	}
1011 
1012 	/* Clean up stable nodes, but don't worry if some are still busy */
1013 	remove_all_stable_nodes();
1014 	ksm_scan.seqnr = 0;
1015 	return 0;
1016 
1017 error:
1018 	mmap_read_unlock(mm);
1019 	spin_lock(&ksm_mmlist_lock);
1020 	ksm_scan.mm_slot = &ksm_mm_head;
1021 	spin_unlock(&ksm_mmlist_lock);
1022 	return err;
1023 }
1024 #endif /* CONFIG_SYSFS */
1025 
calc_checksum(struct page * page)1026 static u32 calc_checksum(struct page *page)
1027 {
1028 	u32 checksum;
1029 	void *addr = kmap_atomic(page);
1030 	checksum = xxhash(addr, PAGE_SIZE, 0);
1031 	kunmap_atomic(addr);
1032 	return checksum;
1033 }
1034 
write_protect_page(struct vm_area_struct * vma,struct page * page,pte_t * orig_pte)1035 static int write_protect_page(struct vm_area_struct *vma, struct page *page,
1036 			      pte_t *orig_pte)
1037 {
1038 	struct mm_struct *mm = vma->vm_mm;
1039 	struct page_vma_mapped_walk pvmw = {
1040 		.page = page,
1041 		.vma = vma,
1042 	};
1043 	int swapped;
1044 	int err = -EFAULT;
1045 	struct mmu_notifier_range range;
1046 
1047 	pvmw.address = page_address_in_vma(page, vma);
1048 	if (pvmw.address == -EFAULT)
1049 		goto out;
1050 
1051 	BUG_ON(PageTransCompound(page));
1052 
1053 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
1054 				pvmw.address,
1055 				pvmw.address + PAGE_SIZE);
1056 	mmu_notifier_invalidate_range_start(&range);
1057 
1058 	if (!page_vma_mapped_walk(&pvmw))
1059 		goto out_mn;
1060 	if (WARN_ONCE(!pvmw.pte, "Unexpected PMD mapping?"))
1061 		goto out_unlock;
1062 
1063 	if (pte_write(*pvmw.pte) || pte_dirty(*pvmw.pte) ||
1064 	    (pte_protnone(*pvmw.pte) && pte_savedwrite(*pvmw.pte)) ||
1065 						mm_tlb_flush_pending(mm)) {
1066 		pte_t entry;
1067 
1068 		swapped = PageSwapCache(page);
1069 		flush_cache_page(vma, pvmw.address, page_to_pfn(page));
1070 		/*
1071 		 * Ok this is tricky, when get_user_pages_fast() run it doesn't
1072 		 * take any lock, therefore the check that we are going to make
1073 		 * with the pagecount against the mapcount is racey and
1074 		 * O_DIRECT can happen right after the check.
1075 		 * So we clear the pte and flush the tlb before the check
1076 		 * this assure us that no O_DIRECT can happen after the check
1077 		 * or in the middle of the check.
1078 		 *
1079 		 * No need to notify as we are downgrading page table to read
1080 		 * only not changing it to point to a new page.
1081 		 *
1082 		 * See Documentation/vm/mmu_notifier.rst
1083 		 */
1084 		entry = ptep_clear_flush(vma, pvmw.address, pvmw.pte);
1085 		/*
1086 		 * Check that no O_DIRECT or similar I/O is in progress on the
1087 		 * page
1088 		 */
1089 		if (page_mapcount(page) + 1 + swapped != page_count(page)) {
1090 			set_pte_at(mm, pvmw.address, pvmw.pte, entry);
1091 			goto out_unlock;
1092 		}
1093 		if (pte_dirty(entry))
1094 			set_page_dirty(page);
1095 
1096 		if (pte_protnone(entry))
1097 			entry = pte_mkclean(pte_clear_savedwrite(entry));
1098 		else
1099 			entry = pte_mkclean(pte_wrprotect(entry));
1100 		set_pte_at_notify(mm, pvmw.address, pvmw.pte, entry);
1101 	}
1102 	*orig_pte = *pvmw.pte;
1103 	err = 0;
1104 
1105 out_unlock:
1106 	page_vma_mapped_walk_done(&pvmw);
1107 out_mn:
1108 	mmu_notifier_invalidate_range_end(&range);
1109 out:
1110 	return err;
1111 }
1112 
1113 /**
1114  * replace_page - replace page in vma by new ksm page
1115  * @vma:      vma that holds the pte pointing to page
1116  * @page:     the page we are replacing by kpage
1117  * @kpage:    the ksm page we replace page by
1118  * @orig_pte: the original value of the pte
1119  *
1120  * Returns 0 on success, -EFAULT on failure.
1121  */
replace_page(struct vm_area_struct * vma,struct page * page,struct page * kpage,pte_t orig_pte)1122 static int replace_page(struct vm_area_struct *vma, struct page *page,
1123 			struct page *kpage, pte_t orig_pte)
1124 {
1125 	struct mm_struct *mm = vma->vm_mm;
1126 	pmd_t *pmd;
1127 	pte_t *ptep;
1128 	pte_t newpte;
1129 	spinlock_t *ptl;
1130 	unsigned long addr;
1131 	int err = -EFAULT;
1132 	struct mmu_notifier_range range;
1133 
1134 	addr = page_address_in_vma(page, vma);
1135 	if (addr == -EFAULT)
1136 		goto out;
1137 
1138 	pmd = mm_find_pmd(mm, addr);
1139 	if (!pmd)
1140 		goto out;
1141 
1142 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, addr,
1143 				addr + PAGE_SIZE);
1144 	mmu_notifier_invalidate_range_start(&range);
1145 
1146 	ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
1147 	if (!pte_same(*ptep, orig_pte)) {
1148 		pte_unmap_unlock(ptep, ptl);
1149 		goto out_mn;
1150 	}
1151 
1152 	/*
1153 	 * No need to check ksm_use_zero_pages here: we can only have a
1154 	 * zero_page here if ksm_use_zero_pages was enabled already.
1155 	 */
1156 	if (!is_zero_pfn(page_to_pfn(kpage))) {
1157 		get_page(kpage);
1158 		page_add_anon_rmap(kpage, vma, addr, false);
1159 		newpte = mk_pte(kpage, vma->vm_page_prot);
1160 	} else {
1161 		newpte = pte_mkspecial(pfn_pte(page_to_pfn(kpage),
1162 					       vma->vm_page_prot));
1163 		/*
1164 		 * We're replacing an anonymous page with a zero page, which is
1165 		 * not anonymous. We need to do proper accounting otherwise we
1166 		 * will get wrong values in /proc, and a BUG message in dmesg
1167 		 * when tearing down the mm.
1168 		 */
1169 		dec_mm_counter(mm, MM_ANONPAGES);
1170 	}
1171 
1172 	flush_cache_page(vma, addr, pte_pfn(*ptep));
1173 	/*
1174 	 * No need to notify as we are replacing a read only page with another
1175 	 * read only page with the same content.
1176 	 *
1177 	 * See Documentation/vm/mmu_notifier.rst
1178 	 */
1179 	ptep_clear_flush(vma, addr, ptep);
1180 	set_pte_at_notify(mm, addr, ptep, newpte);
1181 
1182 	page_remove_rmap(page, false);
1183 	if (!page_mapped(page))
1184 		try_to_free_swap(page);
1185 	put_page(page);
1186 
1187 	pte_unmap_unlock(ptep, ptl);
1188 	err = 0;
1189 out_mn:
1190 	mmu_notifier_invalidate_range_end(&range);
1191 out:
1192 	return err;
1193 }
1194 
1195 /*
1196  * try_to_merge_one_page - take two pages and merge them into one
1197  * @vma: the vma that holds the pte pointing to page
1198  * @page: the PageAnon page that we want to replace with kpage
1199  * @kpage: the PageKsm page that we want to map instead of page,
1200  *         or NULL the first time when we want to use page as kpage.
1201  *
1202  * This function returns 0 if the pages were merged, -EFAULT otherwise.
1203  */
try_to_merge_one_page(struct vm_area_struct * vma,struct page * page,struct page * kpage)1204 static int try_to_merge_one_page(struct vm_area_struct *vma,
1205 				 struct page *page, struct page *kpage)
1206 {
1207 	pte_t orig_pte = __pte(0);
1208 	int err = -EFAULT;
1209 
1210 	if (page == kpage)			/* ksm page forked */
1211 		return 0;
1212 
1213 	if (!PageAnon(page))
1214 		goto out;
1215 
1216 	if(!xpm_integrity_check_one_page_merge(page, kpage))
1217 		goto out;
1218 
1219 	/*
1220 	 * We need the page lock to read a stable PageSwapCache in
1221 	 * write_protect_page().  We use trylock_page() instead of
1222 	 * lock_page() because we don't want to wait here - we
1223 	 * prefer to continue scanning and merging different pages,
1224 	 * then come back to this page when it is unlocked.
1225 	 */
1226 	if (!trylock_page(page))
1227 		goto out;
1228 
1229 	if (PageTransCompound(page)) {
1230 		if (split_huge_page(page))
1231 			goto out_unlock;
1232 	}
1233 
1234 	/*
1235 	 * If this anonymous page is mapped only here, its pte may need
1236 	 * to be write-protected.  If it's mapped elsewhere, all of its
1237 	 * ptes are necessarily already write-protected.  But in either
1238 	 * case, we need to lock and check page_count is not raised.
1239 	 */
1240 	if (write_protect_page(vma, page, &orig_pte) == 0) {
1241 		if (!kpage) {
1242 			/*
1243 			 * While we hold page lock, upgrade page from
1244 			 * PageAnon+anon_vma to PageKsm+NULL stable_node:
1245 			 * stable_tree_insert() will update stable_node.
1246 			 */
1247 			set_page_stable_node(page, NULL);
1248 			mark_page_accessed(page);
1249 			/*
1250 			 * Page reclaim just frees a clean page with no dirty
1251 			 * ptes: make sure that the ksm page would be swapped.
1252 			 */
1253 			if (!PageDirty(page))
1254 				SetPageDirty(page);
1255 			err = 0;
1256 		} else if (pages_identical(page, kpage))
1257 			err = replace_page(vma, page, kpage, orig_pte);
1258 	}
1259 
1260 	if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
1261 		munlock_vma_page(page);
1262 		if (!PageMlocked(kpage)) {
1263 			unlock_page(page);
1264 			lock_page(kpage);
1265 			mlock_vma_page(kpage);
1266 			page = kpage;		/* for final unlock */
1267 		}
1268 	}
1269 
1270 out_unlock:
1271 	unlock_page(page);
1272 out:
1273 	return err;
1274 }
1275 
1276 /*
1277  * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
1278  * but no new kernel page is allocated: kpage must already be a ksm page.
1279  *
1280  * This function returns 0 if the pages were merged, -EFAULT otherwise.
1281  */
try_to_merge_with_ksm_page(struct rmap_item * rmap_item,struct page * page,struct page * kpage)1282 static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
1283 				      struct page *page, struct page *kpage)
1284 {
1285 	struct mm_struct *mm = rmap_item->mm;
1286 	struct vm_area_struct *vma;
1287 	int err = -EFAULT;
1288 
1289 	mmap_read_lock(mm);
1290 	vma = find_mergeable_vma(mm, rmap_item->address);
1291 	if (!vma)
1292 		goto out;
1293 
1294 	err = try_to_merge_one_page(vma, page, kpage);
1295 	if (err)
1296 		goto out;
1297 
1298 	/* Unstable nid is in union with stable anon_vma: remove first */
1299 	remove_rmap_item_from_tree(rmap_item);
1300 
1301 	/* Must get reference to anon_vma while still holding mmap_lock */
1302 	rmap_item->anon_vma = vma->anon_vma;
1303 	get_anon_vma(vma->anon_vma);
1304 out:
1305 	mmap_read_unlock(mm);
1306 	return err;
1307 }
1308 
1309 /*
1310  * try_to_merge_two_pages - take two identical pages and prepare them
1311  * to be merged into one page.
1312  *
1313  * This function returns the kpage if we successfully merged two identical
1314  * pages into one ksm page, NULL otherwise.
1315  *
1316  * Note that this function upgrades page to ksm page: if one of the pages
1317  * is already a ksm page, try_to_merge_with_ksm_page should be used.
1318  */
try_to_merge_two_pages(struct rmap_item * rmap_item,struct page * page,struct rmap_item * tree_rmap_item,struct page * tree_page)1319 static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
1320 					   struct page *page,
1321 					   struct rmap_item *tree_rmap_item,
1322 					   struct page *tree_page)
1323 {
1324 	int err;
1325 
1326 	err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
1327 	if (!err) {
1328 		err = try_to_merge_with_ksm_page(tree_rmap_item,
1329 							tree_page, page);
1330 		/*
1331 		 * If that fails, we have a ksm page with only one pte
1332 		 * pointing to it: so break it.
1333 		 */
1334 		if (err)
1335 			break_cow(rmap_item);
1336 	}
1337 	return err ? NULL : page;
1338 }
1339 
1340 static __always_inline
__is_page_sharing_candidate(struct stable_node * stable_node,int offset)1341 bool __is_page_sharing_candidate(struct stable_node *stable_node, int offset)
1342 {
1343 	VM_BUG_ON(stable_node->rmap_hlist_len < 0);
1344 	/*
1345 	 * Check that at least one mapping still exists, otherwise
1346 	 * there's no much point to merge and share with this
1347 	 * stable_node, as the underlying tree_page of the other
1348 	 * sharer is going to be freed soon.
1349 	 */
1350 	return stable_node->rmap_hlist_len &&
1351 		stable_node->rmap_hlist_len + offset < ksm_max_page_sharing;
1352 }
1353 
1354 static __always_inline
is_page_sharing_candidate(struct stable_node * stable_node)1355 bool is_page_sharing_candidate(struct stable_node *stable_node)
1356 {
1357 	return __is_page_sharing_candidate(stable_node, 0);
1358 }
1359 
stable_node_dup(struct stable_node ** _stable_node_dup,struct stable_node ** _stable_node,struct rb_root * root,bool prune_stale_stable_nodes)1360 static struct page *stable_node_dup(struct stable_node **_stable_node_dup,
1361 				    struct stable_node **_stable_node,
1362 				    struct rb_root *root,
1363 				    bool prune_stale_stable_nodes)
1364 {
1365 	struct stable_node *dup, *found = NULL, *stable_node = *_stable_node;
1366 	struct hlist_node *hlist_safe;
1367 	struct page *_tree_page, *tree_page = NULL;
1368 	int nr = 0;
1369 	int found_rmap_hlist_len;
1370 
1371 	if (!prune_stale_stable_nodes ||
1372 	    time_before(jiffies, stable_node->chain_prune_time +
1373 			msecs_to_jiffies(
1374 				ksm_stable_node_chains_prune_millisecs)))
1375 		prune_stale_stable_nodes = false;
1376 	else
1377 		stable_node->chain_prune_time = jiffies;
1378 
1379 	hlist_for_each_entry_safe(dup, hlist_safe,
1380 				  &stable_node->hlist, hlist_dup) {
1381 		cond_resched();
1382 		/*
1383 		 * We must walk all stable_node_dup to prune the stale
1384 		 * stable nodes during lookup.
1385 		 *
1386 		 * get_ksm_page can drop the nodes from the
1387 		 * stable_node->hlist if they point to freed pages
1388 		 * (that's why we do a _safe walk). The "dup"
1389 		 * stable_node parameter itself will be freed from
1390 		 * under us if it returns NULL.
1391 		 */
1392 		_tree_page = get_ksm_page(dup, GET_KSM_PAGE_NOLOCK);
1393 		if (!_tree_page)
1394 			continue;
1395 		nr += 1;
1396 		if (is_page_sharing_candidate(dup)) {
1397 			if (!found ||
1398 			    dup->rmap_hlist_len > found_rmap_hlist_len) {
1399 				if (found)
1400 					put_page(tree_page);
1401 				found = dup;
1402 				found_rmap_hlist_len = found->rmap_hlist_len;
1403 				tree_page = _tree_page;
1404 
1405 				/* skip put_page for found dup */
1406 				if (!prune_stale_stable_nodes)
1407 					break;
1408 				continue;
1409 			}
1410 		}
1411 		put_page(_tree_page);
1412 	}
1413 
1414 	if (found) {
1415 		/*
1416 		 * nr is counting all dups in the chain only if
1417 		 * prune_stale_stable_nodes is true, otherwise we may
1418 		 * break the loop at nr == 1 even if there are
1419 		 * multiple entries.
1420 		 */
1421 		if (prune_stale_stable_nodes && nr == 1) {
1422 			/*
1423 			 * If there's not just one entry it would
1424 			 * corrupt memory, better BUG_ON. In KSM
1425 			 * context with no lock held it's not even
1426 			 * fatal.
1427 			 */
1428 			BUG_ON(stable_node->hlist.first->next);
1429 
1430 			/*
1431 			 * There's just one entry and it is below the
1432 			 * deduplication limit so drop the chain.
1433 			 */
1434 			rb_replace_node(&stable_node->node, &found->node,
1435 					root);
1436 			free_stable_node(stable_node);
1437 			ksm_stable_node_chains--;
1438 			ksm_stable_node_dups--;
1439 			/*
1440 			 * NOTE: the caller depends on the stable_node
1441 			 * to be equal to stable_node_dup if the chain
1442 			 * was collapsed.
1443 			 */
1444 			*_stable_node = found;
1445 			/*
1446 			 * Just for robustneess as stable_node is
1447 			 * otherwise left as a stable pointer, the
1448 			 * compiler shall optimize it away at build
1449 			 * time.
1450 			 */
1451 			stable_node = NULL;
1452 		} else if (stable_node->hlist.first != &found->hlist_dup &&
1453 			   __is_page_sharing_candidate(found, 1)) {
1454 			/*
1455 			 * If the found stable_node dup can accept one
1456 			 * more future merge (in addition to the one
1457 			 * that is underway) and is not at the head of
1458 			 * the chain, put it there so next search will
1459 			 * be quicker in the !prune_stale_stable_nodes
1460 			 * case.
1461 			 *
1462 			 * NOTE: it would be inaccurate to use nr > 1
1463 			 * instead of checking the hlist.first pointer
1464 			 * directly, because in the
1465 			 * prune_stale_stable_nodes case "nr" isn't
1466 			 * the position of the found dup in the chain,
1467 			 * but the total number of dups in the chain.
1468 			 */
1469 			hlist_del(&found->hlist_dup);
1470 			hlist_add_head(&found->hlist_dup,
1471 				       &stable_node->hlist);
1472 		}
1473 	}
1474 
1475 	*_stable_node_dup = found;
1476 	return tree_page;
1477 }
1478 
stable_node_dup_any(struct stable_node * stable_node,struct rb_root * root)1479 static struct stable_node *stable_node_dup_any(struct stable_node *stable_node,
1480 					       struct rb_root *root)
1481 {
1482 	if (!is_stable_node_chain(stable_node))
1483 		return stable_node;
1484 	if (hlist_empty(&stable_node->hlist)) {
1485 		free_stable_node_chain(stable_node, root);
1486 		return NULL;
1487 	}
1488 	return hlist_entry(stable_node->hlist.first,
1489 			   typeof(*stable_node), hlist_dup);
1490 }
1491 
1492 /*
1493  * Like for get_ksm_page, this function can free the *_stable_node and
1494  * *_stable_node_dup if the returned tree_page is NULL.
1495  *
1496  * It can also free and overwrite *_stable_node with the found
1497  * stable_node_dup if the chain is collapsed (in which case
1498  * *_stable_node will be equal to *_stable_node_dup like if the chain
1499  * never existed). It's up to the caller to verify tree_page is not
1500  * NULL before dereferencing *_stable_node or *_stable_node_dup.
1501  *
1502  * *_stable_node_dup is really a second output parameter of this
1503  * function and will be overwritten in all cases, the caller doesn't
1504  * need to initialize it.
1505  */
__stable_node_chain(struct stable_node ** _stable_node_dup,struct stable_node ** _stable_node,struct rb_root * root,bool prune_stale_stable_nodes)1506 static struct page *__stable_node_chain(struct stable_node **_stable_node_dup,
1507 					struct stable_node **_stable_node,
1508 					struct rb_root *root,
1509 					bool prune_stale_stable_nodes)
1510 {
1511 	struct stable_node *stable_node = *_stable_node;
1512 	if (!is_stable_node_chain(stable_node)) {
1513 		if (is_page_sharing_candidate(stable_node)) {
1514 			*_stable_node_dup = stable_node;
1515 			return get_ksm_page(stable_node, GET_KSM_PAGE_NOLOCK);
1516 		}
1517 		/*
1518 		 * _stable_node_dup set to NULL means the stable_node
1519 		 * reached the ksm_max_page_sharing limit.
1520 		 */
1521 		*_stable_node_dup = NULL;
1522 		return NULL;
1523 	}
1524 	return stable_node_dup(_stable_node_dup, _stable_node, root,
1525 			       prune_stale_stable_nodes);
1526 }
1527 
chain_prune(struct stable_node ** s_n_d,struct stable_node ** s_n,struct rb_root * root)1528 static __always_inline struct page *chain_prune(struct stable_node **s_n_d,
1529 						struct stable_node **s_n,
1530 						struct rb_root *root)
1531 {
1532 	return __stable_node_chain(s_n_d, s_n, root, true);
1533 }
1534 
chain(struct stable_node ** s_n_d,struct stable_node * s_n,struct rb_root * root)1535 static __always_inline struct page *chain(struct stable_node **s_n_d,
1536 					  struct stable_node *s_n,
1537 					  struct rb_root *root)
1538 {
1539 	struct stable_node *old_stable_node = s_n;
1540 	struct page *tree_page;
1541 
1542 	tree_page = __stable_node_chain(s_n_d, &s_n, root, false);
1543 	/* not pruning dups so s_n cannot have changed */
1544 	VM_BUG_ON(s_n != old_stable_node);
1545 	return tree_page;
1546 }
1547 
1548 /*
1549  * stable_tree_search - search for page inside the stable tree
1550  *
1551  * This function checks if there is a page inside the stable tree
1552  * with identical content to the page that we are scanning right now.
1553  *
1554  * This function returns the stable tree node of identical content if found,
1555  * NULL otherwise.
1556  */
stable_tree_search(struct page * page)1557 static struct page *stable_tree_search(struct page *page)
1558 {
1559 	int nid;
1560 	struct rb_root *root;
1561 	struct rb_node **new;
1562 	struct rb_node *parent;
1563 	struct stable_node *stable_node, *stable_node_dup, *stable_node_any;
1564 	struct stable_node *page_node;
1565 
1566 	page_node = page_stable_node(page);
1567 	if (page_node && page_node->head != &migrate_nodes) {
1568 		/* ksm page forked */
1569 		get_page(page);
1570 		return page;
1571 	}
1572 
1573 	nid = get_kpfn_nid(page_to_pfn(page));
1574 	root = root_stable_tree + nid;
1575 again:
1576 	new = &root->rb_node;
1577 	parent = NULL;
1578 
1579 	while (*new) {
1580 		struct page *tree_page;
1581 		int ret;
1582 
1583 		cond_resched();
1584 		stable_node = rb_entry(*new, struct stable_node, node);
1585 		stable_node_any = NULL;
1586 		tree_page = chain_prune(&stable_node_dup, &stable_node,	root);
1587 		/*
1588 		 * NOTE: stable_node may have been freed by
1589 		 * chain_prune() if the returned stable_node_dup is
1590 		 * not NULL. stable_node_dup may have been inserted in
1591 		 * the rbtree instead as a regular stable_node (in
1592 		 * order to collapse the stable_node chain if a single
1593 		 * stable_node dup was found in it). In such case the
1594 		 * stable_node is overwritten by the calleee to point
1595 		 * to the stable_node_dup that was collapsed in the
1596 		 * stable rbtree and stable_node will be equal to
1597 		 * stable_node_dup like if the chain never existed.
1598 		 */
1599 		if (!stable_node_dup) {
1600 			/*
1601 			 * Either all stable_node dups were full in
1602 			 * this stable_node chain, or this chain was
1603 			 * empty and should be rb_erased.
1604 			 */
1605 			stable_node_any = stable_node_dup_any(stable_node,
1606 							      root);
1607 			if (!stable_node_any) {
1608 				/* rb_erase just run */
1609 				goto again;
1610 			}
1611 			/*
1612 			 * Take any of the stable_node dups page of
1613 			 * this stable_node chain to let the tree walk
1614 			 * continue. All KSM pages belonging to the
1615 			 * stable_node dups in a stable_node chain
1616 			 * have the same content and they're
1617 			 * write protected at all times. Any will work
1618 			 * fine to continue the walk.
1619 			 */
1620 			tree_page = get_ksm_page(stable_node_any,
1621 						 GET_KSM_PAGE_NOLOCK);
1622 		}
1623 		VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
1624 		if (!tree_page) {
1625 			/*
1626 			 * If we walked over a stale stable_node,
1627 			 * get_ksm_page() will call rb_erase() and it
1628 			 * may rebalance the tree from under us. So
1629 			 * restart the search from scratch. Returning
1630 			 * NULL would be safe too, but we'd generate
1631 			 * false negative insertions just because some
1632 			 * stable_node was stale.
1633 			 */
1634 			goto again;
1635 		}
1636 
1637 		ret = memcmp_pages(page, tree_page);
1638 		put_page(tree_page);
1639 
1640 		parent = *new;
1641 		if (ret < 0)
1642 			new = &parent->rb_left;
1643 		else if (ret > 0)
1644 			new = &parent->rb_right;
1645 		else {
1646 			if (page_node) {
1647 				VM_BUG_ON(page_node->head != &migrate_nodes);
1648 				/*
1649 				 * Test if the migrated page should be merged
1650 				 * into a stable node dup. If the mapcount is
1651 				 * 1 we can migrate it with another KSM page
1652 				 * without adding it to the chain.
1653 				 */
1654 				if (page_mapcount(page) > 1)
1655 					goto chain_append;
1656 			}
1657 
1658 			if (!stable_node_dup) {
1659 				/*
1660 				 * If the stable_node is a chain and
1661 				 * we got a payload match in memcmp
1662 				 * but we cannot merge the scanned
1663 				 * page in any of the existing
1664 				 * stable_node dups because they're
1665 				 * all full, we need to wait the
1666 				 * scanned page to find itself a match
1667 				 * in the unstable tree to create a
1668 				 * brand new KSM page to add later to
1669 				 * the dups of this stable_node.
1670 				 */
1671 				return NULL;
1672 			}
1673 
1674 			/*
1675 			 * Lock and unlock the stable_node's page (which
1676 			 * might already have been migrated) so that page
1677 			 * migration is sure to notice its raised count.
1678 			 * It would be more elegant to return stable_node
1679 			 * than kpage, but that involves more changes.
1680 			 */
1681 			tree_page = get_ksm_page(stable_node_dup,
1682 						 GET_KSM_PAGE_TRYLOCK);
1683 
1684 			if (PTR_ERR(tree_page) == -EBUSY)
1685 				return ERR_PTR(-EBUSY);
1686 
1687 			if (unlikely(!tree_page))
1688 				/*
1689 				 * The tree may have been rebalanced,
1690 				 * so re-evaluate parent and new.
1691 				 */
1692 				goto again;
1693 			unlock_page(tree_page);
1694 
1695 			if (get_kpfn_nid(stable_node_dup->kpfn) !=
1696 			    NUMA(stable_node_dup->nid)) {
1697 				put_page(tree_page);
1698 				goto replace;
1699 			}
1700 			return tree_page;
1701 		}
1702 	}
1703 
1704 	if (!page_node)
1705 		return NULL;
1706 
1707 	list_del(&page_node->list);
1708 	DO_NUMA(page_node->nid = nid);
1709 	rb_link_node(&page_node->node, parent, new);
1710 	rb_insert_color(&page_node->node, root);
1711 out:
1712 	if (is_page_sharing_candidate(page_node)) {
1713 		get_page(page);
1714 		return page;
1715 	} else
1716 		return NULL;
1717 
1718 replace:
1719 	/*
1720 	 * If stable_node was a chain and chain_prune collapsed it,
1721 	 * stable_node has been updated to be the new regular
1722 	 * stable_node. A collapse of the chain is indistinguishable
1723 	 * from the case there was no chain in the stable
1724 	 * rbtree. Otherwise stable_node is the chain and
1725 	 * stable_node_dup is the dup to replace.
1726 	 */
1727 	if (stable_node_dup == stable_node) {
1728 		VM_BUG_ON(is_stable_node_chain(stable_node_dup));
1729 		VM_BUG_ON(is_stable_node_dup(stable_node_dup));
1730 		/* there is no chain */
1731 		if (page_node) {
1732 			VM_BUG_ON(page_node->head != &migrate_nodes);
1733 			list_del(&page_node->list);
1734 			DO_NUMA(page_node->nid = nid);
1735 			rb_replace_node(&stable_node_dup->node,
1736 					&page_node->node,
1737 					root);
1738 			if (is_page_sharing_candidate(page_node))
1739 				get_page(page);
1740 			else
1741 				page = NULL;
1742 		} else {
1743 			rb_erase(&stable_node_dup->node, root);
1744 			page = NULL;
1745 		}
1746 	} else {
1747 		VM_BUG_ON(!is_stable_node_chain(stable_node));
1748 		__stable_node_dup_del(stable_node_dup);
1749 		if (page_node) {
1750 			VM_BUG_ON(page_node->head != &migrate_nodes);
1751 			list_del(&page_node->list);
1752 			DO_NUMA(page_node->nid = nid);
1753 			stable_node_chain_add_dup(page_node, stable_node);
1754 			if (is_page_sharing_candidate(page_node))
1755 				get_page(page);
1756 			else
1757 				page = NULL;
1758 		} else {
1759 			page = NULL;
1760 		}
1761 	}
1762 	stable_node_dup->head = &migrate_nodes;
1763 	list_add(&stable_node_dup->list, stable_node_dup->head);
1764 	return page;
1765 
1766 chain_append:
1767 	/* stable_node_dup could be null if it reached the limit */
1768 	if (!stable_node_dup)
1769 		stable_node_dup = stable_node_any;
1770 	/*
1771 	 * If stable_node was a chain and chain_prune collapsed it,
1772 	 * stable_node has been updated to be the new regular
1773 	 * stable_node. A collapse of the chain is indistinguishable
1774 	 * from the case there was no chain in the stable
1775 	 * rbtree. Otherwise stable_node is the chain and
1776 	 * stable_node_dup is the dup to replace.
1777 	 */
1778 	if (stable_node_dup == stable_node) {
1779 		VM_BUG_ON(is_stable_node_chain(stable_node_dup));
1780 		VM_BUG_ON(is_stable_node_dup(stable_node_dup));
1781 		/* chain is missing so create it */
1782 		stable_node = alloc_stable_node_chain(stable_node_dup,
1783 						      root);
1784 		if (!stable_node)
1785 			return NULL;
1786 	}
1787 	/*
1788 	 * Add this stable_node dup that was
1789 	 * migrated to the stable_node chain
1790 	 * of the current nid for this page
1791 	 * content.
1792 	 */
1793 	VM_BUG_ON(!is_stable_node_chain(stable_node));
1794 	VM_BUG_ON(!is_stable_node_dup(stable_node_dup));
1795 	VM_BUG_ON(page_node->head != &migrate_nodes);
1796 	list_del(&page_node->list);
1797 	DO_NUMA(page_node->nid = nid);
1798 	stable_node_chain_add_dup(page_node, stable_node);
1799 	goto out;
1800 }
1801 
1802 /*
1803  * stable_tree_insert - insert stable tree node pointing to new ksm page
1804  * into the stable tree.
1805  *
1806  * This function returns the stable tree node just allocated on success,
1807  * NULL otherwise.
1808  */
stable_tree_insert(struct page * kpage)1809 static struct stable_node *stable_tree_insert(struct page *kpage)
1810 {
1811 	int nid;
1812 	unsigned long kpfn;
1813 	struct rb_root *root;
1814 	struct rb_node **new;
1815 	struct rb_node *parent;
1816 	struct stable_node *stable_node, *stable_node_dup, *stable_node_any;
1817 	bool need_chain = false;
1818 
1819 	kpfn = page_to_pfn(kpage);
1820 	nid = get_kpfn_nid(kpfn);
1821 	root = root_stable_tree + nid;
1822 again:
1823 	parent = NULL;
1824 	new = &root->rb_node;
1825 
1826 	while (*new) {
1827 		struct page *tree_page;
1828 		int ret;
1829 
1830 		cond_resched();
1831 		stable_node = rb_entry(*new, struct stable_node, node);
1832 		stable_node_any = NULL;
1833 		tree_page = chain(&stable_node_dup, stable_node, root);
1834 		if (!stable_node_dup) {
1835 			/*
1836 			 * Either all stable_node dups were full in
1837 			 * this stable_node chain, or this chain was
1838 			 * empty and should be rb_erased.
1839 			 */
1840 			stable_node_any = stable_node_dup_any(stable_node,
1841 							      root);
1842 			if (!stable_node_any) {
1843 				/* rb_erase just run */
1844 				goto again;
1845 			}
1846 			/*
1847 			 * Take any of the stable_node dups page of
1848 			 * this stable_node chain to let the tree walk
1849 			 * continue. All KSM pages belonging to the
1850 			 * stable_node dups in a stable_node chain
1851 			 * have the same content and they're
1852 			 * write protected at all times. Any will work
1853 			 * fine to continue the walk.
1854 			 */
1855 			tree_page = get_ksm_page(stable_node_any,
1856 						 GET_KSM_PAGE_NOLOCK);
1857 		}
1858 		VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
1859 		if (!tree_page) {
1860 			/*
1861 			 * If we walked over a stale stable_node,
1862 			 * get_ksm_page() will call rb_erase() and it
1863 			 * may rebalance the tree from under us. So
1864 			 * restart the search from scratch. Returning
1865 			 * NULL would be safe too, but we'd generate
1866 			 * false negative insertions just because some
1867 			 * stable_node was stale.
1868 			 */
1869 			goto again;
1870 		}
1871 
1872 		ret = memcmp_pages(kpage, tree_page);
1873 		put_page(tree_page);
1874 
1875 		parent = *new;
1876 		if (ret < 0)
1877 			new = &parent->rb_left;
1878 		else if (ret > 0)
1879 			new = &parent->rb_right;
1880 		else {
1881 			need_chain = true;
1882 			break;
1883 		}
1884 	}
1885 
1886 	stable_node_dup = alloc_stable_node();
1887 	if (!stable_node_dup)
1888 		return NULL;
1889 
1890 	INIT_HLIST_HEAD(&stable_node_dup->hlist);
1891 	stable_node_dup->kpfn = kpfn;
1892 	set_page_stable_node(kpage, stable_node_dup);
1893 	stable_node_dup->rmap_hlist_len = 0;
1894 	DO_NUMA(stable_node_dup->nid = nid);
1895 	if (!need_chain) {
1896 		rb_link_node(&stable_node_dup->node, parent, new);
1897 		rb_insert_color(&stable_node_dup->node, root);
1898 	} else {
1899 		if (!is_stable_node_chain(stable_node)) {
1900 			struct stable_node *orig = stable_node;
1901 			/* chain is missing so create it */
1902 			stable_node = alloc_stable_node_chain(orig, root);
1903 			if (!stable_node) {
1904 				free_stable_node(stable_node_dup);
1905 				return NULL;
1906 			}
1907 		}
1908 		stable_node_chain_add_dup(stable_node_dup, stable_node);
1909 	}
1910 
1911 	return stable_node_dup;
1912 }
1913 
1914 /*
1915  * unstable_tree_search_insert - search for identical page,
1916  * else insert rmap_item into the unstable tree.
1917  *
1918  * This function searches for a page in the unstable tree identical to the
1919  * page currently being scanned; and if no identical page is found in the
1920  * tree, we insert rmap_item as a new object into the unstable tree.
1921  *
1922  * This function returns pointer to rmap_item found to be identical
1923  * to the currently scanned page, NULL otherwise.
1924  *
1925  * This function does both searching and inserting, because they share
1926  * the same walking algorithm in an rbtree.
1927  */
1928 static
unstable_tree_search_insert(struct rmap_item * rmap_item,struct page * page,struct page ** tree_pagep)1929 struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
1930 					      struct page *page,
1931 					      struct page **tree_pagep)
1932 {
1933 	struct rb_node **new;
1934 	struct rb_root *root;
1935 	struct rb_node *parent = NULL;
1936 	int nid;
1937 
1938 	nid = get_kpfn_nid(page_to_pfn(page));
1939 	root = root_unstable_tree + nid;
1940 	new = &root->rb_node;
1941 
1942 	while (*new) {
1943 		struct rmap_item *tree_rmap_item;
1944 		struct page *tree_page;
1945 		int ret;
1946 
1947 		cond_resched();
1948 		tree_rmap_item = rb_entry(*new, struct rmap_item, node);
1949 		tree_page = get_mergeable_page(tree_rmap_item);
1950 		if (!tree_page)
1951 			return NULL;
1952 
1953 		/*
1954 		 * Don't substitute a ksm page for a forked page.
1955 		 */
1956 		if (page == tree_page) {
1957 			put_page(tree_page);
1958 			return NULL;
1959 		}
1960 
1961 		ret = memcmp_pages(page, tree_page);
1962 
1963 		parent = *new;
1964 		if (ret < 0) {
1965 			put_page(tree_page);
1966 			new = &parent->rb_left;
1967 		} else if (ret > 0) {
1968 			put_page(tree_page);
1969 			new = &parent->rb_right;
1970 		} else if (!ksm_merge_across_nodes &&
1971 			   page_to_nid(tree_page) != nid) {
1972 			/*
1973 			 * If tree_page has been migrated to another NUMA node,
1974 			 * it will be flushed out and put in the right unstable
1975 			 * tree next time: only merge with it when across_nodes.
1976 			 */
1977 			put_page(tree_page);
1978 			return NULL;
1979 		} else {
1980 			*tree_pagep = tree_page;
1981 			return tree_rmap_item;
1982 		}
1983 	}
1984 
1985 	rmap_item->address |= UNSTABLE_FLAG;
1986 	rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
1987 	DO_NUMA(rmap_item->nid = nid);
1988 	rb_link_node(&rmap_item->node, parent, new);
1989 	rb_insert_color(&rmap_item->node, root);
1990 
1991 	ksm_pages_unshared++;
1992 	return NULL;
1993 }
1994 
1995 /*
1996  * stable_tree_append - add another rmap_item to the linked list of
1997  * rmap_items hanging off a given node of the stable tree, all sharing
1998  * the same ksm page.
1999  */
stable_tree_append(struct rmap_item * rmap_item,struct stable_node * stable_node,bool max_page_sharing_bypass)2000 static void stable_tree_append(struct rmap_item *rmap_item,
2001 			       struct stable_node *stable_node,
2002 			       bool max_page_sharing_bypass)
2003 {
2004 	/*
2005 	 * rmap won't find this mapping if we don't insert the
2006 	 * rmap_item in the right stable_node
2007 	 * duplicate. page_migration could break later if rmap breaks,
2008 	 * so we can as well crash here. We really need to check for
2009 	 * rmap_hlist_len == STABLE_NODE_CHAIN, but we can as well check
2010 	 * for other negative values as an underflow if detected here
2011 	 * for the first time (and not when decreasing rmap_hlist_len)
2012 	 * would be sign of memory corruption in the stable_node.
2013 	 */
2014 	BUG_ON(stable_node->rmap_hlist_len < 0);
2015 
2016 	stable_node->rmap_hlist_len++;
2017 	if (!max_page_sharing_bypass)
2018 		/* possibly non fatal but unexpected overflow, only warn */
2019 		WARN_ON_ONCE(stable_node->rmap_hlist_len >
2020 			     ksm_max_page_sharing);
2021 
2022 	rmap_item->head = stable_node;
2023 	rmap_item->address |= STABLE_FLAG;
2024 	hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
2025 
2026 	if (rmap_item->hlist.next)
2027 		ksm_pages_sharing++;
2028 	else
2029 		ksm_pages_shared++;
2030 }
2031 
2032 /*
2033  * cmp_and_merge_page - first see if page can be merged into the stable tree;
2034  * if not, compare checksum to previous and if it's the same, see if page can
2035  * be inserted into the unstable tree, or merged with a page already there and
2036  * both transferred to the stable tree.
2037  *
2038  * @page: the page that we are searching identical page to.
2039  * @rmap_item: the reverse mapping into the virtual address of this page
2040  */
cmp_and_merge_page(struct page * page,struct rmap_item * rmap_item)2041 static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
2042 {
2043 	struct mm_struct *mm = rmap_item->mm;
2044 	struct rmap_item *tree_rmap_item;
2045 	struct page *tree_page = NULL;
2046 	struct stable_node *stable_node;
2047 	struct page *kpage;
2048 	unsigned int checksum;
2049 	int err;
2050 	bool max_page_sharing_bypass = false;
2051 
2052 	stable_node = page_stable_node(page);
2053 	if (stable_node) {
2054 		if (stable_node->head != &migrate_nodes &&
2055 		    get_kpfn_nid(READ_ONCE(stable_node->kpfn)) !=
2056 		    NUMA(stable_node->nid)) {
2057 			stable_node_dup_del(stable_node);
2058 			stable_node->head = &migrate_nodes;
2059 			list_add(&stable_node->list, stable_node->head);
2060 		}
2061 		if (stable_node->head != &migrate_nodes &&
2062 		    rmap_item->head == stable_node)
2063 			return;
2064 		/*
2065 		 * If it's a KSM fork, allow it to go over the sharing limit
2066 		 * without warnings.
2067 		 */
2068 		if (!is_page_sharing_candidate(stable_node))
2069 			max_page_sharing_bypass = true;
2070 	}
2071 
2072 	/* We first start with searching the page inside the stable tree */
2073 	kpage = stable_tree_search(page);
2074 	if (kpage == page && rmap_item->head == stable_node) {
2075 		put_page(kpage);
2076 		return;
2077 	}
2078 
2079 	remove_rmap_item_from_tree(rmap_item);
2080 
2081 	if (kpage) {
2082 		if (PTR_ERR(kpage) == -EBUSY)
2083 			return;
2084 
2085 		err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
2086 		if (!err) {
2087 			/*
2088 			 * The page was successfully merged:
2089 			 * add its rmap_item to the stable tree.
2090 			 */
2091 			lock_page(kpage);
2092 			stable_tree_append(rmap_item, page_stable_node(kpage),
2093 					   max_page_sharing_bypass);
2094 			unlock_page(kpage);
2095 		}
2096 		put_page(kpage);
2097 		return;
2098 	}
2099 
2100 	/*
2101 	 * If the hash value of the page has changed from the last time
2102 	 * we calculated it, this page is changing frequently: therefore we
2103 	 * don't want to insert it in the unstable tree, and we don't want
2104 	 * to waste our time searching for something identical to it there.
2105 	 */
2106 	checksum = calc_checksum(page);
2107 	if (rmap_item->oldchecksum != checksum) {
2108 		rmap_item->oldchecksum = checksum;
2109 		return;
2110 	}
2111 
2112 	/*
2113 	 * Same checksum as an empty page. We attempt to merge it with the
2114 	 * appropriate zero page if the user enabled this via sysfs.
2115 	 */
2116 	if (ksm_use_zero_pages && (checksum == zero_checksum)) {
2117 		struct vm_area_struct *vma;
2118 
2119 		mmap_read_lock(mm);
2120 		vma = find_mergeable_vma(mm, rmap_item->address);
2121 		if (vma) {
2122 			err = try_to_merge_one_page(vma, page,
2123 					ZERO_PAGE(rmap_item->address));
2124 		} else {
2125 			/*
2126 			 * If the vma is out of date, we do not need to
2127 			 * continue.
2128 			 */
2129 			err = 0;
2130 		}
2131 		mmap_read_unlock(mm);
2132 		/*
2133 		 * In case of failure, the page was not really empty, so we
2134 		 * need to continue. Otherwise we're done.
2135 		 */
2136 		if (!err)
2137 			return;
2138 	}
2139 	tree_rmap_item =
2140 		unstable_tree_search_insert(rmap_item, page, &tree_page);
2141 	if (tree_rmap_item) {
2142 		bool split;
2143 
2144 		kpage = try_to_merge_two_pages(rmap_item, page,
2145 						tree_rmap_item, tree_page);
2146 		/*
2147 		 * If both pages we tried to merge belong to the same compound
2148 		 * page, then we actually ended up increasing the reference
2149 		 * count of the same compound page twice, and split_huge_page
2150 		 * failed.
2151 		 * Here we set a flag if that happened, and we use it later to
2152 		 * try split_huge_page again. Since we call put_page right
2153 		 * afterwards, the reference count will be correct and
2154 		 * split_huge_page should succeed.
2155 		 */
2156 		split = PageTransCompound(page)
2157 			&& compound_head(page) == compound_head(tree_page);
2158 		put_page(tree_page);
2159 		if (kpage) {
2160 			/*
2161 			 * The pages were successfully merged: insert new
2162 			 * node in the stable tree and add both rmap_items.
2163 			 */
2164 			lock_page(kpage);
2165 			stable_node = stable_tree_insert(kpage);
2166 			if (stable_node) {
2167 				stable_tree_append(tree_rmap_item, stable_node,
2168 						   false);
2169 				stable_tree_append(rmap_item, stable_node,
2170 						   false);
2171 			}
2172 			unlock_page(kpage);
2173 
2174 			/*
2175 			 * If we fail to insert the page into the stable tree,
2176 			 * we will have 2 virtual addresses that are pointing
2177 			 * to a ksm page left outside the stable tree,
2178 			 * in which case we need to break_cow on both.
2179 			 */
2180 			if (!stable_node) {
2181 				break_cow(tree_rmap_item);
2182 				break_cow(rmap_item);
2183 			}
2184 		} else if (split) {
2185 			/*
2186 			 * We are here if we tried to merge two pages and
2187 			 * failed because they both belonged to the same
2188 			 * compound page. We will split the page now, but no
2189 			 * merging will take place.
2190 			 * We do not want to add the cost of a full lock; if
2191 			 * the page is locked, it is better to skip it and
2192 			 * perhaps try again later.
2193 			 */
2194 			if (!trylock_page(page))
2195 				return;
2196 			split_huge_page(page);
2197 			unlock_page(page);
2198 		}
2199 	}
2200 }
2201 
get_next_rmap_item(struct mm_slot * mm_slot,struct rmap_item ** rmap_list,unsigned long addr)2202 static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
2203 					    struct rmap_item **rmap_list,
2204 					    unsigned long addr)
2205 {
2206 	struct rmap_item *rmap_item;
2207 
2208 	while (*rmap_list) {
2209 		rmap_item = *rmap_list;
2210 		if ((rmap_item->address & PAGE_MASK) == addr)
2211 			return rmap_item;
2212 		if (rmap_item->address > addr)
2213 			break;
2214 		*rmap_list = rmap_item->rmap_list;
2215 		remove_rmap_item_from_tree(rmap_item);
2216 		free_rmap_item(rmap_item);
2217 	}
2218 
2219 	rmap_item = alloc_rmap_item();
2220 	if (rmap_item) {
2221 		/* It has already been zeroed */
2222 		rmap_item->mm = mm_slot->mm;
2223 		rmap_item->address = addr;
2224 		rmap_item->rmap_list = *rmap_list;
2225 		*rmap_list = rmap_item;
2226 	}
2227 	return rmap_item;
2228 }
2229 
scan_get_next_rmap_item(struct page ** page)2230 static struct rmap_item *scan_get_next_rmap_item(struct page **page)
2231 {
2232 	struct mm_struct *mm;
2233 	struct mm_slot *slot;
2234 	struct vm_area_struct *vma;
2235 	struct rmap_item *rmap_item;
2236 	int nid;
2237 
2238 	if (list_empty(&ksm_mm_head.mm_list))
2239 		return NULL;
2240 
2241 	slot = ksm_scan.mm_slot;
2242 	if (slot == &ksm_mm_head) {
2243 		/*
2244 		 * A number of pages can hang around indefinitely on per-cpu
2245 		 * pagevecs, raised page count preventing write_protect_page
2246 		 * from merging them.  Though it doesn't really matter much,
2247 		 * it is puzzling to see some stuck in pages_volatile until
2248 		 * other activity jostles them out, and they also prevented
2249 		 * LTP's KSM test from succeeding deterministically; so drain
2250 		 * them here (here rather than on entry to ksm_do_scan(),
2251 		 * so we don't IPI too often when pages_to_scan is set low).
2252 		 */
2253 		lru_add_drain_all();
2254 
2255 		/*
2256 		 * Whereas stale stable_nodes on the stable_tree itself
2257 		 * get pruned in the regular course of stable_tree_search(),
2258 		 * those moved out to the migrate_nodes list can accumulate:
2259 		 * so prune them once before each full scan.
2260 		 */
2261 		if (!ksm_merge_across_nodes) {
2262 			struct stable_node *stable_node, *next;
2263 			struct page *page;
2264 
2265 			list_for_each_entry_safe(stable_node, next,
2266 						 &migrate_nodes, list) {
2267 				page = get_ksm_page(stable_node,
2268 						    GET_KSM_PAGE_NOLOCK);
2269 				if (page)
2270 					put_page(page);
2271 				cond_resched();
2272 			}
2273 		}
2274 
2275 		for (nid = 0; nid < ksm_nr_node_ids; nid++)
2276 			root_unstable_tree[nid] = RB_ROOT;
2277 
2278 		spin_lock(&ksm_mmlist_lock);
2279 		slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
2280 		ksm_scan.mm_slot = slot;
2281 		spin_unlock(&ksm_mmlist_lock);
2282 		/*
2283 		 * Although we tested list_empty() above, a racing __ksm_exit
2284 		 * of the last mm on the list may have removed it since then.
2285 		 */
2286 		if (slot == &ksm_mm_head)
2287 			return NULL;
2288 next_mm:
2289 		ksm_scan.address = 0;
2290 		ksm_scan.rmap_list = &slot->rmap_list;
2291 	}
2292 
2293 	mm = slot->mm;
2294 	mmap_read_lock(mm);
2295 	if (ksm_test_exit(mm))
2296 		vma = NULL;
2297 	else
2298 		vma = find_vma(mm, ksm_scan.address);
2299 
2300 	for (; vma; vma = vma->vm_next) {
2301 		if (!(vma->vm_flags & VM_MERGEABLE))
2302 			continue;
2303 		if (ksm_scan.address < vma->vm_start)
2304 			ksm_scan.address = vma->vm_start;
2305 		if (!vma->anon_vma)
2306 			ksm_scan.address = vma->vm_end;
2307 
2308 		while (ksm_scan.address < vma->vm_end) {
2309 			if (ksm_test_exit(mm))
2310 				break;
2311 			*page = follow_page(vma, ksm_scan.address, FOLL_GET);
2312 			if (IS_ERR_OR_NULL(*page)) {
2313 				ksm_scan.address += PAGE_SIZE;
2314 				cond_resched();
2315 				continue;
2316 			}
2317 			if (PageAnon(*page)) {
2318 				flush_anon_page(vma, *page, ksm_scan.address);
2319 				flush_dcache_page(*page);
2320 				rmap_item = get_next_rmap_item(slot,
2321 					ksm_scan.rmap_list, ksm_scan.address);
2322 				if (rmap_item) {
2323 					ksm_scan.rmap_list =
2324 							&rmap_item->rmap_list;
2325 					ksm_scan.address += PAGE_SIZE;
2326 				} else
2327 					put_page(*page);
2328 				mmap_read_unlock(mm);
2329 				return rmap_item;
2330 			}
2331 			put_page(*page);
2332 			ksm_scan.address += PAGE_SIZE;
2333 			cond_resched();
2334 		}
2335 	}
2336 
2337 	if (ksm_test_exit(mm)) {
2338 		ksm_scan.address = 0;
2339 		ksm_scan.rmap_list = &slot->rmap_list;
2340 	}
2341 	/*
2342 	 * Nuke all the rmap_items that are above this current rmap:
2343 	 * because there were no VM_MERGEABLE vmas with such addresses.
2344 	 */
2345 	remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
2346 
2347 	spin_lock(&ksm_mmlist_lock);
2348 	ksm_scan.mm_slot = list_entry(slot->mm_list.next,
2349 						struct mm_slot, mm_list);
2350 	if (ksm_scan.address == 0) {
2351 		/*
2352 		 * We've completed a full scan of all vmas, holding mmap_lock
2353 		 * throughout, and found no VM_MERGEABLE: so do the same as
2354 		 * __ksm_exit does to remove this mm from all our lists now.
2355 		 * This applies either when cleaning up after __ksm_exit
2356 		 * (but beware: we can reach here even before __ksm_exit),
2357 		 * or when all VM_MERGEABLE areas have been unmapped (and
2358 		 * mmap_lock then protects against race with MADV_MERGEABLE).
2359 		 */
2360 		hash_del(&slot->link);
2361 		list_del(&slot->mm_list);
2362 		spin_unlock(&ksm_mmlist_lock);
2363 
2364 		free_mm_slot(slot);
2365 		clear_bit(MMF_VM_MERGEABLE, &mm->flags);
2366 		mmap_read_unlock(mm);
2367 		mmdrop(mm);
2368 	} else {
2369 		mmap_read_unlock(mm);
2370 		/*
2371 		 * mmap_read_unlock(mm) first because after
2372 		 * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
2373 		 * already have been freed under us by __ksm_exit()
2374 		 * because the "mm_slot" is still hashed and
2375 		 * ksm_scan.mm_slot doesn't point to it anymore.
2376 		 */
2377 		spin_unlock(&ksm_mmlist_lock);
2378 	}
2379 
2380 	/* Repeat until we've completed scanning the whole list */
2381 	slot = ksm_scan.mm_slot;
2382 	if (slot != &ksm_mm_head)
2383 		goto next_mm;
2384 
2385 	ksm_scan.seqnr++;
2386 	return NULL;
2387 }
2388 
2389 /**
2390  * ksm_do_scan  - the ksm scanner main worker function.
2391  * @scan_npages:  number of pages we want to scan before we return.
2392  */
ksm_do_scan(unsigned int scan_npages)2393 static void ksm_do_scan(unsigned int scan_npages)
2394 {
2395 	struct rmap_item *rmap_item;
2396 	struct page *page;
2397 
2398 	while (scan_npages-- && likely(!freezing(current))) {
2399 		cond_resched();
2400 		rmap_item = scan_get_next_rmap_item(&page);
2401 		if (!rmap_item)
2402 			return;
2403 		cmp_and_merge_page(page, rmap_item);
2404 		put_page(page);
2405 	}
2406 }
2407 
ksmd_should_run(void)2408 static int ksmd_should_run(void)
2409 {
2410 	return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
2411 }
2412 
ksm_scan_thread(void * nothing)2413 static int ksm_scan_thread(void *nothing)
2414 {
2415 	unsigned int sleep_ms;
2416 
2417 	set_freezable();
2418 	set_user_nice(current, 5);
2419 
2420 	while (!kthread_should_stop()) {
2421 		mutex_lock(&ksm_thread_mutex);
2422 		wait_while_offlining();
2423 		if (ksmd_should_run())
2424 			ksm_do_scan(ksm_thread_pages_to_scan);
2425 		mutex_unlock(&ksm_thread_mutex);
2426 
2427 		try_to_freeze();
2428 
2429 		if (ksmd_should_run()) {
2430 			sleep_ms = READ_ONCE(ksm_thread_sleep_millisecs);
2431 			wait_event_interruptible_timeout(ksm_iter_wait,
2432 				sleep_ms != READ_ONCE(ksm_thread_sleep_millisecs),
2433 				msecs_to_jiffies(sleep_ms));
2434 		} else {
2435 			wait_event_freezable(ksm_thread_wait,
2436 				ksmd_should_run() || kthread_should_stop());
2437 		}
2438 	}
2439 	return 0;
2440 }
2441 
ksm_madvise(struct vm_area_struct * vma,unsigned long start,unsigned long end,int advice,unsigned long * vm_flags)2442 int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
2443 		unsigned long end, int advice, unsigned long *vm_flags)
2444 {
2445 	struct mm_struct *mm = vma->vm_mm;
2446 	int err;
2447 
2448 	switch (advice) {
2449 	case MADV_MERGEABLE:
2450 		/*
2451 		 * Be somewhat over-protective for now!
2452 		 */
2453 		if (*vm_flags & (VM_MERGEABLE | VM_SHARED  | VM_MAYSHARE   |
2454 				 VM_PFNMAP    | VM_IO      | VM_DONTEXPAND |
2455 				 VM_HUGETLB | VM_MIXEDMAP))
2456 			return 0;		/* just ignore the advice */
2457 
2458 		if (vma_is_dax(vma))
2459 			return 0;
2460 
2461 #ifdef VM_SAO
2462 		if (*vm_flags & VM_SAO)
2463 			return 0;
2464 #endif
2465 #ifdef VM_SPARC_ADI
2466 		if (*vm_flags & VM_SPARC_ADI)
2467 			return 0;
2468 #endif
2469 
2470 		if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
2471 			err = __ksm_enter(mm);
2472 			if (err)
2473 				return err;
2474 		}
2475 
2476 		*vm_flags |= VM_MERGEABLE;
2477 		break;
2478 
2479 	case MADV_UNMERGEABLE:
2480 		if (!(*vm_flags & VM_MERGEABLE))
2481 			return 0;		/* just ignore the advice */
2482 
2483 		if (vma->anon_vma) {
2484 			err = unmerge_ksm_pages(vma, start, end);
2485 			if (err)
2486 				return err;
2487 		}
2488 
2489 		*vm_flags &= ~VM_MERGEABLE;
2490 		break;
2491 	}
2492 
2493 	return 0;
2494 }
2495 EXPORT_SYMBOL_GPL(ksm_madvise);
2496 
__ksm_enter(struct mm_struct * mm)2497 int __ksm_enter(struct mm_struct *mm)
2498 {
2499 	struct mm_slot *mm_slot;
2500 	int needs_wakeup;
2501 
2502 	mm_slot = alloc_mm_slot();
2503 	if (!mm_slot)
2504 		return -ENOMEM;
2505 
2506 	/* Check ksm_run too?  Would need tighter locking */
2507 	needs_wakeup = list_empty(&ksm_mm_head.mm_list);
2508 
2509 	spin_lock(&ksm_mmlist_lock);
2510 	insert_to_mm_slots_hash(mm, mm_slot);
2511 	/*
2512 	 * When KSM_RUN_MERGE (or KSM_RUN_STOP),
2513 	 * insert just behind the scanning cursor, to let the area settle
2514 	 * down a little; when fork is followed by immediate exec, we don't
2515 	 * want ksmd to waste time setting up and tearing down an rmap_list.
2516 	 *
2517 	 * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
2518 	 * scanning cursor, otherwise KSM pages in newly forked mms will be
2519 	 * missed: then we might as well insert at the end of the list.
2520 	 */
2521 	if (ksm_run & KSM_RUN_UNMERGE)
2522 		list_add_tail(&mm_slot->mm_list, &ksm_mm_head.mm_list);
2523 	else
2524 		list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
2525 	spin_unlock(&ksm_mmlist_lock);
2526 
2527 	set_bit(MMF_VM_MERGEABLE, &mm->flags);
2528 	mmgrab(mm);
2529 
2530 	if (needs_wakeup)
2531 		wake_up_interruptible(&ksm_thread_wait);
2532 
2533 	return 0;
2534 }
2535 
__ksm_exit(struct mm_struct * mm)2536 void __ksm_exit(struct mm_struct *mm)
2537 {
2538 	struct mm_slot *mm_slot;
2539 	int easy_to_free = 0;
2540 
2541 	/*
2542 	 * This process is exiting: if it's straightforward (as is the
2543 	 * case when ksmd was never running), free mm_slot immediately.
2544 	 * But if it's at the cursor or has rmap_items linked to it, use
2545 	 * mmap_lock to synchronize with any break_cows before pagetables
2546 	 * are freed, and leave the mm_slot on the list for ksmd to free.
2547 	 * Beware: ksm may already have noticed it exiting and freed the slot.
2548 	 */
2549 
2550 	spin_lock(&ksm_mmlist_lock);
2551 	mm_slot = get_mm_slot(mm);
2552 	if (mm_slot && ksm_scan.mm_slot != mm_slot) {
2553 		if (!mm_slot->rmap_list) {
2554 			hash_del(&mm_slot->link);
2555 			list_del(&mm_slot->mm_list);
2556 			easy_to_free = 1;
2557 		} else {
2558 			list_move(&mm_slot->mm_list,
2559 				  &ksm_scan.mm_slot->mm_list);
2560 		}
2561 	}
2562 	spin_unlock(&ksm_mmlist_lock);
2563 
2564 	if (easy_to_free) {
2565 		free_mm_slot(mm_slot);
2566 		clear_bit(MMF_VM_MERGEABLE, &mm->flags);
2567 		mmdrop(mm);
2568 	} else if (mm_slot) {
2569 		mmap_write_lock(mm);
2570 		mmap_write_unlock(mm);
2571 	}
2572 }
2573 
ksm_might_need_to_copy(struct page * page,struct vm_area_struct * vma,unsigned long address)2574 struct page *ksm_might_need_to_copy(struct page *page,
2575 			struct vm_area_struct *vma, unsigned long address)
2576 {
2577 	struct anon_vma *anon_vma = page_anon_vma(page);
2578 	struct page *new_page;
2579 
2580 	if (PageKsm(page)) {
2581 		if (page_stable_node(page) &&
2582 		    !(ksm_run & KSM_RUN_UNMERGE))
2583 			return page;	/* no need to copy it */
2584 	} else if (!anon_vma) {
2585 		return page;		/* no need to copy it */
2586 	} else if (anon_vma->root == vma->anon_vma->root &&
2587 		 page->index == linear_page_index(vma, address)) {
2588 		return page;		/* still no need to copy it */
2589 	}
2590 	if (!PageUptodate(page))
2591 		return page;		/* let do_swap_page report the error */
2592 
2593 	new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
2594 	if (new_page && mem_cgroup_charge(new_page, vma->vm_mm, GFP_KERNEL)) {
2595 		put_page(new_page);
2596 		new_page = NULL;
2597 	}
2598 	if (new_page) {
2599 		copy_user_highpage(new_page, page, address, vma);
2600 
2601 		SetPageDirty(new_page);
2602 		__SetPageUptodate(new_page);
2603 		__SetPageLocked(new_page);
2604 	}
2605 
2606 	return new_page;
2607 }
2608 
rmap_walk_ksm(struct page * page,struct rmap_walk_control * rwc)2609 void rmap_walk_ksm(struct page *page, struct rmap_walk_control *rwc)
2610 {
2611 	struct stable_node *stable_node;
2612 	struct rmap_item *rmap_item;
2613 	int search_new_forks = 0;
2614 
2615 	VM_BUG_ON_PAGE(!PageKsm(page), page);
2616 
2617 	/*
2618 	 * Rely on the page lock to protect against concurrent modifications
2619 	 * to that page's node of the stable tree.
2620 	 */
2621 	VM_BUG_ON_PAGE(!PageLocked(page), page);
2622 
2623 	stable_node = page_stable_node(page);
2624 	if (!stable_node)
2625 		return;
2626 again:
2627 	hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
2628 		struct anon_vma *anon_vma = rmap_item->anon_vma;
2629 		struct anon_vma_chain *vmac;
2630 		struct vm_area_struct *vma;
2631 
2632 		cond_resched();
2633 		anon_vma_lock_read(anon_vma);
2634 		anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
2635 					       0, ULONG_MAX) {
2636 			unsigned long addr;
2637 
2638 			cond_resched();
2639 			vma = vmac->vma;
2640 
2641 			/* Ignore the stable/unstable/sqnr flags */
2642 			addr = rmap_item->address & ~KSM_FLAG_MASK;
2643 
2644 			if (addr < vma->vm_start || addr >= vma->vm_end)
2645 				continue;
2646 			/*
2647 			 * Initially we examine only the vma which covers this
2648 			 * rmap_item; but later, if there is still work to do,
2649 			 * we examine covering vmas in other mms: in case they
2650 			 * were forked from the original since ksmd passed.
2651 			 */
2652 			if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
2653 				continue;
2654 
2655 			if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2656 				continue;
2657 
2658 			if (!rwc->rmap_one(page, vma, addr, rwc->arg)) {
2659 				anon_vma_unlock_read(anon_vma);
2660 				return;
2661 			}
2662 			if (rwc->done && rwc->done(page)) {
2663 				anon_vma_unlock_read(anon_vma);
2664 				return;
2665 			}
2666 		}
2667 		anon_vma_unlock_read(anon_vma);
2668 	}
2669 	if (!search_new_forks++)
2670 		goto again;
2671 }
2672 
2673 #ifdef CONFIG_MIGRATION
ksm_migrate_page(struct page * newpage,struct page * oldpage)2674 void ksm_migrate_page(struct page *newpage, struct page *oldpage)
2675 {
2676 	struct stable_node *stable_node;
2677 
2678 	VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
2679 	VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
2680 	VM_BUG_ON_PAGE(newpage->mapping != oldpage->mapping, newpage);
2681 
2682 	stable_node = page_stable_node(newpage);
2683 	if (stable_node) {
2684 		VM_BUG_ON_PAGE(stable_node->kpfn != page_to_pfn(oldpage), oldpage);
2685 		stable_node->kpfn = page_to_pfn(newpage);
2686 		/*
2687 		 * newpage->mapping was set in advance; now we need smp_wmb()
2688 		 * to make sure that the new stable_node->kpfn is visible
2689 		 * to get_ksm_page() before it can see that oldpage->mapping
2690 		 * has gone stale (or that PageSwapCache has been cleared).
2691 		 */
2692 		smp_wmb();
2693 		set_page_stable_node(oldpage, NULL);
2694 	}
2695 }
2696 #endif /* CONFIG_MIGRATION */
2697 
2698 #ifdef CONFIG_MEMORY_HOTREMOVE
wait_while_offlining(void)2699 static void wait_while_offlining(void)
2700 {
2701 	while (ksm_run & KSM_RUN_OFFLINE) {
2702 		mutex_unlock(&ksm_thread_mutex);
2703 		wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
2704 			    TASK_UNINTERRUPTIBLE);
2705 		mutex_lock(&ksm_thread_mutex);
2706 	}
2707 }
2708 
stable_node_dup_remove_range(struct stable_node * stable_node,unsigned long start_pfn,unsigned long end_pfn)2709 static bool stable_node_dup_remove_range(struct stable_node *stable_node,
2710 					 unsigned long start_pfn,
2711 					 unsigned long end_pfn)
2712 {
2713 	if (stable_node->kpfn >= start_pfn &&
2714 	    stable_node->kpfn < end_pfn) {
2715 		/*
2716 		 * Don't get_ksm_page, page has already gone:
2717 		 * which is why we keep kpfn instead of page*
2718 		 */
2719 		remove_node_from_stable_tree(stable_node);
2720 		return true;
2721 	}
2722 	return false;
2723 }
2724 
stable_node_chain_remove_range(struct stable_node * stable_node,unsigned long start_pfn,unsigned long end_pfn,struct rb_root * root)2725 static bool stable_node_chain_remove_range(struct stable_node *stable_node,
2726 					   unsigned long start_pfn,
2727 					   unsigned long end_pfn,
2728 					   struct rb_root *root)
2729 {
2730 	struct stable_node *dup;
2731 	struct hlist_node *hlist_safe;
2732 
2733 	if (!is_stable_node_chain(stable_node)) {
2734 		VM_BUG_ON(is_stable_node_dup(stable_node));
2735 		return stable_node_dup_remove_range(stable_node, start_pfn,
2736 						    end_pfn);
2737 	}
2738 
2739 	hlist_for_each_entry_safe(dup, hlist_safe,
2740 				  &stable_node->hlist, hlist_dup) {
2741 		VM_BUG_ON(!is_stable_node_dup(dup));
2742 		stable_node_dup_remove_range(dup, start_pfn, end_pfn);
2743 	}
2744 	if (hlist_empty(&stable_node->hlist)) {
2745 		free_stable_node_chain(stable_node, root);
2746 		return true; /* notify caller that tree was rebalanced */
2747 	} else
2748 		return false;
2749 }
2750 
ksm_check_stable_tree(unsigned long start_pfn,unsigned long end_pfn)2751 static void ksm_check_stable_tree(unsigned long start_pfn,
2752 				  unsigned long end_pfn)
2753 {
2754 	struct stable_node *stable_node, *next;
2755 	struct rb_node *node;
2756 	int nid;
2757 
2758 	for (nid = 0; nid < ksm_nr_node_ids; nid++) {
2759 		node = rb_first(root_stable_tree + nid);
2760 		while (node) {
2761 			stable_node = rb_entry(node, struct stable_node, node);
2762 			if (stable_node_chain_remove_range(stable_node,
2763 							   start_pfn, end_pfn,
2764 							   root_stable_tree +
2765 							   nid))
2766 				node = rb_first(root_stable_tree + nid);
2767 			else
2768 				node = rb_next(node);
2769 			cond_resched();
2770 		}
2771 	}
2772 	list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
2773 		if (stable_node->kpfn >= start_pfn &&
2774 		    stable_node->kpfn < end_pfn)
2775 			remove_node_from_stable_tree(stable_node);
2776 		cond_resched();
2777 	}
2778 }
2779 
ksm_memory_callback(struct notifier_block * self,unsigned long action,void * arg)2780 static int ksm_memory_callback(struct notifier_block *self,
2781 			       unsigned long action, void *arg)
2782 {
2783 	struct memory_notify *mn = arg;
2784 
2785 	switch (action) {
2786 	case MEM_GOING_OFFLINE:
2787 		/*
2788 		 * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
2789 		 * and remove_all_stable_nodes() while memory is going offline:
2790 		 * it is unsafe for them to touch the stable tree at this time.
2791 		 * But unmerge_ksm_pages(), rmap lookups and other entry points
2792 		 * which do not need the ksm_thread_mutex are all safe.
2793 		 */
2794 		mutex_lock(&ksm_thread_mutex);
2795 		ksm_run |= KSM_RUN_OFFLINE;
2796 		mutex_unlock(&ksm_thread_mutex);
2797 		break;
2798 
2799 	case MEM_OFFLINE:
2800 		/*
2801 		 * Most of the work is done by page migration; but there might
2802 		 * be a few stable_nodes left over, still pointing to struct
2803 		 * pages which have been offlined: prune those from the tree,
2804 		 * otherwise get_ksm_page() might later try to access a
2805 		 * non-existent struct page.
2806 		 */
2807 		ksm_check_stable_tree(mn->start_pfn,
2808 				      mn->start_pfn + mn->nr_pages);
2809 		fallthrough;
2810 	case MEM_CANCEL_OFFLINE:
2811 		mutex_lock(&ksm_thread_mutex);
2812 		ksm_run &= ~KSM_RUN_OFFLINE;
2813 		mutex_unlock(&ksm_thread_mutex);
2814 
2815 		smp_mb();	/* wake_up_bit advises this */
2816 		wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
2817 		break;
2818 	}
2819 	return NOTIFY_OK;
2820 }
2821 #else
wait_while_offlining(void)2822 static void wait_while_offlining(void)
2823 {
2824 }
2825 #endif /* CONFIG_MEMORY_HOTREMOVE */
2826 
2827 #ifdef CONFIG_SYSFS
2828 /*
2829  * This all compiles without CONFIG_SYSFS, but is a waste of space.
2830  */
2831 
2832 #define KSM_ATTR_RO(_name) \
2833 	static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2834 #define KSM_ATTR(_name) \
2835 	static struct kobj_attribute _name##_attr = \
2836 		__ATTR(_name, 0644, _name##_show, _name##_store)
2837 
sleep_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2838 static ssize_t sleep_millisecs_show(struct kobject *kobj,
2839 				    struct kobj_attribute *attr, char *buf)
2840 {
2841 	return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
2842 }
2843 
sleep_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2844 static ssize_t sleep_millisecs_store(struct kobject *kobj,
2845 				     struct kobj_attribute *attr,
2846 				     const char *buf, size_t count)
2847 {
2848 	unsigned long msecs;
2849 	int err;
2850 
2851 	err = kstrtoul(buf, 10, &msecs);
2852 	if (err || msecs > UINT_MAX)
2853 		return -EINVAL;
2854 
2855 	ksm_thread_sleep_millisecs = msecs;
2856 	wake_up_interruptible(&ksm_iter_wait);
2857 
2858 	return count;
2859 }
2860 KSM_ATTR(sleep_millisecs);
2861 
pages_to_scan_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2862 static ssize_t pages_to_scan_show(struct kobject *kobj,
2863 				  struct kobj_attribute *attr, char *buf)
2864 {
2865 	return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
2866 }
2867 
pages_to_scan_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2868 static ssize_t pages_to_scan_store(struct kobject *kobj,
2869 				   struct kobj_attribute *attr,
2870 				   const char *buf, size_t count)
2871 {
2872 	int err;
2873 	unsigned long nr_pages;
2874 
2875 	err = kstrtoul(buf, 10, &nr_pages);
2876 	if (err || nr_pages > UINT_MAX)
2877 		return -EINVAL;
2878 
2879 	ksm_thread_pages_to_scan = nr_pages;
2880 
2881 	return count;
2882 }
2883 KSM_ATTR(pages_to_scan);
2884 
run_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2885 static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
2886 			char *buf)
2887 {
2888 	return sprintf(buf, "%lu\n", ksm_run);
2889 }
2890 
run_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2891 static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
2892 			 const char *buf, size_t count)
2893 {
2894 	int err;
2895 	unsigned long flags;
2896 
2897 	err = kstrtoul(buf, 10, &flags);
2898 	if (err || flags > UINT_MAX)
2899 		return -EINVAL;
2900 	if (flags > KSM_RUN_UNMERGE)
2901 		return -EINVAL;
2902 
2903 	/*
2904 	 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
2905 	 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
2906 	 * breaking COW to free the pages_shared (but leaves mm_slots
2907 	 * on the list for when ksmd may be set running again).
2908 	 */
2909 
2910 	mutex_lock(&ksm_thread_mutex);
2911 	wait_while_offlining();
2912 	if (ksm_run != flags) {
2913 		ksm_run = flags;
2914 		if (flags & KSM_RUN_UNMERGE) {
2915 			set_current_oom_origin();
2916 			err = unmerge_and_remove_all_rmap_items();
2917 			clear_current_oom_origin();
2918 			if (err) {
2919 				ksm_run = KSM_RUN_STOP;
2920 				count = err;
2921 			}
2922 		}
2923 	}
2924 	mutex_unlock(&ksm_thread_mutex);
2925 
2926 	if (flags & KSM_RUN_MERGE)
2927 		wake_up_interruptible(&ksm_thread_wait);
2928 
2929 	return count;
2930 }
2931 KSM_ATTR(run);
2932 
2933 #ifdef CONFIG_NUMA
merge_across_nodes_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2934 static ssize_t merge_across_nodes_show(struct kobject *kobj,
2935 				struct kobj_attribute *attr, char *buf)
2936 {
2937 	return sprintf(buf, "%u\n", ksm_merge_across_nodes);
2938 }
2939 
merge_across_nodes_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2940 static ssize_t merge_across_nodes_store(struct kobject *kobj,
2941 				   struct kobj_attribute *attr,
2942 				   const char *buf, size_t count)
2943 {
2944 	int err;
2945 	unsigned long knob;
2946 
2947 	err = kstrtoul(buf, 10, &knob);
2948 	if (err)
2949 		return err;
2950 	if (knob > 1)
2951 		return -EINVAL;
2952 
2953 	mutex_lock(&ksm_thread_mutex);
2954 	wait_while_offlining();
2955 	if (ksm_merge_across_nodes != knob) {
2956 		if (ksm_pages_shared || remove_all_stable_nodes())
2957 			err = -EBUSY;
2958 		else if (root_stable_tree == one_stable_tree) {
2959 			struct rb_root *buf;
2960 			/*
2961 			 * This is the first time that we switch away from the
2962 			 * default of merging across nodes: must now allocate
2963 			 * a buffer to hold as many roots as may be needed.
2964 			 * Allocate stable and unstable together:
2965 			 * MAXSMP NODES_SHIFT 10 will use 16kB.
2966 			 */
2967 			buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf),
2968 				      GFP_KERNEL);
2969 			/* Let us assume that RB_ROOT is NULL is zero */
2970 			if (!buf)
2971 				err = -ENOMEM;
2972 			else {
2973 				root_stable_tree = buf;
2974 				root_unstable_tree = buf + nr_node_ids;
2975 				/* Stable tree is empty but not the unstable */
2976 				root_unstable_tree[0] = one_unstable_tree[0];
2977 			}
2978 		}
2979 		if (!err) {
2980 			ksm_merge_across_nodes = knob;
2981 			ksm_nr_node_ids = knob ? 1 : nr_node_ids;
2982 		}
2983 	}
2984 	mutex_unlock(&ksm_thread_mutex);
2985 
2986 	return err ? err : count;
2987 }
2988 KSM_ATTR(merge_across_nodes);
2989 #endif
2990 
use_zero_pages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2991 static ssize_t use_zero_pages_show(struct kobject *kobj,
2992 				struct kobj_attribute *attr, char *buf)
2993 {
2994 	return sprintf(buf, "%u\n", ksm_use_zero_pages);
2995 }
use_zero_pages_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2996 static ssize_t use_zero_pages_store(struct kobject *kobj,
2997 				   struct kobj_attribute *attr,
2998 				   const char *buf, size_t count)
2999 {
3000 	int err;
3001 	bool value;
3002 
3003 	err = kstrtobool(buf, &value);
3004 	if (err)
3005 		return -EINVAL;
3006 
3007 	ksm_use_zero_pages = value;
3008 
3009 	return count;
3010 }
3011 KSM_ATTR(use_zero_pages);
3012 
max_page_sharing_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3013 static ssize_t max_page_sharing_show(struct kobject *kobj,
3014 				     struct kobj_attribute *attr, char *buf)
3015 {
3016 	return sprintf(buf, "%u\n", ksm_max_page_sharing);
3017 }
3018 
max_page_sharing_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3019 static ssize_t max_page_sharing_store(struct kobject *kobj,
3020 				      struct kobj_attribute *attr,
3021 				      const char *buf, size_t count)
3022 {
3023 	int err;
3024 	int knob;
3025 
3026 	err = kstrtoint(buf, 10, &knob);
3027 	if (err)
3028 		return err;
3029 	/*
3030 	 * When a KSM page is created it is shared by 2 mappings. This
3031 	 * being a signed comparison, it implicitly verifies it's not
3032 	 * negative.
3033 	 */
3034 	if (knob < 2)
3035 		return -EINVAL;
3036 
3037 	if (READ_ONCE(ksm_max_page_sharing) == knob)
3038 		return count;
3039 
3040 	mutex_lock(&ksm_thread_mutex);
3041 	wait_while_offlining();
3042 	if (ksm_max_page_sharing != knob) {
3043 		if (ksm_pages_shared || remove_all_stable_nodes())
3044 			err = -EBUSY;
3045 		else
3046 			ksm_max_page_sharing = knob;
3047 	}
3048 	mutex_unlock(&ksm_thread_mutex);
3049 
3050 	return err ? err : count;
3051 }
3052 KSM_ATTR(max_page_sharing);
3053 
pages_shared_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3054 static ssize_t pages_shared_show(struct kobject *kobj,
3055 				 struct kobj_attribute *attr, char *buf)
3056 {
3057 	return sprintf(buf, "%lu\n", ksm_pages_shared);
3058 }
3059 KSM_ATTR_RO(pages_shared);
3060 
pages_sharing_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3061 static ssize_t pages_sharing_show(struct kobject *kobj,
3062 				  struct kobj_attribute *attr, char *buf)
3063 {
3064 	return sprintf(buf, "%lu\n", ksm_pages_sharing);
3065 }
3066 KSM_ATTR_RO(pages_sharing);
3067 
pages_unshared_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3068 static ssize_t pages_unshared_show(struct kobject *kobj,
3069 				   struct kobj_attribute *attr, char *buf)
3070 {
3071 	return sprintf(buf, "%lu\n", ksm_pages_unshared);
3072 }
3073 KSM_ATTR_RO(pages_unshared);
3074 
pages_volatile_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3075 static ssize_t pages_volatile_show(struct kobject *kobj,
3076 				   struct kobj_attribute *attr, char *buf)
3077 {
3078 	long ksm_pages_volatile;
3079 
3080 	ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
3081 				- ksm_pages_sharing - ksm_pages_unshared;
3082 	/*
3083 	 * It was not worth any locking to calculate that statistic,
3084 	 * but it might therefore sometimes be negative: conceal that.
3085 	 */
3086 	if (ksm_pages_volatile < 0)
3087 		ksm_pages_volatile = 0;
3088 	return sprintf(buf, "%ld\n", ksm_pages_volatile);
3089 }
3090 KSM_ATTR_RO(pages_volatile);
3091 
stable_node_dups_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3092 static ssize_t stable_node_dups_show(struct kobject *kobj,
3093 				     struct kobj_attribute *attr, char *buf)
3094 {
3095 	return sprintf(buf, "%lu\n", ksm_stable_node_dups);
3096 }
3097 KSM_ATTR_RO(stable_node_dups);
3098 
stable_node_chains_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3099 static ssize_t stable_node_chains_show(struct kobject *kobj,
3100 				       struct kobj_attribute *attr, char *buf)
3101 {
3102 	return sprintf(buf, "%lu\n", ksm_stable_node_chains);
3103 }
3104 KSM_ATTR_RO(stable_node_chains);
3105 
3106 static ssize_t
stable_node_chains_prune_millisecs_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3107 stable_node_chains_prune_millisecs_show(struct kobject *kobj,
3108 					struct kobj_attribute *attr,
3109 					char *buf)
3110 {
3111 	return sprintf(buf, "%u\n", ksm_stable_node_chains_prune_millisecs);
3112 }
3113 
3114 static ssize_t
stable_node_chains_prune_millisecs_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3115 stable_node_chains_prune_millisecs_store(struct kobject *kobj,
3116 					 struct kobj_attribute *attr,
3117 					 const char *buf, size_t count)
3118 {
3119 	unsigned long msecs;
3120 	int err;
3121 
3122 	err = kstrtoul(buf, 10, &msecs);
3123 	if (err || msecs > UINT_MAX)
3124 		return -EINVAL;
3125 
3126 	ksm_stable_node_chains_prune_millisecs = msecs;
3127 
3128 	return count;
3129 }
3130 KSM_ATTR(stable_node_chains_prune_millisecs);
3131 
full_scans_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3132 static ssize_t full_scans_show(struct kobject *kobj,
3133 			       struct kobj_attribute *attr, char *buf)
3134 {
3135 	return sprintf(buf, "%lu\n", ksm_scan.seqnr);
3136 }
3137 KSM_ATTR_RO(full_scans);
3138 
3139 static struct attribute *ksm_attrs[] = {
3140 	&sleep_millisecs_attr.attr,
3141 	&pages_to_scan_attr.attr,
3142 	&run_attr.attr,
3143 	&pages_shared_attr.attr,
3144 	&pages_sharing_attr.attr,
3145 	&pages_unshared_attr.attr,
3146 	&pages_volatile_attr.attr,
3147 	&full_scans_attr.attr,
3148 #ifdef CONFIG_NUMA
3149 	&merge_across_nodes_attr.attr,
3150 #endif
3151 	&max_page_sharing_attr.attr,
3152 	&stable_node_chains_attr.attr,
3153 	&stable_node_dups_attr.attr,
3154 	&stable_node_chains_prune_millisecs_attr.attr,
3155 	&use_zero_pages_attr.attr,
3156 	NULL,
3157 };
3158 
3159 static const struct attribute_group ksm_attr_group = {
3160 	.attrs = ksm_attrs,
3161 	.name = "ksm",
3162 };
3163 #endif /* CONFIG_SYSFS */
3164 
ksm_init(void)3165 static int __init ksm_init(void)
3166 {
3167 	struct task_struct *ksm_thread;
3168 	int err;
3169 
3170 	/* The correct value depends on page size and endianness */
3171 	zero_checksum = calc_checksum(ZERO_PAGE(0));
3172 	/* Default to false for backwards compatibility */
3173 	ksm_use_zero_pages = false;
3174 
3175 	err = ksm_slab_init();
3176 	if (err)
3177 		goto out;
3178 
3179 	ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
3180 	if (IS_ERR(ksm_thread)) {
3181 		pr_err("ksm: creating kthread failed\n");
3182 		err = PTR_ERR(ksm_thread);
3183 		goto out_free;
3184 	}
3185 
3186 #ifdef CONFIG_SYSFS
3187 	err = sysfs_create_group(mm_kobj, &ksm_attr_group);
3188 	if (err) {
3189 		pr_err("ksm: register sysfs failed\n");
3190 		kthread_stop(ksm_thread);
3191 		goto out_free;
3192 	}
3193 #else
3194 	ksm_run = KSM_RUN_MERGE;	/* no way for user to start it */
3195 
3196 #endif /* CONFIG_SYSFS */
3197 
3198 #ifdef CONFIG_MEMORY_HOTREMOVE
3199 	/* There is no significance to this priority 100 */
3200 	hotplug_memory_notifier(ksm_memory_callback, 100);
3201 #endif
3202 	return 0;
3203 
3204 out_free:
3205 	ksm_slab_free();
3206 out:
3207 	return err;
3208 }
3209 subsys_initcall(ksm_init);
3210