xref: /openbmc/linux/fs/fs-writeback.c (revision 1ba1199e)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * fs/fs-writeback.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  * Copyright (C) 2002, Linus Torvalds.
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  * Contains all the functions related to writing back and waiting
81da177e4SLinus Torvalds  * upon dirty inodes against superblocks, and writing back dirty
91da177e4SLinus Torvalds  * pages against inodes.  ie: data writeback.  Writeout of the
101da177e4SLinus Torvalds  * inode itself is not handled here.
111da177e4SLinus Torvalds  *
12e1f8e874SFrancois Cami  * 10Apr2002	Andrew Morton
131da177e4SLinus Torvalds  *		Split out of fs/inode.c
141da177e4SLinus Torvalds  *		Additions for address_space-based writeback
151da177e4SLinus Torvalds  */
161da177e4SLinus Torvalds 
171da177e4SLinus Torvalds #include <linux/kernel.h>
18630d9c47SPaul Gortmaker #include <linux/export.h>
191da177e4SLinus Torvalds #include <linux/spinlock.h>
205a0e3ad6STejun Heo #include <linux/slab.h>
211da177e4SLinus Torvalds #include <linux/sched.h>
221da177e4SLinus Torvalds #include <linux/fs.h>
231da177e4SLinus Torvalds #include <linux/mm.h>
24bc31b86aSWu Fengguang #include <linux/pagemap.h>
2503ba3782SJens Axboe #include <linux/kthread.h>
261da177e4SLinus Torvalds #include <linux/writeback.h>
271da177e4SLinus Torvalds #include <linux/blkdev.h>
281da177e4SLinus Torvalds #include <linux/backing-dev.h>
29455b2864SDave Chinner #include <linux/tracepoint.h>
30719ea2fbSAl Viro #include <linux/device.h>
3121c6321fSTejun Heo #include <linux/memcontrol.h>
3207f3f05cSDavid Howells #include "internal.h"
331da177e4SLinus Torvalds 
34d0bceac7SJens Axboe /*
35bc31b86aSWu Fengguang  * 4MB minimal write chunk size
36bc31b86aSWu Fengguang  */
3709cbfeafSKirill A. Shutemov #define MIN_WRITEBACK_PAGES	(4096UL >> (PAGE_SHIFT - 10))
38bc31b86aSWu Fengguang 
39bc31b86aSWu Fengguang /*
40c4a77a6cSJens Axboe  * Passed into wb_writeback(), essentially a subset of writeback_control
41c4a77a6cSJens Axboe  */
4283ba7b07SChristoph Hellwig struct wb_writeback_work {
43c4a77a6cSJens Axboe 	long nr_pages;
44c4a77a6cSJens Axboe 	struct super_block *sb;
45c4a77a6cSJens Axboe 	enum writeback_sync_modes sync_mode;
466e6938b6SWu Fengguang 	unsigned int tagged_writepages:1;
4752957fe1SH Hartley Sweeten 	unsigned int for_kupdate:1;
4852957fe1SH Hartley Sweeten 	unsigned int range_cyclic:1;
4952957fe1SH Hartley Sweeten 	unsigned int for_background:1;
507747bd4bSDave Chinner 	unsigned int for_sync:1;	/* sync(2) WB_SYNC_ALL writeback */
51ac7b19a3STejun Heo 	unsigned int auto_free:1;	/* free on completion */
520e175a18SCurt Wohlgemuth 	enum wb_reason reason;		/* why was writeback initiated? */
53c4a77a6cSJens Axboe 
548010c3b6SJens Axboe 	struct list_head list;		/* pending work list */
55cc395d7fSTejun Heo 	struct wb_completion *done;	/* set if the caller waits */
5603ba3782SJens Axboe };
5703ba3782SJens Axboe 
58a2f48706STheodore Ts'o /*
59a2f48706STheodore Ts'o  * If an inode is constantly having its pages dirtied, but then the
60a2f48706STheodore Ts'o  * updates stop dirtytime_expire_interval seconds in the past, it's
61a2f48706STheodore Ts'o  * possible for the worst case time between when an inode has its
62a2f48706STheodore Ts'o  * timestamps updated and when they finally get written out to be two
63a2f48706STheodore Ts'o  * dirtytime_expire_intervals.  We set the default to 12 hours (in
64a2f48706STheodore Ts'o  * seconds), which means most of the time inodes will have their
65a2f48706STheodore Ts'o  * timestamps written to disk after 12 hours, but in the worst case a
66a2f48706STheodore Ts'o  * few inodes might not their timestamps updated for 24 hours.
67a2f48706STheodore Ts'o  */
68a2f48706STheodore Ts'o unsigned int dirtytime_expire_interval = 12 * 60 * 60;
69a2f48706STheodore Ts'o 
707ccf19a8SNick Piggin static inline struct inode *wb_inode(struct list_head *head)
717ccf19a8SNick Piggin {
72c7f54084SDave Chinner 	return list_entry(head, struct inode, i_io_list);
737ccf19a8SNick Piggin }
747ccf19a8SNick Piggin 
7515eb77a0SWu Fengguang /*
7615eb77a0SWu Fengguang  * Include the creation of the trace points after defining the
7715eb77a0SWu Fengguang  * wb_writeback_work structure and inline functions so that the definition
7815eb77a0SWu Fengguang  * remains local to this file.
7915eb77a0SWu Fengguang  */
8015eb77a0SWu Fengguang #define CREATE_TRACE_POINTS
8115eb77a0SWu Fengguang #include <trace/events/writeback.h>
8215eb77a0SWu Fengguang 
83774016b2SSteven Whitehouse EXPORT_TRACEPOINT_SYMBOL_GPL(wbc_writepage);
84774016b2SSteven Whitehouse 
85d6c10f1fSTejun Heo static bool wb_io_lists_populated(struct bdi_writeback *wb)
86d6c10f1fSTejun Heo {
87d6c10f1fSTejun Heo 	if (wb_has_dirty_io(wb)) {
88d6c10f1fSTejun Heo 		return false;
89d6c10f1fSTejun Heo 	} else {
90d6c10f1fSTejun Heo 		set_bit(WB_has_dirty_io, &wb->state);
9195a46c65STejun Heo 		WARN_ON_ONCE(!wb->avg_write_bandwidth);
92766a9d6eSTejun Heo 		atomic_long_add(wb->avg_write_bandwidth,
93766a9d6eSTejun Heo 				&wb->bdi->tot_write_bandwidth);
94d6c10f1fSTejun Heo 		return true;
95d6c10f1fSTejun Heo 	}
96d6c10f1fSTejun Heo }
97d6c10f1fSTejun Heo 
98d6c10f1fSTejun Heo static void wb_io_lists_depopulated(struct bdi_writeback *wb)
99d6c10f1fSTejun Heo {
100d6c10f1fSTejun Heo 	if (wb_has_dirty_io(wb) && list_empty(&wb->b_dirty) &&
101766a9d6eSTejun Heo 	    list_empty(&wb->b_io) && list_empty(&wb->b_more_io)) {
102d6c10f1fSTejun Heo 		clear_bit(WB_has_dirty_io, &wb->state);
10395a46c65STejun Heo 		WARN_ON_ONCE(atomic_long_sub_return(wb->avg_write_bandwidth,
10495a46c65STejun Heo 					&wb->bdi->tot_write_bandwidth) < 0);
105766a9d6eSTejun Heo 	}
106d6c10f1fSTejun Heo }
107d6c10f1fSTejun Heo 
108d6c10f1fSTejun Heo /**
109c7f54084SDave Chinner  * inode_io_list_move_locked - move an inode onto a bdi_writeback IO list
110d6c10f1fSTejun Heo  * @inode: inode to be moved
111d6c10f1fSTejun Heo  * @wb: target bdi_writeback
112bbbc3c1cSWang Long  * @head: one of @wb->b_{dirty|io|more_io|dirty_time}
113d6c10f1fSTejun Heo  *
114c7f54084SDave Chinner  * Move @inode->i_io_list to @list of @wb and set %WB_has_dirty_io.
115d6c10f1fSTejun Heo  * Returns %true if @inode is the first occupant of the !dirty_time IO
116d6c10f1fSTejun Heo  * lists; otherwise, %false.
117d6c10f1fSTejun Heo  */
118c7f54084SDave Chinner static bool inode_io_list_move_locked(struct inode *inode,
119d6c10f1fSTejun Heo 				      struct bdi_writeback *wb,
120d6c10f1fSTejun Heo 				      struct list_head *head)
121d6c10f1fSTejun Heo {
122d6c10f1fSTejun Heo 	assert_spin_locked(&wb->list_lock);
12310e14073SJchao Sun 	assert_spin_locked(&inode->i_lock);
124a9438b44SJan Kara 	WARN_ON_ONCE(inode->i_state & I_FREEING);
125d6c10f1fSTejun Heo 
126c7f54084SDave Chinner 	list_move(&inode->i_io_list, head);
127d6c10f1fSTejun Heo 
128d6c10f1fSTejun Heo 	/* dirty_time doesn't count as dirty_io until expiration */
129d6c10f1fSTejun Heo 	if (head != &wb->b_dirty_time)
130d6c10f1fSTejun Heo 		return wb_io_lists_populated(wb);
131d6c10f1fSTejun Heo 
132d6c10f1fSTejun Heo 	wb_io_lists_depopulated(wb);
133d6c10f1fSTejun Heo 	return false;
134d6c10f1fSTejun Heo }
135d6c10f1fSTejun Heo 
136f0054bb1STejun Heo static void wb_wakeup(struct bdi_writeback *wb)
1375acda9d1SJan Kara {
138f87904c0SKhazhismel Kumykov 	spin_lock_irq(&wb->work_lock);
139f0054bb1STejun Heo 	if (test_bit(WB_registered, &wb->state))
140f0054bb1STejun Heo 		mod_delayed_work(bdi_wq, &wb->dwork, 0);
141f87904c0SKhazhismel Kumykov 	spin_unlock_irq(&wb->work_lock);
1425acda9d1SJan Kara }
1435acda9d1SJan Kara 
1444a3a485bSTahsin Erdogan static void finish_writeback_work(struct bdi_writeback *wb,
1454a3a485bSTahsin Erdogan 				  struct wb_writeback_work *work)
1464a3a485bSTahsin Erdogan {
1474a3a485bSTahsin Erdogan 	struct wb_completion *done = work->done;
1484a3a485bSTahsin Erdogan 
1494a3a485bSTahsin Erdogan 	if (work->auto_free)
1504a3a485bSTahsin Erdogan 		kfree(work);
1518e00c4e9STejun Heo 	if (done) {
1528e00c4e9STejun Heo 		wait_queue_head_t *waitq = done->waitq;
1538e00c4e9STejun Heo 
1548e00c4e9STejun Heo 		/* @done can't be accessed after the following dec */
1558e00c4e9STejun Heo 		if (atomic_dec_and_test(&done->cnt))
1568e00c4e9STejun Heo 			wake_up_all(waitq);
1578e00c4e9STejun Heo 	}
1584a3a485bSTahsin Erdogan }
1594a3a485bSTahsin Erdogan 
160f0054bb1STejun Heo static void wb_queue_work(struct bdi_writeback *wb,
1616585027aSJan Kara 			  struct wb_writeback_work *work)
1626585027aSJan Kara {
1635634cc2aSTejun Heo 	trace_writeback_queue(wb, work);
1646585027aSJan Kara 
165cc395d7fSTejun Heo 	if (work->done)
166cc395d7fSTejun Heo 		atomic_inc(&work->done->cnt);
1674a3a485bSTahsin Erdogan 
168f87904c0SKhazhismel Kumykov 	spin_lock_irq(&wb->work_lock);
1694a3a485bSTahsin Erdogan 
1704a3a485bSTahsin Erdogan 	if (test_bit(WB_registered, &wb->state)) {
171f0054bb1STejun Heo 		list_add_tail(&work->list, &wb->work_list);
172f0054bb1STejun Heo 		mod_delayed_work(bdi_wq, &wb->dwork, 0);
1734a3a485bSTahsin Erdogan 	} else
1744a3a485bSTahsin Erdogan 		finish_writeback_work(wb, work);
1754a3a485bSTahsin Erdogan 
176f87904c0SKhazhismel Kumykov 	spin_unlock_irq(&wb->work_lock);
17703ba3782SJens Axboe }
1781da177e4SLinus Torvalds 
179cc395d7fSTejun Heo /**
180cc395d7fSTejun Heo  * wb_wait_for_completion - wait for completion of bdi_writeback_works
181cc395d7fSTejun Heo  * @done: target wb_completion
182cc395d7fSTejun Heo  *
183cc395d7fSTejun Heo  * Wait for one or more work items issued to @bdi with their ->done field
1845b9cce4cSTejun Heo  * set to @done, which should have been initialized with
1855b9cce4cSTejun Heo  * DEFINE_WB_COMPLETION().  This function returns after all such work items
1865b9cce4cSTejun Heo  * are completed.  Work items which are waited upon aren't freed
187cc395d7fSTejun Heo  * automatically on completion.
188cc395d7fSTejun Heo  */
1895b9cce4cSTejun Heo void wb_wait_for_completion(struct wb_completion *done)
190cc395d7fSTejun Heo {
191cc395d7fSTejun Heo 	atomic_dec(&done->cnt);		/* put down the initial count */
1925b9cce4cSTejun Heo 	wait_event(*done->waitq, !atomic_read(&done->cnt));
193cc395d7fSTejun Heo }
194cc395d7fSTejun Heo 
195703c2708STejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
196703c2708STejun Heo 
19755a694dfSTejun Heo /*
19855a694dfSTejun Heo  * Parameters for foreign inode detection, see wbc_detach_inode() to see
19955a694dfSTejun Heo  * how they're used.
20055a694dfSTejun Heo  *
20155a694dfSTejun Heo  * These paramters are inherently heuristical as the detection target
20255a694dfSTejun Heo  * itself is fuzzy.  All we want to do is detaching an inode from the
20355a694dfSTejun Heo  * current owner if it's being written to by some other cgroups too much.
20455a694dfSTejun Heo  *
20555a694dfSTejun Heo  * The current cgroup writeback is built on the assumption that multiple
20655a694dfSTejun Heo  * cgroups writing to the same inode concurrently is very rare and a mode
20755a694dfSTejun Heo  * of operation which isn't well supported.  As such, the goal is not
20855a694dfSTejun Heo  * taking too long when a different cgroup takes over an inode while
20955a694dfSTejun Heo  * avoiding too aggressive flip-flops from occasional foreign writes.
21055a694dfSTejun Heo  *
21155a694dfSTejun Heo  * We record, very roughly, 2s worth of IO time history and if more than
21255a694dfSTejun Heo  * half of that is foreign, trigger the switch.  The recording is quantized
21355a694dfSTejun Heo  * to 16 slots.  To avoid tiny writes from swinging the decision too much,
21455a694dfSTejun Heo  * writes smaller than 1/8 of avg size are ignored.
21555a694dfSTejun Heo  */
2162a814908STejun Heo #define WB_FRN_TIME_SHIFT	13	/* 1s = 2^13, upto 8 secs w/ 16bit */
2172a814908STejun Heo #define WB_FRN_TIME_AVG_SHIFT	3	/* avg = avg * 7/8 + new * 1/8 */
21855a694dfSTejun Heo #define WB_FRN_TIME_CUT_DIV	8	/* ignore rounds < avg / 8 */
2192a814908STejun Heo #define WB_FRN_TIME_PERIOD	(2 * (1 << WB_FRN_TIME_SHIFT))	/* 2s */
2202a814908STejun Heo 
2212a814908STejun Heo #define WB_FRN_HIST_SLOTS	16	/* inode->i_wb_frn_history is 16bit */
2222a814908STejun Heo #define WB_FRN_HIST_UNIT	(WB_FRN_TIME_PERIOD / WB_FRN_HIST_SLOTS)
2232a814908STejun Heo 					/* each slot's duration is 2s / 16 */
2242a814908STejun Heo #define WB_FRN_HIST_THR_SLOTS	(WB_FRN_HIST_SLOTS / 2)
2252a814908STejun Heo 					/* if foreign slots >= 8, switch */
2262a814908STejun Heo #define WB_FRN_HIST_MAX_SLOTS	(WB_FRN_HIST_THR_SLOTS / 2 + 1)
2272a814908STejun Heo 					/* one round can affect upto 5 slots */
2286444f47eSTejun Heo #define WB_FRN_MAX_IN_FLIGHT	1024	/* don't queue too many concurrently */
2292a814908STejun Heo 
230c22d70a1SRoman Gushchin /*
231c22d70a1SRoman Gushchin  * Maximum inodes per isw.  A specific value has been chosen to make
232c22d70a1SRoman Gushchin  * struct inode_switch_wbs_context fit into 1024 bytes kmalloc.
233c22d70a1SRoman Gushchin  */
234c22d70a1SRoman Gushchin #define WB_MAX_INODES_PER_ISW  ((1024UL - sizeof(struct inode_switch_wbs_context)) \
235c22d70a1SRoman Gushchin                                 / sizeof(struct inode *))
236c22d70a1SRoman Gushchin 
237a1a0e23eSTejun Heo static atomic_t isw_nr_in_flight = ATOMIC_INIT(0);
238a1a0e23eSTejun Heo static struct workqueue_struct *isw_wq;
239a1a0e23eSTejun Heo 
2409cfb816bSMatthew Wilcox (Oracle) void __inode_attach_wb(struct inode *inode, struct folio *folio)
24121c6321fSTejun Heo {
24221c6321fSTejun Heo 	struct backing_dev_info *bdi = inode_to_bdi(inode);
24321c6321fSTejun Heo 	struct bdi_writeback *wb = NULL;
24421c6321fSTejun Heo 
24521c6321fSTejun Heo 	if (inode_cgwb_enabled(inode)) {
24621c6321fSTejun Heo 		struct cgroup_subsys_state *memcg_css;
24721c6321fSTejun Heo 
2489cfb816bSMatthew Wilcox (Oracle) 		if (folio) {
24975376c6fSMatthew Wilcox (Oracle) 			memcg_css = mem_cgroup_css_from_folio(folio);
25021c6321fSTejun Heo 			wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
25121c6321fSTejun Heo 		} else {
25221c6321fSTejun Heo 			/* must pin memcg_css, see wb_get_create() */
25321c6321fSTejun Heo 			memcg_css = task_get_css(current, memory_cgrp_id);
25421c6321fSTejun Heo 			wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
25521c6321fSTejun Heo 			css_put(memcg_css);
25621c6321fSTejun Heo 		}
25721c6321fSTejun Heo 	}
25821c6321fSTejun Heo 
25921c6321fSTejun Heo 	if (!wb)
26021c6321fSTejun Heo 		wb = &bdi->wb;
26121c6321fSTejun Heo 
26221c6321fSTejun Heo 	/*
26321c6321fSTejun Heo 	 * There may be multiple instances of this function racing to
26421c6321fSTejun Heo 	 * update the same inode.  Use cmpxchg() to tell the winner.
26521c6321fSTejun Heo 	 */
26621c6321fSTejun Heo 	if (unlikely(cmpxchg(&inode->i_wb, NULL, wb)))
26721c6321fSTejun Heo 		wb_put(wb);
26821c6321fSTejun Heo }
2699b0eb69bSTejun Heo EXPORT_SYMBOL_GPL(__inode_attach_wb);
27021c6321fSTejun Heo 
271703c2708STejun Heo /**
272f3b6a6dfSRoman Gushchin  * inode_cgwb_move_to_attached - put the inode onto wb->b_attached list
273f3b6a6dfSRoman Gushchin  * @inode: inode of interest with i_lock held
274f3b6a6dfSRoman Gushchin  * @wb: target bdi_writeback
275f3b6a6dfSRoman Gushchin  *
276f3b6a6dfSRoman Gushchin  * Remove the inode from wb's io lists and if necessarily put onto b_attached
277f3b6a6dfSRoman Gushchin  * list.  Only inodes attached to cgwb's are kept on this list.
278f3b6a6dfSRoman Gushchin  */
279f3b6a6dfSRoman Gushchin static void inode_cgwb_move_to_attached(struct inode *inode,
280f3b6a6dfSRoman Gushchin 					struct bdi_writeback *wb)
281f3b6a6dfSRoman Gushchin {
282f3b6a6dfSRoman Gushchin 	assert_spin_locked(&wb->list_lock);
283f3b6a6dfSRoman Gushchin 	assert_spin_locked(&inode->i_lock);
284a9438b44SJan Kara 	WARN_ON_ONCE(inode->i_state & I_FREEING);
285f3b6a6dfSRoman Gushchin 
286f3b6a6dfSRoman Gushchin 	inode->i_state &= ~I_SYNC_QUEUED;
287f3b6a6dfSRoman Gushchin 	if (wb != &wb->bdi->wb)
288f3b6a6dfSRoman Gushchin 		list_move(&inode->i_io_list, &wb->b_attached);
289f3b6a6dfSRoman Gushchin 	else
290f3b6a6dfSRoman Gushchin 		list_del_init(&inode->i_io_list);
291f3b6a6dfSRoman Gushchin 	wb_io_lists_depopulated(wb);
292f3b6a6dfSRoman Gushchin }
293f3b6a6dfSRoman Gushchin 
294f3b6a6dfSRoman Gushchin /**
29587e1d789STejun Heo  * locked_inode_to_wb_and_lock_list - determine a locked inode's wb and lock it
29687e1d789STejun Heo  * @inode: inode of interest with i_lock held
29787e1d789STejun Heo  *
29887e1d789STejun Heo  * Returns @inode's wb with its list_lock held.  @inode->i_lock must be
29987e1d789STejun Heo  * held on entry and is released on return.  The returned wb is guaranteed
30087e1d789STejun Heo  * to stay @inode's associated wb until its list_lock is released.
30187e1d789STejun Heo  */
30287e1d789STejun Heo static struct bdi_writeback *
30387e1d789STejun Heo locked_inode_to_wb_and_lock_list(struct inode *inode)
30487e1d789STejun Heo 	__releases(&inode->i_lock)
30587e1d789STejun Heo 	__acquires(&wb->list_lock)
30687e1d789STejun Heo {
30787e1d789STejun Heo 	while (true) {
30887e1d789STejun Heo 		struct bdi_writeback *wb = inode_to_wb(inode);
30987e1d789STejun Heo 
31087e1d789STejun Heo 		/*
31187e1d789STejun Heo 		 * inode_to_wb() association is protected by both
31287e1d789STejun Heo 		 * @inode->i_lock and @wb->list_lock but list_lock nests
31387e1d789STejun Heo 		 * outside i_lock.  Drop i_lock and verify that the
31487e1d789STejun Heo 		 * association hasn't changed after acquiring list_lock.
31587e1d789STejun Heo 		 */
31687e1d789STejun Heo 		wb_get(wb);
31787e1d789STejun Heo 		spin_unlock(&inode->i_lock);
31887e1d789STejun Heo 		spin_lock(&wb->list_lock);
31987e1d789STejun Heo 
320aaa2cacfSTejun Heo 		/* i_wb may have changed inbetween, can't use inode_to_wb() */
321614a4e37STejun Heo 		if (likely(wb == inode->i_wb)) {
322614a4e37STejun Heo 			wb_put(wb);	/* @inode already has ref */
323614a4e37STejun Heo 			return wb;
324614a4e37STejun Heo 		}
32587e1d789STejun Heo 
32687e1d789STejun Heo 		spin_unlock(&wb->list_lock);
327614a4e37STejun Heo 		wb_put(wb);
32887e1d789STejun Heo 		cpu_relax();
32987e1d789STejun Heo 		spin_lock(&inode->i_lock);
33087e1d789STejun Heo 	}
33187e1d789STejun Heo }
33287e1d789STejun Heo 
33387e1d789STejun Heo /**
33487e1d789STejun Heo  * inode_to_wb_and_lock_list - determine an inode's wb and lock it
33587e1d789STejun Heo  * @inode: inode of interest
33687e1d789STejun Heo  *
33787e1d789STejun Heo  * Same as locked_inode_to_wb_and_lock_list() but @inode->i_lock isn't held
33887e1d789STejun Heo  * on entry.
33987e1d789STejun Heo  */
34087e1d789STejun Heo static struct bdi_writeback *inode_to_wb_and_lock_list(struct inode *inode)
34187e1d789STejun Heo 	__acquires(&wb->list_lock)
34287e1d789STejun Heo {
34387e1d789STejun Heo 	spin_lock(&inode->i_lock);
34487e1d789STejun Heo 	return locked_inode_to_wb_and_lock_list(inode);
34587e1d789STejun Heo }
34687e1d789STejun Heo 
347682aa8e1STejun Heo struct inode_switch_wbs_context {
34829264d92SRoman Gushchin 	struct rcu_work		work;
349f5fbe6b7SRoman Gushchin 
350f5fbe6b7SRoman Gushchin 	/*
351f5fbe6b7SRoman Gushchin 	 * Multiple inodes can be switched at once.  The switching procedure
352f5fbe6b7SRoman Gushchin 	 * consists of two parts, separated by a RCU grace period.  To make
353f5fbe6b7SRoman Gushchin 	 * sure that the second part is executed for each inode gone through
354f5fbe6b7SRoman Gushchin 	 * the first part, all inode pointers are placed into a NULL-terminated
355f5fbe6b7SRoman Gushchin 	 * array embedded into struct inode_switch_wbs_context.  Otherwise
356f5fbe6b7SRoman Gushchin 	 * an inode could be left in a non-consistent state.
357f5fbe6b7SRoman Gushchin 	 */
358f5fbe6b7SRoman Gushchin 	struct bdi_writeback	*new_wb;
359f5fbe6b7SRoman Gushchin 	struct inode		*inodes[];
360682aa8e1STejun Heo };
361682aa8e1STejun Heo 
3627fc5854fSTejun Heo static void bdi_down_write_wb_switch_rwsem(struct backing_dev_info *bdi)
3637fc5854fSTejun Heo {
3647fc5854fSTejun Heo 	down_write(&bdi->wb_switch_rwsem);
3657fc5854fSTejun Heo }
3667fc5854fSTejun Heo 
3677fc5854fSTejun Heo static void bdi_up_write_wb_switch_rwsem(struct backing_dev_info *bdi)
3687fc5854fSTejun Heo {
3697fc5854fSTejun Heo 	up_write(&bdi->wb_switch_rwsem);
3707fc5854fSTejun Heo }
3717fc5854fSTejun Heo 
372f5fbe6b7SRoman Gushchin static bool inode_do_switch_wbs(struct inode *inode,
373f5fbe6b7SRoman Gushchin 				struct bdi_writeback *old_wb,
37472d4512eSRoman Gushchin 				struct bdi_writeback *new_wb)
375682aa8e1STejun Heo {
376d10c8095STejun Heo 	struct address_space *mapping = inode->i_mapping;
37704edf02cSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, 0);
37822b3c8d6SMatthew Wilcox (Oracle) 	struct folio *folio;
379d10c8095STejun Heo 	bool switched = false;
380682aa8e1STejun Heo 
381682aa8e1STejun Heo 	spin_lock(&inode->i_lock);
382b93b0163SMatthew Wilcox 	xa_lock_irq(&mapping->i_pages);
383682aa8e1STejun Heo 
384d10c8095STejun Heo 	/*
3854ade5867SRoman Gushchin 	 * Once I_FREEING or I_WILL_FREE are visible under i_lock, the eviction
3864ade5867SRoman Gushchin 	 * path owns the inode and we shouldn't modify ->i_io_list.
387d10c8095STejun Heo 	 */
3884ade5867SRoman Gushchin 	if (unlikely(inode->i_state & (I_FREEING | I_WILL_FREE)))
389d10c8095STejun Heo 		goto skip_switch;
390d10c8095STejun Heo 
3913a8e9ac8STejun Heo 	trace_inode_switch_wbs(inode, old_wb, new_wb);
3923a8e9ac8STejun Heo 
393d10c8095STejun Heo 	/*
394d10c8095STejun Heo 	 * Count and transfer stats.  Note that PAGECACHE_TAG_DIRTY points
39522b3c8d6SMatthew Wilcox (Oracle) 	 * to possibly dirty folios while PAGECACHE_TAG_WRITEBACK points to
39622b3c8d6SMatthew Wilcox (Oracle) 	 * folios actually under writeback.
397d10c8095STejun Heo 	 */
39822b3c8d6SMatthew Wilcox (Oracle) 	xas_for_each_marked(&xas, folio, ULONG_MAX, PAGECACHE_TAG_DIRTY) {
39922b3c8d6SMatthew Wilcox (Oracle) 		if (folio_test_dirty(folio)) {
40022b3c8d6SMatthew Wilcox (Oracle) 			long nr = folio_nr_pages(folio);
40122b3c8d6SMatthew Wilcox (Oracle) 			wb_stat_mod(old_wb, WB_RECLAIMABLE, -nr);
40222b3c8d6SMatthew Wilcox (Oracle) 			wb_stat_mod(new_wb, WB_RECLAIMABLE, nr);
403d10c8095STejun Heo 		}
404d10c8095STejun Heo 	}
405d10c8095STejun Heo 
40604edf02cSMatthew Wilcox 	xas_set(&xas, 0);
40722b3c8d6SMatthew Wilcox (Oracle) 	xas_for_each_marked(&xas, folio, ULONG_MAX, PAGECACHE_TAG_WRITEBACK) {
40822b3c8d6SMatthew Wilcox (Oracle) 		long nr = folio_nr_pages(folio);
40922b3c8d6SMatthew Wilcox (Oracle) 		WARN_ON_ONCE(!folio_test_writeback(folio));
41022b3c8d6SMatthew Wilcox (Oracle) 		wb_stat_mod(old_wb, WB_WRITEBACK, -nr);
41122b3c8d6SMatthew Wilcox (Oracle) 		wb_stat_mod(new_wb, WB_WRITEBACK, nr);
412d10c8095STejun Heo 	}
413d10c8095STejun Heo 
414633a2abbSJan Kara 	if (mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK)) {
415633a2abbSJan Kara 		atomic_dec(&old_wb->writeback_inodes);
416633a2abbSJan Kara 		atomic_inc(&new_wb->writeback_inodes);
417633a2abbSJan Kara 	}
418633a2abbSJan Kara 
419d10c8095STejun Heo 	wb_get(new_wb);
420d10c8095STejun Heo 
421d10c8095STejun Heo 	/*
422f3b6a6dfSRoman Gushchin 	 * Transfer to @new_wb's IO list if necessary.  If the @inode is dirty,
423f3b6a6dfSRoman Gushchin 	 * the specific list @inode was on is ignored and the @inode is put on
424f3b6a6dfSRoman Gushchin 	 * ->b_dirty which is always correct including from ->b_dirty_time.
425f3b6a6dfSRoman Gushchin 	 * The transfer preserves @inode->dirtied_when ordering.  If the @inode
426f3b6a6dfSRoman Gushchin 	 * was clean, it means it was on the b_attached list, so move it onto
427f3b6a6dfSRoman Gushchin 	 * the b_attached list of @new_wb.
428d10c8095STejun Heo 	 */
429c7f54084SDave Chinner 	if (!list_empty(&inode->i_io_list)) {
430f3b6a6dfSRoman Gushchin 		inode->i_wb = new_wb;
431f3b6a6dfSRoman Gushchin 
432f3b6a6dfSRoman Gushchin 		if (inode->i_state & I_DIRTY_ALL) {
433d10c8095STejun Heo 			struct inode *pos;
434d10c8095STejun Heo 
435c7f54084SDave Chinner 			list_for_each_entry(pos, &new_wb->b_dirty, i_io_list)
436d10c8095STejun Heo 				if (time_after_eq(inode->dirtied_when,
437d10c8095STejun Heo 						  pos->dirtied_when))
438d10c8095STejun Heo 					break;
439f3b6a6dfSRoman Gushchin 			inode_io_list_move_locked(inode, new_wb,
440f3b6a6dfSRoman Gushchin 						  pos->i_io_list.prev);
441f3b6a6dfSRoman Gushchin 		} else {
442f3b6a6dfSRoman Gushchin 			inode_cgwb_move_to_attached(inode, new_wb);
443f3b6a6dfSRoman Gushchin 		}
444d10c8095STejun Heo 	} else {
445d10c8095STejun Heo 		inode->i_wb = new_wb;
446d10c8095STejun Heo 	}
447d10c8095STejun Heo 
448d10c8095STejun Heo 	/* ->i_wb_frn updates may race wbc_detach_inode() but doesn't matter */
449682aa8e1STejun Heo 	inode->i_wb_frn_winner = 0;
450682aa8e1STejun Heo 	inode->i_wb_frn_avg_time = 0;
451682aa8e1STejun Heo 	inode->i_wb_frn_history = 0;
452d10c8095STejun Heo 	switched = true;
453d10c8095STejun Heo skip_switch:
454682aa8e1STejun Heo 	/*
455682aa8e1STejun Heo 	 * Paired with load_acquire in unlocked_inode_to_wb_begin() and
456682aa8e1STejun Heo 	 * ensures that the new wb is visible if they see !I_WB_SWITCH.
457682aa8e1STejun Heo 	 */
458682aa8e1STejun Heo 	smp_store_release(&inode->i_state, inode->i_state & ~I_WB_SWITCH);
459682aa8e1STejun Heo 
460b93b0163SMatthew Wilcox 	xa_unlock_irq(&mapping->i_pages);
461682aa8e1STejun Heo 	spin_unlock(&inode->i_lock);
462d10c8095STejun Heo 
463f5fbe6b7SRoman Gushchin 	return switched;
46472d4512eSRoman Gushchin }
465682aa8e1STejun Heo 
46672d4512eSRoman Gushchin static void inode_switch_wbs_work_fn(struct work_struct *work)
46772d4512eSRoman Gushchin {
46872d4512eSRoman Gushchin 	struct inode_switch_wbs_context *isw =
46972d4512eSRoman Gushchin 		container_of(to_rcu_work(work), struct inode_switch_wbs_context, work);
470f5fbe6b7SRoman Gushchin 	struct backing_dev_info *bdi = inode_to_bdi(isw->inodes[0]);
471f5fbe6b7SRoman Gushchin 	struct bdi_writeback *old_wb = isw->inodes[0]->i_wb;
472f5fbe6b7SRoman Gushchin 	struct bdi_writeback *new_wb = isw->new_wb;
473f5fbe6b7SRoman Gushchin 	unsigned long nr_switched = 0;
474f5fbe6b7SRoman Gushchin 	struct inode **inodep;
47572d4512eSRoman Gushchin 
476f5fbe6b7SRoman Gushchin 	/*
477f5fbe6b7SRoman Gushchin 	 * If @inode switches cgwb membership while sync_inodes_sb() is
478f5fbe6b7SRoman Gushchin 	 * being issued, sync_inodes_sb() might miss it.  Synchronize.
479f5fbe6b7SRoman Gushchin 	 */
480f5fbe6b7SRoman Gushchin 	down_read(&bdi->wb_switch_rwsem);
481f5fbe6b7SRoman Gushchin 
482f5fbe6b7SRoman Gushchin 	/*
483f5fbe6b7SRoman Gushchin 	 * By the time control reaches here, RCU grace period has passed
484f5fbe6b7SRoman Gushchin 	 * since I_WB_SWITCH assertion and all wb stat update transactions
485f5fbe6b7SRoman Gushchin 	 * between unlocked_inode_to_wb_begin/end() are guaranteed to be
486f5fbe6b7SRoman Gushchin 	 * synchronizing against the i_pages lock.
487f5fbe6b7SRoman Gushchin 	 *
488f5fbe6b7SRoman Gushchin 	 * Grabbing old_wb->list_lock, inode->i_lock and the i_pages lock
489f5fbe6b7SRoman Gushchin 	 * gives us exclusion against all wb related operations on @inode
490f5fbe6b7SRoman Gushchin 	 * including IO list manipulations and stat updates.
491f5fbe6b7SRoman Gushchin 	 */
492f5fbe6b7SRoman Gushchin 	if (old_wb < new_wb) {
493f5fbe6b7SRoman Gushchin 		spin_lock(&old_wb->list_lock);
494f5fbe6b7SRoman Gushchin 		spin_lock_nested(&new_wb->list_lock, SINGLE_DEPTH_NESTING);
495f5fbe6b7SRoman Gushchin 	} else {
496f5fbe6b7SRoman Gushchin 		spin_lock(&new_wb->list_lock);
497f5fbe6b7SRoman Gushchin 		spin_lock_nested(&old_wb->list_lock, SINGLE_DEPTH_NESTING);
498f5fbe6b7SRoman Gushchin 	}
499f5fbe6b7SRoman Gushchin 
500f5fbe6b7SRoman Gushchin 	for (inodep = isw->inodes; *inodep; inodep++) {
501f5fbe6b7SRoman Gushchin 		WARN_ON_ONCE((*inodep)->i_wb != old_wb);
502f5fbe6b7SRoman Gushchin 		if (inode_do_switch_wbs(*inodep, old_wb, new_wb))
503f5fbe6b7SRoman Gushchin 			nr_switched++;
504f5fbe6b7SRoman Gushchin 	}
505f5fbe6b7SRoman Gushchin 
506f5fbe6b7SRoman Gushchin 	spin_unlock(&new_wb->list_lock);
507f5fbe6b7SRoman Gushchin 	spin_unlock(&old_wb->list_lock);
508f5fbe6b7SRoman Gushchin 
509f5fbe6b7SRoman Gushchin 	up_read(&bdi->wb_switch_rwsem);
510f5fbe6b7SRoman Gushchin 
511f5fbe6b7SRoman Gushchin 	if (nr_switched) {
512f5fbe6b7SRoman Gushchin 		wb_wakeup(new_wb);
513f5fbe6b7SRoman Gushchin 		wb_put_many(old_wb, nr_switched);
514f5fbe6b7SRoman Gushchin 	}
515f5fbe6b7SRoman Gushchin 
516f5fbe6b7SRoman Gushchin 	for (inodep = isw->inodes; *inodep; inodep++)
517f5fbe6b7SRoman Gushchin 		iput(*inodep);
518f5fbe6b7SRoman Gushchin 	wb_put(new_wb);
519682aa8e1STejun Heo 	kfree(isw);
520a1a0e23eSTejun Heo 	atomic_dec(&isw_nr_in_flight);
521682aa8e1STejun Heo }
522682aa8e1STejun Heo 
523c22d70a1SRoman Gushchin static bool inode_prepare_wbs_switch(struct inode *inode,
524c22d70a1SRoman Gushchin 				     struct bdi_writeback *new_wb)
525c22d70a1SRoman Gushchin {
526c22d70a1SRoman Gushchin 	/*
527c22d70a1SRoman Gushchin 	 * Paired with smp_mb() in cgroup_writeback_umount().
528c22d70a1SRoman Gushchin 	 * isw_nr_in_flight must be increased before checking SB_ACTIVE and
529c22d70a1SRoman Gushchin 	 * grabbing an inode, otherwise isw_nr_in_flight can be observed as 0
530c22d70a1SRoman Gushchin 	 * in cgroup_writeback_umount() and the isw_wq will be not flushed.
531c22d70a1SRoman Gushchin 	 */
532c22d70a1SRoman Gushchin 	smp_mb();
533c22d70a1SRoman Gushchin 
534593311e8SRoman Gushchin 	if (IS_DAX(inode))
535593311e8SRoman Gushchin 		return false;
536593311e8SRoman Gushchin 
537c22d70a1SRoman Gushchin 	/* while holding I_WB_SWITCH, no one else can update the association */
538c22d70a1SRoman Gushchin 	spin_lock(&inode->i_lock);
539c22d70a1SRoman Gushchin 	if (!(inode->i_sb->s_flags & SB_ACTIVE) ||
540c22d70a1SRoman Gushchin 	    inode->i_state & (I_WB_SWITCH | I_FREEING | I_WILL_FREE) ||
541c22d70a1SRoman Gushchin 	    inode_to_wb(inode) == new_wb) {
542c22d70a1SRoman Gushchin 		spin_unlock(&inode->i_lock);
543c22d70a1SRoman Gushchin 		return false;
544c22d70a1SRoman Gushchin 	}
545c22d70a1SRoman Gushchin 	inode->i_state |= I_WB_SWITCH;
546c22d70a1SRoman Gushchin 	__iget(inode);
547c22d70a1SRoman Gushchin 	spin_unlock(&inode->i_lock);
548c22d70a1SRoman Gushchin 
549c22d70a1SRoman Gushchin 	return true;
550c22d70a1SRoman Gushchin }
551c22d70a1SRoman Gushchin 
552682aa8e1STejun Heo /**
553682aa8e1STejun Heo  * inode_switch_wbs - change the wb association of an inode
554682aa8e1STejun Heo  * @inode: target inode
555682aa8e1STejun Heo  * @new_wb_id: ID of the new wb
556682aa8e1STejun Heo  *
557682aa8e1STejun Heo  * Switch @inode's wb association to the wb identified by @new_wb_id.  The
558682aa8e1STejun Heo  * switching is performed asynchronously and may fail silently.
559682aa8e1STejun Heo  */
560682aa8e1STejun Heo static void inode_switch_wbs(struct inode *inode, int new_wb_id)
561682aa8e1STejun Heo {
562682aa8e1STejun Heo 	struct backing_dev_info *bdi = inode_to_bdi(inode);
563682aa8e1STejun Heo 	struct cgroup_subsys_state *memcg_css;
564682aa8e1STejun Heo 	struct inode_switch_wbs_context *isw;
565682aa8e1STejun Heo 
566682aa8e1STejun Heo 	/* noop if seems to be already in progress */
567682aa8e1STejun Heo 	if (inode->i_state & I_WB_SWITCH)
568682aa8e1STejun Heo 		return;
569682aa8e1STejun Heo 
5706444f47eSTejun Heo 	/* avoid queueing a new switch if too many are already in flight */
5716444f47eSTejun Heo 	if (atomic_read(&isw_nr_in_flight) > WB_FRN_MAX_IN_FLIGHT)
5727fc5854fSTejun Heo 		return;
5737fc5854fSTejun Heo 
57498b160c8SLen Baker 	isw = kzalloc(struct_size(isw, inodes, 2), GFP_ATOMIC);
575682aa8e1STejun Heo 	if (!isw)
5766444f47eSTejun Heo 		return;
577682aa8e1STejun Heo 
5788826ee4fSRoman Gushchin 	atomic_inc(&isw_nr_in_flight);
5798826ee4fSRoman Gushchin 
580682aa8e1STejun Heo 	/* find and pin the new wb */
581682aa8e1STejun Heo 	rcu_read_lock();
582682aa8e1STejun Heo 	memcg_css = css_from_id(new_wb_id, &memory_cgrp_subsys);
5838b0ed844SMuchun Song 	if (memcg_css && !css_tryget(memcg_css))
5848b0ed844SMuchun Song 		memcg_css = NULL;
585682aa8e1STejun Heo 	rcu_read_unlock();
5868b0ed844SMuchun Song 	if (!memcg_css)
5878b0ed844SMuchun Song 		goto out_free;
5888b0ed844SMuchun Song 
5898b0ed844SMuchun Song 	isw->new_wb = wb_get_create(bdi, memcg_css, GFP_ATOMIC);
5908b0ed844SMuchun Song 	css_put(memcg_css);
591682aa8e1STejun Heo 	if (!isw->new_wb)
592682aa8e1STejun Heo 		goto out_free;
593682aa8e1STejun Heo 
594c22d70a1SRoman Gushchin 	if (!inode_prepare_wbs_switch(inode, isw->new_wb))
595a1a0e23eSTejun Heo 		goto out_free;
596682aa8e1STejun Heo 
597f5fbe6b7SRoman Gushchin 	isw->inodes[0] = inode;
598682aa8e1STejun Heo 
599682aa8e1STejun Heo 	/*
600682aa8e1STejun Heo 	 * In addition to synchronizing among switchers, I_WB_SWITCH tells
601b93b0163SMatthew Wilcox 	 * the RCU protected stat update paths to grab the i_page
602b93b0163SMatthew Wilcox 	 * lock so that stat transfer can synchronize against them.
603682aa8e1STejun Heo 	 * Let's continue after I_WB_SWITCH is guaranteed to be visible.
604682aa8e1STejun Heo 	 */
60529264d92SRoman Gushchin 	INIT_RCU_WORK(&isw->work, inode_switch_wbs_work_fn);
60629264d92SRoman Gushchin 	queue_rcu_work(isw_wq, &isw->work);
6076444f47eSTejun Heo 	return;
608682aa8e1STejun Heo 
609682aa8e1STejun Heo out_free:
6108826ee4fSRoman Gushchin 	atomic_dec(&isw_nr_in_flight);
611682aa8e1STejun Heo 	if (isw->new_wb)
612682aa8e1STejun Heo 		wb_put(isw->new_wb);
613682aa8e1STejun Heo 	kfree(isw);
614682aa8e1STejun Heo }
615682aa8e1STejun Heo 
61687e1d789STejun Heo /**
617c22d70a1SRoman Gushchin  * cleanup_offline_cgwb - detach associated inodes
618c22d70a1SRoman Gushchin  * @wb: target wb
619c22d70a1SRoman Gushchin  *
620c22d70a1SRoman Gushchin  * Switch all inodes attached to @wb to a nearest living ancestor's wb in order
621c22d70a1SRoman Gushchin  * to eventually release the dying @wb.  Returns %true if not all inodes were
622c22d70a1SRoman Gushchin  * switched and the function has to be restarted.
623c22d70a1SRoman Gushchin  */
624c22d70a1SRoman Gushchin bool cleanup_offline_cgwb(struct bdi_writeback *wb)
625c22d70a1SRoman Gushchin {
626c22d70a1SRoman Gushchin 	struct cgroup_subsys_state *memcg_css;
627c22d70a1SRoman Gushchin 	struct inode_switch_wbs_context *isw;
628c22d70a1SRoman Gushchin 	struct inode *inode;
629c22d70a1SRoman Gushchin 	int nr;
630c22d70a1SRoman Gushchin 	bool restart = false;
631c22d70a1SRoman Gushchin 
63298b160c8SLen Baker 	isw = kzalloc(struct_size(isw, inodes, WB_MAX_INODES_PER_ISW),
63398b160c8SLen Baker 		      GFP_KERNEL);
634c22d70a1SRoman Gushchin 	if (!isw)
635c22d70a1SRoman Gushchin 		return restart;
636c22d70a1SRoman Gushchin 
637c22d70a1SRoman Gushchin 	atomic_inc(&isw_nr_in_flight);
638c22d70a1SRoman Gushchin 
639c22d70a1SRoman Gushchin 	for (memcg_css = wb->memcg_css->parent; memcg_css;
640c22d70a1SRoman Gushchin 	     memcg_css = memcg_css->parent) {
641c22d70a1SRoman Gushchin 		isw->new_wb = wb_get_create(wb->bdi, memcg_css, GFP_KERNEL);
642c22d70a1SRoman Gushchin 		if (isw->new_wb)
643c22d70a1SRoman Gushchin 			break;
644c22d70a1SRoman Gushchin 	}
645c22d70a1SRoman Gushchin 	if (unlikely(!isw->new_wb))
646c22d70a1SRoman Gushchin 		isw->new_wb = &wb->bdi->wb; /* wb_get() is noop for bdi's wb */
647c22d70a1SRoman Gushchin 
648c22d70a1SRoman Gushchin 	nr = 0;
649c22d70a1SRoman Gushchin 	spin_lock(&wb->list_lock);
650c22d70a1SRoman Gushchin 	list_for_each_entry(inode, &wb->b_attached, i_io_list) {
651c22d70a1SRoman Gushchin 		if (!inode_prepare_wbs_switch(inode, isw->new_wb))
652c22d70a1SRoman Gushchin 			continue;
653c22d70a1SRoman Gushchin 
654c22d70a1SRoman Gushchin 		isw->inodes[nr++] = inode;
655c22d70a1SRoman Gushchin 
656c22d70a1SRoman Gushchin 		if (nr >= WB_MAX_INODES_PER_ISW - 1) {
657c22d70a1SRoman Gushchin 			restart = true;
658c22d70a1SRoman Gushchin 			break;
659c22d70a1SRoman Gushchin 		}
660c22d70a1SRoman Gushchin 	}
661c22d70a1SRoman Gushchin 	spin_unlock(&wb->list_lock);
662c22d70a1SRoman Gushchin 
663c22d70a1SRoman Gushchin 	/* no attached inodes? bail out */
664c22d70a1SRoman Gushchin 	if (nr == 0) {
665c22d70a1SRoman Gushchin 		atomic_dec(&isw_nr_in_flight);
666c22d70a1SRoman Gushchin 		wb_put(isw->new_wb);
667c22d70a1SRoman Gushchin 		kfree(isw);
668c22d70a1SRoman Gushchin 		return restart;
669c22d70a1SRoman Gushchin 	}
670c22d70a1SRoman Gushchin 
671c22d70a1SRoman Gushchin 	/*
672c22d70a1SRoman Gushchin 	 * In addition to synchronizing among switchers, I_WB_SWITCH tells
673c22d70a1SRoman Gushchin 	 * the RCU protected stat update paths to grab the i_page
674c22d70a1SRoman Gushchin 	 * lock so that stat transfer can synchronize against them.
675c22d70a1SRoman Gushchin 	 * Let's continue after I_WB_SWITCH is guaranteed to be visible.
676c22d70a1SRoman Gushchin 	 */
677c22d70a1SRoman Gushchin 	INIT_RCU_WORK(&isw->work, inode_switch_wbs_work_fn);
678c22d70a1SRoman Gushchin 	queue_rcu_work(isw_wq, &isw->work);
679c22d70a1SRoman Gushchin 
680c22d70a1SRoman Gushchin 	return restart;
681c22d70a1SRoman Gushchin }
682c22d70a1SRoman Gushchin 
683c22d70a1SRoman Gushchin /**
684b16b1debSTejun Heo  * wbc_attach_and_unlock_inode - associate wbc with target inode and unlock it
685b16b1debSTejun Heo  * @wbc: writeback_control of interest
686b16b1debSTejun Heo  * @inode: target inode
687b16b1debSTejun Heo  *
688b16b1debSTejun Heo  * @inode is locked and about to be written back under the control of @wbc.
689b16b1debSTejun Heo  * Record @inode's writeback context into @wbc and unlock the i_lock.  On
690b16b1debSTejun Heo  * writeback completion, wbc_detach_inode() should be called.  This is used
691b16b1debSTejun Heo  * to track the cgroup writeback context.
692b16b1debSTejun Heo  */
693b16b1debSTejun Heo void wbc_attach_and_unlock_inode(struct writeback_control *wbc,
694b16b1debSTejun Heo 				 struct inode *inode)
695b16b1debSTejun Heo {
696dd73e4b7STejun Heo 	if (!inode_cgwb_enabled(inode)) {
697dd73e4b7STejun Heo 		spin_unlock(&inode->i_lock);
698dd73e4b7STejun Heo 		return;
699dd73e4b7STejun Heo 	}
700dd73e4b7STejun Heo 
701b16b1debSTejun Heo 	wbc->wb = inode_to_wb(inode);
7022a814908STejun Heo 	wbc->inode = inode;
7032a814908STejun Heo 
7042a814908STejun Heo 	wbc->wb_id = wbc->wb->memcg_css->id;
7052a814908STejun Heo 	wbc->wb_lcand_id = inode->i_wb_frn_winner;
7062a814908STejun Heo 	wbc->wb_tcand_id = 0;
7072a814908STejun Heo 	wbc->wb_bytes = 0;
7082a814908STejun Heo 	wbc->wb_lcand_bytes = 0;
7092a814908STejun Heo 	wbc->wb_tcand_bytes = 0;
7102a814908STejun Heo 
711b16b1debSTejun Heo 	wb_get(wbc->wb);
712b16b1debSTejun Heo 	spin_unlock(&inode->i_lock);
713e8a7abf5STejun Heo 
714e8a7abf5STejun Heo 	/*
71565de03e2STejun Heo 	 * A dying wb indicates that either the blkcg associated with the
71665de03e2STejun Heo 	 * memcg changed or the associated memcg is dying.  In the first
71765de03e2STejun Heo 	 * case, a replacement wb should already be available and we should
71865de03e2STejun Heo 	 * refresh the wb immediately.  In the second case, trying to
71965de03e2STejun Heo 	 * refresh will keep failing.
720e8a7abf5STejun Heo 	 */
72165de03e2STejun Heo 	if (unlikely(wb_dying(wbc->wb) && !css_is_dying(wbc->wb->memcg_css)))
722e8a7abf5STejun Heo 		inode_switch_wbs(inode, wbc->wb_id);
723b16b1debSTejun Heo }
7249b0eb69bSTejun Heo EXPORT_SYMBOL_GPL(wbc_attach_and_unlock_inode);
725b16b1debSTejun Heo 
726b16b1debSTejun Heo /**
7272a814908STejun Heo  * wbc_detach_inode - disassociate wbc from inode and perform foreign detection
7282a814908STejun Heo  * @wbc: writeback_control of the just finished writeback
729b16b1debSTejun Heo  *
730b16b1debSTejun Heo  * To be called after a writeback attempt of an inode finishes and undoes
731b16b1debSTejun Heo  * wbc_attach_and_unlock_inode().  Can be called under any context.
7322a814908STejun Heo  *
7332a814908STejun Heo  * As concurrent write sharing of an inode is expected to be very rare and
7342a814908STejun Heo  * memcg only tracks page ownership on first-use basis severely confining
7352a814908STejun Heo  * the usefulness of such sharing, cgroup writeback tracks ownership
7362a814908STejun Heo  * per-inode.  While the support for concurrent write sharing of an inode
7372a814908STejun Heo  * is deemed unnecessary, an inode being written to by different cgroups at
7382a814908STejun Heo  * different points in time is a lot more common, and, more importantly,
7392a814908STejun Heo  * charging only by first-use can too readily lead to grossly incorrect
7402a814908STejun Heo  * behaviors (single foreign page can lead to gigabytes of writeback to be
7412a814908STejun Heo  * incorrectly attributed).
7422a814908STejun Heo  *
7432a814908STejun Heo  * To resolve this issue, cgroup writeback detects the majority dirtier of
7442999e1e3SJulia Lawall  * an inode and transfers the ownership to it.  To avoid unnecessary
7452a814908STejun Heo  * oscillation, the detection mechanism keeps track of history and gives
7462a814908STejun Heo  * out the switch verdict only if the foreign usage pattern is stable over
7472a814908STejun Heo  * a certain amount of time and/or writeback attempts.
7482a814908STejun Heo  *
7492a814908STejun Heo  * On each writeback attempt, @wbc tries to detect the majority writer
7502a814908STejun Heo  * using Boyer-Moore majority vote algorithm.  In addition to the byte
7512a814908STejun Heo  * count from the majority voting, it also counts the bytes written for the
7522a814908STejun Heo  * current wb and the last round's winner wb (max of last round's current
7532a814908STejun Heo  * wb, the winner from two rounds ago, and the last round's majority
7542a814908STejun Heo  * candidate).  Keeping track of the historical winner helps the algorithm
7552a814908STejun Heo  * to semi-reliably detect the most active writer even when it's not the
7562a814908STejun Heo  * absolute majority.
7572a814908STejun Heo  *
7582a814908STejun Heo  * Once the winner of the round is determined, whether the winner is
7592a814908STejun Heo  * foreign or not and how much IO time the round consumed is recorded in
7602a814908STejun Heo  * inode->i_wb_frn_history.  If the amount of recorded foreign IO time is
7612a814908STejun Heo  * over a certain threshold, the switch verdict is given.
762b16b1debSTejun Heo  */
763b16b1debSTejun Heo void wbc_detach_inode(struct writeback_control *wbc)
764b16b1debSTejun Heo {
7652a814908STejun Heo 	struct bdi_writeback *wb = wbc->wb;
7662a814908STejun Heo 	struct inode *inode = wbc->inode;
767dd73e4b7STejun Heo 	unsigned long avg_time, max_bytes, max_time;
768dd73e4b7STejun Heo 	u16 history;
7692a814908STejun Heo 	int max_id;
7702a814908STejun Heo 
771dd73e4b7STejun Heo 	if (!wb)
772dd73e4b7STejun Heo 		return;
773dd73e4b7STejun Heo 
774dd73e4b7STejun Heo 	history = inode->i_wb_frn_history;
775dd73e4b7STejun Heo 	avg_time = inode->i_wb_frn_avg_time;
776dd73e4b7STejun Heo 
7772a814908STejun Heo 	/* pick the winner of this round */
7782a814908STejun Heo 	if (wbc->wb_bytes >= wbc->wb_lcand_bytes &&
7792a814908STejun Heo 	    wbc->wb_bytes >= wbc->wb_tcand_bytes) {
7802a814908STejun Heo 		max_id = wbc->wb_id;
7812a814908STejun Heo 		max_bytes = wbc->wb_bytes;
7822a814908STejun Heo 	} else if (wbc->wb_lcand_bytes >= wbc->wb_tcand_bytes) {
7832a814908STejun Heo 		max_id = wbc->wb_lcand_id;
7842a814908STejun Heo 		max_bytes = wbc->wb_lcand_bytes;
7852a814908STejun Heo 	} else {
7862a814908STejun Heo 		max_id = wbc->wb_tcand_id;
7872a814908STejun Heo 		max_bytes = wbc->wb_tcand_bytes;
7882a814908STejun Heo 	}
7892a814908STejun Heo 
7902a814908STejun Heo 	/*
7912a814908STejun Heo 	 * Calculate the amount of IO time the winner consumed and fold it
7922a814908STejun Heo 	 * into the running average kept per inode.  If the consumed IO
7932a814908STejun Heo 	 * time is lower than avag / WB_FRN_TIME_CUT_DIV, ignore it for
7942a814908STejun Heo 	 * deciding whether to switch or not.  This is to prevent one-off
7952a814908STejun Heo 	 * small dirtiers from skewing the verdict.
7962a814908STejun Heo 	 */
7972a814908STejun Heo 	max_time = DIV_ROUND_UP((max_bytes >> PAGE_SHIFT) << WB_FRN_TIME_SHIFT,
7982a814908STejun Heo 				wb->avg_write_bandwidth);
7992a814908STejun Heo 	if (avg_time)
8002a814908STejun Heo 		avg_time += (max_time >> WB_FRN_TIME_AVG_SHIFT) -
8012a814908STejun Heo 			    (avg_time >> WB_FRN_TIME_AVG_SHIFT);
8022a814908STejun Heo 	else
8032a814908STejun Heo 		avg_time = max_time;	/* immediate catch up on first run */
8042a814908STejun Heo 
8052a814908STejun Heo 	if (max_time >= avg_time / WB_FRN_TIME_CUT_DIV) {
8062a814908STejun Heo 		int slots;
8072a814908STejun Heo 
8082a814908STejun Heo 		/*
8092a814908STejun Heo 		 * The switch verdict is reached if foreign wb's consume
8102a814908STejun Heo 		 * more than a certain proportion of IO time in a
8112a814908STejun Heo 		 * WB_FRN_TIME_PERIOD.  This is loosely tracked by 16 slot
8122a814908STejun Heo 		 * history mask where each bit represents one sixteenth of
8132a814908STejun Heo 		 * the period.  Determine the number of slots to shift into
8142a814908STejun Heo 		 * history from @max_time.
8152a814908STejun Heo 		 */
8162a814908STejun Heo 		slots = min(DIV_ROUND_UP(max_time, WB_FRN_HIST_UNIT),
8172a814908STejun Heo 			    (unsigned long)WB_FRN_HIST_MAX_SLOTS);
8182a814908STejun Heo 		history <<= slots;
8192a814908STejun Heo 		if (wbc->wb_id != max_id)
8202a814908STejun Heo 			history |= (1U << slots) - 1;
8212a814908STejun Heo 
8223a8e9ac8STejun Heo 		if (history)
8233a8e9ac8STejun Heo 			trace_inode_foreign_history(inode, wbc, history);
8243a8e9ac8STejun Heo 
8252a814908STejun Heo 		/*
8262a814908STejun Heo 		 * Switch if the current wb isn't the consistent winner.
8272a814908STejun Heo 		 * If there are multiple closely competing dirtiers, the
8282a814908STejun Heo 		 * inode may switch across them repeatedly over time, which
8292a814908STejun Heo 		 * is okay.  The main goal is avoiding keeping an inode on
8302a814908STejun Heo 		 * the wrong wb for an extended period of time.
8312a814908STejun Heo 		 */
832682aa8e1STejun Heo 		if (hweight32(history) > WB_FRN_HIST_THR_SLOTS)
833682aa8e1STejun Heo 			inode_switch_wbs(inode, max_id);
8342a814908STejun Heo 	}
8352a814908STejun Heo 
8362a814908STejun Heo 	/*
8372a814908STejun Heo 	 * Multiple instances of this function may race to update the
8382a814908STejun Heo 	 * following fields but we don't mind occassional inaccuracies.
8392a814908STejun Heo 	 */
8402a814908STejun Heo 	inode->i_wb_frn_winner = max_id;
8412a814908STejun Heo 	inode->i_wb_frn_avg_time = min(avg_time, (unsigned long)U16_MAX);
8422a814908STejun Heo 	inode->i_wb_frn_history = history;
8432a814908STejun Heo 
844b16b1debSTejun Heo 	wb_put(wbc->wb);
845b16b1debSTejun Heo 	wbc->wb = NULL;
846b16b1debSTejun Heo }
8479b0eb69bSTejun Heo EXPORT_SYMBOL_GPL(wbc_detach_inode);
848b16b1debSTejun Heo 
849b16b1debSTejun Heo /**
85034e51a5eSTejun Heo  * wbc_account_cgroup_owner - account writeback to update inode cgroup ownership
8512a814908STejun Heo  * @wbc: writeback_control of the writeback in progress
8522a814908STejun Heo  * @page: page being written out
8532a814908STejun Heo  * @bytes: number of bytes being written out
8542a814908STejun Heo  *
8552a814908STejun Heo  * @bytes from @page are about to written out during the writeback
8562a814908STejun Heo  * controlled by @wbc.  Keep the book for foreign inode detection.  See
8572a814908STejun Heo  * wbc_detach_inode().
8582a814908STejun Heo  */
85934e51a5eSTejun Heo void wbc_account_cgroup_owner(struct writeback_control *wbc, struct page *page,
8602a814908STejun Heo 			      size_t bytes)
8612a814908STejun Heo {
86275376c6fSMatthew Wilcox (Oracle) 	struct folio *folio;
86366311422STejun Heo 	struct cgroup_subsys_state *css;
8642a814908STejun Heo 	int id;
8652a814908STejun Heo 
8662a814908STejun Heo 	/*
8672a814908STejun Heo 	 * pageout() path doesn't attach @wbc to the inode being written
8682a814908STejun Heo 	 * out.  This is intentional as we don't want the function to block
8692a814908STejun Heo 	 * behind a slow cgroup.  Ultimately, we want pageout() to kick off
8702a814908STejun Heo 	 * regular writeback instead of writing things out itself.
8712a814908STejun Heo 	 */
87227b36d8fSTejun Heo 	if (!wbc->wb || wbc->no_cgroup_owner)
8732a814908STejun Heo 		return;
8742a814908STejun Heo 
87575376c6fSMatthew Wilcox (Oracle) 	folio = page_folio(page);
87675376c6fSMatthew Wilcox (Oracle) 	css = mem_cgroup_css_from_folio(folio);
87766311422STejun Heo 	/* dead cgroups shouldn't contribute to inode ownership arbitration */
87866311422STejun Heo 	if (!(css->flags & CSS_ONLINE))
87966311422STejun Heo 		return;
88066311422STejun Heo 
88166311422STejun Heo 	id = css->id;
8822a814908STejun Heo 
8832a814908STejun Heo 	if (id == wbc->wb_id) {
8842a814908STejun Heo 		wbc->wb_bytes += bytes;
8852a814908STejun Heo 		return;
8862a814908STejun Heo 	}
8872a814908STejun Heo 
8882a814908STejun Heo 	if (id == wbc->wb_lcand_id)
8892a814908STejun Heo 		wbc->wb_lcand_bytes += bytes;
8902a814908STejun Heo 
8912a814908STejun Heo 	/* Boyer-Moore majority vote algorithm */
8922a814908STejun Heo 	if (!wbc->wb_tcand_bytes)
8932a814908STejun Heo 		wbc->wb_tcand_id = id;
8942a814908STejun Heo 	if (id == wbc->wb_tcand_id)
8952a814908STejun Heo 		wbc->wb_tcand_bytes += bytes;
8962a814908STejun Heo 	else
8972a814908STejun Heo 		wbc->wb_tcand_bytes -= min(bytes, wbc->wb_tcand_bytes);
8982a814908STejun Heo }
89934e51a5eSTejun Heo EXPORT_SYMBOL_GPL(wbc_account_cgroup_owner);
9002a814908STejun Heo 
9012a814908STejun Heo /**
902f2b65121STejun Heo  * wb_split_bdi_pages - split nr_pages to write according to bandwidth
903f2b65121STejun Heo  * @wb: target bdi_writeback to split @nr_pages to
904f2b65121STejun Heo  * @nr_pages: number of pages to write for the whole bdi
905f2b65121STejun Heo  *
906f2b65121STejun Heo  * Split @wb's portion of @nr_pages according to @wb's write bandwidth in
907f2b65121STejun Heo  * relation to the total write bandwidth of all wb's w/ dirty inodes on
908f2b65121STejun Heo  * @wb->bdi.
909f2b65121STejun Heo  */
910f2b65121STejun Heo static long wb_split_bdi_pages(struct bdi_writeback *wb, long nr_pages)
911f2b65121STejun Heo {
912f2b65121STejun Heo 	unsigned long this_bw = wb->avg_write_bandwidth;
913f2b65121STejun Heo 	unsigned long tot_bw = atomic_long_read(&wb->bdi->tot_write_bandwidth);
914f2b65121STejun Heo 
915f2b65121STejun Heo 	if (nr_pages == LONG_MAX)
916f2b65121STejun Heo 		return LONG_MAX;
917f2b65121STejun Heo 
918f2b65121STejun Heo 	/*
919f2b65121STejun Heo 	 * This may be called on clean wb's and proportional distribution
920f2b65121STejun Heo 	 * may not make sense, just use the original @nr_pages in those
921f2b65121STejun Heo 	 * cases.  In general, we wanna err on the side of writing more.
922f2b65121STejun Heo 	 */
923f2b65121STejun Heo 	if (!tot_bw || this_bw >= tot_bw)
924f2b65121STejun Heo 		return nr_pages;
925f2b65121STejun Heo 	else
926f2b65121STejun Heo 		return DIV_ROUND_UP_ULL((u64)nr_pages * this_bw, tot_bw);
927f2b65121STejun Heo }
928f2b65121STejun Heo 
929db125360STejun Heo /**
930db125360STejun Heo  * bdi_split_work_to_wbs - split a wb_writeback_work to all wb's of a bdi
931db125360STejun Heo  * @bdi: target backing_dev_info
932db125360STejun Heo  * @base_work: wb_writeback_work to issue
933db125360STejun Heo  * @skip_if_busy: skip wb's which already have writeback in progress
934db125360STejun Heo  *
935db125360STejun Heo  * Split and issue @base_work to all wb's (bdi_writeback's) of @bdi which
936db125360STejun Heo  * have dirty inodes.  If @base_work->nr_page isn't %LONG_MAX, it's
937db125360STejun Heo  * distributed to the busy wbs according to each wb's proportion in the
938db125360STejun Heo  * total active write bandwidth of @bdi.
939db125360STejun Heo  */
940db125360STejun Heo static void bdi_split_work_to_wbs(struct backing_dev_info *bdi,
941db125360STejun Heo 				  struct wb_writeback_work *base_work,
942db125360STejun Heo 				  bool skip_if_busy)
943db125360STejun Heo {
944b817525aSTejun Heo 	struct bdi_writeback *last_wb = NULL;
945b33e18f6STejun Heo 	struct bdi_writeback *wb = list_entry(&bdi->wb_list,
946b817525aSTejun Heo 					      struct bdi_writeback, bdi_node);
947db125360STejun Heo 
948db125360STejun Heo 	might_sleep();
949db125360STejun Heo restart:
950db125360STejun Heo 	rcu_read_lock();
951b817525aSTejun Heo 	list_for_each_entry_continue_rcu(wb, &bdi->wb_list, bdi_node) {
9525b9cce4cSTejun Heo 		DEFINE_WB_COMPLETION(fallback_work_done, bdi);
9538a1270cdSTejun Heo 		struct wb_writeback_work fallback_work;
9548a1270cdSTejun Heo 		struct wb_writeback_work *work;
9558a1270cdSTejun Heo 		long nr_pages;
9568a1270cdSTejun Heo 
957b817525aSTejun Heo 		if (last_wb) {
958b817525aSTejun Heo 			wb_put(last_wb);
959b817525aSTejun Heo 			last_wb = NULL;
960b817525aSTejun Heo 		}
961b817525aSTejun Heo 
962006a0973STejun Heo 		/* SYNC_ALL writes out I_DIRTY_TIME too */
963006a0973STejun Heo 		if (!wb_has_dirty_io(wb) &&
964006a0973STejun Heo 		    (base_work->sync_mode == WB_SYNC_NONE ||
965006a0973STejun Heo 		     list_empty(&wb->b_dirty_time)))
966006a0973STejun Heo 			continue;
967006a0973STejun Heo 		if (skip_if_busy && writeback_in_progress(wb))
968db125360STejun Heo 			continue;
969db125360STejun Heo 
9708a1270cdSTejun Heo 		nr_pages = wb_split_bdi_pages(wb, base_work->nr_pages);
9718a1270cdSTejun Heo 
9728a1270cdSTejun Heo 		work = kmalloc(sizeof(*work), GFP_ATOMIC);
9738a1270cdSTejun Heo 		if (work) {
9748a1270cdSTejun Heo 			*work = *base_work;
9758a1270cdSTejun Heo 			work->nr_pages = nr_pages;
9768a1270cdSTejun Heo 			work->auto_free = 1;
9778a1270cdSTejun Heo 			wb_queue_work(wb, work);
9788a1270cdSTejun Heo 			continue;
979db125360STejun Heo 		}
9808a1270cdSTejun Heo 
981*1ba1199eSBaokun Li 		/*
982*1ba1199eSBaokun Li 		 * If wb_tryget fails, the wb has been shutdown, skip it.
983*1ba1199eSBaokun Li 		 *
984*1ba1199eSBaokun Li 		 * Pin @wb so that it stays on @bdi->wb_list.  This allows
985*1ba1199eSBaokun Li 		 * continuing iteration from @wb after dropping and
986*1ba1199eSBaokun Li 		 * regrabbing rcu read lock.
987*1ba1199eSBaokun Li 		 */
988*1ba1199eSBaokun Li 		if (!wb_tryget(wb))
989*1ba1199eSBaokun Li 			continue;
990*1ba1199eSBaokun Li 
9918a1270cdSTejun Heo 		/* alloc failed, execute synchronously using on-stack fallback */
9928a1270cdSTejun Heo 		work = &fallback_work;
9938a1270cdSTejun Heo 		*work = *base_work;
9948a1270cdSTejun Heo 		work->nr_pages = nr_pages;
9958a1270cdSTejun Heo 		work->auto_free = 0;
9968a1270cdSTejun Heo 		work->done = &fallback_work_done;
9978a1270cdSTejun Heo 
9988a1270cdSTejun Heo 		wb_queue_work(wb, work);
999b817525aSTejun Heo 		last_wb = wb;
1000b817525aSTejun Heo 
1001db125360STejun Heo 		rcu_read_unlock();
10025b9cce4cSTejun Heo 		wb_wait_for_completion(&fallback_work_done);
1003db125360STejun Heo 		goto restart;
1004db125360STejun Heo 	}
1005db125360STejun Heo 	rcu_read_unlock();
1006b817525aSTejun Heo 
1007b817525aSTejun Heo 	if (last_wb)
1008b817525aSTejun Heo 		wb_put(last_wb);
1009db125360STejun Heo }
1010db125360STejun Heo 
1011a1a0e23eSTejun Heo /**
1012d62241c7STejun Heo  * cgroup_writeback_by_id - initiate cgroup writeback from bdi and memcg IDs
1013d62241c7STejun Heo  * @bdi_id: target bdi id
1014d62241c7STejun Heo  * @memcg_id: target memcg css id
1015d62241c7STejun Heo  * @reason: reason why some writeback work initiated
1016d62241c7STejun Heo  * @done: target wb_completion
1017d62241c7STejun Heo  *
1018d62241c7STejun Heo  * Initiate flush of the bdi_writeback identified by @bdi_id and @memcg_id
1019d62241c7STejun Heo  * with the specified parameters.
1020d62241c7STejun Heo  */
10217490a2d2SShakeel Butt int cgroup_writeback_by_id(u64 bdi_id, int memcg_id,
1022d62241c7STejun Heo 			   enum wb_reason reason, struct wb_completion *done)
1023d62241c7STejun Heo {
1024d62241c7STejun Heo 	struct backing_dev_info *bdi;
1025d62241c7STejun Heo 	struct cgroup_subsys_state *memcg_css;
1026d62241c7STejun Heo 	struct bdi_writeback *wb;
1027d62241c7STejun Heo 	struct wb_writeback_work *work;
10287490a2d2SShakeel Butt 	unsigned long dirty;
1029d62241c7STejun Heo 	int ret;
1030d62241c7STejun Heo 
1031d62241c7STejun Heo 	/* lookup bdi and memcg */
1032d62241c7STejun Heo 	bdi = bdi_get_by_id(bdi_id);
1033d62241c7STejun Heo 	if (!bdi)
1034d62241c7STejun Heo 		return -ENOENT;
1035d62241c7STejun Heo 
1036d62241c7STejun Heo 	rcu_read_lock();
1037d62241c7STejun Heo 	memcg_css = css_from_id(memcg_id, &memory_cgrp_subsys);
1038d62241c7STejun Heo 	if (memcg_css && !css_tryget(memcg_css))
1039d62241c7STejun Heo 		memcg_css = NULL;
1040d62241c7STejun Heo 	rcu_read_unlock();
1041d62241c7STejun Heo 	if (!memcg_css) {
1042d62241c7STejun Heo 		ret = -ENOENT;
1043d62241c7STejun Heo 		goto out_bdi_put;
1044d62241c7STejun Heo 	}
1045d62241c7STejun Heo 
1046d62241c7STejun Heo 	/*
1047d62241c7STejun Heo 	 * And find the associated wb.  If the wb isn't there already
1048d62241c7STejun Heo 	 * there's nothing to flush, don't create one.
1049d62241c7STejun Heo 	 */
1050d62241c7STejun Heo 	wb = wb_get_lookup(bdi, memcg_css);
1051d62241c7STejun Heo 	if (!wb) {
1052d62241c7STejun Heo 		ret = -ENOENT;
1053d62241c7STejun Heo 		goto out_css_put;
1054d62241c7STejun Heo 	}
1055d62241c7STejun Heo 
1056d62241c7STejun Heo 	/*
10577490a2d2SShakeel Butt 	 * The caller is attempting to write out most of
1058d62241c7STejun Heo 	 * the currently dirty pages.  Let's take the current dirty page
1059d62241c7STejun Heo 	 * count and inflate it by 25% which should be large enough to
1060d62241c7STejun Heo 	 * flush out most dirty pages while avoiding getting livelocked by
1061d62241c7STejun Heo 	 * concurrent dirtiers.
10627490a2d2SShakeel Butt 	 *
10637490a2d2SShakeel Butt 	 * BTW the memcg stats are flushed periodically and this is best-effort
10647490a2d2SShakeel Butt 	 * estimation, so some potential error is ok.
1065d62241c7STejun Heo 	 */
10667490a2d2SShakeel Butt 	dirty = memcg_page_state(mem_cgroup_from_css(memcg_css), NR_FILE_DIRTY);
10677490a2d2SShakeel Butt 	dirty = dirty * 10 / 8;
1068d62241c7STejun Heo 
1069d62241c7STejun Heo 	/* issue the writeback work */
1070d62241c7STejun Heo 	work = kzalloc(sizeof(*work), GFP_NOWAIT | __GFP_NOWARN);
1071d62241c7STejun Heo 	if (work) {
10727490a2d2SShakeel Butt 		work->nr_pages = dirty;
1073d62241c7STejun Heo 		work->sync_mode = WB_SYNC_NONE;
1074d62241c7STejun Heo 		work->range_cyclic = 1;
1075d62241c7STejun Heo 		work->reason = reason;
1076d62241c7STejun Heo 		work->done = done;
1077d62241c7STejun Heo 		work->auto_free = 1;
1078d62241c7STejun Heo 		wb_queue_work(wb, work);
1079d62241c7STejun Heo 		ret = 0;
1080d62241c7STejun Heo 	} else {
1081d62241c7STejun Heo 		ret = -ENOMEM;
1082d62241c7STejun Heo 	}
1083d62241c7STejun Heo 
1084d62241c7STejun Heo 	wb_put(wb);
1085d62241c7STejun Heo out_css_put:
1086d62241c7STejun Heo 	css_put(memcg_css);
1087d62241c7STejun Heo out_bdi_put:
1088d62241c7STejun Heo 	bdi_put(bdi);
1089d62241c7STejun Heo 	return ret;
1090d62241c7STejun Heo }
1091d62241c7STejun Heo 
1092d62241c7STejun Heo /**
1093a1a0e23eSTejun Heo  * cgroup_writeback_umount - flush inode wb switches for umount
1094a1a0e23eSTejun Heo  *
1095a1a0e23eSTejun Heo  * This function is called when a super_block is about to be destroyed and
1096a1a0e23eSTejun Heo  * flushes in-flight inode wb switches.  An inode wb switch goes through
1097a1a0e23eSTejun Heo  * RCU and then workqueue, so the two need to be flushed in order to ensure
1098a1a0e23eSTejun Heo  * that all previously scheduled switches are finished.  As wb switches are
1099a1a0e23eSTejun Heo  * rare occurrences and synchronize_rcu() can take a while, perform
1100a1a0e23eSTejun Heo  * flushing iff wb switches are in flight.
1101a1a0e23eSTejun Heo  */
1102a1a0e23eSTejun Heo void cgroup_writeback_umount(void)
1103a1a0e23eSTejun Heo {
1104592fa002SRoman Gushchin 	/*
1105592fa002SRoman Gushchin 	 * SB_ACTIVE should be reliably cleared before checking
1106592fa002SRoman Gushchin 	 * isw_nr_in_flight, see generic_shutdown_super().
1107592fa002SRoman Gushchin 	 */
1108592fa002SRoman Gushchin 	smp_mb();
1109592fa002SRoman Gushchin 
1110a1a0e23eSTejun Heo 	if (atomic_read(&isw_nr_in_flight)) {
1111ec084de9SJiufei Xue 		/*
1112ec084de9SJiufei Xue 		 * Use rcu_barrier() to wait for all pending callbacks to
1113ec084de9SJiufei Xue 		 * ensure that all in-flight wb switches are in the workqueue.
1114ec084de9SJiufei Xue 		 */
1115ec084de9SJiufei Xue 		rcu_barrier();
1116a1a0e23eSTejun Heo 		flush_workqueue(isw_wq);
1117a1a0e23eSTejun Heo 	}
1118a1a0e23eSTejun Heo }
1119a1a0e23eSTejun Heo 
1120a1a0e23eSTejun Heo static int __init cgroup_writeback_init(void)
1121a1a0e23eSTejun Heo {
1122a1a0e23eSTejun Heo 	isw_wq = alloc_workqueue("inode_switch_wbs", 0, 0);
1123a1a0e23eSTejun Heo 	if (!isw_wq)
1124a1a0e23eSTejun Heo 		return -ENOMEM;
1125a1a0e23eSTejun Heo 	return 0;
1126a1a0e23eSTejun Heo }
1127a1a0e23eSTejun Heo fs_initcall(cgroup_writeback_init);
1128a1a0e23eSTejun Heo 
1129f2b65121STejun Heo #else	/* CONFIG_CGROUP_WRITEBACK */
1130f2b65121STejun Heo 
11317fc5854fSTejun Heo static void bdi_down_write_wb_switch_rwsem(struct backing_dev_info *bdi) { }
11327fc5854fSTejun Heo static void bdi_up_write_wb_switch_rwsem(struct backing_dev_info *bdi) { }
11337fc5854fSTejun Heo 
1134f3b6a6dfSRoman Gushchin static void inode_cgwb_move_to_attached(struct inode *inode,
1135f3b6a6dfSRoman Gushchin 					struct bdi_writeback *wb)
1136f3b6a6dfSRoman Gushchin {
1137f3b6a6dfSRoman Gushchin 	assert_spin_locked(&wb->list_lock);
1138f3b6a6dfSRoman Gushchin 	assert_spin_locked(&inode->i_lock);
1139a9438b44SJan Kara 	WARN_ON_ONCE(inode->i_state & I_FREEING);
1140f3b6a6dfSRoman Gushchin 
1141f3b6a6dfSRoman Gushchin 	inode->i_state &= ~I_SYNC_QUEUED;
1142f3b6a6dfSRoman Gushchin 	list_del_init(&inode->i_io_list);
1143f3b6a6dfSRoman Gushchin 	wb_io_lists_depopulated(wb);
1144f3b6a6dfSRoman Gushchin }
1145f3b6a6dfSRoman Gushchin 
114687e1d789STejun Heo static struct bdi_writeback *
114787e1d789STejun Heo locked_inode_to_wb_and_lock_list(struct inode *inode)
114887e1d789STejun Heo 	__releases(&inode->i_lock)
114987e1d789STejun Heo 	__acquires(&wb->list_lock)
115087e1d789STejun Heo {
115187e1d789STejun Heo 	struct bdi_writeback *wb = inode_to_wb(inode);
115287e1d789STejun Heo 
115387e1d789STejun Heo 	spin_unlock(&inode->i_lock);
115487e1d789STejun Heo 	spin_lock(&wb->list_lock);
115587e1d789STejun Heo 	return wb;
115687e1d789STejun Heo }
115787e1d789STejun Heo 
115887e1d789STejun Heo static struct bdi_writeback *inode_to_wb_and_lock_list(struct inode *inode)
115987e1d789STejun Heo 	__acquires(&wb->list_lock)
116087e1d789STejun Heo {
116187e1d789STejun Heo 	struct bdi_writeback *wb = inode_to_wb(inode);
116287e1d789STejun Heo 
116387e1d789STejun Heo 	spin_lock(&wb->list_lock);
116487e1d789STejun Heo 	return wb;
116587e1d789STejun Heo }
116687e1d789STejun Heo 
1167f2b65121STejun Heo static long wb_split_bdi_pages(struct bdi_writeback *wb, long nr_pages)
1168f2b65121STejun Heo {
1169f2b65121STejun Heo 	return nr_pages;
1170f2b65121STejun Heo }
1171f2b65121STejun Heo 
1172db125360STejun Heo static void bdi_split_work_to_wbs(struct backing_dev_info *bdi,
1173db125360STejun Heo 				  struct wb_writeback_work *base_work,
1174db125360STejun Heo 				  bool skip_if_busy)
1175db125360STejun Heo {
1176db125360STejun Heo 	might_sleep();
1177db125360STejun Heo 
1178006a0973STejun Heo 	if (!skip_if_busy || !writeback_in_progress(&bdi->wb)) {
1179db125360STejun Heo 		base_work->auto_free = 0;
1180db125360STejun Heo 		wb_queue_work(&bdi->wb, base_work);
1181db125360STejun Heo 	}
1182db125360STejun Heo }
1183db125360STejun Heo 
1184703c2708STejun Heo #endif	/* CONFIG_CGROUP_WRITEBACK */
1185703c2708STejun Heo 
1186e8e8a0c6SJens Axboe /*
1187e8e8a0c6SJens Axboe  * Add in the number of potentially dirty inodes, because each inode
1188e8e8a0c6SJens Axboe  * write can dirty pagecache in the underlying blockdev.
1189e8e8a0c6SJens Axboe  */
1190e8e8a0c6SJens Axboe static unsigned long get_nr_dirty_pages(void)
1191e8e8a0c6SJens Axboe {
1192e8e8a0c6SJens Axboe 	return global_node_page_state(NR_FILE_DIRTY) +
1193e8e8a0c6SJens Axboe 		get_nr_dirty_inodes();
1194e8e8a0c6SJens Axboe }
1195e8e8a0c6SJens Axboe 
1196e8e8a0c6SJens Axboe static void wb_start_writeback(struct bdi_writeback *wb, enum wb_reason reason)
1197b6e51316SJens Axboe {
1198c00ddad3STejun Heo 	if (!wb_has_dirty_io(wb))
1199c00ddad3STejun Heo 		return;
1200c00ddad3STejun Heo 
1201c00ddad3STejun Heo 	/*
1202aac8d41cSJens Axboe 	 * All callers of this function want to start writeback of all
1203aac8d41cSJens Axboe 	 * dirty pages. Places like vmscan can call this at a very
1204aac8d41cSJens Axboe 	 * high frequency, causing pointless allocations of tons of
1205aac8d41cSJens Axboe 	 * work items and keeping the flusher threads busy retrieving
1206aac8d41cSJens Axboe 	 * that work. Ensure that we only allow one of them pending and
120785009b4fSJens Axboe 	 * inflight at the time.
1208aac8d41cSJens Axboe 	 */
120985009b4fSJens Axboe 	if (test_bit(WB_start_all, &wb->state) ||
121085009b4fSJens Axboe 	    test_and_set_bit(WB_start_all, &wb->state))
1211aac8d41cSJens Axboe 		return;
1212aac8d41cSJens Axboe 
121385009b4fSJens Axboe 	wb->start_all_reason = reason;
1214c00ddad3STejun Heo 	wb_wakeup(wb);
1215d3ddec76SWu Fengguang }
1216d3ddec76SWu Fengguang 
1217c5444198SChristoph Hellwig /**
12189ecf4866STejun Heo  * wb_start_background_writeback - start background writeback
12199ecf4866STejun Heo  * @wb: bdi_writback to write from
1220c5444198SChristoph Hellwig  *
1221c5444198SChristoph Hellwig  * Description:
12226585027aSJan Kara  *   This makes sure WB_SYNC_NONE background writeback happens. When
12239ecf4866STejun Heo  *   this function returns, it is only guaranteed that for given wb
12246585027aSJan Kara  *   some IO is happening if we are over background dirty threshold.
12256585027aSJan Kara  *   Caller need not hold sb s_umount semaphore.
1226c5444198SChristoph Hellwig  */
12279ecf4866STejun Heo void wb_start_background_writeback(struct bdi_writeback *wb)
1228c5444198SChristoph Hellwig {
12296585027aSJan Kara 	/*
12306585027aSJan Kara 	 * We just wake up the flusher thread. It will perform background
12316585027aSJan Kara 	 * writeback as soon as there is no other work to do.
12326585027aSJan Kara 	 */
12335634cc2aSTejun Heo 	trace_writeback_wake_background(wb);
12349ecf4866STejun Heo 	wb_wakeup(wb);
12351da177e4SLinus Torvalds }
12361da177e4SLinus Torvalds 
12371da177e4SLinus Torvalds /*
1238a66979abSDave Chinner  * Remove the inode from the writeback list it is on.
1239a66979abSDave Chinner  */
1240c7f54084SDave Chinner void inode_io_list_del(struct inode *inode)
1241a66979abSDave Chinner {
124287e1d789STejun Heo 	struct bdi_writeback *wb;
1243a66979abSDave Chinner 
124487e1d789STejun Heo 	wb = inode_to_wb_and_lock_list(inode);
1245b35250c0SJan Kara 	spin_lock(&inode->i_lock);
1246f3b6a6dfSRoman Gushchin 
1247f3b6a6dfSRoman Gushchin 	inode->i_state &= ~I_SYNC_QUEUED;
1248f3b6a6dfSRoman Gushchin 	list_del_init(&inode->i_io_list);
1249f3b6a6dfSRoman Gushchin 	wb_io_lists_depopulated(wb);
1250f3b6a6dfSRoman Gushchin 
1251b35250c0SJan Kara 	spin_unlock(&inode->i_lock);
125252ebea74STejun Heo 	spin_unlock(&wb->list_lock);
1253f758eeabSChristoph Hellwig }
12544301efa4SJan Kara EXPORT_SYMBOL(inode_io_list_del);
1255a66979abSDave Chinner 
1256a66979abSDave Chinner /*
12576c60d2b5SDave Chinner  * mark an inode as under writeback on the sb
12586c60d2b5SDave Chinner  */
12596c60d2b5SDave Chinner void sb_mark_inode_writeback(struct inode *inode)
12606c60d2b5SDave Chinner {
12616c60d2b5SDave Chinner 	struct super_block *sb = inode->i_sb;
12626c60d2b5SDave Chinner 	unsigned long flags;
12636c60d2b5SDave Chinner 
12646c60d2b5SDave Chinner 	if (list_empty(&inode->i_wb_list)) {
12656c60d2b5SDave Chinner 		spin_lock_irqsave(&sb->s_inode_wblist_lock, flags);
12669a46b04fSBrian Foster 		if (list_empty(&inode->i_wb_list)) {
12676c60d2b5SDave Chinner 			list_add_tail(&inode->i_wb_list, &sb->s_inodes_wb);
12689a46b04fSBrian Foster 			trace_sb_mark_inode_writeback(inode);
12699a46b04fSBrian Foster 		}
12706c60d2b5SDave Chinner 		spin_unlock_irqrestore(&sb->s_inode_wblist_lock, flags);
12716c60d2b5SDave Chinner 	}
12726c60d2b5SDave Chinner }
12736c60d2b5SDave Chinner 
12746c60d2b5SDave Chinner /*
12756c60d2b5SDave Chinner  * clear an inode as under writeback on the sb
12766c60d2b5SDave Chinner  */
12776c60d2b5SDave Chinner void sb_clear_inode_writeback(struct inode *inode)
12786c60d2b5SDave Chinner {
12796c60d2b5SDave Chinner 	struct super_block *sb = inode->i_sb;
12806c60d2b5SDave Chinner 	unsigned long flags;
12816c60d2b5SDave Chinner 
12826c60d2b5SDave Chinner 	if (!list_empty(&inode->i_wb_list)) {
12836c60d2b5SDave Chinner 		spin_lock_irqsave(&sb->s_inode_wblist_lock, flags);
12849a46b04fSBrian Foster 		if (!list_empty(&inode->i_wb_list)) {
12856c60d2b5SDave Chinner 			list_del_init(&inode->i_wb_list);
12869a46b04fSBrian Foster 			trace_sb_clear_inode_writeback(inode);
12879a46b04fSBrian Foster 		}
12886c60d2b5SDave Chinner 		spin_unlock_irqrestore(&sb->s_inode_wblist_lock, flags);
12896c60d2b5SDave Chinner 	}
12906c60d2b5SDave Chinner }
12916c60d2b5SDave Chinner 
12926c60d2b5SDave Chinner /*
12936610a0bcSAndrew Morton  * Redirty an inode: set its when-it-was dirtied timestamp and move it to the
12946610a0bcSAndrew Morton  * furthest end of its superblock's dirty-inode list.
12956610a0bcSAndrew Morton  *
12966610a0bcSAndrew Morton  * Before stamping the inode's ->dirtied_when, we check to see whether it is
129766f3b8e2SJens Axboe  * already the most-recently-dirtied inode on the b_dirty list.  If that is
12986610a0bcSAndrew Morton  * the case then the inode must have been redirtied while it was being written
12996610a0bcSAndrew Morton  * out and we don't reset its dirtied_when.
13006610a0bcSAndrew Morton  */
1301b35250c0SJan Kara static void redirty_tail_locked(struct inode *inode, struct bdi_writeback *wb)
13026610a0bcSAndrew Morton {
1303b35250c0SJan Kara 	assert_spin_locked(&inode->i_lock);
1304b35250c0SJan Kara 
1305a9438b44SJan Kara 	inode->i_state &= ~I_SYNC_QUEUED;
1306a9438b44SJan Kara 	/*
1307a9438b44SJan Kara 	 * When the inode is being freed just don't bother with dirty list
1308a9438b44SJan Kara 	 * tracking. Flush worker will ignore this inode anyway and it will
1309a9438b44SJan Kara 	 * trigger assertions in inode_io_list_move_locked().
1310a9438b44SJan Kara 	 */
1311a9438b44SJan Kara 	if (inode->i_state & I_FREEING) {
1312a9438b44SJan Kara 		list_del_init(&inode->i_io_list);
1313a9438b44SJan Kara 		wb_io_lists_depopulated(wb);
1314a9438b44SJan Kara 		return;
1315a9438b44SJan Kara 	}
131603ba3782SJens Axboe 	if (!list_empty(&wb->b_dirty)) {
131766f3b8e2SJens Axboe 		struct inode *tail;
13186610a0bcSAndrew Morton 
13197ccf19a8SNick Piggin 		tail = wb_inode(wb->b_dirty.next);
132066f3b8e2SJens Axboe 		if (time_before(inode->dirtied_when, tail->dirtied_when))
13216610a0bcSAndrew Morton 			inode->dirtied_when = jiffies;
13226610a0bcSAndrew Morton 	}
1323c7f54084SDave Chinner 	inode_io_list_move_locked(inode, wb, &wb->b_dirty);
13246610a0bcSAndrew Morton }
13256610a0bcSAndrew Morton 
1326b35250c0SJan Kara static void redirty_tail(struct inode *inode, struct bdi_writeback *wb)
1327b35250c0SJan Kara {
1328b35250c0SJan Kara 	spin_lock(&inode->i_lock);
1329b35250c0SJan Kara 	redirty_tail_locked(inode, wb);
1330b35250c0SJan Kara 	spin_unlock(&inode->i_lock);
1331b35250c0SJan Kara }
1332b35250c0SJan Kara 
13336610a0bcSAndrew Morton /*
133466f3b8e2SJens Axboe  * requeue inode for re-scanning after bdi->b_io list is exhausted.
1335c986d1e2SAndrew Morton  */
1336f758eeabSChristoph Hellwig static void requeue_io(struct inode *inode, struct bdi_writeback *wb)
1337c986d1e2SAndrew Morton {
1338c7f54084SDave Chinner 	inode_io_list_move_locked(inode, wb, &wb->b_more_io);
1339c986d1e2SAndrew Morton }
1340c986d1e2SAndrew Morton 
13411c0eeaf5SJoern Engel static void inode_sync_complete(struct inode *inode)
13421c0eeaf5SJoern Engel {
1343365b94aeSJan Kara 	inode->i_state &= ~I_SYNC;
13444eff96ddSJan Kara 	/* If inode is clean an unused, put it into LRU now... */
13454eff96ddSJan Kara 	inode_add_lru(inode);
1346365b94aeSJan Kara 	/* Waiters must see I_SYNC cleared before being woken up */
13471c0eeaf5SJoern Engel 	smp_mb();
13481c0eeaf5SJoern Engel 	wake_up_bit(&inode->i_state, __I_SYNC);
13491c0eeaf5SJoern Engel }
13501c0eeaf5SJoern Engel 
1351d2caa3c5SJeff Layton static bool inode_dirtied_after(struct inode *inode, unsigned long t)
1352d2caa3c5SJeff Layton {
1353d2caa3c5SJeff Layton 	bool ret = time_after(inode->dirtied_when, t);
1354d2caa3c5SJeff Layton #ifndef CONFIG_64BIT
1355d2caa3c5SJeff Layton 	/*
1356d2caa3c5SJeff Layton 	 * For inodes being constantly redirtied, dirtied_when can get stuck.
1357d2caa3c5SJeff Layton 	 * It _appears_ to be in the future, but is actually in distant past.
1358d2caa3c5SJeff Layton 	 * This test is necessary to prevent such wrapped-around relative times
13595b0830cbSJens Axboe 	 * from permanently stopping the whole bdi writeback.
1360d2caa3c5SJeff Layton 	 */
1361d2caa3c5SJeff Layton 	ret = ret && time_before_eq(inode->dirtied_when, jiffies);
1362d2caa3c5SJeff Layton #endif
1363d2caa3c5SJeff Layton 	return ret;
1364d2caa3c5SJeff Layton }
1365d2caa3c5SJeff Layton 
1366c986d1e2SAndrew Morton /*
1367f9cae926SJan Kara  * Move expired (dirtied before dirtied_before) dirty inodes from
1368697e6fedSJan Kara  * @delaying_queue to @dispatch_queue.
13692c136579SFengguang Wu  */
1370e84d0a4fSWu Fengguang static int move_expired_inodes(struct list_head *delaying_queue,
13712c136579SFengguang Wu 			       struct list_head *dispatch_queue,
13725fcd5750SJan Kara 			       unsigned long dirtied_before)
13732c136579SFengguang Wu {
13745c03449dSShaohua Li 	LIST_HEAD(tmp);
13755c03449dSShaohua Li 	struct list_head *pos, *node;
1376cf137307SJens Axboe 	struct super_block *sb = NULL;
13775c03449dSShaohua Li 	struct inode *inode;
1378cf137307SJens Axboe 	int do_sb_sort = 0;
1379e84d0a4fSWu Fengguang 	int moved = 0;
13805c03449dSShaohua Li 
13812c136579SFengguang Wu 	while (!list_empty(delaying_queue)) {
13827ccf19a8SNick Piggin 		inode = wb_inode(delaying_queue->prev);
1383f9cae926SJan Kara 		if (inode_dirtied_after(inode, dirtied_before))
13842c136579SFengguang Wu 			break;
138510e14073SJchao Sun 		spin_lock(&inode->i_lock);
1386c7f54084SDave Chinner 		list_move(&inode->i_io_list, &tmp);
1387a8855990SJan Kara 		moved++;
13885afced3bSJan Kara 		inode->i_state |= I_SYNC_QUEUED;
13895afced3bSJan Kara 		spin_unlock(&inode->i_lock);
1390a8855990SJan Kara 		if (sb_is_blkdev_sb(inode->i_sb))
1391a8855990SJan Kara 			continue;
1392cf137307SJens Axboe 		if (sb && sb != inode->i_sb)
1393cf137307SJens Axboe 			do_sb_sort = 1;
1394cf137307SJens Axboe 		sb = inode->i_sb;
13955c03449dSShaohua Li 	}
13965c03449dSShaohua Li 
1397cf137307SJens Axboe 	/* just one sb in list, splice to dispatch_queue and we're done */
1398cf137307SJens Axboe 	if (!do_sb_sort) {
1399cf137307SJens Axboe 		list_splice(&tmp, dispatch_queue);
1400e84d0a4fSWu Fengguang 		goto out;
1401cf137307SJens Axboe 	}
1402cf137307SJens Axboe 
140310e14073SJchao Sun 	/*
140410e14073SJchao Sun 	 * Although inode's i_io_list is moved from 'tmp' to 'dispatch_queue',
140510e14073SJchao Sun 	 * we don't take inode->i_lock here because it is just a pointless overhead.
140610e14073SJchao Sun 	 * Inode is already marked as I_SYNC_QUEUED so writeback list handling is
140710e14073SJchao Sun 	 * fully under our control.
140810e14073SJchao Sun 	 */
14095c03449dSShaohua Li 	while (!list_empty(&tmp)) {
14107ccf19a8SNick Piggin 		sb = wb_inode(tmp.prev)->i_sb;
14115c03449dSShaohua Li 		list_for_each_prev_safe(pos, node, &tmp) {
14127ccf19a8SNick Piggin 			inode = wb_inode(pos);
14135c03449dSShaohua Li 			if (inode->i_sb == sb)
1414c7f54084SDave Chinner 				list_move(&inode->i_io_list, dispatch_queue);
14152c136579SFengguang Wu 		}
14162c136579SFengguang Wu 	}
1417e84d0a4fSWu Fengguang out:
1418e84d0a4fSWu Fengguang 	return moved;
14195c03449dSShaohua Li }
14202c136579SFengguang Wu 
14212c136579SFengguang Wu /*
14222c136579SFengguang Wu  * Queue all expired dirty inodes for io, eldest first.
14234ea879b9SWu Fengguang  * Before
14244ea879b9SWu Fengguang  *         newly dirtied     b_dirty    b_io    b_more_io
14254ea879b9SWu Fengguang  *         =============>    gf         edc     BA
14264ea879b9SWu Fengguang  * After
14274ea879b9SWu Fengguang  *         newly dirtied     b_dirty    b_io    b_more_io
14284ea879b9SWu Fengguang  *         =============>    g          fBAedc
14294ea879b9SWu Fengguang  *                                           |
14304ea879b9SWu Fengguang  *                                           +--> dequeue for IO
14312c136579SFengguang Wu  */
1432f9cae926SJan Kara static void queue_io(struct bdi_writeback *wb, struct wb_writeback_work *work,
1433f9cae926SJan Kara 		     unsigned long dirtied_before)
14342c136579SFengguang Wu {
1435e84d0a4fSWu Fengguang 	int moved;
1436f9cae926SJan Kara 	unsigned long time_expire_jif = dirtied_before;
14370ae45f63STheodore Ts'o 
1438f758eeabSChristoph Hellwig 	assert_spin_locked(&wb->list_lock);
14394ea879b9SWu Fengguang 	list_splice_init(&wb->b_more_io, &wb->b_io);
14405fcd5750SJan Kara 	moved = move_expired_inodes(&wb->b_dirty, &wb->b_io, dirtied_before);
1441f9cae926SJan Kara 	if (!work->for_sync)
1442f9cae926SJan Kara 		time_expire_jif = jiffies - dirtytime_expire_interval * HZ;
14430ae45f63STheodore Ts'o 	moved += move_expired_inodes(&wb->b_dirty_time, &wb->b_io,
14445fcd5750SJan Kara 				     time_expire_jif);
1445d6c10f1fSTejun Heo 	if (moved)
1446d6c10f1fSTejun Heo 		wb_io_lists_populated(wb);
1447f9cae926SJan Kara 	trace_writeback_queue_io(wb, work, dirtied_before, moved);
144866f3b8e2SJens Axboe }
144966f3b8e2SJens Axboe 
1450a9185b41SChristoph Hellwig static int write_inode(struct inode *inode, struct writeback_control *wbc)
145166f3b8e2SJens Axboe {
14529fb0a7daSTejun Heo 	int ret;
14539fb0a7daSTejun Heo 
14549fb0a7daSTejun Heo 	if (inode->i_sb->s_op->write_inode && !is_bad_inode(inode)) {
14559fb0a7daSTejun Heo 		trace_writeback_write_inode_start(inode, wbc);
14569fb0a7daSTejun Heo 		ret = inode->i_sb->s_op->write_inode(inode, wbc);
14579fb0a7daSTejun Heo 		trace_writeback_write_inode(inode, wbc);
14589fb0a7daSTejun Heo 		return ret;
14599fb0a7daSTejun Heo 	}
146003ba3782SJens Axboe 	return 0;
146166f3b8e2SJens Axboe }
146208d8e974SFengguang Wu 
14632c136579SFengguang Wu /*
1464169ebd90SJan Kara  * Wait for writeback on an inode to complete. Called with i_lock held.
1465169ebd90SJan Kara  * Caller must make sure inode cannot go away when we drop i_lock.
146601c03194SChristoph Hellwig  */
1467169ebd90SJan Kara static void __inode_wait_for_writeback(struct inode *inode)
1468169ebd90SJan Kara 	__releases(inode->i_lock)
1469169ebd90SJan Kara 	__acquires(inode->i_lock)
147001c03194SChristoph Hellwig {
147101c03194SChristoph Hellwig 	DEFINE_WAIT_BIT(wq, &inode->i_state, __I_SYNC);
147201c03194SChristoph Hellwig 	wait_queue_head_t *wqh;
147301c03194SChristoph Hellwig 
147401c03194SChristoph Hellwig 	wqh = bit_waitqueue(&inode->i_state, __I_SYNC);
147558a9d3d8SRichard Kennedy 	while (inode->i_state & I_SYNC) {
1476250df6edSDave Chinner 		spin_unlock(&inode->i_lock);
147774316201SNeilBrown 		__wait_on_bit(wqh, &wq, bit_wait,
147874316201SNeilBrown 			      TASK_UNINTERRUPTIBLE);
1479250df6edSDave Chinner 		spin_lock(&inode->i_lock);
148058a9d3d8SRichard Kennedy 	}
148101c03194SChristoph Hellwig }
148201c03194SChristoph Hellwig 
148301c03194SChristoph Hellwig /*
1484169ebd90SJan Kara  * Wait for writeback on an inode to complete. Caller must have inode pinned.
1485169ebd90SJan Kara  */
1486169ebd90SJan Kara void inode_wait_for_writeback(struct inode *inode)
1487169ebd90SJan Kara {
1488169ebd90SJan Kara 	spin_lock(&inode->i_lock);
1489169ebd90SJan Kara 	__inode_wait_for_writeback(inode);
1490169ebd90SJan Kara 	spin_unlock(&inode->i_lock);
1491169ebd90SJan Kara }
1492169ebd90SJan Kara 
1493169ebd90SJan Kara /*
1494169ebd90SJan Kara  * Sleep until I_SYNC is cleared. This function must be called with i_lock
1495169ebd90SJan Kara  * held and drops it. It is aimed for callers not holding any inode reference
1496169ebd90SJan Kara  * so once i_lock is dropped, inode can go away.
1497169ebd90SJan Kara  */
1498169ebd90SJan Kara static void inode_sleep_on_writeback(struct inode *inode)
1499169ebd90SJan Kara 	__releases(inode->i_lock)
1500169ebd90SJan Kara {
1501169ebd90SJan Kara 	DEFINE_WAIT(wait);
1502169ebd90SJan Kara 	wait_queue_head_t *wqh = bit_waitqueue(&inode->i_state, __I_SYNC);
1503169ebd90SJan Kara 	int sleep;
1504169ebd90SJan Kara 
1505169ebd90SJan Kara 	prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1506169ebd90SJan Kara 	sleep = inode->i_state & I_SYNC;
1507169ebd90SJan Kara 	spin_unlock(&inode->i_lock);
1508169ebd90SJan Kara 	if (sleep)
1509169ebd90SJan Kara 		schedule();
1510169ebd90SJan Kara 	finish_wait(wqh, &wait);
1511169ebd90SJan Kara }
1512169ebd90SJan Kara 
1513169ebd90SJan Kara /*
1514ccb26b5aSJan Kara  * Find proper writeback list for the inode depending on its current state and
1515ccb26b5aSJan Kara  * possibly also change of its state while we were doing writeback.  Here we
1516ccb26b5aSJan Kara  * handle things such as livelock prevention or fairness of writeback among
1517ccb26b5aSJan Kara  * inodes. This function can be called only by flusher thread - noone else
1518ccb26b5aSJan Kara  * processes all inodes in writeback lists and requeueing inodes behind flusher
1519ccb26b5aSJan Kara  * thread's back can have unexpected consequences.
1520ccb26b5aSJan Kara  */
1521ccb26b5aSJan Kara static void requeue_inode(struct inode *inode, struct bdi_writeback *wb,
1522ccb26b5aSJan Kara 			  struct writeback_control *wbc)
1523ccb26b5aSJan Kara {
1524ccb26b5aSJan Kara 	if (inode->i_state & I_FREEING)
1525ccb26b5aSJan Kara 		return;
1526ccb26b5aSJan Kara 
1527ccb26b5aSJan Kara 	/*
1528ccb26b5aSJan Kara 	 * Sync livelock prevention. Each inode is tagged and synced in one
1529ccb26b5aSJan Kara 	 * shot. If still dirty, it will be redirty_tail()'ed below.  Update
1530ccb26b5aSJan Kara 	 * the dirty time to prevent enqueue and sync it again.
1531ccb26b5aSJan Kara 	 */
1532ccb26b5aSJan Kara 	if ((inode->i_state & I_DIRTY) &&
1533ccb26b5aSJan Kara 	    (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages))
1534ccb26b5aSJan Kara 		inode->dirtied_when = jiffies;
1535ccb26b5aSJan Kara 
15364f8ad655SJan Kara 	if (wbc->pages_skipped) {
15374f8ad655SJan Kara 		/*
15384f8ad655SJan Kara 		 * writeback is not making progress due to locked
15394f8ad655SJan Kara 		 * buffers. Skip this inode for now.
15404f8ad655SJan Kara 		 */
1541b35250c0SJan Kara 		redirty_tail_locked(inode, wb);
15424f8ad655SJan Kara 		return;
15434f8ad655SJan Kara 	}
15444f8ad655SJan Kara 
1545ccb26b5aSJan Kara 	if (mapping_tagged(inode->i_mapping, PAGECACHE_TAG_DIRTY)) {
1546ccb26b5aSJan Kara 		/*
1547ccb26b5aSJan Kara 		 * We didn't write back all the pages.  nfs_writepages()
1548ccb26b5aSJan Kara 		 * sometimes bales out without doing anything.
1549ccb26b5aSJan Kara 		 */
1550ccb26b5aSJan Kara 		if (wbc->nr_to_write <= 0) {
1551ccb26b5aSJan Kara 			/* Slice used up. Queue for next turn. */
1552ccb26b5aSJan Kara 			requeue_io(inode, wb);
1553ccb26b5aSJan Kara 		} else {
1554ccb26b5aSJan Kara 			/*
1555ccb26b5aSJan Kara 			 * Writeback blocked by something other than
1556ccb26b5aSJan Kara 			 * congestion. Delay the inode for some time to
1557ccb26b5aSJan Kara 			 * avoid spinning on the CPU (100% iowait)
1558ccb26b5aSJan Kara 			 * retrying writeback of the dirty page/inode
1559ccb26b5aSJan Kara 			 * that cannot be performed immediately.
1560ccb26b5aSJan Kara 			 */
1561b35250c0SJan Kara 			redirty_tail_locked(inode, wb);
1562ccb26b5aSJan Kara 		}
1563ccb26b5aSJan Kara 	} else if (inode->i_state & I_DIRTY) {
1564ccb26b5aSJan Kara 		/*
1565ccb26b5aSJan Kara 		 * Filesystems can dirty the inode during writeback operations,
1566ccb26b5aSJan Kara 		 * such as delayed allocation during submission or metadata
1567ccb26b5aSJan Kara 		 * updates after data IO completion.
1568ccb26b5aSJan Kara 		 */
1569b35250c0SJan Kara 		redirty_tail_locked(inode, wb);
15700ae45f63STheodore Ts'o 	} else if (inode->i_state & I_DIRTY_TIME) {
1571a2f48706STheodore Ts'o 		inode->dirtied_when = jiffies;
1572c7f54084SDave Chinner 		inode_io_list_move_locked(inode, wb, &wb->b_dirty_time);
15735afced3bSJan Kara 		inode->i_state &= ~I_SYNC_QUEUED;
1574ccb26b5aSJan Kara 	} else {
1575ccb26b5aSJan Kara 		/* The inode is clean. Remove from writeback lists. */
1576f3b6a6dfSRoman Gushchin 		inode_cgwb_move_to_attached(inode, wb);
1577ccb26b5aSJan Kara 	}
1578ccb26b5aSJan Kara }
1579ccb26b5aSJan Kara 
1580ccb26b5aSJan Kara /*
1581da0c4c60SEric Biggers  * Write out an inode and its dirty pages (or some of its dirty pages, depending
1582da0c4c60SEric Biggers  * on @wbc->nr_to_write), and clear the relevant dirty flags from i_state.
1583da0c4c60SEric Biggers  *
1584da0c4c60SEric Biggers  * This doesn't remove the inode from the writeback list it is on, except
1585da0c4c60SEric Biggers  * potentially to move it from b_dirty_time to b_dirty due to timestamp
1586da0c4c60SEric Biggers  * expiration.  The caller is otherwise responsible for writeback list handling.
1587da0c4c60SEric Biggers  *
1588da0c4c60SEric Biggers  * The caller is also responsible for setting the I_SYNC flag beforehand and
1589da0c4c60SEric Biggers  * calling inode_sync_complete() to clear it afterwards.
15901da177e4SLinus Torvalds  */
15911da177e4SLinus Torvalds static int
1592cd8ed2a4SYan Hong __writeback_single_inode(struct inode *inode, struct writeback_control *wbc)
15931da177e4SLinus Torvalds {
15941da177e4SLinus Torvalds 	struct address_space *mapping = inode->i_mapping;
1595251d6a47SWu Fengguang 	long nr_to_write = wbc->nr_to_write;
159601c03194SChristoph Hellwig 	unsigned dirty;
15971da177e4SLinus Torvalds 	int ret;
15981da177e4SLinus Torvalds 
15994f8ad655SJan Kara 	WARN_ON(!(inode->i_state & I_SYNC));
16001da177e4SLinus Torvalds 
16019fb0a7daSTejun Heo 	trace_writeback_single_inode_start(inode, wbc, nr_to_write);
16029fb0a7daSTejun Heo 
16031da177e4SLinus Torvalds 	ret = do_writepages(mapping, wbc);
16041da177e4SLinus Torvalds 
160526821ed4SChristoph Hellwig 	/*
160626821ed4SChristoph Hellwig 	 * Make sure to wait on the data before writing out the metadata.
160726821ed4SChristoph Hellwig 	 * This is important for filesystems that modify metadata on data
16087747bd4bSDave Chinner 	 * I/O completion. We don't do it for sync(2) writeback because it has a
16097747bd4bSDave Chinner 	 * separate, external IO completion path and ->sync_fs for guaranteeing
16107747bd4bSDave Chinner 	 * inode metadata is written back correctly.
161126821ed4SChristoph Hellwig 	 */
16127747bd4bSDave Chinner 	if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync) {
161326821ed4SChristoph Hellwig 		int err = filemap_fdatawait(mapping);
16141da177e4SLinus Torvalds 		if (ret == 0)
16151da177e4SLinus Torvalds 			ret = err;
16161da177e4SLinus Torvalds 	}
16171da177e4SLinus Torvalds 
16185547e8aaSDmitry Monakhov 	/*
16191e249cb5SEric Biggers 	 * If the inode has dirty timestamps and we need to write them, call
16201e249cb5SEric Biggers 	 * mark_inode_dirty_sync() to notify the filesystem about it and to
16211e249cb5SEric Biggers 	 * change I_DIRTY_TIME into I_DIRTY_SYNC.
16221e249cb5SEric Biggers 	 */
16231e249cb5SEric Biggers 	if ((inode->i_state & I_DIRTY_TIME) &&
162483dc881dSEric Biggers 	    (wbc->sync_mode == WB_SYNC_ALL ||
16251e249cb5SEric Biggers 	     time_after(jiffies, inode->dirtied_time_when +
16261e249cb5SEric Biggers 			dirtytime_expire_interval * HZ))) {
16271e249cb5SEric Biggers 		trace_writeback_lazytime(inode);
16281e249cb5SEric Biggers 		mark_inode_dirty_sync(inode);
16291e249cb5SEric Biggers 	}
16301e249cb5SEric Biggers 
16311e249cb5SEric Biggers 	/*
1632da0c4c60SEric Biggers 	 * Get and clear the dirty flags from i_state.  This needs to be done
1633da0c4c60SEric Biggers 	 * after calling writepages because some filesystems may redirty the
1634da0c4c60SEric Biggers 	 * inode during writepages due to delalloc.  It also needs to be done
1635da0c4c60SEric Biggers 	 * after handling timestamp expiration, as that may dirty the inode too.
16365547e8aaSDmitry Monakhov 	 */
1637250df6edSDave Chinner 	spin_lock(&inode->i_lock);
16385547e8aaSDmitry Monakhov 	dirty = inode->i_state & I_DIRTY;
16390ae45f63STheodore Ts'o 	inode->i_state &= ~dirty;
16409c6ac78eSTejun Heo 
16419c6ac78eSTejun Heo 	/*
16429c6ac78eSTejun Heo 	 * Paired with smp_mb() in __mark_inode_dirty().  This allows
16439c6ac78eSTejun Heo 	 * __mark_inode_dirty() to test i_state without grabbing i_lock -
16449c6ac78eSTejun Heo 	 * either they see the I_DIRTY bits cleared or we see the dirtied
16459c6ac78eSTejun Heo 	 * inode.
16469c6ac78eSTejun Heo 	 *
16479c6ac78eSTejun Heo 	 * I_DIRTY_PAGES is always cleared together above even if @mapping
16489c6ac78eSTejun Heo 	 * still has dirty pages.  The flag is reinstated after smp_mb() if
16499c6ac78eSTejun Heo 	 * necessary.  This guarantees that either __mark_inode_dirty()
16509c6ac78eSTejun Heo 	 * sees clear I_DIRTY_PAGES or we see PAGECACHE_TAG_DIRTY.
16519c6ac78eSTejun Heo 	 */
16529c6ac78eSTejun Heo 	smp_mb();
16539c6ac78eSTejun Heo 
16549c6ac78eSTejun Heo 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
16559c6ac78eSTejun Heo 		inode->i_state |= I_DIRTY_PAGES;
165608276bdaSDavid Howells 	else if (unlikely(inode->i_state & I_PINNING_FSCACHE_WB)) {
165708276bdaSDavid Howells 		if (!(inode->i_state & I_DIRTY_PAGES)) {
165808276bdaSDavid Howells 			inode->i_state &= ~I_PINNING_FSCACHE_WB;
165908276bdaSDavid Howells 			wbc->unpinned_fscache_wb = true;
166008276bdaSDavid Howells 			dirty |= I_PINNING_FSCACHE_WB; /* Cause write_inode */
166108276bdaSDavid Howells 		}
166208276bdaSDavid Howells 	}
16639c6ac78eSTejun Heo 
1664250df6edSDave Chinner 	spin_unlock(&inode->i_lock);
16659c6ac78eSTejun Heo 
166626821ed4SChristoph Hellwig 	/* Don't write the inode if only I_DIRTY_PAGES was set */
16670ae45f63STheodore Ts'o 	if (dirty & ~I_DIRTY_PAGES) {
1668a9185b41SChristoph Hellwig 		int err = write_inode(inode, wbc);
16691da177e4SLinus Torvalds 		if (ret == 0)
16701da177e4SLinus Torvalds 			ret = err;
16711da177e4SLinus Torvalds 	}
167208276bdaSDavid Howells 	wbc->unpinned_fscache_wb = false;
16734f8ad655SJan Kara 	trace_writeback_single_inode(inode, wbc, nr_to_write);
16744f8ad655SJan Kara 	return ret;
16754f8ad655SJan Kara }
16764f8ad655SJan Kara 
16774f8ad655SJan Kara /*
1678da0c4c60SEric Biggers  * Write out an inode's dirty data and metadata on-demand, i.e. separately from
1679da0c4c60SEric Biggers  * the regular batched writeback done by the flusher threads in
1680da0c4c60SEric Biggers  * writeback_sb_inodes().  @wbc controls various aspects of the write, such as
1681da0c4c60SEric Biggers  * whether it is a data-integrity sync (%WB_SYNC_ALL) or not (%WB_SYNC_NONE).
16824f8ad655SJan Kara  *
1683da0c4c60SEric Biggers  * To prevent the inode from going away, either the caller must have a reference
1684da0c4c60SEric Biggers  * to the inode, or the inode must have I_WILL_FREE or I_FREEING set.
16854f8ad655SJan Kara  */
1686aaf25593STejun Heo static int writeback_single_inode(struct inode *inode,
16874f8ad655SJan Kara 				  struct writeback_control *wbc)
16884f8ad655SJan Kara {
1689aaf25593STejun Heo 	struct bdi_writeback *wb;
16904f8ad655SJan Kara 	int ret = 0;
16914f8ad655SJan Kara 
16924f8ad655SJan Kara 	spin_lock(&inode->i_lock);
16934f8ad655SJan Kara 	if (!atomic_read(&inode->i_count))
16944f8ad655SJan Kara 		WARN_ON(!(inode->i_state & (I_WILL_FREE|I_FREEING)));
16954f8ad655SJan Kara 	else
16964f8ad655SJan Kara 		WARN_ON(inode->i_state & I_WILL_FREE);
16974f8ad655SJan Kara 
16984f8ad655SJan Kara 	if (inode->i_state & I_SYNC) {
1699da0c4c60SEric Biggers 		/*
1700da0c4c60SEric Biggers 		 * Writeback is already running on the inode.  For WB_SYNC_NONE,
1701da0c4c60SEric Biggers 		 * that's enough and we can just return.  For WB_SYNC_ALL, we
1702da0c4c60SEric Biggers 		 * must wait for the existing writeback to complete, then do
1703da0c4c60SEric Biggers 		 * writeback again if there's anything left.
1704da0c4c60SEric Biggers 		 */
17054f8ad655SJan Kara 		if (wbc->sync_mode != WB_SYNC_ALL)
17064f8ad655SJan Kara 			goto out;
1707169ebd90SJan Kara 		__inode_wait_for_writeback(inode);
17084f8ad655SJan Kara 	}
17094f8ad655SJan Kara 	WARN_ON(inode->i_state & I_SYNC);
17104f8ad655SJan Kara 	/*
1711da0c4c60SEric Biggers 	 * If the inode is already fully clean, then there's nothing to do.
1712da0c4c60SEric Biggers 	 *
1713da0c4c60SEric Biggers 	 * For data-integrity syncs we also need to check whether any pages are
1714da0c4c60SEric Biggers 	 * still under writeback, e.g. due to prior WB_SYNC_NONE writeback.  If
1715da0c4c60SEric Biggers 	 * there are any such pages, we'll need to wait for them.
17164f8ad655SJan Kara 	 */
17170ae45f63STheodore Ts'o 	if (!(inode->i_state & I_DIRTY_ALL) &&
1718f9b0e058SJan Kara 	    (wbc->sync_mode != WB_SYNC_ALL ||
1719f9b0e058SJan Kara 	     !mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK)))
17204f8ad655SJan Kara 		goto out;
17214f8ad655SJan Kara 	inode->i_state |= I_SYNC;
1722b16b1debSTejun Heo 	wbc_attach_and_unlock_inode(wbc, inode);
17234f8ad655SJan Kara 
1724cd8ed2a4SYan Hong 	ret = __writeback_single_inode(inode, wbc);
17251da177e4SLinus Torvalds 
1726b16b1debSTejun Heo 	wbc_detach_inode(wbc);
1727aaf25593STejun Heo 
1728aaf25593STejun Heo 	wb = inode_to_wb_and_lock_list(inode);
1729250df6edSDave Chinner 	spin_lock(&inode->i_lock);
17304f8ad655SJan Kara 	/*
17314e3c51f4SSvyatoslav Feldsherov 	 * If the inode is freeing, its i_io_list shoudn't be updated
17324e3c51f4SSvyatoslav Feldsherov 	 * as it can be finally deleted at this moment.
17334e3c51f4SSvyatoslav Feldsherov 	 */
17344e3c51f4SSvyatoslav Feldsherov 	if (!(inode->i_state & I_FREEING)) {
17354e3c51f4SSvyatoslav Feldsherov 		/*
17364e3c51f4SSvyatoslav Feldsherov 		 * If the inode is now fully clean, then it can be safely
17374e3c51f4SSvyatoslav Feldsherov 		 * removed from its writeback list (if any). Otherwise the
17384e3c51f4SSvyatoslav Feldsherov 		 * flusher threads are responsible for the writeback lists.
17394f8ad655SJan Kara 		 */
17400ae45f63STheodore Ts'o 		if (!(inode->i_state & I_DIRTY_ALL))
1741f3b6a6dfSRoman Gushchin 			inode_cgwb_move_to_attached(inode, wb);
1742cbfecb92SLukas Czerner 		else if (!(inode->i_state & I_SYNC_QUEUED)) {
1743cbfecb92SLukas Czerner 			if ((inode->i_state & I_DIRTY))
1744846a3351SJing Xia 				redirty_tail_locked(inode, wb);
1745cbfecb92SLukas Czerner 			else if (inode->i_state & I_DIRTY_TIME) {
1746cbfecb92SLukas Czerner 				inode->dirtied_when = jiffies;
17474e3c51f4SSvyatoslav Feldsherov 				inode_io_list_move_locked(inode,
17484e3c51f4SSvyatoslav Feldsherov 							  wb,
17494e3c51f4SSvyatoslav Feldsherov 							  &wb->b_dirty_time);
17504e3c51f4SSvyatoslav Feldsherov 			}
1751cbfecb92SLukas Czerner 		}
1752cbfecb92SLukas Czerner 	}
1753846a3351SJing Xia 
17544f8ad655SJan Kara 	spin_unlock(&wb->list_lock);
17551c0eeaf5SJoern Engel 	inode_sync_complete(inode);
17564f8ad655SJan Kara out:
17574f8ad655SJan Kara 	spin_unlock(&inode->i_lock);
17581da177e4SLinus Torvalds 	return ret;
17591da177e4SLinus Torvalds }
17601da177e4SLinus Torvalds 
1761a88a341aSTejun Heo static long writeback_chunk_size(struct bdi_writeback *wb,
17621a12d8bdSWu Fengguang 				 struct wb_writeback_work *work)
1763d46db3d5SWu Fengguang {
1764d46db3d5SWu Fengguang 	long pages;
1765d46db3d5SWu Fengguang 
1766d46db3d5SWu Fengguang 	/*
1767d46db3d5SWu Fengguang 	 * WB_SYNC_ALL mode does livelock avoidance by syncing dirty
1768d46db3d5SWu Fengguang 	 * inodes/pages in one big loop. Setting wbc.nr_to_write=LONG_MAX
1769d46db3d5SWu Fengguang 	 * here avoids calling into writeback_inodes_wb() more than once.
1770d46db3d5SWu Fengguang 	 *
1771d46db3d5SWu Fengguang 	 * The intended call sequence for WB_SYNC_ALL writeback is:
1772d46db3d5SWu Fengguang 	 *
1773d46db3d5SWu Fengguang 	 *      wb_writeback()
1774d46db3d5SWu Fengguang 	 *          writeback_sb_inodes()       <== called only once
1775d46db3d5SWu Fengguang 	 *              write_cache_pages()     <== called once for each inode
1776d46db3d5SWu Fengguang 	 *                   (quickly) tag currently dirty pages
1777d46db3d5SWu Fengguang 	 *                   (maybe slowly) sync all tagged pages
1778d46db3d5SWu Fengguang 	 */
1779d46db3d5SWu Fengguang 	if (work->sync_mode == WB_SYNC_ALL || work->tagged_writepages)
1780d46db3d5SWu Fengguang 		pages = LONG_MAX;
17811a12d8bdSWu Fengguang 	else {
1782a88a341aSTejun Heo 		pages = min(wb->avg_write_bandwidth / 2,
1783dcc25ae7STejun Heo 			    global_wb_domain.dirty_limit / DIRTY_SCOPE);
17841a12d8bdSWu Fengguang 		pages = min(pages, work->nr_pages);
17851a12d8bdSWu Fengguang 		pages = round_down(pages + MIN_WRITEBACK_PAGES,
17861a12d8bdSWu Fengguang 				   MIN_WRITEBACK_PAGES);
17871a12d8bdSWu Fengguang 	}
1788d46db3d5SWu Fengguang 
1789d46db3d5SWu Fengguang 	return pages;
1790d46db3d5SWu Fengguang }
1791d46db3d5SWu Fengguang 
179203ba3782SJens Axboe /*
1793f11c9c5cSEdward Shishkin  * Write a portion of b_io inodes which belong to @sb.
1794edadfb10SChristoph Hellwig  *
1795d46db3d5SWu Fengguang  * Return the number of pages and/or inodes written.
17960ba13fd1SLinus Torvalds  *
17970ba13fd1SLinus Torvalds  * NOTE! This is called with wb->list_lock held, and will
17980ba13fd1SLinus Torvalds  * unlock and relock that for each inode it ends up doing
17990ba13fd1SLinus Torvalds  * IO for.
1800f11c9c5cSEdward Shishkin  */
1801d46db3d5SWu Fengguang static long writeback_sb_inodes(struct super_block *sb,
1802d46db3d5SWu Fengguang 				struct bdi_writeback *wb,
1803d46db3d5SWu Fengguang 				struct wb_writeback_work *work)
180403ba3782SJens Axboe {
1805d46db3d5SWu Fengguang 	struct writeback_control wbc = {
1806d46db3d5SWu Fengguang 		.sync_mode		= work->sync_mode,
1807d46db3d5SWu Fengguang 		.tagged_writepages	= work->tagged_writepages,
1808d46db3d5SWu Fengguang 		.for_kupdate		= work->for_kupdate,
1809d46db3d5SWu Fengguang 		.for_background		= work->for_background,
18107747bd4bSDave Chinner 		.for_sync		= work->for_sync,
1811d46db3d5SWu Fengguang 		.range_cyclic		= work->range_cyclic,
1812d46db3d5SWu Fengguang 		.range_start		= 0,
1813d46db3d5SWu Fengguang 		.range_end		= LLONG_MAX,
1814d46db3d5SWu Fengguang 	};
1815d46db3d5SWu Fengguang 	unsigned long start_time = jiffies;
1816d46db3d5SWu Fengguang 	long write_chunk;
181768f4c6ebSZhihao Cheng 	long total_wrote = 0;  /* count both pages and inodes */
1818d46db3d5SWu Fengguang 
181903ba3782SJens Axboe 	while (!list_empty(&wb->b_io)) {
18207ccf19a8SNick Piggin 		struct inode *inode = wb_inode(wb->b_io.prev);
1821aaf25593STejun Heo 		struct bdi_writeback *tmp_wb;
182268f4c6ebSZhihao Cheng 		long wrote;
1823edadfb10SChristoph Hellwig 
1824edadfb10SChristoph Hellwig 		if (inode->i_sb != sb) {
1825d46db3d5SWu Fengguang 			if (work->sb) {
1826edadfb10SChristoph Hellwig 				/*
1827edadfb10SChristoph Hellwig 				 * We only want to write back data for this
1828edadfb10SChristoph Hellwig 				 * superblock, move all inodes not belonging
1829edadfb10SChristoph Hellwig 				 * to it back onto the dirty list.
1830edadfb10SChristoph Hellwig 				 */
1831f758eeabSChristoph Hellwig 				redirty_tail(inode, wb);
183266f3b8e2SJens Axboe 				continue;
183366f3b8e2SJens Axboe 			}
1834edadfb10SChristoph Hellwig 
1835edadfb10SChristoph Hellwig 			/*
1836edadfb10SChristoph Hellwig 			 * The inode belongs to a different superblock.
1837edadfb10SChristoph Hellwig 			 * Bounce back to the caller to unpin this and
1838edadfb10SChristoph Hellwig 			 * pin the next superblock.
1839edadfb10SChristoph Hellwig 			 */
1840d46db3d5SWu Fengguang 			break;
1841edadfb10SChristoph Hellwig 		}
1842edadfb10SChristoph Hellwig 
18439843b76aSChristoph Hellwig 		/*
1844331cbdeeSWanpeng Li 		 * Don't bother with new inodes or inodes being freed, first
1845331cbdeeSWanpeng Li 		 * kind does not need periodic writeout yet, and for the latter
18469843b76aSChristoph Hellwig 		 * kind writeout is handled by the freer.
18479843b76aSChristoph Hellwig 		 */
1848250df6edSDave Chinner 		spin_lock(&inode->i_lock);
18499843b76aSChristoph Hellwig 		if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) {
1850b35250c0SJan Kara 			redirty_tail_locked(inode, wb);
1851250df6edSDave Chinner 			spin_unlock(&inode->i_lock);
18527ef0d737SNick Piggin 			continue;
18537ef0d737SNick Piggin 		}
1854cc1676d9SJan Kara 		if ((inode->i_state & I_SYNC) && wbc.sync_mode != WB_SYNC_ALL) {
1855cc1676d9SJan Kara 			/*
1856cc1676d9SJan Kara 			 * If this inode is locked for writeback and we are not
1857cc1676d9SJan Kara 			 * doing writeback-for-data-integrity, move it to
1858cc1676d9SJan Kara 			 * b_more_io so that writeback can proceed with the
1859cc1676d9SJan Kara 			 * other inodes on s_io.
1860cc1676d9SJan Kara 			 *
1861cc1676d9SJan Kara 			 * We'll have another go at writing back this inode
1862cc1676d9SJan Kara 			 * when we completed a full scan of b_io.
1863cc1676d9SJan Kara 			 */
1864cc1676d9SJan Kara 			requeue_io(inode, wb);
186510e14073SJchao Sun 			spin_unlock(&inode->i_lock);
1866cc1676d9SJan Kara 			trace_writeback_sb_inodes_requeue(inode);
1867cc1676d9SJan Kara 			continue;
1868cc1676d9SJan Kara 		}
1869f0d07b7fSJan Kara 		spin_unlock(&wb->list_lock);
1870f0d07b7fSJan Kara 
18714f8ad655SJan Kara 		/*
18724f8ad655SJan Kara 		 * We already requeued the inode if it had I_SYNC set and we
18734f8ad655SJan Kara 		 * are doing WB_SYNC_NONE writeback. So this catches only the
18744f8ad655SJan Kara 		 * WB_SYNC_ALL case.
18754f8ad655SJan Kara 		 */
1876169ebd90SJan Kara 		if (inode->i_state & I_SYNC) {
1877169ebd90SJan Kara 			/* Wait for I_SYNC. This function drops i_lock... */
1878169ebd90SJan Kara 			inode_sleep_on_writeback(inode);
1879169ebd90SJan Kara 			/* Inode may be gone, start again */
1880ead188f9SJan Kara 			spin_lock(&wb->list_lock);
1881169ebd90SJan Kara 			continue;
1882169ebd90SJan Kara 		}
18834f8ad655SJan Kara 		inode->i_state |= I_SYNC;
1884b16b1debSTejun Heo 		wbc_attach_and_unlock_inode(&wbc, inode);
1885169ebd90SJan Kara 
1886a88a341aSTejun Heo 		write_chunk = writeback_chunk_size(wb, work);
1887d46db3d5SWu Fengguang 		wbc.nr_to_write = write_chunk;
1888d46db3d5SWu Fengguang 		wbc.pages_skipped = 0;
1889250df6edSDave Chinner 
1890169ebd90SJan Kara 		/*
1891169ebd90SJan Kara 		 * We use I_SYNC to pin the inode in memory. While it is set
1892169ebd90SJan Kara 		 * evict_inode() will wait so the inode cannot be freed.
1893169ebd90SJan Kara 		 */
1894cd8ed2a4SYan Hong 		__writeback_single_inode(inode, &wbc);
1895d46db3d5SWu Fengguang 
1896b16b1debSTejun Heo 		wbc_detach_inode(&wbc);
1897d46db3d5SWu Fengguang 		work->nr_pages -= write_chunk - wbc.nr_to_write;
189868f4c6ebSZhihao Cheng 		wrote = write_chunk - wbc.nr_to_write - wbc.pages_skipped;
189968f4c6ebSZhihao Cheng 		wrote = wrote < 0 ? 0 : wrote;
190068f4c6ebSZhihao Cheng 		total_wrote += wrote;
1901590dca3aSChris Mason 
1902590dca3aSChris Mason 		if (need_resched()) {
1903590dca3aSChris Mason 			/*
1904590dca3aSChris Mason 			 * We're trying to balance between building up a nice
1905590dca3aSChris Mason 			 * long list of IOs to improve our merge rate, and
1906590dca3aSChris Mason 			 * getting those IOs out quickly for anyone throttling
1907590dca3aSChris Mason 			 * in balance_dirty_pages().  cond_resched() doesn't
1908590dca3aSChris Mason 			 * unplug, so get our IOs out the door before we
1909590dca3aSChris Mason 			 * give up the CPU.
1910590dca3aSChris Mason 			 */
1911008f75a2SChristoph Hellwig 			blk_flush_plug(current->plug, false);
1912590dca3aSChris Mason 			cond_resched();
1913590dca3aSChris Mason 		}
1914590dca3aSChris Mason 
1915aaf25593STejun Heo 		/*
1916aaf25593STejun Heo 		 * Requeue @inode if still dirty.  Be careful as @inode may
1917aaf25593STejun Heo 		 * have been switched to another wb in the meantime.
1918aaf25593STejun Heo 		 */
1919aaf25593STejun Heo 		tmp_wb = inode_to_wb_and_lock_list(inode);
19204f8ad655SJan Kara 		spin_lock(&inode->i_lock);
19210ae45f63STheodore Ts'o 		if (!(inode->i_state & I_DIRTY_ALL))
192268f4c6ebSZhihao Cheng 			total_wrote++;
1923aaf25593STejun Heo 		requeue_inode(inode, tmp_wb, &wbc);
19244f8ad655SJan Kara 		inode_sync_complete(inode);
19250f1b1fd8SDave Chinner 		spin_unlock(&inode->i_lock);
1926590dca3aSChris Mason 
1927aaf25593STejun Heo 		if (unlikely(tmp_wb != wb)) {
1928aaf25593STejun Heo 			spin_unlock(&tmp_wb->list_lock);
1929aaf25593STejun Heo 			spin_lock(&wb->list_lock);
1930aaf25593STejun Heo 		}
1931aaf25593STejun Heo 
1932d46db3d5SWu Fengguang 		/*
1933d46db3d5SWu Fengguang 		 * bail out to wb_writeback() often enough to check
1934d46db3d5SWu Fengguang 		 * background threshold and other termination conditions.
1935d46db3d5SWu Fengguang 		 */
193668f4c6ebSZhihao Cheng 		if (total_wrote) {
1937d46db3d5SWu Fengguang 			if (time_is_before_jiffies(start_time + HZ / 10UL))
1938d46db3d5SWu Fengguang 				break;
1939d46db3d5SWu Fengguang 			if (work->nr_pages <= 0)
1940d46db3d5SWu Fengguang 				break;
19411da177e4SLinus Torvalds 		}
19428bc3be27SFengguang Wu 	}
194368f4c6ebSZhihao Cheng 	return total_wrote;
1944f11c9c5cSEdward Shishkin }
194538f21977SNick Piggin 
1946d46db3d5SWu Fengguang static long __writeback_inodes_wb(struct bdi_writeback *wb,
1947d46db3d5SWu Fengguang 				  struct wb_writeback_work *work)
1948f11c9c5cSEdward Shishkin {
1949d46db3d5SWu Fengguang 	unsigned long start_time = jiffies;
1950d46db3d5SWu Fengguang 	long wrote = 0;
1951f11c9c5cSEdward Shishkin 
1952f11c9c5cSEdward Shishkin 	while (!list_empty(&wb->b_io)) {
19537ccf19a8SNick Piggin 		struct inode *inode = wb_inode(wb->b_io.prev);
1954f11c9c5cSEdward Shishkin 		struct super_block *sb = inode->i_sb;
1955f11c9c5cSEdward Shishkin 
1956eb6ef3dfSKonstantin Khlebnikov 		if (!trylock_super(sb)) {
19570e995816SWu Fengguang 			/*
1958eb6ef3dfSKonstantin Khlebnikov 			 * trylock_super() may fail consistently due to
19590e995816SWu Fengguang 			 * s_umount being grabbed by someone else. Don't use
19600e995816SWu Fengguang 			 * requeue_io() to avoid busy retrying the inode/sb.
19610e995816SWu Fengguang 			 */
19620e995816SWu Fengguang 			redirty_tail(inode, wb);
1963d19de7edSChristoph Hellwig 			continue;
1964334132aeSChristoph Hellwig 		}
1965d46db3d5SWu Fengguang 		wrote += writeback_sb_inodes(sb, wb, work);
1966eb6ef3dfSKonstantin Khlebnikov 		up_read(&sb->s_umount);
1967f11c9c5cSEdward Shishkin 
1968d46db3d5SWu Fengguang 		/* refer to the same tests at the end of writeback_sb_inodes */
1969d46db3d5SWu Fengguang 		if (wrote) {
1970d46db3d5SWu Fengguang 			if (time_is_before_jiffies(start_time + HZ / 10UL))
1971d46db3d5SWu Fengguang 				break;
1972d46db3d5SWu Fengguang 			if (work->nr_pages <= 0)
1973f11c9c5cSEdward Shishkin 				break;
1974f11c9c5cSEdward Shishkin 		}
1975d46db3d5SWu Fengguang 	}
197666f3b8e2SJens Axboe 	/* Leave any unwritten inodes on b_io */
1977d46db3d5SWu Fengguang 	return wrote;
197866f3b8e2SJens Axboe }
197966f3b8e2SJens Axboe 
19807d9f073bSWanpeng Li static long writeback_inodes_wb(struct bdi_writeback *wb, long nr_pages,
19810e175a18SCurt Wohlgemuth 				enum wb_reason reason)
1982edadfb10SChristoph Hellwig {
1983d46db3d5SWu Fengguang 	struct wb_writeback_work work = {
1984d46db3d5SWu Fengguang 		.nr_pages	= nr_pages,
1985d46db3d5SWu Fengguang 		.sync_mode	= WB_SYNC_NONE,
1986d46db3d5SWu Fengguang 		.range_cyclic	= 1,
19870e175a18SCurt Wohlgemuth 		.reason		= reason,
1988d46db3d5SWu Fengguang 	};
1989505a666eSLinus Torvalds 	struct blk_plug plug;
1990edadfb10SChristoph Hellwig 
1991505a666eSLinus Torvalds 	blk_start_plug(&plug);
1992f758eeabSChristoph Hellwig 	spin_lock(&wb->list_lock);
1993424b351fSWu Fengguang 	if (list_empty(&wb->b_io))
1994f9cae926SJan Kara 		queue_io(wb, &work, jiffies);
1995d46db3d5SWu Fengguang 	__writeback_inodes_wb(wb, &work);
1996f758eeabSChristoph Hellwig 	spin_unlock(&wb->list_lock);
1997505a666eSLinus Torvalds 	blk_finish_plug(&plug);
1998edadfb10SChristoph Hellwig 
1999d46db3d5SWu Fengguang 	return nr_pages - work.nr_pages;
200066f3b8e2SJens Axboe }
200166f3b8e2SJens Axboe 
200203ba3782SJens Axboe /*
200303ba3782SJens Axboe  * Explicit flushing or periodic writeback of "old" data.
200403ba3782SJens Axboe  *
200503ba3782SJens Axboe  * Define "old": the first time one of an inode's pages is dirtied, we mark the
200603ba3782SJens Axboe  * dirtying-time in the inode's address_space.  So this periodic writeback code
200703ba3782SJens Axboe  * just walks the superblock inode list, writing back any inodes which are
200803ba3782SJens Axboe  * older than a specific point in time.
200903ba3782SJens Axboe  *
201003ba3782SJens Axboe  * Try to run once per dirty_writeback_interval.  But if a writeback event
201103ba3782SJens Axboe  * takes longer than a dirty_writeback_interval interval, then leave a
201203ba3782SJens Axboe  * one-second gap.
201303ba3782SJens Axboe  *
2014f9cae926SJan Kara  * dirtied_before takes precedence over nr_to_write.  So we'll only write back
201503ba3782SJens Axboe  * all dirty pages if they are all attached to "old" mappings.
201603ba3782SJens Axboe  */
2017c4a77a6cSJens Axboe static long wb_writeback(struct bdi_writeback *wb,
201883ba7b07SChristoph Hellwig 			 struct wb_writeback_work *work)
201903ba3782SJens Axboe {
2020d46db3d5SWu Fengguang 	long nr_pages = work->nr_pages;
2021f9cae926SJan Kara 	unsigned long dirtied_before = jiffies;
2022a5989bdcSJan Kara 	struct inode *inode;
2023d46db3d5SWu Fengguang 	long progress;
2024505a666eSLinus Torvalds 	struct blk_plug plug;
202503ba3782SJens Axboe 
2026505a666eSLinus Torvalds 	blk_start_plug(&plug);
2027e8dfc305SWu Fengguang 	spin_lock(&wb->list_lock);
202803ba3782SJens Axboe 	for (;;) {
202903ba3782SJens Axboe 		/*
2030d3ddec76SWu Fengguang 		 * Stop writeback when nr_pages has been consumed
203103ba3782SJens Axboe 		 */
203283ba7b07SChristoph Hellwig 		if (work->nr_pages <= 0)
203303ba3782SJens Axboe 			break;
203403ba3782SJens Axboe 
203503ba3782SJens Axboe 		/*
2036aa373cf5SJan Kara 		 * Background writeout and kupdate-style writeback may
2037aa373cf5SJan Kara 		 * run forever. Stop them if there is other work to do
2038aa373cf5SJan Kara 		 * so that e.g. sync can proceed. They'll be restarted
2039aa373cf5SJan Kara 		 * after the other works are all done.
2040aa373cf5SJan Kara 		 */
2041aa373cf5SJan Kara 		if ((work->for_background || work->for_kupdate) &&
2042f0054bb1STejun Heo 		    !list_empty(&wb->work_list))
2043aa373cf5SJan Kara 			break;
2044aa373cf5SJan Kara 
2045aa373cf5SJan Kara 		/*
2046d3ddec76SWu Fengguang 		 * For background writeout, stop when we are below the
2047d3ddec76SWu Fengguang 		 * background dirty threshold
204803ba3782SJens Axboe 		 */
2049aa661bbeSTejun Heo 		if (work->for_background && !wb_over_bg_thresh(wb))
205003ba3782SJens Axboe 			break;
205103ba3782SJens Axboe 
20521bc36b64SJan Kara 		/*
20531bc36b64SJan Kara 		 * Kupdate and background works are special and we want to
20541bc36b64SJan Kara 		 * include all inodes that need writing. Livelock avoidance is
20551bc36b64SJan Kara 		 * handled by these works yielding to any other work so we are
20561bc36b64SJan Kara 		 * safe.
20571bc36b64SJan Kara 		 */
2058ba9aa839SWu Fengguang 		if (work->for_kupdate) {
2059f9cae926SJan Kara 			dirtied_before = jiffies -
2060ba9aa839SWu Fengguang 				msecs_to_jiffies(dirty_expire_interval * 10);
20611bc36b64SJan Kara 		} else if (work->for_background)
2062f9cae926SJan Kara 			dirtied_before = jiffies;
2063028c2dd1SDave Chinner 
20645634cc2aSTejun Heo 		trace_writeback_start(wb, work);
2065e8dfc305SWu Fengguang 		if (list_empty(&wb->b_io))
2066f9cae926SJan Kara 			queue_io(wb, work, dirtied_before);
206783ba7b07SChristoph Hellwig 		if (work->sb)
2068d46db3d5SWu Fengguang 			progress = writeback_sb_inodes(work->sb, wb, work);
2069edadfb10SChristoph Hellwig 		else
2070d46db3d5SWu Fengguang 			progress = __writeback_inodes_wb(wb, work);
20715634cc2aSTejun Heo 		trace_writeback_written(wb, work);
2072028c2dd1SDave Chinner 
207303ba3782SJens Axboe 		/*
207471fd05a8SJens Axboe 		 * Did we write something? Try for more
2075e6fb6da2SWu Fengguang 		 *
2076e6fb6da2SWu Fengguang 		 * Dirty inodes are moved to b_io for writeback in batches.
2077e6fb6da2SWu Fengguang 		 * The completion of the current batch does not necessarily
2078e6fb6da2SWu Fengguang 		 * mean the overall work is done. So we keep looping as long
2079e6fb6da2SWu Fengguang 		 * as made some progress on cleaning pages or inodes.
208071fd05a8SJens Axboe 		 */
2081d46db3d5SWu Fengguang 		if (progress)
208203ba3782SJens Axboe 			continue;
2083a5989bdcSJan Kara 		/*
2084e6fb6da2SWu Fengguang 		 * No more inodes for IO, bail
2085a5989bdcSJan Kara 		 */
2086b7a2441fSWu Fengguang 		if (list_empty(&wb->b_more_io))
208703ba3782SJens Axboe 			break;
208803ba3782SJens Axboe 		/*
20898010c3b6SJens Axboe 		 * Nothing written. Wait for some inode to
20908010c3b6SJens Axboe 		 * become available for writeback. Otherwise
20918010c3b6SJens Axboe 		 * we'll just busyloop.
209203ba3782SJens Axboe 		 */
20935634cc2aSTejun Heo 		trace_writeback_wait(wb, work);
209403ba3782SJens Axboe 		inode = wb_inode(wb->b_more_io.prev);
2095250df6edSDave Chinner 		spin_lock(&inode->i_lock);
2096f0d07b7fSJan Kara 		spin_unlock(&wb->list_lock);
2097169ebd90SJan Kara 		/* This function drops i_lock... */
2098169ebd90SJan Kara 		inode_sleep_on_writeback(inode);
2099f0d07b7fSJan Kara 		spin_lock(&wb->list_lock);
210003ba3782SJens Axboe 	}
2101e8dfc305SWu Fengguang 	spin_unlock(&wb->list_lock);
2102505a666eSLinus Torvalds 	blk_finish_plug(&plug);
210303ba3782SJens Axboe 
2104d46db3d5SWu Fengguang 	return nr_pages - work->nr_pages;
210503ba3782SJens Axboe }
210603ba3782SJens Axboe 
210703ba3782SJens Axboe /*
210883ba7b07SChristoph Hellwig  * Return the next wb_writeback_work struct that hasn't been processed yet.
210903ba3782SJens Axboe  */
2110f0054bb1STejun Heo static struct wb_writeback_work *get_next_work_item(struct bdi_writeback *wb)
211103ba3782SJens Axboe {
211283ba7b07SChristoph Hellwig 	struct wb_writeback_work *work = NULL;
211303ba3782SJens Axboe 
2114f87904c0SKhazhismel Kumykov 	spin_lock_irq(&wb->work_lock);
2115f0054bb1STejun Heo 	if (!list_empty(&wb->work_list)) {
2116f0054bb1STejun Heo 		work = list_entry(wb->work_list.next,
211783ba7b07SChristoph Hellwig 				  struct wb_writeback_work, list);
211883ba7b07SChristoph Hellwig 		list_del_init(&work->list);
211903ba3782SJens Axboe 	}
2120f87904c0SKhazhismel Kumykov 	spin_unlock_irq(&wb->work_lock);
212183ba7b07SChristoph Hellwig 	return work;
212203ba3782SJens Axboe }
212303ba3782SJens Axboe 
21246585027aSJan Kara static long wb_check_background_flush(struct bdi_writeback *wb)
21256585027aSJan Kara {
2126aa661bbeSTejun Heo 	if (wb_over_bg_thresh(wb)) {
21276585027aSJan Kara 
21286585027aSJan Kara 		struct wb_writeback_work work = {
21296585027aSJan Kara 			.nr_pages	= LONG_MAX,
21306585027aSJan Kara 			.sync_mode	= WB_SYNC_NONE,
21316585027aSJan Kara 			.for_background	= 1,
21326585027aSJan Kara 			.range_cyclic	= 1,
21330e175a18SCurt Wohlgemuth 			.reason		= WB_REASON_BACKGROUND,
21346585027aSJan Kara 		};
21356585027aSJan Kara 
21366585027aSJan Kara 		return wb_writeback(wb, &work);
21376585027aSJan Kara 	}
21386585027aSJan Kara 
21396585027aSJan Kara 	return 0;
21406585027aSJan Kara }
21416585027aSJan Kara 
214203ba3782SJens Axboe static long wb_check_old_data_flush(struct bdi_writeback *wb)
214303ba3782SJens Axboe {
214403ba3782SJens Axboe 	unsigned long expired;
214503ba3782SJens Axboe 	long nr_pages;
214603ba3782SJens Axboe 
214769b62d01SJens Axboe 	/*
214869b62d01SJens Axboe 	 * When set to zero, disable periodic writeback
214969b62d01SJens Axboe 	 */
215069b62d01SJens Axboe 	if (!dirty_writeback_interval)
215169b62d01SJens Axboe 		return 0;
215269b62d01SJens Axboe 
215303ba3782SJens Axboe 	expired = wb->last_old_flush +
215403ba3782SJens Axboe 			msecs_to_jiffies(dirty_writeback_interval * 10);
215503ba3782SJens Axboe 	if (time_before(jiffies, expired))
215603ba3782SJens Axboe 		return 0;
215703ba3782SJens Axboe 
215803ba3782SJens Axboe 	wb->last_old_flush = jiffies;
2159cdf01dd5SLinus Torvalds 	nr_pages = get_nr_dirty_pages();
216003ba3782SJens Axboe 
2161c4a77a6cSJens Axboe 	if (nr_pages) {
216283ba7b07SChristoph Hellwig 		struct wb_writeback_work work = {
2163c4a77a6cSJens Axboe 			.nr_pages	= nr_pages,
2164c4a77a6cSJens Axboe 			.sync_mode	= WB_SYNC_NONE,
2165c4a77a6cSJens Axboe 			.for_kupdate	= 1,
2166c4a77a6cSJens Axboe 			.range_cyclic	= 1,
21670e175a18SCurt Wohlgemuth 			.reason		= WB_REASON_PERIODIC,
2168c4a77a6cSJens Axboe 		};
2169c4a77a6cSJens Axboe 
217083ba7b07SChristoph Hellwig 		return wb_writeback(wb, &work);
2171c4a77a6cSJens Axboe 	}
217203ba3782SJens Axboe 
217303ba3782SJens Axboe 	return 0;
217403ba3782SJens Axboe }
217503ba3782SJens Axboe 
217685009b4fSJens Axboe static long wb_check_start_all(struct bdi_writeback *wb)
217785009b4fSJens Axboe {
217885009b4fSJens Axboe 	long nr_pages;
217985009b4fSJens Axboe 
218085009b4fSJens Axboe 	if (!test_bit(WB_start_all, &wb->state))
218185009b4fSJens Axboe 		return 0;
218285009b4fSJens Axboe 
218385009b4fSJens Axboe 	nr_pages = get_nr_dirty_pages();
218485009b4fSJens Axboe 	if (nr_pages) {
218585009b4fSJens Axboe 		struct wb_writeback_work work = {
218685009b4fSJens Axboe 			.nr_pages	= wb_split_bdi_pages(wb, nr_pages),
218785009b4fSJens Axboe 			.sync_mode	= WB_SYNC_NONE,
218885009b4fSJens Axboe 			.range_cyclic	= 1,
218985009b4fSJens Axboe 			.reason		= wb->start_all_reason,
219085009b4fSJens Axboe 		};
219185009b4fSJens Axboe 
219285009b4fSJens Axboe 		nr_pages = wb_writeback(wb, &work);
219385009b4fSJens Axboe 	}
219485009b4fSJens Axboe 
219585009b4fSJens Axboe 	clear_bit(WB_start_all, &wb->state);
219685009b4fSJens Axboe 	return nr_pages;
219785009b4fSJens Axboe }
219885009b4fSJens Axboe 
219985009b4fSJens Axboe 
220003ba3782SJens Axboe /*
220103ba3782SJens Axboe  * Retrieve work items and do the writeback they describe
220203ba3782SJens Axboe  */
220325d130baSWanpeng Li static long wb_do_writeback(struct bdi_writeback *wb)
220403ba3782SJens Axboe {
220583ba7b07SChristoph Hellwig 	struct wb_writeback_work *work;
2206c4a77a6cSJens Axboe 	long wrote = 0;
220703ba3782SJens Axboe 
22084452226eSTejun Heo 	set_bit(WB_writeback_running, &wb->state);
2209f0054bb1STejun Heo 	while ((work = get_next_work_item(wb)) != NULL) {
22105634cc2aSTejun Heo 		trace_writeback_exec(wb, work);
221183ba7b07SChristoph Hellwig 		wrote += wb_writeback(wb, work);
22124a3a485bSTahsin Erdogan 		finish_writeback_work(wb, work);
221303ba3782SJens Axboe 	}
221403ba3782SJens Axboe 
221503ba3782SJens Axboe 	/*
221685009b4fSJens Axboe 	 * Check for a flush-everything request
221785009b4fSJens Axboe 	 */
221885009b4fSJens Axboe 	wrote += wb_check_start_all(wb);
221985009b4fSJens Axboe 
222085009b4fSJens Axboe 	/*
222103ba3782SJens Axboe 	 * Check for periodic writeback, kupdated() style
222203ba3782SJens Axboe 	 */
222303ba3782SJens Axboe 	wrote += wb_check_old_data_flush(wb);
22246585027aSJan Kara 	wrote += wb_check_background_flush(wb);
22254452226eSTejun Heo 	clear_bit(WB_writeback_running, &wb->state);
222603ba3782SJens Axboe 
222703ba3782SJens Axboe 	return wrote;
222803ba3782SJens Axboe }
222903ba3782SJens Axboe 
223003ba3782SJens Axboe /*
223103ba3782SJens Axboe  * Handle writeback of dirty data for the device backed by this bdi. Also
2232839a8e86STejun Heo  * reschedules periodically and does kupdated style flushing.
223303ba3782SJens Axboe  */
2234f0054bb1STejun Heo void wb_workfn(struct work_struct *work)
223503ba3782SJens Axboe {
2236839a8e86STejun Heo 	struct bdi_writeback *wb = container_of(to_delayed_work(work),
2237839a8e86STejun Heo 						struct bdi_writeback, dwork);
223803ba3782SJens Axboe 	long pages_written;
223903ba3782SJens Axboe 
224068f23b89STheodore Ts'o 	set_worker_desc("flush-%s", bdi_dev_name(wb->bdi));
224103ba3782SJens Axboe 
2242839a8e86STejun Heo 	if (likely(!current_is_workqueue_rescuer() ||
22434452226eSTejun Heo 		   !test_bit(WB_registered, &wb->state))) {
224403ba3782SJens Axboe 		/*
2245f0054bb1STejun Heo 		 * The normal path.  Keep writing back @wb until its
2246839a8e86STejun Heo 		 * work_list is empty.  Note that this path is also taken
2247f0054bb1STejun Heo 		 * if @wb is shutting down even when we're running off the
2248839a8e86STejun Heo 		 * rescuer as work_list needs to be drained.
224903ba3782SJens Axboe 		 */
2250839a8e86STejun Heo 		do {
225125d130baSWanpeng Li 			pages_written = wb_do_writeback(wb);
2252455b2864SDave Chinner 			trace_writeback_pages_written(pages_written);
2253f0054bb1STejun Heo 		} while (!list_empty(&wb->work_list));
2254839a8e86STejun Heo 	} else {
2255253c34e9SArtem Bityutskiy 		/*
2256839a8e86STejun Heo 		 * bdi_wq can't get enough workers and we're running off
2257839a8e86STejun Heo 		 * the emergency worker.  Don't hog it.  Hopefully, 1024 is
2258839a8e86STejun Heo 		 * enough for efficient IO.
2259253c34e9SArtem Bityutskiy 		 */
2260f0054bb1STejun Heo 		pages_written = writeback_inodes_wb(wb, 1024,
2261839a8e86STejun Heo 						    WB_REASON_FORKER_THREAD);
2262839a8e86STejun Heo 		trace_writeback_pages_written(pages_written);
226303ba3782SJens Axboe 	}
226403ba3782SJens Axboe 
2265f0054bb1STejun Heo 	if (!list_empty(&wb->work_list))
2266b8b78495SJan Kara 		wb_wakeup(wb);
22676ca738d6SDerek Basehore 	else if (wb_has_dirty_io(wb) && dirty_writeback_interval)
2268f0054bb1STejun Heo 		wb_wakeup_delayed(wb);
226903ba3782SJens Axboe }
227003ba3782SJens Axboe 
227103ba3782SJens Axboe /*
2272595043e5SJens Axboe  * Start writeback of `nr_pages' pages on this bdi. If `nr_pages' is zero,
2273595043e5SJens Axboe  * write back the whole world.
2274595043e5SJens Axboe  */
2275595043e5SJens Axboe static void __wakeup_flusher_threads_bdi(struct backing_dev_info *bdi,
2276e8e8a0c6SJens Axboe 					 enum wb_reason reason)
2277595043e5SJens Axboe {
2278595043e5SJens Axboe 	struct bdi_writeback *wb;
2279595043e5SJens Axboe 
2280595043e5SJens Axboe 	if (!bdi_has_dirty_io(bdi))
2281595043e5SJens Axboe 		return;
2282595043e5SJens Axboe 
2283595043e5SJens Axboe 	list_for_each_entry_rcu(wb, &bdi->wb_list, bdi_node)
2284e8e8a0c6SJens Axboe 		wb_start_writeback(wb, reason);
2285595043e5SJens Axboe }
2286595043e5SJens Axboe 
2287595043e5SJens Axboe void wakeup_flusher_threads_bdi(struct backing_dev_info *bdi,
2288595043e5SJens Axboe 				enum wb_reason reason)
2289595043e5SJens Axboe {
2290595043e5SJens Axboe 	rcu_read_lock();
2291e8e8a0c6SJens Axboe 	__wakeup_flusher_threads_bdi(bdi, reason);
2292595043e5SJens Axboe 	rcu_read_unlock();
2293595043e5SJens Axboe }
2294595043e5SJens Axboe 
2295595043e5SJens Axboe /*
22969ba4b2dfSJens Axboe  * Wakeup the flusher threads to start writeback of all currently dirty pages
229703ba3782SJens Axboe  */
22989ba4b2dfSJens Axboe void wakeup_flusher_threads(enum wb_reason reason)
229903ba3782SJens Axboe {
2300b8c2f347SChristoph Hellwig 	struct backing_dev_info *bdi;
2301b8c2f347SChristoph Hellwig 
230251350ea0SKonstantin Khlebnikov 	/*
230351350ea0SKonstantin Khlebnikov 	 * If we are expecting writeback progress we must submit plugged IO.
230451350ea0SKonstantin Khlebnikov 	 */
2305008f75a2SChristoph Hellwig 	blk_flush_plug(current->plug, true);
230651350ea0SKonstantin Khlebnikov 
2307b8c2f347SChristoph Hellwig 	rcu_read_lock();
2308595043e5SJens Axboe 	list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
2309e8e8a0c6SJens Axboe 		__wakeup_flusher_threads_bdi(bdi, reason);
2310b8c2f347SChristoph Hellwig 	rcu_read_unlock();
231103ba3782SJens Axboe }
231203ba3782SJens Axboe 
2313a2f48706STheodore Ts'o /*
2314a2f48706STheodore Ts'o  * Wake up bdi's periodically to make sure dirtytime inodes gets
2315a2f48706STheodore Ts'o  * written back periodically.  We deliberately do *not* check the
2316a2f48706STheodore Ts'o  * b_dirtytime list in wb_has_dirty_io(), since this would cause the
2317a2f48706STheodore Ts'o  * kernel to be constantly waking up once there are any dirtytime
2318a2f48706STheodore Ts'o  * inodes on the system.  So instead we define a separate delayed work
2319a2f48706STheodore Ts'o  * function which gets called much more rarely.  (By default, only
2320a2f48706STheodore Ts'o  * once every 12 hours.)
2321a2f48706STheodore Ts'o  *
2322a2f48706STheodore Ts'o  * If there is any other write activity going on in the file system,
2323a2f48706STheodore Ts'o  * this function won't be necessary.  But if the only thing that has
2324a2f48706STheodore Ts'o  * happened on the file system is a dirtytime inode caused by an atime
2325a2f48706STheodore Ts'o  * update, we need this infrastructure below to make sure that inode
2326a2f48706STheodore Ts'o  * eventually gets pushed out to disk.
2327a2f48706STheodore Ts'o  */
2328a2f48706STheodore Ts'o static void wakeup_dirtytime_writeback(struct work_struct *w);
2329a2f48706STheodore Ts'o static DECLARE_DELAYED_WORK(dirtytime_work, wakeup_dirtytime_writeback);
2330a2f48706STheodore Ts'o 
2331a2f48706STheodore Ts'o static void wakeup_dirtytime_writeback(struct work_struct *w)
2332a2f48706STheodore Ts'o {
2333a2f48706STheodore Ts'o 	struct backing_dev_info *bdi;
2334a2f48706STheodore Ts'o 
2335a2f48706STheodore Ts'o 	rcu_read_lock();
2336a2f48706STheodore Ts'o 	list_for_each_entry_rcu(bdi, &bdi_list, bdi_list) {
2337001fe6f6STejun Heo 		struct bdi_writeback *wb;
2338001fe6f6STejun Heo 
2339b817525aSTejun Heo 		list_for_each_entry_rcu(wb, &bdi->wb_list, bdi_node)
23406fdf860fSTejun Heo 			if (!list_empty(&wb->b_dirty_time))
23416fdf860fSTejun Heo 				wb_wakeup(wb);
2342a2f48706STheodore Ts'o 	}
2343a2f48706STheodore Ts'o 	rcu_read_unlock();
2344a2f48706STheodore Ts'o 	schedule_delayed_work(&dirtytime_work, dirtytime_expire_interval * HZ);
2345a2f48706STheodore Ts'o }
2346a2f48706STheodore Ts'o 
2347a2f48706STheodore Ts'o static int __init start_dirtytime_writeback(void)
2348a2f48706STheodore Ts'o {
2349a2f48706STheodore Ts'o 	schedule_delayed_work(&dirtytime_work, dirtytime_expire_interval * HZ);
2350a2f48706STheodore Ts'o 	return 0;
2351a2f48706STheodore Ts'o }
2352a2f48706STheodore Ts'o __initcall(start_dirtytime_writeback);
2353a2f48706STheodore Ts'o 
23541efff914STheodore Ts'o int dirtytime_interval_handler(struct ctl_table *table, int write,
23559ca48e20STobias Klauser 			       void *buffer, size_t *lenp, loff_t *ppos)
23561efff914STheodore Ts'o {
23571efff914STheodore Ts'o 	int ret;
23581efff914STheodore Ts'o 
23591efff914STheodore Ts'o 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
23601efff914STheodore Ts'o 	if (ret == 0 && write)
23611efff914STheodore Ts'o 		mod_delayed_work(system_wq, &dirtytime_work, 0);
23621efff914STheodore Ts'o 	return ret;
23631efff914STheodore Ts'o }
23641efff914STheodore Ts'o 
236503ba3782SJens Axboe /**
236635d14f27SEric Biggers  * __mark_inode_dirty -	internal function to mark an inode dirty
23670117d427SMauro Carvalho Chehab  *
236803ba3782SJens Axboe  * @inode: inode to mark
236935d14f27SEric Biggers  * @flags: what kind of dirty, e.g. I_DIRTY_SYNC.  This can be a combination of
237035d14f27SEric Biggers  *	   multiple I_DIRTY_* flags, except that I_DIRTY_TIME can't be combined
237135d14f27SEric Biggers  *	   with I_DIRTY_PAGES.
23720117d427SMauro Carvalho Chehab  *
237335d14f27SEric Biggers  * Mark an inode as dirty.  We notify the filesystem, then update the inode's
237435d14f27SEric Biggers  * dirty flags.  Then, if needed we add the inode to the appropriate dirty list.
237503ba3782SJens Axboe  *
237635d14f27SEric Biggers  * Most callers should use mark_inode_dirty() or mark_inode_dirty_sync()
237735d14f27SEric Biggers  * instead of calling this directly.
237803ba3782SJens Axboe  *
237935d14f27SEric Biggers  * CAREFUL!  We only add the inode to the dirty list if it is hashed or if it
238035d14f27SEric Biggers  * refers to a blockdev.  Unhashed inodes will never be added to the dirty list
238135d14f27SEric Biggers  * even if they are later hashed, as they will have been marked dirty already.
238203ba3782SJens Axboe  *
238335d14f27SEric Biggers  * In short, ensure you hash any inodes _before_ you start marking them dirty.
238403ba3782SJens Axboe  *
238503ba3782SJens Axboe  * Note that for blockdevs, inode->dirtied_when represents the dirtying time of
238603ba3782SJens Axboe  * the block-special inode (/dev/hda1) itself.  And the ->dirtied_when field of
238703ba3782SJens Axboe  * the kernel-internal blockdev inode represents the dirtying time of the
238803ba3782SJens Axboe  * blockdev's pages.  This is why for I_DIRTY_PAGES we always use
238903ba3782SJens Axboe  * page->mapping->host, so the page-dirtying time is recorded in the internal
239003ba3782SJens Axboe  * blockdev inode.
239103ba3782SJens Axboe  */
239203ba3782SJens Axboe void __mark_inode_dirty(struct inode *inode, int flags)
239303ba3782SJens Axboe {
239403ba3782SJens Axboe 	struct super_block *sb = inode->i_sb;
239535d14f27SEric Biggers 	int dirtytime = 0;
239610e14073SJchao Sun 	struct bdi_writeback *wb = NULL;
23970ae45f63STheodore Ts'o 
23980ae45f63STheodore Ts'o 	trace_writeback_mark_inode_dirty(inode, flags);
239903ba3782SJens Axboe 
2400e2728c56SEric Biggers 	if (flags & I_DIRTY_INODE) {
240135d14f27SEric Biggers 		/*
2402cbfecb92SLukas Czerner 		 * Inode timestamp update will piggback on this dirtying.
2403cbfecb92SLukas Czerner 		 * We tell ->dirty_inode callback that timestamps need to
2404cbfecb92SLukas Czerner 		 * be updated by setting I_DIRTY_TIME in flags.
2405cbfecb92SLukas Czerner 		 */
2406cbfecb92SLukas Czerner 		if (inode->i_state & I_DIRTY_TIME) {
2407cbfecb92SLukas Czerner 			spin_lock(&inode->i_lock);
2408cbfecb92SLukas Czerner 			if (inode->i_state & I_DIRTY_TIME) {
2409cbfecb92SLukas Czerner 				inode->i_state &= ~I_DIRTY_TIME;
2410cbfecb92SLukas Czerner 				flags |= I_DIRTY_TIME;
2411cbfecb92SLukas Czerner 			}
2412cbfecb92SLukas Czerner 			spin_unlock(&inode->i_lock);
2413cbfecb92SLukas Czerner 		}
2414cbfecb92SLukas Czerner 
2415cbfecb92SLukas Czerner 		/*
241635d14f27SEric Biggers 		 * Notify the filesystem about the inode being dirtied, so that
241735d14f27SEric Biggers 		 * (if needed) it can update on-disk fields and journal the
241835d14f27SEric Biggers 		 * inode.  This is only needed when the inode itself is being
241935d14f27SEric Biggers 		 * dirtied now.  I.e. it's only needed for I_DIRTY_INODE, not
242035d14f27SEric Biggers 		 * for just I_DIRTY_PAGES or I_DIRTY_TIME.
242135d14f27SEric Biggers 		 */
24229fb0a7daSTejun Heo 		trace_writeback_dirty_inode_start(inode, flags);
242303ba3782SJens Axboe 		if (sb->s_op->dirty_inode)
2424cbfecb92SLukas Czerner 			sb->s_op->dirty_inode(inode,
2425cbfecb92SLukas Czerner 				flags & (I_DIRTY_INODE | I_DIRTY_TIME));
24269fb0a7daSTejun Heo 		trace_writeback_dirty_inode(inode, flags);
2427e2728c56SEric Biggers 
242835d14f27SEric Biggers 		/* I_DIRTY_INODE supersedes I_DIRTY_TIME. */
24290ae45f63STheodore Ts'o 		flags &= ~I_DIRTY_TIME;
243035d14f27SEric Biggers 	} else {
243135d14f27SEric Biggers 		/*
243235d14f27SEric Biggers 		 * Else it's either I_DIRTY_PAGES, I_DIRTY_TIME, or nothing.
243335d14f27SEric Biggers 		 * (We don't support setting both I_DIRTY_PAGES and I_DIRTY_TIME
243435d14f27SEric Biggers 		 * in one call to __mark_inode_dirty().)
243535d14f27SEric Biggers 		 */
24360ae45f63STheodore Ts'o 		dirtytime = flags & I_DIRTY_TIME;
243735d14f27SEric Biggers 		WARN_ON_ONCE(dirtytime && flags != I_DIRTY_TIME);
243835d14f27SEric Biggers 	}
243903ba3782SJens Axboe 
244003ba3782SJens Axboe 	/*
24419c6ac78eSTejun Heo 	 * Paired with smp_mb() in __writeback_single_inode() for the
24429c6ac78eSTejun Heo 	 * following lockless i_state test.  See there for details.
244303ba3782SJens Axboe 	 */
244403ba3782SJens Axboe 	smp_mb();
244503ba3782SJens Axboe 
2446cbfecb92SLukas Czerner 	if ((inode->i_state & flags) == flags)
244703ba3782SJens Axboe 		return;
244803ba3782SJens Axboe 
2449250df6edSDave Chinner 	spin_lock(&inode->i_lock);
245003ba3782SJens Axboe 	if ((inode->i_state & flags) != flags) {
245103ba3782SJens Axboe 		const int was_dirty = inode->i_state & I_DIRTY;
245203ba3782SJens Axboe 
245352ebea74STejun Heo 		inode_attach_wb(inode, NULL);
245452ebea74STejun Heo 
245503ba3782SJens Axboe 		inode->i_state |= flags;
245603ba3782SJens Axboe 
245703ba3782SJens Axboe 		/*
245810e14073SJchao Sun 		 * Grab inode's wb early because it requires dropping i_lock and we
245910e14073SJchao Sun 		 * need to make sure following checks happen atomically with dirty
246010e14073SJchao Sun 		 * list handling so that we don't move inodes under flush worker's
246110e14073SJchao Sun 		 * hands.
246210e14073SJchao Sun 		 */
246310e14073SJchao Sun 		if (!was_dirty) {
246410e14073SJchao Sun 			wb = locked_inode_to_wb_and_lock_list(inode);
246510e14073SJchao Sun 			spin_lock(&inode->i_lock);
246610e14073SJchao Sun 		}
246710e14073SJchao Sun 
246810e14073SJchao Sun 		/*
24695afced3bSJan Kara 		 * If the inode is queued for writeback by flush worker, just
24705afced3bSJan Kara 		 * update its dirty state. Once the flush worker is done with
24715afced3bSJan Kara 		 * the inode it will place it on the appropriate superblock
24725afced3bSJan Kara 		 * list, based upon its state.
247303ba3782SJens Axboe 		 */
24745afced3bSJan Kara 		if (inode->i_state & I_SYNC_QUEUED)
247510e14073SJchao Sun 			goto out_unlock;
247603ba3782SJens Axboe 
247703ba3782SJens Axboe 		/*
247803ba3782SJens Axboe 		 * Only add valid (hashed) inodes to the superblock's
247903ba3782SJens Axboe 		 * dirty list.  Add blockdev inodes as well.
248003ba3782SJens Axboe 		 */
248103ba3782SJens Axboe 		if (!S_ISBLK(inode->i_mode)) {
24821d3382cbSAl Viro 			if (inode_unhashed(inode))
248310e14073SJchao Sun 				goto out_unlock;
248403ba3782SJens Axboe 		}
2485a4ffdde6SAl Viro 		if (inode->i_state & I_FREEING)
248610e14073SJchao Sun 			goto out_unlock;
248703ba3782SJens Axboe 
248803ba3782SJens Axboe 		/*
248903ba3782SJens Axboe 		 * If the inode was already on b_dirty/b_io/b_more_io, don't
249003ba3782SJens Axboe 		 * reposition it (that would break b_dirty time-ordering).
249103ba3782SJens Axboe 		 */
249203ba3782SJens Axboe 		if (!was_dirty) {
2493d6c10f1fSTejun Heo 			struct list_head *dirty_list;
2494a66979abSDave Chinner 			bool wakeup_bdi = false;
2495500b067cSJens Axboe 
249603ba3782SJens Axboe 			inode->dirtied_when = jiffies;
2497a2f48706STheodore Ts'o 			if (dirtytime)
2498a2f48706STheodore Ts'o 				inode->dirtied_time_when = jiffies;
2499d6c10f1fSTejun Heo 
25000e11f644SChristoph Hellwig 			if (inode->i_state & I_DIRTY)
25010747259dSTejun Heo 				dirty_list = &wb->b_dirty;
2502a2f48706STheodore Ts'o 			else
25030747259dSTejun Heo 				dirty_list = &wb->b_dirty_time;
2504d6c10f1fSTejun Heo 
2505c7f54084SDave Chinner 			wakeup_bdi = inode_io_list_move_locked(inode, wb,
2506d6c10f1fSTejun Heo 							       dirty_list);
2507d6c10f1fSTejun Heo 
25080747259dSTejun Heo 			spin_unlock(&wb->list_lock);
250910e14073SJchao Sun 			spin_unlock(&inode->i_lock);
25100ae45f63STheodore Ts'o 			trace_writeback_dirty_inode_enqueue(inode);
2511253c34e9SArtem Bityutskiy 
2512d6c10f1fSTejun Heo 			/*
2513d6c10f1fSTejun Heo 			 * If this is the first dirty inode for this bdi,
2514d6c10f1fSTejun Heo 			 * we have to wake-up the corresponding bdi thread
2515d6c10f1fSTejun Heo 			 * to make sure background write-back happens
2516d6c10f1fSTejun Heo 			 * later.
2517d6c10f1fSTejun Heo 			 */
2518f56753acSChristoph Hellwig 			if (wakeup_bdi &&
2519f56753acSChristoph Hellwig 			    (wb->bdi->capabilities & BDI_CAP_WRITEBACK))
25200747259dSTejun Heo 				wb_wakeup_delayed(wb);
2521a66979abSDave Chinner 			return;
2522a66979abSDave Chinner 		}
2523a66979abSDave Chinner 	}
252410e14073SJchao Sun out_unlock:
252510e14073SJchao Sun 	if (wb)
252610e14073SJchao Sun 		spin_unlock(&wb->list_lock);
2527a66979abSDave Chinner 	spin_unlock(&inode->i_lock);
252803ba3782SJens Axboe }
252903ba3782SJens Axboe EXPORT_SYMBOL(__mark_inode_dirty);
253003ba3782SJens Axboe 
2531e97fedb9SDave Chinner /*
2532e97fedb9SDave Chinner  * The @s_sync_lock is used to serialise concurrent sync operations
2533e97fedb9SDave Chinner  * to avoid lock contention problems with concurrent wait_sb_inodes() calls.
2534e97fedb9SDave Chinner  * Concurrent callers will block on the s_sync_lock rather than doing contending
2535e97fedb9SDave Chinner  * walks. The queueing maintains sync(2) required behaviour as all the IO that
2536e97fedb9SDave Chinner  * has been issued up to the time this function is enter is guaranteed to be
2537e97fedb9SDave Chinner  * completed by the time we have gained the lock and waited for all IO that is
2538e97fedb9SDave Chinner  * in progress regardless of the order callers are granted the lock.
2539e97fedb9SDave Chinner  */
2540b6e51316SJens Axboe static void wait_sb_inodes(struct super_block *sb)
254166f3b8e2SJens Axboe {
25426c60d2b5SDave Chinner 	LIST_HEAD(sync_list);
254338f21977SNick Piggin 
254403ba3782SJens Axboe 	/*
254503ba3782SJens Axboe 	 * We need to be protected against the filesystem going from
254603ba3782SJens Axboe 	 * r/o to r/w or vice versa.
254703ba3782SJens Axboe 	 */
2548b6e51316SJens Axboe 	WARN_ON(!rwsem_is_locked(&sb->s_umount));
254903ba3782SJens Axboe 
2550e97fedb9SDave Chinner 	mutex_lock(&sb->s_sync_lock);
255166f3b8e2SJens Axboe 
255238f21977SNick Piggin 	/*
25536c60d2b5SDave Chinner 	 * Splice the writeback list onto a temporary list to avoid waiting on
25546c60d2b5SDave Chinner 	 * inodes that have started writeback after this point.
25556c60d2b5SDave Chinner 	 *
25566c60d2b5SDave Chinner 	 * Use rcu_read_lock() to keep the inodes around until we have a
25576c60d2b5SDave Chinner 	 * reference. s_inode_wblist_lock protects sb->s_inodes_wb as well as
25586c60d2b5SDave Chinner 	 * the local list because inodes can be dropped from either by writeback
25596c60d2b5SDave Chinner 	 * completion.
256038f21977SNick Piggin 	 */
25616c60d2b5SDave Chinner 	rcu_read_lock();
25626c60d2b5SDave Chinner 	spin_lock_irq(&sb->s_inode_wblist_lock);
25636c60d2b5SDave Chinner 	list_splice_init(&sb->s_inodes_wb, &sync_list);
25646c60d2b5SDave Chinner 
25656c60d2b5SDave Chinner 	/*
25666c60d2b5SDave Chinner 	 * Data integrity sync. Must wait for all pages under writeback, because
25676c60d2b5SDave Chinner 	 * there may have been pages dirtied before our sync call, but which had
25686c60d2b5SDave Chinner 	 * writeout started before we write it out.  In which case, the inode
25696c60d2b5SDave Chinner 	 * may not be on the dirty list, but we still have to wait for that
25706c60d2b5SDave Chinner 	 * writeout.
25716c60d2b5SDave Chinner 	 */
25726c60d2b5SDave Chinner 	while (!list_empty(&sync_list)) {
25736c60d2b5SDave Chinner 		struct inode *inode = list_first_entry(&sync_list, struct inode,
25746c60d2b5SDave Chinner 						       i_wb_list);
2575250df6edSDave Chinner 		struct address_space *mapping = inode->i_mapping;
257638f21977SNick Piggin 
25776c60d2b5SDave Chinner 		/*
25786c60d2b5SDave Chinner 		 * Move each inode back to the wb list before we drop the lock
25796c60d2b5SDave Chinner 		 * to preserve consistency between i_wb_list and the mapping
25806c60d2b5SDave Chinner 		 * writeback tag. Writeback completion is responsible to remove
25816c60d2b5SDave Chinner 		 * the inode from either list once the writeback tag is cleared.
25826c60d2b5SDave Chinner 		 */
25836c60d2b5SDave Chinner 		list_move_tail(&inode->i_wb_list, &sb->s_inodes_wb);
25846c60d2b5SDave Chinner 
25856c60d2b5SDave Chinner 		/*
25866c60d2b5SDave Chinner 		 * The mapping can appear untagged while still on-list since we
25876c60d2b5SDave Chinner 		 * do not have the mapping lock. Skip it here, wb completion
25886c60d2b5SDave Chinner 		 * will remove it.
25896c60d2b5SDave Chinner 		 */
25906c60d2b5SDave Chinner 		if (!mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK))
25916c60d2b5SDave Chinner 			continue;
25926c60d2b5SDave Chinner 
25936c60d2b5SDave Chinner 		spin_unlock_irq(&sb->s_inode_wblist_lock);
25946c60d2b5SDave Chinner 
2595250df6edSDave Chinner 		spin_lock(&inode->i_lock);
25966c60d2b5SDave Chinner 		if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW)) {
2597250df6edSDave Chinner 			spin_unlock(&inode->i_lock);
25986c60d2b5SDave Chinner 
25996c60d2b5SDave Chinner 			spin_lock_irq(&sb->s_inode_wblist_lock);
260038f21977SNick Piggin 			continue;
2601250df6edSDave Chinner 		}
260238f21977SNick Piggin 		__iget(inode);
2603250df6edSDave Chinner 		spin_unlock(&inode->i_lock);
26046c60d2b5SDave Chinner 		rcu_read_unlock();
260538f21977SNick Piggin 
2606aa750fd7SJunichi Nomura 		/*
2607aa750fd7SJunichi Nomura 		 * We keep the error status of individual mapping so that
2608aa750fd7SJunichi Nomura 		 * applications can catch the writeback error using fsync(2).
2609aa750fd7SJunichi Nomura 		 * See filemap_fdatawait_keep_errors() for details.
2610aa750fd7SJunichi Nomura 		 */
2611aa750fd7SJunichi Nomura 		filemap_fdatawait_keep_errors(mapping);
261238f21977SNick Piggin 
261338f21977SNick Piggin 		cond_resched();
261438f21977SNick Piggin 
26156c60d2b5SDave Chinner 		iput(inode);
26166c60d2b5SDave Chinner 
26176c60d2b5SDave Chinner 		rcu_read_lock();
26186c60d2b5SDave Chinner 		spin_lock_irq(&sb->s_inode_wblist_lock);
261938f21977SNick Piggin 	}
26206c60d2b5SDave Chinner 	spin_unlock_irq(&sb->s_inode_wblist_lock);
26216c60d2b5SDave Chinner 	rcu_read_unlock();
2622e97fedb9SDave Chinner 	mutex_unlock(&sb->s_sync_lock);
262366f3b8e2SJens Axboe }
26241da177e4SLinus Torvalds 
2625f30a7d0cSTejun Heo static void __writeback_inodes_sb_nr(struct super_block *sb, unsigned long nr,
2626f30a7d0cSTejun Heo 				     enum wb_reason reason, bool skip_if_busy)
26271da177e4SLinus Torvalds {
26285b9cce4cSTejun Heo 	struct backing_dev_info *bdi = sb->s_bdi;
26295b9cce4cSTejun Heo 	DEFINE_WB_COMPLETION(done, bdi);
263083ba7b07SChristoph Hellwig 	struct wb_writeback_work work = {
26313c4d7165SChristoph Hellwig 		.sb			= sb,
26323c4d7165SChristoph Hellwig 		.sync_mode		= WB_SYNC_NONE,
26336e6938b6SWu Fengguang 		.tagged_writepages	= 1,
263483ba7b07SChristoph Hellwig 		.done			= &done,
26353259f8beSChris Mason 		.nr_pages		= nr,
26360e175a18SCurt Wohlgemuth 		.reason			= reason,
26373c4d7165SChristoph Hellwig 	};
26380e3c9a22SJens Axboe 
2639e7972912STejun Heo 	if (!bdi_has_dirty_io(bdi) || bdi == &noop_backing_dev_info)
26406eedc701SJan Kara 		return;
2641cf37e972SChristoph Hellwig 	WARN_ON(!rwsem_is_locked(&sb->s_umount));
2642f30a7d0cSTejun Heo 
2643db125360STejun Heo 	bdi_split_work_to_wbs(sb->s_bdi, &work, skip_if_busy);
26445b9cce4cSTejun Heo 	wb_wait_for_completion(&done);
26451da177e4SLinus Torvalds }
2646f30a7d0cSTejun Heo 
2647f30a7d0cSTejun Heo /**
2648f30a7d0cSTejun Heo  * writeback_inodes_sb_nr -	writeback dirty inodes from given super_block
2649f30a7d0cSTejun Heo  * @sb: the superblock
2650f30a7d0cSTejun Heo  * @nr: the number of pages to write
2651f30a7d0cSTejun Heo  * @reason: reason why some writeback work initiated
2652f30a7d0cSTejun Heo  *
2653f30a7d0cSTejun Heo  * Start writeback on some inodes on this super_block. No guarantees are made
2654f30a7d0cSTejun Heo  * on how many (if any) will be written, and this function does not wait
2655f30a7d0cSTejun Heo  * for IO completion of submitted IO.
2656f30a7d0cSTejun Heo  */
2657f30a7d0cSTejun Heo void writeback_inodes_sb_nr(struct super_block *sb,
2658f30a7d0cSTejun Heo 			    unsigned long nr,
2659f30a7d0cSTejun Heo 			    enum wb_reason reason)
2660f30a7d0cSTejun Heo {
2661f30a7d0cSTejun Heo 	__writeback_inodes_sb_nr(sb, nr, reason, false);
2662f30a7d0cSTejun Heo }
26633259f8beSChris Mason EXPORT_SYMBOL(writeback_inodes_sb_nr);
26643259f8beSChris Mason 
26653259f8beSChris Mason /**
26663259f8beSChris Mason  * writeback_inodes_sb	-	writeback dirty inodes from given super_block
26673259f8beSChris Mason  * @sb: the superblock
2668786228abSMarcos Paulo de Souza  * @reason: reason why some writeback work was initiated
26693259f8beSChris Mason  *
26703259f8beSChris Mason  * Start writeback on some inodes on this super_block. No guarantees are made
26713259f8beSChris Mason  * on how many (if any) will be written, and this function does not wait
26723259f8beSChris Mason  * for IO completion of submitted IO.
26733259f8beSChris Mason  */
26740e175a18SCurt Wohlgemuth void writeback_inodes_sb(struct super_block *sb, enum wb_reason reason)
26753259f8beSChris Mason {
26760e175a18SCurt Wohlgemuth 	return writeback_inodes_sb_nr(sb, get_nr_dirty_pages(), reason);
26773259f8beSChris Mason }
2678d8a8559cSJens Axboe EXPORT_SYMBOL(writeback_inodes_sb);
2679d8a8559cSJens Axboe 
2680d8a8559cSJens Axboe /**
268110ee27a0SMiao Xie  * try_to_writeback_inodes_sb - try to start writeback if none underway
268210ee27a0SMiao Xie  * @sb: the superblock
268310ee27a0SMiao Xie  * @reason: reason why some writeback work was initiated
268410ee27a0SMiao Xie  *
26858264c321SRakesh Pandit  * Invoke __writeback_inodes_sb_nr if no writeback is currently underway.
268610ee27a0SMiao Xie  */
26878264c321SRakesh Pandit void try_to_writeback_inodes_sb(struct super_block *sb, enum wb_reason reason)
268810ee27a0SMiao Xie {
26898264c321SRakesh Pandit 	if (!down_read_trylock(&sb->s_umount))
26908264c321SRakesh Pandit 		return;
26918264c321SRakesh Pandit 
26928264c321SRakesh Pandit 	__writeback_inodes_sb_nr(sb, get_nr_dirty_pages(), reason, true);
26938264c321SRakesh Pandit 	up_read(&sb->s_umount);
269410ee27a0SMiao Xie }
269510ee27a0SMiao Xie EXPORT_SYMBOL(try_to_writeback_inodes_sb);
26963259f8beSChris Mason 
26973259f8beSChris Mason /**
2698d8a8559cSJens Axboe  * sync_inodes_sb	-	sync sb inode pages
2699d8a8559cSJens Axboe  * @sb: the superblock
2700d8a8559cSJens Axboe  *
2701d8a8559cSJens Axboe  * This function writes and waits on any dirty inode belonging to this
27020dc83bd3SJan Kara  * super_block.
2703d8a8559cSJens Axboe  */
27040dc83bd3SJan Kara void sync_inodes_sb(struct super_block *sb)
2705d8a8559cSJens Axboe {
27065b9cce4cSTejun Heo 	struct backing_dev_info *bdi = sb->s_bdi;
27075b9cce4cSTejun Heo 	DEFINE_WB_COMPLETION(done, bdi);
270883ba7b07SChristoph Hellwig 	struct wb_writeback_work work = {
27093c4d7165SChristoph Hellwig 		.sb		= sb,
27103c4d7165SChristoph Hellwig 		.sync_mode	= WB_SYNC_ALL,
27113c4d7165SChristoph Hellwig 		.nr_pages	= LONG_MAX,
27123c4d7165SChristoph Hellwig 		.range_cyclic	= 0,
271383ba7b07SChristoph Hellwig 		.done		= &done,
27140e175a18SCurt Wohlgemuth 		.reason		= WB_REASON_SYNC,
27157747bd4bSDave Chinner 		.for_sync	= 1,
27163c4d7165SChristoph Hellwig 	};
27173c4d7165SChristoph Hellwig 
2718006a0973STejun Heo 	/*
2719006a0973STejun Heo 	 * Can't skip on !bdi_has_dirty() because we should wait for !dirty
2720006a0973STejun Heo 	 * inodes under writeback and I_DIRTY_TIME inodes ignored by
2721006a0973STejun Heo 	 * bdi_has_dirty() need to be written out too.
2722006a0973STejun Heo 	 */
2723006a0973STejun Heo 	if (bdi == &noop_backing_dev_info)
27246eedc701SJan Kara 		return;
2725cf37e972SChristoph Hellwig 	WARN_ON(!rwsem_is_locked(&sb->s_umount));
2726cf37e972SChristoph Hellwig 
27277fc5854fSTejun Heo 	/* protect against inode wb switch, see inode_switch_wbs_work_fn() */
27287fc5854fSTejun Heo 	bdi_down_write_wb_switch_rwsem(bdi);
2729db125360STejun Heo 	bdi_split_work_to_wbs(bdi, &work, false);
27305b9cce4cSTejun Heo 	wb_wait_for_completion(&done);
27317fc5854fSTejun Heo 	bdi_up_write_wb_switch_rwsem(bdi);
273283ba7b07SChristoph Hellwig 
2733b6e51316SJens Axboe 	wait_sb_inodes(sb);
2734d8a8559cSJens Axboe }
2735d8a8559cSJens Axboe EXPORT_SYMBOL(sync_inodes_sb);
27361da177e4SLinus Torvalds 
27371da177e4SLinus Torvalds /**
27381da177e4SLinus Torvalds  * write_inode_now	-	write an inode to disk
27391da177e4SLinus Torvalds  * @inode: inode to write to disk
27401da177e4SLinus Torvalds  * @sync: whether the write should be synchronous or not
27411da177e4SLinus Torvalds  *
27427f04c26dSAndrea Arcangeli  * This function commits an inode to disk immediately if it is dirty. This is
27437f04c26dSAndrea Arcangeli  * primarily needed by knfsd.
27447f04c26dSAndrea Arcangeli  *
27457f04c26dSAndrea Arcangeli  * The caller must either have a ref on the inode or must have set I_WILL_FREE.
27461da177e4SLinus Torvalds  */
27471da177e4SLinus Torvalds int write_inode_now(struct inode *inode, int sync)
27481da177e4SLinus Torvalds {
27491da177e4SLinus Torvalds 	struct writeback_control wbc = {
27501da177e4SLinus Torvalds 		.nr_to_write = LONG_MAX,
275118914b18SMike Galbraith 		.sync_mode = sync ? WB_SYNC_ALL : WB_SYNC_NONE,
2752111ebb6eSOGAWA Hirofumi 		.range_start = 0,
2753111ebb6eSOGAWA Hirofumi 		.range_end = LLONG_MAX,
27541da177e4SLinus Torvalds 	};
27551da177e4SLinus Torvalds 
2756f56753acSChristoph Hellwig 	if (!mapping_can_writeback(inode->i_mapping))
275749364ce2SAndrew Morton 		wbc.nr_to_write = 0;
27581da177e4SLinus Torvalds 
27591da177e4SLinus Torvalds 	might_sleep();
2760aaf25593STejun Heo 	return writeback_single_inode(inode, &wbc);
27611da177e4SLinus Torvalds }
27621da177e4SLinus Torvalds EXPORT_SYMBOL(write_inode_now);
27631da177e4SLinus Torvalds 
27641da177e4SLinus Torvalds /**
2765c691b9d9SAndrew Morton  * sync_inode_metadata - write an inode to disk
2766c3765016SChristoph Hellwig  * @inode: the inode to sync
2767c3765016SChristoph Hellwig  * @wait: wait for I/O to complete.
2768c3765016SChristoph Hellwig  *
2769c691b9d9SAndrew Morton  * Write an inode to disk and adjust its dirty state after completion.
2770c3765016SChristoph Hellwig  *
2771c3765016SChristoph Hellwig  * Note: only writes the actual inode, no associated data or other metadata.
2772c3765016SChristoph Hellwig  */
2773c3765016SChristoph Hellwig int sync_inode_metadata(struct inode *inode, int wait)
2774c3765016SChristoph Hellwig {
2775c3765016SChristoph Hellwig 	struct writeback_control wbc = {
2776c3765016SChristoph Hellwig 		.sync_mode = wait ? WB_SYNC_ALL : WB_SYNC_NONE,
2777c3765016SChristoph Hellwig 		.nr_to_write = 0, /* metadata-only */
2778c3765016SChristoph Hellwig 	};
2779c3765016SChristoph Hellwig 
27805662c967SJosef Bacik 	return writeback_single_inode(inode, &wbc);
2781c3765016SChristoph Hellwig }
2782c3765016SChristoph Hellwig EXPORT_SYMBOL(sync_inode_metadata);
2783