vmscan.c 107 KB

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