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