vmscan.c 112 KB

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