page-writeback.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  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/module.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>
  35. #include <linux/pagevec.h>
  36. #include <trace/events/writeback.h>
  37. /*
  38. * Sleep at most 200ms at a time in balance_dirty_pages().
  39. */
  40. #define MAX_PAUSE max(HZ/5, 1)
  41. /*
  42. * Estimate write bandwidth at 200ms intervals.
  43. */
  44. #define BANDWIDTH_INTERVAL max(HZ/5, 1)
  45. /*
  46. * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
  47. * will look to see if it needs to force writeback or throttling.
  48. */
  49. static long ratelimit_pages = 32;
  50. /*
  51. * When balance_dirty_pages decides that the caller needs to perform some
  52. * non-background writeback, this is how many pages it will attempt to write.
  53. * It should be somewhat larger than dirtied pages to ensure that reasonably
  54. * large amounts of I/O are submitted.
  55. */
  56. static inline long sync_writeback_pages(unsigned long dirtied)
  57. {
  58. if (dirtied < ratelimit_pages)
  59. dirtied = ratelimit_pages;
  60. return dirtied + dirtied / 2;
  61. }
  62. /* The following parameters are exported via /proc/sys/vm */
  63. /*
  64. * Start background writeback (via writeback threads) at this percentage
  65. */
  66. int dirty_background_ratio = 10;
  67. /*
  68. * dirty_background_bytes starts at 0 (disabled) so that it is a function of
  69. * dirty_background_ratio * the amount of dirtyable memory
  70. */
  71. unsigned long dirty_background_bytes;
  72. /*
  73. * free highmem will not be subtracted from the total free memory
  74. * for calculating free ratios if vm_highmem_is_dirtyable is true
  75. */
  76. int vm_highmem_is_dirtyable;
  77. /*
  78. * The generator of dirty data starts writeback at this percentage
  79. */
  80. int vm_dirty_ratio = 20;
  81. /*
  82. * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
  83. * vm_dirty_ratio * the amount of dirtyable memory
  84. */
  85. unsigned long vm_dirty_bytes;
  86. /*
  87. * The interval between `kupdate'-style writebacks
  88. */
  89. unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
  90. /*
  91. * The longest time for which data is allowed to remain dirty
  92. */
  93. unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
  94. /*
  95. * Flag that makes the machine dump writes/reads and block dirtyings.
  96. */
  97. int block_dump;
  98. /*
  99. * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
  100. * a full sync is triggered after this time elapses without any disk activity.
  101. */
  102. int laptop_mode;
  103. EXPORT_SYMBOL(laptop_mode);
  104. /* End of sysctl-exported parameters */
  105. unsigned long global_dirty_limit;
  106. /*
  107. * Scale the writeback cache size proportional to the relative writeout speeds.
  108. *
  109. * We do this by keeping a floating proportion between BDIs, based on page
  110. * writeback completions [end_page_writeback()]. Those devices that write out
  111. * pages fastest will get the larger share, while the slower will get a smaller
  112. * share.
  113. *
  114. * We use page writeout completions because we are interested in getting rid of
  115. * dirty pages. Having them written out is the primary goal.
  116. *
  117. * We introduce a concept of time, a period over which we measure these events,
  118. * because demand can/will vary over time. The length of this period itself is
  119. * measured in page writeback completions.
  120. *
  121. */
  122. static struct prop_descriptor vm_completions;
  123. static struct prop_descriptor vm_dirties;
  124. /*
  125. * couple the period to the dirty_ratio:
  126. *
  127. * period/2 ~ roundup_pow_of_two(dirty limit)
  128. */
  129. static int calc_period_shift(void)
  130. {
  131. unsigned long dirty_total;
  132. if (vm_dirty_bytes)
  133. dirty_total = vm_dirty_bytes / PAGE_SIZE;
  134. else
  135. dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) /
  136. 100;
  137. return 2 + ilog2(dirty_total - 1);
  138. }
  139. /*
  140. * update the period when the dirty threshold changes.
  141. */
  142. static void update_completion_period(void)
  143. {
  144. int shift = calc_period_shift();
  145. prop_change_shift(&vm_completions, shift);
  146. prop_change_shift(&vm_dirties, shift);
  147. }
  148. int dirty_background_ratio_handler(struct ctl_table *table, int write,
  149. void __user *buffer, size_t *lenp,
  150. loff_t *ppos)
  151. {
  152. int ret;
  153. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  154. if (ret == 0 && write)
  155. dirty_background_bytes = 0;
  156. return ret;
  157. }
  158. int dirty_background_bytes_handler(struct ctl_table *table, int write,
  159. void __user *buffer, size_t *lenp,
  160. loff_t *ppos)
  161. {
  162. int ret;
  163. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  164. if (ret == 0 && write)
  165. dirty_background_ratio = 0;
  166. return ret;
  167. }
  168. int dirty_ratio_handler(struct ctl_table *table, int write,
  169. void __user *buffer, size_t *lenp,
  170. loff_t *ppos)
  171. {
  172. int old_ratio = vm_dirty_ratio;
  173. int ret;
  174. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  175. if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
  176. update_completion_period();
  177. vm_dirty_bytes = 0;
  178. }
  179. return ret;
  180. }
  181. int dirty_bytes_handler(struct ctl_table *table, int write,
  182. void __user *buffer, size_t *lenp,
  183. loff_t *ppos)
  184. {
  185. unsigned long old_bytes = vm_dirty_bytes;
  186. int ret;
  187. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  188. if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
  189. update_completion_period();
  190. vm_dirty_ratio = 0;
  191. }
  192. return ret;
  193. }
  194. /*
  195. * Increment the BDI's writeout completion count and the global writeout
  196. * completion count. Called from test_clear_page_writeback().
  197. */
  198. static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
  199. {
  200. __inc_bdi_stat(bdi, BDI_WRITTEN);
  201. __prop_inc_percpu_max(&vm_completions, &bdi->completions,
  202. bdi->max_prop_frac);
  203. }
  204. void bdi_writeout_inc(struct backing_dev_info *bdi)
  205. {
  206. unsigned long flags;
  207. local_irq_save(flags);
  208. __bdi_writeout_inc(bdi);
  209. local_irq_restore(flags);
  210. }
  211. EXPORT_SYMBOL_GPL(bdi_writeout_inc);
  212. void task_dirty_inc(struct task_struct *tsk)
  213. {
  214. prop_inc_single(&vm_dirties, &tsk->dirties);
  215. }
  216. /*
  217. * Obtain an accurate fraction of the BDI's portion.
  218. */
  219. static void bdi_writeout_fraction(struct backing_dev_info *bdi,
  220. long *numerator, long *denominator)
  221. {
  222. prop_fraction_percpu(&vm_completions, &bdi->completions,
  223. numerator, denominator);
  224. }
  225. static inline void task_dirties_fraction(struct task_struct *tsk,
  226. long *numerator, long *denominator)
  227. {
  228. prop_fraction_single(&vm_dirties, &tsk->dirties,
  229. numerator, denominator);
  230. }
  231. /*
  232. * task_dirty_limit - scale down dirty throttling threshold for one task
  233. *
  234. * task specific dirty limit:
  235. *
  236. * dirty -= (dirty/8) * p_{t}
  237. *
  238. * To protect light/slow dirtying tasks from heavier/fast ones, we start
  239. * throttling individual tasks before reaching the bdi dirty limit.
  240. * Relatively low thresholds will be allocated to heavy dirtiers. So when
  241. * dirty pages grow large, heavy dirtiers will be throttled first, which will
  242. * effectively curb the growth of dirty pages. Light dirtiers with high enough
  243. * dirty threshold may never get throttled.
  244. */
  245. #define TASK_LIMIT_FRACTION 8
  246. static unsigned long task_dirty_limit(struct task_struct *tsk,
  247. unsigned long bdi_dirty)
  248. {
  249. long numerator, denominator;
  250. unsigned long dirty = bdi_dirty;
  251. u64 inv = dirty / TASK_LIMIT_FRACTION;
  252. task_dirties_fraction(tsk, &numerator, &denominator);
  253. inv *= numerator;
  254. do_div(inv, denominator);
  255. dirty -= inv;
  256. return max(dirty, bdi_dirty/2);
  257. }
  258. /* Minimum limit for any task */
  259. static unsigned long task_min_dirty_limit(unsigned long bdi_dirty)
  260. {
  261. return bdi_dirty - bdi_dirty / TASK_LIMIT_FRACTION;
  262. }
  263. /*
  264. *
  265. */
  266. static unsigned int bdi_min_ratio;
  267. int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
  268. {
  269. int ret = 0;
  270. spin_lock_bh(&bdi_lock);
  271. if (min_ratio > bdi->max_ratio) {
  272. ret = -EINVAL;
  273. } else {
  274. min_ratio -= bdi->min_ratio;
  275. if (bdi_min_ratio + min_ratio < 100) {
  276. bdi_min_ratio += min_ratio;
  277. bdi->min_ratio += min_ratio;
  278. } else {
  279. ret = -EINVAL;
  280. }
  281. }
  282. spin_unlock_bh(&bdi_lock);
  283. return ret;
  284. }
  285. int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
  286. {
  287. int ret = 0;
  288. if (max_ratio > 100)
  289. return -EINVAL;
  290. spin_lock_bh(&bdi_lock);
  291. if (bdi->min_ratio > max_ratio) {
  292. ret = -EINVAL;
  293. } else {
  294. bdi->max_ratio = max_ratio;
  295. bdi->max_prop_frac = (PROP_FRAC_BASE * max_ratio) / 100;
  296. }
  297. spin_unlock_bh(&bdi_lock);
  298. return ret;
  299. }
  300. EXPORT_SYMBOL(bdi_set_max_ratio);
  301. /*
  302. * Work out the current dirty-memory clamping and background writeout
  303. * thresholds.
  304. *
  305. * The main aim here is to lower them aggressively if there is a lot of mapped
  306. * memory around. To avoid stressing page reclaim with lots of unreclaimable
  307. * pages. It is better to clamp down on writers than to start swapping, and
  308. * performing lots of scanning.
  309. *
  310. * We only allow 1/2 of the currently-unmapped memory to be dirtied.
  311. *
  312. * We don't permit the clamping level to fall below 5% - that is getting rather
  313. * excessive.
  314. *
  315. * We make sure that the background writeout level is below the adjusted
  316. * clamping level.
  317. */
  318. static unsigned long highmem_dirtyable_memory(unsigned long total)
  319. {
  320. #ifdef CONFIG_HIGHMEM
  321. int node;
  322. unsigned long x = 0;
  323. for_each_node_state(node, N_HIGH_MEMORY) {
  324. struct zone *z =
  325. &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
  326. x += zone_page_state(z, NR_FREE_PAGES) +
  327. zone_reclaimable_pages(z);
  328. }
  329. /*
  330. * Make sure that the number of highmem pages is never larger
  331. * than the number of the total dirtyable memory. This can only
  332. * occur in very strange VM situations but we want to make sure
  333. * that this does not occur.
  334. */
  335. return min(x, total);
  336. #else
  337. return 0;
  338. #endif
  339. }
  340. /**
  341. * determine_dirtyable_memory - amount of memory that may be used
  342. *
  343. * Returns the numebr of pages that can currently be freed and used
  344. * by the kernel for direct mappings.
  345. */
  346. unsigned long determine_dirtyable_memory(void)
  347. {
  348. unsigned long x;
  349. x = global_page_state(NR_FREE_PAGES) + global_reclaimable_pages();
  350. if (!vm_highmem_is_dirtyable)
  351. x -= highmem_dirtyable_memory(x);
  352. return x + 1; /* Ensure that we never return 0 */
  353. }
  354. static unsigned long hard_dirty_limit(unsigned long thresh)
  355. {
  356. return max(thresh, global_dirty_limit);
  357. }
  358. /*
  359. * global_dirty_limits - background-writeback and dirty-throttling thresholds
  360. *
  361. * Calculate the dirty thresholds based on sysctl parameters
  362. * - vm.dirty_background_ratio or vm.dirty_background_bytes
  363. * - vm.dirty_ratio or vm.dirty_bytes
  364. * The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
  365. * real-time tasks.
  366. */
  367. void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
  368. {
  369. unsigned long background;
  370. unsigned long dirty;
  371. unsigned long uninitialized_var(available_memory);
  372. struct task_struct *tsk;
  373. if (!vm_dirty_bytes || !dirty_background_bytes)
  374. available_memory = determine_dirtyable_memory();
  375. if (vm_dirty_bytes)
  376. dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
  377. else
  378. dirty = (vm_dirty_ratio * available_memory) / 100;
  379. if (dirty_background_bytes)
  380. background = DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE);
  381. else
  382. background = (dirty_background_ratio * available_memory) / 100;
  383. if (background >= dirty)
  384. background = dirty / 2;
  385. tsk = current;
  386. if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
  387. background += background / 4;
  388. dirty += dirty / 4;
  389. }
  390. *pbackground = background;
  391. *pdirty = dirty;
  392. trace_global_dirty_state(background, dirty);
  393. }
  394. /**
  395. * bdi_dirty_limit - @bdi's share of dirty throttling threshold
  396. * @bdi: the backing_dev_info to query
  397. * @dirty: global dirty limit in pages
  398. *
  399. * Returns @bdi's dirty limit in pages. The term "dirty" in the context of
  400. * dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
  401. * And the "limit" in the name is not seriously taken as hard limit in
  402. * balance_dirty_pages().
  403. *
  404. * It allocates high/low dirty limits to fast/slow devices, in order to prevent
  405. * - starving fast devices
  406. * - piling up dirty pages (that will take long time to sync) on slow devices
  407. *
  408. * The bdi's share of dirty limit will be adapting to its throughput and
  409. * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
  410. */
  411. unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty)
  412. {
  413. u64 bdi_dirty;
  414. long numerator, denominator;
  415. /*
  416. * Calculate this BDI's share of the dirty ratio.
  417. */
  418. bdi_writeout_fraction(bdi, &numerator, &denominator);
  419. bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
  420. bdi_dirty *= numerator;
  421. do_div(bdi_dirty, denominator);
  422. bdi_dirty += (dirty * bdi->min_ratio) / 100;
  423. if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
  424. bdi_dirty = dirty * bdi->max_ratio / 100;
  425. return bdi_dirty;
  426. }
  427. static void bdi_update_write_bandwidth(struct backing_dev_info *bdi,
  428. unsigned long elapsed,
  429. unsigned long written)
  430. {
  431. const unsigned long period = roundup_pow_of_two(3 * HZ);
  432. unsigned long avg = bdi->avg_write_bandwidth;
  433. unsigned long old = bdi->write_bandwidth;
  434. u64 bw;
  435. /*
  436. * bw = written * HZ / elapsed
  437. *
  438. * bw * elapsed + write_bandwidth * (period - elapsed)
  439. * write_bandwidth = ---------------------------------------------------
  440. * period
  441. */
  442. bw = written - bdi->written_stamp;
  443. bw *= HZ;
  444. if (unlikely(elapsed > period)) {
  445. do_div(bw, elapsed);
  446. avg = bw;
  447. goto out;
  448. }
  449. bw += (u64)bdi->write_bandwidth * (period - elapsed);
  450. bw >>= ilog2(period);
  451. /*
  452. * one more level of smoothing, for filtering out sudden spikes
  453. */
  454. if (avg > old && old >= (unsigned long)bw)
  455. avg -= (avg - old) >> 3;
  456. if (avg < old && old <= (unsigned long)bw)
  457. avg += (old - avg) >> 3;
  458. out:
  459. bdi->write_bandwidth = bw;
  460. bdi->avg_write_bandwidth = avg;
  461. }
  462. /*
  463. * The global dirtyable memory and dirty threshold could be suddenly knocked
  464. * down by a large amount (eg. on the startup of KVM in a swapless system).
  465. * This may throw the system into deep dirty exceeded state and throttle
  466. * heavy/light dirtiers alike. To retain good responsiveness, maintain
  467. * global_dirty_limit for tracking slowly down to the knocked down dirty
  468. * threshold.
  469. */
  470. static void update_dirty_limit(unsigned long thresh, unsigned long dirty)
  471. {
  472. unsigned long limit = global_dirty_limit;
  473. /*
  474. * Follow up in one step.
  475. */
  476. if (limit < thresh) {
  477. limit = thresh;
  478. goto update;
  479. }
  480. /*
  481. * Follow down slowly. Use the higher one as the target, because thresh
  482. * may drop below dirty. This is exactly the reason to introduce
  483. * global_dirty_limit which is guaranteed to lie above the dirty pages.
  484. */
  485. thresh = max(thresh, dirty);
  486. if (limit > thresh) {
  487. limit -= (limit - thresh) >> 5;
  488. goto update;
  489. }
  490. return;
  491. update:
  492. global_dirty_limit = limit;
  493. }
  494. static void global_update_bandwidth(unsigned long thresh,
  495. unsigned long dirty,
  496. unsigned long now)
  497. {
  498. static DEFINE_SPINLOCK(dirty_lock);
  499. static unsigned long update_time;
  500. /*
  501. * check locklessly first to optimize away locking for the most time
  502. */
  503. if (time_before(now, update_time + BANDWIDTH_INTERVAL))
  504. return;
  505. spin_lock(&dirty_lock);
  506. if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) {
  507. update_dirty_limit(thresh, dirty);
  508. update_time = now;
  509. }
  510. spin_unlock(&dirty_lock);
  511. }
  512. void __bdi_update_bandwidth(struct backing_dev_info *bdi,
  513. unsigned long thresh,
  514. unsigned long dirty,
  515. unsigned long bdi_thresh,
  516. unsigned long bdi_dirty,
  517. unsigned long start_time)
  518. {
  519. unsigned long now = jiffies;
  520. unsigned long elapsed = now - bdi->bw_time_stamp;
  521. unsigned long written;
  522. /*
  523. * rate-limit, only update once every 200ms.
  524. */
  525. if (elapsed < BANDWIDTH_INTERVAL)
  526. return;
  527. written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]);
  528. /*
  529. * Skip quiet periods when disk bandwidth is under-utilized.
  530. * (at least 1s idle time between two flusher runs)
  531. */
  532. if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time))
  533. goto snapshot;
  534. if (thresh)
  535. global_update_bandwidth(thresh, dirty, now);
  536. bdi_update_write_bandwidth(bdi, elapsed, written);
  537. snapshot:
  538. bdi->written_stamp = written;
  539. bdi->bw_time_stamp = now;
  540. }
  541. static void bdi_update_bandwidth(struct backing_dev_info *bdi,
  542. unsigned long thresh,
  543. unsigned long dirty,
  544. unsigned long bdi_thresh,
  545. unsigned long bdi_dirty,
  546. unsigned long start_time)
  547. {
  548. if (time_is_after_eq_jiffies(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
  549. return;
  550. spin_lock(&bdi->wb.list_lock);
  551. __bdi_update_bandwidth(bdi, thresh, dirty, bdi_thresh, bdi_dirty,
  552. start_time);
  553. spin_unlock(&bdi->wb.list_lock);
  554. }
  555. /*
  556. * balance_dirty_pages() must be called by processes which are generating dirty
  557. * data. It looks at the number of dirty pages in the machine and will force
  558. * the caller to perform writeback if the system is over `vm_dirty_ratio'.
  559. * If we're over `background_thresh' then the writeback threads are woken to
  560. * perform some writeout.
  561. */
  562. static void balance_dirty_pages(struct address_space *mapping,
  563. unsigned long write_chunk)
  564. {
  565. unsigned long nr_reclaimable, bdi_nr_reclaimable;
  566. unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */
  567. unsigned long bdi_dirty;
  568. unsigned long background_thresh;
  569. unsigned long dirty_thresh;
  570. unsigned long bdi_thresh;
  571. unsigned long task_bdi_thresh;
  572. unsigned long min_task_bdi_thresh;
  573. unsigned long pages_written = 0;
  574. unsigned long pause = 1;
  575. bool dirty_exceeded = false;
  576. bool clear_dirty_exceeded = true;
  577. struct backing_dev_info *bdi = mapping->backing_dev_info;
  578. unsigned long start_time = jiffies;
  579. for (;;) {
  580. nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
  581. global_page_state(NR_UNSTABLE_NFS);
  582. nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK);
  583. global_dirty_limits(&background_thresh, &dirty_thresh);
  584. /*
  585. * Throttle it only when the background writeback cannot
  586. * catch-up. This avoids (excessively) small writeouts
  587. * when the bdi limits are ramping up.
  588. */
  589. if (nr_dirty <= (background_thresh + dirty_thresh) / 2)
  590. break;
  591. bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh);
  592. min_task_bdi_thresh = task_min_dirty_limit(bdi_thresh);
  593. task_bdi_thresh = task_dirty_limit(current, bdi_thresh);
  594. /*
  595. * In order to avoid the stacked BDI deadlock we need
  596. * to ensure we accurately count the 'dirty' pages when
  597. * the threshold is low.
  598. *
  599. * Otherwise it would be possible to get thresh+n pages
  600. * reported dirty, even though there are thresh-m pages
  601. * actually dirty; with m+n sitting in the percpu
  602. * deltas.
  603. */
  604. if (task_bdi_thresh < 2 * bdi_stat_error(bdi)) {
  605. bdi_nr_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
  606. bdi_dirty = bdi_nr_reclaimable +
  607. bdi_stat_sum(bdi, BDI_WRITEBACK);
  608. } else {
  609. bdi_nr_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
  610. bdi_dirty = bdi_nr_reclaimable +
  611. bdi_stat(bdi, BDI_WRITEBACK);
  612. }
  613. /*
  614. * The bdi thresh is somehow "soft" limit derived from the
  615. * global "hard" limit. The former helps to prevent heavy IO
  616. * bdi or process from holding back light ones; The latter is
  617. * the last resort safeguard.
  618. */
  619. dirty_exceeded = (bdi_dirty > task_bdi_thresh) ||
  620. (nr_dirty > dirty_thresh);
  621. clear_dirty_exceeded = (bdi_dirty <= min_task_bdi_thresh) &&
  622. (nr_dirty <= dirty_thresh);
  623. if (!dirty_exceeded)
  624. break;
  625. if (!bdi->dirty_exceeded)
  626. bdi->dirty_exceeded = 1;
  627. bdi_update_bandwidth(bdi, dirty_thresh, nr_dirty,
  628. bdi_thresh, bdi_dirty, start_time);
  629. /* Note: nr_reclaimable denotes nr_dirty + nr_unstable.
  630. * Unstable writes are a feature of certain networked
  631. * filesystems (i.e. NFS) in which data may have been
  632. * written to the server's write cache, but has not yet
  633. * been flushed to permanent storage.
  634. * Only move pages to writeback if this bdi is over its
  635. * threshold otherwise wait until the disk writes catch
  636. * up.
  637. */
  638. trace_balance_dirty_start(bdi);
  639. if (bdi_nr_reclaimable > task_bdi_thresh) {
  640. pages_written += writeback_inodes_wb(&bdi->wb,
  641. write_chunk);
  642. trace_balance_dirty_written(bdi, pages_written);
  643. if (pages_written >= write_chunk)
  644. break; /* We've done our duty */
  645. }
  646. __set_current_state(TASK_UNINTERRUPTIBLE);
  647. io_schedule_timeout(pause);
  648. trace_balance_dirty_wait(bdi);
  649. dirty_thresh = hard_dirty_limit(dirty_thresh);
  650. /*
  651. * max-pause area. If dirty exceeded but still within this
  652. * area, no need to sleep for more than 200ms: (a) 8 pages per
  653. * 200ms is typically more than enough to curb heavy dirtiers;
  654. * (b) the pause time limit makes the dirtiers more responsive.
  655. */
  656. if (nr_dirty < dirty_thresh &&
  657. bdi_dirty < (task_bdi_thresh + bdi_thresh) / 2 &&
  658. time_after(jiffies, start_time + MAX_PAUSE))
  659. break;
  660. /*
  661. * Increase the delay for each loop, up to our previous
  662. * default of taking a 100ms nap.
  663. */
  664. pause <<= 1;
  665. if (pause > HZ / 10)
  666. pause = HZ / 10;
  667. }
  668. /* Clear dirty_exceeded flag only when no task can exceed the limit */
  669. if (clear_dirty_exceeded && bdi->dirty_exceeded)
  670. bdi->dirty_exceeded = 0;
  671. if (writeback_in_progress(bdi))
  672. return;
  673. /*
  674. * In laptop mode, we wait until hitting the higher threshold before
  675. * starting background writeout, and then write out all the way down
  676. * to the lower threshold. So slow writers cause minimal disk activity.
  677. *
  678. * In normal mode, we start background writeout at the lower
  679. * background_thresh, to keep the amount of dirty memory low.
  680. */
  681. if ((laptop_mode && pages_written) ||
  682. (!laptop_mode && (nr_reclaimable > background_thresh)))
  683. bdi_start_background_writeback(bdi);
  684. }
  685. void set_page_dirty_balance(struct page *page, int page_mkwrite)
  686. {
  687. if (set_page_dirty(page) || page_mkwrite) {
  688. struct address_space *mapping = page_mapping(page);
  689. if (mapping)
  690. balance_dirty_pages_ratelimited(mapping);
  691. }
  692. }
  693. static DEFINE_PER_CPU(unsigned long, bdp_ratelimits) = 0;
  694. /**
  695. * balance_dirty_pages_ratelimited_nr - balance dirty memory state
  696. * @mapping: address_space which was dirtied
  697. * @nr_pages_dirtied: number of pages which the caller has just dirtied
  698. *
  699. * Processes which are dirtying memory should call in here once for each page
  700. * which was newly dirtied. The function will periodically check the system's
  701. * dirty state and will initiate writeback if needed.
  702. *
  703. * On really big machines, get_writeback_state is expensive, so try to avoid
  704. * calling it too often (ratelimiting). But once we're over the dirty memory
  705. * limit we decrease the ratelimiting by a lot, to prevent individual processes
  706. * from overshooting the limit by (ratelimit_pages) each.
  707. */
  708. void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
  709. unsigned long nr_pages_dirtied)
  710. {
  711. struct backing_dev_info *bdi = mapping->backing_dev_info;
  712. unsigned long ratelimit;
  713. unsigned long *p;
  714. if (!bdi_cap_account_dirty(bdi))
  715. return;
  716. ratelimit = ratelimit_pages;
  717. if (mapping->backing_dev_info->dirty_exceeded)
  718. ratelimit = 8;
  719. /*
  720. * Check the rate limiting. Also, we do not want to throttle real-time
  721. * tasks in balance_dirty_pages(). Period.
  722. */
  723. preempt_disable();
  724. p = &__get_cpu_var(bdp_ratelimits);
  725. *p += nr_pages_dirtied;
  726. if (unlikely(*p >= ratelimit)) {
  727. ratelimit = sync_writeback_pages(*p);
  728. *p = 0;
  729. preempt_enable();
  730. balance_dirty_pages(mapping, ratelimit);
  731. return;
  732. }
  733. preempt_enable();
  734. }
  735. EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
  736. void throttle_vm_writeout(gfp_t gfp_mask)
  737. {
  738. unsigned long background_thresh;
  739. unsigned long dirty_thresh;
  740. for ( ; ; ) {
  741. global_dirty_limits(&background_thresh, &dirty_thresh);
  742. /*
  743. * Boost the allowable dirty threshold a bit for page
  744. * allocators so they don't get DoS'ed by heavy writers
  745. */
  746. dirty_thresh += dirty_thresh / 10; /* wheeee... */
  747. if (global_page_state(NR_UNSTABLE_NFS) +
  748. global_page_state(NR_WRITEBACK) <= dirty_thresh)
  749. break;
  750. congestion_wait(BLK_RW_ASYNC, HZ/10);
  751. /*
  752. * The caller might hold locks which can prevent IO completion
  753. * or progress in the filesystem. So we cannot just sit here
  754. * waiting for IO to complete.
  755. */
  756. if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
  757. break;
  758. }
  759. }
  760. /*
  761. * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
  762. */
  763. int dirty_writeback_centisecs_handler(ctl_table *table, int write,
  764. void __user *buffer, size_t *length, loff_t *ppos)
  765. {
  766. proc_dointvec(table, write, buffer, length, ppos);
  767. bdi_arm_supers_timer();
  768. return 0;
  769. }
  770. #ifdef CONFIG_BLOCK
  771. void laptop_mode_timer_fn(unsigned long data)
  772. {
  773. struct request_queue *q = (struct request_queue *)data;
  774. int nr_pages = global_page_state(NR_FILE_DIRTY) +
  775. global_page_state(NR_UNSTABLE_NFS);
  776. /*
  777. * We want to write everything out, not just down to the dirty
  778. * threshold
  779. */
  780. if (bdi_has_dirty_io(&q->backing_dev_info))
  781. bdi_start_writeback(&q->backing_dev_info, nr_pages);
  782. }
  783. /*
  784. * We've spun up the disk and we're in laptop mode: schedule writeback
  785. * of all dirty data a few seconds from now. If the flush is already scheduled
  786. * then push it back - the user is still using the disk.
  787. */
  788. void laptop_io_completion(struct backing_dev_info *info)
  789. {
  790. mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
  791. }
  792. /*
  793. * We're in laptop mode and we've just synced. The sync's writes will have
  794. * caused another writeback to be scheduled by laptop_io_completion.
  795. * Nothing needs to be written back anymore, so we unschedule the writeback.
  796. */
  797. void laptop_sync_completion(void)
  798. {
  799. struct backing_dev_info *bdi;
  800. rcu_read_lock();
  801. list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
  802. del_timer(&bdi->laptop_mode_wb_timer);
  803. rcu_read_unlock();
  804. }
  805. #endif
  806. /*
  807. * If ratelimit_pages is too high then we can get into dirty-data overload
  808. * if a large number of processes all perform writes at the same time.
  809. * If it is too low then SMP machines will call the (expensive)
  810. * get_writeback_state too often.
  811. *
  812. * Here we set ratelimit_pages to a level which ensures that when all CPUs are
  813. * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
  814. * thresholds before writeback cuts in.
  815. *
  816. * But the limit should not be set too high. Because it also controls the
  817. * amount of memory which the balance_dirty_pages() caller has to write back.
  818. * If this is too large then the caller will block on the IO queue all the
  819. * time. So limit it to four megabytes - the balance_dirty_pages() caller
  820. * will write six megabyte chunks, max.
  821. */
  822. void writeback_set_ratelimit(void)
  823. {
  824. ratelimit_pages = vm_total_pages / (num_online_cpus() * 32);
  825. if (ratelimit_pages < 16)
  826. ratelimit_pages = 16;
  827. if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
  828. ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
  829. }
  830. static int __cpuinit
  831. ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
  832. {
  833. writeback_set_ratelimit();
  834. return NOTIFY_DONE;
  835. }
  836. static struct notifier_block __cpuinitdata ratelimit_nb = {
  837. .notifier_call = ratelimit_handler,
  838. .next = NULL,
  839. };
  840. /*
  841. * Called early on to tune the page writeback dirty limits.
  842. *
  843. * We used to scale dirty pages according to how total memory
  844. * related to pages that could be allocated for buffers (by
  845. * comparing nr_free_buffer_pages() to vm_total_pages.
  846. *
  847. * However, that was when we used "dirty_ratio" to scale with
  848. * all memory, and we don't do that any more. "dirty_ratio"
  849. * is now applied to total non-HIGHPAGE memory (by subtracting
  850. * totalhigh_pages from vm_total_pages), and as such we can't
  851. * get into the old insane situation any more where we had
  852. * large amounts of dirty pages compared to a small amount of
  853. * non-HIGHMEM memory.
  854. *
  855. * But we might still want to scale the dirty_ratio by how
  856. * much memory the box has..
  857. */
  858. void __init page_writeback_init(void)
  859. {
  860. int shift;
  861. writeback_set_ratelimit();
  862. register_cpu_notifier(&ratelimit_nb);
  863. shift = calc_period_shift();
  864. prop_descriptor_init(&vm_completions, shift);
  865. prop_descriptor_init(&vm_dirties, shift);
  866. }
  867. /**
  868. * tag_pages_for_writeback - tag pages to be written by write_cache_pages
  869. * @mapping: address space structure to write
  870. * @start: starting page index
  871. * @end: ending page index (inclusive)
  872. *
  873. * This function scans the page range from @start to @end (inclusive) and tags
  874. * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
  875. * that write_cache_pages (or whoever calls this function) will then use
  876. * TOWRITE tag to identify pages eligible for writeback. This mechanism is
  877. * used to avoid livelocking of writeback by a process steadily creating new
  878. * dirty pages in the file (thus it is important for this function to be quick
  879. * so that it can tag pages faster than a dirtying process can create them).
  880. */
  881. /*
  882. * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
  883. */
  884. void tag_pages_for_writeback(struct address_space *mapping,
  885. pgoff_t start, pgoff_t end)
  886. {
  887. #define WRITEBACK_TAG_BATCH 4096
  888. unsigned long tagged;
  889. do {
  890. spin_lock_irq(&mapping->tree_lock);
  891. tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree,
  892. &start, end, WRITEBACK_TAG_BATCH,
  893. PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE);
  894. spin_unlock_irq(&mapping->tree_lock);
  895. WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
  896. cond_resched();
  897. /* We check 'start' to handle wrapping when end == ~0UL */
  898. } while (tagged >= WRITEBACK_TAG_BATCH && start);
  899. }
  900. EXPORT_SYMBOL(tag_pages_for_writeback);
  901. /**
  902. * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
  903. * @mapping: address space structure to write
  904. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  905. * @writepage: function called for each page
  906. * @data: data passed to writepage function
  907. *
  908. * If a page is already under I/O, write_cache_pages() skips it, even
  909. * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
  910. * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
  911. * and msync() need to guarantee that all the data which was dirty at the time
  912. * the call was made get new I/O started against them. If wbc->sync_mode is
  913. * WB_SYNC_ALL then we were called for data integrity and we must wait for
  914. * existing IO to complete.
  915. *
  916. * To avoid livelocks (when other process dirties new pages), we first tag
  917. * pages which should be written back with TOWRITE tag and only then start
  918. * writing them. For data-integrity sync we have to be careful so that we do
  919. * not miss some pages (e.g., because some other process has cleared TOWRITE
  920. * tag we set). The rule we follow is that TOWRITE tag can be cleared only
  921. * by the process clearing the DIRTY tag (and submitting the page for IO).
  922. */
  923. int write_cache_pages(struct address_space *mapping,
  924. struct writeback_control *wbc, writepage_t writepage,
  925. void *data)
  926. {
  927. int ret = 0;
  928. int done = 0;
  929. struct pagevec pvec;
  930. int nr_pages;
  931. pgoff_t uninitialized_var(writeback_index);
  932. pgoff_t index;
  933. pgoff_t end; /* Inclusive */
  934. pgoff_t done_index;
  935. int cycled;
  936. int range_whole = 0;
  937. int tag;
  938. pagevec_init(&pvec, 0);
  939. if (wbc->range_cyclic) {
  940. writeback_index = mapping->writeback_index; /* prev offset */
  941. index = writeback_index;
  942. if (index == 0)
  943. cycled = 1;
  944. else
  945. cycled = 0;
  946. end = -1;
  947. } else {
  948. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  949. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  950. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  951. range_whole = 1;
  952. cycled = 1; /* ignore range_cyclic tests */
  953. }
  954. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  955. tag = PAGECACHE_TAG_TOWRITE;
  956. else
  957. tag = PAGECACHE_TAG_DIRTY;
  958. retry:
  959. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  960. tag_pages_for_writeback(mapping, index, end);
  961. done_index = index;
  962. while (!done && (index <= end)) {
  963. int i;
  964. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  965. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  966. if (nr_pages == 0)
  967. break;
  968. for (i = 0; i < nr_pages; i++) {
  969. struct page *page = pvec.pages[i];
  970. /*
  971. * At this point, the page may be truncated or
  972. * invalidated (changing page->mapping to NULL), or
  973. * even swizzled back from swapper_space to tmpfs file
  974. * mapping. However, page->index will not change
  975. * because we have a reference on the page.
  976. */
  977. if (page->index > end) {
  978. /*
  979. * can't be range_cyclic (1st pass) because
  980. * end == -1 in that case.
  981. */
  982. done = 1;
  983. break;
  984. }
  985. done_index = page->index;
  986. lock_page(page);
  987. /*
  988. * Page truncated or invalidated. We can freely skip it
  989. * then, even for data integrity operations: the page
  990. * has disappeared concurrently, so there could be no
  991. * real expectation of this data interity operation
  992. * even if there is now a new, dirty page at the same
  993. * pagecache address.
  994. */
  995. if (unlikely(page->mapping != mapping)) {
  996. continue_unlock:
  997. unlock_page(page);
  998. continue;
  999. }
  1000. if (!PageDirty(page)) {
  1001. /* someone wrote it for us */
  1002. goto continue_unlock;
  1003. }
  1004. if (PageWriteback(page)) {
  1005. if (wbc->sync_mode != WB_SYNC_NONE)
  1006. wait_on_page_writeback(page);
  1007. else
  1008. goto continue_unlock;
  1009. }
  1010. BUG_ON(PageWriteback(page));
  1011. if (!clear_page_dirty_for_io(page))
  1012. goto continue_unlock;
  1013. trace_wbc_writepage(wbc, mapping->backing_dev_info);
  1014. ret = (*writepage)(page, wbc, data);
  1015. if (unlikely(ret)) {
  1016. if (ret == AOP_WRITEPAGE_ACTIVATE) {
  1017. unlock_page(page);
  1018. ret = 0;
  1019. } else {
  1020. /*
  1021. * done_index is set past this page,
  1022. * so media errors will not choke
  1023. * background writeout for the entire
  1024. * file. This has consequences for
  1025. * range_cyclic semantics (ie. it may
  1026. * not be suitable for data integrity
  1027. * writeout).
  1028. */
  1029. done_index = page->index + 1;
  1030. done = 1;
  1031. break;
  1032. }
  1033. }
  1034. /*
  1035. * We stop writing back only if we are not doing
  1036. * integrity sync. In case of integrity sync we have to
  1037. * keep going until we have written all the pages
  1038. * we tagged for writeback prior to entering this loop.
  1039. */
  1040. if (--wbc->nr_to_write <= 0 &&
  1041. wbc->sync_mode == WB_SYNC_NONE) {
  1042. done = 1;
  1043. break;
  1044. }
  1045. }
  1046. pagevec_release(&pvec);
  1047. cond_resched();
  1048. }
  1049. if (!cycled && !done) {
  1050. /*
  1051. * range_cyclic:
  1052. * We hit the last page and there is more work to be done: wrap
  1053. * back to the start of the file
  1054. */
  1055. cycled = 1;
  1056. index = 0;
  1057. end = writeback_index - 1;
  1058. goto retry;
  1059. }
  1060. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  1061. mapping->writeback_index = done_index;
  1062. return ret;
  1063. }
  1064. EXPORT_SYMBOL(write_cache_pages);
  1065. /*
  1066. * Function used by generic_writepages to call the real writepage
  1067. * function and set the mapping flags on error
  1068. */
  1069. static int __writepage(struct page *page, struct writeback_control *wbc,
  1070. void *data)
  1071. {
  1072. struct address_space *mapping = data;
  1073. int ret = mapping->a_ops->writepage(page, wbc);
  1074. mapping_set_error(mapping, ret);
  1075. return ret;
  1076. }
  1077. /**
  1078. * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
  1079. * @mapping: address space structure to write
  1080. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1081. *
  1082. * This is a library function, which implements the writepages()
  1083. * address_space_operation.
  1084. */
  1085. int generic_writepages(struct address_space *mapping,
  1086. struct writeback_control *wbc)
  1087. {
  1088. struct blk_plug plug;
  1089. int ret;
  1090. /* deal with chardevs and other special file */
  1091. if (!mapping->a_ops->writepage)
  1092. return 0;
  1093. blk_start_plug(&plug);
  1094. ret = write_cache_pages(mapping, wbc, __writepage, mapping);
  1095. blk_finish_plug(&plug);
  1096. return ret;
  1097. }
  1098. EXPORT_SYMBOL(generic_writepages);
  1099. int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
  1100. {
  1101. int ret;
  1102. if (wbc->nr_to_write <= 0)
  1103. return 0;
  1104. if (mapping->a_ops->writepages)
  1105. ret = mapping->a_ops->writepages(mapping, wbc);
  1106. else
  1107. ret = generic_writepages(mapping, wbc);
  1108. return ret;
  1109. }
  1110. /**
  1111. * write_one_page - write out a single page and optionally wait on I/O
  1112. * @page: the page to write
  1113. * @wait: if true, wait on writeout
  1114. *
  1115. * The page must be locked by the caller and will be unlocked upon return.
  1116. *
  1117. * write_one_page() returns a negative error code if I/O failed.
  1118. */
  1119. int write_one_page(struct page *page, int wait)
  1120. {
  1121. struct address_space *mapping = page->mapping;
  1122. int ret = 0;
  1123. struct writeback_control wbc = {
  1124. .sync_mode = WB_SYNC_ALL,
  1125. .nr_to_write = 1,
  1126. };
  1127. BUG_ON(!PageLocked(page));
  1128. if (wait)
  1129. wait_on_page_writeback(page);
  1130. if (clear_page_dirty_for_io(page)) {
  1131. page_cache_get(page);
  1132. ret = mapping->a_ops->writepage(page, &wbc);
  1133. if (ret == 0 && wait) {
  1134. wait_on_page_writeback(page);
  1135. if (PageError(page))
  1136. ret = -EIO;
  1137. }
  1138. page_cache_release(page);
  1139. } else {
  1140. unlock_page(page);
  1141. }
  1142. return ret;
  1143. }
  1144. EXPORT_SYMBOL(write_one_page);
  1145. /*
  1146. * For address_spaces which do not use buffers nor write back.
  1147. */
  1148. int __set_page_dirty_no_writeback(struct page *page)
  1149. {
  1150. if (!PageDirty(page))
  1151. return !TestSetPageDirty(page);
  1152. return 0;
  1153. }
  1154. /*
  1155. * Helper function for set_page_dirty family.
  1156. * NOTE: This relies on being atomic wrt interrupts.
  1157. */
  1158. void account_page_dirtied(struct page *page, struct address_space *mapping)
  1159. {
  1160. if (mapping_cap_account_dirty(mapping)) {
  1161. __inc_zone_page_state(page, NR_FILE_DIRTY);
  1162. __inc_zone_page_state(page, NR_DIRTIED);
  1163. __inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
  1164. task_dirty_inc(current);
  1165. task_io_account_write(PAGE_CACHE_SIZE);
  1166. }
  1167. }
  1168. EXPORT_SYMBOL(account_page_dirtied);
  1169. /*
  1170. * Helper function for set_page_writeback family.
  1171. * NOTE: Unlike account_page_dirtied this does not rely on being atomic
  1172. * wrt interrupts.
  1173. */
  1174. void account_page_writeback(struct page *page)
  1175. {
  1176. inc_zone_page_state(page, NR_WRITEBACK);
  1177. }
  1178. EXPORT_SYMBOL(account_page_writeback);
  1179. /*
  1180. * For address_spaces which do not use buffers. Just tag the page as dirty in
  1181. * its radix tree.
  1182. *
  1183. * This is also used when a single buffer is being dirtied: we want to set the
  1184. * page dirty in that case, but not all the buffers. This is a "bottom-up"
  1185. * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
  1186. *
  1187. * Most callers have locked the page, which pins the address_space in memory.
  1188. * But zap_pte_range() does not lock the page, however in that case the
  1189. * mapping is pinned by the vma's ->vm_file reference.
  1190. *
  1191. * We take care to handle the case where the page was truncated from the
  1192. * mapping by re-checking page_mapping() inside tree_lock.
  1193. */
  1194. int __set_page_dirty_nobuffers(struct page *page)
  1195. {
  1196. if (!TestSetPageDirty(page)) {
  1197. struct address_space *mapping = page_mapping(page);
  1198. struct address_space *mapping2;
  1199. if (!mapping)
  1200. return 1;
  1201. spin_lock_irq(&mapping->tree_lock);
  1202. mapping2 = page_mapping(page);
  1203. if (mapping2) { /* Race with truncate? */
  1204. BUG_ON(mapping2 != mapping);
  1205. WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
  1206. account_page_dirtied(page, mapping);
  1207. radix_tree_tag_set(&mapping->page_tree,
  1208. page_index(page), PAGECACHE_TAG_DIRTY);
  1209. }
  1210. spin_unlock_irq(&mapping->tree_lock);
  1211. if (mapping->host) {
  1212. /* !PageAnon && !swapper_space */
  1213. __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
  1214. }
  1215. return 1;
  1216. }
  1217. return 0;
  1218. }
  1219. EXPORT_SYMBOL(__set_page_dirty_nobuffers);
  1220. /*
  1221. * When a writepage implementation decides that it doesn't want to write this
  1222. * page for some reason, it should redirty the locked page via
  1223. * redirty_page_for_writepage() and it should then unlock the page and return 0
  1224. */
  1225. int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
  1226. {
  1227. wbc->pages_skipped++;
  1228. return __set_page_dirty_nobuffers(page);
  1229. }
  1230. EXPORT_SYMBOL(redirty_page_for_writepage);
  1231. /*
  1232. * Dirty a page.
  1233. *
  1234. * For pages with a mapping this should be done under the page lock
  1235. * for the benefit of asynchronous memory errors who prefer a consistent
  1236. * dirty state. This rule can be broken in some special cases,
  1237. * but should be better not to.
  1238. *
  1239. * If the mapping doesn't provide a set_page_dirty a_op, then
  1240. * just fall through and assume that it wants buffer_heads.
  1241. */
  1242. int set_page_dirty(struct page *page)
  1243. {
  1244. struct address_space *mapping = page_mapping(page);
  1245. if (likely(mapping)) {
  1246. int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
  1247. /*
  1248. * readahead/lru_deactivate_page could remain
  1249. * PG_readahead/PG_reclaim due to race with end_page_writeback
  1250. * About readahead, if the page is written, the flags would be
  1251. * reset. So no problem.
  1252. * About lru_deactivate_page, if the page is redirty, the flag
  1253. * will be reset. So no problem. but if the page is used by readahead
  1254. * it will confuse readahead and make it restart the size rampup
  1255. * process. But it's a trivial problem.
  1256. */
  1257. ClearPageReclaim(page);
  1258. #ifdef CONFIG_BLOCK
  1259. if (!spd)
  1260. spd = __set_page_dirty_buffers;
  1261. #endif
  1262. return (*spd)(page);
  1263. }
  1264. if (!PageDirty(page)) {
  1265. if (!TestSetPageDirty(page))
  1266. return 1;
  1267. }
  1268. return 0;
  1269. }
  1270. EXPORT_SYMBOL(set_page_dirty);
  1271. /*
  1272. * set_page_dirty() is racy if the caller has no reference against
  1273. * page->mapping->host, and if the page is unlocked. This is because another
  1274. * CPU could truncate the page off the mapping and then free the mapping.
  1275. *
  1276. * Usually, the page _is_ locked, or the caller is a user-space process which
  1277. * holds a reference on the inode by having an open file.
  1278. *
  1279. * In other cases, the page should be locked before running set_page_dirty().
  1280. */
  1281. int set_page_dirty_lock(struct page *page)
  1282. {
  1283. int ret;
  1284. lock_page(page);
  1285. ret = set_page_dirty(page);
  1286. unlock_page(page);
  1287. return ret;
  1288. }
  1289. EXPORT_SYMBOL(set_page_dirty_lock);
  1290. /*
  1291. * Clear a page's dirty flag, while caring for dirty memory accounting.
  1292. * Returns true if the page was previously dirty.
  1293. *
  1294. * This is for preparing to put the page under writeout. We leave the page
  1295. * tagged as dirty in the radix tree so that a concurrent write-for-sync
  1296. * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
  1297. * implementation will run either set_page_writeback() or set_page_dirty(),
  1298. * at which stage we bring the page's dirty flag and radix-tree dirty tag
  1299. * back into sync.
  1300. *
  1301. * This incoherency between the page's dirty flag and radix-tree tag is
  1302. * unfortunate, but it only exists while the page is locked.
  1303. */
  1304. int clear_page_dirty_for_io(struct page *page)
  1305. {
  1306. struct address_space *mapping = page_mapping(page);
  1307. BUG_ON(!PageLocked(page));
  1308. if (mapping && mapping_cap_account_dirty(mapping)) {
  1309. /*
  1310. * Yes, Virginia, this is indeed insane.
  1311. *
  1312. * We use this sequence to make sure that
  1313. * (a) we account for dirty stats properly
  1314. * (b) we tell the low-level filesystem to
  1315. * mark the whole page dirty if it was
  1316. * dirty in a pagetable. Only to then
  1317. * (c) clean the page again and return 1 to
  1318. * cause the writeback.
  1319. *
  1320. * This way we avoid all nasty races with the
  1321. * dirty bit in multiple places and clearing
  1322. * them concurrently from different threads.
  1323. *
  1324. * Note! Normally the "set_page_dirty(page)"
  1325. * has no effect on the actual dirty bit - since
  1326. * that will already usually be set. But we
  1327. * need the side effects, and it can help us
  1328. * avoid races.
  1329. *
  1330. * We basically use the page "master dirty bit"
  1331. * as a serialization point for all the different
  1332. * threads doing their things.
  1333. */
  1334. if (page_mkclean(page))
  1335. set_page_dirty(page);
  1336. /*
  1337. * We carefully synchronise fault handlers against
  1338. * installing a dirty pte and marking the page dirty
  1339. * at this point. We do this by having them hold the
  1340. * page lock at some point after installing their
  1341. * pte, but before marking the page dirty.
  1342. * Pages are always locked coming in here, so we get
  1343. * the desired exclusion. See mm/memory.c:do_wp_page()
  1344. * for more comments.
  1345. */
  1346. if (TestClearPageDirty(page)) {
  1347. dec_zone_page_state(page, NR_FILE_DIRTY);
  1348. dec_bdi_stat(mapping->backing_dev_info,
  1349. BDI_RECLAIMABLE);
  1350. return 1;
  1351. }
  1352. return 0;
  1353. }
  1354. return TestClearPageDirty(page);
  1355. }
  1356. EXPORT_SYMBOL(clear_page_dirty_for_io);
  1357. int test_clear_page_writeback(struct page *page)
  1358. {
  1359. struct address_space *mapping = page_mapping(page);
  1360. int ret;
  1361. if (mapping) {
  1362. struct backing_dev_info *bdi = mapping->backing_dev_info;
  1363. unsigned long flags;
  1364. spin_lock_irqsave(&mapping->tree_lock, flags);
  1365. ret = TestClearPageWriteback(page);
  1366. if (ret) {
  1367. radix_tree_tag_clear(&mapping->page_tree,
  1368. page_index(page),
  1369. PAGECACHE_TAG_WRITEBACK);
  1370. if (bdi_cap_account_writeback(bdi)) {
  1371. __dec_bdi_stat(bdi, BDI_WRITEBACK);
  1372. __bdi_writeout_inc(bdi);
  1373. }
  1374. }
  1375. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  1376. } else {
  1377. ret = TestClearPageWriteback(page);
  1378. }
  1379. if (ret) {
  1380. dec_zone_page_state(page, NR_WRITEBACK);
  1381. inc_zone_page_state(page, NR_WRITTEN);
  1382. }
  1383. return ret;
  1384. }
  1385. int test_set_page_writeback(struct page *page)
  1386. {
  1387. struct address_space *mapping = page_mapping(page);
  1388. int ret;
  1389. if (mapping) {
  1390. struct backing_dev_info *bdi = mapping->backing_dev_info;
  1391. unsigned long flags;
  1392. spin_lock_irqsave(&mapping->tree_lock, flags);
  1393. ret = TestSetPageWriteback(page);
  1394. if (!ret) {
  1395. radix_tree_tag_set(&mapping->page_tree,
  1396. page_index(page),
  1397. PAGECACHE_TAG_WRITEBACK);
  1398. if (bdi_cap_account_writeback(bdi))
  1399. __inc_bdi_stat(bdi, BDI_WRITEBACK);
  1400. }
  1401. if (!PageDirty(page))
  1402. radix_tree_tag_clear(&mapping->page_tree,
  1403. page_index(page),
  1404. PAGECACHE_TAG_DIRTY);
  1405. radix_tree_tag_clear(&mapping->page_tree,
  1406. page_index(page),
  1407. PAGECACHE_TAG_TOWRITE);
  1408. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  1409. } else {
  1410. ret = TestSetPageWriteback(page);
  1411. }
  1412. if (!ret)
  1413. account_page_writeback(page);
  1414. return ret;
  1415. }
  1416. EXPORT_SYMBOL(test_set_page_writeback);
  1417. /*
  1418. * Return true if any of the pages in the mapping are marked with the
  1419. * passed tag.
  1420. */
  1421. int mapping_tagged(struct address_space *mapping, int tag)
  1422. {
  1423. return radix_tree_tagged(&mapping->page_tree, tag);
  1424. }
  1425. EXPORT_SYMBOL(mapping_tagged);