ksm.c 45 KB

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