vmscan.c 111 KB

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