page-writeback.c 96 KB

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