ksm.c 55 KB

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