ksm.c 53 KB

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