page-writeback.c 84 KB

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