vmscan.c 114 KB

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