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