vmscan.c 111 KB

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