ksm.c 63 KB

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