vmscan.c 114 KB

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