vmscan.c 109 KB

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