page-writeback.c 75 KB

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