ksm.c 66 KB

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