vmscan.c 110 KB

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