ksm.c 45 KB

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