page-writeback.c 40 KB

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