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