vmscan.c 114 KB

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