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