ksm.c 45 KB

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