ksm.c 64 KB

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