vmscan.c 112 KB

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