page-writeback.c 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837
  1. /*
  2. * mm/page-writeback.c
  3. *
  4. * Copyright (C) 2002, Linus Torvalds.
  5. * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
  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/smp.h>
  30. #include <linux/sysctl.h>
  31. #include <linux/cpu.h>
  32. #include <linux/syscalls.h>
  33. #include <linux/buffer_head.h> /* __set_page_dirty_buffers */
  34. #include <linux/pagevec.h>
  35. #include <linux/timer.h>
  36. #include <linux/sched/rt.h>
  37. #include <linux/sched/signal.h>
  38. #include <linux/mm_inline.h>
  39. #include <trace/events/writeback.h>
  40. #include "internal.h"
  41. /*
  42. * Sleep at most 200ms at a time in balance_dirty_pages().
  43. */
  44. #define MAX_PAUSE max(HZ/5, 1)
  45. /*
  46. * Try to keep balance_dirty_pages() call intervals higher than this many pages
  47. * by raising pause time to max_pause when falls below it.
  48. */
  49. #define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10))
  50. /*
  51. * Estimate write bandwidth at 200ms intervals.
  52. */
  53. #define BANDWIDTH_INTERVAL max(HZ/5, 1)
  54. #define RATELIMIT_CALC_SHIFT 10
  55. /*
  56. * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
  57. * will look to see if it needs to force writeback or throttling.
  58. */
  59. static long ratelimit_pages = 32;
  60. /* The following parameters are exported via /proc/sys/vm */
  61. /*
  62. * Start background writeback (via writeback threads) at this percentage
  63. */
  64. int dirty_background_ratio = 10;
  65. /*
  66. * dirty_background_bytes starts at 0 (disabled) so that it is a function of
  67. * dirty_background_ratio * the amount of dirtyable memory
  68. */
  69. unsigned long dirty_background_bytes;
  70. /*
  71. * free highmem will not be subtracted from the total free memory
  72. * for calculating free ratios if vm_highmem_is_dirtyable is true
  73. */
  74. int vm_highmem_is_dirtyable;
  75. /*
  76. * The generator of dirty data starts writeback at this percentage
  77. */
  78. int vm_dirty_ratio = 20;
  79. /*
  80. * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
  81. * vm_dirty_ratio * the amount of dirtyable memory
  82. */
  83. unsigned long vm_dirty_bytes;
  84. /*
  85. * The interval between `kupdate'-style writebacks
  86. */
  87. unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
  88. EXPORT_SYMBOL_GPL(dirty_writeback_interval);
  89. /*
  90. * The longest time for which data is allowed to remain dirty
  91. */
  92. unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
  93. /*
  94. * Flag that makes the machine dump writes/reads and block dirtyings.
  95. */
  96. int block_dump;
  97. /*
  98. * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
  99. * a full sync is triggered after this time elapses without any disk activity.
  100. */
  101. int laptop_mode;
  102. EXPORT_SYMBOL(laptop_mode);
  103. /* End of sysctl-exported parameters */
  104. struct wb_domain global_wb_domain;
  105. /* consolidated parameters for balance_dirty_pages() and its subroutines */
  106. struct dirty_throttle_control {
  107. #ifdef CONFIG_CGROUP_WRITEBACK
  108. struct wb_domain *dom;
  109. struct dirty_throttle_control *gdtc; /* only set in memcg dtc's */
  110. #endif
  111. struct bdi_writeback *wb;
  112. struct fprop_local_percpu *wb_completions;
  113. unsigned long avail; /* dirtyable */
  114. unsigned long dirty; /* file_dirty + write + nfs */
  115. unsigned long thresh; /* dirty threshold */
  116. unsigned long bg_thresh; /* dirty background threshold */
  117. unsigned long wb_dirty; /* per-wb counterparts */
  118. unsigned long wb_thresh;
  119. unsigned long wb_bg_thresh;
  120. unsigned long pos_ratio;
  121. };
  122. /*
  123. * Length of period for aging writeout fractions of bdis. This is an
  124. * arbitrarily chosen number. The longer the period, the slower fractions will
  125. * reflect changes in current writeout rate.
  126. */
  127. #define VM_COMPLETIONS_PERIOD_LEN (3*HZ)
  128. #ifdef CONFIG_CGROUP_WRITEBACK
  129. #define GDTC_INIT(__wb) .wb = (__wb), \
  130. .dom = &global_wb_domain, \
  131. .wb_completions = &(__wb)->completions
  132. #define GDTC_INIT_NO_WB .dom = &global_wb_domain
  133. #define MDTC_INIT(__wb, __gdtc) .wb = (__wb), \
  134. .dom = mem_cgroup_wb_domain(__wb), \
  135. .wb_completions = &(__wb)->memcg_completions, \
  136. .gdtc = __gdtc
  137. static bool mdtc_valid(struct dirty_throttle_control *dtc)
  138. {
  139. return dtc->dom;
  140. }
  141. static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc)
  142. {
  143. return dtc->dom;
  144. }
  145. static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc)
  146. {
  147. return mdtc->gdtc;
  148. }
  149. static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb)
  150. {
  151. return &wb->memcg_completions;
  152. }
  153. static void wb_min_max_ratio(struct bdi_writeback *wb,
  154. unsigned long *minp, unsigned long *maxp)
  155. {
  156. unsigned long this_bw = wb->avg_write_bandwidth;
  157. unsigned long tot_bw = atomic_long_read(&wb->bdi->tot_write_bandwidth);
  158. unsigned long long min = wb->bdi->min_ratio;
  159. unsigned long long max = wb->bdi->max_ratio;
  160. /*
  161. * @wb may already be clean by the time control reaches here and
  162. * the total may not include its bw.
  163. */
  164. if (this_bw < tot_bw) {
  165. if (min) {
  166. min *= this_bw;
  167. min = div64_ul(min, tot_bw);
  168. }
  169. if (max < 100) {
  170. max *= this_bw;
  171. max = div64_ul(max, tot_bw);
  172. }
  173. }
  174. *minp = min;
  175. *maxp = max;
  176. }
  177. #else /* CONFIG_CGROUP_WRITEBACK */
  178. #define GDTC_INIT(__wb) .wb = (__wb), \
  179. .wb_completions = &(__wb)->completions
  180. #define GDTC_INIT_NO_WB
  181. #define MDTC_INIT(__wb, __gdtc)
  182. static bool mdtc_valid(struct dirty_throttle_control *dtc)
  183. {
  184. return false;
  185. }
  186. static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc)
  187. {
  188. return &global_wb_domain;
  189. }
  190. static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc)
  191. {
  192. return NULL;
  193. }
  194. static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb)
  195. {
  196. return NULL;
  197. }
  198. static void wb_min_max_ratio(struct bdi_writeback *wb,
  199. unsigned long *minp, unsigned long *maxp)
  200. {
  201. *minp = wb->bdi->min_ratio;
  202. *maxp = wb->bdi->max_ratio;
  203. }
  204. #endif /* CONFIG_CGROUP_WRITEBACK */
  205. /*
  206. * In a memory zone, there is a certain amount of pages we consider
  207. * available for the page cache, which is essentially the number of
  208. * free and reclaimable pages, minus some zone reserves to protect
  209. * lowmem and the ability to uphold the zone's watermarks without
  210. * requiring writeback.
  211. *
  212. * This number of dirtyable pages is the base value of which the
  213. * user-configurable dirty ratio is the effictive number of pages that
  214. * are allowed to be actually dirtied. Per individual zone, or
  215. * globally by using the sum of dirtyable pages over all zones.
  216. *
  217. * Because the user is allowed to specify the dirty limit globally as
  218. * absolute number of bytes, calculating the per-zone dirty limit can
  219. * require translating the configured limit into a percentage of
  220. * global dirtyable memory first.
  221. */
  222. /**
  223. * node_dirtyable_memory - number of dirtyable pages in a node
  224. * @pgdat: the node
  225. *
  226. * Returns the node's number of pages potentially available for dirty
  227. * page cache. This is the base value for the per-node dirty limits.
  228. */
  229. static unsigned long node_dirtyable_memory(struct pglist_data *pgdat)
  230. {
  231. unsigned long nr_pages = 0;
  232. int z;
  233. for (z = 0; z < MAX_NR_ZONES; z++) {
  234. struct zone *zone = pgdat->node_zones + z;
  235. if (!populated_zone(zone))
  236. continue;
  237. nr_pages += zone_page_state(zone, NR_FREE_PAGES);
  238. }
  239. /*
  240. * Pages reserved for the kernel should not be considered
  241. * dirtyable, to prevent a situation where reclaim has to
  242. * clean pages in order to balance the zones.
  243. */
  244. nr_pages -= min(nr_pages, pgdat->totalreserve_pages);
  245. nr_pages += node_page_state(pgdat, NR_INACTIVE_FILE);
  246. nr_pages += node_page_state(pgdat, NR_ACTIVE_FILE);
  247. return nr_pages;
  248. }
  249. static unsigned long highmem_dirtyable_memory(unsigned long total)
  250. {
  251. #ifdef CONFIG_HIGHMEM
  252. int node;
  253. unsigned long x = 0;
  254. int i;
  255. for_each_node_state(node, N_HIGH_MEMORY) {
  256. for (i = ZONE_NORMAL + 1; i < MAX_NR_ZONES; i++) {
  257. struct zone *z;
  258. unsigned long nr_pages;
  259. if (!is_highmem_idx(i))
  260. continue;
  261. z = &NODE_DATA(node)->node_zones[i];
  262. if (!populated_zone(z))
  263. continue;
  264. nr_pages = zone_page_state(z, NR_FREE_PAGES);
  265. /* watch for underflows */
  266. nr_pages -= min(nr_pages, high_wmark_pages(z));
  267. nr_pages += zone_page_state(z, NR_ZONE_INACTIVE_FILE);
  268. nr_pages += zone_page_state(z, NR_ZONE_ACTIVE_FILE);
  269. x += nr_pages;
  270. }
  271. }
  272. /*
  273. * Unreclaimable memory (kernel memory or anonymous memory
  274. * without swap) can bring down the dirtyable pages below
  275. * the zone's dirty balance reserve and the above calculation
  276. * will underflow. However we still want to add in nodes
  277. * which are below threshold (negative values) to get a more
  278. * accurate calculation but make sure that the total never
  279. * underflows.
  280. */
  281. if ((long)x < 0)
  282. x = 0;
  283. /*
  284. * Make sure that the number of highmem pages is never larger
  285. * than the number of the total dirtyable memory. This can only
  286. * occur in very strange VM situations but we want to make sure
  287. * that this does not occur.
  288. */
  289. return min(x, total);
  290. #else
  291. return 0;
  292. #endif
  293. }
  294. /**
  295. * global_dirtyable_memory - number of globally dirtyable pages
  296. *
  297. * Returns the global number of pages potentially available for dirty
  298. * page cache. This is the base value for the global dirty limits.
  299. */
  300. static unsigned long global_dirtyable_memory(void)
  301. {
  302. unsigned long x;
  303. x = global_zone_page_state(NR_FREE_PAGES);
  304. /*
  305. * Pages reserved for the kernel should not be considered
  306. * dirtyable, to prevent a situation where reclaim has to
  307. * clean pages in order to balance the zones.
  308. */
  309. x -= min(x, totalreserve_pages);
  310. x += global_node_page_state(NR_INACTIVE_FILE);
  311. x += global_node_page_state(NR_ACTIVE_FILE);
  312. if (!vm_highmem_is_dirtyable)
  313. x -= highmem_dirtyable_memory(x);
  314. return x + 1; /* Ensure that we never return 0 */
  315. }
  316. /**
  317. * domain_dirty_limits - calculate thresh and bg_thresh for a wb_domain
  318. * @dtc: dirty_throttle_control of interest
  319. *
  320. * Calculate @dtc->thresh and ->bg_thresh considering
  321. * vm_dirty_{bytes|ratio} and dirty_background_{bytes|ratio}. The caller
  322. * must ensure that @dtc->avail is set before calling this function. The
  323. * dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
  324. * real-time tasks.
  325. */
  326. static void domain_dirty_limits(struct dirty_throttle_control *dtc)
  327. {
  328. const unsigned long available_memory = dtc->avail;
  329. struct dirty_throttle_control *gdtc = mdtc_gdtc(dtc);
  330. unsigned long bytes = vm_dirty_bytes;
  331. unsigned long bg_bytes = dirty_background_bytes;
  332. /* convert ratios to per-PAGE_SIZE for higher precision */
  333. unsigned long ratio = (vm_dirty_ratio * PAGE_SIZE) / 100;
  334. unsigned long bg_ratio = (dirty_background_ratio * PAGE_SIZE) / 100;
  335. unsigned long thresh;
  336. unsigned long bg_thresh;
  337. struct task_struct *tsk;
  338. /* gdtc is !NULL iff @dtc is for memcg domain */
  339. if (gdtc) {
  340. unsigned long global_avail = gdtc->avail;
  341. /*
  342. * The byte settings can't be applied directly to memcg
  343. * domains. Convert them to ratios by scaling against
  344. * globally available memory. As the ratios are in
  345. * per-PAGE_SIZE, they can be obtained by dividing bytes by
  346. * number of pages.
  347. */
  348. if (bytes)
  349. ratio = min(DIV_ROUND_UP(bytes, global_avail),
  350. PAGE_SIZE);
  351. if (bg_bytes)
  352. bg_ratio = min(DIV_ROUND_UP(bg_bytes, global_avail),
  353. PAGE_SIZE);
  354. bytes = bg_bytes = 0;
  355. }
  356. if (bytes)
  357. thresh = DIV_ROUND_UP(bytes, PAGE_SIZE);
  358. else
  359. thresh = (ratio * available_memory) / PAGE_SIZE;
  360. if (bg_bytes)
  361. bg_thresh = DIV_ROUND_UP(bg_bytes, PAGE_SIZE);
  362. else
  363. bg_thresh = (bg_ratio * available_memory) / PAGE_SIZE;
  364. if (bg_thresh >= thresh)
  365. bg_thresh = thresh / 2;
  366. tsk = current;
  367. if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
  368. bg_thresh += bg_thresh / 4 + global_wb_domain.dirty_limit / 32;
  369. thresh += thresh / 4 + global_wb_domain.dirty_limit / 32;
  370. }
  371. dtc->thresh = thresh;
  372. dtc->bg_thresh = bg_thresh;
  373. /* we should eventually report the domain in the TP */
  374. if (!gdtc)
  375. trace_global_dirty_state(bg_thresh, thresh);
  376. }
  377. /**
  378. * global_dirty_limits - background-writeback and dirty-throttling thresholds
  379. * @pbackground: out parameter for bg_thresh
  380. * @pdirty: out parameter for thresh
  381. *
  382. * Calculate bg_thresh and thresh for global_wb_domain. See
  383. * domain_dirty_limits() for details.
  384. */
  385. void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
  386. {
  387. struct dirty_throttle_control gdtc = { GDTC_INIT_NO_WB };
  388. gdtc.avail = global_dirtyable_memory();
  389. domain_dirty_limits(&gdtc);
  390. *pbackground = gdtc.bg_thresh;
  391. *pdirty = gdtc.thresh;
  392. }
  393. /**
  394. * node_dirty_limit - maximum number of dirty pages allowed in a node
  395. * @pgdat: the node
  396. *
  397. * Returns the maximum number of dirty pages allowed in a node, based
  398. * on the node's dirtyable memory.
  399. */
  400. static unsigned long node_dirty_limit(struct pglist_data *pgdat)
  401. {
  402. unsigned long node_memory = node_dirtyable_memory(pgdat);
  403. struct task_struct *tsk = current;
  404. unsigned long dirty;
  405. if (vm_dirty_bytes)
  406. dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) *
  407. node_memory / global_dirtyable_memory();
  408. else
  409. dirty = vm_dirty_ratio * node_memory / 100;
  410. if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk))
  411. dirty += dirty / 4;
  412. return dirty;
  413. }
  414. /**
  415. * node_dirty_ok - tells whether a node is within its dirty limits
  416. * @pgdat: the node to check
  417. *
  418. * Returns %true when the dirty pages in @pgdat are within the node's
  419. * dirty limit, %false if the limit is exceeded.
  420. */
  421. bool node_dirty_ok(struct pglist_data *pgdat)
  422. {
  423. unsigned long limit = node_dirty_limit(pgdat);
  424. unsigned long nr_pages = 0;
  425. nr_pages += node_page_state(pgdat, NR_FILE_DIRTY);
  426. nr_pages += node_page_state(pgdat, NR_UNSTABLE_NFS);
  427. nr_pages += node_page_state(pgdat, NR_WRITEBACK);
  428. return nr_pages <= limit;
  429. }
  430. int dirty_background_ratio_handler(struct ctl_table *table, int write,
  431. void __user *buffer, size_t *lenp,
  432. loff_t *ppos)
  433. {
  434. int ret;
  435. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  436. if (ret == 0 && write)
  437. dirty_background_bytes = 0;
  438. return ret;
  439. }
  440. int dirty_background_bytes_handler(struct ctl_table *table, int write,
  441. void __user *buffer, size_t *lenp,
  442. loff_t *ppos)
  443. {
  444. int ret;
  445. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  446. if (ret == 0 && write)
  447. dirty_background_ratio = 0;
  448. return ret;
  449. }
  450. int dirty_ratio_handler(struct ctl_table *table, int write,
  451. void __user *buffer, size_t *lenp,
  452. loff_t *ppos)
  453. {
  454. int old_ratio = vm_dirty_ratio;
  455. int ret;
  456. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  457. if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
  458. writeback_set_ratelimit();
  459. vm_dirty_bytes = 0;
  460. }
  461. return ret;
  462. }
  463. int dirty_bytes_handler(struct ctl_table *table, int write,
  464. void __user *buffer, size_t *lenp,
  465. loff_t *ppos)
  466. {
  467. unsigned long old_bytes = vm_dirty_bytes;
  468. int ret;
  469. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  470. if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
  471. writeback_set_ratelimit();
  472. vm_dirty_ratio = 0;
  473. }
  474. return ret;
  475. }
  476. static unsigned long wp_next_time(unsigned long cur_time)
  477. {
  478. cur_time += VM_COMPLETIONS_PERIOD_LEN;
  479. /* 0 has a special meaning... */
  480. if (!cur_time)
  481. return 1;
  482. return cur_time;
  483. }
  484. static void wb_domain_writeout_inc(struct wb_domain *dom,
  485. struct fprop_local_percpu *completions,
  486. unsigned int max_prop_frac)
  487. {
  488. __fprop_inc_percpu_max(&dom->completions, completions,
  489. max_prop_frac);
  490. /* First event after period switching was turned off? */
  491. if (unlikely(!dom->period_time)) {
  492. /*
  493. * We can race with other __bdi_writeout_inc calls here but
  494. * it does not cause any harm since the resulting time when
  495. * timer will fire and what is in writeout_period_time will be
  496. * roughly the same.
  497. */
  498. dom->period_time = wp_next_time(jiffies);
  499. mod_timer(&dom->period_timer, dom->period_time);
  500. }
  501. }
  502. /*
  503. * Increment @wb's writeout completion count and the global writeout
  504. * completion count. Called from test_clear_page_writeback().
  505. */
  506. static inline void __wb_writeout_inc(struct bdi_writeback *wb)
  507. {
  508. struct wb_domain *cgdom;
  509. inc_wb_stat(wb, WB_WRITTEN);
  510. wb_domain_writeout_inc(&global_wb_domain, &wb->completions,
  511. wb->bdi->max_prop_frac);
  512. cgdom = mem_cgroup_wb_domain(wb);
  513. if (cgdom)
  514. wb_domain_writeout_inc(cgdom, wb_memcg_completions(wb),
  515. wb->bdi->max_prop_frac);
  516. }
  517. void wb_writeout_inc(struct bdi_writeback *wb)
  518. {
  519. unsigned long flags;
  520. local_irq_save(flags);
  521. __wb_writeout_inc(wb);
  522. local_irq_restore(flags);
  523. }
  524. EXPORT_SYMBOL_GPL(wb_writeout_inc);
  525. /*
  526. * On idle system, we can be called long after we scheduled because we use
  527. * deferred timers so count with missed periods.
  528. */
  529. static void writeout_period(struct timer_list *t)
  530. {
  531. struct wb_domain *dom = from_timer(dom, t, period_timer);
  532. int miss_periods = (jiffies - dom->period_time) /
  533. VM_COMPLETIONS_PERIOD_LEN;
  534. if (fprop_new_period(&dom->completions, miss_periods + 1)) {
  535. dom->period_time = wp_next_time(dom->period_time +
  536. miss_periods * VM_COMPLETIONS_PERIOD_LEN);
  537. mod_timer(&dom->period_timer, dom->period_time);
  538. } else {
  539. /*
  540. * Aging has zeroed all fractions. Stop wasting CPU on period
  541. * updates.
  542. */
  543. dom->period_time = 0;
  544. }
  545. }
  546. int wb_domain_init(struct wb_domain *dom, gfp_t gfp)
  547. {
  548. memset(dom, 0, sizeof(*dom));
  549. spin_lock_init(&dom->lock);
  550. timer_setup(&dom->period_timer, writeout_period, TIMER_DEFERRABLE);
  551. dom->dirty_limit_tstamp = jiffies;
  552. return fprop_global_init(&dom->completions, gfp);
  553. }
  554. #ifdef CONFIG_CGROUP_WRITEBACK
  555. void wb_domain_exit(struct wb_domain *dom)
  556. {
  557. del_timer_sync(&dom->period_timer);
  558. fprop_global_destroy(&dom->completions);
  559. }
  560. #endif
  561. /*
  562. * bdi_min_ratio keeps the sum of the minimum dirty shares of all
  563. * registered backing devices, which, for obvious reasons, can not
  564. * exceed 100%.
  565. */
  566. static unsigned int bdi_min_ratio;
  567. int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
  568. {
  569. int ret = 0;
  570. spin_lock_bh(&bdi_lock);
  571. if (min_ratio > bdi->max_ratio) {
  572. ret = -EINVAL;
  573. } else {
  574. min_ratio -= bdi->min_ratio;
  575. if (bdi_min_ratio + min_ratio < 100) {
  576. bdi_min_ratio += min_ratio;
  577. bdi->min_ratio += min_ratio;
  578. } else {
  579. ret = -EINVAL;
  580. }
  581. }
  582. spin_unlock_bh(&bdi_lock);
  583. return ret;
  584. }
  585. int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
  586. {
  587. int ret = 0;
  588. if (max_ratio > 100)
  589. return -EINVAL;
  590. spin_lock_bh(&bdi_lock);
  591. if (bdi->min_ratio > max_ratio) {
  592. ret = -EINVAL;
  593. } else {
  594. bdi->max_ratio = max_ratio;
  595. bdi->max_prop_frac = (FPROP_FRAC_BASE * max_ratio) / 100;
  596. }
  597. spin_unlock_bh(&bdi_lock);
  598. return ret;
  599. }
  600. EXPORT_SYMBOL(bdi_set_max_ratio);
  601. static unsigned long dirty_freerun_ceiling(unsigned long thresh,
  602. unsigned long bg_thresh)
  603. {
  604. return (thresh + bg_thresh) / 2;
  605. }
  606. static unsigned long hard_dirty_limit(struct wb_domain *dom,
  607. unsigned long thresh)
  608. {
  609. return max(thresh, dom->dirty_limit);
  610. }
  611. /*
  612. * Memory which can be further allocated to a memcg domain is capped by
  613. * system-wide clean memory excluding the amount being used in the domain.
  614. */
  615. static void mdtc_calc_avail(struct dirty_throttle_control *mdtc,
  616. unsigned long filepages, unsigned long headroom)
  617. {
  618. struct dirty_throttle_control *gdtc = mdtc_gdtc(mdtc);
  619. unsigned long clean = filepages - min(filepages, mdtc->dirty);
  620. unsigned long global_clean = gdtc->avail - min(gdtc->avail, gdtc->dirty);
  621. unsigned long other_clean = global_clean - min(global_clean, clean);
  622. mdtc->avail = filepages + min(headroom, other_clean);
  623. }
  624. /**
  625. * __wb_calc_thresh - @wb's share of dirty throttling threshold
  626. * @dtc: dirty_throttle_context of interest
  627. *
  628. * Returns @wb's dirty limit in pages. The term "dirty" in the context of
  629. * dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
  630. *
  631. * Note that balance_dirty_pages() will only seriously take it as a hard limit
  632. * when sleeping max_pause per page is not enough to keep the dirty pages under
  633. * control. For example, when the device is completely stalled due to some error
  634. * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
  635. * In the other normal situations, it acts more gently by throttling the tasks
  636. * more (rather than completely block them) when the wb dirty pages go high.
  637. *
  638. * It allocates high/low dirty limits to fast/slow devices, in order to prevent
  639. * - starving fast devices
  640. * - piling up dirty pages (that will take long time to sync) on slow devices
  641. *
  642. * The wb's share of dirty limit will be adapting to its throughput and
  643. * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
  644. */
  645. static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc)
  646. {
  647. struct wb_domain *dom = dtc_dom(dtc);
  648. unsigned long thresh = dtc->thresh;
  649. u64 wb_thresh;
  650. long numerator, denominator;
  651. unsigned long wb_min_ratio, wb_max_ratio;
  652. /*
  653. * Calculate this BDI's share of the thresh ratio.
  654. */
  655. fprop_fraction_percpu(&dom->completions, dtc->wb_completions,
  656. &numerator, &denominator);
  657. wb_thresh = (thresh * (100 - bdi_min_ratio)) / 100;
  658. wb_thresh *= numerator;
  659. do_div(wb_thresh, denominator);
  660. wb_min_max_ratio(dtc->wb, &wb_min_ratio, &wb_max_ratio);
  661. wb_thresh += (thresh * wb_min_ratio) / 100;
  662. if (wb_thresh > (thresh * wb_max_ratio) / 100)
  663. wb_thresh = thresh * wb_max_ratio / 100;
  664. return wb_thresh;
  665. }
  666. unsigned long wb_calc_thresh(struct bdi_writeback *wb, unsigned long thresh)
  667. {
  668. struct dirty_throttle_control gdtc = { GDTC_INIT(wb),
  669. .thresh = thresh };
  670. return __wb_calc_thresh(&gdtc);
  671. }
  672. /*
  673. * setpoint - dirty 3
  674. * f(dirty) := 1.0 + (----------------)
  675. * limit - setpoint
  676. *
  677. * it's a 3rd order polynomial that subjects to
  678. *
  679. * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast
  680. * (2) f(setpoint) = 1.0 => the balance point
  681. * (3) f(limit) = 0 => the hard limit
  682. * (4) df/dx <= 0 => negative feedback control
  683. * (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
  684. * => fast response on large errors; small oscillation near setpoint
  685. */
  686. static long long pos_ratio_polynom(unsigned long setpoint,
  687. unsigned long dirty,
  688. unsigned long limit)
  689. {
  690. long long pos_ratio;
  691. long x;
  692. x = div64_s64(((s64)setpoint - (s64)dirty) << RATELIMIT_CALC_SHIFT,
  693. (limit - setpoint) | 1);
  694. pos_ratio = x;
  695. pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
  696. pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
  697. pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
  698. return clamp(pos_ratio, 0LL, 2LL << RATELIMIT_CALC_SHIFT);
  699. }
  700. /*
  701. * Dirty position control.
  702. *
  703. * (o) global/bdi setpoints
  704. *
  705. * We want the dirty pages be balanced around the global/wb setpoints.
  706. * When the number of dirty pages is higher/lower than the setpoint, the
  707. * dirty position control ratio (and hence task dirty ratelimit) will be
  708. * decreased/increased to bring the dirty pages back to the setpoint.
  709. *
  710. * pos_ratio = 1 << RATELIMIT_CALC_SHIFT
  711. *
  712. * if (dirty < setpoint) scale up pos_ratio
  713. * if (dirty > setpoint) scale down pos_ratio
  714. *
  715. * if (wb_dirty < wb_setpoint) scale up pos_ratio
  716. * if (wb_dirty > wb_setpoint) scale down pos_ratio
  717. *
  718. * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
  719. *
  720. * (o) global control line
  721. *
  722. * ^ pos_ratio
  723. * |
  724. * | |<===== global dirty control scope ======>|
  725. * 2.0 .............*
  726. * | .*
  727. * | . *
  728. * | . *
  729. * | . *
  730. * | . *
  731. * | . *
  732. * 1.0 ................................*
  733. * | . . *
  734. * | . . *
  735. * | . . *
  736. * | . . *
  737. * | . . *
  738. * 0 +------------.------------------.----------------------*------------->
  739. * freerun^ setpoint^ limit^ dirty pages
  740. *
  741. * (o) wb control line
  742. *
  743. * ^ pos_ratio
  744. * |
  745. * | *
  746. * | *
  747. * | *
  748. * | *
  749. * | * |<=========== span ============>|
  750. * 1.0 .......................*
  751. * | . *
  752. * | . *
  753. * | . *
  754. * | . *
  755. * | . *
  756. * | . *
  757. * | . *
  758. * | . *
  759. * | . *
  760. * | . *
  761. * | . *
  762. * 1/4 ...............................................* * * * * * * * * * * *
  763. * | . .
  764. * | . .
  765. * | . .
  766. * 0 +----------------------.-------------------------------.------------->
  767. * wb_setpoint^ x_intercept^
  768. *
  769. * The wb control line won't drop below pos_ratio=1/4, so that wb_dirty can
  770. * be smoothly throttled down to normal if it starts high in situations like
  771. * - start writing to a slow SD card and a fast disk at the same time. The SD
  772. * card's wb_dirty may rush to many times higher than wb_setpoint.
  773. * - the wb dirty thresh drops quickly due to change of JBOD workload
  774. */
  775. static void wb_position_ratio(struct dirty_throttle_control *dtc)
  776. {
  777. struct bdi_writeback *wb = dtc->wb;
  778. unsigned long write_bw = wb->avg_write_bandwidth;
  779. unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh);
  780. unsigned long limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh);
  781. unsigned long wb_thresh = dtc->wb_thresh;
  782. unsigned long x_intercept;
  783. unsigned long setpoint; /* dirty pages' target balance point */
  784. unsigned long wb_setpoint;
  785. unsigned long span;
  786. long long pos_ratio; /* for scaling up/down the rate limit */
  787. long x;
  788. dtc->pos_ratio = 0;
  789. if (unlikely(dtc->dirty >= limit))
  790. return;
  791. /*
  792. * global setpoint
  793. *
  794. * See comment for pos_ratio_polynom().
  795. */
  796. setpoint = (freerun + limit) / 2;
  797. pos_ratio = pos_ratio_polynom(setpoint, dtc->dirty, limit);
  798. /*
  799. * The strictlimit feature is a tool preventing mistrusted filesystems
  800. * from growing a large number of dirty pages before throttling. For
  801. * such filesystems balance_dirty_pages always checks wb counters
  802. * against wb limits. Even if global "nr_dirty" is under "freerun".
  803. * This is especially important for fuse which sets bdi->max_ratio to
  804. * 1% by default. Without strictlimit feature, fuse writeback may
  805. * consume arbitrary amount of RAM because it is accounted in
  806. * NR_WRITEBACK_TEMP which is not involved in calculating "nr_dirty".
  807. *
  808. * Here, in wb_position_ratio(), we calculate pos_ratio based on
  809. * two values: wb_dirty and wb_thresh. Let's consider an example:
  810. * total amount of RAM is 16GB, bdi->max_ratio is equal to 1%, global
  811. * limits are set by default to 10% and 20% (background and throttle).
  812. * Then wb_thresh is 1% of 20% of 16GB. This amounts to ~8K pages.
  813. * wb_calc_thresh(wb, bg_thresh) is about ~4K pages. wb_setpoint is
  814. * about ~6K pages (as the average of background and throttle wb
  815. * limits). The 3rd order polynomial will provide positive feedback if
  816. * wb_dirty is under wb_setpoint and vice versa.
  817. *
  818. * Note, that we cannot use global counters in these calculations
  819. * because we want to throttle process writing to a strictlimit wb
  820. * much earlier than global "freerun" is reached (~23MB vs. ~2.3GB
  821. * in the example above).
  822. */
  823. if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
  824. long long wb_pos_ratio;
  825. if (dtc->wb_dirty < 8) {
  826. dtc->pos_ratio = min_t(long long, pos_ratio * 2,
  827. 2 << RATELIMIT_CALC_SHIFT);
  828. return;
  829. }
  830. if (dtc->wb_dirty >= wb_thresh)
  831. return;
  832. wb_setpoint = dirty_freerun_ceiling(wb_thresh,
  833. dtc->wb_bg_thresh);
  834. if (wb_setpoint == 0 || wb_setpoint == wb_thresh)
  835. return;
  836. wb_pos_ratio = pos_ratio_polynom(wb_setpoint, dtc->wb_dirty,
  837. wb_thresh);
  838. /*
  839. * Typically, for strictlimit case, wb_setpoint << setpoint
  840. * and pos_ratio >> wb_pos_ratio. In the other words global
  841. * state ("dirty") is not limiting factor and we have to
  842. * make decision based on wb counters. But there is an
  843. * important case when global pos_ratio should get precedence:
  844. * global limits are exceeded (e.g. due to activities on other
  845. * wb's) while given strictlimit wb is below limit.
  846. *
  847. * "pos_ratio * wb_pos_ratio" would work for the case above,
  848. * but it would look too non-natural for the case of all
  849. * activity in the system coming from a single strictlimit wb
  850. * with bdi->max_ratio == 100%.
  851. *
  852. * Note that min() below somewhat changes the dynamics of the
  853. * control system. Normally, pos_ratio value can be well over 3
  854. * (when globally we are at freerun and wb is well below wb
  855. * setpoint). Now the maximum pos_ratio in the same situation
  856. * is 2. We might want to tweak this if we observe the control
  857. * system is too slow to adapt.
  858. */
  859. dtc->pos_ratio = min(pos_ratio, wb_pos_ratio);
  860. return;
  861. }
  862. /*
  863. * We have computed basic pos_ratio above based on global situation. If
  864. * the wb is over/under its share of dirty pages, we want to scale
  865. * pos_ratio further down/up. That is done by the following mechanism.
  866. */
  867. /*
  868. * wb setpoint
  869. *
  870. * f(wb_dirty) := 1.0 + k * (wb_dirty - wb_setpoint)
  871. *
  872. * x_intercept - wb_dirty
  873. * := --------------------------
  874. * x_intercept - wb_setpoint
  875. *
  876. * The main wb control line is a linear function that subjects to
  877. *
  878. * (1) f(wb_setpoint) = 1.0
  879. * (2) k = - 1 / (8 * write_bw) (in single wb case)
  880. * or equally: x_intercept = wb_setpoint + 8 * write_bw
  881. *
  882. * For single wb case, the dirty pages are observed to fluctuate
  883. * regularly within range
  884. * [wb_setpoint - write_bw/2, wb_setpoint + write_bw/2]
  885. * for various filesystems, where (2) can yield in a reasonable 12.5%
  886. * fluctuation range for pos_ratio.
  887. *
  888. * For JBOD case, wb_thresh (not wb_dirty!) could fluctuate up to its
  889. * own size, so move the slope over accordingly and choose a slope that
  890. * yields 100% pos_ratio fluctuation on suddenly doubled wb_thresh.
  891. */
  892. if (unlikely(wb_thresh > dtc->thresh))
  893. wb_thresh = dtc->thresh;
  894. /*
  895. * It's very possible that wb_thresh is close to 0 not because the
  896. * device is slow, but that it has remained inactive for long time.
  897. * Honour such devices a reasonable good (hopefully IO efficient)
  898. * threshold, so that the occasional writes won't be blocked and active
  899. * writes can rampup the threshold quickly.
  900. */
  901. wb_thresh = max(wb_thresh, (limit - dtc->dirty) / 8);
  902. /*
  903. * scale global setpoint to wb's:
  904. * wb_setpoint = setpoint * wb_thresh / thresh
  905. */
  906. x = div_u64((u64)wb_thresh << 16, dtc->thresh | 1);
  907. wb_setpoint = setpoint * (u64)x >> 16;
  908. /*
  909. * Use span=(8*write_bw) in single wb case as indicated by
  910. * (thresh - wb_thresh ~= 0) and transit to wb_thresh in JBOD case.
  911. *
  912. * wb_thresh thresh - wb_thresh
  913. * span = --------- * (8 * write_bw) + ------------------ * wb_thresh
  914. * thresh thresh
  915. */
  916. span = (dtc->thresh - wb_thresh + 8 * write_bw) * (u64)x >> 16;
  917. x_intercept = wb_setpoint + span;
  918. if (dtc->wb_dirty < x_intercept - span / 4) {
  919. pos_ratio = div64_u64(pos_ratio * (x_intercept - dtc->wb_dirty),
  920. (x_intercept - wb_setpoint) | 1);
  921. } else
  922. pos_ratio /= 4;
  923. /*
  924. * wb reserve area, safeguard against dirty pool underrun and disk idle
  925. * It may push the desired control point of global dirty pages higher
  926. * than setpoint.
  927. */
  928. x_intercept = wb_thresh / 2;
  929. if (dtc->wb_dirty < x_intercept) {
  930. if (dtc->wb_dirty > x_intercept / 8)
  931. pos_ratio = div_u64(pos_ratio * x_intercept,
  932. dtc->wb_dirty);
  933. else
  934. pos_ratio *= 8;
  935. }
  936. dtc->pos_ratio = pos_ratio;
  937. }
  938. static void wb_update_write_bandwidth(struct bdi_writeback *wb,
  939. unsigned long elapsed,
  940. unsigned long written)
  941. {
  942. const unsigned long period = roundup_pow_of_two(3 * HZ);
  943. unsigned long avg = wb->avg_write_bandwidth;
  944. unsigned long old = wb->write_bandwidth;
  945. u64 bw;
  946. /*
  947. * bw = written * HZ / elapsed
  948. *
  949. * bw * elapsed + write_bandwidth * (period - elapsed)
  950. * write_bandwidth = ---------------------------------------------------
  951. * period
  952. *
  953. * @written may have decreased due to account_page_redirty().
  954. * Avoid underflowing @bw calculation.
  955. */
  956. bw = written - min(written, wb->written_stamp);
  957. bw *= HZ;
  958. if (unlikely(elapsed > period)) {
  959. do_div(bw, elapsed);
  960. avg = bw;
  961. goto out;
  962. }
  963. bw += (u64)wb->write_bandwidth * (period - elapsed);
  964. bw >>= ilog2(period);
  965. /*
  966. * one more level of smoothing, for filtering out sudden spikes
  967. */
  968. if (avg > old && old >= (unsigned long)bw)
  969. avg -= (avg - old) >> 3;
  970. if (avg < old && old <= (unsigned long)bw)
  971. avg += (old - avg) >> 3;
  972. out:
  973. /* keep avg > 0 to guarantee that tot > 0 if there are dirty wbs */
  974. avg = max(avg, 1LU);
  975. if (wb_has_dirty_io(wb)) {
  976. long delta = avg - wb->avg_write_bandwidth;
  977. WARN_ON_ONCE(atomic_long_add_return(delta,
  978. &wb->bdi->tot_write_bandwidth) <= 0);
  979. }
  980. wb->write_bandwidth = bw;
  981. wb->avg_write_bandwidth = avg;
  982. }
  983. static void update_dirty_limit(struct dirty_throttle_control *dtc)
  984. {
  985. struct wb_domain *dom = dtc_dom(dtc);
  986. unsigned long thresh = dtc->thresh;
  987. unsigned long limit = dom->dirty_limit;
  988. /*
  989. * Follow up in one step.
  990. */
  991. if (limit < thresh) {
  992. limit = thresh;
  993. goto update;
  994. }
  995. /*
  996. * Follow down slowly. Use the higher one as the target, because thresh
  997. * may drop below dirty. This is exactly the reason to introduce
  998. * dom->dirty_limit which is guaranteed to lie above the dirty pages.
  999. */
  1000. thresh = max(thresh, dtc->dirty);
  1001. if (limit > thresh) {
  1002. limit -= (limit - thresh) >> 5;
  1003. goto update;
  1004. }
  1005. return;
  1006. update:
  1007. dom->dirty_limit = limit;
  1008. }
  1009. static void domain_update_bandwidth(struct dirty_throttle_control *dtc,
  1010. unsigned long now)
  1011. {
  1012. struct wb_domain *dom = dtc_dom(dtc);
  1013. /*
  1014. * check locklessly first to optimize away locking for the most time
  1015. */
  1016. if (time_before(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL))
  1017. return;
  1018. spin_lock(&dom->lock);
  1019. if (time_after_eq(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL)) {
  1020. update_dirty_limit(dtc);
  1021. dom->dirty_limit_tstamp = now;
  1022. }
  1023. spin_unlock(&dom->lock);
  1024. }
  1025. /*
  1026. * Maintain wb->dirty_ratelimit, the base dirty throttle rate.
  1027. *
  1028. * Normal wb tasks will be curbed at or below it in long term.
  1029. * Obviously it should be around (write_bw / N) when there are N dd tasks.
  1030. */
  1031. static void wb_update_dirty_ratelimit(struct dirty_throttle_control *dtc,
  1032. unsigned long dirtied,
  1033. unsigned long elapsed)
  1034. {
  1035. struct bdi_writeback *wb = dtc->wb;
  1036. unsigned long dirty = dtc->dirty;
  1037. unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh);
  1038. unsigned long limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh);
  1039. unsigned long setpoint = (freerun + limit) / 2;
  1040. unsigned long write_bw = wb->avg_write_bandwidth;
  1041. unsigned long dirty_ratelimit = wb->dirty_ratelimit;
  1042. unsigned long dirty_rate;
  1043. unsigned long task_ratelimit;
  1044. unsigned long balanced_dirty_ratelimit;
  1045. unsigned long step;
  1046. unsigned long x;
  1047. unsigned long shift;
  1048. /*
  1049. * The dirty rate will match the writeout rate in long term, except
  1050. * when dirty pages are truncated by userspace or re-dirtied by FS.
  1051. */
  1052. dirty_rate = (dirtied - wb->dirtied_stamp) * HZ / elapsed;
  1053. /*
  1054. * task_ratelimit reflects each dd's dirty rate for the past 200ms.
  1055. */
  1056. task_ratelimit = (u64)dirty_ratelimit *
  1057. dtc->pos_ratio >> RATELIMIT_CALC_SHIFT;
  1058. task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
  1059. /*
  1060. * A linear estimation of the "balanced" throttle rate. The theory is,
  1061. * if there are N dd tasks, each throttled at task_ratelimit, the wb's
  1062. * dirty_rate will be measured to be (N * task_ratelimit). So the below
  1063. * formula will yield the balanced rate limit (write_bw / N).
  1064. *
  1065. * Note that the expanded form is not a pure rate feedback:
  1066. * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
  1067. * but also takes pos_ratio into account:
  1068. * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
  1069. *
  1070. * (1) is not realistic because pos_ratio also takes part in balancing
  1071. * the dirty rate. Consider the state
  1072. * pos_ratio = 0.5 (3)
  1073. * rate = 2 * (write_bw / N) (4)
  1074. * If (1) is used, it will stuck in that state! Because each dd will
  1075. * be throttled at
  1076. * task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
  1077. * yielding
  1078. * dirty_rate = N * task_ratelimit = write_bw (6)
  1079. * put (6) into (1) we get
  1080. * rate_(i+1) = rate_(i) (7)
  1081. *
  1082. * So we end up using (2) to always keep
  1083. * rate_(i+1) ~= (write_bw / N) (8)
  1084. * regardless of the value of pos_ratio. As long as (8) is satisfied,
  1085. * pos_ratio is able to drive itself to 1.0, which is not only where
  1086. * the dirty count meet the setpoint, but also where the slope of
  1087. * pos_ratio is most flat and hence task_ratelimit is least fluctuated.
  1088. */
  1089. balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
  1090. dirty_rate | 1);
  1091. /*
  1092. * balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw
  1093. */
  1094. if (unlikely(balanced_dirty_ratelimit > write_bw))
  1095. balanced_dirty_ratelimit = write_bw;
  1096. /*
  1097. * We could safely do this and return immediately:
  1098. *
  1099. * wb->dirty_ratelimit = balanced_dirty_ratelimit;
  1100. *
  1101. * However to get a more stable dirty_ratelimit, the below elaborated
  1102. * code makes use of task_ratelimit to filter out singular points and
  1103. * limit the step size.
  1104. *
  1105. * The below code essentially only uses the relative value of
  1106. *
  1107. * task_ratelimit - dirty_ratelimit
  1108. * = (pos_ratio - 1) * dirty_ratelimit
  1109. *
  1110. * which reflects the direction and size of dirty position error.
  1111. */
  1112. /*
  1113. * dirty_ratelimit will follow balanced_dirty_ratelimit iff
  1114. * task_ratelimit is on the same side of dirty_ratelimit, too.
  1115. * For example, when
  1116. * - dirty_ratelimit > balanced_dirty_ratelimit
  1117. * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
  1118. * lowering dirty_ratelimit will help meet both the position and rate
  1119. * control targets. Otherwise, don't update dirty_ratelimit if it will
  1120. * only help meet the rate target. After all, what the users ultimately
  1121. * feel and care are stable dirty rate and small position error.
  1122. *
  1123. * |task_ratelimit - dirty_ratelimit| is used to limit the step size
  1124. * and filter out the singular points of balanced_dirty_ratelimit. Which
  1125. * keeps jumping around randomly and can even leap far away at times
  1126. * due to the small 200ms estimation period of dirty_rate (we want to
  1127. * keep that period small to reduce time lags).
  1128. */
  1129. step = 0;
  1130. /*
  1131. * For strictlimit case, calculations above were based on wb counters
  1132. * and limits (starting from pos_ratio = wb_position_ratio() and up to
  1133. * balanced_dirty_ratelimit = task_ratelimit * write_bw / dirty_rate).
  1134. * Hence, to calculate "step" properly, we have to use wb_dirty as
  1135. * "dirty" and wb_setpoint as "setpoint".
  1136. *
  1137. * We rampup dirty_ratelimit forcibly if wb_dirty is low because
  1138. * it's possible that wb_thresh is close to zero due to inactivity
  1139. * of backing device.
  1140. */
  1141. if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
  1142. dirty = dtc->wb_dirty;
  1143. if (dtc->wb_dirty < 8)
  1144. setpoint = dtc->wb_dirty + 1;
  1145. else
  1146. setpoint = (dtc->wb_thresh + dtc->wb_bg_thresh) / 2;
  1147. }
  1148. if (dirty < setpoint) {
  1149. x = min3(wb->balanced_dirty_ratelimit,
  1150. balanced_dirty_ratelimit, task_ratelimit);
  1151. if (dirty_ratelimit < x)
  1152. step = x - dirty_ratelimit;
  1153. } else {
  1154. x = max3(wb->balanced_dirty_ratelimit,
  1155. balanced_dirty_ratelimit, task_ratelimit);
  1156. if (dirty_ratelimit > x)
  1157. step = dirty_ratelimit - x;
  1158. }
  1159. /*
  1160. * Don't pursue 100% rate matching. It's impossible since the balanced
  1161. * rate itself is constantly fluctuating. So decrease the track speed
  1162. * when it gets close to the target. Helps eliminate pointless tremors.
  1163. */
  1164. shift = dirty_ratelimit / (2 * step + 1);
  1165. if (shift < BITS_PER_LONG)
  1166. step = DIV_ROUND_UP(step >> shift, 8);
  1167. else
  1168. step = 0;
  1169. if (dirty_ratelimit < balanced_dirty_ratelimit)
  1170. dirty_ratelimit += step;
  1171. else
  1172. dirty_ratelimit -= step;
  1173. wb->dirty_ratelimit = max(dirty_ratelimit, 1UL);
  1174. wb->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
  1175. trace_bdi_dirty_ratelimit(wb, dirty_rate, task_ratelimit);
  1176. }
  1177. static void __wb_update_bandwidth(struct dirty_throttle_control *gdtc,
  1178. struct dirty_throttle_control *mdtc,
  1179. unsigned long start_time,
  1180. bool update_ratelimit)
  1181. {
  1182. struct bdi_writeback *wb = gdtc->wb;
  1183. unsigned long now = jiffies;
  1184. unsigned long elapsed = now - wb->bw_time_stamp;
  1185. unsigned long dirtied;
  1186. unsigned long written;
  1187. lockdep_assert_held(&wb->list_lock);
  1188. /*
  1189. * rate-limit, only update once every 200ms.
  1190. */
  1191. if (elapsed < BANDWIDTH_INTERVAL)
  1192. return;
  1193. dirtied = percpu_counter_read(&wb->stat[WB_DIRTIED]);
  1194. written = percpu_counter_read(&wb->stat[WB_WRITTEN]);
  1195. /*
  1196. * Skip quiet periods when disk bandwidth is under-utilized.
  1197. * (at least 1s idle time between two flusher runs)
  1198. */
  1199. if (elapsed > HZ && time_before(wb->bw_time_stamp, start_time))
  1200. goto snapshot;
  1201. if (update_ratelimit) {
  1202. domain_update_bandwidth(gdtc, now);
  1203. wb_update_dirty_ratelimit(gdtc, dirtied, elapsed);
  1204. /*
  1205. * @mdtc is always NULL if !CGROUP_WRITEBACK but the
  1206. * compiler has no way to figure that out. Help it.
  1207. */
  1208. if (IS_ENABLED(CONFIG_CGROUP_WRITEBACK) && mdtc) {
  1209. domain_update_bandwidth(mdtc, now);
  1210. wb_update_dirty_ratelimit(mdtc, dirtied, elapsed);
  1211. }
  1212. }
  1213. wb_update_write_bandwidth(wb, elapsed, written);
  1214. snapshot:
  1215. wb->dirtied_stamp = dirtied;
  1216. wb->written_stamp = written;
  1217. wb->bw_time_stamp = now;
  1218. }
  1219. void wb_update_bandwidth(struct bdi_writeback *wb, unsigned long start_time)
  1220. {
  1221. struct dirty_throttle_control gdtc = { GDTC_INIT(wb) };
  1222. __wb_update_bandwidth(&gdtc, NULL, start_time, false);
  1223. }
  1224. /*
  1225. * After a task dirtied this many pages, balance_dirty_pages_ratelimited()
  1226. * will look to see if it needs to start dirty throttling.
  1227. *
  1228. * If dirty_poll_interval is too low, big NUMA machines will call the expensive
  1229. * global_zone_page_state() too often. So scale it near-sqrt to the safety margin
  1230. * (the number of pages we may dirty without exceeding the dirty limits).
  1231. */
  1232. static unsigned long dirty_poll_interval(unsigned long dirty,
  1233. unsigned long thresh)
  1234. {
  1235. if (thresh > dirty)
  1236. return 1UL << (ilog2(thresh - dirty) >> 1);
  1237. return 1;
  1238. }
  1239. static unsigned long wb_max_pause(struct bdi_writeback *wb,
  1240. unsigned long wb_dirty)
  1241. {
  1242. unsigned long bw = wb->avg_write_bandwidth;
  1243. unsigned long t;
  1244. /*
  1245. * Limit pause time for small memory systems. If sleeping for too long
  1246. * time, a small pool of dirty/writeback pages may go empty and disk go
  1247. * idle.
  1248. *
  1249. * 8 serves as the safety ratio.
  1250. */
  1251. t = wb_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
  1252. t++;
  1253. return min_t(unsigned long, t, MAX_PAUSE);
  1254. }
  1255. static long wb_min_pause(struct bdi_writeback *wb,
  1256. long max_pause,
  1257. unsigned long task_ratelimit,
  1258. unsigned long dirty_ratelimit,
  1259. int *nr_dirtied_pause)
  1260. {
  1261. long hi = ilog2(wb->avg_write_bandwidth);
  1262. long lo = ilog2(wb->dirty_ratelimit);
  1263. long t; /* target pause */
  1264. long pause; /* estimated next pause */
  1265. int pages; /* target nr_dirtied_pause */
  1266. /* target for 10ms pause on 1-dd case */
  1267. t = max(1, HZ / 100);
  1268. /*
  1269. * Scale up pause time for concurrent dirtiers in order to reduce CPU
  1270. * overheads.
  1271. *
  1272. * (N * 10ms) on 2^N concurrent tasks.
  1273. */
  1274. if (hi > lo)
  1275. t += (hi - lo) * (10 * HZ) / 1024;
  1276. /*
  1277. * This is a bit convoluted. We try to base the next nr_dirtied_pause
  1278. * on the much more stable dirty_ratelimit. However the next pause time
  1279. * will be computed based on task_ratelimit and the two rate limits may
  1280. * depart considerably at some time. Especially if task_ratelimit goes
  1281. * below dirty_ratelimit/2 and the target pause is max_pause, the next
  1282. * pause time will be max_pause*2 _trimmed down_ to max_pause. As a
  1283. * result task_ratelimit won't be executed faithfully, which could
  1284. * eventually bring down dirty_ratelimit.
  1285. *
  1286. * We apply two rules to fix it up:
  1287. * 1) try to estimate the next pause time and if necessary, use a lower
  1288. * nr_dirtied_pause so as not to exceed max_pause. When this happens,
  1289. * nr_dirtied_pause will be "dancing" with task_ratelimit.
  1290. * 2) limit the target pause time to max_pause/2, so that the normal
  1291. * small fluctuations of task_ratelimit won't trigger rule (1) and
  1292. * nr_dirtied_pause will remain as stable as dirty_ratelimit.
  1293. */
  1294. t = min(t, 1 + max_pause / 2);
  1295. pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
  1296. /*
  1297. * Tiny nr_dirtied_pause is found to hurt I/O performance in the test
  1298. * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}.
  1299. * When the 16 consecutive reads are often interrupted by some dirty
  1300. * throttling pause during the async writes, cfq will go into idles
  1301. * (deadline is fine). So push nr_dirtied_pause as high as possible
  1302. * until reaches DIRTY_POLL_THRESH=32 pages.
  1303. */
  1304. if (pages < DIRTY_POLL_THRESH) {
  1305. t = max_pause;
  1306. pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
  1307. if (pages > DIRTY_POLL_THRESH) {
  1308. pages = DIRTY_POLL_THRESH;
  1309. t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
  1310. }
  1311. }
  1312. pause = HZ * pages / (task_ratelimit + 1);
  1313. if (pause > max_pause) {
  1314. t = max_pause;
  1315. pages = task_ratelimit * t / roundup_pow_of_two(HZ);
  1316. }
  1317. *nr_dirtied_pause = pages;
  1318. /*
  1319. * The minimal pause time will normally be half the target pause time.
  1320. */
  1321. return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
  1322. }
  1323. static inline void wb_dirty_limits(struct dirty_throttle_control *dtc)
  1324. {
  1325. struct bdi_writeback *wb = dtc->wb;
  1326. unsigned long wb_reclaimable;
  1327. /*
  1328. * wb_thresh is not treated as some limiting factor as
  1329. * dirty_thresh, due to reasons
  1330. * - in JBOD setup, wb_thresh can fluctuate a lot
  1331. * - in a system with HDD and USB key, the USB key may somehow
  1332. * go into state (wb_dirty >> wb_thresh) either because
  1333. * wb_dirty starts high, or because wb_thresh drops low.
  1334. * In this case we don't want to hard throttle the USB key
  1335. * dirtiers for 100 seconds until wb_dirty drops under
  1336. * wb_thresh. Instead the auxiliary wb control line in
  1337. * wb_position_ratio() will let the dirtier task progress
  1338. * at some rate <= (write_bw / 2) for bringing down wb_dirty.
  1339. */
  1340. dtc->wb_thresh = __wb_calc_thresh(dtc);
  1341. dtc->wb_bg_thresh = dtc->thresh ?
  1342. div_u64((u64)dtc->wb_thresh * dtc->bg_thresh, dtc->thresh) : 0;
  1343. /*
  1344. * In order to avoid the stacked BDI deadlock we need
  1345. * to ensure we accurately count the 'dirty' pages when
  1346. * the threshold is low.
  1347. *
  1348. * Otherwise it would be possible to get thresh+n pages
  1349. * reported dirty, even though there are thresh-m pages
  1350. * actually dirty; with m+n sitting in the percpu
  1351. * deltas.
  1352. */
  1353. if (dtc->wb_thresh < 2 * wb_stat_error()) {
  1354. wb_reclaimable = wb_stat_sum(wb, WB_RECLAIMABLE);
  1355. dtc->wb_dirty = wb_reclaimable + wb_stat_sum(wb, WB_WRITEBACK);
  1356. } else {
  1357. wb_reclaimable = wb_stat(wb, WB_RECLAIMABLE);
  1358. dtc->wb_dirty = wb_reclaimable + wb_stat(wb, WB_WRITEBACK);
  1359. }
  1360. }
  1361. /*
  1362. * balance_dirty_pages() must be called by processes which are generating dirty
  1363. * data. It looks at the number of dirty pages in the machine and will force
  1364. * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
  1365. * If we're over `background_thresh' then the writeback threads are woken to
  1366. * perform some writeout.
  1367. */
  1368. static void balance_dirty_pages(struct bdi_writeback *wb,
  1369. unsigned long pages_dirtied)
  1370. {
  1371. struct dirty_throttle_control gdtc_stor = { GDTC_INIT(wb) };
  1372. struct dirty_throttle_control mdtc_stor = { MDTC_INIT(wb, &gdtc_stor) };
  1373. struct dirty_throttle_control * const gdtc = &gdtc_stor;
  1374. struct dirty_throttle_control * const mdtc = mdtc_valid(&mdtc_stor) ?
  1375. &mdtc_stor : NULL;
  1376. struct dirty_throttle_control *sdtc;
  1377. unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */
  1378. long period;
  1379. long pause;
  1380. long max_pause;
  1381. long min_pause;
  1382. int nr_dirtied_pause;
  1383. bool dirty_exceeded = false;
  1384. unsigned long task_ratelimit;
  1385. unsigned long dirty_ratelimit;
  1386. struct backing_dev_info *bdi = wb->bdi;
  1387. bool strictlimit = bdi->capabilities & BDI_CAP_STRICTLIMIT;
  1388. unsigned long start_time = jiffies;
  1389. for (;;) {
  1390. unsigned long now = jiffies;
  1391. unsigned long dirty, thresh, bg_thresh;
  1392. unsigned long m_dirty = 0; /* stop bogus uninit warnings */
  1393. unsigned long m_thresh = 0;
  1394. unsigned long m_bg_thresh = 0;
  1395. /*
  1396. * Unstable writes are a feature of certain networked
  1397. * filesystems (i.e. NFS) in which data may have been
  1398. * written to the server's write cache, but has not yet
  1399. * been flushed to permanent storage.
  1400. */
  1401. nr_reclaimable = global_node_page_state(NR_FILE_DIRTY) +
  1402. global_node_page_state(NR_UNSTABLE_NFS);
  1403. gdtc->avail = global_dirtyable_memory();
  1404. gdtc->dirty = nr_reclaimable + global_node_page_state(NR_WRITEBACK);
  1405. domain_dirty_limits(gdtc);
  1406. if (unlikely(strictlimit)) {
  1407. wb_dirty_limits(gdtc);
  1408. dirty = gdtc->wb_dirty;
  1409. thresh = gdtc->wb_thresh;
  1410. bg_thresh = gdtc->wb_bg_thresh;
  1411. } else {
  1412. dirty = gdtc->dirty;
  1413. thresh = gdtc->thresh;
  1414. bg_thresh = gdtc->bg_thresh;
  1415. }
  1416. if (mdtc) {
  1417. unsigned long filepages, headroom, writeback;
  1418. /*
  1419. * If @wb belongs to !root memcg, repeat the same
  1420. * basic calculations for the memcg domain.
  1421. */
  1422. mem_cgroup_wb_stats(wb, &filepages, &headroom,
  1423. &mdtc->dirty, &writeback);
  1424. mdtc->dirty += writeback;
  1425. mdtc_calc_avail(mdtc, filepages, headroom);
  1426. domain_dirty_limits(mdtc);
  1427. if (unlikely(strictlimit)) {
  1428. wb_dirty_limits(mdtc);
  1429. m_dirty = mdtc->wb_dirty;
  1430. m_thresh = mdtc->wb_thresh;
  1431. m_bg_thresh = mdtc->wb_bg_thresh;
  1432. } else {
  1433. m_dirty = mdtc->dirty;
  1434. m_thresh = mdtc->thresh;
  1435. m_bg_thresh = mdtc->bg_thresh;
  1436. }
  1437. }
  1438. /*
  1439. * Throttle it only when the background writeback cannot
  1440. * catch-up. This avoids (excessively) small writeouts
  1441. * when the wb limits are ramping up in case of !strictlimit.
  1442. *
  1443. * In strictlimit case make decision based on the wb counters
  1444. * and limits. Small writeouts when the wb limits are ramping
  1445. * up are the price we consciously pay for strictlimit-ing.
  1446. *
  1447. * If memcg domain is in effect, @dirty should be under
  1448. * both global and memcg freerun ceilings.
  1449. */
  1450. if (dirty <= dirty_freerun_ceiling(thresh, bg_thresh) &&
  1451. (!mdtc ||
  1452. m_dirty <= dirty_freerun_ceiling(m_thresh, m_bg_thresh))) {
  1453. unsigned long intv = dirty_poll_interval(dirty, thresh);
  1454. unsigned long m_intv = ULONG_MAX;
  1455. current->dirty_paused_when = now;
  1456. current->nr_dirtied = 0;
  1457. if (mdtc)
  1458. m_intv = dirty_poll_interval(m_dirty, m_thresh);
  1459. current->nr_dirtied_pause = min(intv, m_intv);
  1460. break;
  1461. }
  1462. if (unlikely(!writeback_in_progress(wb)))
  1463. wb_start_background_writeback(wb);
  1464. /*
  1465. * Calculate global domain's pos_ratio and select the
  1466. * global dtc by default.
  1467. */
  1468. if (!strictlimit)
  1469. wb_dirty_limits(gdtc);
  1470. dirty_exceeded = (gdtc->wb_dirty > gdtc->wb_thresh) &&
  1471. ((gdtc->dirty > gdtc->thresh) || strictlimit);
  1472. wb_position_ratio(gdtc);
  1473. sdtc = gdtc;
  1474. if (mdtc) {
  1475. /*
  1476. * If memcg domain is in effect, calculate its
  1477. * pos_ratio. @wb should satisfy constraints from
  1478. * both global and memcg domains. Choose the one
  1479. * w/ lower pos_ratio.
  1480. */
  1481. if (!strictlimit)
  1482. wb_dirty_limits(mdtc);
  1483. dirty_exceeded |= (mdtc->wb_dirty > mdtc->wb_thresh) &&
  1484. ((mdtc->dirty > mdtc->thresh) || strictlimit);
  1485. wb_position_ratio(mdtc);
  1486. if (mdtc->pos_ratio < gdtc->pos_ratio)
  1487. sdtc = mdtc;
  1488. }
  1489. if (dirty_exceeded && !wb->dirty_exceeded)
  1490. wb->dirty_exceeded = 1;
  1491. if (time_is_before_jiffies(wb->bw_time_stamp +
  1492. BANDWIDTH_INTERVAL)) {
  1493. spin_lock(&wb->list_lock);
  1494. __wb_update_bandwidth(gdtc, mdtc, start_time, true);
  1495. spin_unlock(&wb->list_lock);
  1496. }
  1497. /* throttle according to the chosen dtc */
  1498. dirty_ratelimit = wb->dirty_ratelimit;
  1499. task_ratelimit = ((u64)dirty_ratelimit * sdtc->pos_ratio) >>
  1500. RATELIMIT_CALC_SHIFT;
  1501. max_pause = wb_max_pause(wb, sdtc->wb_dirty);
  1502. min_pause = wb_min_pause(wb, max_pause,
  1503. task_ratelimit, dirty_ratelimit,
  1504. &nr_dirtied_pause);
  1505. if (unlikely(task_ratelimit == 0)) {
  1506. period = max_pause;
  1507. pause = max_pause;
  1508. goto pause;
  1509. }
  1510. period = HZ * pages_dirtied / task_ratelimit;
  1511. pause = period;
  1512. if (current->dirty_paused_when)
  1513. pause -= now - current->dirty_paused_when;
  1514. /*
  1515. * For less than 1s think time (ext3/4 may block the dirtier
  1516. * for up to 800ms from time to time on 1-HDD; so does xfs,
  1517. * however at much less frequency), try to compensate it in
  1518. * future periods by updating the virtual time; otherwise just
  1519. * do a reset, as it may be a light dirtier.
  1520. */
  1521. if (pause < min_pause) {
  1522. trace_balance_dirty_pages(wb,
  1523. sdtc->thresh,
  1524. sdtc->bg_thresh,
  1525. sdtc->dirty,
  1526. sdtc->wb_thresh,
  1527. sdtc->wb_dirty,
  1528. dirty_ratelimit,
  1529. task_ratelimit,
  1530. pages_dirtied,
  1531. period,
  1532. min(pause, 0L),
  1533. start_time);
  1534. if (pause < -HZ) {
  1535. current->dirty_paused_when = now;
  1536. current->nr_dirtied = 0;
  1537. } else if (period) {
  1538. current->dirty_paused_when += period;
  1539. current->nr_dirtied = 0;
  1540. } else if (current->nr_dirtied_pause <= pages_dirtied)
  1541. current->nr_dirtied_pause += pages_dirtied;
  1542. break;
  1543. }
  1544. if (unlikely(pause > max_pause)) {
  1545. /* for occasional dropped task_ratelimit */
  1546. now += min(pause - max_pause, max_pause);
  1547. pause = max_pause;
  1548. }
  1549. pause:
  1550. trace_balance_dirty_pages(wb,
  1551. sdtc->thresh,
  1552. sdtc->bg_thresh,
  1553. sdtc->dirty,
  1554. sdtc->wb_thresh,
  1555. sdtc->wb_dirty,
  1556. dirty_ratelimit,
  1557. task_ratelimit,
  1558. pages_dirtied,
  1559. period,
  1560. pause,
  1561. start_time);
  1562. __set_current_state(TASK_KILLABLE);
  1563. wb->dirty_sleep = now;
  1564. io_schedule_timeout(pause);
  1565. current->dirty_paused_when = now + pause;
  1566. current->nr_dirtied = 0;
  1567. current->nr_dirtied_pause = nr_dirtied_pause;
  1568. /*
  1569. * This is typically equal to (dirty < thresh) and can also
  1570. * keep "1000+ dd on a slow USB stick" under control.
  1571. */
  1572. if (task_ratelimit)
  1573. break;
  1574. /*
  1575. * In the case of an unresponding NFS server and the NFS dirty
  1576. * pages exceeds dirty_thresh, give the other good wb's a pipe
  1577. * to go through, so that tasks on them still remain responsive.
  1578. *
  1579. * In theory 1 page is enough to keep the consumer-producer
  1580. * pipe going: the flusher cleans 1 page => the task dirties 1
  1581. * more page. However wb_dirty has accounting errors. So use
  1582. * the larger and more IO friendly wb_stat_error.
  1583. */
  1584. if (sdtc->wb_dirty <= wb_stat_error())
  1585. break;
  1586. if (fatal_signal_pending(current))
  1587. break;
  1588. }
  1589. if (!dirty_exceeded && wb->dirty_exceeded)
  1590. wb->dirty_exceeded = 0;
  1591. if (writeback_in_progress(wb))
  1592. return;
  1593. /*
  1594. * In laptop mode, we wait until hitting the higher threshold before
  1595. * starting background writeout, and then write out all the way down
  1596. * to the lower threshold. So slow writers cause minimal disk activity.
  1597. *
  1598. * In normal mode, we start background writeout at the lower
  1599. * background_thresh, to keep the amount of dirty memory low.
  1600. */
  1601. if (laptop_mode)
  1602. return;
  1603. if (nr_reclaimable > gdtc->bg_thresh)
  1604. wb_start_background_writeback(wb);
  1605. }
  1606. static DEFINE_PER_CPU(int, bdp_ratelimits);
  1607. /*
  1608. * Normal tasks are throttled by
  1609. * loop {
  1610. * dirty tsk->nr_dirtied_pause pages;
  1611. * take a snap in balance_dirty_pages();
  1612. * }
  1613. * However there is a worst case. If every task exit immediately when dirtied
  1614. * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
  1615. * called to throttle the page dirties. The solution is to save the not yet
  1616. * throttled page dirties in dirty_throttle_leaks on task exit and charge them
  1617. * randomly into the running tasks. This works well for the above worst case,
  1618. * as the new task will pick up and accumulate the old task's leaked dirty
  1619. * count and eventually get throttled.
  1620. */
  1621. DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
  1622. /**
  1623. * balance_dirty_pages_ratelimited - balance dirty memory state
  1624. * @mapping: address_space which was dirtied
  1625. *
  1626. * Processes which are dirtying memory should call in here once for each page
  1627. * which was newly dirtied. The function will periodically check the system's
  1628. * dirty state and will initiate writeback if needed.
  1629. *
  1630. * On really big machines, get_writeback_state is expensive, so try to avoid
  1631. * calling it too often (ratelimiting). But once we're over the dirty memory
  1632. * limit we decrease the ratelimiting by a lot, to prevent individual processes
  1633. * from overshooting the limit by (ratelimit_pages) each.
  1634. */
  1635. void balance_dirty_pages_ratelimited(struct address_space *mapping)
  1636. {
  1637. struct inode *inode = mapping->host;
  1638. struct backing_dev_info *bdi = inode_to_bdi(inode);
  1639. struct bdi_writeback *wb = NULL;
  1640. int ratelimit;
  1641. int *p;
  1642. if (!bdi_cap_account_dirty(bdi))
  1643. return;
  1644. if (inode_cgwb_enabled(inode))
  1645. wb = wb_get_create_current(bdi, GFP_KERNEL);
  1646. if (!wb)
  1647. wb = &bdi->wb;
  1648. ratelimit = current->nr_dirtied_pause;
  1649. if (wb->dirty_exceeded)
  1650. ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
  1651. preempt_disable();
  1652. /*
  1653. * This prevents one CPU to accumulate too many dirtied pages without
  1654. * calling into balance_dirty_pages(), which can happen when there are
  1655. * 1000+ tasks, all of them start dirtying pages at exactly the same
  1656. * time, hence all honoured too large initial task->nr_dirtied_pause.
  1657. */
  1658. p = this_cpu_ptr(&bdp_ratelimits);
  1659. if (unlikely(current->nr_dirtied >= ratelimit))
  1660. *p = 0;
  1661. else if (unlikely(*p >= ratelimit_pages)) {
  1662. *p = 0;
  1663. ratelimit = 0;
  1664. }
  1665. /*
  1666. * Pick up the dirtied pages by the exited tasks. This avoids lots of
  1667. * short-lived tasks (eg. gcc invocations in a kernel build) escaping
  1668. * the dirty throttling and livelock other long-run dirtiers.
  1669. */
  1670. p = this_cpu_ptr(&dirty_throttle_leaks);
  1671. if (*p > 0 && current->nr_dirtied < ratelimit) {
  1672. unsigned long nr_pages_dirtied;
  1673. nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
  1674. *p -= nr_pages_dirtied;
  1675. current->nr_dirtied += nr_pages_dirtied;
  1676. }
  1677. preempt_enable();
  1678. if (unlikely(current->nr_dirtied >= ratelimit))
  1679. balance_dirty_pages(wb, current->nr_dirtied);
  1680. wb_put(wb);
  1681. }
  1682. EXPORT_SYMBOL(balance_dirty_pages_ratelimited);
  1683. /**
  1684. * wb_over_bg_thresh - does @wb need to be written back?
  1685. * @wb: bdi_writeback of interest
  1686. *
  1687. * Determines whether background writeback should keep writing @wb or it's
  1688. * clean enough. Returns %true if writeback should continue.
  1689. */
  1690. bool wb_over_bg_thresh(struct bdi_writeback *wb)
  1691. {
  1692. struct dirty_throttle_control gdtc_stor = { GDTC_INIT(wb) };
  1693. struct dirty_throttle_control mdtc_stor = { MDTC_INIT(wb, &gdtc_stor) };
  1694. struct dirty_throttle_control * const gdtc = &gdtc_stor;
  1695. struct dirty_throttle_control * const mdtc = mdtc_valid(&mdtc_stor) ?
  1696. &mdtc_stor : NULL;
  1697. /*
  1698. * Similar to balance_dirty_pages() but ignores pages being written
  1699. * as we're trying to decide whether to put more under writeback.
  1700. */
  1701. gdtc->avail = global_dirtyable_memory();
  1702. gdtc->dirty = global_node_page_state(NR_FILE_DIRTY) +
  1703. global_node_page_state(NR_UNSTABLE_NFS);
  1704. domain_dirty_limits(gdtc);
  1705. if (gdtc->dirty > gdtc->bg_thresh)
  1706. return true;
  1707. if (wb_stat(wb, WB_RECLAIMABLE) >
  1708. wb_calc_thresh(gdtc->wb, gdtc->bg_thresh))
  1709. return true;
  1710. if (mdtc) {
  1711. unsigned long filepages, headroom, writeback;
  1712. mem_cgroup_wb_stats(wb, &filepages, &headroom, &mdtc->dirty,
  1713. &writeback);
  1714. mdtc_calc_avail(mdtc, filepages, headroom);
  1715. domain_dirty_limits(mdtc); /* ditto, ignore writeback */
  1716. if (mdtc->dirty > mdtc->bg_thresh)
  1717. return true;
  1718. if (wb_stat(wb, WB_RECLAIMABLE) >
  1719. wb_calc_thresh(mdtc->wb, mdtc->bg_thresh))
  1720. return true;
  1721. }
  1722. return false;
  1723. }
  1724. /*
  1725. * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
  1726. */
  1727. int dirty_writeback_centisecs_handler(struct ctl_table *table, int write,
  1728. void __user *buffer, size_t *length, loff_t *ppos)
  1729. {
  1730. unsigned int old_interval = dirty_writeback_interval;
  1731. int ret;
  1732. ret = proc_dointvec(table, write, buffer, length, ppos);
  1733. /*
  1734. * Writing 0 to dirty_writeback_interval will disable periodic writeback
  1735. * and a different non-zero value will wakeup the writeback threads.
  1736. * wb_wakeup_delayed() would be more appropriate, but it's a pain to
  1737. * iterate over all bdis and wbs.
  1738. * The reason we do this is to make the change take effect immediately.
  1739. */
  1740. if (!ret && write && dirty_writeback_interval &&
  1741. dirty_writeback_interval != old_interval)
  1742. wakeup_flusher_threads(WB_REASON_PERIODIC);
  1743. return ret;
  1744. }
  1745. #ifdef CONFIG_BLOCK
  1746. void laptop_mode_timer_fn(struct timer_list *t)
  1747. {
  1748. struct backing_dev_info *backing_dev_info =
  1749. from_timer(backing_dev_info, t, laptop_mode_wb_timer);
  1750. wakeup_flusher_threads_bdi(backing_dev_info, WB_REASON_LAPTOP_TIMER);
  1751. }
  1752. /*
  1753. * We've spun up the disk and we're in laptop mode: schedule writeback
  1754. * of all dirty data a few seconds from now. If the flush is already scheduled
  1755. * then push it back - the user is still using the disk.
  1756. */
  1757. void laptop_io_completion(struct backing_dev_info *info)
  1758. {
  1759. mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
  1760. }
  1761. /*
  1762. * We're in laptop mode and we've just synced. The sync's writes will have
  1763. * caused another writeback to be scheduled by laptop_io_completion.
  1764. * Nothing needs to be written back anymore, so we unschedule the writeback.
  1765. */
  1766. void laptop_sync_completion(void)
  1767. {
  1768. struct backing_dev_info *bdi;
  1769. rcu_read_lock();
  1770. list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
  1771. del_timer(&bdi->laptop_mode_wb_timer);
  1772. rcu_read_unlock();
  1773. }
  1774. #endif
  1775. /*
  1776. * If ratelimit_pages is too high then we can get into dirty-data overload
  1777. * if a large number of processes all perform writes at the same time.
  1778. * If it is too low then SMP machines will call the (expensive)
  1779. * get_writeback_state too often.
  1780. *
  1781. * Here we set ratelimit_pages to a level which ensures that when all CPUs are
  1782. * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
  1783. * thresholds.
  1784. */
  1785. void writeback_set_ratelimit(void)
  1786. {
  1787. struct wb_domain *dom = &global_wb_domain;
  1788. unsigned long background_thresh;
  1789. unsigned long dirty_thresh;
  1790. global_dirty_limits(&background_thresh, &dirty_thresh);
  1791. dom->dirty_limit = dirty_thresh;
  1792. ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
  1793. if (ratelimit_pages < 16)
  1794. ratelimit_pages = 16;
  1795. }
  1796. static int page_writeback_cpu_online(unsigned int cpu)
  1797. {
  1798. writeback_set_ratelimit();
  1799. return 0;
  1800. }
  1801. /*
  1802. * Called early on to tune the page writeback dirty limits.
  1803. *
  1804. * We used to scale dirty pages according to how total memory
  1805. * related to pages that could be allocated for buffers (by
  1806. * comparing nr_free_buffer_pages() to vm_total_pages.
  1807. *
  1808. * However, that was when we used "dirty_ratio" to scale with
  1809. * all memory, and we don't do that any more. "dirty_ratio"
  1810. * is now applied to total non-HIGHPAGE memory (by subtracting
  1811. * totalhigh_pages from vm_total_pages), and as such we can't
  1812. * get into the old insane situation any more where we had
  1813. * large amounts of dirty pages compared to a small amount of
  1814. * non-HIGHMEM memory.
  1815. *
  1816. * But we might still want to scale the dirty_ratio by how
  1817. * much memory the box has..
  1818. */
  1819. void __init page_writeback_init(void)
  1820. {
  1821. BUG_ON(wb_domain_init(&global_wb_domain, GFP_KERNEL));
  1822. cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "mm/writeback:online",
  1823. page_writeback_cpu_online, NULL);
  1824. cpuhp_setup_state(CPUHP_MM_WRITEBACK_DEAD, "mm/writeback:dead", NULL,
  1825. page_writeback_cpu_online);
  1826. }
  1827. /**
  1828. * tag_pages_for_writeback - tag pages to be written by write_cache_pages
  1829. * @mapping: address space structure to write
  1830. * @start: starting page index
  1831. * @end: ending page index (inclusive)
  1832. *
  1833. * This function scans the page range from @start to @end (inclusive) and tags
  1834. * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
  1835. * that write_cache_pages (or whoever calls this function) will then use
  1836. * TOWRITE tag to identify pages eligible for writeback. This mechanism is
  1837. * used to avoid livelocking of writeback by a process steadily creating new
  1838. * dirty pages in the file (thus it is important for this function to be quick
  1839. * so that it can tag pages faster than a dirtying process can create them).
  1840. */
  1841. /*
  1842. * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce the i_pages lock
  1843. * latency.
  1844. */
  1845. void tag_pages_for_writeback(struct address_space *mapping,
  1846. pgoff_t start, pgoff_t end)
  1847. {
  1848. #define WRITEBACK_TAG_BATCH 4096
  1849. unsigned long tagged = 0;
  1850. struct radix_tree_iter iter;
  1851. void **slot;
  1852. xa_lock_irq(&mapping->i_pages);
  1853. radix_tree_for_each_tagged(slot, &mapping->i_pages, &iter, start,
  1854. PAGECACHE_TAG_DIRTY) {
  1855. if (iter.index > end)
  1856. break;
  1857. radix_tree_iter_tag_set(&mapping->i_pages, &iter,
  1858. PAGECACHE_TAG_TOWRITE);
  1859. tagged++;
  1860. if ((tagged % WRITEBACK_TAG_BATCH) != 0)
  1861. continue;
  1862. slot = radix_tree_iter_resume(slot, &iter);
  1863. xa_unlock_irq(&mapping->i_pages);
  1864. cond_resched();
  1865. xa_lock_irq(&mapping->i_pages);
  1866. }
  1867. xa_unlock_irq(&mapping->i_pages);
  1868. }
  1869. EXPORT_SYMBOL(tag_pages_for_writeback);
  1870. /**
  1871. * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
  1872. * @mapping: address space structure to write
  1873. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1874. * @writepage: function called for each page
  1875. * @data: data passed to writepage function
  1876. *
  1877. * If a page is already under I/O, write_cache_pages() skips it, even
  1878. * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
  1879. * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
  1880. * and msync() need to guarantee that all the data which was dirty at the time
  1881. * the call was made get new I/O started against them. If wbc->sync_mode is
  1882. * WB_SYNC_ALL then we were called for data integrity and we must wait for
  1883. * existing IO to complete.
  1884. *
  1885. * To avoid livelocks (when other process dirties new pages), we first tag
  1886. * pages which should be written back with TOWRITE tag and only then start
  1887. * writing them. For data-integrity sync we have to be careful so that we do
  1888. * not miss some pages (e.g., because some other process has cleared TOWRITE
  1889. * tag we set). The rule we follow is that TOWRITE tag can be cleared only
  1890. * by the process clearing the DIRTY tag (and submitting the page for IO).
  1891. *
  1892. * To avoid deadlocks between range_cyclic writeback and callers that hold
  1893. * pages in PageWriteback to aggregate IO until write_cache_pages() returns,
  1894. * we do not loop back to the start of the file. Doing so causes a page
  1895. * lock/page writeback access order inversion - we should only ever lock
  1896. * multiple pages in ascending page->index order, and looping back to the start
  1897. * of the file violates that rule and causes deadlocks.
  1898. */
  1899. int write_cache_pages(struct address_space *mapping,
  1900. struct writeback_control *wbc, writepage_t writepage,
  1901. void *data)
  1902. {
  1903. int ret = 0;
  1904. int done = 0;
  1905. int error;
  1906. struct pagevec pvec;
  1907. int nr_pages;
  1908. pgoff_t uninitialized_var(writeback_index);
  1909. pgoff_t index;
  1910. pgoff_t end; /* Inclusive */
  1911. pgoff_t done_index;
  1912. int range_whole = 0;
  1913. int tag;
  1914. pagevec_init(&pvec);
  1915. if (wbc->range_cyclic) {
  1916. writeback_index = mapping->writeback_index; /* prev offset */
  1917. index = writeback_index;
  1918. end = -1;
  1919. } else {
  1920. index = wbc->range_start >> PAGE_SHIFT;
  1921. end = wbc->range_end >> PAGE_SHIFT;
  1922. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  1923. range_whole = 1;
  1924. }
  1925. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1926. tag = PAGECACHE_TAG_TOWRITE;
  1927. else
  1928. tag = PAGECACHE_TAG_DIRTY;
  1929. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1930. tag_pages_for_writeback(mapping, index, end);
  1931. done_index = index;
  1932. while (!done && (index <= end)) {
  1933. int i;
  1934. nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
  1935. tag);
  1936. if (nr_pages == 0)
  1937. break;
  1938. for (i = 0; i < nr_pages; i++) {
  1939. struct page *page = pvec.pages[i];
  1940. done_index = page->index;
  1941. lock_page(page);
  1942. /*
  1943. * Page truncated or invalidated. We can freely skip it
  1944. * then, even for data integrity operations: the page
  1945. * has disappeared concurrently, so there could be no
  1946. * real expectation of this data interity operation
  1947. * even if there is now a new, dirty page at the same
  1948. * pagecache address.
  1949. */
  1950. if (unlikely(page->mapping != mapping)) {
  1951. continue_unlock:
  1952. unlock_page(page);
  1953. continue;
  1954. }
  1955. if (!PageDirty(page)) {
  1956. /* someone wrote it for us */
  1957. goto continue_unlock;
  1958. }
  1959. if (PageWriteback(page)) {
  1960. if (wbc->sync_mode != WB_SYNC_NONE)
  1961. wait_on_page_writeback(page);
  1962. else
  1963. goto continue_unlock;
  1964. }
  1965. BUG_ON(PageWriteback(page));
  1966. if (!clear_page_dirty_for_io(page))
  1967. goto continue_unlock;
  1968. trace_wbc_writepage(wbc, inode_to_bdi(mapping->host));
  1969. error = (*writepage)(page, wbc, data);
  1970. if (unlikely(error)) {
  1971. /*
  1972. * Handle errors according to the type of
  1973. * writeback. There's no need to continue for
  1974. * background writeback. Just push done_index
  1975. * past this page so media errors won't choke
  1976. * writeout for the entire file. For integrity
  1977. * writeback, we must process the entire dirty
  1978. * set regardless of errors because the fs may
  1979. * still have state to clear for each page. In
  1980. * that case we continue processing and return
  1981. * the first error.
  1982. */
  1983. if (error == AOP_WRITEPAGE_ACTIVATE) {
  1984. unlock_page(page);
  1985. error = 0;
  1986. } else if (wbc->sync_mode != WB_SYNC_ALL) {
  1987. ret = error;
  1988. done_index = page->index + 1;
  1989. done = 1;
  1990. break;
  1991. }
  1992. if (!ret)
  1993. ret = error;
  1994. }
  1995. /*
  1996. * We stop writing back only if we are not doing
  1997. * integrity sync. In case of integrity sync we have to
  1998. * keep going until we have written all the pages
  1999. * we tagged for writeback prior to entering this loop.
  2000. */
  2001. if (--wbc->nr_to_write <= 0 &&
  2002. wbc->sync_mode == WB_SYNC_NONE) {
  2003. done = 1;
  2004. break;
  2005. }
  2006. }
  2007. pagevec_release(&pvec);
  2008. cond_resched();
  2009. }
  2010. /*
  2011. * If we hit the last page and there is more work to be done: wrap
  2012. * back the index back to the start of the file for the next
  2013. * time we are called.
  2014. */
  2015. if (wbc->range_cyclic && !done)
  2016. done_index = 0;
  2017. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  2018. mapping->writeback_index = done_index;
  2019. return ret;
  2020. }
  2021. EXPORT_SYMBOL(write_cache_pages);
  2022. /*
  2023. * Function used by generic_writepages to call the real writepage
  2024. * function and set the mapping flags on error
  2025. */
  2026. static int __writepage(struct page *page, struct writeback_control *wbc,
  2027. void *data)
  2028. {
  2029. struct address_space *mapping = data;
  2030. int ret = mapping->a_ops->writepage(page, wbc);
  2031. mapping_set_error(mapping, ret);
  2032. return ret;
  2033. }
  2034. /**
  2035. * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
  2036. * @mapping: address space structure to write
  2037. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  2038. *
  2039. * This is a library function, which implements the writepages()
  2040. * address_space_operation.
  2041. */
  2042. int generic_writepages(struct address_space *mapping,
  2043. struct writeback_control *wbc)
  2044. {
  2045. struct blk_plug plug;
  2046. int ret;
  2047. /* deal with chardevs and other special file */
  2048. if (!mapping->a_ops->writepage)
  2049. return 0;
  2050. blk_start_plug(&plug);
  2051. ret = write_cache_pages(mapping, wbc, __writepage, mapping);
  2052. blk_finish_plug(&plug);
  2053. return ret;
  2054. }
  2055. EXPORT_SYMBOL(generic_writepages);
  2056. int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
  2057. {
  2058. int ret;
  2059. if (wbc->nr_to_write <= 0)
  2060. return 0;
  2061. while (1) {
  2062. if (mapping->a_ops->writepages)
  2063. ret = mapping->a_ops->writepages(mapping, wbc);
  2064. else
  2065. ret = generic_writepages(mapping, wbc);
  2066. if ((ret != -ENOMEM) || (wbc->sync_mode != WB_SYNC_ALL))
  2067. break;
  2068. cond_resched();
  2069. congestion_wait(BLK_RW_ASYNC, HZ/50);
  2070. }
  2071. return ret;
  2072. }
  2073. /**
  2074. * write_one_page - write out a single page and wait on I/O
  2075. * @page: the page to write
  2076. *
  2077. * The page must be locked by the caller and will be unlocked upon return.
  2078. *
  2079. * Note that the mapping's AS_EIO/AS_ENOSPC flags will be cleared when this
  2080. * function returns.
  2081. */
  2082. int write_one_page(struct page *page)
  2083. {
  2084. struct address_space *mapping = page->mapping;
  2085. int ret = 0;
  2086. struct writeback_control wbc = {
  2087. .sync_mode = WB_SYNC_ALL,
  2088. .nr_to_write = 1,
  2089. };
  2090. BUG_ON(!PageLocked(page));
  2091. wait_on_page_writeback(page);
  2092. if (clear_page_dirty_for_io(page)) {
  2093. get_page(page);
  2094. ret = mapping->a_ops->writepage(page, &wbc);
  2095. if (ret == 0)
  2096. wait_on_page_writeback(page);
  2097. put_page(page);
  2098. } else {
  2099. unlock_page(page);
  2100. }
  2101. if (!ret)
  2102. ret = filemap_check_errors(mapping);
  2103. return ret;
  2104. }
  2105. EXPORT_SYMBOL(write_one_page);
  2106. /*
  2107. * For address_spaces which do not use buffers nor write back.
  2108. */
  2109. int __set_page_dirty_no_writeback(struct page *page)
  2110. {
  2111. if (!PageDirty(page))
  2112. return !TestSetPageDirty(page);
  2113. return 0;
  2114. }
  2115. /*
  2116. * Helper function for set_page_dirty family.
  2117. *
  2118. * Caller must hold lock_page_memcg().
  2119. *
  2120. * NOTE: This relies on being atomic wrt interrupts.
  2121. */
  2122. void account_page_dirtied(struct page *page, struct address_space *mapping)
  2123. {
  2124. struct inode *inode = mapping->host;
  2125. trace_writeback_dirty_page(page, mapping);
  2126. if (mapping_cap_account_dirty(mapping)) {
  2127. struct bdi_writeback *wb;
  2128. inode_attach_wb(inode, page);
  2129. wb = inode_to_wb(inode);
  2130. __inc_lruvec_page_state(page, NR_FILE_DIRTY);
  2131. __inc_zone_page_state(page, NR_ZONE_WRITE_PENDING);
  2132. __inc_node_page_state(page, NR_DIRTIED);
  2133. inc_wb_stat(wb, WB_RECLAIMABLE);
  2134. inc_wb_stat(wb, WB_DIRTIED);
  2135. task_io_account_write(PAGE_SIZE);
  2136. current->nr_dirtied++;
  2137. this_cpu_inc(bdp_ratelimits);
  2138. }
  2139. }
  2140. EXPORT_SYMBOL(account_page_dirtied);
  2141. /*
  2142. * Helper function for deaccounting dirty page without writeback.
  2143. *
  2144. * Caller must hold lock_page_memcg().
  2145. */
  2146. void account_page_cleaned(struct page *page, struct address_space *mapping,
  2147. struct bdi_writeback *wb)
  2148. {
  2149. if (mapping_cap_account_dirty(mapping)) {
  2150. dec_lruvec_page_state(page, NR_FILE_DIRTY);
  2151. dec_zone_page_state(page, NR_ZONE_WRITE_PENDING);
  2152. dec_wb_stat(wb, WB_RECLAIMABLE);
  2153. task_io_account_cancelled_write(PAGE_SIZE);
  2154. }
  2155. }
  2156. /*
  2157. * For address_spaces which do not use buffers. Just tag the page as dirty in
  2158. * its radix tree.
  2159. *
  2160. * This is also used when a single buffer is being dirtied: we want to set the
  2161. * page dirty in that case, but not all the buffers. This is a "bottom-up"
  2162. * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
  2163. *
  2164. * The caller must ensure this doesn't race with truncation. Most will simply
  2165. * hold the page lock, but e.g. zap_pte_range() calls with the page mapped and
  2166. * the pte lock held, which also locks out truncation.
  2167. */
  2168. int __set_page_dirty_nobuffers(struct page *page)
  2169. {
  2170. lock_page_memcg(page);
  2171. if (!TestSetPageDirty(page)) {
  2172. struct address_space *mapping = page_mapping(page);
  2173. unsigned long flags;
  2174. if (!mapping) {
  2175. unlock_page_memcg(page);
  2176. return 1;
  2177. }
  2178. xa_lock_irqsave(&mapping->i_pages, flags);
  2179. BUG_ON(page_mapping(page) != mapping);
  2180. WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
  2181. account_page_dirtied(page, mapping);
  2182. radix_tree_tag_set(&mapping->i_pages, page_index(page),
  2183. PAGECACHE_TAG_DIRTY);
  2184. xa_unlock_irqrestore(&mapping->i_pages, flags);
  2185. unlock_page_memcg(page);
  2186. if (mapping->host) {
  2187. /* !PageAnon && !swapper_space */
  2188. __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
  2189. }
  2190. return 1;
  2191. }
  2192. unlock_page_memcg(page);
  2193. return 0;
  2194. }
  2195. EXPORT_SYMBOL(__set_page_dirty_nobuffers);
  2196. /*
  2197. * Call this whenever redirtying a page, to de-account the dirty counters
  2198. * (NR_DIRTIED, WB_DIRTIED, tsk->nr_dirtied), so that they match the written
  2199. * counters (NR_WRITTEN, WB_WRITTEN) in long term. The mismatches will lead to
  2200. * systematic errors in balanced_dirty_ratelimit and the dirty pages position
  2201. * control.
  2202. */
  2203. void account_page_redirty(struct page *page)
  2204. {
  2205. struct address_space *mapping = page->mapping;
  2206. if (mapping && mapping_cap_account_dirty(mapping)) {
  2207. struct inode *inode = mapping->host;
  2208. struct bdi_writeback *wb;
  2209. struct wb_lock_cookie cookie = {};
  2210. wb = unlocked_inode_to_wb_begin(inode, &cookie);
  2211. current->nr_dirtied--;
  2212. dec_node_page_state(page, NR_DIRTIED);
  2213. dec_wb_stat(wb, WB_DIRTIED);
  2214. unlocked_inode_to_wb_end(inode, &cookie);
  2215. }
  2216. }
  2217. EXPORT_SYMBOL(account_page_redirty);
  2218. /*
  2219. * When a writepage implementation decides that it doesn't want to write this
  2220. * page for some reason, it should redirty the locked page via
  2221. * redirty_page_for_writepage() and it should then unlock the page and return 0
  2222. */
  2223. int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
  2224. {
  2225. int ret;
  2226. wbc->pages_skipped++;
  2227. ret = __set_page_dirty_nobuffers(page);
  2228. account_page_redirty(page);
  2229. return ret;
  2230. }
  2231. EXPORT_SYMBOL(redirty_page_for_writepage);
  2232. /*
  2233. * Dirty a page.
  2234. *
  2235. * For pages with a mapping this should be done under the page lock
  2236. * for the benefit of asynchronous memory errors who prefer a consistent
  2237. * dirty state. This rule can be broken in some special cases,
  2238. * but should be better not to.
  2239. *
  2240. * If the mapping doesn't provide a set_page_dirty a_op, then
  2241. * just fall through and assume that it wants buffer_heads.
  2242. */
  2243. int set_page_dirty(struct page *page)
  2244. {
  2245. struct address_space *mapping = page_mapping(page);
  2246. page = compound_head(page);
  2247. if (likely(mapping)) {
  2248. int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
  2249. /*
  2250. * readahead/lru_deactivate_page could remain
  2251. * PG_readahead/PG_reclaim due to race with end_page_writeback
  2252. * About readahead, if the page is written, the flags would be
  2253. * reset. So no problem.
  2254. * About lru_deactivate_page, if the page is redirty, the flag
  2255. * will be reset. So no problem. but if the page is used by readahead
  2256. * it will confuse readahead and make it restart the size rampup
  2257. * process. But it's a trivial problem.
  2258. */
  2259. if (PageReclaim(page))
  2260. ClearPageReclaim(page);
  2261. #ifdef CONFIG_BLOCK
  2262. if (!spd)
  2263. spd = __set_page_dirty_buffers;
  2264. #endif
  2265. return (*spd)(page);
  2266. }
  2267. if (!PageDirty(page)) {
  2268. if (!TestSetPageDirty(page))
  2269. return 1;
  2270. }
  2271. return 0;
  2272. }
  2273. EXPORT_SYMBOL(set_page_dirty);
  2274. /*
  2275. * set_page_dirty() is racy if the caller has no reference against
  2276. * page->mapping->host, and if the page is unlocked. This is because another
  2277. * CPU could truncate the page off the mapping and then free the mapping.
  2278. *
  2279. * Usually, the page _is_ locked, or the caller is a user-space process which
  2280. * holds a reference on the inode by having an open file.
  2281. *
  2282. * In other cases, the page should be locked before running set_page_dirty().
  2283. */
  2284. int set_page_dirty_lock(struct page *page)
  2285. {
  2286. int ret;
  2287. lock_page(page);
  2288. ret = set_page_dirty(page);
  2289. unlock_page(page);
  2290. return ret;
  2291. }
  2292. EXPORT_SYMBOL(set_page_dirty_lock);
  2293. /*
  2294. * This cancels just the dirty bit on the kernel page itself, it does NOT
  2295. * actually remove dirty bits on any mmap's that may be around. It also
  2296. * leaves the page tagged dirty, so any sync activity will still find it on
  2297. * the dirty lists, and in particular, clear_page_dirty_for_io() will still
  2298. * look at the dirty bits in the VM.
  2299. *
  2300. * Doing this should *normally* only ever be done when a page is truncated,
  2301. * and is not actually mapped anywhere at all. However, fs/buffer.c does
  2302. * this when it notices that somebody has cleaned out all the buffers on a
  2303. * page without actually doing it through the VM. Can you say "ext3 is
  2304. * horribly ugly"? Thought you could.
  2305. */
  2306. void __cancel_dirty_page(struct page *page)
  2307. {
  2308. struct address_space *mapping = page_mapping(page);
  2309. if (mapping_cap_account_dirty(mapping)) {
  2310. struct inode *inode = mapping->host;
  2311. struct bdi_writeback *wb;
  2312. struct wb_lock_cookie cookie = {};
  2313. lock_page_memcg(page);
  2314. wb = unlocked_inode_to_wb_begin(inode, &cookie);
  2315. if (TestClearPageDirty(page))
  2316. account_page_cleaned(page, mapping, wb);
  2317. unlocked_inode_to_wb_end(inode, &cookie);
  2318. unlock_page_memcg(page);
  2319. } else {
  2320. ClearPageDirty(page);
  2321. }
  2322. }
  2323. EXPORT_SYMBOL(__cancel_dirty_page);
  2324. /*
  2325. * Clear a page's dirty flag, while caring for dirty memory accounting.
  2326. * Returns true if the page was previously dirty.
  2327. *
  2328. * This is for preparing to put the page under writeout. We leave the page
  2329. * tagged as dirty in the radix tree so that a concurrent write-for-sync
  2330. * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
  2331. * implementation will run either set_page_writeback() or set_page_dirty(),
  2332. * at which stage we bring the page's dirty flag and radix-tree dirty tag
  2333. * back into sync.
  2334. *
  2335. * This incoherency between the page's dirty flag and radix-tree tag is
  2336. * unfortunate, but it only exists while the page is locked.
  2337. */
  2338. int clear_page_dirty_for_io(struct page *page)
  2339. {
  2340. struct address_space *mapping = page_mapping(page);
  2341. int ret = 0;
  2342. BUG_ON(!PageLocked(page));
  2343. if (mapping && mapping_cap_account_dirty(mapping)) {
  2344. struct inode *inode = mapping->host;
  2345. struct bdi_writeback *wb;
  2346. struct wb_lock_cookie cookie = {};
  2347. /*
  2348. * Yes, Virginia, this is indeed insane.
  2349. *
  2350. * We use this sequence to make sure that
  2351. * (a) we account for dirty stats properly
  2352. * (b) we tell the low-level filesystem to
  2353. * mark the whole page dirty if it was
  2354. * dirty in a pagetable. Only to then
  2355. * (c) clean the page again and return 1 to
  2356. * cause the writeback.
  2357. *
  2358. * This way we avoid all nasty races with the
  2359. * dirty bit in multiple places and clearing
  2360. * them concurrently from different threads.
  2361. *
  2362. * Note! Normally the "set_page_dirty(page)"
  2363. * has no effect on the actual dirty bit - since
  2364. * that will already usually be set. But we
  2365. * need the side effects, and it can help us
  2366. * avoid races.
  2367. *
  2368. * We basically use the page "master dirty bit"
  2369. * as a serialization point for all the different
  2370. * threads doing their things.
  2371. */
  2372. if (page_mkclean(page))
  2373. set_page_dirty(page);
  2374. /*
  2375. * We carefully synchronise fault handlers against
  2376. * installing a dirty pte and marking the page dirty
  2377. * at this point. We do this by having them hold the
  2378. * page lock while dirtying the page, and pages are
  2379. * always locked coming in here, so we get the desired
  2380. * exclusion.
  2381. */
  2382. wb = unlocked_inode_to_wb_begin(inode, &cookie);
  2383. if (TestClearPageDirty(page)) {
  2384. dec_lruvec_page_state(page, NR_FILE_DIRTY);
  2385. dec_zone_page_state(page, NR_ZONE_WRITE_PENDING);
  2386. dec_wb_stat(wb, WB_RECLAIMABLE);
  2387. ret = 1;
  2388. }
  2389. unlocked_inode_to_wb_end(inode, &cookie);
  2390. return ret;
  2391. }
  2392. return TestClearPageDirty(page);
  2393. }
  2394. EXPORT_SYMBOL(clear_page_dirty_for_io);
  2395. int test_clear_page_writeback(struct page *page)
  2396. {
  2397. struct address_space *mapping = page_mapping(page);
  2398. struct mem_cgroup *memcg;
  2399. struct lruvec *lruvec;
  2400. int ret;
  2401. memcg = lock_page_memcg(page);
  2402. lruvec = mem_cgroup_page_lruvec(page, page_pgdat(page));
  2403. if (mapping && mapping_use_writeback_tags(mapping)) {
  2404. struct inode *inode = mapping->host;
  2405. struct backing_dev_info *bdi = inode_to_bdi(inode);
  2406. unsigned long flags;
  2407. xa_lock_irqsave(&mapping->i_pages, flags);
  2408. ret = TestClearPageWriteback(page);
  2409. if (ret) {
  2410. radix_tree_tag_clear(&mapping->i_pages, page_index(page),
  2411. PAGECACHE_TAG_WRITEBACK);
  2412. if (bdi_cap_account_writeback(bdi)) {
  2413. struct bdi_writeback *wb = inode_to_wb(inode);
  2414. dec_wb_stat(wb, WB_WRITEBACK);
  2415. __wb_writeout_inc(wb);
  2416. }
  2417. }
  2418. if (mapping->host && !mapping_tagged(mapping,
  2419. PAGECACHE_TAG_WRITEBACK))
  2420. sb_clear_inode_writeback(mapping->host);
  2421. xa_unlock_irqrestore(&mapping->i_pages, flags);
  2422. } else {
  2423. ret = TestClearPageWriteback(page);
  2424. }
  2425. /*
  2426. * NOTE: Page might be free now! Writeback doesn't hold a page
  2427. * reference on its own, it relies on truncation to wait for
  2428. * the clearing of PG_writeback. The below can only access
  2429. * page state that is static across allocation cycles.
  2430. */
  2431. if (ret) {
  2432. dec_lruvec_state(lruvec, NR_WRITEBACK);
  2433. dec_zone_page_state(page, NR_ZONE_WRITE_PENDING);
  2434. inc_node_page_state(page, NR_WRITTEN);
  2435. }
  2436. __unlock_page_memcg(memcg);
  2437. return ret;
  2438. }
  2439. int __test_set_page_writeback(struct page *page, bool keep_write)
  2440. {
  2441. struct address_space *mapping = page_mapping(page);
  2442. int ret;
  2443. lock_page_memcg(page);
  2444. if (mapping && mapping_use_writeback_tags(mapping)) {
  2445. struct inode *inode = mapping->host;
  2446. struct backing_dev_info *bdi = inode_to_bdi(inode);
  2447. unsigned long flags;
  2448. xa_lock_irqsave(&mapping->i_pages, flags);
  2449. ret = TestSetPageWriteback(page);
  2450. if (!ret) {
  2451. bool on_wblist;
  2452. on_wblist = mapping_tagged(mapping,
  2453. PAGECACHE_TAG_WRITEBACK);
  2454. radix_tree_tag_set(&mapping->i_pages, page_index(page),
  2455. PAGECACHE_TAG_WRITEBACK);
  2456. if (bdi_cap_account_writeback(bdi))
  2457. inc_wb_stat(inode_to_wb(inode), WB_WRITEBACK);
  2458. /*
  2459. * We can come through here when swapping anonymous
  2460. * pages, so we don't necessarily have an inode to track
  2461. * for sync.
  2462. */
  2463. if (mapping->host && !on_wblist)
  2464. sb_mark_inode_writeback(mapping->host);
  2465. }
  2466. if (!PageDirty(page))
  2467. radix_tree_tag_clear(&mapping->i_pages, page_index(page),
  2468. PAGECACHE_TAG_DIRTY);
  2469. if (!keep_write)
  2470. radix_tree_tag_clear(&mapping->i_pages, page_index(page),
  2471. PAGECACHE_TAG_TOWRITE);
  2472. xa_unlock_irqrestore(&mapping->i_pages, flags);
  2473. } else {
  2474. ret = TestSetPageWriteback(page);
  2475. }
  2476. if (!ret) {
  2477. inc_lruvec_page_state(page, NR_WRITEBACK);
  2478. inc_zone_page_state(page, NR_ZONE_WRITE_PENDING);
  2479. }
  2480. unlock_page_memcg(page);
  2481. return ret;
  2482. }
  2483. EXPORT_SYMBOL(__test_set_page_writeback);
  2484. /*
  2485. * Return true if any of the pages in the mapping are marked with the
  2486. * passed tag.
  2487. */
  2488. int mapping_tagged(struct address_space *mapping, int tag)
  2489. {
  2490. return radix_tree_tagged(&mapping->i_pages, tag);
  2491. }
  2492. EXPORT_SYMBOL(mapping_tagged);
  2493. /**
  2494. * wait_for_stable_page() - wait for writeback to finish, if necessary.
  2495. * @page: The page to wait on.
  2496. *
  2497. * This function determines if the given page is related to a backing device
  2498. * that requires page contents to be held stable during writeback. If so, then
  2499. * it will wait for any pending writeback to complete.
  2500. */
  2501. void wait_for_stable_page(struct page *page)
  2502. {
  2503. if (bdi_cap_stable_pages_required(inode_to_bdi(page->mapping->host)))
  2504. wait_on_page_writeback(page);
  2505. }
  2506. EXPORT_SYMBOL_GPL(wait_for_stable_page);