ksm.c 40 KB

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