page-writeback.c 84 KB

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