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