vmscan.c 112 KB

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