vmscan.c 110 KB

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