ksm.c 64 KB

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