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