vmscan.c 109 KB

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