ksm.c 65 KB

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