vmscan.c 110 KB

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