vmscan.c 106 KB

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