vmscan.c 120 KB

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