ksm.c 40 KB

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