vmscan.c 112 KB

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