ksm.c 45 KB

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