xref: /linux/mm/ksm.c (revision dcddffd41d3f1d3bdcc1dce3f1cd142779b6d4c1)
1f8af4da3SHugh Dickins /*
231dbd01fSIzik Eidus  * Memory merging support.
331dbd01fSIzik Eidus  *
431dbd01fSIzik Eidus  * This code enables dynamic sharing of identical pages found in different
531dbd01fSIzik Eidus  * memory areas, even if they are not shared by fork()
631dbd01fSIzik Eidus  *
736b2528dSIzik Eidus  * Copyright (C) 2008-2009 Red Hat, Inc.
831dbd01fSIzik Eidus  * Authors:
931dbd01fSIzik Eidus  *	Izik Eidus
1031dbd01fSIzik Eidus  *	Andrea Arcangeli
1131dbd01fSIzik Eidus  *	Chris Wright
1236b2528dSIzik Eidus  *	Hugh Dickins
1331dbd01fSIzik Eidus  *
1431dbd01fSIzik Eidus  * This work is licensed under the terms of the GNU GPL, version 2.
15f8af4da3SHugh Dickins  */
16f8af4da3SHugh Dickins 
17f8af4da3SHugh Dickins #include <linux/errno.h>
1831dbd01fSIzik Eidus #include <linux/mm.h>
1931dbd01fSIzik Eidus #include <linux/fs.h>
20f8af4da3SHugh Dickins #include <linux/mman.h>
2131dbd01fSIzik Eidus #include <linux/sched.h>
2231dbd01fSIzik Eidus #include <linux/rwsem.h>
2331dbd01fSIzik Eidus #include <linux/pagemap.h>
2431dbd01fSIzik Eidus #include <linux/rmap.h>
2531dbd01fSIzik Eidus #include <linux/spinlock.h>
2631dbd01fSIzik Eidus #include <linux/jhash.h>
2731dbd01fSIzik Eidus #include <linux/delay.h>
2831dbd01fSIzik Eidus #include <linux/kthread.h>
2931dbd01fSIzik Eidus #include <linux/wait.h>
3031dbd01fSIzik Eidus #include <linux/slab.h>
3131dbd01fSIzik Eidus #include <linux/rbtree.h>
3262b61f61SHugh Dickins #include <linux/memory.h>
3331dbd01fSIzik Eidus #include <linux/mmu_notifier.h>
342c6854fdSIzik Eidus #include <linux/swap.h>
35f8af4da3SHugh Dickins #include <linux/ksm.h>
364ca3a69bSSasha Levin #include <linux/hashtable.h>
37878aee7dSAndrea Arcangeli #include <linux/freezer.h>
3872788c38SDavid Rientjes #include <linux/oom.h>
3990bd6fd3SPetr Holasek #include <linux/numa.h>
40f8af4da3SHugh Dickins 
4131dbd01fSIzik Eidus #include <asm/tlbflush.h>
4273848b46SHugh Dickins #include "internal.h"
4331dbd01fSIzik Eidus 
44e850dcf5SHugh Dickins #ifdef CONFIG_NUMA
45e850dcf5SHugh Dickins #define NUMA(x)		(x)
46e850dcf5SHugh Dickins #define DO_NUMA(x)	do { (x); } while (0)
47e850dcf5SHugh Dickins #else
48e850dcf5SHugh Dickins #define NUMA(x)		(0)
49e850dcf5SHugh Dickins #define DO_NUMA(x)	do { } while (0)
50e850dcf5SHugh Dickins #endif
51e850dcf5SHugh Dickins 
5231dbd01fSIzik Eidus /*
5331dbd01fSIzik Eidus  * A few notes about the KSM scanning process,
5431dbd01fSIzik Eidus  * to make it easier to understand the data structures below:
5531dbd01fSIzik Eidus  *
5631dbd01fSIzik Eidus  * In order to reduce excessive scanning, KSM sorts the memory pages by their
5731dbd01fSIzik Eidus  * contents into a data structure that holds pointers to the pages' locations.
5831dbd01fSIzik Eidus  *
5931dbd01fSIzik Eidus  * Since the contents of the pages may change at any moment, KSM cannot just
6031dbd01fSIzik Eidus  * insert the pages into a normal sorted tree and expect it to find anything.
6131dbd01fSIzik Eidus  * Therefore KSM uses two data structures - the stable and the unstable tree.
6231dbd01fSIzik Eidus  *
6331dbd01fSIzik Eidus  * The stable tree holds pointers to all the merged pages (ksm pages), sorted
6431dbd01fSIzik Eidus  * by their contents.  Because each such page is write-protected, searching on
6531dbd01fSIzik Eidus  * this tree is fully assured to be working (except when pages are unmapped),
6631dbd01fSIzik Eidus  * and therefore this tree is called the stable tree.
6731dbd01fSIzik Eidus  *
6831dbd01fSIzik Eidus  * In addition to the stable tree, KSM uses a second data structure called the
6931dbd01fSIzik Eidus  * unstable tree: this tree holds pointers to pages which have been found to
7031dbd01fSIzik Eidus  * be "unchanged for a period of time".  The unstable tree sorts these pages
7131dbd01fSIzik Eidus  * by their contents, but since they are not write-protected, KSM cannot rely
7231dbd01fSIzik Eidus  * upon the unstable tree to work correctly - the unstable tree is liable to
7331dbd01fSIzik Eidus  * be corrupted as its contents are modified, and so it is called unstable.
7431dbd01fSIzik Eidus  *
7531dbd01fSIzik Eidus  * KSM solves this problem by several techniques:
7631dbd01fSIzik Eidus  *
7731dbd01fSIzik Eidus  * 1) The unstable tree is flushed every time KSM completes scanning all
7831dbd01fSIzik Eidus  *    memory areas, and then the tree is rebuilt again from the beginning.
7931dbd01fSIzik Eidus  * 2) KSM will only insert into the unstable tree, pages whose hash value
8031dbd01fSIzik Eidus  *    has not changed since the previous scan of all memory areas.
8131dbd01fSIzik Eidus  * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
8231dbd01fSIzik Eidus  *    colors of the nodes and not on their contents, assuring that even when
8331dbd01fSIzik Eidus  *    the tree gets "corrupted" it won't get out of balance, so scanning time
8431dbd01fSIzik Eidus  *    remains the same (also, searching and inserting nodes in an rbtree uses
8531dbd01fSIzik Eidus  *    the same algorithm, so we have no overhead when we flush and rebuild).
8631dbd01fSIzik Eidus  * 4) KSM never flushes the stable tree, which means that even if it were to
8731dbd01fSIzik Eidus  *    take 10 attempts to find a page in the unstable tree, once it is found,
8831dbd01fSIzik Eidus  *    it is secured in the stable tree.  (When we scan a new page, we first
8931dbd01fSIzik Eidus  *    compare it against the stable tree, and then against the unstable tree.)
908fdb3dbfSHugh Dickins  *
918fdb3dbfSHugh Dickins  * If the merge_across_nodes tunable is unset, then KSM maintains multiple
928fdb3dbfSHugh Dickins  * stable trees and multiple unstable trees: one of each for each NUMA node.
9331dbd01fSIzik Eidus  */
9431dbd01fSIzik Eidus 
9531dbd01fSIzik Eidus /**
9631dbd01fSIzik Eidus  * struct mm_slot - ksm information per mm that is being scanned
9731dbd01fSIzik Eidus  * @link: link to the mm_slots hash list
9831dbd01fSIzik Eidus  * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
996514d511SHugh Dickins  * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
10031dbd01fSIzik Eidus  * @mm: the mm that this information is valid for
10131dbd01fSIzik Eidus  */
10231dbd01fSIzik Eidus struct mm_slot {
10331dbd01fSIzik Eidus 	struct hlist_node link;
10431dbd01fSIzik Eidus 	struct list_head mm_list;
1056514d511SHugh Dickins 	struct rmap_item *rmap_list;
10631dbd01fSIzik Eidus 	struct mm_struct *mm;
10731dbd01fSIzik Eidus };
10831dbd01fSIzik Eidus 
10931dbd01fSIzik Eidus /**
11031dbd01fSIzik Eidus  * struct ksm_scan - cursor for scanning
11131dbd01fSIzik Eidus  * @mm_slot: the current mm_slot we are scanning
11231dbd01fSIzik Eidus  * @address: the next address inside that to be scanned
1136514d511SHugh Dickins  * @rmap_list: link to the next rmap to be scanned in the rmap_list
11431dbd01fSIzik Eidus  * @seqnr: count of completed full scans (needed when removing unstable node)
11531dbd01fSIzik Eidus  *
11631dbd01fSIzik Eidus  * There is only the one ksm_scan instance of this cursor structure.
11731dbd01fSIzik Eidus  */
11831dbd01fSIzik Eidus struct ksm_scan {
11931dbd01fSIzik Eidus 	struct mm_slot *mm_slot;
12031dbd01fSIzik Eidus 	unsigned long address;
1216514d511SHugh Dickins 	struct rmap_item **rmap_list;
12231dbd01fSIzik Eidus 	unsigned long seqnr;
12331dbd01fSIzik Eidus };
12431dbd01fSIzik Eidus 
12531dbd01fSIzik Eidus /**
1267b6ba2c7SHugh Dickins  * struct stable_node - node of the stable rbtree
1277b6ba2c7SHugh Dickins  * @node: rb node of this ksm page in the stable tree
1284146d2d6SHugh Dickins  * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
1294146d2d6SHugh Dickins  * @list: linked into migrate_nodes, pending placement in the proper node tree
1307b6ba2c7SHugh Dickins  * @hlist: hlist head of rmap_items using this ksm page
1314146d2d6SHugh Dickins  * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
1324146d2d6SHugh Dickins  * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
1337b6ba2c7SHugh Dickins  */
1347b6ba2c7SHugh Dickins struct stable_node {
1354146d2d6SHugh Dickins 	union {
1364146d2d6SHugh Dickins 		struct rb_node node;	/* when node of stable tree */
1374146d2d6SHugh Dickins 		struct {		/* when listed for migration */
1384146d2d6SHugh Dickins 			struct list_head *head;
1394146d2d6SHugh Dickins 			struct list_head list;
1404146d2d6SHugh Dickins 		};
1414146d2d6SHugh Dickins 	};
1427b6ba2c7SHugh Dickins 	struct hlist_head hlist;
14362b61f61SHugh Dickins 	unsigned long kpfn;
1444146d2d6SHugh Dickins #ifdef CONFIG_NUMA
1454146d2d6SHugh Dickins 	int nid;
1464146d2d6SHugh Dickins #endif
1477b6ba2c7SHugh Dickins };
1487b6ba2c7SHugh Dickins 
1497b6ba2c7SHugh Dickins /**
15031dbd01fSIzik Eidus  * struct rmap_item - reverse mapping item for virtual addresses
1516514d511SHugh Dickins  * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
152db114b83SHugh Dickins  * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
153bc56620bSHugh Dickins  * @nid: NUMA node id of unstable tree in which linked (may not match page)
15431dbd01fSIzik Eidus  * @mm: the memory structure this rmap_item is pointing into
15531dbd01fSIzik Eidus  * @address: the virtual address this rmap_item tracks (+ flags in low bits)
15631dbd01fSIzik Eidus  * @oldchecksum: previous checksum of the page at that virtual address
1577b6ba2c7SHugh Dickins  * @node: rb node of this rmap_item in the unstable tree
1587b6ba2c7SHugh Dickins  * @head: pointer to stable_node heading this list in the stable tree
1597b6ba2c7SHugh Dickins  * @hlist: link into hlist of rmap_items hanging off that stable_node
16031dbd01fSIzik Eidus  */
16131dbd01fSIzik Eidus struct rmap_item {
1626514d511SHugh Dickins 	struct rmap_item *rmap_list;
163bc56620bSHugh Dickins 	union {
164db114b83SHugh Dickins 		struct anon_vma *anon_vma;	/* when stable */
165bc56620bSHugh Dickins #ifdef CONFIG_NUMA
166bc56620bSHugh Dickins 		int nid;		/* when node of unstable tree */
167bc56620bSHugh Dickins #endif
168bc56620bSHugh Dickins 	};
16931dbd01fSIzik Eidus 	struct mm_struct *mm;
17031dbd01fSIzik Eidus 	unsigned long address;		/* + low bits used for flags below */
17131dbd01fSIzik Eidus 	unsigned int oldchecksum;	/* when unstable */
17231dbd01fSIzik Eidus 	union {
1737b6ba2c7SHugh Dickins 		struct rb_node node;	/* when node of unstable tree */
1747b6ba2c7SHugh Dickins 		struct {		/* when listed from stable tree */
1757b6ba2c7SHugh Dickins 			struct stable_node *head;
1767b6ba2c7SHugh Dickins 			struct hlist_node hlist;
1777b6ba2c7SHugh Dickins 		};
17831dbd01fSIzik Eidus 	};
17931dbd01fSIzik Eidus };
18031dbd01fSIzik Eidus 
18131dbd01fSIzik Eidus #define SEQNR_MASK	0x0ff	/* low bits of unstable tree seqnr */
1827b6ba2c7SHugh Dickins #define UNSTABLE_FLAG	0x100	/* is a node of the unstable tree */
1837b6ba2c7SHugh Dickins #define STABLE_FLAG	0x200	/* is listed from the stable tree */
18431dbd01fSIzik Eidus 
18531dbd01fSIzik Eidus /* The stable and unstable tree heads */
186ef53d16cSHugh Dickins static struct rb_root one_stable_tree[1] = { RB_ROOT };
187ef53d16cSHugh Dickins static struct rb_root one_unstable_tree[1] = { RB_ROOT };
188ef53d16cSHugh Dickins static struct rb_root *root_stable_tree = one_stable_tree;
189ef53d16cSHugh Dickins static struct rb_root *root_unstable_tree = one_unstable_tree;
19031dbd01fSIzik Eidus 
1914146d2d6SHugh Dickins /* Recently migrated nodes of stable tree, pending proper placement */
1924146d2d6SHugh Dickins static LIST_HEAD(migrate_nodes);
1934146d2d6SHugh Dickins 
1944ca3a69bSSasha Levin #define MM_SLOTS_HASH_BITS 10
1954ca3a69bSSasha Levin static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
19631dbd01fSIzik Eidus 
19731dbd01fSIzik Eidus static struct mm_slot ksm_mm_head = {
19831dbd01fSIzik Eidus 	.mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
19931dbd01fSIzik Eidus };
20031dbd01fSIzik Eidus static struct ksm_scan ksm_scan = {
20131dbd01fSIzik Eidus 	.mm_slot = &ksm_mm_head,
20231dbd01fSIzik Eidus };
20331dbd01fSIzik Eidus 
20431dbd01fSIzik Eidus static struct kmem_cache *rmap_item_cache;
2057b6ba2c7SHugh Dickins static struct kmem_cache *stable_node_cache;
20631dbd01fSIzik Eidus static struct kmem_cache *mm_slot_cache;
20731dbd01fSIzik Eidus 
20831dbd01fSIzik Eidus /* The number of nodes in the stable tree */
209b4028260SHugh Dickins static unsigned long ksm_pages_shared;
21031dbd01fSIzik Eidus 
211e178dfdeSHugh Dickins /* The number of page slots additionally sharing those nodes */
212b4028260SHugh Dickins static unsigned long ksm_pages_sharing;
21331dbd01fSIzik Eidus 
214473b0ce4SHugh Dickins /* The number of nodes in the unstable tree */
215473b0ce4SHugh Dickins static unsigned long ksm_pages_unshared;
216473b0ce4SHugh Dickins 
217473b0ce4SHugh Dickins /* The number of rmap_items in use: to calculate pages_volatile */
218473b0ce4SHugh Dickins static unsigned long ksm_rmap_items;
219473b0ce4SHugh Dickins 
22031dbd01fSIzik Eidus /* Number of pages ksmd should scan in one batch */
2212c6854fdSIzik Eidus static unsigned int ksm_thread_pages_to_scan = 100;
22231dbd01fSIzik Eidus 
22331dbd01fSIzik Eidus /* Milliseconds ksmd should sleep between batches */
2242ffd8679SHugh Dickins static unsigned int ksm_thread_sleep_millisecs = 20;
22531dbd01fSIzik Eidus 
226e850dcf5SHugh Dickins #ifdef CONFIG_NUMA
22790bd6fd3SPetr Holasek /* Zeroed when merging across nodes is not allowed */
22890bd6fd3SPetr Holasek static unsigned int ksm_merge_across_nodes = 1;
229ef53d16cSHugh Dickins static int ksm_nr_node_ids = 1;
230e850dcf5SHugh Dickins #else
231e850dcf5SHugh Dickins #define ksm_merge_across_nodes	1U
232ef53d16cSHugh Dickins #define ksm_nr_node_ids		1
233e850dcf5SHugh Dickins #endif
23490bd6fd3SPetr Holasek 
23531dbd01fSIzik Eidus #define KSM_RUN_STOP	0
23631dbd01fSIzik Eidus #define KSM_RUN_MERGE	1
23731dbd01fSIzik Eidus #define KSM_RUN_UNMERGE	2
238ef4d43a8SHugh Dickins #define KSM_RUN_OFFLINE	4
239ef4d43a8SHugh Dickins static unsigned long ksm_run = KSM_RUN_STOP;
240ef4d43a8SHugh Dickins static void wait_while_offlining(void);
24131dbd01fSIzik Eidus 
24231dbd01fSIzik Eidus static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
24331dbd01fSIzik Eidus static DEFINE_MUTEX(ksm_thread_mutex);
24431dbd01fSIzik Eidus static DEFINE_SPINLOCK(ksm_mmlist_lock);
24531dbd01fSIzik Eidus 
24631dbd01fSIzik Eidus #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
24731dbd01fSIzik Eidus 		sizeof(struct __struct), __alignof__(struct __struct),\
24831dbd01fSIzik Eidus 		(__flags), NULL)
24931dbd01fSIzik Eidus 
25031dbd01fSIzik Eidus static int __init ksm_slab_init(void)
25131dbd01fSIzik Eidus {
25231dbd01fSIzik Eidus 	rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
25331dbd01fSIzik Eidus 	if (!rmap_item_cache)
25431dbd01fSIzik Eidus 		goto out;
25531dbd01fSIzik Eidus 
2567b6ba2c7SHugh Dickins 	stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
2577b6ba2c7SHugh Dickins 	if (!stable_node_cache)
2587b6ba2c7SHugh Dickins 		goto out_free1;
2597b6ba2c7SHugh Dickins 
26031dbd01fSIzik Eidus 	mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
26131dbd01fSIzik Eidus 	if (!mm_slot_cache)
2627b6ba2c7SHugh Dickins 		goto out_free2;
26331dbd01fSIzik Eidus 
26431dbd01fSIzik Eidus 	return 0;
26531dbd01fSIzik Eidus 
2667b6ba2c7SHugh Dickins out_free2:
2677b6ba2c7SHugh Dickins 	kmem_cache_destroy(stable_node_cache);
2687b6ba2c7SHugh Dickins out_free1:
26931dbd01fSIzik Eidus 	kmem_cache_destroy(rmap_item_cache);
27031dbd01fSIzik Eidus out:
27131dbd01fSIzik Eidus 	return -ENOMEM;
27231dbd01fSIzik Eidus }
27331dbd01fSIzik Eidus 
27431dbd01fSIzik Eidus static void __init ksm_slab_free(void)
27531dbd01fSIzik Eidus {
27631dbd01fSIzik Eidus 	kmem_cache_destroy(mm_slot_cache);
2777b6ba2c7SHugh Dickins 	kmem_cache_destroy(stable_node_cache);
27831dbd01fSIzik Eidus 	kmem_cache_destroy(rmap_item_cache);
27931dbd01fSIzik Eidus 	mm_slot_cache = NULL;
28031dbd01fSIzik Eidus }
28131dbd01fSIzik Eidus 
28231dbd01fSIzik Eidus static inline struct rmap_item *alloc_rmap_item(void)
28331dbd01fSIzik Eidus {
284473b0ce4SHugh Dickins 	struct rmap_item *rmap_item;
285473b0ce4SHugh Dickins 
286473b0ce4SHugh Dickins 	rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL);
287473b0ce4SHugh Dickins 	if (rmap_item)
288473b0ce4SHugh Dickins 		ksm_rmap_items++;
289473b0ce4SHugh Dickins 	return rmap_item;
29031dbd01fSIzik Eidus }
29131dbd01fSIzik Eidus 
29231dbd01fSIzik Eidus static inline void free_rmap_item(struct rmap_item *rmap_item)
29331dbd01fSIzik Eidus {
294473b0ce4SHugh Dickins 	ksm_rmap_items--;
29531dbd01fSIzik Eidus 	rmap_item->mm = NULL;	/* debug safety */
29631dbd01fSIzik Eidus 	kmem_cache_free(rmap_item_cache, rmap_item);
29731dbd01fSIzik Eidus }
29831dbd01fSIzik Eidus 
2997b6ba2c7SHugh Dickins static inline struct stable_node *alloc_stable_node(void)
3007b6ba2c7SHugh Dickins {
3017b6ba2c7SHugh Dickins 	return kmem_cache_alloc(stable_node_cache, GFP_KERNEL);
3027b6ba2c7SHugh Dickins }
3037b6ba2c7SHugh Dickins 
3047b6ba2c7SHugh Dickins static inline void free_stable_node(struct stable_node *stable_node)
3057b6ba2c7SHugh Dickins {
3067b6ba2c7SHugh Dickins 	kmem_cache_free(stable_node_cache, stable_node);
3077b6ba2c7SHugh Dickins }
3087b6ba2c7SHugh Dickins 
30931dbd01fSIzik Eidus static inline struct mm_slot *alloc_mm_slot(void)
31031dbd01fSIzik Eidus {
31131dbd01fSIzik Eidus 	if (!mm_slot_cache)	/* initialization failed */
31231dbd01fSIzik Eidus 		return NULL;
31331dbd01fSIzik Eidus 	return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
31431dbd01fSIzik Eidus }
31531dbd01fSIzik Eidus 
31631dbd01fSIzik Eidus static inline void free_mm_slot(struct mm_slot *mm_slot)
31731dbd01fSIzik Eidus {
31831dbd01fSIzik Eidus 	kmem_cache_free(mm_slot_cache, mm_slot);
31931dbd01fSIzik Eidus }
32031dbd01fSIzik Eidus 
32131dbd01fSIzik Eidus static struct mm_slot *get_mm_slot(struct mm_struct *mm)
32231dbd01fSIzik Eidus {
3234ca3a69bSSasha Levin 	struct mm_slot *slot;
32431dbd01fSIzik Eidus 
325b67bfe0dSSasha Levin 	hash_for_each_possible(mm_slots_hash, slot, link, (unsigned long)mm)
3264ca3a69bSSasha Levin 		if (slot->mm == mm)
3274ca3a69bSSasha Levin 			return slot;
3284ca3a69bSSasha Levin 
32931dbd01fSIzik Eidus 	return NULL;
33031dbd01fSIzik Eidus }
33131dbd01fSIzik Eidus 
33231dbd01fSIzik Eidus static void insert_to_mm_slots_hash(struct mm_struct *mm,
33331dbd01fSIzik Eidus 				    struct mm_slot *mm_slot)
33431dbd01fSIzik Eidus {
33531dbd01fSIzik Eidus 	mm_slot->mm = mm;
3364ca3a69bSSasha Levin 	hash_add(mm_slots_hash, &mm_slot->link, (unsigned long)mm);
33731dbd01fSIzik Eidus }
33831dbd01fSIzik Eidus 
33931dbd01fSIzik Eidus /*
340a913e182SHugh Dickins  * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
341a913e182SHugh Dickins  * page tables after it has passed through ksm_exit() - which, if necessary,
342a913e182SHugh Dickins  * takes mmap_sem briefly to serialize against them.  ksm_exit() does not set
343a913e182SHugh Dickins  * a special flag: they can just back out as soon as mm_users goes to zero.
344a913e182SHugh Dickins  * ksm_test_exit() is used throughout to make this test for exit: in some
345a913e182SHugh Dickins  * places for correctness, in some places just to avoid unnecessary work.
346a913e182SHugh Dickins  */
347a913e182SHugh Dickins static inline bool ksm_test_exit(struct mm_struct *mm)
348a913e182SHugh Dickins {
349a913e182SHugh Dickins 	return atomic_read(&mm->mm_users) == 0;
350a913e182SHugh Dickins }
351a913e182SHugh Dickins 
352a913e182SHugh Dickins /*
35331dbd01fSIzik Eidus  * We use break_ksm to break COW on a ksm page: it's a stripped down
35431dbd01fSIzik Eidus  *
355d4edcf0dSDave Hansen  *	if (get_user_pages(addr, 1, 1, 1, &page, NULL) == 1)
35631dbd01fSIzik Eidus  *		put_page(page);
35731dbd01fSIzik Eidus  *
35831dbd01fSIzik Eidus  * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
35931dbd01fSIzik Eidus  * in case the application has unmapped and remapped mm,addr meanwhile.
36031dbd01fSIzik Eidus  * Could a ksm page appear anywhere else?  Actually yes, in a VM_PFNMAP
36131dbd01fSIzik Eidus  * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
3621b2ee126SDave Hansen  *
3631b2ee126SDave Hansen  * FAULT_FLAG/FOLL_REMOTE are because we do this outside the context
3641b2ee126SDave Hansen  * of the process that owns 'vma'.  We also do not want to enforce
3651b2ee126SDave Hansen  * protection keys here anyway.
36631dbd01fSIzik Eidus  */
367d952b791SHugh Dickins static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
36831dbd01fSIzik Eidus {
36931dbd01fSIzik Eidus 	struct page *page;
370d952b791SHugh Dickins 	int ret = 0;
37131dbd01fSIzik Eidus 
37231dbd01fSIzik Eidus 	do {
37331dbd01fSIzik Eidus 		cond_resched();
3741b2ee126SDave Hansen 		page = follow_page(vma, addr,
3751b2ee126SDave Hansen 				FOLL_GET | FOLL_MIGRATION | FOLL_REMOTE);
37622eccdd7SDan Carpenter 		if (IS_ERR_OR_NULL(page))
37731dbd01fSIzik Eidus 			break;
37831dbd01fSIzik Eidus 		if (PageKsm(page))
379*dcddffd4SKirill A. Shutemov 			ret = handle_mm_fault(vma, addr,
380*dcddffd4SKirill A. Shutemov 					FAULT_FLAG_WRITE | FAULT_FLAG_REMOTE);
38131dbd01fSIzik Eidus 		else
38231dbd01fSIzik Eidus 			ret = VM_FAULT_WRITE;
38331dbd01fSIzik Eidus 		put_page(page);
38433692f27SLinus Torvalds 	} while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
385d952b791SHugh Dickins 	/*
386d952b791SHugh Dickins 	 * We must loop because handle_mm_fault() may back out if there's
387d952b791SHugh Dickins 	 * any difficulty e.g. if pte accessed bit gets updated concurrently.
388d952b791SHugh Dickins 	 *
389d952b791SHugh Dickins 	 * VM_FAULT_WRITE is what we have been hoping for: it indicates that
390d952b791SHugh Dickins 	 * COW has been broken, even if the vma does not permit VM_WRITE;
391d952b791SHugh Dickins 	 * but note that a concurrent fault might break PageKsm for us.
392d952b791SHugh Dickins 	 *
393d952b791SHugh Dickins 	 * VM_FAULT_SIGBUS could occur if we race with truncation of the
394d952b791SHugh Dickins 	 * backing file, which also invalidates anonymous pages: that's
395d952b791SHugh Dickins 	 * okay, that truncation will have unmapped the PageKsm for us.
396d952b791SHugh Dickins 	 *
397d952b791SHugh Dickins 	 * VM_FAULT_OOM: at the time of writing (late July 2009), setting
398d952b791SHugh Dickins 	 * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
399d952b791SHugh Dickins 	 * current task has TIF_MEMDIE set, and will be OOM killed on return
400d952b791SHugh Dickins 	 * to user; and ksmd, having no mm, would never be chosen for that.
401d952b791SHugh Dickins 	 *
402d952b791SHugh Dickins 	 * But if the mm is in a limited mem_cgroup, then the fault may fail
403d952b791SHugh Dickins 	 * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
404d952b791SHugh Dickins 	 * even ksmd can fail in this way - though it's usually breaking ksm
405d952b791SHugh Dickins 	 * just to undo a merge it made a moment before, so unlikely to oom.
406d952b791SHugh Dickins 	 *
407d952b791SHugh Dickins 	 * That's a pity: we might therefore have more kernel pages allocated
408d952b791SHugh Dickins 	 * than we're counting as nodes in the stable tree; but ksm_do_scan
409d952b791SHugh Dickins 	 * will retry to break_cow on each pass, so should recover the page
410d952b791SHugh Dickins 	 * in due course.  The important thing is to not let VM_MERGEABLE
411d952b791SHugh Dickins 	 * be cleared while any such pages might remain in the area.
412d952b791SHugh Dickins 	 */
413d952b791SHugh Dickins 	return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
41431dbd01fSIzik Eidus }
41531dbd01fSIzik Eidus 
416ef694222SBob Liu static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
417ef694222SBob Liu 		unsigned long addr)
418ef694222SBob Liu {
419ef694222SBob Liu 	struct vm_area_struct *vma;
420ef694222SBob Liu 	if (ksm_test_exit(mm))
421ef694222SBob Liu 		return NULL;
422ef694222SBob Liu 	vma = find_vma(mm, addr);
423ef694222SBob Liu 	if (!vma || vma->vm_start > addr)
424ef694222SBob Liu 		return NULL;
425ef694222SBob Liu 	if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
426ef694222SBob Liu 		return NULL;
427ef694222SBob Liu 	return vma;
428ef694222SBob Liu }
429ef694222SBob Liu 
4308dd3557aSHugh Dickins static void break_cow(struct rmap_item *rmap_item)
43131dbd01fSIzik Eidus {
4328dd3557aSHugh Dickins 	struct mm_struct *mm = rmap_item->mm;
4338dd3557aSHugh Dickins 	unsigned long addr = rmap_item->address;
43431dbd01fSIzik Eidus 	struct vm_area_struct *vma;
43531dbd01fSIzik Eidus 
4364035c07aSHugh Dickins 	/*
4374035c07aSHugh Dickins 	 * It is not an accident that whenever we want to break COW
4384035c07aSHugh Dickins 	 * to undo, we also need to drop a reference to the anon_vma.
4394035c07aSHugh Dickins 	 */
4409e60109fSPeter Zijlstra 	put_anon_vma(rmap_item->anon_vma);
4414035c07aSHugh Dickins 
44281464e30SHugh Dickins 	down_read(&mm->mmap_sem);
443ef694222SBob Liu 	vma = find_mergeable_vma(mm, addr);
444ef694222SBob Liu 	if (vma)
44531dbd01fSIzik Eidus 		break_ksm(vma, addr);
44631dbd01fSIzik Eidus 	up_read(&mm->mmap_sem);
44731dbd01fSIzik Eidus }
44831dbd01fSIzik Eidus 
44931dbd01fSIzik Eidus static struct page *get_mergeable_page(struct rmap_item *rmap_item)
45031dbd01fSIzik Eidus {
45131dbd01fSIzik Eidus 	struct mm_struct *mm = rmap_item->mm;
45231dbd01fSIzik Eidus 	unsigned long addr = rmap_item->address;
45331dbd01fSIzik Eidus 	struct vm_area_struct *vma;
45431dbd01fSIzik Eidus 	struct page *page;
45531dbd01fSIzik Eidus 
45631dbd01fSIzik Eidus 	down_read(&mm->mmap_sem);
457ef694222SBob Liu 	vma = find_mergeable_vma(mm, addr);
458ef694222SBob Liu 	if (!vma)
45931dbd01fSIzik Eidus 		goto out;
46031dbd01fSIzik Eidus 
46131dbd01fSIzik Eidus 	page = follow_page(vma, addr, FOLL_GET);
46222eccdd7SDan Carpenter 	if (IS_ERR_OR_NULL(page))
46331dbd01fSIzik Eidus 		goto out;
464f765f540SKirill A. Shutemov 	if (PageAnon(page)) {
46531dbd01fSIzik Eidus 		flush_anon_page(vma, page, addr);
46631dbd01fSIzik Eidus 		flush_dcache_page(page);
46731dbd01fSIzik Eidus 	} else {
46831dbd01fSIzik Eidus 		put_page(page);
469c8f95ed1SAndrea Arcangeli out:
470c8f95ed1SAndrea Arcangeli 		page = NULL;
47131dbd01fSIzik Eidus 	}
47231dbd01fSIzik Eidus 	up_read(&mm->mmap_sem);
47331dbd01fSIzik Eidus 	return page;
47431dbd01fSIzik Eidus }
47531dbd01fSIzik Eidus 
47690bd6fd3SPetr Holasek /*
47790bd6fd3SPetr Holasek  * This helper is used for getting right index into array of tree roots.
47890bd6fd3SPetr Holasek  * When merge_across_nodes knob is set to 1, there are only two rb-trees for
47990bd6fd3SPetr Holasek  * stable and unstable pages from all nodes with roots in index 0. Otherwise,
48090bd6fd3SPetr Holasek  * every node has its own stable and unstable tree.
48190bd6fd3SPetr Holasek  */
48290bd6fd3SPetr Holasek static inline int get_kpfn_nid(unsigned long kpfn)
48390bd6fd3SPetr Holasek {
484d8fc16a8SHugh Dickins 	return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
48590bd6fd3SPetr Holasek }
48690bd6fd3SPetr Holasek 
4874035c07aSHugh Dickins static void remove_node_from_stable_tree(struct stable_node *stable_node)
4884035c07aSHugh Dickins {
4894035c07aSHugh Dickins 	struct rmap_item *rmap_item;
4904035c07aSHugh Dickins 
491b67bfe0dSSasha Levin 	hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
4924035c07aSHugh Dickins 		if (rmap_item->hlist.next)
4934035c07aSHugh Dickins 			ksm_pages_sharing--;
4944035c07aSHugh Dickins 		else
4954035c07aSHugh Dickins 			ksm_pages_shared--;
4969e60109fSPeter Zijlstra 		put_anon_vma(rmap_item->anon_vma);
4974035c07aSHugh Dickins 		rmap_item->address &= PAGE_MASK;
4984035c07aSHugh Dickins 		cond_resched();
4994035c07aSHugh Dickins 	}
5004035c07aSHugh Dickins 
5014146d2d6SHugh Dickins 	if (stable_node->head == &migrate_nodes)
5024146d2d6SHugh Dickins 		list_del(&stable_node->list);
5034146d2d6SHugh Dickins 	else
5044146d2d6SHugh Dickins 		rb_erase(&stable_node->node,
505ef53d16cSHugh Dickins 			 root_stable_tree + NUMA(stable_node->nid));
5064035c07aSHugh Dickins 	free_stable_node(stable_node);
5074035c07aSHugh Dickins }
5084035c07aSHugh Dickins 
5094035c07aSHugh Dickins /*
5104035c07aSHugh Dickins  * get_ksm_page: checks if the page indicated by the stable node
5114035c07aSHugh Dickins  * is still its ksm page, despite having held no reference to it.
5124035c07aSHugh Dickins  * In which case we can trust the content of the page, and it
5134035c07aSHugh Dickins  * returns the gotten page; but if the page has now been zapped,
5144035c07aSHugh Dickins  * remove the stale node from the stable tree and return NULL.
515c8d6553bSHugh Dickins  * But beware, the stable node's page might be being migrated.
5164035c07aSHugh Dickins  *
5174035c07aSHugh Dickins  * You would expect the stable_node to hold a reference to the ksm page.
5184035c07aSHugh Dickins  * But if it increments the page's count, swapping out has to wait for
5194035c07aSHugh Dickins  * ksmd to come around again before it can free the page, which may take
5204035c07aSHugh Dickins  * seconds or even minutes: much too unresponsive.  So instead we use a
5214035c07aSHugh Dickins  * "keyhole reference": access to the ksm page from the stable node peeps
5224035c07aSHugh Dickins  * out through its keyhole to see if that page still holds the right key,
5234035c07aSHugh Dickins  * pointing back to this stable node.  This relies on freeing a PageAnon
5244035c07aSHugh Dickins  * page to reset its page->mapping to NULL, and relies on no other use of
5254035c07aSHugh Dickins  * a page to put something that might look like our key in page->mapping.
5264035c07aSHugh Dickins  * is on its way to being freed; but it is an anomaly to bear in mind.
5274035c07aSHugh Dickins  */
5288fdb3dbfSHugh Dickins static struct page *get_ksm_page(struct stable_node *stable_node, bool lock_it)
5294035c07aSHugh Dickins {
5304035c07aSHugh Dickins 	struct page *page;
5314035c07aSHugh Dickins 	void *expected_mapping;
532c8d6553bSHugh Dickins 	unsigned long kpfn;
5334035c07aSHugh Dickins 
534bda807d4SMinchan Kim 	expected_mapping = (void *)((unsigned long)stable_node |
535bda807d4SMinchan Kim 					PAGE_MAPPING_KSM);
536c8d6553bSHugh Dickins again:
5374db0c3c2SJason Low 	kpfn = READ_ONCE(stable_node->kpfn);
538c8d6553bSHugh Dickins 	page = pfn_to_page(kpfn);
539c8d6553bSHugh Dickins 
540c8d6553bSHugh Dickins 	/*
541c8d6553bSHugh Dickins 	 * page is computed from kpfn, so on most architectures reading
542c8d6553bSHugh Dickins 	 * page->mapping is naturally ordered after reading node->kpfn,
543c8d6553bSHugh Dickins 	 * but on Alpha we need to be more careful.
544c8d6553bSHugh Dickins 	 */
545c8d6553bSHugh Dickins 	smp_read_barrier_depends();
5464db0c3c2SJason Low 	if (READ_ONCE(page->mapping) != expected_mapping)
5474035c07aSHugh Dickins 		goto stale;
548c8d6553bSHugh Dickins 
549c8d6553bSHugh Dickins 	/*
550c8d6553bSHugh Dickins 	 * We cannot do anything with the page while its refcount is 0.
551c8d6553bSHugh Dickins 	 * Usually 0 means free, or tail of a higher-order page: in which
552c8d6553bSHugh Dickins 	 * case this node is no longer referenced, and should be freed;
553c8d6553bSHugh Dickins 	 * however, it might mean that the page is under page_freeze_refs().
554c8d6553bSHugh Dickins 	 * The __remove_mapping() case is easy, again the node is now stale;
555c8d6553bSHugh Dickins 	 * but if page is swapcache in migrate_page_move_mapping(), it might
556c8d6553bSHugh Dickins 	 * still be our page, in which case it's essential to keep the node.
557c8d6553bSHugh Dickins 	 */
558c8d6553bSHugh Dickins 	while (!get_page_unless_zero(page)) {
559c8d6553bSHugh Dickins 		/*
560c8d6553bSHugh Dickins 		 * Another check for page->mapping != expected_mapping would
561c8d6553bSHugh Dickins 		 * work here too.  We have chosen the !PageSwapCache test to
562c8d6553bSHugh Dickins 		 * optimize the common case, when the page is or is about to
563c8d6553bSHugh Dickins 		 * be freed: PageSwapCache is cleared (under spin_lock_irq)
564c8d6553bSHugh Dickins 		 * in the freeze_refs section of __remove_mapping(); but Anon
565c8d6553bSHugh Dickins 		 * page->mapping reset to NULL later, in free_pages_prepare().
566c8d6553bSHugh Dickins 		 */
567c8d6553bSHugh Dickins 		if (!PageSwapCache(page))
5684035c07aSHugh Dickins 			goto stale;
569c8d6553bSHugh Dickins 		cpu_relax();
570c8d6553bSHugh Dickins 	}
571c8d6553bSHugh Dickins 
5724db0c3c2SJason Low 	if (READ_ONCE(page->mapping) != expected_mapping) {
5734035c07aSHugh Dickins 		put_page(page);
5744035c07aSHugh Dickins 		goto stale;
5754035c07aSHugh Dickins 	}
576c8d6553bSHugh Dickins 
5778fdb3dbfSHugh Dickins 	if (lock_it) {
5788aafa6a4SHugh Dickins 		lock_page(page);
5794db0c3c2SJason Low 		if (READ_ONCE(page->mapping) != expected_mapping) {
5808aafa6a4SHugh Dickins 			unlock_page(page);
5818aafa6a4SHugh Dickins 			put_page(page);
5828aafa6a4SHugh Dickins 			goto stale;
5838aafa6a4SHugh Dickins 		}
5848aafa6a4SHugh Dickins 	}
5854035c07aSHugh Dickins 	return page;
586c8d6553bSHugh Dickins 
5874035c07aSHugh Dickins stale:
588c8d6553bSHugh Dickins 	/*
589c8d6553bSHugh Dickins 	 * We come here from above when page->mapping or !PageSwapCache
590c8d6553bSHugh Dickins 	 * suggests that the node is stale; but it might be under migration.
591c8d6553bSHugh Dickins 	 * We need smp_rmb(), matching the smp_wmb() in ksm_migrate_page(),
592c8d6553bSHugh Dickins 	 * before checking whether node->kpfn has been changed.
593c8d6553bSHugh Dickins 	 */
594c8d6553bSHugh Dickins 	smp_rmb();
5954db0c3c2SJason Low 	if (READ_ONCE(stable_node->kpfn) != kpfn)
596c8d6553bSHugh Dickins 		goto again;
5974035c07aSHugh Dickins 	remove_node_from_stable_tree(stable_node);
5984035c07aSHugh Dickins 	return NULL;
5994035c07aSHugh Dickins }
6004035c07aSHugh Dickins 
60131dbd01fSIzik Eidus /*
60231dbd01fSIzik Eidus  * Removing rmap_item from stable or unstable tree.
60331dbd01fSIzik Eidus  * This function will clean the information from the stable/unstable tree.
60431dbd01fSIzik Eidus  */
60531dbd01fSIzik Eidus static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
60631dbd01fSIzik Eidus {
6077b6ba2c7SHugh Dickins 	if (rmap_item->address & STABLE_FLAG) {
6087b6ba2c7SHugh Dickins 		struct stable_node *stable_node;
6095ad64688SHugh Dickins 		struct page *page;
61031dbd01fSIzik Eidus 
6117b6ba2c7SHugh Dickins 		stable_node = rmap_item->head;
6128aafa6a4SHugh Dickins 		page = get_ksm_page(stable_node, true);
6134035c07aSHugh Dickins 		if (!page)
6144035c07aSHugh Dickins 			goto out;
6155ad64688SHugh Dickins 
6167b6ba2c7SHugh Dickins 		hlist_del(&rmap_item->hlist);
6175ad64688SHugh Dickins 		unlock_page(page);
6185ad64688SHugh Dickins 		put_page(page);
61908beca44SHugh Dickins 
62098666f8aSAndrea Arcangeli 		if (!hlist_empty(&stable_node->hlist))
6214035c07aSHugh Dickins 			ksm_pages_sharing--;
6224035c07aSHugh Dickins 		else
623b4028260SHugh Dickins 			ksm_pages_shared--;
62431dbd01fSIzik Eidus 
6259e60109fSPeter Zijlstra 		put_anon_vma(rmap_item->anon_vma);
62693d17715SHugh Dickins 		rmap_item->address &= PAGE_MASK;
62731dbd01fSIzik Eidus 
6287b6ba2c7SHugh Dickins 	} else if (rmap_item->address & UNSTABLE_FLAG) {
62931dbd01fSIzik Eidus 		unsigned char age;
63031dbd01fSIzik Eidus 		/*
6319ba69294SHugh Dickins 		 * Usually ksmd can and must skip the rb_erase, because
63231dbd01fSIzik Eidus 		 * root_unstable_tree was already reset to RB_ROOT.
6339ba69294SHugh Dickins 		 * But be careful when an mm is exiting: do the rb_erase
6349ba69294SHugh Dickins 		 * if this rmap_item was inserted by this scan, rather
6359ba69294SHugh Dickins 		 * than left over from before.
63631dbd01fSIzik Eidus 		 */
63731dbd01fSIzik Eidus 		age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
638cd551f97SHugh Dickins 		BUG_ON(age > 1);
63931dbd01fSIzik Eidus 		if (!age)
64090bd6fd3SPetr Holasek 			rb_erase(&rmap_item->node,
641ef53d16cSHugh Dickins 				 root_unstable_tree + NUMA(rmap_item->nid));
64293d17715SHugh Dickins 		ksm_pages_unshared--;
64331dbd01fSIzik Eidus 		rmap_item->address &= PAGE_MASK;
64493d17715SHugh Dickins 	}
6454035c07aSHugh Dickins out:
64631dbd01fSIzik Eidus 	cond_resched();		/* we're called from many long loops */
64731dbd01fSIzik Eidus }
64831dbd01fSIzik Eidus 
64931dbd01fSIzik Eidus static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
6506514d511SHugh Dickins 				       struct rmap_item **rmap_list)
65131dbd01fSIzik Eidus {
6526514d511SHugh Dickins 	while (*rmap_list) {
6536514d511SHugh Dickins 		struct rmap_item *rmap_item = *rmap_list;
6546514d511SHugh Dickins 		*rmap_list = rmap_item->rmap_list;
65531dbd01fSIzik Eidus 		remove_rmap_item_from_tree(rmap_item);
65631dbd01fSIzik Eidus 		free_rmap_item(rmap_item);
65731dbd01fSIzik Eidus 	}
65831dbd01fSIzik Eidus }
65931dbd01fSIzik Eidus 
66031dbd01fSIzik Eidus /*
661e850dcf5SHugh Dickins  * Though it's very tempting to unmerge rmap_items from stable tree rather
66231dbd01fSIzik Eidus  * than check every pte of a given vma, the locking doesn't quite work for
66331dbd01fSIzik Eidus  * that - an rmap_item is assigned to the stable tree after inserting ksm
66431dbd01fSIzik Eidus  * page and upping mmap_sem.  Nor does it fit with the way we skip dup'ing
66531dbd01fSIzik Eidus  * rmap_items from parent to child at fork time (so as not to waste time
66631dbd01fSIzik Eidus  * if exit comes before the next scan reaches it).
66781464e30SHugh Dickins  *
66881464e30SHugh Dickins  * Similarly, although we'd like to remove rmap_items (so updating counts
66981464e30SHugh Dickins  * and freeing memory) when unmerging an area, it's easier to leave that
67081464e30SHugh Dickins  * to the next pass of ksmd - consider, for example, how ksmd might be
67181464e30SHugh Dickins  * in cmp_and_merge_page on one of the rmap_items we would be removing.
67231dbd01fSIzik Eidus  */
673d952b791SHugh Dickins static int unmerge_ksm_pages(struct vm_area_struct *vma,
67431dbd01fSIzik Eidus 			     unsigned long start, unsigned long end)
67531dbd01fSIzik Eidus {
67631dbd01fSIzik Eidus 	unsigned long addr;
677d952b791SHugh Dickins 	int err = 0;
67831dbd01fSIzik Eidus 
679d952b791SHugh Dickins 	for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
6809ba69294SHugh Dickins 		if (ksm_test_exit(vma->vm_mm))
6819ba69294SHugh Dickins 			break;
682d952b791SHugh Dickins 		if (signal_pending(current))
683d952b791SHugh Dickins 			err = -ERESTARTSYS;
684d952b791SHugh Dickins 		else
685d952b791SHugh Dickins 			err = break_ksm(vma, addr);
686d952b791SHugh Dickins 	}
687d952b791SHugh Dickins 	return err;
68831dbd01fSIzik Eidus }
68931dbd01fSIzik Eidus 
6902ffd8679SHugh Dickins #ifdef CONFIG_SYSFS
6912ffd8679SHugh Dickins /*
6922ffd8679SHugh Dickins  * Only called through the sysfs control interface:
6932ffd8679SHugh Dickins  */
694cbf86cfeSHugh Dickins static int remove_stable_node(struct stable_node *stable_node)
695cbf86cfeSHugh Dickins {
696cbf86cfeSHugh Dickins 	struct page *page;
697cbf86cfeSHugh Dickins 	int err;
698cbf86cfeSHugh Dickins 
699cbf86cfeSHugh Dickins 	page = get_ksm_page(stable_node, true);
700cbf86cfeSHugh Dickins 	if (!page) {
701cbf86cfeSHugh Dickins 		/*
702cbf86cfeSHugh Dickins 		 * get_ksm_page did remove_node_from_stable_tree itself.
703cbf86cfeSHugh Dickins 		 */
704cbf86cfeSHugh Dickins 		return 0;
705cbf86cfeSHugh Dickins 	}
706cbf86cfeSHugh Dickins 
7078fdb3dbfSHugh Dickins 	if (WARN_ON_ONCE(page_mapped(page))) {
708cbf86cfeSHugh Dickins 		/*
7098fdb3dbfSHugh Dickins 		 * This should not happen: but if it does, just refuse to let
7108fdb3dbfSHugh Dickins 		 * merge_across_nodes be switched - there is no need to panic.
7118fdb3dbfSHugh Dickins 		 */
7128fdb3dbfSHugh Dickins 		err = -EBUSY;
7138fdb3dbfSHugh Dickins 	} else {
7148fdb3dbfSHugh Dickins 		/*
7158fdb3dbfSHugh Dickins 		 * The stable node did not yet appear stale to get_ksm_page(),
7168fdb3dbfSHugh Dickins 		 * since that allows for an unmapped ksm page to be recognized
7178fdb3dbfSHugh Dickins 		 * right up until it is freed; but the node is safe to remove.
718cbf86cfeSHugh Dickins 		 * This page might be in a pagevec waiting to be freed,
719cbf86cfeSHugh Dickins 		 * or it might be PageSwapCache (perhaps under writeback),
720cbf86cfeSHugh Dickins 		 * or it might have been removed from swapcache a moment ago.
721cbf86cfeSHugh Dickins 		 */
722cbf86cfeSHugh Dickins 		set_page_stable_node(page, NULL);
723cbf86cfeSHugh Dickins 		remove_node_from_stable_tree(stable_node);
724cbf86cfeSHugh Dickins 		err = 0;
725cbf86cfeSHugh Dickins 	}
726cbf86cfeSHugh Dickins 
727cbf86cfeSHugh Dickins 	unlock_page(page);
728cbf86cfeSHugh Dickins 	put_page(page);
729cbf86cfeSHugh Dickins 	return err;
730cbf86cfeSHugh Dickins }
731cbf86cfeSHugh Dickins 
732cbf86cfeSHugh Dickins static int remove_all_stable_nodes(void)
733cbf86cfeSHugh Dickins {
73403640418SGeliang Tang 	struct stable_node *stable_node, *next;
735cbf86cfeSHugh Dickins 	int nid;
736cbf86cfeSHugh Dickins 	int err = 0;
737cbf86cfeSHugh Dickins 
738ef53d16cSHugh Dickins 	for (nid = 0; nid < ksm_nr_node_ids; nid++) {
739cbf86cfeSHugh Dickins 		while (root_stable_tree[nid].rb_node) {
740cbf86cfeSHugh Dickins 			stable_node = rb_entry(root_stable_tree[nid].rb_node,
741cbf86cfeSHugh Dickins 						struct stable_node, node);
742cbf86cfeSHugh Dickins 			if (remove_stable_node(stable_node)) {
743cbf86cfeSHugh Dickins 				err = -EBUSY;
744cbf86cfeSHugh Dickins 				break;	/* proceed to next nid */
745cbf86cfeSHugh Dickins 			}
746cbf86cfeSHugh Dickins 			cond_resched();
747cbf86cfeSHugh Dickins 		}
748cbf86cfeSHugh Dickins 	}
74903640418SGeliang Tang 	list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
7504146d2d6SHugh Dickins 		if (remove_stable_node(stable_node))
7514146d2d6SHugh Dickins 			err = -EBUSY;
7524146d2d6SHugh Dickins 		cond_resched();
7534146d2d6SHugh Dickins 	}
754cbf86cfeSHugh Dickins 	return err;
755cbf86cfeSHugh Dickins }
756cbf86cfeSHugh Dickins 
757d952b791SHugh Dickins static int unmerge_and_remove_all_rmap_items(void)
75831dbd01fSIzik Eidus {
75931dbd01fSIzik Eidus 	struct mm_slot *mm_slot;
76031dbd01fSIzik Eidus 	struct mm_struct *mm;
76131dbd01fSIzik Eidus 	struct vm_area_struct *vma;
762d952b791SHugh Dickins 	int err = 0;
76331dbd01fSIzik Eidus 
764d952b791SHugh Dickins 	spin_lock(&ksm_mmlist_lock);
7659ba69294SHugh Dickins 	ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
766d952b791SHugh Dickins 						struct mm_slot, mm_list);
767d952b791SHugh Dickins 	spin_unlock(&ksm_mmlist_lock);
768d952b791SHugh Dickins 
7699ba69294SHugh Dickins 	for (mm_slot = ksm_scan.mm_slot;
7709ba69294SHugh Dickins 			mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
77131dbd01fSIzik Eidus 		mm = mm_slot->mm;
77231dbd01fSIzik Eidus 		down_read(&mm->mmap_sem);
77331dbd01fSIzik Eidus 		for (vma = mm->mmap; vma; vma = vma->vm_next) {
7749ba69294SHugh Dickins 			if (ksm_test_exit(mm))
7759ba69294SHugh Dickins 				break;
77631dbd01fSIzik Eidus 			if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
77731dbd01fSIzik Eidus 				continue;
778d952b791SHugh Dickins 			err = unmerge_ksm_pages(vma,
779d952b791SHugh Dickins 						vma->vm_start, vma->vm_end);
7809ba69294SHugh Dickins 			if (err)
7819ba69294SHugh Dickins 				goto error;
782d952b791SHugh Dickins 		}
7839ba69294SHugh Dickins 
7846514d511SHugh Dickins 		remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
7857496fea9SZhou Chengming 		up_read(&mm->mmap_sem);
78631dbd01fSIzik Eidus 
78731dbd01fSIzik Eidus 		spin_lock(&ksm_mmlist_lock);
7889ba69294SHugh Dickins 		ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
789d952b791SHugh Dickins 						struct mm_slot, mm_list);
7909ba69294SHugh Dickins 		if (ksm_test_exit(mm)) {
7914ca3a69bSSasha Levin 			hash_del(&mm_slot->link);
7929ba69294SHugh Dickins 			list_del(&mm_slot->mm_list);
79331dbd01fSIzik Eidus 			spin_unlock(&ksm_mmlist_lock);
7949ba69294SHugh Dickins 
7959ba69294SHugh Dickins 			free_mm_slot(mm_slot);
7969ba69294SHugh Dickins 			clear_bit(MMF_VM_MERGEABLE, &mm->flags);
7979ba69294SHugh Dickins 			mmdrop(mm);
7987496fea9SZhou Chengming 		} else
7999ba69294SHugh Dickins 			spin_unlock(&ksm_mmlist_lock);
80031dbd01fSIzik Eidus 	}
80131dbd01fSIzik Eidus 
802cbf86cfeSHugh Dickins 	/* Clean up stable nodes, but don't worry if some are still busy */
803cbf86cfeSHugh Dickins 	remove_all_stable_nodes();
804d952b791SHugh Dickins 	ksm_scan.seqnr = 0;
8059ba69294SHugh Dickins 	return 0;
8069ba69294SHugh Dickins 
8079ba69294SHugh Dickins error:
8089ba69294SHugh Dickins 	up_read(&mm->mmap_sem);
809d952b791SHugh Dickins 	spin_lock(&ksm_mmlist_lock);
810d952b791SHugh Dickins 	ksm_scan.mm_slot = &ksm_mm_head;
811d952b791SHugh Dickins 	spin_unlock(&ksm_mmlist_lock);
812d952b791SHugh Dickins 	return err;
813d952b791SHugh Dickins }
8142ffd8679SHugh Dickins #endif /* CONFIG_SYSFS */
815d952b791SHugh Dickins 
81631dbd01fSIzik Eidus static u32 calc_checksum(struct page *page)
81731dbd01fSIzik Eidus {
81831dbd01fSIzik Eidus 	u32 checksum;
8199b04c5feSCong Wang 	void *addr = kmap_atomic(page);
82031dbd01fSIzik Eidus 	checksum = jhash2(addr, PAGE_SIZE / 4, 17);
8219b04c5feSCong Wang 	kunmap_atomic(addr);
82231dbd01fSIzik Eidus 	return checksum;
82331dbd01fSIzik Eidus }
82431dbd01fSIzik Eidus 
82531dbd01fSIzik Eidus static int memcmp_pages(struct page *page1, struct page *page2)
82631dbd01fSIzik Eidus {
82731dbd01fSIzik Eidus 	char *addr1, *addr2;
82831dbd01fSIzik Eidus 	int ret;
82931dbd01fSIzik Eidus 
8309b04c5feSCong Wang 	addr1 = kmap_atomic(page1);
8319b04c5feSCong Wang 	addr2 = kmap_atomic(page2);
83231dbd01fSIzik Eidus 	ret = memcmp(addr1, addr2, PAGE_SIZE);
8339b04c5feSCong Wang 	kunmap_atomic(addr2);
8349b04c5feSCong Wang 	kunmap_atomic(addr1);
83531dbd01fSIzik Eidus 	return ret;
83631dbd01fSIzik Eidus }
83731dbd01fSIzik Eidus 
83831dbd01fSIzik Eidus static inline int pages_identical(struct page *page1, struct page *page2)
83931dbd01fSIzik Eidus {
84031dbd01fSIzik Eidus 	return !memcmp_pages(page1, page2);
84131dbd01fSIzik Eidus }
84231dbd01fSIzik Eidus 
84331dbd01fSIzik Eidus static int write_protect_page(struct vm_area_struct *vma, struct page *page,
84431dbd01fSIzik Eidus 			      pte_t *orig_pte)
84531dbd01fSIzik Eidus {
84631dbd01fSIzik Eidus 	struct mm_struct *mm = vma->vm_mm;
84731dbd01fSIzik Eidus 	unsigned long addr;
84831dbd01fSIzik Eidus 	pte_t *ptep;
84931dbd01fSIzik Eidus 	spinlock_t *ptl;
85031dbd01fSIzik Eidus 	int swapped;
85131dbd01fSIzik Eidus 	int err = -EFAULT;
8526bdb913fSHaggai Eran 	unsigned long mmun_start;	/* For mmu_notifiers */
8536bdb913fSHaggai Eran 	unsigned long mmun_end;		/* For mmu_notifiers */
85431dbd01fSIzik Eidus 
85531dbd01fSIzik Eidus 	addr = page_address_in_vma(page, vma);
85631dbd01fSIzik Eidus 	if (addr == -EFAULT)
85731dbd01fSIzik Eidus 		goto out;
85831dbd01fSIzik Eidus 
85929ad768cSAndrea Arcangeli 	BUG_ON(PageTransCompound(page));
8606bdb913fSHaggai Eran 
8616bdb913fSHaggai Eran 	mmun_start = addr;
8626bdb913fSHaggai Eran 	mmun_end   = addr + PAGE_SIZE;
8636bdb913fSHaggai Eran 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
8646bdb913fSHaggai Eran 
86531dbd01fSIzik Eidus 	ptep = page_check_address(page, mm, addr, &ptl, 0);
86631dbd01fSIzik Eidus 	if (!ptep)
8676bdb913fSHaggai Eran 		goto out_mn;
86831dbd01fSIzik Eidus 
8694e31635cSHugh Dickins 	if (pte_write(*ptep) || pte_dirty(*ptep)) {
87031dbd01fSIzik Eidus 		pte_t entry;
87131dbd01fSIzik Eidus 
87231dbd01fSIzik Eidus 		swapped = PageSwapCache(page);
87331dbd01fSIzik Eidus 		flush_cache_page(vma, addr, page_to_pfn(page));
87431dbd01fSIzik Eidus 		/*
87525985edcSLucas De Marchi 		 * Ok this is tricky, when get_user_pages_fast() run it doesn't
87631dbd01fSIzik Eidus 		 * take any lock, therefore the check that we are going to make
87731dbd01fSIzik Eidus 		 * with the pagecount against the mapcount is racey and
87831dbd01fSIzik Eidus 		 * O_DIRECT can happen right after the check.
87931dbd01fSIzik Eidus 		 * So we clear the pte and flush the tlb before the check
88031dbd01fSIzik Eidus 		 * this assure us that no O_DIRECT can happen after the check
88131dbd01fSIzik Eidus 		 * or in the middle of the check.
88231dbd01fSIzik Eidus 		 */
88334ee645eSJoerg Roedel 		entry = ptep_clear_flush_notify(vma, addr, ptep);
88431dbd01fSIzik Eidus 		/*
88531dbd01fSIzik Eidus 		 * Check that no O_DIRECT or similar I/O is in progress on the
88631dbd01fSIzik Eidus 		 * page
88731dbd01fSIzik Eidus 		 */
88831e855eaSHugh Dickins 		if (page_mapcount(page) + 1 + swapped != page_count(page)) {
889cb532375SRobin Holt 			set_pte_at(mm, addr, ptep, entry);
89031dbd01fSIzik Eidus 			goto out_unlock;
89131dbd01fSIzik Eidus 		}
8924e31635cSHugh Dickins 		if (pte_dirty(entry))
8934e31635cSHugh Dickins 			set_page_dirty(page);
8944e31635cSHugh Dickins 		entry = pte_mkclean(pte_wrprotect(entry));
89531dbd01fSIzik Eidus 		set_pte_at_notify(mm, addr, ptep, entry);
89631dbd01fSIzik Eidus 	}
89731dbd01fSIzik Eidus 	*orig_pte = *ptep;
89831dbd01fSIzik Eidus 	err = 0;
89931dbd01fSIzik Eidus 
90031dbd01fSIzik Eidus out_unlock:
90131dbd01fSIzik Eidus 	pte_unmap_unlock(ptep, ptl);
9026bdb913fSHaggai Eran out_mn:
9036bdb913fSHaggai Eran 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
90431dbd01fSIzik Eidus out:
90531dbd01fSIzik Eidus 	return err;
90631dbd01fSIzik Eidus }
90731dbd01fSIzik Eidus 
90831dbd01fSIzik Eidus /**
90931dbd01fSIzik Eidus  * replace_page - replace page in vma by new ksm page
9108dd3557aSHugh Dickins  * @vma:      vma that holds the pte pointing to page
9118dd3557aSHugh Dickins  * @page:     the page we are replacing by kpage
9128dd3557aSHugh Dickins  * @kpage:    the ksm page we replace page by
91331dbd01fSIzik Eidus  * @orig_pte: the original value of the pte
91431dbd01fSIzik Eidus  *
91531dbd01fSIzik Eidus  * Returns 0 on success, -EFAULT on failure.
91631dbd01fSIzik Eidus  */
9178dd3557aSHugh Dickins static int replace_page(struct vm_area_struct *vma, struct page *page,
9188dd3557aSHugh Dickins 			struct page *kpage, pte_t orig_pte)
91931dbd01fSIzik Eidus {
92031dbd01fSIzik Eidus 	struct mm_struct *mm = vma->vm_mm;
92131dbd01fSIzik Eidus 	pmd_t *pmd;
92231dbd01fSIzik Eidus 	pte_t *ptep;
92331dbd01fSIzik Eidus 	spinlock_t *ptl;
92431dbd01fSIzik Eidus 	unsigned long addr;
92531dbd01fSIzik Eidus 	int err = -EFAULT;
9266bdb913fSHaggai Eran 	unsigned long mmun_start;	/* For mmu_notifiers */
9276bdb913fSHaggai Eran 	unsigned long mmun_end;		/* For mmu_notifiers */
92831dbd01fSIzik Eidus 
9298dd3557aSHugh Dickins 	addr = page_address_in_vma(page, vma);
93031dbd01fSIzik Eidus 	if (addr == -EFAULT)
93131dbd01fSIzik Eidus 		goto out;
93231dbd01fSIzik Eidus 
9336219049aSBob Liu 	pmd = mm_find_pmd(mm, addr);
9346219049aSBob Liu 	if (!pmd)
93531dbd01fSIzik Eidus 		goto out;
93631dbd01fSIzik Eidus 
9376bdb913fSHaggai Eran 	mmun_start = addr;
9386bdb913fSHaggai Eran 	mmun_end   = addr + PAGE_SIZE;
9396bdb913fSHaggai Eran 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
9406bdb913fSHaggai Eran 
94131dbd01fSIzik Eidus 	ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
94231dbd01fSIzik Eidus 	if (!pte_same(*ptep, orig_pte)) {
94331dbd01fSIzik Eidus 		pte_unmap_unlock(ptep, ptl);
9446bdb913fSHaggai Eran 		goto out_mn;
94531dbd01fSIzik Eidus 	}
94631dbd01fSIzik Eidus 
9478dd3557aSHugh Dickins 	get_page(kpage);
948d281ee61SKirill A. Shutemov 	page_add_anon_rmap(kpage, vma, addr, false);
94931dbd01fSIzik Eidus 
95031dbd01fSIzik Eidus 	flush_cache_page(vma, addr, pte_pfn(*ptep));
95134ee645eSJoerg Roedel 	ptep_clear_flush_notify(vma, addr, ptep);
9528dd3557aSHugh Dickins 	set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
95331dbd01fSIzik Eidus 
954d281ee61SKirill A. Shutemov 	page_remove_rmap(page, false);
955ae52a2adSHugh Dickins 	if (!page_mapped(page))
956ae52a2adSHugh Dickins 		try_to_free_swap(page);
9578dd3557aSHugh Dickins 	put_page(page);
95831dbd01fSIzik Eidus 
95931dbd01fSIzik Eidus 	pte_unmap_unlock(ptep, ptl);
96031dbd01fSIzik Eidus 	err = 0;
9616bdb913fSHaggai Eran out_mn:
9626bdb913fSHaggai Eran 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
96331dbd01fSIzik Eidus out:
96431dbd01fSIzik Eidus 	return err;
96531dbd01fSIzik Eidus }
96631dbd01fSIzik Eidus 
96731dbd01fSIzik Eidus /*
96831dbd01fSIzik Eidus  * try_to_merge_one_page - take two pages and merge them into one
9698dd3557aSHugh Dickins  * @vma: the vma that holds the pte pointing to page
9708dd3557aSHugh Dickins  * @page: the PageAnon page that we want to replace with kpage
97180e14822SHugh Dickins  * @kpage: the PageKsm page that we want to map instead of page,
97280e14822SHugh Dickins  *         or NULL the first time when we want to use page as kpage.
97331dbd01fSIzik Eidus  *
97431dbd01fSIzik Eidus  * This function returns 0 if the pages were merged, -EFAULT otherwise.
97531dbd01fSIzik Eidus  */
97631dbd01fSIzik Eidus static int try_to_merge_one_page(struct vm_area_struct *vma,
9778dd3557aSHugh Dickins 				 struct page *page, struct page *kpage)
97831dbd01fSIzik Eidus {
97931dbd01fSIzik Eidus 	pte_t orig_pte = __pte(0);
98031dbd01fSIzik Eidus 	int err = -EFAULT;
98131dbd01fSIzik Eidus 
982db114b83SHugh Dickins 	if (page == kpage)			/* ksm page forked */
983db114b83SHugh Dickins 		return 0;
984db114b83SHugh Dickins 
9858dd3557aSHugh Dickins 	if (!PageAnon(page))
98631dbd01fSIzik Eidus 		goto out;
98731dbd01fSIzik Eidus 
98831dbd01fSIzik Eidus 	/*
98931dbd01fSIzik Eidus 	 * We need the page lock to read a stable PageSwapCache in
99031dbd01fSIzik Eidus 	 * write_protect_page().  We use trylock_page() instead of
99131dbd01fSIzik Eidus 	 * lock_page() because we don't want to wait here - we
99231dbd01fSIzik Eidus 	 * prefer to continue scanning and merging different pages,
99331dbd01fSIzik Eidus 	 * then come back to this page when it is unlocked.
99431dbd01fSIzik Eidus 	 */
9958dd3557aSHugh Dickins 	if (!trylock_page(page))
99631e855eaSHugh Dickins 		goto out;
997f765f540SKirill A. Shutemov 
998f765f540SKirill A. Shutemov 	if (PageTransCompound(page)) {
999f765f540SKirill A. Shutemov 		err = split_huge_page(page);
1000f765f540SKirill A. Shutemov 		if (err)
1001f765f540SKirill A. Shutemov 			goto out_unlock;
1002f765f540SKirill A. Shutemov 	}
1003f765f540SKirill A. Shutemov 
100431dbd01fSIzik Eidus 	/*
100531dbd01fSIzik Eidus 	 * If this anonymous page is mapped only here, its pte may need
100631dbd01fSIzik Eidus 	 * to be write-protected.  If it's mapped elsewhere, all of its
100731dbd01fSIzik Eidus 	 * ptes are necessarily already write-protected.  But in either
100831dbd01fSIzik Eidus 	 * case, we need to lock and check page_count is not raised.
100931dbd01fSIzik Eidus 	 */
101080e14822SHugh Dickins 	if (write_protect_page(vma, page, &orig_pte) == 0) {
101180e14822SHugh Dickins 		if (!kpage) {
101280e14822SHugh Dickins 			/*
101380e14822SHugh Dickins 			 * While we hold page lock, upgrade page from
101480e14822SHugh Dickins 			 * PageAnon+anon_vma to PageKsm+NULL stable_node:
101580e14822SHugh Dickins 			 * stable_tree_insert() will update stable_node.
101680e14822SHugh Dickins 			 */
101780e14822SHugh Dickins 			set_page_stable_node(page, NULL);
101880e14822SHugh Dickins 			mark_page_accessed(page);
1019337ed7ebSMinchan Kim 			/*
1020337ed7ebSMinchan Kim 			 * Page reclaim just frees a clean page with no dirty
1021337ed7ebSMinchan Kim 			 * ptes: make sure that the ksm page would be swapped.
1022337ed7ebSMinchan Kim 			 */
1023337ed7ebSMinchan Kim 			if (!PageDirty(page))
1024337ed7ebSMinchan Kim 				SetPageDirty(page);
102580e14822SHugh Dickins 			err = 0;
102680e14822SHugh Dickins 		} else if (pages_identical(page, kpage))
10278dd3557aSHugh Dickins 			err = replace_page(vma, page, kpage, orig_pte);
102880e14822SHugh Dickins 	}
102931dbd01fSIzik Eidus 
103080e14822SHugh Dickins 	if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
103173848b46SHugh Dickins 		munlock_vma_page(page);
10325ad64688SHugh Dickins 		if (!PageMlocked(kpage)) {
10335ad64688SHugh Dickins 			unlock_page(page);
10345ad64688SHugh Dickins 			lock_page(kpage);
10355ad64688SHugh Dickins 			mlock_vma_page(kpage);
10365ad64688SHugh Dickins 			page = kpage;		/* for final unlock */
10375ad64688SHugh Dickins 		}
10385ad64688SHugh Dickins 	}
103973848b46SHugh Dickins 
1040f765f540SKirill A. Shutemov out_unlock:
10418dd3557aSHugh Dickins 	unlock_page(page);
104231dbd01fSIzik Eidus out:
104331dbd01fSIzik Eidus 	return err;
104431dbd01fSIzik Eidus }
104531dbd01fSIzik Eidus 
104631dbd01fSIzik Eidus /*
104781464e30SHugh Dickins  * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
104881464e30SHugh Dickins  * but no new kernel page is allocated: kpage must already be a ksm page.
10498dd3557aSHugh Dickins  *
10508dd3557aSHugh Dickins  * This function returns 0 if the pages were merged, -EFAULT otherwise.
105181464e30SHugh Dickins  */
10528dd3557aSHugh Dickins static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
10538dd3557aSHugh Dickins 				      struct page *page, struct page *kpage)
105481464e30SHugh Dickins {
10558dd3557aSHugh Dickins 	struct mm_struct *mm = rmap_item->mm;
105681464e30SHugh Dickins 	struct vm_area_struct *vma;
105781464e30SHugh Dickins 	int err = -EFAULT;
105881464e30SHugh Dickins 
10598dd3557aSHugh Dickins 	down_read(&mm->mmap_sem);
106085c6e8ddSAndrea Arcangeli 	vma = find_mergeable_vma(mm, rmap_item->address);
106185c6e8ddSAndrea Arcangeli 	if (!vma)
10629ba69294SHugh Dickins 		goto out;
10639ba69294SHugh Dickins 
10648dd3557aSHugh Dickins 	err = try_to_merge_one_page(vma, page, kpage);
1065db114b83SHugh Dickins 	if (err)
1066db114b83SHugh Dickins 		goto out;
1067db114b83SHugh Dickins 
1068bc56620bSHugh Dickins 	/* Unstable nid is in union with stable anon_vma: remove first */
1069bc56620bSHugh Dickins 	remove_rmap_item_from_tree(rmap_item);
1070bc56620bSHugh Dickins 
1071db114b83SHugh Dickins 	/* Must get reference to anon_vma while still holding mmap_sem */
10729e60109fSPeter Zijlstra 	rmap_item->anon_vma = vma->anon_vma;
10739e60109fSPeter Zijlstra 	get_anon_vma(vma->anon_vma);
107481464e30SHugh Dickins out:
10758dd3557aSHugh Dickins 	up_read(&mm->mmap_sem);
107681464e30SHugh Dickins 	return err;
107781464e30SHugh Dickins }
107881464e30SHugh Dickins 
107981464e30SHugh Dickins /*
108031dbd01fSIzik Eidus  * try_to_merge_two_pages - take two identical pages and prepare them
108131dbd01fSIzik Eidus  * to be merged into one page.
108231dbd01fSIzik Eidus  *
10838dd3557aSHugh Dickins  * This function returns the kpage if we successfully merged two identical
10848dd3557aSHugh Dickins  * pages into one ksm page, NULL otherwise.
108531dbd01fSIzik Eidus  *
108680e14822SHugh Dickins  * Note that this function upgrades page to ksm page: if one of the pages
108731dbd01fSIzik Eidus  * is already a ksm page, try_to_merge_with_ksm_page should be used.
108831dbd01fSIzik Eidus  */
10898dd3557aSHugh Dickins static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
10908dd3557aSHugh Dickins 					   struct page *page,
10918dd3557aSHugh Dickins 					   struct rmap_item *tree_rmap_item,
10928dd3557aSHugh Dickins 					   struct page *tree_page)
109331dbd01fSIzik Eidus {
109480e14822SHugh Dickins 	int err;
109531dbd01fSIzik Eidus 
109680e14822SHugh Dickins 	err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
109731dbd01fSIzik Eidus 	if (!err) {
10988dd3557aSHugh Dickins 		err = try_to_merge_with_ksm_page(tree_rmap_item,
109980e14822SHugh Dickins 							tree_page, page);
110031dbd01fSIzik Eidus 		/*
110181464e30SHugh Dickins 		 * If that fails, we have a ksm page with only one pte
110281464e30SHugh Dickins 		 * pointing to it: so break it.
110331dbd01fSIzik Eidus 		 */
11044035c07aSHugh Dickins 		if (err)
11058dd3557aSHugh Dickins 			break_cow(rmap_item);
110631dbd01fSIzik Eidus 	}
110780e14822SHugh Dickins 	return err ? NULL : page;
110831dbd01fSIzik Eidus }
110931dbd01fSIzik Eidus 
111031dbd01fSIzik Eidus /*
11118dd3557aSHugh Dickins  * stable_tree_search - search for page inside the stable tree
111231dbd01fSIzik Eidus  *
111331dbd01fSIzik Eidus  * This function checks if there is a page inside the stable tree
111431dbd01fSIzik Eidus  * with identical content to the page that we are scanning right now.
111531dbd01fSIzik Eidus  *
11167b6ba2c7SHugh Dickins  * This function returns the stable tree node of identical content if found,
111731dbd01fSIzik Eidus  * NULL otherwise.
111831dbd01fSIzik Eidus  */
111962b61f61SHugh Dickins static struct page *stable_tree_search(struct page *page)
112031dbd01fSIzik Eidus {
112190bd6fd3SPetr Holasek 	int nid;
1122ef53d16cSHugh Dickins 	struct rb_root *root;
11234146d2d6SHugh Dickins 	struct rb_node **new;
11244146d2d6SHugh Dickins 	struct rb_node *parent;
11254146d2d6SHugh Dickins 	struct stable_node *stable_node;
11264146d2d6SHugh Dickins 	struct stable_node *page_node;
112731dbd01fSIzik Eidus 
11284146d2d6SHugh Dickins 	page_node = page_stable_node(page);
11294146d2d6SHugh Dickins 	if (page_node && page_node->head != &migrate_nodes) {
11304146d2d6SHugh Dickins 		/* ksm page forked */
113108beca44SHugh Dickins 		get_page(page);
113262b61f61SHugh Dickins 		return page;
113308beca44SHugh Dickins 	}
113408beca44SHugh Dickins 
113590bd6fd3SPetr Holasek 	nid = get_kpfn_nid(page_to_pfn(page));
1136ef53d16cSHugh Dickins 	root = root_stable_tree + nid;
11374146d2d6SHugh Dickins again:
1138ef53d16cSHugh Dickins 	new = &root->rb_node;
11394146d2d6SHugh Dickins 	parent = NULL;
114090bd6fd3SPetr Holasek 
11414146d2d6SHugh Dickins 	while (*new) {
11424035c07aSHugh Dickins 		struct page *tree_page;
114331dbd01fSIzik Eidus 		int ret;
114431dbd01fSIzik Eidus 
114531dbd01fSIzik Eidus 		cond_resched();
11464146d2d6SHugh Dickins 		stable_node = rb_entry(*new, struct stable_node, node);
11478aafa6a4SHugh Dickins 		tree_page = get_ksm_page(stable_node, false);
1148f2e5ff85SAndrea Arcangeli 		if (!tree_page) {
1149f2e5ff85SAndrea Arcangeli 			/*
1150f2e5ff85SAndrea Arcangeli 			 * If we walked over a stale stable_node,
1151f2e5ff85SAndrea Arcangeli 			 * get_ksm_page() will call rb_erase() and it
1152f2e5ff85SAndrea Arcangeli 			 * may rebalance the tree from under us. So
1153f2e5ff85SAndrea Arcangeli 			 * restart the search from scratch. Returning
1154f2e5ff85SAndrea Arcangeli 			 * NULL would be safe too, but we'd generate
1155f2e5ff85SAndrea Arcangeli 			 * false negative insertions just because some
1156f2e5ff85SAndrea Arcangeli 			 * stable_node was stale.
1157f2e5ff85SAndrea Arcangeli 			 */
1158f2e5ff85SAndrea Arcangeli 			goto again;
1159f2e5ff85SAndrea Arcangeli 		}
116031dbd01fSIzik Eidus 
11614035c07aSHugh Dickins 		ret = memcmp_pages(page, tree_page);
1162c8d6553bSHugh Dickins 		put_page(tree_page);
116331dbd01fSIzik Eidus 
11644146d2d6SHugh Dickins 		parent = *new;
1165c8d6553bSHugh Dickins 		if (ret < 0)
11664146d2d6SHugh Dickins 			new = &parent->rb_left;
1167c8d6553bSHugh Dickins 		else if (ret > 0)
11684146d2d6SHugh Dickins 			new = &parent->rb_right;
1169c8d6553bSHugh Dickins 		else {
1170c8d6553bSHugh Dickins 			/*
1171c8d6553bSHugh Dickins 			 * Lock and unlock the stable_node's page (which
1172c8d6553bSHugh Dickins 			 * might already have been migrated) so that page
1173c8d6553bSHugh Dickins 			 * migration is sure to notice its raised count.
1174c8d6553bSHugh Dickins 			 * It would be more elegant to return stable_node
1175c8d6553bSHugh Dickins 			 * than kpage, but that involves more changes.
1176c8d6553bSHugh Dickins 			 */
1177c8d6553bSHugh Dickins 			tree_page = get_ksm_page(stable_node, true);
11784146d2d6SHugh Dickins 			if (tree_page) {
1179c8d6553bSHugh Dickins 				unlock_page(tree_page);
11804146d2d6SHugh Dickins 				if (get_kpfn_nid(stable_node->kpfn) !=
11814146d2d6SHugh Dickins 						NUMA(stable_node->nid)) {
11824146d2d6SHugh Dickins 					put_page(tree_page);
11834146d2d6SHugh Dickins 					goto replace;
11844146d2d6SHugh Dickins 				}
118562b61f61SHugh Dickins 				return tree_page;
118631dbd01fSIzik Eidus 			}
11874146d2d6SHugh Dickins 			/*
11884146d2d6SHugh Dickins 			 * There is now a place for page_node, but the tree may
11894146d2d6SHugh Dickins 			 * have been rebalanced, so re-evaluate parent and new.
11904146d2d6SHugh Dickins 			 */
11914146d2d6SHugh Dickins 			if (page_node)
11924146d2d6SHugh Dickins 				goto again;
11934146d2d6SHugh Dickins 			return NULL;
11944146d2d6SHugh Dickins 		}
1195c8d6553bSHugh Dickins 	}
119631dbd01fSIzik Eidus 
11974146d2d6SHugh Dickins 	if (!page_node)
119831dbd01fSIzik Eidus 		return NULL;
11994146d2d6SHugh Dickins 
12004146d2d6SHugh Dickins 	list_del(&page_node->list);
12014146d2d6SHugh Dickins 	DO_NUMA(page_node->nid = nid);
12024146d2d6SHugh Dickins 	rb_link_node(&page_node->node, parent, new);
1203ef53d16cSHugh Dickins 	rb_insert_color(&page_node->node, root);
12044146d2d6SHugh Dickins 	get_page(page);
12054146d2d6SHugh Dickins 	return page;
12064146d2d6SHugh Dickins 
12074146d2d6SHugh Dickins replace:
12084146d2d6SHugh Dickins 	if (page_node) {
12094146d2d6SHugh Dickins 		list_del(&page_node->list);
12104146d2d6SHugh Dickins 		DO_NUMA(page_node->nid = nid);
1211ef53d16cSHugh Dickins 		rb_replace_node(&stable_node->node, &page_node->node, root);
12124146d2d6SHugh Dickins 		get_page(page);
12134146d2d6SHugh Dickins 	} else {
1214ef53d16cSHugh Dickins 		rb_erase(&stable_node->node, root);
12154146d2d6SHugh Dickins 		page = NULL;
12164146d2d6SHugh Dickins 	}
12174146d2d6SHugh Dickins 	stable_node->head = &migrate_nodes;
12184146d2d6SHugh Dickins 	list_add(&stable_node->list, stable_node->head);
12194146d2d6SHugh Dickins 	return page;
122031dbd01fSIzik Eidus }
122131dbd01fSIzik Eidus 
122231dbd01fSIzik Eidus /*
1223e850dcf5SHugh Dickins  * stable_tree_insert - insert stable tree node pointing to new ksm page
122431dbd01fSIzik Eidus  * into the stable tree.
122531dbd01fSIzik Eidus  *
12267b6ba2c7SHugh Dickins  * This function returns the stable tree node just allocated on success,
12277b6ba2c7SHugh Dickins  * NULL otherwise.
122831dbd01fSIzik Eidus  */
12297b6ba2c7SHugh Dickins static struct stable_node *stable_tree_insert(struct page *kpage)
123031dbd01fSIzik Eidus {
123190bd6fd3SPetr Holasek 	int nid;
123290bd6fd3SPetr Holasek 	unsigned long kpfn;
1233ef53d16cSHugh Dickins 	struct rb_root *root;
123490bd6fd3SPetr Holasek 	struct rb_node **new;
1235f2e5ff85SAndrea Arcangeli 	struct rb_node *parent;
12367b6ba2c7SHugh Dickins 	struct stable_node *stable_node;
123731dbd01fSIzik Eidus 
123890bd6fd3SPetr Holasek 	kpfn = page_to_pfn(kpage);
123990bd6fd3SPetr Holasek 	nid = get_kpfn_nid(kpfn);
1240ef53d16cSHugh Dickins 	root = root_stable_tree + nid;
1241f2e5ff85SAndrea Arcangeli again:
1242f2e5ff85SAndrea Arcangeli 	parent = NULL;
1243ef53d16cSHugh Dickins 	new = &root->rb_node;
124490bd6fd3SPetr Holasek 
124531dbd01fSIzik Eidus 	while (*new) {
12464035c07aSHugh Dickins 		struct page *tree_page;
124731dbd01fSIzik Eidus 		int ret;
124831dbd01fSIzik Eidus 
124931dbd01fSIzik Eidus 		cond_resched();
125008beca44SHugh Dickins 		stable_node = rb_entry(*new, struct stable_node, node);
12518aafa6a4SHugh Dickins 		tree_page = get_ksm_page(stable_node, false);
1252f2e5ff85SAndrea Arcangeli 		if (!tree_page) {
1253f2e5ff85SAndrea Arcangeli 			/*
1254f2e5ff85SAndrea Arcangeli 			 * If we walked over a stale stable_node,
1255f2e5ff85SAndrea Arcangeli 			 * get_ksm_page() will call rb_erase() and it
1256f2e5ff85SAndrea Arcangeli 			 * may rebalance the tree from under us. So
1257f2e5ff85SAndrea Arcangeli 			 * restart the search from scratch. Returning
1258f2e5ff85SAndrea Arcangeli 			 * NULL would be safe too, but we'd generate
1259f2e5ff85SAndrea Arcangeli 			 * false negative insertions just because some
1260f2e5ff85SAndrea Arcangeli 			 * stable_node was stale.
1261f2e5ff85SAndrea Arcangeli 			 */
1262f2e5ff85SAndrea Arcangeli 			goto again;
1263f2e5ff85SAndrea Arcangeli 		}
126431dbd01fSIzik Eidus 
12654035c07aSHugh Dickins 		ret = memcmp_pages(kpage, tree_page);
12664035c07aSHugh Dickins 		put_page(tree_page);
126731dbd01fSIzik Eidus 
126831dbd01fSIzik Eidus 		parent = *new;
126931dbd01fSIzik Eidus 		if (ret < 0)
127031dbd01fSIzik Eidus 			new = &parent->rb_left;
127131dbd01fSIzik Eidus 		else if (ret > 0)
127231dbd01fSIzik Eidus 			new = &parent->rb_right;
127331dbd01fSIzik Eidus 		else {
127431dbd01fSIzik Eidus 			/*
127531dbd01fSIzik Eidus 			 * It is not a bug that stable_tree_search() didn't
127631dbd01fSIzik Eidus 			 * find this node: because at that time our page was
127731dbd01fSIzik Eidus 			 * not yet write-protected, so may have changed since.
127831dbd01fSIzik Eidus 			 */
127931dbd01fSIzik Eidus 			return NULL;
128031dbd01fSIzik Eidus 		}
128131dbd01fSIzik Eidus 	}
128231dbd01fSIzik Eidus 
12837b6ba2c7SHugh Dickins 	stable_node = alloc_stable_node();
12847b6ba2c7SHugh Dickins 	if (!stable_node)
12857b6ba2c7SHugh Dickins 		return NULL;
128631dbd01fSIzik Eidus 
12877b6ba2c7SHugh Dickins 	INIT_HLIST_HEAD(&stable_node->hlist);
128890bd6fd3SPetr Holasek 	stable_node->kpfn = kpfn;
128908beca44SHugh Dickins 	set_page_stable_node(kpage, stable_node);
12904146d2d6SHugh Dickins 	DO_NUMA(stable_node->nid = nid);
1291e850dcf5SHugh Dickins 	rb_link_node(&stable_node->node, parent, new);
1292ef53d16cSHugh Dickins 	rb_insert_color(&stable_node->node, root);
129308beca44SHugh Dickins 
12947b6ba2c7SHugh Dickins 	return stable_node;
129531dbd01fSIzik Eidus }
129631dbd01fSIzik Eidus 
129731dbd01fSIzik Eidus /*
12988dd3557aSHugh Dickins  * unstable_tree_search_insert - search for identical page,
12998dd3557aSHugh Dickins  * else insert rmap_item into the unstable tree.
130031dbd01fSIzik Eidus  *
130131dbd01fSIzik Eidus  * This function searches for a page in the unstable tree identical to the
130231dbd01fSIzik Eidus  * page currently being scanned; and if no identical page is found in the
130331dbd01fSIzik Eidus  * tree, we insert rmap_item as a new object into the unstable tree.
130431dbd01fSIzik Eidus  *
130531dbd01fSIzik Eidus  * This function returns pointer to rmap_item found to be identical
130631dbd01fSIzik Eidus  * to the currently scanned page, NULL otherwise.
130731dbd01fSIzik Eidus  *
130831dbd01fSIzik Eidus  * This function does both searching and inserting, because they share
130931dbd01fSIzik Eidus  * the same walking algorithm in an rbtree.
131031dbd01fSIzik Eidus  */
13118dd3557aSHugh Dickins static
13128dd3557aSHugh Dickins struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
13138dd3557aSHugh Dickins 					      struct page *page,
13148dd3557aSHugh Dickins 					      struct page **tree_pagep)
131531dbd01fSIzik Eidus {
131690bd6fd3SPetr Holasek 	struct rb_node **new;
131790bd6fd3SPetr Holasek 	struct rb_root *root;
131831dbd01fSIzik Eidus 	struct rb_node *parent = NULL;
131990bd6fd3SPetr Holasek 	int nid;
132090bd6fd3SPetr Holasek 
132190bd6fd3SPetr Holasek 	nid = get_kpfn_nid(page_to_pfn(page));
1322ef53d16cSHugh Dickins 	root = root_unstable_tree + nid;
132390bd6fd3SPetr Holasek 	new = &root->rb_node;
132431dbd01fSIzik Eidus 
132531dbd01fSIzik Eidus 	while (*new) {
132631dbd01fSIzik Eidus 		struct rmap_item *tree_rmap_item;
13278dd3557aSHugh Dickins 		struct page *tree_page;
132831dbd01fSIzik Eidus 		int ret;
132931dbd01fSIzik Eidus 
1330d178f27fSHugh Dickins 		cond_resched();
133131dbd01fSIzik Eidus 		tree_rmap_item = rb_entry(*new, struct rmap_item, node);
13328dd3557aSHugh Dickins 		tree_page = get_mergeable_page(tree_rmap_item);
1333c8f95ed1SAndrea Arcangeli 		if (!tree_page)
133431dbd01fSIzik Eidus 			return NULL;
133531dbd01fSIzik Eidus 
133631dbd01fSIzik Eidus 		/*
13378dd3557aSHugh Dickins 		 * Don't substitute a ksm page for a forked page.
133831dbd01fSIzik Eidus 		 */
13398dd3557aSHugh Dickins 		if (page == tree_page) {
13408dd3557aSHugh Dickins 			put_page(tree_page);
134131dbd01fSIzik Eidus 			return NULL;
134231dbd01fSIzik Eidus 		}
134331dbd01fSIzik Eidus 
13448dd3557aSHugh Dickins 		ret = memcmp_pages(page, tree_page);
134531dbd01fSIzik Eidus 
134631dbd01fSIzik Eidus 		parent = *new;
134731dbd01fSIzik Eidus 		if (ret < 0) {
13488dd3557aSHugh Dickins 			put_page(tree_page);
134931dbd01fSIzik Eidus 			new = &parent->rb_left;
135031dbd01fSIzik Eidus 		} else if (ret > 0) {
13518dd3557aSHugh Dickins 			put_page(tree_page);
135231dbd01fSIzik Eidus 			new = &parent->rb_right;
1353b599cbdfSHugh Dickins 		} else if (!ksm_merge_across_nodes &&
1354b599cbdfSHugh Dickins 			   page_to_nid(tree_page) != nid) {
1355b599cbdfSHugh Dickins 			/*
1356b599cbdfSHugh Dickins 			 * If tree_page has been migrated to another NUMA node,
1357b599cbdfSHugh Dickins 			 * it will be flushed out and put in the right unstable
1358b599cbdfSHugh Dickins 			 * tree next time: only merge with it when across_nodes.
1359b599cbdfSHugh Dickins 			 */
1360b599cbdfSHugh Dickins 			put_page(tree_page);
1361b599cbdfSHugh Dickins 			return NULL;
136231dbd01fSIzik Eidus 		} else {
13638dd3557aSHugh Dickins 			*tree_pagep = tree_page;
136431dbd01fSIzik Eidus 			return tree_rmap_item;
136531dbd01fSIzik Eidus 		}
136631dbd01fSIzik Eidus 	}
136731dbd01fSIzik Eidus 
13687b6ba2c7SHugh Dickins 	rmap_item->address |= UNSTABLE_FLAG;
136931dbd01fSIzik Eidus 	rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
1370e850dcf5SHugh Dickins 	DO_NUMA(rmap_item->nid = nid);
137131dbd01fSIzik Eidus 	rb_link_node(&rmap_item->node, parent, new);
137290bd6fd3SPetr Holasek 	rb_insert_color(&rmap_item->node, root);
137331dbd01fSIzik Eidus 
1374473b0ce4SHugh Dickins 	ksm_pages_unshared++;
137531dbd01fSIzik Eidus 	return NULL;
137631dbd01fSIzik Eidus }
137731dbd01fSIzik Eidus 
137831dbd01fSIzik Eidus /*
137931dbd01fSIzik Eidus  * stable_tree_append - add another rmap_item to the linked list of
138031dbd01fSIzik Eidus  * rmap_items hanging off a given node of the stable tree, all sharing
138131dbd01fSIzik Eidus  * the same ksm page.
138231dbd01fSIzik Eidus  */
138331dbd01fSIzik Eidus static void stable_tree_append(struct rmap_item *rmap_item,
13847b6ba2c7SHugh Dickins 			       struct stable_node *stable_node)
138531dbd01fSIzik Eidus {
13867b6ba2c7SHugh Dickins 	rmap_item->head = stable_node;
138731dbd01fSIzik Eidus 	rmap_item->address |= STABLE_FLAG;
13887b6ba2c7SHugh Dickins 	hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
1389e178dfdeSHugh Dickins 
13907b6ba2c7SHugh Dickins 	if (rmap_item->hlist.next)
1391e178dfdeSHugh Dickins 		ksm_pages_sharing++;
13927b6ba2c7SHugh Dickins 	else
13937b6ba2c7SHugh Dickins 		ksm_pages_shared++;
139431dbd01fSIzik Eidus }
139531dbd01fSIzik Eidus 
139631dbd01fSIzik Eidus /*
139781464e30SHugh Dickins  * cmp_and_merge_page - first see if page can be merged into the stable tree;
139881464e30SHugh Dickins  * if not, compare checksum to previous and if it's the same, see if page can
139981464e30SHugh Dickins  * be inserted into the unstable tree, or merged with a page already there and
140081464e30SHugh Dickins  * both transferred to the stable tree.
140131dbd01fSIzik Eidus  *
140231dbd01fSIzik Eidus  * @page: the page that we are searching identical page to.
140331dbd01fSIzik Eidus  * @rmap_item: the reverse mapping into the virtual address of this page
140431dbd01fSIzik Eidus  */
140531dbd01fSIzik Eidus static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
140631dbd01fSIzik Eidus {
140731dbd01fSIzik Eidus 	struct rmap_item *tree_rmap_item;
14088dd3557aSHugh Dickins 	struct page *tree_page = NULL;
14097b6ba2c7SHugh Dickins 	struct stable_node *stable_node;
14108dd3557aSHugh Dickins 	struct page *kpage;
141131dbd01fSIzik Eidus 	unsigned int checksum;
141231dbd01fSIzik Eidus 	int err;
141331dbd01fSIzik Eidus 
14144146d2d6SHugh Dickins 	stable_node = page_stable_node(page);
14154146d2d6SHugh Dickins 	if (stable_node) {
14164146d2d6SHugh Dickins 		if (stable_node->head != &migrate_nodes &&
14174146d2d6SHugh Dickins 		    get_kpfn_nid(stable_node->kpfn) != NUMA(stable_node->nid)) {
14184146d2d6SHugh Dickins 			rb_erase(&stable_node->node,
1419ef53d16cSHugh Dickins 				 root_stable_tree + NUMA(stable_node->nid));
14204146d2d6SHugh Dickins 			stable_node->head = &migrate_nodes;
14214146d2d6SHugh Dickins 			list_add(&stable_node->list, stable_node->head);
14224146d2d6SHugh Dickins 		}
14234146d2d6SHugh Dickins 		if (stable_node->head != &migrate_nodes &&
14244146d2d6SHugh Dickins 		    rmap_item->head == stable_node)
14254146d2d6SHugh Dickins 			return;
14264146d2d6SHugh Dickins 	}
142731dbd01fSIzik Eidus 
142831dbd01fSIzik Eidus 	/* We first start with searching the page inside the stable tree */
142962b61f61SHugh Dickins 	kpage = stable_tree_search(page);
14304146d2d6SHugh Dickins 	if (kpage == page && rmap_item->head == stable_node) {
14314146d2d6SHugh Dickins 		put_page(kpage);
14324146d2d6SHugh Dickins 		return;
14334146d2d6SHugh Dickins 	}
14344146d2d6SHugh Dickins 
14354146d2d6SHugh Dickins 	remove_rmap_item_from_tree(rmap_item);
14364146d2d6SHugh Dickins 
143762b61f61SHugh Dickins 	if (kpage) {
143808beca44SHugh Dickins 		err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
143931dbd01fSIzik Eidus 		if (!err) {
144031dbd01fSIzik Eidus 			/*
144131dbd01fSIzik Eidus 			 * The page was successfully merged:
144231dbd01fSIzik Eidus 			 * add its rmap_item to the stable tree.
144331dbd01fSIzik Eidus 			 */
14445ad64688SHugh Dickins 			lock_page(kpage);
144562b61f61SHugh Dickins 			stable_tree_append(rmap_item, page_stable_node(kpage));
14465ad64688SHugh Dickins 			unlock_page(kpage);
144731dbd01fSIzik Eidus 		}
14488dd3557aSHugh Dickins 		put_page(kpage);
144931dbd01fSIzik Eidus 		return;
145031dbd01fSIzik Eidus 	}
145131dbd01fSIzik Eidus 
145231dbd01fSIzik Eidus 	/*
14534035c07aSHugh Dickins 	 * If the hash value of the page has changed from the last time
14544035c07aSHugh Dickins 	 * we calculated it, this page is changing frequently: therefore we
14554035c07aSHugh Dickins 	 * don't want to insert it in the unstable tree, and we don't want
14564035c07aSHugh Dickins 	 * to waste our time searching for something identical to it there.
145731dbd01fSIzik Eidus 	 */
145831dbd01fSIzik Eidus 	checksum = calc_checksum(page);
145931dbd01fSIzik Eidus 	if (rmap_item->oldchecksum != checksum) {
146031dbd01fSIzik Eidus 		rmap_item->oldchecksum = checksum;
146131dbd01fSIzik Eidus 		return;
146231dbd01fSIzik Eidus 	}
146331dbd01fSIzik Eidus 
14648dd3557aSHugh Dickins 	tree_rmap_item =
14658dd3557aSHugh Dickins 		unstable_tree_search_insert(rmap_item, page, &tree_page);
146631dbd01fSIzik Eidus 	if (tree_rmap_item) {
14678dd3557aSHugh Dickins 		kpage = try_to_merge_two_pages(rmap_item, page,
14688dd3557aSHugh Dickins 						tree_rmap_item, tree_page);
14698dd3557aSHugh Dickins 		put_page(tree_page);
14708dd3557aSHugh Dickins 		if (kpage) {
1471bc56620bSHugh Dickins 			/*
1472bc56620bSHugh Dickins 			 * The pages were successfully merged: insert new
1473bc56620bSHugh Dickins 			 * node in the stable tree and add both rmap_items.
1474bc56620bSHugh Dickins 			 */
14755ad64688SHugh Dickins 			lock_page(kpage);
14767b6ba2c7SHugh Dickins 			stable_node = stable_tree_insert(kpage);
14777b6ba2c7SHugh Dickins 			if (stable_node) {
14787b6ba2c7SHugh Dickins 				stable_tree_append(tree_rmap_item, stable_node);
14797b6ba2c7SHugh Dickins 				stable_tree_append(rmap_item, stable_node);
14807b6ba2c7SHugh Dickins 			}
14815ad64688SHugh Dickins 			unlock_page(kpage);
14827b6ba2c7SHugh Dickins 
148331dbd01fSIzik Eidus 			/*
148431dbd01fSIzik Eidus 			 * If we fail to insert the page into the stable tree,
148531dbd01fSIzik Eidus 			 * we will have 2 virtual addresses that are pointing
148631dbd01fSIzik Eidus 			 * to a ksm page left outside the stable tree,
148731dbd01fSIzik Eidus 			 * in which case we need to break_cow on both.
148831dbd01fSIzik Eidus 			 */
14897b6ba2c7SHugh Dickins 			if (!stable_node) {
14908dd3557aSHugh Dickins 				break_cow(tree_rmap_item);
14918dd3557aSHugh Dickins 				break_cow(rmap_item);
149231dbd01fSIzik Eidus 			}
149331dbd01fSIzik Eidus 		}
149431dbd01fSIzik Eidus 	}
149531dbd01fSIzik Eidus }
149631dbd01fSIzik Eidus 
149731dbd01fSIzik Eidus static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
14986514d511SHugh Dickins 					    struct rmap_item **rmap_list,
149931dbd01fSIzik Eidus 					    unsigned long addr)
150031dbd01fSIzik Eidus {
150131dbd01fSIzik Eidus 	struct rmap_item *rmap_item;
150231dbd01fSIzik Eidus 
15036514d511SHugh Dickins 	while (*rmap_list) {
15046514d511SHugh Dickins 		rmap_item = *rmap_list;
150593d17715SHugh Dickins 		if ((rmap_item->address & PAGE_MASK) == addr)
150631dbd01fSIzik Eidus 			return rmap_item;
150731dbd01fSIzik Eidus 		if (rmap_item->address > addr)
150831dbd01fSIzik Eidus 			break;
15096514d511SHugh Dickins 		*rmap_list = rmap_item->rmap_list;
151031dbd01fSIzik Eidus 		remove_rmap_item_from_tree(rmap_item);
151131dbd01fSIzik Eidus 		free_rmap_item(rmap_item);
151231dbd01fSIzik Eidus 	}
151331dbd01fSIzik Eidus 
151431dbd01fSIzik Eidus 	rmap_item = alloc_rmap_item();
151531dbd01fSIzik Eidus 	if (rmap_item) {
151631dbd01fSIzik Eidus 		/* It has already been zeroed */
151731dbd01fSIzik Eidus 		rmap_item->mm = mm_slot->mm;
151831dbd01fSIzik Eidus 		rmap_item->address = addr;
15196514d511SHugh Dickins 		rmap_item->rmap_list = *rmap_list;
15206514d511SHugh Dickins 		*rmap_list = rmap_item;
152131dbd01fSIzik Eidus 	}
152231dbd01fSIzik Eidus 	return rmap_item;
152331dbd01fSIzik Eidus }
152431dbd01fSIzik Eidus 
152531dbd01fSIzik Eidus static struct rmap_item *scan_get_next_rmap_item(struct page **page)
152631dbd01fSIzik Eidus {
152731dbd01fSIzik Eidus 	struct mm_struct *mm;
152831dbd01fSIzik Eidus 	struct mm_slot *slot;
152931dbd01fSIzik Eidus 	struct vm_area_struct *vma;
153031dbd01fSIzik Eidus 	struct rmap_item *rmap_item;
153190bd6fd3SPetr Holasek 	int nid;
153231dbd01fSIzik Eidus 
153331dbd01fSIzik Eidus 	if (list_empty(&ksm_mm_head.mm_list))
153431dbd01fSIzik Eidus 		return NULL;
153531dbd01fSIzik Eidus 
153631dbd01fSIzik Eidus 	slot = ksm_scan.mm_slot;
153731dbd01fSIzik Eidus 	if (slot == &ksm_mm_head) {
15382919bfd0SHugh Dickins 		/*
15392919bfd0SHugh Dickins 		 * A number of pages can hang around indefinitely on per-cpu
15402919bfd0SHugh Dickins 		 * pagevecs, raised page count preventing write_protect_page
15412919bfd0SHugh Dickins 		 * from merging them.  Though it doesn't really matter much,
15422919bfd0SHugh Dickins 		 * it is puzzling to see some stuck in pages_volatile until
15432919bfd0SHugh Dickins 		 * other activity jostles them out, and they also prevented
15442919bfd0SHugh Dickins 		 * LTP's KSM test from succeeding deterministically; so drain
15452919bfd0SHugh Dickins 		 * them here (here rather than on entry to ksm_do_scan(),
15462919bfd0SHugh Dickins 		 * so we don't IPI too often when pages_to_scan is set low).
15472919bfd0SHugh Dickins 		 */
15482919bfd0SHugh Dickins 		lru_add_drain_all();
15492919bfd0SHugh Dickins 
15504146d2d6SHugh Dickins 		/*
15514146d2d6SHugh Dickins 		 * Whereas stale stable_nodes on the stable_tree itself
15524146d2d6SHugh Dickins 		 * get pruned in the regular course of stable_tree_search(),
15534146d2d6SHugh Dickins 		 * those moved out to the migrate_nodes list can accumulate:
15544146d2d6SHugh Dickins 		 * so prune them once before each full scan.
15554146d2d6SHugh Dickins 		 */
15564146d2d6SHugh Dickins 		if (!ksm_merge_across_nodes) {
155703640418SGeliang Tang 			struct stable_node *stable_node, *next;
15584146d2d6SHugh Dickins 			struct page *page;
15594146d2d6SHugh Dickins 
156003640418SGeliang Tang 			list_for_each_entry_safe(stable_node, next,
156103640418SGeliang Tang 						 &migrate_nodes, list) {
15624146d2d6SHugh Dickins 				page = get_ksm_page(stable_node, false);
15634146d2d6SHugh Dickins 				if (page)
15644146d2d6SHugh Dickins 					put_page(page);
15654146d2d6SHugh Dickins 				cond_resched();
15664146d2d6SHugh Dickins 			}
15674146d2d6SHugh Dickins 		}
15684146d2d6SHugh Dickins 
1569ef53d16cSHugh Dickins 		for (nid = 0; nid < ksm_nr_node_ids; nid++)
157090bd6fd3SPetr Holasek 			root_unstable_tree[nid] = RB_ROOT;
157131dbd01fSIzik Eidus 
157231dbd01fSIzik Eidus 		spin_lock(&ksm_mmlist_lock);
157331dbd01fSIzik Eidus 		slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
157431dbd01fSIzik Eidus 		ksm_scan.mm_slot = slot;
157531dbd01fSIzik Eidus 		spin_unlock(&ksm_mmlist_lock);
15762b472611SHugh Dickins 		/*
15772b472611SHugh Dickins 		 * Although we tested list_empty() above, a racing __ksm_exit
15782b472611SHugh Dickins 		 * of the last mm on the list may have removed it since then.
15792b472611SHugh Dickins 		 */
15802b472611SHugh Dickins 		if (slot == &ksm_mm_head)
15812b472611SHugh Dickins 			return NULL;
158231dbd01fSIzik Eidus next_mm:
158331dbd01fSIzik Eidus 		ksm_scan.address = 0;
15846514d511SHugh Dickins 		ksm_scan.rmap_list = &slot->rmap_list;
158531dbd01fSIzik Eidus 	}
158631dbd01fSIzik Eidus 
158731dbd01fSIzik Eidus 	mm = slot->mm;
158831dbd01fSIzik Eidus 	down_read(&mm->mmap_sem);
15899ba69294SHugh Dickins 	if (ksm_test_exit(mm))
15909ba69294SHugh Dickins 		vma = NULL;
15919ba69294SHugh Dickins 	else
15929ba69294SHugh Dickins 		vma = find_vma(mm, ksm_scan.address);
15939ba69294SHugh Dickins 
15949ba69294SHugh Dickins 	for (; vma; vma = vma->vm_next) {
159531dbd01fSIzik Eidus 		if (!(vma->vm_flags & VM_MERGEABLE))
159631dbd01fSIzik Eidus 			continue;
159731dbd01fSIzik Eidus 		if (ksm_scan.address < vma->vm_start)
159831dbd01fSIzik Eidus 			ksm_scan.address = vma->vm_start;
159931dbd01fSIzik Eidus 		if (!vma->anon_vma)
160031dbd01fSIzik Eidus 			ksm_scan.address = vma->vm_end;
160131dbd01fSIzik Eidus 
160231dbd01fSIzik Eidus 		while (ksm_scan.address < vma->vm_end) {
16039ba69294SHugh Dickins 			if (ksm_test_exit(mm))
16049ba69294SHugh Dickins 				break;
160531dbd01fSIzik Eidus 			*page = follow_page(vma, ksm_scan.address, FOLL_GET);
160621ae5b01SAndrea Arcangeli 			if (IS_ERR_OR_NULL(*page)) {
160721ae5b01SAndrea Arcangeli 				ksm_scan.address += PAGE_SIZE;
160821ae5b01SAndrea Arcangeli 				cond_resched();
160921ae5b01SAndrea Arcangeli 				continue;
161021ae5b01SAndrea Arcangeli 			}
1611f765f540SKirill A. Shutemov 			if (PageAnon(*page)) {
161231dbd01fSIzik Eidus 				flush_anon_page(vma, *page, ksm_scan.address);
161331dbd01fSIzik Eidus 				flush_dcache_page(*page);
161431dbd01fSIzik Eidus 				rmap_item = get_next_rmap_item(slot,
16156514d511SHugh Dickins 					ksm_scan.rmap_list, ksm_scan.address);
161631dbd01fSIzik Eidus 				if (rmap_item) {
16176514d511SHugh Dickins 					ksm_scan.rmap_list =
16186514d511SHugh Dickins 							&rmap_item->rmap_list;
161931dbd01fSIzik Eidus 					ksm_scan.address += PAGE_SIZE;
162031dbd01fSIzik Eidus 				} else
162131dbd01fSIzik Eidus 					put_page(*page);
162231dbd01fSIzik Eidus 				up_read(&mm->mmap_sem);
162331dbd01fSIzik Eidus 				return rmap_item;
162431dbd01fSIzik Eidus 			}
162531dbd01fSIzik Eidus 			put_page(*page);
162631dbd01fSIzik Eidus 			ksm_scan.address += PAGE_SIZE;
162731dbd01fSIzik Eidus 			cond_resched();
162831dbd01fSIzik Eidus 		}
162931dbd01fSIzik Eidus 	}
163031dbd01fSIzik Eidus 
16319ba69294SHugh Dickins 	if (ksm_test_exit(mm)) {
16329ba69294SHugh Dickins 		ksm_scan.address = 0;
16336514d511SHugh Dickins 		ksm_scan.rmap_list = &slot->rmap_list;
16349ba69294SHugh Dickins 	}
163531dbd01fSIzik Eidus 	/*
163631dbd01fSIzik Eidus 	 * Nuke all the rmap_items that are above this current rmap:
163731dbd01fSIzik Eidus 	 * because there were no VM_MERGEABLE vmas with such addresses.
163831dbd01fSIzik Eidus 	 */
16396514d511SHugh Dickins 	remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
164031dbd01fSIzik Eidus 
164131dbd01fSIzik Eidus 	spin_lock(&ksm_mmlist_lock);
1642cd551f97SHugh Dickins 	ksm_scan.mm_slot = list_entry(slot->mm_list.next,
1643cd551f97SHugh Dickins 						struct mm_slot, mm_list);
1644cd551f97SHugh Dickins 	if (ksm_scan.address == 0) {
1645cd551f97SHugh Dickins 		/*
1646cd551f97SHugh Dickins 		 * We've completed a full scan of all vmas, holding mmap_sem
1647cd551f97SHugh Dickins 		 * throughout, and found no VM_MERGEABLE: so do the same as
1648cd551f97SHugh Dickins 		 * __ksm_exit does to remove this mm from all our lists now.
16499ba69294SHugh Dickins 		 * This applies either when cleaning up after __ksm_exit
16509ba69294SHugh Dickins 		 * (but beware: we can reach here even before __ksm_exit),
16519ba69294SHugh Dickins 		 * or when all VM_MERGEABLE areas have been unmapped (and
16529ba69294SHugh Dickins 		 * mmap_sem then protects against race with MADV_MERGEABLE).
1653cd551f97SHugh Dickins 		 */
16544ca3a69bSSasha Levin 		hash_del(&slot->link);
1655cd551f97SHugh Dickins 		list_del(&slot->mm_list);
16569ba69294SHugh Dickins 		spin_unlock(&ksm_mmlist_lock);
16579ba69294SHugh Dickins 
1658cd551f97SHugh Dickins 		free_mm_slot(slot);
1659cd551f97SHugh Dickins 		clear_bit(MMF_VM_MERGEABLE, &mm->flags);
16609ba69294SHugh Dickins 		up_read(&mm->mmap_sem);
16619ba69294SHugh Dickins 		mmdrop(mm);
16629ba69294SHugh Dickins 	} else {
1663cd551f97SHugh Dickins 		up_read(&mm->mmap_sem);
16647496fea9SZhou Chengming 		/*
16657496fea9SZhou Chengming 		 * up_read(&mm->mmap_sem) first because after
16667496fea9SZhou Chengming 		 * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
16677496fea9SZhou Chengming 		 * already have been freed under us by __ksm_exit()
16687496fea9SZhou Chengming 		 * because the "mm_slot" is still hashed and
16697496fea9SZhou Chengming 		 * ksm_scan.mm_slot doesn't point to it anymore.
16707496fea9SZhou Chengming 		 */
16717496fea9SZhou Chengming 		spin_unlock(&ksm_mmlist_lock);
16729ba69294SHugh Dickins 	}
167331dbd01fSIzik Eidus 
167431dbd01fSIzik Eidus 	/* Repeat until we've completed scanning the whole list */
1675cd551f97SHugh Dickins 	slot = ksm_scan.mm_slot;
167631dbd01fSIzik Eidus 	if (slot != &ksm_mm_head)
167731dbd01fSIzik Eidus 		goto next_mm;
167831dbd01fSIzik Eidus 
167931dbd01fSIzik Eidus 	ksm_scan.seqnr++;
168031dbd01fSIzik Eidus 	return NULL;
168131dbd01fSIzik Eidus }
168231dbd01fSIzik Eidus 
168331dbd01fSIzik Eidus /**
168431dbd01fSIzik Eidus  * ksm_do_scan  - the ksm scanner main worker function.
168531dbd01fSIzik Eidus  * @scan_npages - number of pages we want to scan before we return.
168631dbd01fSIzik Eidus  */
168731dbd01fSIzik Eidus static void ksm_do_scan(unsigned int scan_npages)
168831dbd01fSIzik Eidus {
168931dbd01fSIzik Eidus 	struct rmap_item *rmap_item;
169022eccdd7SDan Carpenter 	struct page *uninitialized_var(page);
169131dbd01fSIzik Eidus 
1692878aee7dSAndrea Arcangeli 	while (scan_npages-- && likely(!freezing(current))) {
169331dbd01fSIzik Eidus 		cond_resched();
169431dbd01fSIzik Eidus 		rmap_item = scan_get_next_rmap_item(&page);
169531dbd01fSIzik Eidus 		if (!rmap_item)
169631dbd01fSIzik Eidus 			return;
169731dbd01fSIzik Eidus 		cmp_and_merge_page(page, rmap_item);
169831dbd01fSIzik Eidus 		put_page(page);
169931dbd01fSIzik Eidus 	}
170031dbd01fSIzik Eidus }
170131dbd01fSIzik Eidus 
17026e158384SHugh Dickins static int ksmd_should_run(void)
17036e158384SHugh Dickins {
17046e158384SHugh Dickins 	return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
17056e158384SHugh Dickins }
17066e158384SHugh Dickins 
170731dbd01fSIzik Eidus static int ksm_scan_thread(void *nothing)
170831dbd01fSIzik Eidus {
1709878aee7dSAndrea Arcangeli 	set_freezable();
1710339aa624SIzik Eidus 	set_user_nice(current, 5);
171131dbd01fSIzik Eidus 
171231dbd01fSIzik Eidus 	while (!kthread_should_stop()) {
171331dbd01fSIzik Eidus 		mutex_lock(&ksm_thread_mutex);
1714ef4d43a8SHugh Dickins 		wait_while_offlining();
17156e158384SHugh Dickins 		if (ksmd_should_run())
171631dbd01fSIzik Eidus 			ksm_do_scan(ksm_thread_pages_to_scan);
171731dbd01fSIzik Eidus 		mutex_unlock(&ksm_thread_mutex);
17186e158384SHugh Dickins 
1719878aee7dSAndrea Arcangeli 		try_to_freeze();
1720878aee7dSAndrea Arcangeli 
17216e158384SHugh Dickins 		if (ksmd_should_run()) {
172231dbd01fSIzik Eidus 			schedule_timeout_interruptible(
172331dbd01fSIzik Eidus 				msecs_to_jiffies(ksm_thread_sleep_millisecs));
172431dbd01fSIzik Eidus 		} else {
1725878aee7dSAndrea Arcangeli 			wait_event_freezable(ksm_thread_wait,
17266e158384SHugh Dickins 				ksmd_should_run() || kthread_should_stop());
172731dbd01fSIzik Eidus 		}
172831dbd01fSIzik Eidus 	}
172931dbd01fSIzik Eidus 	return 0;
173031dbd01fSIzik Eidus }
173131dbd01fSIzik Eidus 
1732f8af4da3SHugh Dickins int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
1733f8af4da3SHugh Dickins 		unsigned long end, int advice, unsigned long *vm_flags)
1734f8af4da3SHugh Dickins {
1735f8af4da3SHugh Dickins 	struct mm_struct *mm = vma->vm_mm;
1736d952b791SHugh Dickins 	int err;
1737f8af4da3SHugh Dickins 
1738f8af4da3SHugh Dickins 	switch (advice) {
1739f8af4da3SHugh Dickins 	case MADV_MERGEABLE:
1740f8af4da3SHugh Dickins 		/*
1741f8af4da3SHugh Dickins 		 * Be somewhat over-protective for now!
1742f8af4da3SHugh Dickins 		 */
1743f8af4da3SHugh Dickins 		if (*vm_flags & (VM_MERGEABLE | VM_SHARED  | VM_MAYSHARE   |
1744f8af4da3SHugh Dickins 				 VM_PFNMAP    | VM_IO      | VM_DONTEXPAND |
17450661a336SKirill A. Shutemov 				 VM_HUGETLB | VM_MIXEDMAP))
1746f8af4da3SHugh Dickins 			return 0;		/* just ignore the advice */
1747f8af4da3SHugh Dickins 
1748cc2383ecSKonstantin Khlebnikov #ifdef VM_SAO
1749cc2383ecSKonstantin Khlebnikov 		if (*vm_flags & VM_SAO)
1750cc2383ecSKonstantin Khlebnikov 			return 0;
1751cc2383ecSKonstantin Khlebnikov #endif
1752cc2383ecSKonstantin Khlebnikov 
1753d952b791SHugh Dickins 		if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
1754d952b791SHugh Dickins 			err = __ksm_enter(mm);
1755d952b791SHugh Dickins 			if (err)
1756d952b791SHugh Dickins 				return err;
1757d952b791SHugh Dickins 		}
1758f8af4da3SHugh Dickins 
1759f8af4da3SHugh Dickins 		*vm_flags |= VM_MERGEABLE;
1760f8af4da3SHugh Dickins 		break;
1761f8af4da3SHugh Dickins 
1762f8af4da3SHugh Dickins 	case MADV_UNMERGEABLE:
1763f8af4da3SHugh Dickins 		if (!(*vm_flags & VM_MERGEABLE))
1764f8af4da3SHugh Dickins 			return 0;		/* just ignore the advice */
1765f8af4da3SHugh Dickins 
1766d952b791SHugh Dickins 		if (vma->anon_vma) {
1767d952b791SHugh Dickins 			err = unmerge_ksm_pages(vma, start, end);
1768d952b791SHugh Dickins 			if (err)
1769d952b791SHugh Dickins 				return err;
1770d952b791SHugh Dickins 		}
1771f8af4da3SHugh Dickins 
1772f8af4da3SHugh Dickins 		*vm_flags &= ~VM_MERGEABLE;
1773f8af4da3SHugh Dickins 		break;
1774f8af4da3SHugh Dickins 	}
1775f8af4da3SHugh Dickins 
1776f8af4da3SHugh Dickins 	return 0;
1777f8af4da3SHugh Dickins }
1778f8af4da3SHugh Dickins 
1779f8af4da3SHugh Dickins int __ksm_enter(struct mm_struct *mm)
1780f8af4da3SHugh Dickins {
17816e158384SHugh Dickins 	struct mm_slot *mm_slot;
17826e158384SHugh Dickins 	int needs_wakeup;
17836e158384SHugh Dickins 
17846e158384SHugh Dickins 	mm_slot = alloc_mm_slot();
178531dbd01fSIzik Eidus 	if (!mm_slot)
178631dbd01fSIzik Eidus 		return -ENOMEM;
178731dbd01fSIzik Eidus 
17886e158384SHugh Dickins 	/* Check ksm_run too?  Would need tighter locking */
17896e158384SHugh Dickins 	needs_wakeup = list_empty(&ksm_mm_head.mm_list);
17906e158384SHugh Dickins 
179131dbd01fSIzik Eidus 	spin_lock(&ksm_mmlist_lock);
179231dbd01fSIzik Eidus 	insert_to_mm_slots_hash(mm, mm_slot);
179331dbd01fSIzik Eidus 	/*
1794cbf86cfeSHugh Dickins 	 * When KSM_RUN_MERGE (or KSM_RUN_STOP),
1795cbf86cfeSHugh Dickins 	 * insert just behind the scanning cursor, to let the area settle
179631dbd01fSIzik Eidus 	 * down a little; when fork is followed by immediate exec, we don't
179731dbd01fSIzik Eidus 	 * want ksmd to waste time setting up and tearing down an rmap_list.
1798cbf86cfeSHugh Dickins 	 *
1799cbf86cfeSHugh Dickins 	 * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
1800cbf86cfeSHugh Dickins 	 * scanning cursor, otherwise KSM pages in newly forked mms will be
1801cbf86cfeSHugh Dickins 	 * missed: then we might as well insert at the end of the list.
180231dbd01fSIzik Eidus 	 */
1803cbf86cfeSHugh Dickins 	if (ksm_run & KSM_RUN_UNMERGE)
1804cbf86cfeSHugh Dickins 		list_add_tail(&mm_slot->mm_list, &ksm_mm_head.mm_list);
1805cbf86cfeSHugh Dickins 	else
180631dbd01fSIzik Eidus 		list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
180731dbd01fSIzik Eidus 	spin_unlock(&ksm_mmlist_lock);
180831dbd01fSIzik Eidus 
1809f8af4da3SHugh Dickins 	set_bit(MMF_VM_MERGEABLE, &mm->flags);
18109ba69294SHugh Dickins 	atomic_inc(&mm->mm_count);
18116e158384SHugh Dickins 
18126e158384SHugh Dickins 	if (needs_wakeup)
18136e158384SHugh Dickins 		wake_up_interruptible(&ksm_thread_wait);
18146e158384SHugh Dickins 
1815f8af4da3SHugh Dickins 	return 0;
1816f8af4da3SHugh Dickins }
1817f8af4da3SHugh Dickins 
18181c2fb7a4SAndrea Arcangeli void __ksm_exit(struct mm_struct *mm)
1819f8af4da3SHugh Dickins {
1820cd551f97SHugh Dickins 	struct mm_slot *mm_slot;
18219ba69294SHugh Dickins 	int easy_to_free = 0;
1822cd551f97SHugh Dickins 
182331dbd01fSIzik Eidus 	/*
18249ba69294SHugh Dickins 	 * This process is exiting: if it's straightforward (as is the
18259ba69294SHugh Dickins 	 * case when ksmd was never running), free mm_slot immediately.
18269ba69294SHugh Dickins 	 * But if it's at the cursor or has rmap_items linked to it, use
18279ba69294SHugh Dickins 	 * mmap_sem to synchronize with any break_cows before pagetables
18289ba69294SHugh Dickins 	 * are freed, and leave the mm_slot on the list for ksmd to free.
18299ba69294SHugh Dickins 	 * Beware: ksm may already have noticed it exiting and freed the slot.
183031dbd01fSIzik Eidus 	 */
18319ba69294SHugh Dickins 
1832cd551f97SHugh Dickins 	spin_lock(&ksm_mmlist_lock);
1833cd551f97SHugh Dickins 	mm_slot = get_mm_slot(mm);
18349ba69294SHugh Dickins 	if (mm_slot && ksm_scan.mm_slot != mm_slot) {
18356514d511SHugh Dickins 		if (!mm_slot->rmap_list) {
18364ca3a69bSSasha Levin 			hash_del(&mm_slot->link);
1837cd551f97SHugh Dickins 			list_del(&mm_slot->mm_list);
18389ba69294SHugh Dickins 			easy_to_free = 1;
18399ba69294SHugh Dickins 		} else {
18409ba69294SHugh Dickins 			list_move(&mm_slot->mm_list,
18419ba69294SHugh Dickins 				  &ksm_scan.mm_slot->mm_list);
18429ba69294SHugh Dickins 		}
18439ba69294SHugh Dickins 	}
1844cd551f97SHugh Dickins 	spin_unlock(&ksm_mmlist_lock);
1845cd551f97SHugh Dickins 
18469ba69294SHugh Dickins 	if (easy_to_free) {
1847cd551f97SHugh Dickins 		free_mm_slot(mm_slot);
1848cd551f97SHugh Dickins 		clear_bit(MMF_VM_MERGEABLE, &mm->flags);
18499ba69294SHugh Dickins 		mmdrop(mm);
18509ba69294SHugh Dickins 	} else if (mm_slot) {
18519ba69294SHugh Dickins 		down_write(&mm->mmap_sem);
18529ba69294SHugh Dickins 		up_write(&mm->mmap_sem);
18539ba69294SHugh Dickins 	}
1854f8af4da3SHugh Dickins }
185531dbd01fSIzik Eidus 
1856cbf86cfeSHugh Dickins struct page *ksm_might_need_to_copy(struct page *page,
18575ad64688SHugh Dickins 			struct vm_area_struct *vma, unsigned long address)
18585ad64688SHugh Dickins {
1859cbf86cfeSHugh Dickins 	struct anon_vma *anon_vma = page_anon_vma(page);
18605ad64688SHugh Dickins 	struct page *new_page;
18615ad64688SHugh Dickins 
1862cbf86cfeSHugh Dickins 	if (PageKsm(page)) {
1863cbf86cfeSHugh Dickins 		if (page_stable_node(page) &&
1864cbf86cfeSHugh Dickins 		    !(ksm_run & KSM_RUN_UNMERGE))
1865cbf86cfeSHugh Dickins 			return page;	/* no need to copy it */
1866cbf86cfeSHugh Dickins 	} else if (!anon_vma) {
1867cbf86cfeSHugh Dickins 		return page;		/* no need to copy it */
1868cbf86cfeSHugh Dickins 	} else if (anon_vma->root == vma->anon_vma->root &&
1869cbf86cfeSHugh Dickins 		 page->index == linear_page_index(vma, address)) {
1870cbf86cfeSHugh Dickins 		return page;		/* still no need to copy it */
1871cbf86cfeSHugh Dickins 	}
1872cbf86cfeSHugh Dickins 	if (!PageUptodate(page))
1873cbf86cfeSHugh Dickins 		return page;		/* let do_swap_page report the error */
1874cbf86cfeSHugh Dickins 
18755ad64688SHugh Dickins 	new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
18765ad64688SHugh Dickins 	if (new_page) {
18775ad64688SHugh Dickins 		copy_user_highpage(new_page, page, address, vma);
18785ad64688SHugh Dickins 
18795ad64688SHugh Dickins 		SetPageDirty(new_page);
18805ad64688SHugh Dickins 		__SetPageUptodate(new_page);
188148c935adSKirill A. Shutemov 		__SetPageLocked(new_page);
18825ad64688SHugh Dickins 	}
18835ad64688SHugh Dickins 
18845ad64688SHugh Dickins 	return new_page;
18855ad64688SHugh Dickins }
18865ad64688SHugh Dickins 
1887051ac83aSJoonsoo Kim int rmap_walk_ksm(struct page *page, struct rmap_walk_control *rwc)
1888e9995ef9SHugh Dickins {
1889e9995ef9SHugh Dickins 	struct stable_node *stable_node;
1890e9995ef9SHugh Dickins 	struct rmap_item *rmap_item;
1891e9995ef9SHugh Dickins 	int ret = SWAP_AGAIN;
1892e9995ef9SHugh Dickins 	int search_new_forks = 0;
1893e9995ef9SHugh Dickins 
1894309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageKsm(page), page);
18959f32624bSJoonsoo Kim 
18969f32624bSJoonsoo Kim 	/*
18979f32624bSJoonsoo Kim 	 * Rely on the page lock to protect against concurrent modifications
18989f32624bSJoonsoo Kim 	 * to that page's node of the stable tree.
18999f32624bSJoonsoo Kim 	 */
1900309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
1901e9995ef9SHugh Dickins 
1902e9995ef9SHugh Dickins 	stable_node = page_stable_node(page);
1903e9995ef9SHugh Dickins 	if (!stable_node)
1904e9995ef9SHugh Dickins 		return ret;
1905e9995ef9SHugh Dickins again:
1906b67bfe0dSSasha Levin 	hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
1907e9995ef9SHugh Dickins 		struct anon_vma *anon_vma = rmap_item->anon_vma;
19085beb4930SRik van Riel 		struct anon_vma_chain *vmac;
1909e9995ef9SHugh Dickins 		struct vm_area_struct *vma;
1910e9995ef9SHugh Dickins 
1911ad12695fSAndrea Arcangeli 		cond_resched();
1912b6b19f25SHugh Dickins 		anon_vma_lock_read(anon_vma);
1913bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
1914bf181b9fSMichel Lespinasse 					       0, ULONG_MAX) {
1915ad12695fSAndrea Arcangeli 			cond_resched();
19165beb4930SRik van Riel 			vma = vmac->vma;
1917e9995ef9SHugh Dickins 			if (rmap_item->address < vma->vm_start ||
1918e9995ef9SHugh Dickins 			    rmap_item->address >= vma->vm_end)
1919e9995ef9SHugh Dickins 				continue;
1920e9995ef9SHugh Dickins 			/*
1921e9995ef9SHugh Dickins 			 * Initially we examine only the vma which covers this
1922e9995ef9SHugh Dickins 			 * rmap_item; but later, if there is still work to do,
1923e9995ef9SHugh Dickins 			 * we examine covering vmas in other mms: in case they
1924e9995ef9SHugh Dickins 			 * were forked from the original since ksmd passed.
1925e9995ef9SHugh Dickins 			 */
1926e9995ef9SHugh Dickins 			if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
1927e9995ef9SHugh Dickins 				continue;
1928e9995ef9SHugh Dickins 
19290dd1c7bbSJoonsoo Kim 			if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
19300dd1c7bbSJoonsoo Kim 				continue;
19310dd1c7bbSJoonsoo Kim 
1932051ac83aSJoonsoo Kim 			ret = rwc->rmap_one(page, vma,
1933051ac83aSJoonsoo Kim 					rmap_item->address, rwc->arg);
1934e9995ef9SHugh Dickins 			if (ret != SWAP_AGAIN) {
1935b6b19f25SHugh Dickins 				anon_vma_unlock_read(anon_vma);
1936e9995ef9SHugh Dickins 				goto out;
1937e9995ef9SHugh Dickins 			}
19380dd1c7bbSJoonsoo Kim 			if (rwc->done && rwc->done(page)) {
19390dd1c7bbSJoonsoo Kim 				anon_vma_unlock_read(anon_vma);
19400dd1c7bbSJoonsoo Kim 				goto out;
19410dd1c7bbSJoonsoo Kim 			}
1942e9995ef9SHugh Dickins 		}
1943b6b19f25SHugh Dickins 		anon_vma_unlock_read(anon_vma);
1944e9995ef9SHugh Dickins 	}
1945e9995ef9SHugh Dickins 	if (!search_new_forks++)
1946e9995ef9SHugh Dickins 		goto again;
1947e9995ef9SHugh Dickins out:
1948e9995ef9SHugh Dickins 	return ret;
1949e9995ef9SHugh Dickins }
1950e9995ef9SHugh Dickins 
195152629506SJoonsoo Kim #ifdef CONFIG_MIGRATION
1952e9995ef9SHugh Dickins void ksm_migrate_page(struct page *newpage, struct page *oldpage)
1953e9995ef9SHugh Dickins {
1954e9995ef9SHugh Dickins 	struct stable_node *stable_node;
1955e9995ef9SHugh Dickins 
1956309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
1957309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
1958309381feSSasha Levin 	VM_BUG_ON_PAGE(newpage->mapping != oldpage->mapping, newpage);
1959e9995ef9SHugh Dickins 
1960e9995ef9SHugh Dickins 	stable_node = page_stable_node(newpage);
1961e9995ef9SHugh Dickins 	if (stable_node) {
1962309381feSSasha Levin 		VM_BUG_ON_PAGE(stable_node->kpfn != page_to_pfn(oldpage), oldpage);
196362b61f61SHugh Dickins 		stable_node->kpfn = page_to_pfn(newpage);
1964c8d6553bSHugh Dickins 		/*
1965c8d6553bSHugh Dickins 		 * newpage->mapping was set in advance; now we need smp_wmb()
1966c8d6553bSHugh Dickins 		 * to make sure that the new stable_node->kpfn is visible
1967c8d6553bSHugh Dickins 		 * to get_ksm_page() before it can see that oldpage->mapping
1968c8d6553bSHugh Dickins 		 * has gone stale (or that PageSwapCache has been cleared).
1969c8d6553bSHugh Dickins 		 */
1970c8d6553bSHugh Dickins 		smp_wmb();
1971c8d6553bSHugh Dickins 		set_page_stable_node(oldpage, NULL);
1972e9995ef9SHugh Dickins 	}
1973e9995ef9SHugh Dickins }
1974e9995ef9SHugh Dickins #endif /* CONFIG_MIGRATION */
1975e9995ef9SHugh Dickins 
197662b61f61SHugh Dickins #ifdef CONFIG_MEMORY_HOTREMOVE
1977ef4d43a8SHugh Dickins static void wait_while_offlining(void)
1978ef4d43a8SHugh Dickins {
1979ef4d43a8SHugh Dickins 	while (ksm_run & KSM_RUN_OFFLINE) {
1980ef4d43a8SHugh Dickins 		mutex_unlock(&ksm_thread_mutex);
1981ef4d43a8SHugh Dickins 		wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
198274316201SNeilBrown 			    TASK_UNINTERRUPTIBLE);
1983ef4d43a8SHugh Dickins 		mutex_lock(&ksm_thread_mutex);
1984ef4d43a8SHugh Dickins 	}
1985ef4d43a8SHugh Dickins }
1986ef4d43a8SHugh Dickins 
1987ee0ea59cSHugh Dickins static void ksm_check_stable_tree(unsigned long start_pfn,
198862b61f61SHugh Dickins 				  unsigned long end_pfn)
198962b61f61SHugh Dickins {
199003640418SGeliang Tang 	struct stable_node *stable_node, *next;
199162b61f61SHugh Dickins 	struct rb_node *node;
199290bd6fd3SPetr Holasek 	int nid;
199362b61f61SHugh Dickins 
1994ef53d16cSHugh Dickins 	for (nid = 0; nid < ksm_nr_node_ids; nid++) {
1995ef53d16cSHugh Dickins 		node = rb_first(root_stable_tree + nid);
1996ee0ea59cSHugh Dickins 		while (node) {
199762b61f61SHugh Dickins 			stable_node = rb_entry(node, struct stable_node, node);
199862b61f61SHugh Dickins 			if (stable_node->kpfn >= start_pfn &&
1999ee0ea59cSHugh Dickins 			    stable_node->kpfn < end_pfn) {
2000ee0ea59cSHugh Dickins 				/*
2001ee0ea59cSHugh Dickins 				 * Don't get_ksm_page, page has already gone:
2002ee0ea59cSHugh Dickins 				 * which is why we keep kpfn instead of page*
2003ee0ea59cSHugh Dickins 				 */
2004ee0ea59cSHugh Dickins 				remove_node_from_stable_tree(stable_node);
2005ef53d16cSHugh Dickins 				node = rb_first(root_stable_tree + nid);
2006ee0ea59cSHugh Dickins 			} else
2007ee0ea59cSHugh Dickins 				node = rb_next(node);
2008ee0ea59cSHugh Dickins 			cond_resched();
200962b61f61SHugh Dickins 		}
2010ee0ea59cSHugh Dickins 	}
201103640418SGeliang Tang 	list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
20124146d2d6SHugh Dickins 		if (stable_node->kpfn >= start_pfn &&
20134146d2d6SHugh Dickins 		    stable_node->kpfn < end_pfn)
20144146d2d6SHugh Dickins 			remove_node_from_stable_tree(stable_node);
20154146d2d6SHugh Dickins 		cond_resched();
20164146d2d6SHugh Dickins 	}
201762b61f61SHugh Dickins }
201862b61f61SHugh Dickins 
201962b61f61SHugh Dickins static int ksm_memory_callback(struct notifier_block *self,
202062b61f61SHugh Dickins 			       unsigned long action, void *arg)
202162b61f61SHugh Dickins {
202262b61f61SHugh Dickins 	struct memory_notify *mn = arg;
202362b61f61SHugh Dickins 
202462b61f61SHugh Dickins 	switch (action) {
202562b61f61SHugh Dickins 	case MEM_GOING_OFFLINE:
202662b61f61SHugh Dickins 		/*
2027ef4d43a8SHugh Dickins 		 * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
2028ef4d43a8SHugh Dickins 		 * and remove_all_stable_nodes() while memory is going offline:
2029ef4d43a8SHugh Dickins 		 * it is unsafe for them to touch the stable tree at this time.
2030ef4d43a8SHugh Dickins 		 * But unmerge_ksm_pages(), rmap lookups and other entry points
2031ef4d43a8SHugh Dickins 		 * which do not need the ksm_thread_mutex are all safe.
203262b61f61SHugh Dickins 		 */
2033ef4d43a8SHugh Dickins 		mutex_lock(&ksm_thread_mutex);
2034ef4d43a8SHugh Dickins 		ksm_run |= KSM_RUN_OFFLINE;
2035ef4d43a8SHugh Dickins 		mutex_unlock(&ksm_thread_mutex);
203662b61f61SHugh Dickins 		break;
203762b61f61SHugh Dickins 
203862b61f61SHugh Dickins 	case MEM_OFFLINE:
203962b61f61SHugh Dickins 		/*
204062b61f61SHugh Dickins 		 * Most of the work is done by page migration; but there might
204162b61f61SHugh Dickins 		 * be a few stable_nodes left over, still pointing to struct
2042ee0ea59cSHugh Dickins 		 * pages which have been offlined: prune those from the tree,
2043ee0ea59cSHugh Dickins 		 * otherwise get_ksm_page() might later try to access a
2044ee0ea59cSHugh Dickins 		 * non-existent struct page.
204562b61f61SHugh Dickins 		 */
2046ee0ea59cSHugh Dickins 		ksm_check_stable_tree(mn->start_pfn,
2047ee0ea59cSHugh Dickins 				      mn->start_pfn + mn->nr_pages);
204862b61f61SHugh Dickins 		/* fallthrough */
204962b61f61SHugh Dickins 
205062b61f61SHugh Dickins 	case MEM_CANCEL_OFFLINE:
2051ef4d43a8SHugh Dickins 		mutex_lock(&ksm_thread_mutex);
2052ef4d43a8SHugh Dickins 		ksm_run &= ~KSM_RUN_OFFLINE;
205362b61f61SHugh Dickins 		mutex_unlock(&ksm_thread_mutex);
2054ef4d43a8SHugh Dickins 
2055ef4d43a8SHugh Dickins 		smp_mb();	/* wake_up_bit advises this */
2056ef4d43a8SHugh Dickins 		wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
205762b61f61SHugh Dickins 		break;
205862b61f61SHugh Dickins 	}
205962b61f61SHugh Dickins 	return NOTIFY_OK;
206062b61f61SHugh Dickins }
2061ef4d43a8SHugh Dickins #else
2062ef4d43a8SHugh Dickins static void wait_while_offlining(void)
2063ef4d43a8SHugh Dickins {
2064ef4d43a8SHugh Dickins }
206562b61f61SHugh Dickins #endif /* CONFIG_MEMORY_HOTREMOVE */
206662b61f61SHugh Dickins 
20672ffd8679SHugh Dickins #ifdef CONFIG_SYSFS
20682ffd8679SHugh Dickins /*
20692ffd8679SHugh Dickins  * This all compiles without CONFIG_SYSFS, but is a waste of space.
20702ffd8679SHugh Dickins  */
20712ffd8679SHugh Dickins 
207231dbd01fSIzik Eidus #define KSM_ATTR_RO(_name) \
207331dbd01fSIzik Eidus 	static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
207431dbd01fSIzik Eidus #define KSM_ATTR(_name) \
207531dbd01fSIzik Eidus 	static struct kobj_attribute _name##_attr = \
207631dbd01fSIzik Eidus 		__ATTR(_name, 0644, _name##_show, _name##_store)
207731dbd01fSIzik Eidus 
207831dbd01fSIzik Eidus static ssize_t sleep_millisecs_show(struct kobject *kobj,
207931dbd01fSIzik Eidus 				    struct kobj_attribute *attr, char *buf)
208031dbd01fSIzik Eidus {
208131dbd01fSIzik Eidus 	return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
208231dbd01fSIzik Eidus }
208331dbd01fSIzik Eidus 
208431dbd01fSIzik Eidus static ssize_t sleep_millisecs_store(struct kobject *kobj,
208531dbd01fSIzik Eidus 				     struct kobj_attribute *attr,
208631dbd01fSIzik Eidus 				     const char *buf, size_t count)
208731dbd01fSIzik Eidus {
208831dbd01fSIzik Eidus 	unsigned long msecs;
208931dbd01fSIzik Eidus 	int err;
209031dbd01fSIzik Eidus 
20913dbb95f7SJingoo Han 	err = kstrtoul(buf, 10, &msecs);
209231dbd01fSIzik Eidus 	if (err || msecs > UINT_MAX)
209331dbd01fSIzik Eidus 		return -EINVAL;
209431dbd01fSIzik Eidus 
209531dbd01fSIzik Eidus 	ksm_thread_sleep_millisecs = msecs;
209631dbd01fSIzik Eidus 
209731dbd01fSIzik Eidus 	return count;
209831dbd01fSIzik Eidus }
209931dbd01fSIzik Eidus KSM_ATTR(sleep_millisecs);
210031dbd01fSIzik Eidus 
210131dbd01fSIzik Eidus static ssize_t pages_to_scan_show(struct kobject *kobj,
210231dbd01fSIzik Eidus 				  struct kobj_attribute *attr, char *buf)
210331dbd01fSIzik Eidus {
210431dbd01fSIzik Eidus 	return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
210531dbd01fSIzik Eidus }
210631dbd01fSIzik Eidus 
210731dbd01fSIzik Eidus static ssize_t pages_to_scan_store(struct kobject *kobj,
210831dbd01fSIzik Eidus 				   struct kobj_attribute *attr,
210931dbd01fSIzik Eidus 				   const char *buf, size_t count)
211031dbd01fSIzik Eidus {
211131dbd01fSIzik Eidus 	int err;
211231dbd01fSIzik Eidus 	unsigned long nr_pages;
211331dbd01fSIzik Eidus 
21143dbb95f7SJingoo Han 	err = kstrtoul(buf, 10, &nr_pages);
211531dbd01fSIzik Eidus 	if (err || nr_pages > UINT_MAX)
211631dbd01fSIzik Eidus 		return -EINVAL;
211731dbd01fSIzik Eidus 
211831dbd01fSIzik Eidus 	ksm_thread_pages_to_scan = nr_pages;
211931dbd01fSIzik Eidus 
212031dbd01fSIzik Eidus 	return count;
212131dbd01fSIzik Eidus }
212231dbd01fSIzik Eidus KSM_ATTR(pages_to_scan);
212331dbd01fSIzik Eidus 
212431dbd01fSIzik Eidus static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
212531dbd01fSIzik Eidus 			char *buf)
212631dbd01fSIzik Eidus {
2127ef4d43a8SHugh Dickins 	return sprintf(buf, "%lu\n", ksm_run);
212831dbd01fSIzik Eidus }
212931dbd01fSIzik Eidus 
213031dbd01fSIzik Eidus static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
213131dbd01fSIzik Eidus 			 const char *buf, size_t count)
213231dbd01fSIzik Eidus {
213331dbd01fSIzik Eidus 	int err;
213431dbd01fSIzik Eidus 	unsigned long flags;
213531dbd01fSIzik Eidus 
21363dbb95f7SJingoo Han 	err = kstrtoul(buf, 10, &flags);
213731dbd01fSIzik Eidus 	if (err || flags > UINT_MAX)
213831dbd01fSIzik Eidus 		return -EINVAL;
213931dbd01fSIzik Eidus 	if (flags > KSM_RUN_UNMERGE)
214031dbd01fSIzik Eidus 		return -EINVAL;
214131dbd01fSIzik Eidus 
214231dbd01fSIzik Eidus 	/*
214331dbd01fSIzik Eidus 	 * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
214431dbd01fSIzik Eidus 	 * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
2145d0f209f6SHugh Dickins 	 * breaking COW to free the pages_shared (but leaves mm_slots
2146d0f209f6SHugh Dickins 	 * on the list for when ksmd may be set running again).
214731dbd01fSIzik Eidus 	 */
214831dbd01fSIzik Eidus 
214931dbd01fSIzik Eidus 	mutex_lock(&ksm_thread_mutex);
2150ef4d43a8SHugh Dickins 	wait_while_offlining();
215131dbd01fSIzik Eidus 	if (ksm_run != flags) {
215231dbd01fSIzik Eidus 		ksm_run = flags;
2153d952b791SHugh Dickins 		if (flags & KSM_RUN_UNMERGE) {
2154e1e12d2fSDavid Rientjes 			set_current_oom_origin();
2155d952b791SHugh Dickins 			err = unmerge_and_remove_all_rmap_items();
2156e1e12d2fSDavid Rientjes 			clear_current_oom_origin();
2157d952b791SHugh Dickins 			if (err) {
2158d952b791SHugh Dickins 				ksm_run = KSM_RUN_STOP;
2159d952b791SHugh Dickins 				count = err;
2160d952b791SHugh Dickins 			}
2161d952b791SHugh Dickins 		}
216231dbd01fSIzik Eidus 	}
216331dbd01fSIzik Eidus 	mutex_unlock(&ksm_thread_mutex);
216431dbd01fSIzik Eidus 
216531dbd01fSIzik Eidus 	if (flags & KSM_RUN_MERGE)
216631dbd01fSIzik Eidus 		wake_up_interruptible(&ksm_thread_wait);
216731dbd01fSIzik Eidus 
216831dbd01fSIzik Eidus 	return count;
216931dbd01fSIzik Eidus }
217031dbd01fSIzik Eidus KSM_ATTR(run);
217131dbd01fSIzik Eidus 
217290bd6fd3SPetr Holasek #ifdef CONFIG_NUMA
217390bd6fd3SPetr Holasek static ssize_t merge_across_nodes_show(struct kobject *kobj,
217490bd6fd3SPetr Holasek 				struct kobj_attribute *attr, char *buf)
217590bd6fd3SPetr Holasek {
217690bd6fd3SPetr Holasek 	return sprintf(buf, "%u\n", ksm_merge_across_nodes);
217790bd6fd3SPetr Holasek }
217890bd6fd3SPetr Holasek 
217990bd6fd3SPetr Holasek static ssize_t merge_across_nodes_store(struct kobject *kobj,
218090bd6fd3SPetr Holasek 				   struct kobj_attribute *attr,
218190bd6fd3SPetr Holasek 				   const char *buf, size_t count)
218290bd6fd3SPetr Holasek {
218390bd6fd3SPetr Holasek 	int err;
218490bd6fd3SPetr Holasek 	unsigned long knob;
218590bd6fd3SPetr Holasek 
218690bd6fd3SPetr Holasek 	err = kstrtoul(buf, 10, &knob);
218790bd6fd3SPetr Holasek 	if (err)
218890bd6fd3SPetr Holasek 		return err;
218990bd6fd3SPetr Holasek 	if (knob > 1)
219090bd6fd3SPetr Holasek 		return -EINVAL;
219190bd6fd3SPetr Holasek 
219290bd6fd3SPetr Holasek 	mutex_lock(&ksm_thread_mutex);
2193ef4d43a8SHugh Dickins 	wait_while_offlining();
219490bd6fd3SPetr Holasek 	if (ksm_merge_across_nodes != knob) {
2195cbf86cfeSHugh Dickins 		if (ksm_pages_shared || remove_all_stable_nodes())
219690bd6fd3SPetr Holasek 			err = -EBUSY;
2197ef53d16cSHugh Dickins 		else if (root_stable_tree == one_stable_tree) {
2198ef53d16cSHugh Dickins 			struct rb_root *buf;
2199ef53d16cSHugh Dickins 			/*
2200ef53d16cSHugh Dickins 			 * This is the first time that we switch away from the
2201ef53d16cSHugh Dickins 			 * default of merging across nodes: must now allocate
2202ef53d16cSHugh Dickins 			 * a buffer to hold as many roots as may be needed.
2203ef53d16cSHugh Dickins 			 * Allocate stable and unstable together:
2204ef53d16cSHugh Dickins 			 * MAXSMP NODES_SHIFT 10 will use 16kB.
2205ef53d16cSHugh Dickins 			 */
2206bafe1e14SJoe Perches 			buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf),
2207bafe1e14SJoe Perches 				      GFP_KERNEL);
2208ef53d16cSHugh Dickins 			/* Let us assume that RB_ROOT is NULL is zero */
2209ef53d16cSHugh Dickins 			if (!buf)
2210ef53d16cSHugh Dickins 				err = -ENOMEM;
2211ef53d16cSHugh Dickins 			else {
2212ef53d16cSHugh Dickins 				root_stable_tree = buf;
2213ef53d16cSHugh Dickins 				root_unstable_tree = buf + nr_node_ids;
2214ef53d16cSHugh Dickins 				/* Stable tree is empty but not the unstable */
2215ef53d16cSHugh Dickins 				root_unstable_tree[0] = one_unstable_tree[0];
2216ef53d16cSHugh Dickins 			}
2217ef53d16cSHugh Dickins 		}
2218ef53d16cSHugh Dickins 		if (!err) {
221990bd6fd3SPetr Holasek 			ksm_merge_across_nodes = knob;
2220ef53d16cSHugh Dickins 			ksm_nr_node_ids = knob ? 1 : nr_node_ids;
2221ef53d16cSHugh Dickins 		}
222290bd6fd3SPetr Holasek 	}
222390bd6fd3SPetr Holasek 	mutex_unlock(&ksm_thread_mutex);
222490bd6fd3SPetr Holasek 
222590bd6fd3SPetr Holasek 	return err ? err : count;
222690bd6fd3SPetr Holasek }
222790bd6fd3SPetr Holasek KSM_ATTR(merge_across_nodes);
222890bd6fd3SPetr Holasek #endif
222990bd6fd3SPetr Holasek 
2230b4028260SHugh Dickins static ssize_t pages_shared_show(struct kobject *kobj,
2231b4028260SHugh Dickins 				 struct kobj_attribute *attr, char *buf)
2232b4028260SHugh Dickins {
2233b4028260SHugh Dickins 	return sprintf(buf, "%lu\n", ksm_pages_shared);
2234b4028260SHugh Dickins }
2235b4028260SHugh Dickins KSM_ATTR_RO(pages_shared);
2236b4028260SHugh Dickins 
2237b4028260SHugh Dickins static ssize_t pages_sharing_show(struct kobject *kobj,
2238b4028260SHugh Dickins 				  struct kobj_attribute *attr, char *buf)
2239b4028260SHugh Dickins {
2240e178dfdeSHugh Dickins 	return sprintf(buf, "%lu\n", ksm_pages_sharing);
2241b4028260SHugh Dickins }
2242b4028260SHugh Dickins KSM_ATTR_RO(pages_sharing);
2243b4028260SHugh Dickins 
2244473b0ce4SHugh Dickins static ssize_t pages_unshared_show(struct kobject *kobj,
2245473b0ce4SHugh Dickins 				   struct kobj_attribute *attr, char *buf)
2246473b0ce4SHugh Dickins {
2247473b0ce4SHugh Dickins 	return sprintf(buf, "%lu\n", ksm_pages_unshared);
2248473b0ce4SHugh Dickins }
2249473b0ce4SHugh Dickins KSM_ATTR_RO(pages_unshared);
2250473b0ce4SHugh Dickins 
2251473b0ce4SHugh Dickins static ssize_t pages_volatile_show(struct kobject *kobj,
2252473b0ce4SHugh Dickins 				   struct kobj_attribute *attr, char *buf)
2253473b0ce4SHugh Dickins {
2254473b0ce4SHugh Dickins 	long ksm_pages_volatile;
2255473b0ce4SHugh Dickins 
2256473b0ce4SHugh Dickins 	ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
2257473b0ce4SHugh Dickins 				- ksm_pages_sharing - ksm_pages_unshared;
2258473b0ce4SHugh Dickins 	/*
2259473b0ce4SHugh Dickins 	 * It was not worth any locking to calculate that statistic,
2260473b0ce4SHugh Dickins 	 * but it might therefore sometimes be negative: conceal that.
2261473b0ce4SHugh Dickins 	 */
2262473b0ce4SHugh Dickins 	if (ksm_pages_volatile < 0)
2263473b0ce4SHugh Dickins 		ksm_pages_volatile = 0;
2264473b0ce4SHugh Dickins 	return sprintf(buf, "%ld\n", ksm_pages_volatile);
2265473b0ce4SHugh Dickins }
2266473b0ce4SHugh Dickins KSM_ATTR_RO(pages_volatile);
2267473b0ce4SHugh Dickins 
2268473b0ce4SHugh Dickins static ssize_t full_scans_show(struct kobject *kobj,
2269473b0ce4SHugh Dickins 			       struct kobj_attribute *attr, char *buf)
2270473b0ce4SHugh Dickins {
2271473b0ce4SHugh Dickins 	return sprintf(buf, "%lu\n", ksm_scan.seqnr);
2272473b0ce4SHugh Dickins }
2273473b0ce4SHugh Dickins KSM_ATTR_RO(full_scans);
2274473b0ce4SHugh Dickins 
227531dbd01fSIzik Eidus static struct attribute *ksm_attrs[] = {
227631dbd01fSIzik Eidus 	&sleep_millisecs_attr.attr,
227731dbd01fSIzik Eidus 	&pages_to_scan_attr.attr,
227831dbd01fSIzik Eidus 	&run_attr.attr,
2279b4028260SHugh Dickins 	&pages_shared_attr.attr,
2280b4028260SHugh Dickins 	&pages_sharing_attr.attr,
2281473b0ce4SHugh Dickins 	&pages_unshared_attr.attr,
2282473b0ce4SHugh Dickins 	&pages_volatile_attr.attr,
2283473b0ce4SHugh Dickins 	&full_scans_attr.attr,
228490bd6fd3SPetr Holasek #ifdef CONFIG_NUMA
228590bd6fd3SPetr Holasek 	&merge_across_nodes_attr.attr,
228690bd6fd3SPetr Holasek #endif
228731dbd01fSIzik Eidus 	NULL,
228831dbd01fSIzik Eidus };
228931dbd01fSIzik Eidus 
229031dbd01fSIzik Eidus static struct attribute_group ksm_attr_group = {
229131dbd01fSIzik Eidus 	.attrs = ksm_attrs,
229231dbd01fSIzik Eidus 	.name = "ksm",
229331dbd01fSIzik Eidus };
22942ffd8679SHugh Dickins #endif /* CONFIG_SYSFS */
229531dbd01fSIzik Eidus 
229631dbd01fSIzik Eidus static int __init ksm_init(void)
229731dbd01fSIzik Eidus {
229831dbd01fSIzik Eidus 	struct task_struct *ksm_thread;
229931dbd01fSIzik Eidus 	int err;
230031dbd01fSIzik Eidus 
230131dbd01fSIzik Eidus 	err = ksm_slab_init();
230231dbd01fSIzik Eidus 	if (err)
230331dbd01fSIzik Eidus 		goto out;
230431dbd01fSIzik Eidus 
230531dbd01fSIzik Eidus 	ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
230631dbd01fSIzik Eidus 	if (IS_ERR(ksm_thread)) {
230725acde31SPaul McQuade 		pr_err("ksm: creating kthread failed\n");
230831dbd01fSIzik Eidus 		err = PTR_ERR(ksm_thread);
2309d9f8984cSLai Jiangshan 		goto out_free;
231031dbd01fSIzik Eidus 	}
231131dbd01fSIzik Eidus 
23122ffd8679SHugh Dickins #ifdef CONFIG_SYSFS
231331dbd01fSIzik Eidus 	err = sysfs_create_group(mm_kobj, &ksm_attr_group);
231431dbd01fSIzik Eidus 	if (err) {
231525acde31SPaul McQuade 		pr_err("ksm: register sysfs failed\n");
23162ffd8679SHugh Dickins 		kthread_stop(ksm_thread);
2317d9f8984cSLai Jiangshan 		goto out_free;
231831dbd01fSIzik Eidus 	}
2319c73602adSHugh Dickins #else
2320c73602adSHugh Dickins 	ksm_run = KSM_RUN_MERGE;	/* no way for user to start it */
2321c73602adSHugh Dickins 
23222ffd8679SHugh Dickins #endif /* CONFIG_SYSFS */
232331dbd01fSIzik Eidus 
232462b61f61SHugh Dickins #ifdef CONFIG_MEMORY_HOTREMOVE
2325ef4d43a8SHugh Dickins 	/* There is no significance to this priority 100 */
232662b61f61SHugh Dickins 	hotplug_memory_notifier(ksm_memory_callback, 100);
232762b61f61SHugh Dickins #endif
232831dbd01fSIzik Eidus 	return 0;
232931dbd01fSIzik Eidus 
2330d9f8984cSLai Jiangshan out_free:
233131dbd01fSIzik Eidus 	ksm_slab_free();
233231dbd01fSIzik Eidus out:
233331dbd01fSIzik Eidus 	return err;
233431dbd01fSIzik Eidus }
2335a64fb3cdSPaul Gortmaker subsys_initcall(ksm_init);
2336