dc39efd05d542553ea65fe861e26443433b39dfa
[linux-2.6.git] / fs / jbd / transaction.c
1 /*
2  * linux/fs/jbd/transaction.c
3  *
4  * Written by Stephen C. Tweedie <sct@redhat.com>, 1998
5  *
6  * Copyright 1998 Red Hat corp --- All Rights Reserved
7  *
8  * This file is part of the Linux kernel and is made available under
9  * the terms of the GNU General Public License, version 2, or at your
10  * option, any later version, incorporated herein by reference.
11  *
12  * Generic filesystem transaction handling code; part of the ext2fs
13  * journaling system.
14  *
15  * This file manages transactions (compound commits managed by the
16  * journaling code) and handles (individual atomic operations by the
17  * filesystem).
18  */
19
20 #include <linux/time.h>
21 #include <linux/fs.h>
22 #include <linux/jbd.h>
23 #include <linux/errno.h>
24 #include <linux/slab.h>
25 #include <linux/timer.h>
26 #include <linux/mm.h>
27 #include <linux/highmem.h>
28 #include <linux/hrtimer.h>
29 #include <linux/backing-dev.h>
30
31 static void __journal_temp_unlink_buffer(struct journal_head *jh);
32
33 /*
34  * get_transaction: obtain a new transaction_t object.
35  *
36  * Simply allocate and initialise a new transaction.  Create it in
37  * RUNNING state and add it to the current journal (which should not
38  * have an existing running transaction: we only make a new transaction
39  * once we have started to commit the old one).
40  *
41  * Preconditions:
42  *      The journal MUST be locked.  We don't perform atomic mallocs on the
43  *      new transaction and we can't block without protecting against other
44  *      processes trying to touch the journal while it is in transition.
45  *
46  * Called under j_state_lock
47  */
48
49 static transaction_t *
50 get_transaction(journal_t *journal, transaction_t *transaction)
51 {
52         transaction->t_journal = journal;
53         transaction->t_state = T_RUNNING;
54         transaction->t_start_time = ktime_get();
55         transaction->t_tid = journal->j_transaction_sequence++;
56         transaction->t_expires = jiffies + journal->j_commit_interval;
57         spin_lock_init(&transaction->t_handle_lock);
58
59         /* Set up the commit timer for the new transaction. */
60         journal->j_commit_timer.expires =
61                                 round_jiffies_up(transaction->t_expires);
62         add_timer(&journal->j_commit_timer);
63
64         J_ASSERT(journal->j_running_transaction == NULL);
65         journal->j_running_transaction = transaction;
66
67         return transaction;
68 }
69
70 /*
71  * Handle management.
72  *
73  * A handle_t is an object which represents a single atomic update to a
74  * filesystem, and which tracks all of the modifications which form part
75  * of that one update.
76  */
77
78 /*
79  * start_this_handle: Given a handle, deal with any locking or stalling
80  * needed to make sure that there is enough journal space for the handle
81  * to begin.  Attach the handle to a transaction and set up the
82  * transaction's buffer credits.
83  */
84
85 static int start_this_handle(journal_t *journal, handle_t *handle)
86 {
87         transaction_t *transaction;
88         int needed;
89         int nblocks = handle->h_buffer_credits;
90         transaction_t *new_transaction = NULL;
91         int ret = 0;
92
93         if (nblocks > journal->j_max_transaction_buffers) {
94                 printk(KERN_ERR "JBD: %s wants too many credits (%d > %d)\n",
95                        current->comm, nblocks,
96                        journal->j_max_transaction_buffers);
97                 ret = -ENOSPC;
98                 goto out;
99         }
100
101 alloc_transaction:
102         if (!journal->j_running_transaction) {
103                 new_transaction = kzalloc(sizeof(*new_transaction), GFP_NOFS);
104                 if (!new_transaction) {
105                         congestion_wait(BLK_RW_ASYNC, HZ/50);
106                         goto alloc_transaction;
107                 }
108         }
109
110         jbd_debug(3, "New handle %p going live.\n", handle);
111
112 repeat:
113
114         /*
115          * We need to hold j_state_lock until t_updates has been incremented,
116          * for proper journal barrier handling
117          */
118         spin_lock(&journal->j_state_lock);
119 repeat_locked:
120         if (is_journal_aborted(journal) ||
121             (journal->j_errno != 0 && !(journal->j_flags & JFS_ACK_ERR))) {
122                 spin_unlock(&journal->j_state_lock);
123                 ret = -EROFS;
124                 goto out;
125         }
126
127         /* Wait on the journal's transaction barrier if necessary */
128         if (journal->j_barrier_count) {
129                 spin_unlock(&journal->j_state_lock);
130                 wait_event(journal->j_wait_transaction_locked,
131                                 journal->j_barrier_count == 0);
132                 goto repeat;
133         }
134
135         if (!journal->j_running_transaction) {
136                 if (!new_transaction) {
137                         spin_unlock(&journal->j_state_lock);
138                         goto alloc_transaction;
139                 }
140                 get_transaction(journal, new_transaction);
141                 new_transaction = NULL;
142         }
143
144         transaction = journal->j_running_transaction;
145
146         /*
147          * If the current transaction is locked down for commit, wait for the
148          * lock to be released.
149          */
150         if (transaction->t_state == T_LOCKED) {
151                 DEFINE_WAIT(wait);
152
153                 prepare_to_wait(&journal->j_wait_transaction_locked,
154                                         &wait, TASK_UNINTERRUPTIBLE);
155                 spin_unlock(&journal->j_state_lock);
156                 schedule();
157                 finish_wait(&journal->j_wait_transaction_locked, &wait);
158                 goto repeat;
159         }
160
161         /*
162          * If there is not enough space left in the log to write all potential
163          * buffers requested by this operation, we need to stall pending a log
164          * checkpoint to free some more log space.
165          */
166         spin_lock(&transaction->t_handle_lock);
167         needed = transaction->t_outstanding_credits + nblocks;
168
169         if (needed > journal->j_max_transaction_buffers) {
170                 /*
171                  * If the current transaction is already too large, then start
172                  * to commit it: we can then go back and attach this handle to
173                  * a new transaction.
174                  */
175                 DEFINE_WAIT(wait);
176
177                 jbd_debug(2, "Handle %p starting new commit...\n", handle);
178                 spin_unlock(&transaction->t_handle_lock);
179                 prepare_to_wait(&journal->j_wait_transaction_locked, &wait,
180                                 TASK_UNINTERRUPTIBLE);
181                 __log_start_commit(journal, transaction->t_tid);
182                 spin_unlock(&journal->j_state_lock);
183                 schedule();
184                 finish_wait(&journal->j_wait_transaction_locked, &wait);
185                 goto repeat;
186         }
187
188         /*
189          * The commit code assumes that it can get enough log space
190          * without forcing a checkpoint.  This is *critical* for
191          * correctness: a checkpoint of a buffer which is also
192          * associated with a committing transaction creates a deadlock,
193          * so commit simply cannot force through checkpoints.
194          *
195          * We must therefore ensure the necessary space in the journal
196          * *before* starting to dirty potentially checkpointed buffers
197          * in the new transaction.
198          *
199          * The worst part is, any transaction currently committing can
200          * reduce the free space arbitrarily.  Be careful to account for
201          * those buffers when checkpointing.
202          */
203
204         /*
205          * @@@ AKPM: This seems rather over-defensive.  We're giving commit
206          * a _lot_ of headroom: 1/4 of the journal plus the size of
207          * the committing transaction.  Really, we only need to give it
208          * committing_transaction->t_outstanding_credits plus "enough" for
209          * the log control blocks.
210          * Also, this test is inconsistent with the matching one in
211          * journal_extend().
212          */
213         if (__log_space_left(journal) < jbd_space_needed(journal)) {
214                 jbd_debug(2, "Handle %p waiting for checkpoint...\n", handle);
215                 spin_unlock(&transaction->t_handle_lock);
216                 __log_wait_for_space(journal);
217                 goto repeat_locked;
218         }
219
220         /* OK, account for the buffers that this operation expects to
221          * use and add the handle to the running transaction. */
222
223         handle->h_transaction = transaction;
224         transaction->t_outstanding_credits += nblocks;
225         transaction->t_updates++;
226         transaction->t_handle_count++;
227         jbd_debug(4, "Handle %p given %d credits (total %d, free %d)\n",
228                   handle, nblocks, transaction->t_outstanding_credits,
229                   __log_space_left(journal));
230         spin_unlock(&transaction->t_handle_lock);
231         spin_unlock(&journal->j_state_lock);
232
233         lock_map_acquire(&handle->h_lockdep_map);
234 out:
235         if (unlikely(new_transaction))          /* It's usually NULL */
236                 kfree(new_transaction);
237         return ret;
238 }
239
240 static struct lock_class_key jbd_handle_key;
241
242 /* Allocate a new handle.  This should probably be in a slab... */
243 static handle_t *new_handle(int nblocks)
244 {
245         handle_t *handle = jbd_alloc_handle(GFP_NOFS);
246         if (!handle)
247                 return NULL;
248         memset(handle, 0, sizeof(*handle));
249         handle->h_buffer_credits = nblocks;
250         handle->h_ref = 1;
251
252         lockdep_init_map(&handle->h_lockdep_map, "jbd_handle", &jbd_handle_key, 0);
253
254         return handle;
255 }
256
257 /**
258  * handle_t *journal_start() - Obtain a new handle.
259  * @journal: Journal to start transaction on.
260  * @nblocks: number of block buffer we might modify
261  *
262  * We make sure that the transaction can guarantee at least nblocks of
263  * modified buffers in the log.  We block until the log can guarantee
264  * that much space.
265  *
266  * This function is visible to journal users (like ext3fs), so is not
267  * called with the journal already locked.
268  *
269  * Return a pointer to a newly allocated handle, or an ERR_PTR() value
270  * on failure.
271  */
272 handle_t *journal_start(journal_t *journal, int nblocks)
273 {
274         handle_t *handle = journal_current_handle();
275         int err;
276
277         if (!journal)
278                 return ERR_PTR(-EROFS);
279
280         if (handle) {
281                 J_ASSERT(handle->h_transaction->t_journal == journal);
282                 handle->h_ref++;
283                 return handle;
284         }
285
286         handle = new_handle(nblocks);
287         if (!handle)
288                 return ERR_PTR(-ENOMEM);
289
290         current->journal_info = handle;
291
292         err = start_this_handle(journal, handle);
293         if (err < 0) {
294                 jbd_free_handle(handle);
295                 current->journal_info = NULL;
296                 handle = ERR_PTR(err);
297         }
298         return handle;
299 }
300
301 /**
302  * int journal_extend() - extend buffer credits.
303  * @handle:  handle to 'extend'
304  * @nblocks: nr blocks to try to extend by.
305  *
306  * Some transactions, such as large extends and truncates, can be done
307  * atomically all at once or in several stages.  The operation requests
308  * a credit for a number of buffer modications in advance, but can
309  * extend its credit if it needs more.
310  *
311  * journal_extend tries to give the running handle more buffer credits.
312  * It does not guarantee that allocation - this is a best-effort only.
313  * The calling process MUST be able to deal cleanly with a failure to
314  * extend here.
315  *
316  * Return 0 on success, non-zero on failure.
317  *
318  * return code < 0 implies an error
319  * return code > 0 implies normal transaction-full status.
320  */
321 int journal_extend(handle_t *handle, int nblocks)
322 {
323         transaction_t *transaction = handle->h_transaction;
324         journal_t *journal = transaction->t_journal;
325         int result;
326         int wanted;
327
328         result = -EIO;
329         if (is_handle_aborted(handle))
330                 goto out;
331
332         result = 1;
333
334         spin_lock(&journal->j_state_lock);
335
336         /* Don't extend a locked-down transaction! */
337         if (handle->h_transaction->t_state != T_RUNNING) {
338                 jbd_debug(3, "denied handle %p %d blocks: "
339                           "transaction not running\n", handle, nblocks);
340                 goto error_out;
341         }
342
343         spin_lock(&transaction->t_handle_lock);
344         wanted = transaction->t_outstanding_credits + nblocks;
345
346         if (wanted > journal->j_max_transaction_buffers) {
347                 jbd_debug(3, "denied handle %p %d blocks: "
348                           "transaction too large\n", handle, nblocks);
349                 goto unlock;
350         }
351
352         if (wanted > __log_space_left(journal)) {
353                 jbd_debug(3, "denied handle %p %d blocks: "
354                           "insufficient log space\n", handle, nblocks);
355                 goto unlock;
356         }
357
358         handle->h_buffer_credits += nblocks;
359         transaction->t_outstanding_credits += nblocks;
360         result = 0;
361
362         jbd_debug(3, "extended handle %p by %d\n", handle, nblocks);
363 unlock:
364         spin_unlock(&transaction->t_handle_lock);
365 error_out:
366         spin_unlock(&journal->j_state_lock);
367 out:
368         return result;
369 }
370
371
372 /**
373  * int journal_restart() - restart a handle.
374  * @handle:  handle to restart
375  * @nblocks: nr credits requested
376  *
377  * Restart a handle for a multi-transaction filesystem
378  * operation.
379  *
380  * If the journal_extend() call above fails to grant new buffer credits
381  * to a running handle, a call to journal_restart will commit the
382  * handle's transaction so far and reattach the handle to a new
383  * transaction capabable of guaranteeing the requested number of
384  * credits.
385  */
386
387 int journal_restart(handle_t *handle, int nblocks)
388 {
389         transaction_t *transaction = handle->h_transaction;
390         journal_t *journal = transaction->t_journal;
391         int ret;
392
393         /* If we've had an abort of any type, don't even think about
394          * actually doing the restart! */
395         if (is_handle_aborted(handle))
396                 return 0;
397
398         /*
399          * First unlink the handle from its current transaction, and start the
400          * commit on that.
401          */
402         J_ASSERT(transaction->t_updates > 0);
403         J_ASSERT(journal_current_handle() == handle);
404
405         spin_lock(&journal->j_state_lock);
406         spin_lock(&transaction->t_handle_lock);
407         transaction->t_outstanding_credits -= handle->h_buffer_credits;
408         transaction->t_updates--;
409
410         if (!transaction->t_updates)
411                 wake_up(&journal->j_wait_updates);
412         spin_unlock(&transaction->t_handle_lock);
413
414         jbd_debug(2, "restarting handle %p\n", handle);
415         __log_start_commit(journal, transaction->t_tid);
416         spin_unlock(&journal->j_state_lock);
417
418         lock_map_release(&handle->h_lockdep_map);
419         handle->h_buffer_credits = nblocks;
420         ret = start_this_handle(journal, handle);
421         return ret;
422 }
423
424
425 /**
426  * void journal_lock_updates () - establish a transaction barrier.
427  * @journal:  Journal to establish a barrier on.
428  *
429  * This locks out any further updates from being started, and blocks
430  * until all existing updates have completed, returning only once the
431  * journal is in a quiescent state with no updates running.
432  *
433  * The journal lock should not be held on entry.
434  */
435 void journal_lock_updates(journal_t *journal)
436 {
437         DEFINE_WAIT(wait);
438
439         spin_lock(&journal->j_state_lock);
440         ++journal->j_barrier_count;
441
442         /* Wait until there are no running updates */
443         while (1) {
444                 transaction_t *transaction = journal->j_running_transaction;
445
446                 if (!transaction)
447                         break;
448
449                 spin_lock(&transaction->t_handle_lock);
450                 if (!transaction->t_updates) {
451                         spin_unlock(&transaction->t_handle_lock);
452                         break;
453                 }
454                 prepare_to_wait(&journal->j_wait_updates, &wait,
455                                 TASK_UNINTERRUPTIBLE);
456                 spin_unlock(&transaction->t_handle_lock);
457                 spin_unlock(&journal->j_state_lock);
458                 schedule();
459                 finish_wait(&journal->j_wait_updates, &wait);
460                 spin_lock(&journal->j_state_lock);
461         }
462         spin_unlock(&journal->j_state_lock);
463
464         /*
465          * We have now established a barrier against other normal updates, but
466          * we also need to barrier against other journal_lock_updates() calls
467          * to make sure that we serialise special journal-locked operations
468          * too.
469          */
470         mutex_lock(&journal->j_barrier);
471 }
472
473 /**
474  * void journal_unlock_updates (journal_t* journal) - release barrier
475  * @journal:  Journal to release the barrier on.
476  *
477  * Release a transaction barrier obtained with journal_lock_updates().
478  *
479  * Should be called without the journal lock held.
480  */
481 void journal_unlock_updates (journal_t *journal)
482 {
483         J_ASSERT(journal->j_barrier_count != 0);
484
485         mutex_unlock(&journal->j_barrier);
486         spin_lock(&journal->j_state_lock);
487         --journal->j_barrier_count;
488         spin_unlock(&journal->j_state_lock);
489         wake_up(&journal->j_wait_transaction_locked);
490 }
491
492 static void warn_dirty_buffer(struct buffer_head *bh)
493 {
494         char b[BDEVNAME_SIZE];
495
496         printk(KERN_WARNING
497                "JBD: Spotted dirty metadata buffer (dev = %s, blocknr = %llu). "
498                "There's a risk of filesystem corruption in case of system "
499                "crash.\n",
500                bdevname(bh->b_bdev, b), (unsigned long long)bh->b_blocknr);
501 }
502
503 /*
504  * If the buffer is already part of the current transaction, then there
505  * is nothing we need to do.  If it is already part of a prior
506  * transaction which we are still committing to disk, then we need to
507  * make sure that we do not overwrite the old copy: we do copy-out to
508  * preserve the copy going to disk.  We also account the buffer against
509  * the handle's metadata buffer credits (unless the buffer is already
510  * part of the transaction, that is).
511  *
512  */
513 static int
514 do_get_write_access(handle_t *handle, struct journal_head *jh,
515                         int force_copy)
516 {
517         struct buffer_head *bh;
518         transaction_t *transaction;
519         journal_t *journal;
520         int error;
521         char *frozen_buffer = NULL;
522         int need_copy = 0;
523
524         if (is_handle_aborted(handle))
525                 return -EROFS;
526
527         transaction = handle->h_transaction;
528         journal = transaction->t_journal;
529
530         jbd_debug(5, "journal_head %p, force_copy %d\n", jh, force_copy);
531
532         JBUFFER_TRACE(jh, "entry");
533 repeat:
534         bh = jh2bh(jh);
535
536         /* @@@ Need to check for errors here at some point. */
537
538         lock_buffer(bh);
539         jbd_lock_bh_state(bh);
540
541         /* We now hold the buffer lock so it is safe to query the buffer
542          * state.  Is the buffer dirty?
543          *
544          * If so, there are two possibilities.  The buffer may be
545          * non-journaled, and undergoing a quite legitimate writeback.
546          * Otherwise, it is journaled, and we don't expect dirty buffers
547          * in that state (the buffers should be marked JBD_Dirty
548          * instead.)  So either the IO is being done under our own
549          * control and this is a bug, or it's a third party IO such as
550          * dump(8) (which may leave the buffer scheduled for read ---
551          * ie. locked but not dirty) or tune2fs (which may actually have
552          * the buffer dirtied, ugh.)  */
553
554         if (buffer_dirty(bh)) {
555                 /*
556                  * First question: is this buffer already part of the current
557                  * transaction or the existing committing transaction?
558                  */
559                 if (jh->b_transaction) {
560                         J_ASSERT_JH(jh,
561                                 jh->b_transaction == transaction ||
562                                 jh->b_transaction ==
563                                         journal->j_committing_transaction);
564                         if (jh->b_next_transaction)
565                                 J_ASSERT_JH(jh, jh->b_next_transaction ==
566                                                         transaction);
567                         warn_dirty_buffer(bh);
568                 }
569                 /*
570                  * In any case we need to clean the dirty flag and we must
571                  * do it under the buffer lock to be sure we don't race
572                  * with running write-out.
573                  */
574                 JBUFFER_TRACE(jh, "Journalling dirty buffer");
575                 clear_buffer_dirty(bh);
576                 set_buffer_jbddirty(bh);
577         }
578
579         unlock_buffer(bh);
580
581         error = -EROFS;
582         if (is_handle_aborted(handle)) {
583                 jbd_unlock_bh_state(bh);
584                 goto out;
585         }
586         error = 0;
587
588         /*
589          * The buffer is already part of this transaction if b_transaction or
590          * b_next_transaction points to it
591          */
592         if (jh->b_transaction == transaction ||
593             jh->b_next_transaction == transaction)
594                 goto done;
595
596         /*
597          * this is the first time this transaction is touching this buffer,
598          * reset the modified flag
599          */
600         jh->b_modified = 0;
601
602         /*
603          * If there is already a copy-out version of this buffer, then we don't
604          * need to make another one
605          */
606         if (jh->b_frozen_data) {
607                 JBUFFER_TRACE(jh, "has frozen data");
608                 J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
609                 jh->b_next_transaction = transaction;
610                 goto done;
611         }
612
613         /* Is there data here we need to preserve? */
614
615         if (jh->b_transaction && jh->b_transaction != transaction) {
616                 JBUFFER_TRACE(jh, "owned by older transaction");
617                 J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
618                 J_ASSERT_JH(jh, jh->b_transaction ==
619                                         journal->j_committing_transaction);
620
621                 /* There is one case we have to be very careful about.
622                  * If the committing transaction is currently writing
623                  * this buffer out to disk and has NOT made a copy-out,
624                  * then we cannot modify the buffer contents at all
625                  * right now.  The essence of copy-out is that it is the
626                  * extra copy, not the primary copy, which gets
627                  * journaled.  If the primary copy is already going to
628                  * disk then we cannot do copy-out here. */
629
630                 if (jh->b_jlist == BJ_Shadow) {
631                         DEFINE_WAIT_BIT(wait, &bh->b_state, BH_Unshadow);
632                         wait_queue_head_t *wqh;
633
634                         wqh = bit_waitqueue(&bh->b_state, BH_Unshadow);
635
636                         JBUFFER_TRACE(jh, "on shadow: sleep");
637                         jbd_unlock_bh_state(bh);
638                         /* commit wakes up all shadow buffers after IO */
639                         for ( ; ; ) {
640                                 prepare_to_wait(wqh, &wait.wait,
641                                                 TASK_UNINTERRUPTIBLE);
642                                 if (jh->b_jlist != BJ_Shadow)
643                                         break;
644                                 schedule();
645                         }
646                         finish_wait(wqh, &wait.wait);
647                         goto repeat;
648                 }
649
650                 /* Only do the copy if the currently-owning transaction
651                  * still needs it.  If it is on the Forget list, the
652                  * committing transaction is past that stage.  The
653                  * buffer had better remain locked during the kmalloc,
654                  * but that should be true --- we hold the journal lock
655                  * still and the buffer is already on the BUF_JOURNAL
656                  * list so won't be flushed.
657                  *
658                  * Subtle point, though: if this is a get_undo_access,
659                  * then we will be relying on the frozen_data to contain
660                  * the new value of the committed_data record after the
661                  * transaction, so we HAVE to force the frozen_data copy
662                  * in that case. */
663
664                 if (jh->b_jlist != BJ_Forget || force_copy) {
665                         JBUFFER_TRACE(jh, "generate frozen data");
666                         if (!frozen_buffer) {
667                                 JBUFFER_TRACE(jh, "allocate memory for buffer");
668                                 jbd_unlock_bh_state(bh);
669                                 frozen_buffer =
670                                         jbd_alloc(jh2bh(jh)->b_size,
671                                                          GFP_NOFS);
672                                 if (!frozen_buffer) {
673                                         printk(KERN_EMERG
674                                                "%s: OOM for frozen_buffer\n",
675                                                __func__);
676                                         JBUFFER_TRACE(jh, "oom!");
677                                         error = -ENOMEM;
678                                         jbd_lock_bh_state(bh);
679                                         goto done;
680                                 }
681                                 goto repeat;
682                         }
683                         jh->b_frozen_data = frozen_buffer;
684                         frozen_buffer = NULL;
685                         need_copy = 1;
686                 }
687                 jh->b_next_transaction = transaction;
688         }
689
690
691         /*
692          * Finally, if the buffer is not journaled right now, we need to make
693          * sure it doesn't get written to disk before the caller actually
694          * commits the new data
695          */
696         if (!jh->b_transaction) {
697                 JBUFFER_TRACE(jh, "no transaction");
698                 J_ASSERT_JH(jh, !jh->b_next_transaction);
699                 jh->b_transaction = transaction;
700                 JBUFFER_TRACE(jh, "file as BJ_Reserved");
701                 spin_lock(&journal->j_list_lock);
702                 __journal_file_buffer(jh, transaction, BJ_Reserved);
703                 spin_unlock(&journal->j_list_lock);
704         }
705
706 done:
707         if (need_copy) {
708                 struct page *page;
709                 int offset;
710                 char *source;
711
712                 J_EXPECT_JH(jh, buffer_uptodate(jh2bh(jh)),
713                             "Possible IO failure.\n");
714                 page = jh2bh(jh)->b_page;
715                 offset = offset_in_page(jh2bh(jh)->b_data);
716                 source = kmap_atomic(page, KM_USER0);
717                 memcpy(jh->b_frozen_data, source+offset, jh2bh(jh)->b_size);
718                 kunmap_atomic(source, KM_USER0);
719         }
720         jbd_unlock_bh_state(bh);
721
722         /*
723          * If we are about to journal a buffer, then any revoke pending on it is
724          * no longer valid
725          */
726         journal_cancel_revoke(handle, jh);
727
728 out:
729         if (unlikely(frozen_buffer))    /* It's usually NULL */
730                 jbd_free(frozen_buffer, bh->b_size);
731
732         JBUFFER_TRACE(jh, "exit");
733         return error;
734 }
735
736 /**
737  * int journal_get_write_access() - notify intent to modify a buffer for metadata (not data) update.
738  * @handle: transaction to add buffer modifications to
739  * @bh:     bh to be used for metadata writes
740  *
741  * Returns an error code or 0 on success.
742  *
743  * In full data journalling mode the buffer may be of type BJ_AsyncData,
744  * because we're write()ing a buffer which is also part of a shared mapping.
745  */
746
747 int journal_get_write_access(handle_t *handle, struct buffer_head *bh)
748 {
749         struct journal_head *jh = journal_add_journal_head(bh);
750         int rc;
751
752         /* We do not want to get caught playing with fields which the
753          * log thread also manipulates.  Make sure that the buffer
754          * completes any outstanding IO before proceeding. */
755         rc = do_get_write_access(handle, jh, 0);
756         journal_put_journal_head(jh);
757         return rc;
758 }
759
760
761 /*
762  * When the user wants to journal a newly created buffer_head
763  * (ie. getblk() returned a new buffer and we are going to populate it
764  * manually rather than reading off disk), then we need to keep the
765  * buffer_head locked until it has been completely filled with new
766  * data.  In this case, we should be able to make the assertion that
767  * the bh is not already part of an existing transaction.
768  *
769  * The buffer should already be locked by the caller by this point.
770  * There is no lock ranking violation: it was a newly created,
771  * unlocked buffer beforehand. */
772
773 /**
774  * int journal_get_create_access () - notify intent to use newly created bh
775  * @handle: transaction to new buffer to
776  * @bh: new buffer.
777  *
778  * Call this if you create a new bh.
779  */
780 int journal_get_create_access(handle_t *handle, struct buffer_head *bh)
781 {
782         transaction_t *transaction = handle->h_transaction;
783         journal_t *journal = transaction->t_journal;
784         struct journal_head *jh = journal_add_journal_head(bh);
785         int err;
786
787         jbd_debug(5, "journal_head %p\n", jh);
788         err = -EROFS;
789         if (is_handle_aborted(handle))
790                 goto out;
791         err = 0;
792
793         JBUFFER_TRACE(jh, "entry");
794         /*
795          * The buffer may already belong to this transaction due to pre-zeroing
796          * in the filesystem's new_block code.  It may also be on the previous,
797          * committing transaction's lists, but it HAS to be in Forget state in
798          * that case: the transaction must have deleted the buffer for it to be
799          * reused here.
800          */
801         jbd_lock_bh_state(bh);
802         spin_lock(&journal->j_list_lock);
803         J_ASSERT_JH(jh, (jh->b_transaction == transaction ||
804                 jh->b_transaction == NULL ||
805                 (jh->b_transaction == journal->j_committing_transaction &&
806                           jh->b_jlist == BJ_Forget)));
807
808         J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
809         J_ASSERT_JH(jh, buffer_locked(jh2bh(jh)));
810
811         if (jh->b_transaction == NULL) {
812                 /*
813                  * Previous journal_forget() could have left the buffer
814                  * with jbddirty bit set because it was being committed. When
815                  * the commit finished, we've filed the buffer for
816                  * checkpointing and marked it dirty. Now we are reallocating
817                  * the buffer so the transaction freeing it must have
818                  * committed and so it's safe to clear the dirty bit.
819                  */
820                 clear_buffer_dirty(jh2bh(jh));
821                 jh->b_transaction = transaction;
822
823                 /* first access by this transaction */
824                 jh->b_modified = 0;
825
826                 JBUFFER_TRACE(jh, "file as BJ_Reserved");
827                 __journal_file_buffer(jh, transaction, BJ_Reserved);
828         } else if (jh->b_transaction == journal->j_committing_transaction) {
829                 /* first access by this transaction */
830                 jh->b_modified = 0;
831
832                 JBUFFER_TRACE(jh, "set next transaction");
833                 jh->b_next_transaction = transaction;
834         }
835         spin_unlock(&journal->j_list_lock);
836         jbd_unlock_bh_state(bh);
837
838         /*
839          * akpm: I added this.  ext3_alloc_branch can pick up new indirect
840          * blocks which contain freed but then revoked metadata.  We need
841          * to cancel the revoke in case we end up freeing it yet again
842          * and the reallocating as data - this would cause a second revoke,
843          * which hits an assertion error.
844          */
845         JBUFFER_TRACE(jh, "cancelling revoke");
846         journal_cancel_revoke(handle, jh);
847 out:
848         journal_put_journal_head(jh);
849         return err;
850 }
851
852 /**
853  * int journal_get_undo_access() - Notify intent to modify metadata with non-rewindable consequences
854  * @handle: transaction
855  * @bh: buffer to undo
856  *
857  * Sometimes there is a need to distinguish between metadata which has
858  * been committed to disk and that which has not.  The ext3fs code uses
859  * this for freeing and allocating space, we have to make sure that we
860  * do not reuse freed space until the deallocation has been committed,
861  * since if we overwrote that space we would make the delete
862  * un-rewindable in case of a crash.
863  *
864  * To deal with that, journal_get_undo_access requests write access to a
865  * buffer for parts of non-rewindable operations such as delete
866  * operations on the bitmaps.  The journaling code must keep a copy of
867  * the buffer's contents prior to the undo_access call until such time
868  * as we know that the buffer has definitely been committed to disk.
869  *
870  * We never need to know which transaction the committed data is part
871  * of, buffers touched here are guaranteed to be dirtied later and so
872  * will be committed to a new transaction in due course, at which point
873  * we can discard the old committed data pointer.
874  *
875  * Returns error number or 0 on success.
876  */
877 int journal_get_undo_access(handle_t *handle, struct buffer_head *bh)
878 {
879         int err;
880         struct journal_head *jh = journal_add_journal_head(bh);
881         char *committed_data = NULL;
882
883         JBUFFER_TRACE(jh, "entry");
884
885         /*
886          * Do this first --- it can drop the journal lock, so we want to
887          * make sure that obtaining the committed_data is done
888          * atomically wrt. completion of any outstanding commits.
889          */
890         err = do_get_write_access(handle, jh, 1);
891         if (err)
892                 goto out;
893
894 repeat:
895         if (!jh->b_committed_data) {
896                 committed_data = jbd_alloc(jh2bh(jh)->b_size, GFP_NOFS);
897                 if (!committed_data) {
898                         printk(KERN_EMERG "%s: No memory for committed data\n",
899                                 __func__);
900                         err = -ENOMEM;
901                         goto out;
902                 }
903         }
904
905         jbd_lock_bh_state(bh);
906         if (!jh->b_committed_data) {
907                 /* Copy out the current buffer contents into the
908                  * preserved, committed copy. */
909                 JBUFFER_TRACE(jh, "generate b_committed data");
910                 if (!committed_data) {
911                         jbd_unlock_bh_state(bh);
912                         goto repeat;
913                 }
914
915                 jh->b_committed_data = committed_data;
916                 committed_data = NULL;
917                 memcpy(jh->b_committed_data, bh->b_data, bh->b_size);
918         }
919         jbd_unlock_bh_state(bh);
920 out:
921         journal_put_journal_head(jh);
922         if (unlikely(committed_data))
923                 jbd_free(committed_data, bh->b_size);
924         return err;
925 }
926
927 /**
928  * int journal_dirty_data() - mark a buffer as containing dirty data to be flushed
929  * @handle: transaction
930  * @bh: bufferhead to mark
931  *
932  * Description:
933  * Mark a buffer as containing dirty data which needs to be flushed before
934  * we can commit the current transaction.
935  *
936  * The buffer is placed on the transaction's data list and is marked as
937  * belonging to the transaction.
938  *
939  * Returns error number or 0 on success.
940  *
941  * journal_dirty_data() can be called via page_launder->ext3_writepage
942  * by kswapd.
943  */
944 int journal_dirty_data(handle_t *handle, struct buffer_head *bh)
945 {
946         journal_t *journal = handle->h_transaction->t_journal;
947         int need_brelse = 0;
948         struct journal_head *jh;
949         int ret = 0;
950
951         if (is_handle_aborted(handle))
952                 return ret;
953
954         jh = journal_add_journal_head(bh);
955         JBUFFER_TRACE(jh, "entry");
956
957         /*
958          * The buffer could *already* be dirty.  Writeout can start
959          * at any time.
960          */
961         jbd_debug(4, "jh: %p, tid:%d\n", jh, handle->h_transaction->t_tid);
962
963         /*
964          * What if the buffer is already part of a running transaction?
965          *
966          * There are two cases:
967          * 1) It is part of the current running transaction.  Refile it,
968          *    just in case we have allocated it as metadata, deallocated
969          *    it, then reallocated it as data.
970          * 2) It is part of the previous, still-committing transaction.
971          *    If all we want to do is to guarantee that the buffer will be
972          *    written to disk before this new transaction commits, then
973          *    being sure that the *previous* transaction has this same
974          *    property is sufficient for us!  Just leave it on its old
975          *    transaction.
976          *
977          * In case (2), the buffer must not already exist as metadata
978          * --- that would violate write ordering (a transaction is free
979          * to write its data at any point, even before the previous
980          * committing transaction has committed).  The caller must
981          * never, ever allow this to happen: there's nothing we can do
982          * about it in this layer.
983          */
984         jbd_lock_bh_state(bh);
985         spin_lock(&journal->j_list_lock);
986
987         /* Now that we have bh_state locked, are we really still mapped? */
988         if (!buffer_mapped(bh)) {
989                 JBUFFER_TRACE(jh, "unmapped buffer, bailing out");
990                 goto no_journal;
991         }
992
993         if (jh->b_transaction) {
994                 JBUFFER_TRACE(jh, "has transaction");
995                 if (jh->b_transaction != handle->h_transaction) {
996                         JBUFFER_TRACE(jh, "belongs to older transaction");
997                         J_ASSERT_JH(jh, jh->b_transaction ==
998                                         journal->j_committing_transaction);
999
1000                         /* @@@ IS THIS TRUE  ? */
1001                         /*
1002                          * Not any more.  Scenario: someone does a write()
1003                          * in data=journal mode.  The buffer's transaction has
1004                          * moved into commit.  Then someone does another
1005                          * write() to the file.  We do the frozen data copyout
1006                          * and set b_next_transaction to point to j_running_t.
1007                          * And while we're in that state, someone does a
1008                          * writepage() in an attempt to pageout the same area
1009                          * of the file via a shared mapping.  At present that
1010                          * calls journal_dirty_data(), and we get right here.
1011                          * It may be too late to journal the data.  Simply
1012                          * falling through to the next test will suffice: the
1013                          * data will be dirty and wil be checkpointed.  The
1014                          * ordering comments in the next comment block still
1015                          * apply.
1016                          */
1017                         //J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
1018
1019                         /*
1020                          * If we're journalling data, and this buffer was
1021                          * subject to a write(), it could be metadata, forget
1022                          * or shadow against the committing transaction.  Now,
1023                          * someone has dirtied the same darn page via a mapping
1024                          * and it is being writepage()'d.
1025                          * We *could* just steal the page from commit, with some
1026                          * fancy locking there.  Instead, we just skip it -
1027                          * don't tie the page's buffers to the new transaction
1028                          * at all.
1029                          * Implication: if we crash before the writepage() data
1030                          * is written into the filesystem, recovery will replay
1031                          * the write() data.
1032                          */
1033                         if (jh->b_jlist != BJ_None &&
1034                                         jh->b_jlist != BJ_SyncData &&
1035                                         jh->b_jlist != BJ_Locked) {
1036                                 JBUFFER_TRACE(jh, "Not stealing");
1037                                 goto no_journal;
1038                         }
1039
1040                         /*
1041                          * This buffer may be undergoing writeout in commit.  We
1042                          * can't return from here and let the caller dirty it
1043                          * again because that can cause the write-out loop in
1044                          * commit to never terminate.
1045                          */
1046                         if (buffer_dirty(bh)) {
1047                                 get_bh(bh);
1048                                 spin_unlock(&journal->j_list_lock);
1049                                 jbd_unlock_bh_state(bh);
1050                                 need_brelse = 1;
1051                                 sync_dirty_buffer(bh);
1052                                 jbd_lock_bh_state(bh);
1053                                 spin_lock(&journal->j_list_lock);
1054                                 /* Since we dropped the lock... */
1055                                 if (!buffer_mapped(bh)) {
1056                                         JBUFFER_TRACE(jh, "buffer got unmapped");
1057                                         goto no_journal;
1058                                 }
1059                                 /* The buffer may become locked again at any
1060                                    time if it is redirtied */
1061                         }
1062
1063                         /*
1064                          * We cannot remove the buffer with io error from the
1065                          * committing transaction, because otherwise it would
1066                          * miss the error and the commit would not abort.
1067                          */
1068                         if (unlikely(!buffer_uptodate(bh))) {
1069                                 ret = -EIO;
1070                                 goto no_journal;
1071                         }
1072
1073                         if (jh->b_transaction != NULL) {
1074                                 JBUFFER_TRACE(jh, "unfile from commit");
1075                                 __journal_temp_unlink_buffer(jh);
1076                                 /* It still points to the committing
1077                                  * transaction; move it to this one so
1078                                  * that the refile assert checks are
1079                                  * happy. */
1080                                 jh->b_transaction = handle->h_transaction;
1081                         }
1082                         /* The buffer will be refiled below */
1083
1084                 }
1085                 /*
1086                  * Special case --- the buffer might actually have been
1087                  * allocated and then immediately deallocated in the previous,
1088                  * committing transaction, so might still be left on that
1089                  * transaction's metadata lists.
1090                  */
1091                 if (jh->b_jlist != BJ_SyncData && jh->b_jlist != BJ_Locked) {
1092                         JBUFFER_TRACE(jh, "not on correct data list: unfile");
1093                         J_ASSERT_JH(jh, jh->b_jlist != BJ_Shadow);
1094                         __journal_temp_unlink_buffer(jh);
1095                         jh->b_transaction = handle->h_transaction;
1096                         JBUFFER_TRACE(jh, "file as data");
1097                         __journal_file_buffer(jh, handle->h_transaction,
1098                                                 BJ_SyncData);
1099                 }
1100         } else {
1101                 JBUFFER_TRACE(jh, "not on a transaction");
1102                 __journal_file_buffer(jh, handle->h_transaction, BJ_SyncData);
1103         }
1104 no_journal:
1105         spin_unlock(&journal->j_list_lock);
1106         jbd_unlock_bh_state(bh);
1107         if (need_brelse) {
1108                 BUFFER_TRACE(bh, "brelse");
1109                 __brelse(bh);
1110         }
1111         JBUFFER_TRACE(jh, "exit");
1112         journal_put_journal_head(jh);
1113         return ret;
1114 }
1115
1116 /**
1117  * int journal_dirty_metadata() - mark a buffer as containing dirty metadata
1118  * @handle: transaction to add buffer to.
1119  * @bh: buffer to mark
1120  *
1121  * Mark dirty metadata which needs to be journaled as part of the current
1122  * transaction.
1123  *
1124  * The buffer is placed on the transaction's metadata list and is marked
1125  * as belonging to the transaction.
1126  *
1127  * Returns error number or 0 on success.
1128  *
1129  * Special care needs to be taken if the buffer already belongs to the
1130  * current committing transaction (in which case we should have frozen
1131  * data present for that commit).  In that case, we don't relink the
1132  * buffer: that only gets done when the old transaction finally
1133  * completes its commit.
1134  */
1135 int journal_dirty_metadata(handle_t *handle, struct buffer_head *bh)
1136 {
1137         transaction_t *transaction = handle->h_transaction;
1138         journal_t *journal = transaction->t_journal;
1139         struct journal_head *jh = bh2jh(bh);
1140
1141         jbd_debug(5, "journal_head %p\n", jh);
1142         JBUFFER_TRACE(jh, "entry");
1143         if (is_handle_aborted(handle))
1144                 goto out;
1145
1146         jbd_lock_bh_state(bh);
1147
1148         if (jh->b_modified == 0) {
1149                 /*
1150                  * This buffer's got modified and becoming part
1151                  * of the transaction. This needs to be done
1152                  * once a transaction -bzzz
1153                  */
1154                 jh->b_modified = 1;
1155                 J_ASSERT_JH(jh, handle->h_buffer_credits > 0);
1156                 handle->h_buffer_credits--;
1157         }
1158
1159         /*
1160          * fastpath, to avoid expensive locking.  If this buffer is already
1161          * on the running transaction's metadata list there is nothing to do.
1162          * Nobody can take it off again because there is a handle open.
1163          * I _think_ we're OK here with SMP barriers - a mistaken decision will
1164          * result in this test being false, so we go in and take the locks.
1165          */
1166         if (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) {
1167                 JBUFFER_TRACE(jh, "fastpath");
1168                 J_ASSERT_JH(jh, jh->b_transaction ==
1169                                         journal->j_running_transaction);
1170                 goto out_unlock_bh;
1171         }
1172
1173         set_buffer_jbddirty(bh);
1174
1175         /*
1176          * Metadata already on the current transaction list doesn't
1177          * need to be filed.  Metadata on another transaction's list must
1178          * be committing, and will be refiled once the commit completes:
1179          * leave it alone for now.
1180          */
1181         if (jh->b_transaction != transaction) {
1182                 JBUFFER_TRACE(jh, "already on other transaction");
1183                 J_ASSERT_JH(jh, jh->b_transaction ==
1184                                         journal->j_committing_transaction);
1185                 J_ASSERT_JH(jh, jh->b_next_transaction == transaction);
1186                 /* And this case is illegal: we can't reuse another
1187                  * transaction's data buffer, ever. */
1188                 goto out_unlock_bh;
1189         }
1190
1191         /* That test should have eliminated the following case: */
1192         J_ASSERT_JH(jh, jh->b_frozen_data == NULL);
1193
1194         JBUFFER_TRACE(jh, "file as BJ_Metadata");
1195         spin_lock(&journal->j_list_lock);
1196         __journal_file_buffer(jh, handle->h_transaction, BJ_Metadata);
1197         spin_unlock(&journal->j_list_lock);
1198 out_unlock_bh:
1199         jbd_unlock_bh_state(bh);
1200 out:
1201         JBUFFER_TRACE(jh, "exit");
1202         return 0;
1203 }
1204
1205 /*
1206  * journal_release_buffer: undo a get_write_access without any buffer
1207  * updates, if the update decided in the end that it didn't need access.
1208  *
1209  */
1210 void
1211 journal_release_buffer(handle_t *handle, struct buffer_head *bh)
1212 {
1213         BUFFER_TRACE(bh, "entry");
1214 }
1215
1216 /**
1217  * void journal_forget() - bforget() for potentially-journaled buffers.
1218  * @handle: transaction handle
1219  * @bh:     bh to 'forget'
1220  *
1221  * We can only do the bforget if there are no commits pending against the
1222  * buffer.  If the buffer is dirty in the current running transaction we
1223  * can safely unlink it.
1224  *
1225  * bh may not be a journalled buffer at all - it may be a non-JBD
1226  * buffer which came off the hashtable.  Check for this.
1227  *
1228  * Decrements bh->b_count by one.
1229  *
1230  * Allow this call even if the handle has aborted --- it may be part of
1231  * the caller's cleanup after an abort.
1232  */
1233 int journal_forget (handle_t *handle, struct buffer_head *bh)
1234 {
1235         transaction_t *transaction = handle->h_transaction;
1236         journal_t *journal = transaction->t_journal;
1237         struct journal_head *jh;
1238         int drop_reserve = 0;
1239         int err = 0;
1240         int was_modified = 0;
1241
1242         BUFFER_TRACE(bh, "entry");
1243
1244         jbd_lock_bh_state(bh);
1245         spin_lock(&journal->j_list_lock);
1246
1247         if (!buffer_jbd(bh))
1248                 goto not_jbd;
1249         jh = bh2jh(bh);
1250
1251         /* Critical error: attempting to delete a bitmap buffer, maybe?
1252          * Don't do any jbd operations, and return an error. */
1253         if (!J_EXPECT_JH(jh, !jh->b_committed_data,
1254                          "inconsistent data on disk")) {
1255                 err = -EIO;
1256                 goto not_jbd;
1257         }
1258
1259         /* keep track of wether or not this transaction modified us */
1260         was_modified = jh->b_modified;
1261
1262         /*
1263          * The buffer's going from the transaction, we must drop
1264          * all references -bzzz
1265          */
1266         jh->b_modified = 0;
1267
1268         if (jh->b_transaction == handle->h_transaction) {
1269                 J_ASSERT_JH(jh, !jh->b_frozen_data);
1270
1271                 /* If we are forgetting a buffer which is already part
1272                  * of this transaction, then we can just drop it from
1273                  * the transaction immediately. */
1274                 clear_buffer_dirty(bh);
1275                 clear_buffer_jbddirty(bh);
1276
1277                 JBUFFER_TRACE(jh, "belongs to current transaction: unfile");
1278
1279                 /*
1280                  * we only want to drop a reference if this transaction
1281                  * modified the buffer
1282                  */
1283                 if (was_modified)
1284                         drop_reserve = 1;
1285
1286                 /*
1287                  * We are no longer going to journal this buffer.
1288                  * However, the commit of this transaction is still
1289                  * important to the buffer: the delete that we are now
1290                  * processing might obsolete an old log entry, so by
1291                  * committing, we can satisfy the buffer's checkpoint.
1292                  *
1293                  * So, if we have a checkpoint on the buffer, we should
1294                  * now refile the buffer on our BJ_Forget list so that
1295                  * we know to remove the checkpoint after we commit.
1296                  */
1297
1298                 if (jh->b_cp_transaction) {
1299                         __journal_temp_unlink_buffer(jh);
1300                         __journal_file_buffer(jh, transaction, BJ_Forget);
1301                 } else {
1302                         __journal_unfile_buffer(jh);
1303                         journal_remove_journal_head(bh);
1304                         __brelse(bh);
1305                         if (!buffer_jbd(bh)) {
1306                                 spin_unlock(&journal->j_list_lock);
1307                                 jbd_unlock_bh_state(bh);
1308                                 __bforget(bh);
1309                                 goto drop;
1310                         }
1311                 }
1312         } else if (jh->b_transaction) {
1313                 J_ASSERT_JH(jh, (jh->b_transaction ==
1314                                  journal->j_committing_transaction));
1315                 /* However, if the buffer is still owned by a prior
1316                  * (committing) transaction, we can't drop it yet... */
1317                 JBUFFER_TRACE(jh, "belongs to older transaction");
1318                 /* ... but we CAN drop it from the new transaction if we
1319                  * have also modified it since the original commit. */
1320
1321                 if (jh->b_next_transaction) {
1322                         J_ASSERT(jh->b_next_transaction == transaction);
1323                         jh->b_next_transaction = NULL;
1324
1325                         /*
1326                          * only drop a reference if this transaction modified
1327                          * the buffer
1328                          */
1329                         if (was_modified)
1330                                 drop_reserve = 1;
1331                 }
1332         }
1333
1334 not_jbd:
1335         spin_unlock(&journal->j_list_lock);
1336         jbd_unlock_bh_state(bh);
1337         __brelse(bh);
1338 drop:
1339         if (drop_reserve) {
1340                 /* no need to reserve log space for this block -bzzz */
1341                 handle->h_buffer_credits++;
1342         }
1343         return err;
1344 }
1345
1346 /**
1347  * int journal_stop() - complete a transaction
1348  * @handle: tranaction to complete.
1349  *
1350  * All done for a particular handle.
1351  *
1352  * There is not much action needed here.  We just return any remaining
1353  * buffer credits to the transaction and remove the handle.  The only
1354  * complication is that we need to start a commit operation if the
1355  * filesystem is marked for synchronous update.
1356  *
1357  * journal_stop itself will not usually return an error, but it may
1358  * do so in unusual circumstances.  In particular, expect it to
1359  * return -EIO if a journal_abort has been executed since the
1360  * transaction began.
1361  */
1362 int journal_stop(handle_t *handle)
1363 {
1364         transaction_t *transaction = handle->h_transaction;
1365         journal_t *journal = transaction->t_journal;
1366         int err;
1367         pid_t pid;
1368
1369         J_ASSERT(journal_current_handle() == handle);
1370
1371         if (is_handle_aborted(handle))
1372                 err = -EIO;
1373         else {
1374                 J_ASSERT(transaction->t_updates > 0);
1375                 err = 0;
1376         }
1377
1378         if (--handle->h_ref > 0) {
1379                 jbd_debug(4, "h_ref %d -> %d\n", handle->h_ref + 1,
1380                           handle->h_ref);
1381                 return err;
1382         }
1383
1384         jbd_debug(4, "Handle %p going down\n", handle);
1385
1386         /*
1387          * Implement synchronous transaction batching.  If the handle
1388          * was synchronous, don't force a commit immediately.  Let's
1389          * yield and let another thread piggyback onto this transaction.
1390          * Keep doing that while new threads continue to arrive.
1391          * It doesn't cost much - we're about to run a commit and sleep
1392          * on IO anyway.  Speeds up many-threaded, many-dir operations
1393          * by 30x or more...
1394          *
1395          * We try and optimize the sleep time against what the underlying disk
1396          * can do, instead of having a static sleep time.  This is useful for
1397          * the case where our storage is so fast that it is more optimal to go
1398          * ahead and force a flush and wait for the transaction to be committed
1399          * than it is to wait for an arbitrary amount of time for new writers to
1400          * join the transaction.  We achieve this by measuring how long it takes
1401          * to commit a transaction, and compare it with how long this
1402          * transaction has been running, and if run time < commit time then we
1403          * sleep for the delta and commit.  This greatly helps super fast disks
1404          * that would see slowdowns as more threads started doing fsyncs.
1405          *
1406          * But don't do this if this process was the most recent one to
1407          * perform a synchronous write.  We do this to detect the case where a
1408          * single process is doing a stream of sync writes.  No point in waiting
1409          * for joiners in that case.
1410          */
1411         pid = current->pid;
1412         if (handle->h_sync && journal->j_last_sync_writer != pid) {
1413                 u64 commit_time, trans_time;
1414
1415                 journal->j_last_sync_writer = pid;
1416
1417                 spin_lock(&journal->j_state_lock);
1418                 commit_time = journal->j_average_commit_time;
1419                 spin_unlock(&journal->j_state_lock);
1420
1421                 trans_time = ktime_to_ns(ktime_sub(ktime_get(),
1422                                                    transaction->t_start_time));
1423
1424                 commit_time = min_t(u64, commit_time,
1425                                     1000*jiffies_to_usecs(1));
1426
1427                 if (trans_time < commit_time) {
1428                         ktime_t expires = ktime_add_ns(ktime_get(),
1429                                                        commit_time);
1430                         set_current_state(TASK_UNINTERRUPTIBLE);
1431                         schedule_hrtimeout(&expires, HRTIMER_MODE_ABS);
1432                 }
1433         }
1434
1435         if (handle->h_sync)
1436                 transaction->t_synchronous_commit = 1;
1437         current->journal_info = NULL;
1438         spin_lock(&journal->j_state_lock);
1439         spin_lock(&transaction->t_handle_lock);
1440         transaction->t_outstanding_credits -= handle->h_buffer_credits;
1441         transaction->t_updates--;
1442         if (!transaction->t_updates) {
1443                 wake_up(&journal->j_wait_updates);
1444                 if (journal->j_barrier_count)
1445                         wake_up(&journal->j_wait_transaction_locked);
1446         }
1447
1448         /*
1449          * If the handle is marked SYNC, we need to set another commit
1450          * going!  We also want to force a commit if the current
1451          * transaction is occupying too much of the log, or if the
1452          * transaction is too old now.
1453          */
1454         if (handle->h_sync ||
1455                         transaction->t_outstanding_credits >
1456                                 journal->j_max_transaction_buffers ||
1457                         time_after_eq(jiffies, transaction->t_expires)) {
1458                 /* Do this even for aborted journals: an abort still
1459                  * completes the commit thread, it just doesn't write
1460                  * anything to disk. */
1461                 tid_t tid = transaction->t_tid;
1462
1463                 spin_unlock(&transaction->t_handle_lock);
1464                 jbd_debug(2, "transaction too old, requesting commit for "
1465                                         "handle %p\n", handle);
1466                 /* This is non-blocking */
1467                 __log_start_commit(journal, transaction->t_tid);
1468                 spin_unlock(&journal->j_state_lock);
1469
1470                 /*
1471                  * Special case: JFS_SYNC synchronous updates require us
1472                  * to wait for the commit to complete.
1473                  */
1474                 if (handle->h_sync && !(current->flags & PF_MEMALLOC))
1475                         err = log_wait_commit(journal, tid);
1476         } else {
1477                 spin_unlock(&transaction->t_handle_lock);
1478                 spin_unlock(&journal->j_state_lock);
1479         }
1480
1481         lock_map_release(&handle->h_lockdep_map);
1482
1483         jbd_free_handle(handle);
1484         return err;
1485 }
1486
1487 /**
1488  * int journal_force_commit() - force any uncommitted transactions
1489  * @journal: journal to force
1490  *
1491  * For synchronous operations: force any uncommitted transactions
1492  * to disk.  May seem kludgy, but it reuses all the handle batching
1493  * code in a very simple manner.
1494  */
1495 int journal_force_commit(journal_t *journal)
1496 {
1497         handle_t *handle;
1498         int ret;
1499
1500         handle = journal_start(journal, 1);
1501         if (IS_ERR(handle)) {
1502                 ret = PTR_ERR(handle);
1503         } else {
1504                 handle->h_sync = 1;
1505                 ret = journal_stop(handle);
1506         }
1507         return ret;
1508 }
1509
1510 /*
1511  *
1512  * List management code snippets: various functions for manipulating the
1513  * transaction buffer lists.
1514  *
1515  */
1516
1517 /*
1518  * Append a buffer to a transaction list, given the transaction's list head
1519  * pointer.
1520  *
1521  * j_list_lock is held.
1522  *
1523  * jbd_lock_bh_state(jh2bh(jh)) is held.
1524  */
1525
1526 static inline void
1527 __blist_add_buffer(struct journal_head **list, struct journal_head *jh)
1528 {
1529         if (!*list) {
1530                 jh->b_tnext = jh->b_tprev = jh;
1531                 *list = jh;
1532         } else {
1533                 /* Insert at the tail of the list to preserve order */
1534                 struct journal_head *first = *list, *last = first->b_tprev;
1535                 jh->b_tprev = last;
1536                 jh->b_tnext = first;
1537                 last->b_tnext = first->b_tprev = jh;
1538         }
1539 }
1540
1541 /*
1542  * Remove a buffer from a transaction list, given the transaction's list
1543  * head pointer.
1544  *
1545  * Called with j_list_lock held, and the journal may not be locked.
1546  *
1547  * jbd_lock_bh_state(jh2bh(jh)) is held.
1548  */
1549
1550 static inline void
1551 __blist_del_buffer(struct journal_head **list, struct journal_head *jh)
1552 {
1553         if (*list == jh) {
1554                 *list = jh->b_tnext;
1555                 if (*list == jh)
1556                         *list = NULL;
1557         }
1558         jh->b_tprev->b_tnext = jh->b_tnext;
1559         jh->b_tnext->b_tprev = jh->b_tprev;
1560 }
1561
1562 /*
1563  * Remove a buffer from the appropriate transaction list.
1564  *
1565  * Note that this function can *change* the value of
1566  * bh->b_transaction->t_sync_datalist, t_buffers, t_forget,
1567  * t_iobuf_list, t_shadow_list, t_log_list or t_reserved_list.  If the caller
1568  * is holding onto a copy of one of thee pointers, it could go bad.
1569  * Generally the caller needs to re-read the pointer from the transaction_t.
1570  *
1571  * Called under j_list_lock.  The journal may not be locked.
1572  */
1573 static void __journal_temp_unlink_buffer(struct journal_head *jh)
1574 {
1575         struct journal_head **list = NULL;
1576         transaction_t *transaction;
1577         struct buffer_head *bh = jh2bh(jh);
1578
1579         J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
1580         transaction = jh->b_transaction;
1581         if (transaction)
1582                 assert_spin_locked(&transaction->t_journal->j_list_lock);
1583
1584         J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
1585         if (jh->b_jlist != BJ_None)
1586                 J_ASSERT_JH(jh, transaction != NULL);
1587
1588         switch (jh->b_jlist) {
1589         case BJ_None:
1590                 return;
1591         case BJ_SyncData:
1592                 list = &transaction->t_sync_datalist;
1593                 break;
1594         case BJ_Metadata:
1595                 transaction->t_nr_buffers--;
1596                 J_ASSERT_JH(jh, transaction->t_nr_buffers >= 0);
1597                 list = &transaction->t_buffers;
1598                 break;
1599         case BJ_Forget:
1600                 list = &transaction->t_forget;
1601                 break;
1602         case BJ_IO:
1603                 list = &transaction->t_iobuf_list;
1604                 break;
1605         case BJ_Shadow:
1606                 list = &transaction->t_shadow_list;
1607                 break;
1608         case BJ_LogCtl:
1609                 list = &transaction->t_log_list;
1610                 break;
1611         case BJ_Reserved:
1612                 list = &transaction->t_reserved_list;
1613                 break;
1614         case BJ_Locked:
1615                 list = &transaction->t_locked_list;
1616                 break;
1617         }
1618
1619         __blist_del_buffer(list, jh);
1620         jh->b_jlist = BJ_None;
1621         if (test_clear_buffer_jbddirty(bh))
1622                 mark_buffer_dirty(bh);  /* Expose it to the VM */
1623 }
1624
1625 void __journal_unfile_buffer(struct journal_head *jh)
1626 {
1627         __journal_temp_unlink_buffer(jh);
1628         jh->b_transaction = NULL;
1629 }
1630
1631 void journal_unfile_buffer(journal_t *journal, struct journal_head *jh)
1632 {
1633         jbd_lock_bh_state(jh2bh(jh));
1634         spin_lock(&journal->j_list_lock);
1635         __journal_unfile_buffer(jh);
1636         spin_unlock(&journal->j_list_lock);
1637         jbd_unlock_bh_state(jh2bh(jh));
1638 }
1639
1640 /*
1641  * Called from journal_try_to_free_buffers().
1642  *
1643  * Called under jbd_lock_bh_state(bh)
1644  */
1645 static void
1646 __journal_try_to_free_buffer(journal_t *journal, struct buffer_head *bh)
1647 {
1648         struct journal_head *jh;
1649
1650         jh = bh2jh(bh);
1651
1652         if (buffer_locked(bh) || buffer_dirty(bh))
1653                 goto out;
1654
1655         if (jh->b_next_transaction != NULL)
1656                 goto out;
1657
1658         spin_lock(&journal->j_list_lock);
1659         if (jh->b_transaction != NULL && jh->b_cp_transaction == NULL) {
1660                 if (jh->b_jlist == BJ_SyncData || jh->b_jlist == BJ_Locked) {
1661                         /* A written-back ordered data buffer */
1662                         JBUFFER_TRACE(jh, "release data");
1663                         __journal_unfile_buffer(jh);
1664                         journal_remove_journal_head(bh);
1665                         __brelse(bh);
1666                 }
1667         } else if (jh->b_cp_transaction != NULL && jh->b_transaction == NULL) {
1668                 /* written-back checkpointed metadata buffer */
1669                 if (jh->b_jlist == BJ_None) {
1670                         JBUFFER_TRACE(jh, "remove from checkpoint list");
1671                         __journal_remove_checkpoint(jh);
1672                         journal_remove_journal_head(bh);
1673                         __brelse(bh);
1674                 }
1675         }
1676         spin_unlock(&journal->j_list_lock);
1677 out:
1678         return;
1679 }
1680
1681 /**
1682  * int journal_try_to_free_buffers() - try to free page buffers.
1683  * @journal: journal for operation
1684  * @page: to try and free
1685  * @gfp_mask: we use the mask to detect how hard should we try to release
1686  * buffers. If __GFP_WAIT and __GFP_FS is set, we wait for commit code to
1687  * release the buffers.
1688  *
1689  *
1690  * For all the buffers on this page,
1691  * if they are fully written out ordered data, move them onto BUF_CLEAN
1692  * so try_to_free_buffers() can reap them.
1693  *
1694  * This function returns non-zero if we wish try_to_free_buffers()
1695  * to be called. We do this if the page is releasable by try_to_free_buffers().
1696  * We also do it if the page has locked or dirty buffers and the caller wants
1697  * us to perform sync or async writeout.
1698  *
1699  * This complicates JBD locking somewhat.  We aren't protected by the
1700  * BKL here.  We wish to remove the buffer from its committing or
1701  * running transaction's ->t_datalist via __journal_unfile_buffer.
1702  *
1703  * This may *change* the value of transaction_t->t_datalist, so anyone
1704  * who looks at t_datalist needs to lock against this function.
1705  *
1706  * Even worse, someone may be doing a journal_dirty_data on this
1707  * buffer.  So we need to lock against that.  journal_dirty_data()
1708  * will come out of the lock with the buffer dirty, which makes it
1709  * ineligible for release here.
1710  *
1711  * Who else is affected by this?  hmm...  Really the only contender
1712  * is do_get_write_access() - it could be looking at the buffer while
1713  * journal_try_to_free_buffer() is changing its state.  But that
1714  * cannot happen because we never reallocate freed data as metadata
1715  * while the data is part of a transaction.  Yes?
1716  *
1717  * Return 0 on failure, 1 on success
1718  */
1719 int journal_try_to_free_buffers(journal_t *journal,
1720                                 struct page *page, gfp_t gfp_mask)
1721 {
1722         struct buffer_head *head;
1723         struct buffer_head *bh;
1724         int ret = 0;
1725
1726         J_ASSERT(PageLocked(page));
1727
1728         head = page_buffers(page);
1729         bh = head;
1730         do {
1731                 struct journal_head *jh;
1732
1733                 /*
1734                  * We take our own ref against the journal_head here to avoid
1735                  * having to add tons of locking around each instance of
1736                  * journal_remove_journal_head() and journal_put_journal_head().
1737                  */
1738                 jh = journal_grab_journal_head(bh);
1739                 if (!jh)
1740                         continue;
1741
1742                 jbd_lock_bh_state(bh);
1743                 __journal_try_to_free_buffer(journal, bh);
1744                 journal_put_journal_head(jh);
1745                 jbd_unlock_bh_state(bh);
1746                 if (buffer_jbd(bh))
1747                         goto busy;
1748         } while ((bh = bh->b_this_page) != head);
1749
1750         ret = try_to_free_buffers(page);
1751
1752 busy:
1753         return ret;
1754 }
1755
1756 /*
1757  * This buffer is no longer needed.  If it is on an older transaction's
1758  * checkpoint list we need to record it on this transaction's forget list
1759  * to pin this buffer (and hence its checkpointing transaction) down until
1760  * this transaction commits.  If the buffer isn't on a checkpoint list, we
1761  * release it.
1762  * Returns non-zero if JBD no longer has an interest in the buffer.
1763  *
1764  * Called under j_list_lock.
1765  *
1766  * Called under jbd_lock_bh_state(bh).
1767  */
1768 static int __dispose_buffer(struct journal_head *jh, transaction_t *transaction)
1769 {
1770         int may_free = 1;
1771         struct buffer_head *bh = jh2bh(jh);
1772
1773         __journal_unfile_buffer(jh);
1774
1775         if (jh->b_cp_transaction) {
1776                 JBUFFER_TRACE(jh, "on running+cp transaction");
1777                 /*
1778                  * We don't want to write the buffer anymore, clear the
1779                  * bit so that we don't confuse checks in
1780                  * __journal_file_buffer
1781                  */
1782                 clear_buffer_dirty(bh);
1783                 __journal_file_buffer(jh, transaction, BJ_Forget);
1784                 may_free = 0;
1785         } else {
1786                 JBUFFER_TRACE(jh, "on running transaction");
1787                 journal_remove_journal_head(bh);
1788                 __brelse(bh);
1789         }
1790         return may_free;
1791 }
1792
1793 /*
1794  * journal_invalidatepage
1795  *
1796  * This code is tricky.  It has a number of cases to deal with.
1797  *
1798  * There are two invariants which this code relies on:
1799  *
1800  * i_size must be updated on disk before we start calling invalidatepage on the
1801  * data.
1802  *
1803  *  This is done in ext3 by defining an ext3_setattr method which
1804  *  updates i_size before truncate gets going.  By maintaining this
1805  *  invariant, we can be sure that it is safe to throw away any buffers
1806  *  attached to the current transaction: once the transaction commits,
1807  *  we know that the data will not be needed.
1808  *
1809  *  Note however that we can *not* throw away data belonging to the
1810  *  previous, committing transaction!
1811  *
1812  * Any disk blocks which *are* part of the previous, committing
1813  * transaction (and which therefore cannot be discarded immediately) are
1814  * not going to be reused in the new running transaction
1815  *
1816  *  The bitmap committed_data images guarantee this: any block which is
1817  *  allocated in one transaction and removed in the next will be marked
1818  *  as in-use in the committed_data bitmap, so cannot be reused until
1819  *  the next transaction to delete the block commits.  This means that
1820  *  leaving committing buffers dirty is quite safe: the disk blocks
1821  *  cannot be reallocated to a different file and so buffer aliasing is
1822  *  not possible.
1823  *
1824  *
1825  * The above applies mainly to ordered data mode.  In writeback mode we
1826  * don't make guarantees about the order in which data hits disk --- in
1827  * particular we don't guarantee that new dirty data is flushed before
1828  * transaction commit --- so it is always safe just to discard data
1829  * immediately in that mode.  --sct
1830  */
1831
1832 /*
1833  * The journal_unmap_buffer helper function returns zero if the buffer
1834  * concerned remains pinned as an anonymous buffer belonging to an older
1835  * transaction.
1836  *
1837  * We're outside-transaction here.  Either or both of j_running_transaction
1838  * and j_committing_transaction may be NULL.
1839  */
1840 static int journal_unmap_buffer(journal_t *journal, struct buffer_head *bh)
1841 {
1842         transaction_t *transaction;
1843         struct journal_head *jh;
1844         int may_free = 1;
1845         int ret;
1846
1847         BUFFER_TRACE(bh, "entry");
1848
1849         /*
1850          * It is safe to proceed here without the j_list_lock because the
1851          * buffers cannot be stolen by try_to_free_buffers as long as we are
1852          * holding the page lock. --sct
1853          */
1854
1855         if (!buffer_jbd(bh))
1856                 goto zap_buffer_unlocked;
1857
1858         spin_lock(&journal->j_state_lock);
1859         jbd_lock_bh_state(bh);
1860         spin_lock(&journal->j_list_lock);
1861
1862         jh = journal_grab_journal_head(bh);
1863         if (!jh)
1864                 goto zap_buffer_no_jh;
1865
1866         /*
1867          * We cannot remove the buffer from checkpoint lists until the
1868          * transaction adding inode to orphan list (let's call it T)
1869          * is committed.  Otherwise if the transaction changing the
1870          * buffer would be cleaned from the journal before T is
1871          * committed, a crash will cause that the correct contents of
1872          * the buffer will be lost.  On the other hand we have to
1873          * clear the buffer dirty bit at latest at the moment when the
1874          * transaction marking the buffer as freed in the filesystem
1875          * structures is committed because from that moment on the
1876          * buffer can be reallocated and used by a different page.
1877          * Since the block hasn't been freed yet but the inode has
1878          * already been added to orphan list, it is safe for us to add
1879          * the buffer to BJ_Forget list of the newest transaction.
1880          */
1881         transaction = jh->b_transaction;
1882         if (transaction == NULL) {
1883                 /* First case: not on any transaction.  If it
1884                  * has no checkpoint link, then we can zap it:
1885                  * it's a writeback-mode buffer so we don't care
1886                  * if it hits disk safely. */
1887                 if (!jh->b_cp_transaction) {
1888                         JBUFFER_TRACE(jh, "not on any transaction: zap");
1889                         goto zap_buffer;
1890                 }
1891
1892                 if (!buffer_dirty(bh)) {
1893                         /* bdflush has written it.  We can drop it now */
1894                         goto zap_buffer;
1895                 }
1896
1897                 /* OK, it must be in the journal but still not
1898                  * written fully to disk: it's metadata or
1899                  * journaled data... */
1900
1901                 if (journal->j_running_transaction) {
1902                         /* ... and once the current transaction has
1903                          * committed, the buffer won't be needed any
1904                          * longer. */
1905                         JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget");
1906                         ret = __dispose_buffer(jh,
1907                                         journal->j_running_transaction);
1908                         journal_put_journal_head(jh);
1909                         spin_unlock(&journal->j_list_lock);
1910                         jbd_unlock_bh_state(bh);
1911                         spin_unlock(&journal->j_state_lock);
1912                         return ret;
1913                 } else {
1914                         /* There is no currently-running transaction. So the
1915                          * orphan record which we wrote for this file must have
1916                          * passed into commit.  We must attach this buffer to
1917                          * the committing transaction, if it exists. */
1918                         if (journal->j_committing_transaction) {
1919                                 JBUFFER_TRACE(jh, "give to committing trans");
1920                                 ret = __dispose_buffer(jh,
1921                                         journal->j_committing_transaction);
1922                                 journal_put_journal_head(jh);
1923                                 spin_unlock(&journal->j_list_lock);
1924                                 jbd_unlock_bh_state(bh);
1925                                 spin_unlock(&journal->j_state_lock);
1926                                 return ret;
1927                         } else {
1928                                 /* The orphan record's transaction has
1929                                  * committed.  We can cleanse this buffer */
1930                                 clear_buffer_jbddirty(bh);
1931                                 goto zap_buffer;
1932                         }
1933                 }
1934         } else if (transaction == journal->j_committing_transaction) {
1935                 JBUFFER_TRACE(jh, "on committing transaction");
1936                 if (jh->b_jlist == BJ_Locked) {
1937                         /*
1938                          * The buffer is on the committing transaction's locked
1939                          * list.  We have the buffer locked, so I/O has
1940                          * completed.  So we can nail the buffer now.
1941                          */
1942                         may_free = __dispose_buffer(jh, transaction);
1943                         goto zap_buffer;
1944                 }
1945                 /*
1946                  * The buffer is committing, we simply cannot touch
1947                  * it. So we just set j_next_transaction to the
1948                  * running transaction (if there is one) and mark
1949                  * buffer as freed so that commit code knows it should
1950                  * clear dirty bits when it is done with the buffer.
1951                  */
1952                 set_buffer_freed(bh);
1953                 if (journal->j_running_transaction && buffer_jbddirty(bh))
1954                         jh->b_next_transaction = journal->j_running_transaction;
1955                 journal_put_journal_head(jh);
1956                 spin_unlock(&journal->j_list_lock);
1957                 jbd_unlock_bh_state(bh);
1958                 spin_unlock(&journal->j_state_lock);
1959                 return 0;
1960         } else {
1961                 /* Good, the buffer belongs to the running transaction.
1962                  * We are writing our own transaction's data, not any
1963                  * previous one's, so it is safe to throw it away
1964                  * (remember that we expect the filesystem to have set
1965                  * i_size already for this truncate so recovery will not
1966                  * expose the disk blocks we are discarding here.) */
1967                 J_ASSERT_JH(jh, transaction == journal->j_running_transaction);
1968                 JBUFFER_TRACE(jh, "on running transaction");
1969                 may_free = __dispose_buffer(jh, transaction);
1970         }
1971
1972 zap_buffer:
1973         journal_put_journal_head(jh);
1974 zap_buffer_no_jh:
1975         spin_unlock(&journal->j_list_lock);
1976         jbd_unlock_bh_state(bh);
1977         spin_unlock(&journal->j_state_lock);
1978 zap_buffer_unlocked:
1979         clear_buffer_dirty(bh);
1980         J_ASSERT_BH(bh, !buffer_jbddirty(bh));
1981         clear_buffer_mapped(bh);
1982         clear_buffer_req(bh);
1983         clear_buffer_new(bh);
1984         bh->b_bdev = NULL;
1985         return may_free;
1986 }
1987
1988 /**
1989  * void journal_invalidatepage() - invalidate a journal page
1990  * @journal: journal to use for flush
1991  * @page:    page to flush
1992  * @offset:  length of page to invalidate.
1993  *
1994  * Reap page buffers containing data after offset in page.
1995  */
1996 void journal_invalidatepage(journal_t *journal,
1997                       struct page *page,
1998                       unsigned long offset)
1999 {
2000         struct buffer_head *head, *bh, *next;
2001         unsigned int curr_off = 0;
2002         int may_free = 1;
2003
2004         if (!PageLocked(page))
2005                 BUG();
2006         if (!page_has_buffers(page))
2007                 return;
2008
2009         /* We will potentially be playing with lists other than just the
2010          * data lists (especially for journaled data mode), so be
2011          * cautious in our locking. */
2012
2013         head = bh = page_buffers(page);
2014         do {
2015                 unsigned int next_off = curr_off + bh->b_size;
2016                 next = bh->b_this_page;
2017
2018                 if (offset <= curr_off) {
2019                         /* This block is wholly outside the truncation point */
2020                         lock_buffer(bh);
2021                         may_free &= journal_unmap_buffer(journal, bh);
2022                         unlock_buffer(bh);
2023                 }
2024                 curr_off = next_off;
2025                 bh = next;
2026
2027         } while (bh != head);
2028
2029         if (!offset) {
2030                 if (may_free && try_to_free_buffers(page))
2031                         J_ASSERT(!page_has_buffers(page));
2032         }
2033 }
2034
2035 /*
2036  * File a buffer on the given transaction list.
2037  */
2038 void __journal_file_buffer(struct journal_head *jh,
2039                         transaction_t *transaction, int jlist)
2040 {
2041         struct journal_head **list = NULL;
2042         int was_dirty = 0;
2043         struct buffer_head *bh = jh2bh(jh);
2044
2045         J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
2046         assert_spin_locked(&transaction->t_journal->j_list_lock);
2047
2048         J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
2049         J_ASSERT_JH(jh, jh->b_transaction == transaction ||
2050                                 jh->b_transaction == NULL);
2051
2052         if (jh->b_transaction && jh->b_jlist == jlist)
2053                 return;
2054
2055         if (jlist == BJ_Metadata || jlist == BJ_Reserved ||
2056             jlist == BJ_Shadow || jlist == BJ_Forget) {
2057                 /*
2058                  * For metadata buffers, we track dirty bit in buffer_jbddirty
2059                  * instead of buffer_dirty. We should not see a dirty bit set
2060                  * here because we clear it in do_get_write_access but e.g.
2061                  * tune2fs can modify the sb and set the dirty bit at any time
2062                  * so we try to gracefully handle that.
2063                  */
2064                 if (buffer_dirty(bh))
2065                         warn_dirty_buffer(bh);
2066                 if (test_clear_buffer_dirty(bh) ||
2067                     test_clear_buffer_jbddirty(bh))
2068                         was_dirty = 1;
2069         }
2070
2071         if (jh->b_transaction)
2072                 __journal_temp_unlink_buffer(jh);
2073         jh->b_transaction = transaction;
2074
2075         switch (jlist) {
2076         case BJ_None:
2077                 J_ASSERT_JH(jh, !jh->b_committed_data);
2078                 J_ASSERT_JH(jh, !jh->b_frozen_data);
2079                 return;
2080         case BJ_SyncData:
2081                 list = &transaction->t_sync_datalist;
2082                 break;
2083         case BJ_Metadata:
2084                 transaction->t_nr_buffers++;
2085                 list = &transaction->t_buffers;
2086                 break;
2087         case BJ_Forget:
2088                 list = &transaction->t_forget;
2089                 break;
2090         case BJ_IO:
2091                 list = &transaction->t_iobuf_list;
2092                 break;
2093         case BJ_Shadow:
2094                 list = &transaction->t_shadow_list;
2095                 break;
2096         case BJ_LogCtl:
2097                 list = &transaction->t_log_list;
2098                 break;
2099         case BJ_Reserved:
2100                 list = &transaction->t_reserved_list;
2101                 break;
2102         case BJ_Locked:
2103                 list =  &transaction->t_locked_list;
2104                 break;
2105         }
2106
2107         __blist_add_buffer(list, jh);
2108         jh->b_jlist = jlist;
2109
2110         if (was_dirty)
2111                 set_buffer_jbddirty(bh);
2112 }
2113
2114 void journal_file_buffer(struct journal_head *jh,
2115                                 transaction_t *transaction, int jlist)
2116 {
2117         jbd_lock_bh_state(jh2bh(jh));
2118         spin_lock(&transaction->t_journal->j_list_lock);
2119         __journal_file_buffer(jh, transaction, jlist);
2120         spin_unlock(&transaction->t_journal->j_list_lock);
2121         jbd_unlock_bh_state(jh2bh(jh));
2122 }
2123
2124 /*
2125  * Remove a buffer from its current buffer list in preparation for
2126  * dropping it from its current transaction entirely.  If the buffer has
2127  * already started to be used by a subsequent transaction, refile the
2128  * buffer on that transaction's metadata list.
2129  *
2130  * Called under journal->j_list_lock
2131  *
2132  * Called under jbd_lock_bh_state(jh2bh(jh))
2133  */
2134 void __journal_refile_buffer(struct journal_head *jh)
2135 {
2136         int was_dirty, jlist;
2137         struct buffer_head *bh = jh2bh(jh);
2138
2139         J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
2140         if (jh->b_transaction)
2141                 assert_spin_locked(&jh->b_transaction->t_journal->j_list_lock);
2142
2143         /* If the buffer is now unused, just drop it. */
2144         if (jh->b_next_transaction == NULL) {
2145                 __journal_unfile_buffer(jh);
2146                 return;
2147         }
2148
2149         /*
2150          * It has been modified by a later transaction: add it to the new
2151          * transaction's metadata list.
2152          */
2153
2154         was_dirty = test_clear_buffer_jbddirty(bh);
2155         __journal_temp_unlink_buffer(jh);
2156         jh->b_transaction = jh->b_next_transaction;
2157         jh->b_next_transaction = NULL;
2158         if (buffer_freed(bh))
2159                 jlist = BJ_Forget;
2160         else if (jh->b_modified)
2161                 jlist = BJ_Metadata;
2162         else
2163                 jlist = BJ_Reserved;
2164         __journal_file_buffer(jh, jh->b_transaction, jlist);
2165         J_ASSERT_JH(jh, jh->b_transaction->t_state == T_RUNNING);
2166
2167         if (was_dirty)
2168                 set_buffer_jbddirty(bh);
2169 }
2170
2171 /*
2172  * For the unlocked version of this call, also make sure that any
2173  * hanging journal_head is cleaned up if necessary.
2174  *
2175  * __journal_refile_buffer is usually called as part of a single locked
2176  * operation on a buffer_head, in which the caller is probably going to
2177  * be hooking the journal_head onto other lists.  In that case it is up
2178  * to the caller to remove the journal_head if necessary.  For the
2179  * unlocked journal_refile_buffer call, the caller isn't going to be
2180  * doing anything else to the buffer so we need to do the cleanup
2181  * ourselves to avoid a jh leak.
2182  *
2183  * *** The journal_head may be freed by this call! ***
2184  */
2185 void journal_refile_buffer(journal_t *journal, struct journal_head *jh)
2186 {
2187         struct buffer_head *bh = jh2bh(jh);
2188
2189         jbd_lock_bh_state(bh);
2190         spin_lock(&journal->j_list_lock);
2191
2192         __journal_refile_buffer(jh);
2193         jbd_unlock_bh_state(bh);
2194         journal_remove_journal_head(bh);
2195
2196         spin_unlock(&journal->j_list_lock);
2197         __brelse(bh);
2198 }