ksm.c 44 KB

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