fs-writeback.c 82 KB

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