vmscan.c 121 KB

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