ksm.c 56 KB

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