page-writeback.c 84 KB

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