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