vmscan.c 111 KB

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