ksm.c 41 KB

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