page-writeback.c 83 KB

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