vmscan.c 121 KB

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