page-writeback.c 85 KB

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