ksm.c 58 KB

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