ksm.c 47 KB

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