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