ksm.c 56 KB

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