page-writeback.c 93 KB

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