page-writeback.c 45 KB

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