fs-writeback.c 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * fs/fs-writeback.c
  4. *
  5. * Copyright (C) 2002, Linus Torvalds.
  6. *
  7. * Contains all the functions related to writing back and waiting
  8. * upon dirty inodes against superblocks, and writing back dirty
  9. * pages against inodes. ie: data writeback. Writeout of the
  10. * inode itself is not handled here.
  11. *
  12. * 10Apr2002 Andrew Morton
  13. * Split out of fs/inode.c
  14. * Additions for address_space-based writeback
  15. */
  16. #include <linux/kernel.h>
  17. #include <linux/export.h>
  18. #include <linux/spinlock.h>
  19. #include <linux/slab.h>
  20. #include <linux/sched.h>
  21. #include <linux/fs.h>
  22. #include <linux/mm.h>
  23. #include <linux/pagemap.h>
  24. #include <linux/kthread.h>
  25. #include <linux/writeback.h>
  26. #include <linux/blkdev.h>
  27. #include <linux/backing-dev.h>
  28. #include <linux/tracepoint.h>
  29. #include <linux/device.h>
  30. #include <linux/memcontrol.h>
  31. #include "internal.h"
  32. /*
  33. * 4MB minimal write chunk size
  34. */
  35. #define MIN_WRITEBACK_PAGES (4096UL >> (PAGE_SHIFT - 10))
  36. /*
  37. * Passed into wb_writeback(), essentially a subset of writeback_control
  38. */
  39. struct wb_writeback_work {
  40. long nr_pages;
  41. struct super_block *sb;
  42. enum writeback_sync_modes sync_mode;
  43. unsigned int tagged_writepages:1;
  44. unsigned int for_kupdate:1;
  45. unsigned int range_cyclic:1;
  46. unsigned int for_background:1;
  47. unsigned int for_sync:1; /* sync(2) WB_SYNC_ALL writeback */
  48. unsigned int auto_free:1; /* free on completion */
  49. enum wb_reason reason; /* why was writeback initiated? */
  50. struct list_head list; /* pending work list */
  51. struct wb_completion *done; /* set if the caller waits */
  52. };
  53. /*
  54. * If an inode is constantly having its pages dirtied, but then the
  55. * updates stop dirtytime_expire_interval seconds in the past, it's
  56. * possible for the worst case time between when an inode has its
  57. * timestamps updated and when they finally get written out to be two
  58. * dirtytime_expire_intervals. We set the default to 12 hours (in
  59. * seconds), which means most of the time inodes will have their
  60. * timestamps written to disk after 12 hours, but in the worst case a
  61. * few inodes might not their timestamps updated for 24 hours.
  62. */
  63. unsigned int dirtytime_expire_interval = 12 * 60 * 60;
  64. static inline struct inode *wb_inode(struct list_head *head)
  65. {
  66. return list_entry(head, struct inode, i_io_list);
  67. }
  68. /*
  69. * Include the creation of the trace points after defining the
  70. * wb_writeback_work structure and inline functions so that the definition
  71. * remains local to this file.
  72. */
  73. #define CREATE_TRACE_POINTS
  74. #include <trace/events/writeback.h>
  75. EXPORT_TRACEPOINT_SYMBOL_GPL(wbc_writepage);
  76. static bool wb_io_lists_populated(struct bdi_writeback *wb)
  77. {
  78. if (wb_has_dirty_io(wb)) {
  79. return false;
  80. } else {
  81. set_bit(WB_has_dirty_io, &wb->state);
  82. WARN_ON_ONCE(!wb->avg_write_bandwidth);
  83. atomic_long_add(wb->avg_write_bandwidth,
  84. &wb->bdi->tot_write_bandwidth);
  85. return true;
  86. }
  87. }
  88. static void wb_io_lists_depopulated(struct bdi_writeback *wb)
  89. {
  90. if (wb_has_dirty_io(wb) && list_empty(&wb->b_dirty) &&
  91. list_empty(&wb->b_io) && list_empty(&wb->b_more_io)) {
  92. clear_bit(WB_has_dirty_io, &wb->state);
  93. WARN_ON_ONCE(atomic_long_sub_return(wb->avg_write_bandwidth,
  94. &wb->bdi->tot_write_bandwidth) < 0);
  95. }
  96. }
  97. /**
  98. * inode_io_list_move_locked - move an inode onto a bdi_writeback IO list
  99. * @inode: inode to be moved
  100. * @wb: target bdi_writeback
  101. * @head: one of @wb->b_{dirty|io|more_io|dirty_time}
  102. *
  103. * Move @inode->i_io_list to @list of @wb and set %WB_has_dirty_io.
  104. * Returns %true if @inode is the first occupant of the !dirty_time IO
  105. * lists; otherwise, %false.
  106. */
  107. static bool inode_io_list_move_locked(struct inode *inode,
  108. struct bdi_writeback *wb,
  109. struct list_head *head)
  110. {
  111. assert_spin_locked(&wb->list_lock);
  112. assert_spin_locked(&inode->i_lock);
  113. WARN_ON_ONCE(inode->i_state & I_FREEING);
  114. list_move(&inode->i_io_list, head);
  115. /* dirty_time doesn't count as dirty_io until expiration */
  116. if (head != &wb->b_dirty_time)
  117. return wb_io_lists_populated(wb);
  118. wb_io_lists_depopulated(wb);
  119. return false;
  120. }
  121. static void wb_wakeup(struct bdi_writeback *wb)
  122. {
  123. spin_lock_irq(&wb->work_lock);
  124. if (test_bit(WB_registered, &wb->state))
  125. mod_delayed_work(bdi_wq, &wb->dwork, 0);
  126. spin_unlock_irq(&wb->work_lock);
  127. }
  128. /*
  129. * This function is used when the first inode for this wb is marked dirty. It
  130. * wakes-up the corresponding bdi thread which should then take care of the
  131. * periodic background write-out of dirty inodes. Since the write-out would
  132. * starts only 'dirty_writeback_interval' centisecs from now anyway, we just
  133. * set up a timer which wakes the bdi thread up later.
  134. *
  135. * Note, we wouldn't bother setting up the timer, but this function is on the
  136. * fast-path (used by '__mark_inode_dirty()'), so we save few context switches
  137. * by delaying the wake-up.
  138. *
  139. * We have to be careful not to postpone flush work if it is scheduled for
  140. * earlier. Thus we use queue_delayed_work().
  141. */
  142. static void wb_wakeup_delayed(struct bdi_writeback *wb)
  143. {
  144. unsigned long timeout;
  145. timeout = msecs_to_jiffies(dirty_writeback_interval * 10);
  146. spin_lock_irq(&wb->work_lock);
  147. if (test_bit(WB_registered, &wb->state))
  148. queue_delayed_work(bdi_wq, &wb->dwork, timeout);
  149. spin_unlock_irq(&wb->work_lock);
  150. }
  151. static void finish_writeback_work(struct wb_writeback_work *work)
  152. {
  153. struct wb_completion *done = work->done;
  154. if (work->auto_free)
  155. kfree(work);
  156. if (done) {
  157. wait_queue_head_t *waitq = done->waitq;
  158. /* @done can't be accessed after the following dec */
  159. if (atomic_dec_and_test(&done->cnt))
  160. wake_up_all(waitq);
  161. }
  162. }
  163. static void wb_queue_work(struct bdi_writeback *wb,
  164. struct wb_writeback_work *work)
  165. {
  166. trace_writeback_queue(wb, work);
  167. if (work->done)
  168. atomic_inc(&work->done->cnt);
  169. spin_lock_irq(&wb->work_lock);
  170. if (test_bit(WB_registered, &wb->state)) {
  171. list_add_tail(&work->list, &wb->work_list);
  172. mod_delayed_work(bdi_wq, &wb->dwork, 0);
  173. } else
  174. finish_writeback_work(work);
  175. spin_unlock_irq(&wb->work_lock);
  176. }
  177. /**
  178. * wb_wait_for_completion - wait for completion of bdi_writeback_works
  179. * @done: target wb_completion
  180. *
  181. * Wait for one or more work items issued to @bdi with their ->done field
  182. * set to @done, which should have been initialized with
  183. * DEFINE_WB_COMPLETION(). This function returns after all such work items
  184. * are completed. Work items which are waited upon aren't freed
  185. * automatically on completion.
  186. */
  187. void wb_wait_for_completion(struct wb_completion *done)
  188. {
  189. atomic_dec(&done->cnt); /* put down the initial count */
  190. wait_event(*done->waitq, !atomic_read(&done->cnt));
  191. }
  192. #ifdef CONFIG_CGROUP_WRITEBACK
  193. /*
  194. * Parameters for foreign inode detection, see wbc_detach_inode() to see
  195. * how they're used.
  196. *
  197. * These paramters are inherently heuristical as the detection target
  198. * itself is fuzzy. All we want to do is detaching an inode from the
  199. * current owner if it's being written to by some other cgroups too much.
  200. *
  201. * The current cgroup writeback is built on the assumption that multiple
  202. * cgroups writing to the same inode concurrently is very rare and a mode
  203. * of operation which isn't well supported. As such, the goal is not
  204. * taking too long when a different cgroup takes over an inode while
  205. * avoiding too aggressive flip-flops from occasional foreign writes.
  206. *
  207. * We record, very roughly, 2s worth of IO time history and if more than
  208. * half of that is foreign, trigger the switch. The recording is quantized
  209. * to 16 slots. To avoid tiny writes from swinging the decision too much,
  210. * writes smaller than 1/8 of avg size are ignored.
  211. */
  212. #define WB_FRN_TIME_SHIFT 13 /* 1s = 2^13, upto 8 secs w/ 16bit */
  213. #define WB_FRN_TIME_AVG_SHIFT 3 /* avg = avg * 7/8 + new * 1/8 */
  214. #define WB_FRN_TIME_CUT_DIV 8 /* ignore rounds < avg / 8 */
  215. #define WB_FRN_TIME_PERIOD (2 * (1 << WB_FRN_TIME_SHIFT)) /* 2s */
  216. #define WB_FRN_HIST_SLOTS 16 /* inode->i_wb_frn_history is 16bit */
  217. #define WB_FRN_HIST_UNIT (WB_FRN_TIME_PERIOD / WB_FRN_HIST_SLOTS)
  218. /* each slot's duration is 2s / 16 */
  219. #define WB_FRN_HIST_THR_SLOTS (WB_FRN_HIST_SLOTS / 2)
  220. /* if foreign slots >= 8, switch */
  221. #define WB_FRN_HIST_MAX_SLOTS (WB_FRN_HIST_THR_SLOTS / 2 + 1)
  222. /* one round can affect upto 5 slots */
  223. #define WB_FRN_MAX_IN_FLIGHT 1024 /* don't queue too many concurrently */
  224. /*
  225. * Maximum inodes per isw. A specific value has been chosen to make
  226. * struct inode_switch_wbs_context fit into 1024 bytes kmalloc.
  227. */
  228. #define WB_MAX_INODES_PER_ISW ((1024UL - sizeof(struct inode_switch_wbs_context)) \
  229. / sizeof(struct inode *))
  230. static atomic_t isw_nr_in_flight = ATOMIC_INIT(0);
  231. static struct workqueue_struct *isw_wq;
  232. void __inode_attach_wb(struct inode *inode, struct folio *folio)
  233. {
  234. struct backing_dev_info *bdi = inode_to_bdi(inode);
  235. struct bdi_writeback *wb = NULL;
  236. if (inode_cgwb_enabled(inode)) {
  237. struct cgroup_subsys_state *memcg_css;
  238. if (folio) {
  239. memcg_css = mem_cgroup_css_from_folio(folio);
  240. wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
  241. } else {
  242. /* must pin memcg_css, see wb_get_create() */
  243. memcg_css = task_get_css(current, memory_cgrp_id);
  244. wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
  245. css_put(memcg_css);
  246. }
  247. }
  248. if (!wb)
  249. wb = &bdi->wb;
  250. /*
  251. * There may be multiple instances of this function racing to
  252. * update the same inode. Use cmpxchg() to tell the winner.
  253. */
  254. if (unlikely(cmpxchg(&inode->i_wb, NULL, wb)))
  255. wb_put(wb);
  256. }
  257. EXPORT_SYMBOL_GPL(__inode_attach_wb);
  258. /**
  259. * inode_cgwb_move_to_attached - put the inode onto wb->b_attached list
  260. * @inode: inode of interest with i_lock held
  261. * @wb: target bdi_writeback
  262. *
  263. * Remove the inode from wb's io lists and if necessarily put onto b_attached
  264. * list. Only inodes attached to cgwb's are kept on this list.
  265. */
  266. static void inode_cgwb_move_to_attached(struct inode *inode,
  267. struct bdi_writeback *wb)
  268. {
  269. assert_spin_locked(&wb->list_lock);
  270. assert_spin_locked(&inode->i_lock);
  271. WARN_ON_ONCE(inode->i_state & I_FREEING);
  272. inode->i_state &= ~I_SYNC_QUEUED;
  273. if (wb != &wb->bdi->wb)
  274. list_move(&inode->i_io_list, &wb->b_attached);
  275. else
  276. list_del_init(&inode->i_io_list);
  277. wb_io_lists_depopulated(wb);
  278. }
  279. /**
  280. * locked_inode_to_wb_and_lock_list - determine a locked inode's wb and lock it
  281. * @inode: inode of interest with i_lock held
  282. *
  283. * Returns @inode's wb with its list_lock held. @inode->i_lock must be
  284. * held on entry and is released on return. The returned wb is guaranteed
  285. * to stay @inode's associated wb until its list_lock is released.
  286. */
  287. static struct bdi_writeback *
  288. locked_inode_to_wb_and_lock_list(struct inode *inode)
  289. __releases(&inode->i_lock)
  290. __acquires(&wb->list_lock)
  291. {
  292. while (true) {
  293. struct bdi_writeback *wb = inode_to_wb(inode);
  294. /*
  295. * inode_to_wb() association is protected by both
  296. * @inode->i_lock and @wb->list_lock but list_lock nests
  297. * outside i_lock. Drop i_lock and verify that the
  298. * association hasn't changed after acquiring list_lock.
  299. */
  300. wb_get(wb);
  301. spin_unlock(&inode->i_lock);
  302. spin_lock(&wb->list_lock);
  303. /* i_wb may have changed inbetween, can't use inode_to_wb() */
  304. if (likely(wb == inode->i_wb)) {
  305. wb_put(wb); /* @inode already has ref */
  306. return wb;
  307. }
  308. spin_unlock(&wb->list_lock);
  309. wb_put(wb);
  310. cpu_relax();
  311. spin_lock(&inode->i_lock);
  312. }
  313. }
  314. /**
  315. * inode_to_wb_and_lock_list - determine an inode's wb and lock it
  316. * @inode: inode of interest
  317. *
  318. * Same as locked_inode_to_wb_and_lock_list() but @inode->i_lock isn't held
  319. * on entry.
  320. */
  321. static struct bdi_writeback *inode_to_wb_and_lock_list(struct inode *inode)
  322. __acquires(&wb->list_lock)
  323. {
  324. spin_lock(&inode->i_lock);
  325. return locked_inode_to_wb_and_lock_list(inode);
  326. }
  327. struct inode_switch_wbs_context {
  328. struct rcu_work work;
  329. /*
  330. * Multiple inodes can be switched at once. The switching procedure
  331. * consists of two parts, separated by a RCU grace period. To make
  332. * sure that the second part is executed for each inode gone through
  333. * the first part, all inode pointers are placed into a NULL-terminated
  334. * array embedded into struct inode_switch_wbs_context. Otherwise
  335. * an inode could be left in a non-consistent state.
  336. */
  337. struct bdi_writeback *new_wb;
  338. struct inode *inodes[];
  339. };
  340. static void bdi_down_write_wb_switch_rwsem(struct backing_dev_info *bdi)
  341. {
  342. down_write(&bdi->wb_switch_rwsem);
  343. }
  344. static void bdi_up_write_wb_switch_rwsem(struct backing_dev_info *bdi)
  345. {
  346. up_write(&bdi->wb_switch_rwsem);
  347. }
  348. static bool inode_do_switch_wbs(struct inode *inode,
  349. struct bdi_writeback *old_wb,
  350. struct bdi_writeback *new_wb)
  351. {
  352. struct address_space *mapping = inode->i_mapping;
  353. XA_STATE(xas, &mapping->i_pages, 0);
  354. struct folio *folio;
  355. bool switched = false;
  356. spin_lock(&inode->i_lock);
  357. xa_lock_irq(&mapping->i_pages);
  358. /*
  359. * Once I_FREEING or I_WILL_FREE are visible under i_lock, the eviction
  360. * path owns the inode and we shouldn't modify ->i_io_list.
  361. */
  362. if (unlikely(inode->i_state & (I_FREEING | I_WILL_FREE)))
  363. goto skip_switch;
  364. trace_inode_switch_wbs(inode, old_wb, new_wb);
  365. /*
  366. * Count and transfer stats. Note that PAGECACHE_TAG_DIRTY points
  367. * to possibly dirty folios while PAGECACHE_TAG_WRITEBACK points to
  368. * folios actually under writeback.
  369. */
  370. xas_for_each_marked(&xas, folio, ULONG_MAX, PAGECACHE_TAG_DIRTY) {
  371. if (folio_test_dirty(folio)) {
  372. long nr = folio_nr_pages(folio);
  373. wb_stat_mod(old_wb, WB_RECLAIMABLE, -nr);
  374. wb_stat_mod(new_wb, WB_RECLAIMABLE, nr);
  375. }
  376. }
  377. xas_set(&xas, 0);
  378. xas_for_each_marked(&xas, folio, ULONG_MAX, PAGECACHE_TAG_WRITEBACK) {
  379. long nr = folio_nr_pages(folio);
  380. WARN_ON_ONCE(!folio_test_writeback(folio));
  381. wb_stat_mod(old_wb, WB_WRITEBACK, -nr);
  382. wb_stat_mod(new_wb, WB_WRITEBACK, nr);
  383. }
  384. if (mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK)) {
  385. atomic_dec(&old_wb->writeback_inodes);
  386. atomic_inc(&new_wb->writeback_inodes);
  387. }
  388. wb_get(new_wb);
  389. /*
  390. * Transfer to @new_wb's IO list if necessary. If the @inode is dirty,
  391. * the specific list @inode was on is ignored and the @inode is put on
  392. * ->b_dirty which is always correct including from ->b_dirty_time.
  393. * The transfer preserves @inode->dirtied_when ordering. If the @inode
  394. * was clean, it means it was on the b_attached list, so move it onto
  395. * the b_attached list of @new_wb.
  396. */
  397. if (!list_empty(&inode->i_io_list)) {
  398. inode->i_wb = new_wb;
  399. if (inode->i_state & I_DIRTY_ALL) {
  400. struct inode *pos;
  401. list_for_each_entry(pos, &new_wb->b_dirty, i_io_list)
  402. if (time_after_eq(inode->dirtied_when,
  403. pos->dirtied_when))
  404. break;
  405. inode_io_list_move_locked(inode, new_wb,
  406. pos->i_io_list.prev);
  407. } else {
  408. inode_cgwb_move_to_attached(inode, new_wb);
  409. }
  410. } else {
  411. inode->i_wb = new_wb;
  412. }
  413. /* ->i_wb_frn updates may race wbc_detach_inode() but doesn't matter */
  414. inode->i_wb_frn_winner = 0;
  415. inode->i_wb_frn_avg_time = 0;
  416. inode->i_wb_frn_history = 0;
  417. switched = true;
  418. skip_switch:
  419. /*
  420. * Paired with load_acquire in unlocked_inode_to_wb_begin() and
  421. * ensures that the new wb is visible if they see !I_WB_SWITCH.
  422. */
  423. smp_store_release(&inode->i_state, inode->i_state & ~I_WB_SWITCH);
  424. xa_unlock_irq(&mapping->i_pages);
  425. spin_unlock(&inode->i_lock);
  426. return switched;
  427. }
  428. static void inode_switch_wbs_work_fn(struct work_struct *work)
  429. {
  430. struct inode_switch_wbs_context *isw =
  431. container_of(to_rcu_work(work), struct inode_switch_wbs_context, work);
  432. struct backing_dev_info *bdi = inode_to_bdi(isw->inodes[0]);
  433. struct bdi_writeback *old_wb = isw->inodes[0]->i_wb;
  434. struct bdi_writeback *new_wb = isw->new_wb;
  435. unsigned long nr_switched = 0;
  436. struct inode **inodep;
  437. /*
  438. * If @inode switches cgwb membership while sync_inodes_sb() is
  439. * being issued, sync_inodes_sb() might miss it. Synchronize.
  440. */
  441. down_read(&bdi->wb_switch_rwsem);
  442. /*
  443. * By the time control reaches here, RCU grace period has passed
  444. * since I_WB_SWITCH assertion and all wb stat update transactions
  445. * between unlocked_inode_to_wb_begin/end() are guaranteed to be
  446. * synchronizing against the i_pages lock.
  447. *
  448. * Grabbing old_wb->list_lock, inode->i_lock and the i_pages lock
  449. * gives us exclusion against all wb related operations on @inode
  450. * including IO list manipulations and stat updates.
  451. */
  452. if (old_wb < new_wb) {
  453. spin_lock(&old_wb->list_lock);
  454. spin_lock_nested(&new_wb->list_lock, SINGLE_DEPTH_NESTING);
  455. } else {
  456. spin_lock(&new_wb->list_lock);
  457. spin_lock_nested(&old_wb->list_lock, SINGLE_DEPTH_NESTING);
  458. }
  459. for (inodep = isw->inodes; *inodep; inodep++) {
  460. WARN_ON_ONCE((*inodep)->i_wb != old_wb);
  461. if (inode_do_switch_wbs(*inodep, old_wb, new_wb))
  462. nr_switched++;
  463. }
  464. spin_unlock(&new_wb->list_lock);
  465. spin_unlock(&old_wb->list_lock);
  466. up_read(&bdi->wb_switch_rwsem);
  467. if (nr_switched) {
  468. wb_wakeup(new_wb);
  469. wb_put_many(old_wb, nr_switched);
  470. }
  471. for (inodep = isw->inodes; *inodep; inodep++)
  472. iput(*inodep);
  473. wb_put(new_wb);
  474. kfree(isw);
  475. atomic_dec(&isw_nr_in_flight);
  476. }
  477. static bool inode_prepare_wbs_switch(struct inode *inode,
  478. struct bdi_writeback *new_wb)
  479. {
  480. /*
  481. * Paired with smp_mb() in cgroup_writeback_umount().
  482. * isw_nr_in_flight must be increased before checking SB_ACTIVE and
  483. * grabbing an inode, otherwise isw_nr_in_flight can be observed as 0
  484. * in cgroup_writeback_umount() and the isw_wq will be not flushed.
  485. */
  486. smp_mb();
  487. if (IS_DAX(inode))
  488. return false;
  489. /* while holding I_WB_SWITCH, no one else can update the association */
  490. spin_lock(&inode->i_lock);
  491. if (!(inode->i_sb->s_flags & SB_ACTIVE) ||
  492. inode->i_state & (I_WB_SWITCH | I_FREEING | I_WILL_FREE) ||
  493. inode_to_wb(inode) == new_wb) {
  494. spin_unlock(&inode->i_lock);
  495. return false;
  496. }
  497. inode->i_state |= I_WB_SWITCH;
  498. __iget(inode);
  499. spin_unlock(&inode->i_lock);
  500. return true;
  501. }
  502. /**
  503. * inode_switch_wbs - change the wb association of an inode
  504. * @inode: target inode
  505. * @new_wb_id: ID of the new wb
  506. *
  507. * Switch @inode's wb association to the wb identified by @new_wb_id. The
  508. * switching is performed asynchronously and may fail silently.
  509. */
  510. static void inode_switch_wbs(struct inode *inode, int new_wb_id)
  511. {
  512. struct backing_dev_info *bdi = inode_to_bdi(inode);
  513. struct cgroup_subsys_state *memcg_css;
  514. struct inode_switch_wbs_context *isw;
  515. /* noop if seems to be already in progress */
  516. if (inode->i_state & I_WB_SWITCH)
  517. return;
  518. /* avoid queueing a new switch if too many are already in flight */
  519. if (atomic_read(&isw_nr_in_flight) > WB_FRN_MAX_IN_FLIGHT)
  520. return;
  521. isw = kzalloc(struct_size(isw, inodes, 2), GFP_ATOMIC);
  522. if (!isw)
  523. return;
  524. atomic_inc(&isw_nr_in_flight);
  525. /* find and pin the new wb */
  526. rcu_read_lock();
  527. memcg_css = css_from_id(new_wb_id, &memory_cgrp_subsys);
  528. if (memcg_css && !css_tryget(memcg_css))
  529. memcg_css = NULL;
  530. rcu_read_unlock();
  531. if (!memcg_css)
  532. goto out_free;
  533. isw->new_wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
  534. css_put(memcg_css);
  535. if (!isw->new_wb)
  536. goto out_free;
  537. if (!inode_prepare_wbs_switch(inode, isw->new_wb))
  538. goto out_free;
  539. isw->inodes[0] = inode;
  540. /*
  541. * In addition to synchronizing among switchers, I_WB_SWITCH tells
  542. * the RCU protected stat update paths to grab the i_page
  543. * lock so that stat transfer can synchronize against them.
  544. * Let's continue after I_WB_SWITCH is guaranteed to be visible.
  545. */
  546. INIT_RCU_WORK(&isw->work, inode_switch_wbs_work_fn);
  547. queue_rcu_work(isw_wq, &isw->work);
  548. return;
  549. out_free:
  550. atomic_dec(&isw_nr_in_flight);
  551. if (isw->new_wb)
  552. wb_put(isw->new_wb);
  553. kfree(isw);
  554. }
  555. static bool isw_prepare_wbs_switch(struct inode_switch_wbs_context *isw,
  556. struct list_head *list, int *nr)
  557. {
  558. struct inode *inode;
  559. list_for_each_entry(inode, list, i_io_list) {
  560. if (!inode_prepare_wbs_switch(inode, isw->new_wb))
  561. continue;
  562. isw->inodes[*nr] = inode;
  563. (*nr)++;
  564. if (*nr >= WB_MAX_INODES_PER_ISW - 1)
  565. return true;
  566. }
  567. return false;
  568. }
  569. /**
  570. * cleanup_offline_cgwb - detach associated inodes
  571. * @wb: target wb
  572. *
  573. * Switch all inodes attached to @wb to a nearest living ancestor's wb in order
  574. * to eventually release the dying @wb. Returns %true if not all inodes were
  575. * switched and the function has to be restarted.
  576. */
  577. bool cleanup_offline_cgwb(struct bdi_writeback *wb)
  578. {
  579. struct cgroup_subsys_state *memcg_css;
  580. struct inode_switch_wbs_context *isw;
  581. int nr;
  582. bool restart = false;
  583. isw = kzalloc(struct_size(isw, inodes, WB_MAX_INODES_PER_ISW),
  584. GFP_KERNEL);
  585. if (!isw)
  586. return restart;
  587. atomic_inc(&isw_nr_in_flight);
  588. for (memcg_css = wb->memcg_css->parent; memcg_css;
  589. memcg_css = memcg_css->parent) {
  590. isw->new_wb = wb_get_create(wb->bdi, memcg_css, GFP_KERNEL);
  591. if (isw->new_wb)
  592. break;
  593. }
  594. if (unlikely(!isw->new_wb))
  595. isw->new_wb = &wb->bdi->wb; /* wb_get() is noop for bdi's wb */
  596. nr = 0;
  597. spin_lock(&wb->list_lock);
  598. /*
  599. * In addition to the inodes that have completed writeback, also switch
  600. * cgwbs for those inodes only with dirty timestamps. Otherwise, those
  601. * inodes won't be written back for a long time when lazytime is
  602. * enabled, and thus pinning the dying cgwbs. It won't break the
  603. * bandwidth restrictions, as writeback of inode metadata is not
  604. * accounted for.
  605. */
  606. restart = isw_prepare_wbs_switch(isw, &wb->b_attached, &nr);
  607. if (!restart)
  608. restart = isw_prepare_wbs_switch(isw, &wb->b_dirty_time, &nr);
  609. spin_unlock(&wb->list_lock);
  610. /* no attached inodes? bail out */
  611. if (nr == 0) {
  612. atomic_dec(&isw_nr_in_flight);
  613. wb_put(isw->new_wb);
  614. kfree(isw);
  615. return restart;
  616. }
  617. /*
  618. * In addition to synchronizing among switchers, I_WB_SWITCH tells
  619. * the RCU protected stat update paths to grab the i_page
  620. * lock so that stat transfer can synchronize against them.
  621. * Let's continue after I_WB_SWITCH is guaranteed to be visible.
  622. */
  623. INIT_RCU_WORK(&isw->work, inode_switch_wbs_work_fn);
  624. queue_rcu_work(isw_wq, &isw->work);
  625. return restart;
  626. }
  627. /**
  628. * wbc_attach_and_unlock_inode - associate wbc with target inode and unlock it
  629. * @wbc: writeback_control of interest
  630. * @inode: target inode
  631. *
  632. * @inode is locked and about to be written back under the control of @wbc.
  633. * Record @inode's writeback context into @wbc and unlock the i_lock. On
  634. * writeback completion, wbc_detach_inode() should be called. This is used
  635. * to track the cgroup writeback context.
  636. */
  637. void wbc_attach_and_unlock_inode(struct writeback_control *wbc,
  638. struct inode *inode)
  639. {
  640. if (!inode_cgwb_enabled(inode)) {
  641. spin_unlock(&inode->i_lock);
  642. return;
  643. }
  644. wbc->wb = inode_to_wb(inode);
  645. wbc->inode = inode;
  646. wbc->wb_id = wbc->wb->memcg_css->id;
  647. wbc->wb_lcand_id = inode->i_wb_frn_winner;
  648. wbc->wb_tcand_id = 0;
  649. wbc->wb_bytes = 0;
  650. wbc->wb_lcand_bytes = 0;
  651. wbc->wb_tcand_bytes = 0;
  652. wb_get(wbc->wb);
  653. spin_unlock(&inode->i_lock);
  654. /*
  655. * A dying wb indicates that either the blkcg associated with the
  656. * memcg changed or the associated memcg is dying. In the first
  657. * case, a replacement wb should already be available and we should
  658. * refresh the wb immediately. In the second case, trying to
  659. * refresh will keep failing.
  660. */
  661. if (unlikely(wb_dying(wbc->wb) && !css_is_dying(wbc->wb->memcg_css)))
  662. inode_switch_wbs(inode, wbc->wb_id);
  663. }
  664. EXPORT_SYMBOL_GPL(wbc_attach_and_unlock_inode);
  665. /**
  666. * wbc_detach_inode - disassociate wbc from inode and perform foreign detection
  667. * @wbc: writeback_control of the just finished writeback
  668. *
  669. * To be called after a writeback attempt of an inode finishes and undoes
  670. * wbc_attach_and_unlock_inode(). Can be called under any context.
  671. *
  672. * As concurrent write sharing of an inode is expected to be very rare and
  673. * memcg only tracks page ownership on first-use basis severely confining
  674. * the usefulness of such sharing, cgroup writeback tracks ownership
  675. * per-inode. While the support for concurrent write sharing of an inode
  676. * is deemed unnecessary, an inode being written to by different cgroups at
  677. * different points in time is a lot more common, and, more importantly,
  678. * charging only by first-use can too readily lead to grossly incorrect
  679. * behaviors (single foreign page can lead to gigabytes of writeback to be
  680. * incorrectly attributed).
  681. *
  682. * To resolve this issue, cgroup writeback detects the majority dirtier of
  683. * an inode and transfers the ownership to it. To avoid unnecessary
  684. * oscillation, the detection mechanism keeps track of history and gives
  685. * out the switch verdict only if the foreign usage pattern is stable over
  686. * a certain amount of time and/or writeback attempts.
  687. *
  688. * On each writeback attempt, @wbc tries to detect the majority writer
  689. * using Boyer-Moore majority vote algorithm. In addition to the byte
  690. * count from the majority voting, it also counts the bytes written for the
  691. * current wb and the last round's winner wb (max of last round's current
  692. * wb, the winner from two rounds ago, and the last round's majority
  693. * candidate). Keeping track of the historical winner helps the algorithm
  694. * to semi-reliably detect the most active writer even when it's not the
  695. * absolute majority.
  696. *
  697. * Once the winner of the round is determined, whether the winner is
  698. * foreign or not and how much IO time the round consumed is recorded in
  699. * inode->i_wb_frn_history. If the amount of recorded foreign IO time is
  700. * over a certain threshold, the switch verdict is given.
  701. */
  702. void wbc_detach_inode(struct writeback_control *wbc)
  703. {
  704. struct bdi_writeback *wb = wbc->wb;
  705. struct inode *inode = wbc->inode;
  706. unsigned long avg_time, max_bytes, max_time;
  707. u16 history;
  708. int max_id;
  709. if (!wb)
  710. return;
  711. history = inode->i_wb_frn_history;
  712. avg_time = inode->i_wb_frn_avg_time;
  713. /* pick the winner of this round */
  714. if (wbc->wb_bytes >= wbc->wb_lcand_bytes &&
  715. wbc->wb_bytes >= wbc->wb_tcand_bytes) {
  716. max_id = wbc->wb_id;
  717. max_bytes = wbc->wb_bytes;
  718. } else if (wbc->wb_lcand_bytes >= wbc->wb_tcand_bytes) {
  719. max_id = wbc->wb_lcand_id;
  720. max_bytes = wbc->wb_lcand_bytes;
  721. } else {
  722. max_id = wbc->wb_tcand_id;
  723. max_bytes = wbc->wb_tcand_bytes;
  724. }
  725. /*
  726. * Calculate the amount of IO time the winner consumed and fold it
  727. * into the running average kept per inode. If the consumed IO
  728. * time is lower than avag / WB_FRN_TIME_CUT_DIV, ignore it for
  729. * deciding whether to switch or not. This is to prevent one-off
  730. * small dirtiers from skewing the verdict.
  731. */
  732. max_time = DIV_ROUND_UP((max_bytes >> PAGE_SHIFT) << WB_FRN_TIME_SHIFT,
  733. wb->avg_write_bandwidth);
  734. if (avg_time)
  735. avg_time += (max_time >> WB_FRN_TIME_AVG_SHIFT) -
  736. (avg_time >> WB_FRN_TIME_AVG_SHIFT);
  737. else
  738. avg_time = max_time; /* immediate catch up on first run */
  739. if (max_time >= avg_time / WB_FRN_TIME_CUT_DIV) {
  740. int slots;
  741. /*
  742. * The switch verdict is reached if foreign wb's consume
  743. * more than a certain proportion of IO time in a
  744. * WB_FRN_TIME_PERIOD. This is loosely tracked by 16 slot
  745. * history mask where each bit represents one sixteenth of
  746. * the period. Determine the number of slots to shift into
  747. * history from @max_time.
  748. */
  749. slots = min(DIV_ROUND_UP(max_time, WB_FRN_HIST_UNIT),
  750. (unsigned long)WB_FRN_HIST_MAX_SLOTS);
  751. history <<= slots;
  752. if (wbc->wb_id != max_id)
  753. history |= (1U << slots) - 1;
  754. if (history)
  755. trace_inode_foreign_history(inode, wbc, history);
  756. /*
  757. * Switch if the current wb isn't the consistent winner.
  758. * If there are multiple closely competing dirtiers, the
  759. * inode may switch across them repeatedly over time, which
  760. * is okay. The main goal is avoiding keeping an inode on
  761. * the wrong wb for an extended period of time.
  762. */
  763. if (hweight16(history) > WB_FRN_HIST_THR_SLOTS)
  764. inode_switch_wbs(inode, max_id);
  765. }
  766. /*
  767. * Multiple instances of this function may race to update the
  768. * following fields but we don't mind occassional inaccuracies.
  769. */
  770. inode->i_wb_frn_winner = max_id;
  771. inode->i_wb_frn_avg_time = min(avg_time, (unsigned long)U16_MAX);
  772. inode->i_wb_frn_history = history;
  773. wb_put(wbc->wb);
  774. wbc->wb = NULL;
  775. }
  776. EXPORT_SYMBOL_GPL(wbc_detach_inode);
  777. /**
  778. * wbc_account_cgroup_owner - account writeback to update inode cgroup ownership
  779. * @wbc: writeback_control of the writeback in progress
  780. * @folio: folio being written out
  781. * @bytes: number of bytes being written out
  782. *
  783. * @bytes from @folio are about to written out during the writeback
  784. * controlled by @wbc. Keep the book for foreign inode detection. See
  785. * wbc_detach_inode().
  786. */
  787. void wbc_account_cgroup_owner(struct writeback_control *wbc, struct folio *folio,
  788. size_t bytes)
  789. {
  790. struct cgroup_subsys_state *css;
  791. int id;
  792. /*
  793. * pageout() path doesn't attach @wbc to the inode being written
  794. * out. This is intentional as we don't want the function to block
  795. * behind a slow cgroup. Ultimately, we want pageout() to kick off
  796. * regular writeback instead of writing things out itself.
  797. */
  798. if (!wbc->wb || wbc->no_cgroup_owner)
  799. return;
  800. css = mem_cgroup_css_from_folio(folio);
  801. /* dead cgroups shouldn't contribute to inode ownership arbitration */
  802. if (!(css->flags & CSS_ONLINE))
  803. return;
  804. id = css->id;
  805. if (id == wbc->wb_id) {
  806. wbc->wb_bytes += bytes;
  807. return;
  808. }
  809. if (id == wbc->wb_lcand_id)
  810. wbc->wb_lcand_bytes += bytes;
  811. /* Boyer-Moore majority vote algorithm */
  812. if (!wbc->wb_tcand_bytes)
  813. wbc->wb_tcand_id = id;
  814. if (id == wbc->wb_tcand_id)
  815. wbc->wb_tcand_bytes += bytes;
  816. else
  817. wbc->wb_tcand_bytes -= min(bytes, wbc->wb_tcand_bytes);
  818. }
  819. EXPORT_SYMBOL_GPL(wbc_account_cgroup_owner);
  820. /**
  821. * wb_split_bdi_pages - split nr_pages to write according to bandwidth
  822. * @wb: target bdi_writeback to split @nr_pages to
  823. * @nr_pages: number of pages to write for the whole bdi
  824. *
  825. * Split @wb's portion of @nr_pages according to @wb's write bandwidth in
  826. * relation to the total write bandwidth of all wb's w/ dirty inodes on
  827. * @wb->bdi.
  828. */
  829. static long wb_split_bdi_pages(struct bdi_writeback *wb, long nr_pages)
  830. {
  831. unsigned long this_bw = wb->avg_write_bandwidth;
  832. unsigned long tot_bw = atomic_long_read(&wb->bdi->tot_write_bandwidth);
  833. if (nr_pages == LONG_MAX)
  834. return LONG_MAX;
  835. /*
  836. * This may be called on clean wb's and proportional distribution
  837. * may not make sense, just use the original @nr_pages in those
  838. * cases. In general, we wanna err on the side of writing more.
  839. */
  840. if (!tot_bw || this_bw >= tot_bw)
  841. return nr_pages;
  842. else
  843. return DIV_ROUND_UP_ULL((u64)nr_pages * this_bw, tot_bw);
  844. }
  845. /**
  846. * bdi_split_work_to_wbs - split a wb_writeback_work to all wb's of a bdi
  847. * @bdi: target backing_dev_info
  848. * @base_work: wb_writeback_work to issue
  849. * @skip_if_busy: skip wb's which already have writeback in progress
  850. *
  851. * Split and issue @base_work to all wb's (bdi_writeback's) of @bdi which
  852. * have dirty inodes. If @base_work->nr_page isn't %LONG_MAX, it's
  853. * distributed to the busy wbs according to each wb's proportion in the
  854. * total active write bandwidth of @bdi.
  855. */
  856. static void bdi_split_work_to_wbs(struct backing_dev_info *bdi,
  857. struct wb_writeback_work *base_work,
  858. bool skip_if_busy)
  859. {
  860. struct bdi_writeback *last_wb = NULL;
  861. struct bdi_writeback *wb = list_entry(&bdi->wb_list,
  862. struct bdi_writeback, bdi_node);
  863. might_sleep();
  864. restart:
  865. rcu_read_lock();
  866. list_for_each_entry_continue_rcu(wb, &bdi->wb_list, bdi_node) {
  867. DEFINE_WB_COMPLETION(fallback_work_done, bdi);
  868. struct wb_writeback_work fallback_work;
  869. struct wb_writeback_work *work;
  870. long nr_pages;
  871. if (last_wb) {
  872. wb_put(last_wb);
  873. last_wb = NULL;
  874. }
  875. /* SYNC_ALL writes out I_DIRTY_TIME too */
  876. if (!wb_has_dirty_io(wb) &&
  877. (base_work->sync_mode == WB_SYNC_NONE ||
  878. list_empty(&wb->b_dirty_time)))
  879. continue;
  880. if (skip_if_busy && writeback_in_progress(wb))
  881. continue;
  882. nr_pages = wb_split_bdi_pages(wb, base_work->nr_pages);
  883. work = kmalloc(sizeof(*work), GFP_ATOMIC);
  884. if (work) {
  885. *work = *base_work;
  886. work->nr_pages = nr_pages;
  887. work->auto_free = 1;
  888. wb_queue_work(wb, work);
  889. continue;
  890. }
  891. /*
  892. * If wb_tryget fails, the wb has been shutdown, skip it.
  893. *
  894. * Pin @wb so that it stays on @bdi->wb_list. This allows
  895. * continuing iteration from @wb after dropping and
  896. * regrabbing rcu read lock.
  897. */
  898. if (!wb_tryget(wb))
  899. continue;
  900. /* alloc failed, execute synchronously using on-stack fallback */
  901. work = &fallback_work;
  902. *work = *base_work;
  903. work->nr_pages = nr_pages;
  904. work->auto_free = 0;
  905. work->done = &fallback_work_done;
  906. wb_queue_work(wb, work);
  907. last_wb = wb;
  908. rcu_read_unlock();
  909. wb_wait_for_completion(&fallback_work_done);
  910. goto restart;
  911. }
  912. rcu_read_unlock();
  913. if (last_wb)
  914. wb_put(last_wb);
  915. }
  916. /**
  917. * cgroup_writeback_by_id - initiate cgroup writeback from bdi and memcg IDs
  918. * @bdi_id: target bdi id
  919. * @memcg_id: target memcg css id
  920. * @reason: reason why some writeback work initiated
  921. * @done: target wb_completion
  922. *
  923. * Initiate flush of the bdi_writeback identified by @bdi_id and @memcg_id
  924. * with the specified parameters.
  925. */
  926. int cgroup_writeback_by_id(u64 bdi_id, int memcg_id,
  927. enum wb_reason reason, struct wb_completion *done)
  928. {
  929. struct backing_dev_info *bdi;
  930. struct cgroup_subsys_state *memcg_css;
  931. struct bdi_writeback *wb;
  932. struct wb_writeback_work *work;
  933. unsigned long dirty;
  934. int ret;
  935. /* lookup bdi and memcg */
  936. bdi = bdi_get_by_id(bdi_id);
  937. if (!bdi)
  938. return -ENOENT;
  939. rcu_read_lock();
  940. memcg_css = css_from_id(memcg_id, &memory_cgrp_subsys);
  941. if (memcg_css && !css_tryget(memcg_css))
  942. memcg_css = NULL;
  943. rcu_read_unlock();
  944. if (!memcg_css) {
  945. ret = -ENOENT;
  946. goto out_bdi_put;
  947. }
  948. /*
  949. * And find the associated wb. If the wb isn't there already
  950. * there's nothing to flush, don't create one.
  951. */
  952. wb = wb_get_lookup(bdi, memcg_css);
  953. if (!wb) {
  954. ret = -ENOENT;
  955. goto out_css_put;
  956. }
  957. /*
  958. * The caller is attempting to write out most of
  959. * the currently dirty pages. Let's take the current dirty page
  960. * count and inflate it by 25% which should be large enough to
  961. * flush out most dirty pages while avoiding getting livelocked by
  962. * concurrent dirtiers.
  963. *
  964. * BTW the memcg stats are flushed periodically and this is best-effort
  965. * estimation, so some potential error is ok.
  966. */
  967. dirty = memcg_page_state(mem_cgroup_from_css(memcg_css), NR_FILE_DIRTY);
  968. dirty = dirty * 10 / 8;
  969. /* issue the writeback work */
  970. work = kzalloc(sizeof(*work), GFP_NOWAIT | __GFP_NOWARN);
  971. if (work) {
  972. work->nr_pages = dirty;
  973. work->sync_mode = WB_SYNC_NONE;
  974. work->range_cyclic = 1;
  975. work->reason = reason;
  976. work->done = done;
  977. work->auto_free = 1;
  978. wb_queue_work(wb, work);
  979. ret = 0;
  980. } else {
  981. ret = -ENOMEM;
  982. }
  983. wb_put(wb);
  984. out_css_put:
  985. css_put(memcg_css);
  986. out_bdi_put:
  987. bdi_put(bdi);
  988. return ret;
  989. }
  990. /**
  991. * cgroup_writeback_umount - flush inode wb switches for umount
  992. * @sb: target super_block
  993. *
  994. * This function is called when a super_block is about to be destroyed and
  995. * flushes in-flight inode wb switches. An inode wb switch goes through
  996. * RCU and then workqueue, so the two need to be flushed in order to ensure
  997. * that all previously scheduled switches are finished. As wb switches are
  998. * rare occurrences and synchronize_rcu() can take a while, perform
  999. * flushing iff wb switches are in flight.
  1000. */
  1001. void cgroup_writeback_umount(struct super_block *sb)
  1002. {
  1003. if (!(sb->s_bdi->capabilities & BDI_CAP_WRITEBACK))
  1004. return;
  1005. /*
  1006. * SB_ACTIVE should be reliably cleared before checking
  1007. * isw_nr_in_flight, see generic_shutdown_super().
  1008. */
  1009. smp_mb();
  1010. if (atomic_read(&isw_nr_in_flight)) {
  1011. /*
  1012. * Use rcu_barrier() to wait for all pending callbacks to
  1013. * ensure that all in-flight wb switches are in the workqueue.
  1014. */
  1015. rcu_barrier();
  1016. flush_workqueue(isw_wq);
  1017. }
  1018. }
  1019. static int __init cgroup_writeback_init(void)
  1020. {
  1021. isw_wq = alloc_workqueue("inode_switch_wbs", 0, 0);
  1022. if (!isw_wq)
  1023. return -ENOMEM;
  1024. return 0;
  1025. }
  1026. fs_initcall(cgroup_writeback_init);
  1027. #else /* CONFIG_CGROUP_WRITEBACK */
  1028. static void bdi_down_write_wb_switch_rwsem(struct backing_dev_info *bdi) { }
  1029. static void bdi_up_write_wb_switch_rwsem(struct backing_dev_info *bdi) { }
  1030. static void inode_cgwb_move_to_attached(struct inode *inode,
  1031. struct bdi_writeback *wb)
  1032. {
  1033. assert_spin_locked(&wb->list_lock);
  1034. assert_spin_locked(&inode->i_lock);
  1035. WARN_ON_ONCE(inode->i_state & I_FREEING);
  1036. inode->i_state &= ~I_SYNC_QUEUED;
  1037. list_del_init(&inode->i_io_list);
  1038. wb_io_lists_depopulated(wb);
  1039. }
  1040. static struct bdi_writeback *
  1041. locked_inode_to_wb_and_lock_list(struct inode *inode)
  1042. __releases(&inode->i_lock)
  1043. __acquires(&wb->list_lock)
  1044. {
  1045. struct bdi_writeback *wb = inode_to_wb(inode);
  1046. spin_unlock(&inode->i_lock);
  1047. spin_lock(&wb->list_lock);
  1048. return wb;
  1049. }
  1050. static struct bdi_writeback *inode_to_wb_and_lock_list(struct inode *inode)
  1051. __acquires(&wb->list_lock)
  1052. {
  1053. struct bdi_writeback *wb = inode_to_wb(inode);
  1054. spin_lock(&wb->list_lock);
  1055. return wb;
  1056. }
  1057. static long wb_split_bdi_pages(struct bdi_writeback *wb, long nr_pages)
  1058. {
  1059. return nr_pages;
  1060. }
  1061. static void bdi_split_work_to_wbs(struct backing_dev_info *bdi,
  1062. struct wb_writeback_work *base_work,
  1063. bool skip_if_busy)
  1064. {
  1065. might_sleep();
  1066. if (!skip_if_busy || !writeback_in_progress(&bdi->wb)) {
  1067. base_work->auto_free = 0;
  1068. wb_queue_work(&bdi->wb, base_work);
  1069. }
  1070. }
  1071. #endif /* CONFIG_CGROUP_WRITEBACK */
  1072. /*
  1073. * Add in the number of potentially dirty inodes, because each inode
  1074. * write can dirty pagecache in the underlying blockdev.
  1075. */
  1076. static unsigned long get_nr_dirty_pages(void)
  1077. {
  1078. return global_node_page_state(NR_FILE_DIRTY) +
  1079. get_nr_dirty_inodes();
  1080. }
  1081. static void wb_start_writeback(struct bdi_writeback *wb, enum wb_reason reason)
  1082. {
  1083. if (!wb_has_dirty_io(wb))
  1084. return;
  1085. /*
  1086. * All callers of this function want to start writeback of all
  1087. * dirty pages. Places like vmscan can call this at a very
  1088. * high frequency, causing pointless allocations of tons of
  1089. * work items and keeping the flusher threads busy retrieving
  1090. * that work. Ensure that we only allow one of them pending and
  1091. * inflight at the time.
  1092. */
  1093. if (test_bit(WB_start_all, &wb->state) ||
  1094. test_and_set_bit(WB_start_all, &wb->state))
  1095. return;
  1096. wb->start_all_reason = reason;
  1097. wb_wakeup(wb);
  1098. }
  1099. /**
  1100. * wb_start_background_writeback - start background writeback
  1101. * @wb: bdi_writback to write from
  1102. *
  1103. * Description:
  1104. * This makes sure WB_SYNC_NONE background writeback happens. When
  1105. * this function returns, it is only guaranteed that for given wb
  1106. * some IO is happening if we are over background dirty threshold.
  1107. * Caller need not hold sb s_umount semaphore.
  1108. */
  1109. void wb_start_background_writeback(struct bdi_writeback *wb)
  1110. {
  1111. /*
  1112. * We just wake up the flusher thread. It will perform background
  1113. * writeback as soon as there is no other work to do.
  1114. */
  1115. trace_writeback_wake_background(wb);
  1116. wb_wakeup(wb);
  1117. }
  1118. /*
  1119. * Remove the inode from the writeback list it is on.
  1120. */
  1121. void inode_io_list_del(struct inode *inode)
  1122. {
  1123. struct bdi_writeback *wb;
  1124. wb = inode_to_wb_and_lock_list(inode);
  1125. spin_lock(&inode->i_lock);
  1126. inode->i_state &= ~I_SYNC_QUEUED;
  1127. list_del_init(&inode->i_io_list);
  1128. wb_io_lists_depopulated(wb);
  1129. spin_unlock(&inode->i_lock);
  1130. spin_unlock(&wb->list_lock);
  1131. }
  1132. EXPORT_SYMBOL(inode_io_list_del);
  1133. /*
  1134. * mark an inode as under writeback on the sb
  1135. */
  1136. void sb_mark_inode_writeback(struct inode *inode)
  1137. {
  1138. struct super_block *sb = inode->i_sb;
  1139. unsigned long flags;
  1140. if (list_empty(&inode->i_wb_list)) {
  1141. spin_lock_irqsave(&sb->s_inode_wblist_lock, flags);
  1142. if (list_empty(&inode->i_wb_list)) {
  1143. list_add_tail(&inode->i_wb_list, &sb->s_inodes_wb);
  1144. trace_sb_mark_inode_writeback(inode);
  1145. }
  1146. spin_unlock_irqrestore(&sb->s_inode_wblist_lock, flags);
  1147. }
  1148. }
  1149. /*
  1150. * clear an inode as under writeback on the sb
  1151. */
  1152. void sb_clear_inode_writeback(struct inode *inode)
  1153. {
  1154. struct super_block *sb = inode->i_sb;
  1155. unsigned long flags;
  1156. if (!list_empty(&inode->i_wb_list)) {
  1157. spin_lock_irqsave(&sb->s_inode_wblist_lock, flags);
  1158. if (!list_empty(&inode->i_wb_list)) {
  1159. list_del_init(&inode->i_wb_list);
  1160. trace_sb_clear_inode_writeback(inode);
  1161. }
  1162. spin_unlock_irqrestore(&sb->s_inode_wblist_lock, flags);
  1163. }
  1164. }
  1165. /*
  1166. * Redirty an inode: set its when-it-was dirtied timestamp and move it to the
  1167. * furthest end of its superblock's dirty-inode list.
  1168. *
  1169. * Before stamping the inode's ->dirtied_when, we check to see whether it is
  1170. * already the most-recently-dirtied inode on the b_dirty list. If that is
  1171. * the case then the inode must have been redirtied while it was being written
  1172. * out and we don't reset its dirtied_when.
  1173. */
  1174. static void redirty_tail_locked(struct inode *inode, struct bdi_writeback *wb)
  1175. {
  1176. assert_spin_locked(&inode->i_lock);
  1177. inode->i_state &= ~I_SYNC_QUEUED;
  1178. /*
  1179. * When the inode is being freed just don't bother with dirty list
  1180. * tracking. Flush worker will ignore this inode anyway and it will
  1181. * trigger assertions in inode_io_list_move_locked().
  1182. */
  1183. if (inode->i_state & I_FREEING) {
  1184. list_del_init(&inode->i_io_list);
  1185. wb_io_lists_depopulated(wb);
  1186. return;
  1187. }
  1188. if (!list_empty(&wb->b_dirty)) {
  1189. struct inode *tail;
  1190. tail = wb_inode(wb->b_dirty.next);
  1191. if (time_before(inode->dirtied_when, tail->dirtied_when))
  1192. inode->dirtied_when = jiffies;
  1193. }
  1194. inode_io_list_move_locked(inode, wb, &wb->b_dirty);
  1195. }
  1196. static void redirty_tail(struct inode *inode, struct bdi_writeback *wb)
  1197. {
  1198. spin_lock(&inode->i_lock);
  1199. redirty_tail_locked(inode, wb);
  1200. spin_unlock(&inode->i_lock);
  1201. }
  1202. /*
  1203. * requeue inode for re-scanning after bdi->b_io list is exhausted.
  1204. */
  1205. static void requeue_io(struct inode *inode, struct bdi_writeback *wb)
  1206. {
  1207. inode_io_list_move_locked(inode, wb, &wb->b_more_io);
  1208. }
  1209. static void inode_sync_complete(struct inode *inode)
  1210. {
  1211. assert_spin_locked(&inode->i_lock);
  1212. inode->i_state &= ~I_SYNC;
  1213. /* If inode is clean an unused, put it into LRU now... */
  1214. inode_add_lru(inode);
  1215. /* Called with inode->i_lock which ensures memory ordering. */
  1216. inode_wake_up_bit(inode, __I_SYNC);
  1217. }
  1218. static bool inode_dirtied_after(struct inode *inode, unsigned long t)
  1219. {
  1220. bool ret = time_after(inode->dirtied_when, t);
  1221. #ifndef CONFIG_64BIT
  1222. /*
  1223. * For inodes being constantly redirtied, dirtied_when can get stuck.
  1224. * It _appears_ to be in the future, but is actually in distant past.
  1225. * This test is necessary to prevent such wrapped-around relative times
  1226. * from permanently stopping the whole bdi writeback.
  1227. */
  1228. ret = ret && time_before_eq(inode->dirtied_when, jiffies);
  1229. #endif
  1230. return ret;
  1231. }
  1232. /*
  1233. * Move expired (dirtied before dirtied_before) dirty inodes from
  1234. * @delaying_queue to @dispatch_queue.
  1235. */
  1236. static int move_expired_inodes(struct list_head *delaying_queue,
  1237. struct list_head *dispatch_queue,
  1238. unsigned long dirtied_before)
  1239. {
  1240. LIST_HEAD(tmp);
  1241. struct list_head *pos, *node;
  1242. struct super_block *sb = NULL;
  1243. struct inode *inode;
  1244. int do_sb_sort = 0;
  1245. int moved = 0;
  1246. while (!list_empty(delaying_queue)) {
  1247. inode = wb_inode(delaying_queue->prev);
  1248. if (inode_dirtied_after(inode, dirtied_before))
  1249. break;
  1250. spin_lock(&inode->i_lock);
  1251. list_move(&inode->i_io_list, &tmp);
  1252. moved++;
  1253. inode->i_state |= I_SYNC_QUEUED;
  1254. spin_unlock(&inode->i_lock);
  1255. if (sb_is_blkdev_sb(inode->i_sb))
  1256. continue;
  1257. if (sb && sb != inode->i_sb)
  1258. do_sb_sort = 1;
  1259. sb = inode->i_sb;
  1260. }
  1261. /* just one sb in list, splice to dispatch_queue and we're done */
  1262. if (!do_sb_sort) {
  1263. list_splice(&tmp, dispatch_queue);
  1264. goto out;
  1265. }
  1266. /*
  1267. * Although inode's i_io_list is moved from 'tmp' to 'dispatch_queue',
  1268. * we don't take inode->i_lock here because it is just a pointless overhead.
  1269. * Inode is already marked as I_SYNC_QUEUED so writeback list handling is
  1270. * fully under our control.
  1271. */
  1272. while (!list_empty(&tmp)) {
  1273. sb = wb_inode(tmp.prev)->i_sb;
  1274. list_for_each_prev_safe(pos, node, &tmp) {
  1275. inode = wb_inode(pos);
  1276. if (inode->i_sb == sb)
  1277. list_move(&inode->i_io_list, dispatch_queue);
  1278. }
  1279. }
  1280. out:
  1281. return moved;
  1282. }
  1283. /*
  1284. * Queue all expired dirty inodes for io, eldest first.
  1285. * Before
  1286. * newly dirtied b_dirty b_io b_more_io
  1287. * =============> gf edc BA
  1288. * After
  1289. * newly dirtied b_dirty b_io b_more_io
  1290. * =============> g fBAedc
  1291. * |
  1292. * +--> dequeue for IO
  1293. */
  1294. static void queue_io(struct bdi_writeback *wb, struct wb_writeback_work *work,
  1295. unsigned long dirtied_before)
  1296. {
  1297. int moved;
  1298. unsigned long time_expire_jif = dirtied_before;
  1299. assert_spin_locked(&wb->list_lock);
  1300. list_splice_init(&wb->b_more_io, &wb->b_io);
  1301. moved = move_expired_inodes(&wb->b_dirty, &wb->b_io, dirtied_before);
  1302. if (!work->for_sync)
  1303. time_expire_jif = jiffies - dirtytime_expire_interval * HZ;
  1304. moved += move_expired_inodes(&wb->b_dirty_time, &wb->b_io,
  1305. time_expire_jif);
  1306. if (moved)
  1307. wb_io_lists_populated(wb);
  1308. trace_writeback_queue_io(wb, work, dirtied_before, moved);
  1309. }
  1310. static int write_inode(struct inode *inode, struct writeback_control *wbc)
  1311. {
  1312. int ret;
  1313. if (inode->i_sb->s_op->write_inode && !is_bad_inode(inode)) {
  1314. trace_writeback_write_inode_start(inode, wbc);
  1315. ret = inode->i_sb->s_op->write_inode(inode, wbc);
  1316. trace_writeback_write_inode(inode, wbc);
  1317. return ret;
  1318. }
  1319. return 0;
  1320. }
  1321. /*
  1322. * Wait for writeback on an inode to complete. Called with i_lock held.
  1323. * Caller must make sure inode cannot go away when we drop i_lock.
  1324. */
  1325. void inode_wait_for_writeback(struct inode *inode)
  1326. {
  1327. struct wait_bit_queue_entry wqe;
  1328. struct wait_queue_head *wq_head;
  1329. assert_spin_locked(&inode->i_lock);
  1330. if (!(inode->i_state & I_SYNC))
  1331. return;
  1332. wq_head = inode_bit_waitqueue(&wqe, inode, __I_SYNC);
  1333. for (;;) {
  1334. prepare_to_wait_event(wq_head, &wqe.wq_entry, TASK_UNINTERRUPTIBLE);
  1335. /* Checking I_SYNC with inode->i_lock guarantees memory ordering. */
  1336. if (!(inode->i_state & I_SYNC))
  1337. break;
  1338. spin_unlock(&inode->i_lock);
  1339. schedule();
  1340. spin_lock(&inode->i_lock);
  1341. }
  1342. finish_wait(wq_head, &wqe.wq_entry);
  1343. }
  1344. /*
  1345. * Sleep until I_SYNC is cleared. This function must be called with i_lock
  1346. * held and drops it. It is aimed for callers not holding any inode reference
  1347. * so once i_lock is dropped, inode can go away.
  1348. */
  1349. static void inode_sleep_on_writeback(struct inode *inode)
  1350. __releases(inode->i_lock)
  1351. {
  1352. struct wait_bit_queue_entry wqe;
  1353. struct wait_queue_head *wq_head;
  1354. bool sleep;
  1355. assert_spin_locked(&inode->i_lock);
  1356. wq_head = inode_bit_waitqueue(&wqe, inode, __I_SYNC);
  1357. prepare_to_wait_event(wq_head, &wqe.wq_entry, TASK_UNINTERRUPTIBLE);
  1358. /* Checking I_SYNC with inode->i_lock guarantees memory ordering. */
  1359. sleep = !!(inode->i_state & I_SYNC);
  1360. spin_unlock(&inode->i_lock);
  1361. if (sleep)
  1362. schedule();
  1363. finish_wait(wq_head, &wqe.wq_entry);
  1364. }
  1365. /*
  1366. * Find proper writeback list for the inode depending on its current state and
  1367. * possibly also change of its state while we were doing writeback. Here we
  1368. * handle things such as livelock prevention or fairness of writeback among
  1369. * inodes. This function can be called only by flusher thread - noone else
  1370. * processes all inodes in writeback lists and requeueing inodes behind flusher
  1371. * thread's back can have unexpected consequences.
  1372. */
  1373. static void requeue_inode(struct inode *inode, struct bdi_writeback *wb,
  1374. struct writeback_control *wbc,
  1375. unsigned long dirtied_before)
  1376. {
  1377. if (inode->i_state & I_FREEING)
  1378. return;
  1379. /*
  1380. * Sync livelock prevention. Each inode is tagged and synced in one
  1381. * shot. If still dirty, it will be redirty_tail()'ed below. Update
  1382. * the dirty time to prevent enqueue and sync it again.
  1383. */
  1384. if ((inode->i_state & I_DIRTY) &&
  1385. (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages))
  1386. inode->dirtied_when = jiffies;
  1387. if (wbc->pages_skipped) {
  1388. /*
  1389. * Writeback is not making progress due to locked buffers.
  1390. * Skip this inode for now. Although having skipped pages
  1391. * is odd for clean inodes, it can happen for some
  1392. * filesystems so handle that gracefully.
  1393. */
  1394. if (inode->i_state & I_DIRTY_ALL)
  1395. redirty_tail_locked(inode, wb);
  1396. else
  1397. inode_cgwb_move_to_attached(inode, wb);
  1398. return;
  1399. }
  1400. if (mapping_tagged(inode->i_mapping, PAGECACHE_TAG_DIRTY)) {
  1401. /*
  1402. * We didn't write back all the pages. nfs_writepages()
  1403. * sometimes bales out without doing anything.
  1404. */
  1405. if (wbc->nr_to_write <= 0 &&
  1406. !inode_dirtied_after(inode, dirtied_before)) {
  1407. /* Slice used up. Queue for next turn. */
  1408. requeue_io(inode, wb);
  1409. } else {
  1410. /*
  1411. * Writeback blocked by something other than
  1412. * congestion. Delay the inode for some time to
  1413. * avoid spinning on the CPU (100% iowait)
  1414. * retrying writeback of the dirty page/inode
  1415. * that cannot be performed immediately.
  1416. */
  1417. redirty_tail_locked(inode, wb);
  1418. }
  1419. } else if (inode->i_state & I_DIRTY) {
  1420. /*
  1421. * Filesystems can dirty the inode during writeback operations,
  1422. * such as delayed allocation during submission or metadata
  1423. * updates after data IO completion.
  1424. */
  1425. redirty_tail_locked(inode, wb);
  1426. } else if (inode->i_state & I_DIRTY_TIME) {
  1427. inode->dirtied_when = jiffies;
  1428. inode_io_list_move_locked(inode, wb, &wb->b_dirty_time);
  1429. inode->i_state &= ~I_SYNC_QUEUED;
  1430. } else {
  1431. /* The inode is clean. Remove from writeback lists. */
  1432. inode_cgwb_move_to_attached(inode, wb);
  1433. }
  1434. }
  1435. /*
  1436. * Write out an inode and its dirty pages (or some of its dirty pages, depending
  1437. * on @wbc->nr_to_write), and clear the relevant dirty flags from i_state.
  1438. *
  1439. * This doesn't remove the inode from the writeback list it is on, except
  1440. * potentially to move it from b_dirty_time to b_dirty due to timestamp
  1441. * expiration. The caller is otherwise responsible for writeback list handling.
  1442. *
  1443. * The caller is also responsible for setting the I_SYNC flag beforehand and
  1444. * calling inode_sync_complete() to clear it afterwards.
  1445. */
  1446. static int
  1447. __writeback_single_inode(struct inode *inode, struct writeback_control *wbc)
  1448. {
  1449. struct address_space *mapping = inode->i_mapping;
  1450. long nr_to_write = wbc->nr_to_write;
  1451. unsigned dirty;
  1452. int ret;
  1453. WARN_ON(!(inode->i_state & I_SYNC));
  1454. trace_writeback_single_inode_start(inode, wbc, nr_to_write);
  1455. ret = do_writepages(mapping, wbc);
  1456. /*
  1457. * Make sure to wait on the data before writing out the metadata.
  1458. * This is important for filesystems that modify metadata on data
  1459. * I/O completion. We don't do it for sync(2) writeback because it has a
  1460. * separate, external IO completion path and ->sync_fs for guaranteeing
  1461. * inode metadata is written back correctly.
  1462. */
  1463. if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync) {
  1464. int err = filemap_fdatawait(mapping);
  1465. if (ret == 0)
  1466. ret = err;
  1467. }
  1468. /*
  1469. * If the inode has dirty timestamps and we need to write them, call
  1470. * mark_inode_dirty_sync() to notify the filesystem about it and to
  1471. * change I_DIRTY_TIME into I_DIRTY_SYNC.
  1472. */
  1473. if ((inode->i_state & I_DIRTY_TIME) &&
  1474. (wbc->sync_mode == WB_SYNC_ALL ||
  1475. time_after(jiffies, inode->dirtied_time_when +
  1476. dirtytime_expire_interval * HZ))) {
  1477. trace_writeback_lazytime(inode);
  1478. mark_inode_dirty_sync(inode);
  1479. }
  1480. /*
  1481. * Get and clear the dirty flags from i_state. This needs to be done
  1482. * after calling writepages because some filesystems may redirty the
  1483. * inode during writepages due to delalloc. It also needs to be done
  1484. * after handling timestamp expiration, as that may dirty the inode too.
  1485. */
  1486. spin_lock(&inode->i_lock);
  1487. dirty = inode->i_state & I_DIRTY;
  1488. inode->i_state &= ~dirty;
  1489. /*
  1490. * Paired with smp_mb() in __mark_inode_dirty(). This allows
  1491. * __mark_inode_dirty() to test i_state without grabbing i_lock -
  1492. * either they see the I_DIRTY bits cleared or we see the dirtied
  1493. * inode.
  1494. *
  1495. * I_DIRTY_PAGES is always cleared together above even if @mapping
  1496. * still has dirty pages. The flag is reinstated after smp_mb() if
  1497. * necessary. This guarantees that either __mark_inode_dirty()
  1498. * sees clear I_DIRTY_PAGES or we see PAGECACHE_TAG_DIRTY.
  1499. */
  1500. smp_mb();
  1501. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  1502. inode->i_state |= I_DIRTY_PAGES;
  1503. else if (unlikely(inode->i_state & I_PINNING_NETFS_WB)) {
  1504. if (!(inode->i_state & I_DIRTY_PAGES)) {
  1505. inode->i_state &= ~I_PINNING_NETFS_WB;
  1506. wbc->unpinned_netfs_wb = true;
  1507. dirty |= I_PINNING_NETFS_WB; /* Cause write_inode */
  1508. }
  1509. }
  1510. spin_unlock(&inode->i_lock);
  1511. /* Don't write the inode if only I_DIRTY_PAGES was set */
  1512. if (dirty & ~I_DIRTY_PAGES) {
  1513. int err = write_inode(inode, wbc);
  1514. if (ret == 0)
  1515. ret = err;
  1516. }
  1517. wbc->unpinned_netfs_wb = false;
  1518. trace_writeback_single_inode(inode, wbc, nr_to_write);
  1519. return ret;
  1520. }
  1521. /*
  1522. * Write out an inode's dirty data and metadata on-demand, i.e. separately from
  1523. * the regular batched writeback done by the flusher threads in
  1524. * writeback_sb_inodes(). @wbc controls various aspects of the write, such as
  1525. * whether it is a data-integrity sync (%WB_SYNC_ALL) or not (%WB_SYNC_NONE).
  1526. *
  1527. * To prevent the inode from going away, either the caller must have a reference
  1528. * to the inode, or the inode must have I_WILL_FREE or I_FREEING set.
  1529. */
  1530. static int writeback_single_inode(struct inode *inode,
  1531. struct writeback_control *wbc)
  1532. {
  1533. struct bdi_writeback *wb;
  1534. int ret = 0;
  1535. spin_lock(&inode->i_lock);
  1536. if (!atomic_read(&inode->i_count))
  1537. WARN_ON(!(inode->i_state & (I_WILL_FREE|I_FREEING)));
  1538. else
  1539. WARN_ON(inode->i_state & I_WILL_FREE);
  1540. if (inode->i_state & I_SYNC) {
  1541. /*
  1542. * Writeback is already running on the inode. For WB_SYNC_NONE,
  1543. * that's enough and we can just return. For WB_SYNC_ALL, we
  1544. * must wait for the existing writeback to complete, then do
  1545. * writeback again if there's anything left.
  1546. */
  1547. if (wbc->sync_mode != WB_SYNC_ALL)
  1548. goto out;
  1549. inode_wait_for_writeback(inode);
  1550. }
  1551. WARN_ON(inode->i_state & I_SYNC);
  1552. /*
  1553. * If the inode is already fully clean, then there's nothing to do.
  1554. *
  1555. * For data-integrity syncs we also need to check whether any pages are
  1556. * still under writeback, e.g. due to prior WB_SYNC_NONE writeback. If
  1557. * there are any such pages, we'll need to wait for them.
  1558. */
  1559. if (!(inode->i_state & I_DIRTY_ALL) &&
  1560. (wbc->sync_mode != WB_SYNC_ALL ||
  1561. !mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK)))
  1562. goto out;
  1563. inode->i_state |= I_SYNC;
  1564. wbc_attach_and_unlock_inode(wbc, inode);
  1565. ret = __writeback_single_inode(inode, wbc);
  1566. wbc_detach_inode(wbc);
  1567. wb = inode_to_wb_and_lock_list(inode);
  1568. spin_lock(&inode->i_lock);
  1569. /*
  1570. * If the inode is freeing, its i_io_list shoudn't be updated
  1571. * as it can be finally deleted at this moment.
  1572. */
  1573. if (!(inode->i_state & I_FREEING)) {
  1574. /*
  1575. * If the inode is now fully clean, then it can be safely
  1576. * removed from its writeback list (if any). Otherwise the
  1577. * flusher threads are responsible for the writeback lists.
  1578. */
  1579. if (!(inode->i_state & I_DIRTY_ALL))
  1580. inode_cgwb_move_to_attached(inode, wb);
  1581. else if (!(inode->i_state & I_SYNC_QUEUED)) {
  1582. if ((inode->i_state & I_DIRTY))
  1583. redirty_tail_locked(inode, wb);
  1584. else if (inode->i_state & I_DIRTY_TIME) {
  1585. inode->dirtied_when = jiffies;
  1586. inode_io_list_move_locked(inode,
  1587. wb,
  1588. &wb->b_dirty_time);
  1589. }
  1590. }
  1591. }
  1592. spin_unlock(&wb->list_lock);
  1593. inode_sync_complete(inode);
  1594. out:
  1595. spin_unlock(&inode->i_lock);
  1596. return ret;
  1597. }
  1598. static long writeback_chunk_size(struct bdi_writeback *wb,
  1599. struct wb_writeback_work *work)
  1600. {
  1601. long pages;
  1602. /*
  1603. * WB_SYNC_ALL mode does livelock avoidance by syncing dirty
  1604. * inodes/pages in one big loop. Setting wbc.nr_to_write=LONG_MAX
  1605. * here avoids calling into writeback_inodes_wb() more than once.
  1606. *
  1607. * The intended call sequence for WB_SYNC_ALL writeback is:
  1608. *
  1609. * wb_writeback()
  1610. * writeback_sb_inodes() <== called only once
  1611. * write_cache_pages() <== called once for each inode
  1612. * (quickly) tag currently dirty pages
  1613. * (maybe slowly) sync all tagged pages
  1614. */
  1615. if (work->sync_mode == WB_SYNC_ALL || work->tagged_writepages)
  1616. pages = LONG_MAX;
  1617. else {
  1618. pages = min(wb->avg_write_bandwidth / 2,
  1619. global_wb_domain.dirty_limit / DIRTY_SCOPE);
  1620. pages = min(pages, work->nr_pages);
  1621. pages = round_down(pages + MIN_WRITEBACK_PAGES,
  1622. MIN_WRITEBACK_PAGES);
  1623. }
  1624. return pages;
  1625. }
  1626. /*
  1627. * Write a portion of b_io inodes which belong to @sb.
  1628. *
  1629. * Return the number of pages and/or inodes written.
  1630. *
  1631. * NOTE! This is called with wb->list_lock held, and will
  1632. * unlock and relock that for each inode it ends up doing
  1633. * IO for.
  1634. */
  1635. static long writeback_sb_inodes(struct super_block *sb,
  1636. struct bdi_writeback *wb,
  1637. struct wb_writeback_work *work)
  1638. {
  1639. struct writeback_control wbc = {
  1640. .sync_mode = work->sync_mode,
  1641. .tagged_writepages = work->tagged_writepages,
  1642. .for_kupdate = work->for_kupdate,
  1643. .for_background = work->for_background,
  1644. .for_sync = work->for_sync,
  1645. .range_cyclic = work->range_cyclic,
  1646. .range_start = 0,
  1647. .range_end = LLONG_MAX,
  1648. };
  1649. unsigned long start_time = jiffies;
  1650. long write_chunk;
  1651. long total_wrote = 0; /* count both pages and inodes */
  1652. unsigned long dirtied_before = jiffies;
  1653. if (work->for_kupdate)
  1654. dirtied_before = jiffies -
  1655. msecs_to_jiffies(dirty_expire_interval * 10);
  1656. while (!list_empty(&wb->b_io)) {
  1657. struct inode *inode = wb_inode(wb->b_io.prev);
  1658. struct bdi_writeback *tmp_wb;
  1659. long wrote;
  1660. if (inode->i_sb != sb) {
  1661. if (work->sb) {
  1662. /*
  1663. * We only want to write back data for this
  1664. * superblock, move all inodes not belonging
  1665. * to it back onto the dirty list.
  1666. */
  1667. redirty_tail(inode, wb);
  1668. continue;
  1669. }
  1670. /*
  1671. * The inode belongs to a different superblock.
  1672. * Bounce back to the caller to unpin this and
  1673. * pin the next superblock.
  1674. */
  1675. break;
  1676. }
  1677. /*
  1678. * Don't bother with new inodes or inodes being freed, first
  1679. * kind does not need periodic writeout yet, and for the latter
  1680. * kind writeout is handled by the freer.
  1681. */
  1682. spin_lock(&inode->i_lock);
  1683. if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) {
  1684. redirty_tail_locked(inode, wb);
  1685. spin_unlock(&inode->i_lock);
  1686. continue;
  1687. }
  1688. if ((inode->i_state & I_SYNC) && wbc.sync_mode != WB_SYNC_ALL) {
  1689. /*
  1690. * If this inode is locked for writeback and we are not
  1691. * doing writeback-for-data-integrity, move it to
  1692. * b_more_io so that writeback can proceed with the
  1693. * other inodes on s_io.
  1694. *
  1695. * We'll have another go at writing back this inode
  1696. * when we completed a full scan of b_io.
  1697. */
  1698. requeue_io(inode, wb);
  1699. spin_unlock(&inode->i_lock);
  1700. trace_writeback_sb_inodes_requeue(inode);
  1701. continue;
  1702. }
  1703. spin_unlock(&wb->list_lock);
  1704. /*
  1705. * We already requeued the inode if it had I_SYNC set and we
  1706. * are doing WB_SYNC_NONE writeback. So this catches only the
  1707. * WB_SYNC_ALL case.
  1708. */
  1709. if (inode->i_state & I_SYNC) {
  1710. /* Wait for I_SYNC. This function drops i_lock... */
  1711. inode_sleep_on_writeback(inode);
  1712. /* Inode may be gone, start again */
  1713. spin_lock(&wb->list_lock);
  1714. continue;
  1715. }
  1716. inode->i_state |= I_SYNC;
  1717. wbc_attach_and_unlock_inode(&wbc, inode);
  1718. write_chunk = writeback_chunk_size(wb, work);
  1719. wbc.nr_to_write = write_chunk;
  1720. wbc.pages_skipped = 0;
  1721. /*
  1722. * We use I_SYNC to pin the inode in memory. While it is set
  1723. * evict_inode() will wait so the inode cannot be freed.
  1724. */
  1725. __writeback_single_inode(inode, &wbc);
  1726. wbc_detach_inode(&wbc);
  1727. work->nr_pages -= write_chunk - wbc.nr_to_write;
  1728. wrote = write_chunk - wbc.nr_to_write - wbc.pages_skipped;
  1729. wrote = wrote < 0 ? 0 : wrote;
  1730. total_wrote += wrote;
  1731. if (need_resched()) {
  1732. /*
  1733. * We're trying to balance between building up a nice
  1734. * long list of IOs to improve our merge rate, and
  1735. * getting those IOs out quickly for anyone throttling
  1736. * in balance_dirty_pages(). cond_resched() doesn't
  1737. * unplug, so get our IOs out the door before we
  1738. * give up the CPU.
  1739. */
  1740. blk_flush_plug(current->plug, false);
  1741. cond_resched();
  1742. }
  1743. /*
  1744. * Requeue @inode if still dirty. Be careful as @inode may
  1745. * have been switched to another wb in the meantime.
  1746. */
  1747. tmp_wb = inode_to_wb_and_lock_list(inode);
  1748. spin_lock(&inode->i_lock);
  1749. if (!(inode->i_state & I_DIRTY_ALL))
  1750. total_wrote++;
  1751. requeue_inode(inode, tmp_wb, &wbc, dirtied_before);
  1752. inode_sync_complete(inode);
  1753. spin_unlock(&inode->i_lock);
  1754. if (unlikely(tmp_wb != wb)) {
  1755. spin_unlock(&tmp_wb->list_lock);
  1756. spin_lock(&wb->list_lock);
  1757. }
  1758. /*
  1759. * bail out to wb_writeback() often enough to check
  1760. * background threshold and other termination conditions.
  1761. */
  1762. if (total_wrote) {
  1763. if (time_is_before_jiffies(start_time + HZ / 10UL))
  1764. break;
  1765. if (work->nr_pages <= 0)
  1766. break;
  1767. }
  1768. }
  1769. return total_wrote;
  1770. }
  1771. static long __writeback_inodes_wb(struct bdi_writeback *wb,
  1772. struct wb_writeback_work *work)
  1773. {
  1774. unsigned long start_time = jiffies;
  1775. long wrote = 0;
  1776. while (!list_empty(&wb->b_io)) {
  1777. struct inode *inode = wb_inode(wb->b_io.prev);
  1778. struct super_block *sb = inode->i_sb;
  1779. if (!super_trylock_shared(sb)) {
  1780. /*
  1781. * super_trylock_shared() may fail consistently due to
  1782. * s_umount being grabbed by someone else. Don't use
  1783. * requeue_io() to avoid busy retrying the inode/sb.
  1784. */
  1785. redirty_tail(inode, wb);
  1786. continue;
  1787. }
  1788. wrote += writeback_sb_inodes(sb, wb, work);
  1789. up_read(&sb->s_umount);
  1790. /* refer to the same tests at the end of writeback_sb_inodes */
  1791. if (wrote) {
  1792. if (time_is_before_jiffies(start_time + HZ / 10UL))
  1793. break;
  1794. if (work->nr_pages <= 0)
  1795. break;
  1796. }
  1797. }
  1798. /* Leave any unwritten inodes on b_io */
  1799. return wrote;
  1800. }
  1801. static long writeback_inodes_wb(struct bdi_writeback *wb, long nr_pages,
  1802. enum wb_reason reason)
  1803. {
  1804. struct wb_writeback_work work = {
  1805. .nr_pages = nr_pages,
  1806. .sync_mode = WB_SYNC_NONE,
  1807. .range_cyclic = 1,
  1808. .reason = reason,
  1809. };
  1810. struct blk_plug plug;
  1811. blk_start_plug(&plug);
  1812. spin_lock(&wb->list_lock);
  1813. if (list_empty(&wb->b_io))
  1814. queue_io(wb, &work, jiffies);
  1815. __writeback_inodes_wb(wb, &work);
  1816. spin_unlock(&wb->list_lock);
  1817. blk_finish_plug(&plug);
  1818. return nr_pages - work.nr_pages;
  1819. }
  1820. /*
  1821. * Explicit flushing or periodic writeback of "old" data.
  1822. *
  1823. * Define "old": the first time one of an inode's pages is dirtied, we mark the
  1824. * dirtying-time in the inode's address_space. So this periodic writeback code
  1825. * just walks the superblock inode list, writing back any inodes which are
  1826. * older than a specific point in time.
  1827. *
  1828. * Try to run once per dirty_writeback_interval. But if a writeback event
  1829. * takes longer than a dirty_writeback_interval interval, then leave a
  1830. * one-second gap.
  1831. *
  1832. * dirtied_before takes precedence over nr_to_write. So we'll only write back
  1833. * all dirty pages if they are all attached to "old" mappings.
  1834. */
  1835. static long wb_writeback(struct bdi_writeback *wb,
  1836. struct wb_writeback_work *work)
  1837. {
  1838. long nr_pages = work->nr_pages;
  1839. unsigned long dirtied_before = jiffies;
  1840. struct inode *inode;
  1841. long progress;
  1842. struct blk_plug plug;
  1843. bool queued = false;
  1844. blk_start_plug(&plug);
  1845. for (;;) {
  1846. /*
  1847. * Stop writeback when nr_pages has been consumed
  1848. */
  1849. if (work->nr_pages <= 0)
  1850. break;
  1851. /*
  1852. * Background writeout and kupdate-style writeback may
  1853. * run forever. Stop them if there is other work to do
  1854. * so that e.g. sync can proceed. They'll be restarted
  1855. * after the other works are all done.
  1856. */
  1857. if ((work->for_background || work->for_kupdate) &&
  1858. !list_empty(&wb->work_list))
  1859. break;
  1860. /*
  1861. * For background writeout, stop when we are below the
  1862. * background dirty threshold
  1863. */
  1864. if (work->for_background && !wb_over_bg_thresh(wb))
  1865. break;
  1866. spin_lock(&wb->list_lock);
  1867. trace_writeback_start(wb, work);
  1868. if (list_empty(&wb->b_io)) {
  1869. /*
  1870. * Kupdate and background works are special and we want
  1871. * to include all inodes that need writing. Livelock
  1872. * avoidance is handled by these works yielding to any
  1873. * other work so we are safe.
  1874. */
  1875. if (work->for_kupdate) {
  1876. dirtied_before = jiffies -
  1877. msecs_to_jiffies(dirty_expire_interval *
  1878. 10);
  1879. } else if (work->for_background)
  1880. dirtied_before = jiffies;
  1881. queue_io(wb, work, dirtied_before);
  1882. queued = true;
  1883. }
  1884. if (work->sb)
  1885. progress = writeback_sb_inodes(work->sb, wb, work);
  1886. else
  1887. progress = __writeback_inodes_wb(wb, work);
  1888. trace_writeback_written(wb, work);
  1889. /*
  1890. * Did we write something? Try for more
  1891. *
  1892. * Dirty inodes are moved to b_io for writeback in batches.
  1893. * The completion of the current batch does not necessarily
  1894. * mean the overall work is done. So we keep looping as long
  1895. * as made some progress on cleaning pages or inodes.
  1896. */
  1897. if (progress || !queued) {
  1898. spin_unlock(&wb->list_lock);
  1899. continue;
  1900. }
  1901. /*
  1902. * No more inodes for IO, bail
  1903. */
  1904. if (list_empty(&wb->b_more_io)) {
  1905. spin_unlock(&wb->list_lock);
  1906. break;
  1907. }
  1908. /*
  1909. * Nothing written. Wait for some inode to
  1910. * become available for writeback. Otherwise
  1911. * we'll just busyloop.
  1912. */
  1913. trace_writeback_wait(wb, work);
  1914. inode = wb_inode(wb->b_more_io.prev);
  1915. spin_lock(&inode->i_lock);
  1916. spin_unlock(&wb->list_lock);
  1917. /* This function drops i_lock... */
  1918. inode_sleep_on_writeback(inode);
  1919. }
  1920. blk_finish_plug(&plug);
  1921. return nr_pages - work->nr_pages;
  1922. }
  1923. /*
  1924. * Return the next wb_writeback_work struct that hasn't been processed yet.
  1925. */
  1926. static struct wb_writeback_work *get_next_work_item(struct bdi_writeback *wb)
  1927. {
  1928. struct wb_writeback_work *work = NULL;
  1929. spin_lock_irq(&wb->work_lock);
  1930. if (!list_empty(&wb->work_list)) {
  1931. work = list_entry(wb->work_list.next,
  1932. struct wb_writeback_work, list);
  1933. list_del_init(&work->list);
  1934. }
  1935. spin_unlock_irq(&wb->work_lock);
  1936. return work;
  1937. }
  1938. static long wb_check_background_flush(struct bdi_writeback *wb)
  1939. {
  1940. if (wb_over_bg_thresh(wb)) {
  1941. struct wb_writeback_work work = {
  1942. .nr_pages = LONG_MAX,
  1943. .sync_mode = WB_SYNC_NONE,
  1944. .for_background = 1,
  1945. .range_cyclic = 1,
  1946. .reason = WB_REASON_BACKGROUND,
  1947. };
  1948. return wb_writeback(wb, &work);
  1949. }
  1950. return 0;
  1951. }
  1952. static long wb_check_old_data_flush(struct bdi_writeback *wb)
  1953. {
  1954. unsigned long expired;
  1955. long nr_pages;
  1956. /*
  1957. * When set to zero, disable periodic writeback
  1958. */
  1959. if (!dirty_writeback_interval)
  1960. return 0;
  1961. expired = wb->last_old_flush +
  1962. msecs_to_jiffies(dirty_writeback_interval * 10);
  1963. if (time_before(jiffies, expired))
  1964. return 0;
  1965. wb->last_old_flush = jiffies;
  1966. nr_pages = get_nr_dirty_pages();
  1967. if (nr_pages) {
  1968. struct wb_writeback_work work = {
  1969. .nr_pages = nr_pages,
  1970. .sync_mode = WB_SYNC_NONE,
  1971. .for_kupdate = 1,
  1972. .range_cyclic = 1,
  1973. .reason = WB_REASON_PERIODIC,
  1974. };
  1975. return wb_writeback(wb, &work);
  1976. }
  1977. return 0;
  1978. }
  1979. static long wb_check_start_all(struct bdi_writeback *wb)
  1980. {
  1981. long nr_pages;
  1982. if (!test_bit(WB_start_all, &wb->state))
  1983. return 0;
  1984. nr_pages = get_nr_dirty_pages();
  1985. if (nr_pages) {
  1986. struct wb_writeback_work work = {
  1987. .nr_pages = wb_split_bdi_pages(wb, nr_pages),
  1988. .sync_mode = WB_SYNC_NONE,
  1989. .range_cyclic = 1,
  1990. .reason = wb->start_all_reason,
  1991. };
  1992. nr_pages = wb_writeback(wb, &work);
  1993. }
  1994. clear_bit(WB_start_all, &wb->state);
  1995. return nr_pages;
  1996. }
  1997. /*
  1998. * Retrieve work items and do the writeback they describe
  1999. */
  2000. static long wb_do_writeback(struct bdi_writeback *wb)
  2001. {
  2002. struct wb_writeback_work *work;
  2003. long wrote = 0;
  2004. set_bit(WB_writeback_running, &wb->state);
  2005. while ((work = get_next_work_item(wb)) != NULL) {
  2006. trace_writeback_exec(wb, work);
  2007. wrote += wb_writeback(wb, work);
  2008. finish_writeback_work(work);
  2009. }
  2010. /*
  2011. * Check for a flush-everything request
  2012. */
  2013. wrote += wb_check_start_all(wb);
  2014. /*
  2015. * Check for periodic writeback, kupdated() style
  2016. */
  2017. wrote += wb_check_old_data_flush(wb);
  2018. wrote += wb_check_background_flush(wb);
  2019. clear_bit(WB_writeback_running, &wb->state);
  2020. return wrote;
  2021. }
  2022. /*
  2023. * Handle writeback of dirty data for the device backed by this bdi. Also
  2024. * reschedules periodically and does kupdated style flushing.
  2025. */
  2026. void wb_workfn(struct work_struct *work)
  2027. {
  2028. struct bdi_writeback *wb = container_of(to_delayed_work(work),
  2029. struct bdi_writeback, dwork);
  2030. long pages_written;
  2031. set_worker_desc("flush-%s", bdi_dev_name(wb->bdi));
  2032. if (likely(!current_is_workqueue_rescuer() ||
  2033. !test_bit(WB_registered, &wb->state))) {
  2034. /*
  2035. * The normal path. Keep writing back @wb until its
  2036. * work_list is empty. Note that this path is also taken
  2037. * if @wb is shutting down even when we're running off the
  2038. * rescuer as work_list needs to be drained.
  2039. */
  2040. do {
  2041. pages_written = wb_do_writeback(wb);
  2042. trace_writeback_pages_written(pages_written);
  2043. } while (!list_empty(&wb->work_list));
  2044. } else {
  2045. /*
  2046. * bdi_wq can't get enough workers and we're running off
  2047. * the emergency worker. Don't hog it. Hopefully, 1024 is
  2048. * enough for efficient IO.
  2049. */
  2050. pages_written = writeback_inodes_wb(wb, 1024,
  2051. WB_REASON_FORKER_THREAD);
  2052. trace_writeback_pages_written(pages_written);
  2053. }
  2054. if (!list_empty(&wb->work_list))
  2055. wb_wakeup(wb);
  2056. else if (wb_has_dirty_io(wb) && dirty_writeback_interval)
  2057. wb_wakeup_delayed(wb);
  2058. }
  2059. /*
  2060. * Start writeback of all dirty pages on this bdi.
  2061. */
  2062. static void __wakeup_flusher_threads_bdi(struct backing_dev_info *bdi,
  2063. enum wb_reason reason)
  2064. {
  2065. struct bdi_writeback *wb;
  2066. if (!bdi_has_dirty_io(bdi))
  2067. return;
  2068. list_for_each_entry_rcu(wb, &bdi->wb_list, bdi_node)
  2069. wb_start_writeback(wb, reason);
  2070. }
  2071. void wakeup_flusher_threads_bdi(struct backing_dev_info *bdi,
  2072. enum wb_reason reason)
  2073. {
  2074. rcu_read_lock();
  2075. __wakeup_flusher_threads_bdi(bdi, reason);
  2076. rcu_read_unlock();
  2077. }
  2078. /*
  2079. * Wakeup the flusher threads to start writeback of all currently dirty pages
  2080. */
  2081. void wakeup_flusher_threads(enum wb_reason reason)
  2082. {
  2083. struct backing_dev_info *bdi;
  2084. /*
  2085. * If we are expecting writeback progress we must submit plugged IO.
  2086. */
  2087. blk_flush_plug(current->plug, true);
  2088. rcu_read_lock();
  2089. list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
  2090. __wakeup_flusher_threads_bdi(bdi, reason);
  2091. rcu_read_unlock();
  2092. }
  2093. /*
  2094. * Wake up bdi's periodically to make sure dirtytime inodes gets
  2095. * written back periodically. We deliberately do *not* check the
  2096. * b_dirtytime list in wb_has_dirty_io(), since this would cause the
  2097. * kernel to be constantly waking up once there are any dirtytime
  2098. * inodes on the system. So instead we define a separate delayed work
  2099. * function which gets called much more rarely. (By default, only
  2100. * once every 12 hours.)
  2101. *
  2102. * If there is any other write activity going on in the file system,
  2103. * this function won't be necessary. But if the only thing that has
  2104. * happened on the file system is a dirtytime inode caused by an atime
  2105. * update, we need this infrastructure below to make sure that inode
  2106. * eventually gets pushed out to disk.
  2107. */
  2108. static void wakeup_dirtytime_writeback(struct work_struct *w);
  2109. static DECLARE_DELAYED_WORK(dirtytime_work, wakeup_dirtytime_writeback);
  2110. static void wakeup_dirtytime_writeback(struct work_struct *w)
  2111. {
  2112. struct backing_dev_info *bdi;
  2113. rcu_read_lock();
  2114. list_for_each_entry_rcu(bdi, &bdi_list, bdi_list) {
  2115. struct bdi_writeback *wb;
  2116. list_for_each_entry_rcu(wb, &bdi->wb_list, bdi_node)
  2117. if (!list_empty(&wb->b_dirty_time))
  2118. wb_wakeup(wb);
  2119. }
  2120. rcu_read_unlock();
  2121. schedule_delayed_work(&dirtytime_work, dirtytime_expire_interval * HZ);
  2122. }
  2123. static int __init start_dirtytime_writeback(void)
  2124. {
  2125. schedule_delayed_work(&dirtytime_work, dirtytime_expire_interval * HZ);
  2126. return 0;
  2127. }
  2128. __initcall(start_dirtytime_writeback);
  2129. int dirtytime_interval_handler(const struct ctl_table *table, int write,
  2130. void *buffer, size_t *lenp, loff_t *ppos)
  2131. {
  2132. int ret;
  2133. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  2134. if (ret == 0 && write)
  2135. mod_delayed_work(system_wq, &dirtytime_work, 0);
  2136. return ret;
  2137. }
  2138. /**
  2139. * __mark_inode_dirty - internal function to mark an inode dirty
  2140. *
  2141. * @inode: inode to mark
  2142. * @flags: what kind of dirty, e.g. I_DIRTY_SYNC. This can be a combination of
  2143. * multiple I_DIRTY_* flags, except that I_DIRTY_TIME can't be combined
  2144. * with I_DIRTY_PAGES.
  2145. *
  2146. * Mark an inode as dirty. We notify the filesystem, then update the inode's
  2147. * dirty flags. Then, if needed we add the inode to the appropriate dirty list.
  2148. *
  2149. * Most callers should use mark_inode_dirty() or mark_inode_dirty_sync()
  2150. * instead of calling this directly.
  2151. *
  2152. * CAREFUL! We only add the inode to the dirty list if it is hashed or if it
  2153. * refers to a blockdev. Unhashed inodes will never be added to the dirty list
  2154. * even if they are later hashed, as they will have been marked dirty already.
  2155. *
  2156. * In short, ensure you hash any inodes _before_ you start marking them dirty.
  2157. *
  2158. * Note that for blockdevs, inode->dirtied_when represents the dirtying time of
  2159. * the block-special inode (/dev/hda1) itself. And the ->dirtied_when field of
  2160. * the kernel-internal blockdev inode represents the dirtying time of the
  2161. * blockdev's pages. This is why for I_DIRTY_PAGES we always use
  2162. * page->mapping->host, so the page-dirtying time is recorded in the internal
  2163. * blockdev inode.
  2164. */
  2165. void __mark_inode_dirty(struct inode *inode, int flags)
  2166. {
  2167. struct super_block *sb = inode->i_sb;
  2168. int dirtytime = 0;
  2169. struct bdi_writeback *wb = NULL;
  2170. trace_writeback_mark_inode_dirty(inode, flags);
  2171. if (flags & I_DIRTY_INODE) {
  2172. /*
  2173. * Inode timestamp update will piggback on this dirtying.
  2174. * We tell ->dirty_inode callback that timestamps need to
  2175. * be updated by setting I_DIRTY_TIME in flags.
  2176. */
  2177. if (inode->i_state & I_DIRTY_TIME) {
  2178. spin_lock(&inode->i_lock);
  2179. if (inode->i_state & I_DIRTY_TIME) {
  2180. inode->i_state &= ~I_DIRTY_TIME;
  2181. flags |= I_DIRTY_TIME;
  2182. }
  2183. spin_unlock(&inode->i_lock);
  2184. }
  2185. /*
  2186. * Notify the filesystem about the inode being dirtied, so that
  2187. * (if needed) it can update on-disk fields and journal the
  2188. * inode. This is only needed when the inode itself is being
  2189. * dirtied now. I.e. it's only needed for I_DIRTY_INODE, not
  2190. * for just I_DIRTY_PAGES or I_DIRTY_TIME.
  2191. */
  2192. trace_writeback_dirty_inode_start(inode, flags);
  2193. if (sb->s_op->dirty_inode)
  2194. sb->s_op->dirty_inode(inode,
  2195. flags & (I_DIRTY_INODE | I_DIRTY_TIME));
  2196. trace_writeback_dirty_inode(inode, flags);
  2197. /* I_DIRTY_INODE supersedes I_DIRTY_TIME. */
  2198. flags &= ~I_DIRTY_TIME;
  2199. } else {
  2200. /*
  2201. * Else it's either I_DIRTY_PAGES, I_DIRTY_TIME, or nothing.
  2202. * (We don't support setting both I_DIRTY_PAGES and I_DIRTY_TIME
  2203. * in one call to __mark_inode_dirty().)
  2204. */
  2205. dirtytime = flags & I_DIRTY_TIME;
  2206. WARN_ON_ONCE(dirtytime && flags != I_DIRTY_TIME);
  2207. }
  2208. /*
  2209. * Paired with smp_mb() in __writeback_single_inode() for the
  2210. * following lockless i_state test. See there for details.
  2211. */
  2212. smp_mb();
  2213. if ((inode->i_state & flags) == flags)
  2214. return;
  2215. spin_lock(&inode->i_lock);
  2216. if ((inode->i_state & flags) != flags) {
  2217. const int was_dirty = inode->i_state & I_DIRTY;
  2218. inode_attach_wb(inode, NULL);
  2219. inode->i_state |= flags;
  2220. /*
  2221. * Grab inode's wb early because it requires dropping i_lock and we
  2222. * need to make sure following checks happen atomically with dirty
  2223. * list handling so that we don't move inodes under flush worker's
  2224. * hands.
  2225. */
  2226. if (!was_dirty) {
  2227. wb = locked_inode_to_wb_and_lock_list(inode);
  2228. spin_lock(&inode->i_lock);
  2229. }
  2230. /*
  2231. * If the inode is queued for writeback by flush worker, just
  2232. * update its dirty state. Once the flush worker is done with
  2233. * the inode it will place it on the appropriate superblock
  2234. * list, based upon its state.
  2235. */
  2236. if (inode->i_state & I_SYNC_QUEUED)
  2237. goto out_unlock;
  2238. /*
  2239. * Only add valid (hashed) inodes to the superblock's
  2240. * dirty list. Add blockdev inodes as well.
  2241. */
  2242. if (!S_ISBLK(inode->i_mode)) {
  2243. if (inode_unhashed(inode))
  2244. goto out_unlock;
  2245. }
  2246. if (inode->i_state & I_FREEING)
  2247. goto out_unlock;
  2248. /*
  2249. * If the inode was already on b_dirty/b_io/b_more_io, don't
  2250. * reposition it (that would break b_dirty time-ordering).
  2251. */
  2252. if (!was_dirty) {
  2253. struct list_head *dirty_list;
  2254. bool wakeup_bdi = false;
  2255. inode->dirtied_when = jiffies;
  2256. if (dirtytime)
  2257. inode->dirtied_time_when = jiffies;
  2258. if (inode->i_state & I_DIRTY)
  2259. dirty_list = &wb->b_dirty;
  2260. else
  2261. dirty_list = &wb->b_dirty_time;
  2262. wakeup_bdi = inode_io_list_move_locked(inode, wb,
  2263. dirty_list);
  2264. spin_unlock(&wb->list_lock);
  2265. spin_unlock(&inode->i_lock);
  2266. trace_writeback_dirty_inode_enqueue(inode);
  2267. /*
  2268. * If this is the first dirty inode for this bdi,
  2269. * we have to wake-up the corresponding bdi thread
  2270. * to make sure background write-back happens
  2271. * later.
  2272. */
  2273. if (wakeup_bdi &&
  2274. (wb->bdi->capabilities & BDI_CAP_WRITEBACK))
  2275. wb_wakeup_delayed(wb);
  2276. return;
  2277. }
  2278. }
  2279. out_unlock:
  2280. if (wb)
  2281. spin_unlock(&wb->list_lock);
  2282. spin_unlock(&inode->i_lock);
  2283. }
  2284. EXPORT_SYMBOL(__mark_inode_dirty);
  2285. /*
  2286. * The @s_sync_lock is used to serialise concurrent sync operations
  2287. * to avoid lock contention problems with concurrent wait_sb_inodes() calls.
  2288. * Concurrent callers will block on the s_sync_lock rather than doing contending
  2289. * walks. The queueing maintains sync(2) required behaviour as all the IO that
  2290. * has been issued up to the time this function is enter is guaranteed to be
  2291. * completed by the time we have gained the lock and waited for all IO that is
  2292. * in progress regardless of the order callers are granted the lock.
  2293. */
  2294. static void wait_sb_inodes(struct super_block *sb)
  2295. {
  2296. LIST_HEAD(sync_list);
  2297. /*
  2298. * We need to be protected against the filesystem going from
  2299. * r/o to r/w or vice versa.
  2300. */
  2301. WARN_ON(!rwsem_is_locked(&sb->s_umount));
  2302. mutex_lock(&sb->s_sync_lock);
  2303. /*
  2304. * Splice the writeback list onto a temporary list to avoid waiting on
  2305. * inodes that have started writeback after this point.
  2306. *
  2307. * Use rcu_read_lock() to keep the inodes around until we have a
  2308. * reference. s_inode_wblist_lock protects sb->s_inodes_wb as well as
  2309. * the local list because inodes can be dropped from either by writeback
  2310. * completion.
  2311. */
  2312. rcu_read_lock();
  2313. spin_lock_irq(&sb->s_inode_wblist_lock);
  2314. list_splice_init(&sb->s_inodes_wb, &sync_list);
  2315. /*
  2316. * Data integrity sync. Must wait for all pages under writeback, because
  2317. * there may have been pages dirtied before our sync call, but which had
  2318. * writeout started before we write it out. In which case, the inode
  2319. * may not be on the dirty list, but we still have to wait for that
  2320. * writeout.
  2321. */
  2322. while (!list_empty(&sync_list)) {
  2323. struct inode *inode = list_first_entry(&sync_list, struct inode,
  2324. i_wb_list);
  2325. struct address_space *mapping = inode->i_mapping;
  2326. /*
  2327. * Move each inode back to the wb list before we drop the lock
  2328. * to preserve consistency between i_wb_list and the mapping
  2329. * writeback tag. Writeback completion is responsible to remove
  2330. * the inode from either list once the writeback tag is cleared.
  2331. */
  2332. list_move_tail(&inode->i_wb_list, &sb->s_inodes_wb);
  2333. /*
  2334. * The mapping can appear untagged while still on-list since we
  2335. * do not have the mapping lock. Skip it here, wb completion
  2336. * will remove it.
  2337. */
  2338. if (!mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK))
  2339. continue;
  2340. spin_unlock_irq(&sb->s_inode_wblist_lock);
  2341. spin_lock(&inode->i_lock);
  2342. if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW)) {
  2343. spin_unlock(&inode->i_lock);
  2344. spin_lock_irq(&sb->s_inode_wblist_lock);
  2345. continue;
  2346. }
  2347. __iget(inode);
  2348. spin_unlock(&inode->i_lock);
  2349. rcu_read_unlock();
  2350. /*
  2351. * We keep the error status of individual mapping so that
  2352. * applications can catch the writeback error using fsync(2).
  2353. * See filemap_fdatawait_keep_errors() for details.
  2354. */
  2355. filemap_fdatawait_keep_errors(mapping);
  2356. cond_resched();
  2357. iput(inode);
  2358. rcu_read_lock();
  2359. spin_lock_irq(&sb->s_inode_wblist_lock);
  2360. }
  2361. spin_unlock_irq(&sb->s_inode_wblist_lock);
  2362. rcu_read_unlock();
  2363. mutex_unlock(&sb->s_sync_lock);
  2364. }
  2365. static void __writeback_inodes_sb_nr(struct super_block *sb, unsigned long nr,
  2366. enum wb_reason reason, bool skip_if_busy)
  2367. {
  2368. struct backing_dev_info *bdi = sb->s_bdi;
  2369. DEFINE_WB_COMPLETION(done, bdi);
  2370. struct wb_writeback_work work = {
  2371. .sb = sb,
  2372. .sync_mode = WB_SYNC_NONE,
  2373. .tagged_writepages = 1,
  2374. .done = &done,
  2375. .nr_pages = nr,
  2376. .reason = reason,
  2377. };
  2378. if (!bdi_has_dirty_io(bdi) || bdi == &noop_backing_dev_info)
  2379. return;
  2380. WARN_ON(!rwsem_is_locked(&sb->s_umount));
  2381. bdi_split_work_to_wbs(sb->s_bdi, &work, skip_if_busy);
  2382. wb_wait_for_completion(&done);
  2383. }
  2384. /**
  2385. * writeback_inodes_sb_nr - writeback dirty inodes from given super_block
  2386. * @sb: the superblock
  2387. * @nr: the number of pages to write
  2388. * @reason: reason why some writeback work initiated
  2389. *
  2390. * Start writeback on some inodes on this super_block. No guarantees are made
  2391. * on how many (if any) will be written, and this function does not wait
  2392. * for IO completion of submitted IO.
  2393. */
  2394. void writeback_inodes_sb_nr(struct super_block *sb,
  2395. unsigned long nr,
  2396. enum wb_reason reason)
  2397. {
  2398. __writeback_inodes_sb_nr(sb, nr, reason, false);
  2399. }
  2400. EXPORT_SYMBOL(writeback_inodes_sb_nr);
  2401. /**
  2402. * writeback_inodes_sb - writeback dirty inodes from given super_block
  2403. * @sb: the superblock
  2404. * @reason: reason why some writeback work was initiated
  2405. *
  2406. * Start writeback on some inodes on this super_block. No guarantees are made
  2407. * on how many (if any) will be written, and this function does not wait
  2408. * for IO completion of submitted IO.
  2409. */
  2410. void writeback_inodes_sb(struct super_block *sb, enum wb_reason reason)
  2411. {
  2412. writeback_inodes_sb_nr(sb, get_nr_dirty_pages(), reason);
  2413. }
  2414. EXPORT_SYMBOL(writeback_inodes_sb);
  2415. /**
  2416. * try_to_writeback_inodes_sb - try to start writeback if none underway
  2417. * @sb: the superblock
  2418. * @reason: reason why some writeback work was initiated
  2419. *
  2420. * Invoke __writeback_inodes_sb_nr if no writeback is currently underway.
  2421. */
  2422. void try_to_writeback_inodes_sb(struct super_block *sb, enum wb_reason reason)
  2423. {
  2424. if (!down_read_trylock(&sb->s_umount))
  2425. return;
  2426. __writeback_inodes_sb_nr(sb, get_nr_dirty_pages(), reason, true);
  2427. up_read(&sb->s_umount);
  2428. }
  2429. EXPORT_SYMBOL(try_to_writeback_inodes_sb);
  2430. /**
  2431. * sync_inodes_sb - sync sb inode pages
  2432. * @sb: the superblock
  2433. *
  2434. * This function writes and waits on any dirty inode belonging to this
  2435. * super_block.
  2436. */
  2437. void sync_inodes_sb(struct super_block *sb)
  2438. {
  2439. struct backing_dev_info *bdi = sb->s_bdi;
  2440. DEFINE_WB_COMPLETION(done, bdi);
  2441. struct wb_writeback_work work = {
  2442. .sb = sb,
  2443. .sync_mode = WB_SYNC_ALL,
  2444. .nr_pages = LONG_MAX,
  2445. .range_cyclic = 0,
  2446. .done = &done,
  2447. .reason = WB_REASON_SYNC,
  2448. .for_sync = 1,
  2449. };
  2450. /*
  2451. * Can't skip on !bdi_has_dirty() because we should wait for !dirty
  2452. * inodes under writeback and I_DIRTY_TIME inodes ignored by
  2453. * bdi_has_dirty() need to be written out too.
  2454. */
  2455. if (bdi == &noop_backing_dev_info)
  2456. return;
  2457. WARN_ON(!rwsem_is_locked(&sb->s_umount));
  2458. /* protect against inode wb switch, see inode_switch_wbs_work_fn() */
  2459. bdi_down_write_wb_switch_rwsem(bdi);
  2460. bdi_split_work_to_wbs(bdi, &work, false);
  2461. wb_wait_for_completion(&done);
  2462. bdi_up_write_wb_switch_rwsem(bdi);
  2463. wait_sb_inodes(sb);
  2464. }
  2465. EXPORT_SYMBOL(sync_inodes_sb);
  2466. /**
  2467. * write_inode_now - write an inode to disk
  2468. * @inode: inode to write to disk
  2469. * @sync: whether the write should be synchronous or not
  2470. *
  2471. * This function commits an inode to disk immediately if it is dirty. This is
  2472. * primarily needed by knfsd.
  2473. *
  2474. * The caller must either have a ref on the inode or must have set I_WILL_FREE.
  2475. */
  2476. int write_inode_now(struct inode *inode, int sync)
  2477. {
  2478. struct writeback_control wbc = {
  2479. .nr_to_write = LONG_MAX,
  2480. .sync_mode = sync ? WB_SYNC_ALL : WB_SYNC_NONE,
  2481. .range_start = 0,
  2482. .range_end = LLONG_MAX,
  2483. };
  2484. if (!mapping_can_writeback(inode->i_mapping))
  2485. wbc.nr_to_write = 0;
  2486. might_sleep();
  2487. return writeback_single_inode(inode, &wbc);
  2488. }
  2489. EXPORT_SYMBOL(write_inode_now);
  2490. /**
  2491. * sync_inode_metadata - write an inode to disk
  2492. * @inode: the inode to sync
  2493. * @wait: wait for I/O to complete.
  2494. *
  2495. * Write an inode to disk and adjust its dirty state after completion.
  2496. *
  2497. * Note: only writes the actual inode, no associated data or other metadata.
  2498. */
  2499. int sync_inode_metadata(struct inode *inode, int wait)
  2500. {
  2501. struct writeback_control wbc = {
  2502. .sync_mode = wait ? WB_SYNC_ALL : WB_SYNC_NONE,
  2503. .nr_to_write = 0, /* metadata-only */
  2504. };
  2505. return writeback_single_inode(inode, &wbc);
  2506. }
  2507. EXPORT_SYMBOL(sync_inode_metadata);