vmscan.c 109 KB

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