vmscan.c 100 KB

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