ksm.c 88 KB

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