GNU Linux-libre 4.19.286-gnu1
[releases.git] / fs / nilfs2 / segment.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * segment.c - 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_gt(a, b)   \
138         (typecheck(__u32, a) && typecheck(__u32, b) && \
139          ((__s32)(b) - (__s32)(a) < 0))
140 #define nilfs_cnt32_ge(a, b)   \
141         (typecheck(__u32, a) && typecheck(__u32, b) && \
142          ((__s32)(a) - (__s32)(b) >= 0))
143 #define nilfs_cnt32_lt(a, b)  nilfs_cnt32_gt(b, a)
144 #define nilfs_cnt32_le(a, b)  nilfs_cnt32_ge(b, a)
145
146 static int nilfs_prepare_segment_lock(struct super_block *sb,
147                                       struct nilfs_transaction_info *ti)
148 {
149         struct nilfs_transaction_info *cur_ti = current->journal_info;
150         void *save = NULL;
151
152         if (cur_ti) {
153                 if (cur_ti->ti_magic == NILFS_TI_MAGIC)
154                         return ++cur_ti->ti_count;
155
156                 /*
157                  * If journal_info field is occupied by other FS,
158                  * it is saved and will be restored on
159                  * nilfs_transaction_commit().
160                  */
161                 nilfs_msg(sb, KERN_WARNING, "journal info from a different FS");
162                 save = current->journal_info;
163         }
164         if (!ti) {
165                 ti = kmem_cache_alloc(nilfs_transaction_cachep, GFP_NOFS);
166                 if (!ti)
167                         return -ENOMEM;
168                 ti->ti_flags = NILFS_TI_DYNAMIC_ALLOC;
169         } else {
170                 ti->ti_flags = 0;
171         }
172         ti->ti_count = 0;
173         ti->ti_save = save;
174         ti->ti_magic = NILFS_TI_MAGIC;
175         current->journal_info = ti;
176         return 0;
177 }
178
179 /**
180  * nilfs_transaction_begin - start indivisible file operations.
181  * @sb: super block
182  * @ti: nilfs_transaction_info
183  * @vacancy_check: flags for vacancy rate checks
184  *
185  * nilfs_transaction_begin() acquires a reader/writer semaphore, called
186  * the segment semaphore, to make a segment construction and write tasks
187  * exclusive.  The function is used with nilfs_transaction_commit() in pairs.
188  * The region enclosed by these two functions can be nested.  To avoid a
189  * deadlock, the semaphore is only acquired or released in the outermost call.
190  *
191  * This function allocates a nilfs_transaction_info struct to keep context
192  * information on it.  It is initialized and hooked onto the current task in
193  * the outermost call.  If a pre-allocated struct is given to @ti, it is used
194  * instead; otherwise a new struct is assigned from a slab.
195  *
196  * When @vacancy_check flag is set, this function will check the amount of
197  * free space, and will wait for the GC to reclaim disk space if low capacity.
198  *
199  * Return Value: On success, 0 is returned. On error, one of the following
200  * negative error code is returned.
201  *
202  * %-ENOMEM - Insufficient memory available.
203  *
204  * %-ENOSPC - No space left on device
205  */
206 int nilfs_transaction_begin(struct super_block *sb,
207                             struct nilfs_transaction_info *ti,
208                             int vacancy_check)
209 {
210         struct the_nilfs *nilfs;
211         int ret = nilfs_prepare_segment_lock(sb, ti);
212         struct nilfs_transaction_info *trace_ti;
213
214         if (unlikely(ret < 0))
215                 return ret;
216         if (ret > 0) {
217                 trace_ti = current->journal_info;
218
219                 trace_nilfs2_transaction_transition(sb, trace_ti,
220                                     trace_ti->ti_count, trace_ti->ti_flags,
221                                     TRACE_NILFS2_TRANSACTION_BEGIN);
222                 return 0;
223         }
224
225         sb_start_intwrite(sb);
226
227         nilfs = sb->s_fs_info;
228         down_read(&nilfs->ns_segctor_sem);
229         if (vacancy_check && nilfs_near_disk_full(nilfs)) {
230                 up_read(&nilfs->ns_segctor_sem);
231                 ret = -ENOSPC;
232                 goto failed;
233         }
234
235         trace_ti = current->journal_info;
236         trace_nilfs2_transaction_transition(sb, trace_ti, trace_ti->ti_count,
237                                             trace_ti->ti_flags,
238                                             TRACE_NILFS2_TRANSACTION_BEGIN);
239         return 0;
240
241  failed:
242         ti = current->journal_info;
243         current->journal_info = ti->ti_save;
244         if (ti->ti_flags & NILFS_TI_DYNAMIC_ALLOC)
245                 kmem_cache_free(nilfs_transaction_cachep, ti);
246         sb_end_intwrite(sb);
247         return ret;
248 }
249
250 /**
251  * nilfs_transaction_commit - commit indivisible file operations.
252  * @sb: super block
253  *
254  * nilfs_transaction_commit() releases the read semaphore which is
255  * acquired by nilfs_transaction_begin(). This is only performed
256  * in outermost call of this function.  If a commit flag is set,
257  * nilfs_transaction_commit() sets a timer to start the segment
258  * constructor.  If a sync flag is set, it starts construction
259  * directly.
260  */
261 int nilfs_transaction_commit(struct super_block *sb)
262 {
263         struct nilfs_transaction_info *ti = current->journal_info;
264         struct the_nilfs *nilfs = sb->s_fs_info;
265         int err = 0;
266
267         BUG_ON(ti == NULL || ti->ti_magic != NILFS_TI_MAGIC);
268         ti->ti_flags |= NILFS_TI_COMMIT;
269         if (ti->ti_count > 0) {
270                 ti->ti_count--;
271                 trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
272                             ti->ti_flags, TRACE_NILFS2_TRANSACTION_COMMIT);
273                 return 0;
274         }
275         if (nilfs->ns_writer) {
276                 struct nilfs_sc_info *sci = nilfs->ns_writer;
277
278                 if (ti->ti_flags & NILFS_TI_COMMIT)
279                         nilfs_segctor_start_timer(sci);
280                 if (atomic_read(&nilfs->ns_ndirtyblks) > sci->sc_watermark)
281                         nilfs_segctor_do_flush(sci, 0);
282         }
283         up_read(&nilfs->ns_segctor_sem);
284         trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
285                             ti->ti_flags, TRACE_NILFS2_TRANSACTION_COMMIT);
286
287         current->journal_info = ti->ti_save;
288
289         if (ti->ti_flags & NILFS_TI_SYNC)
290                 err = nilfs_construct_segment(sb);
291         if (ti->ti_flags & NILFS_TI_DYNAMIC_ALLOC)
292                 kmem_cache_free(nilfs_transaction_cachep, ti);
293         sb_end_intwrite(sb);
294         return err;
295 }
296
297 void nilfs_transaction_abort(struct super_block *sb)
298 {
299         struct nilfs_transaction_info *ti = current->journal_info;
300         struct the_nilfs *nilfs = sb->s_fs_info;
301
302         BUG_ON(ti == NULL || ti->ti_magic != NILFS_TI_MAGIC);
303         if (ti->ti_count > 0) {
304                 ti->ti_count--;
305                 trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
306                             ti->ti_flags, TRACE_NILFS2_TRANSACTION_ABORT);
307                 return;
308         }
309         up_read(&nilfs->ns_segctor_sem);
310
311         trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
312                     ti->ti_flags, TRACE_NILFS2_TRANSACTION_ABORT);
313
314         current->journal_info = ti->ti_save;
315         if (ti->ti_flags & NILFS_TI_DYNAMIC_ALLOC)
316                 kmem_cache_free(nilfs_transaction_cachep, ti);
317         sb_end_intwrite(sb);
318 }
319
320 void nilfs_relax_pressure_in_lock(struct super_block *sb)
321 {
322         struct the_nilfs *nilfs = sb->s_fs_info;
323         struct nilfs_sc_info *sci = nilfs->ns_writer;
324
325         if (sb_rdonly(sb) || unlikely(!sci) || !sci->sc_flush_request)
326                 return;
327
328         set_bit(NILFS_SC_PRIOR_FLUSH, &sci->sc_flags);
329         up_read(&nilfs->ns_segctor_sem);
330
331         down_write(&nilfs->ns_segctor_sem);
332         if (sci->sc_flush_request &&
333             test_bit(NILFS_SC_PRIOR_FLUSH, &sci->sc_flags)) {
334                 struct nilfs_transaction_info *ti = current->journal_info;
335
336                 ti->ti_flags |= NILFS_TI_WRITER;
337                 nilfs_segctor_do_immediate_flush(sci);
338                 ti->ti_flags &= ~NILFS_TI_WRITER;
339         }
340         downgrade_write(&nilfs->ns_segctor_sem);
341 }
342
343 static void nilfs_transaction_lock(struct super_block *sb,
344                                    struct nilfs_transaction_info *ti,
345                                    int gcflag)
346 {
347         struct nilfs_transaction_info *cur_ti = current->journal_info;
348         struct the_nilfs *nilfs = sb->s_fs_info;
349         struct nilfs_sc_info *sci = nilfs->ns_writer;
350
351         WARN_ON(cur_ti);
352         ti->ti_flags = NILFS_TI_WRITER;
353         ti->ti_count = 0;
354         ti->ti_save = cur_ti;
355         ti->ti_magic = NILFS_TI_MAGIC;
356         current->journal_info = ti;
357
358         for (;;) {
359                 trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
360                             ti->ti_flags, TRACE_NILFS2_TRANSACTION_TRYLOCK);
361
362                 down_write(&nilfs->ns_segctor_sem);
363                 if (!test_bit(NILFS_SC_PRIOR_FLUSH, &sci->sc_flags))
364                         break;
365
366                 nilfs_segctor_do_immediate_flush(sci);
367
368                 up_write(&nilfs->ns_segctor_sem);
369                 cond_resched();
370         }
371         if (gcflag)
372                 ti->ti_flags |= NILFS_TI_GC;
373
374         trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
375                             ti->ti_flags, TRACE_NILFS2_TRANSACTION_LOCK);
376 }
377
378 static void nilfs_transaction_unlock(struct super_block *sb)
379 {
380         struct nilfs_transaction_info *ti = current->journal_info;
381         struct the_nilfs *nilfs = sb->s_fs_info;
382
383         BUG_ON(ti == NULL || ti->ti_magic != NILFS_TI_MAGIC);
384         BUG_ON(ti->ti_count > 0);
385
386         up_write(&nilfs->ns_segctor_sem);
387         current->journal_info = ti->ti_save;
388
389         trace_nilfs2_transaction_transition(sb, ti, ti->ti_count,
390                             ti->ti_flags, TRACE_NILFS2_TRANSACTION_UNLOCK);
391 }
392
393 static void *nilfs_segctor_map_segsum_entry(struct nilfs_sc_info *sci,
394                                             struct nilfs_segsum_pointer *ssp,
395                                             unsigned int bytes)
396 {
397         struct nilfs_segment_buffer *segbuf = sci->sc_curseg;
398         unsigned int blocksize = sci->sc_super->s_blocksize;
399         void *p;
400
401         if (unlikely(ssp->offset + bytes > blocksize)) {
402                 ssp->offset = 0;
403                 BUG_ON(NILFS_SEGBUF_BH_IS_LAST(ssp->bh,
404                                                &segbuf->sb_segsum_buffers));
405                 ssp->bh = NILFS_SEGBUF_NEXT_BH(ssp->bh);
406         }
407         p = ssp->bh->b_data + ssp->offset;
408         ssp->offset += bytes;
409         return p;
410 }
411
412 /**
413  * nilfs_segctor_reset_segment_buffer - reset the current segment buffer
414  * @sci: nilfs_sc_info
415  */
416 static int nilfs_segctor_reset_segment_buffer(struct nilfs_sc_info *sci)
417 {
418         struct nilfs_segment_buffer *segbuf = sci->sc_curseg;
419         struct buffer_head *sumbh;
420         unsigned int sumbytes;
421         unsigned int flags = 0;
422         int err;
423
424         if (nilfs_doing_gc())
425                 flags = NILFS_SS_GC;
426         err = nilfs_segbuf_reset(segbuf, flags, sci->sc_seg_ctime, sci->sc_cno);
427         if (unlikely(err))
428                 return err;
429
430         sumbh = NILFS_SEGBUF_FIRST_BH(&segbuf->sb_segsum_buffers);
431         sumbytes = segbuf->sb_sum.sumbytes;
432         sci->sc_finfo_ptr.bh = sumbh;  sci->sc_finfo_ptr.offset = sumbytes;
433         sci->sc_binfo_ptr.bh = sumbh;  sci->sc_binfo_ptr.offset = sumbytes;
434         sci->sc_blk_cnt = sci->sc_datablk_cnt = 0;
435         return 0;
436 }
437
438 /**
439  * nilfs_segctor_zeropad_segsum - zero pad the rest of the segment summary area
440  * @sci: segment constructor object
441  *
442  * nilfs_segctor_zeropad_segsum() zero-fills unallocated space at the end of
443  * the current segment summary block.
444  */
445 static void nilfs_segctor_zeropad_segsum(struct nilfs_sc_info *sci)
446 {
447         struct nilfs_segsum_pointer *ssp;
448
449         ssp = sci->sc_blk_cnt > 0 ? &sci->sc_binfo_ptr : &sci->sc_finfo_ptr;
450         if (ssp->offset < ssp->bh->b_size)
451                 memset(ssp->bh->b_data + ssp->offset, 0,
452                        ssp->bh->b_size - ssp->offset);
453 }
454
455 static int nilfs_segctor_feed_segment(struct nilfs_sc_info *sci)
456 {
457         sci->sc_nblk_this_inc += sci->sc_curseg->sb_sum.nblocks;
458         if (NILFS_SEGBUF_IS_LAST(sci->sc_curseg, &sci->sc_segbufs))
459                 return -E2BIG; /*
460                                 * The current segment is filled up
461                                 * (internal code)
462                                 */
463         nilfs_segctor_zeropad_segsum(sci);
464         sci->sc_curseg = NILFS_NEXT_SEGBUF(sci->sc_curseg);
465         return nilfs_segctor_reset_segment_buffer(sci);
466 }
467
468 static int nilfs_segctor_add_super_root(struct nilfs_sc_info *sci)
469 {
470         struct nilfs_segment_buffer *segbuf = sci->sc_curseg;
471         int err;
472
473         if (segbuf->sb_sum.nblocks >= segbuf->sb_rest_blocks) {
474                 err = nilfs_segctor_feed_segment(sci);
475                 if (err)
476                         return err;
477                 segbuf = sci->sc_curseg;
478         }
479         err = nilfs_segbuf_extend_payload(segbuf, &segbuf->sb_super_root);
480         if (likely(!err))
481                 segbuf->sb_sum.flags |= NILFS_SS_SR;
482         return err;
483 }
484
485 /*
486  * Functions for making segment summary and payloads
487  */
488 static int nilfs_segctor_segsum_block_required(
489         struct nilfs_sc_info *sci, const struct nilfs_segsum_pointer *ssp,
490         unsigned int binfo_size)
491 {
492         unsigned int blocksize = sci->sc_super->s_blocksize;
493         /* Size of finfo and binfo is enough small against blocksize */
494
495         return ssp->offset + binfo_size +
496                 (!sci->sc_blk_cnt ? sizeof(struct nilfs_finfo) : 0) >
497                 blocksize;
498 }
499
500 static void nilfs_segctor_begin_finfo(struct nilfs_sc_info *sci,
501                                       struct inode *inode)
502 {
503         sci->sc_curseg->sb_sum.nfinfo++;
504         sci->sc_binfo_ptr = sci->sc_finfo_ptr;
505         nilfs_segctor_map_segsum_entry(
506                 sci, &sci->sc_binfo_ptr, sizeof(struct nilfs_finfo));
507
508         if (NILFS_I(inode)->i_root &&
509             !test_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags))
510                 set_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags);
511         /* skip finfo */
512 }
513
514 static void nilfs_segctor_end_finfo(struct nilfs_sc_info *sci,
515                                     struct inode *inode)
516 {
517         struct nilfs_finfo *finfo;
518         struct nilfs_inode_info *ii;
519         struct nilfs_segment_buffer *segbuf;
520         __u64 cno;
521
522         if (sci->sc_blk_cnt == 0)
523                 return;
524
525         ii = NILFS_I(inode);
526
527         if (test_bit(NILFS_I_GCINODE, &ii->i_state))
528                 cno = ii->i_cno;
529         else if (NILFS_ROOT_METADATA_FILE(inode->i_ino))
530                 cno = 0;
531         else
532                 cno = sci->sc_cno;
533
534         finfo = nilfs_segctor_map_segsum_entry(sci, &sci->sc_finfo_ptr,
535                                                  sizeof(*finfo));
536         finfo->fi_ino = cpu_to_le64(inode->i_ino);
537         finfo->fi_nblocks = cpu_to_le32(sci->sc_blk_cnt);
538         finfo->fi_ndatablk = cpu_to_le32(sci->sc_datablk_cnt);
539         finfo->fi_cno = cpu_to_le64(cno);
540
541         segbuf = sci->sc_curseg;
542         segbuf->sb_sum.sumbytes = sci->sc_binfo_ptr.offset +
543                 sci->sc_super->s_blocksize * (segbuf->sb_sum.nsumblk - 1);
544         sci->sc_finfo_ptr = sci->sc_binfo_ptr;
545         sci->sc_blk_cnt = sci->sc_datablk_cnt = 0;
546 }
547
548 static int nilfs_segctor_add_file_block(struct nilfs_sc_info *sci,
549                                         struct buffer_head *bh,
550                                         struct inode *inode,
551                                         unsigned int binfo_size)
552 {
553         struct nilfs_segment_buffer *segbuf;
554         int required, err = 0;
555
556  retry:
557         segbuf = sci->sc_curseg;
558         required = nilfs_segctor_segsum_block_required(
559                 sci, &sci->sc_binfo_ptr, binfo_size);
560         if (segbuf->sb_sum.nblocks + required + 1 > segbuf->sb_rest_blocks) {
561                 nilfs_segctor_end_finfo(sci, inode);
562                 err = nilfs_segctor_feed_segment(sci);
563                 if (err)
564                         return err;
565                 goto retry;
566         }
567         if (unlikely(required)) {
568                 nilfs_segctor_zeropad_segsum(sci);
569                 err = nilfs_segbuf_extend_segsum(segbuf);
570                 if (unlikely(err))
571                         goto failed;
572         }
573         if (sci->sc_blk_cnt == 0)
574                 nilfs_segctor_begin_finfo(sci, inode);
575
576         nilfs_segctor_map_segsum_entry(sci, &sci->sc_binfo_ptr, binfo_size);
577         /* Substitution to vblocknr is delayed until update_blocknr() */
578         nilfs_segbuf_add_file_buffer(segbuf, bh);
579         sci->sc_blk_cnt++;
580  failed:
581         return err;
582 }
583
584 /*
585  * Callback functions that enumerate, mark, and collect dirty blocks
586  */
587 static int nilfs_collect_file_data(struct nilfs_sc_info *sci,
588                                    struct buffer_head *bh, struct inode *inode)
589 {
590         int err;
591
592         err = nilfs_bmap_propagate(NILFS_I(inode)->i_bmap, bh);
593         if (err < 0)
594                 return err;
595
596         err = nilfs_segctor_add_file_block(sci, bh, inode,
597                                            sizeof(struct nilfs_binfo_v));
598         if (!err)
599                 sci->sc_datablk_cnt++;
600         return err;
601 }
602
603 static int nilfs_collect_file_node(struct nilfs_sc_info *sci,
604                                    struct buffer_head *bh,
605                                    struct inode *inode)
606 {
607         return nilfs_bmap_propagate(NILFS_I(inode)->i_bmap, bh);
608 }
609
610 static int nilfs_collect_file_bmap(struct nilfs_sc_info *sci,
611                                    struct buffer_head *bh,
612                                    struct inode *inode)
613 {
614         WARN_ON(!buffer_dirty(bh));
615         return nilfs_segctor_add_file_block(sci, bh, inode, sizeof(__le64));
616 }
617
618 static void nilfs_write_file_data_binfo(struct nilfs_sc_info *sci,
619                                         struct nilfs_segsum_pointer *ssp,
620                                         union nilfs_binfo *binfo)
621 {
622         struct nilfs_binfo_v *binfo_v = nilfs_segctor_map_segsum_entry(
623                 sci, ssp, sizeof(*binfo_v));
624         *binfo_v = binfo->bi_v;
625 }
626
627 static void nilfs_write_file_node_binfo(struct nilfs_sc_info *sci,
628                                         struct nilfs_segsum_pointer *ssp,
629                                         union nilfs_binfo *binfo)
630 {
631         __le64 *vblocknr = nilfs_segctor_map_segsum_entry(
632                 sci, ssp, sizeof(*vblocknr));
633         *vblocknr = binfo->bi_v.bi_vblocknr;
634 }
635
636 static const struct nilfs_sc_operations nilfs_sc_file_ops = {
637         .collect_data = nilfs_collect_file_data,
638         .collect_node = nilfs_collect_file_node,
639         .collect_bmap = nilfs_collect_file_bmap,
640         .write_data_binfo = nilfs_write_file_data_binfo,
641         .write_node_binfo = nilfs_write_file_node_binfo,
642 };
643
644 static int nilfs_collect_dat_data(struct nilfs_sc_info *sci,
645                                   struct buffer_head *bh, struct inode *inode)
646 {
647         int err;
648
649         err = nilfs_bmap_propagate(NILFS_I(inode)->i_bmap, bh);
650         if (err < 0)
651                 return err;
652
653         err = nilfs_segctor_add_file_block(sci, bh, inode, sizeof(__le64));
654         if (!err)
655                 sci->sc_datablk_cnt++;
656         return err;
657 }
658
659 static int nilfs_collect_dat_bmap(struct nilfs_sc_info *sci,
660                                   struct buffer_head *bh, struct inode *inode)
661 {
662         WARN_ON(!buffer_dirty(bh));
663         return nilfs_segctor_add_file_block(sci, bh, inode,
664                                             sizeof(struct nilfs_binfo_dat));
665 }
666
667 static void nilfs_write_dat_data_binfo(struct nilfs_sc_info *sci,
668                                        struct nilfs_segsum_pointer *ssp,
669                                        union nilfs_binfo *binfo)
670 {
671         __le64 *blkoff = nilfs_segctor_map_segsum_entry(sci, ssp,
672                                                           sizeof(*blkoff));
673         *blkoff = binfo->bi_dat.bi_blkoff;
674 }
675
676 static void nilfs_write_dat_node_binfo(struct nilfs_sc_info *sci,
677                                        struct nilfs_segsum_pointer *ssp,
678                                        union nilfs_binfo *binfo)
679 {
680         struct nilfs_binfo_dat *binfo_dat =
681                 nilfs_segctor_map_segsum_entry(sci, ssp, sizeof(*binfo_dat));
682         *binfo_dat = binfo->bi_dat;
683 }
684
685 static const struct nilfs_sc_operations nilfs_sc_dat_ops = {
686         .collect_data = nilfs_collect_dat_data,
687         .collect_node = nilfs_collect_file_node,
688         .collect_bmap = nilfs_collect_dat_bmap,
689         .write_data_binfo = nilfs_write_dat_data_binfo,
690         .write_node_binfo = nilfs_write_dat_node_binfo,
691 };
692
693 static const struct nilfs_sc_operations nilfs_sc_dsync_ops = {
694         .collect_data = nilfs_collect_file_data,
695         .collect_node = NULL,
696         .collect_bmap = NULL,
697         .write_data_binfo = nilfs_write_file_data_binfo,
698         .write_node_binfo = NULL,
699 };
700
701 static size_t nilfs_lookup_dirty_data_buffers(struct inode *inode,
702                                               struct list_head *listp,
703                                               size_t nlimit,
704                                               loff_t start, loff_t end)
705 {
706         struct address_space *mapping = inode->i_mapping;
707         struct pagevec pvec;
708         pgoff_t index = 0, last = ULONG_MAX;
709         size_t ndirties = 0;
710         int i;
711
712         if (unlikely(start != 0 || end != LLONG_MAX)) {
713                 /*
714                  * A valid range is given for sync-ing data pages. The
715                  * range is rounded to per-page; extra dirty buffers
716                  * may be included if blocksize < pagesize.
717                  */
718                 index = start >> PAGE_SHIFT;
719                 last = end >> PAGE_SHIFT;
720         }
721         pagevec_init(&pvec);
722  repeat:
723         if (unlikely(index > last) ||
724             !pagevec_lookup_range_tag(&pvec, mapping, &index, last,
725                                 PAGECACHE_TAG_DIRTY))
726                 return ndirties;
727
728         for (i = 0; i < pagevec_count(&pvec); i++) {
729                 struct buffer_head *bh, *head;
730                 struct page *page = pvec.pages[i];
731
732                 lock_page(page);
733                 if (!page_has_buffers(page))
734                         create_empty_buffers(page, i_blocksize(inode), 0);
735                 unlock_page(page);
736
737                 bh = head = page_buffers(page);
738                 do {
739                         if (!buffer_dirty(bh) || buffer_async_write(bh))
740                                 continue;
741                         get_bh(bh);
742                         list_add_tail(&bh->b_assoc_buffers, listp);
743                         ndirties++;
744                         if (unlikely(ndirties >= nlimit)) {
745                                 pagevec_release(&pvec);
746                                 cond_resched();
747                                 return ndirties;
748                         }
749                 } while (bh = bh->b_this_page, bh != head);
750         }
751         pagevec_release(&pvec);
752         cond_resched();
753         goto repeat;
754 }
755
756 static void nilfs_lookup_dirty_node_buffers(struct inode *inode,
757                                             struct list_head *listp)
758 {
759         struct nilfs_inode_info *ii = NILFS_I(inode);
760         struct inode *btnc_inode = ii->i_assoc_inode;
761         struct pagevec pvec;
762         struct buffer_head *bh, *head;
763         unsigned int i;
764         pgoff_t index = 0;
765
766         if (!btnc_inode)
767                 return;
768
769         pagevec_init(&pvec);
770
771         while (pagevec_lookup_tag(&pvec, btnc_inode->i_mapping, &index,
772                                         PAGECACHE_TAG_DIRTY)) {
773                 for (i = 0; i < pagevec_count(&pvec); i++) {
774                         bh = head = page_buffers(pvec.pages[i]);
775                         do {
776                                 if (buffer_dirty(bh) &&
777                                                 !buffer_async_write(bh)) {
778                                         get_bh(bh);
779                                         list_add_tail(&bh->b_assoc_buffers,
780                                                       listp);
781                                 }
782                                 bh = bh->b_this_page;
783                         } while (bh != head);
784                 }
785                 pagevec_release(&pvec);
786                 cond_resched();
787         }
788 }
789
790 static void nilfs_dispose_list(struct the_nilfs *nilfs,
791                                struct list_head *head, int force)
792 {
793         struct nilfs_inode_info *ii, *n;
794         struct nilfs_inode_info *ivec[SC_N_INODEVEC], **pii;
795         unsigned int nv = 0;
796
797         while (!list_empty(head)) {
798                 spin_lock(&nilfs->ns_inode_lock);
799                 list_for_each_entry_safe(ii, n, head, i_dirty) {
800                         list_del_init(&ii->i_dirty);
801                         if (force) {
802                                 if (unlikely(ii->i_bh)) {
803                                         brelse(ii->i_bh);
804                                         ii->i_bh = NULL;
805                                 }
806                         } else if (test_bit(NILFS_I_DIRTY, &ii->i_state)) {
807                                 set_bit(NILFS_I_QUEUED, &ii->i_state);
808                                 list_add_tail(&ii->i_dirty,
809                                               &nilfs->ns_dirty_files);
810                                 continue;
811                         }
812                         ivec[nv++] = ii;
813                         if (nv == SC_N_INODEVEC)
814                                 break;
815                 }
816                 spin_unlock(&nilfs->ns_inode_lock);
817
818                 for (pii = ivec; nv > 0; pii++, nv--)
819                         iput(&(*pii)->vfs_inode);
820         }
821 }
822
823 static void nilfs_iput_work_func(struct work_struct *work)
824 {
825         struct nilfs_sc_info *sci = container_of(work, struct nilfs_sc_info,
826                                                  sc_iput_work);
827         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
828
829         nilfs_dispose_list(nilfs, &sci->sc_iput_queue, 0);
830 }
831
832 static int nilfs_test_metadata_dirty(struct the_nilfs *nilfs,
833                                      struct nilfs_root *root)
834 {
835         int ret = 0;
836
837         if (nilfs_mdt_fetch_dirty(root->ifile))
838                 ret++;
839         if (nilfs_mdt_fetch_dirty(nilfs->ns_cpfile))
840                 ret++;
841         if (nilfs_mdt_fetch_dirty(nilfs->ns_sufile))
842                 ret++;
843         if ((ret || nilfs_doing_gc()) && nilfs_mdt_fetch_dirty(nilfs->ns_dat))
844                 ret++;
845         return ret;
846 }
847
848 static int nilfs_segctor_clean(struct nilfs_sc_info *sci)
849 {
850         return list_empty(&sci->sc_dirty_files) &&
851                 !test_bit(NILFS_SC_DIRTY, &sci->sc_flags) &&
852                 sci->sc_nfreesegs == 0 &&
853                 (!nilfs_doing_gc() || list_empty(&sci->sc_gc_inodes));
854 }
855
856 static int nilfs_segctor_confirm(struct nilfs_sc_info *sci)
857 {
858         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
859         int ret = 0;
860
861         if (nilfs_test_metadata_dirty(nilfs, sci->sc_root))
862                 set_bit(NILFS_SC_DIRTY, &sci->sc_flags);
863
864         spin_lock(&nilfs->ns_inode_lock);
865         if (list_empty(&nilfs->ns_dirty_files) && nilfs_segctor_clean(sci))
866                 ret++;
867
868         spin_unlock(&nilfs->ns_inode_lock);
869         return ret;
870 }
871
872 static void nilfs_segctor_clear_metadata_dirty(struct nilfs_sc_info *sci)
873 {
874         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
875
876         nilfs_mdt_clear_dirty(sci->sc_root->ifile);
877         nilfs_mdt_clear_dirty(nilfs->ns_cpfile);
878         nilfs_mdt_clear_dirty(nilfs->ns_sufile);
879         nilfs_mdt_clear_dirty(nilfs->ns_dat);
880 }
881
882 static int nilfs_segctor_create_checkpoint(struct nilfs_sc_info *sci)
883 {
884         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
885         struct buffer_head *bh_cp;
886         struct nilfs_checkpoint *raw_cp;
887         int err;
888
889         /* XXX: this interface will be changed */
890         err = nilfs_cpfile_get_checkpoint(nilfs->ns_cpfile, nilfs->ns_cno, 1,
891                                           &raw_cp, &bh_cp);
892         if (likely(!err)) {
893                 /*
894                  * The following code is duplicated with cpfile.  But, it is
895                  * needed to collect the checkpoint even if it was not newly
896                  * created.
897                  */
898                 mark_buffer_dirty(bh_cp);
899                 nilfs_mdt_mark_dirty(nilfs->ns_cpfile);
900                 nilfs_cpfile_put_checkpoint(
901                         nilfs->ns_cpfile, nilfs->ns_cno, bh_cp);
902         } else if (err == -EINVAL || err == -ENOENT) {
903                 nilfs_error(sci->sc_super,
904                             "checkpoint creation failed due to metadata corruption.");
905                 err = -EIO;
906         }
907         return err;
908 }
909
910 static int nilfs_segctor_fill_in_checkpoint(struct nilfs_sc_info *sci)
911 {
912         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
913         struct buffer_head *bh_cp;
914         struct nilfs_checkpoint *raw_cp;
915         int err;
916
917         err = nilfs_cpfile_get_checkpoint(nilfs->ns_cpfile, nilfs->ns_cno, 0,
918                                           &raw_cp, &bh_cp);
919         if (unlikely(err)) {
920                 if (err == -EINVAL || err == -ENOENT) {
921                         nilfs_error(sci->sc_super,
922                                     "checkpoint finalization failed due to metadata corruption.");
923                         err = -EIO;
924                 }
925                 goto failed_ibh;
926         }
927         raw_cp->cp_snapshot_list.ssl_next = 0;
928         raw_cp->cp_snapshot_list.ssl_prev = 0;
929         raw_cp->cp_inodes_count =
930                 cpu_to_le64(atomic64_read(&sci->sc_root->inodes_count));
931         raw_cp->cp_blocks_count =
932                 cpu_to_le64(atomic64_read(&sci->sc_root->blocks_count));
933         raw_cp->cp_nblk_inc =
934                 cpu_to_le64(sci->sc_nblk_inc + sci->sc_nblk_this_inc);
935         raw_cp->cp_create = cpu_to_le64(sci->sc_seg_ctime);
936         raw_cp->cp_cno = cpu_to_le64(nilfs->ns_cno);
937
938         if (test_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags))
939                 nilfs_checkpoint_clear_minor(raw_cp);
940         else
941                 nilfs_checkpoint_set_minor(raw_cp);
942
943         nilfs_write_inode_common(sci->sc_root->ifile,
944                                  &raw_cp->cp_ifile_inode, 1);
945         nilfs_cpfile_put_checkpoint(nilfs->ns_cpfile, nilfs->ns_cno, bh_cp);
946         return 0;
947
948  failed_ibh:
949         return err;
950 }
951
952 static void nilfs_fill_in_file_bmap(struct inode *ifile,
953                                     struct nilfs_inode_info *ii)
954
955 {
956         struct buffer_head *ibh;
957         struct nilfs_inode *raw_inode;
958
959         if (test_bit(NILFS_I_BMAP, &ii->i_state)) {
960                 ibh = ii->i_bh;
961                 BUG_ON(!ibh);
962                 raw_inode = nilfs_ifile_map_inode(ifile, ii->vfs_inode.i_ino,
963                                                   ibh);
964                 nilfs_bmap_write(ii->i_bmap, raw_inode);
965                 nilfs_ifile_unmap_inode(ifile, ii->vfs_inode.i_ino, ibh);
966         }
967 }
968
969 static void nilfs_segctor_fill_in_file_bmap(struct nilfs_sc_info *sci)
970 {
971         struct nilfs_inode_info *ii;
972
973         list_for_each_entry(ii, &sci->sc_dirty_files, i_dirty) {
974                 nilfs_fill_in_file_bmap(sci->sc_root->ifile, ii);
975                 set_bit(NILFS_I_COLLECTED, &ii->i_state);
976         }
977 }
978
979 static void nilfs_segctor_fill_in_super_root(struct nilfs_sc_info *sci,
980                                              struct the_nilfs *nilfs)
981 {
982         struct buffer_head *bh_sr;
983         struct nilfs_super_root *raw_sr;
984         unsigned int isz, srsz;
985
986         bh_sr = NILFS_LAST_SEGBUF(&sci->sc_segbufs)->sb_super_root;
987         raw_sr = (struct nilfs_super_root *)bh_sr->b_data;
988         isz = nilfs->ns_inode_size;
989         srsz = NILFS_SR_BYTES(isz);
990
991         raw_sr->sr_bytes = cpu_to_le16(srsz);
992         raw_sr->sr_nongc_ctime
993                 = cpu_to_le64(nilfs_doing_gc() ?
994                               nilfs->ns_nongc_ctime : sci->sc_seg_ctime);
995         raw_sr->sr_flags = 0;
996
997         nilfs_write_inode_common(nilfs->ns_dat, (void *)raw_sr +
998                                  NILFS_SR_DAT_OFFSET(isz), 1);
999         nilfs_write_inode_common(nilfs->ns_cpfile, (void *)raw_sr +
1000                                  NILFS_SR_CPFILE_OFFSET(isz), 1);
1001         nilfs_write_inode_common(nilfs->ns_sufile, (void *)raw_sr +
1002                                  NILFS_SR_SUFILE_OFFSET(isz), 1);
1003         memset((void *)raw_sr + srsz, 0, nilfs->ns_blocksize - srsz);
1004 }
1005
1006 static void nilfs_redirty_inodes(struct list_head *head)
1007 {
1008         struct nilfs_inode_info *ii;
1009
1010         list_for_each_entry(ii, head, i_dirty) {
1011                 if (test_bit(NILFS_I_COLLECTED, &ii->i_state))
1012                         clear_bit(NILFS_I_COLLECTED, &ii->i_state);
1013         }
1014 }
1015
1016 static void nilfs_drop_collected_inodes(struct list_head *head)
1017 {
1018         struct nilfs_inode_info *ii;
1019
1020         list_for_each_entry(ii, head, i_dirty) {
1021                 if (!test_and_clear_bit(NILFS_I_COLLECTED, &ii->i_state))
1022                         continue;
1023
1024                 clear_bit(NILFS_I_INODE_SYNC, &ii->i_state);
1025                 set_bit(NILFS_I_UPDATED, &ii->i_state);
1026         }
1027 }
1028
1029 static int nilfs_segctor_apply_buffers(struct nilfs_sc_info *sci,
1030                                        struct inode *inode,
1031                                        struct list_head *listp,
1032                                        int (*collect)(struct nilfs_sc_info *,
1033                                                       struct buffer_head *,
1034                                                       struct inode *))
1035 {
1036         struct buffer_head *bh, *n;
1037         int err = 0;
1038
1039         if (collect) {
1040                 list_for_each_entry_safe(bh, n, listp, b_assoc_buffers) {
1041                         list_del_init(&bh->b_assoc_buffers);
1042                         err = collect(sci, bh, inode);
1043                         brelse(bh);
1044                         if (unlikely(err))
1045                                 goto dispose_buffers;
1046                 }
1047                 return 0;
1048         }
1049
1050  dispose_buffers:
1051         while (!list_empty(listp)) {
1052                 bh = list_first_entry(listp, struct buffer_head,
1053                                       b_assoc_buffers);
1054                 list_del_init(&bh->b_assoc_buffers);
1055                 brelse(bh);
1056         }
1057         return err;
1058 }
1059
1060 static size_t nilfs_segctor_buffer_rest(struct nilfs_sc_info *sci)
1061 {
1062         /* Remaining number of blocks within segment buffer */
1063         return sci->sc_segbuf_nblocks -
1064                 (sci->sc_nblk_this_inc + sci->sc_curseg->sb_sum.nblocks);
1065 }
1066
1067 static int nilfs_segctor_scan_file(struct nilfs_sc_info *sci,
1068                                    struct inode *inode,
1069                                    const struct nilfs_sc_operations *sc_ops)
1070 {
1071         LIST_HEAD(data_buffers);
1072         LIST_HEAD(node_buffers);
1073         int err;
1074
1075         if (!(sci->sc_stage.flags & NILFS_CF_NODE)) {
1076                 size_t n, rest = nilfs_segctor_buffer_rest(sci);
1077
1078                 n = nilfs_lookup_dirty_data_buffers(
1079                         inode, &data_buffers, rest + 1, 0, LLONG_MAX);
1080                 if (n > rest) {
1081                         err = nilfs_segctor_apply_buffers(
1082                                 sci, inode, &data_buffers,
1083                                 sc_ops->collect_data);
1084                         BUG_ON(!err); /* always receive -E2BIG or true error */
1085                         goto break_or_fail;
1086                 }
1087         }
1088         nilfs_lookup_dirty_node_buffers(inode, &node_buffers);
1089
1090         if (!(sci->sc_stage.flags & NILFS_CF_NODE)) {
1091                 err = nilfs_segctor_apply_buffers(
1092                         sci, inode, &data_buffers, sc_ops->collect_data);
1093                 if (unlikely(err)) {
1094                         /* dispose node list */
1095                         nilfs_segctor_apply_buffers(
1096                                 sci, inode, &node_buffers, NULL);
1097                         goto break_or_fail;
1098                 }
1099                 sci->sc_stage.flags |= NILFS_CF_NODE;
1100         }
1101         /* Collect node */
1102         err = nilfs_segctor_apply_buffers(
1103                 sci, inode, &node_buffers, sc_ops->collect_node);
1104         if (unlikely(err))
1105                 goto break_or_fail;
1106
1107         nilfs_bmap_lookup_dirty_buffers(NILFS_I(inode)->i_bmap, &node_buffers);
1108         err = nilfs_segctor_apply_buffers(
1109                 sci, inode, &node_buffers, sc_ops->collect_bmap);
1110         if (unlikely(err))
1111                 goto break_or_fail;
1112
1113         nilfs_segctor_end_finfo(sci, inode);
1114         sci->sc_stage.flags &= ~NILFS_CF_NODE;
1115
1116  break_or_fail:
1117         return err;
1118 }
1119
1120 static int nilfs_segctor_scan_file_dsync(struct nilfs_sc_info *sci,
1121                                          struct inode *inode)
1122 {
1123         LIST_HEAD(data_buffers);
1124         size_t n, rest = nilfs_segctor_buffer_rest(sci);
1125         int err;
1126
1127         n = nilfs_lookup_dirty_data_buffers(inode, &data_buffers, rest + 1,
1128                                             sci->sc_dsync_start,
1129                                             sci->sc_dsync_end);
1130
1131         err = nilfs_segctor_apply_buffers(sci, inode, &data_buffers,
1132                                           nilfs_collect_file_data);
1133         if (!err) {
1134                 nilfs_segctor_end_finfo(sci, inode);
1135                 BUG_ON(n > rest);
1136                 /* always receive -E2BIG or true error if n > rest */
1137         }
1138         return err;
1139 }
1140
1141 static int nilfs_segctor_collect_blocks(struct nilfs_sc_info *sci, int mode)
1142 {
1143         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
1144         struct list_head *head;
1145         struct nilfs_inode_info *ii;
1146         size_t ndone;
1147         int err = 0;
1148
1149         switch (nilfs_sc_cstage_get(sci)) {
1150         case NILFS_ST_INIT:
1151                 /* Pre-processes */
1152                 sci->sc_stage.flags = 0;
1153
1154                 if (!test_bit(NILFS_SC_UNCLOSED, &sci->sc_flags)) {
1155                         sci->sc_nblk_inc = 0;
1156                         sci->sc_curseg->sb_sum.flags = NILFS_SS_LOGBGN;
1157                         if (mode == SC_LSEG_DSYNC) {
1158                                 nilfs_sc_cstage_set(sci, NILFS_ST_DSYNC);
1159                                 goto dsync_mode;
1160                         }
1161                 }
1162
1163                 sci->sc_stage.dirty_file_ptr = NULL;
1164                 sci->sc_stage.gc_inode_ptr = NULL;
1165                 if (mode == SC_FLUSH_DAT) {
1166                         nilfs_sc_cstage_set(sci, NILFS_ST_DAT);
1167                         goto dat_stage;
1168                 }
1169                 nilfs_sc_cstage_inc(sci);  /* Fall through */
1170         case NILFS_ST_GC:
1171                 if (nilfs_doing_gc()) {
1172                         head = &sci->sc_gc_inodes;
1173                         ii = list_prepare_entry(sci->sc_stage.gc_inode_ptr,
1174                                                 head, i_dirty);
1175                         list_for_each_entry_continue(ii, head, i_dirty) {
1176                                 err = nilfs_segctor_scan_file(
1177                                         sci, &ii->vfs_inode,
1178                                         &nilfs_sc_file_ops);
1179                                 if (unlikely(err)) {
1180                                         sci->sc_stage.gc_inode_ptr = list_entry(
1181                                                 ii->i_dirty.prev,
1182                                                 struct nilfs_inode_info,
1183                                                 i_dirty);
1184                                         goto break_or_fail;
1185                                 }
1186                                 set_bit(NILFS_I_COLLECTED, &ii->i_state);
1187                         }
1188                         sci->sc_stage.gc_inode_ptr = NULL;
1189                 }
1190                 nilfs_sc_cstage_inc(sci);  /* Fall through */
1191         case NILFS_ST_FILE:
1192                 head = &sci->sc_dirty_files;
1193                 ii = list_prepare_entry(sci->sc_stage.dirty_file_ptr, head,
1194                                         i_dirty);
1195                 list_for_each_entry_continue(ii, head, i_dirty) {
1196                         clear_bit(NILFS_I_DIRTY, &ii->i_state);
1197
1198                         err = nilfs_segctor_scan_file(sci, &ii->vfs_inode,
1199                                                       &nilfs_sc_file_ops);
1200                         if (unlikely(err)) {
1201                                 sci->sc_stage.dirty_file_ptr =
1202                                         list_entry(ii->i_dirty.prev,
1203                                                    struct nilfs_inode_info,
1204                                                    i_dirty);
1205                                 goto break_or_fail;
1206                         }
1207                         /* sci->sc_stage.dirty_file_ptr = NILFS_I(inode); */
1208                         /* XXX: required ? */
1209                 }
1210                 sci->sc_stage.dirty_file_ptr = NULL;
1211                 if (mode == SC_FLUSH_FILE) {
1212                         nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1213                         return 0;
1214                 }
1215                 nilfs_sc_cstage_inc(sci);
1216                 sci->sc_stage.flags |= NILFS_CF_IFILE_STARTED;
1217                 /* Fall through */
1218         case NILFS_ST_IFILE:
1219                 err = nilfs_segctor_scan_file(sci, sci->sc_root->ifile,
1220                                               &nilfs_sc_file_ops);
1221                 if (unlikely(err))
1222                         break;
1223                 nilfs_sc_cstage_inc(sci);
1224                 /* Creating a checkpoint */
1225                 err = nilfs_segctor_create_checkpoint(sci);
1226                 if (unlikely(err))
1227                         break;
1228                 /* Fall through */
1229         case NILFS_ST_CPFILE:
1230                 err = nilfs_segctor_scan_file(sci, nilfs->ns_cpfile,
1231                                               &nilfs_sc_file_ops);
1232                 if (unlikely(err))
1233                         break;
1234                 nilfs_sc_cstage_inc(sci);  /* Fall through */
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);  /* Fall through */
1251         case NILFS_ST_DAT:
1252  dat_stage:
1253                 err = nilfs_segctor_scan_file(sci, nilfs->ns_dat,
1254                                               &nilfs_sc_dat_ops);
1255                 if (unlikely(err))
1256                         break;
1257                 if (mode == SC_FLUSH_DAT) {
1258                         nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1259                         return 0;
1260                 }
1261                 nilfs_sc_cstage_inc(sci);  /* Fall through */
1262         case NILFS_ST_SR:
1263                 if (mode == SC_LSEG_SR) {
1264                         /* Appending a super root */
1265                         err = nilfs_segctor_add_super_root(sci);
1266                         if (unlikely(err))
1267                                 break;
1268                 }
1269                 /* End of a logical segment */
1270                 sci->sc_curseg->sb_sum.flags |= NILFS_SS_LOGEND;
1271                 nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1272                 return 0;
1273         case NILFS_ST_DSYNC:
1274  dsync_mode:
1275                 sci->sc_curseg->sb_sum.flags |= NILFS_SS_SYNDT;
1276                 ii = sci->sc_dsync_inode;
1277                 if (!test_bit(NILFS_I_BUSY, &ii->i_state))
1278                         break;
1279
1280                 err = nilfs_segctor_scan_file_dsync(sci, &ii->vfs_inode);
1281                 if (unlikely(err))
1282                         break;
1283                 sci->sc_curseg->sb_sum.flags |= NILFS_SS_LOGEND;
1284                 nilfs_sc_cstage_set(sci, NILFS_ST_DONE);
1285                 return 0;
1286         case NILFS_ST_DONE:
1287                 return 0;
1288         default:
1289                 BUG();
1290         }
1291
1292  break_or_fail:
1293         return err;
1294 }
1295
1296 /**
1297  * nilfs_segctor_begin_construction - setup segment buffer to make a new log
1298  * @sci: nilfs_sc_info
1299  * @nilfs: nilfs object
1300  */
1301 static int nilfs_segctor_begin_construction(struct nilfs_sc_info *sci,
1302                                             struct the_nilfs *nilfs)
1303 {
1304         struct nilfs_segment_buffer *segbuf, *prev;
1305         __u64 nextnum;
1306         int err, alloc = 0;
1307
1308         segbuf = nilfs_segbuf_new(sci->sc_super);
1309         if (unlikely(!segbuf))
1310                 return -ENOMEM;
1311
1312         if (list_empty(&sci->sc_write_logs)) {
1313                 nilfs_segbuf_map(segbuf, nilfs->ns_segnum,
1314                                  nilfs->ns_pseg_offset, nilfs);
1315                 if (segbuf->sb_rest_blocks < NILFS_PSEG_MIN_BLOCKS) {
1316                         nilfs_shift_to_next_segment(nilfs);
1317                         nilfs_segbuf_map(segbuf, nilfs->ns_segnum, 0, nilfs);
1318                 }
1319
1320                 segbuf->sb_sum.seg_seq = nilfs->ns_seg_seq;
1321                 nextnum = nilfs->ns_nextnum;
1322
1323                 if (nilfs->ns_segnum == nilfs->ns_nextnum)
1324                         /* Start from the head of a new full segment */
1325                         alloc++;
1326         } else {
1327                 /* Continue logs */
1328                 prev = NILFS_LAST_SEGBUF(&sci->sc_write_logs);
1329                 nilfs_segbuf_map_cont(segbuf, prev);
1330                 segbuf->sb_sum.seg_seq = prev->sb_sum.seg_seq;
1331                 nextnum = prev->sb_nextnum;
1332
1333                 if (segbuf->sb_rest_blocks < NILFS_PSEG_MIN_BLOCKS) {
1334                         nilfs_segbuf_map(segbuf, prev->sb_nextnum, 0, nilfs);
1335                         segbuf->sb_sum.seg_seq++;
1336                         alloc++;
1337                 }
1338         }
1339
1340         err = nilfs_sufile_mark_dirty(nilfs->ns_sufile, segbuf->sb_segnum);
1341         if (err)
1342                 goto failed;
1343
1344         if (alloc) {
1345                 err = nilfs_sufile_alloc(nilfs->ns_sufile, &nextnum);
1346                 if (err)
1347                         goto failed;
1348         }
1349         nilfs_segbuf_set_next_segnum(segbuf, nextnum, nilfs);
1350
1351         BUG_ON(!list_empty(&sci->sc_segbufs));
1352         list_add_tail(&segbuf->sb_list, &sci->sc_segbufs);
1353         sci->sc_segbuf_nblocks = segbuf->sb_rest_blocks;
1354         return 0;
1355
1356  failed:
1357         nilfs_segbuf_free(segbuf);
1358         return err;
1359 }
1360
1361 static int nilfs_segctor_extend_segments(struct nilfs_sc_info *sci,
1362                                          struct the_nilfs *nilfs, int nadd)
1363 {
1364         struct nilfs_segment_buffer *segbuf, *prev;
1365         struct inode *sufile = nilfs->ns_sufile;
1366         __u64 nextnextnum;
1367         LIST_HEAD(list);
1368         int err, ret, i;
1369
1370         prev = NILFS_LAST_SEGBUF(&sci->sc_segbufs);
1371         /*
1372          * Since the segment specified with nextnum might be allocated during
1373          * the previous construction, the buffer including its segusage may
1374          * not be dirty.  The following call ensures that the buffer is dirty
1375          * and will pin the buffer on memory until the sufile is written.
1376          */
1377         err = nilfs_sufile_mark_dirty(sufile, prev->sb_nextnum);
1378         if (unlikely(err))
1379                 return err;
1380
1381         for (i = 0; i < nadd; i++) {
1382                 /* extend segment info */
1383                 err = -ENOMEM;
1384                 segbuf = nilfs_segbuf_new(sci->sc_super);
1385                 if (unlikely(!segbuf))
1386                         goto failed;
1387
1388                 /* map this buffer to region of segment on-disk */
1389                 nilfs_segbuf_map(segbuf, prev->sb_nextnum, 0, nilfs);
1390                 sci->sc_segbuf_nblocks += segbuf->sb_rest_blocks;
1391
1392                 /* allocate the next next full segment */
1393                 err = nilfs_sufile_alloc(sufile, &nextnextnum);
1394                 if (unlikely(err))
1395                         goto failed_segbuf;
1396
1397                 segbuf->sb_sum.seg_seq = prev->sb_sum.seg_seq + 1;
1398                 nilfs_segbuf_set_next_segnum(segbuf, nextnextnum, nilfs);
1399
1400                 list_add_tail(&segbuf->sb_list, &list);
1401                 prev = segbuf;
1402         }
1403         list_splice_tail(&list, &sci->sc_segbufs);
1404         return 0;
1405
1406  failed_segbuf:
1407         nilfs_segbuf_free(segbuf);
1408  failed:
1409         list_for_each_entry(segbuf, &list, sb_list) {
1410                 ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1411                 WARN_ON(ret); /* never fails */
1412         }
1413         nilfs_destroy_logs(&list);
1414         return err;
1415 }
1416
1417 static void nilfs_free_incomplete_logs(struct list_head *logs,
1418                                        struct the_nilfs *nilfs)
1419 {
1420         struct nilfs_segment_buffer *segbuf, *prev;
1421         struct inode *sufile = nilfs->ns_sufile;
1422         int ret;
1423
1424         segbuf = NILFS_FIRST_SEGBUF(logs);
1425         if (nilfs->ns_nextnum != segbuf->sb_nextnum) {
1426                 ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1427                 WARN_ON(ret); /* never fails */
1428         }
1429         if (atomic_read(&segbuf->sb_err)) {
1430                 /* Case 1: The first segment failed */
1431                 if (segbuf->sb_pseg_start != segbuf->sb_fseg_start)
1432                         /*
1433                          * Case 1a:  Partial segment appended into an existing
1434                          * segment
1435                          */
1436                         nilfs_terminate_segment(nilfs, segbuf->sb_fseg_start,
1437                                                 segbuf->sb_fseg_end);
1438                 else /* Case 1b:  New full segment */
1439                         set_nilfs_discontinued(nilfs);
1440         }
1441
1442         prev = segbuf;
1443         list_for_each_entry_continue(segbuf, logs, sb_list) {
1444                 if (prev->sb_nextnum != segbuf->sb_nextnum) {
1445                         ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1446                         WARN_ON(ret); /* never fails */
1447                 }
1448                 if (atomic_read(&segbuf->sb_err) &&
1449                     segbuf->sb_segnum != nilfs->ns_nextnum)
1450                         /* Case 2: extended segment (!= next) failed */
1451                         nilfs_sufile_set_error(sufile, segbuf->sb_segnum);
1452                 prev = segbuf;
1453         }
1454 }
1455
1456 static void nilfs_segctor_update_segusage(struct nilfs_sc_info *sci,
1457                                           struct inode *sufile)
1458 {
1459         struct nilfs_segment_buffer *segbuf;
1460         unsigned long live_blocks;
1461         int ret;
1462
1463         list_for_each_entry(segbuf, &sci->sc_segbufs, sb_list) {
1464                 live_blocks = segbuf->sb_sum.nblocks +
1465                         (segbuf->sb_pseg_start - segbuf->sb_fseg_start);
1466                 ret = nilfs_sufile_set_segment_usage(sufile, segbuf->sb_segnum,
1467                                                      live_blocks,
1468                                                      sci->sc_seg_ctime);
1469                 WARN_ON(ret); /* always succeed because the segusage is dirty */
1470         }
1471 }
1472
1473 static void nilfs_cancel_segusage(struct list_head *logs, struct inode *sufile)
1474 {
1475         struct nilfs_segment_buffer *segbuf;
1476         int ret;
1477
1478         segbuf = NILFS_FIRST_SEGBUF(logs);
1479         ret = nilfs_sufile_set_segment_usage(sufile, segbuf->sb_segnum,
1480                                              segbuf->sb_pseg_start -
1481                                              segbuf->sb_fseg_start, 0);
1482         WARN_ON(ret); /* always succeed because the segusage is dirty */
1483
1484         list_for_each_entry_continue(segbuf, logs, sb_list) {
1485                 ret = nilfs_sufile_set_segment_usage(sufile, segbuf->sb_segnum,
1486                                                      0, 0);
1487                 WARN_ON(ret); /* always succeed */
1488         }
1489 }
1490
1491 static void nilfs_segctor_truncate_segments(struct nilfs_sc_info *sci,
1492                                             struct nilfs_segment_buffer *last,
1493                                             struct inode *sufile)
1494 {
1495         struct nilfs_segment_buffer *segbuf = last;
1496         int ret;
1497
1498         list_for_each_entry_continue(segbuf, &sci->sc_segbufs, sb_list) {
1499                 sci->sc_segbuf_nblocks -= segbuf->sb_rest_blocks;
1500                 ret = nilfs_sufile_free(sufile, segbuf->sb_nextnum);
1501                 WARN_ON(ret);
1502         }
1503         nilfs_truncate_logs(&sci->sc_segbufs, last);
1504 }
1505
1506
1507 static int nilfs_segctor_collect(struct nilfs_sc_info *sci,
1508                                  struct the_nilfs *nilfs, int mode)
1509 {
1510         struct nilfs_cstage prev_stage = sci->sc_stage;
1511         int err, nadd = 1;
1512
1513         /* Collection retry loop */
1514         for (;;) {
1515                 sci->sc_nblk_this_inc = 0;
1516                 sci->sc_curseg = NILFS_FIRST_SEGBUF(&sci->sc_segbufs);
1517
1518                 err = nilfs_segctor_reset_segment_buffer(sci);
1519                 if (unlikely(err))
1520                         goto failed;
1521
1522                 err = nilfs_segctor_collect_blocks(sci, mode);
1523                 sci->sc_nblk_this_inc += sci->sc_curseg->sb_sum.nblocks;
1524                 if (!err)
1525                         break;
1526
1527                 if (unlikely(err != -E2BIG))
1528                         goto failed;
1529
1530                 /* The current segment is filled up */
1531                 if (mode != SC_LSEG_SR ||
1532                     nilfs_sc_cstage_get(sci) < NILFS_ST_CPFILE)
1533                         break;
1534
1535                 nilfs_clear_logs(&sci->sc_segbufs);
1536
1537                 if (sci->sc_stage.flags & NILFS_CF_SUFREED) {
1538                         err = nilfs_sufile_cancel_freev(nilfs->ns_sufile,
1539                                                         sci->sc_freesegs,
1540                                                         sci->sc_nfreesegs,
1541                                                         NULL);
1542                         WARN_ON(err); /* do not happen */
1543                         sci->sc_stage.flags &= ~NILFS_CF_SUFREED;
1544                 }
1545
1546                 err = nilfs_segctor_extend_segments(sci, nilfs, nadd);
1547                 if (unlikely(err))
1548                         return err;
1549
1550                 nadd = min_t(int, nadd << 1, SC_MAX_SEGDELTA);
1551                 sci->sc_stage = prev_stage;
1552         }
1553         nilfs_segctor_zeropad_segsum(sci);
1554         nilfs_segctor_truncate_segments(sci, sci->sc_curseg, nilfs->ns_sufile);
1555         return 0;
1556
1557  failed:
1558         return err;
1559 }
1560
1561 static void nilfs_list_replace_buffer(struct buffer_head *old_bh,
1562                                       struct buffer_head *new_bh)
1563 {
1564         BUG_ON(!list_empty(&new_bh->b_assoc_buffers));
1565
1566         list_replace_init(&old_bh->b_assoc_buffers, &new_bh->b_assoc_buffers);
1567         /* The caller must release old_bh */
1568 }
1569
1570 static int
1571 nilfs_segctor_update_payload_blocknr(struct nilfs_sc_info *sci,
1572                                      struct nilfs_segment_buffer *segbuf,
1573                                      int mode)
1574 {
1575         struct inode *inode = NULL;
1576         sector_t blocknr;
1577         unsigned long nfinfo = segbuf->sb_sum.nfinfo;
1578         unsigned long nblocks = 0, ndatablk = 0;
1579         const struct nilfs_sc_operations *sc_op = NULL;
1580         struct nilfs_segsum_pointer ssp;
1581         struct nilfs_finfo *finfo = NULL;
1582         union nilfs_binfo binfo;
1583         struct buffer_head *bh, *bh_org;
1584         ino_t ino = 0;
1585         int err = 0;
1586
1587         if (!nfinfo)
1588                 goto out;
1589
1590         blocknr = segbuf->sb_pseg_start + segbuf->sb_sum.nsumblk;
1591         ssp.bh = NILFS_SEGBUF_FIRST_BH(&segbuf->sb_segsum_buffers);
1592         ssp.offset = sizeof(struct nilfs_segment_summary);
1593
1594         list_for_each_entry(bh, &segbuf->sb_payload_buffers, b_assoc_buffers) {
1595                 if (bh == segbuf->sb_super_root)
1596                         break;
1597                 if (!finfo) {
1598                         finfo = nilfs_segctor_map_segsum_entry(
1599                                 sci, &ssp, sizeof(*finfo));
1600                         ino = le64_to_cpu(finfo->fi_ino);
1601                         nblocks = le32_to_cpu(finfo->fi_nblocks);
1602                         ndatablk = le32_to_cpu(finfo->fi_ndatablk);
1603
1604                         inode = bh->b_page->mapping->host;
1605
1606                         if (mode == SC_LSEG_DSYNC)
1607                                 sc_op = &nilfs_sc_dsync_ops;
1608                         else if (ino == NILFS_DAT_INO)
1609                                 sc_op = &nilfs_sc_dat_ops;
1610                         else /* file blocks */
1611                                 sc_op = &nilfs_sc_file_ops;
1612                 }
1613                 bh_org = bh;
1614                 get_bh(bh_org);
1615                 err = nilfs_bmap_assign(NILFS_I(inode)->i_bmap, &bh, blocknr,
1616                                         &binfo);
1617                 if (bh != bh_org)
1618                         nilfs_list_replace_buffer(bh_org, bh);
1619                 brelse(bh_org);
1620                 if (unlikely(err))
1621                         goto failed_bmap;
1622
1623                 if (ndatablk > 0)
1624                         sc_op->write_data_binfo(sci, &ssp, &binfo);
1625                 else
1626                         sc_op->write_node_binfo(sci, &ssp, &binfo);
1627
1628                 blocknr++;
1629                 if (--nblocks == 0) {
1630                         finfo = NULL;
1631                         if (--nfinfo == 0)
1632                                 break;
1633                 } else if (ndatablk > 0)
1634                         ndatablk--;
1635         }
1636  out:
1637         return 0;
1638
1639  failed_bmap:
1640         return err;
1641 }
1642
1643 static int nilfs_segctor_assign(struct nilfs_sc_info *sci, int mode)
1644 {
1645         struct nilfs_segment_buffer *segbuf;
1646         int err;
1647
1648         list_for_each_entry(segbuf, &sci->sc_segbufs, sb_list) {
1649                 err = nilfs_segctor_update_payload_blocknr(sci, segbuf, mode);
1650                 if (unlikely(err))
1651                         return err;
1652                 nilfs_segbuf_fill_in_segsum(segbuf);
1653         }
1654         return 0;
1655 }
1656
1657 static void nilfs_begin_page_io(struct page *page)
1658 {
1659         if (!page || PageWriteback(page))
1660                 /*
1661                  * For split b-tree node pages, this function may be called
1662                  * twice.  We ignore the 2nd or later calls by this check.
1663                  */
1664                 return;
1665
1666         lock_page(page);
1667         clear_page_dirty_for_io(page);
1668         set_page_writeback(page);
1669         unlock_page(page);
1670 }
1671
1672 static void nilfs_segctor_prepare_write(struct nilfs_sc_info *sci)
1673 {
1674         struct nilfs_segment_buffer *segbuf;
1675         struct page *bd_page = NULL, *fs_page = NULL;
1676
1677         list_for_each_entry(segbuf, &sci->sc_segbufs, sb_list) {
1678                 struct buffer_head *bh;
1679
1680                 list_for_each_entry(bh, &segbuf->sb_segsum_buffers,
1681                                     b_assoc_buffers) {
1682                         if (bh->b_page != bd_page) {
1683                                 if (bd_page) {
1684                                         lock_page(bd_page);
1685                                         clear_page_dirty_for_io(bd_page);
1686                                         set_page_writeback(bd_page);
1687                                         unlock_page(bd_page);
1688                                 }
1689                                 bd_page = bh->b_page;
1690                         }
1691                 }
1692
1693                 list_for_each_entry(bh, &segbuf->sb_payload_buffers,
1694                                     b_assoc_buffers) {
1695                         set_buffer_async_write(bh);
1696                         if (bh == segbuf->sb_super_root) {
1697                                 if (bh->b_page != bd_page) {
1698                                         lock_page(bd_page);
1699                                         clear_page_dirty_for_io(bd_page);
1700                                         set_page_writeback(bd_page);
1701                                         unlock_page(bd_page);
1702                                         bd_page = bh->b_page;
1703                                 }
1704                                 break;
1705                         }
1706                         if (bh->b_page != fs_page) {
1707                                 nilfs_begin_page_io(fs_page);
1708                                 fs_page = bh->b_page;
1709                         }
1710                 }
1711         }
1712         if (bd_page) {
1713                 lock_page(bd_page);
1714                 clear_page_dirty_for_io(bd_page);
1715                 set_page_writeback(bd_page);
1716                 unlock_page(bd_page);
1717         }
1718         nilfs_begin_page_io(fs_page);
1719 }
1720
1721 static int nilfs_segctor_write(struct nilfs_sc_info *sci,
1722                                struct the_nilfs *nilfs)
1723 {
1724         int ret;
1725
1726         ret = nilfs_write_logs(&sci->sc_segbufs, nilfs);
1727         list_splice_tail_init(&sci->sc_segbufs, &sci->sc_write_logs);
1728         return ret;
1729 }
1730
1731 static void nilfs_end_page_io(struct page *page, int err)
1732 {
1733         if (!page)
1734                 return;
1735
1736         if (buffer_nilfs_node(page_buffers(page)) && !PageWriteback(page)) {
1737                 /*
1738                  * For b-tree node pages, this function may be called twice
1739                  * or more because they might be split in a segment.
1740                  */
1741                 if (PageDirty(page)) {
1742                         /*
1743                          * For pages holding split b-tree node buffers, dirty
1744                          * flag on the buffers may be cleared discretely.
1745                          * In that case, the page is once redirtied for
1746                          * remaining buffers, and it must be cancelled if
1747                          * all the buffers get cleaned later.
1748                          */
1749                         lock_page(page);
1750                         if (nilfs_page_buffers_clean(page))
1751                                 __nilfs_clear_page_dirty(page);
1752                         unlock_page(page);
1753                 }
1754                 return;
1755         }
1756
1757         if (!err) {
1758                 if (!nilfs_page_buffers_clean(page))
1759                         __set_page_dirty_nobuffers(page);
1760                 ClearPageError(page);
1761         } else {
1762                 __set_page_dirty_nobuffers(page);
1763                 SetPageError(page);
1764         }
1765
1766         end_page_writeback(page);
1767 }
1768
1769 static void nilfs_abort_logs(struct list_head *logs, int err)
1770 {
1771         struct nilfs_segment_buffer *segbuf;
1772         struct page *bd_page = NULL, *fs_page = NULL;
1773         struct buffer_head *bh;
1774
1775         if (list_empty(logs))
1776                 return;
1777
1778         list_for_each_entry(segbuf, logs, sb_list) {
1779                 list_for_each_entry(bh, &segbuf->sb_segsum_buffers,
1780                                     b_assoc_buffers) {
1781                         if (bh->b_page != bd_page) {
1782                                 if (bd_page)
1783                                         end_page_writeback(bd_page);
1784                                 bd_page = bh->b_page;
1785                         }
1786                 }
1787
1788                 list_for_each_entry(bh, &segbuf->sb_payload_buffers,
1789                                     b_assoc_buffers) {
1790                         clear_buffer_async_write(bh);
1791                         if (bh == segbuf->sb_super_root) {
1792                                 if (bh->b_page != bd_page) {
1793                                         end_page_writeback(bd_page);
1794                                         bd_page = bh->b_page;
1795                                 }
1796                                 break;
1797                         }
1798                         if (bh->b_page != fs_page) {
1799                                 nilfs_end_page_io(fs_page, err);
1800                                 fs_page = bh->b_page;
1801                         }
1802                 }
1803         }
1804         if (bd_page)
1805                 end_page_writeback(bd_page);
1806
1807         nilfs_end_page_io(fs_page, err);
1808 }
1809
1810 static void nilfs_segctor_abort_construction(struct nilfs_sc_info *sci,
1811                                              struct the_nilfs *nilfs, int err)
1812 {
1813         LIST_HEAD(logs);
1814         int ret;
1815
1816         list_splice_tail_init(&sci->sc_write_logs, &logs);
1817         ret = nilfs_wait_on_logs(&logs);
1818         nilfs_abort_logs(&logs, ret ? : err);
1819
1820         list_splice_tail_init(&sci->sc_segbufs, &logs);
1821         nilfs_cancel_segusage(&logs, nilfs->ns_sufile);
1822         nilfs_free_incomplete_logs(&logs, nilfs);
1823
1824         if (sci->sc_stage.flags & NILFS_CF_SUFREED) {
1825                 ret = nilfs_sufile_cancel_freev(nilfs->ns_sufile,
1826                                                 sci->sc_freesegs,
1827                                                 sci->sc_nfreesegs,
1828                                                 NULL);
1829                 WARN_ON(ret); /* do not happen */
1830         }
1831
1832         nilfs_destroy_logs(&logs);
1833 }
1834
1835 static void nilfs_set_next_segment(struct the_nilfs *nilfs,
1836                                    struct nilfs_segment_buffer *segbuf)
1837 {
1838         nilfs->ns_segnum = segbuf->sb_segnum;
1839         nilfs->ns_nextnum = segbuf->sb_nextnum;
1840         nilfs->ns_pseg_offset = segbuf->sb_pseg_start - segbuf->sb_fseg_start
1841                 + segbuf->sb_sum.nblocks;
1842         nilfs->ns_seg_seq = segbuf->sb_sum.seg_seq;
1843         nilfs->ns_ctime = segbuf->sb_sum.ctime;
1844 }
1845
1846 static void nilfs_segctor_complete_write(struct nilfs_sc_info *sci)
1847 {
1848         struct nilfs_segment_buffer *segbuf;
1849         struct page *bd_page = NULL, *fs_page = NULL;
1850         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
1851         int update_sr = false;
1852
1853         list_for_each_entry(segbuf, &sci->sc_write_logs, sb_list) {
1854                 struct buffer_head *bh;
1855
1856                 list_for_each_entry(bh, &segbuf->sb_segsum_buffers,
1857                                     b_assoc_buffers) {
1858                         set_buffer_uptodate(bh);
1859                         clear_buffer_dirty(bh);
1860                         if (bh->b_page != bd_page) {
1861                                 if (bd_page)
1862                                         end_page_writeback(bd_page);
1863                                 bd_page = bh->b_page;
1864                         }
1865                 }
1866                 /*
1867                  * We assume that the buffers which belong to the same page
1868                  * continue over the buffer list.
1869                  * Under this assumption, the last BHs of pages is
1870                  * identifiable by the discontinuity of bh->b_page
1871                  * (page != fs_page).
1872                  *
1873                  * For B-tree node blocks, however, this assumption is not
1874                  * guaranteed.  The cleanup code of B-tree node pages needs
1875                  * special care.
1876                  */
1877                 list_for_each_entry(bh, &segbuf->sb_payload_buffers,
1878                                     b_assoc_buffers) {
1879                         const unsigned long set_bits = BIT(BH_Uptodate);
1880                         const unsigned long clear_bits =
1881                                 (BIT(BH_Dirty) | BIT(BH_Async_Write) |
1882                                  BIT(BH_Delay) | BIT(BH_NILFS_Volatile) |
1883                                  BIT(BH_NILFS_Redirected));
1884
1885                         set_mask_bits(&bh->b_state, clear_bits, set_bits);
1886                         if (bh == segbuf->sb_super_root) {
1887                                 if (bh->b_page != bd_page) {
1888                                         end_page_writeback(bd_page);
1889                                         bd_page = bh->b_page;
1890                                 }
1891                                 update_sr = true;
1892                                 break;
1893                         }
1894                         if (bh->b_page != fs_page) {
1895                                 nilfs_end_page_io(fs_page, 0);
1896                                 fs_page = bh->b_page;
1897                         }
1898                 }
1899
1900                 if (!nilfs_segbuf_simplex(segbuf)) {
1901                         if (segbuf->sb_sum.flags & NILFS_SS_LOGBGN) {
1902                                 set_bit(NILFS_SC_UNCLOSED, &sci->sc_flags);
1903                                 sci->sc_lseg_stime = jiffies;
1904                         }
1905                         if (segbuf->sb_sum.flags & NILFS_SS_LOGEND)
1906                                 clear_bit(NILFS_SC_UNCLOSED, &sci->sc_flags);
1907                 }
1908         }
1909         /*
1910          * Since pages may continue over multiple segment buffers,
1911          * end of the last page must be checked outside of the loop.
1912          */
1913         if (bd_page)
1914                 end_page_writeback(bd_page);
1915
1916         nilfs_end_page_io(fs_page, 0);
1917
1918         nilfs_drop_collected_inodes(&sci->sc_dirty_files);
1919
1920         if (nilfs_doing_gc())
1921                 nilfs_drop_collected_inodes(&sci->sc_gc_inodes);
1922         else
1923                 nilfs->ns_nongc_ctime = sci->sc_seg_ctime;
1924
1925         sci->sc_nblk_inc += sci->sc_nblk_this_inc;
1926
1927         segbuf = NILFS_LAST_SEGBUF(&sci->sc_write_logs);
1928         nilfs_set_next_segment(nilfs, segbuf);
1929
1930         if (update_sr) {
1931                 nilfs->ns_flushed_device = 0;
1932                 nilfs_set_last_segment(nilfs, segbuf->sb_pseg_start,
1933                                        segbuf->sb_sum.seg_seq, nilfs->ns_cno++);
1934
1935                 clear_bit(NILFS_SC_HAVE_DELTA, &sci->sc_flags);
1936                 clear_bit(NILFS_SC_DIRTY, &sci->sc_flags);
1937                 set_bit(NILFS_SC_SUPER_ROOT, &sci->sc_flags);
1938                 nilfs_segctor_clear_metadata_dirty(sci);
1939         } else
1940                 clear_bit(NILFS_SC_SUPER_ROOT, &sci->sc_flags);
1941 }
1942
1943 static int nilfs_segctor_wait(struct nilfs_sc_info *sci)
1944 {
1945         int ret;
1946
1947         ret = nilfs_wait_on_logs(&sci->sc_write_logs);
1948         if (!ret) {
1949                 nilfs_segctor_complete_write(sci);
1950                 nilfs_destroy_logs(&sci->sc_write_logs);
1951         }
1952         return ret;
1953 }
1954
1955 static int nilfs_segctor_collect_dirty_files(struct nilfs_sc_info *sci,
1956                                              struct the_nilfs *nilfs)
1957 {
1958         struct nilfs_inode_info *ii, *n;
1959         struct inode *ifile = sci->sc_root->ifile;
1960
1961         spin_lock(&nilfs->ns_inode_lock);
1962  retry:
1963         list_for_each_entry_safe(ii, n, &nilfs->ns_dirty_files, i_dirty) {
1964                 if (!ii->i_bh) {
1965                         struct buffer_head *ibh;
1966                         int err;
1967
1968                         spin_unlock(&nilfs->ns_inode_lock);
1969                         err = nilfs_ifile_get_inode_block(
1970                                 ifile, ii->vfs_inode.i_ino, &ibh);
1971                         if (unlikely(err)) {
1972                                 nilfs_msg(sci->sc_super, KERN_WARNING,
1973                                           "log writer: error %d getting inode block (ino=%lu)",
1974                                           err, ii->vfs_inode.i_ino);
1975                                 return err;
1976                         }
1977                         spin_lock(&nilfs->ns_inode_lock);
1978                         if (likely(!ii->i_bh))
1979                                 ii->i_bh = ibh;
1980                         else
1981                                 brelse(ibh);
1982                         goto retry;
1983                 }
1984
1985                 // Always redirty the buffer to avoid race condition
1986                 mark_buffer_dirty(ii->i_bh);
1987                 nilfs_mdt_mark_dirty(ifile);
1988
1989                 clear_bit(NILFS_I_QUEUED, &ii->i_state);
1990                 set_bit(NILFS_I_BUSY, &ii->i_state);
1991                 list_move_tail(&ii->i_dirty, &sci->sc_dirty_files);
1992         }
1993         spin_unlock(&nilfs->ns_inode_lock);
1994
1995         return 0;
1996 }
1997
1998 static void nilfs_segctor_drop_written_files(struct nilfs_sc_info *sci,
1999                                              struct the_nilfs *nilfs)
2000 {
2001         struct nilfs_inode_info *ii, *n;
2002         int during_mount = !(sci->sc_super->s_flags & SB_ACTIVE);
2003         int defer_iput = false;
2004
2005         spin_lock(&nilfs->ns_inode_lock);
2006         list_for_each_entry_safe(ii, n, &sci->sc_dirty_files, i_dirty) {
2007                 if (!test_and_clear_bit(NILFS_I_UPDATED, &ii->i_state) ||
2008                     test_bit(NILFS_I_DIRTY, &ii->i_state))
2009                         continue;
2010
2011                 clear_bit(NILFS_I_BUSY, &ii->i_state);
2012                 brelse(ii->i_bh);
2013                 ii->i_bh = NULL;
2014                 list_del_init(&ii->i_dirty);
2015                 if (!ii->vfs_inode.i_nlink || during_mount) {
2016                         /*
2017                          * Defer calling iput() to avoid deadlocks if
2018                          * i_nlink == 0 or mount is not yet finished.
2019                          */
2020                         list_add_tail(&ii->i_dirty, &sci->sc_iput_queue);
2021                         defer_iput = true;
2022                 } else {
2023                         spin_unlock(&nilfs->ns_inode_lock);
2024                         iput(&ii->vfs_inode);
2025                         spin_lock(&nilfs->ns_inode_lock);
2026                 }
2027         }
2028         spin_unlock(&nilfs->ns_inode_lock);
2029
2030         if (defer_iput)
2031                 schedule_work(&sci->sc_iput_work);
2032 }
2033
2034 /*
2035  * Main procedure of segment constructor
2036  */
2037 static int nilfs_segctor_do_construct(struct nilfs_sc_info *sci, int mode)
2038 {
2039         struct the_nilfs *nilfs = sci->sc_super->s_fs_info;
2040         int err;
2041
2042         if (sb_rdonly(sci->sc_super))
2043                 return -EROFS;
2044
2045         nilfs_sc_cstage_set(sci, NILFS_ST_INIT);
2046         sci->sc_cno = nilfs->ns_cno;
2047
2048         err = nilfs_segctor_collect_dirty_files(sci, nilfs);
2049         if (unlikely(err))
2050                 goto out;
2051
2052         if (nilfs_test_metadata_dirty(nilfs, sci->sc_root))
2053                 set_bit(NILFS_SC_DIRTY, &sci->sc_flags);
2054
2055         if (nilfs_segctor_clean(sci))
2056                 goto out;
2057
2058         do {
2059                 sci->sc_stage.flags &= ~NILFS_CF_HISTORY_MASK;
2060
2061                 err = nilfs_segctor_begin_construction(sci, nilfs);
2062                 if (unlikely(err))
2063                         goto out;
2064
2065                 /* Update time stamp */
2066                 sci->sc_seg_ctime = ktime_get_real_seconds();
2067
2068                 err = nilfs_segctor_collect(sci, nilfs, mode);
2069                 if (unlikely(err))
2070                         goto failed;
2071
2072                 /* Avoid empty segment */
2073                 if (nilfs_sc_cstage_get(sci) == NILFS_ST_DONE &&
2074                     nilfs_segbuf_empty(sci->sc_curseg)) {
2075                         nilfs_segctor_abort_construction(sci, nilfs, 1);
2076                         goto out;
2077                 }
2078
2079                 err = nilfs_segctor_assign(sci, mode);
2080                 if (unlikely(err))
2081                         goto failed;
2082
2083                 if (sci->sc_stage.flags & NILFS_CF_IFILE_STARTED)
2084                         nilfs_segctor_fill_in_file_bmap(sci);
2085
2086                 if (mode == SC_LSEG_SR &&
2087                     nilfs_sc_cstage_get(sci) >= NILFS_ST_CPFILE) {
2088                         err = nilfs_segctor_fill_in_checkpoint(sci);
2089                         if (unlikely(err))
2090                                 goto failed_to_write;
2091
2092                         nilfs_segctor_fill_in_super_root(sci, nilfs);
2093                 }
2094                 nilfs_segctor_update_segusage(sci, nilfs->ns_sufile);
2095
2096                 /* Write partial segments */
2097                 nilfs_segctor_prepare_write(sci);
2098
2099                 nilfs_add_checksums_on_logs(&sci->sc_segbufs,
2100                                             nilfs->ns_crc_seed);
2101
2102                 err = nilfs_segctor_write(sci, nilfs);
2103                 if (unlikely(err))
2104                         goto failed_to_write;
2105
2106                 if (nilfs_sc_cstage_get(sci) == NILFS_ST_DONE ||
2107                     nilfs->ns_blocksize_bits != PAGE_SHIFT) {
2108                         /*
2109                          * At this point, we avoid double buffering
2110                          * for blocksize < pagesize because page dirty
2111                          * flag is turned off during write and dirty
2112                          * buffers are not properly collected for
2113                          * pages crossing over segments.
2114                          */
2115                         err = nilfs_segctor_wait(sci);
2116                         if (err)
2117                                 goto failed_to_write;
2118                 }
2119         } while (nilfs_sc_cstage_get(sci) != NILFS_ST_DONE);
2120
2121  out:
2122         nilfs_segctor_drop_written_files(sci, nilfs);
2123         return err;
2124
2125  failed_to_write:
2126         if (sci->sc_stage.flags & NILFS_CF_IFILE_STARTED)
2127                 nilfs_redirty_inodes(&sci->sc_dirty_files);
2128
2129  failed:
2130         if (nilfs_doing_gc())
2131                 nilfs_redirty_inodes(&sci->sc_gc_inodes);
2132         nilfs_segctor_abort_construction(sci, nilfs, err);
2133         goto out;
2134 }
2135
2136 /**
2137  * nilfs_segctor_start_timer - set timer of background write
2138  * @sci: nilfs_sc_info
2139  *
2140  * If the timer has already been set, it ignores the new request.
2141  * This function MUST be called within a section locking the segment
2142  * semaphore.
2143  */
2144 static void nilfs_segctor_start_timer(struct nilfs_sc_info *sci)
2145 {
2146         spin_lock(&sci->sc_state_lock);
2147         if (!(sci->sc_state & NILFS_SEGCTOR_COMMIT)) {
2148                 sci->sc_timer.expires = jiffies + sci->sc_interval;
2149                 add_timer(&sci->sc_timer);
2150                 sci->sc_state |= NILFS_SEGCTOR_COMMIT;
2151         }
2152         spin_unlock(&sci->sc_state_lock);
2153 }
2154
2155 static void nilfs_segctor_do_flush(struct nilfs_sc_info *sci, int bn)
2156 {
2157         spin_lock(&sci->sc_state_lock);
2158         if (!(sci->sc_flush_request & BIT(bn))) {
2159                 unsigned long prev_req = sci->sc_flush_request;
2160
2161                 sci->sc_flush_request |= BIT(bn);
2162                 if (!prev_req)
2163                         wake_up(&sci->sc_wait_daemon);
2164         }
2165         spin_unlock(&sci->sc_state_lock);
2166 }
2167
2168 /**
2169  * nilfs_flush_segment - trigger a segment construction for resource control
2170  * @sb: super block
2171  * @ino: inode number of the file to be flushed out.
2172  */
2173 void nilfs_flush_segment(struct super_block *sb, ino_t ino)
2174 {
2175         struct the_nilfs *nilfs = sb->s_fs_info;
2176         struct nilfs_sc_info *sci = nilfs->ns_writer;
2177
2178         if (!sci || nilfs_doing_construction())
2179                 return;
2180         nilfs_segctor_do_flush(sci, NILFS_MDT_INODE(sb, ino) ? ino : 0);
2181                                         /* assign bit 0 to data files */
2182 }
2183
2184 struct nilfs_segctor_wait_request {
2185         wait_queue_entry_t      wq;
2186         __u32           seq;
2187         int             err;
2188         atomic_t        done;
2189 };
2190
2191 static int nilfs_segctor_sync(struct nilfs_sc_info *sci)
2192 {
2193         struct nilfs_segctor_wait_request wait_req;
2194         int err = 0;
2195
2196         spin_lock(&sci->sc_state_lock);
2197         init_wait(&wait_req.wq);
2198         wait_req.err = 0;
2199         atomic_set(&wait_req.done, 0);
2200         wait_req.seq = ++sci->sc_seq_request;
2201         spin_unlock(&sci->sc_state_lock);
2202
2203         init_waitqueue_entry(&wait_req.wq, current);
2204         add_wait_queue(&sci->sc_wait_request, &wait_req.wq);
2205         set_current_state(TASK_INTERRUPTIBLE);
2206         wake_up(&sci->sc_wait_daemon);
2207
2208         for (;;) {
2209                 if (atomic_read(&wait_req.done)) {
2210                         err = wait_req.err;
2211                         break;
2212                 }
2213                 if (!signal_pending(current)) {
2214                         schedule();
2215                         continue;
2216                 }
2217                 err = -ERESTARTSYS;
2218                 break;
2219         }
2220         finish_wait(&sci->sc_wait_request, &wait_req.wq);
2221         return err;
2222 }
2223
2224 static void nilfs_segctor_wakeup(struct nilfs_sc_info *sci, int err)
2225 {
2226         struct nilfs_segctor_wait_request *wrq, *n;
2227         unsigned long flags;
2228
2229         spin_lock_irqsave(&sci->sc_wait_request.lock, flags);
2230         list_for_each_entry_safe(wrq, n, &sci->sc_wait_request.head, wq.entry) {
2231                 if (!atomic_read(&wrq->done) &&
2232                     nilfs_cnt32_ge(sci->sc_seq_done, wrq->seq)) {
2233                         wrq->err = err;
2234                         atomic_set(&wrq->done, 1);
2235                 }
2236                 if (atomic_read(&wrq->done)) {
2237                         wrq->wq.func(&wrq->wq,
2238                                      TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2239                                      0, NULL);
2240                 }
2241         }
2242         spin_unlock_irqrestore(&sci->sc_wait_request.lock, flags);
2243 }
2244
2245 /**
2246  * nilfs_construct_segment - construct a logical segment
2247  * @sb: super block
2248  *
2249  * Return Value: On success, 0 is retured. On errors, one of the following
2250  * negative error code is returned.
2251  *
2252  * %-EROFS - Read only filesystem.
2253  *
2254  * %-EIO - I/O error
2255  *
2256  * %-ENOSPC - No space left on device (only in a panic state).
2257  *
2258  * %-ERESTARTSYS - Interrupted.
2259  *
2260  * %-ENOMEM - Insufficient memory available.
2261  */
2262 int nilfs_construct_segment(struct super_block *sb)
2263 {
2264         struct the_nilfs *nilfs = sb->s_fs_info;
2265         struct nilfs_sc_info *sci = nilfs->ns_writer;
2266         struct nilfs_transaction_info *ti;
2267         int err;
2268
2269         if (sb_rdonly(sb) || unlikely(!sci))
2270                 return -EROFS;
2271
2272         /* A call inside transactions causes a deadlock. */
2273         BUG_ON((ti = current->journal_info) && ti->ti_magic == NILFS_TI_MAGIC);
2274
2275         err = nilfs_segctor_sync(sci);
2276         return err;
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 retured. 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_msg(sb, KERN_WARNING, "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_msg(sb, KERN_WARNING,
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_msg(sci->sc_super, KERN_INFO,
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_msg(sci->sc_super, KERN_ERR,
2651                           "error %d creating segctord thread", 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_msg(sci->sc_super, KERN_WARNING,
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_msg(sci->sc_super, KERN_WARNING,
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         del_timer_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_msg(sb, KERN_WARNING,
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 }