page-writeback.c 85 KB

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