e9428c30862a9857823dedb602e77373b1d3c487
[linux-2.6-microblaze.git] / fs / xfs / xfs_buf_item.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_bit.h"
13 #include "xfs_mount.h"
14 #include "xfs_trans.h"
15 #include "xfs_trans_priv.h"
16 #include "xfs_buf_item.h"
17 #include "xfs_inode.h"
18 #include "xfs_inode_item.h"
19 #include "xfs_quota.h"
20 #include "xfs_dquot_item.h"
21 #include "xfs_dquot.h"
22 #include "xfs_trans_priv.h"
23 #include "xfs_trace.h"
24 #include "xfs_log.h"
25
26
27 kmem_zone_t     *xfs_buf_item_zone;
28
29 static inline struct xfs_buf_log_item *BUF_ITEM(struct xfs_log_item *lip)
30 {
31         return container_of(lip, struct xfs_buf_log_item, bli_item);
32 }
33
34 static void xfs_buf_item_done(struct xfs_buf *bp);
35
36 /* Is this log iovec plausibly large enough to contain the buffer log format? */
37 bool
38 xfs_buf_log_check_iovec(
39         struct xfs_log_iovec            *iovec)
40 {
41         struct xfs_buf_log_format       *blfp = iovec->i_addr;
42         char                            *bmp_end;
43         char                            *item_end;
44
45         if (offsetof(struct xfs_buf_log_format, blf_data_map) > iovec->i_len)
46                 return false;
47
48         item_end = (char *)iovec->i_addr + iovec->i_len;
49         bmp_end = (char *)&blfp->blf_data_map[blfp->blf_map_size];
50         return bmp_end <= item_end;
51 }
52
53 static inline int
54 xfs_buf_log_format_size(
55         struct xfs_buf_log_format *blfp)
56 {
57         return offsetof(struct xfs_buf_log_format, blf_data_map) +
58                         (blfp->blf_map_size * sizeof(blfp->blf_data_map[0]));
59 }
60
61 /*
62  * This returns the number of log iovecs needed to log the
63  * given buf log item.
64  *
65  * It calculates this as 1 iovec for the buf log format structure
66  * and 1 for each stretch of non-contiguous chunks to be logged.
67  * Contiguous chunks are logged in a single iovec.
68  *
69  * If the XFS_BLI_STALE flag has been set, then log nothing.
70  */
71 STATIC void
72 xfs_buf_item_size_segment(
73         struct xfs_buf_log_item         *bip,
74         struct xfs_buf_log_format       *blfp,
75         int                             *nvecs,
76         int                             *nbytes)
77 {
78         struct xfs_buf                  *bp = bip->bli_buf;
79         int                             next_bit;
80         int                             last_bit;
81
82         last_bit = xfs_next_bit(blfp->blf_data_map, blfp->blf_map_size, 0);
83         if (last_bit == -1)
84                 return;
85
86         /*
87          * initial count for a dirty buffer is 2 vectors - the format structure
88          * and the first dirty region.
89          */
90         *nvecs += 2;
91         *nbytes += xfs_buf_log_format_size(blfp) + XFS_BLF_CHUNK;
92
93         while (last_bit != -1) {
94                 /*
95                  * This takes the bit number to start looking from and
96                  * returns the next set bit from there.  It returns -1
97                  * if there are no more bits set or the start bit is
98                  * beyond the end of the bitmap.
99                  */
100                 next_bit = xfs_next_bit(blfp->blf_data_map, blfp->blf_map_size,
101                                         last_bit + 1);
102                 /*
103                  * If we run out of bits, leave the loop,
104                  * else if we find a new set of bits bump the number of vecs,
105                  * else keep scanning the current set of bits.
106                  */
107                 if (next_bit == -1) {
108                         break;
109                 } else if (next_bit != last_bit + 1) {
110                         last_bit = next_bit;
111                         (*nvecs)++;
112                 } else if (xfs_buf_offset(bp, next_bit * XFS_BLF_CHUNK) !=
113                            (xfs_buf_offset(bp, last_bit * XFS_BLF_CHUNK) +
114                             XFS_BLF_CHUNK)) {
115                         last_bit = next_bit;
116                         (*nvecs)++;
117                 } else {
118                         last_bit++;
119                 }
120                 *nbytes += XFS_BLF_CHUNK;
121         }
122 }
123
124 /*
125  * This returns the number of log iovecs needed to log the given buf log item.
126  *
127  * It calculates this as 1 iovec for the buf log format structure and 1 for each
128  * stretch of non-contiguous chunks to be logged.  Contiguous chunks are logged
129  * in a single iovec.
130  *
131  * Discontiguous buffers need a format structure per region that that is being
132  * logged. This makes the changes in the buffer appear to log recovery as though
133  * they came from separate buffers, just like would occur if multiple buffers
134  * were used instead of a single discontiguous buffer. This enables
135  * discontiguous buffers to be in-memory constructs, completely transparent to
136  * what ends up on disk.
137  *
138  * If the XFS_BLI_STALE flag has been set, then log nothing but the buf log
139  * format structures.
140  */
141 STATIC void
142 xfs_buf_item_size(
143         struct xfs_log_item     *lip,
144         int                     *nvecs,
145         int                     *nbytes)
146 {
147         struct xfs_buf_log_item *bip = BUF_ITEM(lip);
148         int                     i;
149
150         ASSERT(atomic_read(&bip->bli_refcount) > 0);
151         if (bip->bli_flags & XFS_BLI_STALE) {
152                 /*
153                  * The buffer is stale, so all we need to log
154                  * is the buf log format structure with the
155                  * cancel flag in it.
156                  */
157                 trace_xfs_buf_item_size_stale(bip);
158                 ASSERT(bip->__bli_format.blf_flags & XFS_BLF_CANCEL);
159                 *nvecs += bip->bli_format_count;
160                 for (i = 0; i < bip->bli_format_count; i++) {
161                         *nbytes += xfs_buf_log_format_size(&bip->bli_formats[i]);
162                 }
163                 return;
164         }
165
166         ASSERT(bip->bli_flags & XFS_BLI_LOGGED);
167
168         if (bip->bli_flags & XFS_BLI_ORDERED) {
169                 /*
170                  * The buffer has been logged just to order it.
171                  * It is not being included in the transaction
172                  * commit, so no vectors are used at all.
173                  */
174                 trace_xfs_buf_item_size_ordered(bip);
175                 *nvecs = XFS_LOG_VEC_ORDERED;
176                 return;
177         }
178
179         /*
180          * the vector count is based on the number of buffer vectors we have
181          * dirty bits in. This will only be greater than one when we have a
182          * compound buffer with more than one segment dirty. Hence for compound
183          * buffers we need to track which segment the dirty bits correspond to,
184          * and when we move from one segment to the next increment the vector
185          * count for the extra buf log format structure that will need to be
186          * written.
187          */
188         for (i = 0; i < bip->bli_format_count; i++) {
189                 xfs_buf_item_size_segment(bip, &bip->bli_formats[i],
190                                           nvecs, nbytes);
191         }
192         trace_xfs_buf_item_size(bip);
193 }
194
195 static inline void
196 xfs_buf_item_copy_iovec(
197         struct xfs_log_vec      *lv,
198         struct xfs_log_iovec    **vecp,
199         struct xfs_buf          *bp,
200         uint                    offset,
201         int                     first_bit,
202         uint                    nbits)
203 {
204         offset += first_bit * XFS_BLF_CHUNK;
205         xlog_copy_iovec(lv, vecp, XLOG_REG_TYPE_BCHUNK,
206                         xfs_buf_offset(bp, offset),
207                         nbits * XFS_BLF_CHUNK);
208 }
209
210 static inline bool
211 xfs_buf_item_straddle(
212         struct xfs_buf          *bp,
213         uint                    offset,
214         int                     next_bit,
215         int                     last_bit)
216 {
217         return xfs_buf_offset(bp, offset + (next_bit << XFS_BLF_SHIFT)) !=
218                 (xfs_buf_offset(bp, offset + (last_bit << XFS_BLF_SHIFT)) +
219                  XFS_BLF_CHUNK);
220 }
221
222 static void
223 xfs_buf_item_format_segment(
224         struct xfs_buf_log_item *bip,
225         struct xfs_log_vec      *lv,
226         struct xfs_log_iovec    **vecp,
227         uint                    offset,
228         struct xfs_buf_log_format *blfp)
229 {
230         struct xfs_buf          *bp = bip->bli_buf;
231         uint                    base_size;
232         int                     first_bit;
233         int                     last_bit;
234         int                     next_bit;
235         uint                    nbits;
236
237         /* copy the flags across from the base format item */
238         blfp->blf_flags = bip->__bli_format.blf_flags;
239
240         /*
241          * Base size is the actual size of the ondisk structure - it reflects
242          * the actual size of the dirty bitmap rather than the size of the in
243          * memory structure.
244          */
245         base_size = xfs_buf_log_format_size(blfp);
246
247         first_bit = xfs_next_bit(blfp->blf_data_map, blfp->blf_map_size, 0);
248         if (!(bip->bli_flags & XFS_BLI_STALE) && first_bit == -1) {
249                 /*
250                  * If the map is not be dirty in the transaction, mark
251                  * the size as zero and do not advance the vector pointer.
252                  */
253                 return;
254         }
255
256         blfp = xlog_copy_iovec(lv, vecp, XLOG_REG_TYPE_BFORMAT, blfp, base_size);
257         blfp->blf_size = 1;
258
259         if (bip->bli_flags & XFS_BLI_STALE) {
260                 /*
261                  * The buffer is stale, so all we need to log
262                  * is the buf log format structure with the
263                  * cancel flag in it.
264                  */
265                 trace_xfs_buf_item_format_stale(bip);
266                 ASSERT(blfp->blf_flags & XFS_BLF_CANCEL);
267                 return;
268         }
269
270
271         /*
272          * Fill in an iovec for each set of contiguous chunks.
273          */
274         last_bit = first_bit;
275         nbits = 1;
276         for (;;) {
277                 /*
278                  * This takes the bit number to start looking from and
279                  * returns the next set bit from there.  It returns -1
280                  * if there are no more bits set or the start bit is
281                  * beyond the end of the bitmap.
282                  */
283                 next_bit = xfs_next_bit(blfp->blf_data_map, blfp->blf_map_size,
284                                         (uint)last_bit + 1);
285                 /*
286                  * If we run out of bits fill in the last iovec and get out of
287                  * the loop.  Else if we start a new set of bits then fill in
288                  * the iovec for the series we were looking at and start
289                  * counting the bits in the new one.  Else we're still in the
290                  * same set of bits so just keep counting and scanning.
291                  */
292                 if (next_bit == -1) {
293                         xfs_buf_item_copy_iovec(lv, vecp, bp, offset,
294                                                 first_bit, nbits);
295                         blfp->blf_size++;
296                         break;
297                 } else if (next_bit != last_bit + 1 ||
298                            xfs_buf_item_straddle(bp, offset, next_bit, last_bit)) {
299                         xfs_buf_item_copy_iovec(lv, vecp, bp, offset,
300                                                 first_bit, nbits);
301                         blfp->blf_size++;
302                         first_bit = next_bit;
303                         last_bit = next_bit;
304                         nbits = 1;
305                 } else {
306                         last_bit++;
307                         nbits++;
308                 }
309         }
310 }
311
312 /*
313  * This is called to fill in the vector of log iovecs for the
314  * given log buf item.  It fills the first entry with a buf log
315  * format structure, and the rest point to contiguous chunks
316  * within the buffer.
317  */
318 STATIC void
319 xfs_buf_item_format(
320         struct xfs_log_item     *lip,
321         struct xfs_log_vec      *lv)
322 {
323         struct xfs_buf_log_item *bip = BUF_ITEM(lip);
324         struct xfs_buf          *bp = bip->bli_buf;
325         struct xfs_log_iovec    *vecp = NULL;
326         uint                    offset = 0;
327         int                     i;
328
329         ASSERT(atomic_read(&bip->bli_refcount) > 0);
330         ASSERT((bip->bli_flags & XFS_BLI_LOGGED) ||
331                (bip->bli_flags & XFS_BLI_STALE));
332         ASSERT((bip->bli_flags & XFS_BLI_STALE) ||
333                (xfs_blft_from_flags(&bip->__bli_format) > XFS_BLFT_UNKNOWN_BUF
334                 && xfs_blft_from_flags(&bip->__bli_format) < XFS_BLFT_MAX_BUF));
335         ASSERT(!(bip->bli_flags & XFS_BLI_ORDERED) ||
336                (bip->bli_flags & XFS_BLI_STALE));
337
338
339         /*
340          * If it is an inode buffer, transfer the in-memory state to the
341          * format flags and clear the in-memory state.
342          *
343          * For buffer based inode allocation, we do not transfer
344          * this state if the inode buffer allocation has not yet been committed
345          * to the log as setting the XFS_BLI_INODE_BUF flag will prevent
346          * correct replay of the inode allocation.
347          *
348          * For icreate item based inode allocation, the buffers aren't written
349          * to the journal during allocation, and hence we should always tag the
350          * buffer as an inode buffer so that the correct unlinked list replay
351          * occurs during recovery.
352          */
353         if (bip->bli_flags & XFS_BLI_INODE_BUF) {
354                 if (xfs_sb_version_has_v3inode(&lip->li_mountp->m_sb) ||
355                     !((bip->bli_flags & XFS_BLI_INODE_ALLOC_BUF) &&
356                       xfs_log_item_in_current_chkpt(lip)))
357                         bip->__bli_format.blf_flags |= XFS_BLF_INODE_BUF;
358                 bip->bli_flags &= ~XFS_BLI_INODE_BUF;
359         }
360
361         for (i = 0; i < bip->bli_format_count; i++) {
362                 xfs_buf_item_format_segment(bip, lv, &vecp, offset,
363                                             &bip->bli_formats[i]);
364                 offset += BBTOB(bp->b_maps[i].bm_len);
365         }
366
367         /*
368          * Check to make sure everything is consistent.
369          */
370         trace_xfs_buf_item_format(bip);
371 }
372
373 /*
374  * This is called to pin the buffer associated with the buf log item in memory
375  * so it cannot be written out.
376  *
377  * We also always take a reference to the buffer log item here so that the bli
378  * is held while the item is pinned in memory. This means that we can
379  * unconditionally drop the reference count a transaction holds when the
380  * transaction is completed.
381  */
382 STATIC void
383 xfs_buf_item_pin(
384         struct xfs_log_item     *lip)
385 {
386         struct xfs_buf_log_item *bip = BUF_ITEM(lip);
387
388         ASSERT(atomic_read(&bip->bli_refcount) > 0);
389         ASSERT((bip->bli_flags & XFS_BLI_LOGGED) ||
390                (bip->bli_flags & XFS_BLI_ORDERED) ||
391                (bip->bli_flags & XFS_BLI_STALE));
392
393         trace_xfs_buf_item_pin(bip);
394
395         atomic_inc(&bip->bli_refcount);
396         atomic_inc(&bip->bli_buf->b_pin_count);
397 }
398
399 /*
400  * This is called to unpin the buffer associated with the buf log
401  * item which was previously pinned with a call to xfs_buf_item_pin().
402  *
403  * Also drop the reference to the buf item for the current transaction.
404  * If the XFS_BLI_STALE flag is set and we are the last reference,
405  * then free up the buf log item and unlock the buffer.
406  *
407  * If the remove flag is set we are called from uncommit in the
408  * forced-shutdown path.  If that is true and the reference count on
409  * the log item is going to drop to zero we need to free the item's
410  * descriptor in the transaction.
411  */
412 STATIC void
413 xfs_buf_item_unpin(
414         struct xfs_log_item     *lip,
415         int                     remove)
416 {
417         struct xfs_buf_log_item *bip = BUF_ITEM(lip);
418         xfs_buf_t               *bp = bip->bli_buf;
419         int                     stale = bip->bli_flags & XFS_BLI_STALE;
420         int                     freed;
421
422         ASSERT(bp->b_log_item == bip);
423         ASSERT(atomic_read(&bip->bli_refcount) > 0);
424
425         trace_xfs_buf_item_unpin(bip);
426
427         freed = atomic_dec_and_test(&bip->bli_refcount);
428
429         if (atomic_dec_and_test(&bp->b_pin_count))
430                 wake_up_all(&bp->b_waiters);
431
432         if (freed && stale) {
433                 ASSERT(bip->bli_flags & XFS_BLI_STALE);
434                 ASSERT(xfs_buf_islocked(bp));
435                 ASSERT(bp->b_flags & XBF_STALE);
436                 ASSERT(bip->__bli_format.blf_flags & XFS_BLF_CANCEL);
437
438                 trace_xfs_buf_item_unpin_stale(bip);
439
440                 if (remove) {
441                         /*
442                          * If we are in a transaction context, we have to
443                          * remove the log item from the transaction as we are
444                          * about to release our reference to the buffer.  If we
445                          * don't, the unlock that occurs later in
446                          * xfs_trans_uncommit() will try to reference the
447                          * buffer which we no longer have a hold on.
448                          */
449                         if (!list_empty(&lip->li_trans))
450                                 xfs_trans_del_item(lip);
451
452                         /*
453                          * Since the transaction no longer refers to the buffer,
454                          * the buffer should no longer refer to the transaction.
455                          */
456                         bp->b_transp = NULL;
457                 }
458
459                 /*
460                  * If we get called here because of an IO error, we may or may
461                  * not have the item on the AIL. xfs_trans_ail_delete() will
462                  * take care of that situation. xfs_trans_ail_delete() drops
463                  * the AIL lock.
464                  */
465                 if (bip->bli_flags & XFS_BLI_STALE_INODE) {
466                         xfs_buf_item_done(bp);
467                         xfs_iflush_done(bp);
468                         ASSERT(list_empty(&bp->b_li_list));
469                 } else {
470                         xfs_trans_ail_delete(lip, SHUTDOWN_LOG_IO_ERROR);
471                         xfs_buf_item_relse(bp);
472                         ASSERT(bp->b_log_item == NULL);
473                 }
474                 xfs_buf_relse(bp);
475         } else if (freed && remove) {
476                 /*
477                  * The buffer must be locked and held by the caller to simulate
478                  * an async I/O failure.
479                  */
480                 xfs_buf_lock(bp);
481                 xfs_buf_hold(bp);
482                 bp->b_flags |= XBF_ASYNC;
483                 xfs_buf_ioend_fail(bp);
484         }
485 }
486
487 STATIC uint
488 xfs_buf_item_push(
489         struct xfs_log_item     *lip,
490         struct list_head        *buffer_list)
491 {
492         struct xfs_buf_log_item *bip = BUF_ITEM(lip);
493         struct xfs_buf          *bp = bip->bli_buf;
494         uint                    rval = XFS_ITEM_SUCCESS;
495
496         if (xfs_buf_ispinned(bp))
497                 return XFS_ITEM_PINNED;
498         if (!xfs_buf_trylock(bp)) {
499                 /*
500                  * If we have just raced with a buffer being pinned and it has
501                  * been marked stale, we could end up stalling until someone else
502                  * issues a log force to unpin the stale buffer. Check for the
503                  * race condition here so xfsaild recognizes the buffer is pinned
504                  * and queues a log force to move it along.
505                  */
506                 if (xfs_buf_ispinned(bp))
507                         return XFS_ITEM_PINNED;
508                 return XFS_ITEM_LOCKED;
509         }
510
511         ASSERT(!(bip->bli_flags & XFS_BLI_STALE));
512
513         trace_xfs_buf_item_push(bip);
514
515         /* has a previous flush failed due to IO errors? */
516         if (bp->b_flags & XBF_WRITE_FAIL) {
517                 xfs_buf_alert_ratelimited(bp, "XFS: Failing async write",
518             "Failing async write on buffer block 0x%llx. Retrying async write.",
519                                           (long long)bp->b_bn);
520         }
521
522         if (!xfs_buf_delwri_queue(bp, buffer_list))
523                 rval = XFS_ITEM_FLUSHING;
524         xfs_buf_unlock(bp);
525         return rval;
526 }
527
528 /*
529  * Drop the buffer log item refcount and take appropriate action. This helper
530  * determines whether the bli must be freed or not, since a decrement to zero
531  * does not necessarily mean the bli is unused.
532  *
533  * Return true if the bli is freed, false otherwise.
534  */
535 bool
536 xfs_buf_item_put(
537         struct xfs_buf_log_item *bip)
538 {
539         struct xfs_log_item     *lip = &bip->bli_item;
540         bool                    aborted;
541         bool                    dirty;
542
543         /* drop the bli ref and return if it wasn't the last one */
544         if (!atomic_dec_and_test(&bip->bli_refcount))
545                 return false;
546
547         /*
548          * We dropped the last ref and must free the item if clean or aborted.
549          * If the bli is dirty and non-aborted, the buffer was clean in the
550          * transaction but still awaiting writeback from previous changes. In
551          * that case, the bli is freed on buffer writeback completion.
552          */
553         aborted = test_bit(XFS_LI_ABORTED, &lip->li_flags) ||
554                   XFS_FORCED_SHUTDOWN(lip->li_mountp);
555         dirty = bip->bli_flags & XFS_BLI_DIRTY;
556         if (dirty && !aborted)
557                 return false;
558
559         /*
560          * The bli is aborted or clean. An aborted item may be in the AIL
561          * regardless of dirty state.  For example, consider an aborted
562          * transaction that invalidated a dirty bli and cleared the dirty
563          * state.
564          */
565         if (aborted)
566                 xfs_trans_ail_delete(lip, 0);
567         xfs_buf_item_relse(bip->bli_buf);
568         return true;
569 }
570
571 /*
572  * Release the buffer associated with the buf log item.  If there is no dirty
573  * logged data associated with the buffer recorded in the buf log item, then
574  * free the buf log item and remove the reference to it in the buffer.
575  *
576  * This call ignores the recursion count.  It is only called when the buffer
577  * should REALLY be unlocked, regardless of the recursion count.
578  *
579  * We unconditionally drop the transaction's reference to the log item. If the
580  * item was logged, then another reference was taken when it was pinned, so we
581  * can safely drop the transaction reference now.  This also allows us to avoid
582  * potential races with the unpin code freeing the bli by not referencing the
583  * bli after we've dropped the reference count.
584  *
585  * If the XFS_BLI_HOLD flag is set in the buf log item, then free the log item
586  * if necessary but do not unlock the buffer.  This is for support of
587  * xfs_trans_bhold(). Make sure the XFS_BLI_HOLD field is cleared if we don't
588  * free the item.
589  */
590 STATIC void
591 xfs_buf_item_release(
592         struct xfs_log_item     *lip)
593 {
594         struct xfs_buf_log_item *bip = BUF_ITEM(lip);
595         struct xfs_buf          *bp = bip->bli_buf;
596         bool                    released;
597         bool                    hold = bip->bli_flags & XFS_BLI_HOLD;
598         bool                    stale = bip->bli_flags & XFS_BLI_STALE;
599 #if defined(DEBUG) || defined(XFS_WARN)
600         bool                    ordered = bip->bli_flags & XFS_BLI_ORDERED;
601         bool                    dirty = bip->bli_flags & XFS_BLI_DIRTY;
602         bool                    aborted = test_bit(XFS_LI_ABORTED,
603                                                    &lip->li_flags);
604 #endif
605
606         trace_xfs_buf_item_release(bip);
607
608         /*
609          * The bli dirty state should match whether the blf has logged segments
610          * except for ordered buffers, where only the bli should be dirty.
611          */
612         ASSERT((!ordered && dirty == xfs_buf_item_dirty_format(bip)) ||
613                (ordered && dirty && !xfs_buf_item_dirty_format(bip)));
614         ASSERT(!stale || (bip->__bli_format.blf_flags & XFS_BLF_CANCEL));
615
616         /*
617          * Clear the buffer's association with this transaction and
618          * per-transaction state from the bli, which has been copied above.
619          */
620         bp->b_transp = NULL;
621         bip->bli_flags &= ~(XFS_BLI_LOGGED | XFS_BLI_HOLD | XFS_BLI_ORDERED);
622
623         /*
624          * Unref the item and unlock the buffer unless held or stale. Stale
625          * buffers remain locked until final unpin unless the bli is freed by
626          * the unref call. The latter implies shutdown because buffer
627          * invalidation dirties the bli and transaction.
628          */
629         released = xfs_buf_item_put(bip);
630         if (hold || (stale && !released))
631                 return;
632         ASSERT(!stale || aborted);
633         xfs_buf_relse(bp);
634 }
635
636 STATIC void
637 xfs_buf_item_committing(
638         struct xfs_log_item     *lip,
639         xfs_lsn_t               commit_lsn)
640 {
641         return xfs_buf_item_release(lip);
642 }
643
644 /*
645  * This is called to find out where the oldest active copy of the
646  * buf log item in the on disk log resides now that the last log
647  * write of it completed at the given lsn.
648  * We always re-log all the dirty data in a buffer, so usually the
649  * latest copy in the on disk log is the only one that matters.  For
650  * those cases we simply return the given lsn.
651  *
652  * The one exception to this is for buffers full of newly allocated
653  * inodes.  These buffers are only relogged with the XFS_BLI_INODE_BUF
654  * flag set, indicating that only the di_next_unlinked fields from the
655  * inodes in the buffers will be replayed during recovery.  If the
656  * original newly allocated inode images have not yet been flushed
657  * when the buffer is so relogged, then we need to make sure that we
658  * keep the old images in the 'active' portion of the log.  We do this
659  * by returning the original lsn of that transaction here rather than
660  * the current one.
661  */
662 STATIC xfs_lsn_t
663 xfs_buf_item_committed(
664         struct xfs_log_item     *lip,
665         xfs_lsn_t               lsn)
666 {
667         struct xfs_buf_log_item *bip = BUF_ITEM(lip);
668
669         trace_xfs_buf_item_committed(bip);
670
671         if ((bip->bli_flags & XFS_BLI_INODE_ALLOC_BUF) && lip->li_lsn != 0)
672                 return lip->li_lsn;
673         return lsn;
674 }
675
676 static const struct xfs_item_ops xfs_buf_item_ops = {
677         .iop_size       = xfs_buf_item_size,
678         .iop_format     = xfs_buf_item_format,
679         .iop_pin        = xfs_buf_item_pin,
680         .iop_unpin      = xfs_buf_item_unpin,
681         .iop_release    = xfs_buf_item_release,
682         .iop_committing = xfs_buf_item_committing,
683         .iop_committed  = xfs_buf_item_committed,
684         .iop_push       = xfs_buf_item_push,
685 };
686
687 STATIC void
688 xfs_buf_item_get_format(
689         struct xfs_buf_log_item *bip,
690         int                     count)
691 {
692         ASSERT(bip->bli_formats == NULL);
693         bip->bli_format_count = count;
694
695         if (count == 1) {
696                 bip->bli_formats = &bip->__bli_format;
697                 return;
698         }
699
700         bip->bli_formats = kmem_zalloc(count * sizeof(struct xfs_buf_log_format),
701                                 0);
702 }
703
704 STATIC void
705 xfs_buf_item_free_format(
706         struct xfs_buf_log_item *bip)
707 {
708         if (bip->bli_formats != &bip->__bli_format) {
709                 kmem_free(bip->bli_formats);
710                 bip->bli_formats = NULL;
711         }
712 }
713
714 /*
715  * Allocate a new buf log item to go with the given buffer.
716  * Set the buffer's b_log_item field to point to the new
717  * buf log item.
718  */
719 int
720 xfs_buf_item_init(
721         struct xfs_buf  *bp,
722         struct xfs_mount *mp)
723 {
724         struct xfs_buf_log_item *bip = bp->b_log_item;
725         int                     chunks;
726         int                     map_size;
727         int                     i;
728
729         /*
730          * Check to see if there is already a buf log item for
731          * this buffer. If we do already have one, there is
732          * nothing to do here so return.
733          */
734         ASSERT(bp->b_mount == mp);
735         if (bip) {
736                 ASSERT(bip->bli_item.li_type == XFS_LI_BUF);
737                 ASSERT(!bp->b_transp);
738                 ASSERT(bip->bli_buf == bp);
739                 return 0;
740         }
741
742         bip = kmem_zone_zalloc(xfs_buf_item_zone, 0);
743         xfs_log_item_init(mp, &bip->bli_item, XFS_LI_BUF, &xfs_buf_item_ops);
744         bip->bli_buf = bp;
745
746         /*
747          * chunks is the number of XFS_BLF_CHUNK size pieces the buffer
748          * can be divided into. Make sure not to truncate any pieces.
749          * map_size is the size of the bitmap needed to describe the
750          * chunks of the buffer.
751          *
752          * Discontiguous buffer support follows the layout of the underlying
753          * buffer. This makes the implementation as simple as possible.
754          */
755         xfs_buf_item_get_format(bip, bp->b_map_count);
756
757         for (i = 0; i < bip->bli_format_count; i++) {
758                 chunks = DIV_ROUND_UP(BBTOB(bp->b_maps[i].bm_len),
759                                       XFS_BLF_CHUNK);
760                 map_size = DIV_ROUND_UP(chunks, NBWORD);
761
762                 if (map_size > XFS_BLF_DATAMAP_SIZE) {
763                         kmem_cache_free(xfs_buf_item_zone, bip);
764                         xfs_err(mp,
765         "buffer item dirty bitmap (%u uints) too small to reflect %u bytes!",
766                                         map_size,
767                                         BBTOB(bp->b_maps[i].bm_len));
768                         return -EFSCORRUPTED;
769                 }
770
771                 bip->bli_formats[i].blf_type = XFS_LI_BUF;
772                 bip->bli_formats[i].blf_blkno = bp->b_maps[i].bm_bn;
773                 bip->bli_formats[i].blf_len = bp->b_maps[i].bm_len;
774                 bip->bli_formats[i].blf_map_size = map_size;
775         }
776
777         bp->b_log_item = bip;
778         xfs_buf_hold(bp);
779         return 0;
780 }
781
782
783 /*
784  * Mark bytes first through last inclusive as dirty in the buf
785  * item's bitmap.
786  */
787 static void
788 xfs_buf_item_log_segment(
789         uint                    first,
790         uint                    last,
791         uint                    *map)
792 {
793         uint            first_bit;
794         uint            last_bit;
795         uint            bits_to_set;
796         uint            bits_set;
797         uint            word_num;
798         uint            *wordp;
799         uint            bit;
800         uint            end_bit;
801         uint            mask;
802
803         ASSERT(first < XFS_BLF_DATAMAP_SIZE * XFS_BLF_CHUNK * NBWORD);
804         ASSERT(last < XFS_BLF_DATAMAP_SIZE * XFS_BLF_CHUNK * NBWORD);
805
806         /*
807          * Convert byte offsets to bit numbers.
808          */
809         first_bit = first >> XFS_BLF_SHIFT;
810         last_bit = last >> XFS_BLF_SHIFT;
811
812         /*
813          * Calculate the total number of bits to be set.
814          */
815         bits_to_set = last_bit - first_bit + 1;
816
817         /*
818          * Get a pointer to the first word in the bitmap
819          * to set a bit in.
820          */
821         word_num = first_bit >> BIT_TO_WORD_SHIFT;
822         wordp = &map[word_num];
823
824         /*
825          * Calculate the starting bit in the first word.
826          */
827         bit = first_bit & (uint)(NBWORD - 1);
828
829         /*
830          * First set any bits in the first word of our range.
831          * If it starts at bit 0 of the word, it will be
832          * set below rather than here.  That is what the variable
833          * bit tells us. The variable bits_set tracks the number
834          * of bits that have been set so far.  End_bit is the number
835          * of the last bit to be set in this word plus one.
836          */
837         if (bit) {
838                 end_bit = min(bit + bits_to_set, (uint)NBWORD);
839                 mask = ((1U << (end_bit - bit)) - 1) << bit;
840                 *wordp |= mask;
841                 wordp++;
842                 bits_set = end_bit - bit;
843         } else {
844                 bits_set = 0;
845         }
846
847         /*
848          * Now set bits a whole word at a time that are between
849          * first_bit and last_bit.
850          */
851         while ((bits_to_set - bits_set) >= NBWORD) {
852                 *wordp = 0xffffffff;
853                 bits_set += NBWORD;
854                 wordp++;
855         }
856
857         /*
858          * Finally, set any bits left to be set in one last partial word.
859          */
860         end_bit = bits_to_set - bits_set;
861         if (end_bit) {
862                 mask = (1U << end_bit) - 1;
863                 *wordp |= mask;
864         }
865 }
866
867 /*
868  * Mark bytes first through last inclusive as dirty in the buf
869  * item's bitmap.
870  */
871 void
872 xfs_buf_item_log(
873         struct xfs_buf_log_item *bip,
874         uint                    first,
875         uint                    last)
876 {
877         int                     i;
878         uint                    start;
879         uint                    end;
880         struct xfs_buf          *bp = bip->bli_buf;
881
882         /*
883          * walk each buffer segment and mark them dirty appropriately.
884          */
885         start = 0;
886         for (i = 0; i < bip->bli_format_count; i++) {
887                 if (start > last)
888                         break;
889                 end = start + BBTOB(bp->b_maps[i].bm_len) - 1;
890
891                 /* skip to the map that includes the first byte to log */
892                 if (first > end) {
893                         start += BBTOB(bp->b_maps[i].bm_len);
894                         continue;
895                 }
896
897                 /*
898                  * Trim the range to this segment and mark it in the bitmap.
899                  * Note that we must convert buffer offsets to segment relative
900                  * offsets (e.g., the first byte of each segment is byte 0 of
901                  * that segment).
902                  */
903                 if (first < start)
904                         first = start;
905                 if (end > last)
906                         end = last;
907                 xfs_buf_item_log_segment(first - start, end - start,
908                                          &bip->bli_formats[i].blf_data_map[0]);
909
910                 start += BBTOB(bp->b_maps[i].bm_len);
911         }
912 }
913
914
915 /*
916  * Return true if the buffer has any ranges logged/dirtied by a transaction,
917  * false otherwise.
918  */
919 bool
920 xfs_buf_item_dirty_format(
921         struct xfs_buf_log_item *bip)
922 {
923         int                     i;
924
925         for (i = 0; i < bip->bli_format_count; i++) {
926                 if (!xfs_bitmap_empty(bip->bli_formats[i].blf_data_map,
927                              bip->bli_formats[i].blf_map_size))
928                         return true;
929         }
930
931         return false;
932 }
933
934 STATIC void
935 xfs_buf_item_free(
936         struct xfs_buf_log_item *bip)
937 {
938         xfs_buf_item_free_format(bip);
939         kmem_free(bip->bli_item.li_lv_shadow);
940         kmem_cache_free(xfs_buf_item_zone, bip);
941 }
942
943 /*
944  * xfs_buf_item_relse() is called when the buf log item is no longer needed.
945  */
946 void
947 xfs_buf_item_relse(
948         xfs_buf_t       *bp)
949 {
950         struct xfs_buf_log_item *bip = bp->b_log_item;
951
952         trace_xfs_buf_item_relse(bp, _RET_IP_);
953         ASSERT(!test_bit(XFS_LI_IN_AIL, &bip->bli_item.li_flags));
954
955         bp->b_log_item = NULL;
956         xfs_buf_rele(bp);
957         xfs_buf_item_free(bip);
958 }
959
960 /*
961  * Decide if we're going to retry the write after a failure, and prepare
962  * the buffer for retrying the write.
963  */
964 static bool
965 xfs_buf_ioerror_fail_without_retry(
966         struct xfs_buf          *bp)
967 {
968         struct xfs_mount        *mp = bp->b_mount;
969         static ulong            lasttime;
970         static xfs_buftarg_t    *lasttarg;
971
972         /*
973          * If we've already decided to shutdown the filesystem because of
974          * I/O errors, there's no point in giving this a retry.
975          */
976         if (XFS_FORCED_SHUTDOWN(mp))
977                 return true;
978
979         if (bp->b_target != lasttarg ||
980             time_after(jiffies, (lasttime + 5*HZ))) {
981                 lasttime = jiffies;
982                 xfs_buf_ioerror_alert(bp, __this_address);
983         }
984         lasttarg = bp->b_target;
985
986         /* synchronous writes will have callers process the error */
987         if (!(bp->b_flags & XBF_ASYNC))
988                 return true;
989         return false;
990 }
991
992 static bool
993 xfs_buf_ioerror_retry(
994         struct xfs_buf          *bp,
995         struct xfs_error_cfg    *cfg)
996 {
997         if ((bp->b_flags & (XBF_STALE | XBF_WRITE_FAIL)) &&
998             bp->b_last_error == bp->b_error)
999                 return false;
1000
1001         bp->b_flags |= (XBF_WRITE | XBF_DONE | XBF_WRITE_FAIL);
1002         bp->b_last_error = bp->b_error;
1003         if (cfg->retry_timeout != XFS_ERR_RETRY_FOREVER &&
1004             !bp->b_first_retry_time)
1005                 bp->b_first_retry_time = jiffies;
1006         return true;
1007 }
1008
1009 /*
1010  * Account for this latest trip around the retry handler, and decide if
1011  * we've failed enough times to constitute a permanent failure.
1012  */
1013 static bool
1014 xfs_buf_ioerror_permanent(
1015         struct xfs_buf          *bp,
1016         struct xfs_error_cfg    *cfg)
1017 {
1018         struct xfs_mount        *mp = bp->b_mount;
1019
1020         if (cfg->max_retries != XFS_ERR_RETRY_FOREVER &&
1021             ++bp->b_retries > cfg->max_retries)
1022                 return true;
1023         if (cfg->retry_timeout != XFS_ERR_RETRY_FOREVER &&
1024             time_after(jiffies, cfg->retry_timeout + bp->b_first_retry_time))
1025                 return true;
1026
1027         /* At unmount we may treat errors differently */
1028         if ((mp->m_flags & XFS_MOUNT_UNMOUNTING) && mp->m_fail_unmount)
1029                 return true;
1030
1031         return false;
1032 }
1033
1034 /*
1035  * On a sync write or shutdown we just want to stale the buffer and let the
1036  * caller handle the error in bp->b_error appropriately.
1037  *
1038  * If the write was asynchronous then no one will be looking for the error.  If
1039  * this is the first failure of this type, clear the error state and write the
1040  * buffer out again. This means we always retry an async write failure at least
1041  * once, but we also need to set the buffer up to behave correctly now for
1042  * repeated failures.
1043  *
1044  * If we get repeated async write failures, then we take action according to the
1045  * error configuration we have been set up to use.
1046  *
1047  * Multi-state return value:
1048  *
1049  * XBF_IOERROR_FINISH: clear IO error retry state and run callback completions
1050  * XBF_IOERROR_DONE: resubmitted immediately, do not run any completions
1051  * XBF_IOERROR_FAIL: transient error, run failure callback completions and then
1052  *    release the buffer
1053  */
1054 enum {
1055         XBF_IOERROR_FINISH,
1056         XBF_IOERROR_DONE,
1057         XBF_IOERROR_FAIL,
1058 };
1059
1060 static int
1061 xfs_buf_iodone_error(
1062         struct xfs_buf          *bp)
1063 {
1064         struct xfs_mount        *mp = bp->b_mount;
1065         struct xfs_error_cfg    *cfg;
1066
1067         if (xfs_buf_ioerror_fail_without_retry(bp))
1068                 goto out_stale;
1069
1070         trace_xfs_buf_item_iodone_async(bp, _RET_IP_);
1071
1072         cfg = xfs_error_get_cfg(mp, XFS_ERR_METADATA, bp->b_error);
1073         if (xfs_buf_ioerror_retry(bp, cfg)) {
1074                 xfs_buf_ioerror(bp, 0);
1075                 xfs_buf_submit(bp);
1076                 return XBF_IOERROR_DONE;
1077         }
1078
1079         /*
1080          * Permanent error - we need to trigger a shutdown if we haven't already
1081          * to indicate that inconsistency will result from this action.
1082          */
1083         if (xfs_buf_ioerror_permanent(bp, cfg)) {
1084                 xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1085                 goto out_stale;
1086         }
1087
1088         /* Still considered a transient error. Caller will schedule retries. */
1089         return XBF_IOERROR_FAIL;
1090
1091 out_stale:
1092         xfs_buf_stale(bp);
1093         bp->b_flags |= XBF_DONE;
1094         trace_xfs_buf_error_relse(bp, _RET_IP_);
1095         return XBF_IOERROR_FINISH;
1096 }
1097
1098 static void
1099 xfs_buf_item_done(
1100         struct xfs_buf          *bp)
1101 {
1102         struct xfs_buf_log_item *bip = bp->b_log_item;
1103
1104         if (!bip)
1105                 return;
1106
1107         /*
1108          * If we are forcibly shutting down, this may well be off the AIL
1109          * already. That's because we simulate the log-committed callbacks to
1110          * unpin these buffers. Or we may never have put this item on AIL
1111          * because of the transaction was aborted forcibly.
1112          * xfs_trans_ail_delete() takes care of these.
1113          *
1114          * Either way, AIL is useless if we're forcing a shutdown.
1115          */
1116         xfs_trans_ail_delete(&bip->bli_item, SHUTDOWN_CORRUPT_INCORE);
1117         bp->b_log_item = NULL;
1118         xfs_buf_item_free(bip);
1119         xfs_buf_rele(bp);
1120 }
1121
1122 static inline void
1123 xfs_buf_clear_ioerror_retry_state(
1124         struct xfs_buf          *bp)
1125 {
1126         bp->b_last_error = 0;
1127         bp->b_retries = 0;
1128         bp->b_first_retry_time = 0;
1129 }
1130
1131 /*
1132  * Inode buffer iodone callback function.
1133  */
1134 void
1135 xfs_buf_inode_iodone(
1136         struct xfs_buf          *bp)
1137 {
1138         if (bp->b_error) {
1139                 struct xfs_log_item *lip;
1140                 int ret = xfs_buf_iodone_error(bp);
1141
1142                 if (ret == XBF_IOERROR_FINISH)
1143                         goto finish_iodone;
1144                 if (ret == XBF_IOERROR_DONE)
1145                         return;
1146                 ASSERT(ret == XBF_IOERROR_FAIL);
1147                 list_for_each_entry(lip, &bp->b_li_list, li_bio_list) {
1148                         set_bit(XFS_LI_FAILED, &lip->li_flags);
1149                 }
1150                 xfs_buf_ioerror(bp, 0);
1151                 xfs_buf_relse(bp);
1152                 return;
1153         }
1154
1155 finish_iodone:
1156         xfs_buf_clear_ioerror_retry_state(bp);
1157         xfs_buf_item_done(bp);
1158         xfs_iflush_done(bp);
1159         xfs_buf_ioend_finish(bp);
1160 }
1161
1162 /*
1163  * Dquot buffer iodone callback function.
1164  */
1165 void
1166 xfs_buf_dquot_iodone(
1167         struct xfs_buf          *bp)
1168 {
1169         if (bp->b_error) {
1170                 struct xfs_log_item *lip;
1171                 int ret = xfs_buf_iodone_error(bp);
1172
1173                 if (ret == XBF_IOERROR_FINISH)
1174                         goto finish_iodone;
1175                 if (ret == XBF_IOERROR_DONE)
1176                         return;
1177                 ASSERT(ret == XBF_IOERROR_FAIL);
1178                 spin_lock(&bp->b_mount->m_ail->ail_lock);
1179                 list_for_each_entry(lip, &bp->b_li_list, li_bio_list) {
1180                         xfs_set_li_failed(lip, bp);
1181                 }
1182                 spin_unlock(&bp->b_mount->m_ail->ail_lock);
1183                 xfs_buf_ioerror(bp, 0);
1184                 xfs_buf_relse(bp);
1185                 return;
1186         }
1187
1188 finish_iodone:
1189         xfs_buf_clear_ioerror_retry_state(bp);
1190         /* a newly allocated dquot buffer might have a log item attached */
1191         xfs_buf_item_done(bp);
1192         xfs_dquot_done(bp);
1193         xfs_buf_ioend_finish(bp);
1194 }
1195
1196 /*
1197  * Dirty buffer iodone callback function.
1198  *
1199  * Note that for things like remote attribute buffers, there may not be a buffer
1200  * log item here, so processing the buffer log item must remain be optional.
1201  */
1202 void
1203 xfs_buf_iodone(
1204         struct xfs_buf          *bp)
1205 {
1206         if (bp->b_error) {
1207                 int ret = xfs_buf_iodone_error(bp);
1208
1209                 if (ret == XBF_IOERROR_FINISH)
1210                         goto finish_iodone;
1211                 if (ret == XBF_IOERROR_DONE)
1212                         return;
1213                 ASSERT(ret == XBF_IOERROR_FAIL);
1214                 ASSERT(list_empty(&bp->b_li_list));
1215                 xfs_buf_ioerror(bp, 0);
1216                 xfs_buf_relse(bp);
1217                 return;
1218         }
1219
1220 finish_iodone:
1221         xfs_buf_clear_ioerror_retry_state(bp);
1222         xfs_buf_item_done(bp);
1223         xfs_buf_ioend_finish(bp);
1224 }