ksm.c 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Memory merging support.
  4. *
  5. * This code enables dynamic sharing of identical pages found in different
  6. * memory areas, even if they are not shared by fork()
  7. *
  8. * Copyright (C) 2008-2009 Red Hat, Inc.
  9. * Authors:
  10. * Izik Eidus
  11. * Andrea Arcangeli
  12. * Chris Wright
  13. * Hugh Dickins
  14. */
  15. #include <linux/errno.h>
  16. #include <linux/mm.h>
  17. #include <linux/mm_inline.h>
  18. #include <linux/fs.h>
  19. #include <linux/mman.h>
  20. #include <linux/sched.h>
  21. #include <linux/sched/mm.h>
  22. #include <linux/sched/coredump.h>
  23. #include <linux/rwsem.h>
  24. #include <linux/pagemap.h>
  25. #include <linux/rmap.h>
  26. #include <linux/spinlock.h>
  27. #include <linux/xxhash.h>
  28. #include <linux/delay.h>
  29. #include <linux/kthread.h>
  30. #include <linux/wait.h>
  31. #include <linux/slab.h>
  32. #include <linux/rbtree.h>
  33. #include <linux/memory.h>
  34. #include <linux/mmu_notifier.h>
  35. #include <linux/swap.h>
  36. #include <linux/ksm.h>
  37. #include <linux/hashtable.h>
  38. #include <linux/freezer.h>
  39. #include <linux/oom.h>
  40. #include <linux/numa.h>
  41. #include <asm/tlbflush.h>
  42. #include "internal.h"
  43. #include "mm_slot.h"
  44. #ifdef CONFIG_NUMA
  45. #define NUMA(x) (x)
  46. #define DO_NUMA(x) do { (x); } while (0)
  47. #else
  48. #define NUMA(x) (0)
  49. #define DO_NUMA(x) do { } while (0)
  50. #endif
  51. /**
  52. * DOC: Overview
  53. *
  54. * A few notes about the KSM scanning process,
  55. * to make it easier to understand the data structures below:
  56. *
  57. * In order to reduce excessive scanning, KSM sorts the memory pages by their
  58. * contents into a data structure that holds pointers to the pages' locations.
  59. *
  60. * Since the contents of the pages may change at any moment, KSM cannot just
  61. * insert the pages into a normal sorted tree and expect it to find anything.
  62. * Therefore KSM uses two data structures - the stable and the unstable tree.
  63. *
  64. * The stable tree holds pointers to all the merged pages (ksm pages), sorted
  65. * by their contents. Because each such page is write-protected, searching on
  66. * this tree is fully assured to be working (except when pages are unmapped),
  67. * and therefore this tree is called the stable tree.
  68. *
  69. * The stable tree node includes information required for reverse
  70. * mapping from a KSM page to virtual addresses that map this page.
  71. *
  72. * In order to avoid large latencies of the rmap walks on KSM pages,
  73. * KSM maintains two types of nodes in the stable tree:
  74. *
  75. * * the regular nodes that keep the reverse mapping structures in a
  76. * linked list
  77. * * the "chains" that link nodes ("dups") that represent the same
  78. * write protected memory content, but each "dup" corresponds to a
  79. * different KSM page copy of that content
  80. *
  81. * Internally, the regular nodes, "dups" and "chains" are represented
  82. * using the same struct ksm_stable_node structure.
  83. *
  84. * In addition to the stable tree, KSM uses a second data structure called the
  85. * unstable tree: this tree holds pointers to pages which have been found to
  86. * be "unchanged for a period of time". The unstable tree sorts these pages
  87. * by their contents, but since they are not write-protected, KSM cannot rely
  88. * upon the unstable tree to work correctly - the unstable tree is liable to
  89. * be corrupted as its contents are modified, and so it is called unstable.
  90. *
  91. * KSM solves this problem by several techniques:
  92. *
  93. * 1) The unstable tree is flushed every time KSM completes scanning all
  94. * memory areas, and then the tree is rebuilt again from the beginning.
  95. * 2) KSM will only insert into the unstable tree, pages whose hash value
  96. * has not changed since the previous scan of all memory areas.
  97. * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the
  98. * colors of the nodes and not on their contents, assuring that even when
  99. * the tree gets "corrupted" it won't get out of balance, so scanning time
  100. * remains the same (also, searching and inserting nodes in an rbtree uses
  101. * the same algorithm, so we have no overhead when we flush and rebuild).
  102. * 4) KSM never flushes the stable tree, which means that even if it were to
  103. * take 10 attempts to find a page in the unstable tree, once it is found,
  104. * it is secured in the stable tree. (When we scan a new page, we first
  105. * compare it against the stable tree, and then against the unstable tree.)
  106. *
  107. * If the merge_across_nodes tunable is unset, then KSM maintains multiple
  108. * stable trees and multiple unstable trees: one of each for each NUMA node.
  109. */
  110. /**
  111. * struct ksm_mm_slot - ksm information per mm that is being scanned
  112. * @slot: hash lookup from mm to mm_slot
  113. * @rmap_list: head for this mm_slot's singly-linked list of rmap_items
  114. */
  115. struct ksm_mm_slot {
  116. struct mm_slot slot;
  117. struct ksm_rmap_item *rmap_list;
  118. };
  119. /**
  120. * struct ksm_scan - cursor for scanning
  121. * @mm_slot: the current mm_slot we are scanning
  122. * @address: the next address inside that to be scanned
  123. * @rmap_list: link to the next rmap to be scanned in the rmap_list
  124. * @seqnr: count of completed full scans (needed when removing unstable node)
  125. *
  126. * There is only the one ksm_scan instance of this cursor structure.
  127. */
  128. struct ksm_scan {
  129. struct ksm_mm_slot *mm_slot;
  130. unsigned long address;
  131. struct ksm_rmap_item **rmap_list;
  132. unsigned long seqnr;
  133. };
  134. /**
  135. * struct ksm_stable_node - node of the stable rbtree
  136. * @node: rb node of this ksm page in the stable tree
  137. * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list
  138. * @hlist_dup: linked into the stable_node->hlist with a stable_node chain
  139. * @list: linked into migrate_nodes, pending placement in the proper node tree
  140. * @hlist: hlist head of rmap_items using this ksm page
  141. * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
  142. * @chain_prune_time: time of the last full garbage collection
  143. * @rmap_hlist_len: number of rmap_item entries in hlist or STABLE_NODE_CHAIN
  144. * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
  145. */
  146. struct ksm_stable_node {
  147. union {
  148. struct rb_node node; /* when node of stable tree */
  149. struct { /* when listed for migration */
  150. struct list_head *head;
  151. struct {
  152. struct hlist_node hlist_dup;
  153. struct list_head list;
  154. };
  155. };
  156. };
  157. struct hlist_head hlist;
  158. union {
  159. unsigned long kpfn;
  160. unsigned long chain_prune_time;
  161. };
  162. /*
  163. * STABLE_NODE_CHAIN can be any negative number in
  164. * rmap_hlist_len negative range, but better not -1 to be able
  165. * to reliably detect underflows.
  166. */
  167. #define STABLE_NODE_CHAIN -1024
  168. int rmap_hlist_len;
  169. #ifdef CONFIG_NUMA
  170. int nid;
  171. #endif
  172. };
  173. /**
  174. * struct ksm_rmap_item - reverse mapping item for virtual addresses
  175. * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list
  176. * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree
  177. * @nid: NUMA node id of unstable tree in which linked (may not match page)
  178. * @mm: the memory structure this rmap_item is pointing into
  179. * @address: the virtual address this rmap_item tracks (+ flags in low bits)
  180. * @oldchecksum: previous checksum of the page at that virtual address
  181. * @node: rb node of this rmap_item in the unstable tree
  182. * @head: pointer to stable_node heading this list in the stable tree
  183. * @hlist: link into hlist of rmap_items hanging off that stable_node
  184. */
  185. struct ksm_rmap_item {
  186. struct ksm_rmap_item *rmap_list;
  187. union {
  188. struct anon_vma *anon_vma; /* when stable */
  189. #ifdef CONFIG_NUMA
  190. int nid; /* when node of unstable tree */
  191. #endif
  192. };
  193. struct mm_struct *mm;
  194. unsigned long address; /* + low bits used for flags below */
  195. unsigned int oldchecksum; /* when unstable */
  196. union {
  197. struct rb_node node; /* when node of unstable tree */
  198. struct { /* when listed from stable tree */
  199. struct ksm_stable_node *head;
  200. struct hlist_node hlist;
  201. };
  202. };
  203. };
  204. #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */
  205. #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */
  206. #define STABLE_FLAG 0x200 /* is listed from the stable tree */
  207. /* The stable and unstable tree heads */
  208. static struct rb_root one_stable_tree[1] = { RB_ROOT };
  209. static struct rb_root one_unstable_tree[1] = { RB_ROOT };
  210. static struct rb_root *root_stable_tree = one_stable_tree;
  211. static struct rb_root *root_unstable_tree = one_unstable_tree;
  212. /* Recently migrated nodes of stable tree, pending proper placement */
  213. static LIST_HEAD(migrate_nodes);
  214. #define STABLE_NODE_DUP_HEAD ((struct list_head *)&migrate_nodes.prev)
  215. #define MM_SLOTS_HASH_BITS 10
  216. static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
  217. static struct ksm_mm_slot ksm_mm_head = {
  218. .slot.mm_node = LIST_HEAD_INIT(ksm_mm_head.slot.mm_node),
  219. };
  220. static struct ksm_scan ksm_scan = {
  221. .mm_slot = &ksm_mm_head,
  222. };
  223. static struct kmem_cache *rmap_item_cache;
  224. static struct kmem_cache *stable_node_cache;
  225. static struct kmem_cache *mm_slot_cache;
  226. /* The number of nodes in the stable tree */
  227. static unsigned long ksm_pages_shared;
  228. /* The number of page slots additionally sharing those nodes */
  229. static unsigned long ksm_pages_sharing;
  230. /* The number of nodes in the unstable tree */
  231. static unsigned long ksm_pages_unshared;
  232. /* The number of rmap_items in use: to calculate pages_volatile */
  233. static unsigned long ksm_rmap_items;
  234. /* The number of stable_node chains */
  235. static unsigned long ksm_stable_node_chains;
  236. /* The number of stable_node dups linked to the stable_node chains */
  237. static unsigned long ksm_stable_node_dups;
  238. /* Delay in pruning stale stable_node_dups in the stable_node_chains */
  239. static unsigned int ksm_stable_node_chains_prune_millisecs = 2000;
  240. /* Maximum number of page slots sharing a stable node */
  241. static int ksm_max_page_sharing = 256;
  242. /* Number of pages ksmd should scan in one batch */
  243. static unsigned int ksm_thread_pages_to_scan = 100;
  244. /* Milliseconds ksmd should sleep between batches */
  245. static unsigned int ksm_thread_sleep_millisecs = 20;
  246. /* Checksum of an empty (zeroed) page */
  247. static unsigned int zero_checksum __read_mostly;
  248. /* Whether to merge empty (zeroed) pages with actual zero pages */
  249. static bool ksm_use_zero_pages __read_mostly;
  250. #ifdef CONFIG_NUMA
  251. /* Zeroed when merging across nodes is not allowed */
  252. static unsigned int ksm_merge_across_nodes = 1;
  253. static int ksm_nr_node_ids = 1;
  254. #else
  255. #define ksm_merge_across_nodes 1U
  256. #define ksm_nr_node_ids 1
  257. #endif
  258. #define KSM_RUN_STOP 0
  259. #define KSM_RUN_MERGE 1
  260. #define KSM_RUN_UNMERGE 2
  261. #define KSM_RUN_OFFLINE 4
  262. static unsigned long ksm_run = KSM_RUN_STOP;
  263. static void wait_while_offlining(void);
  264. static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait);
  265. static DECLARE_WAIT_QUEUE_HEAD(ksm_iter_wait);
  266. static DEFINE_MUTEX(ksm_thread_mutex);
  267. static DEFINE_SPINLOCK(ksm_mmlist_lock);
  268. #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create(#__struct,\
  269. sizeof(struct __struct), __alignof__(struct __struct),\
  270. (__flags), NULL)
  271. static int __init ksm_slab_init(void)
  272. {
  273. rmap_item_cache = KSM_KMEM_CACHE(ksm_rmap_item, 0);
  274. if (!rmap_item_cache)
  275. goto out;
  276. stable_node_cache = KSM_KMEM_CACHE(ksm_stable_node, 0);
  277. if (!stable_node_cache)
  278. goto out_free1;
  279. mm_slot_cache = KSM_KMEM_CACHE(ksm_mm_slot, 0);
  280. if (!mm_slot_cache)
  281. goto out_free2;
  282. return 0;
  283. out_free2:
  284. kmem_cache_destroy(stable_node_cache);
  285. out_free1:
  286. kmem_cache_destroy(rmap_item_cache);
  287. out:
  288. return -ENOMEM;
  289. }
  290. static void __init ksm_slab_free(void)
  291. {
  292. kmem_cache_destroy(mm_slot_cache);
  293. kmem_cache_destroy(stable_node_cache);
  294. kmem_cache_destroy(rmap_item_cache);
  295. mm_slot_cache = NULL;
  296. }
  297. static __always_inline bool is_stable_node_chain(struct ksm_stable_node *chain)
  298. {
  299. return chain->rmap_hlist_len == STABLE_NODE_CHAIN;
  300. }
  301. static __always_inline bool is_stable_node_dup(struct ksm_stable_node *dup)
  302. {
  303. return dup->head == STABLE_NODE_DUP_HEAD;
  304. }
  305. static inline void stable_node_chain_add_dup(struct ksm_stable_node *dup,
  306. struct ksm_stable_node *chain)
  307. {
  308. VM_BUG_ON(is_stable_node_dup(dup));
  309. dup->head = STABLE_NODE_DUP_HEAD;
  310. VM_BUG_ON(!is_stable_node_chain(chain));
  311. hlist_add_head(&dup->hlist_dup, &chain->hlist);
  312. ksm_stable_node_dups++;
  313. }
  314. static inline void __stable_node_dup_del(struct ksm_stable_node *dup)
  315. {
  316. VM_BUG_ON(!is_stable_node_dup(dup));
  317. hlist_del(&dup->hlist_dup);
  318. ksm_stable_node_dups--;
  319. }
  320. static inline void stable_node_dup_del(struct ksm_stable_node *dup)
  321. {
  322. VM_BUG_ON(is_stable_node_chain(dup));
  323. if (is_stable_node_dup(dup))
  324. __stable_node_dup_del(dup);
  325. else
  326. rb_erase(&dup->node, root_stable_tree + NUMA(dup->nid));
  327. #ifdef CONFIG_DEBUG_VM
  328. dup->head = NULL;
  329. #endif
  330. }
  331. static inline struct ksm_rmap_item *alloc_rmap_item(void)
  332. {
  333. struct ksm_rmap_item *rmap_item;
  334. rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL |
  335. __GFP_NORETRY | __GFP_NOWARN);
  336. if (rmap_item)
  337. ksm_rmap_items++;
  338. return rmap_item;
  339. }
  340. static inline void free_rmap_item(struct ksm_rmap_item *rmap_item)
  341. {
  342. ksm_rmap_items--;
  343. rmap_item->mm->ksm_rmap_items--;
  344. rmap_item->mm = NULL; /* debug safety */
  345. kmem_cache_free(rmap_item_cache, rmap_item);
  346. }
  347. static inline struct ksm_stable_node *alloc_stable_node(void)
  348. {
  349. /*
  350. * The allocation can take too long with GFP_KERNEL when memory is under
  351. * pressure, which may lead to hung task warnings. Adding __GFP_HIGH
  352. * grants access to memory reserves, helping to avoid this problem.
  353. */
  354. return kmem_cache_alloc(stable_node_cache, GFP_KERNEL | __GFP_HIGH);
  355. }
  356. static inline void free_stable_node(struct ksm_stable_node *stable_node)
  357. {
  358. VM_BUG_ON(stable_node->rmap_hlist_len &&
  359. !is_stable_node_chain(stable_node));
  360. kmem_cache_free(stable_node_cache, stable_node);
  361. }
  362. /*
  363. * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's
  364. * page tables after it has passed through ksm_exit() - which, if necessary,
  365. * takes mmap_lock briefly to serialize against them. ksm_exit() does not set
  366. * a special flag: they can just back out as soon as mm_users goes to zero.
  367. * ksm_test_exit() is used throughout to make this test for exit: in some
  368. * places for correctness, in some places just to avoid unnecessary work.
  369. */
  370. static inline bool ksm_test_exit(struct mm_struct *mm)
  371. {
  372. return atomic_read(&mm->mm_users) == 0;
  373. }
  374. /*
  375. * We use break_ksm to break COW on a ksm page: it's a stripped down
  376. *
  377. * if (get_user_pages(addr, 1, FOLL_WRITE, &page, NULL) == 1)
  378. * put_page(page);
  379. *
  380. * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma,
  381. * in case the application has unmapped and remapped mm,addr meanwhile.
  382. * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP
  383. * mmap of /dev/mem, where we would not want to touch it.
  384. *
  385. * FAULT_FLAG/FOLL_REMOTE are because we do this outside the context
  386. * of the process that owns 'vma'. We also do not want to enforce
  387. * protection keys here anyway.
  388. */
  389. static int break_ksm(struct vm_area_struct *vma, unsigned long addr, bool lock_vma)
  390. {
  391. struct page *page;
  392. vm_fault_t ret = 0;
  393. do {
  394. cond_resched();
  395. if (lock_vma)
  396. vma_start_write(vma);
  397. else
  398. mmap_assert_locked(vma->vm_mm);
  399. page = follow_page(vma, addr,
  400. FOLL_GET | FOLL_MIGRATION | FOLL_REMOTE);
  401. if (IS_ERR_OR_NULL(page))
  402. break;
  403. if (PageKsm(page))
  404. ret = handle_mm_fault(vma, addr,
  405. FAULT_FLAG_WRITE | FAULT_FLAG_REMOTE,
  406. NULL);
  407. else
  408. ret = VM_FAULT_WRITE;
  409. put_page(page);
  410. } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV | VM_FAULT_OOM)));
  411. /*
  412. * We must loop because handle_mm_fault() may back out if there's
  413. * any difficulty e.g. if pte accessed bit gets updated concurrently.
  414. *
  415. * VM_FAULT_WRITE is what we have been hoping for: it indicates that
  416. * COW has been broken, even if the vma does not permit VM_WRITE;
  417. * but note that a concurrent fault might break PageKsm for us.
  418. *
  419. * VM_FAULT_SIGBUS could occur if we race with truncation of the
  420. * backing file, which also invalidates anonymous pages: that's
  421. * okay, that truncation will have unmapped the PageKsm for us.
  422. *
  423. * VM_FAULT_OOM: at the time of writing (late July 2009), setting
  424. * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the
  425. * current task has TIF_MEMDIE set, and will be OOM killed on return
  426. * to user; and ksmd, having no mm, would never be chosen for that.
  427. *
  428. * But if the mm is in a limited mem_cgroup, then the fault may fail
  429. * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and
  430. * even ksmd can fail in this way - though it's usually breaking ksm
  431. * just to undo a merge it made a moment before, so unlikely to oom.
  432. *
  433. * That's a pity: we might therefore have more kernel pages allocated
  434. * than we're counting as nodes in the stable tree; but ksm_do_scan
  435. * will retry to break_cow on each pass, so should recover the page
  436. * in due course. The important thing is to not let VM_MERGEABLE
  437. * be cleared while any such pages might remain in the area.
  438. */
  439. return (ret & VM_FAULT_OOM) ? -ENOMEM : 0;
  440. }
  441. static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm,
  442. unsigned long addr)
  443. {
  444. struct vm_area_struct *vma;
  445. if (ksm_test_exit(mm))
  446. return NULL;
  447. vma = vma_lookup(mm, addr);
  448. if (!vma || !(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  449. return NULL;
  450. return vma;
  451. }
  452. static void break_cow(struct ksm_rmap_item *rmap_item)
  453. {
  454. struct mm_struct *mm = rmap_item->mm;
  455. unsigned long addr = rmap_item->address;
  456. struct vm_area_struct *vma;
  457. /*
  458. * It is not an accident that whenever we want to break COW
  459. * to undo, we also need to drop a reference to the anon_vma.
  460. */
  461. put_anon_vma(rmap_item->anon_vma);
  462. mmap_read_lock(mm);
  463. vma = find_mergeable_vma(mm, addr);
  464. if (vma)
  465. break_ksm(vma, addr, false);
  466. mmap_read_unlock(mm);
  467. }
  468. static struct page *get_mergeable_page(struct ksm_rmap_item *rmap_item)
  469. {
  470. struct mm_struct *mm = rmap_item->mm;
  471. unsigned long addr = rmap_item->address;
  472. struct vm_area_struct *vma;
  473. struct page *page;
  474. mmap_read_lock(mm);
  475. vma = find_mergeable_vma(mm, addr);
  476. if (!vma)
  477. goto out;
  478. page = follow_page(vma, addr, FOLL_GET);
  479. if (IS_ERR_OR_NULL(page))
  480. goto out;
  481. if (is_zone_device_page(page))
  482. goto out_putpage;
  483. if (PageAnon(page)) {
  484. flush_anon_page(vma, page, addr);
  485. flush_dcache_page(page);
  486. } else {
  487. out_putpage:
  488. put_page(page);
  489. out:
  490. page = NULL;
  491. }
  492. mmap_read_unlock(mm);
  493. return page;
  494. }
  495. /*
  496. * This helper is used for getting right index into array of tree roots.
  497. * When merge_across_nodes knob is set to 1, there are only two rb-trees for
  498. * stable and unstable pages from all nodes with roots in index 0. Otherwise,
  499. * every node has its own stable and unstable tree.
  500. */
  501. static inline int get_kpfn_nid(unsigned long kpfn)
  502. {
  503. return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
  504. }
  505. static struct ksm_stable_node *alloc_stable_node_chain(struct ksm_stable_node *dup,
  506. struct rb_root *root)
  507. {
  508. struct ksm_stable_node *chain = alloc_stable_node();
  509. VM_BUG_ON(is_stable_node_chain(dup));
  510. if (likely(chain)) {
  511. INIT_HLIST_HEAD(&chain->hlist);
  512. chain->chain_prune_time = jiffies;
  513. chain->rmap_hlist_len = STABLE_NODE_CHAIN;
  514. #if defined (CONFIG_DEBUG_VM) && defined(CONFIG_NUMA)
  515. chain->nid = NUMA_NO_NODE; /* debug */
  516. #endif
  517. ksm_stable_node_chains++;
  518. /*
  519. * Put the stable node chain in the first dimension of
  520. * the stable tree and at the same time remove the old
  521. * stable node.
  522. */
  523. rb_replace_node(&dup->node, &chain->node, root);
  524. /*
  525. * Move the old stable node to the second dimension
  526. * queued in the hlist_dup. The invariant is that all
  527. * dup stable_nodes in the chain->hlist point to pages
  528. * that are write protected and have the exact same
  529. * content.
  530. */
  531. stable_node_chain_add_dup(dup, chain);
  532. }
  533. return chain;
  534. }
  535. static inline void free_stable_node_chain(struct ksm_stable_node *chain,
  536. struct rb_root *root)
  537. {
  538. rb_erase(&chain->node, root);
  539. free_stable_node(chain);
  540. ksm_stable_node_chains--;
  541. }
  542. static void remove_node_from_stable_tree(struct ksm_stable_node *stable_node)
  543. {
  544. struct ksm_rmap_item *rmap_item;
  545. /* check it's not STABLE_NODE_CHAIN or negative */
  546. BUG_ON(stable_node->rmap_hlist_len < 0);
  547. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  548. if (rmap_item->hlist.next)
  549. ksm_pages_sharing--;
  550. else
  551. ksm_pages_shared--;
  552. rmap_item->mm->ksm_merging_pages--;
  553. VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
  554. stable_node->rmap_hlist_len--;
  555. put_anon_vma(rmap_item->anon_vma);
  556. rmap_item->address &= PAGE_MASK;
  557. cond_resched();
  558. }
  559. /*
  560. * We need the second aligned pointer of the migrate_nodes
  561. * list_head to stay clear from the rb_parent_color union
  562. * (aligned and different than any node) and also different
  563. * from &migrate_nodes. This will verify that future list.h changes
  564. * don't break STABLE_NODE_DUP_HEAD. Only recent gcc can handle it.
  565. */
  566. BUILD_BUG_ON(STABLE_NODE_DUP_HEAD <= &migrate_nodes);
  567. BUILD_BUG_ON(STABLE_NODE_DUP_HEAD >= &migrate_nodes + 1);
  568. if (stable_node->head == &migrate_nodes)
  569. list_del(&stable_node->list);
  570. else
  571. stable_node_dup_del(stable_node);
  572. free_stable_node(stable_node);
  573. }
  574. enum get_ksm_page_flags {
  575. GET_KSM_PAGE_NOLOCK,
  576. GET_KSM_PAGE_LOCK,
  577. GET_KSM_PAGE_TRYLOCK
  578. };
  579. /*
  580. * get_ksm_page: checks if the page indicated by the stable node
  581. * is still its ksm page, despite having held no reference to it.
  582. * In which case we can trust the content of the page, and it
  583. * returns the gotten page; but if the page has now been zapped,
  584. * remove the stale node from the stable tree and return NULL.
  585. * But beware, the stable node's page might be being migrated.
  586. *
  587. * You would expect the stable_node to hold a reference to the ksm page.
  588. * But if it increments the page's count, swapping out has to wait for
  589. * ksmd to come around again before it can free the page, which may take
  590. * seconds or even minutes: much too unresponsive. So instead we use a
  591. * "keyhole reference": access to the ksm page from the stable node peeps
  592. * out through its keyhole to see if that page still holds the right key,
  593. * pointing back to this stable node. This relies on freeing a PageAnon
  594. * page to reset its page->mapping to NULL, and relies on no other use of
  595. * a page to put something that might look like our key in page->mapping.
  596. * is on its way to being freed; but it is an anomaly to bear in mind.
  597. */
  598. static struct page *get_ksm_page(struct ksm_stable_node *stable_node,
  599. enum get_ksm_page_flags flags)
  600. {
  601. struct page *page;
  602. void *expected_mapping;
  603. unsigned long kpfn;
  604. expected_mapping = (void *)((unsigned long)stable_node |
  605. PAGE_MAPPING_KSM);
  606. again:
  607. kpfn = READ_ONCE(stable_node->kpfn); /* Address dependency. */
  608. page = pfn_to_page(kpfn);
  609. if (READ_ONCE(page->mapping) != expected_mapping)
  610. goto stale;
  611. /*
  612. * We cannot do anything with the page while its refcount is 0.
  613. * Usually 0 means free, or tail of a higher-order page: in which
  614. * case this node is no longer referenced, and should be freed;
  615. * however, it might mean that the page is under page_ref_freeze().
  616. * The __remove_mapping() case is easy, again the node is now stale;
  617. * the same is in reuse_ksm_page() case; but if page is swapcache
  618. * in folio_migrate_mapping(), it might still be our page,
  619. * in which case it's essential to keep the node.
  620. */
  621. while (!get_page_unless_zero(page)) {
  622. /*
  623. * Another check for page->mapping != expected_mapping would
  624. * work here too. We have chosen the !PageSwapCache test to
  625. * optimize the common case, when the page is or is about to
  626. * be freed: PageSwapCache is cleared (under spin_lock_irq)
  627. * in the ref_freeze section of __remove_mapping(); but Anon
  628. * page->mapping reset to NULL later, in free_pages_prepare().
  629. */
  630. if (!PageSwapCache(page))
  631. goto stale;
  632. cpu_relax();
  633. }
  634. if (READ_ONCE(page->mapping) != expected_mapping) {
  635. put_page(page);
  636. goto stale;
  637. }
  638. if (flags == GET_KSM_PAGE_TRYLOCK) {
  639. if (!trylock_page(page)) {
  640. put_page(page);
  641. return ERR_PTR(-EBUSY);
  642. }
  643. } else if (flags == GET_KSM_PAGE_LOCK)
  644. lock_page(page);
  645. if (flags != GET_KSM_PAGE_NOLOCK) {
  646. if (READ_ONCE(page->mapping) != expected_mapping) {
  647. unlock_page(page);
  648. put_page(page);
  649. goto stale;
  650. }
  651. }
  652. return page;
  653. stale:
  654. /*
  655. * We come here from above when page->mapping or !PageSwapCache
  656. * suggests that the node is stale; but it might be under migration.
  657. * We need smp_rmb(), matching the smp_wmb() in folio_migrate_ksm(),
  658. * before checking whether node->kpfn has been changed.
  659. */
  660. smp_rmb();
  661. if (READ_ONCE(stable_node->kpfn) != kpfn)
  662. goto again;
  663. remove_node_from_stable_tree(stable_node);
  664. return NULL;
  665. }
  666. /*
  667. * Removing rmap_item from stable or unstable tree.
  668. * This function will clean the information from the stable/unstable tree.
  669. */
  670. static void remove_rmap_item_from_tree(struct ksm_rmap_item *rmap_item)
  671. {
  672. if (rmap_item->address & STABLE_FLAG) {
  673. struct ksm_stable_node *stable_node;
  674. struct page *page;
  675. stable_node = rmap_item->head;
  676. page = get_ksm_page(stable_node, GET_KSM_PAGE_LOCK);
  677. if (!page)
  678. goto out;
  679. hlist_del(&rmap_item->hlist);
  680. unlock_page(page);
  681. put_page(page);
  682. if (!hlist_empty(&stable_node->hlist))
  683. ksm_pages_sharing--;
  684. else
  685. ksm_pages_shared--;
  686. rmap_item->mm->ksm_merging_pages--;
  687. VM_BUG_ON(stable_node->rmap_hlist_len <= 0);
  688. stable_node->rmap_hlist_len--;
  689. put_anon_vma(rmap_item->anon_vma);
  690. rmap_item->head = NULL;
  691. rmap_item->address &= PAGE_MASK;
  692. } else if (rmap_item->address & UNSTABLE_FLAG) {
  693. unsigned char age;
  694. /*
  695. * Usually ksmd can and must skip the rb_erase, because
  696. * root_unstable_tree was already reset to RB_ROOT.
  697. * But be careful when an mm is exiting: do the rb_erase
  698. * if this rmap_item was inserted by this scan, rather
  699. * than left over from before.
  700. */
  701. age = (unsigned char)(ksm_scan.seqnr - rmap_item->address);
  702. BUG_ON(age > 1);
  703. if (!age)
  704. rb_erase(&rmap_item->node,
  705. root_unstable_tree + NUMA(rmap_item->nid));
  706. ksm_pages_unshared--;
  707. rmap_item->address &= PAGE_MASK;
  708. }
  709. out:
  710. cond_resched(); /* we're called from many long loops */
  711. }
  712. static void remove_trailing_rmap_items(struct ksm_rmap_item **rmap_list)
  713. {
  714. while (*rmap_list) {
  715. struct ksm_rmap_item *rmap_item = *rmap_list;
  716. *rmap_list = rmap_item->rmap_list;
  717. remove_rmap_item_from_tree(rmap_item);
  718. free_rmap_item(rmap_item);
  719. }
  720. }
  721. /*
  722. * Though it's very tempting to unmerge rmap_items from stable tree rather
  723. * than check every pte of a given vma, the locking doesn't quite work for
  724. * that - an rmap_item is assigned to the stable tree after inserting ksm
  725. * page and upping mmap_lock. Nor does it fit with the way we skip dup'ing
  726. * rmap_items from parent to child at fork time (so as not to waste time
  727. * if exit comes before the next scan reaches it).
  728. *
  729. * Similarly, although we'd like to remove rmap_items (so updating counts
  730. * and freeing memory) when unmerging an area, it's easier to leave that
  731. * to the next pass of ksmd - consider, for example, how ksmd might be
  732. * in cmp_and_merge_page on one of the rmap_items we would be removing.
  733. */
  734. static int unmerge_ksm_pages(struct vm_area_struct *vma,
  735. unsigned long start, unsigned long end, bool lock_vma)
  736. {
  737. unsigned long addr;
  738. int err = 0;
  739. for (addr = start; addr < end && !err; addr += PAGE_SIZE) {
  740. if (ksm_test_exit(vma->vm_mm))
  741. break;
  742. if (signal_pending(current))
  743. err = -ERESTARTSYS;
  744. else
  745. err = break_ksm(vma, addr, lock_vma);
  746. }
  747. return err;
  748. }
  749. static inline struct ksm_stable_node *folio_stable_node(struct folio *folio)
  750. {
  751. return folio_test_ksm(folio) ? folio_raw_mapping(folio) : NULL;
  752. }
  753. static inline struct ksm_stable_node *page_stable_node(struct page *page)
  754. {
  755. return folio_stable_node(page_folio(page));
  756. }
  757. static inline void set_page_stable_node(struct page *page,
  758. struct ksm_stable_node *stable_node)
  759. {
  760. VM_BUG_ON_PAGE(PageAnon(page) && PageAnonExclusive(page), page);
  761. page->mapping = (void *)((unsigned long)stable_node | PAGE_MAPPING_KSM);
  762. }
  763. #ifdef CONFIG_SYSFS
  764. /*
  765. * Only called through the sysfs control interface:
  766. */
  767. static int remove_stable_node(struct ksm_stable_node *stable_node)
  768. {
  769. struct page *page;
  770. int err;
  771. page = get_ksm_page(stable_node, GET_KSM_PAGE_LOCK);
  772. if (!page) {
  773. /*
  774. * get_ksm_page did remove_node_from_stable_tree itself.
  775. */
  776. return 0;
  777. }
  778. /*
  779. * Page could be still mapped if this races with __mmput() running in
  780. * between ksm_exit() and exit_mmap(). Just refuse to let
  781. * merge_across_nodes/max_page_sharing be switched.
  782. */
  783. err = -EBUSY;
  784. if (!page_mapped(page)) {
  785. /*
  786. * The stable node did not yet appear stale to get_ksm_page(),
  787. * since that allows for an unmapped ksm page to be recognized
  788. * right up until it is freed; but the node is safe to remove.
  789. * This page might be in a pagevec waiting to be freed,
  790. * or it might be PageSwapCache (perhaps under writeback),
  791. * or it might have been removed from swapcache a moment ago.
  792. */
  793. set_page_stable_node(page, NULL);
  794. remove_node_from_stable_tree(stable_node);
  795. err = 0;
  796. }
  797. unlock_page(page);
  798. put_page(page);
  799. return err;
  800. }
  801. static int remove_stable_node_chain(struct ksm_stable_node *stable_node,
  802. struct rb_root *root)
  803. {
  804. struct ksm_stable_node *dup;
  805. struct hlist_node *hlist_safe;
  806. if (!is_stable_node_chain(stable_node)) {
  807. VM_BUG_ON(is_stable_node_dup(stable_node));
  808. if (remove_stable_node(stable_node))
  809. return true;
  810. else
  811. return false;
  812. }
  813. hlist_for_each_entry_safe(dup, hlist_safe,
  814. &stable_node->hlist, hlist_dup) {
  815. VM_BUG_ON(!is_stable_node_dup(dup));
  816. if (remove_stable_node(dup))
  817. return true;
  818. }
  819. BUG_ON(!hlist_empty(&stable_node->hlist));
  820. free_stable_node_chain(stable_node, root);
  821. return false;
  822. }
  823. static int remove_all_stable_nodes(void)
  824. {
  825. struct ksm_stable_node *stable_node, *next;
  826. int nid;
  827. int err = 0;
  828. for (nid = 0; nid < ksm_nr_node_ids; nid++) {
  829. while (root_stable_tree[nid].rb_node) {
  830. stable_node = rb_entry(root_stable_tree[nid].rb_node,
  831. struct ksm_stable_node, node);
  832. if (remove_stable_node_chain(stable_node,
  833. root_stable_tree + nid)) {
  834. err = -EBUSY;
  835. break; /* proceed to next nid */
  836. }
  837. cond_resched();
  838. }
  839. }
  840. list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
  841. if (remove_stable_node(stable_node))
  842. err = -EBUSY;
  843. cond_resched();
  844. }
  845. return err;
  846. }
  847. static int unmerge_and_remove_all_rmap_items(void)
  848. {
  849. struct ksm_mm_slot *mm_slot;
  850. struct mm_slot *slot;
  851. struct mm_struct *mm;
  852. struct vm_area_struct *vma;
  853. int err = 0;
  854. spin_lock(&ksm_mmlist_lock);
  855. slot = list_entry(ksm_mm_head.slot.mm_node.next,
  856. struct mm_slot, mm_node);
  857. ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  858. spin_unlock(&ksm_mmlist_lock);
  859. for (mm_slot = ksm_scan.mm_slot; mm_slot != &ksm_mm_head;
  860. mm_slot = ksm_scan.mm_slot) {
  861. VMA_ITERATOR(vmi, mm_slot->slot.mm, 0);
  862. mm = mm_slot->slot.mm;
  863. mmap_read_lock(mm);
  864. /*
  865. * Exit right away if mm is exiting to avoid lockdep issue in
  866. * the maple tree
  867. */
  868. if (ksm_test_exit(mm))
  869. goto mm_exiting;
  870. for_each_vma(vmi, vma) {
  871. if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma)
  872. continue;
  873. err = unmerge_ksm_pages(vma,
  874. vma->vm_start, vma->vm_end, false);
  875. if (err)
  876. goto error;
  877. }
  878. mm_exiting:
  879. remove_trailing_rmap_items(&mm_slot->rmap_list);
  880. mmap_read_unlock(mm);
  881. spin_lock(&ksm_mmlist_lock);
  882. slot = list_entry(mm_slot->slot.mm_node.next,
  883. struct mm_slot, mm_node);
  884. ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  885. if (ksm_test_exit(mm)) {
  886. hash_del(&mm_slot->slot.hash);
  887. list_del(&mm_slot->slot.mm_node);
  888. spin_unlock(&ksm_mmlist_lock);
  889. mm_slot_free(mm_slot_cache, mm_slot);
  890. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  891. mmdrop(mm);
  892. } else
  893. spin_unlock(&ksm_mmlist_lock);
  894. }
  895. /* Clean up stable nodes, but don't worry if some are still busy */
  896. remove_all_stable_nodes();
  897. ksm_scan.seqnr = 0;
  898. return 0;
  899. error:
  900. mmap_read_unlock(mm);
  901. spin_lock(&ksm_mmlist_lock);
  902. ksm_scan.mm_slot = &ksm_mm_head;
  903. spin_unlock(&ksm_mmlist_lock);
  904. return err;
  905. }
  906. #endif /* CONFIG_SYSFS */
  907. static u32 calc_checksum(struct page *page)
  908. {
  909. u32 checksum;
  910. void *addr = kmap_atomic(page);
  911. checksum = xxhash(addr, PAGE_SIZE, 0);
  912. kunmap_atomic(addr);
  913. return checksum;
  914. }
  915. static int write_protect_page(struct vm_area_struct *vma, struct page *page,
  916. pte_t *orig_pte)
  917. {
  918. struct mm_struct *mm = vma->vm_mm;
  919. DEFINE_PAGE_VMA_WALK(pvmw, page, vma, 0, 0);
  920. int swapped;
  921. int err = -EFAULT;
  922. struct mmu_notifier_range range;
  923. bool anon_exclusive;
  924. pvmw.address = page_address_in_vma(page, vma);
  925. if (pvmw.address == -EFAULT)
  926. goto out;
  927. BUG_ON(PageTransCompound(page));
  928. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
  929. pvmw.address,
  930. pvmw.address + PAGE_SIZE);
  931. mmu_notifier_invalidate_range_start(&range);
  932. if (!page_vma_mapped_walk(&pvmw))
  933. goto out_mn;
  934. if (WARN_ONCE(!pvmw.pte, "Unexpected PMD mapping?"))
  935. goto out_unlock;
  936. anon_exclusive = PageAnonExclusive(page);
  937. if (pte_write(*pvmw.pte) || pte_dirty(*pvmw.pte) ||
  938. (pte_protnone(*pvmw.pte) && pte_savedwrite(*pvmw.pte)) ||
  939. anon_exclusive || mm_tlb_flush_pending(mm)) {
  940. pte_t entry;
  941. swapped = PageSwapCache(page);
  942. flush_cache_page(vma, pvmw.address, page_to_pfn(page));
  943. /*
  944. * Ok this is tricky, when get_user_pages_fast() run it doesn't
  945. * take any lock, therefore the check that we are going to make
  946. * with the pagecount against the mapcount is racy and
  947. * O_DIRECT can happen right after the check.
  948. * So we clear the pte and flush the tlb before the check
  949. * this assure us that no O_DIRECT can happen after the check
  950. * or in the middle of the check.
  951. *
  952. * No need to notify as we are downgrading page table to read
  953. * only not changing it to point to a new page.
  954. *
  955. * See Documentation/mm/mmu_notifier.rst
  956. */
  957. entry = ptep_clear_flush(vma, pvmw.address, pvmw.pte);
  958. /*
  959. * Check that no O_DIRECT or similar I/O is in progress on the
  960. * page
  961. */
  962. if (page_mapcount(page) + 1 + swapped != page_count(page)) {
  963. set_pte_at(mm, pvmw.address, pvmw.pte, entry);
  964. goto out_unlock;
  965. }
  966. /* See page_try_share_anon_rmap(): clear PTE first. */
  967. if (anon_exclusive && page_try_share_anon_rmap(page)) {
  968. set_pte_at(mm, pvmw.address, pvmw.pte, entry);
  969. goto out_unlock;
  970. }
  971. if (pte_dirty(entry))
  972. set_page_dirty(page);
  973. if (pte_protnone(entry))
  974. entry = pte_mkclean(pte_clear_savedwrite(entry));
  975. else
  976. entry = pte_mkclean(pte_wrprotect(entry));
  977. set_pte_at_notify(mm, pvmw.address, pvmw.pte, entry);
  978. }
  979. *orig_pte = *pvmw.pte;
  980. err = 0;
  981. out_unlock:
  982. page_vma_mapped_walk_done(&pvmw);
  983. out_mn:
  984. mmu_notifier_invalidate_range_end(&range);
  985. out:
  986. return err;
  987. }
  988. /**
  989. * replace_page - replace page in vma by new ksm page
  990. * @vma: vma that holds the pte pointing to page
  991. * @page: the page we are replacing by kpage
  992. * @kpage: the ksm page we replace page by
  993. * @orig_pte: the original value of the pte
  994. *
  995. * Returns 0 on success, -EFAULT on failure.
  996. */
  997. static int replace_page(struct vm_area_struct *vma, struct page *page,
  998. struct page *kpage, pte_t orig_pte)
  999. {
  1000. struct mm_struct *mm = vma->vm_mm;
  1001. struct folio *folio;
  1002. pmd_t *pmd;
  1003. pmd_t pmde;
  1004. pte_t *ptep;
  1005. pte_t newpte;
  1006. spinlock_t *ptl;
  1007. unsigned long addr;
  1008. int err = -EFAULT;
  1009. struct mmu_notifier_range range;
  1010. addr = page_address_in_vma(page, vma);
  1011. if (addr == -EFAULT)
  1012. goto out;
  1013. pmd = mm_find_pmd(mm, addr);
  1014. if (!pmd)
  1015. goto out;
  1016. /*
  1017. * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
  1018. * without holding anon_vma lock for write. So when looking for a
  1019. * genuine pmde (in which to find pte), test present and !THP together.
  1020. */
  1021. pmde = *pmd;
  1022. barrier();
  1023. if (!pmd_present(pmde) || pmd_trans_huge(pmde))
  1024. goto out;
  1025. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, addr,
  1026. addr + PAGE_SIZE);
  1027. mmu_notifier_invalidate_range_start(&range);
  1028. ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
  1029. if (!pte_same(*ptep, orig_pte)) {
  1030. pte_unmap_unlock(ptep, ptl);
  1031. goto out_mn;
  1032. }
  1033. VM_BUG_ON_PAGE(PageAnonExclusive(page), page);
  1034. VM_BUG_ON_PAGE(PageAnon(kpage) && PageAnonExclusive(kpage), kpage);
  1035. /*
  1036. * No need to check ksm_use_zero_pages here: we can only have a
  1037. * zero_page here if ksm_use_zero_pages was enabled already.
  1038. */
  1039. if (!is_zero_pfn(page_to_pfn(kpage))) {
  1040. get_page(kpage);
  1041. page_add_anon_rmap(kpage, vma, addr, RMAP_NONE);
  1042. newpte = mk_pte(kpage, vma->vm_page_prot);
  1043. } else {
  1044. newpte = pte_mkspecial(pfn_pte(page_to_pfn(kpage),
  1045. vma->vm_page_prot));
  1046. /*
  1047. * We're replacing an anonymous page with a zero page, which is
  1048. * not anonymous. We need to do proper accounting otherwise we
  1049. * will get wrong values in /proc, and a BUG message in dmesg
  1050. * when tearing down the mm.
  1051. */
  1052. dec_mm_counter(mm, MM_ANONPAGES);
  1053. }
  1054. flush_cache_page(vma, addr, pte_pfn(*ptep));
  1055. /*
  1056. * No need to notify as we are replacing a read only page with another
  1057. * read only page with the same content.
  1058. *
  1059. * See Documentation/mm/mmu_notifier.rst
  1060. */
  1061. ptep_clear_flush(vma, addr, ptep);
  1062. set_pte_at_notify(mm, addr, ptep, newpte);
  1063. folio = page_folio(page);
  1064. page_remove_rmap(page, vma, false);
  1065. if (!folio_mapped(folio))
  1066. folio_free_swap(folio);
  1067. folio_put(folio);
  1068. pte_unmap_unlock(ptep, ptl);
  1069. err = 0;
  1070. out_mn:
  1071. mmu_notifier_invalidate_range_end(&range);
  1072. out:
  1073. return err;
  1074. }
  1075. /*
  1076. * try_to_merge_one_page - take two pages and merge them into one
  1077. * @vma: the vma that holds the pte pointing to page
  1078. * @page: the PageAnon page that we want to replace with kpage
  1079. * @kpage: the PageKsm page that we want to map instead of page,
  1080. * or NULL the first time when we want to use page as kpage.
  1081. *
  1082. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  1083. */
  1084. static int try_to_merge_one_page(struct vm_area_struct *vma,
  1085. struct page *page, struct page *kpage)
  1086. {
  1087. pte_t orig_pte = __pte(0);
  1088. int err = -EFAULT;
  1089. if (page == kpage) /* ksm page forked */
  1090. return 0;
  1091. if (!PageAnon(page))
  1092. goto out;
  1093. /*
  1094. * We need the page lock to read a stable PageSwapCache in
  1095. * write_protect_page(). We use trylock_page() instead of
  1096. * lock_page() because we don't want to wait here - we
  1097. * prefer to continue scanning and merging different pages,
  1098. * then come back to this page when it is unlocked.
  1099. */
  1100. if (!trylock_page(page))
  1101. goto out;
  1102. if (PageTransCompound(page)) {
  1103. if (split_huge_page(page))
  1104. goto out_unlock;
  1105. }
  1106. /*
  1107. * If this anonymous page is mapped only here, its pte may need
  1108. * to be write-protected. If it's mapped elsewhere, all of its
  1109. * ptes are necessarily already write-protected. But in either
  1110. * case, we need to lock and check page_count is not raised.
  1111. */
  1112. if (write_protect_page(vma, page, &orig_pte) == 0) {
  1113. if (!kpage) {
  1114. /*
  1115. * While we hold page lock, upgrade page from
  1116. * PageAnon+anon_vma to PageKsm+NULL stable_node:
  1117. * stable_tree_insert() will update stable_node.
  1118. */
  1119. set_page_stable_node(page, NULL);
  1120. mark_page_accessed(page);
  1121. /*
  1122. * Page reclaim just frees a clean page with no dirty
  1123. * ptes: make sure that the ksm page would be swapped.
  1124. */
  1125. if (!PageDirty(page))
  1126. SetPageDirty(page);
  1127. err = 0;
  1128. } else if (pages_identical(page, kpage))
  1129. err = replace_page(vma, page, kpage, orig_pte);
  1130. }
  1131. out_unlock:
  1132. unlock_page(page);
  1133. out:
  1134. return err;
  1135. }
  1136. /*
  1137. * try_to_merge_with_ksm_page - like try_to_merge_two_pages,
  1138. * but no new kernel page is allocated: kpage must already be a ksm page.
  1139. *
  1140. * This function returns 0 if the pages were merged, -EFAULT otherwise.
  1141. */
  1142. static int try_to_merge_with_ksm_page(struct ksm_rmap_item *rmap_item,
  1143. struct page *page, struct page *kpage)
  1144. {
  1145. struct mm_struct *mm = rmap_item->mm;
  1146. struct vm_area_struct *vma;
  1147. int err = -EFAULT;
  1148. mmap_read_lock(mm);
  1149. vma = find_mergeable_vma(mm, rmap_item->address);
  1150. if (!vma)
  1151. goto out;
  1152. err = try_to_merge_one_page(vma, page, kpage);
  1153. if (err)
  1154. goto out;
  1155. /* Unstable nid is in union with stable anon_vma: remove first */
  1156. remove_rmap_item_from_tree(rmap_item);
  1157. /* Must get reference to anon_vma while still holding mmap_lock */
  1158. rmap_item->anon_vma = vma->anon_vma;
  1159. get_anon_vma(vma->anon_vma);
  1160. out:
  1161. mmap_read_unlock(mm);
  1162. return err;
  1163. }
  1164. /*
  1165. * try_to_merge_two_pages - take two identical pages and prepare them
  1166. * to be merged into one page.
  1167. *
  1168. * This function returns the kpage if we successfully merged two identical
  1169. * pages into one ksm page, NULL otherwise.
  1170. *
  1171. * Note that this function upgrades page to ksm page: if one of the pages
  1172. * is already a ksm page, try_to_merge_with_ksm_page should be used.
  1173. */
  1174. static struct page *try_to_merge_two_pages(struct ksm_rmap_item *rmap_item,
  1175. struct page *page,
  1176. struct ksm_rmap_item *tree_rmap_item,
  1177. struct page *tree_page)
  1178. {
  1179. int err;
  1180. err = try_to_merge_with_ksm_page(rmap_item, page, NULL);
  1181. if (!err) {
  1182. err = try_to_merge_with_ksm_page(tree_rmap_item,
  1183. tree_page, page);
  1184. /*
  1185. * If that fails, we have a ksm page with only one pte
  1186. * pointing to it: so break it.
  1187. */
  1188. if (err)
  1189. break_cow(rmap_item);
  1190. }
  1191. return err ? NULL : page;
  1192. }
  1193. static __always_inline
  1194. bool __is_page_sharing_candidate(struct ksm_stable_node *stable_node, int offset)
  1195. {
  1196. VM_BUG_ON(stable_node->rmap_hlist_len < 0);
  1197. /*
  1198. * Check that at least one mapping still exists, otherwise
  1199. * there's no much point to merge and share with this
  1200. * stable_node, as the underlying tree_page of the other
  1201. * sharer is going to be freed soon.
  1202. */
  1203. return stable_node->rmap_hlist_len &&
  1204. stable_node->rmap_hlist_len + offset < ksm_max_page_sharing;
  1205. }
  1206. static __always_inline
  1207. bool is_page_sharing_candidate(struct ksm_stable_node *stable_node)
  1208. {
  1209. return __is_page_sharing_candidate(stable_node, 0);
  1210. }
  1211. static struct page *stable_node_dup(struct ksm_stable_node **_stable_node_dup,
  1212. struct ksm_stable_node **_stable_node,
  1213. struct rb_root *root,
  1214. bool prune_stale_stable_nodes)
  1215. {
  1216. struct ksm_stable_node *dup, *found = NULL, *stable_node = *_stable_node;
  1217. struct hlist_node *hlist_safe;
  1218. struct page *_tree_page, *tree_page = NULL;
  1219. int nr = 0;
  1220. int found_rmap_hlist_len;
  1221. if (!prune_stale_stable_nodes ||
  1222. time_before(jiffies, stable_node->chain_prune_time +
  1223. msecs_to_jiffies(
  1224. ksm_stable_node_chains_prune_millisecs)))
  1225. prune_stale_stable_nodes = false;
  1226. else
  1227. stable_node->chain_prune_time = jiffies;
  1228. hlist_for_each_entry_safe(dup, hlist_safe,
  1229. &stable_node->hlist, hlist_dup) {
  1230. cond_resched();
  1231. /*
  1232. * We must walk all stable_node_dup to prune the stale
  1233. * stable nodes during lookup.
  1234. *
  1235. * get_ksm_page can drop the nodes from the
  1236. * stable_node->hlist if they point to freed pages
  1237. * (that's why we do a _safe walk). The "dup"
  1238. * stable_node parameter itself will be freed from
  1239. * under us if it returns NULL.
  1240. */
  1241. _tree_page = get_ksm_page(dup, GET_KSM_PAGE_NOLOCK);
  1242. if (!_tree_page)
  1243. continue;
  1244. nr += 1;
  1245. if (is_page_sharing_candidate(dup)) {
  1246. if (!found ||
  1247. dup->rmap_hlist_len > found_rmap_hlist_len) {
  1248. if (found)
  1249. put_page(tree_page);
  1250. found = dup;
  1251. found_rmap_hlist_len = found->rmap_hlist_len;
  1252. tree_page = _tree_page;
  1253. /* skip put_page for found dup */
  1254. if (!prune_stale_stable_nodes)
  1255. break;
  1256. continue;
  1257. }
  1258. }
  1259. put_page(_tree_page);
  1260. }
  1261. if (found) {
  1262. /*
  1263. * nr is counting all dups in the chain only if
  1264. * prune_stale_stable_nodes is true, otherwise we may
  1265. * break the loop at nr == 1 even if there are
  1266. * multiple entries.
  1267. */
  1268. if (prune_stale_stable_nodes && nr == 1) {
  1269. /*
  1270. * If there's not just one entry it would
  1271. * corrupt memory, better BUG_ON. In KSM
  1272. * context with no lock held it's not even
  1273. * fatal.
  1274. */
  1275. BUG_ON(stable_node->hlist.first->next);
  1276. /*
  1277. * There's just one entry and it is below the
  1278. * deduplication limit so drop the chain.
  1279. */
  1280. rb_replace_node(&stable_node->node, &found->node,
  1281. root);
  1282. free_stable_node(stable_node);
  1283. ksm_stable_node_chains--;
  1284. ksm_stable_node_dups--;
  1285. /*
  1286. * NOTE: the caller depends on the stable_node
  1287. * to be equal to stable_node_dup if the chain
  1288. * was collapsed.
  1289. */
  1290. *_stable_node = found;
  1291. /*
  1292. * Just for robustness, as stable_node is
  1293. * otherwise left as a stable pointer, the
  1294. * compiler shall optimize it away at build
  1295. * time.
  1296. */
  1297. stable_node = NULL;
  1298. } else if (stable_node->hlist.first != &found->hlist_dup &&
  1299. __is_page_sharing_candidate(found, 1)) {
  1300. /*
  1301. * If the found stable_node dup can accept one
  1302. * more future merge (in addition to the one
  1303. * that is underway) and is not at the head of
  1304. * the chain, put it there so next search will
  1305. * be quicker in the !prune_stale_stable_nodes
  1306. * case.
  1307. *
  1308. * NOTE: it would be inaccurate to use nr > 1
  1309. * instead of checking the hlist.first pointer
  1310. * directly, because in the
  1311. * prune_stale_stable_nodes case "nr" isn't
  1312. * the position of the found dup in the chain,
  1313. * but the total number of dups in the chain.
  1314. */
  1315. hlist_del(&found->hlist_dup);
  1316. hlist_add_head(&found->hlist_dup,
  1317. &stable_node->hlist);
  1318. }
  1319. }
  1320. *_stable_node_dup = found;
  1321. return tree_page;
  1322. }
  1323. static struct ksm_stable_node *stable_node_dup_any(struct ksm_stable_node *stable_node,
  1324. struct rb_root *root)
  1325. {
  1326. if (!is_stable_node_chain(stable_node))
  1327. return stable_node;
  1328. if (hlist_empty(&stable_node->hlist)) {
  1329. free_stable_node_chain(stable_node, root);
  1330. return NULL;
  1331. }
  1332. return hlist_entry(stable_node->hlist.first,
  1333. typeof(*stable_node), hlist_dup);
  1334. }
  1335. /*
  1336. * Like for get_ksm_page, this function can free the *_stable_node and
  1337. * *_stable_node_dup if the returned tree_page is NULL.
  1338. *
  1339. * It can also free and overwrite *_stable_node with the found
  1340. * stable_node_dup if the chain is collapsed (in which case
  1341. * *_stable_node will be equal to *_stable_node_dup like if the chain
  1342. * never existed). It's up to the caller to verify tree_page is not
  1343. * NULL before dereferencing *_stable_node or *_stable_node_dup.
  1344. *
  1345. * *_stable_node_dup is really a second output parameter of this
  1346. * function and will be overwritten in all cases, the caller doesn't
  1347. * need to initialize it.
  1348. */
  1349. static struct page *__stable_node_chain(struct ksm_stable_node **_stable_node_dup,
  1350. struct ksm_stable_node **_stable_node,
  1351. struct rb_root *root,
  1352. bool prune_stale_stable_nodes)
  1353. {
  1354. struct ksm_stable_node *stable_node = *_stable_node;
  1355. if (!is_stable_node_chain(stable_node)) {
  1356. if (is_page_sharing_candidate(stable_node)) {
  1357. *_stable_node_dup = stable_node;
  1358. return get_ksm_page(stable_node, GET_KSM_PAGE_NOLOCK);
  1359. }
  1360. /*
  1361. * _stable_node_dup set to NULL means the stable_node
  1362. * reached the ksm_max_page_sharing limit.
  1363. */
  1364. *_stable_node_dup = NULL;
  1365. return NULL;
  1366. }
  1367. return stable_node_dup(_stable_node_dup, _stable_node, root,
  1368. prune_stale_stable_nodes);
  1369. }
  1370. static __always_inline struct page *chain_prune(struct ksm_stable_node **s_n_d,
  1371. struct ksm_stable_node **s_n,
  1372. struct rb_root *root)
  1373. {
  1374. return __stable_node_chain(s_n_d, s_n, root, true);
  1375. }
  1376. static __always_inline struct page *chain(struct ksm_stable_node **s_n_d,
  1377. struct ksm_stable_node *s_n,
  1378. struct rb_root *root)
  1379. {
  1380. struct ksm_stable_node *old_stable_node = s_n;
  1381. struct page *tree_page;
  1382. tree_page = __stable_node_chain(s_n_d, &s_n, root, false);
  1383. /* not pruning dups so s_n cannot have changed */
  1384. VM_BUG_ON(s_n != old_stable_node);
  1385. return tree_page;
  1386. }
  1387. /*
  1388. * stable_tree_search - search for page inside the stable tree
  1389. *
  1390. * This function checks if there is a page inside the stable tree
  1391. * with identical content to the page that we are scanning right now.
  1392. *
  1393. * This function returns the stable tree node of identical content if found,
  1394. * NULL otherwise.
  1395. */
  1396. static struct page *stable_tree_search(struct page *page)
  1397. {
  1398. int nid;
  1399. struct rb_root *root;
  1400. struct rb_node **new;
  1401. struct rb_node *parent;
  1402. struct ksm_stable_node *stable_node, *stable_node_dup, *stable_node_any;
  1403. struct ksm_stable_node *page_node;
  1404. page_node = page_stable_node(page);
  1405. if (page_node && page_node->head != &migrate_nodes) {
  1406. /* ksm page forked */
  1407. get_page(page);
  1408. return page;
  1409. }
  1410. nid = get_kpfn_nid(page_to_pfn(page));
  1411. root = root_stable_tree + nid;
  1412. again:
  1413. new = &root->rb_node;
  1414. parent = NULL;
  1415. while (*new) {
  1416. struct page *tree_page;
  1417. int ret;
  1418. cond_resched();
  1419. stable_node = rb_entry(*new, struct ksm_stable_node, node);
  1420. stable_node_any = NULL;
  1421. tree_page = chain_prune(&stable_node_dup, &stable_node, root);
  1422. /*
  1423. * NOTE: stable_node may have been freed by
  1424. * chain_prune() if the returned stable_node_dup is
  1425. * not NULL. stable_node_dup may have been inserted in
  1426. * the rbtree instead as a regular stable_node (in
  1427. * order to collapse the stable_node chain if a single
  1428. * stable_node dup was found in it). In such case the
  1429. * stable_node is overwritten by the callee to point
  1430. * to the stable_node_dup that was collapsed in the
  1431. * stable rbtree and stable_node will be equal to
  1432. * stable_node_dup like if the chain never existed.
  1433. */
  1434. if (!stable_node_dup) {
  1435. /*
  1436. * Either all stable_node dups were full in
  1437. * this stable_node chain, or this chain was
  1438. * empty and should be rb_erased.
  1439. */
  1440. stable_node_any = stable_node_dup_any(stable_node,
  1441. root);
  1442. if (!stable_node_any) {
  1443. /* rb_erase just run */
  1444. goto again;
  1445. }
  1446. /*
  1447. * Take any of the stable_node dups page of
  1448. * this stable_node chain to let the tree walk
  1449. * continue. All KSM pages belonging to the
  1450. * stable_node dups in a stable_node chain
  1451. * have the same content and they're
  1452. * write protected at all times. Any will work
  1453. * fine to continue the walk.
  1454. */
  1455. tree_page = get_ksm_page(stable_node_any,
  1456. GET_KSM_PAGE_NOLOCK);
  1457. }
  1458. VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
  1459. if (!tree_page) {
  1460. /*
  1461. * If we walked over a stale stable_node,
  1462. * get_ksm_page() will call rb_erase() and it
  1463. * may rebalance the tree from under us. So
  1464. * restart the search from scratch. Returning
  1465. * NULL would be safe too, but we'd generate
  1466. * false negative insertions just because some
  1467. * stable_node was stale.
  1468. */
  1469. goto again;
  1470. }
  1471. ret = memcmp_pages(page, tree_page);
  1472. put_page(tree_page);
  1473. parent = *new;
  1474. if (ret < 0)
  1475. new = &parent->rb_left;
  1476. else if (ret > 0)
  1477. new = &parent->rb_right;
  1478. else {
  1479. if (page_node) {
  1480. VM_BUG_ON(page_node->head != &migrate_nodes);
  1481. /*
  1482. * Test if the migrated page should be merged
  1483. * into a stable node dup. If the mapcount is
  1484. * 1 we can migrate it with another KSM page
  1485. * without adding it to the chain.
  1486. */
  1487. if (page_mapcount(page) > 1)
  1488. goto chain_append;
  1489. }
  1490. if (!stable_node_dup) {
  1491. /*
  1492. * If the stable_node is a chain and
  1493. * we got a payload match in memcmp
  1494. * but we cannot merge the scanned
  1495. * page in any of the existing
  1496. * stable_node dups because they're
  1497. * all full, we need to wait the
  1498. * scanned page to find itself a match
  1499. * in the unstable tree to create a
  1500. * brand new KSM page to add later to
  1501. * the dups of this stable_node.
  1502. */
  1503. return NULL;
  1504. }
  1505. /*
  1506. * Lock and unlock the stable_node's page (which
  1507. * might already have been migrated) so that page
  1508. * migration is sure to notice its raised count.
  1509. * It would be more elegant to return stable_node
  1510. * than kpage, but that involves more changes.
  1511. */
  1512. tree_page = get_ksm_page(stable_node_dup,
  1513. GET_KSM_PAGE_TRYLOCK);
  1514. if (PTR_ERR(tree_page) == -EBUSY)
  1515. return ERR_PTR(-EBUSY);
  1516. if (unlikely(!tree_page))
  1517. /*
  1518. * The tree may have been rebalanced,
  1519. * so re-evaluate parent and new.
  1520. */
  1521. goto again;
  1522. unlock_page(tree_page);
  1523. if (get_kpfn_nid(stable_node_dup->kpfn) !=
  1524. NUMA(stable_node_dup->nid)) {
  1525. put_page(tree_page);
  1526. goto replace;
  1527. }
  1528. return tree_page;
  1529. }
  1530. }
  1531. if (!page_node)
  1532. return NULL;
  1533. list_del(&page_node->list);
  1534. DO_NUMA(page_node->nid = nid);
  1535. rb_link_node(&page_node->node, parent, new);
  1536. rb_insert_color(&page_node->node, root);
  1537. out:
  1538. if (is_page_sharing_candidate(page_node)) {
  1539. get_page(page);
  1540. return page;
  1541. } else
  1542. return NULL;
  1543. replace:
  1544. /*
  1545. * If stable_node was a chain and chain_prune collapsed it,
  1546. * stable_node has been updated to be the new regular
  1547. * stable_node. A collapse of the chain is indistinguishable
  1548. * from the case there was no chain in the stable
  1549. * rbtree. Otherwise stable_node is the chain and
  1550. * stable_node_dup is the dup to replace.
  1551. */
  1552. if (stable_node_dup == stable_node) {
  1553. VM_BUG_ON(is_stable_node_chain(stable_node_dup));
  1554. VM_BUG_ON(is_stable_node_dup(stable_node_dup));
  1555. /* there is no chain */
  1556. if (page_node) {
  1557. VM_BUG_ON(page_node->head != &migrate_nodes);
  1558. list_del(&page_node->list);
  1559. DO_NUMA(page_node->nid = nid);
  1560. rb_replace_node(&stable_node_dup->node,
  1561. &page_node->node,
  1562. root);
  1563. if (is_page_sharing_candidate(page_node))
  1564. get_page(page);
  1565. else
  1566. page = NULL;
  1567. } else {
  1568. rb_erase(&stable_node_dup->node, root);
  1569. page = NULL;
  1570. }
  1571. } else {
  1572. VM_BUG_ON(!is_stable_node_chain(stable_node));
  1573. __stable_node_dup_del(stable_node_dup);
  1574. if (page_node) {
  1575. VM_BUG_ON(page_node->head != &migrate_nodes);
  1576. list_del(&page_node->list);
  1577. DO_NUMA(page_node->nid = nid);
  1578. stable_node_chain_add_dup(page_node, stable_node);
  1579. if (is_page_sharing_candidate(page_node))
  1580. get_page(page);
  1581. else
  1582. page = NULL;
  1583. } else {
  1584. page = NULL;
  1585. }
  1586. }
  1587. stable_node_dup->head = &migrate_nodes;
  1588. list_add(&stable_node_dup->list, stable_node_dup->head);
  1589. return page;
  1590. chain_append:
  1591. /* stable_node_dup could be null if it reached the limit */
  1592. if (!stable_node_dup)
  1593. stable_node_dup = stable_node_any;
  1594. /*
  1595. * If stable_node was a chain and chain_prune collapsed it,
  1596. * stable_node has been updated to be the new regular
  1597. * stable_node. A collapse of the chain is indistinguishable
  1598. * from the case there was no chain in the stable
  1599. * rbtree. Otherwise stable_node is the chain and
  1600. * stable_node_dup is the dup to replace.
  1601. */
  1602. if (stable_node_dup == stable_node) {
  1603. VM_BUG_ON(is_stable_node_dup(stable_node_dup));
  1604. /* chain is missing so create it */
  1605. stable_node = alloc_stable_node_chain(stable_node_dup,
  1606. root);
  1607. if (!stable_node)
  1608. return NULL;
  1609. }
  1610. /*
  1611. * Add this stable_node dup that was
  1612. * migrated to the stable_node chain
  1613. * of the current nid for this page
  1614. * content.
  1615. */
  1616. VM_BUG_ON(!is_stable_node_dup(stable_node_dup));
  1617. VM_BUG_ON(page_node->head != &migrate_nodes);
  1618. list_del(&page_node->list);
  1619. DO_NUMA(page_node->nid = nid);
  1620. stable_node_chain_add_dup(page_node, stable_node);
  1621. goto out;
  1622. }
  1623. /*
  1624. * stable_tree_insert - insert stable tree node pointing to new ksm page
  1625. * into the stable tree.
  1626. *
  1627. * This function returns the stable tree node just allocated on success,
  1628. * NULL otherwise.
  1629. */
  1630. static struct ksm_stable_node *stable_tree_insert(struct page *kpage)
  1631. {
  1632. int nid;
  1633. unsigned long kpfn;
  1634. struct rb_root *root;
  1635. struct rb_node **new;
  1636. struct rb_node *parent;
  1637. struct ksm_stable_node *stable_node, *stable_node_dup, *stable_node_any;
  1638. bool need_chain = false;
  1639. kpfn = page_to_pfn(kpage);
  1640. nid = get_kpfn_nid(kpfn);
  1641. root = root_stable_tree + nid;
  1642. again:
  1643. parent = NULL;
  1644. new = &root->rb_node;
  1645. while (*new) {
  1646. struct page *tree_page;
  1647. int ret;
  1648. cond_resched();
  1649. stable_node = rb_entry(*new, struct ksm_stable_node, node);
  1650. stable_node_any = NULL;
  1651. tree_page = chain(&stable_node_dup, stable_node, root);
  1652. if (!stable_node_dup) {
  1653. /*
  1654. * Either all stable_node dups were full in
  1655. * this stable_node chain, or this chain was
  1656. * empty and should be rb_erased.
  1657. */
  1658. stable_node_any = stable_node_dup_any(stable_node,
  1659. root);
  1660. if (!stable_node_any) {
  1661. /* rb_erase just run */
  1662. goto again;
  1663. }
  1664. /*
  1665. * Take any of the stable_node dups page of
  1666. * this stable_node chain to let the tree walk
  1667. * continue. All KSM pages belonging to the
  1668. * stable_node dups in a stable_node chain
  1669. * have the same content and they're
  1670. * write protected at all times. Any will work
  1671. * fine to continue the walk.
  1672. */
  1673. tree_page = get_ksm_page(stable_node_any,
  1674. GET_KSM_PAGE_NOLOCK);
  1675. }
  1676. VM_BUG_ON(!stable_node_dup ^ !!stable_node_any);
  1677. if (!tree_page) {
  1678. /*
  1679. * If we walked over a stale stable_node,
  1680. * get_ksm_page() will call rb_erase() and it
  1681. * may rebalance the tree from under us. So
  1682. * restart the search from scratch. Returning
  1683. * NULL would be safe too, but we'd generate
  1684. * false negative insertions just because some
  1685. * stable_node was stale.
  1686. */
  1687. goto again;
  1688. }
  1689. ret = memcmp_pages(kpage, tree_page);
  1690. put_page(tree_page);
  1691. parent = *new;
  1692. if (ret < 0)
  1693. new = &parent->rb_left;
  1694. else if (ret > 0)
  1695. new = &parent->rb_right;
  1696. else {
  1697. need_chain = true;
  1698. break;
  1699. }
  1700. }
  1701. stable_node_dup = alloc_stable_node();
  1702. if (!stable_node_dup)
  1703. return NULL;
  1704. INIT_HLIST_HEAD(&stable_node_dup->hlist);
  1705. stable_node_dup->kpfn = kpfn;
  1706. set_page_stable_node(kpage, stable_node_dup);
  1707. stable_node_dup->rmap_hlist_len = 0;
  1708. DO_NUMA(stable_node_dup->nid = nid);
  1709. if (!need_chain) {
  1710. rb_link_node(&stable_node_dup->node, parent, new);
  1711. rb_insert_color(&stable_node_dup->node, root);
  1712. } else {
  1713. if (!is_stable_node_chain(stable_node)) {
  1714. struct ksm_stable_node *orig = stable_node;
  1715. /* chain is missing so create it */
  1716. stable_node = alloc_stable_node_chain(orig, root);
  1717. if (!stable_node) {
  1718. free_stable_node(stable_node_dup);
  1719. return NULL;
  1720. }
  1721. }
  1722. stable_node_chain_add_dup(stable_node_dup, stable_node);
  1723. }
  1724. return stable_node_dup;
  1725. }
  1726. /*
  1727. * unstable_tree_search_insert - search for identical page,
  1728. * else insert rmap_item into the unstable tree.
  1729. *
  1730. * This function searches for a page in the unstable tree identical to the
  1731. * page currently being scanned; and if no identical page is found in the
  1732. * tree, we insert rmap_item as a new object into the unstable tree.
  1733. *
  1734. * This function returns pointer to rmap_item found to be identical
  1735. * to the currently scanned page, NULL otherwise.
  1736. *
  1737. * This function does both searching and inserting, because they share
  1738. * the same walking algorithm in an rbtree.
  1739. */
  1740. static
  1741. struct ksm_rmap_item *unstable_tree_search_insert(struct ksm_rmap_item *rmap_item,
  1742. struct page *page,
  1743. struct page **tree_pagep)
  1744. {
  1745. struct rb_node **new;
  1746. struct rb_root *root;
  1747. struct rb_node *parent = NULL;
  1748. int nid;
  1749. nid = get_kpfn_nid(page_to_pfn(page));
  1750. root = root_unstable_tree + nid;
  1751. new = &root->rb_node;
  1752. while (*new) {
  1753. struct ksm_rmap_item *tree_rmap_item;
  1754. struct page *tree_page;
  1755. int ret;
  1756. cond_resched();
  1757. tree_rmap_item = rb_entry(*new, struct ksm_rmap_item, node);
  1758. tree_page = get_mergeable_page(tree_rmap_item);
  1759. if (!tree_page)
  1760. return NULL;
  1761. /*
  1762. * Don't substitute a ksm page for a forked page.
  1763. */
  1764. if (page == tree_page) {
  1765. put_page(tree_page);
  1766. return NULL;
  1767. }
  1768. ret = memcmp_pages(page, tree_page);
  1769. parent = *new;
  1770. if (ret < 0) {
  1771. put_page(tree_page);
  1772. new = &parent->rb_left;
  1773. } else if (ret > 0) {
  1774. put_page(tree_page);
  1775. new = &parent->rb_right;
  1776. } else if (!ksm_merge_across_nodes &&
  1777. page_to_nid(tree_page) != nid) {
  1778. /*
  1779. * If tree_page has been migrated to another NUMA node,
  1780. * it will be flushed out and put in the right unstable
  1781. * tree next time: only merge with it when across_nodes.
  1782. */
  1783. put_page(tree_page);
  1784. return NULL;
  1785. } else {
  1786. *tree_pagep = tree_page;
  1787. return tree_rmap_item;
  1788. }
  1789. }
  1790. rmap_item->address |= UNSTABLE_FLAG;
  1791. rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK);
  1792. DO_NUMA(rmap_item->nid = nid);
  1793. rb_link_node(&rmap_item->node, parent, new);
  1794. rb_insert_color(&rmap_item->node, root);
  1795. ksm_pages_unshared++;
  1796. return NULL;
  1797. }
  1798. /*
  1799. * stable_tree_append - add another rmap_item to the linked list of
  1800. * rmap_items hanging off a given node of the stable tree, all sharing
  1801. * the same ksm page.
  1802. */
  1803. static void stable_tree_append(struct ksm_rmap_item *rmap_item,
  1804. struct ksm_stable_node *stable_node,
  1805. bool max_page_sharing_bypass)
  1806. {
  1807. /*
  1808. * rmap won't find this mapping if we don't insert the
  1809. * rmap_item in the right stable_node
  1810. * duplicate. page_migration could break later if rmap breaks,
  1811. * so we can as well crash here. We really need to check for
  1812. * rmap_hlist_len == STABLE_NODE_CHAIN, but we can as well check
  1813. * for other negative values as an underflow if detected here
  1814. * for the first time (and not when decreasing rmap_hlist_len)
  1815. * would be sign of memory corruption in the stable_node.
  1816. */
  1817. BUG_ON(stable_node->rmap_hlist_len < 0);
  1818. stable_node->rmap_hlist_len++;
  1819. if (!max_page_sharing_bypass)
  1820. /* possibly non fatal but unexpected overflow, only warn */
  1821. WARN_ON_ONCE(stable_node->rmap_hlist_len >
  1822. ksm_max_page_sharing);
  1823. rmap_item->head = stable_node;
  1824. rmap_item->address |= STABLE_FLAG;
  1825. hlist_add_head(&rmap_item->hlist, &stable_node->hlist);
  1826. if (rmap_item->hlist.next)
  1827. ksm_pages_sharing++;
  1828. else
  1829. ksm_pages_shared++;
  1830. rmap_item->mm->ksm_merging_pages++;
  1831. }
  1832. /*
  1833. * cmp_and_merge_page - first see if page can be merged into the stable tree;
  1834. * if not, compare checksum to previous and if it's the same, see if page can
  1835. * be inserted into the unstable tree, or merged with a page already there and
  1836. * both transferred to the stable tree.
  1837. *
  1838. * @page: the page that we are searching identical page to.
  1839. * @rmap_item: the reverse mapping into the virtual address of this page
  1840. */
  1841. static void cmp_and_merge_page(struct page *page, struct ksm_rmap_item *rmap_item)
  1842. {
  1843. struct mm_struct *mm = rmap_item->mm;
  1844. struct ksm_rmap_item *tree_rmap_item;
  1845. struct page *tree_page = NULL;
  1846. struct ksm_stable_node *stable_node;
  1847. struct page *kpage;
  1848. unsigned int checksum;
  1849. int err;
  1850. bool max_page_sharing_bypass = false;
  1851. stable_node = page_stable_node(page);
  1852. if (stable_node) {
  1853. if (stable_node->head != &migrate_nodes &&
  1854. get_kpfn_nid(READ_ONCE(stable_node->kpfn)) !=
  1855. NUMA(stable_node->nid)) {
  1856. stable_node_dup_del(stable_node);
  1857. stable_node->head = &migrate_nodes;
  1858. list_add(&stable_node->list, stable_node->head);
  1859. }
  1860. if (stable_node->head != &migrate_nodes &&
  1861. rmap_item->head == stable_node)
  1862. return;
  1863. /*
  1864. * If it's a KSM fork, allow it to go over the sharing limit
  1865. * without warnings.
  1866. */
  1867. if (!is_page_sharing_candidate(stable_node))
  1868. max_page_sharing_bypass = true;
  1869. }
  1870. /* We first start with searching the page inside the stable tree */
  1871. kpage = stable_tree_search(page);
  1872. if (kpage == page && rmap_item->head == stable_node) {
  1873. put_page(kpage);
  1874. return;
  1875. }
  1876. remove_rmap_item_from_tree(rmap_item);
  1877. if (kpage) {
  1878. if (PTR_ERR(kpage) == -EBUSY)
  1879. return;
  1880. err = try_to_merge_with_ksm_page(rmap_item, page, kpage);
  1881. if (!err) {
  1882. /*
  1883. * The page was successfully merged:
  1884. * add its rmap_item to the stable tree.
  1885. */
  1886. lock_page(kpage);
  1887. stable_tree_append(rmap_item, page_stable_node(kpage),
  1888. max_page_sharing_bypass);
  1889. unlock_page(kpage);
  1890. }
  1891. put_page(kpage);
  1892. return;
  1893. }
  1894. /*
  1895. * If the hash value of the page has changed from the last time
  1896. * we calculated it, this page is changing frequently: therefore we
  1897. * don't want to insert it in the unstable tree, and we don't want
  1898. * to waste our time searching for something identical to it there.
  1899. */
  1900. checksum = calc_checksum(page);
  1901. if (rmap_item->oldchecksum != checksum) {
  1902. rmap_item->oldchecksum = checksum;
  1903. return;
  1904. }
  1905. /*
  1906. * Same checksum as an empty page. We attempt to merge it with the
  1907. * appropriate zero page if the user enabled this via sysfs.
  1908. */
  1909. if (ksm_use_zero_pages && (checksum == zero_checksum)) {
  1910. struct vm_area_struct *vma;
  1911. mmap_read_lock(mm);
  1912. vma = find_mergeable_vma(mm, rmap_item->address);
  1913. if (vma) {
  1914. err = try_to_merge_one_page(vma, page,
  1915. ZERO_PAGE(rmap_item->address));
  1916. } else {
  1917. /*
  1918. * If the vma is out of date, we do not need to
  1919. * continue.
  1920. */
  1921. err = 0;
  1922. }
  1923. mmap_read_unlock(mm);
  1924. /*
  1925. * In case of failure, the page was not really empty, so we
  1926. * need to continue. Otherwise we're done.
  1927. */
  1928. if (!err)
  1929. return;
  1930. }
  1931. tree_rmap_item =
  1932. unstable_tree_search_insert(rmap_item, page, &tree_page);
  1933. if (tree_rmap_item) {
  1934. bool split;
  1935. kpage = try_to_merge_two_pages(rmap_item, page,
  1936. tree_rmap_item, tree_page);
  1937. /*
  1938. * If both pages we tried to merge belong to the same compound
  1939. * page, then we actually ended up increasing the reference
  1940. * count of the same compound page twice, and split_huge_page
  1941. * failed.
  1942. * Here we set a flag if that happened, and we use it later to
  1943. * try split_huge_page again. Since we call put_page right
  1944. * afterwards, the reference count will be correct and
  1945. * split_huge_page should succeed.
  1946. */
  1947. split = PageTransCompound(page)
  1948. && compound_head(page) == compound_head(tree_page);
  1949. put_page(tree_page);
  1950. if (kpage) {
  1951. /*
  1952. * The pages were successfully merged: insert new
  1953. * node in the stable tree and add both rmap_items.
  1954. */
  1955. lock_page(kpage);
  1956. stable_node = stable_tree_insert(kpage);
  1957. if (stable_node) {
  1958. stable_tree_append(tree_rmap_item, stable_node,
  1959. false);
  1960. stable_tree_append(rmap_item, stable_node,
  1961. false);
  1962. }
  1963. unlock_page(kpage);
  1964. /*
  1965. * If we fail to insert the page into the stable tree,
  1966. * we will have 2 virtual addresses that are pointing
  1967. * to a ksm page left outside the stable tree,
  1968. * in which case we need to break_cow on both.
  1969. */
  1970. if (!stable_node) {
  1971. break_cow(tree_rmap_item);
  1972. break_cow(rmap_item);
  1973. }
  1974. } else if (split) {
  1975. /*
  1976. * We are here if we tried to merge two pages and
  1977. * failed because they both belonged to the same
  1978. * compound page. We will split the page now, but no
  1979. * merging will take place.
  1980. * We do not want to add the cost of a full lock; if
  1981. * the page is locked, it is better to skip it and
  1982. * perhaps try again later.
  1983. */
  1984. if (!trylock_page(page))
  1985. return;
  1986. split_huge_page(page);
  1987. unlock_page(page);
  1988. }
  1989. }
  1990. }
  1991. static struct ksm_rmap_item *get_next_rmap_item(struct ksm_mm_slot *mm_slot,
  1992. struct ksm_rmap_item **rmap_list,
  1993. unsigned long addr)
  1994. {
  1995. struct ksm_rmap_item *rmap_item;
  1996. while (*rmap_list) {
  1997. rmap_item = *rmap_list;
  1998. if ((rmap_item->address & PAGE_MASK) == addr)
  1999. return rmap_item;
  2000. if (rmap_item->address > addr)
  2001. break;
  2002. *rmap_list = rmap_item->rmap_list;
  2003. remove_rmap_item_from_tree(rmap_item);
  2004. free_rmap_item(rmap_item);
  2005. }
  2006. rmap_item = alloc_rmap_item();
  2007. if (rmap_item) {
  2008. /* It has already been zeroed */
  2009. rmap_item->mm = mm_slot->slot.mm;
  2010. rmap_item->mm->ksm_rmap_items++;
  2011. rmap_item->address = addr;
  2012. rmap_item->rmap_list = *rmap_list;
  2013. *rmap_list = rmap_item;
  2014. }
  2015. return rmap_item;
  2016. }
  2017. static struct ksm_rmap_item *scan_get_next_rmap_item(struct page **page)
  2018. {
  2019. struct mm_struct *mm;
  2020. struct ksm_mm_slot *mm_slot;
  2021. struct mm_slot *slot;
  2022. struct vm_area_struct *vma;
  2023. struct ksm_rmap_item *rmap_item;
  2024. struct vma_iterator vmi;
  2025. int nid;
  2026. if (list_empty(&ksm_mm_head.slot.mm_node))
  2027. return NULL;
  2028. mm_slot = ksm_scan.mm_slot;
  2029. if (mm_slot == &ksm_mm_head) {
  2030. /*
  2031. * A number of pages can hang around indefinitely on per-cpu
  2032. * pagevecs, raised page count preventing write_protect_page
  2033. * from merging them. Though it doesn't really matter much,
  2034. * it is puzzling to see some stuck in pages_volatile until
  2035. * other activity jostles them out, and they also prevented
  2036. * LTP's KSM test from succeeding deterministically; so drain
  2037. * them here (here rather than on entry to ksm_do_scan(),
  2038. * so we don't IPI too often when pages_to_scan is set low).
  2039. */
  2040. lru_add_drain_all();
  2041. /*
  2042. * Whereas stale stable_nodes on the stable_tree itself
  2043. * get pruned in the regular course of stable_tree_search(),
  2044. * those moved out to the migrate_nodes list can accumulate:
  2045. * so prune them once before each full scan.
  2046. */
  2047. if (!ksm_merge_across_nodes) {
  2048. struct ksm_stable_node *stable_node, *next;
  2049. struct page *page;
  2050. list_for_each_entry_safe(stable_node, next,
  2051. &migrate_nodes, list) {
  2052. page = get_ksm_page(stable_node,
  2053. GET_KSM_PAGE_NOLOCK);
  2054. if (page)
  2055. put_page(page);
  2056. cond_resched();
  2057. }
  2058. }
  2059. for (nid = 0; nid < ksm_nr_node_ids; nid++)
  2060. root_unstable_tree[nid] = RB_ROOT;
  2061. spin_lock(&ksm_mmlist_lock);
  2062. slot = list_entry(mm_slot->slot.mm_node.next,
  2063. struct mm_slot, mm_node);
  2064. mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  2065. ksm_scan.mm_slot = mm_slot;
  2066. spin_unlock(&ksm_mmlist_lock);
  2067. /*
  2068. * Although we tested list_empty() above, a racing __ksm_exit
  2069. * of the last mm on the list may have removed it since then.
  2070. */
  2071. if (mm_slot == &ksm_mm_head)
  2072. return NULL;
  2073. next_mm:
  2074. ksm_scan.address = 0;
  2075. ksm_scan.rmap_list = &mm_slot->rmap_list;
  2076. }
  2077. slot = &mm_slot->slot;
  2078. mm = slot->mm;
  2079. vma_iter_init(&vmi, mm, ksm_scan.address);
  2080. mmap_read_lock(mm);
  2081. if (ksm_test_exit(mm))
  2082. goto no_vmas;
  2083. for_each_vma(vmi, vma) {
  2084. if (!(vma->vm_flags & VM_MERGEABLE))
  2085. continue;
  2086. if (ksm_scan.address < vma->vm_start)
  2087. ksm_scan.address = vma->vm_start;
  2088. if (!vma->anon_vma)
  2089. ksm_scan.address = vma->vm_end;
  2090. while (ksm_scan.address < vma->vm_end) {
  2091. if (ksm_test_exit(mm))
  2092. break;
  2093. *page = follow_page(vma, ksm_scan.address, FOLL_GET);
  2094. if (IS_ERR_OR_NULL(*page)) {
  2095. ksm_scan.address += PAGE_SIZE;
  2096. cond_resched();
  2097. continue;
  2098. }
  2099. if (is_zone_device_page(*page))
  2100. goto next_page;
  2101. if (PageAnon(*page)) {
  2102. flush_anon_page(vma, *page, ksm_scan.address);
  2103. flush_dcache_page(*page);
  2104. rmap_item = get_next_rmap_item(mm_slot,
  2105. ksm_scan.rmap_list, ksm_scan.address);
  2106. if (rmap_item) {
  2107. ksm_scan.rmap_list =
  2108. &rmap_item->rmap_list;
  2109. ksm_scan.address += PAGE_SIZE;
  2110. } else
  2111. put_page(*page);
  2112. mmap_read_unlock(mm);
  2113. return rmap_item;
  2114. }
  2115. next_page:
  2116. put_page(*page);
  2117. ksm_scan.address += PAGE_SIZE;
  2118. cond_resched();
  2119. }
  2120. }
  2121. if (ksm_test_exit(mm)) {
  2122. no_vmas:
  2123. ksm_scan.address = 0;
  2124. ksm_scan.rmap_list = &mm_slot->rmap_list;
  2125. }
  2126. /*
  2127. * Nuke all the rmap_items that are above this current rmap:
  2128. * because there were no VM_MERGEABLE vmas with such addresses.
  2129. */
  2130. remove_trailing_rmap_items(ksm_scan.rmap_list);
  2131. spin_lock(&ksm_mmlist_lock);
  2132. slot = list_entry(mm_slot->slot.mm_node.next,
  2133. struct mm_slot, mm_node);
  2134. ksm_scan.mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  2135. if (ksm_scan.address == 0) {
  2136. /*
  2137. * We've completed a full scan of all vmas, holding mmap_lock
  2138. * throughout, and found no VM_MERGEABLE: so do the same as
  2139. * __ksm_exit does to remove this mm from all our lists now.
  2140. * This applies either when cleaning up after __ksm_exit
  2141. * (but beware: we can reach here even before __ksm_exit),
  2142. * or when all VM_MERGEABLE areas have been unmapped (and
  2143. * mmap_lock then protects against race with MADV_MERGEABLE).
  2144. */
  2145. hash_del(&mm_slot->slot.hash);
  2146. list_del(&mm_slot->slot.mm_node);
  2147. spin_unlock(&ksm_mmlist_lock);
  2148. mm_slot_free(mm_slot_cache, mm_slot);
  2149. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  2150. mmap_read_unlock(mm);
  2151. mmdrop(mm);
  2152. } else {
  2153. mmap_read_unlock(mm);
  2154. /*
  2155. * mmap_read_unlock(mm) first because after
  2156. * spin_unlock(&ksm_mmlist_lock) run, the "mm" may
  2157. * already have been freed under us by __ksm_exit()
  2158. * because the "mm_slot" is still hashed and
  2159. * ksm_scan.mm_slot doesn't point to it anymore.
  2160. */
  2161. spin_unlock(&ksm_mmlist_lock);
  2162. }
  2163. /* Repeat until we've completed scanning the whole list */
  2164. mm_slot = ksm_scan.mm_slot;
  2165. if (mm_slot != &ksm_mm_head)
  2166. goto next_mm;
  2167. ksm_scan.seqnr++;
  2168. return NULL;
  2169. }
  2170. /**
  2171. * ksm_do_scan - the ksm scanner main worker function.
  2172. * @scan_npages: number of pages we want to scan before we return.
  2173. */
  2174. static void ksm_do_scan(unsigned int scan_npages)
  2175. {
  2176. struct ksm_rmap_item *rmap_item;
  2177. struct page *page;
  2178. while (scan_npages-- && likely(!freezing(current))) {
  2179. cond_resched();
  2180. rmap_item = scan_get_next_rmap_item(&page);
  2181. if (!rmap_item)
  2182. return;
  2183. cmp_and_merge_page(page, rmap_item);
  2184. put_page(page);
  2185. }
  2186. }
  2187. static int ksmd_should_run(void)
  2188. {
  2189. return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.slot.mm_node);
  2190. }
  2191. static int ksm_scan_thread(void *nothing)
  2192. {
  2193. unsigned int sleep_ms;
  2194. set_freezable();
  2195. set_user_nice(current, 5);
  2196. while (!kthread_should_stop()) {
  2197. mutex_lock(&ksm_thread_mutex);
  2198. wait_while_offlining();
  2199. if (ksmd_should_run())
  2200. ksm_do_scan(ksm_thread_pages_to_scan);
  2201. mutex_unlock(&ksm_thread_mutex);
  2202. try_to_freeze();
  2203. if (ksmd_should_run()) {
  2204. sleep_ms = READ_ONCE(ksm_thread_sleep_millisecs);
  2205. wait_event_interruptible_timeout(ksm_iter_wait,
  2206. sleep_ms != READ_ONCE(ksm_thread_sleep_millisecs),
  2207. msecs_to_jiffies(sleep_ms));
  2208. } else {
  2209. wait_event_freezable(ksm_thread_wait,
  2210. ksmd_should_run() || kthread_should_stop());
  2211. }
  2212. }
  2213. return 0;
  2214. }
  2215. int ksm_madvise(struct vm_area_struct *vma, unsigned long start,
  2216. unsigned long end, int advice, unsigned long *vm_flags)
  2217. {
  2218. struct mm_struct *mm = vma->vm_mm;
  2219. int err;
  2220. switch (advice) {
  2221. case MADV_MERGEABLE:
  2222. /*
  2223. * Be somewhat over-protective for now!
  2224. */
  2225. if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE |
  2226. VM_PFNMAP | VM_IO | VM_DONTEXPAND |
  2227. VM_HUGETLB | VM_MIXEDMAP))
  2228. return 0; /* just ignore the advice */
  2229. if (vma_is_dax(vma))
  2230. return 0;
  2231. #ifdef VM_SAO
  2232. if (*vm_flags & VM_SAO)
  2233. return 0;
  2234. #endif
  2235. #ifdef VM_SPARC_ADI
  2236. if (*vm_flags & VM_SPARC_ADI)
  2237. return 0;
  2238. #endif
  2239. if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) {
  2240. err = __ksm_enter(mm);
  2241. if (err)
  2242. return err;
  2243. }
  2244. *vm_flags |= VM_MERGEABLE;
  2245. break;
  2246. case MADV_UNMERGEABLE:
  2247. if (!(*vm_flags & VM_MERGEABLE))
  2248. return 0; /* just ignore the advice */
  2249. if (vma->anon_vma) {
  2250. err = unmerge_ksm_pages(vma, start, end, true);
  2251. if (err)
  2252. return err;
  2253. }
  2254. *vm_flags &= ~VM_MERGEABLE;
  2255. break;
  2256. }
  2257. return 0;
  2258. }
  2259. EXPORT_SYMBOL_GPL(ksm_madvise);
  2260. int __ksm_enter(struct mm_struct *mm)
  2261. {
  2262. struct ksm_mm_slot *mm_slot;
  2263. struct mm_slot *slot;
  2264. int needs_wakeup;
  2265. mm_slot = mm_slot_alloc(mm_slot_cache);
  2266. if (!mm_slot)
  2267. return -ENOMEM;
  2268. slot = &mm_slot->slot;
  2269. /* Check ksm_run too? Would need tighter locking */
  2270. needs_wakeup = list_empty(&ksm_mm_head.slot.mm_node);
  2271. spin_lock(&ksm_mmlist_lock);
  2272. mm_slot_insert(mm_slots_hash, mm, slot);
  2273. /*
  2274. * When KSM_RUN_MERGE (or KSM_RUN_STOP),
  2275. * insert just behind the scanning cursor, to let the area settle
  2276. * down a little; when fork is followed by immediate exec, we don't
  2277. * want ksmd to waste time setting up and tearing down an rmap_list.
  2278. *
  2279. * But when KSM_RUN_UNMERGE, it's important to insert ahead of its
  2280. * scanning cursor, otherwise KSM pages in newly forked mms will be
  2281. * missed: then we might as well insert at the end of the list.
  2282. */
  2283. if (ksm_run & KSM_RUN_UNMERGE)
  2284. list_add_tail(&slot->mm_node, &ksm_mm_head.slot.mm_node);
  2285. else
  2286. list_add_tail(&slot->mm_node, &ksm_scan.mm_slot->slot.mm_node);
  2287. spin_unlock(&ksm_mmlist_lock);
  2288. set_bit(MMF_VM_MERGEABLE, &mm->flags);
  2289. mmgrab(mm);
  2290. if (needs_wakeup)
  2291. wake_up_interruptible(&ksm_thread_wait);
  2292. return 0;
  2293. }
  2294. void __ksm_exit(struct mm_struct *mm)
  2295. {
  2296. struct ksm_mm_slot *mm_slot;
  2297. struct mm_slot *slot;
  2298. int easy_to_free = 0;
  2299. /*
  2300. * This process is exiting: if it's straightforward (as is the
  2301. * case when ksmd was never running), free mm_slot immediately.
  2302. * But if it's at the cursor or has rmap_items linked to it, use
  2303. * mmap_lock to synchronize with any break_cows before pagetables
  2304. * are freed, and leave the mm_slot on the list for ksmd to free.
  2305. * Beware: ksm may already have noticed it exiting and freed the slot.
  2306. */
  2307. spin_lock(&ksm_mmlist_lock);
  2308. slot = mm_slot_lookup(mm_slots_hash, mm);
  2309. mm_slot = mm_slot_entry(slot, struct ksm_mm_slot, slot);
  2310. if (mm_slot && ksm_scan.mm_slot != mm_slot) {
  2311. if (!mm_slot->rmap_list) {
  2312. hash_del(&slot->hash);
  2313. list_del(&slot->mm_node);
  2314. easy_to_free = 1;
  2315. } else {
  2316. list_move(&slot->mm_node,
  2317. &ksm_scan.mm_slot->slot.mm_node);
  2318. }
  2319. }
  2320. spin_unlock(&ksm_mmlist_lock);
  2321. if (easy_to_free) {
  2322. mm_slot_free(mm_slot_cache, mm_slot);
  2323. clear_bit(MMF_VM_MERGEABLE, &mm->flags);
  2324. mmdrop(mm);
  2325. } else if (mm_slot) {
  2326. mmap_write_lock(mm);
  2327. mmap_write_unlock(mm);
  2328. }
  2329. }
  2330. struct page *ksm_might_need_to_copy(struct page *page,
  2331. struct vm_area_struct *vma, unsigned long address)
  2332. {
  2333. struct folio *folio = page_folio(page);
  2334. struct anon_vma *anon_vma = folio_anon_vma(folio);
  2335. struct page *new_page;
  2336. if (PageKsm(page)) {
  2337. if (page_stable_node(page) &&
  2338. !(ksm_run & KSM_RUN_UNMERGE))
  2339. return page; /* no need to copy it */
  2340. } else if (!anon_vma) {
  2341. return page; /* no need to copy it */
  2342. } else if (page->index == linear_page_index(vma, address) &&
  2343. anon_vma->root == vma->anon_vma->root) {
  2344. return page; /* still no need to copy it */
  2345. }
  2346. if (!PageUptodate(page))
  2347. return page; /* let do_swap_page report the error */
  2348. new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
  2349. if (new_page &&
  2350. mem_cgroup_charge(page_folio(new_page), vma->vm_mm, GFP_KERNEL)) {
  2351. put_page(new_page);
  2352. new_page = NULL;
  2353. }
  2354. if (new_page) {
  2355. copy_user_highpage(new_page, page, address, vma);
  2356. SetPageDirty(new_page);
  2357. __SetPageUptodate(new_page);
  2358. __SetPageLocked(new_page);
  2359. #ifdef CONFIG_SWAP
  2360. count_vm_event(KSM_SWPIN_COPY);
  2361. #endif
  2362. }
  2363. return new_page;
  2364. }
  2365. void rmap_walk_ksm(struct folio *folio, struct rmap_walk_control *rwc)
  2366. {
  2367. struct ksm_stable_node *stable_node;
  2368. struct ksm_rmap_item *rmap_item;
  2369. int search_new_forks = 0;
  2370. VM_BUG_ON_FOLIO(!folio_test_ksm(folio), folio);
  2371. /*
  2372. * Rely on the page lock to protect against concurrent modifications
  2373. * to that page's node of the stable tree.
  2374. */
  2375. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2376. stable_node = folio_stable_node(folio);
  2377. if (!stable_node)
  2378. return;
  2379. again:
  2380. hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
  2381. struct anon_vma *anon_vma = rmap_item->anon_vma;
  2382. struct anon_vma_chain *vmac;
  2383. struct vm_area_struct *vma;
  2384. cond_resched();
  2385. if (!anon_vma_trylock_read(anon_vma)) {
  2386. if (rwc->try_lock) {
  2387. rwc->contended = true;
  2388. return;
  2389. }
  2390. anon_vma_lock_read(anon_vma);
  2391. }
  2392. anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root,
  2393. 0, ULONG_MAX) {
  2394. unsigned long addr;
  2395. cond_resched();
  2396. vma = vmac->vma;
  2397. /* Ignore the stable/unstable/sqnr flags */
  2398. addr = rmap_item->address & PAGE_MASK;
  2399. if (addr < vma->vm_start || addr >= vma->vm_end)
  2400. continue;
  2401. /*
  2402. * Initially we examine only the vma which covers this
  2403. * rmap_item; but later, if there is still work to do,
  2404. * we examine covering vmas in other mms: in case they
  2405. * were forked from the original since ksmd passed.
  2406. */
  2407. if ((rmap_item->mm == vma->vm_mm) == search_new_forks)
  2408. continue;
  2409. if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
  2410. continue;
  2411. if (!rwc->rmap_one(folio, vma, addr, rwc->arg)) {
  2412. anon_vma_unlock_read(anon_vma);
  2413. return;
  2414. }
  2415. if (rwc->done && rwc->done(folio)) {
  2416. anon_vma_unlock_read(anon_vma);
  2417. return;
  2418. }
  2419. }
  2420. anon_vma_unlock_read(anon_vma);
  2421. }
  2422. if (!search_new_forks++)
  2423. goto again;
  2424. }
  2425. #ifdef CONFIG_MIGRATION
  2426. void folio_migrate_ksm(struct folio *newfolio, struct folio *folio)
  2427. {
  2428. struct ksm_stable_node *stable_node;
  2429. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2430. VM_BUG_ON_FOLIO(!folio_test_locked(newfolio), newfolio);
  2431. VM_BUG_ON_FOLIO(newfolio->mapping != folio->mapping, newfolio);
  2432. stable_node = folio_stable_node(folio);
  2433. if (stable_node) {
  2434. VM_BUG_ON_FOLIO(stable_node->kpfn != folio_pfn(folio), folio);
  2435. stable_node->kpfn = folio_pfn(newfolio);
  2436. /*
  2437. * newfolio->mapping was set in advance; now we need smp_wmb()
  2438. * to make sure that the new stable_node->kpfn is visible
  2439. * to get_ksm_page() before it can see that folio->mapping
  2440. * has gone stale (or that folio_test_swapcache has been cleared).
  2441. */
  2442. smp_wmb();
  2443. set_page_stable_node(&folio->page, NULL);
  2444. }
  2445. }
  2446. #endif /* CONFIG_MIGRATION */
  2447. #ifdef CONFIG_MEMORY_HOTREMOVE
  2448. static void wait_while_offlining(void)
  2449. {
  2450. while (ksm_run & KSM_RUN_OFFLINE) {
  2451. mutex_unlock(&ksm_thread_mutex);
  2452. wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE),
  2453. TASK_UNINTERRUPTIBLE);
  2454. mutex_lock(&ksm_thread_mutex);
  2455. }
  2456. }
  2457. static bool stable_node_dup_remove_range(struct ksm_stable_node *stable_node,
  2458. unsigned long start_pfn,
  2459. unsigned long end_pfn)
  2460. {
  2461. if (stable_node->kpfn >= start_pfn &&
  2462. stable_node->kpfn < end_pfn) {
  2463. /*
  2464. * Don't get_ksm_page, page has already gone:
  2465. * which is why we keep kpfn instead of page*
  2466. */
  2467. remove_node_from_stable_tree(stable_node);
  2468. return true;
  2469. }
  2470. return false;
  2471. }
  2472. static bool stable_node_chain_remove_range(struct ksm_stable_node *stable_node,
  2473. unsigned long start_pfn,
  2474. unsigned long end_pfn,
  2475. struct rb_root *root)
  2476. {
  2477. struct ksm_stable_node *dup;
  2478. struct hlist_node *hlist_safe;
  2479. if (!is_stable_node_chain(stable_node)) {
  2480. VM_BUG_ON(is_stable_node_dup(stable_node));
  2481. return stable_node_dup_remove_range(stable_node, start_pfn,
  2482. end_pfn);
  2483. }
  2484. hlist_for_each_entry_safe(dup, hlist_safe,
  2485. &stable_node->hlist, hlist_dup) {
  2486. VM_BUG_ON(!is_stable_node_dup(dup));
  2487. stable_node_dup_remove_range(dup, start_pfn, end_pfn);
  2488. }
  2489. if (hlist_empty(&stable_node->hlist)) {
  2490. free_stable_node_chain(stable_node, root);
  2491. return true; /* notify caller that tree was rebalanced */
  2492. } else
  2493. return false;
  2494. }
  2495. static void ksm_check_stable_tree(unsigned long start_pfn,
  2496. unsigned long end_pfn)
  2497. {
  2498. struct ksm_stable_node *stable_node, *next;
  2499. struct rb_node *node;
  2500. int nid;
  2501. for (nid = 0; nid < ksm_nr_node_ids; nid++) {
  2502. node = rb_first(root_stable_tree + nid);
  2503. while (node) {
  2504. stable_node = rb_entry(node, struct ksm_stable_node, node);
  2505. if (stable_node_chain_remove_range(stable_node,
  2506. start_pfn, end_pfn,
  2507. root_stable_tree +
  2508. nid))
  2509. node = rb_first(root_stable_tree + nid);
  2510. else
  2511. node = rb_next(node);
  2512. cond_resched();
  2513. }
  2514. }
  2515. list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
  2516. if (stable_node->kpfn >= start_pfn &&
  2517. stable_node->kpfn < end_pfn)
  2518. remove_node_from_stable_tree(stable_node);
  2519. cond_resched();
  2520. }
  2521. }
  2522. static int ksm_memory_callback(struct notifier_block *self,
  2523. unsigned long action, void *arg)
  2524. {
  2525. struct memory_notify *mn = arg;
  2526. switch (action) {
  2527. case MEM_GOING_OFFLINE:
  2528. /*
  2529. * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items()
  2530. * and remove_all_stable_nodes() while memory is going offline:
  2531. * it is unsafe for them to touch the stable tree at this time.
  2532. * But unmerge_ksm_pages(), rmap lookups and other entry points
  2533. * which do not need the ksm_thread_mutex are all safe.
  2534. */
  2535. mutex_lock(&ksm_thread_mutex);
  2536. ksm_run |= KSM_RUN_OFFLINE;
  2537. mutex_unlock(&ksm_thread_mutex);
  2538. break;
  2539. case MEM_OFFLINE:
  2540. /*
  2541. * Most of the work is done by page migration; but there might
  2542. * be a few stable_nodes left over, still pointing to struct
  2543. * pages which have been offlined: prune those from the tree,
  2544. * otherwise get_ksm_page() might later try to access a
  2545. * non-existent struct page.
  2546. */
  2547. ksm_check_stable_tree(mn->start_pfn,
  2548. mn->start_pfn + mn->nr_pages);
  2549. fallthrough;
  2550. case MEM_CANCEL_OFFLINE:
  2551. mutex_lock(&ksm_thread_mutex);
  2552. ksm_run &= ~KSM_RUN_OFFLINE;
  2553. mutex_unlock(&ksm_thread_mutex);
  2554. smp_mb(); /* wake_up_bit advises this */
  2555. wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE));
  2556. break;
  2557. }
  2558. return NOTIFY_OK;
  2559. }
  2560. #else
  2561. static void wait_while_offlining(void)
  2562. {
  2563. }
  2564. #endif /* CONFIG_MEMORY_HOTREMOVE */
  2565. #ifdef CONFIG_SYSFS
  2566. /*
  2567. * This all compiles without CONFIG_SYSFS, but is a waste of space.
  2568. */
  2569. #define KSM_ATTR_RO(_name) \
  2570. static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
  2571. #define KSM_ATTR(_name) \
  2572. static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
  2573. static ssize_t sleep_millisecs_show(struct kobject *kobj,
  2574. struct kobj_attribute *attr, char *buf)
  2575. {
  2576. return sysfs_emit(buf, "%u\n", ksm_thread_sleep_millisecs);
  2577. }
  2578. static ssize_t sleep_millisecs_store(struct kobject *kobj,
  2579. struct kobj_attribute *attr,
  2580. const char *buf, size_t count)
  2581. {
  2582. unsigned int msecs;
  2583. int err;
  2584. err = kstrtouint(buf, 10, &msecs);
  2585. if (err)
  2586. return -EINVAL;
  2587. ksm_thread_sleep_millisecs = msecs;
  2588. wake_up_interruptible(&ksm_iter_wait);
  2589. return count;
  2590. }
  2591. KSM_ATTR(sleep_millisecs);
  2592. static ssize_t pages_to_scan_show(struct kobject *kobj,
  2593. struct kobj_attribute *attr, char *buf)
  2594. {
  2595. return sysfs_emit(buf, "%u\n", ksm_thread_pages_to_scan);
  2596. }
  2597. static ssize_t pages_to_scan_store(struct kobject *kobj,
  2598. struct kobj_attribute *attr,
  2599. const char *buf, size_t count)
  2600. {
  2601. unsigned int nr_pages;
  2602. int err;
  2603. err = kstrtouint(buf, 10, &nr_pages);
  2604. if (err)
  2605. return -EINVAL;
  2606. ksm_thread_pages_to_scan = nr_pages;
  2607. return count;
  2608. }
  2609. KSM_ATTR(pages_to_scan);
  2610. static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr,
  2611. char *buf)
  2612. {
  2613. return sysfs_emit(buf, "%lu\n", ksm_run);
  2614. }
  2615. static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr,
  2616. const char *buf, size_t count)
  2617. {
  2618. unsigned int flags;
  2619. int err;
  2620. err = kstrtouint(buf, 10, &flags);
  2621. if (err)
  2622. return -EINVAL;
  2623. if (flags > KSM_RUN_UNMERGE)
  2624. return -EINVAL;
  2625. /*
  2626. * KSM_RUN_MERGE sets ksmd running, and 0 stops it running.
  2627. * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items,
  2628. * breaking COW to free the pages_shared (but leaves mm_slots
  2629. * on the list for when ksmd may be set running again).
  2630. */
  2631. mutex_lock(&ksm_thread_mutex);
  2632. wait_while_offlining();
  2633. if (ksm_run != flags) {
  2634. ksm_run = flags;
  2635. if (flags & KSM_RUN_UNMERGE) {
  2636. set_current_oom_origin();
  2637. err = unmerge_and_remove_all_rmap_items();
  2638. clear_current_oom_origin();
  2639. if (err) {
  2640. ksm_run = KSM_RUN_STOP;
  2641. count = err;
  2642. }
  2643. }
  2644. }
  2645. mutex_unlock(&ksm_thread_mutex);
  2646. if (flags & KSM_RUN_MERGE)
  2647. wake_up_interruptible(&ksm_thread_wait);
  2648. return count;
  2649. }
  2650. KSM_ATTR(run);
  2651. #ifdef CONFIG_NUMA
  2652. static ssize_t merge_across_nodes_show(struct kobject *kobj,
  2653. struct kobj_attribute *attr, char *buf)
  2654. {
  2655. return sysfs_emit(buf, "%u\n", ksm_merge_across_nodes);
  2656. }
  2657. static ssize_t merge_across_nodes_store(struct kobject *kobj,
  2658. struct kobj_attribute *attr,
  2659. const char *buf, size_t count)
  2660. {
  2661. int err;
  2662. unsigned long knob;
  2663. err = kstrtoul(buf, 10, &knob);
  2664. if (err)
  2665. return err;
  2666. if (knob > 1)
  2667. return -EINVAL;
  2668. mutex_lock(&ksm_thread_mutex);
  2669. wait_while_offlining();
  2670. if (ksm_merge_across_nodes != knob) {
  2671. if (ksm_pages_shared || remove_all_stable_nodes())
  2672. err = -EBUSY;
  2673. else if (root_stable_tree == one_stable_tree) {
  2674. struct rb_root *buf;
  2675. /*
  2676. * This is the first time that we switch away from the
  2677. * default of merging across nodes: must now allocate
  2678. * a buffer to hold as many roots as may be needed.
  2679. * Allocate stable and unstable together:
  2680. * MAXSMP NODES_SHIFT 10 will use 16kB.
  2681. */
  2682. buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf),
  2683. GFP_KERNEL);
  2684. /* Let us assume that RB_ROOT is NULL is zero */
  2685. if (!buf)
  2686. err = -ENOMEM;
  2687. else {
  2688. root_stable_tree = buf;
  2689. root_unstable_tree = buf + nr_node_ids;
  2690. /* Stable tree is empty but not the unstable */
  2691. root_unstable_tree[0] = one_unstable_tree[0];
  2692. }
  2693. }
  2694. if (!err) {
  2695. ksm_merge_across_nodes = knob;
  2696. ksm_nr_node_ids = knob ? 1 : nr_node_ids;
  2697. }
  2698. }
  2699. mutex_unlock(&ksm_thread_mutex);
  2700. return err ? err : count;
  2701. }
  2702. KSM_ATTR(merge_across_nodes);
  2703. #endif
  2704. static ssize_t use_zero_pages_show(struct kobject *kobj,
  2705. struct kobj_attribute *attr, char *buf)
  2706. {
  2707. return sysfs_emit(buf, "%u\n", ksm_use_zero_pages);
  2708. }
  2709. static ssize_t use_zero_pages_store(struct kobject *kobj,
  2710. struct kobj_attribute *attr,
  2711. const char *buf, size_t count)
  2712. {
  2713. int err;
  2714. bool value;
  2715. err = kstrtobool(buf, &value);
  2716. if (err)
  2717. return -EINVAL;
  2718. ksm_use_zero_pages = value;
  2719. return count;
  2720. }
  2721. KSM_ATTR(use_zero_pages);
  2722. static ssize_t max_page_sharing_show(struct kobject *kobj,
  2723. struct kobj_attribute *attr, char *buf)
  2724. {
  2725. return sysfs_emit(buf, "%u\n", ksm_max_page_sharing);
  2726. }
  2727. static ssize_t max_page_sharing_store(struct kobject *kobj,
  2728. struct kobj_attribute *attr,
  2729. const char *buf, size_t count)
  2730. {
  2731. int err;
  2732. int knob;
  2733. err = kstrtoint(buf, 10, &knob);
  2734. if (err)
  2735. return err;
  2736. /*
  2737. * When a KSM page is created it is shared by 2 mappings. This
  2738. * being a signed comparison, it implicitly verifies it's not
  2739. * negative.
  2740. */
  2741. if (knob < 2)
  2742. return -EINVAL;
  2743. if (READ_ONCE(ksm_max_page_sharing) == knob)
  2744. return count;
  2745. mutex_lock(&ksm_thread_mutex);
  2746. wait_while_offlining();
  2747. if (ksm_max_page_sharing != knob) {
  2748. if (ksm_pages_shared || remove_all_stable_nodes())
  2749. err = -EBUSY;
  2750. else
  2751. ksm_max_page_sharing = knob;
  2752. }
  2753. mutex_unlock(&ksm_thread_mutex);
  2754. return err ? err : count;
  2755. }
  2756. KSM_ATTR(max_page_sharing);
  2757. static ssize_t pages_shared_show(struct kobject *kobj,
  2758. struct kobj_attribute *attr, char *buf)
  2759. {
  2760. return sysfs_emit(buf, "%lu\n", ksm_pages_shared);
  2761. }
  2762. KSM_ATTR_RO(pages_shared);
  2763. static ssize_t pages_sharing_show(struct kobject *kobj,
  2764. struct kobj_attribute *attr, char *buf)
  2765. {
  2766. return sysfs_emit(buf, "%lu\n", ksm_pages_sharing);
  2767. }
  2768. KSM_ATTR_RO(pages_sharing);
  2769. static ssize_t pages_unshared_show(struct kobject *kobj,
  2770. struct kobj_attribute *attr, char *buf)
  2771. {
  2772. return sysfs_emit(buf, "%lu\n", ksm_pages_unshared);
  2773. }
  2774. KSM_ATTR_RO(pages_unshared);
  2775. static ssize_t pages_volatile_show(struct kobject *kobj,
  2776. struct kobj_attribute *attr, char *buf)
  2777. {
  2778. long ksm_pages_volatile;
  2779. ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared
  2780. - ksm_pages_sharing - ksm_pages_unshared;
  2781. /*
  2782. * It was not worth any locking to calculate that statistic,
  2783. * but it might therefore sometimes be negative: conceal that.
  2784. */
  2785. if (ksm_pages_volatile < 0)
  2786. ksm_pages_volatile = 0;
  2787. return sysfs_emit(buf, "%ld\n", ksm_pages_volatile);
  2788. }
  2789. KSM_ATTR_RO(pages_volatile);
  2790. static ssize_t stable_node_dups_show(struct kobject *kobj,
  2791. struct kobj_attribute *attr, char *buf)
  2792. {
  2793. return sysfs_emit(buf, "%lu\n", ksm_stable_node_dups);
  2794. }
  2795. KSM_ATTR_RO(stable_node_dups);
  2796. static ssize_t stable_node_chains_show(struct kobject *kobj,
  2797. struct kobj_attribute *attr, char *buf)
  2798. {
  2799. return sysfs_emit(buf, "%lu\n", ksm_stable_node_chains);
  2800. }
  2801. KSM_ATTR_RO(stable_node_chains);
  2802. static ssize_t
  2803. stable_node_chains_prune_millisecs_show(struct kobject *kobj,
  2804. struct kobj_attribute *attr,
  2805. char *buf)
  2806. {
  2807. return sysfs_emit(buf, "%u\n", ksm_stable_node_chains_prune_millisecs);
  2808. }
  2809. static ssize_t
  2810. stable_node_chains_prune_millisecs_store(struct kobject *kobj,
  2811. struct kobj_attribute *attr,
  2812. const char *buf, size_t count)
  2813. {
  2814. unsigned int msecs;
  2815. int err;
  2816. err = kstrtouint(buf, 10, &msecs);
  2817. if (err)
  2818. return -EINVAL;
  2819. ksm_stable_node_chains_prune_millisecs = msecs;
  2820. return count;
  2821. }
  2822. KSM_ATTR(stable_node_chains_prune_millisecs);
  2823. static ssize_t full_scans_show(struct kobject *kobj,
  2824. struct kobj_attribute *attr, char *buf)
  2825. {
  2826. return sysfs_emit(buf, "%lu\n", ksm_scan.seqnr);
  2827. }
  2828. KSM_ATTR_RO(full_scans);
  2829. static struct attribute *ksm_attrs[] = {
  2830. &sleep_millisecs_attr.attr,
  2831. &pages_to_scan_attr.attr,
  2832. &run_attr.attr,
  2833. &pages_shared_attr.attr,
  2834. &pages_sharing_attr.attr,
  2835. &pages_unshared_attr.attr,
  2836. &pages_volatile_attr.attr,
  2837. &full_scans_attr.attr,
  2838. #ifdef CONFIG_NUMA
  2839. &merge_across_nodes_attr.attr,
  2840. #endif
  2841. &max_page_sharing_attr.attr,
  2842. &stable_node_chains_attr.attr,
  2843. &stable_node_dups_attr.attr,
  2844. &stable_node_chains_prune_millisecs_attr.attr,
  2845. &use_zero_pages_attr.attr,
  2846. NULL,
  2847. };
  2848. static const struct attribute_group ksm_attr_group = {
  2849. .attrs = ksm_attrs,
  2850. .name = "ksm",
  2851. };
  2852. #endif /* CONFIG_SYSFS */
  2853. static int __init ksm_init(void)
  2854. {
  2855. struct task_struct *ksm_thread;
  2856. int err;
  2857. /* The correct value depends on page size and endianness */
  2858. zero_checksum = calc_checksum(ZERO_PAGE(0));
  2859. /* Default to false for backwards compatibility */
  2860. ksm_use_zero_pages = false;
  2861. err = ksm_slab_init();
  2862. if (err)
  2863. goto out;
  2864. ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd");
  2865. if (IS_ERR(ksm_thread)) {
  2866. pr_err("ksm: creating kthread failed\n");
  2867. err = PTR_ERR(ksm_thread);
  2868. goto out_free;
  2869. }
  2870. #ifdef CONFIG_SYSFS
  2871. err = sysfs_create_group(mm_kobj, &ksm_attr_group);
  2872. if (err) {
  2873. pr_err("ksm: register sysfs failed\n");
  2874. kthread_stop(ksm_thread);
  2875. goto out_free;
  2876. }
  2877. #else
  2878. ksm_run = KSM_RUN_MERGE; /* no way for user to start it */
  2879. #endif /* CONFIG_SYSFS */
  2880. #ifdef CONFIG_MEMORY_HOTREMOVE
  2881. /* There is no significance to this priority 100 */
  2882. hotplug_memory_notifier(ksm_memory_callback, 100);
  2883. #endif
  2884. return 0;
  2885. out_free:
  2886. ksm_slab_free();
  2887. out:
  2888. return err;
  2889. }
  2890. subsys_initcall(ksm_init);