ksm.c 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Memory merging support.
  4. *
  5. * This code enables dynamic sharing of identical pages found in different
  6. * memory areas, even if they are not shared by fork()
  7. *
  8. * Copyright (C) 2008-2009 Red Hat, Inc.
  9. * Authors:
  10. * Izik Eidus
  11. * Andrea Arcangeli
  12. * Chris Wright
  13. * Hugh Dickins
  14. */
  15. #include <linux/errno.h>
  16. #include <linux/mm.h>
  17. #include <linux/mm_inline.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/cputime.h>
  23. #include <linux/rwsem.h>
  24. #include <linux/pagemap.h>
  25. #include <linux/rmap.h>
  26. #include <linux/spinlock.h>
  27. #include <linux/xxhash.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 <linux/pagewalk.h>
  42. #include <asm/tlbflush.h>
  43. #include "internal.h"
  44. #include "mm_slot.h"
  45. #define CREATE_TRACE_POINTS
  46. #include <trace/events/ksm.h>
  47. #ifdef CONFIG_NUMA
  48. #define NUMA(x) (x)
  49. #define DO_NUMA(x) do { (x); } while (0)
  50. #else
  51. #define NUMA(x) (0)
  52. #define DO_NUMA(x) do { } while (0)
  53. #endif
  54. typedef u8 rmap_age_t;
  55. /**
  56. * DOC: Overview
  57. *
  58. * A few notes about the KSM scanning process,
  59. * to make it easier to understand the data structures below:
  60. *
  61. * In order to reduce excessive scanning, KSM sorts the memory pages by their
  62. * contents into a data structure that holds pointers to the pages' locations.
  63. *
  64. * Since the contents of the pages may change at any moment, KSM cannot just
  65. * insert the pages into a normal sorted tree and expect it to find anything.
  66. * Therefore KSM uses two data structures - the stable and the unstable tree.
  67. *
  68. * The stable tree holds pointers to all the merged pages (ksm pages), sorted
  69. * by their contents. Because each such page is write-protected, searching on
  70. * this tree is fully assured to be working (except when pages are unmapped),
  71. * and therefore this tree is called the stable tree.
  72. *
  73. * The stable tree node includes information required for reverse
  74. * mapping from a KSM page to virtual addresses that map this page.
  75. *
  76. * In order to avoid large latencies of the rmap walks on KSM pages,
  77. * KSM maintains two types of nodes in the stable tree:
  78. *
  79. * * the regular nodes that keep the reverse mapping structures in a
  80. * linked list
  81. * * the "chains" that link nodes ("dups") that represent the same
  82. * write protected memory content, but each "dup" corresponds to a
  83. * different KSM page copy of that content
  84. *
  85. * Internally, the regular nodes, "dups" and "chains" are represented
  86. * using the same struct ksm_stable_node structure.
  87. *
  88. * In addition to the stable tree, KSM uses a second data structure called the
  89. * unstable tree: this tree holds pointers to pages which have been found to
  90. * be "unchanged for a period of time". The unstable tree sorts these pages
  91. * by their contents, but since they are not write-protected, KSM cannot rely
  92. * upon the unstable tree to work correctly - the unstable tree is liable to
  93. * be corrupted as its contents are modified, and so it is called unstable.
  94. *
  95. * KSM solves this problem by several techniques:
  96. *
  97. * 1) The unstable tree is flushed every time KSM completes scanning all
  98. * memory areas, and then the tree is rebuilt again from the beginning.
  99. * 2) KSM will only insert into the unstable tree, pages whose hash value
  100. * has not changed since the previous scan of all memory areas.
  101. * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
  102. * colors of the nodes and not on their contents, assuring that even when
  103. * the tree gets "corrupted" it won't get out of balance, so scanning time
  104. * remains the same (also, searching and inserting nodes in an rbtree uses
  105. * the same algorithm, so we have no overhead when we flush and rebuild).
  106. * 4) KSM never flushes the stable tree, which means that even if it were to
  107. * take 10 attempts to find a page in the unstable tree, once it is found,
  108. * it is secured in the stable tree. (When we scan a new page, we first
  109. * compare it against the stable tree, and then against the unstable tree.)
  110. *
  111. * If the merge_across_nodes tunable is unset, then KSM maintains multiple
  112. * stable trees and multiple unstable trees: one of each for each NUMA node.
  113. */
  114. /**
  115. * struct ksm_mm_slot - ksm information per mm that is being scanned
  116. * @slot: hash lookup from mm to mm_slot
  117. * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
  118. */
  119. struct ksm_mm_slot {
  120. struct mm_slot slot;
  121. struct ksm_rmap_item *rmap_list;
  122. };
  123. /**
  124. * struct ksm_scan - cursor for scanning
  125. * @mm_slot: the current mm_slot we are scanning
  126. * @address: the next address inside that to be scanned
  127. * @rmap_list: link to the next rmap to be scanned in the rmap_list
  128. * @seqnr: count of completed full scans (needed when removing unstable node)
  129. *
  130. * There is only the one ksm_scan instance of this cursor structure.
  131. */
  132. struct ksm_scan {
  133. struct ksm_mm_slot *mm_slot;
  134. unsigned long address;
  135. struct ksm_rmap_item **rmap_list;
  136. unsigned long seqnr;
  137. };
  138. /**
  139. * struct ksm_stable_node - node of the stable rbtree
  140. * @node: rb node of this ksm page in the stable tree
  141. * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
  142. * @hlist_dup: linked into the stable_node->hlist with a stable_node chain
  143. * @list: linked into migrate_nodes, pending placement in the proper node tree
  144. * @hlist: hlist head of rmap_items using this ksm page
  145. * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
  146. * @chain_prune_time: time of the last full garbage collection
  147. * @rmap_hlist_len: number of rmap_item entries in hlist or STABLE_NODE_CHAIN
  148. * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
  149. */
  150. struct ksm_stable_node {
  151. union {
  152. struct rb_node node; /* when node of stable tree */
  153. struct { /* when listed for migration */
  154. struct list_head *head;
  155. struct {
  156. struct hlist_node hlist_dup;
  157. struct list_head list;
  158. };
  159. };
  160. };
  161. struct hlist_head hlist;
  162. union {
  163. unsigned long kpfn;
  164. unsigned long chain_prune_time;
  165. };
  166. /*
  167. * STABLE_NODE_CHAIN can be any negative number in
  168. * rmap_hlist_len negative range, but better not -1 to be able
  169. * to reliably detect underflows.
  170. */
  171. #define STABLE_NODE_CHAIN -1024
  172. int rmap_hlist_len;
  173. #ifdef CONFIG_NUMA
  174. int nid;
  175. #endif
  176. };
  177. /**
  178. * struct ksm_rmap_item - reverse mapping item for virtual addresses
  179. * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
  180. * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
  181. * @nid: NUMA node id of unstable tree in which linked (may not match page)
  182. * @mm: the memory structure this rmap_item is pointing into
  183. * @address: the virtual address this rmap_item tracks (+ flags in low bits)
  184. * @oldchecksum: previous checksum of the page at that virtual address
  185. * @node: rb node of this rmap_item in the unstable tree
  186. * @head: pointer to stable_node heading this list in the stable tree
  187. * @hlist: link into hlist of rmap_items hanging off that stable_node
  188. * @age: number of scan iterations since creation
  189. * @remaining_skips: how many scans to skip
  190. */
  191. struct ksm_rmap_item {
  192. struct ksm_rmap_item *rmap_list;
  193. union {
  194. struct anon_vma *anon_vma; /* when stable */
  195. #ifdef CONFIG_NUMA
  196. int nid; /* when node of unstable tree */
  197. #endif
  198. };
  199. struct mm_struct *mm;
  200. unsigned long address; /* + low bits used for flags below */
  201. unsigned int oldchecksum; /* when unstable */
  202. rmap_age_t age;
  203. rmap_age_t remaining_skips;
  204. union {
  205. struct rb_node node; /* when node of unstable tree */
  206. struct { /* when listed from stable tree */
  207. struct ksm_stable_node *head;
  208. struct hlist_node hlist;
  209. };
  210. };
  211. };
  212. #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
  213. #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
  214. #define STABLE_FLAG 0x200 /* is listed from the stable tree */
  215. /* The stable and unstable tree heads */
  216. static struct rb_root one_stable_tree[1] = { RB_ROOT };
  217. static struct rb_root one_unstable_tree[1] = { RB_ROOT };
  218. static struct rb_root *root_stable_tree = one_stable_tree;
  219. static struct rb_root *root_unstable_tree = one_unstable_tree;
  220. /* Recently migrated nodes of stable tree, pending proper placement */
  221. static LIST_HEAD(migrate_nodes);
  222. #define STABLE_NODE_DUP_HEAD ((struct list_head *)&migrate_nodes.prev)
  223. #define MM_SLOTS_HASH_BITS 10
  224. static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
  225. static struct ksm_mm_slot ksm_mm_head = {
  226. .slot.mm_node = LIST_HEAD_INIT(ksm_mm_head.slot.mm_node),
  227. };
  228. static struct ksm_scan ksm_scan = {
  229. .mm_slot = &ksm_mm_head,
  230. };
  231. static struct kmem_cache *rmap_item_cache;
  232. static struct kmem_cache *stable_node_cache;
  233. static struct kmem_cache *mm_slot_cache;
  234. /* Default number of pages to scan per batch */
  235. #define DEFAULT_PAGES_TO_SCAN 100
  236. /* The number of pages scanned */
  237. static unsigned long ksm_pages_scanned;
  238. /* The number of nodes in the stable tree */
  239. static unsigned long ksm_pages_shared;
  240. /* The number of page slots additionally sharing those nodes */
  241. static unsigned long ksm_pages_sharing;
  242. /* The number of nodes in the unstable tree */
  243. static unsigned long ksm_pages_unshared;
  244. /* The number of rmap_items in use: to calculate pages_volatile */
  245. static unsigned long ksm_rmap_items;
  246. /* The number of stable_node chains */
  247. static unsigned long ksm_stable_node_chains;
  248. /* The number of stable_node dups linked to the stable_node chains */
  249. static unsigned long ksm_stable_node_dups;
  250. /* Delay in pruning stale stable_node_dups in the stable_node_chains */
  251. static unsigned int ksm_stable_node_chains_prune_millisecs = 2000;
  252. /* Maximum number of page slots sharing a stable node */
  253. static int ksm_max_page_sharing = 256;
  254. /* Number of pages ksmd should scan in one batch */
  255. static unsigned int ksm_thread_pages_to_scan = DEFAULT_PAGES_TO_SCAN;
  256. /* Milliseconds ksmd should sleep between batches */
  257. static unsigned int ksm_thread_sleep_millisecs = 20;
  258. /* Checksum of an empty (zeroed) page */
  259. static unsigned int zero_checksum __read_mostly;
  260. /* Whether to merge empty (zeroed) pages with actual zero pages */
  261. static bool ksm_use_zero_pages __read_mostly;
  262. /* Skip pages that couldn't be de-duplicated previously */
  263. /* Default to true at least temporarily, for testing */
  264. static bool ksm_smart_scan = true;
  265. /* The number of zero pages which is placed by KSM */
  266. atomic_long_t ksm_zero_pages = ATOMIC_LONG_INIT(0);
  267. /* The number of pages that have been skipped due to "smart scanning" */
  268. static unsigned long ksm_pages_skipped;
  269. /* Don't scan more than max pages per batch. */
  270. static unsigned long ksm_advisor_max_pages_to_scan = 30000;
  271. /* Min CPU for scanning pages per scan */
  272. #define KSM_ADVISOR_MIN_CPU 10
  273. /* Max CPU for scanning pages per scan */
  274. static unsigned int ksm_advisor_max_cpu = 70;
  275. /* Target scan time in seconds to analyze all KSM candidate pages. */
  276. static unsigned long ksm_advisor_target_scan_time = 200;
  277. /* Exponentially weighted moving average. */
  278. #define EWMA_WEIGHT 30
  279. /**
  280. * struct advisor_ctx - metadata for KSM advisor
  281. * @start_scan: start time of the current scan
  282. * @scan_time: scan time of previous scan
  283. * @change: change in percent to pages_to_scan parameter
  284. * @cpu_time: cpu time consumed by the ksmd thread in the previous scan
  285. */
  286. struct advisor_ctx {
  287. ktime_t start_scan;
  288. unsigned long scan_time;
  289. unsigned long change;
  290. unsigned long long cpu_time;
  291. };
  292. static struct advisor_ctx advisor_ctx;
  293. /* Define different advisor's */
  294. enum ksm_advisor_type {
  295. KSM_ADVISOR_NONE,
  296. KSM_ADVISOR_SCAN_TIME,
  297. };
  298. static enum ksm_advisor_type ksm_advisor;
  299. #ifdef CONFIG_SYSFS
  300. /*
  301. * Only called through the sysfs control interface:
  302. */
  303. /* At least scan this many pages per batch. */
  304. static unsigned long ksm_advisor_min_pages_to_scan = 500;
  305. static void set_advisor_defaults(void)
  306. {
  307. if (ksm_advisor == KSM_ADVISOR_NONE) {
  308. ksm_thread_pages_to_scan = DEFAULT_PAGES_TO_SCAN;
  309. } else if (ksm_advisor == KSM_ADVISOR_SCAN_TIME) {
  310. advisor_ctx = (const struct advisor_ctx){ 0 };
  311. ksm_thread_pages_to_scan = ksm_advisor_min_pages_to_scan;
  312. }
  313. }
  314. #endif /* CONFIG_SYSFS */
  315. static inline void advisor_start_scan(void)
  316. {
  317. if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
  318. advisor_ctx.start_scan = ktime_get();
  319. }
  320. /*
  321. * Use previous scan time if available, otherwise use current scan time as an
  322. * approximation for the previous scan time.
  323. */
  324. static inline unsigned long prev_scan_time(struct advisor_ctx *ctx,
  325. unsigned long scan_time)
  326. {
  327. return ctx->scan_time ? ctx->scan_time : scan_time;
  328. }
  329. /* Calculate exponential weighted moving average */
  330. static unsigned long ewma(unsigned long prev, unsigned long curr)
  331. {
  332. return ((100 - EWMA_WEIGHT) * prev + EWMA_WEIGHT * curr) / 100;
  333. }
  334. /*
  335. * The scan time advisor is based on the current scan rate and the target
  336. * scan rate.
  337. *
  338. * new_pages_to_scan = pages_to_scan * (scan_time / target_scan_time)
  339. *
  340. * To avoid perturbations it calculates a change factor of previous changes.
  341. * A new change factor is calculated for each iteration and it uses an
  342. * exponentially weighted moving average. The new pages_to_scan value is
  343. * multiplied with that change factor:
  344. *
  345. * new_pages_to_scan *= change factor
  346. *
  347. * The new_pages_to_scan value is limited by the cpu min and max values. It
  348. * calculates the cpu percent for the last scan and calculates the new
  349. * estimated cpu percent cost for the next scan. That value is capped by the
  350. * cpu min and max setting.
  351. *
  352. * In addition the new pages_to_scan value is capped by the max and min
  353. * limits.
  354. */
  355. static void scan_time_advisor(void)
  356. {
  357. unsigned int cpu_percent;
  358. unsigned long cpu_time;
  359. unsigned long cpu_time_diff;
  360. unsigned long cpu_time_diff_ms;
  361. unsigned long pages;
  362. unsigned long per_page_cost;
  363. unsigned long factor;
  364. unsigned long change;
  365. unsigned long last_scan_time;
  366. unsigned long scan_time;
  367. /* Convert scan time to seconds */
  368. scan_time = div_s64(ktime_ms_delta(ktime_get(), advisor_ctx.start_scan),
  369. MSEC_PER_SEC);
  370. scan_time = scan_time ? scan_time : 1;
  371. /* Calculate CPU consumption of ksmd background thread */
  372. cpu_time = task_sched_runtime(current);
  373. cpu_time_diff = cpu_time - advisor_ctx.cpu_time;
  374. cpu_time_diff_ms = cpu_time_diff / 1000 / 1000;
  375. cpu_percent = (cpu_time_diff_ms * 100) / (scan_time * 1000);
  376. cpu_percent = cpu_percent ? cpu_percent : 1;
  377. last_scan_time = prev_scan_time(&advisor_ctx, scan_time);
  378. /* Calculate scan time as percentage of target scan time */
  379. factor = ksm_advisor_target_scan_time * 100 / scan_time;
  380. factor = factor ? factor : 1;
  381. /*
  382. * Calculate scan time as percentage of last scan time and use
  383. * exponentially weighted average to smooth it
  384. */
  385. change = scan_time * 100 / last_scan_time;
  386. change = change ? change : 1;
  387. change = ewma(advisor_ctx.change, change);
  388. /* Calculate new scan rate based on target scan rate. */
  389. pages = ksm_thread_pages_to_scan * 100 / factor;
  390. /* Update pages_to_scan by weighted change percentage. */
  391. pages = pages * change / 100;
  392. /* Cap new pages_to_scan value */
  393. per_page_cost = ksm_thread_pages_to_scan / cpu_percent;
  394. per_page_cost = per_page_cost ? per_page_cost : 1;
  395. pages = min(pages, per_page_cost * ksm_advisor_max_cpu);
  396. pages = max(pages, per_page_cost * KSM_ADVISOR_MIN_CPU);
  397. pages = min(pages, ksm_advisor_max_pages_to_scan);
  398. /* Update advisor context */
  399. advisor_ctx.change = change;
  400. advisor_ctx.scan_time = scan_time;
  401. advisor_ctx.cpu_time = cpu_time;
  402. ksm_thread_pages_to_scan = pages;
  403. trace_ksm_advisor(scan_time, pages, cpu_percent);
  404. }
  405. static void advisor_stop_scan(void)
  406. {
  407. if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
  408. scan_time_advisor();
  409. }
  410. #ifdef CONFIG_NUMA
  411. /* Zeroed when merging across nodes is not allowed */
  412. static unsigned int ksm_merge_across_nodes = 1;
  413. static int ksm_nr_node_ids = 1;
  414. #else
  415. #define ksm_merge_across_nodes 1U
  416. #define ksm_nr_node_ids 1
  417. #endif
  418. #define KSM_RUN_STOP 0
  419. #define KSM_RUN_MERGE 1
  420. #define KSM_RUN_UNMERGE 2
  421. #define KSM_RUN_OFFLINE 4
  422. static unsigned long ksm_run = KSM_RUN_STOP;
  423. static void wait_while_offlining(void);
  424. static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
  425. static DECLARE_WAIT_QUEUE_HEAD(ksm_iter_wait);
  426. static DEFINE_MUTEX(ksm_thread_mutex);
  427. static DEFINE_SPINLOCK(ksm_mmlist_lock);
  428. static int __init ksm_slab_init(void)
  429. {
  430. rmap_item_cache = KMEM_CACHE(ksm_rmap_item, 0);
  431. if (!rmap_item_cache)
  432. goto out;
  433. stable_node_cache = KMEM_CACHE(ksm_stable_node, 0);
  434. if (!stable_node_cache)
  435. goto out_free1;
  436. mm_slot_cache = KMEM_CACHE(ksm_mm_slot, 0);
  437. if (!mm_slot_cache)
  438. goto out_free2;
  439. return 0;
  440. out_free2:
  441. kmem_cache_destroy(stable_node_cache);
  442. out_free1:
  443. kmem_cache_destroy(rmap_item_cache);
  444. out:
  445. return -ENOMEM;
  446. }
  447. static void __init ksm_slab_free(void)
  448. {
  449. kmem_cache_destroy(mm_slot_cache);
  450. kmem_cache_destroy(stable_node_cache);
  451. kmem_cache_destroy(rmap_item_cache);
  452. mm_slot_cache = NULL;
  453. }
  454. static __always_inline bool is_stable_node_chain(struct ksm_stable_node *chain)
  455. {
  456. return chain->rmap_hlist_len == STABLE_NODE_CHAIN;
  457. }
  458. static __always_inline bool is_stable_node_dup(struct ksm_stable_node *dup)
  459. {
  460. return dup->head == STABLE_NODE_DUP_HEAD;
  461. }
  462. static inline void stable_node_chain_add_dup(struct ksm_stable_node *dup,
  463. struct ksm_stable_node *chain)
  464. {
  465. VM_BUG_ON(is_stable_node_dup(dup));
  466. dup->head = STABLE_NODE_DUP_HEAD;
  467. VM_BUG_ON(!is_stable_node_chain(chain));
  468. hlist_add_head(&dup->hlist_dup, &chain->hlist);
  469. ksm_stable_node_dups++;
  470. }
  471. static inline void __stable_node_dup_del(struct ksm_stable_node *dup)
  472. {
  473. VM_BUG_ON(!is_stable_node_dup(dup));
  474. hlist_del(&dup->hlist_dup);
  475. ksm_stable_node_dups--;
  476. }
  477. static inline void stable_node_dup_del(struct ksm_stable_node *dup)
  478. {
  479. VM_BUG_ON(is_stable_node_chain(dup));
  480. if (is_stable_node_dup(dup))
  481. __stable_node_dup_del(dup);
  482. else
  483. rb_erase(&dup->node, root_stable_tree + NUMA(dup->nid));
  484. #ifdef CONFIG_DEBUG_VM
  485. dup->head = NULL;
  486. #endif
  487. }
  488. static inline struct ksm_rmap_item *alloc_rmap_item(void)
  489. {
  490. struct ksm_rmap_item *rmap_item;
  491. rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL |
  492. __GFP_NORETRY | __GFP_NOWARN);
  493. if (rmap_item)
  494. ksm_rmap_items++;
  495. return rmap_item;
  496. }
  497. static inline void free_rmap_item(struct ksm_rmap_item *rmap_item)
  498. {
  499. ksm_rmap_items--;
  500. rmap_item->mm->ksm_rmap_items--;
  501. rmap_item->mm = NULL; /* debug safety */
  502. kmem_cache_free(rmap_item_cache, rmap_item);
  503. }
  504. static inline struct ksm_stable_node *alloc_stable_node(void)
  505. {
  506. /*
  507. * The allocation can take too long with GFP_KERNEL when memory is under
  508. * pressure, which may lead to hung task warnings. Adding __GFP_HIGH
  509. * grants access to memory reserves, helping to avoid this problem.
  510. */
  511. return kmem_cache_alloc(stable_node_cache, GFP_KERNEL | __GFP_HIGH);
  512. }
  513. static inline void free_stable_node(struct ksm_stable_node *stable_node)
  514. {
  515. VM_BUG_ON(stable_node->rmap_hlist_len &&
  516. !is_stable_node_chain(stable_node));
  517. kmem_cache_free(stable_node_cache, stable_node);
  518. }
  519. /*
  520. * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
  521. * page tables after it has passed through ksm_exit() - which, if necessary,
  522. * takes mmap_lock briefly to serialize against them. ksm_exit() does not set
  523. * a special flag: they can just back out as soon as mm_users goes to zero.
  524. * ksm_test_exit() is used throughout to make this test for exit: in some
  525. * places for correctness, in some places just to avoid unnecessary work.
  526. */
  527. static inline bool ksm_test_exit(struct mm_struct *mm)
  528. {
  529. return atomic_read(&mm->mm_users) == 0;
  530. }
  531. static int break_ksm_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long end,
  532. struct mm_walk *walk)
  533. {
  534. unsigned long *found_addr = (unsigned long *) walk->private;
  535. struct mm_struct *mm = walk->mm;
  536. pte_t *start_ptep, *ptep;
  537. spinlock_t *ptl;
  538. int found = 0;
  539. if (ksm_test_exit(walk->mm))
  540. return 0;
  541. if (signal_pending(current))
  542. return -ERESTARTSYS;
  543. start_ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
  544. if (!start_ptep)
  545. return 0;
  546. for (ptep = start_ptep; addr < end; ptep++, addr += PAGE_SIZE) {
  547. pte_t pte = ptep_get(ptep);
  548. struct folio *folio = NULL;
  549. if (pte_present(pte)) {
  550. folio = vm_normal_folio(walk->vma, addr, pte);
  551. } else if (!pte_none(pte)) {
  552. const softleaf_t entry = softleaf_from_pte(pte);
  553. /*
  554. * As KSM pages remain KSM pages until freed, no need to wait
  555. * here for migration to end.
  556. */
  557. if (softleaf_is_migration(entry))
  558. folio = softleaf_to_folio(entry);
  559. }
  560. /* return 1 if the page is an normal ksm page or KSM-placed zero page */
  561. found = (folio && folio_test_ksm(folio)) ||
  562. (pte_present(pte) && is_ksm_zero_pte(pte));
  563. if (found) {
  564. *found_addr = addr;
  565. goto out_unlock;
  566. }
  567. }
  568. out_unlock:
  569. pte_unmap_unlock(start_ptep, ptl);
  570. return found;
  571. }
  572. static const struct mm_walk_ops break_ksm_ops = {
  573. .pmd_entry = break_ksm_pmd_entry,
  574. .walk_lock = PGWALK_RDLOCK,
  575. };
  576. static const struct mm_walk_ops break_ksm_lock_vma_ops = {
  577. .pmd_entry = break_ksm_pmd_entry,
  578. .walk_lock = PGWALK_WRLOCK,
  579. };
  580. /*
  581. * Though it's very tempting to unmerge rmap_items from stable tree rather
  582. * than check every pte of a given vma, the locking doesn't quite work for
  583. * that - an rmap_item is assigned to the stable tree after inserting ksm
  584. * page and upping mmap_lock. Nor does it fit with the way we skip dup'ing
  585. * rmap_items from parent to child at fork time (so as not to waste time
  586. * if exit comes before the next scan reaches it).
  587. *
  588. * Similarly, although we'd like to remove rmap_items (so updating counts
  589. * and freeing memory) when unmerging an area, it's easier to leave that
  590. * to the next pass of ksmd - consider, for example, how ksmd might be
  591. * in cmp_and_merge_page on one of the rmap_items we would be removing.
  592. *
  593. * We use break_ksm to break COW on a ksm page by triggering unsharing,
  594. * such that the ksm page will get replaced by an exclusive anonymous page.
  595. *
  596. * We take great care only to touch a ksm page, in a VM_MERGEABLE vma,
  597. * in case the application has unmapped and remapped mm,addr meanwhile.
  598. * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
  599. * mmap of /dev/mem, where we would not want to touch it.
  600. *
  601. * FAULT_FLAG_REMOTE/FOLL_REMOTE are because we do this outside the context
  602. * of the process that owns 'vma'. We also do not want to enforce
  603. * protection keys here anyway.
  604. */
  605. static int break_ksm(struct vm_area_struct *vma, unsigned long addr,
  606. unsigned long end, bool lock_vma)
  607. {
  608. vm_fault_t ret = 0;
  609. const struct mm_walk_ops *ops = lock_vma ?
  610. &break_ksm_lock_vma_ops : &break_ksm_ops;
  611. do {
  612. int ksm_page;
  613. cond_resched();
  614. ksm_page = walk_page_range_vma(vma, addr, end, ops, &addr);
  615. if (ksm_page <= 0)
  616. return ksm_page;
  617. ret = handle_mm_fault(vma, addr,
  618. FAULT_FLAG_UNSHARE | FAULT_FLAG_REMOTE,
  619. NULL);
  620. } while (!(ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
  621. /*
  622. * We must loop until we no longer find a KSM page because
  623. * handle_mm_fault() may back out if there's any difficulty e.g. if
  624. * pte accessed bit gets updated concurrently.
  625. *
  626. * VM_FAULT_SIGBUS could occur if we race with truncation of the
  627. * backing file, which also invalidates anonymous pages: that's
  628. * okay, that truncation will have unmapped the KSM page for us.
  629. *
  630. * VM_FAULT_OOM: at the time of writing (late July 2009), setting
  631. * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
  632. * current task has TIF_MEMDIE set, and will be OOM killed on return
  633. * to user; and ksmd, having no mm, would never be chosen for that.
  634. *
  635. * But if the mm is in a limited mem_cgroup, then the fault may fail
  636. * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
  637. * even ksmd can fail in this way - though it's usually breaking ksm
  638. * just to undo a merge it made a moment before, so unlikely to oom.
  639. *
  640. * That's a pity: we might therefore have more kernel pages allocated
  641. * than we're counting as nodes in the stable tree; but ksm_do_scan
  642. * will retry to break_cow on each pass, so should recover the page
  643. * in due course. The important thing is to not let VM_MERGEABLE
  644. * be cleared while any such pages might remain in the area.
  645. */
  646. return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
  647. }
  648. static bool ksm_compatible(const struct file *file, vm_flags_t vm_flags)
  649. {
  650. if (vm_flags & (VM_SHARED | VM_MAYSHARE | VM_SPECIAL |
  651. VM_HUGETLB | VM_DROPPABLE))
  652. return false; /* just ignore the advice */
  653. if (file_is_dax(file))
  654. return false;
  655. #ifdef VM_SAO
  656. if (vm_flags & VM_SAO)
  657. return false;
  658. #endif
  659. #ifdef VM_SPARC_ADI
  660. if (vm_flags & VM_SPARC_ADI)
  661. return false;
  662. #endif
  663. return true;
  664. }
  665. static bool vma_ksm_compatible(struct vm_area_struct *vma)
  666. {
  667. return ksm_compatible(vma->vm_file, vma->vm_flags);
  668. }
  669. static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
  670. unsigned long addr)
  671. {
  672. struct vm_area_struct *vma;
  673. if (ksm_test_exit(mm))
  674. return NULL;
  675. vma = vma_lookup(mm, addr);
  676. if (!vma || !(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  677. return NULL;
  678. return vma;
  679. }
  680. static void break_cow(struct ksm_rmap_item *rmap_item)
  681. {
  682. struct mm_struct *mm = rmap_item->mm;
  683. unsigned long addr = rmap_item->address;
  684. struct vm_area_struct *vma;
  685. /*
  686. * It is not an accident that whenever we want to break COW
  687. * to undo, we also need to drop a reference to the anon_vma.
  688. */
  689. put_anon_vma(rmap_item->anon_vma);
  690. mmap_read_lock(mm);
  691. vma = find_mergeable_vma(mm, addr);
  692. if (vma)
  693. break_ksm(vma, addr, addr + PAGE_SIZE, false);
  694. mmap_read_unlock(mm);
  695. }
  696. static struct page *get_mergeable_page(struct ksm_rmap_item *rmap_item)
  697. {
  698. struct mm_struct *mm = rmap_item->mm;
  699. unsigned long addr = rmap_item->address;
  700. struct vm_area_struct *vma;
  701. struct page *page = NULL;
  702. struct folio_walk fw;
  703. struct folio *folio;
  704. mmap_read_lock(mm);
  705. vma = find_mergeable_vma(mm, addr);
  706. if (!vma)
  707. goto out;
  708. folio = folio_walk_start(&fw, vma, addr, 0);
  709. if (folio) {
  710. if (!folio_is_zone_device(folio) &&
  711. folio_test_anon(folio)) {
  712. folio_get(folio);
  713. page = fw.page;
  714. }
  715. folio_walk_end(&fw, vma);
  716. }
  717. out:
  718. if (page) {
  719. flush_anon_page(vma, page, addr);
  720. flush_dcache_page(page);
  721. }
  722. mmap_read_unlock(mm);
  723. return page;
  724. }
  725. /*
  726. * This helper is used for getting right index into array of tree roots.
  727. * When merge_across_nodes knob is set to 1, there are only two rb-trees for
  728. * stable and unstable pages from all nodes with roots in index 0. Otherwise,
  729. * every node has its own stable and unstable tree.
  730. */
  731. static inline int get_kpfn_nid(unsigned long kpfn)
  732. {
  733. return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
  734. }
  735. static struct ksm_stable_node *alloc_stable_node_chain(struct ksm_stable_node *dup,
  736. struct rb_root *root)
  737. {
  738. struct ksm_stable_node *chain = alloc_stable_node();
  739. VM_BUG_ON(is_stable_node_chain(dup));
  740. if (likely(chain)) {
  741. INIT_HLIST_HEAD(&chain->hlist);
  742. chain->chain_prune_time = jiffies;
  743. chain->rmap_hlist_len = STABLE_NODE_CHAIN;
  744. #if defined (CONFIG_DEBUG_VM) && defined(CONFIG_NUMA)
  745. chain->nid = NUMA_NO_NODE; /* debug */
  746. #endif
  747. ksm_stable_node_chains++;
  748. /*
  749. * Put the stable node chain in the first dimension of
  750. * the stable tree and at the same time remove the old
  751. * stable node.
  752. */
  753. rb_replace_node(&dup->node, &chain->node, root);
  754. /*
  755. * Move the old stable node to the second dimension
  756. * queued in the hlist_dup. The invariant is that all
  757. * dup stable_nodes in the chain->hlist point to pages
  758. * that are write protected and have the exact same
  759. * content.
  760. */
  761. stable_node_chain_add_dup(dup, chain);
  762. }
  763. return chain;
  764. }
  765. static inline void free_stable_node_chain(struct ksm_stable_node *chain,
  766. struct rb_root *root)
  767. {
  768. rb_erase(&chain->node, root);
  769. free_stable_node(chain);
  770. ksm_stable_node_chains--;
  771. }
  772. static void remove_node_from_stable_tree(struct ksm_stable_node *stable_node)
  773. {
  774. struct ksm_rmap_item *rmap_item;
  775. /* check it's not STABLE_NODE_CHAIN or negative */
  776. BUG_ON(stable_node->rmap_hlist_len < 0);
  777. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  778. if (rmap_item->hlist.next) {
  779. ksm_pages_sharing--;
  780. trace_ksm_remove_rmap_item(stable_node->kpfn, rmap_item, rmap_item->mm);
  781. } else {
  782. ksm_pages_shared--;
  783. }
  784. rmap_item->mm->ksm_merging_pages--;
  785. VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
  786. stable_node->rmap_hlist_len--;
  787. put_anon_vma(rmap_item->anon_vma);
  788. rmap_item->address &= PAGE_MASK;
  789. cond_resched();
  790. }
  791. /*
  792. * We need the second aligned pointer of the migrate_nodes
  793. * list_head to stay clear from the rb_parent_color union
  794. * (aligned and different than any node) and also different
  795. * from &migrate_nodes. This will verify that future list.h changes
  796. * don't break STABLE_NODE_DUP_HEAD. Only recent gcc can handle it.
  797. */
  798. BUILD_BUG_ON(STABLE_NODE_DUP_HEAD <= &migrate_nodes);
  799. BUILD_BUG_ON(STABLE_NODE_DUP_HEAD >= &migrate_nodes + 1);
  800. trace_ksm_remove_ksm_page(stable_node->kpfn);
  801. if (stable_node->head == &migrate_nodes)
  802. list_del(&stable_node->list);
  803. else
  804. stable_node_dup_del(stable_node);
  805. free_stable_node(stable_node);
  806. }
  807. enum ksm_get_folio_flags {
  808. KSM_GET_FOLIO_NOLOCK,
  809. KSM_GET_FOLIO_LOCK,
  810. KSM_GET_FOLIO_TRYLOCK
  811. };
  812. /*
  813. * ksm_get_folio: checks if the page indicated by the stable node
  814. * is still its ksm page, despite having held no reference to it.
  815. * In which case we can trust the content of the page, and it
  816. * returns the gotten page; but if the page has now been zapped,
  817. * remove the stale node from the stable tree and return NULL.
  818. * But beware, the stable node's page might be being migrated.
  819. *
  820. * You would expect the stable_node to hold a reference to the ksm page.
  821. * But if it increments the page's count, swapping out has to wait for
  822. * ksmd to come around again before it can free the page, which may take
  823. * seconds or even minutes: much too unresponsive. So instead we use a
  824. * "keyhole reference": access to the ksm page from the stable node peeps
  825. * out through its keyhole to see if that page still holds the right key,
  826. * pointing back to this stable node. This relies on freeing a PageAnon
  827. * page to reset its page->mapping to NULL, and relies on no other use of
  828. * a page to put something that might look like our key in page->mapping.
  829. * is on its way to being freed; but it is an anomaly to bear in mind.
  830. */
  831. static struct folio *ksm_get_folio(struct ksm_stable_node *stable_node,
  832. enum ksm_get_folio_flags flags)
  833. {
  834. struct folio *folio;
  835. void *expected_mapping;
  836. unsigned long kpfn;
  837. expected_mapping = (void *)((unsigned long)stable_node |
  838. FOLIO_MAPPING_KSM);
  839. again:
  840. kpfn = READ_ONCE(stable_node->kpfn); /* Address dependency. */
  841. folio = pfn_folio(kpfn);
  842. if (READ_ONCE(folio->mapping) != expected_mapping)
  843. goto stale;
  844. /*
  845. * We cannot do anything with the page while its refcount is 0.
  846. * Usually 0 means free, or tail of a higher-order page: in which
  847. * case this node is no longer referenced, and should be freed;
  848. * however, it might mean that the page is under page_ref_freeze().
  849. * The __remove_mapping() case is easy, again the node is now stale;
  850. * the same is in reuse_ksm_page() case; but if page is swapcache
  851. * in folio_migrate_mapping(), it might still be our page,
  852. * in which case it's essential to keep the node.
  853. */
  854. while (!folio_try_get(folio)) {
  855. /*
  856. * Another check for folio->mapping != expected_mapping
  857. * would work here too. We have chosen to test the
  858. * swapcache flag to optimize the common case, when the
  859. * folio is or is about to be freed: the swapcache flag
  860. * is cleared (under spin_lock_irq) in the ref_freeze
  861. * section of __remove_mapping(); but anon folio->mapping
  862. * is reset to NULL later, in free_pages_prepare().
  863. */
  864. if (!folio_test_swapcache(folio))
  865. goto stale;
  866. cpu_relax();
  867. }
  868. if (READ_ONCE(folio->mapping) != expected_mapping) {
  869. folio_put(folio);
  870. goto stale;
  871. }
  872. if (flags == KSM_GET_FOLIO_TRYLOCK) {
  873. if (!folio_trylock(folio)) {
  874. folio_put(folio);
  875. return ERR_PTR(-EBUSY);
  876. }
  877. } else if (flags == KSM_GET_FOLIO_LOCK)
  878. folio_lock(folio);
  879. if (flags != KSM_GET_FOLIO_NOLOCK) {
  880. if (READ_ONCE(folio->mapping) != expected_mapping) {
  881. folio_unlock(folio);
  882. folio_put(folio);
  883. goto stale;
  884. }
  885. }
  886. return folio;
  887. stale:
  888. /*
  889. * We come here from above when folio->mapping or the swapcache flag
  890. * suggests that the node is stale; but it might be under migration.
  891. * We need smp_rmb(), matching the smp_wmb() in folio_migrate_ksm(),
  892. * before checking whether node->kpfn has been changed.
  893. */
  894. smp_rmb();
  895. if (READ_ONCE(stable_node->kpfn) != kpfn)
  896. goto again;
  897. remove_node_from_stable_tree(stable_node);
  898. return NULL;
  899. }
  900. /*
  901. * Removing rmap_item from stable or unstable tree.
  902. * This function will clean the information from the stable/unstable tree.
  903. */
  904. static void remove_rmap_item_from_tree(struct ksm_rmap_item *rmap_item)
  905. {
  906. if (rmap_item->address & STABLE_FLAG) {
  907. struct ksm_stable_node *stable_node;
  908. struct folio *folio;
  909. stable_node = rmap_item->head;
  910. folio = ksm_get_folio(stable_node, KSM_GET_FOLIO_LOCK);
  911. if (!folio)
  912. goto out;
  913. hlist_del(&rmap_item->hlist);
  914. folio_unlock(folio);
  915. folio_put(folio);
  916. if (!hlist_empty(&stable_node->hlist))
  917. ksm_pages_sharing--;
  918. else
  919. ksm_pages_shared--;
  920. rmap_item->mm->ksm_merging_pages--;
  921. VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
  922. stable_node->rmap_hlist_len--;
  923. put_anon_vma(rmap_item->anon_vma);
  924. rmap_item->head = NULL;
  925. rmap_item->address &= PAGE_MASK;
  926. } else if (rmap_item->address & UNSTABLE_FLAG) {
  927. unsigned char age;
  928. /*
  929. * Usually ksmd can and must skip the rb_erase, because
  930. * root_unstable_tree was already reset to RB_ROOT.
  931. * But be careful when an mm is exiting: do the rb_erase
  932. * if this rmap_item was inserted by this scan, rather
  933. * than left over from before.
  934. */
  935. age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
  936. BUG_ON(age > 1);
  937. if (!age)
  938. rb_erase(&rmap_item->node,
  939. root_unstable_tree + NUMA(rmap_item->nid));
  940. ksm_pages_unshared--;
  941. rmap_item->address &= PAGE_MASK;
  942. }
  943. out:
  944. cond_resched(); /* we're called from many long loops */
  945. }
  946. static void remove_trailing_rmap_items(struct ksm_rmap_item **rmap_list)
  947. {
  948. while (*rmap_list) {
  949. struct ksm_rmap_item *rmap_item = *rmap_list;
  950. *rmap_list = rmap_item->rmap_list;
  951. remove_rmap_item_from_tree(rmap_item);
  952. free_rmap_item(rmap_item);
  953. }
  954. }
  955. static inline
  956. struct ksm_stable_node *folio_stable_node(const struct folio *folio)
  957. {
  958. return folio_test_ksm(folio) ? folio_raw_mapping(folio) : NULL;
  959. }
  960. static inline void folio_set_stable_node(struct folio *folio,
  961. struct ksm_stable_node *stable_node)
  962. {
  963. VM_WARN_ON_FOLIO(folio_test_anon(folio) && PageAnonExclusive(&folio->page), folio);
  964. folio->mapping = (void *)((unsigned long)stable_node | FOLIO_MAPPING_KSM);
  965. }
  966. #ifdef CONFIG_SYSFS
  967. /*
  968. * Only called through the sysfs control interface:
  969. */
  970. static int remove_stable_node(struct ksm_stable_node *stable_node)
  971. {
  972. struct folio *folio;
  973. int err;
  974. folio = ksm_get_folio(stable_node, KSM_GET_FOLIO_LOCK);
  975. if (!folio) {
  976. /*
  977. * ksm_get_folio did remove_node_from_stable_tree itself.
  978. */
  979. return 0;
  980. }
  981. /*
  982. * Page could be still mapped if this races with __mmput() running in
  983. * between ksm_exit() and exit_mmap(). Just refuse to let
  984. * merge_across_nodes/max_page_sharing be switched.
  985. */
  986. err = -EBUSY;
  987. if (!folio_mapped(folio)) {
  988. /*
  989. * The stable node did not yet appear stale to ksm_get_folio(),
  990. * since that allows for an unmapped ksm folio to be recognized
  991. * right up until it is freed; but the node is safe to remove.
  992. * This folio might be in an LRU cache waiting to be freed,
  993. * or it might be in the swapcache (perhaps under writeback),
  994. * or it might have been removed from swapcache a moment ago.
  995. */
  996. folio_set_stable_node(folio, NULL);
  997. remove_node_from_stable_tree(stable_node);
  998. err = 0;
  999. }
  1000. folio_unlock(folio);
  1001. folio_put(folio);
  1002. return err;
  1003. }
  1004. static int remove_stable_node_chain(struct ksm_stable_node *stable_node,
  1005. struct rb_root *root)
  1006. {
  1007. struct ksm_stable_node *dup;
  1008. struct hlist_node *hlist_safe;
  1009. if (!is_stable_node_chain(stable_node)) {
  1010. VM_BUG_ON(is_stable_node_dup(stable_node));
  1011. if (remove_stable_node(stable_node))
  1012. return true;
  1013. else
  1014. return false;
  1015. }
  1016. hlist_for_each_entry_safe(dup, hlist_safe,
  1017. &stable_node->hlist, hlist_dup) {
  1018. VM_BUG_ON(!is_stable_node_dup(dup));
  1019. if (remove_stable_node(dup))
  1020. return true;
  1021. }
  1022. BUG_ON(!hlist_empty(&stable_node->hlist));
  1023. free_stable_node_chain(stable_node, root);
  1024. return false;
  1025. }
  1026. static int remove_all_stable_nodes(void)
  1027. {
  1028. struct ksm_stable_node *stable_node, *next;
  1029. int nid;
  1030. int err = 0;
  1031. for (nid = 0; nid < ksm_nr_node_ids; nid++) {
  1032. while (root_stable_tree[nid].rb_node) {
  1033. stable_node = rb_entry(root_stable_tree[nid].rb_node,
  1034. struct ksm_stable_node, node);
  1035. if (remove_stable_node_chain(stable_node,
  1036. root_stable_tree + nid)) {
  1037. err = -EBUSY;
  1038. break; /* proceed to next nid */
  1039. }
  1040. cond_resched();
  1041. }
  1042. }
  1043. list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
  1044. if (remove_stable_node(stable_node))
  1045. err = -EBUSY;
  1046. cond_resched();
  1047. }
  1048. return err;
  1049. }
  1050. static int unmerge_and_remove_all_rmap_items(void)
  1051. {
  1052. struct ksm_mm_slot *mm_slot;
  1053. struct mm_slot *slot;
  1054. struct mm_struct *mm;
  1055. struct vm_area_struct *vma;
  1056. int err = 0;
  1057. spin_lock(&ksm_mmlist_lock);
  1058. slot = list_entry(ksm_mm_head.slot.mm_node.next,
  1059. struct mm_slot, mm_node);
  1060. ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  1061. spin_unlock(&ksm_mmlist_lock);
  1062. for (mm_slot = ksm_scan.mm_slot; mm_slot != &ksm_mm_head;
  1063. mm_slot = ksm_scan.mm_slot) {
  1064. VMA_ITERATOR(vmi, mm_slot->slot.mm, 0);
  1065. mm = mm_slot->slot.mm;
  1066. mmap_read_lock(mm);
  1067. /*
  1068. * Exit right away if mm is exiting to avoid lockdep issue in
  1069. * the maple tree
  1070. */
  1071. if (ksm_test_exit(mm))
  1072. goto mm_exiting;
  1073. for_each_vma(vmi, vma) {
  1074. if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  1075. continue;
  1076. err = break_ksm(vma, vma->vm_start, vma->vm_end, false);
  1077. if (err)
  1078. goto error;
  1079. }
  1080. mm_exiting:
  1081. remove_trailing_rmap_items(&mm_slot->rmap_list);
  1082. mmap_read_unlock(mm);
  1083. spin_lock(&ksm_mmlist_lock);
  1084. slot = list_entry(mm_slot->slot.mm_node.next,
  1085. struct mm_slot, mm_node);
  1086. ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  1087. if (ksm_test_exit(mm)) {
  1088. hash_del(&mm_slot->slot.hash);
  1089. list_del(&mm_slot->slot.mm_node);
  1090. spin_unlock(&ksm_mmlist_lock);
  1091. mm_slot_free(mm_slot_cache, mm_slot);
  1092. mm_flags_clear(MMF_VM_MERGEABLE, mm);
  1093. mm_flags_clear(MMF_VM_MERGE_ANY, mm);
  1094. mmdrop(mm);
  1095. } else
  1096. spin_unlock(&ksm_mmlist_lock);
  1097. }
  1098. /* Clean up stable nodes, but don't worry if some are still busy */
  1099. remove_all_stable_nodes();
  1100. ksm_scan.seqnr = 0;
  1101. return 0;
  1102. error:
  1103. mmap_read_unlock(mm);
  1104. spin_lock(&ksm_mmlist_lock);
  1105. ksm_scan.mm_slot = &ksm_mm_head;
  1106. spin_unlock(&ksm_mmlist_lock);
  1107. return err;
  1108. }
  1109. #endif /* CONFIG_SYSFS */
  1110. static u32 calc_checksum(struct page *page)
  1111. {
  1112. u32 checksum;
  1113. void *addr = kmap_local_page(page);
  1114. checksum = xxhash(addr, PAGE_SIZE, 0);
  1115. kunmap_local(addr);
  1116. return checksum;
  1117. }
  1118. static int write_protect_page(struct vm_area_struct *vma, struct folio *folio,
  1119. pte_t *orig_pte)
  1120. {
  1121. struct mm_struct *mm = vma->vm_mm;
  1122. DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, 0, 0);
  1123. int swapped;
  1124. int err = -EFAULT;
  1125. struct mmu_notifier_range range;
  1126. bool anon_exclusive;
  1127. pte_t entry;
  1128. if (WARN_ON_ONCE(folio_test_large(folio)))
  1129. return err;
  1130. pvmw.address = page_address_in_vma(folio, folio_page(folio, 0), vma);
  1131. if (pvmw.address == -EFAULT)
  1132. goto out;
  1133. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, pvmw.address,
  1134. pvmw.address + PAGE_SIZE);
  1135. mmu_notifier_invalidate_range_start(&range);
  1136. if (!page_vma_mapped_walk(&pvmw))
  1137. goto out_mn;
  1138. if (WARN_ONCE(!pvmw.pte, "Unexpected PMD mapping?"))
  1139. goto out_unlock;
  1140. entry = ptep_get(pvmw.pte);
  1141. /*
  1142. * Handle PFN swap PTEs, such as device-exclusive ones, that actually
  1143. * map pages: give up just like the next folio_walk would.
  1144. */
  1145. if (unlikely(!pte_present(entry)))
  1146. goto out_unlock;
  1147. anon_exclusive = PageAnonExclusive(&folio->page);
  1148. if (pte_write(entry) || pte_dirty(entry) ||
  1149. anon_exclusive || mm_tlb_flush_pending(mm)) {
  1150. swapped = folio_test_swapcache(folio);
  1151. flush_cache_page(vma, pvmw.address, folio_pfn(folio));
  1152. /*
  1153. * Ok this is tricky, when get_user_pages_fast() run it doesn't
  1154. * take any lock, therefore the check that we are going to make
  1155. * with the pagecount against the mapcount is racy and
  1156. * O_DIRECT can happen right after the check.
  1157. * So we clear the pte and flush the tlb before the check
  1158. * this assure us that no O_DIRECT can happen after the check
  1159. * or in the middle of the check.
  1160. *
  1161. * No need to notify as we are downgrading page table to read
  1162. * only not changing it to point to a new page.
  1163. *
  1164. * See Documentation/mm/mmu_notifier.rst
  1165. */
  1166. entry = ptep_clear_flush(vma, pvmw.address, pvmw.pte);
  1167. /*
  1168. * Check that no O_DIRECT or similar I/O is in progress on the
  1169. * page
  1170. */
  1171. if (folio_mapcount(folio) + 1 + swapped != folio_ref_count(folio)) {
  1172. set_pte_at(mm, pvmw.address, pvmw.pte, entry);
  1173. goto out_unlock;
  1174. }
  1175. /* See folio_try_share_anon_rmap_pte(): clear PTE first. */
  1176. if (anon_exclusive &&
  1177. folio_try_share_anon_rmap_pte(folio, &folio->page)) {
  1178. set_pte_at(mm, pvmw.address, pvmw.pte, entry);
  1179. goto out_unlock;
  1180. }
  1181. if (pte_dirty(entry))
  1182. folio_mark_dirty(folio);
  1183. entry = pte_mkclean(entry);
  1184. if (pte_write(entry))
  1185. entry = pte_wrprotect(entry);
  1186. set_pte_at(mm, pvmw.address, pvmw.pte, entry);
  1187. }
  1188. *orig_pte = entry;
  1189. err = 0;
  1190. out_unlock:
  1191. page_vma_mapped_walk_done(&pvmw);
  1192. out_mn:
  1193. mmu_notifier_invalidate_range_end(&range);
  1194. out:
  1195. return err;
  1196. }
  1197. /**
  1198. * replace_page - replace page in vma by new ksm page
  1199. * @vma: vma that holds the pte pointing to page
  1200. * @page: the page we are replacing by kpage
  1201. * @kpage: the ksm page we replace page by
  1202. * @orig_pte: the original value of the pte
  1203. *
  1204. * Returns 0 on success, -EFAULT on failure.
  1205. */
  1206. static int replace_page(struct vm_area_struct *vma, struct page *page,
  1207. struct page *kpage, pte_t orig_pte)
  1208. {
  1209. struct folio *kfolio = page_folio(kpage);
  1210. struct mm_struct *mm = vma->vm_mm;
  1211. struct folio *folio = page_folio(page);
  1212. pmd_t *pmd;
  1213. pmd_t pmde;
  1214. pte_t *ptep;
  1215. pte_t newpte;
  1216. spinlock_t *ptl;
  1217. unsigned long addr;
  1218. int err = -EFAULT;
  1219. struct mmu_notifier_range range;
  1220. addr = page_address_in_vma(folio, page, vma);
  1221. if (addr == -EFAULT)
  1222. goto out;
  1223. pmd = mm_find_pmd(mm, addr);
  1224. if (!pmd)
  1225. goto out;
  1226. /*
  1227. * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
  1228. * without holding anon_vma lock for write. So when looking for a
  1229. * genuine pmde (in which to find pte), test present and !THP together.
  1230. */
  1231. pmde = pmdp_get_lockless(pmd);
  1232. if (!pmd_present(pmde) || pmd_trans_huge(pmde))
  1233. goto out;
  1234. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, addr,
  1235. addr + PAGE_SIZE);
  1236. mmu_notifier_invalidate_range_start(&range);
  1237. ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
  1238. if (!ptep)
  1239. goto out_mn;
  1240. if (!pte_same(ptep_get(ptep), orig_pte)) {
  1241. pte_unmap_unlock(ptep, ptl);
  1242. goto out_mn;
  1243. }
  1244. VM_BUG_ON_PAGE(PageAnonExclusive(page), page);
  1245. VM_BUG_ON_FOLIO(folio_test_anon(kfolio) && PageAnonExclusive(kpage),
  1246. kfolio);
  1247. /*
  1248. * No need to check ksm_use_zero_pages here: we can only have a
  1249. * zero_page here if ksm_use_zero_pages was enabled already.
  1250. */
  1251. if (!is_zero_pfn(page_to_pfn(kpage))) {
  1252. folio_get(kfolio);
  1253. folio_add_anon_rmap_pte(kfolio, kpage, vma, addr, RMAP_NONE);
  1254. newpte = mk_pte(kpage, vma->vm_page_prot);
  1255. } else {
  1256. /*
  1257. * Use pte_mkdirty to mark the zero page mapped by KSM, and then
  1258. * we can easily track all KSM-placed zero pages by checking if
  1259. * the dirty bit in zero page's PTE is set.
  1260. */
  1261. newpte = pte_mkdirty(pte_mkspecial(pfn_pte(page_to_pfn(kpage), vma->vm_page_prot)));
  1262. ksm_map_zero_page(mm);
  1263. /*
  1264. * We're replacing an anonymous page with a zero page, which is
  1265. * not anonymous. We need to do proper accounting otherwise we
  1266. * will get wrong values in /proc, and a BUG message in dmesg
  1267. * when tearing down the mm.
  1268. */
  1269. dec_mm_counter(mm, MM_ANONPAGES);
  1270. }
  1271. flush_cache_page(vma, addr, pte_pfn(ptep_get(ptep)));
  1272. /*
  1273. * No need to notify as we are replacing a read only page with another
  1274. * read only page with the same content.
  1275. *
  1276. * See Documentation/mm/mmu_notifier.rst
  1277. */
  1278. ptep_clear_flush(vma, addr, ptep);
  1279. set_pte_at(mm, addr, ptep, newpte);
  1280. folio_remove_rmap_pte(folio, page, vma);
  1281. if (!folio_mapped(folio))
  1282. folio_free_swap(folio);
  1283. folio_put(folio);
  1284. pte_unmap_unlock(ptep, ptl);
  1285. err = 0;
  1286. out_mn:
  1287. mmu_notifier_invalidate_range_end(&range);
  1288. out:
  1289. return err;
  1290. }
  1291. /*
  1292. * try_to_merge_one_page - take two pages and merge them into one
  1293. * @vma: the vma that holds the pte pointing to page
  1294. * @page: the PageAnon page that we want to replace with kpage
  1295. * @kpage: the KSM page that we want to map instead of page,
  1296. * or NULL the first time when we want to use page as kpage.
  1297. *
  1298. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  1299. */
  1300. static int try_to_merge_one_page(struct vm_area_struct *vma,
  1301. struct page *page, struct page *kpage)
  1302. {
  1303. struct folio *folio = page_folio(page);
  1304. pte_t orig_pte = __pte(0);
  1305. int err = -EFAULT;
  1306. if (page == kpage) /* ksm page forked */
  1307. return 0;
  1308. if (!folio_test_anon(folio))
  1309. goto out;
  1310. /*
  1311. * We need the folio lock to read a stable swapcache flag in
  1312. * write_protect_page(). We trylock because we don't want to wait
  1313. * here - we prefer to continue scanning and merging different
  1314. * pages, then come back to this page when it is unlocked.
  1315. */
  1316. if (!folio_trylock(folio))
  1317. goto out;
  1318. if (folio_test_large(folio)) {
  1319. if (split_huge_page(page))
  1320. goto out_unlock;
  1321. folio = page_folio(page);
  1322. }
  1323. /*
  1324. * If this anonymous page is mapped only here, its pte may need
  1325. * to be write-protected. If it's mapped elsewhere, all of its
  1326. * ptes are necessarily already write-protected. But in either
  1327. * case, we need to lock and check page_count is not raised.
  1328. */
  1329. if (write_protect_page(vma, folio, &orig_pte) == 0) {
  1330. if (!kpage) {
  1331. /*
  1332. * While we hold folio lock, upgrade folio from
  1333. * anon to a NULL stable_node with the KSM flag set:
  1334. * stable_tree_insert() will update stable_node.
  1335. */
  1336. folio_set_stable_node(folio, NULL);
  1337. folio_mark_accessed(folio);
  1338. /*
  1339. * Page reclaim just frees a clean folio with no dirty
  1340. * ptes: make sure that the ksm page would be swapped.
  1341. */
  1342. if (!folio_test_dirty(folio))
  1343. folio_mark_dirty(folio);
  1344. err = 0;
  1345. } else if (pages_identical(page, kpage))
  1346. err = replace_page(vma, page, kpage, orig_pte);
  1347. }
  1348. out_unlock:
  1349. folio_unlock(folio);
  1350. out:
  1351. return err;
  1352. }
  1353. /*
  1354. * This function returns 0 if the pages were merged or if they are
  1355. * no longer merging candidates (e.g., VMA stale), -EFAULT otherwise.
  1356. */
  1357. static int try_to_merge_with_zero_page(struct ksm_rmap_item *rmap_item,
  1358. struct page *page)
  1359. {
  1360. struct mm_struct *mm = rmap_item->mm;
  1361. int err = -EFAULT;
  1362. /*
  1363. * Same checksum as an empty page. We attempt to merge it with the
  1364. * appropriate zero page if the user enabled this via sysfs.
  1365. */
  1366. if (ksm_use_zero_pages && (rmap_item->oldchecksum == zero_checksum)) {
  1367. struct vm_area_struct *vma;
  1368. mmap_read_lock(mm);
  1369. vma = find_mergeable_vma(mm, rmap_item->address);
  1370. if (vma) {
  1371. err = try_to_merge_one_page(vma, page,
  1372. ZERO_PAGE(rmap_item->address));
  1373. trace_ksm_merge_one_page(
  1374. page_to_pfn(ZERO_PAGE(rmap_item->address)),
  1375. rmap_item, mm, err);
  1376. } else {
  1377. /*
  1378. * If the vma is out of date, we do not need to
  1379. * continue.
  1380. */
  1381. err = 0;
  1382. }
  1383. mmap_read_unlock(mm);
  1384. }
  1385. return err;
  1386. }
  1387. /*
  1388. * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
  1389. * but no new kernel page is allocated: kpage must already be a ksm page.
  1390. *
  1391. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  1392. */
  1393. static int try_to_merge_with_ksm_page(struct ksm_rmap_item *rmap_item,
  1394. struct page *page, struct page *kpage)
  1395. {
  1396. struct mm_struct *mm = rmap_item->mm;
  1397. struct vm_area_struct *vma;
  1398. int err = -EFAULT;
  1399. mmap_read_lock(mm);
  1400. vma = find_mergeable_vma(mm, rmap_item->address);
  1401. if (!vma)
  1402. goto out;
  1403. err = try_to_merge_one_page(vma, page, kpage);
  1404. if (err)
  1405. goto out;
  1406. /* Unstable nid is in union with stable anon_vma: remove first */
  1407. remove_rmap_item_from_tree(rmap_item);
  1408. /* Must get reference to anon_vma while still holding mmap_lock */
  1409. rmap_item->anon_vma = vma->anon_vma;
  1410. get_anon_vma(vma->anon_vma);
  1411. out:
  1412. mmap_read_unlock(mm);
  1413. trace_ksm_merge_with_ksm_page(kpage, page_to_pfn(kpage ? kpage : page),
  1414. rmap_item, mm, err);
  1415. return err;
  1416. }
  1417. /*
  1418. * try_to_merge_two_pages - take two identical pages and prepare them
  1419. * to be merged into one page.
  1420. *
  1421. * This function returns the kpage if we successfully merged two identical
  1422. * pages into one ksm page, NULL otherwise.
  1423. *
  1424. * Note that this function upgrades page to ksm page: if one of the pages
  1425. * is already a ksm page, try_to_merge_with_ksm_page should be used.
  1426. */
  1427. static struct folio *try_to_merge_two_pages(struct ksm_rmap_item *rmap_item,
  1428. struct page *page,
  1429. struct ksm_rmap_item *tree_rmap_item,
  1430. struct page *tree_page)
  1431. {
  1432. int err;
  1433. err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
  1434. if (!err) {
  1435. err = try_to_merge_with_ksm_page(tree_rmap_item,
  1436. tree_page, page);
  1437. /*
  1438. * If that fails, we have a ksm page with only one pte
  1439. * pointing to it: so break it.
  1440. */
  1441. if (err)
  1442. break_cow(rmap_item);
  1443. }
  1444. return err ? NULL : page_folio(page);
  1445. }
  1446. static __always_inline
  1447. bool __is_page_sharing_candidate(struct ksm_stable_node *stable_node, int offset)
  1448. {
  1449. VM_BUG_ON(stable_node->rmap_hlist_len < 0);
  1450. /*
  1451. * Check that at least one mapping still exists, otherwise
  1452. * there's no much point to merge and share with this
  1453. * stable_node, as the underlying tree_page of the other
  1454. * sharer is going to be freed soon.
  1455. */
  1456. return stable_node->rmap_hlist_len &&
  1457. stable_node->rmap_hlist_len + offset < ksm_max_page_sharing;
  1458. }
  1459. static __always_inline
  1460. bool is_page_sharing_candidate(struct ksm_stable_node *stable_node)
  1461. {
  1462. return __is_page_sharing_candidate(stable_node, 0);
  1463. }
  1464. static struct folio *stable_node_dup(struct ksm_stable_node **_stable_node_dup,
  1465. struct ksm_stable_node **_stable_node,
  1466. struct rb_root *root,
  1467. bool prune_stale_stable_nodes)
  1468. {
  1469. struct ksm_stable_node *dup, *found = NULL, *stable_node = *_stable_node;
  1470. struct hlist_node *hlist_safe;
  1471. struct folio *folio, *tree_folio = NULL;
  1472. int found_rmap_hlist_len;
  1473. if (!prune_stale_stable_nodes ||
  1474. time_before(jiffies, stable_node->chain_prune_time +
  1475. msecs_to_jiffies(
  1476. ksm_stable_node_chains_prune_millisecs)))
  1477. prune_stale_stable_nodes = false;
  1478. else
  1479. stable_node->chain_prune_time = jiffies;
  1480. hlist_for_each_entry_safe(dup, hlist_safe,
  1481. &stable_node->hlist, hlist_dup) {
  1482. cond_resched();
  1483. /*
  1484. * We must walk all stable_node_dup to prune the stale
  1485. * stable nodes during lookup.
  1486. *
  1487. * ksm_get_folio can drop the nodes from the
  1488. * stable_node->hlist if they point to freed pages
  1489. * (that's why we do a _safe walk). The "dup"
  1490. * stable_node parameter itself will be freed from
  1491. * under us if it returns NULL.
  1492. */
  1493. folio = ksm_get_folio(dup, KSM_GET_FOLIO_NOLOCK);
  1494. if (!folio)
  1495. continue;
  1496. /* Pick the best candidate if possible. */
  1497. if (!found || (is_page_sharing_candidate(dup) &&
  1498. (!is_page_sharing_candidate(found) ||
  1499. dup->rmap_hlist_len > found_rmap_hlist_len))) {
  1500. if (found)
  1501. folio_put(tree_folio);
  1502. found = dup;
  1503. found_rmap_hlist_len = found->rmap_hlist_len;
  1504. tree_folio = folio;
  1505. /* skip put_page for found candidate */
  1506. if (!prune_stale_stable_nodes &&
  1507. is_page_sharing_candidate(found))
  1508. break;
  1509. continue;
  1510. }
  1511. folio_put(folio);
  1512. }
  1513. if (found) {
  1514. if (hlist_is_singular_node(&found->hlist_dup, &stable_node->hlist)) {
  1515. /*
  1516. * If there's not just one entry it would
  1517. * corrupt memory, better BUG_ON. In KSM
  1518. * context with no lock held it's not even
  1519. * fatal.
  1520. */
  1521. BUG_ON(stable_node->hlist.first->next);
  1522. /*
  1523. * There's just one entry and it is below the
  1524. * deduplication limit so drop the chain.
  1525. */
  1526. rb_replace_node(&stable_node->node, &found->node,
  1527. root);
  1528. free_stable_node(stable_node);
  1529. ksm_stable_node_chains--;
  1530. ksm_stable_node_dups--;
  1531. /*
  1532. * NOTE: the caller depends on the stable_node
  1533. * to be equal to stable_node_dup if the chain
  1534. * was collapsed.
  1535. */
  1536. *_stable_node = found;
  1537. /*
  1538. * Just for robustness, as stable_node is
  1539. * otherwise left as a stable pointer, the
  1540. * compiler shall optimize it away at build
  1541. * time.
  1542. */
  1543. stable_node = NULL;
  1544. } else if (stable_node->hlist.first != &found->hlist_dup &&
  1545. __is_page_sharing_candidate(found, 1)) {
  1546. /*
  1547. * If the found stable_node dup can accept one
  1548. * more future merge (in addition to the one
  1549. * that is underway) and is not at the head of
  1550. * the chain, put it there so next search will
  1551. * be quicker in the !prune_stale_stable_nodes
  1552. * case.
  1553. *
  1554. * NOTE: it would be inaccurate to use nr > 1
  1555. * instead of checking the hlist.first pointer
  1556. * directly, because in the
  1557. * prune_stale_stable_nodes case "nr" isn't
  1558. * the position of the found dup in the chain,
  1559. * but the total number of dups in the chain.
  1560. */
  1561. hlist_del(&found->hlist_dup);
  1562. hlist_add_head(&found->hlist_dup,
  1563. &stable_node->hlist);
  1564. }
  1565. } else {
  1566. /* Its hlist must be empty if no one found. */
  1567. free_stable_node_chain(stable_node, root);
  1568. }
  1569. *_stable_node_dup = found;
  1570. return tree_folio;
  1571. }
  1572. /*
  1573. * Like for ksm_get_folio, this function can free the *_stable_node and
  1574. * *_stable_node_dup if the returned tree_page is NULL.
  1575. *
  1576. * It can also free and overwrite *_stable_node with the found
  1577. * stable_node_dup if the chain is collapsed (in which case
  1578. * *_stable_node will be equal to *_stable_node_dup like if the chain
  1579. * never existed). It's up to the caller to verify tree_page is not
  1580. * NULL before dereferencing *_stable_node or *_stable_node_dup.
  1581. *
  1582. * *_stable_node_dup is really a second output parameter of this
  1583. * function and will be overwritten in all cases, the caller doesn't
  1584. * need to initialize it.
  1585. */
  1586. static struct folio *__stable_node_chain(struct ksm_stable_node **_stable_node_dup,
  1587. struct ksm_stable_node **_stable_node,
  1588. struct rb_root *root,
  1589. bool prune_stale_stable_nodes)
  1590. {
  1591. struct ksm_stable_node *stable_node = *_stable_node;
  1592. if (!is_stable_node_chain(stable_node)) {
  1593. *_stable_node_dup = stable_node;
  1594. return ksm_get_folio(stable_node, KSM_GET_FOLIO_NOLOCK);
  1595. }
  1596. return stable_node_dup(_stable_node_dup, _stable_node, root,
  1597. prune_stale_stable_nodes);
  1598. }
  1599. static __always_inline struct folio *chain_prune(struct ksm_stable_node **s_n_d,
  1600. struct ksm_stable_node **s_n,
  1601. struct rb_root *root)
  1602. {
  1603. return __stable_node_chain(s_n_d, s_n, root, true);
  1604. }
  1605. static __always_inline struct folio *chain(struct ksm_stable_node **s_n_d,
  1606. struct ksm_stable_node **s_n,
  1607. struct rb_root *root)
  1608. {
  1609. return __stable_node_chain(s_n_d, s_n, root, false);
  1610. }
  1611. /*
  1612. * stable_tree_search - search for page inside the stable tree
  1613. *
  1614. * This function checks if there is a page inside the stable tree
  1615. * with identical content to the page that we are scanning right now.
  1616. *
  1617. * This function returns the stable tree node of identical content if found,
  1618. * -EBUSY if the stable node's page is being migrated, NULL otherwise.
  1619. */
  1620. static struct folio *stable_tree_search(struct page *page)
  1621. {
  1622. int nid;
  1623. struct rb_root *root;
  1624. struct rb_node **new;
  1625. struct rb_node *parent;
  1626. struct ksm_stable_node *stable_node, *stable_node_dup;
  1627. struct ksm_stable_node *page_node;
  1628. struct folio *folio;
  1629. folio = page_folio(page);
  1630. page_node = folio_stable_node(folio);
  1631. if (page_node && page_node->head != &migrate_nodes) {
  1632. /* ksm page forked */
  1633. folio_get(folio);
  1634. return folio;
  1635. }
  1636. nid = get_kpfn_nid(folio_pfn(folio));
  1637. root = root_stable_tree + nid;
  1638. again:
  1639. new = &root->rb_node;
  1640. parent = NULL;
  1641. while (*new) {
  1642. struct folio *tree_folio;
  1643. int ret;
  1644. cond_resched();
  1645. stable_node = rb_entry(*new, struct ksm_stable_node, node);
  1646. tree_folio = chain_prune(&stable_node_dup, &stable_node, root);
  1647. if (!tree_folio) {
  1648. /*
  1649. * If we walked over a stale stable_node,
  1650. * ksm_get_folio() will call rb_erase() and it
  1651. * may rebalance the tree from under us. So
  1652. * restart the search from scratch. Returning
  1653. * NULL would be safe too, but we'd generate
  1654. * false negative insertions just because some
  1655. * stable_node was stale.
  1656. */
  1657. goto again;
  1658. }
  1659. ret = memcmp_pages(page, &tree_folio->page);
  1660. folio_put(tree_folio);
  1661. parent = *new;
  1662. if (ret < 0)
  1663. new = &parent->rb_left;
  1664. else if (ret > 0)
  1665. new = &parent->rb_right;
  1666. else {
  1667. if (page_node) {
  1668. VM_BUG_ON(page_node->head != &migrate_nodes);
  1669. /*
  1670. * If the mapcount of our migrated KSM folio is
  1671. * at most 1, we can merge it with another
  1672. * KSM folio where we know that we have space
  1673. * for one more mapping without exceeding the
  1674. * ksm_max_page_sharing limit: see
  1675. * chain_prune(). This way, we can avoid adding
  1676. * this stable node to the chain.
  1677. */
  1678. if (folio_mapcount(folio) > 1)
  1679. goto chain_append;
  1680. }
  1681. if (!is_page_sharing_candidate(stable_node_dup)) {
  1682. /*
  1683. * If the stable_node is a chain and
  1684. * we got a payload match in memcmp
  1685. * but we cannot merge the scanned
  1686. * page in any of the existing
  1687. * stable_node dups because they're
  1688. * all full, we need to wait the
  1689. * scanned page to find itself a match
  1690. * in the unstable tree to create a
  1691. * brand new KSM page to add later to
  1692. * the dups of this stable_node.
  1693. */
  1694. return NULL;
  1695. }
  1696. /*
  1697. * Lock and unlock the stable_node's page (which
  1698. * might already have been migrated) so that page
  1699. * migration is sure to notice its raised count.
  1700. * It would be more elegant to return stable_node
  1701. * than kpage, but that involves more changes.
  1702. */
  1703. tree_folio = ksm_get_folio(stable_node_dup,
  1704. KSM_GET_FOLIO_TRYLOCK);
  1705. if (PTR_ERR(tree_folio) == -EBUSY)
  1706. return ERR_PTR(-EBUSY);
  1707. if (unlikely(!tree_folio))
  1708. /*
  1709. * The tree may have been rebalanced,
  1710. * so re-evaluate parent and new.
  1711. */
  1712. goto again;
  1713. folio_unlock(tree_folio);
  1714. if (get_kpfn_nid(stable_node_dup->kpfn) !=
  1715. NUMA(stable_node_dup->nid)) {
  1716. folio_put(tree_folio);
  1717. goto replace;
  1718. }
  1719. return tree_folio;
  1720. }
  1721. }
  1722. if (!page_node)
  1723. return NULL;
  1724. list_del(&page_node->list);
  1725. DO_NUMA(page_node->nid = nid);
  1726. rb_link_node(&page_node->node, parent, new);
  1727. rb_insert_color(&page_node->node, root);
  1728. out:
  1729. if (is_page_sharing_candidate(page_node)) {
  1730. folio_get(folio);
  1731. return folio;
  1732. } else
  1733. return NULL;
  1734. replace:
  1735. /*
  1736. * If stable_node was a chain and chain_prune collapsed it,
  1737. * stable_node has been updated to be the new regular
  1738. * stable_node. A collapse of the chain is indistinguishable
  1739. * from the case there was no chain in the stable
  1740. * rbtree. Otherwise stable_node is the chain and
  1741. * stable_node_dup is the dup to replace.
  1742. */
  1743. if (stable_node_dup == stable_node) {
  1744. VM_BUG_ON(is_stable_node_chain(stable_node_dup));
  1745. VM_BUG_ON(is_stable_node_dup(stable_node_dup));
  1746. /* there is no chain */
  1747. if (page_node) {
  1748. VM_BUG_ON(page_node->head != &migrate_nodes);
  1749. list_del(&page_node->list);
  1750. DO_NUMA(page_node->nid = nid);
  1751. rb_replace_node(&stable_node_dup->node,
  1752. &page_node->node,
  1753. root);
  1754. if (is_page_sharing_candidate(page_node))
  1755. folio_get(folio);
  1756. else
  1757. folio = NULL;
  1758. } else {
  1759. rb_erase(&stable_node_dup->node, root);
  1760. folio = NULL;
  1761. }
  1762. } else {
  1763. VM_BUG_ON(!is_stable_node_chain(stable_node));
  1764. __stable_node_dup_del(stable_node_dup);
  1765. if (page_node) {
  1766. VM_BUG_ON(page_node->head != &migrate_nodes);
  1767. list_del(&page_node->list);
  1768. DO_NUMA(page_node->nid = nid);
  1769. stable_node_chain_add_dup(page_node, stable_node);
  1770. if (is_page_sharing_candidate(page_node))
  1771. folio_get(folio);
  1772. else
  1773. folio = NULL;
  1774. } else {
  1775. folio = NULL;
  1776. }
  1777. }
  1778. stable_node_dup->head = &migrate_nodes;
  1779. list_add(&stable_node_dup->list, stable_node_dup->head);
  1780. return folio;
  1781. chain_append:
  1782. /*
  1783. * If stable_node was a chain and chain_prune collapsed it,
  1784. * stable_node has been updated to be the new regular
  1785. * stable_node. A collapse of the chain is indistinguishable
  1786. * from the case there was no chain in the stable
  1787. * rbtree. Otherwise stable_node is the chain and
  1788. * stable_node_dup is the dup to replace.
  1789. */
  1790. if (stable_node_dup == stable_node) {
  1791. VM_BUG_ON(is_stable_node_dup(stable_node_dup));
  1792. /* chain is missing so create it */
  1793. stable_node = alloc_stable_node_chain(stable_node_dup,
  1794. root);
  1795. if (!stable_node)
  1796. return NULL;
  1797. }
  1798. /*
  1799. * Add this stable_node dup that was
  1800. * migrated to the stable_node chain
  1801. * of the current nid for this page
  1802. * content.
  1803. */
  1804. VM_BUG_ON(!is_stable_node_dup(stable_node_dup));
  1805. VM_BUG_ON(page_node->head != &migrate_nodes);
  1806. list_del(&page_node->list);
  1807. DO_NUMA(page_node->nid = nid);
  1808. stable_node_chain_add_dup(page_node, stable_node);
  1809. goto out;
  1810. }
  1811. /*
  1812. * stable_tree_insert - insert stable tree node pointing to new ksm page
  1813. * into the stable tree.
  1814. *
  1815. * This function returns the stable tree node just allocated on success,
  1816. * NULL otherwise.
  1817. */
  1818. static struct ksm_stable_node *stable_tree_insert(struct folio *kfolio)
  1819. {
  1820. int nid;
  1821. unsigned long kpfn;
  1822. struct rb_root *root;
  1823. struct rb_node **new;
  1824. struct rb_node *parent;
  1825. struct ksm_stable_node *stable_node, *stable_node_dup;
  1826. bool need_chain = false;
  1827. kpfn = folio_pfn(kfolio);
  1828. nid = get_kpfn_nid(kpfn);
  1829. root = root_stable_tree + nid;
  1830. again:
  1831. parent = NULL;
  1832. new = &root->rb_node;
  1833. while (*new) {
  1834. struct folio *tree_folio;
  1835. int ret;
  1836. cond_resched();
  1837. stable_node = rb_entry(*new, struct ksm_stable_node, node);
  1838. tree_folio = chain(&stable_node_dup, &stable_node, root);
  1839. if (!tree_folio) {
  1840. /*
  1841. * If we walked over a stale stable_node,
  1842. * ksm_get_folio() will call rb_erase() and it
  1843. * may rebalance the tree from under us. So
  1844. * restart the search from scratch. Returning
  1845. * NULL would be safe too, but we'd generate
  1846. * false negative insertions just because some
  1847. * stable_node was stale.
  1848. */
  1849. goto again;
  1850. }
  1851. ret = memcmp_pages(&kfolio->page, &tree_folio->page);
  1852. folio_put(tree_folio);
  1853. parent = *new;
  1854. if (ret < 0)
  1855. new = &parent->rb_left;
  1856. else if (ret > 0)
  1857. new = &parent->rb_right;
  1858. else {
  1859. need_chain = true;
  1860. break;
  1861. }
  1862. }
  1863. stable_node_dup = alloc_stable_node();
  1864. if (!stable_node_dup)
  1865. return NULL;
  1866. INIT_HLIST_HEAD(&stable_node_dup->hlist);
  1867. stable_node_dup->kpfn = kpfn;
  1868. stable_node_dup->rmap_hlist_len = 0;
  1869. DO_NUMA(stable_node_dup->nid = nid);
  1870. if (!need_chain) {
  1871. rb_link_node(&stable_node_dup->node, parent, new);
  1872. rb_insert_color(&stable_node_dup->node, root);
  1873. } else {
  1874. if (!is_stable_node_chain(stable_node)) {
  1875. struct ksm_stable_node *orig = stable_node;
  1876. /* chain is missing so create it */
  1877. stable_node = alloc_stable_node_chain(orig, root);
  1878. if (!stable_node) {
  1879. free_stable_node(stable_node_dup);
  1880. return NULL;
  1881. }
  1882. }
  1883. stable_node_chain_add_dup(stable_node_dup, stable_node);
  1884. }
  1885. folio_set_stable_node(kfolio, stable_node_dup);
  1886. return stable_node_dup;
  1887. }
  1888. /*
  1889. * unstable_tree_search_insert - search for identical page,
  1890. * else insert rmap_item into the unstable tree.
  1891. *
  1892. * This function searches for a page in the unstable tree identical to the
  1893. * page currently being scanned; and if no identical page is found in the
  1894. * tree, we insert rmap_item as a new object into the unstable tree.
  1895. *
  1896. * This function returns pointer to rmap_item found to be identical
  1897. * to the currently scanned page, NULL otherwise.
  1898. *
  1899. * This function does both searching and inserting, because they share
  1900. * the same walking algorithm in an rbtree.
  1901. */
  1902. static
  1903. struct ksm_rmap_item *unstable_tree_search_insert(struct ksm_rmap_item *rmap_item,
  1904. struct page *page,
  1905. struct page **tree_pagep)
  1906. {
  1907. struct rb_node **new;
  1908. struct rb_root *root;
  1909. struct rb_node *parent = NULL;
  1910. int nid;
  1911. nid = get_kpfn_nid(page_to_pfn(page));
  1912. root = root_unstable_tree + nid;
  1913. new = &root->rb_node;
  1914. while (*new) {
  1915. struct ksm_rmap_item *tree_rmap_item;
  1916. struct page *tree_page;
  1917. int ret;
  1918. cond_resched();
  1919. tree_rmap_item = rb_entry(*new, struct ksm_rmap_item, node);
  1920. tree_page = get_mergeable_page(tree_rmap_item);
  1921. if (!tree_page)
  1922. return NULL;
  1923. /*
  1924. * Don't substitute a ksm page for a forked page.
  1925. */
  1926. if (page == tree_page) {
  1927. put_page(tree_page);
  1928. return NULL;
  1929. }
  1930. ret = memcmp_pages(page, tree_page);
  1931. parent = *new;
  1932. if (ret < 0) {
  1933. put_page(tree_page);
  1934. new = &parent->rb_left;
  1935. } else if (ret > 0) {
  1936. put_page(tree_page);
  1937. new = &parent->rb_right;
  1938. } else if (!ksm_merge_across_nodes &&
  1939. page_to_nid(tree_page) != nid) {
  1940. /*
  1941. * If tree_page has been migrated to another NUMA node,
  1942. * it will be flushed out and put in the right unstable
  1943. * tree next time: only merge with it when across_nodes.
  1944. */
  1945. put_page(tree_page);
  1946. return NULL;
  1947. } else {
  1948. *tree_pagep = tree_page;
  1949. return tree_rmap_item;
  1950. }
  1951. }
  1952. rmap_item->address |= UNSTABLE_FLAG;
  1953. rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
  1954. DO_NUMA(rmap_item->nid = nid);
  1955. rb_link_node(&rmap_item->node, parent, new);
  1956. rb_insert_color(&rmap_item->node, root);
  1957. ksm_pages_unshared++;
  1958. return NULL;
  1959. }
  1960. /*
  1961. * stable_tree_append - add another rmap_item to the linked list of
  1962. * rmap_items hanging off a given node of the stable tree, all sharing
  1963. * the same ksm page.
  1964. */
  1965. static void stable_tree_append(struct ksm_rmap_item *rmap_item,
  1966. struct ksm_stable_node *stable_node,
  1967. bool max_page_sharing_bypass)
  1968. {
  1969. /*
  1970. * rmap won't find this mapping if we don't insert the
  1971. * rmap_item in the right stable_node
  1972. * duplicate. page_migration could break later if rmap breaks,
  1973. * so we can as well crash here. We really need to check for
  1974. * rmap_hlist_len == STABLE_NODE_CHAIN, but we can as well check
  1975. * for other negative values as an underflow if detected here
  1976. * for the first time (and not when decreasing rmap_hlist_len)
  1977. * would be sign of memory corruption in the stable_node.
  1978. */
  1979. BUG_ON(stable_node->rmap_hlist_len < 0);
  1980. stable_node->rmap_hlist_len++;
  1981. if (!max_page_sharing_bypass)
  1982. /* possibly non fatal but unexpected overflow, only warn */
  1983. WARN_ON_ONCE(stable_node->rmap_hlist_len >
  1984. ksm_max_page_sharing);
  1985. rmap_item->head = stable_node;
  1986. rmap_item->address |= STABLE_FLAG;
  1987. hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
  1988. if (rmap_item->hlist.next)
  1989. ksm_pages_sharing++;
  1990. else
  1991. ksm_pages_shared++;
  1992. rmap_item->mm->ksm_merging_pages++;
  1993. }
  1994. /*
  1995. * cmp_and_merge_page - first see if page can be merged into the stable tree;
  1996. * if not, compare checksum to previous and if it's the same, see if page can
  1997. * be inserted into the unstable tree, or merged with a page already there and
  1998. * both transferred to the stable tree.
  1999. *
  2000. * @page: the page that we are searching identical page to.
  2001. * @rmap_item: the reverse mapping into the virtual address of this page
  2002. */
  2003. static void cmp_and_merge_page(struct page *page, struct ksm_rmap_item *rmap_item)
  2004. {
  2005. struct folio *folio = page_folio(page);
  2006. struct ksm_rmap_item *tree_rmap_item;
  2007. struct page *tree_page = NULL;
  2008. struct ksm_stable_node *stable_node;
  2009. struct folio *kfolio;
  2010. unsigned int checksum;
  2011. int err;
  2012. bool max_page_sharing_bypass = false;
  2013. stable_node = folio_stable_node(folio);
  2014. if (stable_node) {
  2015. if (stable_node->head != &migrate_nodes &&
  2016. get_kpfn_nid(READ_ONCE(stable_node->kpfn)) !=
  2017. NUMA(stable_node->nid)) {
  2018. stable_node_dup_del(stable_node);
  2019. stable_node->head = &migrate_nodes;
  2020. list_add(&stable_node->list, stable_node->head);
  2021. }
  2022. if (stable_node->head != &migrate_nodes &&
  2023. rmap_item->head == stable_node)
  2024. return;
  2025. /*
  2026. * If it's a KSM fork, allow it to go over the sharing limit
  2027. * without warnings.
  2028. */
  2029. if (!is_page_sharing_candidate(stable_node))
  2030. max_page_sharing_bypass = true;
  2031. } else {
  2032. remove_rmap_item_from_tree(rmap_item);
  2033. /*
  2034. * If the hash value of the page has changed from the last time
  2035. * we calculated it, this page is changing frequently: therefore we
  2036. * don't want to insert it in the unstable tree, and we don't want
  2037. * to waste our time searching for something identical to it there.
  2038. */
  2039. checksum = calc_checksum(page);
  2040. if (rmap_item->oldchecksum != checksum) {
  2041. rmap_item->oldchecksum = checksum;
  2042. return;
  2043. }
  2044. if (!try_to_merge_with_zero_page(rmap_item, page))
  2045. return;
  2046. }
  2047. /* Start by searching for the folio in the stable tree */
  2048. kfolio = stable_tree_search(page);
  2049. if (kfolio == folio && rmap_item->head == stable_node) {
  2050. folio_put(kfolio);
  2051. return;
  2052. }
  2053. remove_rmap_item_from_tree(rmap_item);
  2054. if (kfolio) {
  2055. if (kfolio == ERR_PTR(-EBUSY))
  2056. return;
  2057. err = try_to_merge_with_ksm_page(rmap_item, page, &kfolio->page);
  2058. if (!err) {
  2059. /*
  2060. * The page was successfully merged:
  2061. * add its rmap_item to the stable tree.
  2062. */
  2063. folio_lock(kfolio);
  2064. stable_tree_append(rmap_item, folio_stable_node(kfolio),
  2065. max_page_sharing_bypass);
  2066. folio_unlock(kfolio);
  2067. }
  2068. folio_put(kfolio);
  2069. return;
  2070. }
  2071. tree_rmap_item =
  2072. unstable_tree_search_insert(rmap_item, page, &tree_page);
  2073. if (tree_rmap_item) {
  2074. bool split;
  2075. kfolio = try_to_merge_two_pages(rmap_item, page,
  2076. tree_rmap_item, tree_page);
  2077. /*
  2078. * If both pages we tried to merge belong to the same compound
  2079. * page, then we actually ended up increasing the reference
  2080. * count of the same compound page twice, and split_huge_page
  2081. * failed.
  2082. * Here we set a flag if that happened, and we use it later to
  2083. * try split_huge_page again. Since we call put_page right
  2084. * afterwards, the reference count will be correct and
  2085. * split_huge_page should succeed.
  2086. */
  2087. split = PageTransCompound(page)
  2088. && compound_head(page) == compound_head(tree_page);
  2089. put_page(tree_page);
  2090. if (kfolio) {
  2091. /*
  2092. * The pages were successfully merged: insert new
  2093. * node in the stable tree and add both rmap_items.
  2094. */
  2095. folio_lock(kfolio);
  2096. stable_node = stable_tree_insert(kfolio);
  2097. if (stable_node) {
  2098. stable_tree_append(tree_rmap_item, stable_node,
  2099. false);
  2100. stable_tree_append(rmap_item, stable_node,
  2101. false);
  2102. }
  2103. folio_unlock(kfolio);
  2104. /*
  2105. * If we fail to insert the page into the stable tree,
  2106. * we will have 2 virtual addresses that are pointing
  2107. * to a ksm page left outside the stable tree,
  2108. * in which case we need to break_cow on both.
  2109. */
  2110. if (!stable_node) {
  2111. break_cow(tree_rmap_item);
  2112. break_cow(rmap_item);
  2113. }
  2114. } else if (split) {
  2115. /*
  2116. * We are here if we tried to merge two pages and
  2117. * failed because they both belonged to the same
  2118. * compound page. We will split the page now, but no
  2119. * merging will take place.
  2120. * We do not want to add the cost of a full lock; if
  2121. * the page is locked, it is better to skip it and
  2122. * perhaps try again later.
  2123. */
  2124. if (!folio_trylock(folio))
  2125. return;
  2126. split_huge_page(page);
  2127. folio = page_folio(page);
  2128. folio_unlock(folio);
  2129. }
  2130. }
  2131. }
  2132. static struct ksm_rmap_item *get_next_rmap_item(struct ksm_mm_slot *mm_slot,
  2133. struct ksm_rmap_item **rmap_list,
  2134. unsigned long addr)
  2135. {
  2136. struct ksm_rmap_item *rmap_item;
  2137. while (*rmap_list) {
  2138. rmap_item = *rmap_list;
  2139. if ((rmap_item->address & PAGE_MASK) == addr)
  2140. return rmap_item;
  2141. if (rmap_item->address > addr)
  2142. break;
  2143. *rmap_list = rmap_item->rmap_list;
  2144. remove_rmap_item_from_tree(rmap_item);
  2145. free_rmap_item(rmap_item);
  2146. }
  2147. rmap_item = alloc_rmap_item();
  2148. if (rmap_item) {
  2149. /* It has already been zeroed */
  2150. rmap_item->mm = mm_slot->slot.mm;
  2151. rmap_item->mm->ksm_rmap_items++;
  2152. rmap_item->address = addr;
  2153. rmap_item->rmap_list = *rmap_list;
  2154. *rmap_list = rmap_item;
  2155. }
  2156. return rmap_item;
  2157. }
  2158. /*
  2159. * Calculate skip age for the ksm page age. The age determines how often
  2160. * de-duplicating has already been tried unsuccessfully. If the age is
  2161. * smaller, the scanning of this page is skipped for less scans.
  2162. *
  2163. * @age: rmap_item age of page
  2164. */
  2165. static unsigned int skip_age(rmap_age_t age)
  2166. {
  2167. if (age <= 3)
  2168. return 1;
  2169. if (age <= 5)
  2170. return 2;
  2171. if (age <= 8)
  2172. return 4;
  2173. return 8;
  2174. }
  2175. /*
  2176. * Determines if a page should be skipped for the current scan.
  2177. *
  2178. * @folio: folio containing the page to check
  2179. * @rmap_item: associated rmap_item of page
  2180. */
  2181. static bool should_skip_rmap_item(struct folio *folio,
  2182. struct ksm_rmap_item *rmap_item)
  2183. {
  2184. rmap_age_t age;
  2185. if (!ksm_smart_scan)
  2186. return false;
  2187. /*
  2188. * Never skip pages that are already KSM; pages cmp_and_merge_page()
  2189. * will essentially ignore them, but we still have to process them
  2190. * properly.
  2191. */
  2192. if (folio_test_ksm(folio))
  2193. return false;
  2194. age = rmap_item->age;
  2195. if (age != U8_MAX)
  2196. rmap_item->age++;
  2197. /*
  2198. * Smaller ages are not skipped, they need to get a chance to go
  2199. * through the different phases of the KSM merging.
  2200. */
  2201. if (age < 3)
  2202. return false;
  2203. /*
  2204. * Are we still allowed to skip? If not, then don't skip it
  2205. * and determine how much more often we are allowed to skip next.
  2206. */
  2207. if (!rmap_item->remaining_skips) {
  2208. rmap_item->remaining_skips = skip_age(age);
  2209. return false;
  2210. }
  2211. /* Skip this page */
  2212. ksm_pages_skipped++;
  2213. rmap_item->remaining_skips--;
  2214. remove_rmap_item_from_tree(rmap_item);
  2215. return true;
  2216. }
  2217. struct ksm_next_page_arg {
  2218. struct folio *folio;
  2219. struct page *page;
  2220. unsigned long addr;
  2221. };
  2222. static int ksm_next_page_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long end,
  2223. struct mm_walk *walk)
  2224. {
  2225. struct ksm_next_page_arg *private = walk->private;
  2226. struct vm_area_struct *vma = walk->vma;
  2227. pte_t *start_ptep = NULL, *ptep, pte;
  2228. struct mm_struct *mm = walk->mm;
  2229. struct folio *folio;
  2230. struct page *page;
  2231. spinlock_t *ptl;
  2232. pmd_t pmd;
  2233. if (ksm_test_exit(mm))
  2234. return 0;
  2235. cond_resched();
  2236. pmd = pmdp_get_lockless(pmdp);
  2237. if (!pmd_present(pmd))
  2238. return 0;
  2239. if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && pmd_leaf(pmd)) {
  2240. ptl = pmd_lock(mm, pmdp);
  2241. pmd = pmdp_get(pmdp);
  2242. if (!pmd_present(pmd)) {
  2243. goto not_found_unlock;
  2244. } else if (pmd_leaf(pmd)) {
  2245. page = vm_normal_page_pmd(vma, addr, pmd);
  2246. if (!page)
  2247. goto not_found_unlock;
  2248. folio = page_folio(page);
  2249. if (folio_is_zone_device(folio) || !folio_test_anon(folio))
  2250. goto not_found_unlock;
  2251. page += ((addr & (PMD_SIZE - 1)) >> PAGE_SHIFT);
  2252. goto found_unlock;
  2253. }
  2254. spin_unlock(ptl);
  2255. }
  2256. start_ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
  2257. if (!start_ptep)
  2258. return 0;
  2259. for (ptep = start_ptep; addr < end; ptep++, addr += PAGE_SIZE) {
  2260. pte = ptep_get(ptep);
  2261. if (!pte_present(pte))
  2262. continue;
  2263. page = vm_normal_page(vma, addr, pte);
  2264. if (!page)
  2265. continue;
  2266. folio = page_folio(page);
  2267. if (folio_is_zone_device(folio) || !folio_test_anon(folio))
  2268. continue;
  2269. goto found_unlock;
  2270. }
  2271. not_found_unlock:
  2272. spin_unlock(ptl);
  2273. if (start_ptep)
  2274. pte_unmap(start_ptep);
  2275. return 0;
  2276. found_unlock:
  2277. folio_get(folio);
  2278. spin_unlock(ptl);
  2279. if (start_ptep)
  2280. pte_unmap(start_ptep);
  2281. private->page = page;
  2282. private->folio = folio;
  2283. private->addr = addr;
  2284. return 1;
  2285. }
  2286. static struct mm_walk_ops ksm_next_page_ops = {
  2287. .pmd_entry = ksm_next_page_pmd_entry,
  2288. .walk_lock = PGWALK_RDLOCK,
  2289. };
  2290. static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
  2291. {
  2292. struct mm_struct *mm;
  2293. struct ksm_mm_slot *mm_slot;
  2294. struct mm_slot *slot;
  2295. struct vm_area_struct *vma;
  2296. struct ksm_rmap_item *rmap_item;
  2297. struct vma_iterator vmi;
  2298. int nid;
  2299. if (list_empty(&ksm_mm_head.slot.mm_node))
  2300. return NULL;
  2301. mm_slot = ksm_scan.mm_slot;
  2302. if (mm_slot == &ksm_mm_head) {
  2303. advisor_start_scan();
  2304. trace_ksm_start_scan(ksm_scan.seqnr, ksm_rmap_items);
  2305. /*
  2306. * A number of pages can hang around indefinitely in per-cpu
  2307. * LRU cache, raised page count preventing write_protect_page
  2308. * from merging them. Though it doesn't really matter much,
  2309. * it is puzzling to see some stuck in pages_volatile until
  2310. * other activity jostles them out, and they also prevented
  2311. * LTP's KSM test from succeeding deterministically; so drain
  2312. * them here (here rather than on entry to ksm_do_scan(),
  2313. * so we don't IPI too often when pages_to_scan is set low).
  2314. */
  2315. lru_add_drain_all();
  2316. /*
  2317. * Whereas stale stable_nodes on the stable_tree itself
  2318. * get pruned in the regular course of stable_tree_search(),
  2319. * those moved out to the migrate_nodes list can accumulate:
  2320. * so prune them once before each full scan.
  2321. */
  2322. if (!ksm_merge_across_nodes) {
  2323. struct ksm_stable_node *stable_node, *next;
  2324. struct folio *folio;
  2325. list_for_each_entry_safe(stable_node, next,
  2326. &migrate_nodes, list) {
  2327. folio = ksm_get_folio(stable_node,
  2328. KSM_GET_FOLIO_NOLOCK);
  2329. if (folio)
  2330. folio_put(folio);
  2331. cond_resched();
  2332. }
  2333. }
  2334. for (nid = 0; nid < ksm_nr_node_ids; nid++)
  2335. root_unstable_tree[nid] = RB_ROOT;
  2336. spin_lock(&ksm_mmlist_lock);
  2337. slot = list_entry(mm_slot->slot.mm_node.next,
  2338. struct mm_slot, mm_node);
  2339. mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  2340. ksm_scan.mm_slot = mm_slot;
  2341. spin_unlock(&ksm_mmlist_lock);
  2342. /*
  2343. * Although we tested list_empty() above, a racing __ksm_exit
  2344. * of the last mm on the list may have removed it since then.
  2345. */
  2346. if (mm_slot == &ksm_mm_head)
  2347. return NULL;
  2348. next_mm:
  2349. ksm_scan.address = 0;
  2350. ksm_scan.rmap_list = &mm_slot->rmap_list;
  2351. }
  2352. slot = &mm_slot->slot;
  2353. mm = slot->mm;
  2354. vma_iter_init(&vmi, mm, ksm_scan.address);
  2355. mmap_read_lock(mm);
  2356. if (ksm_test_exit(mm))
  2357. goto no_vmas;
  2358. for_each_vma(vmi, vma) {
  2359. if (!(vma->vm_flags & VM_MERGEABLE))
  2360. continue;
  2361. if (ksm_scan.address < vma->vm_start)
  2362. ksm_scan.address = vma->vm_start;
  2363. if (!vma->anon_vma)
  2364. ksm_scan.address = vma->vm_end;
  2365. while (ksm_scan.address < vma->vm_end) {
  2366. struct ksm_next_page_arg ksm_next_page_arg;
  2367. struct page *tmp_page = NULL;
  2368. struct folio *folio;
  2369. if (ksm_test_exit(mm))
  2370. break;
  2371. int found;
  2372. found = walk_page_range_vma(vma, ksm_scan.address,
  2373. vma->vm_end,
  2374. &ksm_next_page_ops,
  2375. &ksm_next_page_arg);
  2376. if (found > 0) {
  2377. folio = ksm_next_page_arg.folio;
  2378. tmp_page = ksm_next_page_arg.page;
  2379. ksm_scan.address = ksm_next_page_arg.addr;
  2380. } else {
  2381. VM_WARN_ON_ONCE(found < 0);
  2382. ksm_scan.address = vma->vm_end - PAGE_SIZE;
  2383. }
  2384. if (tmp_page) {
  2385. flush_anon_page(vma, tmp_page, ksm_scan.address);
  2386. flush_dcache_page(tmp_page);
  2387. rmap_item = get_next_rmap_item(mm_slot,
  2388. ksm_scan.rmap_list, ksm_scan.address);
  2389. if (rmap_item) {
  2390. ksm_scan.rmap_list =
  2391. &rmap_item->rmap_list;
  2392. if (should_skip_rmap_item(folio, rmap_item)) {
  2393. folio_put(folio);
  2394. goto next_page;
  2395. }
  2396. ksm_scan.address += PAGE_SIZE;
  2397. *page = tmp_page;
  2398. } else {
  2399. folio_put(folio);
  2400. }
  2401. mmap_read_unlock(mm);
  2402. return rmap_item;
  2403. }
  2404. next_page:
  2405. ksm_scan.address += PAGE_SIZE;
  2406. cond_resched();
  2407. }
  2408. }
  2409. if (ksm_test_exit(mm)) {
  2410. no_vmas:
  2411. ksm_scan.address = 0;
  2412. ksm_scan.rmap_list = &mm_slot->rmap_list;
  2413. }
  2414. /*
  2415. * Nuke all the rmap_items that are above this current rmap:
  2416. * because there were no VM_MERGEABLE vmas with such addresses.
  2417. */
  2418. remove_trailing_rmap_items(ksm_scan.rmap_list);
  2419. spin_lock(&ksm_mmlist_lock);
  2420. slot = list_entry(mm_slot->slot.mm_node.next,
  2421. struct mm_slot, mm_node);
  2422. ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  2423. if (ksm_scan.address == 0) {
  2424. /*
  2425. * We've completed a full scan of all vmas, holding mmap_lock
  2426. * throughout, and found no VM_MERGEABLE: so do the same as
  2427. * __ksm_exit does to remove this mm from all our lists now.
  2428. * This applies either when cleaning up after __ksm_exit
  2429. * (but beware: we can reach here even before __ksm_exit),
  2430. * or when all VM_MERGEABLE areas have been unmapped (and
  2431. * mmap_lock then protects against race with MADV_MERGEABLE).
  2432. */
  2433. hash_del(&mm_slot->slot.hash);
  2434. list_del(&mm_slot->slot.mm_node);
  2435. spin_unlock(&ksm_mmlist_lock);
  2436. mm_slot_free(mm_slot_cache, mm_slot);
  2437. /*
  2438. * Only clear MMF_VM_MERGEABLE. We must not clear
  2439. * MMF_VM_MERGE_ANY, because for those MMF_VM_MERGE_ANY process,
  2440. * perhaps their mm_struct has just been added to ksm_mm_slot
  2441. * list, and its process has not yet officially started running
  2442. * or has not yet performed mmap/brk to allocate anonymous VMAS.
  2443. */
  2444. mm_flags_clear(MMF_VM_MERGEABLE, mm);
  2445. mmap_read_unlock(mm);
  2446. mmdrop(mm);
  2447. } else {
  2448. mmap_read_unlock(mm);
  2449. /*
  2450. * mmap_read_unlock(mm) first because after
  2451. * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
  2452. * already have been freed under us by __ksm_exit()
  2453. * because the "mm_slot" is still hashed and
  2454. * ksm_scan.mm_slot doesn't point to it anymore.
  2455. */
  2456. spin_unlock(&ksm_mmlist_lock);
  2457. }
  2458. /* Repeat until we've completed scanning the whole list */
  2459. mm_slot = ksm_scan.mm_slot;
  2460. if (mm_slot != &ksm_mm_head)
  2461. goto next_mm;
  2462. advisor_stop_scan();
  2463. trace_ksm_stop_scan(ksm_scan.seqnr, ksm_rmap_items);
  2464. ksm_scan.seqnr++;
  2465. return NULL;
  2466. }
  2467. /**
  2468. * ksm_do_scan - the ksm scanner main worker function.
  2469. * @scan_npages: number of pages we want to scan before we return.
  2470. */
  2471. static void ksm_do_scan(unsigned int scan_npages)
  2472. {
  2473. struct ksm_rmap_item *rmap_item;
  2474. struct page *page;
  2475. while (scan_npages-- && likely(!freezing(current))) {
  2476. cond_resched();
  2477. rmap_item = scan_get_next_rmap_item(&page);
  2478. if (!rmap_item)
  2479. return;
  2480. cmp_and_merge_page(page, rmap_item);
  2481. put_page(page);
  2482. ksm_pages_scanned++;
  2483. }
  2484. }
  2485. static int ksmd_should_run(void)
  2486. {
  2487. return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.slot.mm_node);
  2488. }
  2489. static int ksm_scan_thread(void *nothing)
  2490. {
  2491. unsigned int sleep_ms;
  2492. set_freezable();
  2493. set_user_nice(current, 5);
  2494. while (!kthread_should_stop()) {
  2495. mutex_lock(&ksm_thread_mutex);
  2496. wait_while_offlining();
  2497. if (ksmd_should_run())
  2498. ksm_do_scan(ksm_thread_pages_to_scan);
  2499. mutex_unlock(&ksm_thread_mutex);
  2500. if (ksmd_should_run()) {
  2501. sleep_ms = READ_ONCE(ksm_thread_sleep_millisecs);
  2502. wait_event_freezable_timeout(ksm_iter_wait,
  2503. sleep_ms != READ_ONCE(ksm_thread_sleep_millisecs),
  2504. msecs_to_jiffies(sleep_ms));
  2505. } else {
  2506. wait_event_freezable(ksm_thread_wait,
  2507. ksmd_should_run() || kthread_should_stop());
  2508. }
  2509. }
  2510. return 0;
  2511. }
  2512. static bool __ksm_should_add_vma(const struct file *file, vm_flags_t vm_flags)
  2513. {
  2514. if (vm_flags & VM_MERGEABLE)
  2515. return false;
  2516. return ksm_compatible(file, vm_flags);
  2517. }
  2518. static void __ksm_add_vma(struct vm_area_struct *vma)
  2519. {
  2520. if (__ksm_should_add_vma(vma->vm_file, vma->vm_flags))
  2521. vm_flags_set(vma, VM_MERGEABLE);
  2522. }
  2523. static int __ksm_del_vma(struct vm_area_struct *vma)
  2524. {
  2525. int err;
  2526. if (!(vma->vm_flags & VM_MERGEABLE))
  2527. return 0;
  2528. if (vma->anon_vma) {
  2529. err = break_ksm(vma, vma->vm_start, vma->vm_end, true);
  2530. if (err)
  2531. return err;
  2532. }
  2533. vm_flags_clear(vma, VM_MERGEABLE);
  2534. return 0;
  2535. }
  2536. /**
  2537. * ksm_vma_flags - Update VMA flags to mark as mergeable if compatible
  2538. *
  2539. * @mm: Proposed VMA's mm_struct
  2540. * @file: Proposed VMA's file-backed mapping, if any.
  2541. * @vm_flags: Proposed VMA"s flags.
  2542. *
  2543. * Returns: @vm_flags possibly updated to mark mergeable.
  2544. */
  2545. vm_flags_t ksm_vma_flags(struct mm_struct *mm, const struct file *file,
  2546. vm_flags_t vm_flags)
  2547. {
  2548. if (mm_flags_test(MMF_VM_MERGE_ANY, mm) &&
  2549. __ksm_should_add_vma(file, vm_flags)) {
  2550. vm_flags |= VM_MERGEABLE;
  2551. /*
  2552. * Generally, the flags here always include MMF_VM_MERGEABLE.
  2553. * However, in rare cases, this flag may be cleared by ksmd who
  2554. * scans a cycle without finding any mergeable vma.
  2555. */
  2556. if (unlikely(!mm_flags_test(MMF_VM_MERGEABLE, mm)))
  2557. __ksm_enter(mm);
  2558. }
  2559. return vm_flags;
  2560. }
  2561. static void ksm_add_vmas(struct mm_struct *mm)
  2562. {
  2563. struct vm_area_struct *vma;
  2564. VMA_ITERATOR(vmi, mm, 0);
  2565. for_each_vma(vmi, vma)
  2566. __ksm_add_vma(vma);
  2567. }
  2568. static int ksm_del_vmas(struct mm_struct *mm)
  2569. {
  2570. struct vm_area_struct *vma;
  2571. int err;
  2572. VMA_ITERATOR(vmi, mm, 0);
  2573. for_each_vma(vmi, vma) {
  2574. err = __ksm_del_vma(vma);
  2575. if (err)
  2576. return err;
  2577. }
  2578. return 0;
  2579. }
  2580. /**
  2581. * ksm_enable_merge_any - Add mm to mm ksm list and enable merging on all
  2582. * compatible VMA's
  2583. *
  2584. * @mm: Pointer to mm
  2585. *
  2586. * Returns 0 on success, otherwise error code
  2587. */
  2588. int ksm_enable_merge_any(struct mm_struct *mm)
  2589. {
  2590. int err;
  2591. if (mm_flags_test(MMF_VM_MERGE_ANY, mm))
  2592. return 0;
  2593. if (!mm_flags_test(MMF_VM_MERGEABLE, mm)) {
  2594. err = __ksm_enter(mm);
  2595. if (err)
  2596. return err;
  2597. }
  2598. mm_flags_set(MMF_VM_MERGE_ANY, mm);
  2599. ksm_add_vmas(mm);
  2600. return 0;
  2601. }
  2602. /**
  2603. * ksm_disable_merge_any - Disable merging on all compatible VMA's of the mm,
  2604. * previously enabled via ksm_enable_merge_any().
  2605. *
  2606. * Disabling merging implies unmerging any merged pages, like setting
  2607. * MADV_UNMERGEABLE would. If unmerging fails, the whole operation fails and
  2608. * merging on all compatible VMA's remains enabled.
  2609. *
  2610. * @mm: Pointer to mm
  2611. *
  2612. * Returns 0 on success, otherwise error code
  2613. */
  2614. int ksm_disable_merge_any(struct mm_struct *mm)
  2615. {
  2616. int err;
  2617. if (!mm_flags_test(MMF_VM_MERGE_ANY, mm))
  2618. return 0;
  2619. err = ksm_del_vmas(mm);
  2620. if (err) {
  2621. ksm_add_vmas(mm);
  2622. return err;
  2623. }
  2624. mm_flags_clear(MMF_VM_MERGE_ANY, mm);
  2625. return 0;
  2626. }
  2627. int ksm_disable(struct mm_struct *mm)
  2628. {
  2629. mmap_assert_write_locked(mm);
  2630. if (!mm_flags_test(MMF_VM_MERGEABLE, mm))
  2631. return 0;
  2632. if (mm_flags_test(MMF_VM_MERGE_ANY, mm))
  2633. return ksm_disable_merge_any(mm);
  2634. return ksm_del_vmas(mm);
  2635. }
  2636. int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
  2637. unsigned long end, int advice, vm_flags_t *vm_flags)
  2638. {
  2639. struct mm_struct *mm = vma->vm_mm;
  2640. int err;
  2641. switch (advice) {
  2642. case MADV_MERGEABLE:
  2643. if (vma->vm_flags & VM_MERGEABLE)
  2644. return 0;
  2645. if (!vma_ksm_compatible(vma))
  2646. return 0;
  2647. if (!mm_flags_test(MMF_VM_MERGEABLE, mm)) {
  2648. err = __ksm_enter(mm);
  2649. if (err)
  2650. return err;
  2651. }
  2652. *vm_flags |= VM_MERGEABLE;
  2653. break;
  2654. case MADV_UNMERGEABLE:
  2655. if (!(*vm_flags & VM_MERGEABLE))
  2656. return 0; /* just ignore the advice */
  2657. if (vma->anon_vma) {
  2658. err = break_ksm(vma, start, end, true);
  2659. if (err)
  2660. return err;
  2661. }
  2662. *vm_flags &= ~VM_MERGEABLE;
  2663. break;
  2664. }
  2665. return 0;
  2666. }
  2667. EXPORT_SYMBOL_GPL(ksm_madvise);
  2668. int __ksm_enter(struct mm_struct *mm)
  2669. {
  2670. struct ksm_mm_slot *mm_slot;
  2671. struct mm_slot *slot;
  2672. int needs_wakeup;
  2673. mm_slot = mm_slot_alloc(mm_slot_cache);
  2674. if (!mm_slot)
  2675. return -ENOMEM;
  2676. slot = &mm_slot->slot;
  2677. /* Check ksm_run too? Would need tighter locking */
  2678. needs_wakeup = list_empty(&ksm_mm_head.slot.mm_node);
  2679. spin_lock(&ksm_mmlist_lock);
  2680. mm_slot_insert(mm_slots_hash, mm, slot);
  2681. /*
  2682. * When KSM_RUN_MERGE (or KSM_RUN_STOP),
  2683. * insert just behind the scanning cursor, to let the area settle
  2684. * down a little; when fork is followed by immediate exec, we don't
  2685. * want ksmd to waste time setting up and tearing down an rmap_list.
  2686. *
  2687. * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
  2688. * scanning cursor, otherwise KSM pages in newly forked mms will be
  2689. * missed: then we might as well insert at the end of the list.
  2690. */
  2691. if (ksm_run & KSM_RUN_UNMERGE)
  2692. list_add_tail(&slot->mm_node, &ksm_mm_head.slot.mm_node);
  2693. else
  2694. list_add_tail(&slot->mm_node, &ksm_scan.mm_slot->slot.mm_node);
  2695. spin_unlock(&ksm_mmlist_lock);
  2696. mm_flags_set(MMF_VM_MERGEABLE, mm);
  2697. mmgrab(mm);
  2698. if (needs_wakeup)
  2699. wake_up_interruptible(&ksm_thread_wait);
  2700. trace_ksm_enter(mm);
  2701. return 0;
  2702. }
  2703. void __ksm_exit(struct mm_struct *mm)
  2704. {
  2705. struct ksm_mm_slot *mm_slot = NULL;
  2706. struct mm_slot *slot;
  2707. int easy_to_free = 0;
  2708. /*
  2709. * This process is exiting: if it's straightforward (as is the
  2710. * case when ksmd was never running), free mm_slot immediately.
  2711. * But if it's at the cursor or has rmap_items linked to it, use
  2712. * mmap_lock to synchronize with any break_cows before pagetables
  2713. * are freed, and leave the mm_slot on the list for ksmd to free.
  2714. * Beware: ksm may already have noticed it exiting and freed the slot.
  2715. */
  2716. spin_lock(&ksm_mmlist_lock);
  2717. slot = mm_slot_lookup(mm_slots_hash, mm);
  2718. if (!slot)
  2719. goto unlock;
  2720. mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  2721. if (ksm_scan.mm_slot == mm_slot)
  2722. goto unlock;
  2723. if (!mm_slot->rmap_list) {
  2724. hash_del(&slot->hash);
  2725. list_del(&slot->mm_node);
  2726. easy_to_free = 1;
  2727. } else {
  2728. list_move(&slot->mm_node,
  2729. &ksm_scan.mm_slot->slot.mm_node);
  2730. }
  2731. unlock:
  2732. spin_unlock(&ksm_mmlist_lock);
  2733. if (easy_to_free) {
  2734. mm_slot_free(mm_slot_cache, mm_slot);
  2735. mm_flags_clear(MMF_VM_MERGE_ANY, mm);
  2736. mm_flags_clear(MMF_VM_MERGEABLE, mm);
  2737. mmdrop(mm);
  2738. } else if (mm_slot) {
  2739. mmap_write_lock(mm);
  2740. mmap_write_unlock(mm);
  2741. }
  2742. trace_ksm_exit(mm);
  2743. }
  2744. struct folio *ksm_might_need_to_copy(struct folio *folio,
  2745. struct vm_area_struct *vma, unsigned long addr)
  2746. {
  2747. struct page *page = folio_page(folio, 0);
  2748. struct anon_vma *anon_vma = folio_anon_vma(folio);
  2749. struct folio *new_folio;
  2750. if (folio_test_large(folio))
  2751. return folio;
  2752. if (folio_test_ksm(folio)) {
  2753. if (folio_stable_node(folio) &&
  2754. !(ksm_run & KSM_RUN_UNMERGE))
  2755. return folio; /* no need to copy it */
  2756. } else if (!anon_vma) {
  2757. return folio; /* no need to copy it */
  2758. } else if (folio->index == linear_page_index(vma, addr) &&
  2759. anon_vma->root == vma->anon_vma->root) {
  2760. return folio; /* still no need to copy it */
  2761. }
  2762. if (PageHWPoison(page))
  2763. return ERR_PTR(-EHWPOISON);
  2764. if (!folio_test_uptodate(folio))
  2765. return folio; /* let do_swap_page report the error */
  2766. new_folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, addr);
  2767. if (new_folio &&
  2768. mem_cgroup_charge(new_folio, vma->vm_mm, GFP_KERNEL)) {
  2769. folio_put(new_folio);
  2770. new_folio = NULL;
  2771. }
  2772. if (new_folio) {
  2773. if (copy_mc_user_highpage(folio_page(new_folio, 0), page,
  2774. addr, vma)) {
  2775. folio_put(new_folio);
  2776. return ERR_PTR(-EHWPOISON);
  2777. }
  2778. folio_set_dirty(new_folio);
  2779. __folio_mark_uptodate(new_folio);
  2780. __folio_set_locked(new_folio);
  2781. #ifdef CONFIG_SWAP
  2782. count_vm_event(KSM_SWPIN_COPY);
  2783. #endif
  2784. }
  2785. return new_folio;
  2786. }
  2787. void rmap_walk_ksm(struct folio *folio, struct rmap_walk_control *rwc)
  2788. {
  2789. struct ksm_stable_node *stable_node;
  2790. struct ksm_rmap_item *rmap_item;
  2791. int search_new_forks = 0;
  2792. VM_BUG_ON_FOLIO(!folio_test_ksm(folio), folio);
  2793. /*
  2794. * Rely on the page lock to protect against concurrent modifications
  2795. * to that page's node of the stable tree.
  2796. */
  2797. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2798. stable_node = folio_stable_node(folio);
  2799. if (!stable_node)
  2800. return;
  2801. again:
  2802. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  2803. struct anon_vma *anon_vma = rmap_item->anon_vma;
  2804. struct anon_vma_chain *vmac;
  2805. struct vm_area_struct *vma;
  2806. cond_resched();
  2807. if (!anon_vma_trylock_read(anon_vma)) {
  2808. if (rwc->try_lock) {
  2809. rwc->contended = true;
  2810. return;
  2811. }
  2812. anon_vma_lock_read(anon_vma);
  2813. }
  2814. anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
  2815. 0, ULONG_MAX) {
  2816. unsigned long addr;
  2817. cond_resched();
  2818. vma = vmac->vma;
  2819. /* Ignore the stable/unstable/sqnr flags */
  2820. addr = rmap_item->address & PAGE_MASK;
  2821. if (addr < vma->vm_start || addr >= vma->vm_end)
  2822. continue;
  2823. /*
  2824. * Initially we examine only the vma which covers this
  2825. * rmap_item; but later, if there is still work to do,
  2826. * we examine covering vmas in other mms: in case they
  2827. * were forked from the original since ksmd passed.
  2828. */
  2829. if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
  2830. continue;
  2831. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  2832. continue;
  2833. if (!rwc->rmap_one(folio, vma, addr, rwc->arg)) {
  2834. anon_vma_unlock_read(anon_vma);
  2835. return;
  2836. }
  2837. if (rwc->done && rwc->done(folio)) {
  2838. anon_vma_unlock_read(anon_vma);
  2839. return;
  2840. }
  2841. }
  2842. anon_vma_unlock_read(anon_vma);
  2843. }
  2844. if (!search_new_forks++)
  2845. goto again;
  2846. }
  2847. #ifdef CONFIG_MEMORY_FAILURE
  2848. /*
  2849. * Collect processes when the error hit an ksm page.
  2850. */
  2851. void collect_procs_ksm(const struct folio *folio, const struct page *page,
  2852. struct list_head *to_kill, int force_early)
  2853. {
  2854. struct ksm_stable_node *stable_node;
  2855. struct ksm_rmap_item *rmap_item;
  2856. struct vm_area_struct *vma;
  2857. struct task_struct *tsk;
  2858. stable_node = folio_stable_node(folio);
  2859. if (!stable_node)
  2860. return;
  2861. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  2862. struct anon_vma *av = rmap_item->anon_vma;
  2863. anon_vma_lock_read(av);
  2864. rcu_read_lock();
  2865. for_each_process(tsk) {
  2866. struct anon_vma_chain *vmac;
  2867. unsigned long addr;
  2868. struct task_struct *t =
  2869. task_early_kill(tsk, force_early);
  2870. if (!t)
  2871. continue;
  2872. anon_vma_interval_tree_foreach(vmac, &av->rb_root, 0,
  2873. ULONG_MAX)
  2874. {
  2875. vma = vmac->vma;
  2876. if (vma->vm_mm == t->mm) {
  2877. addr = rmap_item->address & PAGE_MASK;
  2878. add_to_kill_ksm(t, page, vma, to_kill,
  2879. addr);
  2880. }
  2881. }
  2882. }
  2883. rcu_read_unlock();
  2884. anon_vma_unlock_read(av);
  2885. }
  2886. }
  2887. #endif
  2888. #ifdef CONFIG_MIGRATION
  2889. void folio_migrate_ksm(struct folio *newfolio, struct folio *folio)
  2890. {
  2891. struct ksm_stable_node *stable_node;
  2892. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2893. VM_BUG_ON_FOLIO(!folio_test_locked(newfolio), newfolio);
  2894. VM_BUG_ON_FOLIO(newfolio->mapping != folio->mapping, newfolio);
  2895. stable_node = folio_stable_node(folio);
  2896. if (stable_node) {
  2897. VM_BUG_ON_FOLIO(stable_node->kpfn != folio_pfn(folio), folio);
  2898. stable_node->kpfn = folio_pfn(newfolio);
  2899. /*
  2900. * newfolio->mapping was set in advance; now we need smp_wmb()
  2901. * to make sure that the new stable_node->kpfn is visible
  2902. * to ksm_get_folio() before it can see that folio->mapping
  2903. * has gone stale (or that the swapcache flag has been cleared).
  2904. */
  2905. smp_wmb();
  2906. folio_set_stable_node(folio, NULL);
  2907. }
  2908. }
  2909. #endif /* CONFIG_MIGRATION */
  2910. #ifdef CONFIG_MEMORY_HOTREMOVE
  2911. static void wait_while_offlining(void)
  2912. {
  2913. while (ksm_run & KSM_RUN_OFFLINE) {
  2914. mutex_unlock(&ksm_thread_mutex);
  2915. wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
  2916. TASK_UNINTERRUPTIBLE);
  2917. mutex_lock(&ksm_thread_mutex);
  2918. }
  2919. }
  2920. static bool stable_node_dup_remove_range(struct ksm_stable_node *stable_node,
  2921. unsigned long start_pfn,
  2922. unsigned long end_pfn)
  2923. {
  2924. if (stable_node->kpfn >= start_pfn &&
  2925. stable_node->kpfn < end_pfn) {
  2926. /*
  2927. * Don't ksm_get_folio, page has already gone:
  2928. * which is why we keep kpfn instead of page*
  2929. */
  2930. remove_node_from_stable_tree(stable_node);
  2931. return true;
  2932. }
  2933. return false;
  2934. }
  2935. static bool stable_node_chain_remove_range(struct ksm_stable_node *stable_node,
  2936. unsigned long start_pfn,
  2937. unsigned long end_pfn,
  2938. struct rb_root *root)
  2939. {
  2940. struct ksm_stable_node *dup;
  2941. struct hlist_node *hlist_safe;
  2942. if (!is_stable_node_chain(stable_node)) {
  2943. VM_BUG_ON(is_stable_node_dup(stable_node));
  2944. return stable_node_dup_remove_range(stable_node, start_pfn,
  2945. end_pfn);
  2946. }
  2947. hlist_for_each_entry_safe(dup, hlist_safe,
  2948. &stable_node->hlist, hlist_dup) {
  2949. VM_BUG_ON(!is_stable_node_dup(dup));
  2950. stable_node_dup_remove_range(dup, start_pfn, end_pfn);
  2951. }
  2952. if (hlist_empty(&stable_node->hlist)) {
  2953. free_stable_node_chain(stable_node, root);
  2954. return true; /* notify caller that tree was rebalanced */
  2955. } else
  2956. return false;
  2957. }
  2958. static void ksm_check_stable_tree(unsigned long start_pfn,
  2959. unsigned long end_pfn)
  2960. {
  2961. struct ksm_stable_node *stable_node, *next;
  2962. struct rb_node *node;
  2963. int nid;
  2964. for (nid = 0; nid < ksm_nr_node_ids; nid++) {
  2965. node = rb_first(root_stable_tree + nid);
  2966. while (node) {
  2967. stable_node = rb_entry(node, struct ksm_stable_node, node);
  2968. if (stable_node_chain_remove_range(stable_node,
  2969. start_pfn, end_pfn,
  2970. root_stable_tree +
  2971. nid))
  2972. node = rb_first(root_stable_tree + nid);
  2973. else
  2974. node = rb_next(node);
  2975. cond_resched();
  2976. }
  2977. }
  2978. list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
  2979. if (stable_node->kpfn >= start_pfn &&
  2980. stable_node->kpfn < end_pfn)
  2981. remove_node_from_stable_tree(stable_node);
  2982. cond_resched();
  2983. }
  2984. }
  2985. static int ksm_memory_callback(struct notifier_block *self,
  2986. unsigned long action, void *arg)
  2987. {
  2988. struct memory_notify *mn = arg;
  2989. switch (action) {
  2990. case MEM_GOING_OFFLINE:
  2991. /*
  2992. * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
  2993. * and remove_all_stable_nodes() while memory is going offline:
  2994. * it is unsafe for them to touch the stable tree at this time.
  2995. * But break_ksm(), rmap lookups and other entry points
  2996. * which do not need the ksm_thread_mutex are all safe.
  2997. */
  2998. mutex_lock(&ksm_thread_mutex);
  2999. ksm_run |= KSM_RUN_OFFLINE;
  3000. mutex_unlock(&ksm_thread_mutex);
  3001. break;
  3002. case MEM_OFFLINE:
  3003. /*
  3004. * Most of the work is done by page migration; but there might
  3005. * be a few stable_nodes left over, still pointing to struct
  3006. * pages which have been offlined: prune those from the tree,
  3007. * otherwise ksm_get_folio() might later try to access a
  3008. * non-existent struct page.
  3009. */
  3010. ksm_check_stable_tree(mn->start_pfn,
  3011. mn->start_pfn + mn->nr_pages);
  3012. fallthrough;
  3013. case MEM_CANCEL_OFFLINE:
  3014. mutex_lock(&ksm_thread_mutex);
  3015. ksm_run &= ~KSM_RUN_OFFLINE;
  3016. mutex_unlock(&ksm_thread_mutex);
  3017. smp_mb(); /* wake_up_bit advises this */
  3018. wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
  3019. break;
  3020. }
  3021. return NOTIFY_OK;
  3022. }
  3023. #else
  3024. static void wait_while_offlining(void)
  3025. {
  3026. }
  3027. #endif /* CONFIG_MEMORY_HOTREMOVE */
  3028. #ifdef CONFIG_PROC_FS
  3029. /*
  3030. * The process is mergeable only if any VMA is currently
  3031. * applicable to KSM.
  3032. *
  3033. * The mmap lock must be held in read mode.
  3034. */
  3035. bool ksm_process_mergeable(struct mm_struct *mm)
  3036. {
  3037. struct vm_area_struct *vma;
  3038. mmap_assert_locked(mm);
  3039. VMA_ITERATOR(vmi, mm, 0);
  3040. for_each_vma(vmi, vma)
  3041. if (vma->vm_flags & VM_MERGEABLE)
  3042. return true;
  3043. return false;
  3044. }
  3045. long ksm_process_profit(struct mm_struct *mm)
  3046. {
  3047. return (long)(mm->ksm_merging_pages + mm_ksm_zero_pages(mm)) * PAGE_SIZE -
  3048. mm->ksm_rmap_items * sizeof(struct ksm_rmap_item);
  3049. }
  3050. #endif /* CONFIG_PROC_FS */
  3051. #ifdef CONFIG_SYSFS
  3052. /*
  3053. * This all compiles without CONFIG_SYSFS, but is a waste of space.
  3054. */
  3055. #define KSM_ATTR_RO(_name) \
  3056. static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
  3057. #define KSM_ATTR(_name) \
  3058. static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
  3059. static ssize_t sleep_millisecs_show(struct kobject *kobj,
  3060. struct kobj_attribute *attr, char *buf)
  3061. {
  3062. return sysfs_emit(buf, "%u\n", ksm_thread_sleep_millisecs);
  3063. }
  3064. static ssize_t sleep_millisecs_store(struct kobject *kobj,
  3065. struct kobj_attribute *attr,
  3066. const char *buf, size_t count)
  3067. {
  3068. unsigned int msecs;
  3069. int err;
  3070. err = kstrtouint(buf, 10, &msecs);
  3071. if (err)
  3072. return -EINVAL;
  3073. ksm_thread_sleep_millisecs = msecs;
  3074. wake_up_interruptible(&ksm_iter_wait);
  3075. return count;
  3076. }
  3077. KSM_ATTR(sleep_millisecs);
  3078. static ssize_t pages_to_scan_show(struct kobject *kobj,
  3079. struct kobj_attribute *attr, char *buf)
  3080. {
  3081. return sysfs_emit(buf, "%u\n", ksm_thread_pages_to_scan);
  3082. }
  3083. static ssize_t pages_to_scan_store(struct kobject *kobj,
  3084. struct kobj_attribute *attr,
  3085. const char *buf, size_t count)
  3086. {
  3087. unsigned int nr_pages;
  3088. int err;
  3089. if (ksm_advisor != KSM_ADVISOR_NONE)
  3090. return -EINVAL;
  3091. err = kstrtouint(buf, 10, &nr_pages);
  3092. if (err)
  3093. return -EINVAL;
  3094. ksm_thread_pages_to_scan = nr_pages;
  3095. return count;
  3096. }
  3097. KSM_ATTR(pages_to_scan);
  3098. static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
  3099. char *buf)
  3100. {
  3101. return sysfs_emit(buf, "%lu\n", ksm_run);
  3102. }
  3103. static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
  3104. const char *buf, size_t count)
  3105. {
  3106. unsigned int flags;
  3107. int err;
  3108. err = kstrtouint(buf, 10, &flags);
  3109. if (err)
  3110. return -EINVAL;
  3111. if (flags > KSM_RUN_UNMERGE)
  3112. return -EINVAL;
  3113. /*
  3114. * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
  3115. * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
  3116. * breaking COW to free the pages_shared (but leaves mm_slots
  3117. * on the list for when ksmd may be set running again).
  3118. */
  3119. mutex_lock(&ksm_thread_mutex);
  3120. wait_while_offlining();
  3121. if (ksm_run != flags) {
  3122. ksm_run = flags;
  3123. if (flags & KSM_RUN_UNMERGE) {
  3124. set_current_oom_origin();
  3125. err = unmerge_and_remove_all_rmap_items();
  3126. clear_current_oom_origin();
  3127. if (err) {
  3128. ksm_run = KSM_RUN_STOP;
  3129. count = err;
  3130. }
  3131. }
  3132. }
  3133. mutex_unlock(&ksm_thread_mutex);
  3134. if (flags & KSM_RUN_MERGE)
  3135. wake_up_interruptible(&ksm_thread_wait);
  3136. return count;
  3137. }
  3138. KSM_ATTR(run);
  3139. #ifdef CONFIG_NUMA
  3140. static ssize_t merge_across_nodes_show(struct kobject *kobj,
  3141. struct kobj_attribute *attr, char *buf)
  3142. {
  3143. return sysfs_emit(buf, "%u\n", ksm_merge_across_nodes);
  3144. }
  3145. static ssize_t merge_across_nodes_store(struct kobject *kobj,
  3146. struct kobj_attribute *attr,
  3147. const char *buf, size_t count)
  3148. {
  3149. int err;
  3150. unsigned long knob;
  3151. err = kstrtoul(buf, 10, &knob);
  3152. if (err)
  3153. return err;
  3154. if (knob > 1)
  3155. return -EINVAL;
  3156. mutex_lock(&ksm_thread_mutex);
  3157. wait_while_offlining();
  3158. if (ksm_merge_across_nodes != knob) {
  3159. if (ksm_pages_shared || remove_all_stable_nodes())
  3160. err = -EBUSY;
  3161. else if (root_stable_tree == one_stable_tree) {
  3162. struct rb_root *buf;
  3163. /*
  3164. * This is the first time that we switch away from the
  3165. * default of merging across nodes: must now allocate
  3166. * a buffer to hold as many roots as may be needed.
  3167. * Allocate stable and unstable together:
  3168. * MAXSMP NODES_SHIFT 10 will use 16kB.
  3169. */
  3170. buf = kzalloc_objs(*buf, nr_node_ids + nr_node_ids);
  3171. /* Let us assume that RB_ROOT is NULL is zero */
  3172. if (!buf)
  3173. err = -ENOMEM;
  3174. else {
  3175. root_stable_tree = buf;
  3176. root_unstable_tree = buf + nr_node_ids;
  3177. /* Stable tree is empty but not the unstable */
  3178. root_unstable_tree[0] = one_unstable_tree[0];
  3179. }
  3180. }
  3181. if (!err) {
  3182. ksm_merge_across_nodes = knob;
  3183. ksm_nr_node_ids = knob ? 1 : nr_node_ids;
  3184. }
  3185. }
  3186. mutex_unlock(&ksm_thread_mutex);
  3187. return err ? err : count;
  3188. }
  3189. KSM_ATTR(merge_across_nodes);
  3190. #endif
  3191. static ssize_t use_zero_pages_show(struct kobject *kobj,
  3192. struct kobj_attribute *attr, char *buf)
  3193. {
  3194. return sysfs_emit(buf, "%u\n", ksm_use_zero_pages);
  3195. }
  3196. static ssize_t use_zero_pages_store(struct kobject *kobj,
  3197. struct kobj_attribute *attr,
  3198. const char *buf, size_t count)
  3199. {
  3200. int err;
  3201. bool value;
  3202. err = kstrtobool(buf, &value);
  3203. if (err)
  3204. return -EINVAL;
  3205. ksm_use_zero_pages = value;
  3206. return count;
  3207. }
  3208. KSM_ATTR(use_zero_pages);
  3209. static ssize_t max_page_sharing_show(struct kobject *kobj,
  3210. struct kobj_attribute *attr, char *buf)
  3211. {
  3212. return sysfs_emit(buf, "%u\n", ksm_max_page_sharing);
  3213. }
  3214. static ssize_t max_page_sharing_store(struct kobject *kobj,
  3215. struct kobj_attribute *attr,
  3216. const char *buf, size_t count)
  3217. {
  3218. int err;
  3219. int knob;
  3220. err = kstrtoint(buf, 10, &knob);
  3221. if (err)
  3222. return err;
  3223. /*
  3224. * When a KSM page is created it is shared by 2 mappings. This
  3225. * being a signed comparison, it implicitly verifies it's not
  3226. * negative.
  3227. */
  3228. if (knob < 2)
  3229. return -EINVAL;
  3230. if (READ_ONCE(ksm_max_page_sharing) == knob)
  3231. return count;
  3232. mutex_lock(&ksm_thread_mutex);
  3233. wait_while_offlining();
  3234. if (ksm_max_page_sharing != knob) {
  3235. if (ksm_pages_shared || remove_all_stable_nodes())
  3236. err = -EBUSY;
  3237. else
  3238. ksm_max_page_sharing = knob;
  3239. }
  3240. mutex_unlock(&ksm_thread_mutex);
  3241. return err ? err : count;
  3242. }
  3243. KSM_ATTR(max_page_sharing);
  3244. static ssize_t pages_scanned_show(struct kobject *kobj,
  3245. struct kobj_attribute *attr, char *buf)
  3246. {
  3247. return sysfs_emit(buf, "%lu\n", ksm_pages_scanned);
  3248. }
  3249. KSM_ATTR_RO(pages_scanned);
  3250. static ssize_t pages_shared_show(struct kobject *kobj,
  3251. struct kobj_attribute *attr, char *buf)
  3252. {
  3253. return sysfs_emit(buf, "%lu\n", ksm_pages_shared);
  3254. }
  3255. KSM_ATTR_RO(pages_shared);
  3256. static ssize_t pages_sharing_show(struct kobject *kobj,
  3257. struct kobj_attribute *attr, char *buf)
  3258. {
  3259. return sysfs_emit(buf, "%lu\n", ksm_pages_sharing);
  3260. }
  3261. KSM_ATTR_RO(pages_sharing);
  3262. static ssize_t pages_unshared_show(struct kobject *kobj,
  3263. struct kobj_attribute *attr, char *buf)
  3264. {
  3265. return sysfs_emit(buf, "%lu\n", ksm_pages_unshared);
  3266. }
  3267. KSM_ATTR_RO(pages_unshared);
  3268. static ssize_t pages_volatile_show(struct kobject *kobj,
  3269. struct kobj_attribute *attr, char *buf)
  3270. {
  3271. long ksm_pages_volatile;
  3272. ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
  3273. - ksm_pages_sharing - ksm_pages_unshared;
  3274. /*
  3275. * It was not worth any locking to calculate that statistic,
  3276. * but it might therefore sometimes be negative: conceal that.
  3277. */
  3278. if (ksm_pages_volatile < 0)
  3279. ksm_pages_volatile = 0;
  3280. return sysfs_emit(buf, "%ld\n", ksm_pages_volatile);
  3281. }
  3282. KSM_ATTR_RO(pages_volatile);
  3283. static ssize_t pages_skipped_show(struct kobject *kobj,
  3284. struct kobj_attribute *attr, char *buf)
  3285. {
  3286. return sysfs_emit(buf, "%lu\n", ksm_pages_skipped);
  3287. }
  3288. KSM_ATTR_RO(pages_skipped);
  3289. static ssize_t ksm_zero_pages_show(struct kobject *kobj,
  3290. struct kobj_attribute *attr, char *buf)
  3291. {
  3292. return sysfs_emit(buf, "%ld\n", atomic_long_read(&ksm_zero_pages));
  3293. }
  3294. KSM_ATTR_RO(ksm_zero_pages);
  3295. static ssize_t general_profit_show(struct kobject *kobj,
  3296. struct kobj_attribute *attr, char *buf)
  3297. {
  3298. long general_profit;
  3299. general_profit = (ksm_pages_sharing + atomic_long_read(&ksm_zero_pages)) * PAGE_SIZE -
  3300. ksm_rmap_items * sizeof(struct ksm_rmap_item);
  3301. return sysfs_emit(buf, "%ld\n", general_profit);
  3302. }
  3303. KSM_ATTR_RO(general_profit);
  3304. static ssize_t stable_node_dups_show(struct kobject *kobj,
  3305. struct kobj_attribute *attr, char *buf)
  3306. {
  3307. return sysfs_emit(buf, "%lu\n", ksm_stable_node_dups);
  3308. }
  3309. KSM_ATTR_RO(stable_node_dups);
  3310. static ssize_t stable_node_chains_show(struct kobject *kobj,
  3311. struct kobj_attribute *attr, char *buf)
  3312. {
  3313. return sysfs_emit(buf, "%lu\n", ksm_stable_node_chains);
  3314. }
  3315. KSM_ATTR_RO(stable_node_chains);
  3316. static ssize_t
  3317. stable_node_chains_prune_millisecs_show(struct kobject *kobj,
  3318. struct kobj_attribute *attr,
  3319. char *buf)
  3320. {
  3321. return sysfs_emit(buf, "%u\n", ksm_stable_node_chains_prune_millisecs);
  3322. }
  3323. static ssize_t
  3324. stable_node_chains_prune_millisecs_store(struct kobject *kobj,
  3325. struct kobj_attribute *attr,
  3326. const char *buf, size_t count)
  3327. {
  3328. unsigned int msecs;
  3329. int err;
  3330. err = kstrtouint(buf, 10, &msecs);
  3331. if (err)
  3332. return -EINVAL;
  3333. ksm_stable_node_chains_prune_millisecs = msecs;
  3334. return count;
  3335. }
  3336. KSM_ATTR(stable_node_chains_prune_millisecs);
  3337. static ssize_t full_scans_show(struct kobject *kobj,
  3338. struct kobj_attribute *attr, char *buf)
  3339. {
  3340. return sysfs_emit(buf, "%lu\n", ksm_scan.seqnr);
  3341. }
  3342. KSM_ATTR_RO(full_scans);
  3343. static ssize_t smart_scan_show(struct kobject *kobj,
  3344. struct kobj_attribute *attr, char *buf)
  3345. {
  3346. return sysfs_emit(buf, "%u\n", ksm_smart_scan);
  3347. }
  3348. static ssize_t smart_scan_store(struct kobject *kobj,
  3349. struct kobj_attribute *attr,
  3350. const char *buf, size_t count)
  3351. {
  3352. int err;
  3353. bool value;
  3354. err = kstrtobool(buf, &value);
  3355. if (err)
  3356. return -EINVAL;
  3357. ksm_smart_scan = value;
  3358. return count;
  3359. }
  3360. KSM_ATTR(smart_scan);
  3361. static ssize_t advisor_mode_show(struct kobject *kobj,
  3362. struct kobj_attribute *attr, char *buf)
  3363. {
  3364. const char *output;
  3365. if (ksm_advisor == KSM_ADVISOR_SCAN_TIME)
  3366. output = "none [scan-time]";
  3367. else
  3368. output = "[none] scan-time";
  3369. return sysfs_emit(buf, "%s\n", output);
  3370. }
  3371. static ssize_t advisor_mode_store(struct kobject *kobj,
  3372. struct kobj_attribute *attr, const char *buf,
  3373. size_t count)
  3374. {
  3375. enum ksm_advisor_type curr_advisor = ksm_advisor;
  3376. if (sysfs_streq("scan-time", buf))
  3377. ksm_advisor = KSM_ADVISOR_SCAN_TIME;
  3378. else if (sysfs_streq("none", buf))
  3379. ksm_advisor = KSM_ADVISOR_NONE;
  3380. else
  3381. return -EINVAL;
  3382. /* Set advisor default values */
  3383. if (curr_advisor != ksm_advisor)
  3384. set_advisor_defaults();
  3385. return count;
  3386. }
  3387. KSM_ATTR(advisor_mode);
  3388. static ssize_t advisor_max_cpu_show(struct kobject *kobj,
  3389. struct kobj_attribute *attr, char *buf)
  3390. {
  3391. return sysfs_emit(buf, "%u\n", ksm_advisor_max_cpu);
  3392. }
  3393. static ssize_t advisor_max_cpu_store(struct kobject *kobj,
  3394. struct kobj_attribute *attr,
  3395. const char *buf, size_t count)
  3396. {
  3397. int err;
  3398. unsigned long value;
  3399. err = kstrtoul(buf, 10, &value);
  3400. if (err)
  3401. return -EINVAL;
  3402. ksm_advisor_max_cpu = value;
  3403. return count;
  3404. }
  3405. KSM_ATTR(advisor_max_cpu);
  3406. static ssize_t advisor_min_pages_to_scan_show(struct kobject *kobj,
  3407. struct kobj_attribute *attr, char *buf)
  3408. {
  3409. return sysfs_emit(buf, "%lu\n", ksm_advisor_min_pages_to_scan);
  3410. }
  3411. static ssize_t advisor_min_pages_to_scan_store(struct kobject *kobj,
  3412. struct kobj_attribute *attr,
  3413. const char *buf, size_t count)
  3414. {
  3415. int err;
  3416. unsigned long value;
  3417. err = kstrtoul(buf, 10, &value);
  3418. if (err)
  3419. return -EINVAL;
  3420. ksm_advisor_min_pages_to_scan = value;
  3421. return count;
  3422. }
  3423. KSM_ATTR(advisor_min_pages_to_scan);
  3424. static ssize_t advisor_max_pages_to_scan_show(struct kobject *kobj,
  3425. struct kobj_attribute *attr, char *buf)
  3426. {
  3427. return sysfs_emit(buf, "%lu\n", ksm_advisor_max_pages_to_scan);
  3428. }
  3429. static ssize_t advisor_max_pages_to_scan_store(struct kobject *kobj,
  3430. struct kobj_attribute *attr,
  3431. const char *buf, size_t count)
  3432. {
  3433. int err;
  3434. unsigned long value;
  3435. err = kstrtoul(buf, 10, &value);
  3436. if (err)
  3437. return -EINVAL;
  3438. ksm_advisor_max_pages_to_scan = value;
  3439. return count;
  3440. }
  3441. KSM_ATTR(advisor_max_pages_to_scan);
  3442. static ssize_t advisor_target_scan_time_show(struct kobject *kobj,
  3443. struct kobj_attribute *attr, char *buf)
  3444. {
  3445. return sysfs_emit(buf, "%lu\n", ksm_advisor_target_scan_time);
  3446. }
  3447. static ssize_t advisor_target_scan_time_store(struct kobject *kobj,
  3448. struct kobj_attribute *attr,
  3449. const char *buf, size_t count)
  3450. {
  3451. int err;
  3452. unsigned long value;
  3453. err = kstrtoul(buf, 10, &value);
  3454. if (err)
  3455. return -EINVAL;
  3456. if (value < 1)
  3457. return -EINVAL;
  3458. ksm_advisor_target_scan_time = value;
  3459. return count;
  3460. }
  3461. KSM_ATTR(advisor_target_scan_time);
  3462. static struct attribute *ksm_attrs[] = {
  3463. &sleep_millisecs_attr.attr,
  3464. &pages_to_scan_attr.attr,
  3465. &run_attr.attr,
  3466. &pages_scanned_attr.attr,
  3467. &pages_shared_attr.attr,
  3468. &pages_sharing_attr.attr,
  3469. &pages_unshared_attr.attr,
  3470. &pages_volatile_attr.attr,
  3471. &pages_skipped_attr.attr,
  3472. &ksm_zero_pages_attr.attr,
  3473. &full_scans_attr.attr,
  3474. #ifdef CONFIG_NUMA
  3475. &merge_across_nodes_attr.attr,
  3476. #endif
  3477. &max_page_sharing_attr.attr,
  3478. &stable_node_chains_attr.attr,
  3479. &stable_node_dups_attr.attr,
  3480. &stable_node_chains_prune_millisecs_attr.attr,
  3481. &use_zero_pages_attr.attr,
  3482. &general_profit_attr.attr,
  3483. &smart_scan_attr.attr,
  3484. &advisor_mode_attr.attr,
  3485. &advisor_max_cpu_attr.attr,
  3486. &advisor_min_pages_to_scan_attr.attr,
  3487. &advisor_max_pages_to_scan_attr.attr,
  3488. &advisor_target_scan_time_attr.attr,
  3489. NULL,
  3490. };
  3491. static const struct attribute_group ksm_attr_group = {
  3492. .attrs = ksm_attrs,
  3493. .name = "ksm",
  3494. };
  3495. #endif /* CONFIG_SYSFS */
  3496. static int __init ksm_init(void)
  3497. {
  3498. struct task_struct *ksm_thread;
  3499. int err;
  3500. /* The correct value depends on page size and endianness */
  3501. zero_checksum = calc_checksum(ZERO_PAGE(0));
  3502. /* Default to false for backwards compatibility */
  3503. ksm_use_zero_pages = false;
  3504. err = ksm_slab_init();
  3505. if (err)
  3506. goto out;
  3507. ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
  3508. if (IS_ERR(ksm_thread)) {
  3509. pr_err("ksm: creating kthread failed\n");
  3510. err = PTR_ERR(ksm_thread);
  3511. goto out_free;
  3512. }
  3513. #ifdef CONFIG_SYSFS
  3514. err = sysfs_create_group(mm_kobj, &ksm_attr_group);
  3515. if (err) {
  3516. pr_err("ksm: register sysfs failed\n");
  3517. kthread_stop(ksm_thread);
  3518. goto out_free;
  3519. }
  3520. #else
  3521. ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
  3522. #endif /* CONFIG_SYSFS */
  3523. #ifdef CONFIG_MEMORY_HOTREMOVE
  3524. /* There is no significance to this priority 100 */
  3525. hotplug_memory_notifier(ksm_memory_callback, KSM_CALLBACK_PRI);
  3526. #endif
  3527. return 0;
  3528. out_free:
  3529. ksm_slab_free();
  3530. out:
  3531. return err;
  3532. }
  3533. subsys_initcall(ksm_init);