vmscan.c 109 KB

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