ksm.c 88 KB

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