vmscan.c 111 KB

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