ksm.c 55 KB

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