vmscan.c 108 KB

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