vmscan.c 107 KB

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