ksm.c 85 KB

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