ksm.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  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_SIGSEGV | 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_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 = READ_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 (READ_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 (READ_ONCE(page->mapping) != expected_mapping) {
  520. put_page(page);
  521. goto stale;
  522. }
  523. if (lock_it) {
  524. lock_page(page);
  525. if (READ_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 (READ_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_notify(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. mmun_start = addr;
  848. mmun_end = addr + PAGE_SIZE;
  849. mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
  850. ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
  851. if (!pte_same(*ptep, orig_pte)) {
  852. pte_unmap_unlock(ptep, ptl);
  853. goto out_mn;
  854. }
  855. get_page(kpage);
  856. page_add_anon_rmap(kpage, vma, addr);
  857. flush_cache_page(vma, addr, pte_pfn(*ptep));
  858. ptep_clear_flush_notify(vma, addr, ptep);
  859. set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
  860. page_remove_rmap(page);
  861. if (!page_mapped(page))
  862. try_to_free_swap(page);
  863. put_page(page);
  864. pte_unmap_unlock(ptep, ptl);
  865. err = 0;
  866. out_mn:
  867. mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
  868. out:
  869. return err;
  870. }
  871. static int page_trans_compound_anon_split(struct page *page)
  872. {
  873. int ret = 0;
  874. struct page *transhuge_head = page_trans_compound_anon(page);
  875. if (transhuge_head) {
  876. /* Get the reference on the head to split it. */
  877. if (get_page_unless_zero(transhuge_head)) {
  878. /*
  879. * Recheck we got the reference while the head
  880. * was still anonymous.
  881. */
  882. if (PageAnon(transhuge_head))
  883. ret = split_huge_page(transhuge_head);
  884. else
  885. /*
  886. * Retry later if split_huge_page run
  887. * from under us.
  888. */
  889. ret = 1;
  890. put_page(transhuge_head);
  891. } else
  892. /* Retry later if split_huge_page run from under us. */
  893. ret = 1;
  894. }
  895. return ret;
  896. }
  897. /*
  898. * try_to_merge_one_page - take two pages and merge them into one
  899. * @vma: the vma that holds the pte pointing to page
  900. * @page: the PageAnon page that we want to replace with kpage
  901. * @kpage: the PageKsm page that we want to map instead of page,
  902. * or NULL the first time when we want to use page as kpage.
  903. *
  904. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  905. */
  906. static int try_to_merge_one_page(struct vm_area_struct *vma,
  907. struct page *page, struct page *kpage)
  908. {
  909. pte_t orig_pte = __pte(0);
  910. int err = -EFAULT;
  911. if (page == kpage) /* ksm page forked */
  912. return 0;
  913. if (!(vma->vm_flags & VM_MERGEABLE))
  914. goto out;
  915. if (PageTransCompound(page) && page_trans_compound_anon_split(page))
  916. goto out;
  917. BUG_ON(PageTransCompound(page));
  918. if (!PageAnon(page))
  919. goto out;
  920. /*
  921. * We need the page lock to read a stable PageSwapCache in
  922. * write_protect_page(). We use trylock_page() instead of
  923. * lock_page() because we don't want to wait here - we
  924. * prefer to continue scanning and merging different pages,
  925. * then come back to this page when it is unlocked.
  926. */
  927. if (!trylock_page(page))
  928. goto out;
  929. /*
  930. * If this anonymous page is mapped only here, its pte may need
  931. * to be write-protected. If it's mapped elsewhere, all of its
  932. * ptes are necessarily already write-protected. But in either
  933. * case, we need to lock and check page_count is not raised.
  934. */
  935. if (write_protect_page(vma, page, &orig_pte) == 0) {
  936. if (!kpage) {
  937. /*
  938. * While we hold page lock, upgrade page from
  939. * PageAnon+anon_vma to PageKsm+NULL stable_node:
  940. * stable_tree_insert() will update stable_node.
  941. */
  942. set_page_stable_node(page, NULL);
  943. mark_page_accessed(page);
  944. err = 0;
  945. } else if (pages_identical(page, kpage))
  946. err = replace_page(vma, page, kpage, orig_pte);
  947. }
  948. if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
  949. munlock_vma_page(page);
  950. if (!PageMlocked(kpage)) {
  951. unlock_page(page);
  952. lock_page(kpage);
  953. mlock_vma_page(kpage);
  954. page = kpage; /* for final unlock */
  955. }
  956. }
  957. unlock_page(page);
  958. out:
  959. return err;
  960. }
  961. /*
  962. * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
  963. * but no new kernel page is allocated: kpage must already be a ksm page.
  964. *
  965. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  966. */
  967. static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
  968. struct page *page, struct page *kpage)
  969. {
  970. struct mm_struct *mm = rmap_item->mm;
  971. struct vm_area_struct *vma;
  972. int err = -EFAULT;
  973. down_read(&mm->mmap_sem);
  974. if (ksm_test_exit(mm))
  975. goto out;
  976. vma = find_vma(mm, rmap_item->address);
  977. if (!vma || vma->vm_start > rmap_item->address)
  978. goto out;
  979. err = try_to_merge_one_page(vma, page, kpage);
  980. if (err)
  981. goto out;
  982. /* Unstable nid is in union with stable anon_vma: remove first */
  983. remove_rmap_item_from_tree(rmap_item);
  984. /* Must get reference to anon_vma while still holding mmap_sem */
  985. rmap_item->anon_vma = vma->anon_vma;
  986. get_anon_vma(vma->anon_vma);
  987. out:
  988. up_read(&mm->mmap_sem);
  989. return err;
  990. }
  991. /*
  992. * try_to_merge_two_pages - take two identical pages and prepare them
  993. * to be merged into one page.
  994. *
  995. * This function returns the kpage if we successfully merged two identical
  996. * pages into one ksm page, NULL otherwise.
  997. *
  998. * Note that this function upgrades page to ksm page: if one of the pages
  999. * is already a ksm page, try_to_merge_with_ksm_page should be used.
  1000. */
  1001. static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
  1002. struct page *page,
  1003. struct rmap_item *tree_rmap_item,
  1004. struct page *tree_page)
  1005. {
  1006. int err;
  1007. err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
  1008. if (!err) {
  1009. err = try_to_merge_with_ksm_page(tree_rmap_item,
  1010. tree_page, page);
  1011. /*
  1012. * If that fails, we have a ksm page with only one pte
  1013. * pointing to it: so break it.
  1014. */
  1015. if (err)
  1016. break_cow(rmap_item);
  1017. }
  1018. return err ? NULL : page;
  1019. }
  1020. /*
  1021. * stable_tree_search - search for page inside the stable tree
  1022. *
  1023. * This function checks if there is a page inside the stable tree
  1024. * with identical content to the page that we are scanning right now.
  1025. *
  1026. * This function returns the stable tree node of identical content if found,
  1027. * NULL otherwise.
  1028. */
  1029. static struct page *stable_tree_search(struct page *page)
  1030. {
  1031. int nid;
  1032. struct rb_root *root;
  1033. struct rb_node **new;
  1034. struct rb_node *parent;
  1035. struct stable_node *stable_node;
  1036. struct stable_node *page_node;
  1037. page_node = page_stable_node(page);
  1038. if (page_node && page_node->head != &migrate_nodes) {
  1039. /* ksm page forked */
  1040. get_page(page);
  1041. return page;
  1042. }
  1043. nid = get_kpfn_nid(page_to_pfn(page));
  1044. root = root_stable_tree + nid;
  1045. again:
  1046. new = &root->rb_node;
  1047. parent = NULL;
  1048. while (*new) {
  1049. struct page *tree_page;
  1050. int ret;
  1051. cond_resched();
  1052. stable_node = rb_entry(*new, struct stable_node, node);
  1053. tree_page = get_ksm_page(stable_node, false);
  1054. if (!tree_page)
  1055. return NULL;
  1056. ret = memcmp_pages(page, tree_page);
  1057. put_page(tree_page);
  1058. parent = *new;
  1059. if (ret < 0)
  1060. new = &parent->rb_left;
  1061. else if (ret > 0)
  1062. new = &parent->rb_right;
  1063. else {
  1064. /*
  1065. * Lock and unlock the stable_node's page (which
  1066. * might already have been migrated) so that page
  1067. * migration is sure to notice its raised count.
  1068. * It would be more elegant to return stable_node
  1069. * than kpage, but that involves more changes.
  1070. */
  1071. tree_page = get_ksm_page(stable_node, true);
  1072. if (tree_page) {
  1073. unlock_page(tree_page);
  1074. if (get_kpfn_nid(stable_node->kpfn) !=
  1075. NUMA(stable_node->nid)) {
  1076. put_page(tree_page);
  1077. goto replace;
  1078. }
  1079. return tree_page;
  1080. }
  1081. /*
  1082. * There is now a place for page_node, but the tree may
  1083. * have been rebalanced, so re-evaluate parent and new.
  1084. */
  1085. if (page_node)
  1086. goto again;
  1087. return NULL;
  1088. }
  1089. }
  1090. if (!page_node)
  1091. return NULL;
  1092. list_del(&page_node->list);
  1093. DO_NUMA(page_node->nid = nid);
  1094. rb_link_node(&page_node->node, parent, new);
  1095. rb_insert_color(&page_node->node, root);
  1096. get_page(page);
  1097. return page;
  1098. replace:
  1099. if (page_node) {
  1100. list_del(&page_node->list);
  1101. DO_NUMA(page_node->nid = nid);
  1102. rb_replace_node(&stable_node->node, &page_node->node, root);
  1103. get_page(page);
  1104. } else {
  1105. rb_erase(&stable_node->node, root);
  1106. page = NULL;
  1107. }
  1108. stable_node->head = &migrate_nodes;
  1109. list_add(&stable_node->list, stable_node->head);
  1110. return page;
  1111. }
  1112. /*
  1113. * stable_tree_insert - insert stable tree node pointing to new ksm page
  1114. * into the stable tree.
  1115. *
  1116. * This function returns the stable tree node just allocated on success,
  1117. * NULL otherwise.
  1118. */
  1119. static struct stable_node *stable_tree_insert(struct page *kpage)
  1120. {
  1121. int nid;
  1122. unsigned long kpfn;
  1123. struct rb_root *root;
  1124. struct rb_node **new;
  1125. struct rb_node *parent = NULL;
  1126. struct stable_node *stable_node;
  1127. kpfn = page_to_pfn(kpage);
  1128. nid = get_kpfn_nid(kpfn);
  1129. root = root_stable_tree + nid;
  1130. new = &root->rb_node;
  1131. while (*new) {
  1132. struct page *tree_page;
  1133. int ret;
  1134. cond_resched();
  1135. stable_node = rb_entry(*new, struct stable_node, node);
  1136. tree_page = get_ksm_page(stable_node, false);
  1137. if (!tree_page)
  1138. return NULL;
  1139. ret = memcmp_pages(kpage, tree_page);
  1140. put_page(tree_page);
  1141. parent = *new;
  1142. if (ret < 0)
  1143. new = &parent->rb_left;
  1144. else if (ret > 0)
  1145. new = &parent->rb_right;
  1146. else {
  1147. /*
  1148. * It is not a bug that stable_tree_search() didn't
  1149. * find this node: because at that time our page was
  1150. * not yet write-protected, so may have changed since.
  1151. */
  1152. return NULL;
  1153. }
  1154. }
  1155. stable_node = alloc_stable_node();
  1156. if (!stable_node)
  1157. return NULL;
  1158. INIT_HLIST_HEAD(&stable_node->hlist);
  1159. stable_node->kpfn = kpfn;
  1160. set_page_stable_node(kpage, stable_node);
  1161. DO_NUMA(stable_node->nid = nid);
  1162. rb_link_node(&stable_node->node, parent, new);
  1163. rb_insert_color(&stable_node->node, root);
  1164. return stable_node;
  1165. }
  1166. /*
  1167. * unstable_tree_search_insert - search for identical page,
  1168. * else insert rmap_item into the unstable tree.
  1169. *
  1170. * This function searches for a page in the unstable tree identical to the
  1171. * page currently being scanned; and if no identical page is found in the
  1172. * tree, we insert rmap_item as a new object into the unstable tree.
  1173. *
  1174. * This function returns pointer to rmap_item found to be identical
  1175. * to the currently scanned page, NULL otherwise.
  1176. *
  1177. * This function does both searching and inserting, because they share
  1178. * the same walking algorithm in an rbtree.
  1179. */
  1180. static
  1181. struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
  1182. struct page *page,
  1183. struct page **tree_pagep)
  1184. {
  1185. struct rb_node **new;
  1186. struct rb_root *root;
  1187. struct rb_node *parent = NULL;
  1188. int nid;
  1189. nid = get_kpfn_nid(page_to_pfn(page));
  1190. root = root_unstable_tree + nid;
  1191. new = &root->rb_node;
  1192. while (*new) {
  1193. struct rmap_item *tree_rmap_item;
  1194. struct page *tree_page;
  1195. int ret;
  1196. cond_resched();
  1197. tree_rmap_item = rb_entry(*new, struct rmap_item, node);
  1198. tree_page = get_mergeable_page(tree_rmap_item);
  1199. if (IS_ERR_OR_NULL(tree_page))
  1200. return NULL;
  1201. /*
  1202. * Don't substitute a ksm page for a forked page.
  1203. */
  1204. if (page == tree_page) {
  1205. put_page(tree_page);
  1206. return NULL;
  1207. }
  1208. ret = memcmp_pages(page, tree_page);
  1209. parent = *new;
  1210. if (ret < 0) {
  1211. put_page(tree_page);
  1212. new = &parent->rb_left;
  1213. } else if (ret > 0) {
  1214. put_page(tree_page);
  1215. new = &parent->rb_right;
  1216. } else if (!ksm_merge_across_nodes &&
  1217. page_to_nid(tree_page) != nid) {
  1218. /*
  1219. * If tree_page has been migrated to another NUMA node,
  1220. * it will be flushed out and put in the right unstable
  1221. * tree next time: only merge with it when across_nodes.
  1222. */
  1223. put_page(tree_page);
  1224. return NULL;
  1225. } else {
  1226. *tree_pagep = tree_page;
  1227. return tree_rmap_item;
  1228. }
  1229. }
  1230. rmap_item->address |= UNSTABLE_FLAG;
  1231. rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
  1232. DO_NUMA(rmap_item->nid = nid);
  1233. rb_link_node(&rmap_item->node, parent, new);
  1234. rb_insert_color(&rmap_item->node, root);
  1235. ksm_pages_unshared++;
  1236. return NULL;
  1237. }
  1238. /*
  1239. * stable_tree_append - add another rmap_item to the linked list of
  1240. * rmap_items hanging off a given node of the stable tree, all sharing
  1241. * the same ksm page.
  1242. */
  1243. static void stable_tree_append(struct rmap_item *rmap_item,
  1244. struct stable_node *stable_node)
  1245. {
  1246. rmap_item->head = stable_node;
  1247. rmap_item->address |= STABLE_FLAG;
  1248. hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
  1249. if (rmap_item->hlist.next)
  1250. ksm_pages_sharing++;
  1251. else
  1252. ksm_pages_shared++;
  1253. }
  1254. /*
  1255. * cmp_and_merge_page - first see if page can be merged into the stable tree;
  1256. * if not, compare checksum to previous and if it's the same, see if page can
  1257. * be inserted into the unstable tree, or merged with a page already there and
  1258. * both transferred to the stable tree.
  1259. *
  1260. * @page: the page that we are searching identical page to.
  1261. * @rmap_item: the reverse mapping into the virtual address of this page
  1262. */
  1263. static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
  1264. {
  1265. struct rmap_item *tree_rmap_item;
  1266. struct page *tree_page = NULL;
  1267. struct stable_node *stable_node;
  1268. struct page *kpage;
  1269. unsigned int checksum;
  1270. int err;
  1271. stable_node = page_stable_node(page);
  1272. if (stable_node) {
  1273. if (stable_node->head != &migrate_nodes &&
  1274. get_kpfn_nid(stable_node->kpfn) != NUMA(stable_node->nid)) {
  1275. rb_erase(&stable_node->node,
  1276. root_stable_tree + NUMA(stable_node->nid));
  1277. stable_node->head = &migrate_nodes;
  1278. list_add(&stable_node->list, stable_node->head);
  1279. }
  1280. if (stable_node->head != &migrate_nodes &&
  1281. rmap_item->head == stable_node)
  1282. return;
  1283. }
  1284. /* We first start with searching the page inside the stable tree */
  1285. kpage = stable_tree_search(page);
  1286. if (kpage == page && rmap_item->head == stable_node) {
  1287. put_page(kpage);
  1288. return;
  1289. }
  1290. remove_rmap_item_from_tree(rmap_item);
  1291. if (kpage) {
  1292. err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
  1293. if (!err) {
  1294. /*
  1295. * The page was successfully merged:
  1296. * add its rmap_item to the stable tree.
  1297. */
  1298. lock_page(kpage);
  1299. stable_tree_append(rmap_item, page_stable_node(kpage));
  1300. unlock_page(kpage);
  1301. }
  1302. put_page(kpage);
  1303. return;
  1304. }
  1305. /*
  1306. * If the hash value of the page has changed from the last time
  1307. * we calculated it, this page is changing frequently: therefore we
  1308. * don't want to insert it in the unstable tree, and we don't want
  1309. * to waste our time searching for something identical to it there.
  1310. */
  1311. checksum = calc_checksum(page);
  1312. if (rmap_item->oldchecksum != checksum) {
  1313. rmap_item->oldchecksum = checksum;
  1314. return;
  1315. }
  1316. tree_rmap_item =
  1317. unstable_tree_search_insert(rmap_item, page, &tree_page);
  1318. if (tree_rmap_item) {
  1319. kpage = try_to_merge_two_pages(rmap_item, page,
  1320. tree_rmap_item, tree_page);
  1321. put_page(tree_page);
  1322. if (kpage) {
  1323. /*
  1324. * The pages were successfully merged: insert new
  1325. * node in the stable tree and add both rmap_items.
  1326. */
  1327. lock_page(kpage);
  1328. stable_node = stable_tree_insert(kpage);
  1329. if (stable_node) {
  1330. stable_tree_append(tree_rmap_item, stable_node);
  1331. stable_tree_append(rmap_item, stable_node);
  1332. }
  1333. unlock_page(kpage);
  1334. /*
  1335. * If we fail to insert the page into the stable tree,
  1336. * we will have 2 virtual addresses that are pointing
  1337. * to a ksm page left outside the stable tree,
  1338. * in which case we need to break_cow on both.
  1339. */
  1340. if (!stable_node) {
  1341. break_cow(tree_rmap_item);
  1342. break_cow(rmap_item);
  1343. }
  1344. }
  1345. }
  1346. }
  1347. static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
  1348. struct rmap_item **rmap_list,
  1349. unsigned long addr)
  1350. {
  1351. struct rmap_item *rmap_item;
  1352. while (*rmap_list) {
  1353. rmap_item = *rmap_list;
  1354. if ((rmap_item->address & PAGE_MASK) == addr)
  1355. return rmap_item;
  1356. if (rmap_item->address > addr)
  1357. break;
  1358. *rmap_list = rmap_item->rmap_list;
  1359. remove_rmap_item_from_tree(rmap_item);
  1360. free_rmap_item(rmap_item);
  1361. }
  1362. rmap_item = alloc_rmap_item();
  1363. if (rmap_item) {
  1364. /* It has already been zeroed */
  1365. rmap_item->mm = mm_slot->mm;
  1366. rmap_item->address = addr;
  1367. rmap_item->rmap_list = *rmap_list;
  1368. *rmap_list = rmap_item;
  1369. }
  1370. return rmap_item;
  1371. }
  1372. static struct rmap_item *scan_get_next_rmap_item(struct page **page)
  1373. {
  1374. struct mm_struct *mm;
  1375. struct mm_slot *slot;
  1376. struct vm_area_struct *vma;
  1377. struct rmap_item *rmap_item;
  1378. int nid;
  1379. if (list_empty(&ksm_mm_head.mm_list))
  1380. return NULL;
  1381. slot = ksm_scan.mm_slot;
  1382. if (slot == &ksm_mm_head) {
  1383. /*
  1384. * A number of pages can hang around indefinitely on per-cpu
  1385. * pagevecs, raised page count preventing write_protect_page
  1386. * from merging them. Though it doesn't really matter much,
  1387. * it is puzzling to see some stuck in pages_volatile until
  1388. * other activity jostles them out, and they also prevented
  1389. * LTP's KSM test from succeeding deterministically; so drain
  1390. * them here (here rather than on entry to ksm_do_scan(),
  1391. * so we don't IPI too often when pages_to_scan is set low).
  1392. */
  1393. lru_add_drain_all();
  1394. /*
  1395. * Whereas stale stable_nodes on the stable_tree itself
  1396. * get pruned in the regular course of stable_tree_search(),
  1397. * those moved out to the migrate_nodes list can accumulate:
  1398. * so prune them once before each full scan.
  1399. */
  1400. if (!ksm_merge_across_nodes) {
  1401. struct stable_node *stable_node;
  1402. struct list_head *this, *next;
  1403. struct page *page;
  1404. list_for_each_safe(this, next, &migrate_nodes) {
  1405. stable_node = list_entry(this,
  1406. struct stable_node, list);
  1407. page = get_ksm_page(stable_node, false);
  1408. if (page)
  1409. put_page(page);
  1410. cond_resched();
  1411. }
  1412. }
  1413. for (nid = 0; nid < ksm_nr_node_ids; nid++)
  1414. root_unstable_tree[nid] = RB_ROOT;
  1415. spin_lock(&ksm_mmlist_lock);
  1416. slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
  1417. ksm_scan.mm_slot = slot;
  1418. spin_unlock(&ksm_mmlist_lock);
  1419. /*
  1420. * Although we tested list_empty() above, a racing __ksm_exit
  1421. * of the last mm on the list may have removed it since then.
  1422. */
  1423. if (slot == &ksm_mm_head)
  1424. return NULL;
  1425. next_mm:
  1426. ksm_scan.address = 0;
  1427. ksm_scan.rmap_list = &slot->rmap_list;
  1428. }
  1429. mm = slot->mm;
  1430. down_read(&mm->mmap_sem);
  1431. if (ksm_test_exit(mm))
  1432. vma = NULL;
  1433. else
  1434. vma = find_vma(mm, ksm_scan.address);
  1435. for (; vma; vma = vma->vm_next) {
  1436. if (!(vma->vm_flags & VM_MERGEABLE))
  1437. continue;
  1438. if (ksm_scan.address < vma->vm_start)
  1439. ksm_scan.address = vma->vm_start;
  1440. if (!vma->anon_vma)
  1441. ksm_scan.address = vma->vm_end;
  1442. while (ksm_scan.address < vma->vm_end) {
  1443. if (ksm_test_exit(mm))
  1444. break;
  1445. *page = follow_page(vma, ksm_scan.address, FOLL_GET);
  1446. if (IS_ERR_OR_NULL(*page)) {
  1447. ksm_scan.address += PAGE_SIZE;
  1448. cond_resched();
  1449. continue;
  1450. }
  1451. if (PageAnon(*page) ||
  1452. page_trans_compound_anon(*page)) {
  1453. flush_anon_page(vma, *page, ksm_scan.address);
  1454. flush_dcache_page(*page);
  1455. rmap_item = get_next_rmap_item(slot,
  1456. ksm_scan.rmap_list, ksm_scan.address);
  1457. if (rmap_item) {
  1458. ksm_scan.rmap_list =
  1459. &rmap_item->rmap_list;
  1460. ksm_scan.address += PAGE_SIZE;
  1461. } else
  1462. put_page(*page);
  1463. up_read(&mm->mmap_sem);
  1464. return rmap_item;
  1465. }
  1466. put_page(*page);
  1467. ksm_scan.address += PAGE_SIZE;
  1468. cond_resched();
  1469. }
  1470. }
  1471. if (ksm_test_exit(mm)) {
  1472. ksm_scan.address = 0;
  1473. ksm_scan.rmap_list = &slot->rmap_list;
  1474. }
  1475. /*
  1476. * Nuke all the rmap_items that are above this current rmap:
  1477. * because there were no VM_MERGEABLE vmas with such addresses.
  1478. */
  1479. remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
  1480. spin_lock(&ksm_mmlist_lock);
  1481. ksm_scan.mm_slot = list_entry(slot->mm_list.next,
  1482. struct mm_slot, mm_list);
  1483. if (ksm_scan.address == 0) {
  1484. /*
  1485. * We've completed a full scan of all vmas, holding mmap_sem
  1486. * throughout, and found no VM_MERGEABLE: so do the same as
  1487. * __ksm_exit does to remove this mm from all our lists now.
  1488. * This applies either when cleaning up after __ksm_exit
  1489. * (but beware: we can reach here even before __ksm_exit),
  1490. * or when all VM_MERGEABLE areas have been unmapped (and
  1491. * mmap_sem then protects against race with MADV_MERGEABLE).
  1492. */
  1493. hash_del(&slot->link);
  1494. list_del(&slot->mm_list);
  1495. spin_unlock(&ksm_mmlist_lock);
  1496. free_mm_slot(slot);
  1497. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  1498. up_read(&mm->mmap_sem);
  1499. mmdrop(mm);
  1500. } else {
  1501. spin_unlock(&ksm_mmlist_lock);
  1502. up_read(&mm->mmap_sem);
  1503. }
  1504. /* Repeat until we've completed scanning the whole list */
  1505. slot = ksm_scan.mm_slot;
  1506. if (slot != &ksm_mm_head)
  1507. goto next_mm;
  1508. ksm_scan.seqnr++;
  1509. return NULL;
  1510. }
  1511. /**
  1512. * ksm_do_scan - the ksm scanner main worker function.
  1513. * @scan_npages - number of pages we want to scan before we return.
  1514. */
  1515. static void ksm_do_scan(unsigned int scan_npages)
  1516. {
  1517. struct rmap_item *rmap_item;
  1518. struct page *uninitialized_var(page);
  1519. while (scan_npages-- && likely(!freezing(current))) {
  1520. cond_resched();
  1521. rmap_item = scan_get_next_rmap_item(&page);
  1522. if (!rmap_item)
  1523. return;
  1524. cmp_and_merge_page(page, rmap_item);
  1525. put_page(page);
  1526. }
  1527. }
  1528. static int ksmd_should_run(void)
  1529. {
  1530. return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
  1531. }
  1532. static int ksm_scan_thread(void *nothing)
  1533. {
  1534. set_freezable();
  1535. set_user_nice(current, 5);
  1536. while (!kthread_should_stop()) {
  1537. mutex_lock(&ksm_thread_mutex);
  1538. wait_while_offlining();
  1539. if (ksmd_should_run())
  1540. ksm_do_scan(ksm_thread_pages_to_scan);
  1541. mutex_unlock(&ksm_thread_mutex);
  1542. try_to_freeze();
  1543. if (ksmd_should_run()) {
  1544. schedule_timeout_interruptible(
  1545. msecs_to_jiffies(ksm_thread_sleep_millisecs));
  1546. } else {
  1547. wait_event_freezable(ksm_thread_wait,
  1548. ksmd_should_run() || kthread_should_stop());
  1549. }
  1550. }
  1551. return 0;
  1552. }
  1553. int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
  1554. unsigned long end, int advice, unsigned long *vm_flags)
  1555. {
  1556. struct mm_struct *mm = vma->vm_mm;
  1557. int err;
  1558. switch (advice) {
  1559. case MADV_MERGEABLE:
  1560. /*
  1561. * Be somewhat over-protective for now!
  1562. */
  1563. if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
  1564. VM_PFNMAP | VM_IO | VM_DONTEXPAND |
  1565. VM_HUGETLB | VM_MIXEDMAP))
  1566. return 0; /* just ignore the advice */
  1567. #ifdef VM_SAO
  1568. if (*vm_flags & VM_SAO)
  1569. return 0;
  1570. #endif
  1571. if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
  1572. err = __ksm_enter(mm);
  1573. if (err)
  1574. return err;
  1575. }
  1576. *vm_flags |= VM_MERGEABLE;
  1577. break;
  1578. case MADV_UNMERGEABLE:
  1579. if (!(*vm_flags & VM_MERGEABLE))
  1580. return 0; /* just ignore the advice */
  1581. if (vma->anon_vma) {
  1582. err = unmerge_ksm_pages(vma, start, end);
  1583. if (err)
  1584. return err;
  1585. }
  1586. *vm_flags &= ~VM_MERGEABLE;
  1587. break;
  1588. }
  1589. return 0;
  1590. }
  1591. int __ksm_enter(struct mm_struct *mm)
  1592. {
  1593. struct mm_slot *mm_slot;
  1594. int needs_wakeup;
  1595. mm_slot = alloc_mm_slot();
  1596. if (!mm_slot)
  1597. return -ENOMEM;
  1598. /* Check ksm_run too? Would need tighter locking */
  1599. needs_wakeup = list_empty(&ksm_mm_head.mm_list);
  1600. spin_lock(&ksm_mmlist_lock);
  1601. insert_to_mm_slots_hash(mm, mm_slot);
  1602. /*
  1603. * When KSM_RUN_MERGE (or KSM_RUN_STOP),
  1604. * insert just behind the scanning cursor, to let the area settle
  1605. * down a little; when fork is followed by immediate exec, we don't
  1606. * want ksmd to waste time setting up and tearing down an rmap_list.
  1607. *
  1608. * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
  1609. * scanning cursor, otherwise KSM pages in newly forked mms will be
  1610. * missed: then we might as well insert at the end of the list.
  1611. */
  1612. if (ksm_run & KSM_RUN_UNMERGE)
  1613. list_add_tail(&mm_slot->mm_list, &ksm_mm_head.mm_list);
  1614. else
  1615. list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
  1616. spin_unlock(&ksm_mmlist_lock);
  1617. set_bit(MMF_VM_MERGEABLE, &mm->flags);
  1618. atomic_inc(&mm->mm_count);
  1619. if (needs_wakeup)
  1620. wake_up_interruptible(&ksm_thread_wait);
  1621. return 0;
  1622. }
  1623. void __ksm_exit(struct mm_struct *mm)
  1624. {
  1625. struct mm_slot *mm_slot;
  1626. int easy_to_free = 0;
  1627. /*
  1628. * This process is exiting: if it's straightforward (as is the
  1629. * case when ksmd was never running), free mm_slot immediately.
  1630. * But if it's at the cursor or has rmap_items linked to it, use
  1631. * mmap_sem to synchronize with any break_cows before pagetables
  1632. * are freed, and leave the mm_slot on the list for ksmd to free.
  1633. * Beware: ksm may already have noticed it exiting and freed the slot.
  1634. */
  1635. spin_lock(&ksm_mmlist_lock);
  1636. mm_slot = get_mm_slot(mm);
  1637. if (mm_slot && ksm_scan.mm_slot != mm_slot) {
  1638. if (!mm_slot->rmap_list) {
  1639. hash_del(&mm_slot->link);
  1640. list_del(&mm_slot->mm_list);
  1641. easy_to_free = 1;
  1642. } else {
  1643. list_move(&mm_slot->mm_list,
  1644. &ksm_scan.mm_slot->mm_list);
  1645. }
  1646. }
  1647. spin_unlock(&ksm_mmlist_lock);
  1648. if (easy_to_free) {
  1649. free_mm_slot(mm_slot);
  1650. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  1651. mmdrop(mm);
  1652. } else if (mm_slot) {
  1653. down_write(&mm->mmap_sem);
  1654. up_write(&mm->mmap_sem);
  1655. }
  1656. }
  1657. struct page *ksm_might_need_to_copy(struct page *page,
  1658. struct vm_area_struct *vma, unsigned long address)
  1659. {
  1660. struct anon_vma *anon_vma = page_anon_vma(page);
  1661. struct page *new_page;
  1662. if (PageKsm(page)) {
  1663. if (page_stable_node(page) &&
  1664. !(ksm_run & KSM_RUN_UNMERGE))
  1665. return page; /* no need to copy it */
  1666. } else if (!anon_vma) {
  1667. return page; /* no need to copy it */
  1668. } else if (anon_vma->root == vma->anon_vma->root &&
  1669. page->index == linear_page_index(vma, address)) {
  1670. return page; /* still no need to copy it */
  1671. }
  1672. if (!PageUptodate(page))
  1673. return page; /* let do_swap_page report the error */
  1674. new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
  1675. if (new_page) {
  1676. copy_user_highpage(new_page, page, address, vma);
  1677. SetPageDirty(new_page);
  1678. __SetPageUptodate(new_page);
  1679. __set_page_locked(new_page);
  1680. }
  1681. return new_page;
  1682. }
  1683. int rmap_walk_ksm(struct page *page, struct rmap_walk_control *rwc)
  1684. {
  1685. struct stable_node *stable_node;
  1686. struct rmap_item *rmap_item;
  1687. int ret = SWAP_AGAIN;
  1688. int search_new_forks = 0;
  1689. VM_BUG_ON_PAGE(!PageKsm(page), page);
  1690. /*
  1691. * Rely on the page lock to protect against concurrent modifications
  1692. * to that page's node of the stable tree.
  1693. */
  1694. VM_BUG_ON_PAGE(!PageLocked(page), page);
  1695. stable_node = page_stable_node(page);
  1696. if (!stable_node)
  1697. return ret;
  1698. again:
  1699. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  1700. struct anon_vma *anon_vma = rmap_item->anon_vma;
  1701. struct anon_vma_chain *vmac;
  1702. struct vm_area_struct *vma;
  1703. anon_vma_lock_read(anon_vma);
  1704. anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
  1705. 0, ULONG_MAX) {
  1706. vma = vmac->vma;
  1707. if (rmap_item->address < vma->vm_start ||
  1708. rmap_item->address >= vma->vm_end)
  1709. continue;
  1710. /*
  1711. * Initially we examine only the vma which covers this
  1712. * rmap_item; but later, if there is still work to do,
  1713. * we examine covering vmas in other mms: in case they
  1714. * were forked from the original since ksmd passed.
  1715. */
  1716. if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
  1717. continue;
  1718. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  1719. continue;
  1720. ret = rwc->rmap_one(page, vma,
  1721. rmap_item->address, rwc->arg);
  1722. if (ret != SWAP_AGAIN) {
  1723. anon_vma_unlock_read(anon_vma);
  1724. goto out;
  1725. }
  1726. if (rwc->done && rwc->done(page)) {
  1727. anon_vma_unlock_read(anon_vma);
  1728. goto out;
  1729. }
  1730. }
  1731. anon_vma_unlock_read(anon_vma);
  1732. }
  1733. if (!search_new_forks++)
  1734. goto again;
  1735. out:
  1736. return ret;
  1737. }
  1738. #ifdef CONFIG_MIGRATION
  1739. void ksm_migrate_page(struct page *newpage, struct page *oldpage)
  1740. {
  1741. struct stable_node *stable_node;
  1742. VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
  1743. VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
  1744. VM_BUG_ON_PAGE(newpage->mapping != oldpage->mapping, newpage);
  1745. stable_node = page_stable_node(newpage);
  1746. if (stable_node) {
  1747. VM_BUG_ON_PAGE(stable_node->kpfn != page_to_pfn(oldpage), oldpage);
  1748. stable_node->kpfn = page_to_pfn(newpage);
  1749. /*
  1750. * newpage->mapping was set in advance; now we need smp_wmb()
  1751. * to make sure that the new stable_node->kpfn is visible
  1752. * to get_ksm_page() before it can see that oldpage->mapping
  1753. * has gone stale (or that PageSwapCache has been cleared).
  1754. */
  1755. smp_wmb();
  1756. set_page_stable_node(oldpage, NULL);
  1757. }
  1758. }
  1759. #endif /* CONFIG_MIGRATION */
  1760. #ifdef CONFIG_MEMORY_HOTREMOVE
  1761. static void wait_while_offlining(void)
  1762. {
  1763. while (ksm_run & KSM_RUN_OFFLINE) {
  1764. mutex_unlock(&ksm_thread_mutex);
  1765. wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
  1766. TASK_UNINTERRUPTIBLE);
  1767. mutex_lock(&ksm_thread_mutex);
  1768. }
  1769. }
  1770. static void ksm_check_stable_tree(unsigned long start_pfn,
  1771. unsigned long end_pfn)
  1772. {
  1773. struct stable_node *stable_node;
  1774. struct list_head *this, *next;
  1775. struct rb_node *node;
  1776. int nid;
  1777. for (nid = 0; nid < ksm_nr_node_ids; nid++) {
  1778. node = rb_first(root_stable_tree + nid);
  1779. while (node) {
  1780. stable_node = rb_entry(node, struct stable_node, node);
  1781. if (stable_node->kpfn >= start_pfn &&
  1782. stable_node->kpfn < end_pfn) {
  1783. /*
  1784. * Don't get_ksm_page, page has already gone:
  1785. * which is why we keep kpfn instead of page*
  1786. */
  1787. remove_node_from_stable_tree(stable_node);
  1788. node = rb_first(root_stable_tree + nid);
  1789. } else
  1790. node = rb_next(node);
  1791. cond_resched();
  1792. }
  1793. }
  1794. list_for_each_safe(this, next, &migrate_nodes) {
  1795. stable_node = list_entry(this, struct stable_node, list);
  1796. if (stable_node->kpfn >= start_pfn &&
  1797. stable_node->kpfn < end_pfn)
  1798. remove_node_from_stable_tree(stable_node);
  1799. cond_resched();
  1800. }
  1801. }
  1802. static int ksm_memory_callback(struct notifier_block *self,
  1803. unsigned long action, void *arg)
  1804. {
  1805. struct memory_notify *mn = arg;
  1806. switch (action) {
  1807. case MEM_GOING_OFFLINE:
  1808. /*
  1809. * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
  1810. * and remove_all_stable_nodes() while memory is going offline:
  1811. * it is unsafe for them to touch the stable tree at this time.
  1812. * But unmerge_ksm_pages(), rmap lookups and other entry points
  1813. * which do not need the ksm_thread_mutex are all safe.
  1814. */
  1815. mutex_lock(&ksm_thread_mutex);
  1816. ksm_run |= KSM_RUN_OFFLINE;
  1817. mutex_unlock(&ksm_thread_mutex);
  1818. break;
  1819. case MEM_OFFLINE:
  1820. /*
  1821. * Most of the work is done by page migration; but there might
  1822. * be a few stable_nodes left over, still pointing to struct
  1823. * pages which have been offlined: prune those from the tree,
  1824. * otherwise get_ksm_page() might later try to access a
  1825. * non-existent struct page.
  1826. */
  1827. ksm_check_stable_tree(mn->start_pfn,
  1828. mn->start_pfn + mn->nr_pages);
  1829. /* fallthrough */
  1830. case MEM_CANCEL_OFFLINE:
  1831. mutex_lock(&ksm_thread_mutex);
  1832. ksm_run &= ~KSM_RUN_OFFLINE;
  1833. mutex_unlock(&ksm_thread_mutex);
  1834. smp_mb(); /* wake_up_bit advises this */
  1835. wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
  1836. break;
  1837. }
  1838. return NOTIFY_OK;
  1839. }
  1840. #else
  1841. static void wait_while_offlining(void)
  1842. {
  1843. }
  1844. #endif /* CONFIG_MEMORY_HOTREMOVE */
  1845. #ifdef CONFIG_SYSFS
  1846. /*
  1847. * This all compiles without CONFIG_SYSFS, but is a waste of space.
  1848. */
  1849. #define KSM_ATTR_RO(_name) \
  1850. static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
  1851. #define KSM_ATTR(_name) \
  1852. static struct kobj_attribute _name##_attr = \
  1853. __ATTR(_name, 0644, _name##_show, _name##_store)
  1854. static ssize_t sleep_millisecs_show(struct kobject *kobj,
  1855. struct kobj_attribute *attr, char *buf)
  1856. {
  1857. return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
  1858. }
  1859. static ssize_t sleep_millisecs_store(struct kobject *kobj,
  1860. struct kobj_attribute *attr,
  1861. const char *buf, size_t count)
  1862. {
  1863. unsigned long msecs;
  1864. int err;
  1865. err = kstrtoul(buf, 10, &msecs);
  1866. if (err || msecs > UINT_MAX)
  1867. return -EINVAL;
  1868. ksm_thread_sleep_millisecs = msecs;
  1869. return count;
  1870. }
  1871. KSM_ATTR(sleep_millisecs);
  1872. static ssize_t pages_to_scan_show(struct kobject *kobj,
  1873. struct kobj_attribute *attr, char *buf)
  1874. {
  1875. return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
  1876. }
  1877. static ssize_t pages_to_scan_store(struct kobject *kobj,
  1878. struct kobj_attribute *attr,
  1879. const char *buf, size_t count)
  1880. {
  1881. int err;
  1882. unsigned long nr_pages;
  1883. err = kstrtoul(buf, 10, &nr_pages);
  1884. if (err || nr_pages > UINT_MAX)
  1885. return -EINVAL;
  1886. ksm_thread_pages_to_scan = nr_pages;
  1887. return count;
  1888. }
  1889. KSM_ATTR(pages_to_scan);
  1890. static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
  1891. char *buf)
  1892. {
  1893. return sprintf(buf, "%lu\n", ksm_run);
  1894. }
  1895. static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
  1896. const char *buf, size_t count)
  1897. {
  1898. int err;
  1899. unsigned long flags;
  1900. err = kstrtoul(buf, 10, &flags);
  1901. if (err || flags > UINT_MAX)
  1902. return -EINVAL;
  1903. if (flags > KSM_RUN_UNMERGE)
  1904. return -EINVAL;
  1905. /*
  1906. * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
  1907. * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
  1908. * breaking COW to free the pages_shared (but leaves mm_slots
  1909. * on the list for when ksmd may be set running again).
  1910. */
  1911. mutex_lock(&ksm_thread_mutex);
  1912. wait_while_offlining();
  1913. if (ksm_run != flags) {
  1914. ksm_run = flags;
  1915. if (flags & KSM_RUN_UNMERGE) {
  1916. set_current_oom_origin();
  1917. err = unmerge_and_remove_all_rmap_items();
  1918. clear_current_oom_origin();
  1919. if (err) {
  1920. ksm_run = KSM_RUN_STOP;
  1921. count = err;
  1922. }
  1923. }
  1924. }
  1925. mutex_unlock(&ksm_thread_mutex);
  1926. if (flags & KSM_RUN_MERGE)
  1927. wake_up_interruptible(&ksm_thread_wait);
  1928. return count;
  1929. }
  1930. KSM_ATTR(run);
  1931. #ifdef CONFIG_NUMA
  1932. static ssize_t merge_across_nodes_show(struct kobject *kobj,
  1933. struct kobj_attribute *attr, char *buf)
  1934. {
  1935. return sprintf(buf, "%u\n", ksm_merge_across_nodes);
  1936. }
  1937. static ssize_t merge_across_nodes_store(struct kobject *kobj,
  1938. struct kobj_attribute *attr,
  1939. const char *buf, size_t count)
  1940. {
  1941. int err;
  1942. unsigned long knob;
  1943. err = kstrtoul(buf, 10, &knob);
  1944. if (err)
  1945. return err;
  1946. if (knob > 1)
  1947. return -EINVAL;
  1948. mutex_lock(&ksm_thread_mutex);
  1949. wait_while_offlining();
  1950. if (ksm_merge_across_nodes != knob) {
  1951. if (ksm_pages_shared || remove_all_stable_nodes())
  1952. err = -EBUSY;
  1953. else if (root_stable_tree == one_stable_tree) {
  1954. struct rb_root *buf;
  1955. /*
  1956. * This is the first time that we switch away from the
  1957. * default of merging across nodes: must now allocate
  1958. * a buffer to hold as many roots as may be needed.
  1959. * Allocate stable and unstable together:
  1960. * MAXSMP NODES_SHIFT 10 will use 16kB.
  1961. */
  1962. buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf),
  1963. GFP_KERNEL);
  1964. /* Let us assume that RB_ROOT is NULL is zero */
  1965. if (!buf)
  1966. err = -ENOMEM;
  1967. else {
  1968. root_stable_tree = buf;
  1969. root_unstable_tree = buf + nr_node_ids;
  1970. /* Stable tree is empty but not the unstable */
  1971. root_unstable_tree[0] = one_unstable_tree[0];
  1972. }
  1973. }
  1974. if (!err) {
  1975. ksm_merge_across_nodes = knob;
  1976. ksm_nr_node_ids = knob ? 1 : nr_node_ids;
  1977. }
  1978. }
  1979. mutex_unlock(&ksm_thread_mutex);
  1980. return err ? err : count;
  1981. }
  1982. KSM_ATTR(merge_across_nodes);
  1983. #endif
  1984. static ssize_t pages_shared_show(struct kobject *kobj,
  1985. struct kobj_attribute *attr, char *buf)
  1986. {
  1987. return sprintf(buf, "%lu\n", ksm_pages_shared);
  1988. }
  1989. KSM_ATTR_RO(pages_shared);
  1990. static ssize_t pages_sharing_show(struct kobject *kobj,
  1991. struct kobj_attribute *attr, char *buf)
  1992. {
  1993. return sprintf(buf, "%lu\n", ksm_pages_sharing);
  1994. }
  1995. KSM_ATTR_RO(pages_sharing);
  1996. static ssize_t pages_unshared_show(struct kobject *kobj,
  1997. struct kobj_attribute *attr, char *buf)
  1998. {
  1999. return sprintf(buf, "%lu\n", ksm_pages_unshared);
  2000. }
  2001. KSM_ATTR_RO(pages_unshared);
  2002. static ssize_t pages_volatile_show(struct kobject *kobj,
  2003. struct kobj_attribute *attr, char *buf)
  2004. {
  2005. long ksm_pages_volatile;
  2006. ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
  2007. - ksm_pages_sharing - ksm_pages_unshared;
  2008. /*
  2009. * It was not worth any locking to calculate that statistic,
  2010. * but it might therefore sometimes be negative: conceal that.
  2011. */
  2012. if (ksm_pages_volatile < 0)
  2013. ksm_pages_volatile = 0;
  2014. return sprintf(buf, "%ld\n", ksm_pages_volatile);
  2015. }
  2016. KSM_ATTR_RO(pages_volatile);
  2017. static ssize_t full_scans_show(struct kobject *kobj,
  2018. struct kobj_attribute *attr, char *buf)
  2019. {
  2020. return sprintf(buf, "%lu\n", ksm_scan.seqnr);
  2021. }
  2022. KSM_ATTR_RO(full_scans);
  2023. static struct attribute *ksm_attrs[] = {
  2024. &sleep_millisecs_attr.attr,
  2025. &pages_to_scan_attr.attr,
  2026. &run_attr.attr,
  2027. &pages_shared_attr.attr,
  2028. &pages_sharing_attr.attr,
  2029. &pages_unshared_attr.attr,
  2030. &pages_volatile_attr.attr,
  2031. &full_scans_attr.attr,
  2032. #ifdef CONFIG_NUMA
  2033. &merge_across_nodes_attr.attr,
  2034. #endif
  2035. NULL,
  2036. };
  2037. static struct attribute_group ksm_attr_group = {
  2038. .attrs = ksm_attrs,
  2039. .name = "ksm",
  2040. };
  2041. #endif /* CONFIG_SYSFS */
  2042. static int __init ksm_init(void)
  2043. {
  2044. struct task_struct *ksm_thread;
  2045. int err;
  2046. err = ksm_slab_init();
  2047. if (err)
  2048. goto out;
  2049. ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
  2050. if (IS_ERR(ksm_thread)) {
  2051. pr_err("ksm: creating kthread failed\n");
  2052. err = PTR_ERR(ksm_thread);
  2053. goto out_free;
  2054. }
  2055. #ifdef CONFIG_SYSFS
  2056. err = sysfs_create_group(mm_kobj, &ksm_attr_group);
  2057. if (err) {
  2058. pr_err("ksm: register sysfs failed\n");
  2059. kthread_stop(ksm_thread);
  2060. goto out_free;
  2061. }
  2062. #else
  2063. ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
  2064. #endif /* CONFIG_SYSFS */
  2065. #ifdef CONFIG_MEMORY_HOTREMOVE
  2066. /* There is no significance to this priority 100 */
  2067. hotplug_memory_notifier(ksm_memory_callback, 100);
  2068. #endif
  2069. return 0;
  2070. out_free:
  2071. ksm_slab_free();
  2072. out:
  2073. return err;
  2074. }
  2075. subsys_initcall(ksm_init);