page-writeback.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154
  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/export.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. * Try to keep balance_dirty_pages() call intervals higher than this many pages
  43. * by raising pause time to max_pause when falls below it.
  44. */
  45. #define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10))
  46. /*
  47. * Estimate write bandwidth at 200ms intervals.
  48. */
  49. #define BANDWIDTH_INTERVAL max(HZ/5, 1)
  50. #define RATELIMIT_CALC_SHIFT 10
  51. /*
  52. * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
  53. * will look to see if it needs to force writeback or throttling.
  54. */
  55. static long ratelimit_pages = 32;
  56. /* The following parameters are exported via /proc/sys/vm */
  57. /*
  58. * Start background writeback (via writeback threads) at this percentage
  59. */
  60. int dirty_background_ratio = 10;
  61. /*
  62. * dirty_background_bytes starts at 0 (disabled) so that it is a function of
  63. * dirty_background_ratio * the amount of dirtyable memory
  64. */
  65. unsigned long dirty_background_bytes;
  66. /*
  67. * free highmem will not be subtracted from the total free memory
  68. * for calculating free ratios if vm_highmem_is_dirtyable is true
  69. */
  70. int vm_highmem_is_dirtyable;
  71. /*
  72. * The generator of dirty data starts writeback at this percentage
  73. */
  74. int vm_dirty_ratio = 20;
  75. /*
  76. * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
  77. * vm_dirty_ratio * the amount of dirtyable memory
  78. */
  79. unsigned long vm_dirty_bytes;
  80. /*
  81. * The interval between `kupdate'-style writebacks
  82. */
  83. unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
  84. /*
  85. * The longest time for which data is allowed to remain dirty
  86. */
  87. unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
  88. /*
  89. * Flag that makes the machine dump writes/reads and block dirtyings.
  90. */
  91. int block_dump;
  92. /*
  93. * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
  94. * a full sync is triggered after this time elapses without any disk activity.
  95. */
  96. int laptop_mode;
  97. EXPORT_SYMBOL(laptop_mode);
  98. /* End of sysctl-exported parameters */
  99. unsigned long global_dirty_limit;
  100. /*
  101. * Scale the writeback cache size proportional to the relative writeout speeds.
  102. *
  103. * We do this by keeping a floating proportion between BDIs, based on page
  104. * writeback completions [end_page_writeback()]. Those devices that write out
  105. * pages fastest will get the larger share, while the slower will get a smaller
  106. * share.
  107. *
  108. * We use page writeout completions because we are interested in getting rid of
  109. * dirty pages. Having them written out is the primary goal.
  110. *
  111. * We introduce a concept of time, a period over which we measure these events,
  112. * because demand can/will vary over time. The length of this period itself is
  113. * measured in page writeback completions.
  114. *
  115. */
  116. static struct prop_descriptor vm_completions;
  117. /*
  118. * couple the period to the dirty_ratio:
  119. *
  120. * period/2 ~ roundup_pow_of_two(dirty limit)
  121. */
  122. static int calc_period_shift(void)
  123. {
  124. unsigned long dirty_total;
  125. if (vm_dirty_bytes)
  126. dirty_total = vm_dirty_bytes / PAGE_SIZE;
  127. else
  128. dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) /
  129. 100;
  130. return 2 + ilog2(dirty_total - 1);
  131. }
  132. /*
  133. * update the period when the dirty threshold changes.
  134. */
  135. static void update_completion_period(void)
  136. {
  137. int shift = calc_period_shift();
  138. prop_change_shift(&vm_completions, shift);
  139. writeback_set_ratelimit();
  140. }
  141. int dirty_background_ratio_handler(struct ctl_table *table, int write,
  142. void __user *buffer, size_t *lenp,
  143. loff_t *ppos)
  144. {
  145. int ret;
  146. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  147. if (ret == 0 && write)
  148. dirty_background_bytes = 0;
  149. return ret;
  150. }
  151. int dirty_background_bytes_handler(struct ctl_table *table, int write,
  152. void __user *buffer, size_t *lenp,
  153. loff_t *ppos)
  154. {
  155. int ret;
  156. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  157. if (ret == 0 && write)
  158. dirty_background_ratio = 0;
  159. return ret;
  160. }
  161. int dirty_ratio_handler(struct ctl_table *table, int write,
  162. void __user *buffer, size_t *lenp,
  163. loff_t *ppos)
  164. {
  165. int old_ratio = vm_dirty_ratio;
  166. int ret;
  167. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  168. if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
  169. update_completion_period();
  170. vm_dirty_bytes = 0;
  171. }
  172. return ret;
  173. }
  174. int dirty_bytes_handler(struct ctl_table *table, int write,
  175. void __user *buffer, size_t *lenp,
  176. loff_t *ppos)
  177. {
  178. unsigned long old_bytes = vm_dirty_bytes;
  179. int ret;
  180. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  181. if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
  182. update_completion_period();
  183. vm_dirty_ratio = 0;
  184. }
  185. return ret;
  186. }
  187. /*
  188. * Increment the BDI's writeout completion count and the global writeout
  189. * completion count. Called from test_clear_page_writeback().
  190. */
  191. static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
  192. {
  193. __inc_bdi_stat(bdi, BDI_WRITTEN);
  194. __prop_inc_percpu_max(&vm_completions, &bdi->completions,
  195. bdi->max_prop_frac);
  196. }
  197. void bdi_writeout_inc(struct backing_dev_info *bdi)
  198. {
  199. unsigned long flags;
  200. local_irq_save(flags);
  201. __bdi_writeout_inc(bdi);
  202. local_irq_restore(flags);
  203. }
  204. EXPORT_SYMBOL_GPL(bdi_writeout_inc);
  205. /*
  206. * Obtain an accurate fraction of the BDI's portion.
  207. */
  208. static void bdi_writeout_fraction(struct backing_dev_info *bdi,
  209. long *numerator, long *denominator)
  210. {
  211. prop_fraction_percpu(&vm_completions, &bdi->completions,
  212. numerator, denominator);
  213. }
  214. /*
  215. * bdi_min_ratio keeps the sum of the minimum dirty shares of all
  216. * registered backing devices, which, for obvious reasons, can not
  217. * exceed 100%.
  218. */
  219. static unsigned int bdi_min_ratio;
  220. int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
  221. {
  222. int ret = 0;
  223. spin_lock_bh(&bdi_lock);
  224. if (min_ratio > bdi->max_ratio) {
  225. ret = -EINVAL;
  226. } else {
  227. min_ratio -= bdi->min_ratio;
  228. if (bdi_min_ratio + min_ratio < 100) {
  229. bdi_min_ratio += min_ratio;
  230. bdi->min_ratio += min_ratio;
  231. } else {
  232. ret = -EINVAL;
  233. }
  234. }
  235. spin_unlock_bh(&bdi_lock);
  236. return ret;
  237. }
  238. int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
  239. {
  240. int ret = 0;
  241. if (max_ratio > 100)
  242. return -EINVAL;
  243. spin_lock_bh(&bdi_lock);
  244. if (bdi->min_ratio > max_ratio) {
  245. ret = -EINVAL;
  246. } else {
  247. bdi->max_ratio = max_ratio;
  248. bdi->max_prop_frac = (PROP_FRAC_BASE * max_ratio) / 100;
  249. }
  250. spin_unlock_bh(&bdi_lock);
  251. return ret;
  252. }
  253. EXPORT_SYMBOL(bdi_set_max_ratio);
  254. /*
  255. * Work out the current dirty-memory clamping and background writeout
  256. * thresholds.
  257. *
  258. * The main aim here is to lower them aggressively if there is a lot of mapped
  259. * memory around. To avoid stressing page reclaim with lots of unreclaimable
  260. * pages. It is better to clamp down on writers than to start swapping, and
  261. * performing lots of scanning.
  262. *
  263. * We only allow 1/2 of the currently-unmapped memory to be dirtied.
  264. *
  265. * We don't permit the clamping level to fall below 5% - that is getting rather
  266. * excessive.
  267. *
  268. * We make sure that the background writeout level is below the adjusted
  269. * clamping level.
  270. */
  271. static unsigned long highmem_dirtyable_memory(unsigned long total)
  272. {
  273. #ifdef CONFIG_HIGHMEM
  274. int node;
  275. unsigned long x = 0;
  276. for_each_node_state(node, N_HIGH_MEMORY) {
  277. struct zone *z =
  278. &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
  279. x += zone_page_state(z, NR_FREE_PAGES) +
  280. zone_reclaimable_pages(z);
  281. }
  282. /*
  283. * Make sure that the number of highmem pages is never larger
  284. * than the number of the total dirtyable memory. This can only
  285. * occur in very strange VM situations but we want to make sure
  286. * that this does not occur.
  287. */
  288. return min(x, total);
  289. #else
  290. return 0;
  291. #endif
  292. }
  293. /**
  294. * determine_dirtyable_memory - amount of memory that may be used
  295. *
  296. * Returns the numebr of pages that can currently be freed and used
  297. * by the kernel for direct mappings.
  298. */
  299. unsigned long determine_dirtyable_memory(void)
  300. {
  301. unsigned long x;
  302. x = global_page_state(NR_FREE_PAGES) + global_reclaimable_pages();
  303. if (!vm_highmem_is_dirtyable)
  304. x -= highmem_dirtyable_memory(x);
  305. return x + 1; /* Ensure that we never return 0 */
  306. }
  307. static unsigned long dirty_freerun_ceiling(unsigned long thresh,
  308. unsigned long bg_thresh)
  309. {
  310. return (thresh + bg_thresh) / 2;
  311. }
  312. static unsigned long hard_dirty_limit(unsigned long thresh)
  313. {
  314. return max(thresh, global_dirty_limit);
  315. }
  316. /*
  317. * global_dirty_limits - background-writeback and dirty-throttling thresholds
  318. *
  319. * Calculate the dirty thresholds based on sysctl parameters
  320. * - vm.dirty_background_ratio or vm.dirty_background_bytes
  321. * - vm.dirty_ratio or vm.dirty_bytes
  322. * The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
  323. * real-time tasks.
  324. */
  325. void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
  326. {
  327. unsigned long background;
  328. unsigned long dirty;
  329. unsigned long uninitialized_var(available_memory);
  330. struct task_struct *tsk;
  331. if (!vm_dirty_bytes || !dirty_background_bytes)
  332. available_memory = determine_dirtyable_memory();
  333. if (vm_dirty_bytes)
  334. dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
  335. else
  336. dirty = (vm_dirty_ratio * available_memory) / 100;
  337. if (dirty_background_bytes)
  338. background = DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE);
  339. else
  340. background = (dirty_background_ratio * available_memory) / 100;
  341. if (background >= dirty)
  342. background = dirty / 2;
  343. tsk = current;
  344. if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
  345. background += background / 4;
  346. dirty += dirty / 4;
  347. }
  348. *pbackground = background;
  349. *pdirty = dirty;
  350. trace_global_dirty_state(background, dirty);
  351. }
  352. /**
  353. * bdi_dirty_limit - @bdi's share of dirty throttling threshold
  354. * @bdi: the backing_dev_info to query
  355. * @dirty: global dirty limit in pages
  356. *
  357. * Returns @bdi's dirty limit in pages. The term "dirty" in the context of
  358. * dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
  359. *
  360. * Note that balance_dirty_pages() will only seriously take it as a hard limit
  361. * when sleeping max_pause per page is not enough to keep the dirty pages under
  362. * control. For example, when the device is completely stalled due to some error
  363. * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
  364. * In the other normal situations, it acts more gently by throttling the tasks
  365. * more (rather than completely block them) when the bdi dirty pages go high.
  366. *
  367. * It allocates high/low dirty limits to fast/slow devices, in order to prevent
  368. * - starving fast devices
  369. * - piling up dirty pages (that will take long time to sync) on slow devices
  370. *
  371. * The bdi's share of dirty limit will be adapting to its throughput and
  372. * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
  373. */
  374. unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty)
  375. {
  376. u64 bdi_dirty;
  377. long numerator, denominator;
  378. /*
  379. * Calculate this BDI's share of the dirty ratio.
  380. */
  381. bdi_writeout_fraction(bdi, &numerator, &denominator);
  382. bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
  383. bdi_dirty *= numerator;
  384. do_div(bdi_dirty, denominator);
  385. bdi_dirty += (dirty * bdi->min_ratio) / 100;
  386. if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
  387. bdi_dirty = dirty * bdi->max_ratio / 100;
  388. return bdi_dirty;
  389. }
  390. /*
  391. * Dirty position control.
  392. *
  393. * (o) global/bdi setpoints
  394. *
  395. * We want the dirty pages be balanced around the global/bdi setpoints.
  396. * When the number of dirty pages is higher/lower than the setpoint, the
  397. * dirty position control ratio (and hence task dirty ratelimit) will be
  398. * decreased/increased to bring the dirty pages back to the setpoint.
  399. *
  400. * pos_ratio = 1 << RATELIMIT_CALC_SHIFT
  401. *
  402. * if (dirty < setpoint) scale up pos_ratio
  403. * if (dirty > setpoint) scale down pos_ratio
  404. *
  405. * if (bdi_dirty < bdi_setpoint) scale up pos_ratio
  406. * if (bdi_dirty > bdi_setpoint) scale down pos_ratio
  407. *
  408. * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
  409. *
  410. * (o) global control line
  411. *
  412. * ^ pos_ratio
  413. * |
  414. * | |<===== global dirty control scope ======>|
  415. * 2.0 .............*
  416. * | .*
  417. * | . *
  418. * | . *
  419. * | . *
  420. * | . *
  421. * | . *
  422. * 1.0 ................................*
  423. * | . . *
  424. * | . . *
  425. * | . . *
  426. * | . . *
  427. * | . . *
  428. * 0 +------------.------------------.----------------------*------------->
  429. * freerun^ setpoint^ limit^ dirty pages
  430. *
  431. * (o) bdi control line
  432. *
  433. * ^ pos_ratio
  434. * |
  435. * | *
  436. * | *
  437. * | *
  438. * | *
  439. * | * |<=========== span ============>|
  440. * 1.0 .......................*
  441. * | . *
  442. * | . *
  443. * | . *
  444. * | . *
  445. * | . *
  446. * | . *
  447. * | . *
  448. * | . *
  449. * | . *
  450. * | . *
  451. * | . *
  452. * 1/4 ...............................................* * * * * * * * * * * *
  453. * | . .
  454. * | . .
  455. * | . .
  456. * 0 +----------------------.-------------------------------.------------->
  457. * bdi_setpoint^ x_intercept^
  458. *
  459. * The bdi control line won't drop below pos_ratio=1/4, so that bdi_dirty can
  460. * be smoothly throttled down to normal if it starts high in situations like
  461. * - start writing to a slow SD card and a fast disk at the same time. The SD
  462. * card's bdi_dirty may rush to many times higher than bdi_setpoint.
  463. * - the bdi dirty thresh drops quickly due to change of JBOD workload
  464. */
  465. static unsigned long bdi_position_ratio(struct backing_dev_info *bdi,
  466. unsigned long thresh,
  467. unsigned long bg_thresh,
  468. unsigned long dirty,
  469. unsigned long bdi_thresh,
  470. unsigned long bdi_dirty)
  471. {
  472. unsigned long write_bw = bdi->avg_write_bandwidth;
  473. unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
  474. unsigned long limit = hard_dirty_limit(thresh);
  475. unsigned long x_intercept;
  476. unsigned long setpoint; /* dirty pages' target balance point */
  477. unsigned long bdi_setpoint;
  478. unsigned long span;
  479. long long pos_ratio; /* for scaling up/down the rate limit */
  480. long x;
  481. if (unlikely(dirty >= limit))
  482. return 0;
  483. /*
  484. * global setpoint
  485. *
  486. * setpoint - dirty 3
  487. * f(dirty) := 1.0 + (----------------)
  488. * limit - setpoint
  489. *
  490. * it's a 3rd order polynomial that subjects to
  491. *
  492. * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast
  493. * (2) f(setpoint) = 1.0 => the balance point
  494. * (3) f(limit) = 0 => the hard limit
  495. * (4) df/dx <= 0 => negative feedback control
  496. * (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
  497. * => fast response on large errors; small oscillation near setpoint
  498. */
  499. setpoint = (freerun + limit) / 2;
  500. x = div_s64((setpoint - dirty) << RATELIMIT_CALC_SHIFT,
  501. limit - setpoint + 1);
  502. pos_ratio = x;
  503. pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
  504. pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
  505. pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
  506. /*
  507. * We have computed basic pos_ratio above based on global situation. If
  508. * the bdi is over/under its share of dirty pages, we want to scale
  509. * pos_ratio further down/up. That is done by the following mechanism.
  510. */
  511. /*
  512. * bdi setpoint
  513. *
  514. * f(bdi_dirty) := 1.0 + k * (bdi_dirty - bdi_setpoint)
  515. *
  516. * x_intercept - bdi_dirty
  517. * := --------------------------
  518. * x_intercept - bdi_setpoint
  519. *
  520. * The main bdi control line is a linear function that subjects to
  521. *
  522. * (1) f(bdi_setpoint) = 1.0
  523. * (2) k = - 1 / (8 * write_bw) (in single bdi case)
  524. * or equally: x_intercept = bdi_setpoint + 8 * write_bw
  525. *
  526. * For single bdi case, the dirty pages are observed to fluctuate
  527. * regularly within range
  528. * [bdi_setpoint - write_bw/2, bdi_setpoint + write_bw/2]
  529. * for various filesystems, where (2) can yield in a reasonable 12.5%
  530. * fluctuation range for pos_ratio.
  531. *
  532. * For JBOD case, bdi_thresh (not bdi_dirty!) could fluctuate up to its
  533. * own size, so move the slope over accordingly and choose a slope that
  534. * yields 100% pos_ratio fluctuation on suddenly doubled bdi_thresh.
  535. */
  536. if (unlikely(bdi_thresh > thresh))
  537. bdi_thresh = thresh;
  538. /*
  539. * It's very possible that bdi_thresh is close to 0 not because the
  540. * device is slow, but that it has remained inactive for long time.
  541. * Honour such devices a reasonable good (hopefully IO efficient)
  542. * threshold, so that the occasional writes won't be blocked and active
  543. * writes can rampup the threshold quickly.
  544. */
  545. bdi_thresh = max(bdi_thresh, (limit - dirty) / 8);
  546. /*
  547. * scale global setpoint to bdi's:
  548. * bdi_setpoint = setpoint * bdi_thresh / thresh
  549. */
  550. x = div_u64((u64)bdi_thresh << 16, thresh + 1);
  551. bdi_setpoint = setpoint * (u64)x >> 16;
  552. /*
  553. * Use span=(8*write_bw) in single bdi case as indicated by
  554. * (thresh - bdi_thresh ~= 0) and transit to bdi_thresh in JBOD case.
  555. *
  556. * bdi_thresh thresh - bdi_thresh
  557. * span = ---------- * (8 * write_bw) + ------------------- * bdi_thresh
  558. * thresh thresh
  559. */
  560. span = (thresh - bdi_thresh + 8 * write_bw) * (u64)x >> 16;
  561. x_intercept = bdi_setpoint + span;
  562. if (bdi_dirty < x_intercept - span / 4) {
  563. pos_ratio = div_u64(pos_ratio * (x_intercept - bdi_dirty),
  564. x_intercept - bdi_setpoint + 1);
  565. } else
  566. pos_ratio /= 4;
  567. /*
  568. * bdi reserve area, safeguard against dirty pool underrun and disk idle
  569. * It may push the desired control point of global dirty pages higher
  570. * than setpoint.
  571. */
  572. x_intercept = bdi_thresh / 2;
  573. if (bdi_dirty < x_intercept) {
  574. if (bdi_dirty > x_intercept / 8)
  575. pos_ratio = div_u64(pos_ratio * x_intercept, bdi_dirty);
  576. else
  577. pos_ratio *= 8;
  578. }
  579. return pos_ratio;
  580. }
  581. static void bdi_update_write_bandwidth(struct backing_dev_info *bdi,
  582. unsigned long elapsed,
  583. unsigned long written)
  584. {
  585. const unsigned long period = roundup_pow_of_two(3 * HZ);
  586. unsigned long avg = bdi->avg_write_bandwidth;
  587. unsigned long old = bdi->write_bandwidth;
  588. u64 bw;
  589. /*
  590. * bw = written * HZ / elapsed
  591. *
  592. * bw * elapsed + write_bandwidth * (period - elapsed)
  593. * write_bandwidth = ---------------------------------------------------
  594. * period
  595. */
  596. bw = written - bdi->written_stamp;
  597. bw *= HZ;
  598. if (unlikely(elapsed > period)) {
  599. do_div(bw, elapsed);
  600. avg = bw;
  601. goto out;
  602. }
  603. bw += (u64)bdi->write_bandwidth * (period - elapsed);
  604. bw >>= ilog2(period);
  605. /*
  606. * one more level of smoothing, for filtering out sudden spikes
  607. */
  608. if (avg > old && old >= (unsigned long)bw)
  609. avg -= (avg - old) >> 3;
  610. if (avg < old && old <= (unsigned long)bw)
  611. avg += (old - avg) >> 3;
  612. out:
  613. bdi->write_bandwidth = bw;
  614. bdi->avg_write_bandwidth = avg;
  615. }
  616. /*
  617. * The global dirtyable memory and dirty threshold could be suddenly knocked
  618. * down by a large amount (eg. on the startup of KVM in a swapless system).
  619. * This may throw the system into deep dirty exceeded state and throttle
  620. * heavy/light dirtiers alike. To retain good responsiveness, maintain
  621. * global_dirty_limit for tracking slowly down to the knocked down dirty
  622. * threshold.
  623. */
  624. static void update_dirty_limit(unsigned long thresh, unsigned long dirty)
  625. {
  626. unsigned long limit = global_dirty_limit;
  627. /*
  628. * Follow up in one step.
  629. */
  630. if (limit < thresh) {
  631. limit = thresh;
  632. goto update;
  633. }
  634. /*
  635. * Follow down slowly. Use the higher one as the target, because thresh
  636. * may drop below dirty. This is exactly the reason to introduce
  637. * global_dirty_limit which is guaranteed to lie above the dirty pages.
  638. */
  639. thresh = max(thresh, dirty);
  640. if (limit > thresh) {
  641. limit -= (limit - thresh) >> 5;
  642. goto update;
  643. }
  644. return;
  645. update:
  646. global_dirty_limit = limit;
  647. }
  648. static void global_update_bandwidth(unsigned long thresh,
  649. unsigned long dirty,
  650. unsigned long now)
  651. {
  652. static DEFINE_SPINLOCK(dirty_lock);
  653. static unsigned long update_time;
  654. /*
  655. * check locklessly first to optimize away locking for the most time
  656. */
  657. if (time_before(now, update_time + BANDWIDTH_INTERVAL))
  658. return;
  659. spin_lock(&dirty_lock);
  660. if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) {
  661. update_dirty_limit(thresh, dirty);
  662. update_time = now;
  663. }
  664. spin_unlock(&dirty_lock);
  665. }
  666. /*
  667. * Maintain bdi->dirty_ratelimit, the base dirty throttle rate.
  668. *
  669. * Normal bdi tasks will be curbed at or below it in long term.
  670. * Obviously it should be around (write_bw / N) when there are N dd tasks.
  671. */
  672. static void bdi_update_dirty_ratelimit(struct backing_dev_info *bdi,
  673. unsigned long thresh,
  674. unsigned long bg_thresh,
  675. unsigned long dirty,
  676. unsigned long bdi_thresh,
  677. unsigned long bdi_dirty,
  678. unsigned long dirtied,
  679. unsigned long elapsed)
  680. {
  681. unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
  682. unsigned long limit = hard_dirty_limit(thresh);
  683. unsigned long setpoint = (freerun + limit) / 2;
  684. unsigned long write_bw = bdi->avg_write_bandwidth;
  685. unsigned long dirty_ratelimit = bdi->dirty_ratelimit;
  686. unsigned long dirty_rate;
  687. unsigned long task_ratelimit;
  688. unsigned long balanced_dirty_ratelimit;
  689. unsigned long pos_ratio;
  690. unsigned long step;
  691. unsigned long x;
  692. /*
  693. * The dirty rate will match the writeout rate in long term, except
  694. * when dirty pages are truncated by userspace or re-dirtied by FS.
  695. */
  696. dirty_rate = (dirtied - bdi->dirtied_stamp) * HZ / elapsed;
  697. pos_ratio = bdi_position_ratio(bdi, thresh, bg_thresh, dirty,
  698. bdi_thresh, bdi_dirty);
  699. /*
  700. * task_ratelimit reflects each dd's dirty rate for the past 200ms.
  701. */
  702. task_ratelimit = (u64)dirty_ratelimit *
  703. pos_ratio >> RATELIMIT_CALC_SHIFT;
  704. task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
  705. /*
  706. * A linear estimation of the "balanced" throttle rate. The theory is,
  707. * if there are N dd tasks, each throttled at task_ratelimit, the bdi's
  708. * dirty_rate will be measured to be (N * task_ratelimit). So the below
  709. * formula will yield the balanced rate limit (write_bw / N).
  710. *
  711. * Note that the expanded form is not a pure rate feedback:
  712. * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
  713. * but also takes pos_ratio into account:
  714. * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
  715. *
  716. * (1) is not realistic because pos_ratio also takes part in balancing
  717. * the dirty rate. Consider the state
  718. * pos_ratio = 0.5 (3)
  719. * rate = 2 * (write_bw / N) (4)
  720. * If (1) is used, it will stuck in that state! Because each dd will
  721. * be throttled at
  722. * task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
  723. * yielding
  724. * dirty_rate = N * task_ratelimit = write_bw (6)
  725. * put (6) into (1) we get
  726. * rate_(i+1) = rate_(i) (7)
  727. *
  728. * So we end up using (2) to always keep
  729. * rate_(i+1) ~= (write_bw / N) (8)
  730. * regardless of the value of pos_ratio. As long as (8) is satisfied,
  731. * pos_ratio is able to drive itself to 1.0, which is not only where
  732. * the dirty count meet the setpoint, but also where the slope of
  733. * pos_ratio is most flat and hence task_ratelimit is least fluctuated.
  734. */
  735. balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
  736. dirty_rate | 1);
  737. /*
  738. * We could safely do this and return immediately:
  739. *
  740. * bdi->dirty_ratelimit = balanced_dirty_ratelimit;
  741. *
  742. * However to get a more stable dirty_ratelimit, the below elaborated
  743. * code makes use of task_ratelimit to filter out sigular points and
  744. * limit the step size.
  745. *
  746. * The below code essentially only uses the relative value of
  747. *
  748. * task_ratelimit - dirty_ratelimit
  749. * = (pos_ratio - 1) * dirty_ratelimit
  750. *
  751. * which reflects the direction and size of dirty position error.
  752. */
  753. /*
  754. * dirty_ratelimit will follow balanced_dirty_ratelimit iff
  755. * task_ratelimit is on the same side of dirty_ratelimit, too.
  756. * For example, when
  757. * - dirty_ratelimit > balanced_dirty_ratelimit
  758. * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
  759. * lowering dirty_ratelimit will help meet both the position and rate
  760. * control targets. Otherwise, don't update dirty_ratelimit if it will
  761. * only help meet the rate target. After all, what the users ultimately
  762. * feel and care are stable dirty rate and small position error.
  763. *
  764. * |task_ratelimit - dirty_ratelimit| is used to limit the step size
  765. * and filter out the sigular points of balanced_dirty_ratelimit. Which
  766. * keeps jumping around randomly and can even leap far away at times
  767. * due to the small 200ms estimation period of dirty_rate (we want to
  768. * keep that period small to reduce time lags).
  769. */
  770. step = 0;
  771. if (dirty < setpoint) {
  772. x = min(bdi->balanced_dirty_ratelimit,
  773. min(balanced_dirty_ratelimit, task_ratelimit));
  774. if (dirty_ratelimit < x)
  775. step = x - dirty_ratelimit;
  776. } else {
  777. x = max(bdi->balanced_dirty_ratelimit,
  778. max(balanced_dirty_ratelimit, task_ratelimit));
  779. if (dirty_ratelimit > x)
  780. step = dirty_ratelimit - x;
  781. }
  782. /*
  783. * Don't pursue 100% rate matching. It's impossible since the balanced
  784. * rate itself is constantly fluctuating. So decrease the track speed
  785. * when it gets close to the target. Helps eliminate pointless tremors.
  786. */
  787. step >>= dirty_ratelimit / (2 * step + 1);
  788. /*
  789. * Limit the tracking speed to avoid overshooting.
  790. */
  791. step = (step + 7) / 8;
  792. if (dirty_ratelimit < balanced_dirty_ratelimit)
  793. dirty_ratelimit += step;
  794. else
  795. dirty_ratelimit -= step;
  796. bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL);
  797. bdi->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
  798. trace_bdi_dirty_ratelimit(bdi, dirty_rate, task_ratelimit);
  799. }
  800. void __bdi_update_bandwidth(struct backing_dev_info *bdi,
  801. unsigned long thresh,
  802. unsigned long bg_thresh,
  803. unsigned long dirty,
  804. unsigned long bdi_thresh,
  805. unsigned long bdi_dirty,
  806. unsigned long start_time)
  807. {
  808. unsigned long now = jiffies;
  809. unsigned long elapsed = now - bdi->bw_time_stamp;
  810. unsigned long dirtied;
  811. unsigned long written;
  812. /*
  813. * rate-limit, only update once every 200ms.
  814. */
  815. if (elapsed < BANDWIDTH_INTERVAL)
  816. return;
  817. dirtied = percpu_counter_read(&bdi->bdi_stat[BDI_DIRTIED]);
  818. written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]);
  819. /*
  820. * Skip quiet periods when disk bandwidth is under-utilized.
  821. * (at least 1s idle time between two flusher runs)
  822. */
  823. if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time))
  824. goto snapshot;
  825. if (thresh) {
  826. global_update_bandwidth(thresh, dirty, now);
  827. bdi_update_dirty_ratelimit(bdi, thresh, bg_thresh, dirty,
  828. bdi_thresh, bdi_dirty,
  829. dirtied, elapsed);
  830. }
  831. bdi_update_write_bandwidth(bdi, elapsed, written);
  832. snapshot:
  833. bdi->dirtied_stamp = dirtied;
  834. bdi->written_stamp = written;
  835. bdi->bw_time_stamp = now;
  836. }
  837. static void bdi_update_bandwidth(struct backing_dev_info *bdi,
  838. unsigned long thresh,
  839. unsigned long bg_thresh,
  840. unsigned long dirty,
  841. unsigned long bdi_thresh,
  842. unsigned long bdi_dirty,
  843. unsigned long start_time)
  844. {
  845. if (time_is_after_eq_jiffies(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
  846. return;
  847. spin_lock(&bdi->wb.list_lock);
  848. __bdi_update_bandwidth(bdi, thresh, bg_thresh, dirty,
  849. bdi_thresh, bdi_dirty, start_time);
  850. spin_unlock(&bdi->wb.list_lock);
  851. }
  852. /*
  853. * After a task dirtied this many pages, balance_dirty_pages_ratelimited_nr()
  854. * will look to see if it needs to start dirty throttling.
  855. *
  856. * If dirty_poll_interval is too low, big NUMA machines will call the expensive
  857. * global_page_state() too often. So scale it near-sqrt to the safety margin
  858. * (the number of pages we may dirty without exceeding the dirty limits).
  859. */
  860. static unsigned long dirty_poll_interval(unsigned long dirty,
  861. unsigned long thresh)
  862. {
  863. if (thresh > dirty)
  864. return 1UL << (ilog2(thresh - dirty) >> 1);
  865. return 1;
  866. }
  867. static long bdi_max_pause(struct backing_dev_info *bdi,
  868. unsigned long bdi_dirty)
  869. {
  870. long bw = bdi->avg_write_bandwidth;
  871. long t;
  872. /*
  873. * Limit pause time for small memory systems. If sleeping for too long
  874. * time, a small pool of dirty/writeback pages may go empty and disk go
  875. * idle.
  876. *
  877. * 8 serves as the safety ratio.
  878. */
  879. t = bdi_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
  880. t++;
  881. return min_t(long, t, MAX_PAUSE);
  882. }
  883. static long bdi_min_pause(struct backing_dev_info *bdi,
  884. long max_pause,
  885. unsigned long task_ratelimit,
  886. unsigned long dirty_ratelimit,
  887. int *nr_dirtied_pause)
  888. {
  889. long hi = ilog2(bdi->avg_write_bandwidth);
  890. long lo = ilog2(bdi->dirty_ratelimit);
  891. long t; /* target pause */
  892. long pause; /* estimated next pause */
  893. int pages; /* target nr_dirtied_pause */
  894. /* target for 10ms pause on 1-dd case */
  895. t = max(1, HZ / 100);
  896. /*
  897. * Scale up pause time for concurrent dirtiers in order to reduce CPU
  898. * overheads.
  899. *
  900. * (N * 10ms) on 2^N concurrent tasks.
  901. */
  902. if (hi > lo)
  903. t += (hi - lo) * (10 * HZ) / 1024;
  904. /*
  905. * This is a bit convoluted. We try to base the next nr_dirtied_pause
  906. * on the much more stable dirty_ratelimit. However the next pause time
  907. * will be computed based on task_ratelimit and the two rate limits may
  908. * depart considerably at some time. Especially if task_ratelimit goes
  909. * below dirty_ratelimit/2 and the target pause is max_pause, the next
  910. * pause time will be max_pause*2 _trimmed down_ to max_pause. As a
  911. * result task_ratelimit won't be executed faithfully, which could
  912. * eventually bring down dirty_ratelimit.
  913. *
  914. * We apply two rules to fix it up:
  915. * 1) try to estimate the next pause time and if necessary, use a lower
  916. * nr_dirtied_pause so as not to exceed max_pause. When this happens,
  917. * nr_dirtied_pause will be "dancing" with task_ratelimit.
  918. * 2) limit the target pause time to max_pause/2, so that the normal
  919. * small fluctuations of task_ratelimit won't trigger rule (1) and
  920. * nr_dirtied_pause will remain as stable as dirty_ratelimit.
  921. */
  922. t = min(t, 1 + max_pause / 2);
  923. pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
  924. /*
  925. * Tiny nr_dirtied_pause is found to hurt I/O performance in the test
  926. * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}.
  927. * When the 16 consecutive reads are often interrupted by some dirty
  928. * throttling pause during the async writes, cfq will go into idles
  929. * (deadline is fine). So push nr_dirtied_pause as high as possible
  930. * until reaches DIRTY_POLL_THRESH=32 pages.
  931. */
  932. if (pages < DIRTY_POLL_THRESH) {
  933. t = max_pause;
  934. pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
  935. if (pages > DIRTY_POLL_THRESH) {
  936. pages = DIRTY_POLL_THRESH;
  937. t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
  938. }
  939. }
  940. pause = HZ * pages / (task_ratelimit + 1);
  941. if (pause > max_pause) {
  942. t = max_pause;
  943. pages = task_ratelimit * t / roundup_pow_of_two(HZ);
  944. }
  945. *nr_dirtied_pause = pages;
  946. /*
  947. * The minimal pause time will normally be half the target pause time.
  948. */
  949. return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
  950. }
  951. /*
  952. * balance_dirty_pages() must be called by processes which are generating dirty
  953. * data. It looks at the number of dirty pages in the machine and will force
  954. * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
  955. * If we're over `background_thresh' then the writeback threads are woken to
  956. * perform some writeout.
  957. */
  958. static void balance_dirty_pages(struct address_space *mapping,
  959. unsigned long pages_dirtied)
  960. {
  961. unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */
  962. unsigned long bdi_reclaimable;
  963. unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */
  964. unsigned long bdi_dirty;
  965. unsigned long freerun;
  966. unsigned long background_thresh;
  967. unsigned long dirty_thresh;
  968. unsigned long bdi_thresh;
  969. long period;
  970. long pause;
  971. long max_pause;
  972. long min_pause;
  973. int nr_dirtied_pause;
  974. bool dirty_exceeded = false;
  975. unsigned long task_ratelimit;
  976. unsigned long dirty_ratelimit;
  977. unsigned long pos_ratio;
  978. struct backing_dev_info *bdi = mapping->backing_dev_info;
  979. unsigned long start_time = jiffies;
  980. for (;;) {
  981. unsigned long now = jiffies;
  982. /*
  983. * Unstable writes are a feature of certain networked
  984. * filesystems (i.e. NFS) in which data may have been
  985. * written to the server's write cache, but has not yet
  986. * been flushed to permanent storage.
  987. */
  988. nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
  989. global_page_state(NR_UNSTABLE_NFS);
  990. nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK);
  991. global_dirty_limits(&background_thresh, &dirty_thresh);
  992. /*
  993. * Throttle it only when the background writeback cannot
  994. * catch-up. This avoids (excessively) small writeouts
  995. * when the bdi limits are ramping up.
  996. */
  997. freerun = dirty_freerun_ceiling(dirty_thresh,
  998. background_thresh);
  999. if (nr_dirty <= freerun) {
  1000. current->dirty_paused_when = now;
  1001. current->nr_dirtied = 0;
  1002. current->nr_dirtied_pause =
  1003. dirty_poll_interval(nr_dirty, dirty_thresh);
  1004. break;
  1005. }
  1006. if (unlikely(!writeback_in_progress(bdi)))
  1007. bdi_start_background_writeback(bdi);
  1008. /*
  1009. * bdi_thresh is not treated as some limiting factor as
  1010. * dirty_thresh, due to reasons
  1011. * - in JBOD setup, bdi_thresh can fluctuate a lot
  1012. * - in a system with HDD and USB key, the USB key may somehow
  1013. * go into state (bdi_dirty >> bdi_thresh) either because
  1014. * bdi_dirty starts high, or because bdi_thresh drops low.
  1015. * In this case we don't want to hard throttle the USB key
  1016. * dirtiers for 100 seconds until bdi_dirty drops under
  1017. * bdi_thresh. Instead the auxiliary bdi control line in
  1018. * bdi_position_ratio() will let the dirtier task progress
  1019. * at some rate <= (write_bw / 2) for bringing down bdi_dirty.
  1020. */
  1021. bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh);
  1022. /*
  1023. * In order to avoid the stacked BDI deadlock we need
  1024. * to ensure we accurately count the 'dirty' pages when
  1025. * the threshold is low.
  1026. *
  1027. * Otherwise it would be possible to get thresh+n pages
  1028. * reported dirty, even though there are thresh-m pages
  1029. * actually dirty; with m+n sitting in the percpu
  1030. * deltas.
  1031. */
  1032. if (bdi_thresh < 2 * bdi_stat_error(bdi)) {
  1033. bdi_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
  1034. bdi_dirty = bdi_reclaimable +
  1035. bdi_stat_sum(bdi, BDI_WRITEBACK);
  1036. } else {
  1037. bdi_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
  1038. bdi_dirty = bdi_reclaimable +
  1039. bdi_stat(bdi, BDI_WRITEBACK);
  1040. }
  1041. dirty_exceeded = (bdi_dirty > bdi_thresh) ||
  1042. (nr_dirty > dirty_thresh);
  1043. if (dirty_exceeded && !bdi->dirty_exceeded)
  1044. bdi->dirty_exceeded = 1;
  1045. bdi_update_bandwidth(bdi, dirty_thresh, background_thresh,
  1046. nr_dirty, bdi_thresh, bdi_dirty,
  1047. start_time);
  1048. dirty_ratelimit = bdi->dirty_ratelimit;
  1049. pos_ratio = bdi_position_ratio(bdi, dirty_thresh,
  1050. background_thresh, nr_dirty,
  1051. bdi_thresh, bdi_dirty);
  1052. task_ratelimit = ((u64)dirty_ratelimit * pos_ratio) >>
  1053. RATELIMIT_CALC_SHIFT;
  1054. max_pause = bdi_max_pause(bdi, bdi_dirty);
  1055. min_pause = bdi_min_pause(bdi, max_pause,
  1056. task_ratelimit, dirty_ratelimit,
  1057. &nr_dirtied_pause);
  1058. if (unlikely(task_ratelimit == 0)) {
  1059. period = max_pause;
  1060. pause = max_pause;
  1061. goto pause;
  1062. }
  1063. period = HZ * pages_dirtied / task_ratelimit;
  1064. pause = period;
  1065. if (current->dirty_paused_when)
  1066. pause -= now - current->dirty_paused_when;
  1067. /*
  1068. * For less than 1s think time (ext3/4 may block the dirtier
  1069. * for up to 800ms from time to time on 1-HDD; so does xfs,
  1070. * however at much less frequency), try to compensate it in
  1071. * future periods by updating the virtual time; otherwise just
  1072. * do a reset, as it may be a light dirtier.
  1073. */
  1074. if (pause < min_pause) {
  1075. trace_balance_dirty_pages(bdi,
  1076. dirty_thresh,
  1077. background_thresh,
  1078. nr_dirty,
  1079. bdi_thresh,
  1080. bdi_dirty,
  1081. dirty_ratelimit,
  1082. task_ratelimit,
  1083. pages_dirtied,
  1084. period,
  1085. min(pause, 0L),
  1086. start_time);
  1087. if (pause < -HZ) {
  1088. current->dirty_paused_when = now;
  1089. current->nr_dirtied = 0;
  1090. } else if (period) {
  1091. current->dirty_paused_when += period;
  1092. current->nr_dirtied = 0;
  1093. } else if (current->nr_dirtied_pause <= pages_dirtied)
  1094. current->nr_dirtied_pause += pages_dirtied;
  1095. break;
  1096. }
  1097. if (unlikely(pause > max_pause)) {
  1098. /* for occasional dropped task_ratelimit */
  1099. now += min(pause - max_pause, max_pause);
  1100. pause = max_pause;
  1101. }
  1102. pause:
  1103. trace_balance_dirty_pages(bdi,
  1104. dirty_thresh,
  1105. background_thresh,
  1106. nr_dirty,
  1107. bdi_thresh,
  1108. bdi_dirty,
  1109. dirty_ratelimit,
  1110. task_ratelimit,
  1111. pages_dirtied,
  1112. period,
  1113. pause,
  1114. start_time);
  1115. __set_current_state(TASK_KILLABLE);
  1116. io_schedule_timeout(pause);
  1117. current->dirty_paused_when = now + pause;
  1118. current->nr_dirtied = 0;
  1119. current->nr_dirtied_pause = nr_dirtied_pause;
  1120. /*
  1121. * This is typically equal to (nr_dirty < dirty_thresh) and can
  1122. * also keep "1000+ dd on a slow USB stick" under control.
  1123. */
  1124. if (task_ratelimit)
  1125. break;
  1126. /*
  1127. * In the case of an unresponding NFS server and the NFS dirty
  1128. * pages exceeds dirty_thresh, give the other good bdi's a pipe
  1129. * to go through, so that tasks on them still remain responsive.
  1130. *
  1131. * In theory 1 page is enough to keep the comsumer-producer
  1132. * pipe going: the flusher cleans 1 page => the task dirties 1
  1133. * more page. However bdi_dirty has accounting errors. So use
  1134. * the larger and more IO friendly bdi_stat_error.
  1135. */
  1136. if (bdi_dirty <= bdi_stat_error(bdi))
  1137. break;
  1138. if (fatal_signal_pending(current))
  1139. break;
  1140. }
  1141. if (!dirty_exceeded && bdi->dirty_exceeded)
  1142. bdi->dirty_exceeded = 0;
  1143. if (writeback_in_progress(bdi))
  1144. return;
  1145. /*
  1146. * In laptop mode, we wait until hitting the higher threshold before
  1147. * starting background writeout, and then write out all the way down
  1148. * to the lower threshold. So slow writers cause minimal disk activity.
  1149. *
  1150. * In normal mode, we start background writeout at the lower
  1151. * background_thresh, to keep the amount of dirty memory low.
  1152. */
  1153. if (laptop_mode)
  1154. return;
  1155. if (nr_reclaimable > background_thresh)
  1156. bdi_start_background_writeback(bdi);
  1157. }
  1158. void set_page_dirty_balance(struct page *page, int page_mkwrite)
  1159. {
  1160. if (set_page_dirty(page) || page_mkwrite) {
  1161. struct address_space *mapping = page_mapping(page);
  1162. if (mapping)
  1163. balance_dirty_pages_ratelimited(mapping);
  1164. }
  1165. }
  1166. static DEFINE_PER_CPU(int, bdp_ratelimits);
  1167. /*
  1168. * Normal tasks are throttled by
  1169. * loop {
  1170. * dirty tsk->nr_dirtied_pause pages;
  1171. * take a snap in balance_dirty_pages();
  1172. * }
  1173. * However there is a worst case. If every task exit immediately when dirtied
  1174. * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
  1175. * called to throttle the page dirties. The solution is to save the not yet
  1176. * throttled page dirties in dirty_throttle_leaks on task exit and charge them
  1177. * randomly into the running tasks. This works well for the above worst case,
  1178. * as the new task will pick up and accumulate the old task's leaked dirty
  1179. * count and eventually get throttled.
  1180. */
  1181. DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
  1182. /**
  1183. * balance_dirty_pages_ratelimited_nr - balance dirty memory state
  1184. * @mapping: address_space which was dirtied
  1185. * @nr_pages_dirtied: number of pages which the caller has just dirtied
  1186. *
  1187. * Processes which are dirtying memory should call in here once for each page
  1188. * which was newly dirtied. The function will periodically check the system's
  1189. * dirty state and will initiate writeback if needed.
  1190. *
  1191. * On really big machines, get_writeback_state is expensive, so try to avoid
  1192. * calling it too often (ratelimiting). But once we're over the dirty memory
  1193. * limit we decrease the ratelimiting by a lot, to prevent individual processes
  1194. * from overshooting the limit by (ratelimit_pages) each.
  1195. */
  1196. void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
  1197. unsigned long nr_pages_dirtied)
  1198. {
  1199. struct backing_dev_info *bdi = mapping->backing_dev_info;
  1200. int ratelimit;
  1201. int *p;
  1202. if (!bdi_cap_account_dirty(bdi))
  1203. return;
  1204. ratelimit = current->nr_dirtied_pause;
  1205. if (bdi->dirty_exceeded)
  1206. ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
  1207. preempt_disable();
  1208. /*
  1209. * This prevents one CPU to accumulate too many dirtied pages without
  1210. * calling into balance_dirty_pages(), which can happen when there are
  1211. * 1000+ tasks, all of them start dirtying pages at exactly the same
  1212. * time, hence all honoured too large initial task->nr_dirtied_pause.
  1213. */
  1214. p = &__get_cpu_var(bdp_ratelimits);
  1215. if (unlikely(current->nr_dirtied >= ratelimit))
  1216. *p = 0;
  1217. else if (unlikely(*p >= ratelimit_pages)) {
  1218. *p = 0;
  1219. ratelimit = 0;
  1220. }
  1221. /*
  1222. * Pick up the dirtied pages by the exited tasks. This avoids lots of
  1223. * short-lived tasks (eg. gcc invocations in a kernel build) escaping
  1224. * the dirty throttling and livelock other long-run dirtiers.
  1225. */
  1226. p = &__get_cpu_var(dirty_throttle_leaks);
  1227. if (*p > 0 && current->nr_dirtied < ratelimit) {
  1228. nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
  1229. *p -= nr_pages_dirtied;
  1230. current->nr_dirtied += nr_pages_dirtied;
  1231. }
  1232. preempt_enable();
  1233. if (unlikely(current->nr_dirtied >= ratelimit))
  1234. balance_dirty_pages(mapping, current->nr_dirtied);
  1235. }
  1236. EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
  1237. void throttle_vm_writeout(gfp_t gfp_mask)
  1238. {
  1239. unsigned long background_thresh;
  1240. unsigned long dirty_thresh;
  1241. for ( ; ; ) {
  1242. global_dirty_limits(&background_thresh, &dirty_thresh);
  1243. /*
  1244. * Boost the allowable dirty threshold a bit for page
  1245. * allocators so they don't get DoS'ed by heavy writers
  1246. */
  1247. dirty_thresh += dirty_thresh / 10; /* wheeee... */
  1248. if (global_page_state(NR_UNSTABLE_NFS) +
  1249. global_page_state(NR_WRITEBACK) <= dirty_thresh)
  1250. break;
  1251. congestion_wait(BLK_RW_ASYNC, HZ/10);
  1252. /*
  1253. * The caller might hold locks which can prevent IO completion
  1254. * or progress in the filesystem. So we cannot just sit here
  1255. * waiting for IO to complete.
  1256. */
  1257. if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
  1258. break;
  1259. }
  1260. }
  1261. /*
  1262. * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
  1263. */
  1264. int dirty_writeback_centisecs_handler(ctl_table *table, int write,
  1265. void __user *buffer, size_t *length, loff_t *ppos)
  1266. {
  1267. proc_dointvec(table, write, buffer, length, ppos);
  1268. bdi_arm_supers_timer();
  1269. return 0;
  1270. }
  1271. #ifdef CONFIG_BLOCK
  1272. void laptop_mode_timer_fn(unsigned long data)
  1273. {
  1274. struct request_queue *q = (struct request_queue *)data;
  1275. int nr_pages = global_page_state(NR_FILE_DIRTY) +
  1276. global_page_state(NR_UNSTABLE_NFS);
  1277. /*
  1278. * We want to write everything out, not just down to the dirty
  1279. * threshold
  1280. */
  1281. if (bdi_has_dirty_io(&q->backing_dev_info))
  1282. bdi_start_writeback(&q->backing_dev_info, nr_pages,
  1283. WB_REASON_LAPTOP_TIMER);
  1284. }
  1285. /*
  1286. * We've spun up the disk and we're in laptop mode: schedule writeback
  1287. * of all dirty data a few seconds from now. If the flush is already scheduled
  1288. * then push it back - the user is still using the disk.
  1289. */
  1290. void laptop_io_completion(struct backing_dev_info *info)
  1291. {
  1292. mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
  1293. }
  1294. /*
  1295. * We're in laptop mode and we've just synced. The sync's writes will have
  1296. * caused another writeback to be scheduled by laptop_io_completion.
  1297. * Nothing needs to be written back anymore, so we unschedule the writeback.
  1298. */
  1299. void laptop_sync_completion(void)
  1300. {
  1301. struct backing_dev_info *bdi;
  1302. rcu_read_lock();
  1303. list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
  1304. del_timer(&bdi->laptop_mode_wb_timer);
  1305. rcu_read_unlock();
  1306. }
  1307. #endif
  1308. /*
  1309. * If ratelimit_pages is too high then we can get into dirty-data overload
  1310. * if a large number of processes all perform writes at the same time.
  1311. * If it is too low then SMP machines will call the (expensive)
  1312. * get_writeback_state too often.
  1313. *
  1314. * Here we set ratelimit_pages to a level which ensures that when all CPUs are
  1315. * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
  1316. * thresholds.
  1317. */
  1318. void writeback_set_ratelimit(void)
  1319. {
  1320. unsigned long background_thresh;
  1321. unsigned long dirty_thresh;
  1322. global_dirty_limits(&background_thresh, &dirty_thresh);
  1323. ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
  1324. if (ratelimit_pages < 16)
  1325. ratelimit_pages = 16;
  1326. }
  1327. static int __cpuinit
  1328. ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
  1329. {
  1330. writeback_set_ratelimit();
  1331. return NOTIFY_DONE;
  1332. }
  1333. static struct notifier_block __cpuinitdata ratelimit_nb = {
  1334. .notifier_call = ratelimit_handler,
  1335. .next = NULL,
  1336. };
  1337. /*
  1338. * Called early on to tune the page writeback dirty limits.
  1339. *
  1340. * We used to scale dirty pages according to how total memory
  1341. * related to pages that could be allocated for buffers (by
  1342. * comparing nr_free_buffer_pages() to vm_total_pages.
  1343. *
  1344. * However, that was when we used "dirty_ratio" to scale with
  1345. * all memory, and we don't do that any more. "dirty_ratio"
  1346. * is now applied to total non-HIGHPAGE memory (by subtracting
  1347. * totalhigh_pages from vm_total_pages), and as such we can't
  1348. * get into the old insane situation any more where we had
  1349. * large amounts of dirty pages compared to a small amount of
  1350. * non-HIGHMEM memory.
  1351. *
  1352. * But we might still want to scale the dirty_ratio by how
  1353. * much memory the box has..
  1354. */
  1355. void __init page_writeback_init(void)
  1356. {
  1357. int shift;
  1358. writeback_set_ratelimit();
  1359. register_cpu_notifier(&ratelimit_nb);
  1360. shift = calc_period_shift();
  1361. prop_descriptor_init(&vm_completions, shift);
  1362. }
  1363. /**
  1364. * tag_pages_for_writeback - tag pages to be written by write_cache_pages
  1365. * @mapping: address space structure to write
  1366. * @start: starting page index
  1367. * @end: ending page index (inclusive)
  1368. *
  1369. * This function scans the page range from @start to @end (inclusive) and tags
  1370. * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
  1371. * that write_cache_pages (or whoever calls this function) will then use
  1372. * TOWRITE tag to identify pages eligible for writeback. This mechanism is
  1373. * used to avoid livelocking of writeback by a process steadily creating new
  1374. * dirty pages in the file (thus it is important for this function to be quick
  1375. * so that it can tag pages faster than a dirtying process can create them).
  1376. */
  1377. /*
  1378. * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
  1379. */
  1380. void tag_pages_for_writeback(struct address_space *mapping,
  1381. pgoff_t start, pgoff_t end)
  1382. {
  1383. #define WRITEBACK_TAG_BATCH 4096
  1384. unsigned long tagged;
  1385. do {
  1386. spin_lock_irq(&mapping->tree_lock);
  1387. tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree,
  1388. &start, end, WRITEBACK_TAG_BATCH,
  1389. PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE);
  1390. spin_unlock_irq(&mapping->tree_lock);
  1391. WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
  1392. cond_resched();
  1393. /* We check 'start' to handle wrapping when end == ~0UL */
  1394. } while (tagged >= WRITEBACK_TAG_BATCH && start);
  1395. }
  1396. EXPORT_SYMBOL(tag_pages_for_writeback);
  1397. /**
  1398. * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
  1399. * @mapping: address space structure to write
  1400. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1401. * @writepage: function called for each page
  1402. * @data: data passed to writepage function
  1403. *
  1404. * If a page is already under I/O, write_cache_pages() skips it, even
  1405. * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
  1406. * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
  1407. * and msync() need to guarantee that all the data which was dirty at the time
  1408. * the call was made get new I/O started against them. If wbc->sync_mode is
  1409. * WB_SYNC_ALL then we were called for data integrity and we must wait for
  1410. * existing IO to complete.
  1411. *
  1412. * To avoid livelocks (when other process dirties new pages), we first tag
  1413. * pages which should be written back with TOWRITE tag and only then start
  1414. * writing them. For data-integrity sync we have to be careful so that we do
  1415. * not miss some pages (e.g., because some other process has cleared TOWRITE
  1416. * tag we set). The rule we follow is that TOWRITE tag can be cleared only
  1417. * by the process clearing the DIRTY tag (and submitting the page for IO).
  1418. */
  1419. int write_cache_pages(struct address_space *mapping,
  1420. struct writeback_control *wbc, writepage_t writepage,
  1421. void *data)
  1422. {
  1423. int ret = 0;
  1424. int done = 0;
  1425. struct pagevec pvec;
  1426. int nr_pages;
  1427. pgoff_t uninitialized_var(writeback_index);
  1428. pgoff_t index;
  1429. pgoff_t end; /* Inclusive */
  1430. pgoff_t done_index;
  1431. int cycled;
  1432. int range_whole = 0;
  1433. int tag;
  1434. pagevec_init(&pvec, 0);
  1435. if (wbc->range_cyclic) {
  1436. writeback_index = mapping->writeback_index; /* prev offset */
  1437. index = writeback_index;
  1438. if (index == 0)
  1439. cycled = 1;
  1440. else
  1441. cycled = 0;
  1442. end = -1;
  1443. } else {
  1444. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  1445. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  1446. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  1447. range_whole = 1;
  1448. cycled = 1; /* ignore range_cyclic tests */
  1449. }
  1450. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1451. tag = PAGECACHE_TAG_TOWRITE;
  1452. else
  1453. tag = PAGECACHE_TAG_DIRTY;
  1454. retry:
  1455. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1456. tag_pages_for_writeback(mapping, index, end);
  1457. done_index = index;
  1458. while (!done && (index <= end)) {
  1459. int i;
  1460. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  1461. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  1462. if (nr_pages == 0)
  1463. break;
  1464. for (i = 0; i < nr_pages; i++) {
  1465. struct page *page = pvec.pages[i];
  1466. /*
  1467. * At this point, the page may be truncated or
  1468. * invalidated (changing page->mapping to NULL), or
  1469. * even swizzled back from swapper_space to tmpfs file
  1470. * mapping. However, page->index will not change
  1471. * because we have a reference on the page.
  1472. */
  1473. if (page->index > end) {
  1474. /*
  1475. * can't be range_cyclic (1st pass) because
  1476. * end == -1 in that case.
  1477. */
  1478. done = 1;
  1479. break;
  1480. }
  1481. done_index = page->index;
  1482. lock_page(page);
  1483. /*
  1484. * Page truncated or invalidated. We can freely skip it
  1485. * then, even for data integrity operations: the page
  1486. * has disappeared concurrently, so there could be no
  1487. * real expectation of this data interity operation
  1488. * even if there is now a new, dirty page at the same
  1489. * pagecache address.
  1490. */
  1491. if (unlikely(page->mapping != mapping)) {
  1492. continue_unlock:
  1493. unlock_page(page);
  1494. continue;
  1495. }
  1496. if (!PageDirty(page)) {
  1497. /* someone wrote it for us */
  1498. goto continue_unlock;
  1499. }
  1500. if (PageWriteback(page)) {
  1501. if (wbc->sync_mode != WB_SYNC_NONE)
  1502. wait_on_page_writeback(page);
  1503. else
  1504. goto continue_unlock;
  1505. }
  1506. BUG_ON(PageWriteback(page));
  1507. if (!clear_page_dirty_for_io(page))
  1508. goto continue_unlock;
  1509. trace_wbc_writepage(wbc, mapping->backing_dev_info);
  1510. ret = (*writepage)(page, wbc, data);
  1511. if (unlikely(ret)) {
  1512. if (ret == AOP_WRITEPAGE_ACTIVATE) {
  1513. unlock_page(page);
  1514. ret = 0;
  1515. } else {
  1516. /*
  1517. * done_index is set past this page,
  1518. * so media errors will not choke
  1519. * background writeout for the entire
  1520. * file. This has consequences for
  1521. * range_cyclic semantics (ie. it may
  1522. * not be suitable for data integrity
  1523. * writeout).
  1524. */
  1525. done_index = page->index + 1;
  1526. done = 1;
  1527. break;
  1528. }
  1529. }
  1530. /*
  1531. * We stop writing back only if we are not doing
  1532. * integrity sync. In case of integrity sync we have to
  1533. * keep going until we have written all the pages
  1534. * we tagged for writeback prior to entering this loop.
  1535. */
  1536. if (--wbc->nr_to_write <= 0 &&
  1537. wbc->sync_mode == WB_SYNC_NONE) {
  1538. done = 1;
  1539. break;
  1540. }
  1541. }
  1542. pagevec_release(&pvec);
  1543. cond_resched();
  1544. }
  1545. if (!cycled && !done) {
  1546. /*
  1547. * range_cyclic:
  1548. * We hit the last page and there is more work to be done: wrap
  1549. * back to the start of the file
  1550. */
  1551. cycled = 1;
  1552. index = 0;
  1553. end = writeback_index - 1;
  1554. goto retry;
  1555. }
  1556. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  1557. mapping->writeback_index = done_index;
  1558. return ret;
  1559. }
  1560. EXPORT_SYMBOL(write_cache_pages);
  1561. /*
  1562. * Function used by generic_writepages to call the real writepage
  1563. * function and set the mapping flags on error
  1564. */
  1565. static int __writepage(struct page *page, struct writeback_control *wbc,
  1566. void *data)
  1567. {
  1568. struct address_space *mapping = data;
  1569. int ret = mapping->a_ops->writepage(page, wbc);
  1570. mapping_set_error(mapping, ret);
  1571. return ret;
  1572. }
  1573. /**
  1574. * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
  1575. * @mapping: address space structure to write
  1576. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1577. *
  1578. * This is a library function, which implements the writepages()
  1579. * address_space_operation.
  1580. */
  1581. int generic_writepages(struct address_space *mapping,
  1582. struct writeback_control *wbc)
  1583. {
  1584. struct blk_plug plug;
  1585. int ret;
  1586. /* deal with chardevs and other special file */
  1587. if (!mapping->a_ops->writepage)
  1588. return 0;
  1589. blk_start_plug(&plug);
  1590. ret = write_cache_pages(mapping, wbc, __writepage, mapping);
  1591. blk_finish_plug(&plug);
  1592. return ret;
  1593. }
  1594. EXPORT_SYMBOL(generic_writepages);
  1595. int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
  1596. {
  1597. int ret;
  1598. if (wbc->nr_to_write <= 0)
  1599. return 0;
  1600. if (mapping->a_ops->writepages)
  1601. ret = mapping->a_ops->writepages(mapping, wbc);
  1602. else
  1603. ret = generic_writepages(mapping, wbc);
  1604. return ret;
  1605. }
  1606. /**
  1607. * write_one_page - write out a single page and optionally wait on I/O
  1608. * @page: the page to write
  1609. * @wait: if true, wait on writeout
  1610. *
  1611. * The page must be locked by the caller and will be unlocked upon return.
  1612. *
  1613. * write_one_page() returns a negative error code if I/O failed.
  1614. */
  1615. int write_one_page(struct page *page, int wait)
  1616. {
  1617. struct address_space *mapping = page->mapping;
  1618. int ret = 0;
  1619. struct writeback_control wbc = {
  1620. .sync_mode = WB_SYNC_ALL,
  1621. .nr_to_write = 1,
  1622. };
  1623. BUG_ON(!PageLocked(page));
  1624. if (wait)
  1625. wait_on_page_writeback(page);
  1626. if (clear_page_dirty_for_io(page)) {
  1627. page_cache_get(page);
  1628. ret = mapping->a_ops->writepage(page, &wbc);
  1629. if (ret == 0 && wait) {
  1630. wait_on_page_writeback(page);
  1631. if (PageError(page))
  1632. ret = -EIO;
  1633. }
  1634. page_cache_release(page);
  1635. } else {
  1636. unlock_page(page);
  1637. }
  1638. return ret;
  1639. }
  1640. EXPORT_SYMBOL(write_one_page);
  1641. /*
  1642. * For address_spaces which do not use buffers nor write back.
  1643. */
  1644. int __set_page_dirty_no_writeback(struct page *page)
  1645. {
  1646. if (!PageDirty(page))
  1647. return !TestSetPageDirty(page);
  1648. return 0;
  1649. }
  1650. /*
  1651. * Helper function for set_page_dirty family.
  1652. * NOTE: This relies on being atomic wrt interrupts.
  1653. */
  1654. void account_page_dirtied(struct page *page, struct address_space *mapping)
  1655. {
  1656. if (mapping_cap_account_dirty(mapping)) {
  1657. __inc_zone_page_state(page, NR_FILE_DIRTY);
  1658. __inc_zone_page_state(page, NR_DIRTIED);
  1659. __inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
  1660. __inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
  1661. task_io_account_write(PAGE_CACHE_SIZE);
  1662. current->nr_dirtied++;
  1663. this_cpu_inc(bdp_ratelimits);
  1664. }
  1665. }
  1666. EXPORT_SYMBOL(account_page_dirtied);
  1667. /*
  1668. * Helper function for set_page_writeback family.
  1669. * NOTE: Unlike account_page_dirtied this does not rely on being atomic
  1670. * wrt interrupts.
  1671. */
  1672. void account_page_writeback(struct page *page)
  1673. {
  1674. inc_zone_page_state(page, NR_WRITEBACK);
  1675. }
  1676. EXPORT_SYMBOL(account_page_writeback);
  1677. /*
  1678. * For address_spaces which do not use buffers. Just tag the page as dirty in
  1679. * its radix tree.
  1680. *
  1681. * This is also used when a single buffer is being dirtied: we want to set the
  1682. * page dirty in that case, but not all the buffers. This is a "bottom-up"
  1683. * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
  1684. *
  1685. * Most callers have locked the page, which pins the address_space in memory.
  1686. * But zap_pte_range() does not lock the page, however in that case the
  1687. * mapping is pinned by the vma's ->vm_file reference.
  1688. *
  1689. * We take care to handle the case where the page was truncated from the
  1690. * mapping by re-checking page_mapping() inside tree_lock.
  1691. */
  1692. int __set_page_dirty_nobuffers(struct page *page)
  1693. {
  1694. if (!TestSetPageDirty(page)) {
  1695. struct address_space *mapping = page_mapping(page);
  1696. struct address_space *mapping2;
  1697. if (!mapping)
  1698. return 1;
  1699. spin_lock_irq(&mapping->tree_lock);
  1700. mapping2 = page_mapping(page);
  1701. if (mapping2) { /* Race with truncate? */
  1702. BUG_ON(mapping2 != mapping);
  1703. WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
  1704. account_page_dirtied(page, mapping);
  1705. radix_tree_tag_set(&mapping->page_tree,
  1706. page_index(page), PAGECACHE_TAG_DIRTY);
  1707. }
  1708. spin_unlock_irq(&mapping->tree_lock);
  1709. if (mapping->host) {
  1710. /* !PageAnon && !swapper_space */
  1711. __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
  1712. }
  1713. return 1;
  1714. }
  1715. return 0;
  1716. }
  1717. EXPORT_SYMBOL(__set_page_dirty_nobuffers);
  1718. /*
  1719. * Call this whenever redirtying a page, to de-account the dirty counters
  1720. * (NR_DIRTIED, BDI_DIRTIED, tsk->nr_dirtied), so that they match the written
  1721. * counters (NR_WRITTEN, BDI_WRITTEN) in long term. The mismatches will lead to
  1722. * systematic errors in balanced_dirty_ratelimit and the dirty pages position
  1723. * control.
  1724. */
  1725. void account_page_redirty(struct page *page)
  1726. {
  1727. struct address_space *mapping = page->mapping;
  1728. if (mapping && mapping_cap_account_dirty(mapping)) {
  1729. current->nr_dirtied--;
  1730. dec_zone_page_state(page, NR_DIRTIED);
  1731. dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
  1732. }
  1733. }
  1734. EXPORT_SYMBOL(account_page_redirty);
  1735. /*
  1736. * When a writepage implementation decides that it doesn't want to write this
  1737. * page for some reason, it should redirty the locked page via
  1738. * redirty_page_for_writepage() and it should then unlock the page and return 0
  1739. */
  1740. int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
  1741. {
  1742. wbc->pages_skipped++;
  1743. account_page_redirty(page);
  1744. return __set_page_dirty_nobuffers(page);
  1745. }
  1746. EXPORT_SYMBOL(redirty_page_for_writepage);
  1747. /*
  1748. * Dirty a page.
  1749. *
  1750. * For pages with a mapping this should be done under the page lock
  1751. * for the benefit of asynchronous memory errors who prefer a consistent
  1752. * dirty state. This rule can be broken in some special cases,
  1753. * but should be better not to.
  1754. *
  1755. * If the mapping doesn't provide a set_page_dirty a_op, then
  1756. * just fall through and assume that it wants buffer_heads.
  1757. */
  1758. int set_page_dirty(struct page *page)
  1759. {
  1760. struct address_space *mapping = page_mapping(page);
  1761. if (likely(mapping)) {
  1762. int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
  1763. /*
  1764. * readahead/lru_deactivate_page could remain
  1765. * PG_readahead/PG_reclaim due to race with end_page_writeback
  1766. * About readahead, if the page is written, the flags would be
  1767. * reset. So no problem.
  1768. * About lru_deactivate_page, if the page is redirty, the flag
  1769. * will be reset. So no problem. but if the page is used by readahead
  1770. * it will confuse readahead and make it restart the size rampup
  1771. * process. But it's a trivial problem.
  1772. */
  1773. ClearPageReclaim(page);
  1774. #ifdef CONFIG_BLOCK
  1775. if (!spd)
  1776. spd = __set_page_dirty_buffers;
  1777. #endif
  1778. return (*spd)(page);
  1779. }
  1780. if (!PageDirty(page)) {
  1781. if (!TestSetPageDirty(page))
  1782. return 1;
  1783. }
  1784. return 0;
  1785. }
  1786. EXPORT_SYMBOL(set_page_dirty);
  1787. /*
  1788. * set_page_dirty() is racy if the caller has no reference against
  1789. * page->mapping->host, and if the page is unlocked. This is because another
  1790. * CPU could truncate the page off the mapping and then free the mapping.
  1791. *
  1792. * Usually, the page _is_ locked, or the caller is a user-space process which
  1793. * holds a reference on the inode by having an open file.
  1794. *
  1795. * In other cases, the page should be locked before running set_page_dirty().
  1796. */
  1797. int set_page_dirty_lock(struct page *page)
  1798. {
  1799. int ret;
  1800. lock_page(page);
  1801. ret = set_page_dirty(page);
  1802. unlock_page(page);
  1803. return ret;
  1804. }
  1805. EXPORT_SYMBOL(set_page_dirty_lock);
  1806. /*
  1807. * Clear a page's dirty flag, while caring for dirty memory accounting.
  1808. * Returns true if the page was previously dirty.
  1809. *
  1810. * This is for preparing to put the page under writeout. We leave the page
  1811. * tagged as dirty in the radix tree so that a concurrent write-for-sync
  1812. * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
  1813. * implementation will run either set_page_writeback() or set_page_dirty(),
  1814. * at which stage we bring the page's dirty flag and radix-tree dirty tag
  1815. * back into sync.
  1816. *
  1817. * This incoherency between the page's dirty flag and radix-tree tag is
  1818. * unfortunate, but it only exists while the page is locked.
  1819. */
  1820. int clear_page_dirty_for_io(struct page *page)
  1821. {
  1822. struct address_space *mapping = page_mapping(page);
  1823. BUG_ON(!PageLocked(page));
  1824. if (mapping && mapping_cap_account_dirty(mapping)) {
  1825. /*
  1826. * Yes, Virginia, this is indeed insane.
  1827. *
  1828. * We use this sequence to make sure that
  1829. * (a) we account for dirty stats properly
  1830. * (b) we tell the low-level filesystem to
  1831. * mark the whole page dirty if it was
  1832. * dirty in a pagetable. Only to then
  1833. * (c) clean the page again and return 1 to
  1834. * cause the writeback.
  1835. *
  1836. * This way we avoid all nasty races with the
  1837. * dirty bit in multiple places and clearing
  1838. * them concurrently from different threads.
  1839. *
  1840. * Note! Normally the "set_page_dirty(page)"
  1841. * has no effect on the actual dirty bit - since
  1842. * that will already usually be set. But we
  1843. * need the side effects, and it can help us
  1844. * avoid races.
  1845. *
  1846. * We basically use the page "master dirty bit"
  1847. * as a serialization point for all the different
  1848. * threads doing their things.
  1849. */
  1850. if (page_mkclean(page))
  1851. set_page_dirty(page);
  1852. /*
  1853. * We carefully synchronise fault handlers against
  1854. * installing a dirty pte and marking the page dirty
  1855. * at this point. We do this by having them hold the
  1856. * page lock at some point after installing their
  1857. * pte, but before marking the page dirty.
  1858. * Pages are always locked coming in here, so we get
  1859. * the desired exclusion. See mm/memory.c:do_wp_page()
  1860. * for more comments.
  1861. */
  1862. if (TestClearPageDirty(page)) {
  1863. dec_zone_page_state(page, NR_FILE_DIRTY);
  1864. dec_bdi_stat(mapping->backing_dev_info,
  1865. BDI_RECLAIMABLE);
  1866. return 1;
  1867. }
  1868. return 0;
  1869. }
  1870. return TestClearPageDirty(page);
  1871. }
  1872. EXPORT_SYMBOL(clear_page_dirty_for_io);
  1873. int test_clear_page_writeback(struct page *page)
  1874. {
  1875. struct address_space *mapping = page_mapping(page);
  1876. int ret;
  1877. if (mapping) {
  1878. struct backing_dev_info *bdi = mapping->backing_dev_info;
  1879. unsigned long flags;
  1880. spin_lock_irqsave(&mapping->tree_lock, flags);
  1881. ret = TestClearPageWriteback(page);
  1882. if (ret) {
  1883. radix_tree_tag_clear(&mapping->page_tree,
  1884. page_index(page),
  1885. PAGECACHE_TAG_WRITEBACK);
  1886. if (bdi_cap_account_writeback(bdi)) {
  1887. __dec_bdi_stat(bdi, BDI_WRITEBACK);
  1888. __bdi_writeout_inc(bdi);
  1889. }
  1890. }
  1891. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  1892. } else {
  1893. ret = TestClearPageWriteback(page);
  1894. }
  1895. if (ret) {
  1896. dec_zone_page_state(page, NR_WRITEBACK);
  1897. inc_zone_page_state(page, NR_WRITTEN);
  1898. }
  1899. return ret;
  1900. }
  1901. int test_set_page_writeback(struct page *page)
  1902. {
  1903. struct address_space *mapping = page_mapping(page);
  1904. int ret;
  1905. if (mapping) {
  1906. struct backing_dev_info *bdi = mapping->backing_dev_info;
  1907. unsigned long flags;
  1908. spin_lock_irqsave(&mapping->tree_lock, flags);
  1909. ret = TestSetPageWriteback(page);
  1910. if (!ret) {
  1911. radix_tree_tag_set(&mapping->page_tree,
  1912. page_index(page),
  1913. PAGECACHE_TAG_WRITEBACK);
  1914. if (bdi_cap_account_writeback(bdi))
  1915. __inc_bdi_stat(bdi, BDI_WRITEBACK);
  1916. }
  1917. if (!PageDirty(page))
  1918. radix_tree_tag_clear(&mapping->page_tree,
  1919. page_index(page),
  1920. PAGECACHE_TAG_DIRTY);
  1921. radix_tree_tag_clear(&mapping->page_tree,
  1922. page_index(page),
  1923. PAGECACHE_TAG_TOWRITE);
  1924. spin_unlock_irqrestore(&mapping->tree_lock, flags);
  1925. } else {
  1926. ret = TestSetPageWriteback(page);
  1927. }
  1928. if (!ret)
  1929. account_page_writeback(page);
  1930. return ret;
  1931. }
  1932. EXPORT_SYMBOL(test_set_page_writeback);
  1933. /*
  1934. * Return true if any of the pages in the mapping are marked with the
  1935. * passed tag.
  1936. */
  1937. int mapping_tagged(struct address_space *mapping, int tag)
  1938. {
  1939. return radix_tree_tagged(&mapping->page_tree, tag);
  1940. }
  1941. EXPORT_SYMBOL(mapping_tagged);