ksm.c 64 KB

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