page-writeback.c 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * mm/page-writeback.c
  4. *
  5. * Copyright (C) 2002, Linus Torvalds.
  6. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
  7. *
  8. * Contains functions related to writing back dirty pages at the
  9. * address_space level.
  10. *
  11. * 10Apr2002 Andrew Morton
  12. * Initial version
  13. */
  14. #include <linux/kernel.h>
  15. #include <linux/export.h>
  16. #include <linux/spinlock.h>
  17. #include <linux/fs.h>
  18. #include <linux/mm.h>
  19. #include <linux/swap.h>
  20. #include <linux/slab.h>
  21. #include <linux/pagemap.h>
  22. #include <linux/writeback.h>
  23. #include <linux/init.h>
  24. #include <linux/backing-dev.h>
  25. #include <linux/task_io_accounting_ops.h>
  26. #include <linux/blkdev.h>
  27. #include <linux/mpage.h>
  28. #include <linux/rmap.h>
  29. #include <linux/percpu.h>
  30. #include <linux/smp.h>
  31. #include <linux/sysctl.h>
  32. #include <linux/cpu.h>
  33. #include <linux/syscalls.h>
  34. #include <linux/pagevec.h>
  35. #include <linux/timer.h>
  36. #include <linux/sched/rt.h>
  37. #include <linux/sched/signal.h>
  38. #include <linux/mm_inline.h>
  39. #include <trace/events/writeback.h>
  40. #include <trace/hooks/mm.h>
  41. #include "internal.h"
  42. /*
  43. * Sleep at most 200ms at a time in balance_dirty_pages().
  44. */
  45. #define MAX_PAUSE max(HZ/5, 1)
  46. /*
  47. * Try to keep balance_dirty_pages() call intervals higher than this many pages
  48. * by raising pause time to max_pause when falls below it.
  49. */
  50. #define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10))
  51. /*
  52. * Estimate write bandwidth at 200ms intervals.
  53. */
  54. #define BANDWIDTH_INTERVAL max(HZ/5, 1)
  55. #define RATELIMIT_CALC_SHIFT 10
  56. /*
  57. * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
  58. * will look to see if it needs to force writeback or throttling.
  59. */
  60. static long ratelimit_pages = 32;
  61. /* The following parameters are exported via /proc/sys/vm */
  62. /*
  63. * Start background writeback (via writeback threads) at this percentage
  64. */
  65. static int dirty_background_ratio = 10;
  66. /*
  67. * dirty_background_bytes starts at 0 (disabled) so that it is a function of
  68. * dirty_background_ratio * the amount of dirtyable memory
  69. */
  70. static unsigned long dirty_background_bytes;
  71. /*
  72. * free highmem will not be subtracted from the total free memory
  73. * for calculating free ratios if vm_highmem_is_dirtyable is true
  74. */
  75. static int vm_highmem_is_dirtyable;
  76. /*
  77. * The generator of dirty data starts writeback at this percentage
  78. */
  79. static int vm_dirty_ratio = 20;
  80. /*
  81. * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
  82. * vm_dirty_ratio * the amount of dirtyable memory
  83. */
  84. static unsigned long vm_dirty_bytes;
  85. /*
  86. * The interval between `kupdate'-style writebacks
  87. */
  88. unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
  89. EXPORT_SYMBOL_GPL(dirty_writeback_interval);
  90. /*
  91. * The longest time for which data is allowed to remain dirty
  92. */
  93. unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
  94. /*
  95. * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
  96. * a full sync is triggered after this time elapses without any disk activity.
  97. */
  98. int laptop_mode;
  99. EXPORT_SYMBOL(laptop_mode);
  100. /* End of sysctl-exported parameters */
  101. struct wb_domain global_wb_domain;
  102. /* consolidated parameters for balance_dirty_pages() and its subroutines */
  103. struct dirty_throttle_control {
  104. #ifdef CONFIG_CGROUP_WRITEBACK
  105. struct wb_domain *dom;
  106. struct dirty_throttle_control *gdtc; /* only set in memcg dtc's */
  107. #endif
  108. struct bdi_writeback *wb;
  109. struct fprop_local_percpu *wb_completions;
  110. unsigned long avail; /* dirtyable */
  111. unsigned long dirty; /* file_dirty + write + nfs */
  112. unsigned long thresh; /* dirty threshold */
  113. unsigned long bg_thresh; /* dirty background threshold */
  114. unsigned long wb_dirty; /* per-wb counterparts */
  115. unsigned long wb_thresh;
  116. unsigned long wb_bg_thresh;
  117. unsigned long pos_ratio;
  118. };
  119. /*
  120. * Length of period for aging writeout fractions of bdis. This is an
  121. * arbitrarily chosen number. The longer the period, the slower fractions will
  122. * reflect changes in current writeout rate.
  123. */
  124. #define VM_COMPLETIONS_PERIOD_LEN (3*HZ)
  125. #ifdef CONFIG_CGROUP_WRITEBACK
  126. #define GDTC_INIT(__wb) .wb = (__wb), \
  127. .dom = &global_wb_domain, \
  128. .wb_completions = &(__wb)->completions
  129. #define GDTC_INIT_NO_WB .dom = &global_wb_domain
  130. #define MDTC_INIT(__wb, __gdtc) .wb = (__wb), \
  131. .dom = mem_cgroup_wb_domain(__wb), \
  132. .wb_completions = &(__wb)->memcg_completions, \
  133. .gdtc = __gdtc
  134. static bool mdtc_valid(struct dirty_throttle_control *dtc)
  135. {
  136. return dtc->dom;
  137. }
  138. static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc)
  139. {
  140. return dtc->dom;
  141. }
  142. static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc)
  143. {
  144. return mdtc->gdtc;
  145. }
  146. static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb)
  147. {
  148. return &wb->memcg_completions;
  149. }
  150. static void wb_min_max_ratio(struct bdi_writeback *wb,
  151. unsigned long *minp, unsigned long *maxp)
  152. {
  153. unsigned long this_bw = READ_ONCE(wb->avg_write_bandwidth);
  154. unsigned long tot_bw = atomic_long_read(&wb->bdi->tot_write_bandwidth);
  155. unsigned long long min = wb->bdi->min_ratio;
  156. unsigned long long max = wb->bdi->max_ratio;
  157. /*
  158. * @wb may already be clean by the time control reaches here and
  159. * the total may not include its bw.
  160. */
  161. if (this_bw < tot_bw) {
  162. if (min) {
  163. min *= this_bw;
  164. min = div64_ul(min, tot_bw);
  165. }
  166. if (max < 100) {
  167. max *= this_bw;
  168. max = div64_ul(max, tot_bw);
  169. }
  170. }
  171. *minp = min;
  172. *maxp = max;
  173. }
  174. #else /* CONFIG_CGROUP_WRITEBACK */
  175. #define GDTC_INIT(__wb) .wb = (__wb), \
  176. .wb_completions = &(__wb)->completions
  177. #define GDTC_INIT_NO_WB
  178. #define MDTC_INIT(__wb, __gdtc)
  179. static bool mdtc_valid(struct dirty_throttle_control *dtc)
  180. {
  181. return false;
  182. }
  183. static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc)
  184. {
  185. return &global_wb_domain;
  186. }
  187. static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc)
  188. {
  189. return NULL;
  190. }
  191. static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb)
  192. {
  193. return NULL;
  194. }
  195. static void wb_min_max_ratio(struct bdi_writeback *wb,
  196. unsigned long *minp, unsigned long *maxp)
  197. {
  198. *minp = wb->bdi->min_ratio;
  199. *maxp = wb->bdi->max_ratio;
  200. }
  201. #endif /* CONFIG_CGROUP_WRITEBACK */
  202. /*
  203. * In a memory zone, there is a certain amount of pages we consider
  204. * available for the page cache, which is essentially the number of
  205. * free and reclaimable pages, minus some zone reserves to protect
  206. * lowmem and the ability to uphold the zone's watermarks without
  207. * requiring writeback.
  208. *
  209. * This number of dirtyable pages is the base value of which the
  210. * user-configurable dirty ratio is the effective number of pages that
  211. * are allowed to be actually dirtied. Per individual zone, or
  212. * globally by using the sum of dirtyable pages over all zones.
  213. *
  214. * Because the user is allowed to specify the dirty limit globally as
  215. * absolute number of bytes, calculating the per-zone dirty limit can
  216. * require translating the configured limit into a percentage of
  217. * global dirtyable memory first.
  218. */
  219. /**
  220. * node_dirtyable_memory - number of dirtyable pages in a node
  221. * @pgdat: the node
  222. *
  223. * Return: the node's number of pages potentially available for dirty
  224. * page cache. This is the base value for the per-node dirty limits.
  225. */
  226. static unsigned long node_dirtyable_memory(struct pglist_data *pgdat)
  227. {
  228. unsigned long nr_pages = 0;
  229. int z;
  230. for (z = 0; z < MAX_NR_ZONES; z++) {
  231. struct zone *zone = pgdat->node_zones + z;
  232. if (!populated_zone(zone))
  233. continue;
  234. nr_pages += zone_page_state(zone, NR_FREE_PAGES);
  235. }
  236. /*
  237. * Pages reserved for the kernel should not be considered
  238. * dirtyable, to prevent a situation where reclaim has to
  239. * clean pages in order to balance the zones.
  240. */
  241. nr_pages -= min(nr_pages, pgdat->totalreserve_pages);
  242. nr_pages += node_page_state(pgdat, NR_INACTIVE_FILE);
  243. nr_pages += node_page_state(pgdat, NR_ACTIVE_FILE);
  244. return nr_pages;
  245. }
  246. static unsigned long highmem_dirtyable_memory(unsigned long total)
  247. {
  248. #ifdef CONFIG_HIGHMEM
  249. int node;
  250. unsigned long x = 0;
  251. int i;
  252. for_each_node_state(node, N_HIGH_MEMORY) {
  253. for (i = ZONE_NORMAL + 1; i < MAX_NR_ZONES; i++) {
  254. struct zone *z;
  255. unsigned long nr_pages;
  256. if (!is_highmem_idx(i))
  257. continue;
  258. z = &NODE_DATA(node)->node_zones[i];
  259. if (!populated_zone(z))
  260. continue;
  261. nr_pages = zone_page_state(z, NR_FREE_PAGES);
  262. /* watch for underflows */
  263. nr_pages -= min(nr_pages, high_wmark_pages(z));
  264. nr_pages += zone_page_state(z, NR_ZONE_INACTIVE_FILE);
  265. nr_pages += zone_page_state(z, NR_ZONE_ACTIVE_FILE);
  266. x += nr_pages;
  267. }
  268. }
  269. /*
  270. * Make sure that the number of highmem pages is never larger
  271. * than the number of the total dirtyable memory. This can only
  272. * occur in very strange VM situations but we want to make sure
  273. * that this does not occur.
  274. */
  275. return min(x, total);
  276. #else
  277. return 0;
  278. #endif
  279. }
  280. /**
  281. * global_dirtyable_memory - number of globally dirtyable pages
  282. *
  283. * Return: the global number of pages potentially available for dirty
  284. * page cache. This is the base value for the global dirty limits.
  285. */
  286. static unsigned long global_dirtyable_memory(void)
  287. {
  288. unsigned long x;
  289. x = global_zone_page_state(NR_FREE_PAGES);
  290. /*
  291. * Pages reserved for the kernel should not be considered
  292. * dirtyable, to prevent a situation where reclaim has to
  293. * clean pages in order to balance the zones.
  294. */
  295. x -= min(x, totalreserve_pages);
  296. x += global_node_page_state(NR_INACTIVE_FILE);
  297. x += global_node_page_state(NR_ACTIVE_FILE);
  298. if (!vm_highmem_is_dirtyable)
  299. x -= highmem_dirtyable_memory(x);
  300. return x + 1; /* Ensure that we never return 0 */
  301. }
  302. /**
  303. * domain_dirty_limits - calculate thresh and bg_thresh for a wb_domain
  304. * @dtc: dirty_throttle_control of interest
  305. *
  306. * Calculate @dtc->thresh and ->bg_thresh considering
  307. * vm_dirty_{bytes|ratio} and dirty_background_{bytes|ratio}. The caller
  308. * must ensure that @dtc->avail is set before calling this function. The
  309. * dirty limits will be lifted by 1/4 for real-time tasks.
  310. */
  311. static void domain_dirty_limits(struct dirty_throttle_control *dtc)
  312. {
  313. const unsigned long available_memory = dtc->avail;
  314. struct dirty_throttle_control *gdtc = mdtc_gdtc(dtc);
  315. unsigned long bytes = vm_dirty_bytes;
  316. unsigned long bg_bytes = dirty_background_bytes;
  317. /* convert ratios to per-PAGE_SIZE for higher precision */
  318. unsigned long ratio = (vm_dirty_ratio * PAGE_SIZE) / 100;
  319. unsigned long bg_ratio = (dirty_background_ratio * PAGE_SIZE) / 100;
  320. unsigned long thresh;
  321. unsigned long bg_thresh;
  322. struct task_struct *tsk;
  323. /* gdtc is !NULL iff @dtc is for memcg domain */
  324. if (gdtc) {
  325. unsigned long global_avail = gdtc->avail;
  326. /*
  327. * The byte settings can't be applied directly to memcg
  328. * domains. Convert them to ratios by scaling against
  329. * globally available memory. As the ratios are in
  330. * per-PAGE_SIZE, they can be obtained by dividing bytes by
  331. * number of pages.
  332. */
  333. if (bytes)
  334. ratio = min(DIV_ROUND_UP(bytes, global_avail),
  335. PAGE_SIZE);
  336. if (bg_bytes)
  337. bg_ratio = min(DIV_ROUND_UP(bg_bytes, global_avail),
  338. PAGE_SIZE);
  339. bytes = bg_bytes = 0;
  340. }
  341. if (bytes)
  342. thresh = DIV_ROUND_UP(bytes, PAGE_SIZE);
  343. else
  344. thresh = (ratio * available_memory) / PAGE_SIZE;
  345. if (bg_bytes)
  346. bg_thresh = DIV_ROUND_UP(bg_bytes, PAGE_SIZE);
  347. else
  348. bg_thresh = (bg_ratio * available_memory) / PAGE_SIZE;
  349. if (bg_thresh >= thresh)
  350. bg_thresh = thresh / 2;
  351. tsk = current;
  352. if (rt_task(tsk)) {
  353. bg_thresh += bg_thresh / 4 + global_wb_domain.dirty_limit / 32;
  354. thresh += thresh / 4 + global_wb_domain.dirty_limit / 32;
  355. }
  356. dtc->thresh = thresh;
  357. dtc->bg_thresh = bg_thresh;
  358. /* we should eventually report the domain in the TP */
  359. if (!gdtc)
  360. trace_global_dirty_state(bg_thresh, thresh);
  361. }
  362. /**
  363. * global_dirty_limits - background-writeback and dirty-throttling thresholds
  364. * @pbackground: out parameter for bg_thresh
  365. * @pdirty: out parameter for thresh
  366. *
  367. * Calculate bg_thresh and thresh for global_wb_domain. See
  368. * domain_dirty_limits() for details.
  369. */
  370. void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
  371. {
  372. struct dirty_throttle_control gdtc = { GDTC_INIT_NO_WB };
  373. gdtc.avail = global_dirtyable_memory();
  374. domain_dirty_limits(&gdtc);
  375. *pbackground = gdtc.bg_thresh;
  376. *pdirty = gdtc.thresh;
  377. }
  378. /**
  379. * node_dirty_limit - maximum number of dirty pages allowed in a node
  380. * @pgdat: the node
  381. *
  382. * Return: the maximum number of dirty pages allowed in a node, based
  383. * on the node's dirtyable memory.
  384. */
  385. static unsigned long node_dirty_limit(struct pglist_data *pgdat)
  386. {
  387. unsigned long node_memory = node_dirtyable_memory(pgdat);
  388. struct task_struct *tsk = current;
  389. unsigned long dirty;
  390. if (vm_dirty_bytes)
  391. dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) *
  392. node_memory / global_dirtyable_memory();
  393. else
  394. dirty = vm_dirty_ratio * node_memory / 100;
  395. if (rt_task(tsk))
  396. dirty += dirty / 4;
  397. return dirty;
  398. }
  399. /**
  400. * node_dirty_ok - tells whether a node is within its dirty limits
  401. * @pgdat: the node to check
  402. *
  403. * Return: %true when the dirty pages in @pgdat are within the node's
  404. * dirty limit, %false if the limit is exceeded.
  405. */
  406. bool node_dirty_ok(struct pglist_data *pgdat)
  407. {
  408. unsigned long limit = node_dirty_limit(pgdat);
  409. unsigned long nr_pages = 0;
  410. nr_pages += node_page_state(pgdat, NR_FILE_DIRTY);
  411. nr_pages += node_page_state(pgdat, NR_WRITEBACK);
  412. return nr_pages <= limit;
  413. }
  414. #ifdef CONFIG_SYSCTL
  415. static int dirty_background_ratio_handler(struct ctl_table *table, int write,
  416. void *buffer, size_t *lenp, loff_t *ppos)
  417. {
  418. int ret;
  419. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  420. if (ret == 0 && write)
  421. dirty_background_bytes = 0;
  422. return ret;
  423. }
  424. static int dirty_background_bytes_handler(struct ctl_table *table, int write,
  425. void *buffer, size_t *lenp, loff_t *ppos)
  426. {
  427. int ret;
  428. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  429. if (ret == 0 && write)
  430. dirty_background_ratio = 0;
  431. return ret;
  432. }
  433. static int dirty_ratio_handler(struct ctl_table *table, int write, void *buffer,
  434. size_t *lenp, loff_t *ppos)
  435. {
  436. int old_ratio = vm_dirty_ratio;
  437. int ret;
  438. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  439. if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
  440. writeback_set_ratelimit();
  441. vm_dirty_bytes = 0;
  442. }
  443. return ret;
  444. }
  445. static int dirty_bytes_handler(struct ctl_table *table, int write,
  446. void *buffer, size_t *lenp, loff_t *ppos)
  447. {
  448. unsigned long old_bytes = vm_dirty_bytes;
  449. int ret;
  450. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  451. if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
  452. writeback_set_ratelimit();
  453. vm_dirty_ratio = 0;
  454. }
  455. return ret;
  456. }
  457. #endif
  458. static unsigned long wp_next_time(unsigned long cur_time)
  459. {
  460. cur_time += VM_COMPLETIONS_PERIOD_LEN;
  461. /* 0 has a special meaning... */
  462. if (!cur_time)
  463. return 1;
  464. return cur_time;
  465. }
  466. static void wb_domain_writeout_add(struct wb_domain *dom,
  467. struct fprop_local_percpu *completions,
  468. unsigned int max_prop_frac, long nr)
  469. {
  470. __fprop_add_percpu_max(&dom->completions, completions,
  471. max_prop_frac, nr);
  472. /* First event after period switching was turned off? */
  473. if (unlikely(!dom->period_time)) {
  474. /*
  475. * We can race with other __bdi_writeout_inc calls here but
  476. * it does not cause any harm since the resulting time when
  477. * timer will fire and what is in writeout_period_time will be
  478. * roughly the same.
  479. */
  480. dom->period_time = wp_next_time(jiffies);
  481. mod_timer(&dom->period_timer, dom->period_time);
  482. }
  483. }
  484. /*
  485. * Increment @wb's writeout completion count and the global writeout
  486. * completion count. Called from __folio_end_writeback().
  487. */
  488. static inline void __wb_writeout_add(struct bdi_writeback *wb, long nr)
  489. {
  490. struct wb_domain *cgdom;
  491. wb_stat_mod(wb, WB_WRITTEN, nr);
  492. wb_domain_writeout_add(&global_wb_domain, &wb->completions,
  493. wb->bdi->max_prop_frac, nr);
  494. cgdom = mem_cgroup_wb_domain(wb);
  495. if (cgdom)
  496. wb_domain_writeout_add(cgdom, wb_memcg_completions(wb),
  497. wb->bdi->max_prop_frac, nr);
  498. }
  499. void wb_writeout_inc(struct bdi_writeback *wb)
  500. {
  501. unsigned long flags;
  502. local_irq_save(flags);
  503. __wb_writeout_add(wb, 1);
  504. local_irq_restore(flags);
  505. }
  506. EXPORT_SYMBOL_GPL(wb_writeout_inc);
  507. /*
  508. * On idle system, we can be called long after we scheduled because we use
  509. * deferred timers so count with missed periods.
  510. */
  511. static void writeout_period(struct timer_list *t)
  512. {
  513. struct wb_domain *dom = from_timer(dom, t, period_timer);
  514. int miss_periods = (jiffies - dom->period_time) /
  515. VM_COMPLETIONS_PERIOD_LEN;
  516. if (fprop_new_period(&dom->completions, miss_periods + 1)) {
  517. dom->period_time = wp_next_time(dom->period_time +
  518. miss_periods * VM_COMPLETIONS_PERIOD_LEN);
  519. mod_timer(&dom->period_timer, dom->period_time);
  520. } else {
  521. /*
  522. * Aging has zeroed all fractions. Stop wasting CPU on period
  523. * updates.
  524. */
  525. dom->period_time = 0;
  526. }
  527. }
  528. int wb_domain_init(struct wb_domain *dom, gfp_t gfp)
  529. {
  530. memset(dom, 0, sizeof(*dom));
  531. spin_lock_init(&dom->lock);
  532. timer_setup(&dom->period_timer, writeout_period, TIMER_DEFERRABLE);
  533. dom->dirty_limit_tstamp = jiffies;
  534. return fprop_global_init(&dom->completions, gfp);
  535. }
  536. #ifdef CONFIG_CGROUP_WRITEBACK
  537. void wb_domain_exit(struct wb_domain *dom)
  538. {
  539. del_timer_sync(&dom->period_timer);
  540. fprop_global_destroy(&dom->completions);
  541. }
  542. #endif
  543. /*
  544. * bdi_min_ratio keeps the sum of the minimum dirty shares of all
  545. * registered backing devices, which, for obvious reasons, can not
  546. * exceed 100%.
  547. */
  548. static unsigned int bdi_min_ratio;
  549. int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
  550. {
  551. unsigned int delta;
  552. int ret = 0;
  553. spin_lock_bh(&bdi_lock);
  554. if (min_ratio > bdi->max_ratio) {
  555. ret = -EINVAL;
  556. } else {
  557. if (min_ratio < bdi->min_ratio) {
  558. delta = bdi->min_ratio - min_ratio;
  559. bdi_min_ratio -= delta;
  560. bdi->min_ratio = min_ratio;
  561. } else {
  562. delta = min_ratio - bdi->min_ratio;
  563. if (bdi_min_ratio + delta < 100) {
  564. bdi_min_ratio += delta;
  565. bdi->min_ratio = min_ratio;
  566. } else {
  567. ret = -EINVAL;
  568. }
  569. }
  570. }
  571. spin_unlock_bh(&bdi_lock);
  572. return ret;
  573. }
  574. int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
  575. {
  576. int ret = 0;
  577. if (max_ratio > 100)
  578. return -EINVAL;
  579. spin_lock_bh(&bdi_lock);
  580. if (bdi->min_ratio > max_ratio) {
  581. ret = -EINVAL;
  582. } else {
  583. bdi->max_ratio = max_ratio;
  584. bdi->max_prop_frac = (FPROP_FRAC_BASE * max_ratio) / 100;
  585. }
  586. spin_unlock_bh(&bdi_lock);
  587. return ret;
  588. }
  589. EXPORT_SYMBOL(bdi_set_max_ratio);
  590. static unsigned long dirty_freerun_ceiling(unsigned long thresh,
  591. unsigned long bg_thresh)
  592. {
  593. return (thresh + bg_thresh) / 2;
  594. }
  595. static unsigned long hard_dirty_limit(struct wb_domain *dom,
  596. unsigned long thresh)
  597. {
  598. return max(thresh, dom->dirty_limit);
  599. }
  600. /*
  601. * Memory which can be further allocated to a memcg domain is capped by
  602. * system-wide clean memory excluding the amount being used in the domain.
  603. */
  604. static void mdtc_calc_avail(struct dirty_throttle_control *mdtc,
  605. unsigned long filepages, unsigned long headroom)
  606. {
  607. struct dirty_throttle_control *gdtc = mdtc_gdtc(mdtc);
  608. unsigned long clean = filepages - min(filepages, mdtc->dirty);
  609. unsigned long global_clean = gdtc->avail - min(gdtc->avail, gdtc->dirty);
  610. unsigned long other_clean = global_clean - min(global_clean, clean);
  611. mdtc->avail = filepages + min(headroom, other_clean);
  612. }
  613. /**
  614. * __wb_calc_thresh - @wb's share of dirty throttling threshold
  615. * @dtc: dirty_throttle_context of interest
  616. *
  617. * Note that balance_dirty_pages() will only seriously take it as a hard limit
  618. * when sleeping max_pause per page is not enough to keep the dirty pages under
  619. * control. For example, when the device is completely stalled due to some error
  620. * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
  621. * In the other normal situations, it acts more gently by throttling the tasks
  622. * more (rather than completely block them) when the wb dirty pages go high.
  623. *
  624. * It allocates high/low dirty limits to fast/slow devices, in order to prevent
  625. * - starving fast devices
  626. * - piling up dirty pages (that will take long time to sync) on slow devices
  627. *
  628. * The wb's share of dirty limit will be adapting to its throughput and
  629. * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
  630. *
  631. * Return: @wb's dirty limit in pages. The term "dirty" in the context of
  632. * dirty balancing includes all PG_dirty and PG_writeback pages.
  633. */
  634. static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc)
  635. {
  636. struct wb_domain *dom = dtc_dom(dtc);
  637. unsigned long thresh = dtc->thresh;
  638. u64 wb_thresh;
  639. unsigned long numerator, denominator;
  640. unsigned long wb_min_ratio, wb_max_ratio;
  641. /*
  642. * Calculate this BDI's share of the thresh ratio.
  643. */
  644. fprop_fraction_percpu(&dom->completions, dtc->wb_completions,
  645. &numerator, &denominator);
  646. wb_thresh = (thresh * (100 - bdi_min_ratio)) / 100;
  647. wb_thresh *= numerator;
  648. wb_thresh = div64_ul(wb_thresh, denominator);
  649. wb_min_max_ratio(dtc->wb, &wb_min_ratio, &wb_max_ratio);
  650. wb_thresh += (thresh * wb_min_ratio) / 100;
  651. if (wb_thresh > (thresh * wb_max_ratio) / 100)
  652. wb_thresh = thresh * wb_max_ratio / 100;
  653. return wb_thresh;
  654. }
  655. unsigned long wb_calc_thresh(struct bdi_writeback *wb, unsigned long thresh)
  656. {
  657. struct dirty_throttle_control gdtc = { GDTC_INIT(wb),
  658. .thresh = thresh };
  659. return __wb_calc_thresh(&gdtc);
  660. }
  661. /*
  662. * setpoint - dirty 3
  663. * f(dirty) := 1.0 + (----------------)
  664. * limit - setpoint
  665. *
  666. * it's a 3rd order polynomial that subjects to
  667. *
  668. * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast
  669. * (2) f(setpoint) = 1.0 => the balance point
  670. * (3) f(limit) = 0 => the hard limit
  671. * (4) df/dx <= 0 => negative feedback control
  672. * (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
  673. * => fast response on large errors; small oscillation near setpoint
  674. */
  675. static long long pos_ratio_polynom(unsigned long setpoint,
  676. unsigned long dirty,
  677. unsigned long limit)
  678. {
  679. long long pos_ratio;
  680. long x;
  681. x = div64_s64(((s64)setpoint - (s64)dirty) << RATELIMIT_CALC_SHIFT,
  682. (limit - setpoint) | 1);
  683. pos_ratio = x;
  684. pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
  685. pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
  686. pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
  687. return clamp(pos_ratio, 0LL, 2LL << RATELIMIT_CALC_SHIFT);
  688. }
  689. /*
  690. * Dirty position control.
  691. *
  692. * (o) global/bdi setpoints
  693. *
  694. * We want the dirty pages be balanced around the global/wb setpoints.
  695. * When the number of dirty pages is higher/lower than the setpoint, the
  696. * dirty position control ratio (and hence task dirty ratelimit) will be
  697. * decreased/increased to bring the dirty pages back to the setpoint.
  698. *
  699. * pos_ratio = 1 << RATELIMIT_CALC_SHIFT
  700. *
  701. * if (dirty < setpoint) scale up pos_ratio
  702. * if (dirty > setpoint) scale down pos_ratio
  703. *
  704. * if (wb_dirty < wb_setpoint) scale up pos_ratio
  705. * if (wb_dirty > wb_setpoint) scale down pos_ratio
  706. *
  707. * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
  708. *
  709. * (o) global control line
  710. *
  711. * ^ pos_ratio
  712. * |
  713. * | |<===== global dirty control scope ======>|
  714. * 2.0 * * * * * * *
  715. * | .*
  716. * | . *
  717. * | . *
  718. * | . *
  719. * | . *
  720. * | . *
  721. * 1.0 ................................*
  722. * | . . *
  723. * | . . *
  724. * | . . *
  725. * | . . *
  726. * | . . *
  727. * 0 +------------.------------------.----------------------*------------->
  728. * freerun^ setpoint^ limit^ dirty pages
  729. *
  730. * (o) wb control line
  731. *
  732. * ^ pos_ratio
  733. * |
  734. * | *
  735. * | *
  736. * | *
  737. * | *
  738. * | * |<=========== span ============>|
  739. * 1.0 .......................*
  740. * | . *
  741. * | . *
  742. * | . *
  743. * | . *
  744. * | . *
  745. * | . *
  746. * | . *
  747. * | . *
  748. * | . *
  749. * | . *
  750. * | . *
  751. * 1/4 ...............................................* * * * * * * * * * * *
  752. * | . .
  753. * | . .
  754. * | . .
  755. * 0 +----------------------.-------------------------------.------------->
  756. * wb_setpoint^ x_intercept^
  757. *
  758. * The wb control line won't drop below pos_ratio=1/4, so that wb_dirty can
  759. * be smoothly throttled down to normal if it starts high in situations like
  760. * - start writing to a slow SD card and a fast disk at the same time. The SD
  761. * card's wb_dirty may rush to many times higher than wb_setpoint.
  762. * - the wb dirty thresh drops quickly due to change of JBOD workload
  763. */
  764. static void wb_position_ratio(struct dirty_throttle_control *dtc)
  765. {
  766. struct bdi_writeback *wb = dtc->wb;
  767. unsigned long write_bw = READ_ONCE(wb->avg_write_bandwidth);
  768. unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh);
  769. unsigned long limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh);
  770. unsigned long wb_thresh = dtc->wb_thresh;
  771. unsigned long x_intercept;
  772. unsigned long setpoint; /* dirty pages' target balance point */
  773. unsigned long wb_setpoint;
  774. unsigned long span;
  775. long long pos_ratio; /* for scaling up/down the rate limit */
  776. long x;
  777. dtc->pos_ratio = 0;
  778. if (unlikely(dtc->dirty >= limit))
  779. return;
  780. /*
  781. * global setpoint
  782. *
  783. * See comment for pos_ratio_polynom().
  784. */
  785. setpoint = (freerun + limit) / 2;
  786. pos_ratio = pos_ratio_polynom(setpoint, dtc->dirty, limit);
  787. /*
  788. * The strictlimit feature is a tool preventing mistrusted filesystems
  789. * from growing a large number of dirty pages before throttling. For
  790. * such filesystems balance_dirty_pages always checks wb counters
  791. * against wb limits. Even if global "nr_dirty" is under "freerun".
  792. * This is especially important for fuse which sets bdi->max_ratio to
  793. * 1% by default. Without strictlimit feature, fuse writeback may
  794. * consume arbitrary amount of RAM because it is accounted in
  795. * NR_WRITEBACK_TEMP which is not involved in calculating "nr_dirty".
  796. *
  797. * Here, in wb_position_ratio(), we calculate pos_ratio based on
  798. * two values: wb_dirty and wb_thresh. Let's consider an example:
  799. * total amount of RAM is 16GB, bdi->max_ratio is equal to 1%, global
  800. * limits are set by default to 10% and 20% (background and throttle).
  801. * Then wb_thresh is 1% of 20% of 16GB. This amounts to ~8K pages.
  802. * wb_calc_thresh(wb, bg_thresh) is about ~4K pages. wb_setpoint is
  803. * about ~6K pages (as the average of background and throttle wb
  804. * limits). The 3rd order polynomial will provide positive feedback if
  805. * wb_dirty is under wb_setpoint and vice versa.
  806. *
  807. * Note, that we cannot use global counters in these calculations
  808. * because we want to throttle process writing to a strictlimit wb
  809. * much earlier than global "freerun" is reached (~23MB vs. ~2.3GB
  810. * in the example above).
  811. */
  812. if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
  813. long long wb_pos_ratio;
  814. if (dtc->wb_dirty < 8) {
  815. dtc->pos_ratio = min_t(long long, pos_ratio * 2,
  816. 2 << RATELIMIT_CALC_SHIFT);
  817. return;
  818. }
  819. if (dtc->wb_dirty >= wb_thresh)
  820. return;
  821. wb_setpoint = dirty_freerun_ceiling(wb_thresh,
  822. dtc->wb_bg_thresh);
  823. if (wb_setpoint == 0 || wb_setpoint == wb_thresh)
  824. return;
  825. wb_pos_ratio = pos_ratio_polynom(wb_setpoint, dtc->wb_dirty,
  826. wb_thresh);
  827. /*
  828. * Typically, for strictlimit case, wb_setpoint << setpoint
  829. * and pos_ratio >> wb_pos_ratio. In the other words global
  830. * state ("dirty") is not limiting factor and we have to
  831. * make decision based on wb counters. But there is an
  832. * important case when global pos_ratio should get precedence:
  833. * global limits are exceeded (e.g. due to activities on other
  834. * wb's) while given strictlimit wb is below limit.
  835. *
  836. * "pos_ratio * wb_pos_ratio" would work for the case above,
  837. * but it would look too non-natural for the case of all
  838. * activity in the system coming from a single strictlimit wb
  839. * with bdi->max_ratio == 100%.
  840. *
  841. * Note that min() below somewhat changes the dynamics of the
  842. * control system. Normally, pos_ratio value can be well over 3
  843. * (when globally we are at freerun and wb is well below wb
  844. * setpoint). Now the maximum pos_ratio in the same situation
  845. * is 2. We might want to tweak this if we observe the control
  846. * system is too slow to adapt.
  847. */
  848. dtc->pos_ratio = min(pos_ratio, wb_pos_ratio);
  849. return;
  850. }
  851. /*
  852. * We have computed basic pos_ratio above based on global situation. If
  853. * the wb is over/under its share of dirty pages, we want to scale
  854. * pos_ratio further down/up. That is done by the following mechanism.
  855. */
  856. /*
  857. * wb setpoint
  858. *
  859. * f(wb_dirty) := 1.0 + k * (wb_dirty - wb_setpoint)
  860. *
  861. * x_intercept - wb_dirty
  862. * := --------------------------
  863. * x_intercept - wb_setpoint
  864. *
  865. * The main wb control line is a linear function that subjects to
  866. *
  867. * (1) f(wb_setpoint) = 1.0
  868. * (2) k = - 1 / (8 * write_bw) (in single wb case)
  869. * or equally: x_intercept = wb_setpoint + 8 * write_bw
  870. *
  871. * For single wb case, the dirty pages are observed to fluctuate
  872. * regularly within range
  873. * [wb_setpoint - write_bw/2, wb_setpoint + write_bw/2]
  874. * for various filesystems, where (2) can yield in a reasonable 12.5%
  875. * fluctuation range for pos_ratio.
  876. *
  877. * For JBOD case, wb_thresh (not wb_dirty!) could fluctuate up to its
  878. * own size, so move the slope over accordingly and choose a slope that
  879. * yields 100% pos_ratio fluctuation on suddenly doubled wb_thresh.
  880. */
  881. if (unlikely(wb_thresh > dtc->thresh))
  882. wb_thresh = dtc->thresh;
  883. /*
  884. * It's very possible that wb_thresh is close to 0 not because the
  885. * device is slow, but that it has remained inactive for long time.
  886. * Honour such devices a reasonable good (hopefully IO efficient)
  887. * threshold, so that the occasional writes won't be blocked and active
  888. * writes can rampup the threshold quickly.
  889. */
  890. wb_thresh = max(wb_thresh, (limit - dtc->dirty) / 8);
  891. /*
  892. * scale global setpoint to wb's:
  893. * wb_setpoint = setpoint * wb_thresh / thresh
  894. */
  895. x = div_u64((u64)wb_thresh << 16, dtc->thresh | 1);
  896. wb_setpoint = setpoint * (u64)x >> 16;
  897. /*
  898. * Use span=(8*write_bw) in single wb case as indicated by
  899. * (thresh - wb_thresh ~= 0) and transit to wb_thresh in JBOD case.
  900. *
  901. * wb_thresh thresh - wb_thresh
  902. * span = --------- * (8 * write_bw) + ------------------ * wb_thresh
  903. * thresh thresh
  904. */
  905. span = (dtc->thresh - wb_thresh + 8 * write_bw) * (u64)x >> 16;
  906. x_intercept = wb_setpoint + span;
  907. if (dtc->wb_dirty < x_intercept - span / 4) {
  908. pos_ratio = div64_u64(pos_ratio * (x_intercept - dtc->wb_dirty),
  909. (x_intercept - wb_setpoint) | 1);
  910. } else
  911. pos_ratio /= 4;
  912. /*
  913. * wb reserve area, safeguard against dirty pool underrun and disk idle
  914. * It may push the desired control point of global dirty pages higher
  915. * than setpoint.
  916. */
  917. x_intercept = wb_thresh / 2;
  918. if (dtc->wb_dirty < x_intercept) {
  919. if (dtc->wb_dirty > x_intercept / 8)
  920. pos_ratio = div_u64(pos_ratio * x_intercept,
  921. dtc->wb_dirty);
  922. else
  923. pos_ratio *= 8;
  924. }
  925. dtc->pos_ratio = pos_ratio;
  926. }
  927. static void wb_update_write_bandwidth(struct bdi_writeback *wb,
  928. unsigned long elapsed,
  929. unsigned long written)
  930. {
  931. const unsigned long period = roundup_pow_of_two(3 * HZ);
  932. unsigned long avg = wb->avg_write_bandwidth;
  933. unsigned long old = wb->write_bandwidth;
  934. u64 bw;
  935. /*
  936. * bw = written * HZ / elapsed
  937. *
  938. * bw * elapsed + write_bandwidth * (period - elapsed)
  939. * write_bandwidth = ---------------------------------------------------
  940. * period
  941. *
  942. * @written may have decreased due to folio_account_redirty().
  943. * Avoid underflowing @bw calculation.
  944. */
  945. bw = written - min(written, wb->written_stamp);
  946. bw *= HZ;
  947. if (unlikely(elapsed > period)) {
  948. bw = div64_ul(bw, elapsed);
  949. avg = bw;
  950. goto out;
  951. }
  952. bw += (u64)wb->write_bandwidth * (period - elapsed);
  953. bw >>= ilog2(period);
  954. /*
  955. * one more level of smoothing, for filtering out sudden spikes
  956. */
  957. if (avg > old && old >= (unsigned long)bw)
  958. avg -= (avg - old) >> 3;
  959. if (avg < old && old <= (unsigned long)bw)
  960. avg += (old - avg) >> 3;
  961. out:
  962. /* keep avg > 0 to guarantee that tot > 0 if there are dirty wbs */
  963. avg = max(avg, 1LU);
  964. if (wb_has_dirty_io(wb)) {
  965. long delta = avg - wb->avg_write_bandwidth;
  966. WARN_ON_ONCE(atomic_long_add_return(delta,
  967. &wb->bdi->tot_write_bandwidth) <= 0);
  968. }
  969. wb->write_bandwidth = bw;
  970. WRITE_ONCE(wb->avg_write_bandwidth, avg);
  971. }
  972. static void update_dirty_limit(struct dirty_throttle_control *dtc)
  973. {
  974. struct wb_domain *dom = dtc_dom(dtc);
  975. unsigned long thresh = dtc->thresh;
  976. unsigned long limit = dom->dirty_limit;
  977. /*
  978. * Follow up in one step.
  979. */
  980. if (limit < thresh) {
  981. limit = thresh;
  982. goto update;
  983. }
  984. /*
  985. * Follow down slowly. Use the higher one as the target, because thresh
  986. * may drop below dirty. This is exactly the reason to introduce
  987. * dom->dirty_limit which is guaranteed to lie above the dirty pages.
  988. */
  989. thresh = max(thresh, dtc->dirty);
  990. if (limit > thresh) {
  991. limit -= (limit - thresh) >> 5;
  992. goto update;
  993. }
  994. return;
  995. update:
  996. dom->dirty_limit = limit;
  997. }
  998. static void domain_update_dirty_limit(struct dirty_throttle_control *dtc,
  999. unsigned long now)
  1000. {
  1001. struct wb_domain *dom = dtc_dom(dtc);
  1002. /*
  1003. * check locklessly first to optimize away locking for the most time
  1004. */
  1005. if (time_before(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL))
  1006. return;
  1007. spin_lock(&dom->lock);
  1008. if (time_after_eq(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL)) {
  1009. update_dirty_limit(dtc);
  1010. dom->dirty_limit_tstamp = now;
  1011. }
  1012. spin_unlock(&dom->lock);
  1013. }
  1014. /*
  1015. * Maintain wb->dirty_ratelimit, the base dirty throttle rate.
  1016. *
  1017. * Normal wb tasks will be curbed at or below it in long term.
  1018. * Obviously it should be around (write_bw / N) when there are N dd tasks.
  1019. */
  1020. static void wb_update_dirty_ratelimit(struct dirty_throttle_control *dtc,
  1021. unsigned long dirtied,
  1022. unsigned long elapsed)
  1023. {
  1024. struct bdi_writeback *wb = dtc->wb;
  1025. unsigned long dirty = dtc->dirty;
  1026. unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh);
  1027. unsigned long limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh);
  1028. unsigned long setpoint = (freerun + limit) / 2;
  1029. unsigned long write_bw = wb->avg_write_bandwidth;
  1030. unsigned long dirty_ratelimit = wb->dirty_ratelimit;
  1031. unsigned long dirty_rate;
  1032. unsigned long task_ratelimit;
  1033. unsigned long balanced_dirty_ratelimit;
  1034. unsigned long step;
  1035. unsigned long x;
  1036. unsigned long shift;
  1037. /*
  1038. * The dirty rate will match the writeout rate in long term, except
  1039. * when dirty pages are truncated by userspace or re-dirtied by FS.
  1040. */
  1041. dirty_rate = (dirtied - wb->dirtied_stamp) * HZ / elapsed;
  1042. /*
  1043. * task_ratelimit reflects each dd's dirty rate for the past 200ms.
  1044. */
  1045. task_ratelimit = (u64)dirty_ratelimit *
  1046. dtc->pos_ratio >> RATELIMIT_CALC_SHIFT;
  1047. task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
  1048. /*
  1049. * A linear estimation of the "balanced" throttle rate. The theory is,
  1050. * if there are N dd tasks, each throttled at task_ratelimit, the wb's
  1051. * dirty_rate will be measured to be (N * task_ratelimit). So the below
  1052. * formula will yield the balanced rate limit (write_bw / N).
  1053. *
  1054. * Note that the expanded form is not a pure rate feedback:
  1055. * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
  1056. * but also takes pos_ratio into account:
  1057. * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
  1058. *
  1059. * (1) is not realistic because pos_ratio also takes part in balancing
  1060. * the dirty rate. Consider the state
  1061. * pos_ratio = 0.5 (3)
  1062. * rate = 2 * (write_bw / N) (4)
  1063. * If (1) is used, it will stuck in that state! Because each dd will
  1064. * be throttled at
  1065. * task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
  1066. * yielding
  1067. * dirty_rate = N * task_ratelimit = write_bw (6)
  1068. * put (6) into (1) we get
  1069. * rate_(i+1) = rate_(i) (7)
  1070. *
  1071. * So we end up using (2) to always keep
  1072. * rate_(i+1) ~= (write_bw / N) (8)
  1073. * regardless of the value of pos_ratio. As long as (8) is satisfied,
  1074. * pos_ratio is able to drive itself to 1.0, which is not only where
  1075. * the dirty count meet the setpoint, but also where the slope of
  1076. * pos_ratio is most flat and hence task_ratelimit is least fluctuated.
  1077. */
  1078. balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
  1079. dirty_rate | 1);
  1080. /*
  1081. * balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw
  1082. */
  1083. if (unlikely(balanced_dirty_ratelimit > write_bw))
  1084. balanced_dirty_ratelimit = write_bw;
  1085. /*
  1086. * We could safely do this and return immediately:
  1087. *
  1088. * wb->dirty_ratelimit = balanced_dirty_ratelimit;
  1089. *
  1090. * However to get a more stable dirty_ratelimit, the below elaborated
  1091. * code makes use of task_ratelimit to filter out singular points and
  1092. * limit the step size.
  1093. *
  1094. * The below code essentially only uses the relative value of
  1095. *
  1096. * task_ratelimit - dirty_ratelimit
  1097. * = (pos_ratio - 1) * dirty_ratelimit
  1098. *
  1099. * which reflects the direction and size of dirty position error.
  1100. */
  1101. /*
  1102. * dirty_ratelimit will follow balanced_dirty_ratelimit iff
  1103. * task_ratelimit is on the same side of dirty_ratelimit, too.
  1104. * For example, when
  1105. * - dirty_ratelimit > balanced_dirty_ratelimit
  1106. * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
  1107. * lowering dirty_ratelimit will help meet both the position and rate
  1108. * control targets. Otherwise, don't update dirty_ratelimit if it will
  1109. * only help meet the rate target. After all, what the users ultimately
  1110. * feel and care are stable dirty rate and small position error.
  1111. *
  1112. * |task_ratelimit - dirty_ratelimit| is used to limit the step size
  1113. * and filter out the singular points of balanced_dirty_ratelimit. Which
  1114. * keeps jumping around randomly and can even leap far away at times
  1115. * due to the small 200ms estimation period of dirty_rate (we want to
  1116. * keep that period small to reduce time lags).
  1117. */
  1118. step = 0;
  1119. /*
  1120. * For strictlimit case, calculations above were based on wb counters
  1121. * and limits (starting from pos_ratio = wb_position_ratio() and up to
  1122. * balanced_dirty_ratelimit = task_ratelimit * write_bw / dirty_rate).
  1123. * Hence, to calculate "step" properly, we have to use wb_dirty as
  1124. * "dirty" and wb_setpoint as "setpoint".
  1125. *
  1126. * We rampup dirty_ratelimit forcibly if wb_dirty is low because
  1127. * it's possible that wb_thresh is close to zero due to inactivity
  1128. * of backing device.
  1129. */
  1130. if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
  1131. dirty = dtc->wb_dirty;
  1132. if (dtc->wb_dirty < 8)
  1133. setpoint = dtc->wb_dirty + 1;
  1134. else
  1135. setpoint = (dtc->wb_thresh + dtc->wb_bg_thresh) / 2;
  1136. }
  1137. if (dirty < setpoint) {
  1138. x = min3(wb->balanced_dirty_ratelimit,
  1139. balanced_dirty_ratelimit, task_ratelimit);
  1140. if (dirty_ratelimit < x)
  1141. step = x - dirty_ratelimit;
  1142. } else {
  1143. x = max3(wb->balanced_dirty_ratelimit,
  1144. balanced_dirty_ratelimit, task_ratelimit);
  1145. if (dirty_ratelimit > x)
  1146. step = dirty_ratelimit - x;
  1147. }
  1148. /*
  1149. * Don't pursue 100% rate matching. It's impossible since the balanced
  1150. * rate itself is constantly fluctuating. So decrease the track speed
  1151. * when it gets close to the target. Helps eliminate pointless tremors.
  1152. */
  1153. shift = dirty_ratelimit / (2 * step + 1);
  1154. if (shift < BITS_PER_LONG)
  1155. step = DIV_ROUND_UP(step >> shift, 8);
  1156. else
  1157. step = 0;
  1158. if (dirty_ratelimit < balanced_dirty_ratelimit)
  1159. dirty_ratelimit += step;
  1160. else
  1161. dirty_ratelimit -= step;
  1162. WRITE_ONCE(wb->dirty_ratelimit, max(dirty_ratelimit, 1UL));
  1163. wb->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
  1164. trace_bdi_dirty_ratelimit(wb, dirty_rate, task_ratelimit);
  1165. }
  1166. static void __wb_update_bandwidth(struct dirty_throttle_control *gdtc,
  1167. struct dirty_throttle_control *mdtc,
  1168. bool update_ratelimit)
  1169. {
  1170. struct bdi_writeback *wb = gdtc->wb;
  1171. unsigned long now = jiffies;
  1172. unsigned long elapsed;
  1173. unsigned long dirtied;
  1174. unsigned long written;
  1175. spin_lock(&wb->list_lock);
  1176. /*
  1177. * Lockless checks for elapsed time are racy and delayed update after
  1178. * IO completion doesn't do it at all (to make sure written pages are
  1179. * accounted reasonably quickly). Make sure elapsed >= 1 to avoid
  1180. * division errors.
  1181. */
  1182. elapsed = max(now - wb->bw_time_stamp, 1UL);
  1183. dirtied = percpu_counter_read(&wb->stat[WB_DIRTIED]);
  1184. written = percpu_counter_read(&wb->stat[WB_WRITTEN]);
  1185. if (update_ratelimit) {
  1186. domain_update_dirty_limit(gdtc, now);
  1187. wb_update_dirty_ratelimit(gdtc, dirtied, elapsed);
  1188. /*
  1189. * @mdtc is always NULL if !CGROUP_WRITEBACK but the
  1190. * compiler has no way to figure that out. Help it.
  1191. */
  1192. if (IS_ENABLED(CONFIG_CGROUP_WRITEBACK) && mdtc) {
  1193. domain_update_dirty_limit(mdtc, now);
  1194. wb_update_dirty_ratelimit(mdtc, dirtied, elapsed);
  1195. }
  1196. }
  1197. wb_update_write_bandwidth(wb, elapsed, written);
  1198. wb->dirtied_stamp = dirtied;
  1199. wb->written_stamp = written;
  1200. WRITE_ONCE(wb->bw_time_stamp, now);
  1201. spin_unlock(&wb->list_lock);
  1202. }
  1203. void wb_update_bandwidth(struct bdi_writeback *wb)
  1204. {
  1205. struct dirty_throttle_control gdtc = { GDTC_INIT(wb) };
  1206. __wb_update_bandwidth(&gdtc, NULL, false);
  1207. }
  1208. /* Interval after which we consider wb idle and don't estimate bandwidth */
  1209. #define WB_BANDWIDTH_IDLE_JIF (HZ)
  1210. static void wb_bandwidth_estimate_start(struct bdi_writeback *wb)
  1211. {
  1212. unsigned long now = jiffies;
  1213. unsigned long elapsed = now - READ_ONCE(wb->bw_time_stamp);
  1214. if (elapsed > WB_BANDWIDTH_IDLE_JIF &&
  1215. !atomic_read(&wb->writeback_inodes)) {
  1216. spin_lock(&wb->list_lock);
  1217. wb->dirtied_stamp = wb_stat(wb, WB_DIRTIED);
  1218. wb->written_stamp = wb_stat(wb, WB_WRITTEN);
  1219. WRITE_ONCE(wb->bw_time_stamp, now);
  1220. spin_unlock(&wb->list_lock);
  1221. }
  1222. }
  1223. /*
  1224. * After a task dirtied this many pages, balance_dirty_pages_ratelimited()
  1225. * will look to see if it needs to start dirty throttling.
  1226. *
  1227. * If dirty_poll_interval is too low, big NUMA machines will call the expensive
  1228. * global_zone_page_state() too often. So scale it near-sqrt to the safety margin
  1229. * (the number of pages we may dirty without exceeding the dirty limits).
  1230. */
  1231. static unsigned long dirty_poll_interval(unsigned long dirty,
  1232. unsigned long thresh)
  1233. {
  1234. if (thresh > dirty)
  1235. return 1UL << (ilog2(thresh - dirty) >> 1);
  1236. return 1;
  1237. }
  1238. static unsigned long wb_max_pause(struct bdi_writeback *wb,
  1239. unsigned long wb_dirty)
  1240. {
  1241. unsigned long bw = READ_ONCE(wb->avg_write_bandwidth);
  1242. unsigned long t;
  1243. /*
  1244. * Limit pause time for small memory systems. If sleeping for too long
  1245. * time, a small pool of dirty/writeback pages may go empty and disk go
  1246. * idle.
  1247. *
  1248. * 8 serves as the safety ratio.
  1249. */
  1250. t = wb_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
  1251. t++;
  1252. return min_t(unsigned long, t, MAX_PAUSE);
  1253. }
  1254. static long wb_min_pause(struct bdi_writeback *wb,
  1255. long max_pause,
  1256. unsigned long task_ratelimit,
  1257. unsigned long dirty_ratelimit,
  1258. int *nr_dirtied_pause)
  1259. {
  1260. long hi = ilog2(READ_ONCE(wb->avg_write_bandwidth));
  1261. long lo = ilog2(READ_ONCE(wb->dirty_ratelimit));
  1262. long t; /* target pause */
  1263. long pause; /* estimated next pause */
  1264. int pages; /* target nr_dirtied_pause */
  1265. /* target for 10ms pause on 1-dd case */
  1266. t = max(1, HZ / 100);
  1267. /*
  1268. * Scale up pause time for concurrent dirtiers in order to reduce CPU
  1269. * overheads.
  1270. *
  1271. * (N * 10ms) on 2^N concurrent tasks.
  1272. */
  1273. if (hi > lo)
  1274. t += (hi - lo) * (10 * HZ) / 1024;
  1275. /*
  1276. * This is a bit convoluted. We try to base the next nr_dirtied_pause
  1277. * on the much more stable dirty_ratelimit. However the next pause time
  1278. * will be computed based on task_ratelimit and the two rate limits may
  1279. * depart considerably at some time. Especially if task_ratelimit goes
  1280. * below dirty_ratelimit/2 and the target pause is max_pause, the next
  1281. * pause time will be max_pause*2 _trimmed down_ to max_pause. As a
  1282. * result task_ratelimit won't be executed faithfully, which could
  1283. * eventually bring down dirty_ratelimit.
  1284. *
  1285. * We apply two rules to fix it up:
  1286. * 1) try to estimate the next pause time and if necessary, use a lower
  1287. * nr_dirtied_pause so as not to exceed max_pause. When this happens,
  1288. * nr_dirtied_pause will be "dancing" with task_ratelimit.
  1289. * 2) limit the target pause time to max_pause/2, so that the normal
  1290. * small fluctuations of task_ratelimit won't trigger rule (1) and
  1291. * nr_dirtied_pause will remain as stable as dirty_ratelimit.
  1292. */
  1293. t = min(t, 1 + max_pause / 2);
  1294. pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
  1295. /*
  1296. * Tiny nr_dirtied_pause is found to hurt I/O performance in the test
  1297. * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}.
  1298. * When the 16 consecutive reads are often interrupted by some dirty
  1299. * throttling pause during the async writes, cfq will go into idles
  1300. * (deadline is fine). So push nr_dirtied_pause as high as possible
  1301. * until reaches DIRTY_POLL_THRESH=32 pages.
  1302. */
  1303. if (pages < DIRTY_POLL_THRESH) {
  1304. t = max_pause;
  1305. pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
  1306. if (pages > DIRTY_POLL_THRESH) {
  1307. pages = DIRTY_POLL_THRESH;
  1308. t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
  1309. }
  1310. }
  1311. pause = HZ * pages / (task_ratelimit + 1);
  1312. if (pause > max_pause) {
  1313. t = max_pause;
  1314. pages = task_ratelimit * t / roundup_pow_of_two(HZ);
  1315. }
  1316. *nr_dirtied_pause = pages;
  1317. /*
  1318. * The minimal pause time will normally be half the target pause time.
  1319. */
  1320. return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
  1321. }
  1322. static inline void wb_dirty_limits(struct dirty_throttle_control *dtc)
  1323. {
  1324. struct bdi_writeback *wb = dtc->wb;
  1325. unsigned long wb_reclaimable;
  1326. /*
  1327. * wb_thresh is not treated as some limiting factor as
  1328. * dirty_thresh, due to reasons
  1329. * - in JBOD setup, wb_thresh can fluctuate a lot
  1330. * - in a system with HDD and USB key, the USB key may somehow
  1331. * go into state (wb_dirty >> wb_thresh) either because
  1332. * wb_dirty starts high, or because wb_thresh drops low.
  1333. * In this case we don't want to hard throttle the USB key
  1334. * dirtiers for 100 seconds until wb_dirty drops under
  1335. * wb_thresh. Instead the auxiliary wb control line in
  1336. * wb_position_ratio() will let the dirtier task progress
  1337. * at some rate <= (write_bw / 2) for bringing down wb_dirty.
  1338. */
  1339. dtc->wb_thresh = __wb_calc_thresh(dtc);
  1340. dtc->wb_bg_thresh = dtc->thresh ?
  1341. div_u64((u64)dtc->wb_thresh * dtc->bg_thresh, dtc->thresh) : 0;
  1342. /*
  1343. * In order to avoid the stacked BDI deadlock we need
  1344. * to ensure we accurately count the 'dirty' pages when
  1345. * the threshold is low.
  1346. *
  1347. * Otherwise it would be possible to get thresh+n pages
  1348. * reported dirty, even though there are thresh-m pages
  1349. * actually dirty; with m+n sitting in the percpu
  1350. * deltas.
  1351. */
  1352. if (dtc->wb_thresh < 2 * wb_stat_error()) {
  1353. wb_reclaimable = wb_stat_sum(wb, WB_RECLAIMABLE);
  1354. dtc->wb_dirty = wb_reclaimable + wb_stat_sum(wb, WB_WRITEBACK);
  1355. } else {
  1356. wb_reclaimable = wb_stat(wb, WB_RECLAIMABLE);
  1357. dtc->wb_dirty = wb_reclaimable + wb_stat(wb, WB_WRITEBACK);
  1358. }
  1359. }
  1360. /*
  1361. * balance_dirty_pages() must be called by processes which are generating dirty
  1362. * data. It looks at the number of dirty pages in the machine and will force
  1363. * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
  1364. * If we're over `background_thresh' then the writeback threads are woken to
  1365. * perform some writeout.
  1366. */
  1367. static int balance_dirty_pages(struct bdi_writeback *wb,
  1368. unsigned long pages_dirtied, unsigned int flags)
  1369. {
  1370. struct dirty_throttle_control gdtc_stor = { GDTC_INIT(wb) };
  1371. struct dirty_throttle_control mdtc_stor = { MDTC_INIT(wb, &gdtc_stor) };
  1372. struct dirty_throttle_control * const gdtc = &gdtc_stor;
  1373. struct dirty_throttle_control * const mdtc = mdtc_valid(&mdtc_stor) ?
  1374. &mdtc_stor : NULL;
  1375. struct dirty_throttle_control *sdtc;
  1376. unsigned long nr_reclaimable; /* = file_dirty */
  1377. long period;
  1378. long pause;
  1379. long max_pause;
  1380. long min_pause;
  1381. int nr_dirtied_pause;
  1382. bool dirty_exceeded = false;
  1383. unsigned long task_ratelimit;
  1384. unsigned long dirty_ratelimit;
  1385. struct backing_dev_info *bdi = wb->bdi;
  1386. bool strictlimit = bdi->capabilities & BDI_CAP_STRICTLIMIT;
  1387. unsigned long start_time = jiffies;
  1388. int ret = 0;
  1389. for (;;) {
  1390. unsigned long now = jiffies;
  1391. unsigned long dirty, thresh, bg_thresh;
  1392. unsigned long m_dirty = 0; /* stop bogus uninit warnings */
  1393. unsigned long m_thresh = 0;
  1394. unsigned long m_bg_thresh = 0;
  1395. nr_reclaimable = global_node_page_state(NR_FILE_DIRTY);
  1396. gdtc->avail = global_dirtyable_memory();
  1397. gdtc->dirty = nr_reclaimable + global_node_page_state(NR_WRITEBACK);
  1398. domain_dirty_limits(gdtc);
  1399. if (unlikely(strictlimit)) {
  1400. wb_dirty_limits(gdtc);
  1401. dirty = gdtc->wb_dirty;
  1402. thresh = gdtc->wb_thresh;
  1403. bg_thresh = gdtc->wb_bg_thresh;
  1404. } else {
  1405. dirty = gdtc->dirty;
  1406. thresh = gdtc->thresh;
  1407. bg_thresh = gdtc->bg_thresh;
  1408. }
  1409. if (mdtc) {
  1410. unsigned long filepages, headroom, writeback;
  1411. /*
  1412. * If @wb belongs to !root memcg, repeat the same
  1413. * basic calculations for the memcg domain.
  1414. */
  1415. mem_cgroup_wb_stats(wb, &filepages, &headroom,
  1416. &mdtc->dirty, &writeback);
  1417. mdtc->dirty += writeback;
  1418. mdtc_calc_avail(mdtc, filepages, headroom);
  1419. domain_dirty_limits(mdtc);
  1420. if (unlikely(strictlimit)) {
  1421. wb_dirty_limits(mdtc);
  1422. m_dirty = mdtc->wb_dirty;
  1423. m_thresh = mdtc->wb_thresh;
  1424. m_bg_thresh = mdtc->wb_bg_thresh;
  1425. } else {
  1426. m_dirty = mdtc->dirty;
  1427. m_thresh = mdtc->thresh;
  1428. m_bg_thresh = mdtc->bg_thresh;
  1429. }
  1430. }
  1431. /*
  1432. * In laptop mode, we wait until hitting the higher threshold
  1433. * before starting background writeout, and then write out all
  1434. * the way down to the lower threshold. So slow writers cause
  1435. * minimal disk activity.
  1436. *
  1437. * In normal mode, we start background writeout at the lower
  1438. * background_thresh, to keep the amount of dirty memory low.
  1439. */
  1440. if (!laptop_mode && nr_reclaimable > gdtc->bg_thresh &&
  1441. !writeback_in_progress(wb))
  1442. wb_start_background_writeback(wb);
  1443. /*
  1444. * Throttle it only when the background writeback cannot
  1445. * catch-up. This avoids (excessively) small writeouts
  1446. * when the wb limits are ramping up in case of !strictlimit.
  1447. *
  1448. * In strictlimit case make decision based on the wb counters
  1449. * and limits. Small writeouts when the wb limits are ramping
  1450. * up are the price we consciously pay for strictlimit-ing.
  1451. *
  1452. * If memcg domain is in effect, @dirty should be under
  1453. * both global and memcg freerun ceilings.
  1454. */
  1455. if (dirty <= dirty_freerun_ceiling(thresh, bg_thresh) &&
  1456. (!mdtc ||
  1457. m_dirty <= dirty_freerun_ceiling(m_thresh, m_bg_thresh))) {
  1458. unsigned long intv;
  1459. unsigned long m_intv;
  1460. free_running:
  1461. intv = dirty_poll_interval(dirty, thresh);
  1462. m_intv = ULONG_MAX;
  1463. current->dirty_paused_when = now;
  1464. current->nr_dirtied = 0;
  1465. if (mdtc)
  1466. m_intv = dirty_poll_interval(m_dirty, m_thresh);
  1467. current->nr_dirtied_pause = min(intv, m_intv);
  1468. break;
  1469. }
  1470. /* Start writeback even when in laptop mode */
  1471. if (unlikely(!writeback_in_progress(wb)))
  1472. wb_start_background_writeback(wb);
  1473. mem_cgroup_flush_foreign(wb);
  1474. /*
  1475. * Calculate global domain's pos_ratio and select the
  1476. * global dtc by default.
  1477. */
  1478. if (!strictlimit) {
  1479. wb_dirty_limits(gdtc);
  1480. if ((current->flags & PF_LOCAL_THROTTLE) &&
  1481. gdtc->wb_dirty <
  1482. dirty_freerun_ceiling(gdtc->wb_thresh,
  1483. gdtc->wb_bg_thresh))
  1484. /*
  1485. * LOCAL_THROTTLE tasks must not be throttled
  1486. * when below the per-wb freerun ceiling.
  1487. */
  1488. goto free_running;
  1489. }
  1490. dirty_exceeded = (gdtc->wb_dirty > gdtc->wb_thresh) &&
  1491. ((gdtc->dirty > gdtc->thresh) || strictlimit);
  1492. wb_position_ratio(gdtc);
  1493. sdtc = gdtc;
  1494. if (mdtc) {
  1495. /*
  1496. * If memcg domain is in effect, calculate its
  1497. * pos_ratio. @wb should satisfy constraints from
  1498. * both global and memcg domains. Choose the one
  1499. * w/ lower pos_ratio.
  1500. */
  1501. if (!strictlimit) {
  1502. wb_dirty_limits(mdtc);
  1503. if ((current->flags & PF_LOCAL_THROTTLE) &&
  1504. mdtc->wb_dirty <
  1505. dirty_freerun_ceiling(mdtc->wb_thresh,
  1506. mdtc->wb_bg_thresh))
  1507. /*
  1508. * LOCAL_THROTTLE tasks must not be
  1509. * throttled when below the per-wb
  1510. * freerun ceiling.
  1511. */
  1512. goto free_running;
  1513. }
  1514. dirty_exceeded |= (mdtc->wb_dirty > mdtc->wb_thresh) &&
  1515. ((mdtc->dirty > mdtc->thresh) || strictlimit);
  1516. wb_position_ratio(mdtc);
  1517. if (mdtc->pos_ratio < gdtc->pos_ratio)
  1518. sdtc = mdtc;
  1519. }
  1520. if (dirty_exceeded != wb->dirty_exceeded)
  1521. wb->dirty_exceeded = dirty_exceeded;
  1522. if (time_is_before_jiffies(READ_ONCE(wb->bw_time_stamp) +
  1523. BANDWIDTH_INTERVAL))
  1524. __wb_update_bandwidth(gdtc, mdtc, true);
  1525. /* throttle according to the chosen dtc */
  1526. dirty_ratelimit = READ_ONCE(wb->dirty_ratelimit);
  1527. task_ratelimit = ((u64)dirty_ratelimit * sdtc->pos_ratio) >>
  1528. RATELIMIT_CALC_SHIFT;
  1529. max_pause = wb_max_pause(wb, sdtc->wb_dirty);
  1530. min_pause = wb_min_pause(wb, max_pause,
  1531. task_ratelimit, dirty_ratelimit,
  1532. &nr_dirtied_pause);
  1533. if (unlikely(task_ratelimit == 0)) {
  1534. period = max_pause;
  1535. pause = max_pause;
  1536. goto pause;
  1537. }
  1538. period = HZ * pages_dirtied / task_ratelimit;
  1539. pause = period;
  1540. if (current->dirty_paused_when)
  1541. pause -= now - current->dirty_paused_when;
  1542. /*
  1543. * For less than 1s think time (ext3/4 may block the dirtier
  1544. * for up to 800ms from time to time on 1-HDD; so does xfs,
  1545. * however at much less frequency), try to compensate it in
  1546. * future periods by updating the virtual time; otherwise just
  1547. * do a reset, as it may be a light dirtier.
  1548. */
  1549. if (pause < min_pause) {
  1550. trace_balance_dirty_pages(wb,
  1551. sdtc->thresh,
  1552. sdtc->bg_thresh,
  1553. sdtc->dirty,
  1554. sdtc->wb_thresh,
  1555. sdtc->wb_dirty,
  1556. dirty_ratelimit,
  1557. task_ratelimit,
  1558. pages_dirtied,
  1559. period,
  1560. min(pause, 0L),
  1561. start_time);
  1562. if (pause < -HZ) {
  1563. current->dirty_paused_when = now;
  1564. current->nr_dirtied = 0;
  1565. } else if (period) {
  1566. current->dirty_paused_when += period;
  1567. current->nr_dirtied = 0;
  1568. } else if (current->nr_dirtied_pause <= pages_dirtied)
  1569. current->nr_dirtied_pause += pages_dirtied;
  1570. break;
  1571. }
  1572. if (unlikely(pause > max_pause)) {
  1573. /* for occasional dropped task_ratelimit */
  1574. now += min(pause - max_pause, max_pause);
  1575. pause = max_pause;
  1576. }
  1577. pause:
  1578. trace_balance_dirty_pages(wb,
  1579. sdtc->thresh,
  1580. sdtc->bg_thresh,
  1581. sdtc->dirty,
  1582. sdtc->wb_thresh,
  1583. sdtc->wb_dirty,
  1584. dirty_ratelimit,
  1585. task_ratelimit,
  1586. pages_dirtied,
  1587. period,
  1588. pause,
  1589. start_time);
  1590. if (flags & BDP_ASYNC) {
  1591. ret = -EAGAIN;
  1592. break;
  1593. }
  1594. __set_current_state(TASK_KILLABLE);
  1595. wb->dirty_sleep = now;
  1596. io_schedule_timeout(pause);
  1597. current->dirty_paused_when = now + pause;
  1598. current->nr_dirtied = 0;
  1599. current->nr_dirtied_pause = nr_dirtied_pause;
  1600. /*
  1601. * This is typically equal to (dirty < thresh) and can also
  1602. * keep "1000+ dd on a slow USB stick" under control.
  1603. */
  1604. if (task_ratelimit)
  1605. break;
  1606. /*
  1607. * In the case of an unresponsive NFS server and the NFS dirty
  1608. * pages exceeds dirty_thresh, give the other good wb's a pipe
  1609. * to go through, so that tasks on them still remain responsive.
  1610. *
  1611. * In theory 1 page is enough to keep the consumer-producer
  1612. * pipe going: the flusher cleans 1 page => the task dirties 1
  1613. * more page. However wb_dirty has accounting errors. So use
  1614. * the larger and more IO friendly wb_stat_error.
  1615. */
  1616. if (sdtc->wb_dirty <= wb_stat_error())
  1617. break;
  1618. if (fatal_signal_pending(current))
  1619. break;
  1620. }
  1621. return ret;
  1622. }
  1623. static DEFINE_PER_CPU(int, bdp_ratelimits);
  1624. /*
  1625. * Normal tasks are throttled by
  1626. * loop {
  1627. * dirty tsk->nr_dirtied_pause pages;
  1628. * take a snap in balance_dirty_pages();
  1629. * }
  1630. * However there is a worst case. If every task exit immediately when dirtied
  1631. * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
  1632. * called to throttle the page dirties. The solution is to save the not yet
  1633. * throttled page dirties in dirty_throttle_leaks on task exit and charge them
  1634. * randomly into the running tasks. This works well for the above worst case,
  1635. * as the new task will pick up and accumulate the old task's leaked dirty
  1636. * count and eventually get throttled.
  1637. */
  1638. DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
  1639. /**
  1640. * balance_dirty_pages_ratelimited_flags - Balance dirty memory state.
  1641. * @mapping: address_space which was dirtied.
  1642. * @flags: BDP flags.
  1643. *
  1644. * Processes which are dirtying memory should call in here once for each page
  1645. * which was newly dirtied. The function will periodically check the system's
  1646. * dirty state and will initiate writeback if needed.
  1647. *
  1648. * See balance_dirty_pages_ratelimited() for details.
  1649. *
  1650. * Return: If @flags contains BDP_ASYNC, it may return -EAGAIN to
  1651. * indicate that memory is out of balance and the caller must wait
  1652. * for I/O to complete. Otherwise, it will return 0 to indicate
  1653. * that either memory was already in balance, or it was able to sleep
  1654. * until the amount of dirty memory returned to balance.
  1655. */
  1656. int balance_dirty_pages_ratelimited_flags(struct address_space *mapping,
  1657. unsigned int flags)
  1658. {
  1659. struct inode *inode = mapping->host;
  1660. struct backing_dev_info *bdi = inode_to_bdi(inode);
  1661. struct bdi_writeback *wb = NULL;
  1662. int ratelimit;
  1663. int ret = 0;
  1664. int *p;
  1665. if (!(bdi->capabilities & BDI_CAP_WRITEBACK))
  1666. return ret;
  1667. trace_android_rvh_ctl_dirty_rate(NULL);
  1668. if (inode_cgwb_enabled(inode))
  1669. wb = wb_get_create_current(bdi, GFP_KERNEL);
  1670. if (!wb)
  1671. wb = &bdi->wb;
  1672. ratelimit = current->nr_dirtied_pause;
  1673. if (wb->dirty_exceeded)
  1674. ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
  1675. preempt_disable();
  1676. /*
  1677. * This prevents one CPU to accumulate too many dirtied pages without
  1678. * calling into balance_dirty_pages(), which can happen when there are
  1679. * 1000+ tasks, all of them start dirtying pages at exactly the same
  1680. * time, hence all honoured too large initial task->nr_dirtied_pause.
  1681. */
  1682. p = this_cpu_ptr(&bdp_ratelimits);
  1683. if (unlikely(current->nr_dirtied >= ratelimit))
  1684. *p = 0;
  1685. else if (unlikely(*p >= ratelimit_pages)) {
  1686. *p = 0;
  1687. ratelimit = 0;
  1688. }
  1689. /*
  1690. * Pick up the dirtied pages by the exited tasks. This avoids lots of
  1691. * short-lived tasks (eg. gcc invocations in a kernel build) escaping
  1692. * the dirty throttling and livelock other long-run dirtiers.
  1693. */
  1694. p = this_cpu_ptr(&dirty_throttle_leaks);
  1695. if (*p > 0 && current->nr_dirtied < ratelimit) {
  1696. unsigned long nr_pages_dirtied;
  1697. nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
  1698. *p -= nr_pages_dirtied;
  1699. current->nr_dirtied += nr_pages_dirtied;
  1700. }
  1701. preempt_enable();
  1702. if (unlikely(current->nr_dirtied >= ratelimit))
  1703. ret = balance_dirty_pages(wb, current->nr_dirtied, flags);
  1704. wb_put(wb);
  1705. return ret;
  1706. }
  1707. EXPORT_SYMBOL_GPL(balance_dirty_pages_ratelimited_flags);
  1708. /**
  1709. * balance_dirty_pages_ratelimited - balance dirty memory state.
  1710. * @mapping: address_space which was dirtied.
  1711. *
  1712. * Processes which are dirtying memory should call in here once for each page
  1713. * which was newly dirtied. The function will periodically check the system's
  1714. * dirty state and will initiate writeback if needed.
  1715. *
  1716. * Once we're over the dirty memory limit we decrease the ratelimiting
  1717. * by a lot, to prevent individual processes from overshooting the limit
  1718. * by (ratelimit_pages) each.
  1719. */
  1720. void balance_dirty_pages_ratelimited(struct address_space *mapping)
  1721. {
  1722. balance_dirty_pages_ratelimited_flags(mapping, 0);
  1723. }
  1724. EXPORT_SYMBOL(balance_dirty_pages_ratelimited);
  1725. /**
  1726. * wb_over_bg_thresh - does @wb need to be written back?
  1727. * @wb: bdi_writeback of interest
  1728. *
  1729. * Determines whether background writeback should keep writing @wb or it's
  1730. * clean enough.
  1731. *
  1732. * Return: %true if writeback should continue.
  1733. */
  1734. bool wb_over_bg_thresh(struct bdi_writeback *wb)
  1735. {
  1736. struct dirty_throttle_control gdtc_stor = { GDTC_INIT(wb) };
  1737. struct dirty_throttle_control mdtc_stor = { MDTC_INIT(wb, &gdtc_stor) };
  1738. struct dirty_throttle_control * const gdtc = &gdtc_stor;
  1739. struct dirty_throttle_control * const mdtc = mdtc_valid(&mdtc_stor) ?
  1740. &mdtc_stor : NULL;
  1741. unsigned long reclaimable;
  1742. unsigned long thresh;
  1743. /*
  1744. * Similar to balance_dirty_pages() but ignores pages being written
  1745. * as we're trying to decide whether to put more under writeback.
  1746. */
  1747. gdtc->avail = global_dirtyable_memory();
  1748. gdtc->dirty = global_node_page_state(NR_FILE_DIRTY);
  1749. domain_dirty_limits(gdtc);
  1750. if (gdtc->dirty > gdtc->bg_thresh)
  1751. return true;
  1752. thresh = wb_calc_thresh(gdtc->wb, gdtc->bg_thresh);
  1753. if (thresh < 2 * wb_stat_error())
  1754. reclaimable = wb_stat_sum(wb, WB_RECLAIMABLE);
  1755. else
  1756. reclaimable = wb_stat(wb, WB_RECLAIMABLE);
  1757. if (reclaimable > thresh)
  1758. return true;
  1759. if (mdtc) {
  1760. unsigned long filepages, headroom, writeback;
  1761. mem_cgroup_wb_stats(wb, &filepages, &headroom, &mdtc->dirty,
  1762. &writeback);
  1763. mdtc_calc_avail(mdtc, filepages, headroom);
  1764. domain_dirty_limits(mdtc); /* ditto, ignore writeback */
  1765. if (mdtc->dirty > mdtc->bg_thresh)
  1766. return true;
  1767. thresh = wb_calc_thresh(mdtc->wb, mdtc->bg_thresh);
  1768. if (thresh < 2 * wb_stat_error())
  1769. reclaimable = wb_stat_sum(wb, WB_RECLAIMABLE);
  1770. else
  1771. reclaimable = wb_stat(wb, WB_RECLAIMABLE);
  1772. if (reclaimable > thresh)
  1773. return true;
  1774. }
  1775. return false;
  1776. }
  1777. #ifdef CONFIG_SYSCTL
  1778. /*
  1779. * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
  1780. */
  1781. static int dirty_writeback_centisecs_handler(struct ctl_table *table, int write,
  1782. void *buffer, size_t *length, loff_t *ppos)
  1783. {
  1784. unsigned int old_interval = dirty_writeback_interval;
  1785. int ret;
  1786. ret = proc_dointvec(table, write, buffer, length, ppos);
  1787. /*
  1788. * Writing 0 to dirty_writeback_interval will disable periodic writeback
  1789. * and a different non-zero value will wakeup the writeback threads.
  1790. * wb_wakeup_delayed() would be more appropriate, but it's a pain to
  1791. * iterate over all bdis and wbs.
  1792. * The reason we do this is to make the change take effect immediately.
  1793. */
  1794. if (!ret && write && dirty_writeback_interval &&
  1795. dirty_writeback_interval != old_interval)
  1796. wakeup_flusher_threads(WB_REASON_PERIODIC);
  1797. return ret;
  1798. }
  1799. #endif
  1800. void laptop_mode_timer_fn(struct timer_list *t)
  1801. {
  1802. struct backing_dev_info *backing_dev_info =
  1803. from_timer(backing_dev_info, t, laptop_mode_wb_timer);
  1804. wakeup_flusher_threads_bdi(backing_dev_info, WB_REASON_LAPTOP_TIMER);
  1805. }
  1806. /*
  1807. * We've spun up the disk and we're in laptop mode: schedule writeback
  1808. * of all dirty data a few seconds from now. If the flush is already scheduled
  1809. * then push it back - the user is still using the disk.
  1810. */
  1811. void laptop_io_completion(struct backing_dev_info *info)
  1812. {
  1813. mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
  1814. }
  1815. /*
  1816. * We're in laptop mode and we've just synced. The sync's writes will have
  1817. * caused another writeback to be scheduled by laptop_io_completion.
  1818. * Nothing needs to be written back anymore, so we unschedule the writeback.
  1819. */
  1820. void laptop_sync_completion(void)
  1821. {
  1822. struct backing_dev_info *bdi;
  1823. rcu_read_lock();
  1824. list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
  1825. del_timer(&bdi->laptop_mode_wb_timer);
  1826. rcu_read_unlock();
  1827. }
  1828. /*
  1829. * If ratelimit_pages is too high then we can get into dirty-data overload
  1830. * if a large number of processes all perform writes at the same time.
  1831. *
  1832. * Here we set ratelimit_pages to a level which ensures that when all CPUs are
  1833. * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
  1834. * thresholds.
  1835. */
  1836. void writeback_set_ratelimit(void)
  1837. {
  1838. struct wb_domain *dom = &global_wb_domain;
  1839. unsigned long background_thresh;
  1840. unsigned long dirty_thresh;
  1841. global_dirty_limits(&background_thresh, &dirty_thresh);
  1842. dom->dirty_limit = dirty_thresh;
  1843. ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
  1844. if (ratelimit_pages < 16)
  1845. ratelimit_pages = 16;
  1846. }
  1847. static int page_writeback_cpu_online(unsigned int cpu)
  1848. {
  1849. writeback_set_ratelimit();
  1850. return 0;
  1851. }
  1852. #ifdef CONFIG_SYSCTL
  1853. /* this is needed for the proc_doulongvec_minmax of vm_dirty_bytes */
  1854. static const unsigned long dirty_bytes_min = 2 * PAGE_SIZE;
  1855. static struct ctl_table vm_page_writeback_sysctls[] = {
  1856. {
  1857. .procname = "dirty_background_ratio",
  1858. .data = &dirty_background_ratio,
  1859. .maxlen = sizeof(dirty_background_ratio),
  1860. .mode = 0644,
  1861. .proc_handler = dirty_background_ratio_handler,
  1862. .extra1 = SYSCTL_ZERO,
  1863. .extra2 = SYSCTL_ONE_HUNDRED,
  1864. },
  1865. {
  1866. .procname = "dirty_background_bytes",
  1867. .data = &dirty_background_bytes,
  1868. .maxlen = sizeof(dirty_background_bytes),
  1869. .mode = 0644,
  1870. .proc_handler = dirty_background_bytes_handler,
  1871. .extra1 = SYSCTL_LONG_ONE,
  1872. },
  1873. {
  1874. .procname = "dirty_ratio",
  1875. .data = &vm_dirty_ratio,
  1876. .maxlen = sizeof(vm_dirty_ratio),
  1877. .mode = 0644,
  1878. .proc_handler = dirty_ratio_handler,
  1879. .extra1 = SYSCTL_ZERO,
  1880. .extra2 = SYSCTL_ONE_HUNDRED,
  1881. },
  1882. {
  1883. .procname = "dirty_bytes",
  1884. .data = &vm_dirty_bytes,
  1885. .maxlen = sizeof(vm_dirty_bytes),
  1886. .mode = 0644,
  1887. .proc_handler = dirty_bytes_handler,
  1888. .extra1 = (void *)&dirty_bytes_min,
  1889. },
  1890. {
  1891. .procname = "dirty_writeback_centisecs",
  1892. .data = &dirty_writeback_interval,
  1893. .maxlen = sizeof(dirty_writeback_interval),
  1894. .mode = 0644,
  1895. .proc_handler = dirty_writeback_centisecs_handler,
  1896. },
  1897. {
  1898. .procname = "dirty_expire_centisecs",
  1899. .data = &dirty_expire_interval,
  1900. .maxlen = sizeof(dirty_expire_interval),
  1901. .mode = 0644,
  1902. .proc_handler = proc_dointvec_minmax,
  1903. .extra1 = SYSCTL_ZERO,
  1904. },
  1905. #ifdef CONFIG_HIGHMEM
  1906. {
  1907. .procname = "highmem_is_dirtyable",
  1908. .data = &vm_highmem_is_dirtyable,
  1909. .maxlen = sizeof(vm_highmem_is_dirtyable),
  1910. .mode = 0644,
  1911. .proc_handler = proc_dointvec_minmax,
  1912. .extra1 = SYSCTL_ZERO,
  1913. .extra2 = SYSCTL_ONE,
  1914. },
  1915. #endif
  1916. {
  1917. .procname = "laptop_mode",
  1918. .data = &laptop_mode,
  1919. .maxlen = sizeof(laptop_mode),
  1920. .mode = 0644,
  1921. .proc_handler = proc_dointvec_jiffies,
  1922. },
  1923. {}
  1924. };
  1925. #endif
  1926. /*
  1927. * Called early on to tune the page writeback dirty limits.
  1928. *
  1929. * We used to scale dirty pages according to how total memory
  1930. * related to pages that could be allocated for buffers.
  1931. *
  1932. * However, that was when we used "dirty_ratio" to scale with
  1933. * all memory, and we don't do that any more. "dirty_ratio"
  1934. * is now applied to total non-HIGHPAGE memory, and as such we can't
  1935. * get into the old insane situation any more where we had
  1936. * large amounts of dirty pages compared to a small amount of
  1937. * non-HIGHMEM memory.
  1938. *
  1939. * But we might still want to scale the dirty_ratio by how
  1940. * much memory the box has..
  1941. */
  1942. void __init page_writeback_init(void)
  1943. {
  1944. BUG_ON(wb_domain_init(&global_wb_domain, GFP_KERNEL));
  1945. cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "mm/writeback:online",
  1946. page_writeback_cpu_online, NULL);
  1947. cpuhp_setup_state(CPUHP_MM_WRITEBACK_DEAD, "mm/writeback:dead", NULL,
  1948. page_writeback_cpu_online);
  1949. #ifdef CONFIG_SYSCTL
  1950. register_sysctl_init("vm", vm_page_writeback_sysctls);
  1951. #endif
  1952. }
  1953. /**
  1954. * tag_pages_for_writeback - tag pages to be written by write_cache_pages
  1955. * @mapping: address space structure to write
  1956. * @start: starting page index
  1957. * @end: ending page index (inclusive)
  1958. *
  1959. * This function scans the page range from @start to @end (inclusive) and tags
  1960. * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
  1961. * that write_cache_pages (or whoever calls this function) will then use
  1962. * TOWRITE tag to identify pages eligible for writeback. This mechanism is
  1963. * used to avoid livelocking of writeback by a process steadily creating new
  1964. * dirty pages in the file (thus it is important for this function to be quick
  1965. * so that it can tag pages faster than a dirtying process can create them).
  1966. */
  1967. void tag_pages_for_writeback(struct address_space *mapping,
  1968. pgoff_t start, pgoff_t end)
  1969. {
  1970. XA_STATE(xas, &mapping->i_pages, start);
  1971. unsigned int tagged = 0;
  1972. void *page;
  1973. xas_lock_irq(&xas);
  1974. xas_for_each_marked(&xas, page, end, PAGECACHE_TAG_DIRTY) {
  1975. xas_set_mark(&xas, PAGECACHE_TAG_TOWRITE);
  1976. if (++tagged % XA_CHECK_SCHED)
  1977. continue;
  1978. xas_pause(&xas);
  1979. xas_unlock_irq(&xas);
  1980. cond_resched();
  1981. xas_lock_irq(&xas);
  1982. }
  1983. xas_unlock_irq(&xas);
  1984. }
  1985. EXPORT_SYMBOL(tag_pages_for_writeback);
  1986. /**
  1987. * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
  1988. * @mapping: address space structure to write
  1989. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1990. * @writepage: function called for each page
  1991. * @data: data passed to writepage function
  1992. *
  1993. * If a page is already under I/O, write_cache_pages() skips it, even
  1994. * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
  1995. * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
  1996. * and msync() need to guarantee that all the data which was dirty at the time
  1997. * the call was made get new I/O started against them. If wbc->sync_mode is
  1998. * WB_SYNC_ALL then we were called for data integrity and we must wait for
  1999. * existing IO to complete.
  2000. *
  2001. * To avoid livelocks (when other process dirties new pages), we first tag
  2002. * pages which should be written back with TOWRITE tag and only then start
  2003. * writing them. For data-integrity sync we have to be careful so that we do
  2004. * not miss some pages (e.g., because some other process has cleared TOWRITE
  2005. * tag we set). The rule we follow is that TOWRITE tag can be cleared only
  2006. * by the process clearing the DIRTY tag (and submitting the page for IO).
  2007. *
  2008. * To avoid deadlocks between range_cyclic writeback and callers that hold
  2009. * pages in PageWriteback to aggregate IO until write_cache_pages() returns,
  2010. * we do not loop back to the start of the file. Doing so causes a page
  2011. * lock/page writeback access order inversion - we should only ever lock
  2012. * multiple pages in ascending page->index order, and looping back to the start
  2013. * of the file violates that rule and causes deadlocks.
  2014. *
  2015. * Return: %0 on success, negative error code otherwise
  2016. */
  2017. int write_cache_pages(struct address_space *mapping,
  2018. struct writeback_control *wbc, writepage_t writepage,
  2019. void *data)
  2020. {
  2021. int ret = 0;
  2022. int done = 0;
  2023. int error;
  2024. struct pagevec pvec;
  2025. int nr_pages;
  2026. pgoff_t index;
  2027. pgoff_t end; /* Inclusive */
  2028. pgoff_t done_index;
  2029. int range_whole = 0;
  2030. xa_mark_t tag;
  2031. pagevec_init(&pvec);
  2032. if (wbc->range_cyclic) {
  2033. index = mapping->writeback_index; /* prev offset */
  2034. end = -1;
  2035. } else {
  2036. index = wbc->range_start >> PAGE_SHIFT;
  2037. end = wbc->range_end >> PAGE_SHIFT;
  2038. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  2039. range_whole = 1;
  2040. }
  2041. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) {
  2042. tag_pages_for_writeback(mapping, index, end);
  2043. tag = PAGECACHE_TAG_TOWRITE;
  2044. } else {
  2045. tag = PAGECACHE_TAG_DIRTY;
  2046. }
  2047. done_index = index;
  2048. while (!done && (index <= end)) {
  2049. int i;
  2050. nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
  2051. tag);
  2052. if (nr_pages == 0)
  2053. break;
  2054. for (i = 0; i < nr_pages; i++) {
  2055. struct page *page = pvec.pages[i];
  2056. done_index = page->index;
  2057. lock_page(page);
  2058. /*
  2059. * Page truncated or invalidated. We can freely skip it
  2060. * then, even for data integrity operations: the page
  2061. * has disappeared concurrently, so there could be no
  2062. * real expectation of this data integrity operation
  2063. * even if there is now a new, dirty page at the same
  2064. * pagecache address.
  2065. */
  2066. if (unlikely(page->mapping != mapping)) {
  2067. continue_unlock:
  2068. unlock_page(page);
  2069. continue;
  2070. }
  2071. if (!PageDirty(page)) {
  2072. /* someone wrote it for us */
  2073. goto continue_unlock;
  2074. }
  2075. if (PageWriteback(page)) {
  2076. if (wbc->sync_mode != WB_SYNC_NONE)
  2077. wait_on_page_writeback(page);
  2078. else
  2079. goto continue_unlock;
  2080. }
  2081. BUG_ON(PageWriteback(page));
  2082. if (!clear_page_dirty_for_io(page))
  2083. goto continue_unlock;
  2084. trace_wbc_writepage(wbc, inode_to_bdi(mapping->host));
  2085. error = (*writepage)(page, wbc, data);
  2086. if (unlikely(error)) {
  2087. /*
  2088. * Handle errors according to the type of
  2089. * writeback. There's no need to continue for
  2090. * background writeback. Just push done_index
  2091. * past this page so media errors won't choke
  2092. * writeout for the entire file. For integrity
  2093. * writeback, we must process the entire dirty
  2094. * set regardless of errors because the fs may
  2095. * still have state to clear for each page. In
  2096. * that case we continue processing and return
  2097. * the first error.
  2098. */
  2099. if (error == AOP_WRITEPAGE_ACTIVATE) {
  2100. unlock_page(page);
  2101. error = 0;
  2102. } else if (wbc->sync_mode != WB_SYNC_ALL) {
  2103. ret = error;
  2104. done_index = page->index + 1;
  2105. done = 1;
  2106. break;
  2107. }
  2108. if (!ret)
  2109. ret = error;
  2110. }
  2111. /*
  2112. * We stop writing back only if we are not doing
  2113. * integrity sync. In case of integrity sync we have to
  2114. * keep going until we have written all the pages
  2115. * we tagged for writeback prior to entering this loop.
  2116. */
  2117. if (--wbc->nr_to_write <= 0 &&
  2118. wbc->sync_mode == WB_SYNC_NONE) {
  2119. done = 1;
  2120. break;
  2121. }
  2122. }
  2123. pagevec_release(&pvec);
  2124. cond_resched();
  2125. }
  2126. /*
  2127. * If we hit the last page and there is more work to be done: wrap
  2128. * back the index back to the start of the file for the next
  2129. * time we are called.
  2130. */
  2131. if (wbc->range_cyclic && !done)
  2132. done_index = 0;
  2133. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  2134. mapping->writeback_index = done_index;
  2135. return ret;
  2136. }
  2137. EXPORT_SYMBOL(write_cache_pages);
  2138. /*
  2139. * Function used by generic_writepages to call the real writepage
  2140. * function and set the mapping flags on error
  2141. */
  2142. static int __writepage(struct page *page, struct writeback_control *wbc,
  2143. void *data)
  2144. {
  2145. struct address_space *mapping = data;
  2146. int ret = mapping->a_ops->writepage(page, wbc);
  2147. mapping_set_error(mapping, ret);
  2148. return ret;
  2149. }
  2150. /**
  2151. * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
  2152. * @mapping: address space structure to write
  2153. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  2154. *
  2155. * This is a library function, which implements the writepages()
  2156. * address_space_operation.
  2157. *
  2158. * Return: %0 on success, negative error code otherwise
  2159. */
  2160. int generic_writepages(struct address_space *mapping,
  2161. struct writeback_control *wbc)
  2162. {
  2163. struct blk_plug plug;
  2164. int ret;
  2165. /* deal with chardevs and other special file */
  2166. if (!mapping->a_ops->writepage)
  2167. return 0;
  2168. blk_start_plug(&plug);
  2169. ret = write_cache_pages(mapping, wbc, __writepage, mapping);
  2170. blk_finish_plug(&plug);
  2171. return ret;
  2172. }
  2173. EXPORT_SYMBOL(generic_writepages);
  2174. int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
  2175. {
  2176. int ret;
  2177. struct bdi_writeback *wb;
  2178. if (wbc->nr_to_write <= 0)
  2179. return 0;
  2180. wb = inode_to_wb_wbc(mapping->host, wbc);
  2181. wb_bandwidth_estimate_start(wb);
  2182. while (1) {
  2183. if (mapping->a_ops->writepages)
  2184. ret = mapping->a_ops->writepages(mapping, wbc);
  2185. else
  2186. ret = generic_writepages(mapping, wbc);
  2187. if ((ret != -ENOMEM) || (wbc->sync_mode != WB_SYNC_ALL))
  2188. break;
  2189. /*
  2190. * Lacking an allocation context or the locality or writeback
  2191. * state of any of the inode's pages, throttle based on
  2192. * writeback activity on the local node. It's as good a
  2193. * guess as any.
  2194. */
  2195. reclaim_throttle(NODE_DATA(numa_node_id()),
  2196. VMSCAN_THROTTLE_WRITEBACK);
  2197. }
  2198. /*
  2199. * Usually few pages are written by now from those we've just submitted
  2200. * but if there's constant writeback being submitted, this makes sure
  2201. * writeback bandwidth is updated once in a while.
  2202. */
  2203. if (time_is_before_jiffies(READ_ONCE(wb->bw_time_stamp) +
  2204. BANDWIDTH_INTERVAL))
  2205. wb_update_bandwidth(wb);
  2206. return ret;
  2207. }
  2208. /**
  2209. * folio_write_one - write out a single folio and wait on I/O.
  2210. * @folio: The folio to write.
  2211. *
  2212. * The folio must be locked by the caller and will be unlocked upon return.
  2213. *
  2214. * Note that the mapping's AS_EIO/AS_ENOSPC flags will be cleared when this
  2215. * function returns.
  2216. *
  2217. * Return: %0 on success, negative error code otherwise
  2218. */
  2219. int folio_write_one(struct folio *folio)
  2220. {
  2221. struct address_space *mapping = folio->mapping;
  2222. int ret = 0;
  2223. struct writeback_control wbc = {
  2224. .sync_mode = WB_SYNC_ALL,
  2225. .nr_to_write = folio_nr_pages(folio),
  2226. };
  2227. BUG_ON(!folio_test_locked(folio));
  2228. folio_wait_writeback(folio);
  2229. if (folio_clear_dirty_for_io(folio)) {
  2230. folio_get(folio);
  2231. ret = mapping->a_ops->writepage(&folio->page, &wbc);
  2232. if (ret == 0)
  2233. folio_wait_writeback(folio);
  2234. folio_put(folio);
  2235. } else {
  2236. folio_unlock(folio);
  2237. }
  2238. if (!ret)
  2239. ret = filemap_check_errors(mapping);
  2240. return ret;
  2241. }
  2242. EXPORT_SYMBOL(folio_write_one);
  2243. /*
  2244. * For address_spaces which do not use buffers nor write back.
  2245. */
  2246. bool noop_dirty_folio(struct address_space *mapping, struct folio *folio)
  2247. {
  2248. if (!folio_test_dirty(folio))
  2249. return !folio_test_set_dirty(folio);
  2250. return false;
  2251. }
  2252. EXPORT_SYMBOL(noop_dirty_folio);
  2253. /*
  2254. * Helper function for set_page_dirty family.
  2255. *
  2256. * Caller must hold lock_page_memcg().
  2257. *
  2258. * NOTE: This relies on being atomic wrt interrupts.
  2259. */
  2260. static void folio_account_dirtied(struct folio *folio,
  2261. struct address_space *mapping)
  2262. {
  2263. struct inode *inode = mapping->host;
  2264. trace_writeback_dirty_folio(folio, mapping);
  2265. if (mapping_can_writeback(mapping)) {
  2266. struct bdi_writeback *wb;
  2267. long nr = folio_nr_pages(folio);
  2268. inode_attach_wb(inode, &folio->page);
  2269. wb = inode_to_wb(inode);
  2270. __lruvec_stat_mod_folio(folio, NR_FILE_DIRTY, nr);
  2271. __zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, nr);
  2272. __node_stat_mod_folio(folio, NR_DIRTIED, nr);
  2273. wb_stat_mod(wb, WB_RECLAIMABLE, nr);
  2274. wb_stat_mod(wb, WB_DIRTIED, nr);
  2275. task_io_account_write(nr * PAGE_SIZE);
  2276. current->nr_dirtied += nr;
  2277. __this_cpu_add(bdp_ratelimits, nr);
  2278. mem_cgroup_track_foreign_dirty(folio, wb);
  2279. }
  2280. }
  2281. /*
  2282. * Helper function for deaccounting dirty page without writeback.
  2283. *
  2284. * Caller must hold lock_page_memcg().
  2285. */
  2286. void folio_account_cleaned(struct folio *folio, struct bdi_writeback *wb)
  2287. {
  2288. long nr = folio_nr_pages(folio);
  2289. lruvec_stat_mod_folio(folio, NR_FILE_DIRTY, -nr);
  2290. zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, -nr);
  2291. wb_stat_mod(wb, WB_RECLAIMABLE, -nr);
  2292. task_io_account_cancelled_write(nr * PAGE_SIZE);
  2293. }
  2294. /*
  2295. * Mark the folio dirty, and set it dirty in the page cache, and mark
  2296. * the inode dirty.
  2297. *
  2298. * If warn is true, then emit a warning if the folio is not uptodate and has
  2299. * not been truncated.
  2300. *
  2301. * The caller must hold lock_page_memcg(). Most callers have the folio
  2302. * locked. A few have the folio blocked from truncation through other
  2303. * means (eg zap_page_range() has it mapped and is holding the page table
  2304. * lock). This can also be called from mark_buffer_dirty(), which I
  2305. * cannot prove is always protected against truncate.
  2306. */
  2307. void __folio_mark_dirty(struct folio *folio, struct address_space *mapping,
  2308. int warn)
  2309. {
  2310. unsigned long flags;
  2311. xa_lock_irqsave(&mapping->i_pages, flags);
  2312. if (folio->mapping) { /* Race with truncate? */
  2313. WARN_ON_ONCE(warn && !folio_test_uptodate(folio));
  2314. folio_account_dirtied(folio, mapping);
  2315. __xa_set_mark(&mapping->i_pages, folio_index(folio),
  2316. PAGECACHE_TAG_DIRTY);
  2317. }
  2318. xa_unlock_irqrestore(&mapping->i_pages, flags);
  2319. }
  2320. /**
  2321. * filemap_dirty_folio - Mark a folio dirty for filesystems which do not use buffer_heads.
  2322. * @mapping: Address space this folio belongs to.
  2323. * @folio: Folio to be marked as dirty.
  2324. *
  2325. * Filesystems which do not use buffer heads should call this function
  2326. * from their set_page_dirty address space operation. It ignores the
  2327. * contents of folio_get_private(), so if the filesystem marks individual
  2328. * blocks as dirty, the filesystem should handle that itself.
  2329. *
  2330. * This is also sometimes used by filesystems which use buffer_heads when
  2331. * a single buffer is being dirtied: we want to set the folio dirty in
  2332. * that case, but not all the buffers. This is a "bottom-up" dirtying,
  2333. * whereas block_dirty_folio() is a "top-down" dirtying.
  2334. *
  2335. * The caller must ensure this doesn't race with truncation. Most will
  2336. * simply hold the folio lock, but e.g. zap_pte_range() calls with the
  2337. * folio mapped and the pte lock held, which also locks out truncation.
  2338. */
  2339. bool filemap_dirty_folio(struct address_space *mapping, struct folio *folio)
  2340. {
  2341. folio_memcg_lock(folio);
  2342. if (folio_test_set_dirty(folio)) {
  2343. folio_memcg_unlock(folio);
  2344. return false;
  2345. }
  2346. __folio_mark_dirty(folio, mapping, !folio_test_private(folio));
  2347. folio_memcg_unlock(folio);
  2348. if (mapping->host) {
  2349. /* !PageAnon && !swapper_space */
  2350. __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
  2351. }
  2352. return true;
  2353. }
  2354. EXPORT_SYMBOL(filemap_dirty_folio);
  2355. /**
  2356. * folio_account_redirty - Manually account for redirtying a page.
  2357. * @folio: The folio which is being redirtied.
  2358. *
  2359. * Most filesystems should call folio_redirty_for_writepage() instead
  2360. * of this fuction. If your filesystem is doing writeback outside the
  2361. * context of a writeback_control(), it can call this when redirtying
  2362. * a folio, to de-account the dirty counters (NR_DIRTIED, WB_DIRTIED,
  2363. * tsk->nr_dirtied), so that they match the written counters (NR_WRITTEN,
  2364. * WB_WRITTEN) in long term. The mismatches will lead to systematic errors
  2365. * in balanced_dirty_ratelimit and the dirty pages position control.
  2366. */
  2367. void folio_account_redirty(struct folio *folio)
  2368. {
  2369. struct address_space *mapping = folio->mapping;
  2370. if (mapping && mapping_can_writeback(mapping)) {
  2371. struct inode *inode = mapping->host;
  2372. struct bdi_writeback *wb;
  2373. struct wb_lock_cookie cookie = {};
  2374. long nr = folio_nr_pages(folio);
  2375. wb = unlocked_inode_to_wb_begin(inode, &cookie);
  2376. current->nr_dirtied -= nr;
  2377. node_stat_mod_folio(folio, NR_DIRTIED, -nr);
  2378. wb_stat_mod(wb, WB_DIRTIED, -nr);
  2379. unlocked_inode_to_wb_end(inode, &cookie);
  2380. }
  2381. }
  2382. EXPORT_SYMBOL(folio_account_redirty);
  2383. /**
  2384. * folio_redirty_for_writepage - Decline to write a dirty folio.
  2385. * @wbc: The writeback control.
  2386. * @folio: The folio.
  2387. *
  2388. * When a writepage implementation decides that it doesn't want to write
  2389. * @folio for some reason, it should call this function, unlock @folio and
  2390. * return 0.
  2391. *
  2392. * Return: True if we redirtied the folio. False if someone else dirtied
  2393. * it first.
  2394. */
  2395. bool folio_redirty_for_writepage(struct writeback_control *wbc,
  2396. struct folio *folio)
  2397. {
  2398. bool ret;
  2399. long nr = folio_nr_pages(folio);
  2400. wbc->pages_skipped += nr;
  2401. ret = filemap_dirty_folio(folio->mapping, folio);
  2402. folio_account_redirty(folio);
  2403. return ret;
  2404. }
  2405. EXPORT_SYMBOL(folio_redirty_for_writepage);
  2406. /**
  2407. * folio_mark_dirty - Mark a folio as being modified.
  2408. * @folio: The folio.
  2409. *
  2410. * The folio may not be truncated while this function is running.
  2411. * Holding the folio lock is sufficient to prevent truncation, but some
  2412. * callers cannot acquire a sleeping lock. These callers instead hold
  2413. * the page table lock for a page table which contains at least one page
  2414. * in this folio. Truncation will block on the page table lock as it
  2415. * unmaps pages before removing the folio from its mapping.
  2416. *
  2417. * Return: True if the folio was newly dirtied, false if it was already dirty.
  2418. */
  2419. bool folio_mark_dirty(struct folio *folio)
  2420. {
  2421. struct address_space *mapping = folio_mapping(folio);
  2422. if (likely(mapping)) {
  2423. /*
  2424. * readahead/lru_deactivate_page could remain
  2425. * PG_readahead/PG_reclaim due to race with folio_end_writeback
  2426. * About readahead, if the folio is written, the flags would be
  2427. * reset. So no problem.
  2428. * About lru_deactivate_page, if the folio is redirtied,
  2429. * the flag will be reset. So no problem. but if the
  2430. * folio is used by readahead it will confuse readahead
  2431. * and make it restart the size rampup process. But it's
  2432. * a trivial problem.
  2433. */
  2434. if (folio_test_reclaim(folio))
  2435. folio_clear_reclaim(folio);
  2436. return mapping->a_ops->dirty_folio(mapping, folio);
  2437. }
  2438. return noop_dirty_folio(mapping, folio);
  2439. }
  2440. EXPORT_SYMBOL(folio_mark_dirty);
  2441. /*
  2442. * set_page_dirty() is racy if the caller has no reference against
  2443. * page->mapping->host, and if the page is unlocked. This is because another
  2444. * CPU could truncate the page off the mapping and then free the mapping.
  2445. *
  2446. * Usually, the page _is_ locked, or the caller is a user-space process which
  2447. * holds a reference on the inode by having an open file.
  2448. *
  2449. * In other cases, the page should be locked before running set_page_dirty().
  2450. */
  2451. int set_page_dirty_lock(struct page *page)
  2452. {
  2453. int ret;
  2454. lock_page(page);
  2455. ret = set_page_dirty(page);
  2456. unlock_page(page);
  2457. return ret;
  2458. }
  2459. EXPORT_SYMBOL(set_page_dirty_lock);
  2460. /*
  2461. * This cancels just the dirty bit on the kernel page itself, it does NOT
  2462. * actually remove dirty bits on any mmap's that may be around. It also
  2463. * leaves the page tagged dirty, so any sync activity will still find it on
  2464. * the dirty lists, and in particular, clear_page_dirty_for_io() will still
  2465. * look at the dirty bits in the VM.
  2466. *
  2467. * Doing this should *normally* only ever be done when a page is truncated,
  2468. * and is not actually mapped anywhere at all. However, fs/buffer.c does
  2469. * this when it notices that somebody has cleaned out all the buffers on a
  2470. * page without actually doing it through the VM. Can you say "ext3 is
  2471. * horribly ugly"? Thought you could.
  2472. */
  2473. void __folio_cancel_dirty(struct folio *folio)
  2474. {
  2475. struct address_space *mapping = folio_mapping(folio);
  2476. if (mapping_can_writeback(mapping)) {
  2477. struct inode *inode = mapping->host;
  2478. struct bdi_writeback *wb;
  2479. struct wb_lock_cookie cookie = {};
  2480. folio_memcg_lock(folio);
  2481. wb = unlocked_inode_to_wb_begin(inode, &cookie);
  2482. if (folio_test_clear_dirty(folio))
  2483. folio_account_cleaned(folio, wb);
  2484. unlocked_inode_to_wb_end(inode, &cookie);
  2485. folio_memcg_unlock(folio);
  2486. } else {
  2487. folio_clear_dirty(folio);
  2488. }
  2489. }
  2490. EXPORT_SYMBOL(__folio_cancel_dirty);
  2491. /*
  2492. * Clear a folio's dirty flag, while caring for dirty memory accounting.
  2493. * Returns true if the folio was previously dirty.
  2494. *
  2495. * This is for preparing to put the folio under writeout. We leave
  2496. * the folio tagged as dirty in the xarray so that a concurrent
  2497. * write-for-sync can discover it via a PAGECACHE_TAG_DIRTY walk.
  2498. * The ->writepage implementation will run either folio_start_writeback()
  2499. * or folio_mark_dirty(), at which stage we bring the folio's dirty flag
  2500. * and xarray dirty tag back into sync.
  2501. *
  2502. * This incoherency between the folio's dirty flag and xarray tag is
  2503. * unfortunate, but it only exists while the folio is locked.
  2504. */
  2505. bool folio_clear_dirty_for_io(struct folio *folio)
  2506. {
  2507. struct address_space *mapping = folio_mapping(folio);
  2508. bool ret = false;
  2509. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  2510. if (mapping && mapping_can_writeback(mapping)) {
  2511. struct inode *inode = mapping->host;
  2512. struct bdi_writeback *wb;
  2513. struct wb_lock_cookie cookie = {};
  2514. /*
  2515. * Yes, Virginia, this is indeed insane.
  2516. *
  2517. * We use this sequence to make sure that
  2518. * (a) we account for dirty stats properly
  2519. * (b) we tell the low-level filesystem to
  2520. * mark the whole folio dirty if it was
  2521. * dirty in a pagetable. Only to then
  2522. * (c) clean the folio again and return 1 to
  2523. * cause the writeback.
  2524. *
  2525. * This way we avoid all nasty races with the
  2526. * dirty bit in multiple places and clearing
  2527. * them concurrently from different threads.
  2528. *
  2529. * Note! Normally the "folio_mark_dirty(folio)"
  2530. * has no effect on the actual dirty bit - since
  2531. * that will already usually be set. But we
  2532. * need the side effects, and it can help us
  2533. * avoid races.
  2534. *
  2535. * We basically use the folio "master dirty bit"
  2536. * as a serialization point for all the different
  2537. * threads doing their things.
  2538. */
  2539. if (folio_mkclean(folio))
  2540. folio_mark_dirty(folio);
  2541. /*
  2542. * We carefully synchronise fault handlers against
  2543. * installing a dirty pte and marking the folio dirty
  2544. * at this point. We do this by having them hold the
  2545. * page lock while dirtying the folio, and folios are
  2546. * always locked coming in here, so we get the desired
  2547. * exclusion.
  2548. */
  2549. wb = unlocked_inode_to_wb_begin(inode, &cookie);
  2550. if (folio_test_clear_dirty(folio)) {
  2551. long nr = folio_nr_pages(folio);
  2552. lruvec_stat_mod_folio(folio, NR_FILE_DIRTY, -nr);
  2553. zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, -nr);
  2554. wb_stat_mod(wb, WB_RECLAIMABLE, -nr);
  2555. ret = true;
  2556. }
  2557. unlocked_inode_to_wb_end(inode, &cookie);
  2558. return ret;
  2559. }
  2560. return folio_test_clear_dirty(folio);
  2561. }
  2562. EXPORT_SYMBOL(folio_clear_dirty_for_io);
  2563. static void wb_inode_writeback_start(struct bdi_writeback *wb)
  2564. {
  2565. atomic_inc(&wb->writeback_inodes);
  2566. }
  2567. static void wb_inode_writeback_end(struct bdi_writeback *wb)
  2568. {
  2569. unsigned long flags;
  2570. atomic_dec(&wb->writeback_inodes);
  2571. /*
  2572. * Make sure estimate of writeback throughput gets updated after
  2573. * writeback completed. We delay the update by BANDWIDTH_INTERVAL
  2574. * (which is the interval other bandwidth updates use for batching) so
  2575. * that if multiple inodes end writeback at a similar time, they get
  2576. * batched into one bandwidth update.
  2577. */
  2578. spin_lock_irqsave(&wb->work_lock, flags);
  2579. if (test_bit(WB_registered, &wb->state))
  2580. queue_delayed_work(bdi_wq, &wb->bw_dwork, BANDWIDTH_INTERVAL);
  2581. spin_unlock_irqrestore(&wb->work_lock, flags);
  2582. }
  2583. bool __folio_end_writeback(struct folio *folio)
  2584. {
  2585. long nr = folio_nr_pages(folio);
  2586. struct address_space *mapping = folio_mapping(folio);
  2587. bool ret;
  2588. folio_memcg_lock(folio);
  2589. if (mapping && mapping_use_writeback_tags(mapping)) {
  2590. struct inode *inode = mapping->host;
  2591. struct backing_dev_info *bdi = inode_to_bdi(inode);
  2592. unsigned long flags;
  2593. xa_lock_irqsave(&mapping->i_pages, flags);
  2594. ret = folio_test_clear_writeback(folio);
  2595. if (ret) {
  2596. __xa_clear_mark(&mapping->i_pages, folio_index(folio),
  2597. PAGECACHE_TAG_WRITEBACK);
  2598. if (bdi->capabilities & BDI_CAP_WRITEBACK_ACCT) {
  2599. struct bdi_writeback *wb = inode_to_wb(inode);
  2600. wb_stat_mod(wb, WB_WRITEBACK, -nr);
  2601. __wb_writeout_add(wb, nr);
  2602. if (!mapping_tagged(mapping,
  2603. PAGECACHE_TAG_WRITEBACK))
  2604. wb_inode_writeback_end(wb);
  2605. }
  2606. }
  2607. if (mapping->host && !mapping_tagged(mapping,
  2608. PAGECACHE_TAG_WRITEBACK))
  2609. sb_clear_inode_writeback(mapping->host);
  2610. xa_unlock_irqrestore(&mapping->i_pages, flags);
  2611. } else {
  2612. ret = folio_test_clear_writeback(folio);
  2613. }
  2614. if (ret) {
  2615. lruvec_stat_mod_folio(folio, NR_WRITEBACK, -nr);
  2616. zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, -nr);
  2617. node_stat_mod_folio(folio, NR_WRITTEN, nr);
  2618. }
  2619. folio_memcg_unlock(folio);
  2620. return ret;
  2621. }
  2622. bool __folio_start_writeback(struct folio *folio, bool keep_write)
  2623. {
  2624. long nr = folio_nr_pages(folio);
  2625. struct address_space *mapping = folio_mapping(folio);
  2626. bool ret;
  2627. int access_ret;
  2628. folio_memcg_lock(folio);
  2629. if (mapping && mapping_use_writeback_tags(mapping)) {
  2630. XA_STATE(xas, &mapping->i_pages, folio_index(folio));
  2631. struct inode *inode = mapping->host;
  2632. struct backing_dev_info *bdi = inode_to_bdi(inode);
  2633. unsigned long flags;
  2634. xas_lock_irqsave(&xas, flags);
  2635. xas_load(&xas);
  2636. ret = folio_test_set_writeback(folio);
  2637. if (!ret) {
  2638. bool on_wblist;
  2639. on_wblist = mapping_tagged(mapping,
  2640. PAGECACHE_TAG_WRITEBACK);
  2641. xas_set_mark(&xas, PAGECACHE_TAG_WRITEBACK);
  2642. if (bdi->capabilities & BDI_CAP_WRITEBACK_ACCT) {
  2643. struct bdi_writeback *wb = inode_to_wb(inode);
  2644. wb_stat_mod(wb, WB_WRITEBACK, nr);
  2645. if (!on_wblist)
  2646. wb_inode_writeback_start(wb);
  2647. }
  2648. /*
  2649. * We can come through here when swapping
  2650. * anonymous folios, so we don't necessarily
  2651. * have an inode to track for sync.
  2652. */
  2653. if (mapping->host && !on_wblist)
  2654. sb_mark_inode_writeback(mapping->host);
  2655. }
  2656. if (!folio_test_dirty(folio))
  2657. xas_clear_mark(&xas, PAGECACHE_TAG_DIRTY);
  2658. if (!keep_write)
  2659. xas_clear_mark(&xas, PAGECACHE_TAG_TOWRITE);
  2660. xas_unlock_irqrestore(&xas, flags);
  2661. } else {
  2662. ret = folio_test_set_writeback(folio);
  2663. }
  2664. if (!ret) {
  2665. lruvec_stat_mod_folio(folio, NR_WRITEBACK, nr);
  2666. zone_stat_mod_folio(folio, NR_ZONE_WRITE_PENDING, nr);
  2667. }
  2668. folio_memcg_unlock(folio);
  2669. access_ret = arch_make_folio_accessible(folio);
  2670. /*
  2671. * If writeback has been triggered on a page that cannot be made
  2672. * accessible, it is too late to recover here.
  2673. */
  2674. VM_BUG_ON_FOLIO(access_ret != 0, folio);
  2675. return ret;
  2676. }
  2677. EXPORT_SYMBOL(__folio_start_writeback);
  2678. /**
  2679. * folio_wait_writeback - Wait for a folio to finish writeback.
  2680. * @folio: The folio to wait for.
  2681. *
  2682. * If the folio is currently being written back to storage, wait for the
  2683. * I/O to complete.
  2684. *
  2685. * Context: Sleeps. Must be called in process context and with
  2686. * no spinlocks held. Caller should hold a reference on the folio.
  2687. * If the folio is not locked, writeback may start again after writeback
  2688. * has finished.
  2689. */
  2690. void folio_wait_writeback(struct folio *folio)
  2691. {
  2692. while (folio_test_writeback(folio)) {
  2693. trace_folio_wait_writeback(folio, folio_mapping(folio));
  2694. folio_wait_bit(folio, PG_writeback);
  2695. }
  2696. }
  2697. EXPORT_SYMBOL_GPL(folio_wait_writeback);
  2698. /**
  2699. * folio_wait_writeback_killable - Wait for a folio to finish writeback.
  2700. * @folio: The folio to wait for.
  2701. *
  2702. * If the folio is currently being written back to storage, wait for the
  2703. * I/O to complete or a fatal signal to arrive.
  2704. *
  2705. * Context: Sleeps. Must be called in process context and with
  2706. * no spinlocks held. Caller should hold a reference on the folio.
  2707. * If the folio is not locked, writeback may start again after writeback
  2708. * has finished.
  2709. * Return: 0 on success, -EINTR if we get a fatal signal while waiting.
  2710. */
  2711. int folio_wait_writeback_killable(struct folio *folio)
  2712. {
  2713. while (folio_test_writeback(folio)) {
  2714. trace_folio_wait_writeback(folio, folio_mapping(folio));
  2715. if (folio_wait_bit_killable(folio, PG_writeback))
  2716. return -EINTR;
  2717. }
  2718. return 0;
  2719. }
  2720. EXPORT_SYMBOL_GPL(folio_wait_writeback_killable);
  2721. /**
  2722. * folio_wait_stable() - wait for writeback to finish, if necessary.
  2723. * @folio: The folio to wait on.
  2724. *
  2725. * This function determines if the given folio is related to a backing
  2726. * device that requires folio contents to be held stable during writeback.
  2727. * If so, then it will wait for any pending writeback to complete.
  2728. *
  2729. * Context: Sleeps. Must be called in process context and with
  2730. * no spinlocks held. Caller should hold a reference on the folio.
  2731. * If the folio is not locked, writeback may start again after writeback
  2732. * has finished.
  2733. */
  2734. void folio_wait_stable(struct folio *folio)
  2735. {
  2736. if (folio_inode(folio)->i_sb->s_iflags & SB_I_STABLE_WRITES)
  2737. folio_wait_writeback(folio);
  2738. }
  2739. EXPORT_SYMBOL_GPL(folio_wait_stable);