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