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