ksm.c 48 KB

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