vmscan.c 111 KB

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