vmscan.c 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831
  1. /*
  2. * linux/mm/vmscan.c
  3. *
  4. * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
  5. *
  6. * Swap reorganised 29.12.95, Stephen Tweedie.
  7. * kswapd added: 7.1.96 sct
  8. * Removed kswapd_ctl limits, and swap out as many pages as needed
  9. * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
  10. * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
  11. * Multiqueue VM started 5.8.00, Rik van Riel.
  12. */
  13. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  14. #include <linux/mm.h>
  15. #include <linux/module.h>
  16. #include <linux/gfp.h>
  17. #include <linux/kernel_stat.h>
  18. #include <linux/swap.h>
  19. #include <linux/pagemap.h>
  20. #include <linux/init.h>
  21. #include <linux/highmem.h>
  22. #include <linux/vmpressure.h>
  23. #include <linux/vmstat.h>
  24. #include <linux/file.h>
  25. #include <linux/writeback.h>
  26. #include <linux/blkdev.h>
  27. #include <linux/buffer_head.h> /* for try_to_release_page(),
  28. buffer_heads_over_limit */
  29. #include <linux/mm_inline.h>
  30. #include <linux/backing-dev.h>
  31. #include <linux/rmap.h>
  32. #include <linux/topology.h>
  33. #include <linux/cpu.h>
  34. #include <linux/cpuset.h>
  35. #include <linux/compaction.h>
  36. #include <linux/notifier.h>
  37. #include <linux/rwsem.h>
  38. #include <linux/delay.h>
  39. #include <linux/kthread.h>
  40. #include <linux/freezer.h>
  41. #include <linux/memcontrol.h>
  42. #include <linux/delayacct.h>
  43. #include <linux/sysctl.h>
  44. #include <linux/oom.h>
  45. #include <linux/prefetch.h>
  46. #include <linux/printk.h>
  47. #include <linux/dax.h>
  48. #include <asm/tlbflush.h>
  49. #include <asm/div64.h>
  50. #include <linux/swapops.h>
  51. #include <linux/balloon_compaction.h>
  52. #include "internal.h"
  53. #define CREATE_TRACE_POINTS
  54. #include <trace/events/vmscan.h>
  55. struct scan_control {
  56. /* How many pages shrink_list() should reclaim */
  57. unsigned long nr_to_reclaim;
  58. /* This context's GFP mask */
  59. gfp_t gfp_mask;
  60. /* Allocation order */
  61. int order;
  62. /*
  63. * Nodemask of nodes allowed by the caller. If NULL, all nodes
  64. * are scanned.
  65. */
  66. nodemask_t *nodemask;
  67. /*
  68. * The memory cgroup that hit its limit and as a result is the
  69. * primary target of this reclaim invocation.
  70. */
  71. struct mem_cgroup *target_mem_cgroup;
  72. /* Scan (total_size >> priority) pages at once */
  73. int priority;
  74. unsigned int may_writepage:1;
  75. /* Can mapped pages be reclaimed? */
  76. unsigned int may_unmap:1;
  77. /* Can pages be swapped as part of reclaim? */
  78. unsigned int may_swap:1;
  79. /* Can cgroups be reclaimed below their normal consumption range? */
  80. unsigned int may_thrash:1;
  81. unsigned int hibernation_mode:1;
  82. /* One of the zones is ready for compaction */
  83. unsigned int compaction_ready:1;
  84. /* Incremented by the number of inactive pages that were scanned */
  85. unsigned long nr_scanned;
  86. /* Number of pages freed so far during a call to shrink_zones() */
  87. unsigned long nr_reclaimed;
  88. };
  89. #ifdef ARCH_HAS_PREFETCH
  90. #define prefetch_prev_lru_page(_page, _base, _field) \
  91. do { \
  92. if ((_page)->lru.prev != _base) { \
  93. struct page *prev; \
  94. \
  95. prev = lru_to_page(&(_page->lru)); \
  96. prefetch(&prev->_field); \
  97. } \
  98. } while (0)
  99. #else
  100. #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
  101. #endif
  102. #ifdef ARCH_HAS_PREFETCHW
  103. #define prefetchw_prev_lru_page(_page, _base, _field) \
  104. do { \
  105. if ((_page)->lru.prev != _base) { \
  106. struct page *prev; \
  107. \
  108. prev = lru_to_page(&(_page->lru)); \
  109. prefetchw(&prev->_field); \
  110. } \
  111. } while (0)
  112. #else
  113. #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
  114. #endif
  115. /*
  116. * From 0 .. 100. Higher means more swappy.
  117. */
  118. int vm_swappiness = 60;
  119. /*
  120. * The total number of pages which are beyond the high watermark within all
  121. * zones.
  122. */
  123. unsigned long vm_total_pages;
  124. static LIST_HEAD(shrinker_list);
  125. static DECLARE_RWSEM(shrinker_rwsem);
  126. #ifdef CONFIG_MEMCG
  127. static bool global_reclaim(struct scan_control *sc)
  128. {
  129. return !sc->target_mem_cgroup;
  130. }
  131. /**
  132. * sane_reclaim - is the usual dirty throttling mechanism operational?
  133. * @sc: scan_control in question
  134. *
  135. * The normal page dirty throttling mechanism in balance_dirty_pages() is
  136. * completely broken with the legacy memcg and direct stalling in
  137. * shrink_page_list() is used for throttling instead, which lacks all the
  138. * niceties such as fairness, adaptive pausing, bandwidth proportional
  139. * allocation and configurability.
  140. *
  141. * This function tests whether the vmscan currently in progress can assume
  142. * that the normal dirty throttling mechanism is operational.
  143. */
  144. static bool sane_reclaim(struct scan_control *sc)
  145. {
  146. struct mem_cgroup *memcg = sc->target_mem_cgroup;
  147. if (!memcg)
  148. return true;
  149. #ifdef CONFIG_CGROUP_WRITEBACK
  150. if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
  151. return true;
  152. #endif
  153. return false;
  154. }
  155. #else
  156. static bool global_reclaim(struct scan_control *sc)
  157. {
  158. return true;
  159. }
  160. static bool sane_reclaim(struct scan_control *sc)
  161. {
  162. return true;
  163. }
  164. #endif
  165. static unsigned long zone_reclaimable_pages(struct zone *zone)
  166. {
  167. unsigned long nr;
  168. nr = zone_page_state_snapshot(zone, NR_ACTIVE_FILE) +
  169. zone_page_state_snapshot(zone, NR_INACTIVE_FILE) +
  170. zone_page_state_snapshot(zone, NR_ISOLATED_FILE);
  171. if (get_nr_swap_pages() > 0)
  172. nr += zone_page_state_snapshot(zone, NR_ACTIVE_ANON) +
  173. zone_page_state_snapshot(zone, NR_INACTIVE_ANON) +
  174. zone_page_state_snapshot(zone, NR_ISOLATED_ANON);
  175. return nr;
  176. }
  177. bool zone_reclaimable(struct zone *zone)
  178. {
  179. return zone_page_state_snapshot(zone, NR_PAGES_SCANNED) <
  180. zone_reclaimable_pages(zone) * 6;
  181. }
  182. unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru)
  183. {
  184. if (!mem_cgroup_disabled())
  185. return mem_cgroup_get_lru_size(lruvec, lru);
  186. return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
  187. }
  188. /*
  189. * Add a shrinker callback to be called from the vm.
  190. */
  191. int register_shrinker(struct shrinker *shrinker)
  192. {
  193. size_t size = sizeof(*shrinker->nr_deferred);
  194. if (shrinker->flags & SHRINKER_NUMA_AWARE)
  195. size *= nr_node_ids;
  196. shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
  197. if (!shrinker->nr_deferred)
  198. return -ENOMEM;
  199. down_write(&shrinker_rwsem);
  200. list_add_tail(&shrinker->list, &shrinker_list);
  201. up_write(&shrinker_rwsem);
  202. return 0;
  203. }
  204. EXPORT_SYMBOL(register_shrinker);
  205. /*
  206. * Remove one
  207. */
  208. void unregister_shrinker(struct shrinker *shrinker)
  209. {
  210. down_write(&shrinker_rwsem);
  211. list_del(&shrinker->list);
  212. up_write(&shrinker_rwsem);
  213. kfree(shrinker->nr_deferred);
  214. }
  215. EXPORT_SYMBOL(unregister_shrinker);
  216. #define SHRINK_BATCH 128
  217. static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
  218. struct shrinker *shrinker,
  219. unsigned long nr_scanned,
  220. unsigned long nr_eligible)
  221. {
  222. unsigned long freed = 0;
  223. unsigned long long delta;
  224. long total_scan;
  225. long freeable;
  226. long nr;
  227. long new_nr;
  228. int nid = shrinkctl->nid;
  229. long batch_size = shrinker->batch ? shrinker->batch
  230. : SHRINK_BATCH;
  231. freeable = shrinker->count_objects(shrinker, shrinkctl);
  232. if (freeable == 0)
  233. return 0;
  234. /*
  235. * copy the current shrinker scan count into a local variable
  236. * and zero it so that other concurrent shrinker invocations
  237. * don't also do this scanning work.
  238. */
  239. nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
  240. total_scan = nr;
  241. delta = (4 * nr_scanned) / shrinker->seeks;
  242. delta *= freeable;
  243. do_div(delta, nr_eligible + 1);
  244. total_scan += delta;
  245. if (total_scan < 0) {
  246. pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
  247. shrinker->scan_objects, total_scan);
  248. total_scan = freeable;
  249. }
  250. /*
  251. * We need to avoid excessive windup on filesystem shrinkers
  252. * due to large numbers of GFP_NOFS allocations causing the
  253. * shrinkers to return -1 all the time. This results in a large
  254. * nr being built up so when a shrink that can do some work
  255. * comes along it empties the entire cache due to nr >>>
  256. * freeable. This is bad for sustaining a working set in
  257. * memory.
  258. *
  259. * Hence only allow the shrinker to scan the entire cache when
  260. * a large delta change is calculated directly.
  261. */
  262. if (delta < freeable / 4)
  263. total_scan = min(total_scan, freeable / 2);
  264. /*
  265. * Avoid risking looping forever due to too large nr value:
  266. * never try to free more than twice the estimate number of
  267. * freeable entries.
  268. */
  269. if (total_scan > freeable * 2)
  270. total_scan = freeable * 2;
  271. trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
  272. nr_scanned, nr_eligible,
  273. freeable, delta, total_scan);
  274. /*
  275. * Normally, we should not scan less than batch_size objects in one
  276. * pass to avoid too frequent shrinker calls, but if the slab has less
  277. * than batch_size objects in total and we are really tight on memory,
  278. * we will try to reclaim all available objects, otherwise we can end
  279. * up failing allocations although there are plenty of reclaimable
  280. * objects spread over several slabs with usage less than the
  281. * batch_size.
  282. *
  283. * We detect the "tight on memory" situations by looking at the total
  284. * number of objects we want to scan (total_scan). If it is greater
  285. * than the total number of objects on slab (freeable), we must be
  286. * scanning at high prio and therefore should try to reclaim as much as
  287. * possible.
  288. */
  289. while (total_scan >= batch_size ||
  290. total_scan >= freeable) {
  291. unsigned long ret;
  292. unsigned long nr_to_scan = min(batch_size, total_scan);
  293. shrinkctl->nr_to_scan = nr_to_scan;
  294. ret = shrinker->scan_objects(shrinker, shrinkctl);
  295. if (ret == SHRINK_STOP)
  296. break;
  297. freed += ret;
  298. count_vm_events(SLABS_SCANNED, nr_to_scan);
  299. total_scan -= nr_to_scan;
  300. cond_resched();
  301. }
  302. /*
  303. * move the unused scan count back into the shrinker in a
  304. * manner that handles concurrent updates. If we exhausted the
  305. * scan, there is no need to do an update.
  306. */
  307. if (total_scan > 0)
  308. new_nr = atomic_long_add_return(total_scan,
  309. &shrinker->nr_deferred[nid]);
  310. else
  311. new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
  312. trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
  313. return freed;
  314. }
  315. /**
  316. * shrink_slab - shrink slab caches
  317. * @gfp_mask: allocation context
  318. * @nid: node whose slab caches to target
  319. * @memcg: memory cgroup whose slab caches to target
  320. * @nr_scanned: pressure numerator
  321. * @nr_eligible: pressure denominator
  322. *
  323. * Call the shrink functions to age shrinkable caches.
  324. *
  325. * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
  326. * unaware shrinkers will receive a node id of 0 instead.
  327. *
  328. * @memcg specifies the memory cgroup to target. If it is not NULL,
  329. * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
  330. * objects from the memory cgroup specified. Otherwise, only unaware
  331. * shrinkers are called.
  332. *
  333. * @nr_scanned and @nr_eligible form a ratio that indicate how much of
  334. * the available objects should be scanned. Page reclaim for example
  335. * passes the number of pages scanned and the number of pages on the
  336. * LRU lists that it considered on @nid, plus a bias in @nr_scanned
  337. * when it encountered mapped pages. The ratio is further biased by
  338. * the ->seeks setting of the shrink function, which indicates the
  339. * cost to recreate an object relative to that of an LRU page.
  340. *
  341. * Returns the number of reclaimed slab objects.
  342. */
  343. static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
  344. struct mem_cgroup *memcg,
  345. unsigned long nr_scanned,
  346. unsigned long nr_eligible)
  347. {
  348. struct shrinker *shrinker;
  349. unsigned long freed = 0;
  350. if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
  351. return 0;
  352. if (nr_scanned == 0)
  353. nr_scanned = SWAP_CLUSTER_MAX;
  354. if (!down_read_trylock(&shrinker_rwsem)) {
  355. /*
  356. * If we would return 0, our callers would understand that we
  357. * have nothing else to shrink and give up trying. By returning
  358. * 1 we keep it going and assume we'll be able to shrink next
  359. * time.
  360. */
  361. freed = 1;
  362. goto out;
  363. }
  364. list_for_each_entry(shrinker, &shrinker_list, list) {
  365. struct shrink_control sc = {
  366. .gfp_mask = gfp_mask,
  367. .nid = nid,
  368. .memcg = memcg,
  369. };
  370. /*
  371. * If kernel memory accounting is disabled, we ignore
  372. * SHRINKER_MEMCG_AWARE flag and call all shrinkers
  373. * passing NULL for memcg.
  374. */
  375. if (memcg_kmem_enabled() &&
  376. !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
  377. continue;
  378. if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
  379. sc.nid = 0;
  380. freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
  381. }
  382. up_read(&shrinker_rwsem);
  383. out:
  384. cond_resched();
  385. return freed;
  386. }
  387. void drop_slab_node(int nid)
  388. {
  389. unsigned long freed;
  390. do {
  391. struct mem_cgroup *memcg = NULL;
  392. freed = 0;
  393. do {
  394. freed += shrink_slab(GFP_KERNEL, nid, memcg,
  395. 1000, 1000);
  396. } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
  397. } while (freed > 10);
  398. }
  399. void drop_slab(void)
  400. {
  401. int nid;
  402. for_each_online_node(nid)
  403. drop_slab_node(nid);
  404. }
  405. static inline int is_page_cache_freeable(struct page *page)
  406. {
  407. /*
  408. * A freeable page cache page is referenced only by the caller
  409. * that isolated the page, the page cache radix tree and
  410. * optional buffer heads at page->private.
  411. */
  412. return page_count(page) - page_has_private(page) == 2;
  413. }
  414. static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
  415. {
  416. if (current->flags & PF_SWAPWRITE)
  417. return 1;
  418. if (!inode_write_congested(inode))
  419. return 1;
  420. if (inode_to_bdi(inode) == current->backing_dev_info)
  421. return 1;
  422. return 0;
  423. }
  424. /*
  425. * We detected a synchronous write error writing a page out. Probably
  426. * -ENOSPC. We need to propagate that into the address_space for a subsequent
  427. * fsync(), msync() or close().
  428. *
  429. * The tricky part is that after writepage we cannot touch the mapping: nothing
  430. * prevents it from being freed up. But we have a ref on the page and once
  431. * that page is locked, the mapping is pinned.
  432. *
  433. * We're allowed to run sleeping lock_page() here because we know the caller has
  434. * __GFP_FS.
  435. */
  436. static void handle_write_error(struct address_space *mapping,
  437. struct page *page, int error)
  438. {
  439. lock_page(page);
  440. if (page_mapping(page) == mapping)
  441. mapping_set_error(mapping, error);
  442. unlock_page(page);
  443. }
  444. /* possible outcome of pageout() */
  445. typedef enum {
  446. /* failed to write page out, page is locked */
  447. PAGE_KEEP,
  448. /* move page to the active list, page is locked */
  449. PAGE_ACTIVATE,
  450. /* page has been sent to the disk successfully, page is unlocked */
  451. PAGE_SUCCESS,
  452. /* page is clean and locked */
  453. PAGE_CLEAN,
  454. } pageout_t;
  455. /*
  456. * pageout is called by shrink_page_list() for each dirty page.
  457. * Calls ->writepage().
  458. */
  459. static pageout_t pageout(struct page *page, struct address_space *mapping,
  460. struct scan_control *sc)
  461. {
  462. /*
  463. * If the page is dirty, only perform writeback if that write
  464. * will be non-blocking. To prevent this allocation from being
  465. * stalled by pagecache activity. But note that there may be
  466. * stalls if we need to run get_block(). We could test
  467. * PagePrivate for that.
  468. *
  469. * If this process is currently in __generic_file_write_iter() against
  470. * this page's queue, we can perform writeback even if that
  471. * will block.
  472. *
  473. * If the page is swapcache, write it back even if that would
  474. * block, for some throttling. This happens by accident, because
  475. * swap_backing_dev_info is bust: it doesn't reflect the
  476. * congestion state of the swapdevs. Easy to fix, if needed.
  477. */
  478. if (!is_page_cache_freeable(page))
  479. return PAGE_KEEP;
  480. if (!mapping) {
  481. /*
  482. * Some data journaling orphaned pages can have
  483. * page->mapping == NULL while being dirty with clean buffers.
  484. */
  485. if (page_has_private(page)) {
  486. if (try_to_free_buffers(page)) {
  487. ClearPageDirty(page);
  488. pr_info("%s: orphaned page\n", __func__);
  489. return PAGE_CLEAN;
  490. }
  491. }
  492. return PAGE_KEEP;
  493. }
  494. if (mapping->a_ops->writepage == NULL)
  495. return PAGE_ACTIVATE;
  496. if (!may_write_to_inode(mapping->host, sc))
  497. return PAGE_KEEP;
  498. if (clear_page_dirty_for_io(page)) {
  499. int res;
  500. struct writeback_control wbc = {
  501. .sync_mode = WB_SYNC_NONE,
  502. .nr_to_write = SWAP_CLUSTER_MAX,
  503. .range_start = 0,
  504. .range_end = LLONG_MAX,
  505. .for_reclaim = 1,
  506. };
  507. SetPageReclaim(page);
  508. res = mapping->a_ops->writepage(page, &wbc);
  509. if (res < 0)
  510. handle_write_error(mapping, page, res);
  511. if (res == AOP_WRITEPAGE_ACTIVATE) {
  512. ClearPageReclaim(page);
  513. return PAGE_ACTIVATE;
  514. }
  515. if (!PageWriteback(page)) {
  516. /* synchronous write or broken a_ops? */
  517. ClearPageReclaim(page);
  518. }
  519. trace_mm_vmscan_writepage(page);
  520. inc_zone_page_state(page, NR_VMSCAN_WRITE);
  521. return PAGE_SUCCESS;
  522. }
  523. return PAGE_CLEAN;
  524. }
  525. /*
  526. * Same as remove_mapping, but if the page is removed from the mapping, it
  527. * gets returned with a refcount of 0.
  528. */
  529. static int __remove_mapping(struct address_space *mapping, struct page *page,
  530. bool reclaimed)
  531. {
  532. unsigned long flags;
  533. BUG_ON(!PageLocked(page));
  534. BUG_ON(mapping != page_mapping(page));
  535. spin_lock_irqsave(&mapping->tree_lock, flags);
  536. /*
  537. * The non racy check for a busy page.
  538. *
  539. * Must be careful with the order of the tests. When someone has
  540. * a ref to the page, it may be possible that they dirty it then
  541. * drop the reference. So if PageDirty is tested before page_count
  542. * here, then the following race may occur:
  543. *
  544. * get_user_pages(&page);
  545. * [user mapping goes away]
  546. * write_to(page);
  547. * !PageDirty(page) [good]
  548. * SetPageDirty(page);
  549. * put_page(page);
  550. * !page_count(page) [good, discard it]
  551. *
  552. * [oops, our write_to data is lost]
  553. *
  554. * Reversing the order of the tests ensures such a situation cannot
  555. * escape unnoticed. The smp_rmb is needed to ensure the page->flags
  556. * load is not satisfied before that of page->_refcount.
  557. *
  558. * Note that if SetPageDirty is always performed via set_page_dirty,
  559. * and thus under tree_lock, then this ordering is not required.
  560. */
  561. if (!page_ref_freeze(page, 2))
  562. goto cannot_free;
  563. /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
  564. if (unlikely(PageDirty(page))) {
  565. page_ref_unfreeze(page, 2);
  566. goto cannot_free;
  567. }
  568. if (PageSwapCache(page)) {
  569. swp_entry_t swap = { .val = page_private(page) };
  570. mem_cgroup_swapout(page, swap);
  571. __delete_from_swap_cache(page);
  572. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  573. swapcache_free(swap);
  574. } else {
  575. void (*freepage)(struct page *);
  576. void *shadow = NULL;
  577. freepage = mapping->a_ops->freepage;
  578. /*
  579. * Remember a shadow entry for reclaimed file cache in
  580. * order to detect refaults, thus thrashing, later on.
  581. *
  582. * But don't store shadows in an address space that is
  583. * already exiting. This is not just an optizimation,
  584. * inode reclaim needs to empty out the radix tree or
  585. * the nodes are lost. Don't plant shadows behind its
  586. * back.
  587. *
  588. * We also don't store shadows for DAX mappings because the
  589. * only page cache pages found in these are zero pages
  590. * covering holes, and because we don't want to mix DAX
  591. * exceptional entries and shadow exceptional entries in the
  592. * same page_tree.
  593. */
  594. if (reclaimed && page_is_file_cache(page) &&
  595. !mapping_exiting(mapping) && !dax_mapping(mapping))
  596. shadow = workingset_eviction(mapping, page);
  597. __delete_from_page_cache(page, shadow);
  598. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  599. if (freepage != NULL)
  600. freepage(page);
  601. }
  602. return 1;
  603. cannot_free:
  604. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  605. return 0;
  606. }
  607. /*
  608. * Attempt to detach a locked page from its ->mapping. If it is dirty or if
  609. * someone else has a ref on the page, abort and return 0. If it was
  610. * successfully detached, return 1. Assumes the caller has a single ref on
  611. * this page.
  612. */
  613. int remove_mapping(struct address_space *mapping, struct page *page)
  614. {
  615. if (__remove_mapping(mapping, page, false)) {
  616. /*
  617. * Unfreezing the refcount with 1 rather than 2 effectively
  618. * drops the pagecache ref for us without requiring another
  619. * atomic operation.
  620. */
  621. page_ref_unfreeze(page, 1);
  622. return 1;
  623. }
  624. return 0;
  625. }
  626. /**
  627. * putback_lru_page - put previously isolated page onto appropriate LRU list
  628. * @page: page to be put back to appropriate lru list
  629. *
  630. * Add previously isolated @page to appropriate LRU list.
  631. * Page may still be unevictable for other reasons.
  632. *
  633. * lru_lock must not be held, interrupts must be enabled.
  634. */
  635. void putback_lru_page(struct page *page)
  636. {
  637. bool is_unevictable;
  638. int was_unevictable = PageUnevictable(page);
  639. VM_BUG_ON_PAGE(PageLRU(page), page);
  640. redo:
  641. ClearPageUnevictable(page);
  642. if (page_evictable(page)) {
  643. /*
  644. * For evictable pages, we can use the cache.
  645. * In event of a race, worst case is we end up with an
  646. * unevictable page on [in]active list.
  647. * We know how to handle that.
  648. */
  649. is_unevictable = false;
  650. lru_cache_add(page);
  651. } else {
  652. /*
  653. * Put unevictable pages directly on zone's unevictable
  654. * list.
  655. */
  656. is_unevictable = true;
  657. add_page_to_unevictable_list(page);
  658. /*
  659. * When racing with an mlock or AS_UNEVICTABLE clearing
  660. * (page is unlocked) make sure that if the other thread
  661. * does not observe our setting of PG_lru and fails
  662. * isolation/check_move_unevictable_pages,
  663. * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
  664. * the page back to the evictable list.
  665. *
  666. * The other side is TestClearPageMlocked() or shmem_lock().
  667. */
  668. smp_mb();
  669. }
  670. /*
  671. * page's status can change while we move it among lru. If an evictable
  672. * page is on unevictable list, it never be freed. To avoid that,
  673. * check after we added it to the list, again.
  674. */
  675. if (is_unevictable && page_evictable(page)) {
  676. if (!isolate_lru_page(page)) {
  677. put_page(page);
  678. goto redo;
  679. }
  680. /* This means someone else dropped this page from LRU
  681. * So, it will be freed or putback to LRU again. There is
  682. * nothing to do here.
  683. */
  684. }
  685. if (was_unevictable && !is_unevictable)
  686. count_vm_event(UNEVICTABLE_PGRESCUED);
  687. else if (!was_unevictable && is_unevictable)
  688. count_vm_event(UNEVICTABLE_PGCULLED);
  689. put_page(page); /* drop ref from isolate */
  690. }
  691. enum page_references {
  692. PAGEREF_RECLAIM,
  693. PAGEREF_RECLAIM_CLEAN,
  694. PAGEREF_KEEP,
  695. PAGEREF_ACTIVATE,
  696. };
  697. static enum page_references page_check_references(struct page *page,
  698. struct scan_control *sc)
  699. {
  700. int referenced_ptes, referenced_page;
  701. unsigned long vm_flags;
  702. referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
  703. &vm_flags);
  704. referenced_page = TestClearPageReferenced(page);
  705. /*
  706. * Mlock lost the isolation race with us. Let try_to_unmap()
  707. * move the page to the unevictable list.
  708. */
  709. if (vm_flags & VM_LOCKED)
  710. return PAGEREF_RECLAIM;
  711. if (referenced_ptes) {
  712. if (PageSwapBacked(page))
  713. return PAGEREF_ACTIVATE;
  714. /*
  715. * All mapped pages start out with page table
  716. * references from the instantiating fault, so we need
  717. * to look twice if a mapped file page is used more
  718. * than once.
  719. *
  720. * Mark it and spare it for another trip around the
  721. * inactive list. Another page table reference will
  722. * lead to its activation.
  723. *
  724. * Note: the mark is set for activated pages as well
  725. * so that recently deactivated but used pages are
  726. * quickly recovered.
  727. */
  728. SetPageReferenced(page);
  729. if (referenced_page || referenced_ptes > 1)
  730. return PAGEREF_ACTIVATE;
  731. /*
  732. * Activate file-backed executable pages after first usage.
  733. */
  734. if (vm_flags & VM_EXEC)
  735. return PAGEREF_ACTIVATE;
  736. return PAGEREF_KEEP;
  737. }
  738. /* Reclaim if clean, defer dirty pages to writeback */
  739. if (referenced_page && !PageSwapBacked(page))
  740. return PAGEREF_RECLAIM_CLEAN;
  741. return PAGEREF_RECLAIM;
  742. }
  743. /* Check if a page is dirty or under writeback */
  744. static void page_check_dirty_writeback(struct page *page,
  745. bool *dirty, bool *writeback)
  746. {
  747. struct address_space *mapping;
  748. /*
  749. * Anonymous pages are not handled by flushers and must be written
  750. * from reclaim context. Do not stall reclaim based on them
  751. */
  752. if (!page_is_file_cache(page)) {
  753. *dirty = false;
  754. *writeback = false;
  755. return;
  756. }
  757. /* By default assume that the page flags are accurate */
  758. *dirty = PageDirty(page);
  759. *writeback = PageWriteback(page);
  760. /* Verify dirty/writeback state if the filesystem supports it */
  761. if (!page_has_private(page))
  762. return;
  763. mapping = page_mapping(page);
  764. if (mapping && mapping->a_ops->is_dirty_writeback)
  765. mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
  766. }
  767. /*
  768. * shrink_page_list() returns the number of reclaimed pages
  769. */
  770. static unsigned long shrink_page_list(struct list_head *page_list,
  771. struct zone *zone,
  772. struct scan_control *sc,
  773. enum ttu_flags ttu_flags,
  774. unsigned long *ret_nr_dirty,
  775. unsigned long *ret_nr_unqueued_dirty,
  776. unsigned long *ret_nr_congested,
  777. unsigned long *ret_nr_writeback,
  778. unsigned long *ret_nr_immediate,
  779. bool force_reclaim)
  780. {
  781. LIST_HEAD(ret_pages);
  782. LIST_HEAD(free_pages);
  783. int pgactivate = 0;
  784. unsigned long nr_unqueued_dirty = 0;
  785. unsigned long nr_dirty = 0;
  786. unsigned long nr_congested = 0;
  787. unsigned long nr_reclaimed = 0;
  788. unsigned long nr_writeback = 0;
  789. unsigned long nr_immediate = 0;
  790. cond_resched();
  791. while (!list_empty(page_list)) {
  792. struct address_space *mapping;
  793. struct page *page;
  794. int may_enter_fs;
  795. enum page_references references = PAGEREF_RECLAIM_CLEAN;
  796. bool dirty, writeback;
  797. bool lazyfree = false;
  798. int ret = SWAP_SUCCESS;
  799. cond_resched();
  800. page = lru_to_page(page_list);
  801. list_del(&page->lru);
  802. if (!trylock_page(page))
  803. goto keep;
  804. VM_BUG_ON_PAGE(PageActive(page), page);
  805. VM_BUG_ON_PAGE(page_zone(page) != zone, page);
  806. sc->nr_scanned++;
  807. if (unlikely(!page_evictable(page)))
  808. goto cull_mlocked;
  809. if (!sc->may_unmap && page_mapped(page))
  810. goto keep_locked;
  811. /* Double the slab pressure for mapped and swapcache pages */
  812. if (page_mapped(page) || PageSwapCache(page))
  813. sc->nr_scanned++;
  814. may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
  815. (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
  816. /*
  817. * The number of dirty pages determines if a zone is marked
  818. * reclaim_congested which affects wait_iff_congested. kswapd
  819. * will stall and start writing pages if the tail of the LRU
  820. * is all dirty unqueued pages.
  821. */
  822. page_check_dirty_writeback(page, &dirty, &writeback);
  823. if (dirty || writeback)
  824. nr_dirty++;
  825. if (dirty && !writeback)
  826. nr_unqueued_dirty++;
  827. /*
  828. * Treat this page as congested if the underlying BDI is or if
  829. * pages are cycling through the LRU so quickly that the
  830. * pages marked for immediate reclaim are making it to the
  831. * end of the LRU a second time.
  832. */
  833. mapping = page_mapping(page);
  834. if (((dirty || writeback) && mapping &&
  835. inode_write_congested(mapping->host)) ||
  836. (writeback && PageReclaim(page)))
  837. nr_congested++;
  838. /*
  839. * If a page at the tail of the LRU is under writeback, there
  840. * are three cases to consider.
  841. *
  842. * 1) If reclaim is encountering an excessive number of pages
  843. * under writeback and this page is both under writeback and
  844. * PageReclaim then it indicates that pages are being queued
  845. * for IO but are being recycled through the LRU before the
  846. * IO can complete. Waiting on the page itself risks an
  847. * indefinite stall if it is impossible to writeback the
  848. * page due to IO error or disconnected storage so instead
  849. * note that the LRU is being scanned too quickly and the
  850. * caller can stall after page list has been processed.
  851. *
  852. * 2) Global or new memcg reclaim encounters a page that is
  853. * not marked for immediate reclaim, or the caller does not
  854. * have __GFP_FS (or __GFP_IO if it's simply going to swap,
  855. * not to fs). In this case mark the page for immediate
  856. * reclaim and continue scanning.
  857. *
  858. * Require may_enter_fs because we would wait on fs, which
  859. * may not have submitted IO yet. And the loop driver might
  860. * enter reclaim, and deadlock if it waits on a page for
  861. * which it is needed to do the write (loop masks off
  862. * __GFP_IO|__GFP_FS for this reason); but more thought
  863. * would probably show more reasons.
  864. *
  865. * 3) Legacy memcg encounters a page that is already marked
  866. * PageReclaim. memcg does not have any dirty pages
  867. * throttling so we could easily OOM just because too many
  868. * pages are in writeback and there is nothing else to
  869. * reclaim. Wait for the writeback to complete.
  870. */
  871. if (PageWriteback(page)) {
  872. /* Case 1 above */
  873. if (current_is_kswapd() &&
  874. PageReclaim(page) &&
  875. test_bit(ZONE_WRITEBACK, &zone->flags)) {
  876. nr_immediate++;
  877. goto keep_locked;
  878. /* Case 2 above */
  879. } else if (sane_reclaim(sc) ||
  880. !PageReclaim(page) || !may_enter_fs) {
  881. /*
  882. * This is slightly racy - end_page_writeback()
  883. * might have just cleared PageReclaim, then
  884. * setting PageReclaim here end up interpreted
  885. * as PageReadahead - but that does not matter
  886. * enough to care. What we do want is for this
  887. * page to have PageReclaim set next time memcg
  888. * reclaim reaches the tests above, so it will
  889. * then wait_on_page_writeback() to avoid OOM;
  890. * and it's also appropriate in global reclaim.
  891. */
  892. SetPageReclaim(page);
  893. nr_writeback++;
  894. goto keep_locked;
  895. /* Case 3 above */
  896. } else {
  897. unlock_page(page);
  898. wait_on_page_writeback(page);
  899. /* then go back and try same page again */
  900. list_add_tail(&page->lru, page_list);
  901. continue;
  902. }
  903. }
  904. if (!force_reclaim)
  905. references = page_check_references(page, sc);
  906. switch (references) {
  907. case PAGEREF_ACTIVATE:
  908. goto activate_locked;
  909. case PAGEREF_KEEP:
  910. goto keep_locked;
  911. case PAGEREF_RECLAIM:
  912. case PAGEREF_RECLAIM_CLEAN:
  913. ; /* try to reclaim the page below */
  914. }
  915. /*
  916. * Anonymous process memory has backing store?
  917. * Try to allocate it some swap space here.
  918. */
  919. if (PageAnon(page) && !PageSwapCache(page)) {
  920. if (!(sc->gfp_mask & __GFP_IO))
  921. goto keep_locked;
  922. if (!add_to_swap(page, page_list))
  923. goto activate_locked;
  924. lazyfree = true;
  925. may_enter_fs = 1;
  926. /* Adding to swap updated mapping */
  927. mapping = page_mapping(page);
  928. }
  929. /*
  930. * The page is mapped into the page tables of one or more
  931. * processes. Try to unmap it here.
  932. */
  933. if (page_mapped(page) && mapping) {
  934. switch (ret = try_to_unmap(page, lazyfree ?
  935. (ttu_flags | TTU_BATCH_FLUSH | TTU_LZFREE) :
  936. (ttu_flags | TTU_BATCH_FLUSH))) {
  937. case SWAP_FAIL:
  938. goto activate_locked;
  939. case SWAP_AGAIN:
  940. goto keep_locked;
  941. case SWAP_MLOCK:
  942. goto cull_mlocked;
  943. case SWAP_LZFREE:
  944. goto lazyfree;
  945. case SWAP_SUCCESS:
  946. ; /* try to free the page below */
  947. }
  948. }
  949. if (PageDirty(page)) {
  950. /*
  951. * Only kswapd can writeback filesystem pages to
  952. * avoid risk of stack overflow but only writeback
  953. * if many dirty pages have been encountered.
  954. */
  955. if (page_is_file_cache(page) &&
  956. (!current_is_kswapd() ||
  957. !test_bit(ZONE_DIRTY, &zone->flags))) {
  958. /*
  959. * Immediately reclaim when written back.
  960. * Similar in principal to deactivate_page()
  961. * except we already have the page isolated
  962. * and know it's dirty
  963. */
  964. inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
  965. SetPageReclaim(page);
  966. goto keep_locked;
  967. }
  968. if (references == PAGEREF_RECLAIM_CLEAN)
  969. goto keep_locked;
  970. if (!may_enter_fs)
  971. goto keep_locked;
  972. if (!sc->may_writepage)
  973. goto keep_locked;
  974. /*
  975. * Page is dirty. Flush the TLB if a writable entry
  976. * potentially exists to avoid CPU writes after IO
  977. * starts and then write it out here.
  978. */
  979. try_to_unmap_flush_dirty();
  980. switch (pageout(page, mapping, sc)) {
  981. case PAGE_KEEP:
  982. goto keep_locked;
  983. case PAGE_ACTIVATE:
  984. goto activate_locked;
  985. case PAGE_SUCCESS:
  986. if (PageWriteback(page))
  987. goto keep;
  988. if (PageDirty(page))
  989. goto keep;
  990. /*
  991. * A synchronous write - probably a ramdisk. Go
  992. * ahead and try to reclaim the page.
  993. */
  994. if (!trylock_page(page))
  995. goto keep;
  996. if (PageDirty(page) || PageWriteback(page))
  997. goto keep_locked;
  998. mapping = page_mapping(page);
  999. case PAGE_CLEAN:
  1000. ; /* try to free the page below */
  1001. }
  1002. }
  1003. /*
  1004. * If the page has buffers, try to free the buffer mappings
  1005. * associated with this page. If we succeed we try to free
  1006. * the page as well.
  1007. *
  1008. * We do this even if the page is PageDirty().
  1009. * try_to_release_page() does not perform I/O, but it is
  1010. * possible for a page to have PageDirty set, but it is actually
  1011. * clean (all its buffers are clean). This happens if the
  1012. * buffers were written out directly, with submit_bh(). ext3
  1013. * will do this, as well as the blockdev mapping.
  1014. * try_to_release_page() will discover that cleanness and will
  1015. * drop the buffers and mark the page clean - it can be freed.
  1016. *
  1017. * Rarely, pages can have buffers and no ->mapping. These are
  1018. * the pages which were not successfully invalidated in
  1019. * truncate_complete_page(). We try to drop those buffers here
  1020. * and if that worked, and the page is no longer mapped into
  1021. * process address space (page_count == 1) it can be freed.
  1022. * Otherwise, leave the page on the LRU so it is swappable.
  1023. */
  1024. if (page_has_private(page)) {
  1025. if (!try_to_release_page(page, sc->gfp_mask))
  1026. goto activate_locked;
  1027. if (!mapping && page_count(page) == 1) {
  1028. unlock_page(page);
  1029. if (put_page_testzero(page))
  1030. goto free_it;
  1031. else {
  1032. /*
  1033. * rare race with speculative reference.
  1034. * the speculative reference will free
  1035. * this page shortly, so we may
  1036. * increment nr_reclaimed here (and
  1037. * leave it off the LRU).
  1038. */
  1039. nr_reclaimed++;
  1040. continue;
  1041. }
  1042. }
  1043. }
  1044. lazyfree:
  1045. if (!mapping || !__remove_mapping(mapping, page, true))
  1046. goto keep_locked;
  1047. /*
  1048. * At this point, we have no other references and there is
  1049. * no way to pick any more up (removed from LRU, removed
  1050. * from pagecache). Can use non-atomic bitops now (and
  1051. * we obviously don't have to worry about waking up a process
  1052. * waiting on the page lock, because there are no references.
  1053. */
  1054. __ClearPageLocked(page);
  1055. free_it:
  1056. if (ret == SWAP_LZFREE)
  1057. count_vm_event(PGLAZYFREED);
  1058. nr_reclaimed++;
  1059. /*
  1060. * Is there need to periodically free_page_list? It would
  1061. * appear not as the counts should be low
  1062. */
  1063. list_add(&page->lru, &free_pages);
  1064. continue;
  1065. cull_mlocked:
  1066. if (PageSwapCache(page))
  1067. try_to_free_swap(page);
  1068. unlock_page(page);
  1069. list_add(&page->lru, &ret_pages);
  1070. continue;
  1071. activate_locked:
  1072. /* Not a candidate for swapping, so reclaim swap space. */
  1073. if (PageSwapCache(page) && mem_cgroup_swap_full(page))
  1074. try_to_free_swap(page);
  1075. VM_BUG_ON_PAGE(PageActive(page), page);
  1076. SetPageActive(page);
  1077. pgactivate++;
  1078. keep_locked:
  1079. unlock_page(page);
  1080. keep:
  1081. list_add(&page->lru, &ret_pages);
  1082. VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
  1083. }
  1084. mem_cgroup_uncharge_list(&free_pages);
  1085. try_to_unmap_flush();
  1086. free_hot_cold_page_list(&free_pages, true);
  1087. list_splice(&ret_pages, page_list);
  1088. count_vm_events(PGACTIVATE, pgactivate);
  1089. *ret_nr_dirty += nr_dirty;
  1090. *ret_nr_congested += nr_congested;
  1091. *ret_nr_unqueued_dirty += nr_unqueued_dirty;
  1092. *ret_nr_writeback += nr_writeback;
  1093. *ret_nr_immediate += nr_immediate;
  1094. return nr_reclaimed;
  1095. }
  1096. unsigned long reclaim_clean_pages_from_list(struct zone *zone,
  1097. struct list_head *page_list)
  1098. {
  1099. struct scan_control sc = {
  1100. .gfp_mask = GFP_KERNEL,
  1101. .priority = DEF_PRIORITY,
  1102. .may_unmap = 1,
  1103. };
  1104. unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
  1105. struct page *page, *next;
  1106. LIST_HEAD(clean_pages);
  1107. list_for_each_entry_safe(page, next, page_list, lru) {
  1108. if (page_is_file_cache(page) && !PageDirty(page) &&
  1109. !isolated_balloon_page(page)) {
  1110. ClearPageActive(page);
  1111. list_move(&page->lru, &clean_pages);
  1112. }
  1113. }
  1114. ret = shrink_page_list(&clean_pages, zone, &sc,
  1115. TTU_UNMAP|TTU_IGNORE_ACCESS,
  1116. &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
  1117. list_splice(&clean_pages, page_list);
  1118. mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
  1119. return ret;
  1120. }
  1121. /*
  1122. * Attempt to remove the specified page from its LRU. Only take this page
  1123. * if it is of the appropriate PageActive status. Pages which are being
  1124. * freed elsewhere are also ignored.
  1125. *
  1126. * page: page to consider
  1127. * mode: one of the LRU isolation modes defined above
  1128. *
  1129. * returns 0 on success, -ve errno on failure.
  1130. */
  1131. int __isolate_lru_page(struct page *page, isolate_mode_t mode)
  1132. {
  1133. int ret = -EINVAL;
  1134. /* Only take pages on the LRU. */
  1135. if (!PageLRU(page))
  1136. return ret;
  1137. /* Compaction should not handle unevictable pages but CMA can do so */
  1138. if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
  1139. return ret;
  1140. ret = -EBUSY;
  1141. /*
  1142. * To minimise LRU disruption, the caller can indicate that it only
  1143. * wants to isolate pages it will be able to operate on without
  1144. * blocking - clean pages for the most part.
  1145. *
  1146. * ISOLATE_CLEAN means that only clean pages should be isolated. This
  1147. * is used by reclaim when it is cannot write to backing storage
  1148. *
  1149. * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
  1150. * that it is possible to migrate without blocking
  1151. */
  1152. if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
  1153. /* All the caller can do on PageWriteback is block */
  1154. if (PageWriteback(page))
  1155. return ret;
  1156. if (PageDirty(page)) {
  1157. struct address_space *mapping;
  1158. /* ISOLATE_CLEAN means only clean pages */
  1159. if (mode & ISOLATE_CLEAN)
  1160. return ret;
  1161. /*
  1162. * Only pages without mappings or that have a
  1163. * ->migratepage callback are possible to migrate
  1164. * without blocking
  1165. */
  1166. mapping = page_mapping(page);
  1167. if (mapping && !mapping->a_ops->migratepage)
  1168. return ret;
  1169. }
  1170. }
  1171. if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
  1172. return ret;
  1173. if (likely(get_page_unless_zero(page))) {
  1174. /*
  1175. * Be careful not to clear PageLRU until after we're
  1176. * sure the page is not being freed elsewhere -- the
  1177. * page release code relies on it.
  1178. */
  1179. ClearPageLRU(page);
  1180. ret = 0;
  1181. }
  1182. return ret;
  1183. }
  1184. /*
  1185. * zone->lru_lock is heavily contended. Some of the functions that
  1186. * shrink the lists perform better by taking out a batch of pages
  1187. * and working on them outside the LRU lock.
  1188. *
  1189. * For pagecache intensive workloads, this function is the hottest
  1190. * spot in the kernel (apart from copy_*_user functions).
  1191. *
  1192. * Appropriate locks must be held before calling this function.
  1193. *
  1194. * @nr_to_scan: The number of pages to look through on the list.
  1195. * @lruvec: The LRU vector to pull pages from.
  1196. * @dst: The temp list to put pages on to.
  1197. * @nr_scanned: The number of pages that were scanned.
  1198. * @sc: The scan_control struct for this reclaim session
  1199. * @mode: One of the LRU isolation modes
  1200. * @lru: LRU list id for isolating
  1201. *
  1202. * returns how many pages were moved onto *@dst.
  1203. */
  1204. static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
  1205. struct lruvec *lruvec, struct list_head *dst,
  1206. unsigned long *nr_scanned, struct scan_control *sc,
  1207. isolate_mode_t mode, enum lru_list lru)
  1208. {
  1209. struct list_head *src = &lruvec->lists[lru];
  1210. unsigned long nr_taken = 0;
  1211. unsigned long scan;
  1212. for (scan = 0; scan < nr_to_scan && nr_taken < nr_to_scan &&
  1213. !list_empty(src); scan++) {
  1214. struct page *page;
  1215. page = lru_to_page(src);
  1216. prefetchw_prev_lru_page(page, src, flags);
  1217. VM_BUG_ON_PAGE(!PageLRU(page), page);
  1218. switch (__isolate_lru_page(page, mode)) {
  1219. case 0:
  1220. nr_taken += hpage_nr_pages(page);
  1221. list_move(&page->lru, dst);
  1222. break;
  1223. case -EBUSY:
  1224. /* else it is being freed elsewhere */
  1225. list_move(&page->lru, src);
  1226. continue;
  1227. default:
  1228. BUG();
  1229. }
  1230. }
  1231. *nr_scanned = scan;
  1232. trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
  1233. nr_taken, mode, is_file_lru(lru));
  1234. return nr_taken;
  1235. }
  1236. /**
  1237. * isolate_lru_page - tries to isolate a page from its LRU list
  1238. * @page: page to isolate from its LRU list
  1239. *
  1240. * Isolates a @page from an LRU list, clears PageLRU and adjusts the
  1241. * vmstat statistic corresponding to whatever LRU list the page was on.
  1242. *
  1243. * Returns 0 if the page was removed from an LRU list.
  1244. * Returns -EBUSY if the page was not on an LRU list.
  1245. *
  1246. * The returned page will have PageLRU() cleared. If it was found on
  1247. * the active list, it will have PageActive set. If it was found on
  1248. * the unevictable list, it will have the PageUnevictable bit set. That flag
  1249. * may need to be cleared by the caller before letting the page go.
  1250. *
  1251. * The vmstat statistic corresponding to the list on which the page was
  1252. * found will be decremented.
  1253. *
  1254. * Restrictions:
  1255. * (1) Must be called with an elevated refcount on the page. This is a
  1256. * fundamentnal difference from isolate_lru_pages (which is called
  1257. * without a stable reference).
  1258. * (2) the lru_lock must not be held.
  1259. * (3) interrupts must be enabled.
  1260. */
  1261. int isolate_lru_page(struct page *page)
  1262. {
  1263. int ret = -EBUSY;
  1264. VM_BUG_ON_PAGE(!page_count(page), page);
  1265. WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
  1266. if (PageLRU(page)) {
  1267. struct zone *zone = page_zone(page);
  1268. struct lruvec *lruvec;
  1269. spin_lock_irq(&zone->lru_lock);
  1270. lruvec = mem_cgroup_page_lruvec(page, zone);
  1271. if (PageLRU(page)) {
  1272. int lru = page_lru(page);
  1273. get_page(page);
  1274. ClearPageLRU(page);
  1275. del_page_from_lru_list(page, lruvec, lru);
  1276. ret = 0;
  1277. }
  1278. spin_unlock_irq(&zone->lru_lock);
  1279. }
  1280. return ret;
  1281. }
  1282. /*
  1283. * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
  1284. * then get resheduled. When there are massive number of tasks doing page
  1285. * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
  1286. * the LRU list will go small and be scanned faster than necessary, leading to
  1287. * unnecessary swapping, thrashing and OOM.
  1288. */
  1289. static int too_many_isolated(struct zone *zone, int file,
  1290. struct scan_control *sc)
  1291. {
  1292. unsigned long inactive, isolated;
  1293. if (current_is_kswapd())
  1294. return 0;
  1295. if (!sane_reclaim(sc))
  1296. return 0;
  1297. if (file) {
  1298. inactive = zone_page_state(zone, NR_INACTIVE_FILE);
  1299. isolated = zone_page_state(zone, NR_ISOLATED_FILE);
  1300. } else {
  1301. inactive = zone_page_state(zone, NR_INACTIVE_ANON);
  1302. isolated = zone_page_state(zone, NR_ISOLATED_ANON);
  1303. }
  1304. /*
  1305. * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
  1306. * won't get blocked by normal direct-reclaimers, forming a circular
  1307. * deadlock.
  1308. */
  1309. if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
  1310. inactive >>= 3;
  1311. return isolated > inactive;
  1312. }
  1313. static noinline_for_stack void
  1314. putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
  1315. {
  1316. struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
  1317. struct zone *zone = lruvec_zone(lruvec);
  1318. LIST_HEAD(pages_to_free);
  1319. /*
  1320. * Put back any unfreeable pages.
  1321. */
  1322. while (!list_empty(page_list)) {
  1323. struct page *page = lru_to_page(page_list);
  1324. int lru;
  1325. VM_BUG_ON_PAGE(PageLRU(page), page);
  1326. list_del(&page->lru);
  1327. if (unlikely(!page_evictable(page))) {
  1328. spin_unlock_irq(&zone->lru_lock);
  1329. putback_lru_page(page);
  1330. spin_lock_irq(&zone->lru_lock);
  1331. continue;
  1332. }
  1333. lruvec = mem_cgroup_page_lruvec(page, zone);
  1334. SetPageLRU(page);
  1335. lru = page_lru(page);
  1336. add_page_to_lru_list(page, lruvec, lru);
  1337. if (is_active_lru(lru)) {
  1338. int file = is_file_lru(lru);
  1339. int numpages = hpage_nr_pages(page);
  1340. reclaim_stat->recent_rotated[file] += numpages;
  1341. }
  1342. if (put_page_testzero(page)) {
  1343. __ClearPageLRU(page);
  1344. __ClearPageActive(page);
  1345. del_page_from_lru_list(page, lruvec, lru);
  1346. if (unlikely(PageCompound(page))) {
  1347. spin_unlock_irq(&zone->lru_lock);
  1348. mem_cgroup_uncharge(page);
  1349. (*get_compound_page_dtor(page))(page);
  1350. spin_lock_irq(&zone->lru_lock);
  1351. } else
  1352. list_add(&page->lru, &pages_to_free);
  1353. }
  1354. }
  1355. /*
  1356. * To save our caller's stack, now use input list for pages to free.
  1357. */
  1358. list_splice(&pages_to_free, page_list);
  1359. }
  1360. /*
  1361. * If a kernel thread (such as nfsd for loop-back mounts) services
  1362. * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
  1363. * In that case we should only throttle if the backing device it is
  1364. * writing to is congested. In other cases it is safe to throttle.
  1365. */
  1366. static int current_may_throttle(void)
  1367. {
  1368. return !(current->flags & PF_LESS_THROTTLE) ||
  1369. current->backing_dev_info == NULL ||
  1370. bdi_write_congested(current->backing_dev_info);
  1371. }
  1372. /*
  1373. * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
  1374. * of reclaimed pages
  1375. */
  1376. static noinline_for_stack unsigned long
  1377. shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
  1378. struct scan_control *sc, enum lru_list lru)
  1379. {
  1380. LIST_HEAD(page_list);
  1381. unsigned long nr_scanned;
  1382. unsigned long nr_reclaimed = 0;
  1383. unsigned long nr_taken;
  1384. unsigned long nr_dirty = 0;
  1385. unsigned long nr_congested = 0;
  1386. unsigned long nr_unqueued_dirty = 0;
  1387. unsigned long nr_writeback = 0;
  1388. unsigned long nr_immediate = 0;
  1389. isolate_mode_t isolate_mode = 0;
  1390. int file = is_file_lru(lru);
  1391. struct zone *zone = lruvec_zone(lruvec);
  1392. struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
  1393. while (unlikely(too_many_isolated(zone, file, sc))) {
  1394. congestion_wait(BLK_RW_ASYNC, HZ/10);
  1395. /* We are about to die and free our memory. Return now. */
  1396. if (fatal_signal_pending(current))
  1397. return SWAP_CLUSTER_MAX;
  1398. }
  1399. lru_add_drain();
  1400. if (!sc->may_unmap)
  1401. isolate_mode |= ISOLATE_UNMAPPED;
  1402. if (!sc->may_writepage)
  1403. isolate_mode |= ISOLATE_CLEAN;
  1404. spin_lock_irq(&zone->lru_lock);
  1405. nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
  1406. &nr_scanned, sc, isolate_mode, lru);
  1407. update_lru_size(lruvec, lru, -nr_taken);
  1408. __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
  1409. reclaim_stat->recent_scanned[file] += nr_taken;
  1410. if (global_reclaim(sc)) {
  1411. __mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
  1412. if (current_is_kswapd())
  1413. __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
  1414. else
  1415. __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
  1416. }
  1417. spin_unlock_irq(&zone->lru_lock);
  1418. if (nr_taken == 0)
  1419. return 0;
  1420. nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
  1421. &nr_dirty, &nr_unqueued_dirty, &nr_congested,
  1422. &nr_writeback, &nr_immediate,
  1423. false);
  1424. spin_lock_irq(&zone->lru_lock);
  1425. if (global_reclaim(sc)) {
  1426. if (current_is_kswapd())
  1427. __count_zone_vm_events(PGSTEAL_KSWAPD, zone,
  1428. nr_reclaimed);
  1429. else
  1430. __count_zone_vm_events(PGSTEAL_DIRECT, zone,
  1431. nr_reclaimed);
  1432. }
  1433. putback_inactive_pages(lruvec, &page_list);
  1434. __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
  1435. spin_unlock_irq(&zone->lru_lock);
  1436. mem_cgroup_uncharge_list(&page_list);
  1437. free_hot_cold_page_list(&page_list, true);
  1438. /*
  1439. * If reclaim is isolating dirty pages under writeback, it implies
  1440. * that the long-lived page allocation rate is exceeding the page
  1441. * laundering rate. Either the global limits are not being effective
  1442. * at throttling processes due to the page distribution throughout
  1443. * zones or there is heavy usage of a slow backing device. The
  1444. * only option is to throttle from reclaim context which is not ideal
  1445. * as there is no guarantee the dirtying process is throttled in the
  1446. * same way balance_dirty_pages() manages.
  1447. *
  1448. * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
  1449. * of pages under pages flagged for immediate reclaim and stall if any
  1450. * are encountered in the nr_immediate check below.
  1451. */
  1452. if (nr_writeback && nr_writeback == nr_taken)
  1453. set_bit(ZONE_WRITEBACK, &zone->flags);
  1454. /*
  1455. * Legacy memcg will stall in page writeback so avoid forcibly
  1456. * stalling here.
  1457. */
  1458. if (sane_reclaim(sc)) {
  1459. /*
  1460. * Tag a zone as congested if all the dirty pages scanned were
  1461. * backed by a congested BDI and wait_iff_congested will stall.
  1462. */
  1463. if (nr_dirty && nr_dirty == nr_congested)
  1464. set_bit(ZONE_CONGESTED, &zone->flags);
  1465. /*
  1466. * If dirty pages are scanned that are not queued for IO, it
  1467. * implies that flushers are not keeping up. In this case, flag
  1468. * the zone ZONE_DIRTY and kswapd will start writing pages from
  1469. * reclaim context.
  1470. */
  1471. if (nr_unqueued_dirty == nr_taken)
  1472. set_bit(ZONE_DIRTY, &zone->flags);
  1473. /*
  1474. * If kswapd scans pages marked marked for immediate
  1475. * reclaim and under writeback (nr_immediate), it implies
  1476. * that pages are cycling through the LRU faster than
  1477. * they are written so also forcibly stall.
  1478. */
  1479. if (nr_immediate && current_may_throttle())
  1480. congestion_wait(BLK_RW_ASYNC, HZ/10);
  1481. }
  1482. /*
  1483. * Stall direct reclaim for IO completions if underlying BDIs or zone
  1484. * is congested. Allow kswapd to continue until it starts encountering
  1485. * unqueued dirty pages or cycling through the LRU too quickly.
  1486. */
  1487. if (!sc->hibernation_mode && !current_is_kswapd() &&
  1488. current_may_throttle())
  1489. wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
  1490. trace_mm_vmscan_lru_shrink_inactive(zone, nr_scanned, nr_reclaimed,
  1491. sc->priority, file);
  1492. return nr_reclaimed;
  1493. }
  1494. /*
  1495. * This moves pages from the active list to the inactive list.
  1496. *
  1497. * We move them the other way if the page is referenced by one or more
  1498. * processes, from rmap.
  1499. *
  1500. * If the pages are mostly unmapped, the processing is fast and it is
  1501. * appropriate to hold zone->lru_lock across the whole operation. But if
  1502. * the pages are mapped, the processing is slow (page_referenced()) so we
  1503. * should drop zone->lru_lock around each page. It's impossible to balance
  1504. * this, so instead we remove the pages from the LRU while processing them.
  1505. * It is safe to rely on PG_active against the non-LRU pages in here because
  1506. * nobody will play with that bit on a non-LRU page.
  1507. *
  1508. * The downside is that we have to touch page->_refcount against each page.
  1509. * But we had to alter page->flags anyway.
  1510. */
  1511. static void move_active_pages_to_lru(struct lruvec *lruvec,
  1512. struct list_head *list,
  1513. struct list_head *pages_to_free,
  1514. enum lru_list lru)
  1515. {
  1516. struct zone *zone = lruvec_zone(lruvec);
  1517. unsigned long pgmoved = 0;
  1518. struct page *page;
  1519. int nr_pages;
  1520. while (!list_empty(list)) {
  1521. page = lru_to_page(list);
  1522. lruvec = mem_cgroup_page_lruvec(page, zone);
  1523. VM_BUG_ON_PAGE(PageLRU(page), page);
  1524. SetPageLRU(page);
  1525. nr_pages = hpage_nr_pages(page);
  1526. update_lru_size(lruvec, lru, nr_pages);
  1527. list_move(&page->lru, &lruvec->lists[lru]);
  1528. pgmoved += nr_pages;
  1529. if (put_page_testzero(page)) {
  1530. __ClearPageLRU(page);
  1531. __ClearPageActive(page);
  1532. del_page_from_lru_list(page, lruvec, lru);
  1533. if (unlikely(PageCompound(page))) {
  1534. spin_unlock_irq(&zone->lru_lock);
  1535. mem_cgroup_uncharge(page);
  1536. (*get_compound_page_dtor(page))(page);
  1537. spin_lock_irq(&zone->lru_lock);
  1538. } else
  1539. list_add(&page->lru, pages_to_free);
  1540. }
  1541. }
  1542. if (!is_active_lru(lru))
  1543. __count_vm_events(PGDEACTIVATE, pgmoved);
  1544. }
  1545. static void shrink_active_list(unsigned long nr_to_scan,
  1546. struct lruvec *lruvec,
  1547. struct scan_control *sc,
  1548. enum lru_list lru)
  1549. {
  1550. unsigned long nr_taken;
  1551. unsigned long nr_scanned;
  1552. unsigned long vm_flags;
  1553. LIST_HEAD(l_hold); /* The pages which were snipped off */
  1554. LIST_HEAD(l_active);
  1555. LIST_HEAD(l_inactive);
  1556. struct page *page;
  1557. struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
  1558. unsigned long nr_rotated = 0;
  1559. isolate_mode_t isolate_mode = 0;
  1560. int file = is_file_lru(lru);
  1561. struct zone *zone = lruvec_zone(lruvec);
  1562. lru_add_drain();
  1563. if (!sc->may_unmap)
  1564. isolate_mode |= ISOLATE_UNMAPPED;
  1565. if (!sc->may_writepage)
  1566. isolate_mode |= ISOLATE_CLEAN;
  1567. spin_lock_irq(&zone->lru_lock);
  1568. nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
  1569. &nr_scanned, sc, isolate_mode, lru);
  1570. update_lru_size(lruvec, lru, -nr_taken);
  1571. __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
  1572. reclaim_stat->recent_scanned[file] += nr_taken;
  1573. if (global_reclaim(sc))
  1574. __mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
  1575. __count_zone_vm_events(PGREFILL, zone, nr_scanned);
  1576. spin_unlock_irq(&zone->lru_lock);
  1577. while (!list_empty(&l_hold)) {
  1578. cond_resched();
  1579. page = lru_to_page(&l_hold);
  1580. list_del(&page->lru);
  1581. if (unlikely(!page_evictable(page))) {
  1582. putback_lru_page(page);
  1583. continue;
  1584. }
  1585. if (unlikely(buffer_heads_over_limit)) {
  1586. if (page_has_private(page) && trylock_page(page)) {
  1587. if (page_has_private(page))
  1588. try_to_release_page(page, 0);
  1589. unlock_page(page);
  1590. }
  1591. }
  1592. if (page_referenced(page, 0, sc->target_mem_cgroup,
  1593. &vm_flags)) {
  1594. nr_rotated += hpage_nr_pages(page);
  1595. /*
  1596. * Identify referenced, file-backed active pages and
  1597. * give them one more trip around the active list. So
  1598. * that executable code get better chances to stay in
  1599. * memory under moderate memory pressure. Anon pages
  1600. * are not likely to be evicted by use-once streaming
  1601. * IO, plus JVM can create lots of anon VM_EXEC pages,
  1602. * so we ignore them here.
  1603. */
  1604. if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
  1605. list_add(&page->lru, &l_active);
  1606. continue;
  1607. }
  1608. }
  1609. ClearPageActive(page); /* we are de-activating */
  1610. list_add(&page->lru, &l_inactive);
  1611. }
  1612. /*
  1613. * Move pages back to the lru list.
  1614. */
  1615. spin_lock_irq(&zone->lru_lock);
  1616. /*
  1617. * Count referenced pages from currently used mappings as rotated,
  1618. * even though only some of them are actually re-activated. This
  1619. * helps balance scan pressure between file and anonymous pages in
  1620. * get_scan_count.
  1621. */
  1622. reclaim_stat->recent_rotated[file] += nr_rotated;
  1623. move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
  1624. move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
  1625. __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
  1626. spin_unlock_irq(&zone->lru_lock);
  1627. mem_cgroup_uncharge_list(&l_hold);
  1628. free_hot_cold_page_list(&l_hold, true);
  1629. }
  1630. /*
  1631. * The inactive anon list should be small enough that the VM never has
  1632. * to do too much work.
  1633. *
  1634. * The inactive file list should be small enough to leave most memory
  1635. * to the established workingset on the scan-resistant active list,
  1636. * but large enough to avoid thrashing the aggregate readahead window.
  1637. *
  1638. * Both inactive lists should also be large enough that each inactive
  1639. * page has a chance to be referenced again before it is reclaimed.
  1640. *
  1641. * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
  1642. * on this LRU, maintained by the pageout code. A zone->inactive_ratio
  1643. * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
  1644. *
  1645. * total target max
  1646. * memory ratio inactive
  1647. * -------------------------------------
  1648. * 10MB 1 5MB
  1649. * 100MB 1 50MB
  1650. * 1GB 3 250MB
  1651. * 10GB 10 0.9GB
  1652. * 100GB 31 3GB
  1653. * 1TB 101 10GB
  1654. * 10TB 320 32GB
  1655. */
  1656. static bool inactive_list_is_low(struct lruvec *lruvec, bool file)
  1657. {
  1658. unsigned long inactive_ratio;
  1659. unsigned long inactive;
  1660. unsigned long active;
  1661. unsigned long gb;
  1662. /*
  1663. * If we don't have swap space, anonymous page deactivation
  1664. * is pointless.
  1665. */
  1666. if (!file && !total_swap_pages)
  1667. return false;
  1668. inactive = lruvec_lru_size(lruvec, file * LRU_FILE);
  1669. active = lruvec_lru_size(lruvec, file * LRU_FILE + LRU_ACTIVE);
  1670. gb = (inactive + active) >> (30 - PAGE_SHIFT);
  1671. if (gb)
  1672. inactive_ratio = int_sqrt(10 * gb);
  1673. else
  1674. inactive_ratio = 1;
  1675. return inactive * inactive_ratio < active;
  1676. }
  1677. static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
  1678. struct lruvec *lruvec, struct scan_control *sc)
  1679. {
  1680. if (is_active_lru(lru)) {
  1681. if (inactive_list_is_low(lruvec, is_file_lru(lru)))
  1682. shrink_active_list(nr_to_scan, lruvec, sc, lru);
  1683. return 0;
  1684. }
  1685. return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
  1686. }
  1687. enum scan_balance {
  1688. SCAN_EQUAL,
  1689. SCAN_FRACT,
  1690. SCAN_ANON,
  1691. SCAN_FILE,
  1692. };
  1693. /*
  1694. * Determine how aggressively the anon and file LRU lists should be
  1695. * scanned. The relative value of each set of LRU lists is determined
  1696. * by looking at the fraction of the pages scanned we did rotate back
  1697. * onto the active list instead of evict.
  1698. *
  1699. * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
  1700. * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
  1701. */
  1702. static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
  1703. struct scan_control *sc, unsigned long *nr,
  1704. unsigned long *lru_pages)
  1705. {
  1706. int swappiness = mem_cgroup_swappiness(memcg);
  1707. struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
  1708. u64 fraction[2];
  1709. u64 denominator = 0; /* gcc */
  1710. struct zone *zone = lruvec_zone(lruvec);
  1711. unsigned long anon_prio, file_prio;
  1712. enum scan_balance scan_balance;
  1713. unsigned long anon, file;
  1714. bool force_scan = false;
  1715. unsigned long ap, fp;
  1716. enum lru_list lru;
  1717. bool some_scanned;
  1718. int pass;
  1719. /*
  1720. * If the zone or memcg is small, nr[l] can be 0. This
  1721. * results in no scanning on this priority and a potential
  1722. * priority drop. Global direct reclaim can go to the next
  1723. * zone and tends to have no problems. Global kswapd is for
  1724. * zone balancing and it needs to scan a minimum amount. When
  1725. * reclaiming for a memcg, a priority drop can cause high
  1726. * latencies, so it's better to scan a minimum amount there as
  1727. * well.
  1728. */
  1729. if (current_is_kswapd()) {
  1730. if (!zone_reclaimable(zone))
  1731. force_scan = true;
  1732. if (!mem_cgroup_online(memcg))
  1733. force_scan = true;
  1734. }
  1735. if (!global_reclaim(sc))
  1736. force_scan = true;
  1737. /* If we have no swap space, do not bother scanning anon pages. */
  1738. if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
  1739. scan_balance = SCAN_FILE;
  1740. goto out;
  1741. }
  1742. /*
  1743. * Global reclaim will swap to prevent OOM even with no
  1744. * swappiness, but memcg users want to use this knob to
  1745. * disable swapping for individual groups completely when
  1746. * using the memory controller's swap limit feature would be
  1747. * too expensive.
  1748. */
  1749. if (!global_reclaim(sc) && !swappiness) {
  1750. scan_balance = SCAN_FILE;
  1751. goto out;
  1752. }
  1753. /*
  1754. * Do not apply any pressure balancing cleverness when the
  1755. * system is close to OOM, scan both anon and file equally
  1756. * (unless the swappiness setting disagrees with swapping).
  1757. */
  1758. if (!sc->priority && swappiness) {
  1759. scan_balance = SCAN_EQUAL;
  1760. goto out;
  1761. }
  1762. /*
  1763. * Prevent the reclaimer from falling into the cache trap: as
  1764. * cache pages start out inactive, every cache fault will tip
  1765. * the scan balance towards the file LRU. And as the file LRU
  1766. * shrinks, so does the window for rotation from references.
  1767. * This means we have a runaway feedback loop where a tiny
  1768. * thrashing file LRU becomes infinitely more attractive than
  1769. * anon pages. Try to detect this based on file LRU size.
  1770. */
  1771. if (global_reclaim(sc)) {
  1772. unsigned long zonefile;
  1773. unsigned long zonefree;
  1774. zonefree = zone_page_state(zone, NR_FREE_PAGES);
  1775. zonefile = zone_page_state(zone, NR_ACTIVE_FILE) +
  1776. zone_page_state(zone, NR_INACTIVE_FILE);
  1777. if (unlikely(zonefile + zonefree <= high_wmark_pages(zone))) {
  1778. scan_balance = SCAN_ANON;
  1779. goto out;
  1780. }
  1781. }
  1782. /*
  1783. * If there is enough inactive page cache, i.e. if the size of the
  1784. * inactive list is greater than that of the active list *and* the
  1785. * inactive list actually has some pages to scan on this priority, we
  1786. * do not reclaim anything from the anonymous working set right now.
  1787. * Without the second condition we could end up never scanning an
  1788. * lruvec even if it has plenty of old anonymous pages unless the
  1789. * system is under heavy pressure.
  1790. */
  1791. if (!inactive_list_is_low(lruvec, true) &&
  1792. lruvec_lru_size(lruvec, LRU_INACTIVE_FILE) >> sc->priority) {
  1793. scan_balance = SCAN_FILE;
  1794. goto out;
  1795. }
  1796. scan_balance = SCAN_FRACT;
  1797. /*
  1798. * With swappiness at 100, anonymous and file have the same priority.
  1799. * This scanning priority is essentially the inverse of IO cost.
  1800. */
  1801. anon_prio = swappiness;
  1802. file_prio = 200 - anon_prio;
  1803. /*
  1804. * OK, so we have swap space and a fair amount of page cache
  1805. * pages. We use the recently rotated / recently scanned
  1806. * ratios to determine how valuable each cache is.
  1807. *
  1808. * Because workloads change over time (and to avoid overflow)
  1809. * we keep these statistics as a floating average, which ends
  1810. * up weighing recent references more than old ones.
  1811. *
  1812. * anon in [0], file in [1]
  1813. */
  1814. anon = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON) +
  1815. lruvec_lru_size(lruvec, LRU_INACTIVE_ANON);
  1816. file = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE) +
  1817. lruvec_lru_size(lruvec, LRU_INACTIVE_FILE);
  1818. spin_lock_irq(&zone->lru_lock);
  1819. if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
  1820. reclaim_stat->recent_scanned[0] /= 2;
  1821. reclaim_stat->recent_rotated[0] /= 2;
  1822. }
  1823. if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
  1824. reclaim_stat->recent_scanned[1] /= 2;
  1825. reclaim_stat->recent_rotated[1] /= 2;
  1826. }
  1827. /*
  1828. * The amount of pressure on anon vs file pages is inversely
  1829. * proportional to the fraction of recently scanned pages on
  1830. * each list that were recently referenced and in active use.
  1831. */
  1832. ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
  1833. ap /= reclaim_stat->recent_rotated[0] + 1;
  1834. fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
  1835. fp /= reclaim_stat->recent_rotated[1] + 1;
  1836. spin_unlock_irq(&zone->lru_lock);
  1837. fraction[0] = ap;
  1838. fraction[1] = fp;
  1839. denominator = ap + fp + 1;
  1840. out:
  1841. some_scanned = false;
  1842. /* Only use force_scan on second pass. */
  1843. for (pass = 0; !some_scanned && pass < 2; pass++) {
  1844. *lru_pages = 0;
  1845. for_each_evictable_lru(lru) {
  1846. int file = is_file_lru(lru);
  1847. unsigned long size;
  1848. unsigned long scan;
  1849. size = lruvec_lru_size(lruvec, lru);
  1850. scan = size >> sc->priority;
  1851. if (!scan && pass && force_scan)
  1852. scan = min(size, SWAP_CLUSTER_MAX);
  1853. switch (scan_balance) {
  1854. case SCAN_EQUAL:
  1855. /* Scan lists relative to size */
  1856. break;
  1857. case SCAN_FRACT:
  1858. /*
  1859. * Scan types proportional to swappiness and
  1860. * their relative recent reclaim efficiency.
  1861. */
  1862. scan = div64_u64(scan * fraction[file],
  1863. denominator);
  1864. break;
  1865. case SCAN_FILE:
  1866. case SCAN_ANON:
  1867. /* Scan one type exclusively */
  1868. if ((scan_balance == SCAN_FILE) != file) {
  1869. size = 0;
  1870. scan = 0;
  1871. }
  1872. break;
  1873. default:
  1874. /* Look ma, no brain */
  1875. BUG();
  1876. }
  1877. *lru_pages += size;
  1878. nr[lru] = scan;
  1879. /*
  1880. * Skip the second pass and don't force_scan,
  1881. * if we found something to scan.
  1882. */
  1883. some_scanned |= !!scan;
  1884. }
  1885. }
  1886. }
  1887. #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
  1888. static void init_tlb_ubc(void)
  1889. {
  1890. /*
  1891. * This deliberately does not clear the cpumask as it's expensive
  1892. * and unnecessary. If there happens to be data in there then the
  1893. * first SWAP_CLUSTER_MAX pages will send an unnecessary IPI and
  1894. * then will be cleared.
  1895. */
  1896. current->tlb_ubc.flush_required = false;
  1897. }
  1898. #else
  1899. static inline void init_tlb_ubc(void)
  1900. {
  1901. }
  1902. #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
  1903. /*
  1904. * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
  1905. */
  1906. static void shrink_zone_memcg(struct zone *zone, struct mem_cgroup *memcg,
  1907. struct scan_control *sc, unsigned long *lru_pages)
  1908. {
  1909. struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
  1910. unsigned long nr[NR_LRU_LISTS];
  1911. unsigned long targets[NR_LRU_LISTS];
  1912. unsigned long nr_to_scan;
  1913. enum lru_list lru;
  1914. unsigned long nr_reclaimed = 0;
  1915. unsigned long nr_to_reclaim = sc->nr_to_reclaim;
  1916. struct blk_plug plug;
  1917. bool scan_adjusted;
  1918. get_scan_count(lruvec, memcg, sc, nr, lru_pages);
  1919. /* Record the original scan target for proportional adjustments later */
  1920. memcpy(targets, nr, sizeof(nr));
  1921. /*
  1922. * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
  1923. * event that can occur when there is little memory pressure e.g.
  1924. * multiple streaming readers/writers. Hence, we do not abort scanning
  1925. * when the requested number of pages are reclaimed when scanning at
  1926. * DEF_PRIORITY on the assumption that the fact we are direct
  1927. * reclaiming implies that kswapd is not keeping up and it is best to
  1928. * do a batch of work at once. For memcg reclaim one check is made to
  1929. * abort proportional reclaim if either the file or anon lru has already
  1930. * dropped to zero at the first pass.
  1931. */
  1932. scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
  1933. sc->priority == DEF_PRIORITY);
  1934. init_tlb_ubc();
  1935. blk_start_plug(&plug);
  1936. while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
  1937. nr[LRU_INACTIVE_FILE]) {
  1938. unsigned long nr_anon, nr_file, percentage;
  1939. unsigned long nr_scanned;
  1940. for_each_evictable_lru(lru) {
  1941. if (nr[lru]) {
  1942. nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
  1943. nr[lru] -= nr_to_scan;
  1944. nr_reclaimed += shrink_list(lru, nr_to_scan,
  1945. lruvec, sc);
  1946. }
  1947. }
  1948. if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
  1949. continue;
  1950. /*
  1951. * For kswapd and memcg, reclaim at least the number of pages
  1952. * requested. Ensure that the anon and file LRUs are scanned
  1953. * proportionally what was requested by get_scan_count(). We
  1954. * stop reclaiming one LRU and reduce the amount scanning
  1955. * proportional to the original scan target.
  1956. */
  1957. nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
  1958. nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
  1959. /*
  1960. * It's just vindictive to attack the larger once the smaller
  1961. * has gone to zero. And given the way we stop scanning the
  1962. * smaller below, this makes sure that we only make one nudge
  1963. * towards proportionality once we've got nr_to_reclaim.
  1964. */
  1965. if (!nr_file || !nr_anon)
  1966. break;
  1967. if (nr_file > nr_anon) {
  1968. unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
  1969. targets[LRU_ACTIVE_ANON] + 1;
  1970. lru = LRU_BASE;
  1971. percentage = nr_anon * 100 / scan_target;
  1972. } else {
  1973. unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
  1974. targets[LRU_ACTIVE_FILE] + 1;
  1975. lru = LRU_FILE;
  1976. percentage = nr_file * 100 / scan_target;
  1977. }
  1978. /* Stop scanning the smaller of the LRU */
  1979. nr[lru] = 0;
  1980. nr[lru + LRU_ACTIVE] = 0;
  1981. /*
  1982. * Recalculate the other LRU scan count based on its original
  1983. * scan target and the percentage scanning already complete
  1984. */
  1985. lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
  1986. nr_scanned = targets[lru] - nr[lru];
  1987. nr[lru] = targets[lru] * (100 - percentage) / 100;
  1988. nr[lru] -= min(nr[lru], nr_scanned);
  1989. lru += LRU_ACTIVE;
  1990. nr_scanned = targets[lru] - nr[lru];
  1991. nr[lru] = targets[lru] * (100 - percentage) / 100;
  1992. nr[lru] -= min(nr[lru], nr_scanned);
  1993. scan_adjusted = true;
  1994. }
  1995. blk_finish_plug(&plug);
  1996. sc->nr_reclaimed += nr_reclaimed;
  1997. /*
  1998. * Even if we did not try to evict anon pages at all, we want to
  1999. * rebalance the anon lru active/inactive ratio.
  2000. */
  2001. if (inactive_list_is_low(lruvec, false))
  2002. shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
  2003. sc, LRU_ACTIVE_ANON);
  2004. throttle_vm_writeout(sc->gfp_mask);
  2005. }
  2006. /* Use reclaim/compaction for costly allocs or under memory pressure */
  2007. static bool in_reclaim_compaction(struct scan_control *sc)
  2008. {
  2009. if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
  2010. (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
  2011. sc->priority < DEF_PRIORITY - 2))
  2012. return true;
  2013. return false;
  2014. }
  2015. /*
  2016. * Reclaim/compaction is used for high-order allocation requests. It reclaims
  2017. * order-0 pages before compacting the zone. should_continue_reclaim() returns
  2018. * true if more pages should be reclaimed such that when the page allocator
  2019. * calls try_to_compact_zone() that it will have enough free pages to succeed.
  2020. * It will give up earlier than that if there is difficulty reclaiming pages.
  2021. */
  2022. static inline bool should_continue_reclaim(struct zone *zone,
  2023. unsigned long nr_reclaimed,
  2024. unsigned long nr_scanned,
  2025. struct scan_control *sc)
  2026. {
  2027. unsigned long pages_for_compaction;
  2028. unsigned long inactive_lru_pages;
  2029. /* If not in reclaim/compaction mode, stop */
  2030. if (!in_reclaim_compaction(sc))
  2031. return false;
  2032. /* Consider stopping depending on scan and reclaim activity */
  2033. if (sc->gfp_mask & __GFP_REPEAT) {
  2034. /*
  2035. * For __GFP_REPEAT allocations, stop reclaiming if the
  2036. * full LRU list has been scanned and we are still failing
  2037. * to reclaim pages. This full LRU scan is potentially
  2038. * expensive but a __GFP_REPEAT caller really wants to succeed
  2039. */
  2040. if (!nr_reclaimed && !nr_scanned)
  2041. return false;
  2042. } else {
  2043. /*
  2044. * For non-__GFP_REPEAT allocations which can presumably
  2045. * fail without consequence, stop if we failed to reclaim
  2046. * any pages from the last SWAP_CLUSTER_MAX number of
  2047. * pages that were scanned. This will return to the
  2048. * caller faster at the risk reclaim/compaction and
  2049. * the resulting allocation attempt fails
  2050. */
  2051. if (!nr_reclaimed)
  2052. return false;
  2053. }
  2054. /*
  2055. * If we have not reclaimed enough pages for compaction and the
  2056. * inactive lists are large enough, continue reclaiming
  2057. */
  2058. pages_for_compaction = (2UL << sc->order);
  2059. inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
  2060. if (get_nr_swap_pages() > 0)
  2061. inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
  2062. if (sc->nr_reclaimed < pages_for_compaction &&
  2063. inactive_lru_pages > pages_for_compaction)
  2064. return true;
  2065. /* If compaction would go ahead or the allocation would succeed, stop */
  2066. switch (compaction_suitable(zone, sc->order, 0, 0)) {
  2067. case COMPACT_PARTIAL:
  2068. case COMPACT_CONTINUE:
  2069. return false;
  2070. default:
  2071. return true;
  2072. }
  2073. }
  2074. static bool shrink_zone(struct zone *zone, struct scan_control *sc,
  2075. bool is_classzone)
  2076. {
  2077. struct reclaim_state *reclaim_state = current->reclaim_state;
  2078. unsigned long nr_reclaimed, nr_scanned;
  2079. bool reclaimable = false;
  2080. do {
  2081. struct mem_cgroup *root = sc->target_mem_cgroup;
  2082. struct mem_cgroup_reclaim_cookie reclaim = {
  2083. .zone = zone,
  2084. .priority = sc->priority,
  2085. };
  2086. unsigned long zone_lru_pages = 0;
  2087. struct mem_cgroup *memcg;
  2088. nr_reclaimed = sc->nr_reclaimed;
  2089. nr_scanned = sc->nr_scanned;
  2090. memcg = mem_cgroup_iter(root, NULL, &reclaim);
  2091. do {
  2092. unsigned long lru_pages;
  2093. unsigned long reclaimed;
  2094. unsigned long scanned;
  2095. if (mem_cgroup_low(root, memcg)) {
  2096. if (!sc->may_thrash)
  2097. continue;
  2098. mem_cgroup_events(memcg, MEMCG_LOW, 1);
  2099. }
  2100. reclaimed = sc->nr_reclaimed;
  2101. scanned = sc->nr_scanned;
  2102. shrink_zone_memcg(zone, memcg, sc, &lru_pages);
  2103. zone_lru_pages += lru_pages;
  2104. if (memcg && is_classzone)
  2105. shrink_slab(sc->gfp_mask, zone_to_nid(zone),
  2106. memcg, sc->nr_scanned - scanned,
  2107. lru_pages);
  2108. /* Record the group's reclaim efficiency */
  2109. vmpressure(sc->gfp_mask, memcg, false,
  2110. sc->nr_scanned - scanned,
  2111. sc->nr_reclaimed - reclaimed);
  2112. /*
  2113. * Direct reclaim and kswapd have to scan all memory
  2114. * cgroups to fulfill the overall scan target for the
  2115. * zone.
  2116. *
  2117. * Limit reclaim, on the other hand, only cares about
  2118. * nr_to_reclaim pages to be reclaimed and it will
  2119. * retry with decreasing priority if one round over the
  2120. * whole hierarchy is not sufficient.
  2121. */
  2122. if (!global_reclaim(sc) &&
  2123. sc->nr_reclaimed >= sc->nr_to_reclaim) {
  2124. mem_cgroup_iter_break(root, memcg);
  2125. break;
  2126. }
  2127. } while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
  2128. /*
  2129. * Shrink the slab caches in the same proportion that
  2130. * the eligible LRU pages were scanned.
  2131. */
  2132. if (global_reclaim(sc) && is_classzone)
  2133. shrink_slab(sc->gfp_mask, zone_to_nid(zone), NULL,
  2134. sc->nr_scanned - nr_scanned,
  2135. zone_lru_pages);
  2136. if (reclaim_state) {
  2137. sc->nr_reclaimed += reclaim_state->reclaimed_slab;
  2138. reclaim_state->reclaimed_slab = 0;
  2139. }
  2140. /* Record the subtree's reclaim efficiency */
  2141. vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
  2142. sc->nr_scanned - nr_scanned,
  2143. sc->nr_reclaimed - nr_reclaimed);
  2144. if (sc->nr_reclaimed - nr_reclaimed)
  2145. reclaimable = true;
  2146. } while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
  2147. sc->nr_scanned - nr_scanned, sc));
  2148. return reclaimable;
  2149. }
  2150. /*
  2151. * Returns true if compaction should go ahead for a high-order request, or
  2152. * the high-order allocation would succeed without compaction.
  2153. */
  2154. static inline bool compaction_ready(struct zone *zone, int order)
  2155. {
  2156. unsigned long balance_gap, watermark;
  2157. bool watermark_ok;
  2158. /*
  2159. * Compaction takes time to run and there are potentially other
  2160. * callers using the pages just freed. Continue reclaiming until
  2161. * there is a buffer of free pages available to give compaction
  2162. * a reasonable chance of completing and allocating the page
  2163. */
  2164. balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
  2165. zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
  2166. watermark = high_wmark_pages(zone) + balance_gap + (2UL << order);
  2167. watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0);
  2168. /*
  2169. * If compaction is deferred, reclaim up to a point where
  2170. * compaction will have a chance of success when re-enabled
  2171. */
  2172. if (compaction_deferred(zone, order))
  2173. return watermark_ok;
  2174. /*
  2175. * If compaction is not ready to start and allocation is not likely
  2176. * to succeed without it, then keep reclaiming.
  2177. */
  2178. if (compaction_suitable(zone, order, 0, 0) == COMPACT_SKIPPED)
  2179. return false;
  2180. return watermark_ok;
  2181. }
  2182. /*
  2183. * This is the direct reclaim path, for page-allocating processes. We only
  2184. * try to reclaim pages from zones which will satisfy the caller's allocation
  2185. * request.
  2186. *
  2187. * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
  2188. * Because:
  2189. * a) The caller may be trying to free *extra* pages to satisfy a higher-order
  2190. * allocation or
  2191. * b) The target zone may be at high_wmark_pages(zone) but the lower zones
  2192. * must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
  2193. * zone defense algorithm.
  2194. *
  2195. * If a zone is deemed to be full of pinned pages then just give it a light
  2196. * scan then give up on it.
  2197. *
  2198. * Returns true if a zone was reclaimable.
  2199. */
  2200. static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
  2201. {
  2202. struct zoneref *z;
  2203. struct zone *zone;
  2204. unsigned long nr_soft_reclaimed;
  2205. unsigned long nr_soft_scanned;
  2206. gfp_t orig_mask;
  2207. enum zone_type requested_highidx = gfp_zone(sc->gfp_mask);
  2208. bool reclaimable = false;
  2209. /*
  2210. * If the number of buffer_heads in the machine exceeds the maximum
  2211. * allowed level, force direct reclaim to scan the highmem zone as
  2212. * highmem pages could be pinning lowmem pages storing buffer_heads
  2213. */
  2214. orig_mask = sc->gfp_mask;
  2215. if (buffer_heads_over_limit)
  2216. sc->gfp_mask |= __GFP_HIGHMEM;
  2217. for_each_zone_zonelist_nodemask(zone, z, zonelist,
  2218. gfp_zone(sc->gfp_mask), sc->nodemask) {
  2219. enum zone_type classzone_idx;
  2220. if (!populated_zone(zone))
  2221. continue;
  2222. classzone_idx = requested_highidx;
  2223. while (!populated_zone(zone->zone_pgdat->node_zones +
  2224. classzone_idx))
  2225. classzone_idx--;
  2226. /*
  2227. * Take care memory controller reclaiming has small influence
  2228. * to global LRU.
  2229. */
  2230. if (global_reclaim(sc)) {
  2231. if (!cpuset_zone_allowed(zone,
  2232. GFP_KERNEL | __GFP_HARDWALL))
  2233. continue;
  2234. if (sc->priority != DEF_PRIORITY &&
  2235. !zone_reclaimable(zone))
  2236. continue; /* Let kswapd poll it */
  2237. /*
  2238. * If we already have plenty of memory free for
  2239. * compaction in this zone, don't free any more.
  2240. * Even though compaction is invoked for any
  2241. * non-zero order, only frequent costly order
  2242. * reclamation is disruptive enough to become a
  2243. * noticeable problem, like transparent huge
  2244. * page allocations.
  2245. */
  2246. if (IS_ENABLED(CONFIG_COMPACTION) &&
  2247. sc->order > PAGE_ALLOC_COSTLY_ORDER &&
  2248. zonelist_zone_idx(z) <= requested_highidx &&
  2249. compaction_ready(zone, sc->order)) {
  2250. sc->compaction_ready = true;
  2251. continue;
  2252. }
  2253. /*
  2254. * This steals pages from memory cgroups over softlimit
  2255. * and returns the number of reclaimed pages and
  2256. * scanned pages. This works for global memory pressure
  2257. * and balancing, not for a memcg's limit.
  2258. */
  2259. nr_soft_scanned = 0;
  2260. nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
  2261. sc->order, sc->gfp_mask,
  2262. &nr_soft_scanned);
  2263. sc->nr_reclaimed += nr_soft_reclaimed;
  2264. sc->nr_scanned += nr_soft_scanned;
  2265. if (nr_soft_reclaimed)
  2266. reclaimable = true;
  2267. /* need some check for avoid more shrink_zone() */
  2268. }
  2269. if (shrink_zone(zone, sc, zone_idx(zone) == classzone_idx))
  2270. reclaimable = true;
  2271. if (global_reclaim(sc) &&
  2272. !reclaimable && zone_reclaimable(zone))
  2273. reclaimable = true;
  2274. }
  2275. /*
  2276. * Restore to original mask to avoid the impact on the caller if we
  2277. * promoted it to __GFP_HIGHMEM.
  2278. */
  2279. sc->gfp_mask = orig_mask;
  2280. return reclaimable;
  2281. }
  2282. /*
  2283. * This is the main entry point to direct page reclaim.
  2284. *
  2285. * If a full scan of the inactive list fails to free enough memory then we
  2286. * are "out of memory" and something needs to be killed.
  2287. *
  2288. * If the caller is !__GFP_FS then the probability of a failure is reasonably
  2289. * high - the zone may be full of dirty or under-writeback pages, which this
  2290. * caller can't do much about. We kick the writeback threads and take explicit
  2291. * naps in the hope that some of these pages can be written. But if the
  2292. * allocating task holds filesystem locks which prevent writeout this might not
  2293. * work, and the allocation attempt will fail.
  2294. *
  2295. * returns: 0, if no pages reclaimed
  2296. * else, the number of pages reclaimed
  2297. */
  2298. static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
  2299. struct scan_control *sc)
  2300. {
  2301. int initial_priority = sc->priority;
  2302. unsigned long total_scanned = 0;
  2303. unsigned long writeback_threshold;
  2304. bool zones_reclaimable;
  2305. retry:
  2306. delayacct_freepages_start();
  2307. if (global_reclaim(sc))
  2308. count_vm_event(ALLOCSTALL);
  2309. do {
  2310. vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
  2311. sc->priority);
  2312. sc->nr_scanned = 0;
  2313. zones_reclaimable = shrink_zones(zonelist, sc);
  2314. total_scanned += sc->nr_scanned;
  2315. if (sc->nr_reclaimed >= sc->nr_to_reclaim)
  2316. break;
  2317. if (sc->compaction_ready)
  2318. break;
  2319. /*
  2320. * If we're getting trouble reclaiming, start doing
  2321. * writepage even in laptop mode.
  2322. */
  2323. if (sc->priority < DEF_PRIORITY - 2)
  2324. sc->may_writepage = 1;
  2325. /*
  2326. * Try to write back as many pages as we just scanned. This
  2327. * tends to cause slow streaming writers to write data to the
  2328. * disk smoothly, at the dirtying rate, which is nice. But
  2329. * that's undesirable in laptop mode, where we *want* lumpy
  2330. * writeout. So in laptop mode, write out the whole world.
  2331. */
  2332. writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
  2333. if (total_scanned > writeback_threshold) {
  2334. wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
  2335. WB_REASON_TRY_TO_FREE_PAGES);
  2336. sc->may_writepage = 1;
  2337. }
  2338. } while (--sc->priority >= 0);
  2339. delayacct_freepages_end();
  2340. if (sc->nr_reclaimed)
  2341. return sc->nr_reclaimed;
  2342. /* Aborted reclaim to try compaction? don't OOM, then */
  2343. if (sc->compaction_ready)
  2344. return 1;
  2345. /* Untapped cgroup reserves? Don't OOM, retry. */
  2346. if (!sc->may_thrash) {
  2347. sc->priority = initial_priority;
  2348. sc->may_thrash = 1;
  2349. goto retry;
  2350. }
  2351. /* Any of the zones still reclaimable? Don't OOM. */
  2352. if (zones_reclaimable)
  2353. return 1;
  2354. return 0;
  2355. }
  2356. static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
  2357. {
  2358. struct zone *zone;
  2359. unsigned long pfmemalloc_reserve = 0;
  2360. unsigned long free_pages = 0;
  2361. int i;
  2362. bool wmark_ok;
  2363. for (i = 0; i <= ZONE_NORMAL; i++) {
  2364. zone = &pgdat->node_zones[i];
  2365. if (!populated_zone(zone) ||
  2366. zone_reclaimable_pages(zone) == 0)
  2367. continue;
  2368. pfmemalloc_reserve += min_wmark_pages(zone);
  2369. free_pages += zone_page_state(zone, NR_FREE_PAGES);
  2370. }
  2371. /* If there are no reserves (unexpected config) then do not throttle */
  2372. if (!pfmemalloc_reserve)
  2373. return true;
  2374. wmark_ok = free_pages > pfmemalloc_reserve / 2;
  2375. /* kswapd must be awake if processes are being throttled */
  2376. if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
  2377. pgdat->classzone_idx = min(pgdat->classzone_idx,
  2378. (enum zone_type)ZONE_NORMAL);
  2379. wake_up_interruptible(&pgdat->kswapd_wait);
  2380. }
  2381. return wmark_ok;
  2382. }
  2383. /*
  2384. * Throttle direct reclaimers if backing storage is backed by the network
  2385. * and the PFMEMALLOC reserve for the preferred node is getting dangerously
  2386. * depleted. kswapd will continue to make progress and wake the processes
  2387. * when the low watermark is reached.
  2388. *
  2389. * Returns true if a fatal signal was delivered during throttling. If this
  2390. * happens, the page allocator should not consider triggering the OOM killer.
  2391. */
  2392. static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
  2393. nodemask_t *nodemask)
  2394. {
  2395. struct zoneref *z;
  2396. struct zone *zone;
  2397. pg_data_t *pgdat = NULL;
  2398. /*
  2399. * Kernel threads should not be throttled as they may be indirectly
  2400. * responsible for cleaning pages necessary for reclaim to make forward
  2401. * progress. kjournald for example may enter direct reclaim while
  2402. * committing a transaction where throttling it could forcing other
  2403. * processes to block on log_wait_commit().
  2404. */
  2405. if (current->flags & PF_KTHREAD)
  2406. goto out;
  2407. /*
  2408. * If a fatal signal is pending, this process should not throttle.
  2409. * It should return quickly so it can exit and free its memory
  2410. */
  2411. if (fatal_signal_pending(current))
  2412. goto out;
  2413. /*
  2414. * Check if the pfmemalloc reserves are ok by finding the first node
  2415. * with a usable ZONE_NORMAL or lower zone. The expectation is that
  2416. * GFP_KERNEL will be required for allocating network buffers when
  2417. * swapping over the network so ZONE_HIGHMEM is unusable.
  2418. *
  2419. * Throttling is based on the first usable node and throttled processes
  2420. * wait on a queue until kswapd makes progress and wakes them. There
  2421. * is an affinity then between processes waking up and where reclaim
  2422. * progress has been made assuming the process wakes on the same node.
  2423. * More importantly, processes running on remote nodes will not compete
  2424. * for remote pfmemalloc reserves and processes on different nodes
  2425. * should make reasonable progress.
  2426. */
  2427. for_each_zone_zonelist_nodemask(zone, z, zonelist,
  2428. gfp_zone(gfp_mask), nodemask) {
  2429. if (zone_idx(zone) > ZONE_NORMAL)
  2430. continue;
  2431. /* Throttle based on the first usable node */
  2432. pgdat = zone->zone_pgdat;
  2433. if (pfmemalloc_watermark_ok(pgdat))
  2434. goto out;
  2435. break;
  2436. }
  2437. /* If no zone was usable by the allocation flags then do not throttle */
  2438. if (!pgdat)
  2439. goto out;
  2440. /* Account for the throttling */
  2441. count_vm_event(PGSCAN_DIRECT_THROTTLE);
  2442. /*
  2443. * If the caller cannot enter the filesystem, it's possible that it
  2444. * is due to the caller holding an FS lock or performing a journal
  2445. * transaction in the case of a filesystem like ext[3|4]. In this case,
  2446. * it is not safe to block on pfmemalloc_wait as kswapd could be
  2447. * blocked waiting on the same lock. Instead, throttle for up to a
  2448. * second before continuing.
  2449. */
  2450. if (!(gfp_mask & __GFP_FS)) {
  2451. wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
  2452. pfmemalloc_watermark_ok(pgdat), HZ);
  2453. goto check_pending;
  2454. }
  2455. /* Throttle until kswapd wakes the process */
  2456. wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
  2457. pfmemalloc_watermark_ok(pgdat));
  2458. check_pending:
  2459. if (fatal_signal_pending(current))
  2460. return true;
  2461. out:
  2462. return false;
  2463. }
  2464. unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
  2465. gfp_t gfp_mask, nodemask_t *nodemask)
  2466. {
  2467. unsigned long nr_reclaimed;
  2468. struct scan_control sc = {
  2469. .nr_to_reclaim = SWAP_CLUSTER_MAX,
  2470. .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
  2471. .order = order,
  2472. .nodemask = nodemask,
  2473. .priority = DEF_PRIORITY,
  2474. .may_writepage = !laptop_mode,
  2475. .may_unmap = 1,
  2476. .may_swap = 1,
  2477. };
  2478. /*
  2479. * Do not enter reclaim if fatal signal was delivered while throttled.
  2480. * 1 is returned so that the page allocator does not OOM kill at this
  2481. * point.
  2482. */
  2483. if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
  2484. return 1;
  2485. trace_mm_vmscan_direct_reclaim_begin(order,
  2486. sc.may_writepage,
  2487. gfp_mask);
  2488. nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
  2489. trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
  2490. return nr_reclaimed;
  2491. }
  2492. #ifdef CONFIG_MEMCG
  2493. unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
  2494. gfp_t gfp_mask, bool noswap,
  2495. struct zone *zone,
  2496. unsigned long *nr_scanned)
  2497. {
  2498. struct scan_control sc = {
  2499. .nr_to_reclaim = SWAP_CLUSTER_MAX,
  2500. .target_mem_cgroup = memcg,
  2501. .may_writepage = !laptop_mode,
  2502. .may_unmap = 1,
  2503. .may_swap = !noswap,
  2504. };
  2505. unsigned long lru_pages;
  2506. sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
  2507. (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
  2508. trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
  2509. sc.may_writepage,
  2510. sc.gfp_mask);
  2511. /*
  2512. * NOTE: Although we can get the priority field, using it
  2513. * here is not a good idea, since it limits the pages we can scan.
  2514. * if we don't reclaim here, the shrink_zone from balance_pgdat
  2515. * will pick up pages from other mem cgroup's as well. We hack
  2516. * the priority and make it zero.
  2517. */
  2518. shrink_zone_memcg(zone, memcg, &sc, &lru_pages);
  2519. trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
  2520. *nr_scanned = sc.nr_scanned;
  2521. return sc.nr_reclaimed;
  2522. }
  2523. unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
  2524. unsigned long nr_pages,
  2525. gfp_t gfp_mask,
  2526. bool may_swap)
  2527. {
  2528. struct zonelist *zonelist;
  2529. unsigned long nr_reclaimed;
  2530. int nid;
  2531. struct scan_control sc = {
  2532. .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
  2533. .gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
  2534. (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
  2535. .target_mem_cgroup = memcg,
  2536. .priority = DEF_PRIORITY,
  2537. .may_writepage = !laptop_mode,
  2538. .may_unmap = 1,
  2539. .may_swap = may_swap,
  2540. };
  2541. /*
  2542. * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
  2543. * take care of from where we get pages. So the node where we start the
  2544. * scan does not need to be the current node.
  2545. */
  2546. nid = mem_cgroup_select_victim_node(memcg);
  2547. zonelist = NODE_DATA(nid)->node_zonelists;
  2548. trace_mm_vmscan_memcg_reclaim_begin(0,
  2549. sc.may_writepage,
  2550. sc.gfp_mask);
  2551. nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
  2552. trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
  2553. return nr_reclaimed;
  2554. }
  2555. #endif
  2556. static void age_active_anon(struct zone *zone, struct scan_control *sc)
  2557. {
  2558. struct mem_cgroup *memcg;
  2559. if (!total_swap_pages)
  2560. return;
  2561. memcg = mem_cgroup_iter(NULL, NULL, NULL);
  2562. do {
  2563. struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
  2564. if (inactive_list_is_low(lruvec, false))
  2565. shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
  2566. sc, LRU_ACTIVE_ANON);
  2567. memcg = mem_cgroup_iter(NULL, memcg, NULL);
  2568. } while (memcg);
  2569. }
  2570. static bool zone_balanced(struct zone *zone, int order, bool highorder,
  2571. unsigned long balance_gap, int classzone_idx)
  2572. {
  2573. unsigned long mark = high_wmark_pages(zone) + balance_gap;
  2574. /*
  2575. * When checking from pgdat_balanced(), kswapd should stop and sleep
  2576. * when it reaches the high order-0 watermark and let kcompactd take
  2577. * over. Other callers such as wakeup_kswapd() want to determine the
  2578. * true high-order watermark.
  2579. */
  2580. if (IS_ENABLED(CONFIG_COMPACTION) && !highorder) {
  2581. mark += (1UL << order);
  2582. order = 0;
  2583. }
  2584. return zone_watermark_ok_safe(zone, order, mark, classzone_idx);
  2585. }
  2586. /*
  2587. * pgdat_balanced() is used when checking if a node is balanced.
  2588. *
  2589. * For order-0, all zones must be balanced!
  2590. *
  2591. * For high-order allocations only zones that meet watermarks and are in a
  2592. * zone allowed by the callers classzone_idx are added to balanced_pages. The
  2593. * total of balanced pages must be at least 25% of the zones allowed by
  2594. * classzone_idx for the node to be considered balanced. Forcing all zones to
  2595. * be balanced for high orders can cause excessive reclaim when there are
  2596. * imbalanced zones.
  2597. * The choice of 25% is due to
  2598. * o a 16M DMA zone that is balanced will not balance a zone on any
  2599. * reasonable sized machine
  2600. * o On all other machines, the top zone must be at least a reasonable
  2601. * percentage of the middle zones. For example, on 32-bit x86, highmem
  2602. * would need to be at least 256M for it to be balance a whole node.
  2603. * Similarly, on x86-64 the Normal zone would need to be at least 1G
  2604. * to balance a node on its own. These seemed like reasonable ratios.
  2605. */
  2606. static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
  2607. {
  2608. unsigned long managed_pages = 0;
  2609. unsigned long balanced_pages = 0;
  2610. int i;
  2611. /* Check the watermark levels */
  2612. for (i = 0; i <= classzone_idx; i++) {
  2613. struct zone *zone = pgdat->node_zones + i;
  2614. if (!populated_zone(zone))
  2615. continue;
  2616. managed_pages += zone->managed_pages;
  2617. /*
  2618. * A special case here:
  2619. *
  2620. * balance_pgdat() skips over all_unreclaimable after
  2621. * DEF_PRIORITY. Effectively, it considers them balanced so
  2622. * they must be considered balanced here as well!
  2623. */
  2624. if (!zone_reclaimable(zone)) {
  2625. balanced_pages += zone->managed_pages;
  2626. continue;
  2627. }
  2628. if (zone_balanced(zone, order, false, 0, i))
  2629. balanced_pages += zone->managed_pages;
  2630. else if (!order)
  2631. return false;
  2632. }
  2633. if (order)
  2634. return balanced_pages >= (managed_pages >> 2);
  2635. else
  2636. return true;
  2637. }
  2638. /*
  2639. * Prepare kswapd for sleeping. This verifies that there are no processes
  2640. * waiting in throttle_direct_reclaim() and that watermarks have been met.
  2641. *
  2642. * Returns true if kswapd is ready to sleep
  2643. */
  2644. static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
  2645. int classzone_idx)
  2646. {
  2647. /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
  2648. if (remaining)
  2649. return false;
  2650. /*
  2651. * The throttled processes are normally woken up in balance_pgdat() as
  2652. * soon as pfmemalloc_watermark_ok() is true. But there is a potential
  2653. * race between when kswapd checks the watermarks and a process gets
  2654. * throttled. There is also a potential race if processes get
  2655. * throttled, kswapd wakes, a large process exits thereby balancing the
  2656. * zones, which causes kswapd to exit balance_pgdat() before reaching
  2657. * the wake up checks. If kswapd is going to sleep, no process should
  2658. * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
  2659. * the wake up is premature, processes will wake kswapd and get
  2660. * throttled again. The difference from wake ups in balance_pgdat() is
  2661. * that here we are under prepare_to_wait().
  2662. */
  2663. if (waitqueue_active(&pgdat->pfmemalloc_wait))
  2664. wake_up_all(&pgdat->pfmemalloc_wait);
  2665. return pgdat_balanced(pgdat, order, classzone_idx);
  2666. }
  2667. /*
  2668. * kswapd shrinks the zone by the number of pages required to reach
  2669. * the high watermark.
  2670. *
  2671. * Returns true if kswapd scanned at least the requested number of pages to
  2672. * reclaim or if the lack of progress was due to pages under writeback.
  2673. * This is used to determine if the scanning priority needs to be raised.
  2674. */
  2675. static bool kswapd_shrink_zone(struct zone *zone,
  2676. int classzone_idx,
  2677. struct scan_control *sc)
  2678. {
  2679. unsigned long balance_gap;
  2680. bool lowmem_pressure;
  2681. /* Reclaim above the high watermark. */
  2682. sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
  2683. /*
  2684. * We put equal pressure on every zone, unless one zone has way too
  2685. * many pages free already. The "too many pages" is defined as the
  2686. * high wmark plus a "gap" where the gap is either the low
  2687. * watermark or 1% of the zone, whichever is smaller.
  2688. */
  2689. balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
  2690. zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
  2691. /*
  2692. * If there is no low memory pressure or the zone is balanced then no
  2693. * reclaim is necessary
  2694. */
  2695. lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
  2696. if (!lowmem_pressure && zone_balanced(zone, sc->order, false,
  2697. balance_gap, classzone_idx))
  2698. return true;
  2699. shrink_zone(zone, sc, zone_idx(zone) == classzone_idx);
  2700. clear_bit(ZONE_WRITEBACK, &zone->flags);
  2701. /*
  2702. * If a zone reaches its high watermark, consider it to be no longer
  2703. * congested. It's possible there are dirty pages backed by congested
  2704. * BDIs but as pressure is relieved, speculatively avoid congestion
  2705. * waits.
  2706. */
  2707. if (zone_reclaimable(zone) &&
  2708. zone_balanced(zone, sc->order, false, 0, classzone_idx)) {
  2709. clear_bit(ZONE_CONGESTED, &zone->flags);
  2710. clear_bit(ZONE_DIRTY, &zone->flags);
  2711. }
  2712. return sc->nr_scanned >= sc->nr_to_reclaim;
  2713. }
  2714. /*
  2715. * For kswapd, balance_pgdat() will work across all this node's zones until
  2716. * they are all at high_wmark_pages(zone).
  2717. *
  2718. * Returns the highest zone idx kswapd was reclaiming at
  2719. *
  2720. * There is special handling here for zones which are full of pinned pages.
  2721. * This can happen if the pages are all mlocked, or if they are all used by
  2722. * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
  2723. * What we do is to detect the case where all pages in the zone have been
  2724. * scanned twice and there has been zero successful reclaim. Mark the zone as
  2725. * dead and from now on, only perform a short scan. Basically we're polling
  2726. * the zone for when the problem goes away.
  2727. *
  2728. * kswapd scans the zones in the highmem->normal->dma direction. It skips
  2729. * zones which have free_pages > high_wmark_pages(zone), but once a zone is
  2730. * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
  2731. * lower zones regardless of the number of free pages in the lower zones. This
  2732. * interoperates with the page allocator fallback scheme to ensure that aging
  2733. * of pages is balanced across the zones.
  2734. */
  2735. static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
  2736. {
  2737. int i;
  2738. int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
  2739. unsigned long nr_soft_reclaimed;
  2740. unsigned long nr_soft_scanned;
  2741. struct scan_control sc = {
  2742. .gfp_mask = GFP_KERNEL,
  2743. .order = order,
  2744. .priority = DEF_PRIORITY,
  2745. .may_writepage = !laptop_mode,
  2746. .may_unmap = 1,
  2747. .may_swap = 1,
  2748. };
  2749. count_vm_event(PAGEOUTRUN);
  2750. do {
  2751. bool raise_priority = true;
  2752. sc.nr_reclaimed = 0;
  2753. /*
  2754. * Scan in the highmem->dma direction for the highest
  2755. * zone which needs scanning
  2756. */
  2757. for (i = pgdat->nr_zones - 1; i >= 0; i--) {
  2758. struct zone *zone = pgdat->node_zones + i;
  2759. if (!populated_zone(zone))
  2760. continue;
  2761. if (sc.priority != DEF_PRIORITY &&
  2762. !zone_reclaimable(zone))
  2763. continue;
  2764. /*
  2765. * Do some background aging of the anon list, to give
  2766. * pages a chance to be referenced before reclaiming.
  2767. */
  2768. age_active_anon(zone, &sc);
  2769. /*
  2770. * If the number of buffer_heads in the machine
  2771. * exceeds the maximum allowed level and this node
  2772. * has a highmem zone, force kswapd to reclaim from
  2773. * it to relieve lowmem pressure.
  2774. */
  2775. if (buffer_heads_over_limit && is_highmem_idx(i)) {
  2776. end_zone = i;
  2777. break;
  2778. }
  2779. if (!zone_balanced(zone, order, false, 0, 0)) {
  2780. end_zone = i;
  2781. break;
  2782. } else {
  2783. /*
  2784. * If balanced, clear the dirty and congested
  2785. * flags
  2786. */
  2787. clear_bit(ZONE_CONGESTED, &zone->flags);
  2788. clear_bit(ZONE_DIRTY, &zone->flags);
  2789. }
  2790. }
  2791. if (i < 0)
  2792. goto out;
  2793. /*
  2794. * If we're getting trouble reclaiming, start doing writepage
  2795. * even in laptop mode.
  2796. */
  2797. if (sc.priority < DEF_PRIORITY - 2)
  2798. sc.may_writepage = 1;
  2799. /*
  2800. * Now scan the zone in the dma->highmem direction, stopping
  2801. * at the last zone which needs scanning.
  2802. *
  2803. * We do this because the page allocator works in the opposite
  2804. * direction. This prevents the page allocator from allocating
  2805. * pages behind kswapd's direction of progress, which would
  2806. * cause too much scanning of the lower zones.
  2807. */
  2808. for (i = 0; i <= end_zone; i++) {
  2809. struct zone *zone = pgdat->node_zones + i;
  2810. if (!populated_zone(zone))
  2811. continue;
  2812. if (sc.priority != DEF_PRIORITY &&
  2813. !zone_reclaimable(zone))
  2814. continue;
  2815. sc.nr_scanned = 0;
  2816. nr_soft_scanned = 0;
  2817. /*
  2818. * Call soft limit reclaim before calling shrink_zone.
  2819. */
  2820. nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
  2821. order, sc.gfp_mask,
  2822. &nr_soft_scanned);
  2823. sc.nr_reclaimed += nr_soft_reclaimed;
  2824. /*
  2825. * There should be no need to raise the scanning
  2826. * priority if enough pages are already being scanned
  2827. * that that high watermark would be met at 100%
  2828. * efficiency.
  2829. */
  2830. if (kswapd_shrink_zone(zone, end_zone, &sc))
  2831. raise_priority = false;
  2832. }
  2833. /*
  2834. * If the low watermark is met there is no need for processes
  2835. * to be throttled on pfmemalloc_wait as they should not be
  2836. * able to safely make forward progress. Wake them
  2837. */
  2838. if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
  2839. pfmemalloc_watermark_ok(pgdat))
  2840. wake_up_all(&pgdat->pfmemalloc_wait);
  2841. /* Check if kswapd should be suspending */
  2842. if (try_to_freeze() || kthread_should_stop())
  2843. break;
  2844. /*
  2845. * Raise priority if scanning rate is too low or there was no
  2846. * progress in reclaiming pages
  2847. */
  2848. if (raise_priority || !sc.nr_reclaimed)
  2849. sc.priority--;
  2850. } while (sc.priority >= 1 &&
  2851. !pgdat_balanced(pgdat, order, classzone_idx));
  2852. out:
  2853. /*
  2854. * Return the highest zone idx we were reclaiming at so
  2855. * prepare_kswapd_sleep() makes the same decisions as here.
  2856. */
  2857. return end_zone;
  2858. }
  2859. static void kswapd_try_to_sleep(pg_data_t *pgdat, int order,
  2860. int classzone_idx, int balanced_classzone_idx)
  2861. {
  2862. long remaining = 0;
  2863. DEFINE_WAIT(wait);
  2864. if (freezing(current) || kthread_should_stop())
  2865. return;
  2866. prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
  2867. /* Try to sleep for a short interval */
  2868. if (prepare_kswapd_sleep(pgdat, order, remaining,
  2869. balanced_classzone_idx)) {
  2870. /*
  2871. * Compaction records what page blocks it recently failed to
  2872. * isolate pages from and skips them in the future scanning.
  2873. * When kswapd is going to sleep, it is reasonable to assume
  2874. * that pages and compaction may succeed so reset the cache.
  2875. */
  2876. reset_isolation_suitable(pgdat);
  2877. /*
  2878. * We have freed the memory, now we should compact it to make
  2879. * allocation of the requested order possible.
  2880. */
  2881. wakeup_kcompactd(pgdat, order, classzone_idx);
  2882. remaining = schedule_timeout(HZ/10);
  2883. finish_wait(&pgdat->kswapd_wait, &wait);
  2884. prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
  2885. }
  2886. /*
  2887. * After a short sleep, check if it was a premature sleep. If not, then
  2888. * go fully to sleep until explicitly woken up.
  2889. */
  2890. if (prepare_kswapd_sleep(pgdat, order, remaining,
  2891. balanced_classzone_idx)) {
  2892. trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
  2893. /*
  2894. * vmstat counters are not perfectly accurate and the estimated
  2895. * value for counters such as NR_FREE_PAGES can deviate from the
  2896. * true value by nr_online_cpus * threshold. To avoid the zone
  2897. * watermarks being breached while under pressure, we reduce the
  2898. * per-cpu vmstat threshold while kswapd is awake and restore
  2899. * them before going back to sleep.
  2900. */
  2901. set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
  2902. if (!kthread_should_stop())
  2903. schedule();
  2904. set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
  2905. } else {
  2906. if (remaining)
  2907. count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
  2908. else
  2909. count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
  2910. }
  2911. finish_wait(&pgdat->kswapd_wait, &wait);
  2912. }
  2913. /*
  2914. * The background pageout daemon, started as a kernel thread
  2915. * from the init process.
  2916. *
  2917. * This basically trickles out pages so that we have _some_
  2918. * free memory available even if there is no other activity
  2919. * that frees anything up. This is needed for things like routing
  2920. * etc, where we otherwise might have all activity going on in
  2921. * asynchronous contexts that cannot page things out.
  2922. *
  2923. * If there are applications that are active memory-allocators
  2924. * (most normal use), this basically shouldn't matter.
  2925. */
  2926. static int kswapd(void *p)
  2927. {
  2928. unsigned long order, new_order;
  2929. int classzone_idx, new_classzone_idx;
  2930. int balanced_classzone_idx;
  2931. pg_data_t *pgdat = (pg_data_t*)p;
  2932. struct task_struct *tsk = current;
  2933. struct reclaim_state reclaim_state = {
  2934. .reclaimed_slab = 0,
  2935. };
  2936. const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
  2937. lockdep_set_current_reclaim_state(GFP_KERNEL);
  2938. if (!cpumask_empty(cpumask))
  2939. set_cpus_allowed_ptr(tsk, cpumask);
  2940. current->reclaim_state = &reclaim_state;
  2941. /*
  2942. * Tell the memory management that we're a "memory allocator",
  2943. * and that if we need more memory we should get access to it
  2944. * regardless (see "__alloc_pages()"). "kswapd" should
  2945. * never get caught in the normal page freeing logic.
  2946. *
  2947. * (Kswapd normally doesn't need memory anyway, but sometimes
  2948. * you need a small amount of memory in order to be able to
  2949. * page out something else, and this flag essentially protects
  2950. * us from recursively trying to free more memory as we're
  2951. * trying to free the first piece of memory in the first place).
  2952. */
  2953. tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
  2954. set_freezable();
  2955. order = new_order = 0;
  2956. classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
  2957. balanced_classzone_idx = classzone_idx;
  2958. for ( ; ; ) {
  2959. bool ret;
  2960. /*
  2961. * While we were reclaiming, there might have been another
  2962. * wakeup, so check the values.
  2963. */
  2964. new_order = pgdat->kswapd_max_order;
  2965. new_classzone_idx = pgdat->classzone_idx;
  2966. pgdat->kswapd_max_order = 0;
  2967. pgdat->classzone_idx = pgdat->nr_zones - 1;
  2968. if (order < new_order || classzone_idx > new_classzone_idx) {
  2969. /*
  2970. * Don't sleep if someone wants a larger 'order'
  2971. * allocation or has tigher zone constraints
  2972. */
  2973. order = new_order;
  2974. classzone_idx = new_classzone_idx;
  2975. } else {
  2976. kswapd_try_to_sleep(pgdat, order, classzone_idx,
  2977. balanced_classzone_idx);
  2978. order = pgdat->kswapd_max_order;
  2979. classzone_idx = pgdat->classzone_idx;
  2980. new_order = order;
  2981. new_classzone_idx = classzone_idx;
  2982. pgdat->kswapd_max_order = 0;
  2983. pgdat->classzone_idx = pgdat->nr_zones - 1;
  2984. }
  2985. ret = try_to_freeze();
  2986. if (kthread_should_stop())
  2987. break;
  2988. /*
  2989. * We can speed up thawing tasks if we don't call balance_pgdat
  2990. * after returning from the refrigerator
  2991. */
  2992. if (!ret) {
  2993. trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
  2994. balanced_classzone_idx = balance_pgdat(pgdat, order,
  2995. classzone_idx);
  2996. }
  2997. }
  2998. tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
  2999. current->reclaim_state = NULL;
  3000. lockdep_clear_current_reclaim_state();
  3001. return 0;
  3002. }
  3003. /*
  3004. * A zone is low on free memory, so wake its kswapd task to service it.
  3005. */
  3006. void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
  3007. {
  3008. pg_data_t *pgdat;
  3009. if (!populated_zone(zone))
  3010. return;
  3011. if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
  3012. return;
  3013. pgdat = zone->zone_pgdat;
  3014. if (pgdat->kswapd_max_order < order) {
  3015. pgdat->kswapd_max_order = order;
  3016. pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
  3017. }
  3018. if (!waitqueue_active(&pgdat->kswapd_wait))
  3019. return;
  3020. if (zone_balanced(zone, order, true, 0, 0))
  3021. return;
  3022. trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
  3023. wake_up_interruptible(&pgdat->kswapd_wait);
  3024. }
  3025. #ifdef CONFIG_HIBERNATION
  3026. /*
  3027. * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
  3028. * freed pages.
  3029. *
  3030. * Rather than trying to age LRUs the aim is to preserve the overall
  3031. * LRU order by reclaiming preferentially
  3032. * inactive > active > active referenced > active mapped
  3033. */
  3034. unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
  3035. {
  3036. struct reclaim_state reclaim_state;
  3037. struct scan_control sc = {
  3038. .nr_to_reclaim = nr_to_reclaim,
  3039. .gfp_mask = GFP_HIGHUSER_MOVABLE,
  3040. .priority = DEF_PRIORITY,
  3041. .may_writepage = 1,
  3042. .may_unmap = 1,
  3043. .may_swap = 1,
  3044. .hibernation_mode = 1,
  3045. };
  3046. struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
  3047. struct task_struct *p = current;
  3048. unsigned long nr_reclaimed;
  3049. p->flags |= PF_MEMALLOC;
  3050. lockdep_set_current_reclaim_state(sc.gfp_mask);
  3051. reclaim_state.reclaimed_slab = 0;
  3052. p->reclaim_state = &reclaim_state;
  3053. nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
  3054. p->reclaim_state = NULL;
  3055. lockdep_clear_current_reclaim_state();
  3056. p->flags &= ~PF_MEMALLOC;
  3057. return nr_reclaimed;
  3058. }
  3059. #endif /* CONFIG_HIBERNATION */
  3060. /* It's optimal to keep kswapds on the same CPUs as their memory, but
  3061. not required for correctness. So if the last cpu in a node goes
  3062. away, we get changed to run anywhere: as the first one comes back,
  3063. restore their cpu bindings. */
  3064. static int cpu_callback(struct notifier_block *nfb, unsigned long action,
  3065. void *hcpu)
  3066. {
  3067. int nid;
  3068. if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
  3069. for_each_node_state(nid, N_MEMORY) {
  3070. pg_data_t *pgdat = NODE_DATA(nid);
  3071. const struct cpumask *mask;
  3072. mask = cpumask_of_node(pgdat->node_id);
  3073. if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
  3074. /* One of our CPUs online: restore mask */
  3075. set_cpus_allowed_ptr(pgdat->kswapd, mask);
  3076. }
  3077. }
  3078. return NOTIFY_OK;
  3079. }
  3080. /*
  3081. * This kswapd start function will be called by init and node-hot-add.
  3082. * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
  3083. */
  3084. int kswapd_run(int nid)
  3085. {
  3086. pg_data_t *pgdat = NODE_DATA(nid);
  3087. int ret = 0;
  3088. if (pgdat->kswapd)
  3089. return 0;
  3090. pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
  3091. if (IS_ERR(pgdat->kswapd)) {
  3092. /* failure at boot is fatal */
  3093. BUG_ON(system_state == SYSTEM_BOOTING);
  3094. pr_err("Failed to start kswapd on node %d\n", nid);
  3095. ret = PTR_ERR(pgdat->kswapd);
  3096. pgdat->kswapd = NULL;
  3097. }
  3098. return ret;
  3099. }
  3100. /*
  3101. * Called by memory hotplug when all memory in a node is offlined. Caller must
  3102. * hold mem_hotplug_begin/end().
  3103. */
  3104. void kswapd_stop(int nid)
  3105. {
  3106. struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
  3107. if (kswapd) {
  3108. kthread_stop(kswapd);
  3109. NODE_DATA(nid)->kswapd = NULL;
  3110. }
  3111. }
  3112. static int __init kswapd_init(void)
  3113. {
  3114. int nid;
  3115. swap_setup();
  3116. for_each_node_state(nid, N_MEMORY)
  3117. kswapd_run(nid);
  3118. hotcpu_notifier(cpu_callback, 0);
  3119. return 0;
  3120. }
  3121. module_init(kswapd_init)
  3122. #ifdef CONFIG_NUMA
  3123. /*
  3124. * Zone reclaim mode
  3125. *
  3126. * If non-zero call zone_reclaim when the number of free pages falls below
  3127. * the watermarks.
  3128. */
  3129. int zone_reclaim_mode __read_mostly;
  3130. #define RECLAIM_OFF 0
  3131. #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
  3132. #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
  3133. #define RECLAIM_UNMAP (1<<2) /* Unmap pages during reclaim */
  3134. /*
  3135. * Priority for ZONE_RECLAIM. This determines the fraction of pages
  3136. * of a node considered for each zone_reclaim. 4 scans 1/16th of
  3137. * a zone.
  3138. */
  3139. #define ZONE_RECLAIM_PRIORITY 4
  3140. /*
  3141. * Percentage of pages in a zone that must be unmapped for zone_reclaim to
  3142. * occur.
  3143. */
  3144. int sysctl_min_unmapped_ratio = 1;
  3145. /*
  3146. * If the number of slab pages in a zone grows beyond this percentage then
  3147. * slab reclaim needs to occur.
  3148. */
  3149. int sysctl_min_slab_ratio = 5;
  3150. static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
  3151. {
  3152. unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
  3153. unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
  3154. zone_page_state(zone, NR_ACTIVE_FILE);
  3155. /*
  3156. * It's possible for there to be more file mapped pages than
  3157. * accounted for by the pages on the file LRU lists because
  3158. * tmpfs pages accounted for as ANON can also be FILE_MAPPED
  3159. */
  3160. return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
  3161. }
  3162. /* Work out how many page cache pages we can reclaim in this reclaim_mode */
  3163. static unsigned long zone_pagecache_reclaimable(struct zone *zone)
  3164. {
  3165. unsigned long nr_pagecache_reclaimable;
  3166. unsigned long delta = 0;
  3167. /*
  3168. * If RECLAIM_UNMAP is set, then all file pages are considered
  3169. * potentially reclaimable. Otherwise, we have to worry about
  3170. * pages like swapcache and zone_unmapped_file_pages() provides
  3171. * a better estimate
  3172. */
  3173. if (zone_reclaim_mode & RECLAIM_UNMAP)
  3174. nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
  3175. else
  3176. nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
  3177. /* If we can't clean pages, remove dirty pages from consideration */
  3178. if (!(zone_reclaim_mode & RECLAIM_WRITE))
  3179. delta += zone_page_state(zone, NR_FILE_DIRTY);
  3180. /* Watch for any possible underflows due to delta */
  3181. if (unlikely(delta > nr_pagecache_reclaimable))
  3182. delta = nr_pagecache_reclaimable;
  3183. return nr_pagecache_reclaimable - delta;
  3184. }
  3185. /*
  3186. * Try to free up some pages from this zone through reclaim.
  3187. */
  3188. static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
  3189. {
  3190. /* Minimum pages needed in order to stay on node */
  3191. const unsigned long nr_pages = 1 << order;
  3192. struct task_struct *p = current;
  3193. struct reclaim_state reclaim_state;
  3194. struct scan_control sc = {
  3195. .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
  3196. .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
  3197. .order = order,
  3198. .priority = ZONE_RECLAIM_PRIORITY,
  3199. .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
  3200. .may_unmap = !!(zone_reclaim_mode & RECLAIM_UNMAP),
  3201. .may_swap = 1,
  3202. };
  3203. cond_resched();
  3204. /*
  3205. * We need to be able to allocate from the reserves for RECLAIM_UNMAP
  3206. * and we also need to be able to write out pages for RECLAIM_WRITE
  3207. * and RECLAIM_UNMAP.
  3208. */
  3209. p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
  3210. lockdep_set_current_reclaim_state(gfp_mask);
  3211. reclaim_state.reclaimed_slab = 0;
  3212. p->reclaim_state = &reclaim_state;
  3213. if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
  3214. /*
  3215. * Free memory by calling shrink zone with increasing
  3216. * priorities until we have enough memory freed.
  3217. */
  3218. do {
  3219. shrink_zone(zone, &sc, true);
  3220. } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
  3221. }
  3222. p->reclaim_state = NULL;
  3223. current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
  3224. lockdep_clear_current_reclaim_state();
  3225. return sc.nr_reclaimed >= nr_pages;
  3226. }
  3227. int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
  3228. {
  3229. int node_id;
  3230. int ret;
  3231. /*
  3232. * Zone reclaim reclaims unmapped file backed pages and
  3233. * slab pages if we are over the defined limits.
  3234. *
  3235. * A small portion of unmapped file backed pages is needed for
  3236. * file I/O otherwise pages read by file I/O will be immediately
  3237. * thrown out if the zone is overallocated. So we do not reclaim
  3238. * if less than a specified percentage of the zone is used by
  3239. * unmapped file backed pages.
  3240. */
  3241. if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
  3242. zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
  3243. return ZONE_RECLAIM_FULL;
  3244. if (!zone_reclaimable(zone))
  3245. return ZONE_RECLAIM_FULL;
  3246. /*
  3247. * Do not scan if the allocation should not be delayed.
  3248. */
  3249. if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
  3250. return ZONE_RECLAIM_NOSCAN;
  3251. /*
  3252. * Only run zone reclaim on the local zone or on zones that do not
  3253. * have associated processors. This will favor the local processor
  3254. * over remote processors and spread off node memory allocations
  3255. * as wide as possible.
  3256. */
  3257. node_id = zone_to_nid(zone);
  3258. if (node_state(node_id, N_CPU) && node_id != numa_node_id())
  3259. return ZONE_RECLAIM_NOSCAN;
  3260. if (test_and_set_bit(ZONE_RECLAIM_LOCKED, &zone->flags))
  3261. return ZONE_RECLAIM_NOSCAN;
  3262. ret = __zone_reclaim(zone, gfp_mask, order);
  3263. clear_bit(ZONE_RECLAIM_LOCKED, &zone->flags);
  3264. if (!ret)
  3265. count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
  3266. return ret;
  3267. }
  3268. #endif
  3269. /*
  3270. * page_evictable - test whether a page is evictable
  3271. * @page: the page to test
  3272. *
  3273. * Test whether page is evictable--i.e., should be placed on active/inactive
  3274. * lists vs unevictable list.
  3275. *
  3276. * Reasons page might not be evictable:
  3277. * (1) page's mapping marked unevictable
  3278. * (2) page is part of an mlocked VMA
  3279. *
  3280. */
  3281. int page_evictable(struct page *page)
  3282. {
  3283. return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
  3284. }
  3285. #ifdef CONFIG_SHMEM
  3286. /**
  3287. * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
  3288. * @pages: array of pages to check
  3289. * @nr_pages: number of pages to check
  3290. *
  3291. * Checks pages for evictability and moves them to the appropriate lru list.
  3292. *
  3293. * This function is only used for SysV IPC SHM_UNLOCK.
  3294. */
  3295. void check_move_unevictable_pages(struct page **pages, int nr_pages)
  3296. {
  3297. struct lruvec *lruvec;
  3298. struct zone *zone = NULL;
  3299. int pgscanned = 0;
  3300. int pgrescued = 0;
  3301. int i;
  3302. for (i = 0; i < nr_pages; i++) {
  3303. struct page *page = pages[i];
  3304. struct zone *pagezone;
  3305. pgscanned++;
  3306. pagezone = page_zone(page);
  3307. if (pagezone != zone) {
  3308. if (zone)
  3309. spin_unlock_irq(&zone->lru_lock);
  3310. zone = pagezone;
  3311. spin_lock_irq(&zone->lru_lock);
  3312. }
  3313. lruvec = mem_cgroup_page_lruvec(page, zone);
  3314. if (!PageLRU(page) || !PageUnevictable(page))
  3315. continue;
  3316. if (page_evictable(page)) {
  3317. enum lru_list lru = page_lru_base_type(page);
  3318. VM_BUG_ON_PAGE(PageActive(page), page);
  3319. ClearPageUnevictable(page);
  3320. del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
  3321. add_page_to_lru_list(page, lruvec, lru);
  3322. pgrescued++;
  3323. }
  3324. }
  3325. if (zone) {
  3326. __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
  3327. __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
  3328. spin_unlock_irq(&zone->lru_lock);
  3329. }
  3330. }
  3331. #endif /* CONFIG_SHMEM */