ksm.c 63 KB

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