ksm.c 86 KB

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