xref: /linux/fs/xfs/xfs_buf.c (revision 29a7b2614357393b176ef06ba5bc3ff5afc8df69)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs_platform.h"
7 #include <linux/backing-dev.h>
8 #include <linux/dax.h>
9 
10 #include "xfs_shared.h"
11 #include "xfs_format.h"
12 #include "xfs_log_format.h"
13 #include "xfs_trans_resv.h"
14 #include "xfs_mount.h"
15 #include "xfs_trace.h"
16 #include "xfs_log.h"
17 #include "xfs_log_recover.h"
18 #include "xfs_log_priv.h"
19 #include "xfs_trans.h"
20 #include "xfs_buf_item.h"
21 #include "xfs_errortag.h"
22 #include "xfs_error.h"
23 #include "xfs_ag.h"
24 #include "xfs_buf_mem.h"
25 #include "xfs_notify_failure.h"
26 
27 struct kmem_cache *xfs_buf_cache;
28 
29 /*
30  * Locking orders
31  *
32  * xfs_buf_stale:
33  *	b_sema (caller holds)
34  *	  b_lockref.lock
35  *	    lru_lock
36  *
37  * xfs_buf_rele:
38  *	b_lockref.lock
39  *	  lru_lock
40  *
41  * xfs_buftarg_drain_rele
42  *	lru_lock
43  *	  b_lockref.lock (trylock due to inversion)
44  *
45  * xfs_buftarg_isolate
46  *	lru_lock
47  *	  b_lockref.lock (trylock due to inversion)
48  */
49 
50 static void xfs_buf_submit(struct xfs_buf *bp);
51 static int xfs_buf_iowait(struct xfs_buf *bp);
52 
53 static inline bool xfs_buf_is_uncached(struct xfs_buf *bp)
54 {
55 	return bp->b_rhash_key == XFS_BUF_DADDR_NULL;
56 }
57 
58 /*
59  * When we mark a buffer stale, we remove the buffer from the LRU and clear the
60  * b_lru_ref count so that the buffer is freed immediately when the buffer
61  * reference count falls to zero. If the buffer is already on the LRU, we need
62  * to remove the reference that LRU holds on the buffer.
63  *
64  * This prevents build-up of stale buffers on the LRU.
65  */
66 void
67 xfs_buf_stale(
68 	struct xfs_buf	*bp)
69 {
70 	ASSERT(xfs_buf_islocked(bp));
71 
72 	bp->b_flags |= XBF_STALE;
73 
74 	/*
75 	 * Clear the delwri status so that a delwri queue walker will not
76 	 * flush this buffer to disk now that it is stale. The delwri queue has
77 	 * a reference to the buffer, so this is safe to do.
78 	 */
79 	bp->b_flags &= ~_XBF_DELWRI_Q;
80 
81 	spin_lock(&bp->b_lockref.lock);
82 	atomic_set(&bp->b_lru_ref, 0);
83 	if (!__lockref_is_dead(&bp->b_lockref))
84 		list_lru_del_obj(&bp->b_target->bt_lru, &bp->b_lru);
85 	spin_unlock(&bp->b_lockref.lock);
86 }
87 
88 static void
89 xfs_buf_free_callback(
90 	struct callback_head	*cb)
91 {
92 	struct xfs_buf		*bp = container_of(cb, struct xfs_buf, b_rcu);
93 
94 	if (bp->b_maps != &bp->__b_map)
95 		kfree(bp->b_maps);
96 	kmem_cache_free(xfs_buf_cache, bp);
97 }
98 
99 static void
100 xfs_buf_free(
101 	struct xfs_buf		*bp)
102 {
103 	unsigned int		size = BBTOB(bp->b_length);
104 
105 	might_sleep();
106 	trace_xfs_buf_free(bp, _RET_IP_);
107 
108 	ASSERT(list_empty(&bp->b_lru));
109 
110 	if (!xfs_buftarg_is_mem(bp->b_target) && size >= PAGE_SIZE)
111 		mm_account_reclaimed_pages(howmany(size, PAGE_SHIFT));
112 
113 	if (is_vmalloc_addr(bp->b_addr))
114 		vfree(bp->b_addr);
115 	else if (bp->b_flags & _XBF_KMEM)
116 		kfree(bp->b_addr);
117 	else
118 		folio_put(virt_to_folio(bp->b_addr));
119 
120 	call_rcu(&bp->b_rcu, xfs_buf_free_callback);
121 }
122 
123 static int
124 xfs_buf_alloc_kmem(
125 	struct xfs_buf		*bp,
126 	size_t			size,
127 	gfp_t			gfp_mask)
128 {
129 	ASSERT(is_power_of_2(size));
130 	ASSERT(size < PAGE_SIZE);
131 
132 	bp->b_addr = kmalloc(size, gfp_mask | __GFP_NOFAIL);
133 	if (!bp->b_addr)
134 		return -ENOMEM;
135 
136 	/*
137 	 * Slab guarantees that we get back naturally aligned allocations for
138 	 * power of two sizes.  Keep this check as the canary in the coal mine
139 	 * if anything changes in slab.
140 	 */
141 	if (WARN_ON_ONCE(!IS_ALIGNED((unsigned long)bp->b_addr, size))) {
142 		kfree(bp->b_addr);
143 		bp->b_addr = NULL;
144 		return -ENOMEM;
145 	}
146 	bp->b_flags |= _XBF_KMEM;
147 	trace_xfs_buf_backing_kmem(bp, _RET_IP_);
148 	return 0;
149 }
150 
151 /*
152  * Allocate backing memory for a buffer.
153  *
154  * For tmpfs-backed buffers used by in-memory btrees this directly maps the
155  * tmpfs page cache folios.
156  *
157  * For real file system buffers there are three different kinds backing memory:
158  *
159  * The first type backs the buffer by a kmalloc allocation.  This is done for
160  * less than PAGE_SIZE allocations to avoid wasting memory.
161  *
162  * The second type is a single folio buffer - this may be a high order folio or
163  * just a single page sized folio, but either way they get treated the same way
164  * by the rest of the code - the buffer memory spans a single contiguous memory
165  * region that we don't have to map and unmap to access the data directly.
166  *
167  * The third type of buffer is the vmalloc()d buffer. This provides the buffer
168  * with the required contiguous memory region but backed by discontiguous
169  * physical pages.
170  */
171 static int
172 xfs_buf_alloc_backing_mem(
173 	struct xfs_buf	*bp,
174 	xfs_buf_flags_t	flags)
175 {
176 	size_t		size = BBTOB(bp->b_length);
177 	gfp_t		gfp_mask = GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOWARN;
178 	struct folio	*folio;
179 
180 	if (xfs_buftarg_is_mem(bp->b_target))
181 		return xmbuf_map_backing_mem(bp);
182 
183 	/* Assure zeroed buffer for non-read cases. */
184 	if (!(flags & XBF_READ))
185 		gfp_mask |= __GFP_ZERO;
186 
187 	if (flags & XBF_READ_AHEAD)
188 		gfp_mask |= __GFP_NORETRY;
189 
190 	/*
191 	 * For buffers smaller than PAGE_SIZE use a kmalloc allocation if that
192 	 * is properly aligned.  The slab allocator now guarantees an aligned
193 	 * allocation for all power of two sizes, which matches most of the
194 	 * smaller than PAGE_SIZE buffers used by XFS.
195 	 */
196 	if (size < PAGE_SIZE && is_power_of_2(size))
197 		return xfs_buf_alloc_kmem(bp, size, gfp_mask);
198 
199 	/*
200 	 * Don't bother with the retry loop for single PAGE allocations: vmalloc
201 	 * won't do any better.
202 	 */
203 	if (size <= PAGE_SIZE)
204 		gfp_mask |= __GFP_NOFAIL;
205 
206 	/*
207 	 * Optimistically attempt a single high order folio allocation for
208 	 * larger than PAGE_SIZE buffers.
209 	 *
210 	 * Allocating a high order folio makes the assumption that buffers are a
211 	 * power-of-2 size, matching the power-of-2 folios sizes available.
212 	 *
213 	 * The exception here are user xattr data buffers, which can be arbitrarily
214 	 * sized up to 64kB plus structure metadata, skip straight to the vmalloc
215 	 * path for them instead of wasting memory here.
216 	 */
217 	if (size > PAGE_SIZE) {
218 		if (!is_power_of_2(size))
219 			goto fallback;
220 		gfp_mask &= ~__GFP_DIRECT_RECLAIM;
221 		gfp_mask |= __GFP_NORETRY;
222 	}
223 	folio = folio_alloc(gfp_mask, get_order(size));
224 	if (!folio) {
225 		if (size <= PAGE_SIZE)
226 			return -ENOMEM;
227 		trace_xfs_buf_backing_fallback(bp, _RET_IP_);
228 		goto fallback;
229 	}
230 	bp->b_addr = folio_address(folio);
231 	trace_xfs_buf_backing_folio(bp, _RET_IP_);
232 	return 0;
233 
234 fallback:
235 	for (;;) {
236 		bp->b_addr = __vmalloc(size, gfp_mask);
237 		if (bp->b_addr)
238 			break;
239 		if (flags & XBF_READ_AHEAD)
240 			return -ENOMEM;
241 		XFS_STATS_INC(bp->b_mount, xb_page_retries);
242 		memalloc_retry_wait(gfp_mask);
243 	}
244 
245 	trace_xfs_buf_backing_vmalloc(bp, _RET_IP_);
246 	return 0;
247 }
248 
249 static int
250 xfs_buf_alloc(
251 	struct xfs_buftarg	*target,
252 	struct xfs_buf_map	*map,
253 	int			nmaps,
254 	xfs_buf_flags_t		flags,
255 	struct xfs_buf		**bpp)
256 {
257 	struct xfs_buf		*bp;
258 	int			error;
259 	int			i;
260 
261 	*bpp = NULL;
262 	bp = kmem_cache_zalloc(xfs_buf_cache,
263 			GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOFAIL);
264 
265 	/*
266 	 * We don't want certain flags to appear in b_flags unless they are
267 	 * specifically set by later operations on the buffer.
268 	 */
269 	flags &= ~(XBF_TRYLOCK | XBF_ASYNC | XBF_READ_AHEAD);
270 
271 	/*
272 	 * A new buffer is held and locked by the owner.  This ensures that the
273 	 * buffer is owned by the caller and racing RCU lookups right after
274 	 * inserting into the hash table are safe (and will have to wait for
275 	 * the unlock to do anything non-trivial).
276 	 */
277 	lockref_init(&bp->b_lockref);
278 	sema_init(&bp->b_sema, 0); /* held, no waiters */
279 	atomic_set(&bp->b_lru_ref, 1);
280 	init_completion(&bp->b_iowait);
281 	INIT_LIST_HEAD(&bp->b_lru);
282 	INIT_LIST_HEAD(&bp->b_list);
283 	INIT_LIST_HEAD(&bp->b_li_list);
284 	bp->b_target = target;
285 	bp->b_mount = target->bt_mount;
286 	bp->b_flags = flags;
287 	bp->b_rhash_key = map[0].bm_bn;
288 	bp->b_length = 0;
289 	bp->b_map_count = nmaps;
290 	if (nmaps == 1)
291 		bp->b_maps = &bp->__b_map;
292 	else
293 		bp->b_maps = kzalloc_objs(struct xfs_buf_map, nmaps,
294 					  GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOFAIL);
295 	for (i = 0; i < nmaps; i++) {
296 		bp->b_maps[i].bm_bn = map[i].bm_bn;
297 		bp->b_maps[i].bm_len = map[i].bm_len;
298 		bp->b_length += map[i].bm_len;
299 	}
300 
301 	atomic_set(&bp->b_pin_count, 0);
302 	init_waitqueue_head(&bp->b_waiters);
303 
304 	XFS_STATS_INC(bp->b_mount, xb_create);
305 	trace_xfs_buf_init(bp, _RET_IP_);
306 
307 	error = xfs_buf_alloc_backing_mem(bp, flags);
308 	if (error) {
309 		xfs_buf_free(bp);
310 		return error;
311 	}
312 
313 	*bpp = bp;
314 	return 0;
315 }
316 
317 /*
318  *	Finding and Reading Buffers
319  */
320 static int
321 _xfs_buf_obj_cmp(
322 	struct rhashtable_compare_arg	*arg,
323 	const void			*obj)
324 {
325 	const struct xfs_buf_map	*map = arg->key;
326 	const struct xfs_buf		*bp = obj;
327 
328 	/*
329 	 * The key hashing in the lookup path depends on the key being the
330 	 * first element of the compare_arg, make sure to assert this.
331 	 */
332 	BUILD_BUG_ON(offsetof(struct xfs_buf_map, bm_bn) != 0);
333 
334 	if (bp->b_rhash_key != map->bm_bn)
335 		return 1;
336 
337 	if (unlikely(bp->b_length != map->bm_len)) {
338 		/*
339 		 * found a block number match. If the range doesn't
340 		 * match, the only way this is allowed is if the buffer
341 		 * in the cache is stale and the transaction that made
342 		 * it stale has not yet committed. i.e. we are
343 		 * reallocating a busy extent. Skip this buffer and
344 		 * continue searching for an exact match.
345 		 *
346 		 * Note: If we're scanning for incore buffers to stale, don't
347 		 * complain if we find non-stale buffers.
348 		 */
349 		if (!(map->bm_flags & XBM_LIVESCAN))
350 			ASSERT(bp->b_flags & XBF_STALE);
351 		return 1;
352 	}
353 	return 0;
354 }
355 
356 static const struct rhashtable_params xfs_buf_hash_params = {
357 	.min_size		= 32,	/* empty AGs have minimal footprint */
358 	.nelem_hint		= 16,
359 	.key_len		= sizeof(xfs_daddr_t),
360 	.key_offset		= offsetof(struct xfs_buf, b_rhash_key),
361 	.head_offset		= offsetof(struct xfs_buf, b_rhash_head),
362 	.automatic_shrinking	= true,
363 	.obj_cmpfn		= _xfs_buf_obj_cmp,
364 };
365 
366 static int
367 xfs_buf_map_verify(
368 	struct xfs_buftarg	*btp,
369 	struct xfs_buf_map	*map)
370 {
371 	/* Check for IOs smaller than the sector size / not sector aligned */
372 	ASSERT(!(BBTOB(map->bm_len) < btp->bt_meta_sectorsize));
373 	ASSERT(!(BBTOB(map->bm_bn) & (xfs_off_t)btp->bt_meta_sectormask));
374 
375 	/*
376 	 * Corrupted block numbers can get through to here, unfortunately, so we
377 	 * have to check that the buffer falls within the filesystem bounds.
378 	 */
379 	if (map->bm_bn < 0 || map->bm_bn >= btp->bt_nr_sectors) {
380 		xfs_alert(btp->bt_mount,
381 			  "%s: daddr 0x%llx out of range, EOFS 0x%llx",
382 			  __func__, map->bm_bn, btp->bt_nr_sectors);
383 		WARN_ON(1);
384 		return -EFSCORRUPTED;
385 	}
386 	return 0;
387 }
388 
389 static int
390 xfs_buf_find_lock(
391 	struct xfs_buf          *bp,
392 	xfs_buf_flags_t		flags)
393 {
394 	if (flags & XBF_TRYLOCK) {
395 		if (!xfs_buf_trylock(bp)) {
396 			XFS_STATS_INC(bp->b_mount, xb_busy_locked);
397 			return -EAGAIN;
398 		}
399 	} else {
400 		xfs_buf_lock(bp);
401 		XFS_STATS_INC(bp->b_mount, xb_get_locked_waited);
402 	}
403 
404 	/*
405 	 * if the buffer is stale, clear all the external state associated with
406 	 * it. We need to keep flags such as how we allocated the buffer memory
407 	 * intact here.
408 	 */
409 	if (bp->b_flags & XBF_STALE) {
410 		if (flags & XBF_LIVESCAN) {
411 			xfs_buf_unlock(bp);
412 			return -ENOENT;
413 		}
414 		ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0);
415 		bp->b_flags &= _XBF_KMEM;
416 		bp->b_ops = NULL;
417 	}
418 	return 0;
419 }
420 
421 static inline int
422 xfs_buf_lookup(
423 	struct xfs_buftarg	*btp,
424 	struct xfs_buf_map	*map,
425 	xfs_buf_flags_t		flags,
426 	struct xfs_buf		**bpp)
427 {
428 	struct xfs_buf          *bp;
429 	int			error;
430 
431 	rcu_read_lock();
432 	bp = rhashtable_lookup(&btp->bt_hash, map, xfs_buf_hash_params);
433 	if (!bp || !lockref_get_not_dead(&bp->b_lockref)) {
434 		rcu_read_unlock();
435 		return -ENOENT;
436 	}
437 	rcu_read_unlock();
438 
439 	error = xfs_buf_find_lock(bp, flags);
440 	if (error) {
441 		xfs_buf_rele(bp);
442 		return error;
443 	}
444 
445 	trace_xfs_buf_find(bp, flags, _RET_IP_);
446 	*bpp = bp;
447 	return 0;
448 }
449 
450 /*
451  * Insert the new_bp into the hash table. This consumes the perag reference
452  * taken for the lookup regardless of the result of the insert.
453  */
454 static int
455 xfs_buf_find_insert(
456 	struct xfs_buftarg	*btp,
457 	struct xfs_perag	*pag,
458 	struct xfs_buf_map	*cmap,
459 	struct xfs_buf_map	*map,
460 	int			nmaps,
461 	xfs_buf_flags_t		flags,
462 	struct xfs_buf		**bpp)
463 {
464 	struct xfs_buf		*new_bp;
465 	struct xfs_buf		*bp;
466 	int			error;
467 
468 	error = xfs_buf_alloc(btp, map, nmaps, flags, &new_bp);
469 	if (error)
470 		goto out_drop_pag;
471 
472 	/* The new buffer keeps the perag reference until it is freed. */
473 	new_bp->b_pag = pag;
474 
475 	rcu_read_lock();
476 	bp = rhashtable_lookup_get_insert_fast(&btp->bt_hash,
477 			&new_bp->b_rhash_head, xfs_buf_hash_params);
478 	if (IS_ERR(bp)) {
479 		rcu_read_unlock();
480 		error = PTR_ERR(bp);
481 		goto out_free_buf;
482 	}
483 	if (bp && lockref_get_not_dead(&bp->b_lockref)) {
484 		/* found an existing buffer */
485 		rcu_read_unlock();
486 		error = xfs_buf_find_lock(bp, flags);
487 		if (error)
488 			xfs_buf_rele(bp);
489 		else
490 			*bpp = bp;
491 		goto out_free_buf;
492 	}
493 	rcu_read_unlock();
494 
495 	*bpp = new_bp;
496 	return 0;
497 
498 out_free_buf:
499 	xfs_buf_free(new_bp);
500 out_drop_pag:
501 	if (pag)
502 		xfs_perag_put(pag);
503 	return error;
504 }
505 
506 static inline struct xfs_perag *
507 xfs_buftarg_get_pag(
508 	struct xfs_buftarg		*btp,
509 	const struct xfs_buf_map	*map)
510 {
511 	struct xfs_mount		*mp = btp->bt_mount;
512 
513 	if (xfs_buftarg_is_mem(btp))
514 		return NULL;
515 	return xfs_perag_get(mp, xfs_daddr_to_agno(mp, map->bm_bn));
516 }
517 
518 /*
519  * Assembles a buffer covering the specified range. The code is optimised for
520  * cache hits, as metadata intensive workloads will see 3 orders of magnitude
521  * more hits than misses.
522  */
523 int
524 xfs_buf_get_map(
525 	struct xfs_buftarg	*btp,
526 	struct xfs_buf_map	*map,
527 	int			nmaps,
528 	xfs_buf_flags_t		flags,
529 	struct xfs_buf		**bpp)
530 {
531 	struct xfs_perag	*pag;
532 	struct xfs_buf		*bp = NULL;
533 	struct xfs_buf_map	cmap = { .bm_bn = map[0].bm_bn };
534 	int			error;
535 	int			i;
536 
537 	if (flags & XBF_LIVESCAN)
538 		cmap.bm_flags |= XBM_LIVESCAN;
539 	for (i = 0; i < nmaps; i++)
540 		cmap.bm_len += map[i].bm_len;
541 
542 	error = xfs_buf_map_verify(btp, &cmap);
543 	if (error)
544 		return error;
545 
546 	pag = xfs_buftarg_get_pag(btp, &cmap);
547 
548 	error = xfs_buf_lookup(btp, &cmap, flags, &bp);
549 	if (error && error != -ENOENT)
550 		goto out_put_perag;
551 
552 	/* cache hits always outnumber misses by at least 10:1 */
553 	if (unlikely(!bp)) {
554 		XFS_STATS_INC(btp->bt_mount, xb_miss_locked);
555 
556 		if (flags & XBF_INCORE)
557 			goto out_put_perag;
558 
559 		/* xfs_buf_find_insert() consumes the perag reference. */
560 		error = xfs_buf_find_insert(btp, pag, &cmap, map, nmaps,
561 				flags, &bp);
562 		if (error)
563 			return error;
564 	} else {
565 		XFS_STATS_INC(btp->bt_mount, xb_get_locked);
566 		if (pag)
567 			xfs_perag_put(pag);
568 	}
569 
570 	/*
571 	 * Clear b_error if this is a lookup from a caller that doesn't expect
572 	 * valid data to be found in the buffer.
573 	 */
574 	if (!(flags & XBF_READ))
575 		xfs_buf_ioerror(bp, 0);
576 
577 	XFS_STATS_INC(btp->bt_mount, xb_get);
578 	trace_xfs_buf_get(bp, flags, _RET_IP_);
579 	*bpp = bp;
580 	return 0;
581 
582 out_put_perag:
583 	if (pag)
584 		xfs_perag_put(pag);
585 	return error;
586 }
587 
588 int
589 _xfs_buf_read(
590 	struct xfs_buf		*bp)
591 {
592 	ASSERT(bp->b_maps[0].bm_bn != XFS_BUF_DADDR_NULL);
593 
594 	bp->b_flags &= ~(XBF_WRITE | XBF_ASYNC | XBF_READ_AHEAD | XBF_DONE);
595 	bp->b_flags |= XBF_READ;
596 	xfs_buf_submit(bp);
597 	return xfs_buf_iowait(bp);
598 }
599 
600 /*
601  * Reverify a buffer found in cache without an attached ->b_ops.
602  *
603  * If the caller passed an ops structure and the buffer doesn't have ops
604  * assigned, set the ops and use it to verify the contents. If verification
605  * fails, clear XBF_DONE. We assume the buffer has no recorded errors and is
606  * already in XBF_DONE state on entry.
607  *
608  * Under normal operations, every in-core buffer is verified on read I/O
609  * completion. There are two scenarios that can lead to in-core buffers without
610  * an assigned ->b_ops. The first is during log recovery of buffers on a V4
611  * filesystem, though these buffers are purged at the end of recovery. The
612  * other is online repair, which intentionally reads with a NULL buffer ops to
613  * run several verifiers across an in-core buffer in order to establish buffer
614  * type.  If repair can't establish that, the buffer will be left in memory
615  * with NULL buffer ops.
616  */
617 int
618 xfs_buf_reverify(
619 	struct xfs_buf		*bp,
620 	const struct xfs_buf_ops *ops)
621 {
622 	ASSERT(bp->b_flags & XBF_DONE);
623 	ASSERT(bp->b_error == 0);
624 
625 	if (!ops || bp->b_ops)
626 		return 0;
627 
628 	bp->b_ops = ops;
629 	bp->b_ops->verify_read(bp);
630 	if (bp->b_error)
631 		bp->b_flags &= ~XBF_DONE;
632 	return bp->b_error;
633 }
634 
635 int
636 xfs_buf_read_map(
637 	struct xfs_buftarg	*target,
638 	struct xfs_buf_map	*map,
639 	int			nmaps,
640 	xfs_buf_flags_t		flags,
641 	struct xfs_buf		**bpp,
642 	const struct xfs_buf_ops *ops,
643 	xfs_failaddr_t		fa)
644 {
645 	struct xfs_buf		*bp;
646 	int			error;
647 
648 	ASSERT(!(flags & (XBF_WRITE | XBF_ASYNC | XBF_READ_AHEAD)));
649 
650 	flags |= XBF_READ;
651 	*bpp = NULL;
652 
653 	error = xfs_buf_get_map(target, map, nmaps, flags, &bp);
654 	if (error)
655 		return error;
656 
657 	trace_xfs_buf_read(bp, flags, _RET_IP_);
658 
659 	if (!(bp->b_flags & XBF_DONE)) {
660 		/* Initiate the buffer read and wait. */
661 		XFS_STATS_INC(target->bt_mount, xb_get_read);
662 		bp->b_ops = ops;
663 		error = _xfs_buf_read(bp);
664 	} else {
665 		/* Buffer already read; all we need to do is check it. */
666 		error = xfs_buf_reverify(bp, ops);
667 
668 		/* We do not want read in the flags */
669 		bp->b_flags &= ~XBF_READ;
670 		ASSERT(bp->b_ops != NULL || ops == NULL);
671 	}
672 
673 	/*
674 	 * If we've had a read error, then the contents of the buffer are
675 	 * invalid and should not be used. To ensure that a followup read tries
676 	 * to pull the buffer from disk again, we clear the XBF_DONE flag and
677 	 * mark the buffer stale. This ensures that anyone who has a current
678 	 * reference to the buffer will interpret it's contents correctly and
679 	 * future cache lookups will also treat it as an empty, uninitialised
680 	 * buffer.
681 	 */
682 	if (error) {
683 		/*
684 		 * Check against log shutdown for error reporting because
685 		 * metadata writeback may require a read first and we need to
686 		 * report errors in metadata writeback until the log is shut
687 		 * down. High level transaction read functions already check
688 		 * against mount shutdown, anyway, so we only need to be
689 		 * concerned about low level IO interactions here.
690 		 */
691 		if (!xlog_is_shutdown(target->bt_mount->m_log))
692 			xfs_buf_ioerror_alert(bp, fa);
693 
694 		bp->b_flags &= ~XBF_DONE;
695 		xfs_buf_stale(bp);
696 		xfs_buf_relse(bp);
697 
698 		/* bad CRC means corrupted metadata */
699 		if (error == -EFSBADCRC)
700 			error = -EFSCORRUPTED;
701 		return error;
702 	}
703 
704 	*bpp = bp;
705 	return 0;
706 }
707 
708 /*
709  *	If we are not low on memory then do the readahead in a deadlock
710  *	safe manner.
711  */
712 void
713 xfs_buf_readahead_map(
714 	struct xfs_buftarg	*target,
715 	struct xfs_buf_map	*map,
716 	int			nmaps,
717 	const struct xfs_buf_ops *ops)
718 {
719 	const xfs_buf_flags_t	flags = XBF_READ | XBF_ASYNC | XBF_READ_AHEAD;
720 	struct xfs_buf		*bp;
721 
722 	/*
723 	 * Currently we don't have a good means or justification for performing
724 	 * xmbuf_map_page asynchronously, so we don't do readahead.
725 	 */
726 	if (xfs_buftarg_is_mem(target))
727 		return;
728 
729 	if (xfs_buf_get_map(target, map, nmaps, flags | XBF_TRYLOCK, &bp))
730 		return;
731 	trace_xfs_buf_readahead(bp, 0, _RET_IP_);
732 
733 	if (bp->b_flags & XBF_DONE) {
734 		xfs_buf_reverify(bp, ops);
735 		xfs_buf_relse(bp);
736 		return;
737 	}
738 	XFS_STATS_INC(target->bt_mount, xb_get_read);
739 	bp->b_ops = ops;
740 	bp->b_flags &= ~(XBF_WRITE | XBF_DONE);
741 	bp->b_flags |= flags;
742 	percpu_counter_inc(&target->bt_readahead_count);
743 	xfs_buf_submit(bp);
744 }
745 
746 /*
747  * Read an uncached buffer from disk. Allocates and returns a locked
748  * buffer containing the disk contents or nothing. Uncached buffers always have
749  * a cache index of XFS_BUF_DADDR_NULL so we can easily determine if the buffer
750  * is cached or uncached during fault diagnosis.
751  */
752 int
753 xfs_buf_read_uncached(
754 	struct xfs_buftarg	*target,
755 	xfs_daddr_t		daddr,
756 	size_t			numblks,
757 	struct xfs_buf		**bpp,
758 	const struct xfs_buf_ops *ops)
759 {
760 	struct xfs_buf		*bp;
761 	int			error;
762 
763 	*bpp = NULL;
764 
765 	error = xfs_buf_get_uncached(target, numblks, &bp);
766 	if (error)
767 		return error;
768 
769 	/* set up the buffer for a read IO */
770 	ASSERT(bp->b_map_count == 1);
771 	bp->b_rhash_key = XFS_BUF_DADDR_NULL;
772 	bp->b_maps[0].bm_bn = daddr;
773 	bp->b_flags |= XBF_READ;
774 	bp->b_ops = ops;
775 
776 	xfs_buf_submit(bp);
777 	error = xfs_buf_iowait(bp);
778 	if (error) {
779 		xfs_buf_relse(bp);
780 		return error;
781 	}
782 
783 	*bpp = bp;
784 	return 0;
785 }
786 
787 int
788 xfs_buf_get_uncached(
789 	struct xfs_buftarg	*target,
790 	size_t			numblks,
791 	struct xfs_buf		**bpp)
792 {
793 	int			error;
794 	DEFINE_SINGLE_BUF_MAP(map, XFS_BUF_DADDR_NULL, numblks);
795 
796 	error = xfs_buf_alloc(target, &map, 1, 0, bpp);
797 	if (!error)
798 		trace_xfs_buf_get_uncached(*bpp, _RET_IP_);
799 	return error;
800 }
801 
802 /*
803  *	Increment reference count on buffer, to hold the buffer concurrently
804  *	with another thread which may release (free) the buffer asynchronously.
805  *	Must hold the buffer already to call this function.
806  */
807 void
808 xfs_buf_hold(
809 	struct xfs_buf		*bp)
810 {
811 	trace_xfs_buf_hold(bp, _RET_IP_);
812 
813 	lockref_get(&bp->b_lockref);
814 }
815 
816 static void
817 xfs_buf_destroy(
818 	struct xfs_buf		*bp)
819 {
820 	ASSERT(__lockref_is_dead(&bp->b_lockref));
821 	ASSERT(!(bp->b_flags & _XBF_DELWRI_Q));
822 
823 	if (!xfs_buf_is_uncached(bp)) {
824 		rhashtable_remove_fast(&bp->b_target->bt_hash,
825 				&bp->b_rhash_head, xfs_buf_hash_params);
826 
827 		if (bp->b_pag)
828 			xfs_perag_put(bp->b_pag);
829 	}
830 
831 	xfs_buf_free(bp);
832 }
833 
834 /*
835  * Release a hold on the specified buffer.
836  */
837 void
838 xfs_buf_rele(
839 	struct xfs_buf		*bp)
840 {
841 	trace_xfs_buf_rele(bp, _RET_IP_);
842 
843 	if (lockref_put_or_lock(&bp->b_lockref))
844 		return;
845 	if (!--bp->b_lockref.count) {
846 		if (xfs_buf_is_uncached(bp) || !atomic_read(&bp->b_lru_ref))
847 			goto kill;
848 		list_lru_add_obj(&bp->b_target->bt_lru, &bp->b_lru);
849 	}
850 	spin_unlock(&bp->b_lockref.lock);
851 	return;
852 
853 kill:
854 	lockref_mark_dead(&bp->b_lockref);
855 	list_lru_del_obj(&bp->b_target->bt_lru, &bp->b_lru);
856 	spin_unlock(&bp->b_lockref.lock);
857 
858 	xfs_buf_destroy(bp);
859 }
860 
861 /*
862  *	Lock a buffer object, if it is not already locked.
863  *
864  *	If we come across a stale, pinned, locked buffer, we know that we are
865  *	being asked to lock a buffer that has been reallocated. Because it is
866  *	pinned, we know that the log has not been pushed to disk and hence it
867  *	will still be locked.  Rather than continuing to have trylock attempts
868  *	fail until someone else pushes the log, push it ourselves before
869  *	returning.  This means that the xfsaild will not get stuck trying
870  *	to push on stale inode buffers.
871  */
872 int
873 xfs_buf_trylock(
874 	struct xfs_buf		*bp)
875 {
876 	int			locked;
877 
878 	locked = down_trylock(&bp->b_sema) == 0;
879 	if (locked)
880 		trace_xfs_buf_trylock(bp, _RET_IP_);
881 	else
882 		trace_xfs_buf_trylock_fail(bp, _RET_IP_);
883 	return locked;
884 }
885 
886 /*
887  *	Lock a buffer object.
888  *
889  *	If we come across a stale, pinned, locked buffer, we know that we
890  *	are being asked to lock a buffer that has been reallocated. Because
891  *	it is pinned, we know that the log has not been pushed to disk and
892  *	hence it will still be locked. Rather than sleeping until someone
893  *	else pushes the log, push it ourselves before trying to get the lock.
894  */
895 void
896 xfs_buf_lock(
897 	struct xfs_buf		*bp)
898 {
899 	trace_xfs_buf_lock(bp, _RET_IP_);
900 
901 	if (atomic_read(&bp->b_pin_count) && (bp->b_flags & XBF_STALE))
902 		xfs_log_force(bp->b_mount, 0);
903 	down(&bp->b_sema);
904 
905 	trace_xfs_buf_lock_done(bp, _RET_IP_);
906 }
907 
908 void
909 xfs_buf_unlock(
910 	struct xfs_buf		*bp)
911 {
912 	ASSERT(xfs_buf_islocked(bp));
913 
914 	up(&bp->b_sema);
915 	trace_xfs_buf_unlock(bp, _RET_IP_);
916 }
917 
918 STATIC void
919 xfs_buf_wait_unpin(
920 	struct xfs_buf		*bp)
921 {
922 	DECLARE_WAITQUEUE	(wait, current);
923 
924 	if (atomic_read(&bp->b_pin_count) == 0)
925 		return;
926 
927 	add_wait_queue(&bp->b_waiters, &wait);
928 	for (;;) {
929 		set_current_state(TASK_UNINTERRUPTIBLE);
930 		if (atomic_read(&bp->b_pin_count) == 0)
931 			break;
932 		io_schedule();
933 	}
934 	remove_wait_queue(&bp->b_waiters, &wait);
935 	set_current_state(TASK_RUNNING);
936 }
937 
938 static void
939 xfs_buf_ioerror_alert_ratelimited(
940 	struct xfs_buf		*bp)
941 {
942 	static unsigned long	lasttime;
943 	static struct xfs_buftarg *lasttarg;
944 
945 	if (bp->b_target != lasttarg ||
946 	    time_after(jiffies, (lasttime + 5*HZ))) {
947 		lasttime = jiffies;
948 		xfs_buf_ioerror_alert(bp, __this_address);
949 	}
950 	lasttarg = bp->b_target;
951 }
952 
953 /*
954  * Account for this latest trip around the retry handler, and decide if
955  * we've failed enough times to constitute a permanent failure.
956  */
957 static bool
958 xfs_buf_ioerror_permanent(
959 	struct xfs_buf		*bp,
960 	struct xfs_error_cfg	*cfg)
961 {
962 	struct xfs_mount	*mp = bp->b_mount;
963 
964 	if (cfg->max_retries != XFS_ERR_RETRY_FOREVER &&
965 	    ++bp->b_retries > cfg->max_retries)
966 		return true;
967 	if (cfg->retry_timeout != XFS_ERR_RETRY_FOREVER &&
968 	    time_after(jiffies, cfg->retry_timeout + bp->b_first_retry_time))
969 		return true;
970 
971 	/* At unmount we may treat errors differently */
972 	if (xfs_is_unmounting(mp) && mp->m_fail_unmount)
973 		return true;
974 
975 	return false;
976 }
977 
978 /*
979  * On a sync write or shutdown we just want to stale the buffer and let the
980  * caller handle the error in bp->b_error appropriately.
981  *
982  * If the write was asynchronous then no one will be looking for the error.  If
983  * this is the first failure of this type, clear the error state and write the
984  * buffer out again. This means we always retry an async write failure at least
985  * once, but we also need to set the buffer up to behave correctly now for
986  * repeated failures.
987  *
988  * If we get repeated async write failures, then we take action according to the
989  * error configuration we have been set up to use.
990  *
991  * Returns true if this function took care of error handling and the caller must
992  * not touch the buffer again.  Return false if the caller should proceed with
993  * normal I/O completion handling.
994  */
995 static bool
996 xfs_buf_ioend_handle_error(
997 	struct xfs_buf		*bp)
998 {
999 	struct xfs_mount	*mp = bp->b_mount;
1000 	struct xfs_error_cfg	*cfg;
1001 	struct xfs_log_item	*lip;
1002 
1003 	/*
1004 	 * If we've already shutdown the journal because of I/O errors, there's
1005 	 * no point in giving this a retry.
1006 	 */
1007 	if (xlog_is_shutdown(mp->m_log))
1008 		goto out_stale;
1009 
1010 	xfs_buf_ioerror_alert_ratelimited(bp);
1011 
1012 	/*
1013 	 * We're not going to bother about retrying this during recovery.
1014 	 * One strike!
1015 	 */
1016 	if (bp->b_flags & _XBF_LOGRECOVERY) {
1017 		xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1018 		return false;
1019 	}
1020 
1021 	/*
1022 	 * Synchronous writes will have callers process the error.
1023 	 */
1024 	if (!(bp->b_flags & XBF_ASYNC))
1025 		goto out_stale;
1026 
1027 	trace_xfs_buf_iodone_async(bp, _RET_IP_);
1028 
1029 	cfg = xfs_error_get_cfg(mp, XFS_ERR_METADATA, bp->b_error);
1030 	if (bp->b_last_error != bp->b_error ||
1031 	    !(bp->b_flags & (XBF_STALE | XBF_WRITE_FAIL))) {
1032 		bp->b_last_error = bp->b_error;
1033 		if (cfg->retry_timeout != XFS_ERR_RETRY_FOREVER &&
1034 		    !bp->b_first_retry_time)
1035 			bp->b_first_retry_time = jiffies;
1036 		goto resubmit;
1037 	}
1038 
1039 	/*
1040 	 * Permanent error - we need to trigger a shutdown if we haven't already
1041 	 * to indicate that inconsistency will result from this action.
1042 	 */
1043 	if (xfs_buf_ioerror_permanent(bp, cfg)) {
1044 		xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1045 		goto out_stale;
1046 	}
1047 
1048 	/* Still considered a transient error. Caller will schedule retries. */
1049 	list_for_each_entry(lip, &bp->b_li_list, li_bio_list) {
1050 		set_bit(XFS_LI_FAILED, &lip->li_flags);
1051 		clear_bit(XFS_LI_FLUSHING, &lip->li_flags);
1052 	}
1053 
1054 	xfs_buf_ioerror(bp, 0);
1055 	xfs_buf_relse(bp);
1056 	return true;
1057 
1058 resubmit:
1059 	xfs_buf_ioerror(bp, 0);
1060 	bp->b_flags |= (XBF_DONE | XBF_WRITE_FAIL);
1061 	reinit_completion(&bp->b_iowait);
1062 	xfs_buf_submit(bp);
1063 	return true;
1064 out_stale:
1065 	xfs_buf_stale(bp);
1066 	bp->b_flags |= XBF_DONE;
1067 	bp->b_flags &= ~XBF_WRITE;
1068 	trace_xfs_buf_error_relse(bp, _RET_IP_);
1069 	return false;
1070 }
1071 
1072 /* returns false if the caller needs to resubmit the I/O, else true */
1073 static bool
1074 __xfs_buf_ioend(
1075 	struct xfs_buf	*bp)
1076 {
1077 	trace_xfs_buf_iodone(bp, _RET_IP_);
1078 
1079 	if (bp->b_flags & XBF_READ) {
1080 		if (!bp->b_error && is_vmalloc_addr(bp->b_addr))
1081 			invalidate_kernel_vmap_range(bp->b_addr,
1082 				roundup(BBTOB(bp->b_length), PAGE_SIZE));
1083 		if (!bp->b_error && bp->b_ops)
1084 			bp->b_ops->verify_read(bp);
1085 		if (!bp->b_error)
1086 			bp->b_flags |= XBF_DONE;
1087 		if (bp->b_flags & XBF_READ_AHEAD)
1088 			percpu_counter_dec(&bp->b_target->bt_readahead_count);
1089 	} else {
1090 		if (!bp->b_error) {
1091 			bp->b_flags &= ~XBF_WRITE_FAIL;
1092 			bp->b_flags |= XBF_DONE;
1093 		}
1094 
1095 		if (unlikely(bp->b_error) && xfs_buf_ioend_handle_error(bp))
1096 			return false;
1097 
1098 		/* clear the retry state */
1099 		bp->b_last_error = 0;
1100 		bp->b_retries = 0;
1101 		bp->b_first_retry_time = 0;
1102 
1103 		/*
1104 		 * Note that for things like remote attribute buffers, there may
1105 		 * not be a buffer log item here, so processing the buffer log
1106 		 * item must remain optional.
1107 		 */
1108 		if (bp->b_log_item)
1109 			xfs_buf_item_done(bp);
1110 
1111 		if (bp->b_iodone)
1112 			bp->b_iodone(bp);
1113 	}
1114 
1115 	bp->b_flags &= ~(XBF_READ | XBF_WRITE | XBF_READ_AHEAD |
1116 			 _XBF_LOGRECOVERY);
1117 	return true;
1118 }
1119 
1120 static void
1121 xfs_buf_ioend(
1122 	struct xfs_buf	*bp)
1123 {
1124 	if (!__xfs_buf_ioend(bp))
1125 		return;
1126 	if (bp->b_flags & XBF_ASYNC)
1127 		xfs_buf_relse(bp);
1128 	else
1129 		complete(&bp->b_iowait);
1130 }
1131 
1132 static void
1133 xfs_buf_ioend_work(
1134 	struct work_struct	*work)
1135 {
1136 	struct xfs_buf		*bp =
1137 		container_of(work, struct xfs_buf, b_ioend_work);
1138 
1139 	if (__xfs_buf_ioend(bp))
1140 		xfs_buf_relse(bp);
1141 }
1142 
1143 void
1144 __xfs_buf_ioerror(
1145 	struct xfs_buf		*bp,
1146 	int			error,
1147 	xfs_failaddr_t		failaddr)
1148 {
1149 	ASSERT(error <= 0 && error >= -1000);
1150 	bp->b_error = error;
1151 	trace_xfs_buf_ioerror(bp, error, failaddr);
1152 }
1153 
1154 void
1155 xfs_buf_ioerror_alert(
1156 	struct xfs_buf		*bp,
1157 	xfs_failaddr_t		func)
1158 {
1159 	xfs_buf_alert_ratelimited(bp, "XFS: metadata IO error",
1160 		"metadata I/O error in \"%pS\" at daddr 0x%llx len %d error %d",
1161 				  func, (uint64_t)xfs_buf_daddr(bp),
1162 				  bp->b_length, -bp->b_error);
1163 }
1164 
1165 /*
1166  * To simulate an I/O failure, the buffer must be locked and held with at least
1167  * two references.
1168  *
1169  * The buf item reference is dropped via ioend processing. The second reference
1170  * is owned by the caller and is dropped on I/O completion if the buffer is
1171  * XBF_ASYNC.
1172  */
1173 void
1174 xfs_buf_ioend_fail(
1175 	struct xfs_buf	*bp)
1176 {
1177 	bp->b_flags &= ~XBF_DONE;
1178 	xfs_buf_stale(bp);
1179 	xfs_buf_ioerror(bp, -EIO);
1180 	xfs_buf_ioend(bp);
1181 }
1182 
1183 int
1184 xfs_bwrite(
1185 	struct xfs_buf		*bp)
1186 {
1187 	int			error;
1188 
1189 	ASSERT(xfs_buf_islocked(bp));
1190 
1191 	bp->b_flags |= XBF_WRITE;
1192 	bp->b_flags &= ~(XBF_ASYNC | XBF_READ | _XBF_DELWRI_Q |
1193 			 XBF_DONE);
1194 
1195 	xfs_buf_submit(bp);
1196 	error = xfs_buf_iowait(bp);
1197 	if (error)
1198 		xfs_force_shutdown(bp->b_mount, SHUTDOWN_META_IO_ERROR);
1199 	return error;
1200 }
1201 
1202 static void
1203 xfs_buf_bio_end_io(
1204 	struct bio		*bio)
1205 {
1206 	struct xfs_buf		*bp = bio->bi_private;
1207 
1208 	if (bio->bi_status)
1209 		xfs_buf_ioerror(bp, blk_status_to_errno(bio->bi_status));
1210 	else if ((bp->b_flags & XBF_WRITE) && (bp->b_flags & XBF_ASYNC) &&
1211 		 XFS_TEST_ERROR(bp->b_mount, XFS_ERRTAG_BUF_IOERROR))
1212 		xfs_buf_ioerror(bp, -EIO);
1213 
1214 	if (bp->b_flags & XBF_ASYNC) {
1215 		INIT_WORK(&bp->b_ioend_work, xfs_buf_ioend_work);
1216 		queue_work(bp->b_mount->m_buf_workqueue, &bp->b_ioend_work);
1217 	} else {
1218 		complete(&bp->b_iowait);
1219 	}
1220 
1221 	bio_put(bio);
1222 }
1223 
1224 static inline blk_opf_t
1225 xfs_buf_bio_op(
1226 	struct xfs_buf		*bp)
1227 {
1228 	blk_opf_t		op;
1229 
1230 	if (bp->b_flags & XBF_WRITE) {
1231 		op = REQ_OP_WRITE;
1232 	} else {
1233 		op = REQ_OP_READ;
1234 		if (bp->b_flags & XBF_READ_AHEAD)
1235 			op |= REQ_RAHEAD;
1236 	}
1237 
1238 	return op | REQ_META;
1239 }
1240 
1241 static void
1242 xfs_buf_submit_bio(
1243 	struct xfs_buf		*bp)
1244 {
1245 	unsigned int		len = BBTOB(bp->b_length);
1246 	unsigned int		nr_vecs = bio_add_max_vecs(bp->b_addr, len);
1247 	unsigned int		map = 0;
1248 	struct blk_plug		plug;
1249 	struct bio		*bio;
1250 
1251 	bio = bio_alloc(bp->b_target->bt_bdev, nr_vecs, xfs_buf_bio_op(bp),
1252 			GFP_NOIO);
1253 	if (is_vmalloc_addr(bp->b_addr))
1254 		bio_add_vmalloc(bio, bp->b_addr, len);
1255 	else
1256 		bio_add_virt_nofail(bio, bp->b_addr, len);
1257 	bio->bi_private = bp;
1258 	bio->bi_end_io = xfs_buf_bio_end_io;
1259 
1260 	/*
1261 	 * If there is more than one map segment, split out a new bio for each
1262 	 * map except of the last one.  The last map is handled by the
1263 	 * remainder of the original bio outside the loop.
1264 	 */
1265 	blk_start_plug(&plug);
1266 	for (map = 0; map < bp->b_map_count - 1; map++) {
1267 		struct bio	*split;
1268 
1269 		split = bio_split(bio, bp->b_maps[map].bm_len, GFP_NOFS,
1270 				&fs_bio_set);
1271 		split->bi_iter.bi_sector = bp->b_maps[map].bm_bn;
1272 		bio_chain(split, bio);
1273 		submit_bio(split);
1274 	}
1275 	bio->bi_iter.bi_sector = bp->b_maps[map].bm_bn;
1276 	submit_bio(bio);
1277 	blk_finish_plug(&plug);
1278 }
1279 
1280 /*
1281  * Wait for I/O completion of a sync buffer and return the I/O error code.
1282  */
1283 static int
1284 xfs_buf_iowait(
1285 	struct xfs_buf	*bp)
1286 {
1287 	ASSERT(!(bp->b_flags & XBF_ASYNC));
1288 
1289 	do {
1290 		trace_xfs_buf_iowait(bp, _RET_IP_);
1291 		wait_for_completion(&bp->b_iowait);
1292 		trace_xfs_buf_iowait_done(bp, _RET_IP_);
1293 	} while (!__xfs_buf_ioend(bp));
1294 
1295 	return bp->b_error;
1296 }
1297 
1298 /*
1299  * Run the write verifier callback function if it exists. If this fails, mark
1300  * the buffer with an error and do not dispatch the I/O.
1301  */
1302 static bool
1303 xfs_buf_verify_write(
1304 	struct xfs_buf		*bp)
1305 {
1306 	if (bp->b_ops) {
1307 		bp->b_ops->verify_write(bp);
1308 		if (bp->b_error)
1309 			return false;
1310 	} else if (bp->b_rhash_key != XFS_BUF_DADDR_NULL) {
1311 		/*
1312 		 * Non-crc filesystems don't attach verifiers during log
1313 		 * recovery, so don't warn for such filesystems.
1314 		 */
1315 		if (xfs_has_crc(bp->b_mount)) {
1316 			xfs_warn(bp->b_mount,
1317 				"%s: no buf ops on daddr 0x%llx len %d",
1318 				__func__, xfs_buf_daddr(bp),
1319 				bp->b_length);
1320 			xfs_hex_dump(bp->b_addr, XFS_CORRUPTION_DUMP_LEN);
1321 			dump_stack();
1322 		}
1323 	}
1324 
1325 	return true;
1326 }
1327 
1328 /*
1329  * Buffer I/O submission path, read or write. Asynchronous submission transfers
1330  * the buffer lock ownership and the current reference to the IO. It is not
1331  * safe to reference the buffer after a call to this function unless the caller
1332  * holds an additional reference itself.
1333  */
1334 static void
1335 xfs_buf_submit(
1336 	struct xfs_buf	*bp)
1337 {
1338 	trace_xfs_buf_submit(bp, _RET_IP_);
1339 
1340 	ASSERT(!(bp->b_flags & _XBF_DELWRI_Q));
1341 
1342 	/*
1343 	 * On log shutdown we stale and complete the buffer immediately. We can
1344 	 * be called to read the superblock before the log has been set up, so
1345 	 * be careful checking the log state.
1346 	 *
1347 	 * Checking the mount shutdown state here can result in the log tail
1348 	 * moving inappropriately on disk as the log may not yet be shut down.
1349 	 * i.e. failing this buffer on mount shutdown can remove it from the AIL
1350 	 * and move the tail of the log forwards without having written this
1351 	 * buffer to disk. This corrupts the log tail state in memory, and
1352 	 * because the log may not be shut down yet, it can then be propagated
1353 	 * to disk before the log is shutdown. Hence we check log shutdown
1354 	 * state here rather than mount state to avoid corrupting the log tail
1355 	 * on shutdown.
1356 	 */
1357 	if (bp->b_mount->m_log && xlog_is_shutdown(bp->b_mount->m_log)) {
1358 		xfs_buf_ioend_fail(bp);
1359 		return;
1360 	}
1361 
1362 	if (bp->b_flags & XBF_WRITE)
1363 		xfs_buf_wait_unpin(bp);
1364 
1365 	/*
1366 	 * Make sure we capture only current IO errors rather than stale errors
1367 	 * left over from previous use of the buffer (e.g. failed readahead).
1368 	 */
1369 	bp->b_error = 0;
1370 
1371 	if ((bp->b_flags & XBF_WRITE) && !xfs_buf_verify_write(bp)) {
1372 		xfs_force_shutdown(bp->b_mount, SHUTDOWN_CORRUPT_INCORE);
1373 		xfs_buf_ioend(bp);
1374 		return;
1375 	}
1376 
1377 	/* In-memory targets are directly mapped, no I/O required. */
1378 	if (xfs_buftarg_is_mem(bp->b_target)) {
1379 		xfs_buf_ioend(bp);
1380 		return;
1381 	}
1382 
1383 	xfs_buf_submit_bio(bp);
1384 }
1385 
1386 /*
1387  * Log a message about and stale a buffer that a caller has decided is corrupt.
1388  *
1389  * This function should be called for the kinds of metadata corruption that
1390  * cannot be detect from a verifier, such as incorrect inter-block relationship
1391  * data.  Do /not/ call this function from a verifier function.
1392  *
1393  * The buffer must be XBF_DONE prior to the call.  Afterwards, the buffer will
1394  * be marked stale, but b_error will not be set.  The caller is responsible for
1395  * releasing the buffer or fixing it.
1396  */
1397 void
1398 __xfs_buf_mark_corrupt(
1399 	struct xfs_buf		*bp,
1400 	xfs_failaddr_t		fa)
1401 {
1402 	ASSERT(bp->b_flags & XBF_DONE);
1403 
1404 	xfs_buf_corruption_error(bp, fa);
1405 	xfs_buf_stale(bp);
1406 }
1407 
1408 /*
1409  *	Handling of buffer targets (buftargs).
1410  */
1411 
1412 /*
1413  * Wait for any bufs with callbacks that have been submitted but have not yet
1414  * returned. These buffers will have an elevated hold count, so wait on those
1415  * while freeing all the buffers only held by the LRU.
1416  */
1417 static enum lru_status
1418 xfs_buftarg_drain_rele(
1419 	struct list_head	*item,
1420 	struct list_lru_one	*lru,
1421 	void			*arg)
1422 
1423 {
1424 	struct xfs_buf		*bp = container_of(item, struct xfs_buf, b_lru);
1425 	struct list_head	*dispose = arg;
1426 
1427 	if (!spin_trylock(&bp->b_lockref.lock))
1428 		return LRU_SKIP;
1429 	if (bp->b_lockref.count > 0) {
1430 		/* need to wait, so skip it this pass */
1431 		spin_unlock(&bp->b_lockref.lock);
1432 		trace_xfs_buf_drain_buftarg(bp, _RET_IP_);
1433 		return LRU_SKIP;
1434 	}
1435 
1436 	lockref_mark_dead(&bp->b_lockref);
1437 	list_lru_isolate_move(lru, item, dispose);
1438 	spin_unlock(&bp->b_lockref.lock);
1439 	return LRU_REMOVED;
1440 }
1441 
1442 /*
1443  * Wait for outstanding I/O on the buftarg to complete.
1444  */
1445 void
1446 xfs_buftarg_wait(
1447 	struct xfs_buftarg	*btp)
1448 {
1449 	/*
1450 	 * First wait for all in-flight readahead buffers to be released.  This is
1451 	 * critical as new buffers do not make the LRU until they are released.
1452 	 *
1453 	 * Next, flush the buffer workqueue to ensure all completion processing
1454 	 * has finished. Just waiting on buffer locks is not sufficient for
1455 	 * async IO as the reference count held over IO is not released until
1456 	 * after the buffer lock is dropped. Hence we need to ensure here that
1457 	 * all reference counts have been dropped before we start walking the
1458 	 * LRU list.
1459 	 */
1460 	while (percpu_counter_sum(&btp->bt_readahead_count))
1461 		delay(100);
1462 	flush_workqueue(btp->bt_mount->m_buf_workqueue);
1463 }
1464 
1465 void
1466 xfs_buftarg_drain(
1467 	struct xfs_buftarg	*btp)
1468 {
1469 	LIST_HEAD(dispose);
1470 	int			loop = 0;
1471 	bool			write_fail = false;
1472 
1473 	xfs_buftarg_wait(btp);
1474 
1475 	/* loop until there is nothing left on the lru list. */
1476 	while (list_lru_count(&btp->bt_lru)) {
1477 		list_lru_walk(&btp->bt_lru, xfs_buftarg_drain_rele,
1478 			      &dispose, LONG_MAX);
1479 
1480 		while (!list_empty(&dispose)) {
1481 			struct xfs_buf *bp;
1482 			bp = list_first_entry(&dispose, struct xfs_buf, b_lru);
1483 			list_del_init(&bp->b_lru);
1484 			if (bp->b_flags & XBF_WRITE_FAIL) {
1485 				write_fail = true;
1486 				xfs_buf_alert_ratelimited(bp,
1487 					"XFS: Corruption Alert",
1488 "Corruption Alert: Buffer at daddr 0x%llx had permanent write failures!",
1489 					(long long)xfs_buf_daddr(bp));
1490 			}
1491 			xfs_buf_destroy(bp);
1492 		}
1493 		if (loop++ != 0)
1494 			delay(100);
1495 	}
1496 
1497 	/*
1498 	 * If one or more failed buffers were freed, that means dirty metadata
1499 	 * was thrown away. This should only ever happen after I/O completion
1500 	 * handling has elevated I/O error(s) to permanent failures and shuts
1501 	 * down the journal.
1502 	 */
1503 	if (write_fail) {
1504 		ASSERT(xlog_is_shutdown(btp->bt_mount->m_log));
1505 		xfs_alert(btp->bt_mount,
1506 	      "Please run xfs_repair to determine the extent of the problem.");
1507 	}
1508 }
1509 
1510 static enum lru_status
1511 xfs_buftarg_isolate(
1512 	struct list_head	*item,
1513 	struct list_lru_one	*lru,
1514 	void			*arg)
1515 {
1516 	struct xfs_buf		*bp = container_of(item, struct xfs_buf, b_lru);
1517 	struct list_head	*dispose = arg;
1518 
1519 	/*
1520 	 * We are inverting the lru lock vs bp->b_lockref.lock order here, so
1521 	 * use a trylock.  If we fail to get the lock, just skip the buffer.
1522 	 */
1523 	if (!spin_trylock(&bp->b_lockref.lock))
1524 		return LRU_SKIP;
1525 
1526 	/*
1527 	 * If the buffer is in use, remove it from the LRU for now.  We can't
1528 	 * free it while someone is using it, and we should also not count
1529 	 * eviction passed for it, just as if it hadn't been added to the LRU
1530 	 * yet.
1531 	 */
1532 	if (bp->b_lockref.count > 0) {
1533 		list_lru_isolate(lru, &bp->b_lru);
1534 		spin_unlock(&bp->b_lockref.lock);
1535 		return LRU_REMOVED;
1536 	}
1537 
1538 	/*
1539 	 * Decrement the b_lru_ref count unless the value is already
1540 	 * zero. If the value is already zero, we need to reclaim the
1541 	 * buffer, otherwise it gets another trip through the LRU.
1542 	 */
1543 	if (atomic_add_unless(&bp->b_lru_ref, -1, 0)) {
1544 		spin_unlock(&bp->b_lockref.lock);
1545 		return LRU_ROTATE;
1546 	}
1547 
1548 	lockref_mark_dead(&bp->b_lockref);
1549 	list_lru_isolate_move(lru, item, dispose);
1550 	spin_unlock(&bp->b_lockref.lock);
1551 	return LRU_REMOVED;
1552 }
1553 
1554 static unsigned long
1555 xfs_buftarg_shrink_scan(
1556 	struct shrinker		*shrink,
1557 	struct shrink_control	*sc)
1558 {
1559 	struct xfs_buftarg	*btp = shrink->private_data;
1560 	LIST_HEAD(dispose);
1561 	unsigned long		freed;
1562 
1563 	freed = list_lru_shrink_walk(&btp->bt_lru, sc,
1564 				     xfs_buftarg_isolate, &dispose);
1565 
1566 	while (!list_empty(&dispose)) {
1567 		struct xfs_buf *bp;
1568 		bp = list_first_entry(&dispose, struct xfs_buf, b_lru);
1569 		list_del_init(&bp->b_lru);
1570 		xfs_buf_destroy(bp);
1571 	}
1572 
1573 	return freed;
1574 }
1575 
1576 static unsigned long
1577 xfs_buftarg_shrink_count(
1578 	struct shrinker		*shrink,
1579 	struct shrink_control	*sc)
1580 {
1581 	struct xfs_buftarg	*btp = shrink->private_data;
1582 	return list_lru_shrink_count(&btp->bt_lru, sc);
1583 }
1584 
1585 void
1586 xfs_destroy_buftarg(
1587 	struct xfs_buftarg	*btp)
1588 {
1589 	shrinker_free(btp->bt_shrinker);
1590 	ASSERT(percpu_counter_sum(&btp->bt_readahead_count) == 0);
1591 	percpu_counter_destroy(&btp->bt_readahead_count);
1592 	list_lru_destroy(&btp->bt_lru);
1593 	rhashtable_destroy(&btp->bt_hash);
1594 }
1595 
1596 void
1597 xfs_free_buftarg(
1598 	struct xfs_buftarg	*btp)
1599 {
1600 	xfs_destroy_buftarg(btp);
1601 	fs_put_dax(btp->bt_daxdev, btp->bt_mount);
1602 	/* the main block device is closed by kill_block_super */
1603 	if (btp->bt_bdev != btp->bt_mount->m_super->s_bdev)
1604 		bdev_fput(btp->bt_file);
1605 	kfree(btp);
1606 }
1607 
1608 /*
1609  * Configure this buffer target for hardware-assisted atomic writes if the
1610  * underlying block device supports is congruent with the filesystem geometry.
1611  */
1612 static inline void
1613 xfs_configure_buftarg_atomic_writes(
1614 	struct xfs_buftarg	*btp)
1615 {
1616 	struct xfs_mount	*mp = btp->bt_mount;
1617 	unsigned int		min_bytes, max_bytes;
1618 
1619 	min_bytes = bdev_atomic_write_unit_min_bytes(btp->bt_bdev);
1620 	max_bytes = bdev_atomic_write_unit_max_bytes(btp->bt_bdev);
1621 
1622 	/*
1623 	 * Ignore atomic write geometry that is nonsense or doesn't even cover
1624 	 * a single fsblock.
1625 	 */
1626 	if (min_bytes > max_bytes ||
1627 	    min_bytes > mp->m_sb.sb_blocksize ||
1628 	    max_bytes < mp->m_sb.sb_blocksize) {
1629 		min_bytes = 0;
1630 		max_bytes = 0;
1631 	}
1632 
1633 	btp->bt_awu_min = min_bytes;
1634 	btp->bt_awu_max = max_bytes;
1635 }
1636 
1637 /* Configure a buffer target that abstracts a block device. */
1638 int
1639 xfs_configure_buftarg(
1640 	struct xfs_buftarg	*btp,
1641 	unsigned int		sectorsize,
1642 	xfs_rfsblock_t		nr_blocks)
1643 {
1644 	struct xfs_mount	*mp = btp->bt_mount;
1645 
1646 	if (btp->bt_bdev) {
1647 		int		error;
1648 
1649 		error = bdev_validate_blocksize(btp->bt_bdev, sectorsize);
1650 		if (error) {
1651 			xfs_warn(mp,
1652 				"Cannot use blocksize %u on device %pg, err %d",
1653 				sectorsize, btp->bt_bdev, error);
1654 			return -EINVAL;
1655 		}
1656 
1657 		if (bdev_can_atomic_write(btp->bt_bdev))
1658 			xfs_configure_buftarg_atomic_writes(btp);
1659 	}
1660 
1661 	btp->bt_meta_sectorsize = sectorsize;
1662 	btp->bt_meta_sectormask = sectorsize - 1;
1663 	/* m_blkbb_log is not set up yet */
1664 	btp->bt_nr_sectors = nr_blocks << (mp->m_sb.sb_blocklog - BBSHIFT);
1665 	return 0;
1666 }
1667 
1668 int
1669 xfs_init_buftarg(
1670 	struct xfs_buftarg		*btp,
1671 	size_t				logical_sectorsize,
1672 	const char			*descr)
1673 {
1674 	/* The maximum size of the buftarg is only known once the sb is read. */
1675 	btp->bt_nr_sectors = XFS_BUF_DADDR_MAX;
1676 
1677 	/* Set up device logical sector size mask */
1678 	btp->bt_logical_sectorsize = logical_sectorsize;
1679 	btp->bt_logical_sectormask = logical_sectorsize - 1;
1680 
1681 	/*
1682 	 * Buffer IO error rate limiting. Limit it to no more than 10 messages
1683 	 * per 30 seconds so as to not spam logs too much on repeated errors.
1684 	 */
1685 	ratelimit_state_init(&btp->bt_ioerror_rl, 30 * HZ,
1686 			     DEFAULT_RATELIMIT_BURST);
1687 
1688 	if (rhashtable_init(&btp->bt_hash, &xfs_buf_hash_params))
1689 		return -ENOMEM;
1690 	if (list_lru_init(&btp->bt_lru))
1691 		goto out_destroy_hash;
1692 	if (percpu_counter_init(&btp->bt_readahead_count, 0, GFP_KERNEL))
1693 		goto out_destroy_lru;
1694 
1695 	btp->bt_shrinker =
1696 		shrinker_alloc(SHRINKER_NUMA_AWARE, "xfs-buf:%s", descr);
1697 	if (!btp->bt_shrinker)
1698 		goto out_destroy_io_count;
1699 	btp->bt_shrinker->count_objects = xfs_buftarg_shrink_count;
1700 	btp->bt_shrinker->scan_objects = xfs_buftarg_shrink_scan;
1701 	btp->bt_shrinker->private_data = btp;
1702 	shrinker_register(btp->bt_shrinker);
1703 	return 0;
1704 
1705 out_destroy_io_count:
1706 	percpu_counter_destroy(&btp->bt_readahead_count);
1707 out_destroy_lru:
1708 	list_lru_destroy(&btp->bt_lru);
1709 out_destroy_hash:
1710 	rhashtable_destroy(&btp->bt_hash);
1711 	return -ENOMEM;
1712 }
1713 
1714 struct xfs_buftarg *
1715 xfs_alloc_buftarg(
1716 	struct xfs_mount	*mp,
1717 	struct file		*bdev_file)
1718 {
1719 	struct xfs_buftarg	*btp;
1720 	const struct dax_holder_operations *ops = NULL;
1721 	int			error;
1722 
1723 
1724 #if defined(CONFIG_FS_DAX) && defined(CONFIG_MEMORY_FAILURE)
1725 	ops = &xfs_dax_holder_operations;
1726 #endif
1727 	btp = kzalloc_obj(*btp, GFP_KERNEL | __GFP_NOFAIL);
1728 
1729 	btp->bt_mount = mp;
1730 	btp->bt_file = bdev_file;
1731 	btp->bt_bdev = file_bdev(bdev_file);
1732 	btp->bt_dev = btp->bt_bdev->bd_dev;
1733 	btp->bt_daxdev = fs_dax_get_by_bdev(btp->bt_bdev, &btp->bt_dax_part_off,
1734 					    mp, ops);
1735 
1736 	/*
1737 	 * Flush and invalidate all devices' pagecaches before reading any
1738 	 * metadata because XFS doesn't use the bdev pagecache.
1739 	 */
1740 	error = sync_blockdev(btp->bt_bdev);
1741 	if (error)
1742 		goto error_free;
1743 
1744 	/*
1745 	 * When allocating the buftargs we have not yet read the super block and
1746 	 * thus don't know the file system sector size yet.
1747 	 */
1748 	btp->bt_meta_sectorsize = bdev_logical_block_size(btp->bt_bdev);
1749 	btp->bt_meta_sectormask = btp->bt_meta_sectorsize - 1;
1750 
1751 	error = xfs_init_buftarg(btp, btp->bt_meta_sectorsize,
1752 				mp->m_super->s_id);
1753 	if (error)
1754 		goto error_free;
1755 
1756 	return btp;
1757 
1758 error_free:
1759 	fs_put_dax(btp->bt_daxdev, mp);
1760 	kfree(btp);
1761 	return ERR_PTR(error);
1762 }
1763 
1764 static inline void
1765 xfs_buf_list_del(
1766 	struct xfs_buf		*bp)
1767 {
1768 	list_del_init(&bp->b_list);
1769 	wake_up_var(&bp->b_list);
1770 }
1771 
1772 /*
1773  * Cancel a delayed write list.
1774  *
1775  * Remove each buffer from the list, clear the delwri queue flag and drop the
1776  * associated buffer reference.
1777  */
1778 void
1779 xfs_buf_delwri_cancel(
1780 	struct list_head	*list)
1781 {
1782 	struct xfs_buf		*bp;
1783 
1784 	while (!list_empty(list)) {
1785 		bp = list_first_entry(list, struct xfs_buf, b_list);
1786 
1787 		xfs_buf_lock(bp);
1788 		bp->b_flags &= ~_XBF_DELWRI_Q;
1789 		xfs_buf_list_del(bp);
1790 		xfs_buf_relse(bp);
1791 	}
1792 }
1793 
1794 /*
1795  * Add a buffer to the delayed write list.
1796  *
1797  * This queues a buffer for writeout if it hasn't already been.  Note that
1798  * neither this routine nor the buffer list submission functions perform
1799  * any internal synchronization.  It is expected that the lists are thread-local
1800  * to the callers.
1801  *
1802  * Returns true if we queued up the buffer, or false if it already had
1803  * been on the buffer list.
1804  */
1805 bool
1806 xfs_buf_delwri_queue(
1807 	struct xfs_buf		*bp,
1808 	struct list_head	*list)
1809 {
1810 	ASSERT(xfs_buf_islocked(bp));
1811 	ASSERT(!(bp->b_flags & XBF_READ));
1812 
1813 	/*
1814 	 * If the buffer is already marked delwri it already is queued up
1815 	 * by someone else for imediate writeout.  Just ignore it in that
1816 	 * case.
1817 	 */
1818 	if (bp->b_flags & _XBF_DELWRI_Q) {
1819 		trace_xfs_buf_delwri_queued(bp, _RET_IP_);
1820 		return false;
1821 	}
1822 
1823 	trace_xfs_buf_delwri_queue(bp, _RET_IP_);
1824 
1825 	/*
1826 	 * If a buffer gets written out synchronously or marked stale while it
1827 	 * is on a delwri list we lazily remove it. To do this, the other party
1828 	 * clears the  _XBF_DELWRI_Q flag but otherwise leaves the buffer alone.
1829 	 * It remains referenced and on the list.  In a rare corner case it
1830 	 * might get readded to a delwri list after the synchronous writeout, in
1831 	 * which case we need just need to re-add the flag here.
1832 	 */
1833 	bp->b_flags |= _XBF_DELWRI_Q;
1834 	if (list_empty(&bp->b_list)) {
1835 		xfs_buf_hold(bp);
1836 		list_add_tail(&bp->b_list, list);
1837 	}
1838 
1839 	return true;
1840 }
1841 
1842 /*
1843  * Queue a buffer to this delwri list as part of a data integrity operation.
1844  * If the buffer is on any other delwri list, we'll wait for that to clear
1845  * so that the caller can submit the buffer for IO and wait for the result.
1846  * Callers must ensure the buffer is not already on the list.
1847  */
1848 void
1849 xfs_buf_delwri_queue_here(
1850 	struct xfs_buf		*bp,
1851 	struct list_head	*buffer_list)
1852 {
1853 	/*
1854 	 * We need this buffer to end up on the /caller's/ delwri list, not any
1855 	 * old list.  This can happen if the buffer is marked stale (which
1856 	 * clears DELWRI_Q) after the AIL queues the buffer to its list but
1857 	 * before the AIL has a chance to submit the list.
1858 	 */
1859 	while (!list_empty(&bp->b_list)) {
1860 		xfs_buf_unlock(bp);
1861 		wait_var_event(&bp->b_list, list_empty(&bp->b_list));
1862 		xfs_buf_lock(bp);
1863 	}
1864 
1865 	ASSERT(!(bp->b_flags & _XBF_DELWRI_Q));
1866 
1867 	xfs_buf_delwri_queue(bp, buffer_list);
1868 }
1869 
1870 /*
1871  * Compare function is more complex than it needs to be because
1872  * the return value is only 32 bits and we are doing comparisons
1873  * on 64 bit values
1874  */
1875 static int
1876 xfs_buf_cmp(
1877 	void			*priv,
1878 	const struct list_head	*a,
1879 	const struct list_head	*b)
1880 {
1881 	struct xfs_buf	*ap = container_of(a, struct xfs_buf, b_list);
1882 	struct xfs_buf	*bp = container_of(b, struct xfs_buf, b_list);
1883 	xfs_daddr_t		diff;
1884 
1885 	diff = ap->b_maps[0].bm_bn - bp->b_maps[0].bm_bn;
1886 	if (diff < 0)
1887 		return -1;
1888 	if (diff > 0)
1889 		return 1;
1890 	return 0;
1891 }
1892 
1893 static bool
1894 xfs_buf_delwri_submit_prep(
1895 	struct xfs_buf		*bp)
1896 {
1897 	/*
1898 	 * Someone else might have written the buffer synchronously or marked it
1899 	 * stale in the meantime.  In that case only the _XBF_DELWRI_Q flag got
1900 	 * cleared, and we have to drop the reference and remove it from the
1901 	 * list here.
1902 	 */
1903 	if (!(bp->b_flags & _XBF_DELWRI_Q)) {
1904 		xfs_buf_list_del(bp);
1905 		xfs_buf_relse(bp);
1906 		return false;
1907 	}
1908 
1909 	trace_xfs_buf_delwri_split(bp, _RET_IP_);
1910 	bp->b_flags &= ~_XBF_DELWRI_Q;
1911 	bp->b_flags |= XBF_WRITE;
1912 	return true;
1913 }
1914 
1915 /*
1916  * Write out a buffer list asynchronously.
1917  *
1918  * This will take the @buffer_list, write all non-locked and non-pinned buffers
1919  * out and not wait for I/O completion on any of the buffers.  This interface
1920  * is only safely useable for callers that can track I/O completion by higher
1921  * level means, e.g. AIL pushing as the @buffer_list is consumed in this
1922  * function.
1923  *
1924  * Note: this function will skip buffers it would block on, and in doing so
1925  * leaves them on @buffer_list so they can be retried on a later pass. As such,
1926  * it is up to the caller to ensure that the buffer list is fully submitted or
1927  * cancelled appropriately when they are finished with the list. Failure to
1928  * cancel or resubmit the list until it is empty will result in leaked buffers
1929  * at unmount time.
1930  */
1931 int
1932 xfs_buf_delwri_submit_nowait(
1933 	struct list_head	*buffer_list)
1934 {
1935 	struct xfs_buf		*bp, *n;
1936 	int			pinned = 0;
1937 	struct blk_plug		plug;
1938 
1939 	list_sort(NULL, buffer_list, xfs_buf_cmp);
1940 
1941 	blk_start_plug(&plug);
1942 	list_for_each_entry_safe(bp, n, buffer_list, b_list) {
1943 		if (!xfs_buf_trylock(bp))
1944 			continue;
1945 		if (xfs_buf_ispinned(bp)) {
1946 			xfs_buf_unlock(bp);
1947 			pinned++;
1948 			continue;
1949 		}
1950 		if (!xfs_buf_delwri_submit_prep(bp))
1951 			continue;
1952 		bp->b_flags |= XBF_ASYNC;
1953 		xfs_buf_list_del(bp);
1954 		xfs_buf_submit(bp);
1955 	}
1956 	blk_finish_plug(&plug);
1957 
1958 	return pinned;
1959 }
1960 
1961 /*
1962  * Write out a buffer list synchronously.
1963  *
1964  * This will take the @buffer_list, write all buffers out and wait for I/O
1965  * completion on all of the buffers. @buffer_list is consumed by the function,
1966  * so callers must have some other way of tracking buffers if they require such
1967  * functionality.
1968  */
1969 int
1970 xfs_buf_delwri_submit(
1971 	struct list_head	*buffer_list)
1972 {
1973 	LIST_HEAD		(wait_list);
1974 	int			error = 0, error2;
1975 	struct xfs_buf		*bp, *n;
1976 	struct blk_plug		plug;
1977 
1978 	list_sort(NULL, buffer_list, xfs_buf_cmp);
1979 
1980 	blk_start_plug(&plug);
1981 	list_for_each_entry_safe(bp, n, buffer_list, b_list) {
1982 		xfs_buf_lock(bp);
1983 		if (!xfs_buf_delwri_submit_prep(bp))
1984 			continue;
1985 		bp->b_flags &= ~XBF_ASYNC;
1986 		list_move_tail(&bp->b_list, &wait_list);
1987 		xfs_buf_submit(bp);
1988 	}
1989 	blk_finish_plug(&plug);
1990 
1991 	/* Wait for IO to complete. */
1992 	while (!list_empty(&wait_list)) {
1993 		bp = list_first_entry(&wait_list, struct xfs_buf, b_list);
1994 
1995 		xfs_buf_list_del(bp);
1996 
1997 		/*
1998 		 * Wait on the locked buffer, check for errors and unlock and
1999 		 * release the delwri queue reference.
2000 		 */
2001 		error2 = xfs_buf_iowait(bp);
2002 		xfs_buf_relse(bp);
2003 		if (!error)
2004 			error = error2;
2005 	}
2006 
2007 	return error;
2008 }
2009 
2010 void xfs_buf_set_ref(struct xfs_buf *bp, int lru_ref)
2011 {
2012 	/*
2013 	 * Set the lru reference count to 0 based on the error injection tag.
2014 	 * This allows userspace to disrupt buffer caching for debug/testing
2015 	 * purposes.
2016 	 */
2017 	if (XFS_TEST_ERROR(bp->b_mount, XFS_ERRTAG_BUF_LRU_REF))
2018 		lru_ref = 0;
2019 
2020 	atomic_set(&bp->b_lru_ref, lru_ref);
2021 }
2022 
2023 /*
2024  * Verify an on-disk magic value against the magic value specified in the
2025  * verifier structure. The verifier magic is in disk byte order so the caller is
2026  * expected to pass the value directly from disk.
2027  */
2028 bool
2029 xfs_verify_magic(
2030 	struct xfs_buf		*bp,
2031 	__be32			dmagic)
2032 {
2033 	struct xfs_mount	*mp = bp->b_mount;
2034 	int			idx;
2035 
2036 	idx = xfs_has_crc(mp);
2037 	if (WARN_ON(!bp->b_ops || !bp->b_ops->magic[idx]))
2038 		return false;
2039 	return dmagic == bp->b_ops->magic[idx];
2040 }
2041 /*
2042  * Verify an on-disk magic value against the magic value specified in the
2043  * verifier structure. The verifier magic is in disk byte order so the caller is
2044  * expected to pass the value directly from disk.
2045  */
2046 bool
2047 xfs_verify_magic16(
2048 	struct xfs_buf		*bp,
2049 	__be16			dmagic)
2050 {
2051 	struct xfs_mount	*mp = bp->b_mount;
2052 	int			idx;
2053 
2054 	idx = xfs_has_crc(mp);
2055 	if (WARN_ON(!bp->b_ops || !bp->b_ops->magic16[idx]))
2056 		return false;
2057 	return dmagic == bp->b_ops->magic16[idx];
2058 }
2059