vmscan.c 115 KB

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