vmscan.c 111 KB

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