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