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