ksm.c 45 KB

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