vmscan.c 121 KB

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