ksm.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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/mmu_notifier.h>
  32. #include <linux/swap.h>
  33. #include <linux/ksm.h>
  34. #include <asm/tlbflush.h>
  35. /*
  36. * A few notes about the KSM scanning process,
  37. * to make it easier to understand the data structures below:
  38. *
  39. * In order to reduce excessive scanning, KSM sorts the memory pages by their
  40. * contents into a data structure that holds pointers to the pages' locations.
  41. *
  42. * Since the contents of the pages may change at any moment, KSM cannot just
  43. * insert the pages into a normal sorted tree and expect it to find anything.
  44. * Therefore KSM uses two data structures - the stable and the unstable tree.
  45. *
  46. * The stable tree holds pointers to all the merged pages (ksm pages), sorted
  47. * by their contents. Because each such page is write-protected, searching on
  48. * this tree is fully assured to be working (except when pages are unmapped),
  49. * and therefore this tree is called the stable tree.
  50. *
  51. * In addition to the stable tree, KSM uses a second data structure called the
  52. * unstable tree: this tree holds pointers to pages which have been found to
  53. * be "unchanged for a period of time". The unstable tree sorts these pages
  54. * by their contents, but since they are not write-protected, KSM cannot rely
  55. * upon the unstable tree to work correctly - the unstable tree is liable to
  56. * be corrupted as its contents are modified, and so it is called unstable.
  57. *
  58. * KSM solves this problem by several techniques:
  59. *
  60. * 1) The unstable tree is flushed every time KSM completes scanning all
  61. * memory areas, and then the tree is rebuilt again from the beginning.
  62. * 2) KSM will only insert into the unstable tree, pages whose hash value
  63. * has not changed since the previous scan of all memory areas.
  64. * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
  65. * colors of the nodes and not on their contents, assuring that even when
  66. * the tree gets "corrupted" it won't get out of balance, so scanning time
  67. * remains the same (also, searching and inserting nodes in an rbtree uses
  68. * the same algorithm, so we have no overhead when we flush and rebuild).
  69. * 4) KSM never flushes the stable tree, which means that even if it were to
  70. * take 10 attempts to find a page in the unstable tree, once it is found,
  71. * it is secured in the stable tree. (When we scan a new page, we first
  72. * compare it against the stable tree, and then against the unstable tree.)
  73. */
  74. /**
  75. * struct mm_slot - ksm information per mm that is being scanned
  76. * @link: link to the mm_slots hash list
  77. * @mm_list: link into the mm_slots list, rooted in ksm_mm_head
  78. * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
  79. * @mm: the mm that this information is valid for
  80. */
  81. struct mm_slot {
  82. struct hlist_node link;
  83. struct list_head mm_list;
  84. struct rmap_item *rmap_list;
  85. struct mm_struct *mm;
  86. };
  87. /**
  88. * struct ksm_scan - cursor for scanning
  89. * @mm_slot: the current mm_slot we are scanning
  90. * @address: the next address inside that to be scanned
  91. * @rmap_list: link to the next rmap to be scanned in the rmap_list
  92. * @seqnr: count of completed full scans (needed when removing unstable node)
  93. *
  94. * There is only the one ksm_scan instance of this cursor structure.
  95. */
  96. struct ksm_scan {
  97. struct mm_slot *mm_slot;
  98. unsigned long address;
  99. struct rmap_item **rmap_list;
  100. unsigned long seqnr;
  101. };
  102. /**
  103. * struct stable_node - node of the stable rbtree
  104. * @page: pointer to struct page of the ksm page
  105. * @node: rb node of this ksm page in the stable tree
  106. * @hlist: hlist head of rmap_items using this ksm page
  107. */
  108. struct stable_node {
  109. struct page *page;
  110. struct rb_node node;
  111. struct hlist_head hlist;
  112. };
  113. /**
  114. * struct rmap_item - reverse mapping item for virtual addresses
  115. * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
  116. * @filler: unused space we're making available in this patch
  117. * @mm: the memory structure this rmap_item is pointing into
  118. * @address: the virtual address this rmap_item tracks (+ flags in low bits)
  119. * @oldchecksum: previous checksum of the page at that virtual address
  120. * @node: rb node of this rmap_item in the unstable tree
  121. * @head: pointer to stable_node heading this list in the stable tree
  122. * @hlist: link into hlist of rmap_items hanging off that stable_node
  123. */
  124. struct rmap_item {
  125. struct rmap_item *rmap_list;
  126. unsigned long filler;
  127. struct mm_struct *mm;
  128. unsigned long address; /* + low bits used for flags below */
  129. unsigned int oldchecksum; /* when unstable */
  130. union {
  131. struct rb_node node; /* when node of unstable tree */
  132. struct { /* when listed from stable tree */
  133. struct stable_node *head;
  134. struct hlist_node hlist;
  135. };
  136. };
  137. };
  138. #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
  139. #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
  140. #define STABLE_FLAG 0x200 /* is listed from the stable tree */
  141. /* The stable and unstable tree heads */
  142. static struct rb_root root_stable_tree = RB_ROOT;
  143. static struct rb_root root_unstable_tree = RB_ROOT;
  144. #define MM_SLOTS_HASH_HEADS 1024
  145. static struct hlist_head *mm_slots_hash;
  146. static struct mm_slot ksm_mm_head = {
  147. .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list),
  148. };
  149. static struct ksm_scan ksm_scan = {
  150. .mm_slot = &ksm_mm_head,
  151. };
  152. static struct kmem_cache *rmap_item_cache;
  153. static struct kmem_cache *stable_node_cache;
  154. static struct kmem_cache *mm_slot_cache;
  155. /* The number of nodes in the stable tree */
  156. static unsigned long ksm_pages_shared;
  157. /* The number of page slots additionally sharing those nodes */
  158. static unsigned long ksm_pages_sharing;
  159. /* The number of nodes in the unstable tree */
  160. static unsigned long ksm_pages_unshared;
  161. /* The number of rmap_items in use: to calculate pages_volatile */
  162. static unsigned long ksm_rmap_items;
  163. /* Limit on the number of unswappable pages used */
  164. static unsigned long ksm_max_kernel_pages;
  165. /* Number of pages ksmd should scan in one batch */
  166. static unsigned int ksm_thread_pages_to_scan = 100;
  167. /* Milliseconds ksmd should sleep between batches */
  168. static unsigned int ksm_thread_sleep_millisecs = 20;
  169. #define KSM_RUN_STOP 0
  170. #define KSM_RUN_MERGE 1
  171. #define KSM_RUN_UNMERGE 2
  172. static unsigned int ksm_run = KSM_RUN_STOP;
  173. static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
  174. static DEFINE_MUTEX(ksm_thread_mutex);
  175. static DEFINE_SPINLOCK(ksm_mmlist_lock);
  176. #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\
  177. sizeof(struct __struct), __alignof__(struct __struct),\
  178. (__flags), NULL)
  179. static int __init ksm_slab_init(void)
  180. {
  181. rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0);
  182. if (!rmap_item_cache)
  183. goto out;
  184. stable_node_cache = KSM_KMEM_CACHE(stable_node, 0);
  185. if (!stable_node_cache)
  186. goto out_free1;
  187. mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0);
  188. if (!mm_slot_cache)
  189. goto out_free2;
  190. return 0;
  191. out_free2:
  192. kmem_cache_destroy(stable_node_cache);
  193. out_free1:
  194. kmem_cache_destroy(rmap_item_cache);
  195. out:
  196. return -ENOMEM;
  197. }
  198. static void __init ksm_slab_free(void)
  199. {
  200. kmem_cache_destroy(mm_slot_cache);
  201. kmem_cache_destroy(stable_node_cache);
  202. kmem_cache_destroy(rmap_item_cache);
  203. mm_slot_cache = NULL;
  204. }
  205. static inline struct rmap_item *alloc_rmap_item(void)
  206. {
  207. struct rmap_item *rmap_item;
  208. rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL);
  209. if (rmap_item)
  210. ksm_rmap_items++;
  211. return rmap_item;
  212. }
  213. static inline void free_rmap_item(struct rmap_item *rmap_item)
  214. {
  215. ksm_rmap_items--;
  216. rmap_item->mm = NULL; /* debug safety */
  217. kmem_cache_free(rmap_item_cache, rmap_item);
  218. }
  219. static inline struct stable_node *alloc_stable_node(void)
  220. {
  221. return kmem_cache_alloc(stable_node_cache, GFP_KERNEL);
  222. }
  223. static inline void free_stable_node(struct stable_node *stable_node)
  224. {
  225. kmem_cache_free(stable_node_cache, stable_node);
  226. }
  227. static inline struct mm_slot *alloc_mm_slot(void)
  228. {
  229. if (!mm_slot_cache) /* initialization failed */
  230. return NULL;
  231. return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
  232. }
  233. static inline void free_mm_slot(struct mm_slot *mm_slot)
  234. {
  235. kmem_cache_free(mm_slot_cache, mm_slot);
  236. }
  237. static int __init mm_slots_hash_init(void)
  238. {
  239. mm_slots_hash = kzalloc(MM_SLOTS_HASH_HEADS * sizeof(struct hlist_head),
  240. GFP_KERNEL);
  241. if (!mm_slots_hash)
  242. return -ENOMEM;
  243. return 0;
  244. }
  245. static void __init mm_slots_hash_free(void)
  246. {
  247. kfree(mm_slots_hash);
  248. }
  249. static struct mm_slot *get_mm_slot(struct mm_struct *mm)
  250. {
  251. struct mm_slot *mm_slot;
  252. struct hlist_head *bucket;
  253. struct hlist_node *node;
  254. bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
  255. % MM_SLOTS_HASH_HEADS];
  256. hlist_for_each_entry(mm_slot, node, bucket, link) {
  257. if (mm == mm_slot->mm)
  258. return mm_slot;
  259. }
  260. return NULL;
  261. }
  262. static void insert_to_mm_slots_hash(struct mm_struct *mm,
  263. struct mm_slot *mm_slot)
  264. {
  265. struct hlist_head *bucket;
  266. bucket = &mm_slots_hash[((unsigned long)mm / sizeof(struct mm_struct))
  267. % MM_SLOTS_HASH_HEADS];
  268. mm_slot->mm = mm;
  269. hlist_add_head(&mm_slot->link, bucket);
  270. }
  271. static inline int in_stable_tree(struct rmap_item *rmap_item)
  272. {
  273. return rmap_item->address & STABLE_FLAG;
  274. }
  275. /*
  276. * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
  277. * page tables after it has passed through ksm_exit() - which, if necessary,
  278. * takes mmap_sem briefly to serialize against them. ksm_exit() does not set
  279. * a special flag: they can just back out as soon as mm_users goes to zero.
  280. * ksm_test_exit() is used throughout to make this test for exit: in some
  281. * places for correctness, in some places just to avoid unnecessary work.
  282. */
  283. static inline bool ksm_test_exit(struct mm_struct *mm)
  284. {
  285. return atomic_read(&mm->mm_users) == 0;
  286. }
  287. /*
  288. * We use break_ksm to break COW on a ksm page: it's a stripped down
  289. *
  290. * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1)
  291. * put_page(page);
  292. *
  293. * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
  294. * in case the application has unmapped and remapped mm,addr meanwhile.
  295. * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
  296. * mmap of /dev/mem or /dev/kmem, where we would not want to touch it.
  297. */
  298. static int break_ksm(struct vm_area_struct *vma, unsigned long addr)
  299. {
  300. struct page *page;
  301. int ret = 0;
  302. do {
  303. cond_resched();
  304. page = follow_page(vma, addr, FOLL_GET);
  305. if (!page)
  306. break;
  307. if (PageKsm(page))
  308. ret = handle_mm_fault(vma->vm_mm, vma, addr,
  309. FAULT_FLAG_WRITE);
  310. else
  311. ret = VM_FAULT_WRITE;
  312. put_page(page);
  313. } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_OOM)));
  314. /*
  315. * We must loop because handle_mm_fault() may back out if there's
  316. * any difficulty e.g. if pte accessed bit gets updated concurrently.
  317. *
  318. * VM_FAULT_WRITE is what we have been hoping for: it indicates that
  319. * COW has been broken, even if the vma does not permit VM_WRITE;
  320. * but note that a concurrent fault might break PageKsm for us.
  321. *
  322. * VM_FAULT_SIGBUS could occur if we race with truncation of the
  323. * backing file, which also invalidates anonymous pages: that's
  324. * okay, that truncation will have unmapped the PageKsm for us.
  325. *
  326. * VM_FAULT_OOM: at the time of writing (late July 2009), setting
  327. * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
  328. * current task has TIF_MEMDIE set, and will be OOM killed on return
  329. * to user; and ksmd, having no mm, would never be chosen for that.
  330. *
  331. * But if the mm is in a limited mem_cgroup, then the fault may fail
  332. * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
  333. * even ksmd can fail in this way - though it's usually breaking ksm
  334. * just to undo a merge it made a moment before, so unlikely to oom.
  335. *
  336. * That's a pity: we might therefore have more kernel pages allocated
  337. * than we're counting as nodes in the stable tree; but ksm_do_scan
  338. * will retry to break_cow on each pass, so should recover the page
  339. * in due course. The important thing is to not let VM_MERGEABLE
  340. * be cleared while any such pages might remain in the area.
  341. */
  342. return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
  343. }
  344. static void break_cow(struct rmap_item *rmap_item)
  345. {
  346. struct mm_struct *mm = rmap_item->mm;
  347. unsigned long addr = rmap_item->address;
  348. struct vm_area_struct *vma;
  349. down_read(&mm->mmap_sem);
  350. if (ksm_test_exit(mm))
  351. goto out;
  352. vma = find_vma(mm, addr);
  353. if (!vma || vma->vm_start > addr)
  354. goto out;
  355. if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  356. goto out;
  357. break_ksm(vma, addr);
  358. out:
  359. up_read(&mm->mmap_sem);
  360. }
  361. static struct page *get_mergeable_page(struct rmap_item *rmap_item)
  362. {
  363. struct mm_struct *mm = rmap_item->mm;
  364. unsigned long addr = rmap_item->address;
  365. struct vm_area_struct *vma;
  366. struct page *page;
  367. down_read(&mm->mmap_sem);
  368. if (ksm_test_exit(mm))
  369. goto out;
  370. vma = find_vma(mm, addr);
  371. if (!vma || vma->vm_start > addr)
  372. goto out;
  373. if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  374. goto out;
  375. page = follow_page(vma, addr, FOLL_GET);
  376. if (!page)
  377. goto out;
  378. if (PageAnon(page)) {
  379. flush_anon_page(vma, page, addr);
  380. flush_dcache_page(page);
  381. } else {
  382. put_page(page);
  383. out: page = NULL;
  384. }
  385. up_read(&mm->mmap_sem);
  386. return page;
  387. }
  388. /*
  389. * Removing rmap_item from stable or unstable tree.
  390. * This function will clean the information from the stable/unstable tree.
  391. */
  392. static void remove_rmap_item_from_tree(struct rmap_item *rmap_item)
  393. {
  394. if (rmap_item->address & STABLE_FLAG) {
  395. struct stable_node *stable_node;
  396. stable_node = rmap_item->head;
  397. hlist_del(&rmap_item->hlist);
  398. if (stable_node->hlist.first)
  399. ksm_pages_sharing--;
  400. else {
  401. set_page_stable_node(stable_node->page, NULL);
  402. put_page(stable_node->page);
  403. rb_erase(&stable_node->node, &root_stable_tree);
  404. free_stable_node(stable_node);
  405. ksm_pages_shared--;
  406. }
  407. rmap_item->address &= PAGE_MASK;
  408. } else if (rmap_item->address & UNSTABLE_FLAG) {
  409. unsigned char age;
  410. /*
  411. * Usually ksmd can and must skip the rb_erase, because
  412. * root_unstable_tree was already reset to RB_ROOT.
  413. * But be careful when an mm is exiting: do the rb_erase
  414. * if this rmap_item was inserted by this scan, rather
  415. * than left over from before.
  416. */
  417. age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
  418. BUG_ON(age > 1);
  419. if (!age)
  420. rb_erase(&rmap_item->node, &root_unstable_tree);
  421. ksm_pages_unshared--;
  422. rmap_item->address &= PAGE_MASK;
  423. }
  424. cond_resched(); /* we're called from many long loops */
  425. }
  426. static void remove_trailing_rmap_items(struct mm_slot *mm_slot,
  427. struct rmap_item **rmap_list)
  428. {
  429. while (*rmap_list) {
  430. struct rmap_item *rmap_item = *rmap_list;
  431. *rmap_list = rmap_item->rmap_list;
  432. remove_rmap_item_from_tree(rmap_item);
  433. free_rmap_item(rmap_item);
  434. }
  435. }
  436. /*
  437. * Though it's very tempting to unmerge in_stable_tree(rmap_item)s rather
  438. * than check every pte of a given vma, the locking doesn't quite work for
  439. * that - an rmap_item is assigned to the stable tree after inserting ksm
  440. * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing
  441. * rmap_items from parent to child at fork time (so as not to waste time
  442. * if exit comes before the next scan reaches it).
  443. *
  444. * Similarly, although we'd like to remove rmap_items (so updating counts
  445. * and freeing memory) when unmerging an area, it's easier to leave that
  446. * to the next pass of ksmd - consider, for example, how ksmd might be
  447. * in cmp_and_merge_page on one of the rmap_items we would be removing.
  448. */
  449. static int unmerge_ksm_pages(struct vm_area_struct *vma,
  450. unsigned long start, unsigned long end)
  451. {
  452. unsigned long addr;
  453. int err = 0;
  454. for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
  455. if (ksm_test_exit(vma->vm_mm))
  456. break;
  457. if (signal_pending(current))
  458. err = -ERESTARTSYS;
  459. else
  460. err = break_ksm(vma, addr);
  461. }
  462. return err;
  463. }
  464. #ifdef CONFIG_SYSFS
  465. /*
  466. * Only called through the sysfs control interface:
  467. */
  468. static int unmerge_and_remove_all_rmap_items(void)
  469. {
  470. struct mm_slot *mm_slot;
  471. struct mm_struct *mm;
  472. struct vm_area_struct *vma;
  473. int err = 0;
  474. spin_lock(&ksm_mmlist_lock);
  475. ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next,
  476. struct mm_slot, mm_list);
  477. spin_unlock(&ksm_mmlist_lock);
  478. for (mm_slot = ksm_scan.mm_slot;
  479. mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) {
  480. mm = mm_slot->mm;
  481. down_read(&mm->mmap_sem);
  482. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  483. if (ksm_test_exit(mm))
  484. break;
  485. if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  486. continue;
  487. err = unmerge_ksm_pages(vma,
  488. vma->vm_start, vma->vm_end);
  489. if (err)
  490. goto error;
  491. }
  492. remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list);
  493. spin_lock(&ksm_mmlist_lock);
  494. ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next,
  495. struct mm_slot, mm_list);
  496. if (ksm_test_exit(mm)) {
  497. hlist_del(&mm_slot->link);
  498. list_del(&mm_slot->mm_list);
  499. spin_unlock(&ksm_mmlist_lock);
  500. free_mm_slot(mm_slot);
  501. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  502. up_read(&mm->mmap_sem);
  503. mmdrop(mm);
  504. } else {
  505. spin_unlock(&ksm_mmlist_lock);
  506. up_read(&mm->mmap_sem);
  507. }
  508. }
  509. ksm_scan.seqnr = 0;
  510. return 0;
  511. error:
  512. up_read(&mm->mmap_sem);
  513. spin_lock(&ksm_mmlist_lock);
  514. ksm_scan.mm_slot = &ksm_mm_head;
  515. spin_unlock(&ksm_mmlist_lock);
  516. return err;
  517. }
  518. #endif /* CONFIG_SYSFS */
  519. static u32 calc_checksum(struct page *page)
  520. {
  521. u32 checksum;
  522. void *addr = kmap_atomic(page, KM_USER0);
  523. checksum = jhash2(addr, PAGE_SIZE / 4, 17);
  524. kunmap_atomic(addr, KM_USER0);
  525. return checksum;
  526. }
  527. static int memcmp_pages(struct page *page1, struct page *page2)
  528. {
  529. char *addr1, *addr2;
  530. int ret;
  531. addr1 = kmap_atomic(page1, KM_USER0);
  532. addr2 = kmap_atomic(page2, KM_USER1);
  533. ret = memcmp(addr1, addr2, PAGE_SIZE);
  534. kunmap_atomic(addr2, KM_USER1);
  535. kunmap_atomic(addr1, KM_USER0);
  536. return ret;
  537. }
  538. static inline int pages_identical(struct page *page1, struct page *page2)
  539. {
  540. return !memcmp_pages(page1, page2);
  541. }
  542. static int write_protect_page(struct vm_area_struct *vma, struct page *page,
  543. pte_t *orig_pte)
  544. {
  545. struct mm_struct *mm = vma->vm_mm;
  546. unsigned long addr;
  547. pte_t *ptep;
  548. spinlock_t *ptl;
  549. int swapped;
  550. int err = -EFAULT;
  551. addr = page_address_in_vma(page, vma);
  552. if (addr == -EFAULT)
  553. goto out;
  554. ptep = page_check_address(page, mm, addr, &ptl, 0);
  555. if (!ptep)
  556. goto out;
  557. if (pte_write(*ptep)) {
  558. pte_t entry;
  559. swapped = PageSwapCache(page);
  560. flush_cache_page(vma, addr, page_to_pfn(page));
  561. /*
  562. * Ok this is tricky, when get_user_pages_fast() run it doesnt
  563. * take any lock, therefore the check that we are going to make
  564. * with the pagecount against the mapcount is racey and
  565. * O_DIRECT can happen right after the check.
  566. * So we clear the pte and flush the tlb before the check
  567. * this assure us that no O_DIRECT can happen after the check
  568. * or in the middle of the check.
  569. */
  570. entry = ptep_clear_flush(vma, addr, ptep);
  571. /*
  572. * Check that no O_DIRECT or similar I/O is in progress on the
  573. * page
  574. */
  575. if (page_mapcount(page) + 1 + swapped != page_count(page)) {
  576. set_pte_at_notify(mm, addr, ptep, entry);
  577. goto out_unlock;
  578. }
  579. entry = pte_wrprotect(entry);
  580. set_pte_at_notify(mm, addr, ptep, entry);
  581. }
  582. *orig_pte = *ptep;
  583. err = 0;
  584. out_unlock:
  585. pte_unmap_unlock(ptep, ptl);
  586. out:
  587. return err;
  588. }
  589. /**
  590. * replace_page - replace page in vma by new ksm page
  591. * @vma: vma that holds the pte pointing to page
  592. * @page: the page we are replacing by kpage
  593. * @kpage: the ksm page we replace page by
  594. * @orig_pte: the original value of the pte
  595. *
  596. * Returns 0 on success, -EFAULT on failure.
  597. */
  598. static int replace_page(struct vm_area_struct *vma, struct page *page,
  599. struct page *kpage, pte_t orig_pte)
  600. {
  601. struct mm_struct *mm = vma->vm_mm;
  602. pgd_t *pgd;
  603. pud_t *pud;
  604. pmd_t *pmd;
  605. pte_t *ptep;
  606. spinlock_t *ptl;
  607. unsigned long addr;
  608. int err = -EFAULT;
  609. addr = page_address_in_vma(page, vma);
  610. if (addr == -EFAULT)
  611. goto out;
  612. pgd = pgd_offset(mm, addr);
  613. if (!pgd_present(*pgd))
  614. goto out;
  615. pud = pud_offset(pgd, addr);
  616. if (!pud_present(*pud))
  617. goto out;
  618. pmd = pmd_offset(pud, addr);
  619. if (!pmd_present(*pmd))
  620. goto out;
  621. ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
  622. if (!pte_same(*ptep, orig_pte)) {
  623. pte_unmap_unlock(ptep, ptl);
  624. goto out;
  625. }
  626. get_page(kpage);
  627. page_add_ksm_rmap(kpage);
  628. flush_cache_page(vma, addr, pte_pfn(*ptep));
  629. ptep_clear_flush(vma, addr, ptep);
  630. set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
  631. page_remove_rmap(page);
  632. put_page(page);
  633. pte_unmap_unlock(ptep, ptl);
  634. err = 0;
  635. out:
  636. return err;
  637. }
  638. /*
  639. * try_to_merge_one_page - take two pages and merge them into one
  640. * @vma: the vma that holds the pte pointing to page
  641. * @page: the PageAnon page that we want to replace with kpage
  642. * @kpage: the PageKsm page that we want to map instead of page
  643. *
  644. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  645. */
  646. static int try_to_merge_one_page(struct vm_area_struct *vma,
  647. struct page *page, struct page *kpage)
  648. {
  649. pte_t orig_pte = __pte(0);
  650. int err = -EFAULT;
  651. if (!(vma->vm_flags & VM_MERGEABLE))
  652. goto out;
  653. if (!PageAnon(page))
  654. goto out;
  655. /*
  656. * We need the page lock to read a stable PageSwapCache in
  657. * write_protect_page(). We use trylock_page() instead of
  658. * lock_page() because we don't want to wait here - we
  659. * prefer to continue scanning and merging different pages,
  660. * then come back to this page when it is unlocked.
  661. */
  662. if (!trylock_page(page))
  663. goto out;
  664. /*
  665. * If this anonymous page is mapped only here, its pte may need
  666. * to be write-protected. If it's mapped elsewhere, all of its
  667. * ptes are necessarily already write-protected. But in either
  668. * case, we need to lock and check page_count is not raised.
  669. */
  670. if (write_protect_page(vma, page, &orig_pte) == 0 &&
  671. pages_identical(page, kpage))
  672. err = replace_page(vma, page, kpage, orig_pte);
  673. unlock_page(page);
  674. out:
  675. return err;
  676. }
  677. /*
  678. * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
  679. * but no new kernel page is allocated: kpage must already be a ksm page.
  680. *
  681. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  682. */
  683. static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item,
  684. struct page *page, struct page *kpage)
  685. {
  686. struct mm_struct *mm = rmap_item->mm;
  687. struct vm_area_struct *vma;
  688. int err = -EFAULT;
  689. if (page == kpage) /* ksm page forked */
  690. return 0;
  691. down_read(&mm->mmap_sem);
  692. if (ksm_test_exit(mm))
  693. goto out;
  694. vma = find_vma(mm, rmap_item->address);
  695. if (!vma || vma->vm_start > rmap_item->address)
  696. goto out;
  697. err = try_to_merge_one_page(vma, page, kpage);
  698. out:
  699. up_read(&mm->mmap_sem);
  700. return err;
  701. }
  702. /*
  703. * try_to_merge_two_pages - take two identical pages and prepare them
  704. * to be merged into one page.
  705. *
  706. * This function returns the kpage if we successfully merged two identical
  707. * pages into one ksm page, NULL otherwise.
  708. *
  709. * Note that this function allocates a new kernel page: if one of the pages
  710. * is already a ksm page, try_to_merge_with_ksm_page should be used.
  711. */
  712. static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item,
  713. struct page *page,
  714. struct rmap_item *tree_rmap_item,
  715. struct page *tree_page)
  716. {
  717. struct mm_struct *mm = rmap_item->mm;
  718. struct vm_area_struct *vma;
  719. struct page *kpage;
  720. int err = -EFAULT;
  721. /*
  722. * The number of nodes in the stable tree
  723. * is the number of kernel pages that we hold.
  724. */
  725. if (ksm_max_kernel_pages &&
  726. ksm_max_kernel_pages <= ksm_pages_shared)
  727. return NULL;
  728. kpage = alloc_page(GFP_HIGHUSER);
  729. if (!kpage)
  730. return NULL;
  731. down_read(&mm->mmap_sem);
  732. if (ksm_test_exit(mm))
  733. goto up;
  734. vma = find_vma(mm, rmap_item->address);
  735. if (!vma || vma->vm_start > rmap_item->address)
  736. goto up;
  737. copy_user_highpage(kpage, page, rmap_item->address, vma);
  738. set_page_stable_node(kpage, NULL); /* mark it PageKsm */
  739. err = try_to_merge_one_page(vma, page, kpage);
  740. up:
  741. up_read(&mm->mmap_sem);
  742. if (!err) {
  743. err = try_to_merge_with_ksm_page(tree_rmap_item,
  744. tree_page, kpage);
  745. /*
  746. * If that fails, we have a ksm page with only one pte
  747. * pointing to it: so break it.
  748. */
  749. if (err)
  750. break_cow(rmap_item);
  751. }
  752. if (err) {
  753. put_page(kpage);
  754. kpage = NULL;
  755. }
  756. return kpage;
  757. }
  758. /*
  759. * stable_tree_search - search for page inside the stable tree
  760. *
  761. * This function checks if there is a page inside the stable tree
  762. * with identical content to the page that we are scanning right now.
  763. *
  764. * This function returns the stable tree node of identical content if found,
  765. * NULL otherwise.
  766. */
  767. static struct stable_node *stable_tree_search(struct page *page)
  768. {
  769. struct rb_node *node = root_stable_tree.rb_node;
  770. struct stable_node *stable_node;
  771. stable_node = page_stable_node(page);
  772. if (stable_node) { /* ksm page forked */
  773. get_page(page);
  774. return stable_node;
  775. }
  776. while (node) {
  777. int ret;
  778. cond_resched();
  779. stable_node = rb_entry(node, struct stable_node, node);
  780. ret = memcmp_pages(page, stable_node->page);
  781. if (ret < 0)
  782. node = node->rb_left;
  783. else if (ret > 0)
  784. node = node->rb_right;
  785. else {
  786. get_page(stable_node->page);
  787. return stable_node;
  788. }
  789. }
  790. return NULL;
  791. }
  792. /*
  793. * stable_tree_insert - insert rmap_item pointing to new ksm page
  794. * into the stable tree.
  795. *
  796. * This function returns the stable tree node just allocated on success,
  797. * NULL otherwise.
  798. */
  799. static struct stable_node *stable_tree_insert(struct page *kpage)
  800. {
  801. struct rb_node **new = &root_stable_tree.rb_node;
  802. struct rb_node *parent = NULL;
  803. struct stable_node *stable_node;
  804. while (*new) {
  805. int ret;
  806. cond_resched();
  807. stable_node = rb_entry(*new, struct stable_node, node);
  808. ret = memcmp_pages(kpage, stable_node->page);
  809. parent = *new;
  810. if (ret < 0)
  811. new = &parent->rb_left;
  812. else if (ret > 0)
  813. new = &parent->rb_right;
  814. else {
  815. /*
  816. * It is not a bug that stable_tree_search() didn't
  817. * find this node: because at that time our page was
  818. * not yet write-protected, so may have changed since.
  819. */
  820. return NULL;
  821. }
  822. }
  823. stable_node = alloc_stable_node();
  824. if (!stable_node)
  825. return NULL;
  826. rb_link_node(&stable_node->node, parent, new);
  827. rb_insert_color(&stable_node->node, &root_stable_tree);
  828. INIT_HLIST_HEAD(&stable_node->hlist);
  829. get_page(kpage);
  830. stable_node->page = kpage;
  831. set_page_stable_node(kpage, stable_node);
  832. return stable_node;
  833. }
  834. /*
  835. * unstable_tree_search_insert - search for identical page,
  836. * else insert rmap_item into the unstable tree.
  837. *
  838. * This function searches for a page in the unstable tree identical to the
  839. * page currently being scanned; and if no identical page is found in the
  840. * tree, we insert rmap_item as a new object into the unstable tree.
  841. *
  842. * This function returns pointer to rmap_item found to be identical
  843. * to the currently scanned page, NULL otherwise.
  844. *
  845. * This function does both searching and inserting, because they share
  846. * the same walking algorithm in an rbtree.
  847. */
  848. static
  849. struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item,
  850. struct page *page,
  851. struct page **tree_pagep)
  852. {
  853. struct rb_node **new = &root_unstable_tree.rb_node;
  854. struct rb_node *parent = NULL;
  855. while (*new) {
  856. struct rmap_item *tree_rmap_item;
  857. struct page *tree_page;
  858. int ret;
  859. cond_resched();
  860. tree_rmap_item = rb_entry(*new, struct rmap_item, node);
  861. tree_page = get_mergeable_page(tree_rmap_item);
  862. if (!tree_page)
  863. return NULL;
  864. /*
  865. * Don't substitute a ksm page for a forked page.
  866. */
  867. if (page == tree_page) {
  868. put_page(tree_page);
  869. return NULL;
  870. }
  871. ret = memcmp_pages(page, tree_page);
  872. parent = *new;
  873. if (ret < 0) {
  874. put_page(tree_page);
  875. new = &parent->rb_left;
  876. } else if (ret > 0) {
  877. put_page(tree_page);
  878. new = &parent->rb_right;
  879. } else {
  880. *tree_pagep = tree_page;
  881. return tree_rmap_item;
  882. }
  883. }
  884. rmap_item->address |= UNSTABLE_FLAG;
  885. rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
  886. rb_link_node(&rmap_item->node, parent, new);
  887. rb_insert_color(&rmap_item->node, &root_unstable_tree);
  888. ksm_pages_unshared++;
  889. return NULL;
  890. }
  891. /*
  892. * stable_tree_append - add another rmap_item to the linked list of
  893. * rmap_items hanging off a given node of the stable tree, all sharing
  894. * the same ksm page.
  895. */
  896. static void stable_tree_append(struct rmap_item *rmap_item,
  897. struct stable_node *stable_node)
  898. {
  899. rmap_item->head = stable_node;
  900. rmap_item->address |= STABLE_FLAG;
  901. hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
  902. if (rmap_item->hlist.next)
  903. ksm_pages_sharing++;
  904. else
  905. ksm_pages_shared++;
  906. }
  907. /*
  908. * cmp_and_merge_page - first see if page can be merged into the stable tree;
  909. * if not, compare checksum to previous and if it's the same, see if page can
  910. * be inserted into the unstable tree, or merged with a page already there and
  911. * both transferred to the stable tree.
  912. *
  913. * @page: the page that we are searching identical page to.
  914. * @rmap_item: the reverse mapping into the virtual address of this page
  915. */
  916. static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item)
  917. {
  918. struct rmap_item *tree_rmap_item;
  919. struct page *tree_page = NULL;
  920. struct stable_node *stable_node;
  921. struct page *kpage;
  922. unsigned int checksum;
  923. int err;
  924. remove_rmap_item_from_tree(rmap_item);
  925. /* We first start with searching the page inside the stable tree */
  926. stable_node = stable_tree_search(page);
  927. if (stable_node) {
  928. kpage = stable_node->page;
  929. err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
  930. if (!err) {
  931. /*
  932. * The page was successfully merged:
  933. * add its rmap_item to the stable tree.
  934. */
  935. stable_tree_append(rmap_item, stable_node);
  936. }
  937. put_page(kpage);
  938. return;
  939. }
  940. /*
  941. * A ksm page might have got here by fork, but its other
  942. * references have already been removed from the stable tree.
  943. * Or it might be left over from a break_ksm which failed
  944. * when the mem_cgroup had reached its limit: try again now.
  945. */
  946. if (PageKsm(page))
  947. break_cow(rmap_item);
  948. /*
  949. * In case the hash value of the page was changed from the last time we
  950. * have calculated it, this page to be changed frequely, therefore we
  951. * don't want to insert it to the unstable tree, and we don't want to
  952. * waste our time to search if there is something identical to it there.
  953. */
  954. checksum = calc_checksum(page);
  955. if (rmap_item->oldchecksum != checksum) {
  956. rmap_item->oldchecksum = checksum;
  957. return;
  958. }
  959. tree_rmap_item =
  960. unstable_tree_search_insert(rmap_item, page, &tree_page);
  961. if (tree_rmap_item) {
  962. kpage = try_to_merge_two_pages(rmap_item, page,
  963. tree_rmap_item, tree_page);
  964. put_page(tree_page);
  965. /*
  966. * As soon as we merge this page, we want to remove the
  967. * rmap_item of the page we have merged with from the unstable
  968. * tree, and insert it instead as new node in the stable tree.
  969. */
  970. if (kpage) {
  971. remove_rmap_item_from_tree(tree_rmap_item);
  972. stable_node = stable_tree_insert(kpage);
  973. if (stable_node) {
  974. stable_tree_append(tree_rmap_item, stable_node);
  975. stable_tree_append(rmap_item, stable_node);
  976. }
  977. put_page(kpage);
  978. /*
  979. * If we fail to insert the page into the stable tree,
  980. * we will have 2 virtual addresses that are pointing
  981. * to a ksm page left outside the stable tree,
  982. * in which case we need to break_cow on both.
  983. */
  984. if (!stable_node) {
  985. break_cow(tree_rmap_item);
  986. break_cow(rmap_item);
  987. }
  988. }
  989. }
  990. }
  991. static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot,
  992. struct rmap_item **rmap_list,
  993. unsigned long addr)
  994. {
  995. struct rmap_item *rmap_item;
  996. while (*rmap_list) {
  997. rmap_item = *rmap_list;
  998. if ((rmap_item->address & PAGE_MASK) == addr)
  999. return rmap_item;
  1000. if (rmap_item->address > addr)
  1001. break;
  1002. *rmap_list = rmap_item->rmap_list;
  1003. remove_rmap_item_from_tree(rmap_item);
  1004. free_rmap_item(rmap_item);
  1005. }
  1006. rmap_item = alloc_rmap_item();
  1007. if (rmap_item) {
  1008. /* It has already been zeroed */
  1009. rmap_item->mm = mm_slot->mm;
  1010. rmap_item->address = addr;
  1011. rmap_item->rmap_list = *rmap_list;
  1012. *rmap_list = rmap_item;
  1013. }
  1014. return rmap_item;
  1015. }
  1016. static struct rmap_item *scan_get_next_rmap_item(struct page **page)
  1017. {
  1018. struct mm_struct *mm;
  1019. struct mm_slot *slot;
  1020. struct vm_area_struct *vma;
  1021. struct rmap_item *rmap_item;
  1022. if (list_empty(&ksm_mm_head.mm_list))
  1023. return NULL;
  1024. slot = ksm_scan.mm_slot;
  1025. if (slot == &ksm_mm_head) {
  1026. root_unstable_tree = RB_ROOT;
  1027. spin_lock(&ksm_mmlist_lock);
  1028. slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list);
  1029. ksm_scan.mm_slot = slot;
  1030. spin_unlock(&ksm_mmlist_lock);
  1031. next_mm:
  1032. ksm_scan.address = 0;
  1033. ksm_scan.rmap_list = &slot->rmap_list;
  1034. }
  1035. mm = slot->mm;
  1036. down_read(&mm->mmap_sem);
  1037. if (ksm_test_exit(mm))
  1038. vma = NULL;
  1039. else
  1040. vma = find_vma(mm, ksm_scan.address);
  1041. for (; vma; vma = vma->vm_next) {
  1042. if (!(vma->vm_flags & VM_MERGEABLE))
  1043. continue;
  1044. if (ksm_scan.address < vma->vm_start)
  1045. ksm_scan.address = vma->vm_start;
  1046. if (!vma->anon_vma)
  1047. ksm_scan.address = vma->vm_end;
  1048. while (ksm_scan.address < vma->vm_end) {
  1049. if (ksm_test_exit(mm))
  1050. break;
  1051. *page = follow_page(vma, ksm_scan.address, FOLL_GET);
  1052. if (*page && PageAnon(*page)) {
  1053. flush_anon_page(vma, *page, ksm_scan.address);
  1054. flush_dcache_page(*page);
  1055. rmap_item = get_next_rmap_item(slot,
  1056. ksm_scan.rmap_list, ksm_scan.address);
  1057. if (rmap_item) {
  1058. ksm_scan.rmap_list =
  1059. &rmap_item->rmap_list;
  1060. ksm_scan.address += PAGE_SIZE;
  1061. } else
  1062. put_page(*page);
  1063. up_read(&mm->mmap_sem);
  1064. return rmap_item;
  1065. }
  1066. if (*page)
  1067. put_page(*page);
  1068. ksm_scan.address += PAGE_SIZE;
  1069. cond_resched();
  1070. }
  1071. }
  1072. if (ksm_test_exit(mm)) {
  1073. ksm_scan.address = 0;
  1074. ksm_scan.rmap_list = &slot->rmap_list;
  1075. }
  1076. /*
  1077. * Nuke all the rmap_items that are above this current rmap:
  1078. * because there were no VM_MERGEABLE vmas with such addresses.
  1079. */
  1080. remove_trailing_rmap_items(slot, ksm_scan.rmap_list);
  1081. spin_lock(&ksm_mmlist_lock);
  1082. ksm_scan.mm_slot = list_entry(slot->mm_list.next,
  1083. struct mm_slot, mm_list);
  1084. if (ksm_scan.address == 0) {
  1085. /*
  1086. * We've completed a full scan of all vmas, holding mmap_sem
  1087. * throughout, and found no VM_MERGEABLE: so do the same as
  1088. * __ksm_exit does to remove this mm from all our lists now.
  1089. * This applies either when cleaning up after __ksm_exit
  1090. * (but beware: we can reach here even before __ksm_exit),
  1091. * or when all VM_MERGEABLE areas have been unmapped (and
  1092. * mmap_sem then protects against race with MADV_MERGEABLE).
  1093. */
  1094. hlist_del(&slot->link);
  1095. list_del(&slot->mm_list);
  1096. spin_unlock(&ksm_mmlist_lock);
  1097. free_mm_slot(slot);
  1098. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  1099. up_read(&mm->mmap_sem);
  1100. mmdrop(mm);
  1101. } else {
  1102. spin_unlock(&ksm_mmlist_lock);
  1103. up_read(&mm->mmap_sem);
  1104. }
  1105. /* Repeat until we've completed scanning the whole list */
  1106. slot = ksm_scan.mm_slot;
  1107. if (slot != &ksm_mm_head)
  1108. goto next_mm;
  1109. ksm_scan.seqnr++;
  1110. return NULL;
  1111. }
  1112. /**
  1113. * ksm_do_scan - the ksm scanner main worker function.
  1114. * @scan_npages - number of pages we want to scan before we return.
  1115. */
  1116. static void ksm_do_scan(unsigned int scan_npages)
  1117. {
  1118. struct rmap_item *rmap_item;
  1119. struct page *page;
  1120. while (scan_npages--) {
  1121. cond_resched();
  1122. rmap_item = scan_get_next_rmap_item(&page);
  1123. if (!rmap_item)
  1124. return;
  1125. if (!PageKsm(page) || !in_stable_tree(rmap_item))
  1126. cmp_and_merge_page(page, rmap_item);
  1127. else if (page_mapcount(page) == 1) {
  1128. /*
  1129. * Replace now-unshared ksm page by ordinary page.
  1130. */
  1131. break_cow(rmap_item);
  1132. remove_rmap_item_from_tree(rmap_item);
  1133. rmap_item->oldchecksum = calc_checksum(page);
  1134. }
  1135. put_page(page);
  1136. }
  1137. }
  1138. static int ksmd_should_run(void)
  1139. {
  1140. return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list);
  1141. }
  1142. static int ksm_scan_thread(void *nothing)
  1143. {
  1144. set_user_nice(current, 5);
  1145. while (!kthread_should_stop()) {
  1146. mutex_lock(&ksm_thread_mutex);
  1147. if (ksmd_should_run())
  1148. ksm_do_scan(ksm_thread_pages_to_scan);
  1149. mutex_unlock(&ksm_thread_mutex);
  1150. if (ksmd_should_run()) {
  1151. schedule_timeout_interruptible(
  1152. msecs_to_jiffies(ksm_thread_sleep_millisecs));
  1153. } else {
  1154. wait_event_interruptible(ksm_thread_wait,
  1155. ksmd_should_run() || kthread_should_stop());
  1156. }
  1157. }
  1158. return 0;
  1159. }
  1160. int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
  1161. unsigned long end, int advice, unsigned long *vm_flags)
  1162. {
  1163. struct mm_struct *mm = vma->vm_mm;
  1164. int err;
  1165. switch (advice) {
  1166. case MADV_MERGEABLE:
  1167. /*
  1168. * Be somewhat over-protective for now!
  1169. */
  1170. if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
  1171. VM_PFNMAP | VM_IO | VM_DONTEXPAND |
  1172. VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
  1173. VM_MIXEDMAP | VM_SAO))
  1174. return 0; /* just ignore the advice */
  1175. if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
  1176. err = __ksm_enter(mm);
  1177. if (err)
  1178. return err;
  1179. }
  1180. *vm_flags |= VM_MERGEABLE;
  1181. break;
  1182. case MADV_UNMERGEABLE:
  1183. if (!(*vm_flags & VM_MERGEABLE))
  1184. return 0; /* just ignore the advice */
  1185. if (vma->anon_vma) {
  1186. err = unmerge_ksm_pages(vma, start, end);
  1187. if (err)
  1188. return err;
  1189. }
  1190. *vm_flags &= ~VM_MERGEABLE;
  1191. break;
  1192. }
  1193. return 0;
  1194. }
  1195. int __ksm_enter(struct mm_struct *mm)
  1196. {
  1197. struct mm_slot *mm_slot;
  1198. int needs_wakeup;
  1199. mm_slot = alloc_mm_slot();
  1200. if (!mm_slot)
  1201. return -ENOMEM;
  1202. /* Check ksm_run too? Would need tighter locking */
  1203. needs_wakeup = list_empty(&ksm_mm_head.mm_list);
  1204. spin_lock(&ksm_mmlist_lock);
  1205. insert_to_mm_slots_hash(mm, mm_slot);
  1206. /*
  1207. * Insert just behind the scanning cursor, to let the area settle
  1208. * down a little; when fork is followed by immediate exec, we don't
  1209. * want ksmd to waste time setting up and tearing down an rmap_list.
  1210. */
  1211. list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list);
  1212. spin_unlock(&ksm_mmlist_lock);
  1213. set_bit(MMF_VM_MERGEABLE, &mm->flags);
  1214. atomic_inc(&mm->mm_count);
  1215. if (needs_wakeup)
  1216. wake_up_interruptible(&ksm_thread_wait);
  1217. return 0;
  1218. }
  1219. void __ksm_exit(struct mm_struct *mm)
  1220. {
  1221. struct mm_slot *mm_slot;
  1222. int easy_to_free = 0;
  1223. /*
  1224. * This process is exiting: if it's straightforward (as is the
  1225. * case when ksmd was never running), free mm_slot immediately.
  1226. * But if it's at the cursor or has rmap_items linked to it, use
  1227. * mmap_sem to synchronize with any break_cows before pagetables
  1228. * are freed, and leave the mm_slot on the list for ksmd to free.
  1229. * Beware: ksm may already have noticed it exiting and freed the slot.
  1230. */
  1231. spin_lock(&ksm_mmlist_lock);
  1232. mm_slot = get_mm_slot(mm);
  1233. if (mm_slot && ksm_scan.mm_slot != mm_slot) {
  1234. if (!mm_slot->rmap_list) {
  1235. hlist_del(&mm_slot->link);
  1236. list_del(&mm_slot->mm_list);
  1237. easy_to_free = 1;
  1238. } else {
  1239. list_move(&mm_slot->mm_list,
  1240. &ksm_scan.mm_slot->mm_list);
  1241. }
  1242. }
  1243. spin_unlock(&ksm_mmlist_lock);
  1244. if (easy_to_free) {
  1245. free_mm_slot(mm_slot);
  1246. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  1247. mmdrop(mm);
  1248. } else if (mm_slot) {
  1249. down_write(&mm->mmap_sem);
  1250. up_write(&mm->mmap_sem);
  1251. }
  1252. }
  1253. #ifdef CONFIG_SYSFS
  1254. /*
  1255. * This all compiles without CONFIG_SYSFS, but is a waste of space.
  1256. */
  1257. #define KSM_ATTR_RO(_name) \
  1258. static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
  1259. #define KSM_ATTR(_name) \
  1260. static struct kobj_attribute _name##_attr = \
  1261. __ATTR(_name, 0644, _name##_show, _name##_store)
  1262. static ssize_t sleep_millisecs_show(struct kobject *kobj,
  1263. struct kobj_attribute *attr, char *buf)
  1264. {
  1265. return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs);
  1266. }
  1267. static ssize_t sleep_millisecs_store(struct kobject *kobj,
  1268. struct kobj_attribute *attr,
  1269. const char *buf, size_t count)
  1270. {
  1271. unsigned long msecs;
  1272. int err;
  1273. err = strict_strtoul(buf, 10, &msecs);
  1274. if (err || msecs > UINT_MAX)
  1275. return -EINVAL;
  1276. ksm_thread_sleep_millisecs = msecs;
  1277. return count;
  1278. }
  1279. KSM_ATTR(sleep_millisecs);
  1280. static ssize_t pages_to_scan_show(struct kobject *kobj,
  1281. struct kobj_attribute *attr, char *buf)
  1282. {
  1283. return sprintf(buf, "%u\n", ksm_thread_pages_to_scan);
  1284. }
  1285. static ssize_t pages_to_scan_store(struct kobject *kobj,
  1286. struct kobj_attribute *attr,
  1287. const char *buf, size_t count)
  1288. {
  1289. int err;
  1290. unsigned long nr_pages;
  1291. err = strict_strtoul(buf, 10, &nr_pages);
  1292. if (err || nr_pages > UINT_MAX)
  1293. return -EINVAL;
  1294. ksm_thread_pages_to_scan = nr_pages;
  1295. return count;
  1296. }
  1297. KSM_ATTR(pages_to_scan);
  1298. static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
  1299. char *buf)
  1300. {
  1301. return sprintf(buf, "%u\n", ksm_run);
  1302. }
  1303. static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
  1304. const char *buf, size_t count)
  1305. {
  1306. int err;
  1307. unsigned long flags;
  1308. err = strict_strtoul(buf, 10, &flags);
  1309. if (err || flags > UINT_MAX)
  1310. return -EINVAL;
  1311. if (flags > KSM_RUN_UNMERGE)
  1312. return -EINVAL;
  1313. /*
  1314. * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
  1315. * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
  1316. * breaking COW to free the unswappable pages_shared (but leaves
  1317. * mm_slots on the list for when ksmd may be set running again).
  1318. */
  1319. mutex_lock(&ksm_thread_mutex);
  1320. if (ksm_run != flags) {
  1321. ksm_run = flags;
  1322. if (flags & KSM_RUN_UNMERGE) {
  1323. current->flags |= PF_OOM_ORIGIN;
  1324. err = unmerge_and_remove_all_rmap_items();
  1325. current->flags &= ~PF_OOM_ORIGIN;
  1326. if (err) {
  1327. ksm_run = KSM_RUN_STOP;
  1328. count = err;
  1329. }
  1330. }
  1331. }
  1332. mutex_unlock(&ksm_thread_mutex);
  1333. if (flags & KSM_RUN_MERGE)
  1334. wake_up_interruptible(&ksm_thread_wait);
  1335. return count;
  1336. }
  1337. KSM_ATTR(run);
  1338. static ssize_t max_kernel_pages_store(struct kobject *kobj,
  1339. struct kobj_attribute *attr,
  1340. const char *buf, size_t count)
  1341. {
  1342. int err;
  1343. unsigned long nr_pages;
  1344. err = strict_strtoul(buf, 10, &nr_pages);
  1345. if (err)
  1346. return -EINVAL;
  1347. ksm_max_kernel_pages = nr_pages;
  1348. return count;
  1349. }
  1350. static ssize_t max_kernel_pages_show(struct kobject *kobj,
  1351. struct kobj_attribute *attr, char *buf)
  1352. {
  1353. return sprintf(buf, "%lu\n", ksm_max_kernel_pages);
  1354. }
  1355. KSM_ATTR(max_kernel_pages);
  1356. static ssize_t pages_shared_show(struct kobject *kobj,
  1357. struct kobj_attribute *attr, char *buf)
  1358. {
  1359. return sprintf(buf, "%lu\n", ksm_pages_shared);
  1360. }
  1361. KSM_ATTR_RO(pages_shared);
  1362. static ssize_t pages_sharing_show(struct kobject *kobj,
  1363. struct kobj_attribute *attr, char *buf)
  1364. {
  1365. return sprintf(buf, "%lu\n", ksm_pages_sharing);
  1366. }
  1367. KSM_ATTR_RO(pages_sharing);
  1368. static ssize_t pages_unshared_show(struct kobject *kobj,
  1369. struct kobj_attribute *attr, char *buf)
  1370. {
  1371. return sprintf(buf, "%lu\n", ksm_pages_unshared);
  1372. }
  1373. KSM_ATTR_RO(pages_unshared);
  1374. static ssize_t pages_volatile_show(struct kobject *kobj,
  1375. struct kobj_attribute *attr, char *buf)
  1376. {
  1377. long ksm_pages_volatile;
  1378. ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
  1379. - ksm_pages_sharing - ksm_pages_unshared;
  1380. /*
  1381. * It was not worth any locking to calculate that statistic,
  1382. * but it might therefore sometimes be negative: conceal that.
  1383. */
  1384. if (ksm_pages_volatile < 0)
  1385. ksm_pages_volatile = 0;
  1386. return sprintf(buf, "%ld\n", ksm_pages_volatile);
  1387. }
  1388. KSM_ATTR_RO(pages_volatile);
  1389. static ssize_t full_scans_show(struct kobject *kobj,
  1390. struct kobj_attribute *attr, char *buf)
  1391. {
  1392. return sprintf(buf, "%lu\n", ksm_scan.seqnr);
  1393. }
  1394. KSM_ATTR_RO(full_scans);
  1395. static struct attribute *ksm_attrs[] = {
  1396. &sleep_millisecs_attr.attr,
  1397. &pages_to_scan_attr.attr,
  1398. &run_attr.attr,
  1399. &max_kernel_pages_attr.attr,
  1400. &pages_shared_attr.attr,
  1401. &pages_sharing_attr.attr,
  1402. &pages_unshared_attr.attr,
  1403. &pages_volatile_attr.attr,
  1404. &full_scans_attr.attr,
  1405. NULL,
  1406. };
  1407. static struct attribute_group ksm_attr_group = {
  1408. .attrs = ksm_attrs,
  1409. .name = "ksm",
  1410. };
  1411. #endif /* CONFIG_SYSFS */
  1412. static int __init ksm_init(void)
  1413. {
  1414. struct task_struct *ksm_thread;
  1415. int err;
  1416. ksm_max_kernel_pages = totalram_pages / 4;
  1417. err = ksm_slab_init();
  1418. if (err)
  1419. goto out;
  1420. err = mm_slots_hash_init();
  1421. if (err)
  1422. goto out_free1;
  1423. ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
  1424. if (IS_ERR(ksm_thread)) {
  1425. printk(KERN_ERR "ksm: creating kthread failed\n");
  1426. err = PTR_ERR(ksm_thread);
  1427. goto out_free2;
  1428. }
  1429. #ifdef CONFIG_SYSFS
  1430. err = sysfs_create_group(mm_kobj, &ksm_attr_group);
  1431. if (err) {
  1432. printk(KERN_ERR "ksm: register sysfs failed\n");
  1433. kthread_stop(ksm_thread);
  1434. goto out_free2;
  1435. }
  1436. #else
  1437. ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
  1438. #endif /* CONFIG_SYSFS */
  1439. return 0;
  1440. out_free2:
  1441. mm_slots_hash_free();
  1442. out_free1:
  1443. ksm_slab_free();
  1444. out:
  1445. return err;
  1446. }
  1447. module_init(ksm_init)