vmscan.c 115 KB

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