vmscan.c 110 KB

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