page-writeback.c 84 KB

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