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