vmscan.c 121 KB

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