ksm.c 65 KB

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