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