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