ksm.c 44 KB

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