vmscan.c 116 KB

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