vmscan.c 109 KB

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