net: avoid NULL deref in inet_ctl_sock_destroy()
[pandora-kernel.git] / fs / reiserfs / journal.c
1 /*
2 ** Write ahead logging implementation copyright Chris Mason 2000
3 **
4 ** The background commits make this code very interrelated, and
5 ** overly complex.  I need to rethink things a bit....The major players:
6 **
7 ** journal_begin -- call with the number of blocks you expect to log.
8 **                  If the current transaction is too
9 **                  old, it will block until the current transaction is
10 **                  finished, and then start a new one.
11 **                  Usually, your transaction will get joined in with
12 **                  previous ones for speed.
13 **
14 ** journal_join  -- same as journal_begin, but won't block on the current
15 **                  transaction regardless of age.  Don't ever call
16 **                  this.  Ever.  There are only two places it should be
17 **                  called from, and they are both inside this file.
18 **
19 ** journal_mark_dirty -- adds blocks into this transaction.  clears any flags
20 **                       that might make them get sent to disk
21 **                       and then marks them BH_JDirty.  Puts the buffer head
22 **                       into the current transaction hash.
23 **
24 ** journal_end -- if the current transaction is batchable, it does nothing
25 **                   otherwise, it could do an async/synchronous commit, or
26 **                   a full flush of all log and real blocks in the
27 **                   transaction.
28 **
29 ** flush_old_commits -- if the current transaction is too old, it is ended and
30 **                      commit blocks are sent to disk.  Forces commit blocks
31 **                      to disk for all backgrounded commits that have been
32 **                      around too long.
33 **                   -- Note, if you call this as an immediate flush from
34 **                      from within kupdate, it will ignore the immediate flag
35 */
36
37 #include <linux/time.h>
38 #include <linux/semaphore.h>
39 #include <linux/vmalloc.h>
40 #include <linux/reiserfs_fs.h>
41 #include <linux/kernel.h>
42 #include <linux/errno.h>
43 #include <linux/fcntl.h>
44 #include <linux/stat.h>
45 #include <linux/string.h>
46 #include <linux/buffer_head.h>
47 #include <linux/workqueue.h>
48 #include <linux/writeback.h>
49 #include <linux/blkdev.h>
50 #include <linux/backing-dev.h>
51 #include <linux/uaccess.h>
52 #include <linux/slab.h>
53
54 #include <asm/system.h>
55
56 /* gets a struct reiserfs_journal_list * from a list head */
57 #define JOURNAL_LIST_ENTRY(h) (list_entry((h), struct reiserfs_journal_list, \
58                                j_list))
59 #define JOURNAL_WORK_ENTRY(h) (list_entry((h), struct reiserfs_journal_list, \
60                                j_working_list))
61
62 /* the number of mounted filesystems.  This is used to decide when to
63 ** start and kill the commit workqueue
64 */
65 static int reiserfs_mounted_fs_count;
66
67 static struct workqueue_struct *commit_wq;
68
69 #define JOURNAL_TRANS_HALF 1018 /* must be correct to keep the desc and commit
70                                    structs at 4k */
71 #define BUFNR 64                /*read ahead */
72
73 /* cnode stat bits.  Move these into reiserfs_fs.h */
74
75 #define BLOCK_FREED 2           /* this block was freed, and can't be written.  */
76 #define BLOCK_FREED_HOLDER 3    /* this block was freed during this transaction, and can't be written */
77
78 #define BLOCK_NEEDS_FLUSH 4     /* used in flush_journal_list */
79 #define BLOCK_DIRTIED 5
80
81 /* journal list state bits */
82 #define LIST_TOUCHED 1
83 #define LIST_DIRTY   2
84 #define LIST_COMMIT_PENDING  4  /* someone will commit this list */
85
86 /* flags for do_journal_end */
87 #define FLUSH_ALL   1           /* flush commit and real blocks */
88 #define COMMIT_NOW  2           /* end and commit this transaction */
89 #define WAIT        4           /* wait for the log blocks to hit the disk */
90
91 static int do_journal_end(struct reiserfs_transaction_handle *,
92                           struct super_block *, unsigned long nblocks,
93                           int flags);
94 static int flush_journal_list(struct super_block *s,
95                               struct reiserfs_journal_list *jl, int flushall);
96 static int flush_commit_list(struct super_block *s,
97                              struct reiserfs_journal_list *jl, int flushall);
98 static int can_dirty(struct reiserfs_journal_cnode *cn);
99 static int journal_join(struct reiserfs_transaction_handle *th,
100                         struct super_block *sb, unsigned long nblocks);
101 static int release_journal_dev(struct super_block *super,
102                                struct reiserfs_journal *journal);
103 static int dirty_one_transaction(struct super_block *s,
104                                  struct reiserfs_journal_list *jl);
105 static void flush_async_commits(struct work_struct *work);
106 static void queue_log_writer(struct super_block *s);
107
108 /* values for join in do_journal_begin_r */
109 enum {
110         JBEGIN_REG = 0,         /* regular journal begin */
111         JBEGIN_JOIN = 1,        /* join the running transaction if at all possible */
112         JBEGIN_ABORT = 2,       /* called from cleanup code, ignores aborted flag */
113 };
114
115 static int do_journal_begin_r(struct reiserfs_transaction_handle *th,
116                               struct super_block *sb,
117                               unsigned long nblocks, int join);
118
119 static void init_journal_hash(struct super_block *sb)
120 {
121         struct reiserfs_journal *journal = SB_JOURNAL(sb);
122         memset(journal->j_hash_table, 0,
123                JOURNAL_HASH_SIZE * sizeof(struct reiserfs_journal_cnode *));
124 }
125
126 /*
127 ** clears BH_Dirty and sticks the buffer on the clean list.  Called because I can't allow refile_buffer to
128 ** make schedule happen after I've freed a block.  Look at remove_from_transaction and journal_mark_freed for
129 ** more details.
130 */
131 static int reiserfs_clean_and_file_buffer(struct buffer_head *bh)
132 {
133         if (bh) {
134                 clear_buffer_dirty(bh);
135                 clear_buffer_journal_test(bh);
136         }
137         return 0;
138 }
139
140 static struct reiserfs_bitmap_node *allocate_bitmap_node(struct super_block
141                                                          *sb)
142 {
143         struct reiserfs_bitmap_node *bn;
144         static int id;
145
146         bn = kmalloc(sizeof(struct reiserfs_bitmap_node), GFP_NOFS);
147         if (!bn) {
148                 return NULL;
149         }
150         bn->data = kzalloc(sb->s_blocksize, GFP_NOFS);
151         if (!bn->data) {
152                 kfree(bn);
153                 return NULL;
154         }
155         bn->id = id++;
156         INIT_LIST_HEAD(&bn->list);
157         return bn;
158 }
159
160 static struct reiserfs_bitmap_node *get_bitmap_node(struct super_block *sb)
161 {
162         struct reiserfs_journal *journal = SB_JOURNAL(sb);
163         struct reiserfs_bitmap_node *bn = NULL;
164         struct list_head *entry = journal->j_bitmap_nodes.next;
165
166         journal->j_used_bitmap_nodes++;
167       repeat:
168
169         if (entry != &journal->j_bitmap_nodes) {
170                 bn = list_entry(entry, struct reiserfs_bitmap_node, list);
171                 list_del(entry);
172                 memset(bn->data, 0, sb->s_blocksize);
173                 journal->j_free_bitmap_nodes--;
174                 return bn;
175         }
176         bn = allocate_bitmap_node(sb);
177         if (!bn) {
178                 yield();
179                 goto repeat;
180         }
181         return bn;
182 }
183 static inline void free_bitmap_node(struct super_block *sb,
184                                     struct reiserfs_bitmap_node *bn)
185 {
186         struct reiserfs_journal *journal = SB_JOURNAL(sb);
187         journal->j_used_bitmap_nodes--;
188         if (journal->j_free_bitmap_nodes > REISERFS_MAX_BITMAP_NODES) {
189                 kfree(bn->data);
190                 kfree(bn);
191         } else {
192                 list_add(&bn->list, &journal->j_bitmap_nodes);
193                 journal->j_free_bitmap_nodes++;
194         }
195 }
196
197 static void allocate_bitmap_nodes(struct super_block *sb)
198 {
199         int i;
200         struct reiserfs_journal *journal = SB_JOURNAL(sb);
201         struct reiserfs_bitmap_node *bn = NULL;
202         for (i = 0; i < REISERFS_MIN_BITMAP_NODES; i++) {
203                 bn = allocate_bitmap_node(sb);
204                 if (bn) {
205                         list_add(&bn->list, &journal->j_bitmap_nodes);
206                         journal->j_free_bitmap_nodes++;
207                 } else {
208                         break;  /* this is ok, we'll try again when more are needed */
209                 }
210         }
211 }
212
213 static int set_bit_in_list_bitmap(struct super_block *sb,
214                                   b_blocknr_t block,
215                                   struct reiserfs_list_bitmap *jb)
216 {
217         unsigned int bmap_nr = block / (sb->s_blocksize << 3);
218         unsigned int bit_nr = block % (sb->s_blocksize << 3);
219
220         if (!jb->bitmaps[bmap_nr]) {
221                 jb->bitmaps[bmap_nr] = get_bitmap_node(sb);
222         }
223         set_bit(bit_nr, (unsigned long *)jb->bitmaps[bmap_nr]->data);
224         return 0;
225 }
226
227 static void cleanup_bitmap_list(struct super_block *sb,
228                                 struct reiserfs_list_bitmap *jb)
229 {
230         int i;
231         if (jb->bitmaps == NULL)
232                 return;
233
234         for (i = 0; i < reiserfs_bmap_count(sb); i++) {
235                 if (jb->bitmaps[i]) {
236                         free_bitmap_node(sb, jb->bitmaps[i]);
237                         jb->bitmaps[i] = NULL;
238                 }
239         }
240 }
241
242 /*
243 ** only call this on FS unmount.
244 */
245 static int free_list_bitmaps(struct super_block *sb,
246                              struct reiserfs_list_bitmap *jb_array)
247 {
248         int i;
249         struct reiserfs_list_bitmap *jb;
250         for (i = 0; i < JOURNAL_NUM_BITMAPS; i++) {
251                 jb = jb_array + i;
252                 jb->journal_list = NULL;
253                 cleanup_bitmap_list(sb, jb);
254                 vfree(jb->bitmaps);
255                 jb->bitmaps = NULL;
256         }
257         return 0;
258 }
259
260 static int free_bitmap_nodes(struct super_block *sb)
261 {
262         struct reiserfs_journal *journal = SB_JOURNAL(sb);
263         struct list_head *next = journal->j_bitmap_nodes.next;
264         struct reiserfs_bitmap_node *bn;
265
266         while (next != &journal->j_bitmap_nodes) {
267                 bn = list_entry(next, struct reiserfs_bitmap_node, list);
268                 list_del(next);
269                 kfree(bn->data);
270                 kfree(bn);
271                 next = journal->j_bitmap_nodes.next;
272                 journal->j_free_bitmap_nodes--;
273         }
274
275         return 0;
276 }
277
278 /*
279 ** get memory for JOURNAL_NUM_BITMAPS worth of bitmaps.
280 ** jb_array is the array to be filled in.
281 */
282 int reiserfs_allocate_list_bitmaps(struct super_block *sb,
283                                    struct reiserfs_list_bitmap *jb_array,
284                                    unsigned int bmap_nr)
285 {
286         int i;
287         int failed = 0;
288         struct reiserfs_list_bitmap *jb;
289         int mem = bmap_nr * sizeof(struct reiserfs_bitmap_node *);
290
291         for (i = 0; i < JOURNAL_NUM_BITMAPS; i++) {
292                 jb = jb_array + i;
293                 jb->journal_list = NULL;
294                 jb->bitmaps = vzalloc(mem);
295                 if (!jb->bitmaps) {
296                         reiserfs_warning(sb, "clm-2000", "unable to "
297                                          "allocate bitmaps for journal lists");
298                         failed = 1;
299                         break;
300                 }
301         }
302         if (failed) {
303                 free_list_bitmaps(sb, jb_array);
304                 return -1;
305         }
306         return 0;
307 }
308
309 /*
310 ** find an available list bitmap.  If you can't find one, flush a commit list
311 ** and try again
312 */
313 static struct reiserfs_list_bitmap *get_list_bitmap(struct super_block *sb,
314                                                     struct reiserfs_journal_list
315                                                     *jl)
316 {
317         int i, j;
318         struct reiserfs_journal *journal = SB_JOURNAL(sb);
319         struct reiserfs_list_bitmap *jb = NULL;
320
321         for (j = 0; j < (JOURNAL_NUM_BITMAPS * 3); j++) {
322                 i = journal->j_list_bitmap_index;
323                 journal->j_list_bitmap_index = (i + 1) % JOURNAL_NUM_BITMAPS;
324                 jb = journal->j_list_bitmap + i;
325                 if (journal->j_list_bitmap[i].journal_list) {
326                         flush_commit_list(sb,
327                                           journal->j_list_bitmap[i].
328                                           journal_list, 1);
329                         if (!journal->j_list_bitmap[i].journal_list) {
330                                 break;
331                         }
332                 } else {
333                         break;
334                 }
335         }
336         if (jb->journal_list) { /* double check to make sure if flushed correctly */
337                 return NULL;
338         }
339         jb->journal_list = jl;
340         return jb;
341 }
342
343 /*
344 ** allocates a new chunk of X nodes, and links them all together as a list.
345 ** Uses the cnode->next and cnode->prev pointers
346 ** returns NULL on failure
347 */
348 static struct reiserfs_journal_cnode *allocate_cnodes(int num_cnodes)
349 {
350         struct reiserfs_journal_cnode *head;
351         int i;
352         if (num_cnodes <= 0) {
353                 return NULL;
354         }
355         head = vzalloc(num_cnodes * sizeof(struct reiserfs_journal_cnode));
356         if (!head) {
357                 return NULL;
358         }
359         head[0].prev = NULL;
360         head[0].next = head + 1;
361         for (i = 1; i < num_cnodes; i++) {
362                 head[i].prev = head + (i - 1);
363                 head[i].next = head + (i + 1);  /* if last one, overwrite it after the if */
364         }
365         head[num_cnodes - 1].next = NULL;
366         return head;
367 }
368
369 /*
370 ** pulls a cnode off the free list, or returns NULL on failure
371 */
372 static struct reiserfs_journal_cnode *get_cnode(struct super_block *sb)
373 {
374         struct reiserfs_journal_cnode *cn;
375         struct reiserfs_journal *journal = SB_JOURNAL(sb);
376
377         reiserfs_check_lock_depth(sb, "get_cnode");
378
379         if (journal->j_cnode_free <= 0) {
380                 return NULL;
381         }
382         journal->j_cnode_used++;
383         journal->j_cnode_free--;
384         cn = journal->j_cnode_free_list;
385         if (!cn) {
386                 return cn;
387         }
388         if (cn->next) {
389                 cn->next->prev = NULL;
390         }
391         journal->j_cnode_free_list = cn->next;
392         memset(cn, 0, sizeof(struct reiserfs_journal_cnode));
393         return cn;
394 }
395
396 /*
397 ** returns a cnode to the free list
398 */
399 static void free_cnode(struct super_block *sb,
400                        struct reiserfs_journal_cnode *cn)
401 {
402         struct reiserfs_journal *journal = SB_JOURNAL(sb);
403
404         reiserfs_check_lock_depth(sb, "free_cnode");
405
406         journal->j_cnode_used--;
407         journal->j_cnode_free++;
408         /* memset(cn, 0, sizeof(struct reiserfs_journal_cnode)) ; */
409         cn->next = journal->j_cnode_free_list;
410         if (journal->j_cnode_free_list) {
411                 journal->j_cnode_free_list->prev = cn;
412         }
413         cn->prev = NULL;        /* not needed with the memset, but I might kill the memset, and forget to do this */
414         journal->j_cnode_free_list = cn;
415 }
416
417 static void clear_prepared_bits(struct buffer_head *bh)
418 {
419         clear_buffer_journal_prepared(bh);
420         clear_buffer_journal_restore_dirty(bh);
421 }
422
423 /* return a cnode with same dev, block number and size in table, or null if not found */
424 static inline struct reiserfs_journal_cnode *get_journal_hash_dev(struct
425                                                                   super_block
426                                                                   *sb,
427                                                                   struct
428                                                                   reiserfs_journal_cnode
429                                                                   **table,
430                                                                   long bl)
431 {
432         struct reiserfs_journal_cnode *cn;
433         cn = journal_hash(table, sb, bl);
434         while (cn) {
435                 if (cn->blocknr == bl && cn->sb == sb)
436                         return cn;
437                 cn = cn->hnext;
438         }
439         return (struct reiserfs_journal_cnode *)0;
440 }
441
442 /*
443 ** this actually means 'can this block be reallocated yet?'.  If you set search_all, a block can only be allocated
444 ** if it is not in the current transaction, was not freed by the current transaction, and has no chance of ever
445 ** being overwritten by a replay after crashing.
446 **
447 ** If you don't set search_all, a block can only be allocated if it is not in the current transaction.  Since deleting
448 ** a block removes it from the current transaction, this case should never happen.  If you don't set search_all, make
449 ** sure you never write the block without logging it.
450 **
451 ** next_zero_bit is a suggestion about the next block to try for find_forward.
452 ** when bl is rejected because it is set in a journal list bitmap, we search
453 ** for the next zero bit in the bitmap that rejected bl.  Then, we return that
454 ** through next_zero_bit for find_forward to try.
455 **
456 ** Just because we return something in next_zero_bit does not mean we won't
457 ** reject it on the next call to reiserfs_in_journal
458 **
459 */
460 int reiserfs_in_journal(struct super_block *sb,
461                         unsigned int bmap_nr, int bit_nr, int search_all,
462                         b_blocknr_t * next_zero_bit)
463 {
464         struct reiserfs_journal *journal = SB_JOURNAL(sb);
465         struct reiserfs_journal_cnode *cn;
466         struct reiserfs_list_bitmap *jb;
467         int i;
468         unsigned long bl;
469
470         *next_zero_bit = 0;     /* always start this at zero. */
471
472         PROC_INFO_INC(sb, journal.in_journal);
473         /* If we aren't doing a search_all, this is a metablock, and it will be logged before use.
474          ** if we crash before the transaction that freed it commits,  this transaction won't
475          ** have committed either, and the block will never be written
476          */
477         if (search_all) {
478                 for (i = 0; i < JOURNAL_NUM_BITMAPS; i++) {
479                         PROC_INFO_INC(sb, journal.in_journal_bitmap);
480                         jb = journal->j_list_bitmap + i;
481                         if (jb->journal_list && jb->bitmaps[bmap_nr] &&
482                             test_bit(bit_nr,
483                                      (unsigned long *)jb->bitmaps[bmap_nr]->
484                                      data)) {
485                                 *next_zero_bit =
486                                     find_next_zero_bit((unsigned long *)
487                                                        (jb->bitmaps[bmap_nr]->
488                                                         data),
489                                                        sb->s_blocksize << 3,
490                                                        bit_nr + 1);
491                                 return 1;
492                         }
493                 }
494         }
495
496         bl = bmap_nr * (sb->s_blocksize << 3) + bit_nr;
497         /* is it in any old transactions? */
498         if (search_all
499             && (cn =
500                 get_journal_hash_dev(sb, journal->j_list_hash_table, bl))) {
501                 return 1;
502         }
503
504         /* is it in the current transaction.  This should never happen */
505         if ((cn = get_journal_hash_dev(sb, journal->j_hash_table, bl))) {
506                 BUG();
507                 return 1;
508         }
509
510         PROC_INFO_INC(sb, journal.in_journal_reusable);
511         /* safe for reuse */
512         return 0;
513 }
514
515 /* insert cn into table
516 */
517 static inline void insert_journal_hash(struct reiserfs_journal_cnode **table,
518                                        struct reiserfs_journal_cnode *cn)
519 {
520         struct reiserfs_journal_cnode *cn_orig;
521
522         cn_orig = journal_hash(table, cn->sb, cn->blocknr);
523         cn->hnext = cn_orig;
524         cn->hprev = NULL;
525         if (cn_orig) {
526                 cn_orig->hprev = cn;
527         }
528         journal_hash(table, cn->sb, cn->blocknr) = cn;
529 }
530
531 /* lock the current transaction */
532 static inline void lock_journal(struct super_block *sb)
533 {
534         PROC_INFO_INC(sb, journal.lock_journal);
535
536         reiserfs_mutex_lock_safe(&SB_JOURNAL(sb)->j_mutex, sb);
537 }
538
539 /* unlock the current transaction */
540 static inline void unlock_journal(struct super_block *sb)
541 {
542         mutex_unlock(&SB_JOURNAL(sb)->j_mutex);
543 }
544
545 static inline void get_journal_list(struct reiserfs_journal_list *jl)
546 {
547         jl->j_refcount++;
548 }
549
550 static inline void put_journal_list(struct super_block *s,
551                                     struct reiserfs_journal_list *jl)
552 {
553         if (jl->j_refcount < 1) {
554                 reiserfs_panic(s, "journal-2", "trans id %u, refcount at %d",
555                                jl->j_trans_id, jl->j_refcount);
556         }
557         if (--jl->j_refcount == 0)
558                 kfree(jl);
559 }
560
561 /*
562 ** this used to be much more involved, and I'm keeping it just in case things get ugly again.
563 ** it gets called by flush_commit_list, and cleans up any data stored about blocks freed during a
564 ** transaction.
565 */
566 static void cleanup_freed_for_journal_list(struct super_block *sb,
567                                            struct reiserfs_journal_list *jl)
568 {
569
570         struct reiserfs_list_bitmap *jb = jl->j_list_bitmap;
571         if (jb) {
572                 cleanup_bitmap_list(sb, jb);
573         }
574         jl->j_list_bitmap->journal_list = NULL;
575         jl->j_list_bitmap = NULL;
576 }
577
578 static int journal_list_still_alive(struct super_block *s,
579                                     unsigned int trans_id)
580 {
581         struct reiserfs_journal *journal = SB_JOURNAL(s);
582         struct list_head *entry = &journal->j_journal_list;
583         struct reiserfs_journal_list *jl;
584
585         if (!list_empty(entry)) {
586                 jl = JOURNAL_LIST_ENTRY(entry->next);
587                 if (jl->j_trans_id <= trans_id) {
588                         return 1;
589                 }
590         }
591         return 0;
592 }
593
594 /*
595  * If page->mapping was null, we failed to truncate this page for
596  * some reason.  Most likely because it was truncated after being
597  * logged via data=journal.
598  *
599  * This does a check to see if the buffer belongs to one of these
600  * lost pages before doing the final put_bh.  If page->mapping was
601  * null, it tries to free buffers on the page, which should make the
602  * final page_cache_release drop the page from the lru.
603  */
604 static void release_buffer_page(struct buffer_head *bh)
605 {
606         struct page *page = bh->b_page;
607         if (!page->mapping && trylock_page(page)) {
608                 page_cache_get(page);
609                 put_bh(bh);
610                 if (!page->mapping)
611                         try_to_free_buffers(page);
612                 unlock_page(page);
613                 page_cache_release(page);
614         } else {
615                 put_bh(bh);
616         }
617 }
618
619 static void reiserfs_end_buffer_io_sync(struct buffer_head *bh, int uptodate)
620 {
621         char b[BDEVNAME_SIZE];
622
623         if (buffer_journaled(bh)) {
624                 reiserfs_warning(NULL, "clm-2084",
625                                  "pinned buffer %lu:%s sent to disk",
626                                  bh->b_blocknr, bdevname(bh->b_bdev, b));
627         }
628         if (uptodate)
629                 set_buffer_uptodate(bh);
630         else
631                 clear_buffer_uptodate(bh);
632
633         unlock_buffer(bh);
634         release_buffer_page(bh);
635 }
636
637 static void reiserfs_end_ordered_io(struct buffer_head *bh, int uptodate)
638 {
639         if (uptodate)
640                 set_buffer_uptodate(bh);
641         else
642                 clear_buffer_uptodate(bh);
643         unlock_buffer(bh);
644         put_bh(bh);
645 }
646
647 static void submit_logged_buffer(struct buffer_head *bh)
648 {
649         get_bh(bh);
650         bh->b_end_io = reiserfs_end_buffer_io_sync;
651         clear_buffer_journal_new(bh);
652         clear_buffer_dirty(bh);
653         if (!test_clear_buffer_journal_test(bh))
654                 BUG();
655         if (!buffer_uptodate(bh))
656                 BUG();
657         submit_bh(WRITE, bh);
658 }
659
660 static void submit_ordered_buffer(struct buffer_head *bh)
661 {
662         get_bh(bh);
663         bh->b_end_io = reiserfs_end_ordered_io;
664         clear_buffer_dirty(bh);
665         if (!buffer_uptodate(bh))
666                 BUG();
667         submit_bh(WRITE, bh);
668 }
669
670 #define CHUNK_SIZE 32
671 struct buffer_chunk {
672         struct buffer_head *bh[CHUNK_SIZE];
673         int nr;
674 };
675
676 static void write_chunk(struct buffer_chunk *chunk)
677 {
678         int i;
679         for (i = 0; i < chunk->nr; i++) {
680                 submit_logged_buffer(chunk->bh[i]);
681         }
682         chunk->nr = 0;
683 }
684
685 static void write_ordered_chunk(struct buffer_chunk *chunk)
686 {
687         int i;
688         for (i = 0; i < chunk->nr; i++) {
689                 submit_ordered_buffer(chunk->bh[i]);
690         }
691         chunk->nr = 0;
692 }
693
694 static int add_to_chunk(struct buffer_chunk *chunk, struct buffer_head *bh,
695                         spinlock_t * lock, void (fn) (struct buffer_chunk *))
696 {
697         int ret = 0;
698         BUG_ON(chunk->nr >= CHUNK_SIZE);
699         chunk->bh[chunk->nr++] = bh;
700         if (chunk->nr >= CHUNK_SIZE) {
701                 ret = 1;
702                 if (lock)
703                         spin_unlock(lock);
704                 fn(chunk);
705                 if (lock)
706                         spin_lock(lock);
707         }
708         return ret;
709 }
710
711 static atomic_t nr_reiserfs_jh = ATOMIC_INIT(0);
712 static struct reiserfs_jh *alloc_jh(void)
713 {
714         struct reiserfs_jh *jh;
715         while (1) {
716                 jh = kmalloc(sizeof(*jh), GFP_NOFS);
717                 if (jh) {
718                         atomic_inc(&nr_reiserfs_jh);
719                         return jh;
720                 }
721                 yield();
722         }
723 }
724
725 /*
726  * we want to free the jh when the buffer has been written
727  * and waited on
728  */
729 void reiserfs_free_jh(struct buffer_head *bh)
730 {
731         struct reiserfs_jh *jh;
732
733         jh = bh->b_private;
734         if (jh) {
735                 bh->b_private = NULL;
736                 jh->bh = NULL;
737                 list_del_init(&jh->list);
738                 kfree(jh);
739                 if (atomic_read(&nr_reiserfs_jh) <= 0)
740                         BUG();
741                 atomic_dec(&nr_reiserfs_jh);
742                 put_bh(bh);
743         }
744 }
745
746 static inline int __add_jh(struct reiserfs_journal *j, struct buffer_head *bh,
747                            int tail)
748 {
749         struct reiserfs_jh *jh;
750
751         if (bh->b_private) {
752                 spin_lock(&j->j_dirty_buffers_lock);
753                 if (!bh->b_private) {
754                         spin_unlock(&j->j_dirty_buffers_lock);
755                         goto no_jh;
756                 }
757                 jh = bh->b_private;
758                 list_del_init(&jh->list);
759         } else {
760               no_jh:
761                 get_bh(bh);
762                 jh = alloc_jh();
763                 spin_lock(&j->j_dirty_buffers_lock);
764                 /* buffer must be locked for __add_jh, should be able to have
765                  * two adds at the same time
766                  */
767                 BUG_ON(bh->b_private);
768                 jh->bh = bh;
769                 bh->b_private = jh;
770         }
771         jh->jl = j->j_current_jl;
772         if (tail)
773                 list_add_tail(&jh->list, &jh->jl->j_tail_bh_list);
774         else {
775                 list_add_tail(&jh->list, &jh->jl->j_bh_list);
776         }
777         spin_unlock(&j->j_dirty_buffers_lock);
778         return 0;
779 }
780
781 int reiserfs_add_tail_list(struct inode *inode, struct buffer_head *bh)
782 {
783         return __add_jh(SB_JOURNAL(inode->i_sb), bh, 1);
784 }
785 int reiserfs_add_ordered_list(struct inode *inode, struct buffer_head *bh)
786 {
787         return __add_jh(SB_JOURNAL(inode->i_sb), bh, 0);
788 }
789
790 #define JH_ENTRY(l) list_entry((l), struct reiserfs_jh, list)
791 static int write_ordered_buffers(spinlock_t * lock,
792                                  struct reiserfs_journal *j,
793                                  struct reiserfs_journal_list *jl,
794                                  struct list_head *list)
795 {
796         struct buffer_head *bh;
797         struct reiserfs_jh *jh;
798         int ret = j->j_errno;
799         struct buffer_chunk chunk;
800         struct list_head tmp;
801         INIT_LIST_HEAD(&tmp);
802
803         chunk.nr = 0;
804         spin_lock(lock);
805         while (!list_empty(list)) {
806                 jh = JH_ENTRY(list->next);
807                 bh = jh->bh;
808                 get_bh(bh);
809                 if (!trylock_buffer(bh)) {
810                         if (!buffer_dirty(bh)) {
811                                 list_move(&jh->list, &tmp);
812                                 goto loop_next;
813                         }
814                         spin_unlock(lock);
815                         if (chunk.nr)
816                                 write_ordered_chunk(&chunk);
817                         wait_on_buffer(bh);
818                         cond_resched();
819                         spin_lock(lock);
820                         goto loop_next;
821                 }
822                 /* in theory, dirty non-uptodate buffers should never get here,
823                  * but the upper layer io error paths still have a few quirks.
824                  * Handle them here as gracefully as we can
825                  */
826                 if (!buffer_uptodate(bh) && buffer_dirty(bh)) {
827                         clear_buffer_dirty(bh);
828                         ret = -EIO;
829                 }
830                 if (buffer_dirty(bh)) {
831                         list_move(&jh->list, &tmp);
832                         add_to_chunk(&chunk, bh, lock, write_ordered_chunk);
833                 } else {
834                         reiserfs_free_jh(bh);
835                         unlock_buffer(bh);
836                 }
837               loop_next:
838                 put_bh(bh);
839                 cond_resched_lock(lock);
840         }
841         if (chunk.nr) {
842                 spin_unlock(lock);
843                 write_ordered_chunk(&chunk);
844                 spin_lock(lock);
845         }
846         while (!list_empty(&tmp)) {
847                 jh = JH_ENTRY(tmp.prev);
848                 bh = jh->bh;
849                 get_bh(bh);
850                 reiserfs_free_jh(bh);
851
852                 if (buffer_locked(bh)) {
853                         spin_unlock(lock);
854                         wait_on_buffer(bh);
855                         spin_lock(lock);
856                 }
857                 if (!buffer_uptodate(bh)) {
858                         ret = -EIO;
859                 }
860                 /* ugly interaction with invalidatepage here.
861                  * reiserfs_invalidate_page will pin any buffer that has a valid
862                  * journal head from an older transaction.  If someone else sets
863                  * our buffer dirty after we write it in the first loop, and
864                  * then someone truncates the page away, nobody will ever write
865                  * the buffer. We're safe if we write the page one last time
866                  * after freeing the journal header.
867                  */
868                 if (buffer_dirty(bh) && unlikely(bh->b_page->mapping == NULL)) {
869                         spin_unlock(lock);
870                         ll_rw_block(WRITE, 1, &bh);
871                         spin_lock(lock);
872                 }
873                 put_bh(bh);
874                 cond_resched_lock(lock);
875         }
876         spin_unlock(lock);
877         return ret;
878 }
879
880 static int flush_older_commits(struct super_block *s,
881                                struct reiserfs_journal_list *jl)
882 {
883         struct reiserfs_journal *journal = SB_JOURNAL(s);
884         struct reiserfs_journal_list *other_jl;
885         struct reiserfs_journal_list *first_jl;
886         struct list_head *entry;
887         unsigned int trans_id = jl->j_trans_id;
888         unsigned int other_trans_id;
889         unsigned int first_trans_id;
890
891       find_first:
892         /*
893          * first we walk backwards to find the oldest uncommitted transation
894          */
895         first_jl = jl;
896         entry = jl->j_list.prev;
897         while (1) {
898                 other_jl = JOURNAL_LIST_ENTRY(entry);
899                 if (entry == &journal->j_journal_list ||
900                     atomic_read(&other_jl->j_older_commits_done))
901                         break;
902
903                 first_jl = other_jl;
904                 entry = other_jl->j_list.prev;
905         }
906
907         /* if we didn't find any older uncommitted transactions, return now */
908         if (first_jl == jl) {
909                 return 0;
910         }
911
912         first_trans_id = first_jl->j_trans_id;
913
914         entry = &first_jl->j_list;
915         while (1) {
916                 other_jl = JOURNAL_LIST_ENTRY(entry);
917                 other_trans_id = other_jl->j_trans_id;
918
919                 if (other_trans_id < trans_id) {
920                         if (atomic_read(&other_jl->j_commit_left) != 0) {
921                                 flush_commit_list(s, other_jl, 0);
922
923                                 /* list we were called with is gone, return */
924                                 if (!journal_list_still_alive(s, trans_id))
925                                         return 1;
926
927                                 /* the one we just flushed is gone, this means all
928                                  * older lists are also gone, so first_jl is no longer
929                                  * valid either.  Go back to the beginning.
930                                  */
931                                 if (!journal_list_still_alive
932                                     (s, other_trans_id)) {
933                                         goto find_first;
934                                 }
935                         }
936                         entry = entry->next;
937                         if (entry == &journal->j_journal_list)
938                                 return 0;
939                 } else {
940                         return 0;
941                 }
942         }
943         return 0;
944 }
945
946 static int reiserfs_async_progress_wait(struct super_block *s)
947 {
948         struct reiserfs_journal *j = SB_JOURNAL(s);
949
950         if (atomic_read(&j->j_async_throttle)) {
951                 reiserfs_write_unlock(s);
952                 congestion_wait(BLK_RW_ASYNC, HZ / 10);
953                 reiserfs_write_lock(s);
954         }
955
956         return 0;
957 }
958
959 /*
960 ** if this journal list still has commit blocks unflushed, send them to disk.
961 **
962 ** log areas must be flushed in order (transaction 2 can't commit before transaction 1)
963 ** Before the commit block can by written, every other log block must be safely on disk
964 **
965 */
966 static int flush_commit_list(struct super_block *s,
967                              struct reiserfs_journal_list *jl, int flushall)
968 {
969         int i;
970         b_blocknr_t bn;
971         struct buffer_head *tbh = NULL;
972         unsigned int trans_id = jl->j_trans_id;
973         struct reiserfs_journal *journal = SB_JOURNAL(s);
974         int retval = 0;
975         int write_len;
976
977         reiserfs_check_lock_depth(s, "flush_commit_list");
978
979         if (atomic_read(&jl->j_older_commits_done)) {
980                 return 0;
981         }
982
983         /* before we can put our commit blocks on disk, we have to make sure everyone older than
984          ** us is on disk too
985          */
986         BUG_ON(jl->j_len <= 0);
987         BUG_ON(trans_id == journal->j_trans_id);
988
989         get_journal_list(jl);
990         if (flushall) {
991                 if (flush_older_commits(s, jl) == 1) {
992                         /* list disappeared during flush_older_commits.  return */
993                         goto put_jl;
994                 }
995         }
996
997         /* make sure nobody is trying to flush this one at the same time */
998         reiserfs_mutex_lock_safe(&jl->j_commit_mutex, s);
999
1000         if (!journal_list_still_alive(s, trans_id)) {
1001                 mutex_unlock(&jl->j_commit_mutex);
1002                 goto put_jl;
1003         }
1004         BUG_ON(jl->j_trans_id == 0);
1005
1006         /* this commit is done, exit */
1007         if (atomic_read(&(jl->j_commit_left)) <= 0) {
1008                 if (flushall) {
1009                         atomic_set(&(jl->j_older_commits_done), 1);
1010                 }
1011                 mutex_unlock(&jl->j_commit_mutex);
1012                 goto put_jl;
1013         }
1014
1015         if (!list_empty(&jl->j_bh_list)) {
1016                 int ret;
1017
1018                 /*
1019                  * We might sleep in numerous places inside
1020                  * write_ordered_buffers. Relax the write lock.
1021                  */
1022                 reiserfs_write_unlock(s);
1023                 ret = write_ordered_buffers(&journal->j_dirty_buffers_lock,
1024                                             journal, jl, &jl->j_bh_list);
1025                 if (ret < 0 && retval == 0)
1026                         retval = ret;
1027                 reiserfs_write_lock(s);
1028         }
1029         BUG_ON(!list_empty(&jl->j_bh_list));
1030         /*
1031          * for the description block and all the log blocks, submit any buffers
1032          * that haven't already reached the disk.  Try to write at least 256
1033          * log blocks. later on, we will only wait on blocks that correspond
1034          * to this transaction, but while we're unplugging we might as well
1035          * get a chunk of data on there.
1036          */
1037         atomic_inc(&journal->j_async_throttle);
1038         write_len = jl->j_len + 1;
1039         if (write_len < 256)
1040                 write_len = 256;
1041         for (i = 0 ; i < write_len ; i++) {
1042                 bn = SB_ONDISK_JOURNAL_1st_BLOCK(s) + (jl->j_start + i) %
1043                     SB_ONDISK_JOURNAL_SIZE(s);
1044                 tbh = journal_find_get_block(s, bn);
1045                 if (tbh) {
1046                         if (buffer_dirty(tbh)) {
1047                             reiserfs_write_unlock(s);
1048                             ll_rw_block(WRITE, 1, &tbh);
1049                             reiserfs_write_lock(s);
1050                         }
1051                         put_bh(tbh) ;
1052                 }
1053         }
1054         atomic_dec(&journal->j_async_throttle);
1055
1056         for (i = 0; i < (jl->j_len + 1); i++) {
1057                 bn = SB_ONDISK_JOURNAL_1st_BLOCK(s) +
1058                     (jl->j_start + i) % SB_ONDISK_JOURNAL_SIZE(s);
1059                 tbh = journal_find_get_block(s, bn);
1060
1061                 reiserfs_write_unlock(s);
1062                 wait_on_buffer(tbh);
1063                 reiserfs_write_lock(s);
1064                 // since we're using ll_rw_blk above, it might have skipped over
1065                 // a locked buffer.  Double check here
1066                 //
1067                 /* redundant, sync_dirty_buffer() checks */
1068                 if (buffer_dirty(tbh)) {
1069                         reiserfs_write_unlock(s);
1070                         sync_dirty_buffer(tbh);
1071                         reiserfs_write_lock(s);
1072                 }
1073                 if (unlikely(!buffer_uptodate(tbh))) {
1074 #ifdef CONFIG_REISERFS_CHECK
1075                         reiserfs_warning(s, "journal-601",
1076                                          "buffer write failed");
1077 #endif
1078                         retval = -EIO;
1079                 }
1080                 put_bh(tbh);    /* once for journal_find_get_block */
1081                 put_bh(tbh);    /* once due to original getblk in do_journal_end */
1082                 atomic_dec(&(jl->j_commit_left));
1083         }
1084
1085         BUG_ON(atomic_read(&(jl->j_commit_left)) != 1);
1086
1087         /* If there was a write error in the journal - we can't commit
1088          * this transaction - it will be invalid and, if successful,
1089          * will just end up propagating the write error out to
1090          * the file system. */
1091         if (likely(!retval && !reiserfs_is_journal_aborted (journal))) {
1092                 if (buffer_dirty(jl->j_commit_bh))
1093                         BUG();
1094                 mark_buffer_dirty(jl->j_commit_bh) ;
1095                 reiserfs_write_unlock(s);
1096                 if (reiserfs_barrier_flush(s))
1097                         __sync_dirty_buffer(jl->j_commit_bh, WRITE_FLUSH_FUA);
1098                 else
1099                         sync_dirty_buffer(jl->j_commit_bh);
1100                 reiserfs_write_lock(s);
1101         }
1102
1103         /* If there was a write error in the journal - we can't commit this
1104          * transaction - it will be invalid and, if successful, will just end
1105          * up propagating the write error out to the filesystem. */
1106         if (unlikely(!buffer_uptodate(jl->j_commit_bh))) {
1107 #ifdef CONFIG_REISERFS_CHECK
1108                 reiserfs_warning(s, "journal-615", "buffer write failed");
1109 #endif
1110                 retval = -EIO;
1111         }
1112         bforget(jl->j_commit_bh);
1113         if (journal->j_last_commit_id != 0 &&
1114             (jl->j_trans_id - journal->j_last_commit_id) != 1) {
1115                 reiserfs_warning(s, "clm-2200", "last commit %lu, current %lu",
1116                                  journal->j_last_commit_id, jl->j_trans_id);
1117         }
1118         journal->j_last_commit_id = jl->j_trans_id;
1119
1120         /* now, every commit block is on the disk.  It is safe to allow blocks freed during this transaction to be reallocated */
1121         cleanup_freed_for_journal_list(s, jl);
1122
1123         retval = retval ? retval : journal->j_errno;
1124
1125         /* mark the metadata dirty */
1126         if (!retval)
1127                 dirty_one_transaction(s, jl);
1128         atomic_dec(&(jl->j_commit_left));
1129
1130         if (flushall) {
1131                 atomic_set(&(jl->j_older_commits_done), 1);
1132         }
1133         mutex_unlock(&jl->j_commit_mutex);
1134       put_jl:
1135         put_journal_list(s, jl);
1136
1137         if (retval)
1138                 reiserfs_abort(s, retval, "Journal write error in %s",
1139                                __func__);
1140         return retval;
1141 }
1142
1143 /*
1144 ** flush_journal_list frequently needs to find a newer transaction for a given block.  This does that, or
1145 ** returns NULL if it can't find anything
1146 */
1147 static struct reiserfs_journal_list *find_newer_jl_for_cn(struct
1148                                                           reiserfs_journal_cnode
1149                                                           *cn)
1150 {
1151         struct super_block *sb = cn->sb;
1152         b_blocknr_t blocknr = cn->blocknr;
1153
1154         cn = cn->hprev;
1155         while (cn) {
1156                 if (cn->sb == sb && cn->blocknr == blocknr && cn->jlist) {
1157                         return cn->jlist;
1158                 }
1159                 cn = cn->hprev;
1160         }
1161         return NULL;
1162 }
1163
1164 static int newer_jl_done(struct reiserfs_journal_cnode *cn)
1165 {
1166         struct super_block *sb = cn->sb;
1167         b_blocknr_t blocknr = cn->blocknr;
1168
1169         cn = cn->hprev;
1170         while (cn) {
1171                 if (cn->sb == sb && cn->blocknr == blocknr && cn->jlist &&
1172                     atomic_read(&cn->jlist->j_commit_left) != 0)
1173                                     return 0;
1174                 cn = cn->hprev;
1175         }
1176         return 1;
1177 }
1178
1179 static void remove_journal_hash(struct super_block *,
1180                                 struct reiserfs_journal_cnode **,
1181                                 struct reiserfs_journal_list *, unsigned long,
1182                                 int);
1183
1184 /*
1185 ** once all the real blocks have been flushed, it is safe to remove them from the
1186 ** journal list for this transaction.  Aside from freeing the cnode, this also allows the
1187 ** block to be reallocated for data blocks if it had been deleted.
1188 */
1189 static void remove_all_from_journal_list(struct super_block *sb,
1190                                          struct reiserfs_journal_list *jl,
1191                                          int debug)
1192 {
1193         struct reiserfs_journal *journal = SB_JOURNAL(sb);
1194         struct reiserfs_journal_cnode *cn, *last;
1195         cn = jl->j_realblock;
1196
1197         /* which is better, to lock once around the whole loop, or
1198          ** to lock for each call to remove_journal_hash?
1199          */
1200         while (cn) {
1201                 if (cn->blocknr != 0) {
1202                         if (debug) {
1203                                 reiserfs_warning(sb, "reiserfs-2201",
1204                                                  "block %u, bh is %d, state %ld",
1205                                                  cn->blocknr, cn->bh ? 1 : 0,
1206                                                  cn->state);
1207                         }
1208                         cn->state = 0;
1209                         remove_journal_hash(sb, journal->j_list_hash_table,
1210                                             jl, cn->blocknr, 1);
1211                 }
1212                 last = cn;
1213                 cn = cn->next;
1214                 free_cnode(sb, last);
1215         }
1216         jl->j_realblock = NULL;
1217 }
1218
1219 /*
1220 ** if this timestamp is greater than the timestamp we wrote last to the header block, write it to the header block.
1221 ** once this is done, I can safely say the log area for this transaction won't ever be replayed, and I can start
1222 ** releasing blocks in this transaction for reuse as data blocks.
1223 ** called by flush_journal_list, before it calls remove_all_from_journal_list
1224 **
1225 */
1226 static int _update_journal_header_block(struct super_block *sb,
1227                                         unsigned long offset,
1228                                         unsigned int trans_id)
1229 {
1230         struct reiserfs_journal_header *jh;
1231         struct reiserfs_journal *journal = SB_JOURNAL(sb);
1232
1233         if (reiserfs_is_journal_aborted(journal))
1234                 return -EIO;
1235
1236         if (trans_id >= journal->j_last_flush_trans_id) {
1237                 if (buffer_locked((journal->j_header_bh))) {
1238                         reiserfs_write_unlock(sb);
1239                         wait_on_buffer((journal->j_header_bh));
1240                         reiserfs_write_lock(sb);
1241                         if (unlikely(!buffer_uptodate(journal->j_header_bh))) {
1242 #ifdef CONFIG_REISERFS_CHECK
1243                                 reiserfs_warning(sb, "journal-699",
1244                                                  "buffer write failed");
1245 #endif
1246                                 return -EIO;
1247                         }
1248                 }
1249                 journal->j_last_flush_trans_id = trans_id;
1250                 journal->j_first_unflushed_offset = offset;
1251                 jh = (struct reiserfs_journal_header *)(journal->j_header_bh->
1252                                                         b_data);
1253                 jh->j_last_flush_trans_id = cpu_to_le32(trans_id);
1254                 jh->j_first_unflushed_offset = cpu_to_le32(offset);
1255                 jh->j_mount_id = cpu_to_le32(journal->j_mount_id);
1256
1257                 set_buffer_dirty(journal->j_header_bh);
1258                 reiserfs_write_unlock(sb);
1259
1260                 if (reiserfs_barrier_flush(sb))
1261                         __sync_dirty_buffer(journal->j_header_bh, WRITE_FLUSH_FUA);
1262                 else
1263                         sync_dirty_buffer(journal->j_header_bh);
1264
1265                 reiserfs_write_lock(sb);
1266                 if (!buffer_uptodate(journal->j_header_bh)) {
1267                         reiserfs_warning(sb, "journal-837",
1268                                          "IO error during journal replay");
1269                         return -EIO;
1270                 }
1271         }
1272         return 0;
1273 }
1274
1275 static int update_journal_header_block(struct super_block *sb,
1276                                        unsigned long offset,
1277                                        unsigned int trans_id)
1278 {
1279         return _update_journal_header_block(sb, offset, trans_id);
1280 }
1281
1282 /*
1283 ** flush any and all journal lists older than you are
1284 ** can only be called from flush_journal_list
1285 */
1286 static int flush_older_journal_lists(struct super_block *sb,
1287                                      struct reiserfs_journal_list *jl)
1288 {
1289         struct list_head *entry;
1290         struct reiserfs_journal_list *other_jl;
1291         struct reiserfs_journal *journal = SB_JOURNAL(sb);
1292         unsigned int trans_id = jl->j_trans_id;
1293
1294         /* we know we are the only ones flushing things, no extra race
1295          * protection is required.
1296          */
1297       restart:
1298         entry = journal->j_journal_list.next;
1299         /* Did we wrap? */
1300         if (entry == &journal->j_journal_list)
1301                 return 0;
1302         other_jl = JOURNAL_LIST_ENTRY(entry);
1303         if (other_jl->j_trans_id < trans_id) {
1304                 BUG_ON(other_jl->j_refcount <= 0);
1305                 /* do not flush all */
1306                 flush_journal_list(sb, other_jl, 0);
1307
1308                 /* other_jl is now deleted from the list */
1309                 goto restart;
1310         }
1311         return 0;
1312 }
1313
1314 static void del_from_work_list(struct super_block *s,
1315                                struct reiserfs_journal_list *jl)
1316 {
1317         struct reiserfs_journal *journal = SB_JOURNAL(s);
1318         if (!list_empty(&jl->j_working_list)) {
1319                 list_del_init(&jl->j_working_list);
1320                 journal->j_num_work_lists--;
1321         }
1322 }
1323
1324 /* flush a journal list, both commit and real blocks
1325 **
1326 ** always set flushall to 1, unless you are calling from inside
1327 ** flush_journal_list
1328 **
1329 ** IMPORTANT.  This can only be called while there are no journal writers,
1330 ** and the journal is locked.  That means it can only be called from
1331 ** do_journal_end, or by journal_release
1332 */
1333 static int flush_journal_list(struct super_block *s,
1334                               struct reiserfs_journal_list *jl, int flushall)
1335 {
1336         struct reiserfs_journal_list *pjl;
1337         struct reiserfs_journal_cnode *cn, *last;
1338         int count;
1339         int was_jwait = 0;
1340         int was_dirty = 0;
1341         struct buffer_head *saved_bh;
1342         unsigned long j_len_saved = jl->j_len;
1343         struct reiserfs_journal *journal = SB_JOURNAL(s);
1344         int err = 0;
1345
1346         BUG_ON(j_len_saved <= 0);
1347
1348         if (atomic_read(&journal->j_wcount) != 0) {
1349                 reiserfs_warning(s, "clm-2048", "called with wcount %d",
1350                                  atomic_read(&journal->j_wcount));
1351         }
1352         BUG_ON(jl->j_trans_id == 0);
1353
1354         /* if flushall == 0, the lock is already held */
1355         if (flushall) {
1356                 reiserfs_mutex_lock_safe(&journal->j_flush_mutex, s);
1357         } else if (mutex_trylock(&journal->j_flush_mutex)) {
1358                 BUG();
1359         }
1360
1361         count = 0;
1362         if (j_len_saved > journal->j_trans_max) {
1363                 reiserfs_panic(s, "journal-715", "length is %lu, trans id %lu",
1364                                j_len_saved, jl->j_trans_id);
1365                 return 0;
1366         }
1367
1368         /* if all the work is already done, get out of here */
1369         if (atomic_read(&(jl->j_nonzerolen)) <= 0 &&
1370             atomic_read(&(jl->j_commit_left)) <= 0) {
1371                 goto flush_older_and_return;
1372         }
1373
1374         /* start by putting the commit list on disk.  This will also flush
1375          ** the commit lists of any olders transactions
1376          */
1377         flush_commit_list(s, jl, 1);
1378
1379         if (!(jl->j_state & LIST_DIRTY)
1380             && !reiserfs_is_journal_aborted(journal))
1381                 BUG();
1382
1383         /* are we done now? */
1384         if (atomic_read(&(jl->j_nonzerolen)) <= 0 &&
1385             atomic_read(&(jl->j_commit_left)) <= 0) {
1386                 goto flush_older_and_return;
1387         }
1388
1389         /* loop through each cnode, see if we need to write it,
1390          ** or wait on a more recent transaction, or just ignore it
1391          */
1392         if (atomic_read(&(journal->j_wcount)) != 0) {
1393                 reiserfs_panic(s, "journal-844", "journal list is flushing, "
1394                                "wcount is not 0");
1395         }
1396         cn = jl->j_realblock;
1397         while (cn) {
1398                 was_jwait = 0;
1399                 was_dirty = 0;
1400                 saved_bh = NULL;
1401                 /* blocknr of 0 is no longer in the hash, ignore it */
1402                 if (cn->blocknr == 0) {
1403                         goto free_cnode;
1404                 }
1405
1406                 /* This transaction failed commit. Don't write out to the disk */
1407                 if (!(jl->j_state & LIST_DIRTY))
1408                         goto free_cnode;
1409
1410                 pjl = find_newer_jl_for_cn(cn);
1411                 /* the order is important here.  We check pjl to make sure we
1412                  ** don't clear BH_JDirty_wait if we aren't the one writing this
1413                  ** block to disk
1414                  */
1415                 if (!pjl && cn->bh) {
1416                         saved_bh = cn->bh;
1417
1418                         /* we do this to make sure nobody releases the buffer while
1419                          ** we are working with it
1420                          */
1421                         get_bh(saved_bh);
1422
1423                         if (buffer_journal_dirty(saved_bh)) {
1424                                 BUG_ON(!can_dirty(cn));
1425                                 was_jwait = 1;
1426                                 was_dirty = 1;
1427                         } else if (can_dirty(cn)) {
1428                                 /* everything with !pjl && jwait should be writable */
1429                                 BUG();
1430                         }
1431                 }
1432
1433                 /* if someone has this block in a newer transaction, just make
1434                  ** sure they are committed, and don't try writing it to disk
1435                  */
1436                 if (pjl) {
1437                         if (atomic_read(&pjl->j_commit_left))
1438                                 flush_commit_list(s, pjl, 1);
1439                         goto free_cnode;
1440                 }
1441
1442                 /* bh == NULL when the block got to disk on its own, OR,
1443                  ** the block got freed in a future transaction
1444                  */
1445                 if (saved_bh == NULL) {
1446                         goto free_cnode;
1447                 }
1448
1449                 /* this should never happen.  kupdate_one_transaction has this list
1450                  ** locked while it works, so we should never see a buffer here that
1451                  ** is not marked JDirty_wait
1452                  */
1453                 if ((!was_jwait) && !buffer_locked(saved_bh)) {
1454                         reiserfs_warning(s, "journal-813",
1455                                          "BAD! buffer %llu %cdirty %cjwait, "
1456                                          "not in a newer tranasction",
1457                                          (unsigned long long)saved_bh->
1458                                          b_blocknr, was_dirty ? ' ' : '!',
1459                                          was_jwait ? ' ' : '!');
1460                 }
1461                 if (was_dirty) {
1462                         /* we inc again because saved_bh gets decremented at free_cnode */
1463                         get_bh(saved_bh);
1464                         set_bit(BLOCK_NEEDS_FLUSH, &cn->state);
1465                         lock_buffer(saved_bh);
1466                         BUG_ON(cn->blocknr != saved_bh->b_blocknr);
1467                         if (buffer_dirty(saved_bh))
1468                                 submit_logged_buffer(saved_bh);
1469                         else
1470                                 unlock_buffer(saved_bh);
1471                         count++;
1472                 } else {
1473                         reiserfs_warning(s, "clm-2082",
1474                                          "Unable to flush buffer %llu in %s",
1475                                          (unsigned long long)saved_bh->
1476                                          b_blocknr, __func__);
1477                 }
1478               free_cnode:
1479                 last = cn;
1480                 cn = cn->next;
1481                 if (saved_bh) {
1482                         /* we incremented this to keep others from taking the buffer head away */
1483                         put_bh(saved_bh);
1484                         if (atomic_read(&(saved_bh->b_count)) < 0) {
1485                                 reiserfs_warning(s, "journal-945",
1486                                                  "saved_bh->b_count < 0");
1487                         }
1488                 }
1489         }
1490         if (count > 0) {
1491                 cn = jl->j_realblock;
1492                 while (cn) {
1493                         if (test_bit(BLOCK_NEEDS_FLUSH, &cn->state)) {
1494                                 if (!cn->bh) {
1495                                         reiserfs_panic(s, "journal-1011",
1496                                                        "cn->bh is NULL");
1497                                 }
1498
1499                                 reiserfs_write_unlock(s);
1500                                 wait_on_buffer(cn->bh);
1501                                 reiserfs_write_lock(s);
1502
1503                                 if (!cn->bh) {
1504                                         reiserfs_panic(s, "journal-1012",
1505                                                        "cn->bh is NULL");
1506                                 }
1507                                 if (unlikely(!buffer_uptodate(cn->bh))) {
1508 #ifdef CONFIG_REISERFS_CHECK
1509                                         reiserfs_warning(s, "journal-949",
1510                                                          "buffer write failed");
1511 #endif
1512                                         err = -EIO;
1513                                 }
1514                                 /* note, we must clear the JDirty_wait bit after the up to date
1515                                  ** check, otherwise we race against our flushpage routine
1516                                  */
1517                                 BUG_ON(!test_clear_buffer_journal_dirty
1518                                        (cn->bh));
1519
1520                                 /* drop one ref for us */
1521                                 put_bh(cn->bh);
1522                                 /* drop one ref for journal_mark_dirty */
1523                                 release_buffer_page(cn->bh);
1524                         }
1525                         cn = cn->next;
1526                 }
1527         }
1528
1529         if (err)
1530                 reiserfs_abort(s, -EIO,
1531                                "Write error while pushing transaction to disk in %s",
1532                                __func__);
1533       flush_older_and_return:
1534
1535         /* before we can update the journal header block, we _must_ flush all
1536          ** real blocks from all older transactions to disk.  This is because
1537          ** once the header block is updated, this transaction will not be
1538          ** replayed after a crash
1539          */
1540         if (flushall) {
1541                 flush_older_journal_lists(s, jl);
1542         }
1543
1544         err = journal->j_errno;
1545         /* before we can remove everything from the hash tables for this
1546          ** transaction, we must make sure it can never be replayed
1547          **
1548          ** since we are only called from do_journal_end, we know for sure there
1549          ** are no allocations going on while we are flushing journal lists.  So,
1550          ** we only need to update the journal header block for the last list
1551          ** being flushed
1552          */
1553         if (!err && flushall) {
1554                 err =
1555                     update_journal_header_block(s,
1556                                                 (jl->j_start + jl->j_len +
1557                                                  2) % SB_ONDISK_JOURNAL_SIZE(s),
1558                                                 jl->j_trans_id);
1559                 if (err)
1560                         reiserfs_abort(s, -EIO,
1561                                        "Write error while updating journal header in %s",
1562                                        __func__);
1563         }
1564         remove_all_from_journal_list(s, jl, 0);
1565         list_del_init(&jl->j_list);
1566         journal->j_num_lists--;
1567         del_from_work_list(s, jl);
1568
1569         if (journal->j_last_flush_id != 0 &&
1570             (jl->j_trans_id - journal->j_last_flush_id) != 1) {
1571                 reiserfs_warning(s, "clm-2201", "last flush %lu, current %lu",
1572                                  journal->j_last_flush_id, jl->j_trans_id);
1573         }
1574         journal->j_last_flush_id = jl->j_trans_id;
1575
1576         /* not strictly required since we are freeing the list, but it should
1577          * help find code using dead lists later on
1578          */
1579         jl->j_len = 0;
1580         atomic_set(&(jl->j_nonzerolen), 0);
1581         jl->j_start = 0;
1582         jl->j_realblock = NULL;
1583         jl->j_commit_bh = NULL;
1584         jl->j_trans_id = 0;
1585         jl->j_state = 0;
1586         put_journal_list(s, jl);
1587         if (flushall)
1588                 mutex_unlock(&journal->j_flush_mutex);
1589         return err;
1590 }
1591
1592 static int test_transaction(struct super_block *s,
1593                             struct reiserfs_journal_list *jl)
1594 {
1595         struct reiserfs_journal_cnode *cn;
1596
1597         if (jl->j_len == 0 || atomic_read(&jl->j_nonzerolen) == 0)
1598                 return 1;
1599
1600         cn = jl->j_realblock;
1601         while (cn) {
1602                 /* if the blocknr == 0, this has been cleared from the hash,
1603                  ** skip it
1604                  */
1605                 if (cn->blocknr == 0) {
1606                         goto next;
1607                 }
1608                 if (cn->bh && !newer_jl_done(cn))
1609                         return 0;
1610               next:
1611                 cn = cn->next;
1612                 cond_resched();
1613         }
1614         return 0;
1615 }
1616
1617 static int write_one_transaction(struct super_block *s,
1618                                  struct reiserfs_journal_list *jl,
1619                                  struct buffer_chunk *chunk)
1620 {
1621         struct reiserfs_journal_cnode *cn;
1622         int ret = 0;
1623
1624         jl->j_state |= LIST_TOUCHED;
1625         del_from_work_list(s, jl);
1626         if (jl->j_len == 0 || atomic_read(&jl->j_nonzerolen) == 0) {
1627                 return 0;
1628         }
1629
1630         cn = jl->j_realblock;
1631         while (cn) {
1632                 /* if the blocknr == 0, this has been cleared from the hash,
1633                  ** skip it
1634                  */
1635                 if (cn->blocknr == 0) {
1636                         goto next;
1637                 }
1638                 if (cn->bh && can_dirty(cn) && buffer_dirty(cn->bh)) {
1639                         struct buffer_head *tmp_bh;
1640                         /* we can race against journal_mark_freed when we try
1641                          * to lock_buffer(cn->bh), so we have to inc the buffer
1642                          * count, and recheck things after locking
1643                          */
1644                         tmp_bh = cn->bh;
1645                         get_bh(tmp_bh);
1646                         lock_buffer(tmp_bh);
1647                         if (cn->bh && can_dirty(cn) && buffer_dirty(tmp_bh)) {
1648                                 if (!buffer_journal_dirty(tmp_bh) ||
1649                                     buffer_journal_prepared(tmp_bh))
1650                                         BUG();
1651                                 add_to_chunk(chunk, tmp_bh, NULL, write_chunk);
1652                                 ret++;
1653                         } else {
1654                                 /* note, cn->bh might be null now */
1655                                 unlock_buffer(tmp_bh);
1656                         }
1657                         put_bh(tmp_bh);
1658                 }
1659               next:
1660                 cn = cn->next;
1661                 cond_resched();
1662         }
1663         return ret;
1664 }
1665
1666 /* used by flush_commit_list */
1667 static int dirty_one_transaction(struct super_block *s,
1668                                  struct reiserfs_journal_list *jl)
1669 {
1670         struct reiserfs_journal_cnode *cn;
1671         struct reiserfs_journal_list *pjl;
1672         int ret = 0;
1673
1674         jl->j_state |= LIST_DIRTY;
1675         cn = jl->j_realblock;
1676         while (cn) {
1677                 /* look for a more recent transaction that logged this
1678                  ** buffer.  Only the most recent transaction with a buffer in
1679                  ** it is allowed to send that buffer to disk
1680                  */
1681                 pjl = find_newer_jl_for_cn(cn);
1682                 if (!pjl && cn->blocknr && cn->bh
1683                     && buffer_journal_dirty(cn->bh)) {
1684                         BUG_ON(!can_dirty(cn));
1685                         /* if the buffer is prepared, it will either be logged
1686                          * or restored.  If restored, we need to make sure
1687                          * it actually gets marked dirty
1688                          */
1689                         clear_buffer_journal_new(cn->bh);
1690                         if (buffer_journal_prepared(cn->bh)) {
1691                                 set_buffer_journal_restore_dirty(cn->bh);
1692                         } else {
1693                                 set_buffer_journal_test(cn->bh);
1694                                 mark_buffer_dirty(cn->bh);
1695                         }
1696                 }
1697                 cn = cn->next;
1698         }
1699         return ret;
1700 }
1701
1702 static int kupdate_transactions(struct super_block *s,
1703                                 struct reiserfs_journal_list *jl,
1704                                 struct reiserfs_journal_list **next_jl,
1705                                 unsigned int *next_trans_id,
1706                                 int num_blocks, int num_trans)
1707 {
1708         int ret = 0;
1709         int written = 0;
1710         int transactions_flushed = 0;
1711         unsigned int orig_trans_id = jl->j_trans_id;
1712         struct buffer_chunk chunk;
1713         struct list_head *entry;
1714         struct reiserfs_journal *journal = SB_JOURNAL(s);
1715         chunk.nr = 0;
1716
1717         reiserfs_mutex_lock_safe(&journal->j_flush_mutex, s);
1718         if (!journal_list_still_alive(s, orig_trans_id)) {
1719                 goto done;
1720         }
1721
1722         /* we've got j_flush_mutex held, nobody is going to delete any
1723          * of these lists out from underneath us
1724          */
1725         while ((num_trans && transactions_flushed < num_trans) ||
1726                (!num_trans && written < num_blocks)) {
1727
1728                 if (jl->j_len == 0 || (jl->j_state & LIST_TOUCHED) ||
1729                     atomic_read(&jl->j_commit_left)
1730                     || !(jl->j_state & LIST_DIRTY)) {
1731                         del_from_work_list(s, jl);
1732                         break;
1733                 }
1734                 ret = write_one_transaction(s, jl, &chunk);
1735
1736                 if (ret < 0)
1737                         goto done;
1738                 transactions_flushed++;
1739                 written += ret;
1740                 entry = jl->j_list.next;
1741
1742                 /* did we wrap? */
1743                 if (entry == &journal->j_journal_list) {
1744                         break;
1745                 }
1746                 jl = JOURNAL_LIST_ENTRY(entry);
1747
1748                 /* don't bother with older transactions */
1749                 if (jl->j_trans_id <= orig_trans_id)
1750                         break;
1751         }
1752         if (chunk.nr) {
1753                 write_chunk(&chunk);
1754         }
1755
1756       done:
1757         mutex_unlock(&journal->j_flush_mutex);
1758         return ret;
1759 }
1760
1761 /* for o_sync and fsync heavy applications, they tend to use
1762 ** all the journa list slots with tiny transactions.  These
1763 ** trigger lots and lots of calls to update the header block, which
1764 ** adds seeks and slows things down.
1765 **
1766 ** This function tries to clear out a large chunk of the journal lists
1767 ** at once, which makes everything faster since only the newest journal
1768 ** list updates the header block
1769 */
1770 static int flush_used_journal_lists(struct super_block *s,
1771                                     struct reiserfs_journal_list *jl)
1772 {
1773         unsigned long len = 0;
1774         unsigned long cur_len;
1775         int ret;
1776         int i;
1777         int limit = 256;
1778         struct reiserfs_journal_list *tjl;
1779         struct reiserfs_journal_list *flush_jl;
1780         unsigned int trans_id;
1781         struct reiserfs_journal *journal = SB_JOURNAL(s);
1782
1783         flush_jl = tjl = jl;
1784
1785         /* in data logging mode, try harder to flush a lot of blocks */
1786         if (reiserfs_data_log(s))
1787                 limit = 1024;
1788         /* flush for 256 transactions or limit blocks, whichever comes first */
1789         for (i = 0; i < 256 && len < limit; i++) {
1790                 if (atomic_read(&tjl->j_commit_left) ||
1791                     tjl->j_trans_id < jl->j_trans_id) {
1792                         break;
1793                 }
1794                 cur_len = atomic_read(&tjl->j_nonzerolen);
1795                 if (cur_len > 0) {
1796                         tjl->j_state &= ~LIST_TOUCHED;
1797                 }
1798                 len += cur_len;
1799                 flush_jl = tjl;
1800                 if (tjl->j_list.next == &journal->j_journal_list)
1801                         break;
1802                 tjl = JOURNAL_LIST_ENTRY(tjl->j_list.next);
1803         }
1804         /* try to find a group of blocks we can flush across all the
1805          ** transactions, but only bother if we've actually spanned
1806          ** across multiple lists
1807          */
1808         if (flush_jl != jl) {
1809                 ret = kupdate_transactions(s, jl, &tjl, &trans_id, len, i);
1810         }
1811         flush_journal_list(s, flush_jl, 1);
1812         return 0;
1813 }
1814
1815 /*
1816 ** removes any nodes in table with name block and dev as bh.
1817 ** only touchs the hnext and hprev pointers.
1818 */
1819 void remove_journal_hash(struct super_block *sb,
1820                          struct reiserfs_journal_cnode **table,
1821                          struct reiserfs_journal_list *jl,
1822                          unsigned long block, int remove_freed)
1823 {
1824         struct reiserfs_journal_cnode *cur;
1825         struct reiserfs_journal_cnode **head;
1826
1827         head = &(journal_hash(table, sb, block));
1828         if (!head) {
1829                 return;
1830         }
1831         cur = *head;
1832         while (cur) {
1833                 if (cur->blocknr == block && cur->sb == sb
1834                     && (jl == NULL || jl == cur->jlist)
1835                     && (!test_bit(BLOCK_FREED, &cur->state) || remove_freed)) {
1836                         if (cur->hnext) {
1837                                 cur->hnext->hprev = cur->hprev;
1838                         }
1839                         if (cur->hprev) {
1840                                 cur->hprev->hnext = cur->hnext;
1841                         } else {
1842                                 *head = cur->hnext;
1843                         }
1844                         cur->blocknr = 0;
1845                         cur->sb = NULL;
1846                         cur->state = 0;
1847                         if (cur->bh && cur->jlist)      /* anybody who clears the cur->bh will also dec the nonzerolen */
1848                                 atomic_dec(&(cur->jlist->j_nonzerolen));
1849                         cur->bh = NULL;
1850                         cur->jlist = NULL;
1851                 }
1852                 cur = cur->hnext;
1853         }
1854 }
1855
1856 static void free_journal_ram(struct super_block *sb)
1857 {
1858         struct reiserfs_journal *journal = SB_JOURNAL(sb);
1859         kfree(journal->j_current_jl);
1860         journal->j_num_lists--;
1861
1862         vfree(journal->j_cnode_free_orig);
1863         free_list_bitmaps(sb, journal->j_list_bitmap);
1864         free_bitmap_nodes(sb);  /* must be after free_list_bitmaps */
1865         if (journal->j_header_bh) {
1866                 brelse(journal->j_header_bh);
1867         }
1868         /* j_header_bh is on the journal dev, make sure not to release the journal
1869          * dev until we brelse j_header_bh
1870          */
1871         release_journal_dev(sb, journal);
1872         vfree(journal);
1873 }
1874
1875 /*
1876 ** call on unmount.  Only set error to 1 if you haven't made your way out
1877 ** of read_super() yet.  Any other caller must keep error at 0.
1878 */
1879 static int do_journal_release(struct reiserfs_transaction_handle *th,
1880                               struct super_block *sb, int error)
1881 {
1882         struct reiserfs_transaction_handle myth;
1883         int flushed = 0;
1884         struct reiserfs_journal *journal = SB_JOURNAL(sb);
1885
1886         /* we only want to flush out transactions if we were called with error == 0
1887          */
1888         if (!error && !(sb->s_flags & MS_RDONLY)) {
1889                 /* end the current trans */
1890                 BUG_ON(!th->t_trans_id);
1891                 do_journal_end(th, sb, 10, FLUSH_ALL);
1892
1893                 /* make sure something gets logged to force our way into the flush code */
1894                 if (!journal_join(&myth, sb, 1)) {
1895                         reiserfs_prepare_for_journal(sb,
1896                                                      SB_BUFFER_WITH_SB(sb),
1897                                                      1);
1898                         journal_mark_dirty(&myth, sb,
1899                                            SB_BUFFER_WITH_SB(sb));
1900                         do_journal_end(&myth, sb, 1, FLUSH_ALL);
1901                         flushed = 1;
1902                 }
1903         }
1904
1905         /* this also catches errors during the do_journal_end above */
1906         if (!error && reiserfs_is_journal_aborted(journal)) {
1907                 memset(&myth, 0, sizeof(myth));
1908                 if (!journal_join_abort(&myth, sb, 1)) {
1909                         reiserfs_prepare_for_journal(sb,
1910                                                      SB_BUFFER_WITH_SB(sb),
1911                                                      1);
1912                         journal_mark_dirty(&myth, sb,
1913                                            SB_BUFFER_WITH_SB(sb));
1914                         do_journal_end(&myth, sb, 1, FLUSH_ALL);
1915                 }
1916         }
1917
1918         reiserfs_mounted_fs_count--;
1919
1920         /*
1921          * We must release the write lock here because
1922          * the workqueue job (flush_async_commit) needs this lock
1923          */
1924         reiserfs_write_unlock(sb);
1925         /*
1926          * Cancel flushing of old commits. Note that this work will not
1927          * be requeued because superblock is being shutdown and doesn't
1928          * have MS_ACTIVE set.
1929          */
1930         /* wait for all commits to finish */
1931         cancel_delayed_work_sync(&SB_JOURNAL(sb)->j_work);
1932
1933         if (!reiserfs_mounted_fs_count) {
1934                 destroy_workqueue(commit_wq);
1935                 commit_wq = NULL;
1936         }
1937
1938         free_journal_ram(sb);
1939
1940         reiserfs_write_lock(sb);
1941
1942         return 0;
1943 }
1944
1945 /*
1946 ** call on unmount.  flush all journal trans, release all alloc'd ram
1947 */
1948 int journal_release(struct reiserfs_transaction_handle *th,
1949                     struct super_block *sb)
1950 {
1951         return do_journal_release(th, sb, 0);
1952 }
1953
1954 /*
1955 ** only call from an error condition inside reiserfs_read_super!
1956 */
1957 int journal_release_error(struct reiserfs_transaction_handle *th,
1958                           struct super_block *sb)
1959 {
1960         return do_journal_release(th, sb, 1);
1961 }
1962
1963 /* compares description block with commit block.  returns 1 if they differ, 0 if they are the same */
1964 static int journal_compare_desc_commit(struct super_block *sb,
1965                                        struct reiserfs_journal_desc *desc,
1966                                        struct reiserfs_journal_commit *commit)
1967 {
1968         if (get_commit_trans_id(commit) != get_desc_trans_id(desc) ||
1969             get_commit_trans_len(commit) != get_desc_trans_len(desc) ||
1970             get_commit_trans_len(commit) > SB_JOURNAL(sb)->j_trans_max ||
1971             get_commit_trans_len(commit) <= 0) {
1972                 return 1;
1973         }
1974         return 0;
1975 }
1976
1977 /* returns 0 if it did not find a description block
1978 ** returns -1 if it found a corrupt commit block
1979 ** returns 1 if both desc and commit were valid
1980 */
1981 static int journal_transaction_is_valid(struct super_block *sb,
1982                                         struct buffer_head *d_bh,
1983                                         unsigned int *oldest_invalid_trans_id,
1984                                         unsigned long *newest_mount_id)
1985 {
1986         struct reiserfs_journal_desc *desc;
1987         struct reiserfs_journal_commit *commit;
1988         struct buffer_head *c_bh;
1989         unsigned long offset;
1990
1991         if (!d_bh)
1992                 return 0;
1993
1994         desc = (struct reiserfs_journal_desc *)d_bh->b_data;
1995         if (get_desc_trans_len(desc) > 0
1996             && !memcmp(get_journal_desc_magic(d_bh), JOURNAL_DESC_MAGIC, 8)) {
1997                 if (oldest_invalid_trans_id && *oldest_invalid_trans_id
1998                     && get_desc_trans_id(desc) > *oldest_invalid_trans_id) {
1999                         reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2000                                        "journal-986: transaction "
2001                                        "is valid returning because trans_id %d is greater than "
2002                                        "oldest_invalid %lu",
2003                                        get_desc_trans_id(desc),
2004                                        *oldest_invalid_trans_id);
2005                         return 0;
2006                 }
2007                 if (newest_mount_id
2008                     && *newest_mount_id > get_desc_mount_id(desc)) {
2009                         reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2010                                        "journal-1087: transaction "
2011                                        "is valid returning because mount_id %d is less than "
2012                                        "newest_mount_id %lu",
2013                                        get_desc_mount_id(desc),
2014                                        *newest_mount_id);
2015                         return -1;
2016                 }
2017                 if (get_desc_trans_len(desc) > SB_JOURNAL(sb)->j_trans_max) {
2018                         reiserfs_warning(sb, "journal-2018",
2019                                          "Bad transaction length %d "
2020                                          "encountered, ignoring transaction",
2021                                          get_desc_trans_len(desc));
2022                         return -1;
2023                 }
2024                 offset = d_bh->b_blocknr - SB_ONDISK_JOURNAL_1st_BLOCK(sb);
2025
2026                 /* ok, we have a journal description block, lets see if the transaction was valid */
2027                 c_bh =
2028                     journal_bread(sb,
2029                                   SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2030                                   ((offset + get_desc_trans_len(desc) +
2031                                     1) % SB_ONDISK_JOURNAL_SIZE(sb)));
2032                 if (!c_bh)
2033                         return 0;
2034                 commit = (struct reiserfs_journal_commit *)c_bh->b_data;
2035                 if (journal_compare_desc_commit(sb, desc, commit)) {
2036                         reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2037                                        "journal_transaction_is_valid, commit offset %ld had bad "
2038                                        "time %d or length %d",
2039                                        c_bh->b_blocknr -
2040                                        SB_ONDISK_JOURNAL_1st_BLOCK(sb),
2041                                        get_commit_trans_id(commit),
2042                                        get_commit_trans_len(commit));
2043                         brelse(c_bh);
2044                         if (oldest_invalid_trans_id) {
2045                                 *oldest_invalid_trans_id =
2046                                     get_desc_trans_id(desc);
2047                                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2048                                                "journal-1004: "
2049                                                "transaction_is_valid setting oldest invalid trans_id "
2050                                                "to %d",
2051                                                get_desc_trans_id(desc));
2052                         }
2053                         return -1;
2054                 }
2055                 brelse(c_bh);
2056                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2057                                "journal-1006: found valid "
2058                                "transaction start offset %llu, len %d id %d",
2059                                d_bh->b_blocknr -
2060                                SB_ONDISK_JOURNAL_1st_BLOCK(sb),
2061                                get_desc_trans_len(desc),
2062                                get_desc_trans_id(desc));
2063                 return 1;
2064         } else {
2065                 return 0;
2066         }
2067 }
2068
2069 static void brelse_array(struct buffer_head **heads, int num)
2070 {
2071         int i;
2072         for (i = 0; i < num; i++) {
2073                 brelse(heads[i]);
2074         }
2075 }
2076
2077 /*
2078 ** given the start, and values for the oldest acceptable transactions,
2079 ** this either reads in a replays a transaction, or returns because the transaction
2080 ** is invalid, or too old.
2081 */
2082 static int journal_read_transaction(struct super_block *sb,
2083                                     unsigned long cur_dblock,
2084                                     unsigned long oldest_start,
2085                                     unsigned int oldest_trans_id,
2086                                     unsigned long newest_mount_id)
2087 {
2088         struct reiserfs_journal *journal = SB_JOURNAL(sb);
2089         struct reiserfs_journal_desc *desc;
2090         struct reiserfs_journal_commit *commit;
2091         unsigned int trans_id = 0;
2092         struct buffer_head *c_bh;
2093         struct buffer_head *d_bh;
2094         struct buffer_head **log_blocks = NULL;
2095         struct buffer_head **real_blocks = NULL;
2096         unsigned int trans_offset;
2097         int i;
2098         int trans_half;
2099
2100         d_bh = journal_bread(sb, cur_dblock);
2101         if (!d_bh)
2102                 return 1;
2103         desc = (struct reiserfs_journal_desc *)d_bh->b_data;
2104         trans_offset = d_bh->b_blocknr - SB_ONDISK_JOURNAL_1st_BLOCK(sb);
2105         reiserfs_debug(sb, REISERFS_DEBUG_CODE, "journal-1037: "
2106                        "journal_read_transaction, offset %llu, len %d mount_id %d",
2107                        d_bh->b_blocknr - SB_ONDISK_JOURNAL_1st_BLOCK(sb),
2108                        get_desc_trans_len(desc), get_desc_mount_id(desc));
2109         if (get_desc_trans_id(desc) < oldest_trans_id) {
2110                 reiserfs_debug(sb, REISERFS_DEBUG_CODE, "journal-1039: "
2111                                "journal_read_trans skipping because %lu is too old",
2112                                cur_dblock -
2113                                SB_ONDISK_JOURNAL_1st_BLOCK(sb));
2114                 brelse(d_bh);
2115                 return 1;
2116         }
2117         if (get_desc_mount_id(desc) != newest_mount_id) {
2118                 reiserfs_debug(sb, REISERFS_DEBUG_CODE, "journal-1146: "
2119                                "journal_read_trans skipping because %d is != "
2120                                "newest_mount_id %lu", get_desc_mount_id(desc),
2121                                newest_mount_id);
2122                 brelse(d_bh);
2123                 return 1;
2124         }
2125         c_bh = journal_bread(sb, SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2126                              ((trans_offset + get_desc_trans_len(desc) + 1) %
2127                               SB_ONDISK_JOURNAL_SIZE(sb)));
2128         if (!c_bh) {
2129                 brelse(d_bh);
2130                 return 1;
2131         }
2132         commit = (struct reiserfs_journal_commit *)c_bh->b_data;
2133         if (journal_compare_desc_commit(sb, desc, commit)) {
2134                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2135                                "journal_read_transaction, "
2136                                "commit offset %llu had bad time %d or length %d",
2137                                c_bh->b_blocknr -
2138                                SB_ONDISK_JOURNAL_1st_BLOCK(sb),
2139                                get_commit_trans_id(commit),
2140                                get_commit_trans_len(commit));
2141                 brelse(c_bh);
2142                 brelse(d_bh);
2143                 return 1;
2144         }
2145
2146         if (bdev_read_only(sb->s_bdev)) {
2147                 reiserfs_warning(sb, "clm-2076",
2148                                  "device is readonly, unable to replay log");
2149                 brelse(c_bh);
2150                 brelse(d_bh);
2151                 return -EROFS;
2152         }
2153
2154         trans_id = get_desc_trans_id(desc);
2155         /* now we know we've got a good transaction, and it was inside the valid time ranges */
2156         log_blocks = kmalloc(get_desc_trans_len(desc) *
2157                              sizeof(struct buffer_head *), GFP_NOFS);
2158         real_blocks = kmalloc(get_desc_trans_len(desc) *
2159                               sizeof(struct buffer_head *), GFP_NOFS);
2160         if (!log_blocks || !real_blocks) {
2161                 brelse(c_bh);
2162                 brelse(d_bh);
2163                 kfree(log_blocks);
2164                 kfree(real_blocks);
2165                 reiserfs_warning(sb, "journal-1169",
2166                                  "kmalloc failed, unable to mount FS");
2167                 return -1;
2168         }
2169         /* get all the buffer heads */
2170         trans_half = journal_trans_half(sb->s_blocksize);
2171         for (i = 0; i < get_desc_trans_len(desc); i++) {
2172                 log_blocks[i] =
2173                     journal_getblk(sb,
2174                                    SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2175                                    (trans_offset + 1 +
2176                                     i) % SB_ONDISK_JOURNAL_SIZE(sb));
2177                 if (i < trans_half) {
2178                         real_blocks[i] =
2179                             sb_getblk(sb,
2180                                       le32_to_cpu(desc->j_realblock[i]));
2181                 } else {
2182                         real_blocks[i] =
2183                             sb_getblk(sb,
2184                                       le32_to_cpu(commit->
2185                                                   j_realblock[i - trans_half]));
2186                 }
2187                 if (real_blocks[i]->b_blocknr > SB_BLOCK_COUNT(sb)) {
2188                         reiserfs_warning(sb, "journal-1207",
2189                                          "REPLAY FAILURE fsck required! "
2190                                          "Block to replay is outside of "
2191                                          "filesystem");
2192                         goto abort_replay;
2193                 }
2194                 /* make sure we don't try to replay onto log or reserved area */
2195                 if (is_block_in_log_or_reserved_area
2196                     (sb, real_blocks[i]->b_blocknr)) {
2197                         reiserfs_warning(sb, "journal-1204",
2198                                          "REPLAY FAILURE fsck required! "
2199                                          "Trying to replay onto a log block");
2200                       abort_replay:
2201                         brelse_array(log_blocks, i);
2202                         brelse_array(real_blocks, i);
2203                         brelse(c_bh);
2204                         brelse(d_bh);
2205                         kfree(log_blocks);
2206                         kfree(real_blocks);
2207                         return -1;
2208                 }
2209         }
2210         /* read in the log blocks, memcpy to the corresponding real block */
2211         ll_rw_block(READ, get_desc_trans_len(desc), log_blocks);
2212         for (i = 0; i < get_desc_trans_len(desc); i++) {
2213
2214                 reiserfs_write_unlock(sb);
2215                 wait_on_buffer(log_blocks[i]);
2216                 reiserfs_write_lock(sb);
2217
2218                 if (!buffer_uptodate(log_blocks[i])) {
2219                         reiserfs_warning(sb, "journal-1212",
2220                                          "REPLAY FAILURE fsck required! "
2221                                          "buffer write failed");
2222                         brelse_array(log_blocks + i,
2223                                      get_desc_trans_len(desc) - i);
2224                         brelse_array(real_blocks, get_desc_trans_len(desc));
2225                         brelse(c_bh);
2226                         brelse(d_bh);
2227                         kfree(log_blocks);
2228                         kfree(real_blocks);
2229                         return -1;
2230                 }
2231                 memcpy(real_blocks[i]->b_data, log_blocks[i]->b_data,
2232                        real_blocks[i]->b_size);
2233                 set_buffer_uptodate(real_blocks[i]);
2234                 brelse(log_blocks[i]);
2235         }
2236         /* flush out the real blocks */
2237         for (i = 0; i < get_desc_trans_len(desc); i++) {
2238                 set_buffer_dirty(real_blocks[i]);
2239                 write_dirty_buffer(real_blocks[i], WRITE);
2240         }
2241         for (i = 0; i < get_desc_trans_len(desc); i++) {
2242                 wait_on_buffer(real_blocks[i]);
2243                 if (!buffer_uptodate(real_blocks[i])) {
2244                         reiserfs_warning(sb, "journal-1226",
2245                                          "REPLAY FAILURE, fsck required! "
2246                                          "buffer write failed");
2247                         brelse_array(real_blocks + i,
2248                                      get_desc_trans_len(desc) - i);
2249                         brelse(c_bh);
2250                         brelse(d_bh);
2251                         kfree(log_blocks);
2252                         kfree(real_blocks);
2253                         return -1;
2254                 }
2255                 brelse(real_blocks[i]);
2256         }
2257         cur_dblock =
2258             SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2259             ((trans_offset + get_desc_trans_len(desc) +
2260               2) % SB_ONDISK_JOURNAL_SIZE(sb));
2261         reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2262                        "journal-1095: setting journal " "start to offset %ld",
2263                        cur_dblock - SB_ONDISK_JOURNAL_1st_BLOCK(sb));
2264
2265         /* init starting values for the first transaction, in case this is the last transaction to be replayed. */
2266         journal->j_start = cur_dblock - SB_ONDISK_JOURNAL_1st_BLOCK(sb);
2267         journal->j_last_flush_trans_id = trans_id;
2268         journal->j_trans_id = trans_id + 1;
2269         /* check for trans_id overflow */
2270         if (journal->j_trans_id == 0)
2271                 journal->j_trans_id = 10;
2272         brelse(c_bh);
2273         brelse(d_bh);
2274         kfree(log_blocks);
2275         kfree(real_blocks);
2276         return 0;
2277 }
2278
2279 /* This function reads blocks starting from block and to max_block of bufsize
2280    size (but no more than BUFNR blocks at a time). This proved to improve
2281    mounting speed on self-rebuilding raid5 arrays at least.
2282    Right now it is only used from journal code. But later we might use it
2283    from other places.
2284    Note: Do not use journal_getblk/sb_getblk functions here! */
2285 static struct buffer_head *reiserfs_breada(struct block_device *dev,
2286                                            b_blocknr_t block, int bufsize,
2287                                            b_blocknr_t max_block)
2288 {
2289         struct buffer_head *bhlist[BUFNR];
2290         unsigned int blocks = BUFNR;
2291         struct buffer_head *bh;
2292         int i, j;
2293
2294         bh = __getblk(dev, block, bufsize);
2295         if (buffer_uptodate(bh))
2296                 return (bh);
2297
2298         if (block + BUFNR > max_block) {
2299                 blocks = max_block - block;
2300         }
2301         bhlist[0] = bh;
2302         j = 1;
2303         for (i = 1; i < blocks; i++) {
2304                 bh = __getblk(dev, block + i, bufsize);
2305                 if (buffer_uptodate(bh)) {
2306                         brelse(bh);
2307                         break;
2308                 } else
2309                         bhlist[j++] = bh;
2310         }
2311         ll_rw_block(READ, j, bhlist);
2312         for (i = 1; i < j; i++)
2313                 brelse(bhlist[i]);
2314         bh = bhlist[0];
2315         wait_on_buffer(bh);
2316         if (buffer_uptodate(bh))
2317                 return bh;
2318         brelse(bh);
2319         return NULL;
2320 }
2321
2322 /*
2323 ** read and replay the log
2324 ** on a clean unmount, the journal header's next unflushed pointer will be to an invalid
2325 ** transaction.  This tests that before finding all the transactions in the log, which makes normal mount times fast.
2326 **
2327 ** After a crash, this starts with the next unflushed transaction, and replays until it finds one too old, or invalid.
2328 **
2329 ** On exit, it sets things up so the first transaction will work correctly.
2330 */
2331 static int journal_read(struct super_block *sb)
2332 {
2333         struct reiserfs_journal *journal = SB_JOURNAL(sb);
2334         struct reiserfs_journal_desc *desc;
2335         unsigned int oldest_trans_id = 0;
2336         unsigned int oldest_invalid_trans_id = 0;
2337         time_t start;
2338         unsigned long oldest_start = 0;
2339         unsigned long cur_dblock = 0;
2340         unsigned long newest_mount_id = 9;
2341         struct buffer_head *d_bh;
2342         struct reiserfs_journal_header *jh;
2343         int valid_journal_header = 0;
2344         int replay_count = 0;
2345         int continue_replay = 1;
2346         int ret;
2347         char b[BDEVNAME_SIZE];
2348
2349         cur_dblock = SB_ONDISK_JOURNAL_1st_BLOCK(sb);
2350         reiserfs_info(sb, "checking transaction log (%s)\n",
2351                       bdevname(journal->j_dev_bd, b));
2352         start = get_seconds();
2353
2354         /* step 1, read in the journal header block.  Check the transaction it says
2355          ** is the first unflushed, and if that transaction is not valid,
2356          ** replay is done
2357          */
2358         journal->j_header_bh = journal_bread(sb,
2359                                              SB_ONDISK_JOURNAL_1st_BLOCK(sb)
2360                                              + SB_ONDISK_JOURNAL_SIZE(sb));
2361         if (!journal->j_header_bh) {
2362                 return 1;
2363         }
2364         jh = (struct reiserfs_journal_header *)(journal->j_header_bh->b_data);
2365         if (le32_to_cpu(jh->j_first_unflushed_offset) <
2366             SB_ONDISK_JOURNAL_SIZE(sb)
2367             && le32_to_cpu(jh->j_last_flush_trans_id) > 0) {
2368                 oldest_start =
2369                     SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2370                     le32_to_cpu(jh->j_first_unflushed_offset);
2371                 oldest_trans_id = le32_to_cpu(jh->j_last_flush_trans_id) + 1;
2372                 newest_mount_id = le32_to_cpu(jh->j_mount_id);
2373                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2374                                "journal-1153: found in "
2375                                "header: first_unflushed_offset %d, last_flushed_trans_id "
2376                                "%lu", le32_to_cpu(jh->j_first_unflushed_offset),
2377                                le32_to_cpu(jh->j_last_flush_trans_id));
2378                 valid_journal_header = 1;
2379
2380                 /* now, we try to read the first unflushed offset.  If it is not valid,
2381                  ** there is nothing more we can do, and it makes no sense to read
2382                  ** through the whole log.
2383                  */
2384                 d_bh =
2385                     journal_bread(sb,
2386                                   SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2387                                   le32_to_cpu(jh->j_first_unflushed_offset));
2388                 ret = journal_transaction_is_valid(sb, d_bh, NULL, NULL);
2389                 if (!ret) {
2390                         continue_replay = 0;
2391                 }
2392                 brelse(d_bh);
2393                 goto start_log_replay;
2394         }
2395
2396         /* ok, there are transactions that need to be replayed.  start with the first log block, find
2397          ** all the valid transactions, and pick out the oldest.
2398          */
2399         while (continue_replay
2400                && cur_dblock <
2401                (SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2402                 SB_ONDISK_JOURNAL_SIZE(sb))) {
2403                 /* Note that it is required for blocksize of primary fs device and journal
2404                    device to be the same */
2405                 d_bh =
2406                     reiserfs_breada(journal->j_dev_bd, cur_dblock,
2407                                     sb->s_blocksize,
2408                                     SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2409                                     SB_ONDISK_JOURNAL_SIZE(sb));
2410                 ret =
2411                     journal_transaction_is_valid(sb, d_bh,
2412                                                  &oldest_invalid_trans_id,
2413                                                  &newest_mount_id);
2414                 if (ret == 1) {
2415                         desc = (struct reiserfs_journal_desc *)d_bh->b_data;
2416                         if (oldest_start == 0) {        /* init all oldest_ values */
2417                                 oldest_trans_id = get_desc_trans_id(desc);
2418                                 oldest_start = d_bh->b_blocknr;
2419                                 newest_mount_id = get_desc_mount_id(desc);
2420                                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2421                                                "journal-1179: Setting "
2422                                                "oldest_start to offset %llu, trans_id %lu",
2423                                                oldest_start -
2424                                                SB_ONDISK_JOURNAL_1st_BLOCK
2425                                                (sb), oldest_trans_id);
2426                         } else if (oldest_trans_id > get_desc_trans_id(desc)) {
2427                                 /* one we just read was older */
2428                                 oldest_trans_id = get_desc_trans_id(desc);
2429                                 oldest_start = d_bh->b_blocknr;
2430                                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2431                                                "journal-1180: Resetting "
2432                                                "oldest_start to offset %lu, trans_id %lu",
2433                                                oldest_start -
2434                                                SB_ONDISK_JOURNAL_1st_BLOCK
2435                                                (sb), oldest_trans_id);
2436                         }
2437                         if (newest_mount_id < get_desc_mount_id(desc)) {
2438                                 newest_mount_id = get_desc_mount_id(desc);
2439                                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2440                                                "journal-1299: Setting "
2441                                                "newest_mount_id to %d",
2442                                                get_desc_mount_id(desc));
2443                         }
2444                         cur_dblock += get_desc_trans_len(desc) + 2;
2445                 } else {
2446                         cur_dblock++;
2447                 }
2448                 brelse(d_bh);
2449         }
2450
2451       start_log_replay:
2452         cur_dblock = oldest_start;
2453         if (oldest_trans_id) {
2454                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2455                                "journal-1206: Starting replay "
2456                                "from offset %llu, trans_id %lu",
2457                                cur_dblock - SB_ONDISK_JOURNAL_1st_BLOCK(sb),
2458                                oldest_trans_id);
2459
2460         }
2461         replay_count = 0;
2462         while (continue_replay && oldest_trans_id > 0) {
2463                 ret =
2464                     journal_read_transaction(sb, cur_dblock, oldest_start,
2465                                              oldest_trans_id, newest_mount_id);
2466                 if (ret < 0) {
2467                         return ret;
2468                 } else if (ret != 0) {
2469                         break;
2470                 }
2471                 cur_dblock =
2472                     SB_ONDISK_JOURNAL_1st_BLOCK(sb) + journal->j_start;
2473                 replay_count++;
2474                 if (cur_dblock == oldest_start)
2475                         break;
2476         }
2477
2478         if (oldest_trans_id == 0) {
2479                 reiserfs_debug(sb, REISERFS_DEBUG_CODE,
2480                                "journal-1225: No valid " "transactions found");
2481         }
2482         /* j_start does not get set correctly if we don't replay any transactions.
2483          ** if we had a valid journal_header, set j_start to the first unflushed transaction value,
2484          ** copy the trans_id from the header
2485          */
2486         if (valid_journal_header && replay_count == 0) {
2487                 journal->j_start = le32_to_cpu(jh->j_first_unflushed_offset);
2488                 journal->j_trans_id =
2489                     le32_to_cpu(jh->j_last_flush_trans_id) + 1;
2490                 /* check for trans_id overflow */
2491                 if (journal->j_trans_id == 0)
2492                         journal->j_trans_id = 10;
2493                 journal->j_last_flush_trans_id =
2494                     le32_to_cpu(jh->j_last_flush_trans_id);
2495                 journal->j_mount_id = le32_to_cpu(jh->j_mount_id) + 1;
2496         } else {
2497                 journal->j_mount_id = newest_mount_id + 1;
2498         }
2499         reiserfs_debug(sb, REISERFS_DEBUG_CODE, "journal-1299: Setting "
2500                        "newest_mount_id to %lu", journal->j_mount_id);
2501         journal->j_first_unflushed_offset = journal->j_start;
2502         if (replay_count > 0) {
2503                 reiserfs_info(sb,
2504                               "replayed %d transactions in %lu seconds\n",
2505                               replay_count, get_seconds() - start);
2506         }
2507         if (!bdev_read_only(sb->s_bdev) &&
2508             _update_journal_header_block(sb, journal->j_start,
2509                                          journal->j_last_flush_trans_id)) {
2510                 /* replay failed, caller must call free_journal_ram and abort
2511                  ** the mount
2512                  */
2513                 return -1;
2514         }
2515         return 0;
2516 }
2517
2518 static struct reiserfs_journal_list *alloc_journal_list(struct super_block *s)
2519 {
2520         struct reiserfs_journal_list *jl;
2521         jl = kzalloc(sizeof(struct reiserfs_journal_list),
2522                      GFP_NOFS | __GFP_NOFAIL);
2523         INIT_LIST_HEAD(&jl->j_list);
2524         INIT_LIST_HEAD(&jl->j_working_list);
2525         INIT_LIST_HEAD(&jl->j_tail_bh_list);
2526         INIT_LIST_HEAD(&jl->j_bh_list);
2527         mutex_init(&jl->j_commit_mutex);
2528         SB_JOURNAL(s)->j_num_lists++;
2529         get_journal_list(jl);
2530         return jl;
2531 }
2532
2533 static void journal_list_init(struct super_block *sb)
2534 {
2535         SB_JOURNAL(sb)->j_current_jl = alloc_journal_list(sb);
2536 }
2537
2538 static int release_journal_dev(struct super_block *super,
2539                                struct reiserfs_journal *journal)
2540 {
2541         int result;
2542
2543         result = 0;
2544
2545         if (journal->j_dev_bd != NULL) {
2546                 result = blkdev_put(journal->j_dev_bd, journal->j_dev_mode);
2547                 journal->j_dev_bd = NULL;
2548         }
2549
2550         if (result != 0) {
2551                 reiserfs_warning(super, "sh-457",
2552                                  "Cannot release journal device: %i", result);
2553         }
2554         return result;
2555 }
2556
2557 static int journal_init_dev(struct super_block *super,
2558                             struct reiserfs_journal *journal,
2559                             const char *jdev_name)
2560 {
2561         int result;
2562         dev_t jdev;
2563         fmode_t blkdev_mode = FMODE_READ | FMODE_WRITE | FMODE_EXCL;
2564         char b[BDEVNAME_SIZE];
2565
2566         result = 0;
2567
2568         journal->j_dev_bd = NULL;
2569         jdev = SB_ONDISK_JOURNAL_DEVICE(super) ?
2570             new_decode_dev(SB_ONDISK_JOURNAL_DEVICE(super)) : super->s_dev;
2571
2572         if (bdev_read_only(super->s_bdev))
2573                 blkdev_mode = FMODE_READ;
2574
2575         /* there is no "jdev" option and journal is on separate device */
2576         if ((!jdev_name || !jdev_name[0])) {
2577                 if (jdev == super->s_dev)
2578                         blkdev_mode &= ~FMODE_EXCL;
2579                 journal->j_dev_bd = blkdev_get_by_dev(jdev, blkdev_mode,
2580                                                       journal);
2581                 journal->j_dev_mode = blkdev_mode;
2582                 if (IS_ERR(journal->j_dev_bd)) {
2583                         result = PTR_ERR(journal->j_dev_bd);
2584                         journal->j_dev_bd = NULL;
2585                         reiserfs_warning(super, "sh-458",
2586                                          "cannot init journal device '%s': %i",
2587                                          __bdevname(jdev, b), result);
2588                         return result;
2589                 } else if (jdev != super->s_dev)
2590                         set_blocksize(journal->j_dev_bd, super->s_blocksize);
2591
2592                 return 0;
2593         }
2594
2595         journal->j_dev_mode = blkdev_mode;
2596         journal->j_dev_bd = blkdev_get_by_path(jdev_name, blkdev_mode, journal);
2597         if (IS_ERR(journal->j_dev_bd)) {
2598                 result = PTR_ERR(journal->j_dev_bd);
2599                 journal->j_dev_bd = NULL;
2600                 reiserfs_warning(super,
2601                                  "journal_init_dev: Cannot open '%s': %i",
2602                                  jdev_name, result);
2603                 return result;
2604         }
2605
2606         set_blocksize(journal->j_dev_bd, super->s_blocksize);
2607         reiserfs_info(super,
2608                       "journal_init_dev: journal device: %s\n",
2609                       bdevname(journal->j_dev_bd, b));
2610         return 0;
2611 }
2612
2613 /**
2614  * When creating/tuning a file system user can assign some
2615  * journal params within boundaries which depend on the ratio
2616  * blocksize/standard_blocksize.
2617  *
2618  * For blocks >= standard_blocksize transaction size should
2619  * be not less then JOURNAL_TRANS_MIN_DEFAULT, and not more
2620  * then JOURNAL_TRANS_MAX_DEFAULT.
2621  *
2622  * For blocks < standard_blocksize these boundaries should be
2623  * decreased proportionally.
2624  */
2625 #define REISERFS_STANDARD_BLKSIZE (4096)
2626
2627 static int check_advise_trans_params(struct super_block *sb,
2628                                      struct reiserfs_journal *journal)
2629 {
2630         if (journal->j_trans_max) {
2631                 /* Non-default journal params.
2632                    Do sanity check for them. */
2633                 int ratio = 1;
2634                 if (sb->s_blocksize < REISERFS_STANDARD_BLKSIZE)
2635                         ratio = REISERFS_STANDARD_BLKSIZE / sb->s_blocksize;
2636
2637                 if (journal->j_trans_max > JOURNAL_TRANS_MAX_DEFAULT / ratio ||
2638                     journal->j_trans_max < JOURNAL_TRANS_MIN_DEFAULT / ratio ||
2639                     SB_ONDISK_JOURNAL_SIZE(sb) / journal->j_trans_max <
2640                     JOURNAL_MIN_RATIO) {
2641                         reiserfs_warning(sb, "sh-462",
2642                                          "bad transaction max size (%u). "
2643                                          "FSCK?", journal->j_trans_max);
2644                         return 1;
2645                 }
2646                 if (journal->j_max_batch != (journal->j_trans_max) *
2647                         JOURNAL_MAX_BATCH_DEFAULT/JOURNAL_TRANS_MAX_DEFAULT) {
2648                         reiserfs_warning(sb, "sh-463",
2649                                          "bad transaction max batch (%u). "
2650                                          "FSCK?", journal->j_max_batch);
2651                         return 1;
2652                 }
2653         } else {
2654                 /* Default journal params.
2655                    The file system was created by old version
2656                    of mkreiserfs, so some fields contain zeros,
2657                    and we need to advise proper values for them */
2658                 if (sb->s_blocksize != REISERFS_STANDARD_BLKSIZE) {
2659                         reiserfs_warning(sb, "sh-464", "bad blocksize (%u)",
2660                                          sb->s_blocksize);
2661                         return 1;
2662                 }
2663                 journal->j_trans_max = JOURNAL_TRANS_MAX_DEFAULT;
2664                 journal->j_max_batch = JOURNAL_MAX_BATCH_DEFAULT;
2665                 journal->j_max_commit_age = JOURNAL_MAX_COMMIT_AGE;
2666         }
2667         return 0;
2668 }
2669
2670 /*
2671 ** must be called once on fs mount.  calls journal_read for you
2672 */
2673 int journal_init(struct super_block *sb, const char *j_dev_name,
2674                  int old_format, unsigned int commit_max_age)
2675 {
2676         int num_cnodes = SB_ONDISK_JOURNAL_SIZE(sb) * 2;
2677         struct buffer_head *bhjh;
2678         struct reiserfs_super_block *rs;
2679         struct reiserfs_journal_header *jh;
2680         struct reiserfs_journal *journal;
2681         struct reiserfs_journal_list *jl;
2682         char b[BDEVNAME_SIZE];
2683         int ret;
2684
2685         /*
2686          * Unlock here to avoid various RECLAIM-FS-ON <-> IN-RECLAIM-FS
2687          * dependency inversion warnings.
2688          */
2689         reiserfs_write_unlock(sb);
2690         journal = SB_JOURNAL(sb) = vzalloc(sizeof(struct reiserfs_journal));
2691         if (!journal) {
2692                 reiserfs_warning(sb, "journal-1256",
2693                                  "unable to get memory for journal structure");
2694                 reiserfs_write_lock(sb);
2695                 return 1;
2696         }
2697         INIT_LIST_HEAD(&journal->j_bitmap_nodes);
2698         INIT_LIST_HEAD(&journal->j_prealloc_list);
2699         INIT_LIST_HEAD(&journal->j_working_list);
2700         INIT_LIST_HEAD(&journal->j_journal_list);
2701         journal->j_persistent_trans = 0;
2702         ret = reiserfs_allocate_list_bitmaps(sb, journal->j_list_bitmap,
2703                                            reiserfs_bmap_count(sb));
2704         reiserfs_write_lock(sb);
2705         if (ret)
2706                 goto free_and_return;
2707
2708         allocate_bitmap_nodes(sb);
2709
2710         /* reserved for journal area support */
2711         SB_JOURNAL_1st_RESERVED_BLOCK(sb) = (old_format ?
2712                                                  REISERFS_OLD_DISK_OFFSET_IN_BYTES
2713                                                  / sb->s_blocksize +
2714                                                  reiserfs_bmap_count(sb) +
2715                                                  1 :
2716                                                  REISERFS_DISK_OFFSET_IN_BYTES /
2717                                                  sb->s_blocksize + 2);
2718
2719         /* Sanity check to see is the standard journal fitting within first bitmap
2720            (actual for small blocksizes) */
2721         if (!SB_ONDISK_JOURNAL_DEVICE(sb) &&
2722             (SB_JOURNAL_1st_RESERVED_BLOCK(sb) +
2723              SB_ONDISK_JOURNAL_SIZE(sb) > sb->s_blocksize * 8)) {
2724                 reiserfs_warning(sb, "journal-1393",
2725                                  "journal does not fit for area addressed "
2726                                  "by first of bitmap blocks. It starts at "
2727                                  "%u and its size is %u. Block size %ld",
2728                                  SB_JOURNAL_1st_RESERVED_BLOCK(sb),
2729                                  SB_ONDISK_JOURNAL_SIZE(sb),
2730                                  sb->s_blocksize);
2731                 goto free_and_return;
2732         }
2733
2734         /*
2735          * We need to unlock here to avoid creating the following
2736          * dependency:
2737          * reiserfs_lock -> sysfs_mutex
2738          * Because the reiserfs mmap path creates the following dependency:
2739          * mm->mmap -> reiserfs_lock, hence we have
2740          * mm->mmap -> reiserfs_lock ->sysfs_mutex
2741          * This would ends up in a circular dependency with sysfs readdir path
2742          * which does sysfs_mutex -> mm->mmap_sem
2743          * This is fine because the reiserfs lock is useless in mount path,
2744          * at least until we call journal_begin. We keep it for paranoid
2745          * reasons.
2746          */
2747         reiserfs_write_unlock(sb);
2748         if (journal_init_dev(sb, journal, j_dev_name) != 0) {
2749                 reiserfs_write_lock(sb);
2750                 reiserfs_warning(sb, "sh-462",
2751                                  "unable to initialize jornal device");
2752                 goto free_and_return;
2753         }
2754         reiserfs_write_lock(sb);
2755
2756         rs = SB_DISK_SUPER_BLOCK(sb);
2757
2758         /* read journal header */
2759         bhjh = journal_bread(sb,
2760                              SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
2761                              SB_ONDISK_JOURNAL_SIZE(sb));
2762         if (!bhjh) {
2763                 reiserfs_warning(sb, "sh-459",
2764                                  "unable to read journal header");
2765                 goto free_and_return;
2766         }
2767         jh = (struct reiserfs_journal_header *)(bhjh->b_data);
2768
2769         /* make sure that journal matches to the super block */
2770         if (is_reiserfs_jr(rs)
2771             && (le32_to_cpu(jh->jh_journal.jp_journal_magic) !=
2772                 sb_jp_journal_magic(rs))) {
2773                 reiserfs_warning(sb, "sh-460",
2774                                  "journal header magic %x (device %s) does "
2775                                  "not match to magic found in super block %x",
2776                                  jh->jh_journal.jp_journal_magic,
2777                                  bdevname(journal->j_dev_bd, b),
2778                                  sb_jp_journal_magic(rs));
2779                 brelse(bhjh);
2780                 goto free_and_return;
2781         }
2782
2783         journal->j_trans_max = le32_to_cpu(jh->jh_journal.jp_journal_trans_max);
2784         journal->j_max_batch = le32_to_cpu(jh->jh_journal.jp_journal_max_batch);
2785         journal->j_max_commit_age =
2786             le32_to_cpu(jh->jh_journal.jp_journal_max_commit_age);
2787         journal->j_max_trans_age = JOURNAL_MAX_TRANS_AGE;
2788
2789         if (check_advise_trans_params(sb, journal) != 0)
2790                 goto free_and_return;
2791         journal->j_default_max_commit_age = journal->j_max_commit_age;
2792
2793         if (commit_max_age != 0) {
2794                 journal->j_max_commit_age = commit_max_age;
2795                 journal->j_max_trans_age = commit_max_age;
2796         }
2797
2798         reiserfs_info(sb, "journal params: device %s, size %u, "
2799                       "journal first block %u, max trans len %u, max batch %u, "
2800                       "max commit age %u, max trans age %u\n",
2801                       bdevname(journal->j_dev_bd, b),
2802                       SB_ONDISK_JOURNAL_SIZE(sb),
2803                       SB_ONDISK_JOURNAL_1st_BLOCK(sb),
2804                       journal->j_trans_max,
2805                       journal->j_max_batch,
2806                       journal->j_max_commit_age, journal->j_max_trans_age);
2807
2808         brelse(bhjh);
2809
2810         journal->j_list_bitmap_index = 0;
2811         journal_list_init(sb);
2812
2813         memset(journal->j_list_hash_table, 0,
2814                JOURNAL_HASH_SIZE * sizeof(struct reiserfs_journal_cnode *));
2815
2816         INIT_LIST_HEAD(&journal->j_dirty_buffers);
2817         spin_lock_init(&journal->j_dirty_buffers_lock);
2818
2819         journal->j_start = 0;
2820         journal->j_len = 0;
2821         journal->j_len_alloc = 0;
2822         atomic_set(&(journal->j_wcount), 0);
2823         atomic_set(&(journal->j_async_throttle), 0);
2824         journal->j_bcount = 0;
2825         journal->j_trans_start_time = 0;
2826         journal->j_last = NULL;
2827         journal->j_first = NULL;
2828         init_waitqueue_head(&(journal->j_join_wait));
2829         mutex_init(&journal->j_mutex);
2830         mutex_init(&journal->j_flush_mutex);
2831
2832         journal->j_trans_id = 10;
2833         journal->j_mount_id = 10;
2834         journal->j_state = 0;
2835         atomic_set(&(journal->j_jlock), 0);
2836         reiserfs_write_unlock(sb);
2837         journal->j_cnode_free_list = allocate_cnodes(num_cnodes);
2838         reiserfs_write_lock(sb);
2839         journal->j_cnode_free_orig = journal->j_cnode_free_list;
2840         journal->j_cnode_free = journal->j_cnode_free_list ? num_cnodes : 0;
2841         journal->j_cnode_used = 0;
2842         journal->j_must_wait = 0;
2843
2844         if (journal->j_cnode_free == 0) {
2845                 reiserfs_warning(sb, "journal-2004", "Journal cnode memory "
2846                                  "allocation failed (%ld bytes). Journal is "
2847                                  "too large for available memory. Usually "
2848                                  "this is due to a journal that is too large.",
2849                                  sizeof (struct reiserfs_journal_cnode) * num_cnodes);
2850                 goto free_and_return;
2851         }
2852
2853         init_journal_hash(sb);
2854         jl = journal->j_current_jl;
2855         jl->j_list_bitmap = get_list_bitmap(sb, jl);
2856         if (!jl->j_list_bitmap) {
2857                 reiserfs_warning(sb, "journal-2005",
2858                                  "get_list_bitmap failed for journal list 0");
2859                 goto free_and_return;
2860         }
2861         if (journal_read(sb) < 0) {
2862                 reiserfs_warning(sb, "reiserfs-2006",
2863                                  "Replay Failure, unable to mount");
2864                 goto free_and_return;
2865         }
2866
2867         reiserfs_mounted_fs_count++;
2868         if (reiserfs_mounted_fs_count <= 1) {
2869                 reiserfs_write_unlock(sb);
2870                 commit_wq = alloc_workqueue("reiserfs", WQ_MEM_RECLAIM, 0);
2871                 reiserfs_write_lock(sb);
2872         }
2873
2874         INIT_DELAYED_WORK(&journal->j_work, flush_async_commits);
2875         journal->j_work_sb = sb;
2876         return 0;
2877       free_and_return:
2878         free_journal_ram(sb);
2879         return 1;
2880 }
2881
2882 /*
2883 ** test for a polite end of the current transaction.  Used by file_write, and should
2884 ** be used by delete to make sure they don't write more than can fit inside a single
2885 ** transaction
2886 */
2887 int journal_transaction_should_end(struct reiserfs_transaction_handle *th,
2888                                    int new_alloc)
2889 {
2890         struct reiserfs_journal *journal = SB_JOURNAL(th->t_super);
2891         time_t now = get_seconds();
2892         /* cannot restart while nested */
2893         BUG_ON(!th->t_trans_id);
2894         if (th->t_refcount > 1)
2895                 return 0;
2896         if (journal->j_must_wait > 0 ||
2897             (journal->j_len_alloc + new_alloc) >= journal->j_max_batch ||
2898             atomic_read(&(journal->j_jlock)) ||
2899             (now - journal->j_trans_start_time) > journal->j_max_trans_age ||
2900             journal->j_cnode_free < (journal->j_trans_max * 3)) {
2901                 return 1;
2902         }
2903         /* protected by the BKL here */
2904         journal->j_len_alloc += new_alloc;
2905         th->t_blocks_allocated += new_alloc ;
2906         return 0;
2907 }
2908
2909 /* this must be called inside a transaction, and requires the
2910 ** kernel_lock to be held
2911 */
2912 void reiserfs_block_writes(struct reiserfs_transaction_handle *th)
2913 {
2914         struct reiserfs_journal *journal = SB_JOURNAL(th->t_super);
2915         BUG_ON(!th->t_trans_id);
2916         journal->j_must_wait = 1;
2917         set_bit(J_WRITERS_BLOCKED, &journal->j_state);
2918         return;
2919 }
2920
2921 /* this must be called without a transaction started, and does not
2922 ** require BKL
2923 */
2924 void reiserfs_allow_writes(struct super_block *s)
2925 {
2926         struct reiserfs_journal *journal = SB_JOURNAL(s);
2927         clear_bit(J_WRITERS_BLOCKED, &journal->j_state);
2928         wake_up(&journal->j_join_wait);
2929 }
2930
2931 /* this must be called without a transaction started, and does not
2932 ** require BKL
2933 */
2934 void reiserfs_wait_on_write_block(struct super_block *s)
2935 {
2936         struct reiserfs_journal *journal = SB_JOURNAL(s);
2937         wait_event(journal->j_join_wait,
2938                    !test_bit(J_WRITERS_BLOCKED, &journal->j_state));
2939 }
2940
2941 static void queue_log_writer(struct super_block *s)
2942 {
2943         wait_queue_t wait;
2944         struct reiserfs_journal *journal = SB_JOURNAL(s);
2945         set_bit(J_WRITERS_QUEUED, &journal->j_state);
2946
2947         /*
2948          * we don't want to use wait_event here because
2949          * we only want to wait once.
2950          */
2951         init_waitqueue_entry(&wait, current);
2952         add_wait_queue(&journal->j_join_wait, &wait);
2953         set_current_state(TASK_UNINTERRUPTIBLE);
2954         if (test_bit(J_WRITERS_QUEUED, &journal->j_state)) {
2955                 reiserfs_write_unlock(s);
2956                 schedule();
2957                 reiserfs_write_lock(s);
2958         }
2959         __set_current_state(TASK_RUNNING);
2960         remove_wait_queue(&journal->j_join_wait, &wait);
2961 }
2962
2963 static void wake_queued_writers(struct super_block *s)
2964 {
2965         struct reiserfs_journal *journal = SB_JOURNAL(s);
2966         if (test_and_clear_bit(J_WRITERS_QUEUED, &journal->j_state))
2967                 wake_up(&journal->j_join_wait);
2968 }
2969
2970 static void let_transaction_grow(struct super_block *sb, unsigned int trans_id)
2971 {
2972         struct reiserfs_journal *journal = SB_JOURNAL(sb);
2973         unsigned long bcount = journal->j_bcount;
2974         while (1) {
2975                 reiserfs_write_unlock(sb);
2976                 schedule_timeout_uninterruptible(1);
2977                 reiserfs_write_lock(sb);
2978                 journal->j_current_jl->j_state |= LIST_COMMIT_PENDING;
2979                 while ((atomic_read(&journal->j_wcount) > 0 ||
2980                         atomic_read(&journal->j_jlock)) &&
2981                        journal->j_trans_id == trans_id) {
2982                         queue_log_writer(sb);
2983                 }
2984                 if (journal->j_trans_id != trans_id)
2985                         break;
2986                 if (bcount == journal->j_bcount)
2987                         break;
2988                 bcount = journal->j_bcount;
2989         }
2990 }
2991
2992 /* join == true if you must join an existing transaction.
2993 ** join == false if you can deal with waiting for others to finish
2994 **
2995 ** this will block until the transaction is joinable.  send the number of blocks you
2996 ** expect to use in nblocks.
2997 */
2998 static int do_journal_begin_r(struct reiserfs_transaction_handle *th,
2999                               struct super_block *sb, unsigned long nblocks,
3000                               int join)
3001 {
3002         time_t now = get_seconds();
3003         unsigned int old_trans_id;
3004         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3005         struct reiserfs_transaction_handle myth;
3006         int sched_count = 0;
3007         int retval;
3008
3009         reiserfs_check_lock_depth(sb, "journal_begin");
3010         BUG_ON(nblocks > journal->j_trans_max);
3011
3012         PROC_INFO_INC(sb, journal.journal_being);
3013         /* set here for journal_join */
3014         th->t_refcount = 1;
3015         th->t_super = sb;
3016
3017       relock:
3018         lock_journal(sb);
3019         if (join != JBEGIN_ABORT && reiserfs_is_journal_aborted(journal)) {
3020                 unlock_journal(sb);
3021                 retval = journal->j_errno;
3022                 goto out_fail;
3023         }
3024         journal->j_bcount++;
3025
3026         if (test_bit(J_WRITERS_BLOCKED, &journal->j_state)) {
3027                 unlock_journal(sb);
3028                 reiserfs_write_unlock(sb);
3029                 reiserfs_wait_on_write_block(sb);
3030                 reiserfs_write_lock(sb);
3031                 PROC_INFO_INC(sb, journal.journal_relock_writers);
3032                 goto relock;
3033         }
3034         now = get_seconds();
3035
3036         /* if there is no room in the journal OR
3037          ** if this transaction is too old, and we weren't called joinable, wait for it to finish before beginning
3038          ** we don't sleep if there aren't other writers
3039          */
3040
3041         if ((!join && journal->j_must_wait > 0) ||
3042             (!join
3043              && (journal->j_len_alloc + nblocks + 2) >= journal->j_max_batch)
3044             || (!join && atomic_read(&journal->j_wcount) > 0
3045                 && journal->j_trans_start_time > 0
3046                 && (now - journal->j_trans_start_time) >
3047                 journal->j_max_trans_age) || (!join
3048                                               && atomic_read(&journal->j_jlock))
3049             || (!join && journal->j_cnode_free < (journal->j_trans_max * 3))) {
3050
3051                 old_trans_id = journal->j_trans_id;
3052                 unlock_journal(sb);     /* allow others to finish this transaction */
3053
3054                 if (!join && (journal->j_len_alloc + nblocks + 2) >=
3055                     journal->j_max_batch &&
3056                     ((journal->j_len + nblocks + 2) * 100) <
3057                     (journal->j_len_alloc * 75)) {
3058                         if (atomic_read(&journal->j_wcount) > 10) {
3059                                 sched_count++;
3060                                 queue_log_writer(sb);
3061                                 goto relock;
3062                         }
3063                 }
3064                 /* don't mess with joining the transaction if all we have to do is
3065                  * wait for someone else to do a commit
3066                  */
3067                 if (atomic_read(&journal->j_jlock)) {
3068                         while (journal->j_trans_id == old_trans_id &&
3069                                atomic_read(&journal->j_jlock)) {
3070                                 queue_log_writer(sb);
3071                         }
3072                         goto relock;
3073                 }
3074                 retval = journal_join(&myth, sb, 1);
3075                 if (retval)
3076                         goto out_fail;
3077
3078                 /* someone might have ended the transaction while we joined */
3079                 if (old_trans_id != journal->j_trans_id) {
3080                         retval = do_journal_end(&myth, sb, 1, 0);
3081                 } else {
3082                         retval = do_journal_end(&myth, sb, 1, COMMIT_NOW);
3083                 }
3084
3085                 if (retval)
3086                         goto out_fail;
3087
3088                 PROC_INFO_INC(sb, journal.journal_relock_wcount);
3089                 goto relock;
3090         }
3091         /* we are the first writer, set trans_id */
3092         if (journal->j_trans_start_time == 0) {
3093                 journal->j_trans_start_time = get_seconds();
3094         }
3095         atomic_inc(&(journal->j_wcount));
3096         journal->j_len_alloc += nblocks;
3097         th->t_blocks_logged = 0;
3098         th->t_blocks_allocated = nblocks;
3099         th->t_trans_id = journal->j_trans_id;
3100         unlock_journal(sb);
3101         INIT_LIST_HEAD(&th->t_list);
3102         return 0;
3103
3104       out_fail:
3105         memset(th, 0, sizeof(*th));
3106         /* Re-set th->t_super, so we can properly keep track of how many
3107          * persistent transactions there are. We need to do this so if this
3108          * call is part of a failed restart_transaction, we can free it later */
3109         th->t_super = sb;
3110         return retval;
3111 }
3112
3113 struct reiserfs_transaction_handle *reiserfs_persistent_transaction(struct
3114                                                                     super_block
3115                                                                     *s,
3116                                                                     int nblocks)
3117 {
3118         int ret;
3119         struct reiserfs_transaction_handle *th;
3120
3121         /* if we're nesting into an existing transaction.  It will be
3122          ** persistent on its own
3123          */
3124         if (reiserfs_transaction_running(s)) {
3125                 th = current->journal_info;
3126                 th->t_refcount++;
3127                 BUG_ON(th->t_refcount < 2);
3128                 
3129                 return th;
3130         }
3131         th = kmalloc(sizeof(struct reiserfs_transaction_handle), GFP_NOFS);
3132         if (!th)
3133                 return NULL;
3134         ret = journal_begin(th, s, nblocks);
3135         if (ret) {
3136                 kfree(th);
3137                 return NULL;
3138         }
3139
3140         SB_JOURNAL(s)->j_persistent_trans++;
3141         return th;
3142 }
3143
3144 int reiserfs_end_persistent_transaction(struct reiserfs_transaction_handle *th)
3145 {
3146         struct super_block *s = th->t_super;
3147         int ret = 0;
3148         if (th->t_trans_id)
3149                 ret = journal_end(th, th->t_super, th->t_blocks_allocated);
3150         else
3151                 ret = -EIO;
3152         if (th->t_refcount == 0) {
3153                 SB_JOURNAL(s)->j_persistent_trans--;
3154                 kfree(th);
3155         }
3156         return ret;
3157 }
3158
3159 static int journal_join(struct reiserfs_transaction_handle *th,
3160                         struct super_block *sb, unsigned long nblocks)
3161 {
3162         struct reiserfs_transaction_handle *cur_th = current->journal_info;
3163
3164         /* this keeps do_journal_end from NULLing out the current->journal_info
3165          ** pointer
3166          */
3167         th->t_handle_save = cur_th;
3168         BUG_ON(cur_th && cur_th->t_refcount > 1);
3169         return do_journal_begin_r(th, sb, nblocks, JBEGIN_JOIN);
3170 }
3171
3172 int journal_join_abort(struct reiserfs_transaction_handle *th,
3173                        struct super_block *sb, unsigned long nblocks)
3174 {
3175         struct reiserfs_transaction_handle *cur_th = current->journal_info;
3176
3177         /* this keeps do_journal_end from NULLing out the current->journal_info
3178          ** pointer
3179          */
3180         th->t_handle_save = cur_th;
3181         BUG_ON(cur_th && cur_th->t_refcount > 1);
3182         return do_journal_begin_r(th, sb, nblocks, JBEGIN_ABORT);
3183 }
3184
3185 int journal_begin(struct reiserfs_transaction_handle *th,
3186                   struct super_block *sb, unsigned long nblocks)
3187 {
3188         struct reiserfs_transaction_handle *cur_th = current->journal_info;
3189         int ret;
3190
3191         th->t_handle_save = NULL;
3192         if (cur_th) {
3193                 /* we are nesting into the current transaction */
3194                 if (cur_th->t_super == sb) {
3195                         BUG_ON(!cur_th->t_refcount);
3196                         cur_th->t_refcount++;
3197                         memcpy(th, cur_th, sizeof(*th));
3198                         if (th->t_refcount <= 1)
3199                                 reiserfs_warning(sb, "reiserfs-2005",
3200                                                  "BAD: refcount <= 1, but "
3201                                                  "journal_info != 0");
3202                         return 0;
3203                 } else {
3204                         /* we've ended up with a handle from a different filesystem.
3205                          ** save it and restore on journal_end.  This should never
3206                          ** really happen...
3207                          */
3208                         reiserfs_warning(sb, "clm-2100",
3209                                          "nesting info a different FS");
3210                         th->t_handle_save = current->journal_info;
3211                         current->journal_info = th;
3212                 }
3213         } else {
3214                 current->journal_info = th;
3215         }
3216         ret = do_journal_begin_r(th, sb, nblocks, JBEGIN_REG);
3217         BUG_ON(current->journal_info != th);
3218
3219         /* I guess this boils down to being the reciprocal of clm-2100 above.
3220          * If do_journal_begin_r fails, we need to put it back, since journal_end
3221          * won't be called to do it. */
3222         if (ret)
3223                 current->journal_info = th->t_handle_save;
3224         else
3225                 BUG_ON(!th->t_refcount);
3226
3227         return ret;
3228 }
3229
3230 /*
3231 ** puts bh into the current transaction.  If it was already there, reorders removes the
3232 ** old pointers from the hash, and puts new ones in (to make sure replay happen in the right order).
3233 **
3234 ** if it was dirty, cleans and files onto the clean list.  I can't let it be dirty again until the
3235 ** transaction is committed.
3236 **
3237 ** if j_len, is bigger than j_len_alloc, it pushes j_len_alloc to 10 + j_len.
3238 */
3239 int journal_mark_dirty(struct reiserfs_transaction_handle *th,
3240                        struct super_block *sb, struct buffer_head *bh)
3241 {
3242         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3243         struct reiserfs_journal_cnode *cn = NULL;
3244         int count_already_incd = 0;
3245         int prepared = 0;
3246         BUG_ON(!th->t_trans_id);
3247
3248         PROC_INFO_INC(sb, journal.mark_dirty);
3249         if (th->t_trans_id != journal->j_trans_id) {
3250                 reiserfs_panic(th->t_super, "journal-1577",
3251                                "handle trans id %ld != current trans id %ld",
3252                                th->t_trans_id, journal->j_trans_id);
3253         }
3254
3255         sb->s_dirt = 1;
3256
3257         prepared = test_clear_buffer_journal_prepared(bh);
3258         clear_buffer_journal_restore_dirty(bh);
3259         /* already in this transaction, we are done */
3260         if (buffer_journaled(bh)) {
3261                 PROC_INFO_INC(sb, journal.mark_dirty_already);
3262                 return 0;
3263         }
3264
3265         /* this must be turned into a panic instead of a warning.  We can't allow
3266          ** a dirty or journal_dirty or locked buffer to be logged, as some changes
3267          ** could get to disk too early.  NOT GOOD.
3268          */
3269         if (!prepared || buffer_dirty(bh)) {
3270                 reiserfs_warning(sb, "journal-1777",
3271                                  "buffer %llu bad state "
3272                                  "%cPREPARED %cLOCKED %cDIRTY %cJDIRTY_WAIT",
3273                                  (unsigned long long)bh->b_blocknr,
3274                                  prepared ? ' ' : '!',
3275                                  buffer_locked(bh) ? ' ' : '!',
3276                                  buffer_dirty(bh) ? ' ' : '!',
3277                                  buffer_journal_dirty(bh) ? ' ' : '!');
3278         }
3279
3280         if (atomic_read(&(journal->j_wcount)) <= 0) {
3281                 reiserfs_warning(sb, "journal-1409",
3282                                  "returning because j_wcount was %d",
3283                                  atomic_read(&(journal->j_wcount)));
3284                 return 1;
3285         }
3286         /* this error means I've screwed up, and we've overflowed the transaction.
3287          ** Nothing can be done here, except make the FS readonly or panic.
3288          */
3289         if (journal->j_len >= journal->j_trans_max) {
3290                 reiserfs_panic(th->t_super, "journal-1413",
3291                                "j_len (%lu) is too big",
3292                                journal->j_len);
3293         }
3294
3295         if (buffer_journal_dirty(bh)) {
3296                 count_already_incd = 1;
3297                 PROC_INFO_INC(sb, journal.mark_dirty_notjournal);
3298                 clear_buffer_journal_dirty(bh);
3299         }
3300
3301         if (journal->j_len > journal->j_len_alloc) {
3302                 journal->j_len_alloc = journal->j_len + JOURNAL_PER_BALANCE_CNT;
3303         }
3304
3305         set_buffer_journaled(bh);
3306
3307         /* now put this guy on the end */
3308         if (!cn) {
3309                 cn = get_cnode(sb);
3310                 if (!cn) {
3311                         reiserfs_panic(sb, "journal-4", "get_cnode failed!");
3312                 }
3313
3314                 if (th->t_blocks_logged == th->t_blocks_allocated) {
3315                         th->t_blocks_allocated += JOURNAL_PER_BALANCE_CNT;
3316                         journal->j_len_alloc += JOURNAL_PER_BALANCE_CNT;
3317                 }
3318                 th->t_blocks_logged++;
3319                 journal->j_len++;
3320
3321                 cn->bh = bh;
3322                 cn->blocknr = bh->b_blocknr;
3323                 cn->sb = sb;
3324                 cn->jlist = NULL;
3325                 insert_journal_hash(journal->j_hash_table, cn);
3326                 if (!count_already_incd) {
3327                         get_bh(bh);
3328                 }
3329         }
3330         cn->next = NULL;
3331         cn->prev = journal->j_last;
3332         cn->bh = bh;
3333         if (journal->j_last) {
3334                 journal->j_last->next = cn;
3335                 journal->j_last = cn;
3336         } else {
3337                 journal->j_first = cn;
3338                 journal->j_last = cn;
3339         }
3340         return 0;
3341 }
3342
3343 int journal_end(struct reiserfs_transaction_handle *th,
3344                 struct super_block *sb, unsigned long nblocks)
3345 {
3346         if (!current->journal_info && th->t_refcount > 1)
3347                 reiserfs_warning(sb, "REISER-NESTING",
3348                                  "th NULL, refcount %d", th->t_refcount);
3349
3350         if (!th->t_trans_id) {
3351                 WARN_ON(1);
3352                 return -EIO;
3353         }
3354
3355         th->t_refcount--;
3356         if (th->t_refcount > 0) {
3357                 struct reiserfs_transaction_handle *cur_th =
3358                     current->journal_info;
3359
3360                 /* we aren't allowed to close a nested transaction on a different
3361                  ** filesystem from the one in the task struct
3362                  */
3363                 BUG_ON(cur_th->t_super != th->t_super);
3364
3365                 if (th != cur_th) {
3366                         memcpy(current->journal_info, th, sizeof(*th));
3367                         th->t_trans_id = 0;
3368                 }
3369                 return 0;
3370         } else {
3371                 return do_journal_end(th, sb, nblocks, 0);
3372         }
3373 }
3374
3375 /* removes from the current transaction, relsing and descrementing any counters.
3376 ** also files the removed buffer directly onto the clean list
3377 **
3378 ** called by journal_mark_freed when a block has been deleted
3379 **
3380 ** returns 1 if it cleaned and relsed the buffer. 0 otherwise
3381 */
3382 static int remove_from_transaction(struct super_block *sb,
3383                                    b_blocknr_t blocknr, int already_cleaned)
3384 {
3385         struct buffer_head *bh;
3386         struct reiserfs_journal_cnode *cn;
3387         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3388         int ret = 0;
3389
3390         cn = get_journal_hash_dev(sb, journal->j_hash_table, blocknr);
3391         if (!cn || !cn->bh) {
3392                 return ret;
3393         }
3394         bh = cn->bh;
3395         if (cn->prev) {
3396                 cn->prev->next = cn->next;
3397         }
3398         if (cn->next) {
3399                 cn->next->prev = cn->prev;
3400         }
3401         if (cn == journal->j_first) {
3402                 journal->j_first = cn->next;
3403         }
3404         if (cn == journal->j_last) {
3405                 journal->j_last = cn->prev;
3406         }
3407         if (bh)
3408                 remove_journal_hash(sb, journal->j_hash_table, NULL,
3409                                     bh->b_blocknr, 0);
3410         clear_buffer_journaled(bh);     /* don't log this one */
3411
3412         if (!already_cleaned) {
3413                 clear_buffer_journal_dirty(bh);
3414                 clear_buffer_dirty(bh);
3415                 clear_buffer_journal_test(bh);
3416                 put_bh(bh);
3417                 if (atomic_read(&(bh->b_count)) < 0) {
3418                         reiserfs_warning(sb, "journal-1752",
3419                                          "b_count < 0");
3420                 }
3421                 ret = 1;
3422         }
3423         journal->j_len--;
3424         journal->j_len_alloc--;
3425         free_cnode(sb, cn);
3426         return ret;
3427 }
3428
3429 /*
3430 ** for any cnode in a journal list, it can only be dirtied of all the
3431 ** transactions that include it are committed to disk.
3432 ** this checks through each transaction, and returns 1 if you are allowed to dirty,
3433 ** and 0 if you aren't
3434 **
3435 ** it is called by dirty_journal_list, which is called after flush_commit_list has gotten all the log
3436 ** blocks for a given transaction on disk
3437 **
3438 */
3439 static int can_dirty(struct reiserfs_journal_cnode *cn)
3440 {
3441         struct super_block *sb = cn->sb;
3442         b_blocknr_t blocknr = cn->blocknr;
3443         struct reiserfs_journal_cnode *cur = cn->hprev;
3444         int can_dirty = 1;
3445
3446         /* first test hprev.  These are all newer than cn, so any node here
3447          ** with the same block number and dev means this node can't be sent
3448          ** to disk right now.
3449          */
3450         while (cur && can_dirty) {
3451                 if (cur->jlist && cur->bh && cur->blocknr && cur->sb == sb &&
3452                     cur->blocknr == blocknr) {
3453                         can_dirty = 0;
3454                 }
3455                 cur = cur->hprev;
3456         }
3457         /* then test hnext.  These are all older than cn.  As long as they
3458          ** are committed to the log, it is safe to write cn to disk
3459          */
3460         cur = cn->hnext;
3461         while (cur && can_dirty) {
3462                 if (cur->jlist && cur->jlist->j_len > 0 &&
3463                     atomic_read(&(cur->jlist->j_commit_left)) > 0 && cur->bh &&
3464                     cur->blocknr && cur->sb == sb && cur->blocknr == blocknr) {
3465                         can_dirty = 0;
3466                 }
3467                 cur = cur->hnext;
3468         }
3469         return can_dirty;
3470 }
3471
3472 /* syncs the commit blocks, but does not force the real buffers to disk
3473 ** will wait until the current transaction is done/committed before returning
3474 */
3475 int journal_end_sync(struct reiserfs_transaction_handle *th,
3476                      struct super_block *sb, unsigned long nblocks)
3477 {
3478         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3479
3480         BUG_ON(!th->t_trans_id);
3481         /* you can sync while nested, very, very bad */
3482         BUG_ON(th->t_refcount > 1);
3483         if (journal->j_len == 0) {
3484                 reiserfs_prepare_for_journal(sb, SB_BUFFER_WITH_SB(sb),
3485                                              1);
3486                 journal_mark_dirty(th, sb, SB_BUFFER_WITH_SB(sb));
3487         }
3488         return do_journal_end(th, sb, nblocks, COMMIT_NOW | WAIT);
3489 }
3490
3491 /*
3492 ** writeback the pending async commits to disk
3493 */
3494 static void flush_async_commits(struct work_struct *work)
3495 {
3496         struct reiserfs_journal *journal =
3497                 container_of(work, struct reiserfs_journal, j_work.work);
3498         struct super_block *sb = journal->j_work_sb;
3499         struct reiserfs_journal_list *jl;
3500         struct list_head *entry;
3501
3502         reiserfs_write_lock(sb);
3503         if (!list_empty(&journal->j_journal_list)) {
3504                 /* last entry is the youngest, commit it and you get everything */
3505                 entry = journal->j_journal_list.prev;
3506                 jl = JOURNAL_LIST_ENTRY(entry);
3507                 flush_commit_list(sb, jl, 1);
3508         }
3509         reiserfs_write_unlock(sb);
3510 }
3511
3512 /*
3513 ** flushes any old transactions to disk
3514 ** ends the current transaction if it is too old
3515 */
3516 int reiserfs_flush_old_commits(struct super_block *sb)
3517 {
3518         time_t now;
3519         struct reiserfs_transaction_handle th;
3520         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3521
3522         now = get_seconds();
3523         /* safety check so we don't flush while we are replaying the log during
3524          * mount
3525          */
3526         if (list_empty(&journal->j_journal_list)) {
3527                 return 0;
3528         }
3529
3530         /* check the current transaction.  If there are no writers, and it is
3531          * too old, finish it, and force the commit blocks to disk
3532          */
3533         if (atomic_read(&journal->j_wcount) <= 0 &&
3534             journal->j_trans_start_time > 0 &&
3535             journal->j_len > 0 &&
3536             (now - journal->j_trans_start_time) > journal->j_max_trans_age) {
3537                 if (!journal_join(&th, sb, 1)) {
3538                         reiserfs_prepare_for_journal(sb,
3539                                                      SB_BUFFER_WITH_SB(sb),
3540                                                      1);
3541                         journal_mark_dirty(&th, sb,
3542                                            SB_BUFFER_WITH_SB(sb));
3543
3544                         /* we're only being called from kreiserfsd, it makes no sense to do
3545                          ** an async commit so that kreiserfsd can do it later
3546                          */
3547                         do_journal_end(&th, sb, 1, COMMIT_NOW | WAIT);
3548                 }
3549         }
3550         return sb->s_dirt;
3551 }
3552
3553 /*
3554 ** returns 0 if do_journal_end should return right away, returns 1 if do_journal_end should finish the commit
3555 **
3556 ** if the current transaction is too old, but still has writers, this will wait on j_join_wait until all
3557 ** the writers are done.  By the time it wakes up, the transaction it was called has already ended, so it just
3558 ** flushes the commit list and returns 0.
3559 **
3560 ** Won't batch when flush or commit_now is set.  Also won't batch when others are waiting on j_join_wait.
3561 **
3562 ** Note, we can't allow the journal_end to proceed while there are still writers in the log.
3563 */
3564 static int check_journal_end(struct reiserfs_transaction_handle *th,
3565                              struct super_block *sb, unsigned long nblocks,
3566                              int flags)
3567 {
3568
3569         time_t now;
3570         int flush = flags & FLUSH_ALL;
3571         int commit_now = flags & COMMIT_NOW;
3572         int wait_on_commit = flags & WAIT;
3573         struct reiserfs_journal_list *jl;
3574         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3575
3576         BUG_ON(!th->t_trans_id);
3577
3578         if (th->t_trans_id != journal->j_trans_id) {
3579                 reiserfs_panic(th->t_super, "journal-1577",
3580                                "handle trans id %ld != current trans id %ld",
3581                                th->t_trans_id, journal->j_trans_id);
3582         }
3583
3584         journal->j_len_alloc -= (th->t_blocks_allocated - th->t_blocks_logged);
3585         if (atomic_read(&(journal->j_wcount)) > 0) {    /* <= 0 is allowed.  unmounting might not call begin */
3586                 atomic_dec(&(journal->j_wcount));
3587         }
3588
3589         /* BUG, deal with case where j_len is 0, but people previously freed blocks need to be released
3590          ** will be dealt with by next transaction that actually writes something, but should be taken
3591          ** care of in this trans
3592          */
3593         BUG_ON(journal->j_len == 0);
3594
3595         /* if wcount > 0, and we are called to with flush or commit_now,
3596          ** we wait on j_join_wait.  We will wake up when the last writer has
3597          ** finished the transaction, and started it on its way to the disk.
3598          ** Then, we flush the commit or journal list, and just return 0
3599          ** because the rest of journal end was already done for this transaction.
3600          */
3601         if (atomic_read(&(journal->j_wcount)) > 0) {
3602                 if (flush || commit_now) {
3603                         unsigned trans_id;
3604
3605                         jl = journal->j_current_jl;
3606                         trans_id = jl->j_trans_id;
3607                         if (wait_on_commit)
3608                                 jl->j_state |= LIST_COMMIT_PENDING;
3609                         atomic_set(&(journal->j_jlock), 1);
3610                         if (flush) {
3611                                 journal->j_next_full_flush = 1;
3612                         }
3613                         unlock_journal(sb);
3614
3615                         /* sleep while the current transaction is still j_jlocked */
3616                         while (journal->j_trans_id == trans_id) {
3617                                 if (atomic_read(&journal->j_jlock)) {
3618                                         queue_log_writer(sb);
3619                                 } else {
3620                                         lock_journal(sb);
3621                                         if (journal->j_trans_id == trans_id) {
3622                                                 atomic_set(&(journal->j_jlock),
3623                                                            1);
3624                                         }
3625                                         unlock_journal(sb);
3626                                 }
3627                         }
3628                         BUG_ON(journal->j_trans_id == trans_id);
3629                         
3630                         if (commit_now
3631                             && journal_list_still_alive(sb, trans_id)
3632                             && wait_on_commit) {
3633                                 flush_commit_list(sb, jl, 1);
3634                         }
3635                         return 0;
3636                 }
3637                 unlock_journal(sb);
3638                 return 0;
3639         }
3640
3641         /* deal with old transactions where we are the last writers */
3642         now = get_seconds();
3643         if ((now - journal->j_trans_start_time) > journal->j_max_trans_age) {
3644                 commit_now = 1;
3645                 journal->j_next_async_flush = 1;
3646         }
3647         /* don't batch when someone is waiting on j_join_wait */
3648         /* don't batch when syncing the commit or flushing the whole trans */
3649         if (!(journal->j_must_wait > 0) && !(atomic_read(&(journal->j_jlock)))
3650             && !flush && !commit_now && (journal->j_len < journal->j_max_batch)
3651             && journal->j_len_alloc < journal->j_max_batch
3652             && journal->j_cnode_free > (journal->j_trans_max * 3)) {
3653                 journal->j_bcount++;
3654                 unlock_journal(sb);
3655                 return 0;
3656         }
3657
3658         if (journal->j_start > SB_ONDISK_JOURNAL_SIZE(sb)) {
3659                 reiserfs_panic(sb, "journal-003",
3660                                "j_start (%ld) is too high",
3661                                journal->j_start);
3662         }
3663         return 1;
3664 }
3665
3666 /*
3667 ** Does all the work that makes deleting blocks safe.
3668 ** when deleting a block mark BH_JNew, just remove it from the current transaction, clean it's buffer_head and move on.
3669 **
3670 ** otherwise:
3671 ** set a bit for the block in the journal bitmap.  That will prevent it from being allocated for unformatted nodes
3672 ** before this transaction has finished.
3673 **
3674 ** mark any cnodes for this block as BLOCK_FREED, and clear their bh pointers.  That will prevent any old transactions with
3675 ** this block from trying to flush to the real location.  Since we aren't removing the cnode from the journal_list_hash,
3676 ** the block can't be reallocated yet.
3677 **
3678 ** Then remove it from the current transaction, decrementing any counters and filing it on the clean list.
3679 */
3680 int journal_mark_freed(struct reiserfs_transaction_handle *th,
3681                        struct super_block *sb, b_blocknr_t blocknr)
3682 {
3683         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3684         struct reiserfs_journal_cnode *cn = NULL;
3685         struct buffer_head *bh = NULL;
3686         struct reiserfs_list_bitmap *jb = NULL;
3687         int cleaned = 0;
3688         BUG_ON(!th->t_trans_id);
3689
3690         cn = get_journal_hash_dev(sb, journal->j_hash_table, blocknr);
3691         if (cn && cn->bh) {
3692                 bh = cn->bh;
3693                 get_bh(bh);
3694         }
3695         /* if it is journal new, we just remove it from this transaction */
3696         if (bh && buffer_journal_new(bh)) {
3697                 clear_buffer_journal_new(bh);
3698                 clear_prepared_bits(bh);
3699                 reiserfs_clean_and_file_buffer(bh);
3700                 cleaned = remove_from_transaction(sb, blocknr, cleaned);
3701         } else {
3702                 /* set the bit for this block in the journal bitmap for this transaction */
3703                 jb = journal->j_current_jl->j_list_bitmap;
3704                 if (!jb) {
3705                         reiserfs_panic(sb, "journal-1702",
3706                                        "journal_list_bitmap is NULL");
3707                 }
3708                 set_bit_in_list_bitmap(sb, blocknr, jb);
3709
3710                 /* Note, the entire while loop is not allowed to schedule.  */
3711
3712                 if (bh) {
3713                         clear_prepared_bits(bh);
3714                         reiserfs_clean_and_file_buffer(bh);
3715                 }
3716                 cleaned = remove_from_transaction(sb, blocknr, cleaned);
3717
3718                 /* find all older transactions with this block, make sure they don't try to write it out */
3719                 cn = get_journal_hash_dev(sb, journal->j_list_hash_table,
3720                                           blocknr);
3721                 while (cn) {
3722                         if (sb == cn->sb && blocknr == cn->blocknr) {
3723                                 set_bit(BLOCK_FREED, &cn->state);
3724                                 if (cn->bh) {
3725                                         if (!cleaned) {
3726                                                 /* remove_from_transaction will brelse the buffer if it was 
3727                                                  ** in the current trans
3728                                                  */
3729                                                 clear_buffer_journal_dirty(cn->
3730                                                                            bh);
3731                                                 clear_buffer_dirty(cn->bh);
3732                                                 clear_buffer_journal_test(cn->
3733                                                                           bh);
3734                                                 cleaned = 1;
3735                                                 put_bh(cn->bh);
3736                                                 if (atomic_read
3737                                                     (&(cn->bh->b_count)) < 0) {
3738                                                         reiserfs_warning(sb,
3739                                                                  "journal-2138",
3740                                                                  "cn->bh->b_count < 0");
3741                                                 }
3742                                         }
3743                                         if (cn->jlist) {        /* since we are clearing the bh, we MUST dec nonzerolen */
3744                                                 atomic_dec(&
3745                                                            (cn->jlist->
3746                                                             j_nonzerolen));
3747                                         }
3748                                         cn->bh = NULL;
3749                                 }
3750                         }
3751                         cn = cn->hnext;
3752                 }
3753         }
3754
3755         if (bh)
3756                 release_buffer_page(bh); /* get_hash grabs the buffer */
3757         return 0;
3758 }
3759
3760 void reiserfs_update_inode_transaction(struct inode *inode)
3761 {
3762         struct reiserfs_journal *journal = SB_JOURNAL(inode->i_sb);
3763         REISERFS_I(inode)->i_jl = journal->j_current_jl;
3764         REISERFS_I(inode)->i_trans_id = journal->j_trans_id;
3765 }
3766
3767 /*
3768  * returns -1 on error, 0 if no commits/barriers were done and 1
3769  * if a transaction was actually committed and the barrier was done
3770  */
3771 static int __commit_trans_jl(struct inode *inode, unsigned long id,
3772                              struct reiserfs_journal_list *jl)
3773 {
3774         struct reiserfs_transaction_handle th;
3775         struct super_block *sb = inode->i_sb;
3776         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3777         int ret = 0;
3778
3779         /* is it from the current transaction, or from an unknown transaction? */
3780         if (id == journal->j_trans_id) {
3781                 jl = journal->j_current_jl;
3782                 /* try to let other writers come in and grow this transaction */
3783                 let_transaction_grow(sb, id);
3784                 if (journal->j_trans_id != id) {
3785                         goto flush_commit_only;
3786                 }
3787
3788                 ret = journal_begin(&th, sb, 1);
3789                 if (ret)
3790                         return ret;
3791
3792                 /* someone might have ended this transaction while we joined */
3793                 if (journal->j_trans_id != id) {
3794                         reiserfs_prepare_for_journal(sb, SB_BUFFER_WITH_SB(sb),
3795                                                      1);
3796                         journal_mark_dirty(&th, sb, SB_BUFFER_WITH_SB(sb));
3797                         ret = journal_end(&th, sb, 1);
3798                         goto flush_commit_only;
3799                 }
3800
3801                 ret = journal_end_sync(&th, sb, 1);
3802                 if (!ret)
3803                         ret = 1;
3804
3805         } else {
3806                 /* this gets tricky, we have to make sure the journal list in
3807                  * the inode still exists.  We know the list is still around
3808                  * if we've got a larger transaction id than the oldest list
3809                  */
3810               flush_commit_only:
3811                 if (journal_list_still_alive(inode->i_sb, id)) {
3812                         /*
3813                          * we only set ret to 1 when we know for sure
3814                          * the barrier hasn't been started yet on the commit
3815                          * block.
3816                          */
3817                         if (atomic_read(&jl->j_commit_left) > 1)
3818                                 ret = 1;
3819                         flush_commit_list(sb, jl, 1);
3820                         if (journal->j_errno)
3821                                 ret = journal->j_errno;
3822                 }
3823         }
3824         /* otherwise the list is gone, and long since committed */
3825         return ret;
3826 }
3827
3828 int reiserfs_commit_for_inode(struct inode *inode)
3829 {
3830         unsigned int id = REISERFS_I(inode)->i_trans_id;
3831         struct reiserfs_journal_list *jl = REISERFS_I(inode)->i_jl;
3832
3833         /* for the whole inode, assume unset id means it was
3834          * changed in the current transaction.  More conservative
3835          */
3836         if (!id || !jl) {
3837                 reiserfs_update_inode_transaction(inode);
3838                 id = REISERFS_I(inode)->i_trans_id;
3839                 /* jl will be updated in __commit_trans_jl */
3840         }
3841
3842         return __commit_trans_jl(inode, id, jl);
3843 }
3844
3845 void reiserfs_restore_prepared_buffer(struct super_block *sb,
3846                                       struct buffer_head *bh)
3847 {
3848         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3849         PROC_INFO_INC(sb, journal.restore_prepared);
3850         if (!bh) {
3851                 return;
3852         }
3853         if (test_clear_buffer_journal_restore_dirty(bh) &&
3854             buffer_journal_dirty(bh)) {
3855                 struct reiserfs_journal_cnode *cn;
3856                 cn = get_journal_hash_dev(sb,
3857                                           journal->j_list_hash_table,
3858                                           bh->b_blocknr);
3859                 if (cn && can_dirty(cn)) {
3860                         set_buffer_journal_test(bh);
3861                         mark_buffer_dirty(bh);
3862                 }
3863         }
3864         clear_buffer_journal_prepared(bh);
3865 }
3866
3867 extern struct tree_balance *cur_tb;
3868 /*
3869 ** before we can change a metadata block, we have to make sure it won't
3870 ** be written to disk while we are altering it.  So, we must:
3871 ** clean it
3872 ** wait on it.
3873 **
3874 */
3875 int reiserfs_prepare_for_journal(struct super_block *sb,
3876                                  struct buffer_head *bh, int wait)
3877 {
3878         PROC_INFO_INC(sb, journal.prepare);
3879
3880         if (!trylock_buffer(bh)) {
3881                 if (!wait)
3882                         return 0;
3883                 lock_buffer(bh);
3884         }
3885         set_buffer_journal_prepared(bh);
3886         if (test_clear_buffer_dirty(bh) && buffer_journal_dirty(bh)) {
3887                 clear_buffer_journal_test(bh);
3888                 set_buffer_journal_restore_dirty(bh);
3889         }
3890         unlock_buffer(bh);
3891         return 1;
3892 }
3893
3894 static void flush_old_journal_lists(struct super_block *s)
3895 {
3896         struct reiserfs_journal *journal = SB_JOURNAL(s);
3897         struct reiserfs_journal_list *jl;
3898         struct list_head *entry;
3899         time_t now = get_seconds();
3900
3901         while (!list_empty(&journal->j_journal_list)) {
3902                 entry = journal->j_journal_list.next;
3903                 jl = JOURNAL_LIST_ENTRY(entry);
3904                 /* this check should always be run, to send old lists to disk */
3905                 if (jl->j_timestamp < (now - (JOURNAL_MAX_TRANS_AGE * 4)) &&
3906                     atomic_read(&jl->j_commit_left) == 0 &&
3907                     test_transaction(s, jl)) {
3908                         flush_used_journal_lists(s, jl);
3909                 } else {
3910                         break;
3911                 }
3912         }
3913 }
3914
3915 /*
3916 ** long and ugly.  If flush, will not return until all commit
3917 ** blocks and all real buffers in the trans are on disk.
3918 ** If no_async, won't return until all commit blocks are on disk.
3919 **
3920 ** keep reading, there are comments as you go along
3921 **
3922 ** If the journal is aborted, we just clean up. Things like flushing
3923 ** journal lists, etc just won't happen.
3924 */
3925 static int do_journal_end(struct reiserfs_transaction_handle *th,
3926                           struct super_block *sb, unsigned long nblocks,
3927                           int flags)
3928 {
3929         struct reiserfs_journal *journal = SB_JOURNAL(sb);
3930         struct reiserfs_journal_cnode *cn, *next, *jl_cn;
3931         struct reiserfs_journal_cnode *last_cn = NULL;
3932         struct reiserfs_journal_desc *desc;
3933         struct reiserfs_journal_commit *commit;
3934         struct buffer_head *c_bh;       /* commit bh */
3935         struct buffer_head *d_bh;       /* desc bh */
3936         int cur_write_start = 0;        /* start index of current log write */
3937         int old_start;
3938         int i;
3939         int flush;
3940         int wait_on_commit;
3941         struct reiserfs_journal_list *jl, *temp_jl;
3942         struct list_head *entry, *safe;
3943         unsigned long jindex;
3944         unsigned int commit_trans_id;
3945         int trans_half;
3946
3947         BUG_ON(th->t_refcount > 1);
3948         BUG_ON(!th->t_trans_id);
3949
3950         /* protect flush_older_commits from doing mistakes if the
3951            transaction ID counter gets overflowed.  */
3952         if (th->t_trans_id == ~0U)
3953                 flags |= FLUSH_ALL | COMMIT_NOW | WAIT;
3954         flush = flags & FLUSH_ALL;
3955         wait_on_commit = flags & WAIT;
3956
3957         current->journal_info = th->t_handle_save;
3958         reiserfs_check_lock_depth(sb, "journal end");
3959         if (journal->j_len == 0) {
3960                 reiserfs_prepare_for_journal(sb, SB_BUFFER_WITH_SB(sb),
3961                                              1);
3962                 journal_mark_dirty(th, sb, SB_BUFFER_WITH_SB(sb));
3963         }
3964
3965         lock_journal(sb);
3966         if (journal->j_next_full_flush) {
3967                 flags |= FLUSH_ALL;
3968                 flush = 1;
3969         }
3970         if (journal->j_next_async_flush) {
3971                 flags |= COMMIT_NOW | WAIT;
3972                 wait_on_commit = 1;
3973         }
3974
3975         /* check_journal_end locks the journal, and unlocks if it does not return 1
3976          ** it tells us if we should continue with the journal_end, or just return
3977          */
3978         if (!check_journal_end(th, sb, nblocks, flags)) {
3979                 sb->s_dirt = 1;
3980                 wake_queued_writers(sb);
3981                 reiserfs_async_progress_wait(sb);
3982                 goto out;
3983         }
3984
3985         /* check_journal_end might set these, check again */
3986         if (journal->j_next_full_flush) {
3987                 flush = 1;
3988         }
3989
3990         /*
3991          ** j must wait means we have to flush the log blocks, and the real blocks for
3992          ** this transaction
3993          */
3994         if (journal->j_must_wait > 0) {
3995                 flush = 1;
3996         }
3997 #ifdef REISERFS_PREALLOCATE
3998         /* quota ops might need to nest, setup the journal_info pointer for them
3999          * and raise the refcount so that it is > 0. */
4000         current->journal_info = th;
4001         th->t_refcount++;
4002         reiserfs_discard_all_prealloc(th);      /* it should not involve new blocks into
4003                                                  * the transaction */
4004         th->t_refcount--;
4005         current->journal_info = th->t_handle_save;
4006 #endif
4007
4008         /* setup description block */
4009         d_bh =
4010             journal_getblk(sb,
4011                            SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
4012                            journal->j_start);
4013         set_buffer_uptodate(d_bh);
4014         desc = (struct reiserfs_journal_desc *)(d_bh)->b_data;
4015         memset(d_bh->b_data, 0, d_bh->b_size);
4016         memcpy(get_journal_desc_magic(d_bh), JOURNAL_DESC_MAGIC, 8);
4017         set_desc_trans_id(desc, journal->j_trans_id);
4018
4019         /* setup commit block.  Don't write (keep it clean too) this one until after everyone else is written */
4020         c_bh = journal_getblk(sb, SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
4021                               ((journal->j_start + journal->j_len +
4022                                 1) % SB_ONDISK_JOURNAL_SIZE(sb)));
4023         commit = (struct reiserfs_journal_commit *)c_bh->b_data;
4024         memset(c_bh->b_data, 0, c_bh->b_size);
4025         set_commit_trans_id(commit, journal->j_trans_id);
4026         set_buffer_uptodate(c_bh);
4027
4028         /* init this journal list */
4029         jl = journal->j_current_jl;
4030
4031         /* we lock the commit before doing anything because
4032          * we want to make sure nobody tries to run flush_commit_list until
4033          * the new transaction is fully setup, and we've already flushed the
4034          * ordered bh list
4035          */
4036         reiserfs_mutex_lock_safe(&jl->j_commit_mutex, sb);
4037
4038         /* save the transaction id in case we need to commit it later */
4039         commit_trans_id = jl->j_trans_id;
4040
4041         atomic_set(&jl->j_older_commits_done, 0);
4042         jl->j_trans_id = journal->j_trans_id;
4043         jl->j_timestamp = journal->j_trans_start_time;
4044         jl->j_commit_bh = c_bh;
4045         jl->j_start = journal->j_start;
4046         jl->j_len = journal->j_len;
4047         atomic_set(&jl->j_nonzerolen, journal->j_len);
4048         atomic_set(&jl->j_commit_left, journal->j_len + 2);
4049         jl->j_realblock = NULL;
4050
4051         /* The ENTIRE FOR LOOP MUST not cause schedule to occur.
4052          **  for each real block, add it to the journal list hash,
4053          ** copy into real block index array in the commit or desc block
4054          */
4055         trans_half = journal_trans_half(sb->s_blocksize);
4056         for (i = 0, cn = journal->j_first; cn; cn = cn->next, i++) {
4057                 if (buffer_journaled(cn->bh)) {
4058                         jl_cn = get_cnode(sb);
4059                         if (!jl_cn) {
4060                                 reiserfs_panic(sb, "journal-1676",
4061                                                "get_cnode returned NULL");
4062                         }
4063                         if (i == 0) {
4064                                 jl->j_realblock = jl_cn;
4065                         }
4066                         jl_cn->prev = last_cn;
4067                         jl_cn->next = NULL;
4068                         if (last_cn) {
4069                                 last_cn->next = jl_cn;
4070                         }
4071                         last_cn = jl_cn;
4072                         /* make sure the block we are trying to log is not a block
4073                            of journal or reserved area */
4074
4075                         if (is_block_in_log_or_reserved_area
4076                             (sb, cn->bh->b_blocknr)) {
4077                                 reiserfs_panic(sb, "journal-2332",
4078                                                "Trying to log block %lu, "
4079                                                "which is a log block",
4080                                                cn->bh->b_blocknr);
4081                         }
4082                         jl_cn->blocknr = cn->bh->b_blocknr;
4083                         jl_cn->state = 0;
4084                         jl_cn->sb = sb;
4085                         jl_cn->bh = cn->bh;
4086                         jl_cn->jlist = jl;
4087                         insert_journal_hash(journal->j_list_hash_table, jl_cn);
4088                         if (i < trans_half) {
4089                                 desc->j_realblock[i] =
4090                                     cpu_to_le32(cn->bh->b_blocknr);
4091                         } else {
4092                                 commit->j_realblock[i - trans_half] =
4093                                     cpu_to_le32(cn->bh->b_blocknr);
4094                         }
4095                 } else {
4096                         i--;
4097                 }
4098         }
4099         set_desc_trans_len(desc, journal->j_len);
4100         set_desc_mount_id(desc, journal->j_mount_id);
4101         set_desc_trans_id(desc, journal->j_trans_id);
4102         set_commit_trans_len(commit, journal->j_len);
4103
4104         /* special check in case all buffers in the journal were marked for not logging */
4105         BUG_ON(journal->j_len == 0);
4106
4107         /* we're about to dirty all the log blocks, mark the description block
4108          * dirty now too.  Don't mark the commit block dirty until all the
4109          * others are on disk
4110          */
4111         mark_buffer_dirty(d_bh);
4112
4113         /* first data block is j_start + 1, so add one to cur_write_start wherever you use it */
4114         cur_write_start = journal->j_start;
4115         cn = journal->j_first;
4116         jindex = 1;             /* start at one so we don't get the desc again */
4117         while (cn) {
4118                 clear_buffer_journal_new(cn->bh);
4119                 /* copy all the real blocks into log area.  dirty log blocks */
4120                 if (buffer_journaled(cn->bh)) {
4121                         struct buffer_head *tmp_bh;
4122                         char *addr;
4123                         struct page *page;
4124                         tmp_bh =
4125                             journal_getblk(sb,
4126                                            SB_ONDISK_JOURNAL_1st_BLOCK(sb) +
4127                                            ((cur_write_start +
4128                                              jindex) %
4129                                             SB_ONDISK_JOURNAL_SIZE(sb)));
4130                         set_buffer_uptodate(tmp_bh);
4131                         page = cn->bh->b_page;
4132                         addr = kmap(page);
4133                         memcpy(tmp_bh->b_data,
4134                                addr + offset_in_page(cn->bh->b_data),
4135                                cn->bh->b_size);
4136                         kunmap(page);
4137                         mark_buffer_dirty(tmp_bh);
4138                         jindex++;
4139                         set_buffer_journal_dirty(cn->bh);
4140                         clear_buffer_journaled(cn->bh);
4141                 } else {
4142                         /* JDirty cleared sometime during transaction.  don't log this one */
4143                         reiserfs_warning(sb, "journal-2048",
4144                                          "BAD, buffer in journal hash, "
4145                                          "but not JDirty!");
4146                         brelse(cn->bh);
4147                 }
4148                 next = cn->next;
4149                 free_cnode(sb, cn);
4150                 cn = next;
4151                 reiserfs_write_unlock(sb);
4152                 cond_resched();
4153                 reiserfs_write_lock(sb);
4154         }
4155
4156         /* we are done  with both the c_bh and d_bh, but
4157          ** c_bh must be written after all other commit blocks,
4158          ** so we dirty/relse c_bh in flush_commit_list, with commit_left <= 1.
4159          */
4160
4161         journal->j_current_jl = alloc_journal_list(sb);
4162
4163         /* now it is safe to insert this transaction on the main list */
4164         list_add_tail(&jl->j_list, &journal->j_journal_list);
4165         list_add_tail(&jl->j_working_list, &journal->j_working_list);
4166         journal->j_num_work_lists++;
4167
4168         /* reset journal values for the next transaction */
4169         old_start = journal->j_start;
4170         journal->j_start =
4171             (journal->j_start + journal->j_len +
4172              2) % SB_ONDISK_JOURNAL_SIZE(sb);
4173         atomic_set(&(journal->j_wcount), 0);
4174         journal->j_bcount = 0;
4175         journal->j_last = NULL;
4176         journal->j_first = NULL;
4177         journal->j_len = 0;
4178         journal->j_trans_start_time = 0;
4179         /* check for trans_id overflow */
4180         if (++journal->j_trans_id == 0)
4181                 journal->j_trans_id = 10;
4182         journal->j_current_jl->j_trans_id = journal->j_trans_id;
4183         journal->j_must_wait = 0;
4184         journal->j_len_alloc = 0;
4185         journal->j_next_full_flush = 0;
4186         journal->j_next_async_flush = 0;
4187         init_journal_hash(sb);
4188
4189         // make sure reiserfs_add_jh sees the new current_jl before we
4190         // write out the tails
4191         smp_mb();
4192
4193         /* tail conversion targets have to hit the disk before we end the
4194          * transaction.  Otherwise a later transaction might repack the tail
4195          * before this transaction commits, leaving the data block unflushed and
4196          * clean, if we crash before the later transaction commits, the data block
4197          * is lost.
4198          */
4199         if (!list_empty(&jl->j_tail_bh_list)) {
4200                 reiserfs_write_unlock(sb);
4201                 write_ordered_buffers(&journal->j_dirty_buffers_lock,
4202                                       journal, jl, &jl->j_tail_bh_list);
4203                 reiserfs_write_lock(sb);
4204         }
4205         BUG_ON(!list_empty(&jl->j_tail_bh_list));
4206         mutex_unlock(&jl->j_commit_mutex);
4207
4208         /* honor the flush wishes from the caller, simple commits can
4209          ** be done outside the journal lock, they are done below
4210          **
4211          ** if we don't flush the commit list right now, we put it into
4212          ** the work queue so the people waiting on the async progress work
4213          ** queue don't wait for this proc to flush journal lists and such.
4214          */
4215         if (flush) {
4216                 flush_commit_list(sb, jl, 1);
4217                 flush_journal_list(sb, jl, 1);
4218         } else if (!(jl->j_state & LIST_COMMIT_PENDING)) {
4219                 /*
4220                  * Avoid queueing work when sb is being shut down. Transaction
4221                  * will be flushed on journal shutdown.
4222                  */
4223                 if (sb->s_flags & MS_ACTIVE)
4224                         queue_delayed_work(commit_wq,
4225                                            &journal->j_work, HZ / 10);
4226         }
4227
4228         /* if the next transaction has any chance of wrapping, flush
4229          ** transactions that might get overwritten.  If any journal lists are very
4230          ** old flush them as well.
4231          */
4232       first_jl:
4233         list_for_each_safe(entry, safe, &journal->j_journal_list) {
4234                 temp_jl = JOURNAL_LIST_ENTRY(entry);
4235                 if (journal->j_start <= temp_jl->j_start) {
4236                         if ((journal->j_start + journal->j_trans_max + 1) >=
4237                             temp_jl->j_start) {
4238                                 flush_used_journal_lists(sb, temp_jl);
4239                                 goto first_jl;
4240                         } else if ((journal->j_start +
4241                                     journal->j_trans_max + 1) <
4242                                    SB_ONDISK_JOURNAL_SIZE(sb)) {
4243                                 /* if we don't cross into the next transaction and we don't
4244                                  * wrap, there is no way we can overlap any later transactions
4245                                  * break now
4246                                  */
4247                                 break;
4248                         }
4249                 } else if ((journal->j_start +
4250                             journal->j_trans_max + 1) >
4251                            SB_ONDISK_JOURNAL_SIZE(sb)) {
4252                         if (((journal->j_start + journal->j_trans_max + 1) %
4253                              SB_ONDISK_JOURNAL_SIZE(sb)) >=
4254                             temp_jl->j_start) {
4255                                 flush_used_journal_lists(sb, temp_jl);
4256                                 goto first_jl;
4257                         } else {
4258                                 /* we don't overlap anything from out start to the end of the
4259                                  * log, and our wrapped portion doesn't overlap anything at
4260                                  * the start of the log.  We can break
4261                                  */
4262                                 break;
4263                         }
4264                 }
4265         }
4266         flush_old_journal_lists(sb);
4267
4268         journal->j_current_jl->j_list_bitmap =
4269             get_list_bitmap(sb, journal->j_current_jl);
4270
4271         if (!(journal->j_current_jl->j_list_bitmap)) {
4272                 reiserfs_panic(sb, "journal-1996",
4273                                "could not get a list bitmap");
4274         }
4275
4276         atomic_set(&(journal->j_jlock), 0);
4277         unlock_journal(sb);
4278         /* wake up any body waiting to join. */
4279         clear_bit(J_WRITERS_QUEUED, &journal->j_state);
4280         wake_up(&(journal->j_join_wait));
4281
4282         if (!flush && wait_on_commit &&
4283             journal_list_still_alive(sb, commit_trans_id)) {
4284                 flush_commit_list(sb, jl, 1);
4285         }
4286       out:
4287         reiserfs_check_lock_depth(sb, "journal end2");
4288
4289         memset(th, 0, sizeof(*th));
4290         /* Re-set th->t_super, so we can properly keep track of how many
4291          * persistent transactions there are. We need to do this so if this
4292          * call is part of a failed restart_transaction, we can free it later */
4293         th->t_super = sb;
4294
4295         return journal->j_errno;
4296 }
4297
4298 /* Send the file system read only and refuse new transactions */
4299 void reiserfs_abort_journal(struct super_block *sb, int errno)
4300 {
4301         struct reiserfs_journal *journal = SB_JOURNAL(sb);
4302         if (test_bit(J_ABORTED, &journal->j_state))
4303                 return;
4304
4305         if (!journal->j_errno)
4306                 journal->j_errno = errno;
4307
4308         sb->s_flags |= MS_RDONLY;
4309         set_bit(J_ABORTED, &journal->j_state);
4310
4311 #ifdef CONFIG_REISERFS_CHECK
4312         dump_stack();
4313 #endif
4314 }