vmscan.c 115 KB

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