page-writeback.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  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. dirty_thresh / DIRTY_MAXPAUSE_AREA &&
  658. time_after(jiffies, start_time + MAX_PAUSE))
  659. break;
  660. /*
  661. * pass-good area. When some bdi gets blocked (eg. NFS server
  662. * not responding), or write bandwidth dropped dramatically due
  663. * to concurrent reads, or dirty threshold suddenly dropped and
  664. * the dirty pages cannot be brought down anytime soon (eg. on
  665. * slow USB stick), at least let go of the good bdi's.
  666. */
  667. if (nr_dirty < dirty_thresh +
  668. dirty_thresh / DIRTY_PASSGOOD_AREA &&
  669. bdi_dirty < bdi_thresh)
  670. break;
  671. /*
  672. * Increase the delay for each loop, up to our previous
  673. * default of taking a 100ms nap.
  674. */
  675. pause <<= 1;
  676. if (pause > HZ / 10)
  677. pause = HZ / 10;
  678. }
  679. /* Clear dirty_exceeded flag only when no task can exceed the limit */
  680. if (clear_dirty_exceeded && bdi->dirty_exceeded)
  681. bdi->dirty_exceeded = 0;
  682. if (writeback_in_progress(bdi))
  683. return;
  684. /*
  685. * In laptop mode, we wait until hitting the higher threshold before
  686. * starting background writeout, and then write out all the way down
  687. * to the lower threshold. So slow writers cause minimal disk activity.
  688. *
  689. * In normal mode, we start background writeout at the lower
  690. * background_thresh, to keep the amount of dirty memory low.
  691. */
  692. if ((laptop_mode && pages_written) ||
  693. (!laptop_mode && (nr_reclaimable > background_thresh)))
  694. bdi_start_background_writeback(bdi);
  695. }
  696. void set_page_dirty_balance(struct page *page, int page_mkwrite)
  697. {
  698. if (set_page_dirty(page) || page_mkwrite) {
  699. struct address_space *mapping = page_mapping(page);
  700. if (mapping)
  701. balance_dirty_pages_ratelimited(mapping);
  702. }
  703. }
  704. static DEFINE_PER_CPU(unsigned long, bdp_ratelimits) = 0;
  705. /**
  706. * balance_dirty_pages_ratelimited_nr - balance dirty memory state
  707. * @mapping: address_space which was dirtied
  708. * @nr_pages_dirtied: number of pages which the caller has just dirtied
  709. *
  710. * Processes which are dirtying memory should call in here once for each page
  711. * which was newly dirtied. The function will periodically check the system's
  712. * dirty state and will initiate writeback if needed.
  713. *
  714. * On really big machines, get_writeback_state is expensive, so try to avoid
  715. * calling it too often (ratelimiting). But once we're over the dirty memory
  716. * limit we decrease the ratelimiting by a lot, to prevent individual processes
  717. * from overshooting the limit by (ratelimit_pages) each.
  718. */
  719. void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
  720. unsigned long nr_pages_dirtied)
  721. {
  722. struct backing_dev_info *bdi = mapping->backing_dev_info;
  723. unsigned long ratelimit;
  724. unsigned long *p;
  725. if (!bdi_cap_account_dirty(bdi))
  726. return;
  727. ratelimit = ratelimit_pages;
  728. if (mapping->backing_dev_info->dirty_exceeded)
  729. ratelimit = 8;
  730. /*
  731. * Check the rate limiting. Also, we do not want to throttle real-time
  732. * tasks in balance_dirty_pages(). Period.
  733. */
  734. preempt_disable();
  735. p = &__get_cpu_var(bdp_ratelimits);
  736. *p += nr_pages_dirtied;
  737. if (unlikely(*p >= ratelimit)) {
  738. ratelimit = sync_writeback_pages(*p);
  739. *p = 0;
  740. preempt_enable();
  741. balance_dirty_pages(mapping, ratelimit);
  742. return;
  743. }
  744. preempt_enable();
  745. }
  746. EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
  747. void throttle_vm_writeout(gfp_t gfp_mask)
  748. {
  749. unsigned long background_thresh;
  750. unsigned long dirty_thresh;
  751. for ( ; ; ) {
  752. global_dirty_limits(&background_thresh, &dirty_thresh);
  753. /*
  754. * Boost the allowable dirty threshold a bit for page
  755. * allocators so they don't get DoS'ed by heavy writers
  756. */
  757. dirty_thresh += dirty_thresh / 10; /* wheeee... */
  758. if (global_page_state(NR_UNSTABLE_NFS) +
  759. global_page_state(NR_WRITEBACK) <= dirty_thresh)
  760. break;
  761. congestion_wait(BLK_RW_ASYNC, HZ/10);
  762. /*
  763. * The caller might hold locks which can prevent IO completion
  764. * or progress in the filesystem. So we cannot just sit here
  765. * waiting for IO to complete.
  766. */
  767. if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
  768. break;
  769. }
  770. }
  771. /*
  772. * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
  773. */
  774. int dirty_writeback_centisecs_handler(ctl_table *table, int write,
  775. void __user *buffer, size_t *length, loff_t *ppos)
  776. {
  777. proc_dointvec(table, write, buffer, length, ppos);
  778. bdi_arm_supers_timer();
  779. return 0;
  780. }
  781. #ifdef CONFIG_BLOCK
  782. void laptop_mode_timer_fn(unsigned long data)
  783. {
  784. struct request_queue *q = (struct request_queue *)data;
  785. int nr_pages = global_page_state(NR_FILE_DIRTY) +
  786. global_page_state(NR_UNSTABLE_NFS);
  787. /*
  788. * We want to write everything out, not just down to the dirty
  789. * threshold
  790. */
  791. if (bdi_has_dirty_io(&q->backing_dev_info))
  792. bdi_start_writeback(&q->backing_dev_info, nr_pages);
  793. }
  794. /*
  795. * We've spun up the disk and we're in laptop mode: schedule writeback
  796. * of all dirty data a few seconds from now. If the flush is already scheduled
  797. * then push it back - the user is still using the disk.
  798. */
  799. void laptop_io_completion(struct backing_dev_info *info)
  800. {
  801. mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
  802. }
  803. /*
  804. * We're in laptop mode and we've just synced. The sync's writes will have
  805. * caused another writeback to be scheduled by laptop_io_completion.
  806. * Nothing needs to be written back anymore, so we unschedule the writeback.
  807. */
  808. void laptop_sync_completion(void)
  809. {
  810. struct backing_dev_info *bdi;
  811. rcu_read_lock();
  812. list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
  813. del_timer(&bdi->laptop_mode_wb_timer);
  814. rcu_read_unlock();
  815. }
  816. #endif
  817. /*
  818. * If ratelimit_pages is too high then we can get into dirty-data overload
  819. * if a large number of processes all perform writes at the same time.
  820. * If it is too low then SMP machines will call the (expensive)
  821. * get_writeback_state too often.
  822. *
  823. * Here we set ratelimit_pages to a level which ensures that when all CPUs are
  824. * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
  825. * thresholds before writeback cuts in.
  826. *
  827. * But the limit should not be set too high. Because it also controls the
  828. * amount of memory which the balance_dirty_pages() caller has to write back.
  829. * If this is too large then the caller will block on the IO queue all the
  830. * time. So limit it to four megabytes - the balance_dirty_pages() caller
  831. * will write six megabyte chunks, max.
  832. */
  833. void writeback_set_ratelimit(void)
  834. {
  835. ratelimit_pages = vm_total_pages / (num_online_cpus() * 32);
  836. if (ratelimit_pages < 16)
  837. ratelimit_pages = 16;
  838. if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
  839. ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
  840. }
  841. static int __cpuinit
  842. ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
  843. {
  844. writeback_set_ratelimit();
  845. return NOTIFY_DONE;
  846. }
  847. static struct notifier_block __cpuinitdata ratelimit_nb = {
  848. .notifier_call = ratelimit_handler,
  849. .next = NULL,
  850. };
  851. /*
  852. * Called early on to tune the page writeback dirty limits.
  853. *
  854. * We used to scale dirty pages according to how total memory
  855. * related to pages that could be allocated for buffers (by
  856. * comparing nr_free_buffer_pages() to vm_total_pages.
  857. *
  858. * However, that was when we used "dirty_ratio" to scale with
  859. * all memory, and we don't do that any more. "dirty_ratio"
  860. * is now applied to total non-HIGHPAGE memory (by subtracting
  861. * totalhigh_pages from vm_total_pages), and as such we can't
  862. * get into the old insane situation any more where we had
  863. * large amounts of dirty pages compared to a small amount of
  864. * non-HIGHMEM memory.
  865. *
  866. * But we might still want to scale the dirty_ratio by how
  867. * much memory the box has..
  868. */
  869. void __init page_writeback_init(void)
  870. {
  871. int shift;
  872. writeback_set_ratelimit();
  873. register_cpu_notifier(&ratelimit_nb);
  874. shift = calc_period_shift();
  875. prop_descriptor_init(&vm_completions, shift);
  876. prop_descriptor_init(&vm_dirties, shift);
  877. }
  878. /**
  879. * tag_pages_for_writeback - tag pages to be written by write_cache_pages
  880. * @mapping: address space structure to write
  881. * @start: starting page index
  882. * @end: ending page index (inclusive)
  883. *
  884. * This function scans the page range from @start to @end (inclusive) and tags
  885. * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
  886. * that write_cache_pages (or whoever calls this function) will then use
  887. * TOWRITE tag to identify pages eligible for writeback. This mechanism is
  888. * used to avoid livelocking of writeback by a process steadily creating new
  889. * dirty pages in the file (thus it is important for this function to be quick
  890. * so that it can tag pages faster than a dirtying process can create them).
  891. */
  892. /*
  893. * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
  894. */
  895. void tag_pages_for_writeback(struct address_space *mapping,
  896. pgoff_t start, pgoff_t end)
  897. {
  898. #define WRITEBACK_TAG_BATCH 4096
  899. unsigned long tagged;
  900. do {
  901. spin_lock_irq(&mapping->tree_lock);
  902. tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree,
  903. &start, end, WRITEBACK_TAG_BATCH,
  904. PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE);
  905. spin_unlock_irq(&mapping->tree_lock);
  906. WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
  907. cond_resched();
  908. /* We check 'start' to handle wrapping when end == ~0UL */
  909. } while (tagged >= WRITEBACK_TAG_BATCH && start);
  910. }
  911. EXPORT_SYMBOL(tag_pages_for_writeback);
  912. /**
  913. * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
  914. * @mapping: address space structure to write
  915. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  916. * @writepage: function called for each page
  917. * @data: data passed to writepage function
  918. *
  919. * If a page is already under I/O, write_cache_pages() skips it, even
  920. * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
  921. * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
  922. * and msync() need to guarantee that all the data which was dirty at the time
  923. * the call was made get new I/O started against them. If wbc->sync_mode is
  924. * WB_SYNC_ALL then we were called for data integrity and we must wait for
  925. * existing IO to complete.
  926. *
  927. * To avoid livelocks (when other process dirties new pages), we first tag
  928. * pages which should be written back with TOWRITE tag and only then start
  929. * writing them. For data-integrity sync we have to be careful so that we do
  930. * not miss some pages (e.g., because some other process has cleared TOWRITE
  931. * tag we set). The rule we follow is that TOWRITE tag can be cleared only
  932. * by the process clearing the DIRTY tag (and submitting the page for IO).
  933. */
  934. int write_cache_pages(struct address_space *mapping,
  935. struct writeback_control *wbc, writepage_t writepage,
  936. void *data)
  937. {
  938. int ret = 0;
  939. int done = 0;
  940. struct pagevec pvec;
  941. int nr_pages;
  942. pgoff_t uninitialized_var(writeback_index);
  943. pgoff_t index;
  944. pgoff_t end; /* Inclusive */
  945. pgoff_t done_index;
  946. int cycled;
  947. int range_whole = 0;
  948. int tag;
  949. pagevec_init(&pvec, 0);
  950. if (wbc->range_cyclic) {
  951. writeback_index = mapping->writeback_index; /* prev offset */
  952. index = writeback_index;
  953. if (index == 0)
  954. cycled = 1;
  955. else
  956. cycled = 0;
  957. end = -1;
  958. } else {
  959. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  960. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  961. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  962. range_whole = 1;
  963. cycled = 1; /* ignore range_cyclic tests */
  964. }
  965. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  966. tag = PAGECACHE_TAG_TOWRITE;
  967. else
  968. tag = PAGECACHE_TAG_DIRTY;
  969. retry:
  970. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  971. tag_pages_for_writeback(mapping, index, end);
  972. done_index = index;
  973. while (!done && (index <= end)) {
  974. int i;
  975. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  976. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  977. if (nr_pages == 0)
  978. break;
  979. for (i = 0; i < nr_pages; i++) {
  980. struct page *page = pvec.pages[i];
  981. /*
  982. * At this point, the page may be truncated or
  983. * invalidated (changing page->mapping to NULL), or
  984. * even swizzled back from swapper_space to tmpfs file
  985. * mapping. However, page->index will not change
  986. * because we have a reference on the page.
  987. */
  988. if (page->index > end) {
  989. /*
  990. * can't be range_cyclic (1st pass) because
  991. * end == -1 in that case.
  992. */
  993. done = 1;
  994. break;
  995. }
  996. done_index = page->index;
  997. lock_page(page);
  998. /*
  999. * Page truncated or invalidated. We can freely skip it
  1000. * then, even for data integrity operations: the page
  1001. * has disappeared concurrently, so there could be no
  1002. * real expectation of this data interity operation
  1003. * even if there is now a new, dirty page at the same
  1004. * pagecache address.
  1005. */
  1006. if (unlikely(page->mapping != mapping)) {
  1007. continue_unlock:
  1008. unlock_page(page);
  1009. continue;
  1010. }
  1011. if (!PageDirty(page)) {
  1012. /* someone wrote it for us */
  1013. goto continue_unlock;
  1014. }
  1015. if (PageWriteback(page)) {
  1016. if (wbc->sync_mode != WB_SYNC_NONE)
  1017. wait_on_page_writeback(page);
  1018. else
  1019. goto continue_unlock;
  1020. }
  1021. BUG_ON(PageWriteback(page));
  1022. if (!clear_page_dirty_for_io(page))
  1023. goto continue_unlock;
  1024. trace_wbc_writepage(wbc, mapping->backing_dev_info);
  1025. ret = (*writepage)(page, wbc, data);
  1026. if (unlikely(ret)) {
  1027. if (ret == AOP_WRITEPAGE_ACTIVATE) {
  1028. unlock_page(page);
  1029. ret = 0;
  1030. } else {
  1031. /*
  1032. * done_index is set past this page,
  1033. * so media errors will not choke
  1034. * background writeout for the entire
  1035. * file. This has consequences for
  1036. * range_cyclic semantics (ie. it may
  1037. * not be suitable for data integrity
  1038. * writeout).
  1039. */
  1040. done_index = page->index + 1;
  1041. done = 1;
  1042. break;
  1043. }
  1044. }
  1045. /*
  1046. * We stop writing back only if we are not doing
  1047. * integrity sync. In case of integrity sync we have to
  1048. * keep going until we have written all the pages
  1049. * we tagged for writeback prior to entering this loop.
  1050. */
  1051. if (--wbc->nr_to_write <= 0 &&
  1052. wbc->sync_mode == WB_SYNC_NONE) {
  1053. done = 1;
  1054. break;
  1055. }
  1056. }
  1057. pagevec_release(&pvec);
  1058. cond_resched();
  1059. }
  1060. if (!cycled && !done) {
  1061. /*
  1062. * range_cyclic:
  1063. * We hit the last page and there is more work to be done: wrap
  1064. * back to the start of the file
  1065. */
  1066. cycled = 1;
  1067. index = 0;
  1068. end = writeback_index - 1;
  1069. goto retry;
  1070. }
  1071. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  1072. mapping->writeback_index = done_index;
  1073. return ret;
  1074. }
  1075. EXPORT_SYMBOL(write_cache_pages);
  1076. /*
  1077. * Function used by generic_writepages to call the real writepage
  1078. * function and set the mapping flags on error
  1079. */
  1080. static int __writepage(struct page *page, struct writeback_control *wbc,
  1081. void *data)
  1082. {
  1083. struct address_space *mapping = data;
  1084. int ret = mapping->a_ops->writepage(page, wbc);
  1085. mapping_set_error(mapping, ret);
  1086. return ret;
  1087. }
  1088. /**
  1089. * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
  1090. * @mapping: address space structure to write
  1091. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1092. *
  1093. * This is a library function, which implements the writepages()
  1094. * address_space_operation.
  1095. */
  1096. int generic_writepages(struct address_space *mapping,
  1097. struct writeback_control *wbc)
  1098. {
  1099. struct blk_plug plug;
  1100. int ret;
  1101. /* deal with chardevs and other special file */
  1102. if (!mapping->a_ops->writepage)
  1103. return 0;
  1104. blk_start_plug(&plug);
  1105. ret = write_cache_pages(mapping, wbc, __writepage, mapping);
  1106. blk_finish_plug(&plug);
  1107. return ret;
  1108. }
  1109. EXPORT_SYMBOL(generic_writepages);
  1110. int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
  1111. {
  1112. int ret;
  1113. if (wbc->nr_to_write <= 0)
  1114. return 0;
  1115. if (mapping->a_ops->writepages)
  1116. ret = mapping->a_ops->writepages(mapping, wbc);
  1117. else
  1118. ret = generic_writepages(mapping, wbc);
  1119. return ret;
  1120. }
  1121. /**
  1122. * write_one_page - write out a single page and optionally wait on I/O
  1123. * @page: the page to write
  1124. * @wait: if true, wait on writeout
  1125. *
  1126. * The page must be locked by the caller and will be unlocked upon return.
  1127. *
  1128. * write_one_page() returns a negative error code if I/O failed.
  1129. */
  1130. int write_one_page(struct page *page, int wait)
  1131. {
  1132. struct address_space *mapping = page->mapping;
  1133. int ret = 0;
  1134. struct writeback_control wbc = {
  1135. .sync_mode = WB_SYNC_ALL,
  1136. .nr_to_write = 1,
  1137. };
  1138. BUG_ON(!PageLocked(page));
  1139. if (wait)
  1140. wait_on_page_writeback(page);
  1141. if (clear_page_dirty_for_io(page)) {
  1142. page_cache_get(page);
  1143. ret = mapping->a_ops->writepage(page, &wbc);
  1144. if (ret == 0 && wait) {
  1145. wait_on_page_writeback(page);
  1146. if (PageError(page))
  1147. ret = -EIO;
  1148. }
  1149. page_cache_release(page);
  1150. } else {
  1151. unlock_page(page);
  1152. }
  1153. return ret;
  1154. }
  1155. EXPORT_SYMBOL(write_one_page);
  1156. /*
  1157. * For address_spaces which do not use buffers nor write back.
  1158. */
  1159. int __set_page_dirty_no_writeback(struct page *page)
  1160. {
  1161. if (!PageDirty(page))
  1162. return !TestSetPageDirty(page);
  1163. return 0;
  1164. }
  1165. /*
  1166. * Helper function for set_page_dirty family.
  1167. * NOTE: This relies on being atomic wrt interrupts.
  1168. */
  1169. void account_page_dirtied(struct page *page, struct address_space *mapping)
  1170. {
  1171. if (mapping_cap_account_dirty(mapping)) {
  1172. __inc_zone_page_state(page, NR_FILE_DIRTY);
  1173. __inc_zone_page_state(page, NR_DIRTIED);
  1174. __inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
  1175. task_dirty_inc(current);
  1176. task_io_account_write(PAGE_CACHE_SIZE);
  1177. }
  1178. }
  1179. EXPORT_SYMBOL(account_page_dirtied);
  1180. /*
  1181. * Helper function for set_page_writeback family.
  1182. * NOTE: Unlike account_page_dirtied this does not rely on being atomic
  1183. * wrt interrupts.
  1184. */
  1185. void account_page_writeback(struct page *page)
  1186. {
  1187. inc_zone_page_state(page, NR_WRITEBACK);
  1188. }
  1189. EXPORT_SYMBOL(account_page_writeback);
  1190. /*
  1191. * For address_spaces which do not use buffers. Just tag the page as dirty in
  1192. * its radix tree.
  1193. *
  1194. * This is also used when a single buffer is being dirtied: we want to set the
  1195. * page dirty in that case, but not all the buffers. This is a "bottom-up"
  1196. * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
  1197. *
  1198. * Most callers have locked the page, which pins the address_space in memory.
  1199. * But zap_pte_range() does not lock the page, however in that case the
  1200. * mapping is pinned by the vma's ->vm_file reference.
  1201. *
  1202. * We take care to handle the case where the page was truncated from the
  1203. * mapping by re-checking page_mapping() inside tree_lock.
  1204. */
  1205. int __set_page_dirty_nobuffers(struct page *page)
  1206. {
  1207. if (!TestSetPageDirty(page)) {
  1208. struct address_space *mapping = page_mapping(page);
  1209. struct address_space *mapping2;
  1210. if (!mapping)
  1211. return 1;
  1212. spin_lock_irq(&mapping->tree_lock);
  1213. mapping2 = page_mapping(page);
  1214. if (mapping2) { /* Race with truncate? */
  1215. BUG_ON(mapping2 != mapping);
  1216. WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
  1217. account_page_dirtied(page, mapping);
  1218. radix_tree_tag_set(&mapping->page_tree,
  1219. page_index(page), PAGECACHE_TAG_DIRTY);
  1220. }
  1221. spin_unlock_irq(&mapping->tree_lock);
  1222. if (mapping->host) {
  1223. /* !PageAnon && !swapper_space */
  1224. __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
  1225. }
  1226. return 1;
  1227. }
  1228. return 0;
  1229. }
  1230. EXPORT_SYMBOL(__set_page_dirty_nobuffers);
  1231. /*
  1232. * When a writepage implementation decides that it doesn't want to write this
  1233. * page for some reason, it should redirty the locked page via
  1234. * redirty_page_for_writepage() and it should then unlock the page and return 0
  1235. */
  1236. int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
  1237. {
  1238. wbc->pages_skipped++;
  1239. return __set_page_dirty_nobuffers(page);
  1240. }
  1241. EXPORT_SYMBOL(redirty_page_for_writepage);
  1242. /*
  1243. * Dirty a page.
  1244. *
  1245. * For pages with a mapping this should be done under the page lock
  1246. * for the benefit of asynchronous memory errors who prefer a consistent
  1247. * dirty state. This rule can be broken in some special cases,
  1248. * but should be better not to.
  1249. *
  1250. * If the mapping doesn't provide a set_page_dirty a_op, then
  1251. * just fall through and assume that it wants buffer_heads.
  1252. */
  1253. int set_page_dirty(struct page *page)
  1254. {
  1255. struct address_space *mapping = page_mapping(page);
  1256. if (likely(mapping)) {
  1257. int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
  1258. /*
  1259. * readahead/lru_deactivate_page could remain
  1260. * PG_readahead/PG_reclaim due to race with end_page_writeback
  1261. * About readahead, if the page is written, the flags would be
  1262. * reset. So no problem.
  1263. * About lru_deactivate_page, if the page is redirty, the flag
  1264. * will be reset. So no problem. but if the page is used by readahead
  1265. * it will confuse readahead and make it restart the size rampup
  1266. * process. But it's a trivial problem.
  1267. */
  1268. ClearPageReclaim(page);
  1269. #ifdef CONFIG_BLOCK
  1270. if (!spd)
  1271. spd = __set_page_dirty_buffers;
  1272. #endif
  1273. return (*spd)(page);
  1274. }
  1275. if (!PageDirty(page)) {
  1276. if (!TestSetPageDirty(page))
  1277. return 1;
  1278. }
  1279. return 0;
  1280. }
  1281. EXPORT_SYMBOL(set_page_dirty);
  1282. /*
  1283. * set_page_dirty() is racy if the caller has no reference against
  1284. * page->mapping->host, and if the page is unlocked. This is because another
  1285. * CPU could truncate the page off the mapping and then free the mapping.
  1286. *
  1287. * Usually, the page _is_ locked, or the caller is a user-space process which
  1288. * holds a reference on the inode by having an open file.
  1289. *
  1290. * In other cases, the page should be locked before running set_page_dirty().
  1291. */
  1292. int set_page_dirty_lock(struct page *page)
  1293. {
  1294. int ret;
  1295. lock_page(page);
  1296. ret = set_page_dirty(page);
  1297. unlock_page(page);
  1298. return ret;
  1299. }
  1300. EXPORT_SYMBOL(set_page_dirty_lock);
  1301. /*
  1302. * Clear a page's dirty flag, while caring for dirty memory accounting.
  1303. * Returns true if the page was previously dirty.
  1304. *
  1305. * This is for preparing to put the page under writeout. We leave the page
  1306. * tagged as dirty in the radix tree so that a concurrent write-for-sync
  1307. * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
  1308. * implementation will run either set_page_writeback() or set_page_dirty(),
  1309. * at which stage we bring the page's dirty flag and radix-tree dirty tag
  1310. * back into sync.
  1311. *
  1312. * This incoherency between the page's dirty flag and radix-tree tag is
  1313. * unfortunate, but it only exists while the page is locked.
  1314. */
  1315. int clear_page_dirty_for_io(struct page *page)
  1316. {
  1317. struct address_space *mapping = page_mapping(page);
  1318. BUG_ON(!PageLocked(page));
  1319. if (mapping && mapping_cap_account_dirty(mapping)) {
  1320. /*
  1321. * Yes, Virginia, this is indeed insane.
  1322. *
  1323. * We use this sequence to make sure that
  1324. * (a) we account for dirty stats properly
  1325. * (b) we tell the low-level filesystem to
  1326. * mark the whole page dirty if it was
  1327. * dirty in a pagetable. Only to then
  1328. * (c) clean the page again and return 1 to
  1329. * cause the writeback.
  1330. *
  1331. * This way we avoid all nasty races with the
  1332. * dirty bit in multiple places and clearing
  1333. * them concurrently from different threads.
  1334. *
  1335. * Note! Normally the "set_page_dirty(page)"
  1336. * has no effect on the actual dirty bit - since
  1337. * that will already usually be set. But we
  1338. * need the side effects, and it can help us
  1339. * avoid races.
  1340. *
  1341. * We basically use the page "master dirty bit"
  1342. * as a serialization point for all the different
  1343. * threads doing their things.
  1344. */
  1345. if (page_mkclean(page))
  1346. set_page_dirty(page);
  1347. /*
  1348. * We carefully synchronise fault handlers against
  1349. * installing a dirty pte and marking the page dirty
  1350. * at this point. We do this by having them hold the
  1351. * page lock at some point after installing their
  1352. * pte, but before marking the page dirty.
  1353. * Pages are always locked coming in here, so we get
  1354. * the desired exclusion. See mm/memory.c:do_wp_page()
  1355. * for more comments.
  1356. */
  1357. if (TestClearPageDirty(page)) {
  1358. dec_zone_page_state(page, NR_FILE_DIRTY);
  1359. dec_bdi_stat(mapping->backing_dev_info,
  1360. BDI_RECLAIMABLE);
  1361. return 1;
  1362. }
  1363. return 0;
  1364. }
  1365. return TestClearPageDirty(page);
  1366. }
  1367. EXPORT_SYMBOL(clear_page_dirty_for_io);
  1368. int test_clear_page_writeback(struct page *page)
  1369. {
  1370. struct address_space *mapping = page_mapping(page);
  1371. int ret;
  1372. if (mapping) {
  1373. struct backing_dev_info *bdi = mapping->backing_dev_info;
  1374. unsigned long flags;
  1375. spin_lock_irqsave(&mapping->tree_lock, flags);
  1376. ret = TestClearPageWriteback(page);
  1377. if (ret) {
  1378. radix_tree_tag_clear(&mapping->page_tree,
  1379. page_index(page),
  1380. PAGECACHE_TAG_WRITEBACK);
  1381. if (bdi_cap_account_writeback(bdi)) {
  1382. __dec_bdi_stat(bdi, BDI_WRITEBACK);
  1383. __bdi_writeout_inc(bdi);
  1384. }
  1385. }
  1386. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  1387. } else {
  1388. ret = TestClearPageWriteback(page);
  1389. }
  1390. if (ret) {
  1391. dec_zone_page_state(page, NR_WRITEBACK);
  1392. inc_zone_page_state(page, NR_WRITTEN);
  1393. }
  1394. return ret;
  1395. }
  1396. int test_set_page_writeback(struct page *page)
  1397. {
  1398. struct address_space *mapping = page_mapping(page);
  1399. int ret;
  1400. if (mapping) {
  1401. struct backing_dev_info *bdi = mapping->backing_dev_info;
  1402. unsigned long flags;
  1403. spin_lock_irqsave(&mapping->tree_lock, flags);
  1404. ret = TestSetPageWriteback(page);
  1405. if (!ret) {
  1406. radix_tree_tag_set(&mapping->page_tree,
  1407. page_index(page),
  1408. PAGECACHE_TAG_WRITEBACK);
  1409. if (bdi_cap_account_writeback(bdi))
  1410. __inc_bdi_stat(bdi, BDI_WRITEBACK);
  1411. }
  1412. if (!PageDirty(page))
  1413. radix_tree_tag_clear(&mapping->page_tree,
  1414. page_index(page),
  1415. PAGECACHE_TAG_DIRTY);
  1416. radix_tree_tag_clear(&mapping->page_tree,
  1417. page_index(page),
  1418. PAGECACHE_TAG_TOWRITE);
  1419. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  1420. } else {
  1421. ret = TestSetPageWriteback(page);
  1422. }
  1423. if (!ret)
  1424. account_page_writeback(page);
  1425. return ret;
  1426. }
  1427. EXPORT_SYMBOL(test_set_page_writeback);
  1428. /*
  1429. * Return true if any of the pages in the mapping are marked with the
  1430. * passed tag.
  1431. */
  1432. int mapping_tagged(struct address_space *mapping, int tag)
  1433. {
  1434. return radix_tree_tagged(&mapping->page_tree, tag);
  1435. }
  1436. EXPORT_SYMBOL(mapping_tagged);