ksm.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448
  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/rwsem.h>
  22. #include <linux/pagemap.h>
  23. #include <linux/rmap.h>
  24. #include <linux/spinlock.h>
  25. #include <linux/jhash.h>
  26. #include <linux/delay.h>
  27. #include <linux/kthread.h>
  28. #include <linux/wait.h>
  29. #include <linux/slab.h>
  30. #include <linux/rbtree.h>
  31. #include <linux/memory.h>
  32. #include <linux/mmu_notifier.h>
  33. #include <linux/swap.h>
  34. #include <linux/ksm.h>
  35. #include <linux/hashtable.h>
  36. #include <linux/freezer.h>
  37. #include <linux/oom.h>
  38. #include <linux/numa.h>
  39. #include <linux/show_mem_notifier.h>
  40. #include <asm/tlbflush.h>
  41. #include "internal.h"
  42. #ifdef CONFIG_NUMA
  43. #define NUMA(x) (x)
  44. #define DO_NUMA(x) do { (x); } while (0)
  45. #else
  46. #define NUMA(x) (0)
  47. #define DO_NUMA(x) do { } while (0)
  48. #endif
  49. /*
  50. * A few notes about the KSM scanning process,
  51. * to make it easier to understand the data structures below:
  52. *
  53. * In order to reduce excessive scanning, KSM sorts the memory pages by their
  54. * contents into a data structure that holds pointers to the pages' locations.
  55. *
  56. * Since the contents of the pages may change at any moment, KSM cannot just
  57. * insert the pages into a normal sorted tree and expect it to find anything.
  58. * Therefore KSM uses two data structures - the stable and the unstable tree.
  59. *
  60. * The stable tree holds pointers to all the merged pages (ksm pages), sorted
  61. * by their contents. Because each such page is write-protected, searching on
  62. * this tree is fully assured to be working (except when pages are unmapped),
  63. * and therefore this tree is called the stable tree.
  64. *
  65. * In addition to the stable tree, KSM uses a second data structure called the
  66. * unstable tree: this tree holds pointers to pages which have been found to
  67. * be "unchanged for a period of time". The unstable tree sorts these pages
  68. * by their contents, but since they are not write-protected, KSM cannot rely
  69. * upon the unstable tree to work correctly - the unstable tree is liable to
  70. * be corrupted as its contents are modified, and so it is called unstable.
  71. *
  72. * KSM solves this problem by several techniques:
  73. *
  74. * 1) The unstable tree is flushed every time KSM completes scanning all
  75. * memory areas, and then the tree is rebuilt again from the beginning.
  76. * 2) KSM will only insert into the unstable tree, pages whose hash value
  77. * has not changed since the previous scan of all memory areas.
  78. * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
  79. * colors of the nodes and not on their contents, assuring that even when
  80. * the tree gets "corrupted" it won't get out of balance, so scanning time
  81. * remains the same (also, searching and inserting nodes in an rbtree uses
  82. * the same algorithm, so we have no overhead when we flush and rebuild).
  83. * 4) KSM never flushes the stable tree, which means that even if it were to
  84. * take 10 attempts to find a page in the unstable tree, once it is found,
  85. * it is secured in the stable tree. (When we scan a new page, we first
  86. * compare it against the stable tree, and then against the unstable tree.)
  87. *
  88. * If the merge_across_nodes tunable is unset, then KSM maintains multiple
  89. * stable trees and multiple unstable trees: one of each for each NUMA node.
  90. */
  91. /**
  92. * struct mm_slot - ksm information per mm that is being scanned
  93. * @link: link to the mm_slots hash list
  94. * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
  95. * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
  96. * @mm: the mm that this information is valid for
  97. */
  98. struct mm_slot {
  99. struct hlist_node link;
  100. struct list_head mm_list;
  101. struct rmap_item *rmap_list;
  102. struct mm_struct *mm;
  103. };
  104. /**
  105. * struct ksm_scan - cursor for scanning
  106. * @mm_slot: the current mm_slot we are scanning
  107. * @address: the next address inside that to be scanned
  108. * @rmap_list: link to the next rmap to be scanned in the rmap_list
  109. * @seqnr: count of completed full scans (needed when removing unstable node)
  110. *
  111. * There is only the one ksm_scan instance of this cursor structure.
  112. */
  113. struct ksm_scan {
  114. struct mm_slot *mm_slot;
  115. unsigned long address;
  116. struct rmap_item **rmap_list;
  117. unsigned long seqnr;
  118. };
  119. /**
  120. * struct stable_node - node of the stable rbtree
  121. * @node: rb node of this ksm page in the stable tree
  122. * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
  123. * @list: linked into migrate_nodes, pending placement in the proper node tree
  124. * @hlist: hlist head of rmap_items using this ksm page
  125. * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
  126. * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
  127. */
  128. struct stable_node {
  129. union {
  130. struct rb_node node; /* when node of stable tree */
  131. struct { /* when listed for migration */
  132. struct list_head *head;
  133. struct list_head list;
  134. };
  135. };
  136. struct hlist_head hlist;
  137. unsigned long kpfn;
  138. #ifdef CONFIG_NUMA
  139. int nid;
  140. #endif
  141. };
  142. /**
  143. * struct rmap_item - reverse mapping item for virtual addresses
  144. * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
  145. * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
  146. * @nid: NUMA node id of unstable tree in which linked (may not match page)
  147. * @mm: the memory structure this rmap_item is pointing into
  148. * @address: the virtual address this rmap_item tracks (+ flags in low bits)
  149. * @oldchecksum: previous checksum of the page at that virtual address
  150. * @node: rb node of this rmap_item in the unstable tree
  151. * @head: pointer to stable_node heading this list in the stable tree
  152. * @hlist: link into hlist of rmap_items hanging off that stable_node
  153. */
  154. struct rmap_item {
  155. struct rmap_item *rmap_list;
  156. union {
  157. struct anon_vma *anon_vma; /* when stable */
  158. #ifdef CONFIG_NUMA
  159. int nid; /* when node of unstable tree */
  160. #endif
  161. };
  162. struct mm_struct *mm;
  163. unsigned long address; /* + low bits used for flags below */
  164. unsigned int oldchecksum; /* when unstable */
  165. union {
  166. struct rb_node node; /* when node of unstable tree */
  167. struct { /* when listed from stable tree */
  168. struct stable_node *head;
  169. struct hlist_node hlist;
  170. };
  171. };
  172. };
  173. #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
  174. #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
  175. #define STABLE_FLAG 0x200 /* is listed from the stable tree */
  176. /* The stable and unstable tree heads */
  177. static struct rb_root one_stable_tree[1] = { RB_ROOT };
  178. static struct rb_root one_unstable_tree[1] = { RB_ROOT };
  179. static struct rb_root *root_stable_tree = one_stable_tree;
  180. static struct rb_root *root_unstable_tree = one_unstable_tree;
  181. /* Recently migrated nodes of stable tree, pending proper placement */
  182. static LIST_HEAD(migrate_nodes);
  183. #define MM_SLOTS_HASH_BITS 10
  184. static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
  185. static struct mm_slot ksm_mm_head = {
  186. .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
  187. };
  188. static struct ksm_scan ksm_scan = {
  189. .mm_slot = &ksm_mm_head,
  190. };
  191. static struct kmem_cache *rmap_item_cache;
  192. static struct kmem_cache *stable_node_cache;
  193. static struct kmem_cache *mm_slot_cache;
  194. /* The number of nodes in the stable tree */
  195. static unsigned long ksm_pages_shared;
  196. /* The number of page slots additionally sharing those nodes */
  197. static unsigned long ksm_pages_sharing;
  198. /* The number of nodes in the unstable tree */
  199. static unsigned long ksm_pages_unshared;
  200. /* The number of rmap_items in use: to calculate pages_volatile */
  201. static unsigned long ksm_rmap_items;
  202. /* Number of pages ksmd should scan in one batch */
  203. static unsigned int ksm_thread_pages_to_scan = 100;
  204. /* Milliseconds ksmd should sleep between batches */
  205. static unsigned int ksm_thread_sleep_millisecs = 20;
  206. /* Boolean to indicate whether to use deferred timer or not */
  207. static bool use_deferred_timer;
  208. #ifdef CONFIG_NUMA
  209. /* Zeroed when merging across nodes is not allowed */
  210. static unsigned int ksm_merge_across_nodes = 1;
  211. static int ksm_nr_node_ids = 1;
  212. #else
  213. #define ksm_merge_across_nodes 1U
  214. #define ksm_nr_node_ids 1
  215. #endif
  216. #define KSM_RUN_STOP 0
  217. #define KSM_RUN_MERGE 1
  218. #define KSM_RUN_UNMERGE 2
  219. #define KSM_RUN_OFFLINE 4
  220. static unsigned long ksm_run = KSM_RUN_MERGE;
  221. static void wait_while_offlining(void);
  222. static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
  223. static DEFINE_MUTEX(ksm_thread_mutex);
  224. static DEFINE_SPINLOCK(ksm_mmlist_lock);
  225. #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
  226. sizeof(struct __struct), __alignof__(struct __struct),\
  227. (__flags), NULL)
  228. static int ksm_show_mem_notifier(struct notifier_block *nb,
  229. unsigned long action,
  230. void *data)
  231. {
  232. pr_info("ksm_pages_sharing: %lu\n", ksm_pages_sharing);
  233. pr_info("ksm_pages_shared: %lu\n", ksm_pages_shared);
  234. return 0;
  235. }
  236. static struct notifier_block ksm_show_mem_notifier_block = {
  237. .notifier_call = ksm_show_mem_notifier,
  238. };
  239. static int __init ksm_slab_init(void)
  240. {
  241. rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
  242. if (!rmap_item_cache)
  243. goto out;
  244. stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
  245. if (!stable_node_cache)
  246. goto out_free1;
  247. mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
  248. if (!mm_slot_cache)
  249. goto out_free2;
  250. return 0;
  251. out_free2:
  252. kmem_cache_destroy(stable_node_cache);
  253. out_free1:
  254. kmem_cache_destroy(rmap_item_cache);
  255. out:
  256. return -ENOMEM;
  257. }
  258. static void __init ksm_slab_free(void)
  259. {
  260. kmem_cache_destroy(mm_slot_cache);
  261. kmem_cache_destroy(stable_node_cache);
  262. kmem_cache_destroy(rmap_item_cache);
  263. mm_slot_cache = NULL;
  264. }
  265. static inline struct rmap_item *alloc_rmap_item(void)
  266. {
  267. struct rmap_item *rmap_item;
  268. rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL |
  269. __GFP_NORETRY | __GFP_NOWARN);
  270. if (rmap_item)
  271. ksm_rmap_items++;
  272. return rmap_item;
  273. }
  274. static inline void free_rmap_item(struct rmap_item *rmap_item)
  275. {
  276. ksm_rmap_items--;
  277. rmap_item->mm = NULL; /* debug safety */
  278. kmem_cache_free(rmap_item_cache, rmap_item);
  279. }
  280. static inline struct stable_node *alloc_stable_node(void)
  281. {
  282. /*
  283. * The allocation can take too long with GFP_KERNEL when memory is under
  284. * pressure, which may lead to hung task warnings. Adding __GFP_HIGH
  285. * grants access to memory reserves, helping to avoid this problem.
  286. */
  287. return kmem_cache_alloc(stable_node_cache, GFP_KERNEL | __GFP_HIGH);
  288. }
  289. static inline void free_stable_node(struct stable_node *stable_node)
  290. {
  291. kmem_cache_free(stable_node_cache, stable_node);
  292. }
  293. static inline struct mm_slot *alloc_mm_slot(void)
  294. {
  295. if (!mm_slot_cache) /* initialization failed */
  296. return NULL;
  297. return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
  298. }
  299. static inline void free_mm_slot(struct mm_slot *mm_slot)
  300. {
  301. kmem_cache_free(mm_slot_cache, mm_slot);
  302. }
  303. static struct mm_slot *get_mm_slot(struct mm_struct *mm)
  304. {
  305. struct mm_slot *slot;
  306. hash_for_each_possible(mm_slots_hash, slot, link, (unsigned long)mm)
  307. if (slot->mm == mm)
  308. return slot;
  309. return NULL;
  310. }
  311. static void insert_to_mm_slots_hash(struct mm_struct *mm,
  312. struct mm_slot *mm_slot)
  313. {
  314. mm_slot->mm = mm;
  315. hash_add(mm_slots_hash, &mm_slot->link, (unsigned long)mm);
  316. }
  317. /*
  318. * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
  319. * page tables after it has passed through ksm_exit() - which, if necessary,
  320. * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
  321. * a special flag: they can just back out as soon as mm_users goes to zero.
  322. * ksm_test_exit() is used throughout to make this test for exit: in some
  323. * places for correctness, in some places just to avoid unnecessary work.
  324. */
  325. static inline bool ksm_test_exit(struct mm_struct *mm)
  326. {
  327. return atomic_read(&mm->mm_users) == 0;
  328. }
  329. /*
  330. * We use break_ksm to break COW on a ksm page: it's a stripped down
  331. *
  332. * if (get_user_pages(addr, 1, 1, 1, &page, NULL) == 1)
  333. * put_page(page);
  334. *
  335. * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
  336. * in case the application has unmapped and remapped mm,addr meanwhile.
  337. * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
  338. * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
  339. *
  340. * FAULT_FLAG/FOLL_REMOTE are because we do this outside the context
  341. * of the process that owns 'vma'. We also do not want to enforce
  342. * protection keys here anyway.
  343. */
  344. static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
  345. {
  346. struct page *page;
  347. int ret = 0;
  348. do {
  349. cond_resched();
  350. page = follow_page(vma, addr,
  351. FOLL_GET | FOLL_MIGRATION | FOLL_REMOTE);
  352. if (IS_ERR_OR_NULL(page))
  353. break;
  354. if (PageKsm(page))
  355. ret = handle_mm_fault(vma, addr,
  356. FAULT_FLAG_WRITE | FAULT_FLAG_REMOTE);
  357. else
  358. ret = VM_FAULT_WRITE;
  359. put_page(page);
  360. } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
  361. /*
  362. * We must loop because handle_mm_fault() may back out if there's
  363. * any difficulty e.g. if pte accessed bit gets updated concurrently.
  364. *
  365. * VM_FAULT_WRITE is what we have been hoping for: it indicates that
  366. * COW has been broken, even if the vma does not permit VM_WRITE;
  367. * but note that a concurrent fault might break PageKsm for us.
  368. *
  369. * VM_FAULT_SIGBUS could occur if we race with truncation of the
  370. * backing file, which also invalidates anonymous pages: that's
  371. * okay, that truncation will have unmapped the PageKsm for us.
  372. *
  373. * VM_FAULT_OOM: at the time of writing (late July 2009), setting
  374. * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
  375. * current task has TIF_MEMDIE set, and will be OOM killed on return
  376. * to user; and ksmd, having no mm, would never be chosen for that.
  377. *
  378. * But if the mm is in a limited mem_cgroup, then the fault may fail
  379. * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
  380. * even ksmd can fail in this way - though it's usually breaking ksm
  381. * just to undo a merge it made a moment before, so unlikely to oom.
  382. *
  383. * That's a pity: we might therefore have more kernel pages allocated
  384. * than we're counting as nodes in the stable tree; but ksm_do_scan
  385. * will retry to break_cow on each pass, so should recover the page
  386. * in due course. The important thing is to not let VM_MERGEABLE
  387. * be cleared while any such pages might remain in the area.
  388. */
  389. return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
  390. }
  391. static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
  392. unsigned long addr)
  393. {
  394. struct vm_area_struct *vma;
  395. if (ksm_test_exit(mm))
  396. return NULL;
  397. vma = find_vma(mm, addr);
  398. if (!vma || vma->vm_start > addr)
  399. return NULL;
  400. if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  401. return NULL;
  402. return vma;
  403. }
  404. static void break_cow(struct rmap_item *rmap_item)
  405. {
  406. struct mm_struct *mm = rmap_item->mm;
  407. unsigned long addr = rmap_item->address;
  408. struct vm_area_struct *vma;
  409. /*
  410. * It is not an accident that whenever we want to break COW
  411. * to undo, we also need to drop a reference to the anon_vma.
  412. */
  413. put_anon_vma(rmap_item->anon_vma);
  414. down_read(&mm->mmap_sem);
  415. vma = find_mergeable_vma(mm, addr);
  416. if (vma)
  417. break_ksm(vma, addr);
  418. up_read(&mm->mmap_sem);
  419. }
  420. static struct page *get_mergeable_page(struct rmap_item *rmap_item)
  421. {
  422. struct mm_struct *mm = rmap_item->mm;
  423. unsigned long addr = rmap_item->address;
  424. struct vm_area_struct *vma;
  425. struct page *page;
  426. down_read(&mm->mmap_sem);
  427. vma = find_mergeable_vma(mm, addr);
  428. if (!vma)
  429. goto out;
  430. page = follow_page(vma, addr, FOLL_GET);
  431. if (IS_ERR_OR_NULL(page))
  432. goto out;
  433. if (PageAnon(page)) {
  434. flush_anon_page(vma, page, addr);
  435. flush_dcache_page(page);
  436. } else {
  437. put_page(page);
  438. out:
  439. page = NULL;
  440. }
  441. up_read(&mm->mmap_sem);
  442. return page;
  443. }
  444. /*
  445. * This helper is used for getting right index into array of tree roots.
  446. * When merge_across_nodes knob is set to 1, there are only two rb-trees for
  447. * stable and unstable pages from all nodes with roots in index 0. Otherwise,
  448. * every node has its own stable and unstable tree.
  449. */
  450. static inline int get_kpfn_nid(unsigned long kpfn)
  451. {
  452. return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
  453. }
  454. static void remove_node_from_stable_tree(struct stable_node *stable_node)
  455. {
  456. struct rmap_item *rmap_item;
  457. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  458. if (rmap_item->hlist.next)
  459. ksm_pages_sharing--;
  460. else
  461. ksm_pages_shared--;
  462. put_anon_vma(rmap_item->anon_vma);
  463. rmap_item->address &= PAGE_MASK;
  464. cond_resched();
  465. }
  466. if (stable_node->head == &migrate_nodes)
  467. list_del(&stable_node->list);
  468. else
  469. rb_erase(&stable_node->node,
  470. root_stable_tree + NUMA(stable_node->nid));
  471. free_stable_node(stable_node);
  472. }
  473. /*
  474. * get_ksm_page: checks if the page indicated by the stable node
  475. * is still its ksm page, despite having held no reference to it.
  476. * In which case we can trust the content of the page, and it
  477. * returns the gotten page; but if the page has now been zapped,
  478. * remove the stale node from the stable tree and return NULL.
  479. * But beware, the stable node's page might be being migrated.
  480. *
  481. * You would expect the stable_node to hold a reference to the ksm page.
  482. * But if it increments the page's count, swapping out has to wait for
  483. * ksmd to come around again before it can free the page, which may take
  484. * seconds or even minutes: much too unresponsive. So instead we use a
  485. * "keyhole reference": access to the ksm page from the stable node peeps
  486. * out through its keyhole to see if that page still holds the right key,
  487. * pointing back to this stable node. This relies on freeing a PageAnon
  488. * page to reset its page->mapping to NULL, and relies on no other use of
  489. * a page to put something that might look like our key in page->mapping.
  490. * is on its way to being freed; but it is an anomaly to bear in mind.
  491. */
  492. static struct page *get_ksm_page(struct stable_node *stable_node, bool lock_it)
  493. {
  494. struct page *page;
  495. void *expected_mapping;
  496. unsigned long kpfn;
  497. expected_mapping = (void *)((unsigned long)stable_node |
  498. PAGE_MAPPING_KSM);
  499. again:
  500. kpfn = READ_ONCE(stable_node->kpfn);
  501. page = pfn_to_page(kpfn);
  502. /*
  503. * page is computed from kpfn, so on most architectures reading
  504. * page->mapping is naturally ordered after reading node->kpfn,
  505. * but on Alpha we need to be more careful.
  506. */
  507. smp_read_barrier_depends();
  508. if (READ_ONCE(page->mapping) != expected_mapping)
  509. goto stale;
  510. /*
  511. * We cannot do anything with the page while its refcount is 0.
  512. * Usually 0 means free, or tail of a higher-order page: in which
  513. * case this node is no longer referenced, and should be freed;
  514. * however, it might mean that the page is under page_freeze_refs().
  515. * The __remove_mapping() case is easy, again the node is now stale;
  516. * but if page is swapcache in migrate_page_move_mapping(), it might
  517. * still be our page, in which case it's essential to keep the node.
  518. */
  519. while (!get_page_unless_zero(page)) {
  520. /*
  521. * Another check for page->mapping != expected_mapping would
  522. * work here too. We have chosen the !PageSwapCache test to
  523. * optimize the common case, when the page is or is about to
  524. * be freed: PageSwapCache is cleared (under spin_lock_irq)
  525. * in the freeze_refs section of __remove_mapping(); but Anon
  526. * page->mapping reset to NULL later, in free_pages_prepare().
  527. */
  528. if (!PageSwapCache(page))
  529. goto stale;
  530. cpu_relax();
  531. }
  532. if (READ_ONCE(page->mapping) != expected_mapping) {
  533. put_page(page);
  534. goto stale;
  535. }
  536. if (lock_it) {
  537. lock_page(page);
  538. if (READ_ONCE(page->mapping) != expected_mapping) {
  539. unlock_page(page);
  540. put_page(page);
  541. goto stale;
  542. }
  543. }
  544. return page;
  545. stale:
  546. /*
  547. * We come here from above when page->mapping or !PageSwapCache
  548. * suggests that the node is stale; but it might be under migration.
  549. * We need smp_rmb(), matching the smp_wmb() in ksm_migrate_page(),
  550. * before checking whether node->kpfn has been changed.
  551. */
  552. smp_rmb();
  553. if (READ_ONCE(stable_node->kpfn) != kpfn)
  554. goto again;
  555. remove_node_from_stable_tree(stable_node);
  556. return NULL;
  557. }
  558. /*
  559. * Removing rmap_item from stable or unstable tree.
  560. * This function will clean the information from the stable/unstable tree.
  561. */
  562. static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
  563. {
  564. if (rmap_item->address & STABLE_FLAG) {
  565. struct stable_node *stable_node;
  566. struct page *page;
  567. stable_node = rmap_item->head;
  568. page = get_ksm_page(stable_node, true);
  569. if (!page)
  570. goto out;
  571. hlist_del(&rmap_item->hlist);
  572. unlock_page(page);
  573. put_page(page);
  574. if (!hlist_empty(&stable_node->hlist))
  575. ksm_pages_sharing--;
  576. else
  577. ksm_pages_shared--;
  578. put_anon_vma(rmap_item->anon_vma);
  579. rmap_item->address &= PAGE_MASK;
  580. } else if (rmap_item->address & UNSTABLE_FLAG) {
  581. unsigned char age;
  582. /*
  583. * Usually ksmd can and must skip the rb_erase, because
  584. * root_unstable_tree was already reset to RB_ROOT.
  585. * But be careful when an mm is exiting: do the rb_erase
  586. * if this rmap_item was inserted by this scan, rather
  587. * than left over from before.
  588. */
  589. age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
  590. BUG_ON(age > 1);
  591. if (!age)
  592. rb_erase(&rmap_item->node,
  593. root_unstable_tree + NUMA(rmap_item->nid));
  594. ksm_pages_unshared--;
  595. rmap_item->address &= PAGE_MASK;
  596. }
  597. out:
  598. cond_resched(); /* we're called from many long loops */
  599. }
  600. static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
  601. struct rmap_item **rmap_list)
  602. {
  603. while (*rmap_list) {
  604. struct rmap_item *rmap_item = *rmap_list;
  605. *rmap_list = rmap_item->rmap_list;
  606. remove_rmap_item_from_tree(rmap_item);
  607. free_rmap_item(rmap_item);
  608. }
  609. }
  610. /*
  611. * Though it's very tempting to unmerge rmap_items from stable tree rather
  612. * than check every pte of a given vma, the locking doesn't quite work for
  613. * that - an rmap_item is assigned to the stable tree after inserting ksm
  614. * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
  615. * rmap_items from parent to child at fork time (so as not to waste time
  616. * if exit comes before the next scan reaches it).
  617. *
  618. * Similarly, although we'd like to remove rmap_items (so updating counts
  619. * and freeing memory) when unmerging an area, it's easier to leave that
  620. * to the next pass of ksmd - consider, for example, how ksmd might be
  621. * in cmp_and_merge_page on one of the rmap_items we would be removing.
  622. */
  623. static int unmerge_ksm_pages(struct vm_area_struct *vma,
  624. unsigned long start, unsigned long end)
  625. {
  626. unsigned long addr;
  627. int err = 0;
  628. for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
  629. if (ksm_test_exit(vma->vm_mm))
  630. break;
  631. if (signal_pending(current))
  632. err = -ERESTARTSYS;
  633. else
  634. err = break_ksm(vma, addr);
  635. }
  636. return err;
  637. }
  638. #ifdef CONFIG_SYSFS
  639. /*
  640. * Only called through the sysfs control interface:
  641. */
  642. static int remove_stable_node(struct stable_node *stable_node)
  643. {
  644. struct page *page;
  645. int err;
  646. page = get_ksm_page(stable_node, true);
  647. if (!page) {
  648. /*
  649. * get_ksm_page did remove_node_from_stable_tree itself.
  650. */
  651. return 0;
  652. }
  653. if (WARN_ON_ONCE(page_mapped(page))) {
  654. /*
  655. * This should not happen: but if it does, just refuse to let
  656. * merge_across_nodes be switched - there is no need to panic.
  657. */
  658. err = -EBUSY;
  659. } else {
  660. /*
  661. * The stable node did not yet appear stale to get_ksm_page(),
  662. * since that allows for an unmapped ksm page to be recognized
  663. * right up until it is freed; but the node is safe to remove.
  664. * This page might be in a pagevec waiting to be freed,
  665. * or it might be PageSwapCache (perhaps under writeback),
  666. * or it might have been removed from swapcache a moment ago.
  667. */
  668. set_page_stable_node(page, NULL);
  669. remove_node_from_stable_tree(stable_node);
  670. err = 0;
  671. }
  672. unlock_page(page);
  673. put_page(page);
  674. return err;
  675. }
  676. static int remove_all_stable_nodes(void)
  677. {
  678. struct stable_node *stable_node, *next;
  679. int nid;
  680. int err = 0;
  681. for (nid = 0; nid < ksm_nr_node_ids; nid++) {
  682. while (root_stable_tree[nid].rb_node) {
  683. stable_node = rb_entry(root_stable_tree[nid].rb_node,
  684. struct stable_node, node);
  685. if (remove_stable_node(stable_node)) {
  686. err = -EBUSY;
  687. break; /* proceed to next nid */
  688. }
  689. cond_resched();
  690. }
  691. }
  692. list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
  693. if (remove_stable_node(stable_node))
  694. err = -EBUSY;
  695. cond_resched();
  696. }
  697. return err;
  698. }
  699. static int unmerge_and_remove_all_rmap_items(void)
  700. {
  701. struct mm_slot *mm_slot;
  702. struct mm_struct *mm;
  703. struct vm_area_struct *vma;
  704. int err = 0;
  705. spin_lock(&ksm_mmlist_lock);
  706. ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
  707. struct mm_slot, mm_list);
  708. spin_unlock(&ksm_mmlist_lock);
  709. for (mm_slot = ksm_scan.mm_slot;
  710. mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
  711. mm = mm_slot->mm;
  712. down_read(&mm->mmap_sem);
  713. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  714. if (ksm_test_exit(mm))
  715. break;
  716. if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  717. continue;
  718. err = unmerge_ksm_pages(vma,
  719. vma->vm_start, vma->vm_end);
  720. if (err)
  721. goto error;
  722. }
  723. remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
  724. up_read(&mm->mmap_sem);
  725. spin_lock(&ksm_mmlist_lock);
  726. ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
  727. struct mm_slot, mm_list);
  728. if (ksm_test_exit(mm)) {
  729. hash_del(&mm_slot->link);
  730. list_del(&mm_slot->mm_list);
  731. spin_unlock(&ksm_mmlist_lock);
  732. free_mm_slot(mm_slot);
  733. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  734. mmdrop(mm);
  735. } else
  736. spin_unlock(&ksm_mmlist_lock);
  737. }
  738. /* Clean up stable nodes, but don't worry if some are still busy */
  739. remove_all_stable_nodes();
  740. ksm_scan.seqnr = 0;
  741. return 0;
  742. error:
  743. up_read(&mm->mmap_sem);
  744. spin_lock(&ksm_mmlist_lock);
  745. ksm_scan.mm_slot = &ksm_mm_head;
  746. spin_unlock(&ksm_mmlist_lock);
  747. return err;
  748. }
  749. #endif /* CONFIG_SYSFS */
  750. static u32 calc_checksum(struct page *page)
  751. {
  752. u32 checksum;
  753. void *addr = kmap_atomic(page);
  754. checksum = jhash2(addr, PAGE_SIZE / 4, 17);
  755. kunmap_atomic(addr);
  756. return checksum;
  757. }
  758. static int memcmp_pages(struct page *page1, struct page *page2)
  759. {
  760. char *addr1, *addr2;
  761. int ret;
  762. addr1 = kmap_atomic(page1);
  763. addr2 = kmap_atomic(page2);
  764. ret = memcmp(addr1, addr2, PAGE_SIZE);
  765. kunmap_atomic(addr2);
  766. kunmap_atomic(addr1);
  767. return ret;
  768. }
  769. static inline int pages_identical(struct page *page1, struct page *page2)
  770. {
  771. return !memcmp_pages(page1, page2);
  772. }
  773. static int write_protect_page(struct vm_area_struct *vma, struct page *page,
  774. pte_t *orig_pte)
  775. {
  776. struct mm_struct *mm = vma->vm_mm;
  777. unsigned long addr;
  778. pte_t *ptep;
  779. spinlock_t *ptl;
  780. int swapped;
  781. int err = -EFAULT;
  782. unsigned long mmun_start; /* For mmu_notifiers */
  783. unsigned long mmun_end; /* For mmu_notifiers */
  784. addr = page_address_in_vma(page, vma);
  785. if (addr == -EFAULT)
  786. goto out;
  787. BUG_ON(PageTransCompound(page));
  788. mmun_start = addr;
  789. mmun_end = addr + PAGE_SIZE;
  790. mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
  791. ptep = page_check_address(page, mm, addr, &ptl, 0);
  792. if (!ptep)
  793. goto out_mn;
  794. if (pte_write(*ptep) || pte_dirty(*ptep)) {
  795. pte_t entry;
  796. swapped = PageSwapCache(page);
  797. flush_cache_page(vma, addr, page_to_pfn(page));
  798. /*
  799. * Ok this is tricky, when get_user_pages_fast() run it doesn't
  800. * take any lock, therefore the check that we are going to make
  801. * with the pagecount against the mapcount is racey and
  802. * O_DIRECT can happen right after the check.
  803. * So we clear the pte and flush the tlb before the check
  804. * this assure us that no O_DIRECT can happen after the check
  805. * or in the middle of the check.
  806. */
  807. entry = ptep_clear_flush_notify(vma, addr, ptep);
  808. /*
  809. * Check that no O_DIRECT or similar I/O is in progress on the
  810. * page
  811. */
  812. if (page_mapcount(page) + 1 + swapped != page_count(page)) {
  813. set_pte_at(mm, addr, ptep, entry);
  814. goto out_unlock;
  815. }
  816. if (pte_dirty(entry))
  817. set_page_dirty(page);
  818. entry = pte_mkclean(pte_wrprotect(entry));
  819. set_pte_at_notify(mm, addr, ptep, entry);
  820. }
  821. *orig_pte = *ptep;
  822. err = 0;
  823. out_unlock:
  824. pte_unmap_unlock(ptep, ptl);
  825. out_mn:
  826. mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
  827. out:
  828. return err;
  829. }
  830. /**
  831. * replace_page - replace page in vma by new ksm page
  832. * @vma: vma that holds the pte pointing to page
  833. * @page: the page we are replacing by kpage
  834. * @kpage: the ksm page we replace page by
  835. * @orig_pte: the original value of the pte
  836. *
  837. * Returns 0 on success, -EFAULT on failure.
  838. */
  839. static int replace_page(struct vm_area_struct *vma, struct page *page,
  840. struct page *kpage, pte_t orig_pte)
  841. {
  842. struct mm_struct *mm = vma->vm_mm;
  843. pmd_t *pmd;
  844. pte_t *ptep;
  845. spinlock_t *ptl;
  846. unsigned long addr;
  847. int err = -EFAULT;
  848. unsigned long mmun_start; /* For mmu_notifiers */
  849. unsigned long mmun_end; /* For mmu_notifiers */
  850. addr = page_address_in_vma(page, vma);
  851. if (addr == -EFAULT)
  852. goto out;
  853. pmd = mm_find_pmd(mm, addr);
  854. if (!pmd)
  855. goto out;
  856. mmun_start = addr;
  857. mmun_end = addr + PAGE_SIZE;
  858. mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
  859. ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
  860. if (!pte_same(*ptep, orig_pte)) {
  861. pte_unmap_unlock(ptep, ptl);
  862. goto out_mn;
  863. }
  864. get_page(kpage);
  865. page_add_anon_rmap(kpage, vma, addr, false);
  866. flush_cache_page(vma, addr, pte_pfn(*ptep));
  867. ptep_clear_flush_notify(vma, addr, ptep);
  868. set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
  869. page_remove_rmap(page, false);
  870. if (!page_mapped(page))
  871. try_to_free_swap(page);
  872. put_page(page);
  873. pte_unmap_unlock(ptep, ptl);
  874. err = 0;
  875. out_mn:
  876. mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
  877. out:
  878. return err;
  879. }
  880. /*
  881. * try_to_merge_one_page - take two pages and merge them into one
  882. * @vma: the vma that holds the pte pointing to page
  883. * @page: the PageAnon page that we want to replace with kpage
  884. * @kpage: the PageKsm page that we want to map instead of page,
  885. * or NULL the first time when we want to use page as kpage.
  886. *
  887. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  888. */
  889. static int try_to_merge_one_page(struct vm_area_struct *vma,
  890. struct page *page, struct page *kpage)
  891. {
  892. pte_t orig_pte = __pte(0);
  893. int err = -EFAULT;
  894. if (page == kpage) /* ksm page forked */
  895. return 0;
  896. if (!PageAnon(page))
  897. goto out;
  898. /*
  899. * We need the page lock to read a stable PageSwapCache in
  900. * write_protect_page(). We use trylock_page() instead of
  901. * lock_page() because we don't want to wait here - we
  902. * prefer to continue scanning and merging different pages,
  903. * then come back to this page when it is unlocked.
  904. */
  905. if (!trylock_page(page))
  906. goto out;
  907. if (PageTransCompound(page)) {
  908. if (split_huge_page(page))
  909. goto out_unlock;
  910. }
  911. /*
  912. * If this anonymous page is mapped only here, its pte may need
  913. * to be write-protected. If it's mapped elsewhere, all of its
  914. * ptes are necessarily already write-protected. But in either
  915. * case, we need to lock and check page_count is not raised.
  916. */
  917. if (write_protect_page(vma, page, &orig_pte) == 0) {
  918. if (!kpage) {
  919. /*
  920. * While we hold page lock, upgrade page from
  921. * PageAnon+anon_vma to PageKsm+NULL stable_node:
  922. * stable_tree_insert() will update stable_node.
  923. */
  924. set_page_stable_node(page, NULL);
  925. mark_page_accessed(page);
  926. /*
  927. * Page reclaim just frees a clean page with no dirty
  928. * ptes: make sure that the ksm page would be swapped.
  929. */
  930. if (!PageDirty(page))
  931. SetPageDirty(page);
  932. err = 0;
  933. } else if (pages_identical(page, kpage))
  934. err = replace_page(vma, page, kpage, orig_pte);
  935. }
  936. if ((vma->vm_flags & VM_LOCKED) && kpage && !err) {
  937. munlock_vma_page(page);
  938. if (!PageMlocked(kpage)) {
  939. unlock_page(page);
  940. lock_page(kpage);
  941. mlock_vma_page(kpage);
  942. page = kpage; /* for final unlock */
  943. }
  944. }
  945. out_unlock:
  946. unlock_page(page);
  947. out:
  948. return err;
  949. }
  950. /*
  951. * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
  952. * but no new kernel page is allocated: kpage must already be a ksm page.
  953. *
  954. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  955. */
  956. static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
  957. struct page *page, struct page *kpage)
  958. {
  959. struct mm_struct *mm = rmap_item->mm;
  960. struct vm_area_struct *vma;
  961. int err = -EFAULT;
  962. down_read(&mm->mmap_sem);
  963. vma = find_mergeable_vma(mm, rmap_item->address);
  964. if (!vma)
  965. goto out;
  966. err = try_to_merge_one_page(vma, page, kpage);
  967. if (err)
  968. goto out;
  969. /* Unstable nid is in union with stable anon_vma: remove first */
  970. remove_rmap_item_from_tree(rmap_item);
  971. /* Must get reference to anon_vma while still holding mmap_sem */
  972. rmap_item->anon_vma = vma->anon_vma;
  973. get_anon_vma(vma->anon_vma);
  974. out:
  975. up_read(&mm->mmap_sem);
  976. return err;
  977. }
  978. /*
  979. * try_to_merge_two_pages - take two identical pages and prepare them
  980. * to be merged into one page.
  981. *
  982. * This function returns the kpage if we successfully merged two identical
  983. * pages into one ksm page, NULL otherwise.
  984. *
  985. * Note that this function upgrades page to ksm page: if one of the pages
  986. * is already a ksm page, try_to_merge_with_ksm_page should be used.
  987. */
  988. static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
  989. struct page *page,
  990. struct rmap_item *tree_rmap_item,
  991. struct page *tree_page)
  992. {
  993. int err;
  994. err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
  995. if (!err) {
  996. err = try_to_merge_with_ksm_page(tree_rmap_item,
  997. tree_page, page);
  998. /*
  999. * If that fails, we have a ksm page with only one pte
  1000. * pointing to it: so break it.
  1001. */
  1002. if (err)
  1003. break_cow(rmap_item);
  1004. }
  1005. return err ? NULL : page;
  1006. }
  1007. /*
  1008. * stable_tree_search - search for page inside the stable tree
  1009. *
  1010. * This function checks if there is a page inside the stable tree
  1011. * with identical content to the page that we are scanning right now.
  1012. *
  1013. * This function returns the stable tree node of identical content if found,
  1014. * NULL otherwise.
  1015. */
  1016. static struct page *stable_tree_search(struct page *page)
  1017. {
  1018. int nid;
  1019. struct rb_root *root;
  1020. struct rb_node **new;
  1021. struct rb_node *parent;
  1022. struct stable_node *stable_node;
  1023. struct stable_node *page_node;
  1024. page_node = page_stable_node(page);
  1025. if (page_node && page_node->head != &migrate_nodes) {
  1026. /* ksm page forked */
  1027. get_page(page);
  1028. return page;
  1029. }
  1030. nid = get_kpfn_nid(page_to_pfn(page));
  1031. root = root_stable_tree + nid;
  1032. again:
  1033. new = &root->rb_node;
  1034. parent = NULL;
  1035. while (*new) {
  1036. struct page *tree_page;
  1037. int ret;
  1038. cond_resched();
  1039. stable_node = rb_entry(*new, struct stable_node, node);
  1040. tree_page = get_ksm_page(stable_node, false);
  1041. if (!tree_page) {
  1042. /*
  1043. * If we walked over a stale stable_node,
  1044. * get_ksm_page() will call rb_erase() and it
  1045. * may rebalance the tree from under us. So
  1046. * restart the search from scratch. Returning
  1047. * NULL would be safe too, but we'd generate
  1048. * false negative insertions just because some
  1049. * stable_node was stale.
  1050. */
  1051. goto again;
  1052. }
  1053. ret = memcmp_pages(page, tree_page);
  1054. put_page(tree_page);
  1055. parent = *new;
  1056. if (ret < 0)
  1057. new = &parent->rb_left;
  1058. else if (ret > 0)
  1059. new = &parent->rb_right;
  1060. else {
  1061. /*
  1062. * Lock and unlock the stable_node's page (which
  1063. * might already have been migrated) so that page
  1064. * migration is sure to notice its raised count.
  1065. * It would be more elegant to return stable_node
  1066. * than kpage, but that involves more changes.
  1067. */
  1068. tree_page = get_ksm_page(stable_node, true);
  1069. if (tree_page) {
  1070. unlock_page(tree_page);
  1071. if (get_kpfn_nid(stable_node->kpfn) !=
  1072. NUMA(stable_node->nid)) {
  1073. put_page(tree_page);
  1074. goto replace;
  1075. }
  1076. return tree_page;
  1077. }
  1078. /*
  1079. * There is now a place for page_node, but the tree may
  1080. * have been rebalanced, so re-evaluate parent and new.
  1081. */
  1082. if (page_node)
  1083. goto again;
  1084. return NULL;
  1085. }
  1086. }
  1087. if (!page_node)
  1088. return NULL;
  1089. list_del(&page_node->list);
  1090. DO_NUMA(page_node->nid = nid);
  1091. rb_link_node(&page_node->node, parent, new);
  1092. rb_insert_color(&page_node->node, root);
  1093. get_page(page);
  1094. return page;
  1095. replace:
  1096. if (page_node) {
  1097. list_del(&page_node->list);
  1098. DO_NUMA(page_node->nid = nid);
  1099. rb_replace_node(&stable_node->node, &page_node->node, root);
  1100. get_page(page);
  1101. } else {
  1102. rb_erase(&stable_node->node, root);
  1103. page = NULL;
  1104. }
  1105. stable_node->head = &migrate_nodes;
  1106. list_add(&stable_node->list, stable_node->head);
  1107. return page;
  1108. }
  1109. /*
  1110. * stable_tree_insert - insert stable tree node pointing to new ksm page
  1111. * into the stable tree.
  1112. *
  1113. * This function returns the stable tree node just allocated on success,
  1114. * NULL otherwise.
  1115. */
  1116. static struct stable_node *stable_tree_insert(struct page *kpage)
  1117. {
  1118. int nid;
  1119. unsigned long kpfn;
  1120. struct rb_root *root;
  1121. struct rb_node **new;
  1122. struct rb_node *parent;
  1123. struct stable_node *stable_node;
  1124. kpfn = page_to_pfn(kpage);
  1125. nid = get_kpfn_nid(kpfn);
  1126. root = root_stable_tree + nid;
  1127. again:
  1128. parent = NULL;
  1129. new = &root->rb_node;
  1130. while (*new) {
  1131. struct page *tree_page;
  1132. int ret;
  1133. cond_resched();
  1134. stable_node = rb_entry(*new, struct stable_node, node);
  1135. tree_page = get_ksm_page(stable_node, false);
  1136. if (!tree_page) {
  1137. /*
  1138. * If we walked over a stale stable_node,
  1139. * get_ksm_page() will call rb_erase() and it
  1140. * may rebalance the tree from under us. So
  1141. * restart the search from scratch. Returning
  1142. * NULL would be safe too, but we'd generate
  1143. * false negative insertions just because some
  1144. * stable_node was stale.
  1145. */
  1146. goto again;
  1147. }
  1148. ret = memcmp_pages(kpage, tree_page);
  1149. put_page(tree_page);
  1150. parent = *new;
  1151. if (ret < 0)
  1152. new = &parent->rb_left;
  1153. else if (ret > 0)
  1154. new = &parent->rb_right;
  1155. else {
  1156. /*
  1157. * It is not a bug that stable_tree_search() didn't
  1158. * find this node: because at that time our page was
  1159. * not yet write-protected, so may have changed since.
  1160. */
  1161. return NULL;
  1162. }
  1163. }
  1164. stable_node = alloc_stable_node();
  1165. if (!stable_node)
  1166. return NULL;
  1167. INIT_HLIST_HEAD(&stable_node->hlist);
  1168. stable_node->kpfn = kpfn;
  1169. set_page_stable_node(kpage, stable_node);
  1170. DO_NUMA(stable_node->nid = nid);
  1171. rb_link_node(&stable_node->node, parent, new);
  1172. rb_insert_color(&stable_node->node, root);
  1173. return stable_node;
  1174. }
  1175. /*
  1176. * unstable_tree_search_insert - search for identical page,
  1177. * else insert rmap_item into the unstable tree.
  1178. *
  1179. * This function searches for a page in the unstable tree identical to the
  1180. * page currently being scanned; and if no identical page is found in the
  1181. * tree, we insert rmap_item as a new object into the unstable tree.
  1182. *
  1183. * This function returns pointer to rmap_item found to be identical
  1184. * to the currently scanned page, NULL otherwise.
  1185. *
  1186. * This function does both searching and inserting, because they share
  1187. * the same walking algorithm in an rbtree.
  1188. */
  1189. static
  1190. struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
  1191. struct page *page,
  1192. struct page **tree_pagep)
  1193. {
  1194. struct rb_node **new;
  1195. struct rb_root *root;
  1196. struct rb_node *parent = NULL;
  1197. int nid;
  1198. nid = get_kpfn_nid(page_to_pfn(page));
  1199. root = root_unstable_tree + nid;
  1200. new = &root->rb_node;
  1201. while (*new) {
  1202. struct rmap_item *tree_rmap_item;
  1203. struct page *tree_page;
  1204. int ret;
  1205. cond_resched();
  1206. tree_rmap_item = rb_entry(*new, struct rmap_item, node);
  1207. tree_page = get_mergeable_page(tree_rmap_item);
  1208. if (!tree_page)
  1209. return NULL;
  1210. /*
  1211. * Don't substitute a ksm page for a forked page.
  1212. */
  1213. if (page == tree_page) {
  1214. put_page(tree_page);
  1215. return NULL;
  1216. }
  1217. ret = memcmp_pages(page, tree_page);
  1218. parent = *new;
  1219. if (ret < 0) {
  1220. put_page(tree_page);
  1221. new = &parent->rb_left;
  1222. } else if (ret > 0) {
  1223. put_page(tree_page);
  1224. new = &parent->rb_right;
  1225. } else if (!ksm_merge_across_nodes &&
  1226. page_to_nid(tree_page) != nid) {
  1227. /*
  1228. * If tree_page has been migrated to another NUMA node,
  1229. * it will be flushed out and put in the right unstable
  1230. * tree next time: only merge with it when across_nodes.
  1231. */
  1232. put_page(tree_page);
  1233. return NULL;
  1234. } else {
  1235. *tree_pagep = tree_page;
  1236. return tree_rmap_item;
  1237. }
  1238. }
  1239. rmap_item->address |= UNSTABLE_FLAG;
  1240. rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
  1241. DO_NUMA(rmap_item->nid = nid);
  1242. rb_link_node(&rmap_item->node, parent, new);
  1243. rb_insert_color(&rmap_item->node, root);
  1244. ksm_pages_unshared++;
  1245. return NULL;
  1246. }
  1247. /*
  1248. * stable_tree_append - add another rmap_item to the linked list of
  1249. * rmap_items hanging off a given node of the stable tree, all sharing
  1250. * the same ksm page.
  1251. */
  1252. static void stable_tree_append(struct rmap_item *rmap_item,
  1253. struct stable_node *stable_node)
  1254. {
  1255. rmap_item->head = stable_node;
  1256. rmap_item->address |= STABLE_FLAG;
  1257. hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
  1258. if (rmap_item->hlist.next)
  1259. ksm_pages_sharing++;
  1260. else
  1261. ksm_pages_shared++;
  1262. }
  1263. /*
  1264. * cmp_and_merge_page - first see if page can be merged into the stable tree;
  1265. * if not, compare checksum to previous and if it's the same, see if page can
  1266. * be inserted into the unstable tree, or merged with a page already there and
  1267. * both transferred to the stable tree.
  1268. *
  1269. * @page: the page that we are searching identical page to.
  1270. * @rmap_item: the reverse mapping into the virtual address of this page
  1271. */
  1272. static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
  1273. {
  1274. struct rmap_item *tree_rmap_item;
  1275. struct page *tree_page = NULL;
  1276. struct stable_node *stable_node;
  1277. struct page *kpage;
  1278. unsigned int checksum;
  1279. int err;
  1280. stable_node = page_stable_node(page);
  1281. if (stable_node) {
  1282. if (stable_node->head != &migrate_nodes &&
  1283. get_kpfn_nid(stable_node->kpfn) != NUMA(stable_node->nid)) {
  1284. rb_erase(&stable_node->node,
  1285. root_stable_tree + NUMA(stable_node->nid));
  1286. stable_node->head = &migrate_nodes;
  1287. list_add(&stable_node->list, stable_node->head);
  1288. }
  1289. if (stable_node->head != &migrate_nodes &&
  1290. rmap_item->head == stable_node)
  1291. return;
  1292. }
  1293. /* We first start with searching the page inside the stable tree */
  1294. kpage = stable_tree_search(page);
  1295. if (kpage == page && rmap_item->head == stable_node) {
  1296. put_page(kpage);
  1297. return;
  1298. }
  1299. remove_rmap_item_from_tree(rmap_item);
  1300. if (kpage) {
  1301. err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
  1302. if (!err) {
  1303. /*
  1304. * The page was successfully merged:
  1305. * add its rmap_item to the stable tree.
  1306. */
  1307. lock_page(kpage);
  1308. stable_tree_append(rmap_item, page_stable_node(kpage));
  1309. unlock_page(kpage);
  1310. }
  1311. put_page(kpage);
  1312. return;
  1313. }
  1314. /*
  1315. * If the hash value of the page has changed from the last time
  1316. * we calculated it, this page is changing frequently: therefore we
  1317. * don't want to insert it in the unstable tree, and we don't want
  1318. * to waste our time searching for something identical to it there.
  1319. */
  1320. checksum = calc_checksum(page);
  1321. if (rmap_item->oldchecksum != checksum) {
  1322. rmap_item->oldchecksum = checksum;
  1323. return;
  1324. }
  1325. tree_rmap_item =
  1326. unstable_tree_search_insert(rmap_item, page, &tree_page);
  1327. if (tree_rmap_item) {
  1328. bool split;
  1329. kpage = try_to_merge_two_pages(rmap_item, page,
  1330. tree_rmap_item, tree_page);
  1331. /*
  1332. * If both pages we tried to merge belong to the same compound
  1333. * page, then we actually ended up increasing the reference
  1334. * count of the same compound page twice, and split_huge_page
  1335. * failed.
  1336. * Here we set a flag if that happened, and we use it later to
  1337. * try split_huge_page again. Since we call put_page right
  1338. * afterwards, the reference count will be correct and
  1339. * split_huge_page should succeed.
  1340. */
  1341. split = PageTransCompound(page)
  1342. && compound_head(page) == compound_head(tree_page);
  1343. put_page(tree_page);
  1344. if (kpage) {
  1345. /*
  1346. * The pages were successfully merged: insert new
  1347. * node in the stable tree and add both rmap_items.
  1348. */
  1349. lock_page(kpage);
  1350. stable_node = stable_tree_insert(kpage);
  1351. if (stable_node) {
  1352. stable_tree_append(tree_rmap_item, stable_node);
  1353. stable_tree_append(rmap_item, stable_node);
  1354. }
  1355. unlock_page(kpage);
  1356. /*
  1357. * If we fail to insert the page into the stable tree,
  1358. * we will have 2 virtual addresses that are pointing
  1359. * to a ksm page left outside the stable tree,
  1360. * in which case we need to break_cow on both.
  1361. */
  1362. if (!stable_node) {
  1363. break_cow(tree_rmap_item);
  1364. break_cow(rmap_item);
  1365. }
  1366. } else if (split) {
  1367. /*
  1368. * We are here if we tried to merge two pages and
  1369. * failed because they both belonged to the same
  1370. * compound page. We will split the page now, but no
  1371. * merging will take place.
  1372. * We do not want to add the cost of a full lock; if
  1373. * the page is locked, it is better to skip it and
  1374. * perhaps try again later.
  1375. */
  1376. if (!trylock_page(page))
  1377. return;
  1378. split_huge_page(page);
  1379. unlock_page(page);
  1380. }
  1381. }
  1382. }
  1383. static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
  1384. struct rmap_item **rmap_list,
  1385. unsigned long addr)
  1386. {
  1387. struct rmap_item *rmap_item;
  1388. while (*rmap_list) {
  1389. rmap_item = *rmap_list;
  1390. if ((rmap_item->address & PAGE_MASK) == addr)
  1391. return rmap_item;
  1392. if (rmap_item->address > addr)
  1393. break;
  1394. *rmap_list = rmap_item->rmap_list;
  1395. remove_rmap_item_from_tree(rmap_item);
  1396. free_rmap_item(rmap_item);
  1397. }
  1398. rmap_item = alloc_rmap_item();
  1399. if (rmap_item) {
  1400. /* It has already been zeroed */
  1401. rmap_item->mm = mm_slot->mm;
  1402. rmap_item->address = addr;
  1403. rmap_item->rmap_list = *rmap_list;
  1404. *rmap_list = rmap_item;
  1405. }
  1406. return rmap_item;
  1407. }
  1408. static struct rmap_item *scan_get_next_rmap_item(struct page **page)
  1409. {
  1410. struct mm_struct *mm;
  1411. struct mm_slot *slot;
  1412. struct vm_area_struct *vma;
  1413. struct rmap_item *rmap_item;
  1414. int nid;
  1415. if (list_empty(&ksm_mm_head.mm_list))
  1416. return NULL;
  1417. slot = ksm_scan.mm_slot;
  1418. if (slot == &ksm_mm_head) {
  1419. /*
  1420. * A number of pages can hang around indefinitely on per-cpu
  1421. * pagevecs, raised page count preventing write_protect_page
  1422. * from merging them. Though it doesn't really matter much,
  1423. * it is puzzling to see some stuck in pages_volatile until
  1424. * other activity jostles them out, and they also prevented
  1425. * LTP's KSM test from succeeding deterministically; so drain
  1426. * them here (here rather than on entry to ksm_do_scan(),
  1427. * so we don't IPI too often when pages_to_scan is set low).
  1428. */
  1429. lru_add_drain_all();
  1430. /*
  1431. * Whereas stale stable_nodes on the stable_tree itself
  1432. * get pruned in the regular course of stable_tree_search(),
  1433. * those moved out to the migrate_nodes list can accumulate:
  1434. * so prune them once before each full scan.
  1435. */
  1436. if (!ksm_merge_across_nodes) {
  1437. struct stable_node *stable_node, *next;
  1438. struct page *page;
  1439. list_for_each_entry_safe(stable_node, next,
  1440. &migrate_nodes, list) {
  1441. page = get_ksm_page(stable_node, false);
  1442. if (page)
  1443. put_page(page);
  1444. cond_resched();
  1445. }
  1446. }
  1447. for (nid = 0; nid < ksm_nr_node_ids; nid++)
  1448. root_unstable_tree[nid] = RB_ROOT;
  1449. spin_lock(&ksm_mmlist_lock);
  1450. slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
  1451. ksm_scan.mm_slot = slot;
  1452. spin_unlock(&ksm_mmlist_lock);
  1453. /*
  1454. * Although we tested list_empty() above, a racing __ksm_exit
  1455. * of the last mm on the list may have removed it since then.
  1456. */
  1457. if (slot == &ksm_mm_head)
  1458. return NULL;
  1459. next_mm:
  1460. ksm_scan.address = 0;
  1461. ksm_scan.rmap_list = &slot->rmap_list;
  1462. }
  1463. mm = slot->mm;
  1464. down_read(&mm->mmap_sem);
  1465. if (ksm_test_exit(mm))
  1466. vma = NULL;
  1467. else
  1468. vma = find_vma(mm, ksm_scan.address);
  1469. for (; vma; vma = vma->vm_next) {
  1470. if (!(vma->vm_flags & VM_MERGEABLE))
  1471. continue;
  1472. if (ksm_scan.address < vma->vm_start)
  1473. ksm_scan.address = vma->vm_start;
  1474. if (!vma->anon_vma)
  1475. ksm_scan.address = vma->vm_end;
  1476. while (ksm_scan.address < vma->vm_end) {
  1477. if (ksm_test_exit(mm))
  1478. break;
  1479. *page = follow_page(vma, ksm_scan.address, FOLL_GET);
  1480. if (IS_ERR_OR_NULL(*page)) {
  1481. ksm_scan.address += PAGE_SIZE;
  1482. cond_resched();
  1483. continue;
  1484. }
  1485. if (PageAnon(*page)) {
  1486. flush_anon_page(vma, *page, ksm_scan.address);
  1487. flush_dcache_page(*page);
  1488. rmap_item = get_next_rmap_item(slot,
  1489. ksm_scan.rmap_list, ksm_scan.address);
  1490. if (rmap_item) {
  1491. ksm_scan.rmap_list =
  1492. &rmap_item->rmap_list;
  1493. ksm_scan.address += PAGE_SIZE;
  1494. } else
  1495. put_page(*page);
  1496. up_read(&mm->mmap_sem);
  1497. return rmap_item;
  1498. }
  1499. put_page(*page);
  1500. ksm_scan.address += PAGE_SIZE;
  1501. cond_resched();
  1502. }
  1503. }
  1504. if (ksm_test_exit(mm)) {
  1505. ksm_scan.address = 0;
  1506. ksm_scan.rmap_list = &slot->rmap_list;
  1507. }
  1508. /*
  1509. * Nuke all the rmap_items that are above this current rmap:
  1510. * because there were no VM_MERGEABLE vmas with such addresses.
  1511. */
  1512. remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
  1513. spin_lock(&ksm_mmlist_lock);
  1514. ksm_scan.mm_slot = list_entry(slot->mm_list.next,
  1515. struct mm_slot, mm_list);
  1516. if (ksm_scan.address == 0) {
  1517. /*
  1518. * We've completed a full scan of all vmas, holding mmap_sem
  1519. * throughout, and found no VM_MERGEABLE: so do the same as
  1520. * __ksm_exit does to remove this mm from all our lists now.
  1521. * This applies either when cleaning up after __ksm_exit
  1522. * (but beware: we can reach here even before __ksm_exit),
  1523. * or when all VM_MERGEABLE areas have been unmapped (and
  1524. * mmap_sem then protects against race with MADV_MERGEABLE).
  1525. */
  1526. hash_del(&slot->link);
  1527. list_del(&slot->mm_list);
  1528. spin_unlock(&ksm_mmlist_lock);
  1529. free_mm_slot(slot);
  1530. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  1531. up_read(&mm->mmap_sem);
  1532. mmdrop(mm);
  1533. } else {
  1534. up_read(&mm->mmap_sem);
  1535. /*
  1536. * up_read(&mm->mmap_sem) first because after
  1537. * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
  1538. * already have been freed under us by __ksm_exit()
  1539. * because the "mm_slot" is still hashed and
  1540. * ksm_scan.mm_slot doesn't point to it anymore.
  1541. */
  1542. spin_unlock(&ksm_mmlist_lock);
  1543. }
  1544. /* Repeat until we've completed scanning the whole list */
  1545. slot = ksm_scan.mm_slot;
  1546. if (slot != &ksm_mm_head)
  1547. goto next_mm;
  1548. ksm_scan.seqnr++;
  1549. return NULL;
  1550. }
  1551. /**
  1552. * ksm_do_scan - the ksm scanner main worker function.
  1553. * @scan_npages - number of pages we want to scan before we return.
  1554. */
  1555. static void ksm_do_scan(unsigned int scan_npages)
  1556. {
  1557. struct rmap_item *rmap_item;
  1558. struct page *uninitialized_var(page);
  1559. while (scan_npages-- && likely(!freezing(current))) {
  1560. cond_resched();
  1561. rmap_item = scan_get_next_rmap_item(&page);
  1562. if (!rmap_item)
  1563. return;
  1564. cmp_and_merge_page(page, rmap_item);
  1565. put_page(page);
  1566. }
  1567. }
  1568. static void process_timeout(unsigned long __data)
  1569. {
  1570. wake_up_process((struct task_struct *)__data);
  1571. }
  1572. static signed long __sched deferred_schedule_timeout(signed long timeout)
  1573. {
  1574. struct timer_list timer;
  1575. unsigned long expire;
  1576. __set_current_state(TASK_INTERRUPTIBLE);
  1577. if (timeout < 0) {
  1578. pr_err("schedule_timeout: wrong timeout value %lx\n",
  1579. timeout);
  1580. __set_current_state(TASK_RUNNING);
  1581. goto out;
  1582. }
  1583. expire = timeout + jiffies;
  1584. setup_deferrable_timer_on_stack(&timer, process_timeout,
  1585. (unsigned long)current);
  1586. mod_timer(&timer, expire);
  1587. schedule();
  1588. del_singleshot_timer_sync(&timer);
  1589. /* Remove the timer from the object tracker */
  1590. destroy_timer_on_stack(&timer);
  1591. timeout = expire - jiffies;
  1592. out:
  1593. return timeout < 0 ? 0 : timeout;
  1594. }
  1595. static int ksmd_should_run(void)
  1596. {
  1597. return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
  1598. }
  1599. static int ksm_scan_thread(void *nothing)
  1600. {
  1601. set_freezable();
  1602. set_user_nice(current, 5);
  1603. while (!kthread_should_stop()) {
  1604. mutex_lock(&ksm_thread_mutex);
  1605. wait_while_offlining();
  1606. if (ksmd_should_run())
  1607. ksm_do_scan(ksm_thread_pages_to_scan);
  1608. mutex_unlock(&ksm_thread_mutex);
  1609. try_to_freeze();
  1610. if (ksmd_should_run()) {
  1611. if (use_deferred_timer)
  1612. deferred_schedule_timeout(
  1613. msecs_to_jiffies(ksm_thread_sleep_millisecs));
  1614. else
  1615. schedule_timeout_interruptible(
  1616. msecs_to_jiffies(ksm_thread_sleep_millisecs));
  1617. } else {
  1618. wait_event_freezable(ksm_thread_wait,
  1619. ksmd_should_run() || kthread_should_stop());
  1620. }
  1621. }
  1622. return 0;
  1623. }
  1624. int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
  1625. unsigned long end, int advice, unsigned long *vm_flags)
  1626. {
  1627. struct mm_struct *mm = vma->vm_mm;
  1628. int err;
  1629. switch (advice) {
  1630. case MADV_MERGEABLE:
  1631. /*
  1632. * Be somewhat over-protective for now!
  1633. */
  1634. if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
  1635. VM_PFNMAP | VM_IO | VM_DONTEXPAND |
  1636. VM_HUGETLB | VM_MIXEDMAP))
  1637. return 0; /* just ignore the advice */
  1638. #ifdef VM_SAO
  1639. if (*vm_flags & VM_SAO)
  1640. return 0;
  1641. #endif
  1642. if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
  1643. err = __ksm_enter(mm);
  1644. if (err)
  1645. return err;
  1646. }
  1647. *vm_flags |= VM_MERGEABLE;
  1648. break;
  1649. case MADV_UNMERGEABLE:
  1650. if (!(*vm_flags & VM_MERGEABLE))
  1651. return 0; /* just ignore the advice */
  1652. if (vma->anon_vma) {
  1653. err = unmerge_ksm_pages(vma, start, end);
  1654. if (err)
  1655. return err;
  1656. }
  1657. *vm_flags &= ~VM_MERGEABLE;
  1658. break;
  1659. }
  1660. return 0;
  1661. }
  1662. int __ksm_enter(struct mm_struct *mm)
  1663. {
  1664. struct mm_slot *mm_slot;
  1665. int needs_wakeup;
  1666. mm_slot = alloc_mm_slot();
  1667. if (!mm_slot)
  1668. return -ENOMEM;
  1669. /* Check ksm_run too? Would need tighter locking */
  1670. needs_wakeup = list_empty(&ksm_mm_head.mm_list);
  1671. spin_lock(&ksm_mmlist_lock);
  1672. insert_to_mm_slots_hash(mm, mm_slot);
  1673. /*
  1674. * When KSM_RUN_MERGE (or KSM_RUN_STOP),
  1675. * insert just behind the scanning cursor, to let the area settle
  1676. * down a little; when fork is followed by immediate exec, we don't
  1677. * want ksmd to waste time setting up and tearing down an rmap_list.
  1678. *
  1679. * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
  1680. * scanning cursor, otherwise KSM pages in newly forked mms will be
  1681. * missed: then we might as well insert at the end of the list.
  1682. */
  1683. if (ksm_run & KSM_RUN_UNMERGE)
  1684. list_add_tail(&mm_slot->mm_list, &ksm_mm_head.mm_list);
  1685. else
  1686. list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
  1687. spin_unlock(&ksm_mmlist_lock);
  1688. set_bit(MMF_VM_MERGEABLE, &mm->flags);
  1689. atomic_inc(&mm->mm_count);
  1690. if (needs_wakeup)
  1691. wake_up_interruptible(&ksm_thread_wait);
  1692. return 0;
  1693. }
  1694. void __ksm_exit(struct mm_struct *mm)
  1695. {
  1696. struct mm_slot *mm_slot;
  1697. int easy_to_free = 0;
  1698. /*
  1699. * This process is exiting: if it's straightforward (as is the
  1700. * case when ksmd was never running), free mm_slot immediately.
  1701. * But if it's at the cursor or has rmap_items linked to it, use
  1702. * mmap_sem to synchronize with any break_cows before pagetables
  1703. * are freed, and leave the mm_slot on the list for ksmd to free.
  1704. * Beware: ksm may already have noticed it exiting and freed the slot.
  1705. */
  1706. spin_lock(&ksm_mmlist_lock);
  1707. mm_slot = get_mm_slot(mm);
  1708. if (mm_slot && ksm_scan.mm_slot != mm_slot) {
  1709. if (!mm_slot->rmap_list) {
  1710. hash_del(&mm_slot->link);
  1711. list_del(&mm_slot->mm_list);
  1712. easy_to_free = 1;
  1713. } else {
  1714. list_move(&mm_slot->mm_list,
  1715. &ksm_scan.mm_slot->mm_list);
  1716. }
  1717. }
  1718. spin_unlock(&ksm_mmlist_lock);
  1719. if (easy_to_free) {
  1720. free_mm_slot(mm_slot);
  1721. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  1722. mmdrop(mm);
  1723. } else if (mm_slot) {
  1724. down_write(&mm->mmap_sem);
  1725. up_write(&mm->mmap_sem);
  1726. }
  1727. }
  1728. struct page *ksm_might_need_to_copy(struct page *page,
  1729. struct vm_area_struct *vma, unsigned long address)
  1730. {
  1731. struct anon_vma *anon_vma = page_anon_vma(page);
  1732. struct page *new_page;
  1733. if (PageKsm(page)) {
  1734. if (page_stable_node(page) &&
  1735. !(ksm_run & KSM_RUN_UNMERGE))
  1736. return page; /* no need to copy it */
  1737. } else if (!anon_vma) {
  1738. return page; /* no need to copy it */
  1739. } else if (anon_vma->root == vma->anon_vma->root &&
  1740. page->index == linear_page_index(vma, address)) {
  1741. return page; /* still no need to copy it */
  1742. }
  1743. if (!PageUptodate(page))
  1744. return page; /* let do_swap_page report the error */
  1745. new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
  1746. if (new_page) {
  1747. copy_user_highpage(new_page, page, address, vma);
  1748. SetPageDirty(new_page);
  1749. __SetPageUptodate(new_page);
  1750. __SetPageLocked(new_page);
  1751. }
  1752. return new_page;
  1753. }
  1754. int rmap_walk_ksm(struct page *page, struct rmap_walk_control *rwc)
  1755. {
  1756. struct stable_node *stable_node;
  1757. struct rmap_item *rmap_item;
  1758. int ret = SWAP_AGAIN;
  1759. int search_new_forks = 0;
  1760. VM_BUG_ON_PAGE(!PageKsm(page), page);
  1761. /*
  1762. * Rely on the page lock to protect against concurrent modifications
  1763. * to that page's node of the stable tree.
  1764. */
  1765. VM_BUG_ON_PAGE(!PageLocked(page), page);
  1766. stable_node = page_stable_node(page);
  1767. if (!stable_node)
  1768. return ret;
  1769. again:
  1770. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  1771. struct anon_vma *anon_vma = rmap_item->anon_vma;
  1772. struct anon_vma_chain *vmac;
  1773. struct vm_area_struct *vma;
  1774. cond_resched();
  1775. anon_vma_lock_read(anon_vma);
  1776. anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
  1777. 0, ULONG_MAX) {
  1778. cond_resched();
  1779. vma = vmac->vma;
  1780. if (rmap_item->address < vma->vm_start ||
  1781. rmap_item->address >= vma->vm_end)
  1782. continue;
  1783. /*
  1784. * Initially we examine only the vma which covers this
  1785. * rmap_item; but later, if there is still work to do,
  1786. * we examine covering vmas in other mms: in case they
  1787. * were forked from the original since ksmd passed.
  1788. */
  1789. if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
  1790. continue;
  1791. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  1792. continue;
  1793. ret = rwc->rmap_one(page, vma,
  1794. rmap_item->address, rwc->arg);
  1795. if (ret != SWAP_AGAIN) {
  1796. anon_vma_unlock_read(anon_vma);
  1797. goto out;
  1798. }
  1799. if (rwc->done && rwc->done(page)) {
  1800. anon_vma_unlock_read(anon_vma);
  1801. goto out;
  1802. }
  1803. }
  1804. anon_vma_unlock_read(anon_vma);
  1805. }
  1806. if (!search_new_forks++)
  1807. goto again;
  1808. out:
  1809. return ret;
  1810. }
  1811. #ifdef CONFIG_MIGRATION
  1812. void ksm_migrate_page(struct page *newpage, struct page *oldpage)
  1813. {
  1814. struct stable_node *stable_node;
  1815. VM_BUG_ON_PAGE(!PageLocked(oldpage), oldpage);
  1816. VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
  1817. VM_BUG_ON_PAGE(newpage->mapping != oldpage->mapping, newpage);
  1818. stable_node = page_stable_node(newpage);
  1819. if (stable_node) {
  1820. VM_BUG_ON_PAGE(stable_node->kpfn != page_to_pfn(oldpage), oldpage);
  1821. stable_node->kpfn = page_to_pfn(newpage);
  1822. /*
  1823. * newpage->mapping was set in advance; now we need smp_wmb()
  1824. * to make sure that the new stable_node->kpfn is visible
  1825. * to get_ksm_page() before it can see that oldpage->mapping
  1826. * has gone stale (or that PageSwapCache has been cleared).
  1827. */
  1828. smp_wmb();
  1829. set_page_stable_node(oldpage, NULL);
  1830. }
  1831. }
  1832. #endif /* CONFIG_MIGRATION */
  1833. #ifdef CONFIG_MEMORY_HOTREMOVE
  1834. static void wait_while_offlining(void)
  1835. {
  1836. while (ksm_run & KSM_RUN_OFFLINE) {
  1837. mutex_unlock(&ksm_thread_mutex);
  1838. wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
  1839. TASK_UNINTERRUPTIBLE);
  1840. mutex_lock(&ksm_thread_mutex);
  1841. }
  1842. }
  1843. static void ksm_check_stable_tree(unsigned long start_pfn,
  1844. unsigned long end_pfn)
  1845. {
  1846. struct stable_node *stable_node, *next;
  1847. struct rb_node *node;
  1848. int nid;
  1849. for (nid = 0; nid < ksm_nr_node_ids; nid++) {
  1850. node = rb_first(root_stable_tree + nid);
  1851. while (node) {
  1852. stable_node = rb_entry(node, struct stable_node, node);
  1853. if (stable_node->kpfn >= start_pfn &&
  1854. stable_node->kpfn < end_pfn) {
  1855. /*
  1856. * Don't get_ksm_page, page has already gone:
  1857. * which is why we keep kpfn instead of page*
  1858. */
  1859. remove_node_from_stable_tree(stable_node);
  1860. node = rb_first(root_stable_tree + nid);
  1861. } else
  1862. node = rb_next(node);
  1863. cond_resched();
  1864. }
  1865. }
  1866. list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
  1867. if (stable_node->kpfn >= start_pfn &&
  1868. stable_node->kpfn < end_pfn)
  1869. remove_node_from_stable_tree(stable_node);
  1870. cond_resched();
  1871. }
  1872. }
  1873. static int ksm_memory_callback(struct notifier_block *self,
  1874. unsigned long action, void *arg)
  1875. {
  1876. struct memory_notify *mn = arg;
  1877. switch (action) {
  1878. case MEM_GOING_OFFLINE:
  1879. /*
  1880. * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
  1881. * and remove_all_stable_nodes() while memory is going offline:
  1882. * it is unsafe for them to touch the stable tree at this time.
  1883. * But unmerge_ksm_pages(), rmap lookups and other entry points
  1884. * which do not need the ksm_thread_mutex are all safe.
  1885. */
  1886. mutex_lock(&ksm_thread_mutex);
  1887. ksm_run |= KSM_RUN_OFFLINE;
  1888. mutex_unlock(&ksm_thread_mutex);
  1889. break;
  1890. case MEM_OFFLINE:
  1891. /*
  1892. * Most of the work is done by page migration; but there might
  1893. * be a few stable_nodes left over, still pointing to struct
  1894. * pages which have been offlined: prune those from the tree,
  1895. * otherwise get_ksm_page() might later try to access a
  1896. * non-existent struct page.
  1897. */
  1898. ksm_check_stable_tree(mn->start_pfn,
  1899. mn->start_pfn + mn->nr_pages);
  1900. /* fallthrough */
  1901. case MEM_CANCEL_OFFLINE:
  1902. mutex_lock(&ksm_thread_mutex);
  1903. ksm_run &= ~KSM_RUN_OFFLINE;
  1904. mutex_unlock(&ksm_thread_mutex);
  1905. smp_mb(); /* wake_up_bit advises this */
  1906. wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
  1907. break;
  1908. }
  1909. return NOTIFY_OK;
  1910. }
  1911. #else
  1912. static void wait_while_offlining(void)
  1913. {
  1914. }
  1915. #endif /* CONFIG_MEMORY_HOTREMOVE */
  1916. #ifdef CONFIG_SYSFS
  1917. /*
  1918. * This all compiles without CONFIG_SYSFS, but is a waste of space.
  1919. */
  1920. #define KSM_ATTR_RO(_name) \
  1921. static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
  1922. #define KSM_ATTR(_name) \
  1923. static struct kobj_attribute _name##_attr = \
  1924. __ATTR(_name, 0644, _name##_show, _name##_store)
  1925. static ssize_t sleep_millisecs_show(struct kobject *kobj,
  1926. struct kobj_attribute *attr, char *buf)
  1927. {
  1928. return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
  1929. }
  1930. static ssize_t sleep_millisecs_store(struct kobject *kobj,
  1931. struct kobj_attribute *attr,
  1932. const char *buf, size_t count)
  1933. {
  1934. unsigned long msecs;
  1935. int err;
  1936. err = kstrtoul(buf, 10, &msecs);
  1937. if (err || msecs > UINT_MAX)
  1938. return -EINVAL;
  1939. ksm_thread_sleep_millisecs = msecs;
  1940. return count;
  1941. }
  1942. KSM_ATTR(sleep_millisecs);
  1943. static ssize_t pages_to_scan_show(struct kobject *kobj,
  1944. struct kobj_attribute *attr, char *buf)
  1945. {
  1946. return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
  1947. }
  1948. static ssize_t pages_to_scan_store(struct kobject *kobj,
  1949. struct kobj_attribute *attr,
  1950. const char *buf, size_t count)
  1951. {
  1952. int err;
  1953. unsigned long nr_pages;
  1954. err = kstrtoul(buf, 10, &nr_pages);
  1955. if (err || nr_pages > UINT_MAX)
  1956. return -EINVAL;
  1957. ksm_thread_pages_to_scan = nr_pages;
  1958. return count;
  1959. }
  1960. KSM_ATTR(pages_to_scan);
  1961. static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
  1962. char *buf)
  1963. {
  1964. return sprintf(buf, "%lu\n", ksm_run);
  1965. }
  1966. static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
  1967. const char *buf, size_t count)
  1968. {
  1969. int err;
  1970. unsigned long flags;
  1971. err = kstrtoul(buf, 10, &flags);
  1972. if (err || flags > UINT_MAX)
  1973. return -EINVAL;
  1974. if (flags > KSM_RUN_UNMERGE)
  1975. return -EINVAL;
  1976. /*
  1977. * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
  1978. * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
  1979. * breaking COW to free the pages_shared (but leaves mm_slots
  1980. * on the list for when ksmd may be set running again).
  1981. */
  1982. mutex_lock(&ksm_thread_mutex);
  1983. wait_while_offlining();
  1984. if (ksm_run != flags) {
  1985. ksm_run = flags;
  1986. if (flags & KSM_RUN_UNMERGE) {
  1987. set_current_oom_origin();
  1988. err = unmerge_and_remove_all_rmap_items();
  1989. clear_current_oom_origin();
  1990. if (err) {
  1991. ksm_run = KSM_RUN_STOP;
  1992. count = err;
  1993. }
  1994. }
  1995. }
  1996. mutex_unlock(&ksm_thread_mutex);
  1997. if (flags & KSM_RUN_MERGE)
  1998. wake_up_interruptible(&ksm_thread_wait);
  1999. return count;
  2000. }
  2001. KSM_ATTR(run);
  2002. static ssize_t deferred_timer_show(struct kobject *kobj,
  2003. struct kobj_attribute *attr, char *buf)
  2004. {
  2005. return snprintf(buf, 8, "%d\n", use_deferred_timer);
  2006. }
  2007. static ssize_t deferred_timer_store(struct kobject *kobj,
  2008. struct kobj_attribute *attr,
  2009. const char *buf, size_t count)
  2010. {
  2011. unsigned long enable;
  2012. int err;
  2013. err = kstrtoul(buf, 10, &enable);
  2014. use_deferred_timer = enable;
  2015. return count;
  2016. }
  2017. KSM_ATTR(deferred_timer);
  2018. #ifdef CONFIG_NUMA
  2019. static ssize_t merge_across_nodes_show(struct kobject *kobj,
  2020. struct kobj_attribute *attr, char *buf)
  2021. {
  2022. return sprintf(buf, "%u\n", ksm_merge_across_nodes);
  2023. }
  2024. static ssize_t merge_across_nodes_store(struct kobject *kobj,
  2025. struct kobj_attribute *attr,
  2026. const char *buf, size_t count)
  2027. {
  2028. int err;
  2029. unsigned long knob;
  2030. err = kstrtoul(buf, 10, &knob);
  2031. if (err)
  2032. return err;
  2033. if (knob > 1)
  2034. return -EINVAL;
  2035. mutex_lock(&ksm_thread_mutex);
  2036. wait_while_offlining();
  2037. if (ksm_merge_across_nodes != knob) {
  2038. if (ksm_pages_shared || remove_all_stable_nodes())
  2039. err = -EBUSY;
  2040. else if (root_stable_tree == one_stable_tree) {
  2041. struct rb_root *buf;
  2042. /*
  2043. * This is the first time that we switch away from the
  2044. * default of merging across nodes: must now allocate
  2045. * a buffer to hold as many roots as may be needed.
  2046. * Allocate stable and unstable together:
  2047. * MAXSMP NODES_SHIFT 10 will use 16kB.
  2048. */
  2049. buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf),
  2050. GFP_KERNEL);
  2051. /* Let us assume that RB_ROOT is NULL is zero */
  2052. if (!buf)
  2053. err = -ENOMEM;
  2054. else {
  2055. root_stable_tree = buf;
  2056. root_unstable_tree = buf + nr_node_ids;
  2057. /* Stable tree is empty but not the unstable */
  2058. root_unstable_tree[0] = one_unstable_tree[0];
  2059. }
  2060. }
  2061. if (!err) {
  2062. ksm_merge_across_nodes = knob;
  2063. ksm_nr_node_ids = knob ? 1 : nr_node_ids;
  2064. }
  2065. }
  2066. mutex_unlock(&ksm_thread_mutex);
  2067. return err ? err : count;
  2068. }
  2069. KSM_ATTR(merge_across_nodes);
  2070. #endif
  2071. static ssize_t pages_shared_show(struct kobject *kobj,
  2072. struct kobj_attribute *attr, char *buf)
  2073. {
  2074. return sprintf(buf, "%lu\n", ksm_pages_shared);
  2075. }
  2076. KSM_ATTR_RO(pages_shared);
  2077. static ssize_t pages_sharing_show(struct kobject *kobj,
  2078. struct kobj_attribute *attr, char *buf)
  2079. {
  2080. return sprintf(buf, "%lu\n", ksm_pages_sharing);
  2081. }
  2082. KSM_ATTR_RO(pages_sharing);
  2083. static ssize_t pages_unshared_show(struct kobject *kobj,
  2084. struct kobj_attribute *attr, char *buf)
  2085. {
  2086. return sprintf(buf, "%lu\n", ksm_pages_unshared);
  2087. }
  2088. KSM_ATTR_RO(pages_unshared);
  2089. static ssize_t pages_volatile_show(struct kobject *kobj,
  2090. struct kobj_attribute *attr, char *buf)
  2091. {
  2092. long ksm_pages_volatile;
  2093. ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
  2094. - ksm_pages_sharing - ksm_pages_unshared;
  2095. /*
  2096. * It was not worth any locking to calculate that statistic,
  2097. * but it might therefore sometimes be negative: conceal that.
  2098. */
  2099. if (ksm_pages_volatile < 0)
  2100. ksm_pages_volatile = 0;
  2101. return sprintf(buf, "%ld\n", ksm_pages_volatile);
  2102. }
  2103. KSM_ATTR_RO(pages_volatile);
  2104. static ssize_t full_scans_show(struct kobject *kobj,
  2105. struct kobj_attribute *attr, char *buf)
  2106. {
  2107. return sprintf(buf, "%lu\n", ksm_scan.seqnr);
  2108. }
  2109. KSM_ATTR_RO(full_scans);
  2110. static struct attribute *ksm_attrs[] = {
  2111. &sleep_millisecs_attr.attr,
  2112. &pages_to_scan_attr.attr,
  2113. &run_attr.attr,
  2114. &pages_shared_attr.attr,
  2115. &pages_sharing_attr.attr,
  2116. &pages_unshared_attr.attr,
  2117. &pages_volatile_attr.attr,
  2118. &full_scans_attr.attr,
  2119. &deferred_timer_attr.attr,
  2120. #ifdef CONFIG_NUMA
  2121. &merge_across_nodes_attr.attr,
  2122. #endif
  2123. NULL,
  2124. };
  2125. static struct attribute_group ksm_attr_group = {
  2126. .attrs = ksm_attrs,
  2127. .name = "ksm",
  2128. };
  2129. #endif /* CONFIG_SYSFS */
  2130. static int __init ksm_init(void)
  2131. {
  2132. struct task_struct *ksm_thread;
  2133. int err;
  2134. err = ksm_slab_init();
  2135. if (err)
  2136. goto out;
  2137. ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
  2138. if (IS_ERR(ksm_thread)) {
  2139. pr_err("ksm: creating kthread failed\n");
  2140. err = PTR_ERR(ksm_thread);
  2141. goto out_free;
  2142. }
  2143. #ifdef CONFIG_SYSFS
  2144. err = sysfs_create_group(mm_kobj, &ksm_attr_group);
  2145. if (err) {
  2146. pr_err("ksm: register sysfs failed\n");
  2147. kthread_stop(ksm_thread);
  2148. goto out_free;
  2149. }
  2150. #else
  2151. ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
  2152. #endif /* CONFIG_SYSFS */
  2153. #ifdef CONFIG_MEMORY_HOTREMOVE
  2154. /* There is no significance to this priority 100 */
  2155. hotplug_memory_notifier(ksm_memory_callback, 100);
  2156. #endif
  2157. show_mem_notifier_register(&ksm_show_mem_notifier_block);
  2158. return 0;
  2159. out_free:
  2160. ksm_slab_free();
  2161. out:
  2162. return err;
  2163. }
  2164. subsys_initcall(ksm_init);