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