ksm.c 55 KB

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