vmscan.c 100 KB

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