vmscan.c 109 KB

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