ksm.c 66 KB

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