vmscan.c 100 KB

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