xref: /openbmc/linux/fs/nilfs2/segment.c (revision 0545810f)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * NILFS segment constructor.
4  *
5  * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation.
6  *
7  * Written by Ryusuke Konishi.
8  *
9  */
10 
11 #include <linux/pagemap.h>
12 #include <linux/buffer_head.h>
13 #include <linux/writeback.h>
14 #include <linux/bitops.h>
15 #include <linux/bio.h>
16 #include <linux/completion.h>
17 #include <linux/blkdev.h>
18 #include <linux/backing-dev.h>
19 #include <linux/freezer.h>
20 #include <linux/kthread.h>
21 #include <linux/crc32.h>
22 #include <linux/pagevec.h>
23 #include <linux/slab.h>
24 #include <linux/sched/signal.h>
25 
26 #include "nilfs.h"
27 #include "btnode.h"
28 #include "page.h"
29 #include "segment.h"
30 #include "sufile.h"
31 #include "cpfile.h"
32 #include "ifile.h"
33 #include "segbuf.h"
34 
35 
36 /*
37  * Segment constructor
38  */
39 #define SC_N_INODEVEC	16   /* Size of locally allocated inode vector */
40 
41 #define SC_MAX_SEGDELTA 64   /*
42 			      * Upper limit of the number of segments
43 			      * appended in collection retry loop
44 			      */
45 
46 /* Construction mode */
47 enum {
48 	SC_LSEG_SR = 1,	/* Make a logical segment having a super root */
49 	SC_LSEG_DSYNC,	/*
50 			 * Flush data blocks of a given file and make
51 			 * a logical segment without a super root.
52 			 */
53 	SC_FLUSH_FILE,	/*
54 			 * Flush data files, leads to segment writes without
55 			 * creating a checkpoint.
56 			 */
57 	SC_FLUSH_DAT,	/*
58 			 * Flush DAT file.  This also creates segments
59 			 * without a checkpoint.
60 			 */
61 };
62 
63 /* Stage numbers of dirty block collection */
64 enum {
65 	NILFS_ST_INIT = 0,
66 	NILFS_ST_GC,		/* Collecting dirty blocks for GC */
67 	NILFS_ST_FILE,
68 	NILFS_ST_IFILE,
69 	NILFS_ST_CPFILE,
70 	NILFS_ST_SUFILE,
71 	NILFS_ST_DAT,
72 	NILFS_ST_SR,		/* Super root */
73 	NILFS_ST_DSYNC,		/* Data sync blocks */
74 	NILFS_ST_DONE,
75 };
76 
77 #define CREATE_TRACE_POINTS
78 #include <trace/events/nilfs2.h>
79 
80 /*
81  * nilfs_sc_cstage_inc(), nilfs_sc_cstage_set(), nilfs_sc_cstage_get() are
82  * wrapper functions of stage count (nilfs_sc_info->sc_stage.scnt). Users of
83  * the variable must use them because transition of stage count must involve
84  * trace events (trace_nilfs2_collection_stage_transition).
85  *
86  * nilfs_sc_cstage_get() isn't required for the above purpose because it doesn't
87  * produce tracepoint events. It is provided just for making the intention
88  * clear.
89  */
90 static inline void nilfs_sc_cstage_inc(struct nilfs_sc_info *sci)
91 {
92 	sci->sc_stage.scnt++;
93 	trace_nilfs2_collection_stage_transition(sci);
94 }
95 
96 static inline void nilfs_sc_cstage_set(struct nilfs_sc_info *sci, int next_scnt)
97 {
98 	sci->sc_stage.scnt = next_scnt;
99 	trace_nilfs2_collection_stage_transition(sci);
100 }
101 
102 static inline int nilfs_sc_cstage_get(struct nilfs_sc_info *sci)
103 {
104 	return sci->sc_stage.scnt;
105 }
106 
107 /* State flags of collection */
108 #define NILFS_CF_NODE		0x0001	/* Collecting node blocks */
109 #define NILFS_CF_IFILE_STARTED	0x0002	/* IFILE stage has started */
110 #define NILFS_CF_SUFREED	0x0004	/* segment usages has been freed */
111 #define NILFS_CF_HISTORY_MASK	(NILFS_CF_IFILE_STARTED | NILFS_CF_SUFREED)
112 
113 /* Operations depending on the construction mode and file type */
114 struct nilfs_sc_operations {
115 	int (*collect_data)(struct nilfs_sc_info *, struct buffer_head *,
116 			    struct inode *);
117 	int (*collect_node)(struct nilfs_sc_info *, struct buffer_head *,
118 			    struct inode *);
119 	int (*collect_bmap)(struct nilfs_sc_info *, struct buffer_head *,
120 			    struct inode *);
121 	void (*write_data_binfo)(struct nilfs_sc_info *,
122 				 struct nilfs_segsum_pointer *,
123 				 union nilfs_binfo *);
124 	void (*write_node_binfo)(struct nilfs_sc_info *,
125 				 struct nilfs_segsum_pointer *,
126 				 union nilfs_binfo *);
127 };
128 
129 /*
130  * Other definitions
131  */
132 static void nilfs_segctor_start_timer(struct nilfs_sc_info *);
133 static void nilfs_segctor_do_flush(struct nilfs_sc_info *, int);
134 static void nilfs_segctor_do_immediate_flush(struct nilfs_sc_info *);
135 static void nilfs_dispose_list(struct the_nilfs *, struct list_head *, int);
136 
137 #define nilfs_cnt32_ge(a, b)   \
138 	(typecheck(__u32, a) && typecheck(__u32, b) && \
139 	 ((__s32)(a) - (__s32)(b) >= 0))
140 
141 static int nilfs_prepare_segment_lock(struct super_block *sb,
142 				      struct nilfs_transaction_info *ti)
143 {
144 	struct nilfs_transaction_info *cur_ti = current->journal_info;
145 	void *save = NULL;
146 
147 	if (cur_ti) {
148 		if (cur_ti->ti_magic == NILFS_TI_MAGIC)
149 			return ++cur_ti->ti_count;
150 
151 		/*
152 		 * If journal_info field is occupied by other FS,
153 		 * it is saved and will be restored on
154 		 * nilfs_transaction_commit().
155 		 */
156 		nilfs_warn(sb, "journal info from a different FS");
157 		save = current->journal_info;
158 	}
159 	if (!ti) {
160 		ti = kmem_cache_alloc(nilfs_transaction_cachep, GFP_NOFS);
161 		if (!ti)
162 			return -ENOMEM;
163 		ti->ti_flags = NILFS_TI_DYNAMIC_ALLOC;
164 	} else {
165 		ti->ti_flags = 0;
166 	}
167 	ti->ti_count = 0;
168 	ti->ti_save = save;
169 	ti->ti_magic = NILFS_TI_MAGIC;
170 	current->journal_info = ti;
171 	return 0;
172 }
173 
174 /**
175  * nilfs_transaction_begin - start indivisible file operations.
176  * @sb: super block
177  * @ti: nilfs_transaction_info
178  * @vacancy_check: flags for vacancy rate checks
179  *
180  * nilfs_transaction_begin() acquires a reader/writer semaphore, called
181  * the segment semaphore, to make a segment construction and write tasks
182  * exclusive.  The function is used with nilfs_transaction_commit() in pairs.
183  * The region enclosed by these two functions can be nested.  To avoid a
184  * deadlock, the semaphore is only acquired or released in the outermost call.
185  *
186  * This function allocates a nilfs_transaction_info struct to keep context
187  * information on it.  It is initialized and hooked onto the current task in
188  * the outermost call.  If a pre-allocated struct is given to @ti, it is used
189  * instead; otherwise a new struct is assigned from a slab.
190  *
191  * When @vacancy_check flag is set, this function will check the amount of
192  * free space, and will wait for the GC to reclaim disk space if low capacity.
193  *
194  * Return Value: On success, 0 is returned. On error, one of the following
195  * negative error code is returned.
196  *
197  * %-ENOMEM - Insufficient memory available.
198  *
199  * %-ENOSPC - No space left on device
200  */
201 int nilfs_transaction_begin(struct super_block *sb,
202 			    struct nilfs_transaction_info *ti,
203 			    int vacancy_check)
204 {
205 	struct the_nilfs *nilfs;
206 	int ret = nilfs_prepare_segment_lock(sb, ti);
207 	struct nilfs_transaction_info *trace_ti;
208 
209 	if (unlikely(ret < 0))
210 		return ret;
211 	if (ret > 0) {
212 		trace_ti = current->journal_info;
213 
214 		trace_nilfs2_transaction_transition(sb, trace_ti,
215 				    trace_ti->ti_count, trace_ti->ti_flags,
216 				    TRACE_NILFS2_TRANSACTION_BEGIN);
217 		return 0;
218 	}
219 
220 	sb_start_intwrite(sb);
221 
222 	nilfs = sb->s_fs_info;
223 	down_read(&nilfs->ns_segctor_sem);
224 	if (vacancy_check && nilfs_near_disk_full(nilfs)) {
225 		up_read(&nilfs->ns_segctor_sem);
226 		ret = -ENOSPC;
227 		goto failed;
228 	}
229 
230 	trace_ti = current->journal_info;
231 	trace_nilfs2_transaction_transition(sb, trace_ti, trace_ti->ti_count,
232 					    trace_ti->ti_flags,
233 					    TRACE_NILFS2_TRANSACTION_BEGIN);
234 	return 0;
235 
236  failed:
237 	ti = current->journal_info;
238 	current->journal_info = ti->ti_save;
239 	if (ti->ti_flags & NILFS_TI_DYNAMIC_ALLOC)
240 		kmem_cache_free(nilfs_transaction_cachep, ti);
241 	sb_end_intwrite(sb);
242 	return ret;
243 }
244 
245 /**
246  * nilfs_transaction_commit - commit indivisible file operations.
247  * @sb: super block
248  *
249  * nilfs_transaction_commit() releases the read semaphore which is
250  * acquired by nilfs_transaction_begin(). This is only performed
251  * in outermost call of this function.  If a commit flag is set,
252  * nilfs_transaction_commit() sets a timer to start the segment
253  * constructor.  If a sync flag is set, it starts construction
254  * directly.
255  */
256 int nilfs_transaction_commit(struct super_block *sb)
257 {
258 	struct nilfs_transaction_info *ti = current->journal_info;
259 	struct the_nilfs *nilfs = sb->s_fs_info;
260 	int err = 0;
261 
262 	BUG_ON(ti == NULL || ti->ti_magic != NILFS_TI_MAGIC);
263 	ti->ti_flags |= NILFS_TI_COMMIT;
264 	if (ti->ti_count > 0) {
265 		ti->ti_count--;
266 		trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
267 			    ti->ti_flags, TRACE_NILFS2_TRANSACTION_COMMIT);
268 		return 0;
269 	}
270 	if (nilfs->ns_writer) {
271 		struct nilfs_sc_info *sci = nilfs->ns_writer;
272 
273 		if (ti->ti_flags & NILFS_TI_COMMIT)
274 			nilfs_segctor_start_timer(sci);
275 		if (atomic_read(&nilfs->ns_ndirtyblks) > sci->sc_watermark)
276 			nilfs_segctor_do_flush(sci, 0);
277 	}
278 	up_read(&nilfs->ns_segctor_sem);
279 	trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
280 			    ti->ti_flags, TRACE_NILFS2_TRANSACTION_COMMIT);
281 
282 	current->journal_info = ti->ti_save;
283 
284 	if (ti->ti_flags & NILFS_TI_SYNC)
285 		err = nilfs_construct_segment(sb);
286 	if (ti->ti_flags & NILFS_TI_DYNAMIC_ALLOC)
287 		kmem_cache_free(nilfs_transaction_cachep, ti);
288 	sb_end_intwrite(sb);
289 	return err;
290 }
291 
292 void nilfs_transaction_abort(struct super_block *sb)
293 {
294 	struct nilfs_transaction_info *ti = current->journal_info;
295 	struct the_nilfs *nilfs = sb->s_fs_info;
296 
297 	BUG_ON(ti == NULL || ti->ti_magic != NILFS_TI_MAGIC);
298 	if (ti->ti_count > 0) {
299 		ti->ti_count--;
300 		trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
301 			    ti->ti_flags, TRACE_NILFS2_TRANSACTION_ABORT);
302 		return;
303 	}
304 	up_read(&nilfs->ns_segctor_sem);
305 
306 	trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
307 		    ti->ti_flags, TRACE_NILFS2_TRANSACTION_ABORT);
308 
309 	current->journal_info = ti->ti_save;
310 	if (ti->ti_flags & NILFS_TI_DYNAMIC_ALLOC)
311 		kmem_cache_free(nilfs_transaction_cachep, ti);
312 	sb_end_intwrite(sb);
313 }
314 
315 void nilfs_relax_pressure_in_lock(struct super_block *sb)
316 {
317 	struct the_nilfs *nilfs = sb->s_fs_info;
318 	struct nilfs_sc_info *sci = nilfs->ns_writer;
319 
320 	if (sb_rdonly(sb) || unlikely(!sci) || !sci->sc_flush_request)
321 		return;
322 
323 	set_bit(NILFS_SC_PRIOR_FLUSH, &sci->sc_flags);
324 	up_read(&nilfs->ns_segctor_sem);
325 
326 	down_write(&nilfs->ns_segctor_sem);
327 	if (sci->sc_flush_request &&
328 	    test_bit(NILFS_SC_PRIOR_FLUSH, &sci->sc_flags)) {
329 		struct nilfs_transaction_info *ti = current->journal_info;
330 
331 		ti->ti_flags |= NILFS_TI_WRITER;
332 		nilfs_segctor_do_immediate_flush(sci);
333 		ti->ti_flags &= ~NILFS_TI_WRITER;
334 	}
335 	downgrade_write(&nilfs->ns_segctor_sem);
336 }
337 
338 static void nilfs_transaction_lock(struct super_block *sb,
339 				   struct nilfs_transaction_info *ti,
340 				   int gcflag)
341 {
342 	struct nilfs_transaction_info *cur_ti = current->journal_info;
343 	struct the_nilfs *nilfs = sb->s_fs_info;
344 	struct nilfs_sc_info *sci = nilfs->ns_writer;
345 
346 	WARN_ON(cur_ti);
347 	ti->ti_flags = NILFS_TI_WRITER;
348 	ti->ti_count = 0;
349 	ti->ti_save = cur_ti;
350 	ti->ti_magic = NILFS_TI_MAGIC;
351 	current->journal_info = ti;
352 
353 	for (;;) {
354 		trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
355 			    ti->ti_flags, TRACE_NILFS2_TRANSACTION_TRYLOCK);
356 
357 		down_write(&nilfs->ns_segctor_sem);
358 		if (!test_bit(NILFS_SC_PRIOR_FLUSH, &sci->sc_flags))
359 			break;
360 
361 		nilfs_segctor_do_immediate_flush(sci);
362 
363 		up_write(&nilfs->ns_segctor_sem);
364 		cond_resched();
365 	}
366 	if (gcflag)
367 		ti->ti_flags |= NILFS_TI_GC;
368 
369 	trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
370 			    ti->ti_flags, TRACE_NILFS2_TRANSACTION_LOCK);
371 }
372 
373 static void nilfs_transaction_unlock(struct super_block *sb)
374 {
375 	struct nilfs_transaction_info *ti = current->journal_info;
376 	struct the_nilfs *nilfs = sb->s_fs_info;
377 
378 	BUG_ON(ti == NULL || ti->ti_magic != NILFS_TI_MAGIC);
379 	BUG_ON(ti->ti_count > 0);
380 
381 	up_write(&nilfs->ns_segctor_sem);
382 	current->journal_info = ti->ti_save;
383 
384 	trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
385 			    ti->ti_flags, TRACE_NILFS2_TRANSACTION_UNLOCK);
386 }
387 
388 static void *nilfs_segctor_map_segsum_entry(struct nilfs_sc_info *sci,
389 					    struct nilfs_segsum_pointer *ssp,
390 					    unsigned int bytes)
391 {
392 	struct nilfs_segment_buffer *segbuf = sci->sc_curseg;
393 	unsigned int blocksize = sci->sc_super->s_blocksize;
394 	void *p;
395 
396 	if (unlikely(ssp->offset + bytes > blocksize)) {
397 		ssp->offset = 0;
398 		BUG_ON(NILFS_SEGBUF_BH_IS_LAST(ssp->bh,
399 					       &segbuf->sb_segsum_buffers));
400 		ssp->bh = NILFS_SEGBUF_NEXT_BH(ssp->bh);
401 	}
402 	p = ssp->bh->b_data + ssp->offset;
403 	ssp->offset += bytes;
404 	return p;
405 }
406 
407 /**
408  * nilfs_segctor_reset_segment_buffer - reset the current segment buffer
409  * @sci: nilfs_sc_info
410  */
411 static int nilfs_segctor_reset_segment_buffer(struct nilfs_sc_info *sci)
412 {
413 	struct nilfs_segment_buffer *segbuf = sci->sc_curseg;
414 	struct buffer_head *sumbh;
415 	unsigned int sumbytes;
416 	unsigned int flags = 0;
417 	int err;
418 
419 	if (nilfs_doing_gc())
420 		flags = NILFS_SS_GC;
421 	err = nilfs_segbuf_reset(segbuf, flags, sci->sc_seg_ctime, sci->sc_cno);
422 	if (unlikely(err))
423 		return err;
424 
425 	sumbh = NILFS_SEGBUF_FIRST_BH(&segbuf->sb_segsum_buffers);
426 	sumbytes = segbuf->sb_sum.sumbytes;
427 	sci->sc_finfo_ptr.bh = sumbh;  sci->sc_finfo_ptr.offset = sumbytes;
428 	sci->sc_binfo_ptr.bh = sumbh;  sci->sc_binfo_ptr.offset = sumbytes;
429 	sci->sc_blk_cnt = sci->sc_datablk_cnt = 0;
430 	return 0;
431 }
432 
433 /**
434  * nilfs_segctor_zeropad_segsum - zero pad the rest of the segment summary area
435  * @sci: segment constructor object
436  *
437  * nilfs_segctor_zeropad_segsum() zero-fills unallocated space at the end of
438  * the current segment summary block.
439  */
440 static void nilfs_segctor_zeropad_segsum(struct nilfs_sc_info *sci)
441 {
442 	struct nilfs_segsum_pointer *ssp;
443 
444 	ssp = sci->sc_blk_cnt > 0 ? &sci->sc_binfo_ptr : &sci->sc_finfo_ptr;
445 	if (ssp->offset < ssp->bh->b_size)
446 		memset(ssp->bh->b_data + ssp->offset, 0,
447 		       ssp->bh->b_size - ssp->offset);
448 }
449 
450 static int nilfs_segctor_feed_segment(struct nilfs_sc_info *sci)
451 {
452 	sci->sc_nblk_this_inc += sci->sc_curseg->sb_sum.nblocks;
453 	if (NILFS_SEGBUF_IS_LAST(sci->sc_curseg, &sci->sc_segbufs))
454 		return -E2BIG; /*
455 				* The current segment is filled up
456 				* (internal code)
457 				*/
458 	nilfs_segctor_zeropad_segsum(sci);
459 	sci->sc_curseg = NILFS_NEXT_SEGBUF(sci->sc_curseg);
460 	return nilfs_segctor_reset_segment_buffer(sci);
461 }
462 
463 static int nilfs_segctor_add_super_root(struct nilfs_sc_info *sci)
464 {
465 	struct nilfs_segment_buffer *segbuf = sci->sc_curseg;
466 	int err;
467 
468 	if (segbuf->sb_sum.nblocks >= segbuf->sb_rest_blocks) {
469 		err = nilfs_segctor_feed_segment(sci);
470 		if (err)
471 			return err;
472 		segbuf = sci->sc_curseg;
473 	}
474 	err = nilfs_segbuf_extend_payload(segbuf, &segbuf->sb_super_root);
475 	if (likely(!err))
476 		segbuf->sb_sum.flags |= NILFS_SS_SR;
477 	return err;
478 }
479 
480 /*
481  * Functions for making segment summary and payloads
482  */
483 static int nilfs_segctor_segsum_block_required(
484 	struct nilfs_sc_info *sci, const struct nilfs_segsum_pointer *ssp,
485 	unsigned int binfo_size)
486 {
487 	unsigned int blocksize = sci->sc_super->s_blocksize;
488 	/* Size of finfo and binfo is enough small against blocksize */
489 
490 	return ssp->offset + binfo_size +
491 		(!sci->sc_blk_cnt ? sizeof(struct nilfs_finfo) : 0) >
492 		blocksize;
493 }
494 
495 static void nilfs_segctor_begin_finfo(struct nilfs_sc_info *sci,
496 				      struct inode *inode)
497 {
498 	sci->sc_curseg->sb_sum.nfinfo++;
499 	sci->sc_binfo_ptr = sci->sc_finfo_ptr;
500 	nilfs_segctor_map_segsum_entry(
501 		sci, &sci->sc_binfo_ptr, sizeof(struct nilfs_finfo));
502 
503 	if (NILFS_I(inode)->i_root &&
504 	    !test_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags))
505 		set_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags);
506 	/* skip finfo */
507 }
508 
509 static void nilfs_segctor_end_finfo(struct nilfs_sc_info *sci,
510 				    struct inode *inode)
511 {
512 	struct nilfs_finfo *finfo;
513 	struct nilfs_inode_info *ii;
514 	struct nilfs_segment_buffer *segbuf;
515 	__u64 cno;
516 
517 	if (sci->sc_blk_cnt == 0)
518 		return;
519 
520 	ii = NILFS_I(inode);
521 
522 	if (test_bit(NILFS_I_GCINODE, &ii->i_state))
523 		cno = ii->i_cno;
524 	else if (NILFS_ROOT_METADATA_FILE(inode->i_ino))
525 		cno = 0;
526 	else
527 		cno = sci->sc_cno;
528 
529 	finfo = nilfs_segctor_map_segsum_entry(sci, &sci->sc_finfo_ptr,
530 						 sizeof(*finfo));
531 	finfo->fi_ino = cpu_to_le64(inode->i_ino);
532 	finfo->fi_nblocks = cpu_to_le32(sci->sc_blk_cnt);
533 	finfo->fi_ndatablk = cpu_to_le32(sci->sc_datablk_cnt);
534 	finfo->fi_cno = cpu_to_le64(cno);
535 
536 	segbuf = sci->sc_curseg;
537 	segbuf->sb_sum.sumbytes = sci->sc_binfo_ptr.offset +
538 		sci->sc_super->s_blocksize * (segbuf->sb_sum.nsumblk - 1);
539 	sci->sc_finfo_ptr = sci->sc_binfo_ptr;
540 	sci->sc_blk_cnt = sci->sc_datablk_cnt = 0;
541 }
542 
543 static int nilfs_segctor_add_file_block(struct nilfs_sc_info *sci,
544 					struct buffer_head *bh,
545 					struct inode *inode,
546 					unsigned int binfo_size)
547 {
548 	struct nilfs_segment_buffer *segbuf;
549 	int required, err = 0;
550 
551  retry:
552 	segbuf = sci->sc_curseg;
553 	required = nilfs_segctor_segsum_block_required(
554 		sci, &sci->sc_binfo_ptr, binfo_size);
555 	if (segbuf->sb_sum.nblocks + required + 1 > segbuf->sb_rest_blocks) {
556 		nilfs_segctor_end_finfo(sci, inode);
557 		err = nilfs_segctor_feed_segment(sci);
558 		if (err)
559 			return err;
560 		goto retry;
561 	}
562 	if (unlikely(required)) {
563 		nilfs_segctor_zeropad_segsum(sci);
564 		err = nilfs_segbuf_extend_segsum(segbuf);
565 		if (unlikely(err))
566 			goto failed;
567 	}
568 	if (sci->sc_blk_cnt == 0)
569 		nilfs_segctor_begin_finfo(sci, inode);
570 
571 	nilfs_segctor_map_segsum_entry(sci, &sci->sc_binfo_ptr, binfo_size);
572 	/* Substitution to vblocknr is delayed until update_blocknr() */
573 	nilfs_segbuf_add_file_buffer(segbuf, bh);
574 	sci->sc_blk_cnt++;
575  failed:
576 	return err;
577 }
578 
579 /*
580  * Callback functions that enumerate, mark, and collect dirty blocks
581  */
582 static int nilfs_collect_file_data(struct nilfs_sc_info *sci,
583 				   struct buffer_head *bh, struct inode *inode)
584 {
585 	int err;
586 
587 	err = nilfs_bmap_propagate(NILFS_I(inode)->i_bmap, bh);
588 	if (err < 0)
589 		return err;
590 
591 	err = nilfs_segctor_add_file_block(sci, bh, inode,
592 					   sizeof(struct nilfs_binfo_v));
593 	if (!err)
594 		sci->sc_datablk_cnt++;
595 	return err;
596 }
597 
598 static int nilfs_collect_file_node(struct nilfs_sc_info *sci,
599 				   struct buffer_head *bh,
600 				   struct inode *inode)
601 {
602 	return nilfs_bmap_propagate(NILFS_I(inode)->i_bmap, bh);
603 }
604 
605 static int nilfs_collect_file_bmap(struct nilfs_sc_info *sci,
606 				   struct buffer_head *bh,
607 				   struct inode *inode)
608 {
609 	WARN_ON(!buffer_dirty(bh));
610 	return nilfs_segctor_add_file_block(sci, bh, inode, sizeof(__le64));
611 }
612 
613 static void nilfs_write_file_data_binfo(struct nilfs_sc_info *sci,
614 					struct nilfs_segsum_pointer *ssp,
615 					union nilfs_binfo *binfo)
616 {
617 	struct nilfs_binfo_v *binfo_v = nilfs_segctor_map_segsum_entry(
618 		sci, ssp, sizeof(*binfo_v));
619 	*binfo_v = binfo->bi_v;
620 }
621 
622 static void nilfs_write_file_node_binfo(struct nilfs_sc_info *sci,
623 					struct nilfs_segsum_pointer *ssp,
624 					union nilfs_binfo *binfo)
625 {
626 	__le64 *vblocknr = nilfs_segctor_map_segsum_entry(
627 		sci, ssp, sizeof(*vblocknr));
628 	*vblocknr = binfo->bi_v.bi_vblocknr;
629 }
630 
631 static const struct nilfs_sc_operations nilfs_sc_file_ops = {
632 	.collect_data = nilfs_collect_file_data,
633 	.collect_node = nilfs_collect_file_node,
634 	.collect_bmap = nilfs_collect_file_bmap,
635 	.write_data_binfo = nilfs_write_file_data_binfo,
636 	.write_node_binfo = nilfs_write_file_node_binfo,
637 };
638 
639 static int nilfs_collect_dat_data(struct nilfs_sc_info *sci,
640 				  struct buffer_head *bh, struct inode *inode)
641 {
642 	int err;
643 
644 	err = nilfs_bmap_propagate(NILFS_I(inode)->i_bmap, bh);
645 	if (err < 0)
646 		return err;
647 
648 	err = nilfs_segctor_add_file_block(sci, bh, inode, sizeof(__le64));
649 	if (!err)
650 		sci->sc_datablk_cnt++;
651 	return err;
652 }
653 
654 static int nilfs_collect_dat_bmap(struct nilfs_sc_info *sci,
655 				  struct buffer_head *bh, struct inode *inode)
656 {
657 	WARN_ON(!buffer_dirty(bh));
658 	return nilfs_segctor_add_file_block(sci, bh, inode,
659 					    sizeof(struct nilfs_binfo_dat));
660 }
661 
662 static void nilfs_write_dat_data_binfo(struct nilfs_sc_info *sci,
663 				       struct nilfs_segsum_pointer *ssp,
664 				       union nilfs_binfo *binfo)
665 {
666 	__le64 *blkoff = nilfs_segctor_map_segsum_entry(sci, ssp,
667 							  sizeof(*blkoff));
668 	*blkoff = binfo->bi_dat.bi_blkoff;
669 }
670 
671 static void nilfs_write_dat_node_binfo(struct nilfs_sc_info *sci,
672 				       struct nilfs_segsum_pointer *ssp,
673 				       union nilfs_binfo *binfo)
674 {
675 	struct nilfs_binfo_dat *binfo_dat =
676 		nilfs_segctor_map_segsum_entry(sci, ssp, sizeof(*binfo_dat));
677 	*binfo_dat = binfo->bi_dat;
678 }
679 
680 static const struct nilfs_sc_operations nilfs_sc_dat_ops = {
681 	.collect_data = nilfs_collect_dat_data,
682 	.collect_node = nilfs_collect_file_node,
683 	.collect_bmap = nilfs_collect_dat_bmap,
684 	.write_data_binfo = nilfs_write_dat_data_binfo,
685 	.write_node_binfo = nilfs_write_dat_node_binfo,
686 };
687 
688 static const struct nilfs_sc_operations nilfs_sc_dsync_ops = {
689 	.collect_data = nilfs_collect_file_data,
690 	.collect_node = NULL,
691 	.collect_bmap = NULL,
692 	.write_data_binfo = nilfs_write_file_data_binfo,
693 	.write_node_binfo = NULL,
694 };
695 
696 static size_t nilfs_lookup_dirty_data_buffers(struct inode *inode,
697 					      struct list_head *listp,
698 					      size_t nlimit,
699 					      loff_t start, loff_t end)
700 {
701 	struct address_space *mapping = inode->i_mapping;
702 	struct folio_batch fbatch;
703 	pgoff_t index = 0, last = ULONG_MAX;
704 	size_t ndirties = 0;
705 	int i;
706 
707 	if (unlikely(start != 0 || end != LLONG_MAX)) {
708 		/*
709 		 * A valid range is given for sync-ing data pages. The
710 		 * range is rounded to per-page; extra dirty buffers
711 		 * may be included if blocksize < pagesize.
712 		 */
713 		index = start >> PAGE_SHIFT;
714 		last = end >> PAGE_SHIFT;
715 	}
716 	folio_batch_init(&fbatch);
717  repeat:
718 	if (unlikely(index > last) ||
719 	      !filemap_get_folios_tag(mapping, &index, last,
720 		      PAGECACHE_TAG_DIRTY, &fbatch))
721 		return ndirties;
722 
723 	for (i = 0; i < folio_batch_count(&fbatch); i++) {
724 		struct buffer_head *bh, *head;
725 		struct folio *folio = fbatch.folios[i];
726 
727 		folio_lock(folio);
728 		head = folio_buffers(folio);
729 		if (!head) {
730 			create_empty_buffers(&folio->page, i_blocksize(inode), 0);
731 			head = folio_buffers(folio);
732 		}
733 		folio_unlock(folio);
734 
735 		bh = head;
736 		do {
737 			if (!buffer_dirty(bh) || buffer_async_write(bh))
738 				continue;
739 			get_bh(bh);
740 			list_add_tail(&bh->b_assoc_buffers, listp);
741 			ndirties++;
742 			if (unlikely(ndirties >= nlimit)) {
743 				folio_batch_release(&fbatch);
744 				cond_resched();
745 				return ndirties;
746 			}
747 		} while (bh = bh->b_this_page, bh != head);
748 	}
749 	folio_batch_release(&fbatch);
750 	cond_resched();
751 	goto repeat;
752 }
753 
754 static void nilfs_lookup_dirty_node_buffers(struct inode *inode,
755 					    struct list_head *listp)
756 {
757 	struct nilfs_inode_info *ii = NILFS_I(inode);
758 	struct inode *btnc_inode = ii->i_assoc_inode;
759 	struct folio_batch fbatch;
760 	struct buffer_head *bh, *head;
761 	unsigned int i;
762 	pgoff_t index = 0;
763 
764 	if (!btnc_inode)
765 		return;
766 	folio_batch_init(&fbatch);
767 
768 	while (filemap_get_folios_tag(btnc_inode->i_mapping, &index,
769 				(pgoff_t)-1, PAGECACHE_TAG_DIRTY, &fbatch)) {
770 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
771 			bh = head = folio_buffers(fbatch.folios[i]);
772 			do {
773 				if (buffer_dirty(bh) &&
774 						!buffer_async_write(bh)) {
775 					get_bh(bh);
776 					list_add_tail(&bh->b_assoc_buffers,
777 						      listp);
778 				}
779 				bh = bh->b_this_page;
780 			} while (bh != head);
781 		}
782 		folio_batch_release(&fbatch);
783 		cond_resched();
784 	}
785 }
786 
787 static void nilfs_dispose_list(struct the_nilfs *nilfs,
788 			       struct list_head *head, int force)
789 {
790 	struct nilfs_inode_info *ii, *n;
791 	struct nilfs_inode_info *ivec[SC_N_INODEVEC], **pii;
792 	unsigned int nv = 0;
793 
794 	while (!list_empty(head)) {
795 		spin_lock(&nilfs->ns_inode_lock);
796 		list_for_each_entry_safe(ii, n, head, i_dirty) {
797 			list_del_init(&ii->i_dirty);
798 			if (force) {
799 				if (unlikely(ii->i_bh)) {
800 					brelse(ii->i_bh);
801 					ii->i_bh = NULL;
802 				}
803 			} else if (test_bit(NILFS_I_DIRTY, &ii->i_state)) {
804 				set_bit(NILFS_I_QUEUED, &ii->i_state);
805 				list_add_tail(&ii->i_dirty,
806 					      &nilfs->ns_dirty_files);
807 				continue;
808 			}
809 			ivec[nv++] = ii;
810 			if (nv == SC_N_INODEVEC)
811 				break;
812 		}
813 		spin_unlock(&nilfs->ns_inode_lock);
814 
815 		for (pii = ivec; nv > 0; pii++, nv--)
816 			iput(&(*pii)->vfs_inode);
817 	}
818 }
819 
820 static void nilfs_iput_work_func(struct work_struct *work)
821 {
822 	struct nilfs_sc_info *sci = container_of(work, struct nilfs_sc_info,
823 						 sc_iput_work);
824 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
825 
826 	nilfs_dispose_list(nilfs, &sci->sc_iput_queue, 0);
827 }
828 
829 static int nilfs_test_metadata_dirty(struct the_nilfs *nilfs,
830 				     struct nilfs_root *root)
831 {
832 	int ret = 0;
833 
834 	if (nilfs_mdt_fetch_dirty(root->ifile))
835 		ret++;
836 	if (nilfs_mdt_fetch_dirty(nilfs->ns_cpfile))
837 		ret++;
838 	if (nilfs_mdt_fetch_dirty(nilfs->ns_sufile))
839 		ret++;
840 	if ((ret || nilfs_doing_gc()) && nilfs_mdt_fetch_dirty(nilfs->ns_dat))
841 		ret++;
842 	return ret;
843 }
844 
845 static int nilfs_segctor_clean(struct nilfs_sc_info *sci)
846 {
847 	return list_empty(&sci->sc_dirty_files) &&
848 		!test_bit(NILFS_SC_DIRTY, &sci->sc_flags) &&
849 		sci->sc_nfreesegs == 0 &&
850 		(!nilfs_doing_gc() || list_empty(&sci->sc_gc_inodes));
851 }
852 
853 static int nilfs_segctor_confirm(struct nilfs_sc_info *sci)
854 {
855 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
856 	int ret = 0;
857 
858 	if (nilfs_test_metadata_dirty(nilfs, sci->sc_root))
859 		set_bit(NILFS_SC_DIRTY, &sci->sc_flags);
860 
861 	spin_lock(&nilfs->ns_inode_lock);
862 	if (list_empty(&nilfs->ns_dirty_files) && nilfs_segctor_clean(sci))
863 		ret++;
864 
865 	spin_unlock(&nilfs->ns_inode_lock);
866 	return ret;
867 }
868 
869 static void nilfs_segctor_clear_metadata_dirty(struct nilfs_sc_info *sci)
870 {
871 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
872 
873 	nilfs_mdt_clear_dirty(sci->sc_root->ifile);
874 	nilfs_mdt_clear_dirty(nilfs->ns_cpfile);
875 	nilfs_mdt_clear_dirty(nilfs->ns_sufile);
876 	nilfs_mdt_clear_dirty(nilfs->ns_dat);
877 }
878 
879 static int nilfs_segctor_create_checkpoint(struct nilfs_sc_info *sci)
880 {
881 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
882 	struct buffer_head *bh_cp;
883 	struct nilfs_checkpoint *raw_cp;
884 	int err;
885 
886 	/* XXX: this interface will be changed */
887 	err = nilfs_cpfile_get_checkpoint(nilfs->ns_cpfile, nilfs->ns_cno, 1,
888 					  &raw_cp, &bh_cp);
889 	if (likely(!err)) {
890 		/*
891 		 * The following code is duplicated with cpfile.  But, it is
892 		 * needed to collect the checkpoint even if it was not newly
893 		 * created.
894 		 */
895 		mark_buffer_dirty(bh_cp);
896 		nilfs_mdt_mark_dirty(nilfs->ns_cpfile);
897 		nilfs_cpfile_put_checkpoint(
898 			nilfs->ns_cpfile, nilfs->ns_cno, bh_cp);
899 	} else if (err == -EINVAL || err == -ENOENT) {
900 		nilfs_error(sci->sc_super,
901 			    "checkpoint creation failed due to metadata corruption.");
902 		err = -EIO;
903 	}
904 	return err;
905 }
906 
907 static int nilfs_segctor_fill_in_checkpoint(struct nilfs_sc_info *sci)
908 {
909 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
910 	struct buffer_head *bh_cp;
911 	struct nilfs_checkpoint *raw_cp;
912 	int err;
913 
914 	err = nilfs_cpfile_get_checkpoint(nilfs->ns_cpfile, nilfs->ns_cno, 0,
915 					  &raw_cp, &bh_cp);
916 	if (unlikely(err)) {
917 		if (err == -EINVAL || err == -ENOENT) {
918 			nilfs_error(sci->sc_super,
919 				    "checkpoint finalization failed due to metadata corruption.");
920 			err = -EIO;
921 		}
922 		goto failed_ibh;
923 	}
924 	raw_cp->cp_snapshot_list.ssl_next = 0;
925 	raw_cp->cp_snapshot_list.ssl_prev = 0;
926 	raw_cp->cp_inodes_count =
927 		cpu_to_le64(atomic64_read(&sci->sc_root->inodes_count));
928 	raw_cp->cp_blocks_count =
929 		cpu_to_le64(atomic64_read(&sci->sc_root->blocks_count));
930 	raw_cp->cp_nblk_inc =
931 		cpu_to_le64(sci->sc_nblk_inc + sci->sc_nblk_this_inc);
932 	raw_cp->cp_create = cpu_to_le64(sci->sc_seg_ctime);
933 	raw_cp->cp_cno = cpu_to_le64(nilfs->ns_cno);
934 
935 	if (test_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags))
936 		nilfs_checkpoint_clear_minor(raw_cp);
937 	else
938 		nilfs_checkpoint_set_minor(raw_cp);
939 
940 	nilfs_write_inode_common(sci->sc_root->ifile,
941 				 &raw_cp->cp_ifile_inode, 1);
942 	nilfs_cpfile_put_checkpoint(nilfs->ns_cpfile, nilfs->ns_cno, bh_cp);
943 	return 0;
944 
945  failed_ibh:
946 	return err;
947 }
948 
949 static void nilfs_fill_in_file_bmap(struct inode *ifile,
950 				    struct nilfs_inode_info *ii)
951 
952 {
953 	struct buffer_head *ibh;
954 	struct nilfs_inode *raw_inode;
955 
956 	if (test_bit(NILFS_I_BMAP, &ii->i_state)) {
957 		ibh = ii->i_bh;
958 		BUG_ON(!ibh);
959 		raw_inode = nilfs_ifile_map_inode(ifile, ii->vfs_inode.i_ino,
960 						  ibh);
961 		nilfs_bmap_write(ii->i_bmap, raw_inode);
962 		nilfs_ifile_unmap_inode(ifile, ii->vfs_inode.i_ino, ibh);
963 	}
964 }
965 
966 static void nilfs_segctor_fill_in_file_bmap(struct nilfs_sc_info *sci)
967 {
968 	struct nilfs_inode_info *ii;
969 
970 	list_for_each_entry(ii, &sci->sc_dirty_files, i_dirty) {
971 		nilfs_fill_in_file_bmap(sci->sc_root->ifile, ii);
972 		set_bit(NILFS_I_COLLECTED, &ii->i_state);
973 	}
974 }
975 
976 static void nilfs_segctor_fill_in_super_root(struct nilfs_sc_info *sci,
977 					     struct the_nilfs *nilfs)
978 {
979 	struct buffer_head *bh_sr;
980 	struct nilfs_super_root *raw_sr;
981 	unsigned int isz, srsz;
982 
983 	bh_sr = NILFS_LAST_SEGBUF(&sci->sc_segbufs)->sb_super_root;
984 	raw_sr = (struct nilfs_super_root *)bh_sr->b_data;
985 	isz = nilfs->ns_inode_size;
986 	srsz = NILFS_SR_BYTES(isz);
987 
988 	raw_sr->sr_bytes = cpu_to_le16(srsz);
989 	raw_sr->sr_nongc_ctime
990 		= cpu_to_le64(nilfs_doing_gc() ?
991 			      nilfs->ns_nongc_ctime : sci->sc_seg_ctime);
992 	raw_sr->sr_flags = 0;
993 
994 	nilfs_write_inode_common(nilfs->ns_dat, (void *)raw_sr +
995 				 NILFS_SR_DAT_OFFSET(isz), 1);
996 	nilfs_write_inode_common(nilfs->ns_cpfile, (void *)raw_sr +
997 				 NILFS_SR_CPFILE_OFFSET(isz), 1);
998 	nilfs_write_inode_common(nilfs->ns_sufile, (void *)raw_sr +
999 				 NILFS_SR_SUFILE_OFFSET(isz), 1);
1000 	memset((void *)raw_sr + srsz, 0, nilfs->ns_blocksize - srsz);
1001 }
1002 
1003 static void nilfs_redirty_inodes(struct list_head *head)
1004 {
1005 	struct nilfs_inode_info *ii;
1006 
1007 	list_for_each_entry(ii, head, i_dirty) {
1008 		if (test_bit(NILFS_I_COLLECTED, &ii->i_state))
1009 			clear_bit(NILFS_I_COLLECTED, &ii->i_state);
1010 	}
1011 }
1012 
1013 static void nilfs_drop_collected_inodes(struct list_head *head)
1014 {
1015 	struct nilfs_inode_info *ii;
1016 
1017 	list_for_each_entry(ii, head, i_dirty) {
1018 		if (!test_and_clear_bit(NILFS_I_COLLECTED, &ii->i_state))
1019 			continue;
1020 
1021 		clear_bit(NILFS_I_INODE_SYNC, &ii->i_state);
1022 		set_bit(NILFS_I_UPDATED, &ii->i_state);
1023 	}
1024 }
1025 
1026 static int nilfs_segctor_apply_buffers(struct nilfs_sc_info *sci,
1027 				       struct inode *inode,
1028 				       struct list_head *listp,
1029 				       int (*collect)(struct nilfs_sc_info *,
1030 						      struct buffer_head *,
1031 						      struct inode *))
1032 {
1033 	struct buffer_head *bh, *n;
1034 	int err = 0;
1035 
1036 	if (collect) {
1037 		list_for_each_entry_safe(bh, n, listp, b_assoc_buffers) {
1038 			list_del_init(&bh->b_assoc_buffers);
1039 			err = collect(sci, bh, inode);
1040 			brelse(bh);
1041 			if (unlikely(err))
1042 				goto dispose_buffers;
1043 		}
1044 		return 0;
1045 	}
1046 
1047  dispose_buffers:
1048 	while (!list_empty(listp)) {
1049 		bh = list_first_entry(listp, struct buffer_head,
1050 				      b_assoc_buffers);
1051 		list_del_init(&bh->b_assoc_buffers);
1052 		brelse(bh);
1053 	}
1054 	return err;
1055 }
1056 
1057 static size_t nilfs_segctor_buffer_rest(struct nilfs_sc_info *sci)
1058 {
1059 	/* Remaining number of blocks within segment buffer */
1060 	return sci->sc_segbuf_nblocks -
1061 		(sci->sc_nblk_this_inc + sci->sc_curseg->sb_sum.nblocks);
1062 }
1063 
1064 static int nilfs_segctor_scan_file(struct nilfs_sc_info *sci,
1065 				   struct inode *inode,
1066 				   const struct nilfs_sc_operations *sc_ops)
1067 {
1068 	LIST_HEAD(data_buffers);
1069 	LIST_HEAD(node_buffers);
1070 	int err;
1071 
1072 	if (!(sci->sc_stage.flags & NILFS_CF_NODE)) {
1073 		size_t n, rest = nilfs_segctor_buffer_rest(sci);
1074 
1075 		n = nilfs_lookup_dirty_data_buffers(
1076 			inode, &data_buffers, rest + 1, 0, LLONG_MAX);
1077 		if (n > rest) {
1078 			err = nilfs_segctor_apply_buffers(
1079 				sci, inode, &data_buffers,
1080 				sc_ops->collect_data);
1081 			BUG_ON(!err); /* always receive -E2BIG or true error */
1082 			goto break_or_fail;
1083 		}
1084 	}
1085 	nilfs_lookup_dirty_node_buffers(inode, &node_buffers);
1086 
1087 	if (!(sci->sc_stage.flags & NILFS_CF_NODE)) {
1088 		err = nilfs_segctor_apply_buffers(
1089 			sci, inode, &data_buffers, sc_ops->collect_data);
1090 		if (unlikely(err)) {
1091 			/* dispose node list */
1092 			nilfs_segctor_apply_buffers(
1093 				sci, inode, &node_buffers, NULL);
1094 			goto break_or_fail;
1095 		}
1096 		sci->sc_stage.flags |= NILFS_CF_NODE;
1097 	}
1098 	/* Collect node */
1099 	err = nilfs_segctor_apply_buffers(
1100 		sci, inode, &node_buffers, sc_ops->collect_node);
1101 	if (unlikely(err))
1102 		goto break_or_fail;
1103 
1104 	nilfs_bmap_lookup_dirty_buffers(NILFS_I(inode)->i_bmap, &node_buffers);
1105 	err = nilfs_segctor_apply_buffers(
1106 		sci, inode, &node_buffers, sc_ops->collect_bmap);
1107 	if (unlikely(err))
1108 		goto break_or_fail;
1109 
1110 	nilfs_segctor_end_finfo(sci, inode);
1111 	sci->sc_stage.flags &= ~NILFS_CF_NODE;
1112 
1113  break_or_fail:
1114 	return err;
1115 }
1116 
1117 static int nilfs_segctor_scan_file_dsync(struct nilfs_sc_info *sci,
1118 					 struct inode *inode)
1119 {
1120 	LIST_HEAD(data_buffers);
1121 	size_t n, rest = nilfs_segctor_buffer_rest(sci);
1122 	int err;
1123 
1124 	n = nilfs_lookup_dirty_data_buffers(inode, &data_buffers, rest + 1,
1125 					    sci->sc_dsync_start,
1126 					    sci->sc_dsync_end);
1127 
1128 	err = nilfs_segctor_apply_buffers(sci, inode, &data_buffers,
1129 					  nilfs_collect_file_data);
1130 	if (!err) {
1131 		nilfs_segctor_end_finfo(sci, inode);
1132 		BUG_ON(n > rest);
1133 		/* always receive -E2BIG or true error if n > rest */
1134 	}
1135 	return err;
1136 }
1137 
1138 static int nilfs_segctor_collect_blocks(struct nilfs_sc_info *sci, int mode)
1139 {
1140 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
1141 	struct list_head *head;
1142 	struct nilfs_inode_info *ii;
1143 	size_t ndone;
1144 	int err = 0;
1145 
1146 	switch (nilfs_sc_cstage_get(sci)) {
1147 	case NILFS_ST_INIT:
1148 		/* Pre-processes */
1149 		sci->sc_stage.flags = 0;
1150 
1151 		if (!test_bit(NILFS_SC_UNCLOSED, &sci->sc_flags)) {
1152 			sci->sc_nblk_inc = 0;
1153 			sci->sc_curseg->sb_sum.flags = NILFS_SS_LOGBGN;
1154 			if (mode == SC_LSEG_DSYNC) {
1155 				nilfs_sc_cstage_set(sci, NILFS_ST_DSYNC);
1156 				goto dsync_mode;
1157 			}
1158 		}
1159 
1160 		sci->sc_stage.dirty_file_ptr = NULL;
1161 		sci->sc_stage.gc_inode_ptr = NULL;
1162 		if (mode == SC_FLUSH_DAT) {
1163 			nilfs_sc_cstage_set(sci, NILFS_ST_DAT);
1164 			goto dat_stage;
1165 		}
1166 		nilfs_sc_cstage_inc(sci);
1167 		fallthrough;
1168 	case NILFS_ST_GC:
1169 		if (nilfs_doing_gc()) {
1170 			head = &sci->sc_gc_inodes;
1171 			ii = list_prepare_entry(sci->sc_stage.gc_inode_ptr,
1172 						head, i_dirty);
1173 			list_for_each_entry_continue(ii, head, i_dirty) {
1174 				err = nilfs_segctor_scan_file(
1175 					sci, &ii->vfs_inode,
1176 					&nilfs_sc_file_ops);
1177 				if (unlikely(err)) {
1178 					sci->sc_stage.gc_inode_ptr = list_entry(
1179 						ii->i_dirty.prev,
1180 						struct nilfs_inode_info,
1181 						i_dirty);
1182 					goto break_or_fail;
1183 				}
1184 				set_bit(NILFS_I_COLLECTED, &ii->i_state);
1185 			}
1186 			sci->sc_stage.gc_inode_ptr = NULL;
1187 		}
1188 		nilfs_sc_cstage_inc(sci);
1189 		fallthrough;
1190 	case NILFS_ST_FILE:
1191 		head = &sci->sc_dirty_files;
1192 		ii = list_prepare_entry(sci->sc_stage.dirty_file_ptr, head,
1193 					i_dirty);
1194 		list_for_each_entry_continue(ii, head, i_dirty) {
1195 			clear_bit(NILFS_I_DIRTY, &ii->i_state);
1196 
1197 			err = nilfs_segctor_scan_file(sci, &ii->vfs_inode,
1198 						      &nilfs_sc_file_ops);
1199 			if (unlikely(err)) {
1200 				sci->sc_stage.dirty_file_ptr =
1201 					list_entry(ii->i_dirty.prev,
1202 						   struct nilfs_inode_info,
1203 						   i_dirty);
1204 				goto break_or_fail;
1205 			}
1206 			/* sci->sc_stage.dirty_file_ptr = NILFS_I(inode); */
1207 			/* XXX: required ? */
1208 		}
1209 		sci->sc_stage.dirty_file_ptr = NULL;
1210 		if (mode == SC_FLUSH_FILE) {
1211 			nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1212 			return 0;
1213 		}
1214 		nilfs_sc_cstage_inc(sci);
1215 		sci->sc_stage.flags |= NILFS_CF_IFILE_STARTED;
1216 		fallthrough;
1217 	case NILFS_ST_IFILE:
1218 		err = nilfs_segctor_scan_file(sci, sci->sc_root->ifile,
1219 					      &nilfs_sc_file_ops);
1220 		if (unlikely(err))
1221 			break;
1222 		nilfs_sc_cstage_inc(sci);
1223 		/* Creating a checkpoint */
1224 		err = nilfs_segctor_create_checkpoint(sci);
1225 		if (unlikely(err))
1226 			break;
1227 		fallthrough;
1228 	case NILFS_ST_CPFILE:
1229 		err = nilfs_segctor_scan_file(sci, nilfs->ns_cpfile,
1230 					      &nilfs_sc_file_ops);
1231 		if (unlikely(err))
1232 			break;
1233 		nilfs_sc_cstage_inc(sci);
1234 		fallthrough;
1235 	case NILFS_ST_SUFILE:
1236 		err = nilfs_sufile_freev(nilfs->ns_sufile, sci->sc_freesegs,
1237 					 sci->sc_nfreesegs, &ndone);
1238 		if (unlikely(err)) {
1239 			nilfs_sufile_cancel_freev(nilfs->ns_sufile,
1240 						  sci->sc_freesegs, ndone,
1241 						  NULL);
1242 			break;
1243 		}
1244 		sci->sc_stage.flags |= NILFS_CF_SUFREED;
1245 
1246 		err = nilfs_segctor_scan_file(sci, nilfs->ns_sufile,
1247 					      &nilfs_sc_file_ops);
1248 		if (unlikely(err))
1249 			break;
1250 		nilfs_sc_cstage_inc(sci);
1251 		fallthrough;
1252 	case NILFS_ST_DAT:
1253  dat_stage:
1254 		err = nilfs_segctor_scan_file(sci, nilfs->ns_dat,
1255 					      &nilfs_sc_dat_ops);
1256 		if (unlikely(err))
1257 			break;
1258 		if (mode == SC_FLUSH_DAT) {
1259 			nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1260 			return 0;
1261 		}
1262 		nilfs_sc_cstage_inc(sci);
1263 		fallthrough;
1264 	case NILFS_ST_SR:
1265 		if (mode == SC_LSEG_SR) {
1266 			/* Appending a super root */
1267 			err = nilfs_segctor_add_super_root(sci);
1268 			if (unlikely(err))
1269 				break;
1270 		}
1271 		/* End of a logical segment */
1272 		sci->sc_curseg->sb_sum.flags |= NILFS_SS_LOGEND;
1273 		nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1274 		return 0;
1275 	case NILFS_ST_DSYNC:
1276  dsync_mode:
1277 		sci->sc_curseg->sb_sum.flags |= NILFS_SS_SYNDT;
1278 		ii = sci->sc_dsync_inode;
1279 		if (!test_bit(NILFS_I_BUSY, &ii->i_state))
1280 			break;
1281 
1282 		err = nilfs_segctor_scan_file_dsync(sci, &ii->vfs_inode);
1283 		if (unlikely(err))
1284 			break;
1285 		sci->sc_curseg->sb_sum.flags |= NILFS_SS_LOGEND;
1286 		nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1287 		return 0;
1288 	case NILFS_ST_DONE:
1289 		return 0;
1290 	default:
1291 		BUG();
1292 	}
1293 
1294  break_or_fail:
1295 	return err;
1296 }
1297 
1298 /**
1299  * nilfs_segctor_begin_construction - setup segment buffer to make a new log
1300  * @sci: nilfs_sc_info
1301  * @nilfs: nilfs object
1302  */
1303 static int nilfs_segctor_begin_construction(struct nilfs_sc_info *sci,
1304 					    struct the_nilfs *nilfs)
1305 {
1306 	struct nilfs_segment_buffer *segbuf, *prev;
1307 	__u64 nextnum;
1308 	int err, alloc = 0;
1309 
1310 	segbuf = nilfs_segbuf_new(sci->sc_super);
1311 	if (unlikely(!segbuf))
1312 		return -ENOMEM;
1313 
1314 	if (list_empty(&sci->sc_write_logs)) {
1315 		nilfs_segbuf_map(segbuf, nilfs->ns_segnum,
1316 				 nilfs->ns_pseg_offset, nilfs);
1317 		if (segbuf->sb_rest_blocks < NILFS_PSEG_MIN_BLOCKS) {
1318 			nilfs_shift_to_next_segment(nilfs);
1319 			nilfs_segbuf_map(segbuf, nilfs->ns_segnum, 0, nilfs);
1320 		}
1321 
1322 		segbuf->sb_sum.seg_seq = nilfs->ns_seg_seq;
1323 		nextnum = nilfs->ns_nextnum;
1324 
1325 		if (nilfs->ns_segnum == nilfs->ns_nextnum)
1326 			/* Start from the head of a new full segment */
1327 			alloc++;
1328 	} else {
1329 		/* Continue logs */
1330 		prev = NILFS_LAST_SEGBUF(&sci->sc_write_logs);
1331 		nilfs_segbuf_map_cont(segbuf, prev);
1332 		segbuf->sb_sum.seg_seq = prev->sb_sum.seg_seq;
1333 		nextnum = prev->sb_nextnum;
1334 
1335 		if (segbuf->sb_rest_blocks < NILFS_PSEG_MIN_BLOCKS) {
1336 			nilfs_segbuf_map(segbuf, prev->sb_nextnum, 0, nilfs);
1337 			segbuf->sb_sum.seg_seq++;
1338 			alloc++;
1339 		}
1340 	}
1341 
1342 	err = nilfs_sufile_mark_dirty(nilfs->ns_sufile, segbuf->sb_segnum);
1343 	if (err)
1344 		goto failed;
1345 
1346 	if (alloc) {
1347 		err = nilfs_sufile_alloc(nilfs->ns_sufile, &nextnum);
1348 		if (err)
1349 			goto failed;
1350 	}
1351 	nilfs_segbuf_set_next_segnum(segbuf, nextnum, nilfs);
1352 
1353 	BUG_ON(!list_empty(&sci->sc_segbufs));
1354 	list_add_tail(&segbuf->sb_list, &sci->sc_segbufs);
1355 	sci->sc_segbuf_nblocks = segbuf->sb_rest_blocks;
1356 	return 0;
1357 
1358  failed:
1359 	nilfs_segbuf_free(segbuf);
1360 	return err;
1361 }
1362 
1363 static int nilfs_segctor_extend_segments(struct nilfs_sc_info *sci,
1364 					 struct the_nilfs *nilfs, int nadd)
1365 {
1366 	struct nilfs_segment_buffer *segbuf, *prev;
1367 	struct inode *sufile = nilfs->ns_sufile;
1368 	__u64 nextnextnum;
1369 	LIST_HEAD(list);
1370 	int err, ret, i;
1371 
1372 	prev = NILFS_LAST_SEGBUF(&sci->sc_segbufs);
1373 	/*
1374 	 * Since the segment specified with nextnum might be allocated during
1375 	 * the previous construction, the buffer including its segusage may
1376 	 * not be dirty.  The following call ensures that the buffer is dirty
1377 	 * and will pin the buffer on memory until the sufile is written.
1378 	 */
1379 	err = nilfs_sufile_mark_dirty(sufile, prev->sb_nextnum);
1380 	if (unlikely(err))
1381 		return err;
1382 
1383 	for (i = 0; i < nadd; i++) {
1384 		/* extend segment info */
1385 		err = -ENOMEM;
1386 		segbuf = nilfs_segbuf_new(sci->sc_super);
1387 		if (unlikely(!segbuf))
1388 			goto failed;
1389 
1390 		/* map this buffer to region of segment on-disk */
1391 		nilfs_segbuf_map(segbuf, prev->sb_nextnum, 0, nilfs);
1392 		sci->sc_segbuf_nblocks += segbuf->sb_rest_blocks;
1393 
1394 		/* allocate the next next full segment */
1395 		err = nilfs_sufile_alloc(sufile, &nextnextnum);
1396 		if (unlikely(err))
1397 			goto failed_segbuf;
1398 
1399 		segbuf->sb_sum.seg_seq = prev->sb_sum.seg_seq + 1;
1400 		nilfs_segbuf_set_next_segnum(segbuf, nextnextnum, nilfs);
1401 
1402 		list_add_tail(&segbuf->sb_list, &list);
1403 		prev = segbuf;
1404 	}
1405 	list_splice_tail(&list, &sci->sc_segbufs);
1406 	return 0;
1407 
1408  failed_segbuf:
1409 	nilfs_segbuf_free(segbuf);
1410  failed:
1411 	list_for_each_entry(segbuf, &list, sb_list) {
1412 		ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1413 		WARN_ON(ret); /* never fails */
1414 	}
1415 	nilfs_destroy_logs(&list);
1416 	return err;
1417 }
1418 
1419 static void nilfs_free_incomplete_logs(struct list_head *logs,
1420 				       struct the_nilfs *nilfs)
1421 {
1422 	struct nilfs_segment_buffer *segbuf, *prev;
1423 	struct inode *sufile = nilfs->ns_sufile;
1424 	int ret;
1425 
1426 	segbuf = NILFS_FIRST_SEGBUF(logs);
1427 	if (nilfs->ns_nextnum != segbuf->sb_nextnum) {
1428 		ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1429 		WARN_ON(ret); /* never fails */
1430 	}
1431 	if (atomic_read(&segbuf->sb_err)) {
1432 		/* Case 1: The first segment failed */
1433 		if (segbuf->sb_pseg_start != segbuf->sb_fseg_start)
1434 			/*
1435 			 * Case 1a:  Partial segment appended into an existing
1436 			 * segment
1437 			 */
1438 			nilfs_terminate_segment(nilfs, segbuf->sb_fseg_start,
1439 						segbuf->sb_fseg_end);
1440 		else /* Case 1b:  New full segment */
1441 			set_nilfs_discontinued(nilfs);
1442 	}
1443 
1444 	prev = segbuf;
1445 	list_for_each_entry_continue(segbuf, logs, sb_list) {
1446 		if (prev->sb_nextnum != segbuf->sb_nextnum) {
1447 			ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1448 			WARN_ON(ret); /* never fails */
1449 		}
1450 		if (atomic_read(&segbuf->sb_err) &&
1451 		    segbuf->sb_segnum != nilfs->ns_nextnum)
1452 			/* Case 2: extended segment (!= next) failed */
1453 			nilfs_sufile_set_error(sufile, segbuf->sb_segnum);
1454 		prev = segbuf;
1455 	}
1456 }
1457 
1458 static void nilfs_segctor_update_segusage(struct nilfs_sc_info *sci,
1459 					  struct inode *sufile)
1460 {
1461 	struct nilfs_segment_buffer *segbuf;
1462 	unsigned long live_blocks;
1463 	int ret;
1464 
1465 	list_for_each_entry(segbuf, &sci->sc_segbufs, sb_list) {
1466 		live_blocks = segbuf->sb_sum.nblocks +
1467 			(segbuf->sb_pseg_start - segbuf->sb_fseg_start);
1468 		ret = nilfs_sufile_set_segment_usage(sufile, segbuf->sb_segnum,
1469 						     live_blocks,
1470 						     sci->sc_seg_ctime);
1471 		WARN_ON(ret); /* always succeed because the segusage is dirty */
1472 	}
1473 }
1474 
1475 static void nilfs_cancel_segusage(struct list_head *logs, struct inode *sufile)
1476 {
1477 	struct nilfs_segment_buffer *segbuf;
1478 	int ret;
1479 
1480 	segbuf = NILFS_FIRST_SEGBUF(logs);
1481 	ret = nilfs_sufile_set_segment_usage(sufile, segbuf->sb_segnum,
1482 					     segbuf->sb_pseg_start -
1483 					     segbuf->sb_fseg_start, 0);
1484 	WARN_ON(ret); /* always succeed because the segusage is dirty */
1485 
1486 	list_for_each_entry_continue(segbuf, logs, sb_list) {
1487 		ret = nilfs_sufile_set_segment_usage(sufile, segbuf->sb_segnum,
1488 						     0, 0);
1489 		WARN_ON(ret); /* always succeed */
1490 	}
1491 }
1492 
1493 static void nilfs_segctor_truncate_segments(struct nilfs_sc_info *sci,
1494 					    struct nilfs_segment_buffer *last,
1495 					    struct inode *sufile)
1496 {
1497 	struct nilfs_segment_buffer *segbuf = last;
1498 	int ret;
1499 
1500 	list_for_each_entry_continue(segbuf, &sci->sc_segbufs, sb_list) {
1501 		sci->sc_segbuf_nblocks -= segbuf->sb_rest_blocks;
1502 		ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1503 		WARN_ON(ret);
1504 	}
1505 	nilfs_truncate_logs(&sci->sc_segbufs, last);
1506 }
1507 
1508 
1509 static int nilfs_segctor_collect(struct nilfs_sc_info *sci,
1510 				 struct the_nilfs *nilfs, int mode)
1511 {
1512 	struct nilfs_cstage prev_stage = sci->sc_stage;
1513 	int err, nadd = 1;
1514 
1515 	/* Collection retry loop */
1516 	for (;;) {
1517 		sci->sc_nblk_this_inc = 0;
1518 		sci->sc_curseg = NILFS_FIRST_SEGBUF(&sci->sc_segbufs);
1519 
1520 		err = nilfs_segctor_reset_segment_buffer(sci);
1521 		if (unlikely(err))
1522 			goto failed;
1523 
1524 		err = nilfs_segctor_collect_blocks(sci, mode);
1525 		sci->sc_nblk_this_inc += sci->sc_curseg->sb_sum.nblocks;
1526 		if (!err)
1527 			break;
1528 
1529 		if (unlikely(err != -E2BIG))
1530 			goto failed;
1531 
1532 		/* The current segment is filled up */
1533 		if (mode != SC_LSEG_SR ||
1534 		    nilfs_sc_cstage_get(sci) < NILFS_ST_CPFILE)
1535 			break;
1536 
1537 		nilfs_clear_logs(&sci->sc_segbufs);
1538 
1539 		if (sci->sc_stage.flags & NILFS_CF_SUFREED) {
1540 			err = nilfs_sufile_cancel_freev(nilfs->ns_sufile,
1541 							sci->sc_freesegs,
1542 							sci->sc_nfreesegs,
1543 							NULL);
1544 			WARN_ON(err); /* do not happen */
1545 			sci->sc_stage.flags &= ~NILFS_CF_SUFREED;
1546 		}
1547 
1548 		err = nilfs_segctor_extend_segments(sci, nilfs, nadd);
1549 		if (unlikely(err))
1550 			return err;
1551 
1552 		nadd = min_t(int, nadd << 1, SC_MAX_SEGDELTA);
1553 		sci->sc_stage = prev_stage;
1554 	}
1555 	nilfs_segctor_zeropad_segsum(sci);
1556 	nilfs_segctor_truncate_segments(sci, sci->sc_curseg, nilfs->ns_sufile);
1557 	return 0;
1558 
1559  failed:
1560 	return err;
1561 }
1562 
1563 static void nilfs_list_replace_buffer(struct buffer_head *old_bh,
1564 				      struct buffer_head *new_bh)
1565 {
1566 	BUG_ON(!list_empty(&new_bh->b_assoc_buffers));
1567 
1568 	list_replace_init(&old_bh->b_assoc_buffers, &new_bh->b_assoc_buffers);
1569 	/* The caller must release old_bh */
1570 }
1571 
1572 static int
1573 nilfs_segctor_update_payload_blocknr(struct nilfs_sc_info *sci,
1574 				     struct nilfs_segment_buffer *segbuf,
1575 				     int mode)
1576 {
1577 	struct inode *inode = NULL;
1578 	sector_t blocknr;
1579 	unsigned long nfinfo = segbuf->sb_sum.nfinfo;
1580 	unsigned long nblocks = 0, ndatablk = 0;
1581 	const struct nilfs_sc_operations *sc_op = NULL;
1582 	struct nilfs_segsum_pointer ssp;
1583 	struct nilfs_finfo *finfo = NULL;
1584 	union nilfs_binfo binfo;
1585 	struct buffer_head *bh, *bh_org;
1586 	ino_t ino = 0;
1587 	int err = 0;
1588 
1589 	if (!nfinfo)
1590 		goto out;
1591 
1592 	blocknr = segbuf->sb_pseg_start + segbuf->sb_sum.nsumblk;
1593 	ssp.bh = NILFS_SEGBUF_FIRST_BH(&segbuf->sb_segsum_buffers);
1594 	ssp.offset = sizeof(struct nilfs_segment_summary);
1595 
1596 	list_for_each_entry(bh, &segbuf->sb_payload_buffers, b_assoc_buffers) {
1597 		if (bh == segbuf->sb_super_root)
1598 			break;
1599 		if (!finfo) {
1600 			finfo =	nilfs_segctor_map_segsum_entry(
1601 				sci, &ssp, sizeof(*finfo));
1602 			ino = le64_to_cpu(finfo->fi_ino);
1603 			nblocks = le32_to_cpu(finfo->fi_nblocks);
1604 			ndatablk = le32_to_cpu(finfo->fi_ndatablk);
1605 
1606 			inode = bh->b_folio->mapping->host;
1607 
1608 			if (mode == SC_LSEG_DSYNC)
1609 				sc_op = &nilfs_sc_dsync_ops;
1610 			else if (ino == NILFS_DAT_INO)
1611 				sc_op = &nilfs_sc_dat_ops;
1612 			else /* file blocks */
1613 				sc_op = &nilfs_sc_file_ops;
1614 		}
1615 		bh_org = bh;
1616 		get_bh(bh_org);
1617 		err = nilfs_bmap_assign(NILFS_I(inode)->i_bmap, &bh, blocknr,
1618 					&binfo);
1619 		if (bh != bh_org)
1620 			nilfs_list_replace_buffer(bh_org, bh);
1621 		brelse(bh_org);
1622 		if (unlikely(err))
1623 			goto failed_bmap;
1624 
1625 		if (ndatablk > 0)
1626 			sc_op->write_data_binfo(sci, &ssp, &binfo);
1627 		else
1628 			sc_op->write_node_binfo(sci, &ssp, &binfo);
1629 
1630 		blocknr++;
1631 		if (--nblocks == 0) {
1632 			finfo = NULL;
1633 			if (--nfinfo == 0)
1634 				break;
1635 		} else if (ndatablk > 0)
1636 			ndatablk--;
1637 	}
1638  out:
1639 	return 0;
1640 
1641  failed_bmap:
1642 	return err;
1643 }
1644 
1645 static int nilfs_segctor_assign(struct nilfs_sc_info *sci, int mode)
1646 {
1647 	struct nilfs_segment_buffer *segbuf;
1648 	int err;
1649 
1650 	list_for_each_entry(segbuf, &sci->sc_segbufs, sb_list) {
1651 		err = nilfs_segctor_update_payload_blocknr(sci, segbuf, mode);
1652 		if (unlikely(err))
1653 			return err;
1654 		nilfs_segbuf_fill_in_segsum(segbuf);
1655 	}
1656 	return 0;
1657 }
1658 
1659 static void nilfs_begin_page_io(struct page *page)
1660 {
1661 	if (!page || PageWriteback(page))
1662 		/*
1663 		 * For split b-tree node pages, this function may be called
1664 		 * twice.  We ignore the 2nd or later calls by this check.
1665 		 */
1666 		return;
1667 
1668 	lock_page(page);
1669 	clear_page_dirty_for_io(page);
1670 	set_page_writeback(page);
1671 	unlock_page(page);
1672 }
1673 
1674 static void nilfs_segctor_prepare_write(struct nilfs_sc_info *sci)
1675 {
1676 	struct nilfs_segment_buffer *segbuf;
1677 	struct page *bd_page = NULL, *fs_page = NULL;
1678 
1679 	list_for_each_entry(segbuf, &sci->sc_segbufs, sb_list) {
1680 		struct buffer_head *bh;
1681 
1682 		list_for_each_entry(bh, &segbuf->sb_segsum_buffers,
1683 				    b_assoc_buffers) {
1684 			if (bh->b_page != bd_page) {
1685 				if (bd_page) {
1686 					lock_page(bd_page);
1687 					clear_page_dirty_for_io(bd_page);
1688 					set_page_writeback(bd_page);
1689 					unlock_page(bd_page);
1690 				}
1691 				bd_page = bh->b_page;
1692 			}
1693 		}
1694 
1695 		list_for_each_entry(bh, &segbuf->sb_payload_buffers,
1696 				    b_assoc_buffers) {
1697 			set_buffer_async_write(bh);
1698 			if (bh == segbuf->sb_super_root) {
1699 				if (bh->b_page != bd_page) {
1700 					lock_page(bd_page);
1701 					clear_page_dirty_for_io(bd_page);
1702 					set_page_writeback(bd_page);
1703 					unlock_page(bd_page);
1704 					bd_page = bh->b_page;
1705 				}
1706 				break;
1707 			}
1708 			if (bh->b_page != fs_page) {
1709 				nilfs_begin_page_io(fs_page);
1710 				fs_page = bh->b_page;
1711 			}
1712 		}
1713 	}
1714 	if (bd_page) {
1715 		lock_page(bd_page);
1716 		clear_page_dirty_for_io(bd_page);
1717 		set_page_writeback(bd_page);
1718 		unlock_page(bd_page);
1719 	}
1720 	nilfs_begin_page_io(fs_page);
1721 }
1722 
1723 static int nilfs_segctor_write(struct nilfs_sc_info *sci,
1724 			       struct the_nilfs *nilfs)
1725 {
1726 	int ret;
1727 
1728 	ret = nilfs_write_logs(&sci->sc_segbufs, nilfs);
1729 	list_splice_tail_init(&sci->sc_segbufs, &sci->sc_write_logs);
1730 	return ret;
1731 }
1732 
1733 static void nilfs_end_page_io(struct page *page, int err)
1734 {
1735 	if (!page)
1736 		return;
1737 
1738 	if (buffer_nilfs_node(page_buffers(page)) && !PageWriteback(page)) {
1739 		/*
1740 		 * For b-tree node pages, this function may be called twice
1741 		 * or more because they might be split in a segment.
1742 		 */
1743 		if (PageDirty(page)) {
1744 			/*
1745 			 * For pages holding split b-tree node buffers, dirty
1746 			 * flag on the buffers may be cleared discretely.
1747 			 * In that case, the page is once redirtied for
1748 			 * remaining buffers, and it must be cancelled if
1749 			 * all the buffers get cleaned later.
1750 			 */
1751 			lock_page(page);
1752 			if (nilfs_page_buffers_clean(page))
1753 				__nilfs_clear_page_dirty(page);
1754 			unlock_page(page);
1755 		}
1756 		return;
1757 	}
1758 
1759 	if (!err) {
1760 		if (!nilfs_page_buffers_clean(page))
1761 			__set_page_dirty_nobuffers(page);
1762 		ClearPageError(page);
1763 	} else {
1764 		__set_page_dirty_nobuffers(page);
1765 		SetPageError(page);
1766 	}
1767 
1768 	end_page_writeback(page);
1769 }
1770 
1771 static void nilfs_abort_logs(struct list_head *logs, int err)
1772 {
1773 	struct nilfs_segment_buffer *segbuf;
1774 	struct page *bd_page = NULL, *fs_page = NULL;
1775 	struct buffer_head *bh;
1776 
1777 	if (list_empty(logs))
1778 		return;
1779 
1780 	list_for_each_entry(segbuf, logs, sb_list) {
1781 		list_for_each_entry(bh, &segbuf->sb_segsum_buffers,
1782 				    b_assoc_buffers) {
1783 			if (bh->b_page != bd_page) {
1784 				if (bd_page)
1785 					end_page_writeback(bd_page);
1786 				bd_page = bh->b_page;
1787 			}
1788 		}
1789 
1790 		list_for_each_entry(bh, &segbuf->sb_payload_buffers,
1791 				    b_assoc_buffers) {
1792 			clear_buffer_async_write(bh);
1793 			if (bh == segbuf->sb_super_root) {
1794 				if (bh->b_page != bd_page) {
1795 					end_page_writeback(bd_page);
1796 					bd_page = bh->b_page;
1797 				}
1798 				break;
1799 			}
1800 			if (bh->b_page != fs_page) {
1801 				nilfs_end_page_io(fs_page, err);
1802 				fs_page = bh->b_page;
1803 			}
1804 		}
1805 	}
1806 	if (bd_page)
1807 		end_page_writeback(bd_page);
1808 
1809 	nilfs_end_page_io(fs_page, err);
1810 }
1811 
1812 static void nilfs_segctor_abort_construction(struct nilfs_sc_info *sci,
1813 					     struct the_nilfs *nilfs, int err)
1814 {
1815 	LIST_HEAD(logs);
1816 	int ret;
1817 
1818 	list_splice_tail_init(&sci->sc_write_logs, &logs);
1819 	ret = nilfs_wait_on_logs(&logs);
1820 	nilfs_abort_logs(&logs, ret ? : err);
1821 
1822 	list_splice_tail_init(&sci->sc_segbufs, &logs);
1823 	nilfs_cancel_segusage(&logs, nilfs->ns_sufile);
1824 	nilfs_free_incomplete_logs(&logs, nilfs);
1825 
1826 	if (sci->sc_stage.flags & NILFS_CF_SUFREED) {
1827 		ret = nilfs_sufile_cancel_freev(nilfs->ns_sufile,
1828 						sci->sc_freesegs,
1829 						sci->sc_nfreesegs,
1830 						NULL);
1831 		WARN_ON(ret); /* do not happen */
1832 	}
1833 
1834 	nilfs_destroy_logs(&logs);
1835 }
1836 
1837 static void nilfs_set_next_segment(struct the_nilfs *nilfs,
1838 				   struct nilfs_segment_buffer *segbuf)
1839 {
1840 	nilfs->ns_segnum = segbuf->sb_segnum;
1841 	nilfs->ns_nextnum = segbuf->sb_nextnum;
1842 	nilfs->ns_pseg_offset = segbuf->sb_pseg_start - segbuf->sb_fseg_start
1843 		+ segbuf->sb_sum.nblocks;
1844 	nilfs->ns_seg_seq = segbuf->sb_sum.seg_seq;
1845 	nilfs->ns_ctime = segbuf->sb_sum.ctime;
1846 }
1847 
1848 static void nilfs_segctor_complete_write(struct nilfs_sc_info *sci)
1849 {
1850 	struct nilfs_segment_buffer *segbuf;
1851 	struct page *bd_page = NULL, *fs_page = NULL;
1852 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
1853 	int update_sr = false;
1854 
1855 	list_for_each_entry(segbuf, &sci->sc_write_logs, sb_list) {
1856 		struct buffer_head *bh;
1857 
1858 		list_for_each_entry(bh, &segbuf->sb_segsum_buffers,
1859 				    b_assoc_buffers) {
1860 			set_buffer_uptodate(bh);
1861 			clear_buffer_dirty(bh);
1862 			if (bh->b_page != bd_page) {
1863 				if (bd_page)
1864 					end_page_writeback(bd_page);
1865 				bd_page = bh->b_page;
1866 			}
1867 		}
1868 		/*
1869 		 * We assume that the buffers which belong to the same page
1870 		 * continue over the buffer list.
1871 		 * Under this assumption, the last BHs of pages is
1872 		 * identifiable by the discontinuity of bh->b_page
1873 		 * (page != fs_page).
1874 		 *
1875 		 * For B-tree node blocks, however, this assumption is not
1876 		 * guaranteed.  The cleanup code of B-tree node pages needs
1877 		 * special care.
1878 		 */
1879 		list_for_each_entry(bh, &segbuf->sb_payload_buffers,
1880 				    b_assoc_buffers) {
1881 			const unsigned long set_bits = BIT(BH_Uptodate);
1882 			const unsigned long clear_bits =
1883 				(BIT(BH_Dirty) | BIT(BH_Async_Write) |
1884 				 BIT(BH_Delay) | BIT(BH_NILFS_Volatile) |
1885 				 BIT(BH_NILFS_Redirected));
1886 
1887 			set_mask_bits(&bh->b_state, clear_bits, set_bits);
1888 			if (bh == segbuf->sb_super_root) {
1889 				if (bh->b_page != bd_page) {
1890 					end_page_writeback(bd_page);
1891 					bd_page = bh->b_page;
1892 				}
1893 				update_sr = true;
1894 				break;
1895 			}
1896 			if (bh->b_page != fs_page) {
1897 				nilfs_end_page_io(fs_page, 0);
1898 				fs_page = bh->b_page;
1899 			}
1900 		}
1901 
1902 		if (!nilfs_segbuf_simplex(segbuf)) {
1903 			if (segbuf->sb_sum.flags & NILFS_SS_LOGBGN) {
1904 				set_bit(NILFS_SC_UNCLOSED, &sci->sc_flags);
1905 				sci->sc_lseg_stime = jiffies;
1906 			}
1907 			if (segbuf->sb_sum.flags & NILFS_SS_LOGEND)
1908 				clear_bit(NILFS_SC_UNCLOSED, &sci->sc_flags);
1909 		}
1910 	}
1911 	/*
1912 	 * Since pages may continue over multiple segment buffers,
1913 	 * end of the last page must be checked outside of the loop.
1914 	 */
1915 	if (bd_page)
1916 		end_page_writeback(bd_page);
1917 
1918 	nilfs_end_page_io(fs_page, 0);
1919 
1920 	nilfs_drop_collected_inodes(&sci->sc_dirty_files);
1921 
1922 	if (nilfs_doing_gc())
1923 		nilfs_drop_collected_inodes(&sci->sc_gc_inodes);
1924 	else
1925 		nilfs->ns_nongc_ctime = sci->sc_seg_ctime;
1926 
1927 	sci->sc_nblk_inc += sci->sc_nblk_this_inc;
1928 
1929 	segbuf = NILFS_LAST_SEGBUF(&sci->sc_write_logs);
1930 	nilfs_set_next_segment(nilfs, segbuf);
1931 
1932 	if (update_sr) {
1933 		nilfs->ns_flushed_device = 0;
1934 		nilfs_set_last_segment(nilfs, segbuf->sb_pseg_start,
1935 				       segbuf->sb_sum.seg_seq, nilfs->ns_cno++);
1936 
1937 		clear_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags);
1938 		clear_bit(NILFS_SC_DIRTY, &sci->sc_flags);
1939 		set_bit(NILFS_SC_SUPER_ROOT, &sci->sc_flags);
1940 		nilfs_segctor_clear_metadata_dirty(sci);
1941 	} else
1942 		clear_bit(NILFS_SC_SUPER_ROOT, &sci->sc_flags);
1943 }
1944 
1945 static int nilfs_segctor_wait(struct nilfs_sc_info *sci)
1946 {
1947 	int ret;
1948 
1949 	ret = nilfs_wait_on_logs(&sci->sc_write_logs);
1950 	if (!ret) {
1951 		nilfs_segctor_complete_write(sci);
1952 		nilfs_destroy_logs(&sci->sc_write_logs);
1953 	}
1954 	return ret;
1955 }
1956 
1957 static int nilfs_segctor_collect_dirty_files(struct nilfs_sc_info *sci,
1958 					     struct the_nilfs *nilfs)
1959 {
1960 	struct nilfs_inode_info *ii, *n;
1961 	struct inode *ifile = sci->sc_root->ifile;
1962 
1963 	spin_lock(&nilfs->ns_inode_lock);
1964  retry:
1965 	list_for_each_entry_safe(ii, n, &nilfs->ns_dirty_files, i_dirty) {
1966 		if (!ii->i_bh) {
1967 			struct buffer_head *ibh;
1968 			int err;
1969 
1970 			spin_unlock(&nilfs->ns_inode_lock);
1971 			err = nilfs_ifile_get_inode_block(
1972 				ifile, ii->vfs_inode.i_ino, &ibh);
1973 			if (unlikely(err)) {
1974 				nilfs_warn(sci->sc_super,
1975 					   "log writer: error %d getting inode block (ino=%lu)",
1976 					   err, ii->vfs_inode.i_ino);
1977 				return err;
1978 			}
1979 			spin_lock(&nilfs->ns_inode_lock);
1980 			if (likely(!ii->i_bh))
1981 				ii->i_bh = ibh;
1982 			else
1983 				brelse(ibh);
1984 			goto retry;
1985 		}
1986 
1987 		// Always redirty the buffer to avoid race condition
1988 		mark_buffer_dirty(ii->i_bh);
1989 		nilfs_mdt_mark_dirty(ifile);
1990 
1991 		clear_bit(NILFS_I_QUEUED, &ii->i_state);
1992 		set_bit(NILFS_I_BUSY, &ii->i_state);
1993 		list_move_tail(&ii->i_dirty, &sci->sc_dirty_files);
1994 	}
1995 	spin_unlock(&nilfs->ns_inode_lock);
1996 
1997 	return 0;
1998 }
1999 
2000 static void nilfs_segctor_drop_written_files(struct nilfs_sc_info *sci,
2001 					     struct the_nilfs *nilfs)
2002 {
2003 	struct nilfs_inode_info *ii, *n;
2004 	int during_mount = !(sci->sc_super->s_flags & SB_ACTIVE);
2005 	int defer_iput = false;
2006 
2007 	spin_lock(&nilfs->ns_inode_lock);
2008 	list_for_each_entry_safe(ii, n, &sci->sc_dirty_files, i_dirty) {
2009 		if (!test_and_clear_bit(NILFS_I_UPDATED, &ii->i_state) ||
2010 		    test_bit(NILFS_I_DIRTY, &ii->i_state))
2011 			continue;
2012 
2013 		clear_bit(NILFS_I_BUSY, &ii->i_state);
2014 		brelse(ii->i_bh);
2015 		ii->i_bh = NULL;
2016 		list_del_init(&ii->i_dirty);
2017 		if (!ii->vfs_inode.i_nlink || during_mount) {
2018 			/*
2019 			 * Defer calling iput() to avoid deadlocks if
2020 			 * i_nlink == 0 or mount is not yet finished.
2021 			 */
2022 			list_add_tail(&ii->i_dirty, &sci->sc_iput_queue);
2023 			defer_iput = true;
2024 		} else {
2025 			spin_unlock(&nilfs->ns_inode_lock);
2026 			iput(&ii->vfs_inode);
2027 			spin_lock(&nilfs->ns_inode_lock);
2028 		}
2029 	}
2030 	spin_unlock(&nilfs->ns_inode_lock);
2031 
2032 	if (defer_iput)
2033 		schedule_work(&sci->sc_iput_work);
2034 }
2035 
2036 /*
2037  * Main procedure of segment constructor
2038  */
2039 static int nilfs_segctor_do_construct(struct nilfs_sc_info *sci, int mode)
2040 {
2041 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
2042 	int err;
2043 
2044 	if (sb_rdonly(sci->sc_super))
2045 		return -EROFS;
2046 
2047 	nilfs_sc_cstage_set(sci, NILFS_ST_INIT);
2048 	sci->sc_cno = nilfs->ns_cno;
2049 
2050 	err = nilfs_segctor_collect_dirty_files(sci, nilfs);
2051 	if (unlikely(err))
2052 		goto out;
2053 
2054 	if (nilfs_test_metadata_dirty(nilfs, sci->sc_root))
2055 		set_bit(NILFS_SC_DIRTY, &sci->sc_flags);
2056 
2057 	if (nilfs_segctor_clean(sci))
2058 		goto out;
2059 
2060 	do {
2061 		sci->sc_stage.flags &= ~NILFS_CF_HISTORY_MASK;
2062 
2063 		err = nilfs_segctor_begin_construction(sci, nilfs);
2064 		if (unlikely(err))
2065 			goto out;
2066 
2067 		/* Update time stamp */
2068 		sci->sc_seg_ctime = ktime_get_real_seconds();
2069 
2070 		err = nilfs_segctor_collect(sci, nilfs, mode);
2071 		if (unlikely(err))
2072 			goto failed;
2073 
2074 		/* Avoid empty segment */
2075 		if (nilfs_sc_cstage_get(sci) == NILFS_ST_DONE &&
2076 		    nilfs_segbuf_empty(sci->sc_curseg)) {
2077 			nilfs_segctor_abort_construction(sci, nilfs, 1);
2078 			goto out;
2079 		}
2080 
2081 		err = nilfs_segctor_assign(sci, mode);
2082 		if (unlikely(err))
2083 			goto failed;
2084 
2085 		if (sci->sc_stage.flags & NILFS_CF_IFILE_STARTED)
2086 			nilfs_segctor_fill_in_file_bmap(sci);
2087 
2088 		if (mode == SC_LSEG_SR &&
2089 		    nilfs_sc_cstage_get(sci) >= NILFS_ST_CPFILE) {
2090 			err = nilfs_segctor_fill_in_checkpoint(sci);
2091 			if (unlikely(err))
2092 				goto failed_to_write;
2093 
2094 			nilfs_segctor_fill_in_super_root(sci, nilfs);
2095 		}
2096 		nilfs_segctor_update_segusage(sci, nilfs->ns_sufile);
2097 
2098 		/* Write partial segments */
2099 		nilfs_segctor_prepare_write(sci);
2100 
2101 		nilfs_add_checksums_on_logs(&sci->sc_segbufs,
2102 					    nilfs->ns_crc_seed);
2103 
2104 		err = nilfs_segctor_write(sci, nilfs);
2105 		if (unlikely(err))
2106 			goto failed_to_write;
2107 
2108 		if (nilfs_sc_cstage_get(sci) == NILFS_ST_DONE ||
2109 		    nilfs->ns_blocksize_bits != PAGE_SHIFT) {
2110 			/*
2111 			 * At this point, we avoid double buffering
2112 			 * for blocksize < pagesize because page dirty
2113 			 * flag is turned off during write and dirty
2114 			 * buffers are not properly collected for
2115 			 * pages crossing over segments.
2116 			 */
2117 			err = nilfs_segctor_wait(sci);
2118 			if (err)
2119 				goto failed_to_write;
2120 		}
2121 	} while (nilfs_sc_cstage_get(sci) != NILFS_ST_DONE);
2122 
2123  out:
2124 	nilfs_segctor_drop_written_files(sci, nilfs);
2125 	return err;
2126 
2127  failed_to_write:
2128 	if (sci->sc_stage.flags & NILFS_CF_IFILE_STARTED)
2129 		nilfs_redirty_inodes(&sci->sc_dirty_files);
2130 
2131  failed:
2132 	if (nilfs_doing_gc())
2133 		nilfs_redirty_inodes(&sci->sc_gc_inodes);
2134 	nilfs_segctor_abort_construction(sci, nilfs, err);
2135 	goto out;
2136 }
2137 
2138 /**
2139  * nilfs_segctor_start_timer - set timer of background write
2140  * @sci: nilfs_sc_info
2141  *
2142  * If the timer has already been set, it ignores the new request.
2143  * This function MUST be called within a section locking the segment
2144  * semaphore.
2145  */
2146 static void nilfs_segctor_start_timer(struct nilfs_sc_info *sci)
2147 {
2148 	spin_lock(&sci->sc_state_lock);
2149 	if (!(sci->sc_state & NILFS_SEGCTOR_COMMIT)) {
2150 		sci->sc_timer.expires = jiffies + sci->sc_interval;
2151 		add_timer(&sci->sc_timer);
2152 		sci->sc_state |= NILFS_SEGCTOR_COMMIT;
2153 	}
2154 	spin_unlock(&sci->sc_state_lock);
2155 }
2156 
2157 static void nilfs_segctor_do_flush(struct nilfs_sc_info *sci, int bn)
2158 {
2159 	spin_lock(&sci->sc_state_lock);
2160 	if (!(sci->sc_flush_request & BIT(bn))) {
2161 		unsigned long prev_req = sci->sc_flush_request;
2162 
2163 		sci->sc_flush_request |= BIT(bn);
2164 		if (!prev_req)
2165 			wake_up(&sci->sc_wait_daemon);
2166 	}
2167 	spin_unlock(&sci->sc_state_lock);
2168 }
2169 
2170 /**
2171  * nilfs_flush_segment - trigger a segment construction for resource control
2172  * @sb: super block
2173  * @ino: inode number of the file to be flushed out.
2174  */
2175 void nilfs_flush_segment(struct super_block *sb, ino_t ino)
2176 {
2177 	struct the_nilfs *nilfs = sb->s_fs_info;
2178 	struct nilfs_sc_info *sci = nilfs->ns_writer;
2179 
2180 	if (!sci || nilfs_doing_construction())
2181 		return;
2182 	nilfs_segctor_do_flush(sci, NILFS_MDT_INODE(sb, ino) ? ino : 0);
2183 					/* assign bit 0 to data files */
2184 }
2185 
2186 struct nilfs_segctor_wait_request {
2187 	wait_queue_entry_t	wq;
2188 	__u32		seq;
2189 	int		err;
2190 	atomic_t	done;
2191 };
2192 
2193 static int nilfs_segctor_sync(struct nilfs_sc_info *sci)
2194 {
2195 	struct nilfs_segctor_wait_request wait_req;
2196 	int err = 0;
2197 
2198 	spin_lock(&sci->sc_state_lock);
2199 	init_wait(&wait_req.wq);
2200 	wait_req.err = 0;
2201 	atomic_set(&wait_req.done, 0);
2202 	wait_req.seq = ++sci->sc_seq_request;
2203 	spin_unlock(&sci->sc_state_lock);
2204 
2205 	init_waitqueue_entry(&wait_req.wq, current);
2206 	add_wait_queue(&sci->sc_wait_request, &wait_req.wq);
2207 	set_current_state(TASK_INTERRUPTIBLE);
2208 	wake_up(&sci->sc_wait_daemon);
2209 
2210 	for (;;) {
2211 		if (atomic_read(&wait_req.done)) {
2212 			err = wait_req.err;
2213 			break;
2214 		}
2215 		if (!signal_pending(current)) {
2216 			schedule();
2217 			continue;
2218 		}
2219 		err = -ERESTARTSYS;
2220 		break;
2221 	}
2222 	finish_wait(&sci->sc_wait_request, &wait_req.wq);
2223 	return err;
2224 }
2225 
2226 static void nilfs_segctor_wakeup(struct nilfs_sc_info *sci, int err)
2227 {
2228 	struct nilfs_segctor_wait_request *wrq, *n;
2229 	unsigned long flags;
2230 
2231 	spin_lock_irqsave(&sci->sc_wait_request.lock, flags);
2232 	list_for_each_entry_safe(wrq, n, &sci->sc_wait_request.head, wq.entry) {
2233 		if (!atomic_read(&wrq->done) &&
2234 		    nilfs_cnt32_ge(sci->sc_seq_done, wrq->seq)) {
2235 			wrq->err = err;
2236 			atomic_set(&wrq->done, 1);
2237 		}
2238 		if (atomic_read(&wrq->done)) {
2239 			wrq->wq.func(&wrq->wq,
2240 				     TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2241 				     0, NULL);
2242 		}
2243 	}
2244 	spin_unlock_irqrestore(&sci->sc_wait_request.lock, flags);
2245 }
2246 
2247 /**
2248  * nilfs_construct_segment - construct a logical segment
2249  * @sb: super block
2250  *
2251  * Return Value: On success, 0 is returned. On errors, one of the following
2252  * negative error code is returned.
2253  *
2254  * %-EROFS - Read only filesystem.
2255  *
2256  * %-EIO - I/O error
2257  *
2258  * %-ENOSPC - No space left on device (only in a panic state).
2259  *
2260  * %-ERESTARTSYS - Interrupted.
2261  *
2262  * %-ENOMEM - Insufficient memory available.
2263  */
2264 int nilfs_construct_segment(struct super_block *sb)
2265 {
2266 	struct the_nilfs *nilfs = sb->s_fs_info;
2267 	struct nilfs_sc_info *sci = nilfs->ns_writer;
2268 	struct nilfs_transaction_info *ti;
2269 
2270 	if (sb_rdonly(sb) || unlikely(!sci))
2271 		return -EROFS;
2272 
2273 	/* A call inside transactions causes a deadlock. */
2274 	BUG_ON((ti = current->journal_info) && ti->ti_magic == NILFS_TI_MAGIC);
2275 
2276 	return nilfs_segctor_sync(sci);
2277 }
2278 
2279 /**
2280  * nilfs_construct_dsync_segment - construct a data-only logical segment
2281  * @sb: super block
2282  * @inode: inode whose data blocks should be written out
2283  * @start: start byte offset
2284  * @end: end byte offset (inclusive)
2285  *
2286  * Return Value: On success, 0 is returned. On errors, one of the following
2287  * negative error code is returned.
2288  *
2289  * %-EROFS - Read only filesystem.
2290  *
2291  * %-EIO - I/O error
2292  *
2293  * %-ENOSPC - No space left on device (only in a panic state).
2294  *
2295  * %-ERESTARTSYS - Interrupted.
2296  *
2297  * %-ENOMEM - Insufficient memory available.
2298  */
2299 int nilfs_construct_dsync_segment(struct super_block *sb, struct inode *inode,
2300 				  loff_t start, loff_t end)
2301 {
2302 	struct the_nilfs *nilfs = sb->s_fs_info;
2303 	struct nilfs_sc_info *sci = nilfs->ns_writer;
2304 	struct nilfs_inode_info *ii;
2305 	struct nilfs_transaction_info ti;
2306 	int err = 0;
2307 
2308 	if (sb_rdonly(sb) || unlikely(!sci))
2309 		return -EROFS;
2310 
2311 	nilfs_transaction_lock(sb, &ti, 0);
2312 
2313 	ii = NILFS_I(inode);
2314 	if (test_bit(NILFS_I_INODE_SYNC, &ii->i_state) ||
2315 	    nilfs_test_opt(nilfs, STRICT_ORDER) ||
2316 	    test_bit(NILFS_SC_UNCLOSED, &sci->sc_flags) ||
2317 	    nilfs_discontinued(nilfs)) {
2318 		nilfs_transaction_unlock(sb);
2319 		err = nilfs_segctor_sync(sci);
2320 		return err;
2321 	}
2322 
2323 	spin_lock(&nilfs->ns_inode_lock);
2324 	if (!test_bit(NILFS_I_QUEUED, &ii->i_state) &&
2325 	    !test_bit(NILFS_I_BUSY, &ii->i_state)) {
2326 		spin_unlock(&nilfs->ns_inode_lock);
2327 		nilfs_transaction_unlock(sb);
2328 		return 0;
2329 	}
2330 	spin_unlock(&nilfs->ns_inode_lock);
2331 	sci->sc_dsync_inode = ii;
2332 	sci->sc_dsync_start = start;
2333 	sci->sc_dsync_end = end;
2334 
2335 	err = nilfs_segctor_do_construct(sci, SC_LSEG_DSYNC);
2336 	if (!err)
2337 		nilfs->ns_flushed_device = 0;
2338 
2339 	nilfs_transaction_unlock(sb);
2340 	return err;
2341 }
2342 
2343 #define FLUSH_FILE_BIT	(0x1) /* data file only */
2344 #define FLUSH_DAT_BIT	BIT(NILFS_DAT_INO) /* DAT only */
2345 
2346 /**
2347  * nilfs_segctor_accept - record accepted sequence count of log-write requests
2348  * @sci: segment constructor object
2349  */
2350 static void nilfs_segctor_accept(struct nilfs_sc_info *sci)
2351 {
2352 	spin_lock(&sci->sc_state_lock);
2353 	sci->sc_seq_accepted = sci->sc_seq_request;
2354 	spin_unlock(&sci->sc_state_lock);
2355 	del_timer_sync(&sci->sc_timer);
2356 }
2357 
2358 /**
2359  * nilfs_segctor_notify - notify the result of request to caller threads
2360  * @sci: segment constructor object
2361  * @mode: mode of log forming
2362  * @err: error code to be notified
2363  */
2364 static void nilfs_segctor_notify(struct nilfs_sc_info *sci, int mode, int err)
2365 {
2366 	/* Clear requests (even when the construction failed) */
2367 	spin_lock(&sci->sc_state_lock);
2368 
2369 	if (mode == SC_LSEG_SR) {
2370 		sci->sc_state &= ~NILFS_SEGCTOR_COMMIT;
2371 		sci->sc_seq_done = sci->sc_seq_accepted;
2372 		nilfs_segctor_wakeup(sci, err);
2373 		sci->sc_flush_request = 0;
2374 	} else {
2375 		if (mode == SC_FLUSH_FILE)
2376 			sci->sc_flush_request &= ~FLUSH_FILE_BIT;
2377 		else if (mode == SC_FLUSH_DAT)
2378 			sci->sc_flush_request &= ~FLUSH_DAT_BIT;
2379 
2380 		/* re-enable timer if checkpoint creation was not done */
2381 		if ((sci->sc_state & NILFS_SEGCTOR_COMMIT) &&
2382 		    time_before(jiffies, sci->sc_timer.expires))
2383 			add_timer(&sci->sc_timer);
2384 	}
2385 	spin_unlock(&sci->sc_state_lock);
2386 }
2387 
2388 /**
2389  * nilfs_segctor_construct - form logs and write them to disk
2390  * @sci: segment constructor object
2391  * @mode: mode of log forming
2392  */
2393 static int nilfs_segctor_construct(struct nilfs_sc_info *sci, int mode)
2394 {
2395 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
2396 	struct nilfs_super_block **sbp;
2397 	int err = 0;
2398 
2399 	nilfs_segctor_accept(sci);
2400 
2401 	if (nilfs_discontinued(nilfs))
2402 		mode = SC_LSEG_SR;
2403 	if (!nilfs_segctor_confirm(sci))
2404 		err = nilfs_segctor_do_construct(sci, mode);
2405 
2406 	if (likely(!err)) {
2407 		if (mode != SC_FLUSH_DAT)
2408 			atomic_set(&nilfs->ns_ndirtyblks, 0);
2409 		if (test_bit(NILFS_SC_SUPER_ROOT, &sci->sc_flags) &&
2410 		    nilfs_discontinued(nilfs)) {
2411 			down_write(&nilfs->ns_sem);
2412 			err = -EIO;
2413 			sbp = nilfs_prepare_super(sci->sc_super,
2414 						  nilfs_sb_will_flip(nilfs));
2415 			if (likely(sbp)) {
2416 				nilfs_set_log_cursor(sbp[0], nilfs);
2417 				err = nilfs_commit_super(sci->sc_super,
2418 							 NILFS_SB_COMMIT);
2419 			}
2420 			up_write(&nilfs->ns_sem);
2421 		}
2422 	}
2423 
2424 	nilfs_segctor_notify(sci, mode, err);
2425 	return err;
2426 }
2427 
2428 static void nilfs_construction_timeout(struct timer_list *t)
2429 {
2430 	struct nilfs_sc_info *sci = from_timer(sci, t, sc_timer);
2431 
2432 	wake_up_process(sci->sc_timer_task);
2433 }
2434 
2435 static void
2436 nilfs_remove_written_gcinodes(struct the_nilfs *nilfs, struct list_head *head)
2437 {
2438 	struct nilfs_inode_info *ii, *n;
2439 
2440 	list_for_each_entry_safe(ii, n, head, i_dirty) {
2441 		if (!test_bit(NILFS_I_UPDATED, &ii->i_state))
2442 			continue;
2443 		list_del_init(&ii->i_dirty);
2444 		truncate_inode_pages(&ii->vfs_inode.i_data, 0);
2445 		nilfs_btnode_cache_clear(ii->i_assoc_inode->i_mapping);
2446 		iput(&ii->vfs_inode);
2447 	}
2448 }
2449 
2450 int nilfs_clean_segments(struct super_block *sb, struct nilfs_argv *argv,
2451 			 void **kbufs)
2452 {
2453 	struct the_nilfs *nilfs = sb->s_fs_info;
2454 	struct nilfs_sc_info *sci = nilfs->ns_writer;
2455 	struct nilfs_transaction_info ti;
2456 	int err;
2457 
2458 	if (unlikely(!sci))
2459 		return -EROFS;
2460 
2461 	nilfs_transaction_lock(sb, &ti, 1);
2462 
2463 	err = nilfs_mdt_save_to_shadow_map(nilfs->ns_dat);
2464 	if (unlikely(err))
2465 		goto out_unlock;
2466 
2467 	err = nilfs_ioctl_prepare_clean_segments(nilfs, argv, kbufs);
2468 	if (unlikely(err)) {
2469 		nilfs_mdt_restore_from_shadow_map(nilfs->ns_dat);
2470 		goto out_unlock;
2471 	}
2472 
2473 	sci->sc_freesegs = kbufs[4];
2474 	sci->sc_nfreesegs = argv[4].v_nmembs;
2475 	list_splice_tail_init(&nilfs->ns_gc_inodes, &sci->sc_gc_inodes);
2476 
2477 	for (;;) {
2478 		err = nilfs_segctor_construct(sci, SC_LSEG_SR);
2479 		nilfs_remove_written_gcinodes(nilfs, &sci->sc_gc_inodes);
2480 
2481 		if (likely(!err))
2482 			break;
2483 
2484 		nilfs_warn(sb, "error %d cleaning segments", err);
2485 		set_current_state(TASK_INTERRUPTIBLE);
2486 		schedule_timeout(sci->sc_interval);
2487 	}
2488 	if (nilfs_test_opt(nilfs, DISCARD)) {
2489 		int ret = nilfs_discard_segments(nilfs, sci->sc_freesegs,
2490 						 sci->sc_nfreesegs);
2491 		if (ret) {
2492 			nilfs_warn(sb,
2493 				   "error %d on discard request, turning discards off for the device",
2494 				   ret);
2495 			nilfs_clear_opt(nilfs, DISCARD);
2496 		}
2497 	}
2498 
2499  out_unlock:
2500 	sci->sc_freesegs = NULL;
2501 	sci->sc_nfreesegs = 0;
2502 	nilfs_mdt_clear_shadow_map(nilfs->ns_dat);
2503 	nilfs_transaction_unlock(sb);
2504 	return err;
2505 }
2506 
2507 static void nilfs_segctor_thread_construct(struct nilfs_sc_info *sci, int mode)
2508 {
2509 	struct nilfs_transaction_info ti;
2510 
2511 	nilfs_transaction_lock(sci->sc_super, &ti, 0);
2512 	nilfs_segctor_construct(sci, mode);
2513 
2514 	/*
2515 	 * Unclosed segment should be retried.  We do this using sc_timer.
2516 	 * Timeout of sc_timer will invoke complete construction which leads
2517 	 * to close the current logical segment.
2518 	 */
2519 	if (test_bit(NILFS_SC_UNCLOSED, &sci->sc_flags))
2520 		nilfs_segctor_start_timer(sci);
2521 
2522 	nilfs_transaction_unlock(sci->sc_super);
2523 }
2524 
2525 static void nilfs_segctor_do_immediate_flush(struct nilfs_sc_info *sci)
2526 {
2527 	int mode = 0;
2528 
2529 	spin_lock(&sci->sc_state_lock);
2530 	mode = (sci->sc_flush_request & FLUSH_DAT_BIT) ?
2531 		SC_FLUSH_DAT : SC_FLUSH_FILE;
2532 	spin_unlock(&sci->sc_state_lock);
2533 
2534 	if (mode) {
2535 		nilfs_segctor_do_construct(sci, mode);
2536 
2537 		spin_lock(&sci->sc_state_lock);
2538 		sci->sc_flush_request &= (mode == SC_FLUSH_FILE) ?
2539 			~FLUSH_FILE_BIT : ~FLUSH_DAT_BIT;
2540 		spin_unlock(&sci->sc_state_lock);
2541 	}
2542 	clear_bit(NILFS_SC_PRIOR_FLUSH, &sci->sc_flags);
2543 }
2544 
2545 static int nilfs_segctor_flush_mode(struct nilfs_sc_info *sci)
2546 {
2547 	if (!test_bit(NILFS_SC_UNCLOSED, &sci->sc_flags) ||
2548 	    time_before(jiffies, sci->sc_lseg_stime + sci->sc_mjcp_freq)) {
2549 		if (!(sci->sc_flush_request & ~FLUSH_FILE_BIT))
2550 			return SC_FLUSH_FILE;
2551 		else if (!(sci->sc_flush_request & ~FLUSH_DAT_BIT))
2552 			return SC_FLUSH_DAT;
2553 	}
2554 	return SC_LSEG_SR;
2555 }
2556 
2557 /**
2558  * nilfs_segctor_thread - main loop of the segment constructor thread.
2559  * @arg: pointer to a struct nilfs_sc_info.
2560  *
2561  * nilfs_segctor_thread() initializes a timer and serves as a daemon
2562  * to execute segment constructions.
2563  */
2564 static int nilfs_segctor_thread(void *arg)
2565 {
2566 	struct nilfs_sc_info *sci = (struct nilfs_sc_info *)arg;
2567 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
2568 	int timeout = 0;
2569 
2570 	sci->sc_timer_task = current;
2571 
2572 	/* start sync. */
2573 	sci->sc_task = current;
2574 	wake_up(&sci->sc_wait_task); /* for nilfs_segctor_start_thread() */
2575 	nilfs_info(sci->sc_super,
2576 		   "segctord starting. Construction interval = %lu seconds, CP frequency < %lu seconds",
2577 		   sci->sc_interval / HZ, sci->sc_mjcp_freq / HZ);
2578 
2579 	spin_lock(&sci->sc_state_lock);
2580  loop:
2581 	for (;;) {
2582 		int mode;
2583 
2584 		if (sci->sc_state & NILFS_SEGCTOR_QUIT)
2585 			goto end_thread;
2586 
2587 		if (timeout || sci->sc_seq_request != sci->sc_seq_done)
2588 			mode = SC_LSEG_SR;
2589 		else if (sci->sc_flush_request)
2590 			mode = nilfs_segctor_flush_mode(sci);
2591 		else
2592 			break;
2593 
2594 		spin_unlock(&sci->sc_state_lock);
2595 		nilfs_segctor_thread_construct(sci, mode);
2596 		spin_lock(&sci->sc_state_lock);
2597 		timeout = 0;
2598 	}
2599 
2600 
2601 	if (freezing(current)) {
2602 		spin_unlock(&sci->sc_state_lock);
2603 		try_to_freeze();
2604 		spin_lock(&sci->sc_state_lock);
2605 	} else {
2606 		DEFINE_WAIT(wait);
2607 		int should_sleep = 1;
2608 
2609 		prepare_to_wait(&sci->sc_wait_daemon, &wait,
2610 				TASK_INTERRUPTIBLE);
2611 
2612 		if (sci->sc_seq_request != sci->sc_seq_done)
2613 			should_sleep = 0;
2614 		else if (sci->sc_flush_request)
2615 			should_sleep = 0;
2616 		else if (sci->sc_state & NILFS_SEGCTOR_COMMIT)
2617 			should_sleep = time_before(jiffies,
2618 					sci->sc_timer.expires);
2619 
2620 		if (should_sleep) {
2621 			spin_unlock(&sci->sc_state_lock);
2622 			schedule();
2623 			spin_lock(&sci->sc_state_lock);
2624 		}
2625 		finish_wait(&sci->sc_wait_daemon, &wait);
2626 		timeout = ((sci->sc_state & NILFS_SEGCTOR_COMMIT) &&
2627 			   time_after_eq(jiffies, sci->sc_timer.expires));
2628 
2629 		if (nilfs_sb_dirty(nilfs) && nilfs_sb_need_update(nilfs))
2630 			set_nilfs_discontinued(nilfs);
2631 	}
2632 	goto loop;
2633 
2634  end_thread:
2635 	/* end sync. */
2636 	sci->sc_task = NULL;
2637 	wake_up(&sci->sc_wait_task); /* for nilfs_segctor_kill_thread() */
2638 	spin_unlock(&sci->sc_state_lock);
2639 	return 0;
2640 }
2641 
2642 static int nilfs_segctor_start_thread(struct nilfs_sc_info *sci)
2643 {
2644 	struct task_struct *t;
2645 
2646 	t = kthread_run(nilfs_segctor_thread, sci, "segctord");
2647 	if (IS_ERR(t)) {
2648 		int err = PTR_ERR(t);
2649 
2650 		nilfs_err(sci->sc_super, "error %d creating segctord thread",
2651 			  err);
2652 		return err;
2653 	}
2654 	wait_event(sci->sc_wait_task, sci->sc_task != NULL);
2655 	return 0;
2656 }
2657 
2658 static void nilfs_segctor_kill_thread(struct nilfs_sc_info *sci)
2659 	__acquires(&sci->sc_state_lock)
2660 	__releases(&sci->sc_state_lock)
2661 {
2662 	sci->sc_state |= NILFS_SEGCTOR_QUIT;
2663 
2664 	while (sci->sc_task) {
2665 		wake_up(&sci->sc_wait_daemon);
2666 		spin_unlock(&sci->sc_state_lock);
2667 		wait_event(sci->sc_wait_task, sci->sc_task == NULL);
2668 		spin_lock(&sci->sc_state_lock);
2669 	}
2670 }
2671 
2672 /*
2673  * Setup & clean-up functions
2674  */
2675 static struct nilfs_sc_info *nilfs_segctor_new(struct super_block *sb,
2676 					       struct nilfs_root *root)
2677 {
2678 	struct the_nilfs *nilfs = sb->s_fs_info;
2679 	struct nilfs_sc_info *sci;
2680 
2681 	sci = kzalloc(sizeof(*sci), GFP_KERNEL);
2682 	if (!sci)
2683 		return NULL;
2684 
2685 	sci->sc_super = sb;
2686 
2687 	nilfs_get_root(root);
2688 	sci->sc_root = root;
2689 
2690 	init_waitqueue_head(&sci->sc_wait_request);
2691 	init_waitqueue_head(&sci->sc_wait_daemon);
2692 	init_waitqueue_head(&sci->sc_wait_task);
2693 	spin_lock_init(&sci->sc_state_lock);
2694 	INIT_LIST_HEAD(&sci->sc_dirty_files);
2695 	INIT_LIST_HEAD(&sci->sc_segbufs);
2696 	INIT_LIST_HEAD(&sci->sc_write_logs);
2697 	INIT_LIST_HEAD(&sci->sc_gc_inodes);
2698 	INIT_LIST_HEAD(&sci->sc_iput_queue);
2699 	INIT_WORK(&sci->sc_iput_work, nilfs_iput_work_func);
2700 	timer_setup(&sci->sc_timer, nilfs_construction_timeout, 0);
2701 
2702 	sci->sc_interval = HZ * NILFS_SC_DEFAULT_TIMEOUT;
2703 	sci->sc_mjcp_freq = HZ * NILFS_SC_DEFAULT_SR_FREQ;
2704 	sci->sc_watermark = NILFS_SC_DEFAULT_WATERMARK;
2705 
2706 	if (nilfs->ns_interval)
2707 		sci->sc_interval = HZ * nilfs->ns_interval;
2708 	if (nilfs->ns_watermark)
2709 		sci->sc_watermark = nilfs->ns_watermark;
2710 	return sci;
2711 }
2712 
2713 static void nilfs_segctor_write_out(struct nilfs_sc_info *sci)
2714 {
2715 	int ret, retrycount = NILFS_SC_CLEANUP_RETRY;
2716 
2717 	/*
2718 	 * The segctord thread was stopped and its timer was removed.
2719 	 * But some tasks remain.
2720 	 */
2721 	do {
2722 		struct nilfs_transaction_info ti;
2723 
2724 		nilfs_transaction_lock(sci->sc_super, &ti, 0);
2725 		ret = nilfs_segctor_construct(sci, SC_LSEG_SR);
2726 		nilfs_transaction_unlock(sci->sc_super);
2727 
2728 		flush_work(&sci->sc_iput_work);
2729 
2730 	} while (ret && ret != -EROFS && retrycount-- > 0);
2731 }
2732 
2733 /**
2734  * nilfs_segctor_destroy - destroy the segment constructor.
2735  * @sci: nilfs_sc_info
2736  *
2737  * nilfs_segctor_destroy() kills the segctord thread and frees
2738  * the nilfs_sc_info struct.
2739  * Caller must hold the segment semaphore.
2740  */
2741 static void nilfs_segctor_destroy(struct nilfs_sc_info *sci)
2742 {
2743 	struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
2744 	int flag;
2745 
2746 	up_write(&nilfs->ns_segctor_sem);
2747 
2748 	spin_lock(&sci->sc_state_lock);
2749 	nilfs_segctor_kill_thread(sci);
2750 	flag = ((sci->sc_state & NILFS_SEGCTOR_COMMIT) || sci->sc_flush_request
2751 		|| sci->sc_seq_request != sci->sc_seq_done);
2752 	spin_unlock(&sci->sc_state_lock);
2753 
2754 	if (flush_work(&sci->sc_iput_work))
2755 		flag = true;
2756 
2757 	if (flag || !nilfs_segctor_confirm(sci))
2758 		nilfs_segctor_write_out(sci);
2759 
2760 	if (!list_empty(&sci->sc_dirty_files)) {
2761 		nilfs_warn(sci->sc_super,
2762 			   "disposed unprocessed dirty file(s) when stopping log writer");
2763 		nilfs_dispose_list(nilfs, &sci->sc_dirty_files, 1);
2764 	}
2765 
2766 	if (!list_empty(&sci->sc_iput_queue)) {
2767 		nilfs_warn(sci->sc_super,
2768 			   "disposed unprocessed inode(s) in iput queue when stopping log writer");
2769 		nilfs_dispose_list(nilfs, &sci->sc_iput_queue, 1);
2770 	}
2771 
2772 	WARN_ON(!list_empty(&sci->sc_segbufs));
2773 	WARN_ON(!list_empty(&sci->sc_write_logs));
2774 
2775 	nilfs_put_root(sci->sc_root);
2776 
2777 	down_write(&nilfs->ns_segctor_sem);
2778 
2779 	timer_shutdown_sync(&sci->sc_timer);
2780 	kfree(sci);
2781 }
2782 
2783 /**
2784  * nilfs_attach_log_writer - attach log writer
2785  * @sb: super block instance
2786  * @root: root object of the current filesystem tree
2787  *
2788  * This allocates a log writer object, initializes it, and starts the
2789  * log writer.
2790  *
2791  * Return Value: On success, 0 is returned. On error, one of the following
2792  * negative error code is returned.
2793  *
2794  * %-ENOMEM - Insufficient memory available.
2795  */
2796 int nilfs_attach_log_writer(struct super_block *sb, struct nilfs_root *root)
2797 {
2798 	struct the_nilfs *nilfs = sb->s_fs_info;
2799 	int err;
2800 
2801 	if (nilfs->ns_writer) {
2802 		/*
2803 		 * This happens if the filesystem is made read-only by
2804 		 * __nilfs_error or nilfs_remount and then remounted
2805 		 * read/write.  In these cases, reuse the existing
2806 		 * writer.
2807 		 */
2808 		return 0;
2809 	}
2810 
2811 	nilfs->ns_writer = nilfs_segctor_new(sb, root);
2812 	if (!nilfs->ns_writer)
2813 		return -ENOMEM;
2814 
2815 	inode_attach_wb(nilfs->ns_bdev->bd_inode, NULL);
2816 
2817 	err = nilfs_segctor_start_thread(nilfs->ns_writer);
2818 	if (unlikely(err))
2819 		nilfs_detach_log_writer(sb);
2820 
2821 	return err;
2822 }
2823 
2824 /**
2825  * nilfs_detach_log_writer - destroy log writer
2826  * @sb: super block instance
2827  *
2828  * This kills log writer daemon, frees the log writer object, and
2829  * destroys list of dirty files.
2830  */
2831 void nilfs_detach_log_writer(struct super_block *sb)
2832 {
2833 	struct the_nilfs *nilfs = sb->s_fs_info;
2834 	LIST_HEAD(garbage_list);
2835 
2836 	down_write(&nilfs->ns_segctor_sem);
2837 	if (nilfs->ns_writer) {
2838 		nilfs_segctor_destroy(nilfs->ns_writer);
2839 		nilfs->ns_writer = NULL;
2840 	}
2841 
2842 	/* Force to free the list of dirty files */
2843 	spin_lock(&nilfs->ns_inode_lock);
2844 	if (!list_empty(&nilfs->ns_dirty_files)) {
2845 		list_splice_init(&nilfs->ns_dirty_files, &garbage_list);
2846 		nilfs_warn(sb,
2847 			   "disposed unprocessed dirty file(s) when detaching log writer");
2848 	}
2849 	spin_unlock(&nilfs->ns_inode_lock);
2850 	up_write(&nilfs->ns_segctor_sem);
2851 
2852 	nilfs_dispose_list(nilfs, &garbage_list, 1);
2853 }
2854