vmscan.c 127 KB

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