xref: /freebsd-src/sys/contrib/openzfs/module/zfs/abd.c (revision 2aa3ef285a23d802f0bd6c7281612e16834e9b68)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2014 by Chunwei Chen. All rights reserved.
23  * Copyright (c) 2019 by Delphix. All rights reserved.
24  */
25 
26 /*
27  * ARC buffer data (ABD).
28  *
29  * ABDs are an abstract data structure for the ARC which can use two
30  * different ways of storing the underlying data:
31  *
32  * (a) Linear buffer. In this case, all the data in the ABD is stored in one
33  *     contiguous buffer in memory (from a zio_[data_]buf_* kmem cache).
34  *
35  *         +-------------------+
36  *         | ABD (linear)      |
37  *         |   abd_flags = ... |
38  *         |   abd_size = ...  |     +--------------------------------+
39  *         |   abd_buf ------------->| raw buffer of size abd_size    |
40  *         +-------------------+     +--------------------------------+
41  *              no abd_chunks
42  *
43  * (b) Scattered buffer. In this case, the data in the ABD is split into
44  *     equal-sized chunks (from the abd_chunk_cache kmem_cache), with pointers
45  *     to the chunks recorded in an array at the end of the ABD structure.
46  *
47  *         +-------------------+
48  *         | ABD (scattered)   |
49  *         |   abd_flags = ... |
50  *         |   abd_size = ...  |
51  *         |   abd_offset = 0  |                           +-----------+
52  *         |   abd_chunks[0] ----------------------------->| chunk 0   |
53  *         |   abd_chunks[1] ---------------------+        +-----------+
54  *         |   ...             |                  |        +-----------+
55  *         |   abd_chunks[N-1] ---------+         +------->| chunk 1   |
56  *         +-------------------+        |                  +-----------+
57  *                                      |                      ...
58  *                                      |                  +-----------+
59  *                                      +----------------->| chunk N-1 |
60  *                                                         +-----------+
61  *
62  * In addition to directly allocating a linear or scattered ABD, it is also
63  * possible to create an ABD by requesting the "sub-ABD" starting at an offset
64  * within an existing ABD. In linear buffers this is simple (set abd_buf of
65  * the new ABD to the starting point within the original raw buffer), but
66  * scattered ABDs are a little more complex. The new ABD makes a copy of the
67  * relevant abd_chunks pointers (but not the underlying data). However, to
68  * provide arbitrary rather than only chunk-aligned starting offsets, it also
69  * tracks an abd_offset field which represents the starting point of the data
70  * within the first chunk in abd_chunks. For both linear and scattered ABDs,
71  * creating an offset ABD marks the original ABD as the offset's parent, and the
72  * original ABD's abd_children refcount is incremented. This data allows us to
73  * ensure the root ABD isn't deleted before its children.
74  *
75  * Most consumers should never need to know what type of ABD they're using --
76  * the ABD public API ensures that it's possible to transparently switch from
77  * using a linear ABD to a scattered one when doing so would be beneficial.
78  *
79  * If you need to use the data within an ABD directly, if you know it's linear
80  * (because you allocated it) you can use abd_to_buf() to access the underlying
81  * raw buffer. Otherwise, you should use one of the abd_borrow_buf* functions
82  * which will allocate a raw buffer if necessary. Use the abd_return_buf*
83  * functions to return any raw buffers that are no longer necessary when you're
84  * done using them.
85  *
86  * There are a variety of ABD APIs that implement basic buffer operations:
87  * compare, copy, read, write, and fill with zeroes. If you need a custom
88  * function which progressively accesses the whole ABD, use the abd_iterate_*
89  * functions.
90  *
91  * As an additional feature, linear and scatter ABD's can be stitched together
92  * by using the gang ABD type (abd_alloc_gang_abd()). This allows for
93  * multiple ABDs to be viewed as a singular ABD.
94  *
95  * It is possible to make all ABDs linear by setting zfs_abd_scatter_enabled to
96  * B_FALSE.
97  */
98 
99 #include <sys/abd_impl.h>
100 #include <sys/param.h>
101 #include <sys/zio.h>
102 #include <sys/zfs_context.h>
103 #include <sys/zfs_znode.h>
104 
105 /* see block comment above for description */
106 int zfs_abd_scatter_enabled = B_TRUE;
107 
108 void
109 abd_verify(abd_t *abd)
110 {
111 	ASSERT3U(abd->abd_size, >, 0);
112 	ASSERT3U(abd->abd_size, <=, SPA_MAXBLOCKSIZE);
113 	ASSERT3U(abd->abd_flags, ==, abd->abd_flags & (ABD_FLAG_LINEAR |
114 	    ABD_FLAG_OWNER | ABD_FLAG_META | ABD_FLAG_MULTI_ZONE |
115 	    ABD_FLAG_MULTI_CHUNK | ABD_FLAG_LINEAR_PAGE | ABD_FLAG_GANG |
116 	    ABD_FLAG_GANG_FREE | ABD_FLAG_ZEROS | ABD_FLAG_ALLOCD));
117 #ifdef ZFS_DEBUG
118 	IMPLY(abd->abd_parent != NULL, !(abd->abd_flags & ABD_FLAG_OWNER));
119 #endif
120 	IMPLY(abd->abd_flags & ABD_FLAG_META, abd->abd_flags & ABD_FLAG_OWNER);
121 	if (abd_is_linear(abd)) {
122 		ASSERT3P(ABD_LINEAR_BUF(abd), !=, NULL);
123 	} else if (abd_is_gang(abd)) {
124 		uint_t child_sizes = 0;
125 		for (abd_t *cabd = list_head(&ABD_GANG(abd).abd_gang_chain);
126 		    cabd != NULL;
127 		    cabd = list_next(&ABD_GANG(abd).abd_gang_chain, cabd)) {
128 			ASSERT(list_link_active(&cabd->abd_gang_link));
129 			child_sizes += cabd->abd_size;
130 			abd_verify(cabd);
131 		}
132 		ASSERT3U(abd->abd_size, ==, child_sizes);
133 	} else {
134 		abd_verify_scatter(abd);
135 	}
136 }
137 
138 static void
139 abd_init_struct(abd_t *abd)
140 {
141 	list_link_init(&abd->abd_gang_link);
142 	mutex_init(&abd->abd_mtx, NULL, MUTEX_DEFAULT, NULL);
143 	abd->abd_flags = 0;
144 #ifdef ZFS_DEBUG
145 	zfs_refcount_create(&abd->abd_children);
146 	abd->abd_parent = NULL;
147 #endif
148 	abd->abd_size = 0;
149 }
150 
151 static void
152 abd_fini_struct(abd_t *abd)
153 {
154 	mutex_destroy(&abd->abd_mtx);
155 	ASSERT(!list_link_active(&abd->abd_gang_link));
156 #ifdef ZFS_DEBUG
157 	zfs_refcount_destroy(&abd->abd_children);
158 #endif
159 }
160 
161 abd_t *
162 abd_alloc_struct(size_t size)
163 {
164 	abd_t *abd = abd_alloc_struct_impl(size);
165 	abd_init_struct(abd);
166 	abd->abd_flags |= ABD_FLAG_ALLOCD;
167 	return (abd);
168 }
169 
170 void
171 abd_free_struct(abd_t *abd)
172 {
173 	abd_fini_struct(abd);
174 	abd_free_struct_impl(abd);
175 }
176 
177 /*
178  * Allocate an ABD, along with its own underlying data buffers. Use this if you
179  * don't care whether the ABD is linear or not.
180  */
181 abd_t *
182 abd_alloc(size_t size, boolean_t is_metadata)
183 {
184 	if (!zfs_abd_scatter_enabled || abd_size_alloc_linear(size))
185 		return (abd_alloc_linear(size, is_metadata));
186 
187 	VERIFY3U(size, <=, SPA_MAXBLOCKSIZE);
188 
189 	abd_t *abd = abd_alloc_struct(size);
190 	abd->abd_flags |= ABD_FLAG_OWNER;
191 	abd->abd_u.abd_scatter.abd_offset = 0;
192 	abd_alloc_chunks(abd, size);
193 
194 	if (is_metadata) {
195 		abd->abd_flags |= ABD_FLAG_META;
196 	}
197 	abd->abd_size = size;
198 
199 	abd_update_scatter_stats(abd, ABDSTAT_INCR);
200 
201 	return (abd);
202 }
203 
204 /*
205  * Allocate an ABD that must be linear, along with its own underlying data
206  * buffer. Only use this when it would be very annoying to write your ABD
207  * consumer with a scattered ABD.
208  */
209 abd_t *
210 abd_alloc_linear(size_t size, boolean_t is_metadata)
211 {
212 	abd_t *abd = abd_alloc_struct(0);
213 
214 	VERIFY3U(size, <=, SPA_MAXBLOCKSIZE);
215 
216 	abd->abd_flags |= ABD_FLAG_LINEAR | ABD_FLAG_OWNER;
217 	if (is_metadata) {
218 		abd->abd_flags |= ABD_FLAG_META;
219 	}
220 	abd->abd_size = size;
221 
222 	if (is_metadata) {
223 		ABD_LINEAR_BUF(abd) = zio_buf_alloc(size);
224 	} else {
225 		ABD_LINEAR_BUF(abd) = zio_data_buf_alloc(size);
226 	}
227 
228 	abd_update_linear_stats(abd, ABDSTAT_INCR);
229 
230 	return (abd);
231 }
232 
233 static void
234 abd_free_linear(abd_t *abd)
235 {
236 	if (abd_is_linear_page(abd)) {
237 		abd_free_linear_page(abd);
238 		return;
239 	}
240 	if (abd->abd_flags & ABD_FLAG_META) {
241 		zio_buf_free(ABD_LINEAR_BUF(abd), abd->abd_size);
242 	} else {
243 		zio_data_buf_free(ABD_LINEAR_BUF(abd), abd->abd_size);
244 	}
245 
246 	abd_update_linear_stats(abd, ABDSTAT_DECR);
247 }
248 
249 static void
250 abd_free_gang(abd_t *abd)
251 {
252 	ASSERT(abd_is_gang(abd));
253 	abd_t *cabd;
254 
255 	while ((cabd = list_head(&ABD_GANG(abd).abd_gang_chain)) != NULL) {
256 		/*
257 		 * We must acquire the child ABDs mutex to ensure that if it
258 		 * is being added to another gang ABD we will set the link
259 		 * as inactive when removing it from this gang ABD and before
260 		 * adding it to the other gang ABD.
261 		 */
262 		mutex_enter(&cabd->abd_mtx);
263 		ASSERT(list_link_active(&cabd->abd_gang_link));
264 		list_remove(&ABD_GANG(abd).abd_gang_chain, cabd);
265 		mutex_exit(&cabd->abd_mtx);
266 		if (cabd->abd_flags & ABD_FLAG_GANG_FREE)
267 			abd_free(cabd);
268 	}
269 	list_destroy(&ABD_GANG(abd).abd_gang_chain);
270 }
271 
272 static void
273 abd_free_scatter(abd_t *abd)
274 {
275 	abd_free_chunks(abd);
276 	abd_update_scatter_stats(abd, ABDSTAT_DECR);
277 }
278 
279 /*
280  * Free an ABD.  Use with any kind of abd: those created with abd_alloc_*()
281  * and abd_get_*(), including abd_get_offset_struct().
282  *
283  * If the ABD was created with abd_alloc_*(), the underlying data
284  * (scatterlist or linear buffer) will also be freed.  (Subject to ownership
285  * changes via abd_*_ownership_of_buf().)
286  *
287  * Unless the ABD was created with abd_get_offset_struct(), the abd_t will
288  * also be freed.
289  */
290 void
291 abd_free(abd_t *abd)
292 {
293 	if (abd == NULL)
294 		return;
295 
296 	abd_verify(abd);
297 #ifdef ZFS_DEBUG
298 	IMPLY(abd->abd_flags & ABD_FLAG_OWNER, abd->abd_parent == NULL);
299 #endif
300 
301 	if (abd_is_gang(abd)) {
302 		abd_free_gang(abd);
303 	} else if (abd_is_linear(abd)) {
304 		if (abd->abd_flags & ABD_FLAG_OWNER)
305 			abd_free_linear(abd);
306 	} else {
307 		if (abd->abd_flags & ABD_FLAG_OWNER)
308 			abd_free_scatter(abd);
309 	}
310 
311 #ifdef ZFS_DEBUG
312 	if (abd->abd_parent != NULL) {
313 		(void) zfs_refcount_remove_many(&abd->abd_parent->abd_children,
314 		    abd->abd_size, abd);
315 	}
316 #endif
317 
318 	abd_fini_struct(abd);
319 	if (abd->abd_flags & ABD_FLAG_ALLOCD)
320 		abd_free_struct_impl(abd);
321 }
322 
323 /*
324  * Allocate an ABD of the same format (same metadata flag, same scatterize
325  * setting) as another ABD.
326  */
327 abd_t *
328 abd_alloc_sametype(abd_t *sabd, size_t size)
329 {
330 	boolean_t is_metadata = (sabd->abd_flags & ABD_FLAG_META) != 0;
331 	if (abd_is_linear(sabd) &&
332 	    !abd_is_linear_page(sabd)) {
333 		return (abd_alloc_linear(size, is_metadata));
334 	} else {
335 		return (abd_alloc(size, is_metadata));
336 	}
337 }
338 
339 /*
340  * Create gang ABD that will be the head of a list of ABD's. This is used
341  * to "chain" scatter/gather lists together when constructing aggregated
342  * IO's. To free this abd, abd_free() must be called.
343  */
344 abd_t *
345 abd_alloc_gang(void)
346 {
347 	abd_t *abd = abd_alloc_struct(0);
348 	abd->abd_flags |= ABD_FLAG_GANG | ABD_FLAG_OWNER;
349 	list_create(&ABD_GANG(abd).abd_gang_chain,
350 	    sizeof (abd_t), offsetof(abd_t, abd_gang_link));
351 	return (abd);
352 }
353 
354 /*
355  * Add a child gang ABD to a parent gang ABDs chained list.
356  */
357 static void
358 abd_gang_add_gang(abd_t *pabd, abd_t *cabd, boolean_t free_on_free)
359 {
360 	ASSERT(abd_is_gang(pabd));
361 	ASSERT(abd_is_gang(cabd));
362 
363 	if (free_on_free) {
364 		/*
365 		 * If the parent is responsible for freeing the child gang
366 		 * ABD we will just splice the child's children ABD list to
367 		 * the parent's list and immediately free the child gang ABD
368 		 * struct. The parent gang ABDs children from the child gang
369 		 * will retain all the free_on_free settings after being
370 		 * added to the parents list.
371 		 */
372 		pabd->abd_size += cabd->abd_size;
373 		list_move_tail(&ABD_GANG(pabd).abd_gang_chain,
374 		    &ABD_GANG(cabd).abd_gang_chain);
375 		ASSERT(list_is_empty(&ABD_GANG(cabd).abd_gang_chain));
376 		abd_verify(pabd);
377 		abd_free(cabd);
378 	} else {
379 		for (abd_t *child = list_head(&ABD_GANG(cabd).abd_gang_chain);
380 		    child != NULL;
381 		    child = list_next(&ABD_GANG(cabd).abd_gang_chain, child)) {
382 			/*
383 			 * We always pass B_FALSE for free_on_free as it is the
384 			 * original child gang ABDs responsibilty to determine
385 			 * if any of its child ABDs should be free'd on the call
386 			 * to abd_free().
387 			 */
388 			abd_gang_add(pabd, child, B_FALSE);
389 		}
390 		abd_verify(pabd);
391 	}
392 }
393 
394 /*
395  * Add a child ABD to a gang ABD's chained list.
396  */
397 void
398 abd_gang_add(abd_t *pabd, abd_t *cabd, boolean_t free_on_free)
399 {
400 	ASSERT(abd_is_gang(pabd));
401 	abd_t *child_abd = NULL;
402 
403 	/*
404 	 * If the child being added is a gang ABD, we will add the
405 	 * child's ABDs to the parent gang ABD. This allows us to account
406 	 * for the offset correctly in the parent gang ABD.
407 	 */
408 	if (abd_is_gang(cabd)) {
409 		ASSERT(!list_link_active(&cabd->abd_gang_link));
410 		ASSERT(!list_is_empty(&ABD_GANG(cabd).abd_gang_chain));
411 		return (abd_gang_add_gang(pabd, cabd, free_on_free));
412 	}
413 	ASSERT(!abd_is_gang(cabd));
414 
415 	/*
416 	 * In order to verify that an ABD is not already part of
417 	 * another gang ABD, we must lock the child ABD's abd_mtx
418 	 * to check its abd_gang_link status. We unlock the abd_mtx
419 	 * only after it is has been added to a gang ABD, which
420 	 * will update the abd_gang_link's status. See comment below
421 	 * for how an ABD can be in multiple gang ABD's simultaneously.
422 	 */
423 	mutex_enter(&cabd->abd_mtx);
424 	if (list_link_active(&cabd->abd_gang_link)) {
425 		/*
426 		 * If the child ABD is already part of another
427 		 * gang ABD then we must allocate a new
428 		 * ABD to use a separate link. We mark the newly
429 		 * allocated ABD with ABD_FLAG_GANG_FREE, before
430 		 * adding it to the gang ABD's list, to make the
431 		 * gang ABD aware that it is responsible to call
432 		 * abd_free(). We use abd_get_offset() in order
433 		 * to just allocate a new ABD but avoid copying the
434 		 * data over into the newly allocated ABD.
435 		 *
436 		 * An ABD may become part of multiple gang ABD's. For
437 		 * example, when writing ditto bocks, the same ABD
438 		 * is used to write 2 or 3 locations with 2 or 3
439 		 * zio_t's. Each of the zio's may be aggregated with
440 		 * different adjacent zio's. zio aggregation uses gang
441 		 * zio's, so the single ABD can become part of multiple
442 		 * gang zio's.
443 		 *
444 		 * The ASSERT below is to make sure that if
445 		 * free_on_free is passed as B_TRUE, the ABD can
446 		 * not be in multiple gang ABD's. The gang ABD
447 		 * can not be responsible for cleaning up the child
448 		 * ABD memory allocation if the ABD can be in
449 		 * multiple gang ABD's at one time.
450 		 */
451 		ASSERT3B(free_on_free, ==, B_FALSE);
452 		child_abd = abd_get_offset(cabd, 0);
453 		child_abd->abd_flags |= ABD_FLAG_GANG_FREE;
454 	} else {
455 		child_abd = cabd;
456 		if (free_on_free)
457 			child_abd->abd_flags |= ABD_FLAG_GANG_FREE;
458 	}
459 	ASSERT3P(child_abd, !=, NULL);
460 
461 	list_insert_tail(&ABD_GANG(pabd).abd_gang_chain, child_abd);
462 	mutex_exit(&cabd->abd_mtx);
463 	pabd->abd_size += child_abd->abd_size;
464 }
465 
466 /*
467  * Locate the ABD for the supplied offset in the gang ABD.
468  * Return a new offset relative to the returned ABD.
469  */
470 abd_t *
471 abd_gang_get_offset(abd_t *abd, size_t *off)
472 {
473 	abd_t *cabd;
474 
475 	ASSERT(abd_is_gang(abd));
476 	ASSERT3U(*off, <, abd->abd_size);
477 	for (cabd = list_head(&ABD_GANG(abd).abd_gang_chain); cabd != NULL;
478 	    cabd = list_next(&ABD_GANG(abd).abd_gang_chain, cabd)) {
479 		if (*off >= cabd->abd_size)
480 			*off -= cabd->abd_size;
481 		else
482 			return (cabd);
483 	}
484 	VERIFY3P(cabd, !=, NULL);
485 	return (cabd);
486 }
487 
488 /*
489  * Allocate a new ABD, using the provided struct (if non-NULL, and if
490  * circumstances allow - otherwise allocate the struct).  The returned ABD will
491  * point to offset off of sabd. It shares the underlying buffer data with sabd.
492  * Use abd_free() to free.  sabd must not be freed while any derived ABDs exist.
493  */
494 static abd_t *
495 abd_get_offset_impl(abd_t *abd, abd_t *sabd, size_t off, size_t size)
496 {
497 	abd_verify(sabd);
498 	ASSERT3U(off + size, <=, sabd->abd_size);
499 
500 	if (abd_is_linear(sabd)) {
501 		if (abd == NULL)
502 			abd = abd_alloc_struct(0);
503 		/*
504 		 * Even if this buf is filesystem metadata, we only track that
505 		 * if we own the underlying data buffer, which is not true in
506 		 * this case. Therefore, we don't ever use ABD_FLAG_META here.
507 		 */
508 		abd->abd_flags |= ABD_FLAG_LINEAR;
509 
510 		ABD_LINEAR_BUF(abd) = (char *)ABD_LINEAR_BUF(sabd) + off;
511 	} else if (abd_is_gang(sabd)) {
512 		size_t left = size;
513 		if (abd == NULL) {
514 			abd = abd_alloc_gang();
515 		} else {
516 			abd->abd_flags |= ABD_FLAG_GANG;
517 			list_create(&ABD_GANG(abd).abd_gang_chain,
518 			    sizeof (abd_t), offsetof(abd_t, abd_gang_link));
519 		}
520 
521 		abd->abd_flags &= ~ABD_FLAG_OWNER;
522 		for (abd_t *cabd = abd_gang_get_offset(sabd, &off);
523 		    cabd != NULL && left > 0;
524 		    cabd = list_next(&ABD_GANG(sabd).abd_gang_chain, cabd)) {
525 			int csize = MIN(left, cabd->abd_size - off);
526 
527 			abd_t *nabd = abd_get_offset_size(cabd, off, csize);
528 			abd_gang_add(abd, nabd, B_TRUE);
529 			left -= csize;
530 			off = 0;
531 		}
532 		ASSERT3U(left, ==, 0);
533 	} else {
534 		abd = abd_get_offset_scatter(abd, sabd, off);
535 	}
536 
537 	ASSERT3P(abd, !=, NULL);
538 	abd->abd_size = size;
539 #ifdef ZFS_DEBUG
540 	abd->abd_parent = sabd;
541 	(void) zfs_refcount_add_many(&sabd->abd_children, abd->abd_size, abd);
542 #endif
543 	return (abd);
544 }
545 
546 /*
547  * Like abd_get_offset_size(), but memory for the abd_t is provided by the
548  * caller.  Using this routine can improve performance by avoiding the cost
549  * of allocating memory for the abd_t struct, and updating the abd stats.
550  * Usually, the provided abd is returned, but in some circumstances (FreeBSD,
551  * if sabd is scatter and size is more than 2 pages) a new abd_t may need to
552  * be allocated.  Therefore callers should be careful to use the returned
553  * abd_t*.
554  */
555 abd_t *
556 abd_get_offset_struct(abd_t *abd, abd_t *sabd, size_t off, size_t size)
557 {
558 	abd_init_struct(abd);
559 	return (abd_get_offset_impl(abd, sabd, off, size));
560 }
561 
562 abd_t *
563 abd_get_offset(abd_t *sabd, size_t off)
564 {
565 	size_t size = sabd->abd_size > off ? sabd->abd_size - off : 0;
566 	VERIFY3U(size, >, 0);
567 	return (abd_get_offset_impl(NULL, sabd, off, size));
568 }
569 
570 abd_t *
571 abd_get_offset_size(abd_t *sabd, size_t off, size_t size)
572 {
573 	ASSERT3U(off + size, <=, sabd->abd_size);
574 	return (abd_get_offset_impl(NULL, sabd, off, size));
575 }
576 
577 /*
578  * Return a size scatter ABD containing only zeros.
579  */
580 abd_t *
581 abd_get_zeros(size_t size)
582 {
583 	ASSERT3P(abd_zero_scatter, !=, NULL);
584 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
585 	return (abd_get_offset_size(abd_zero_scatter, 0, size));
586 }
587 
588 /*
589  * Allocate a linear ABD structure for buf.
590  */
591 abd_t *
592 abd_get_from_buf(void *buf, size_t size)
593 {
594 	abd_t *abd = abd_alloc_struct(0);
595 
596 	VERIFY3U(size, <=, SPA_MAXBLOCKSIZE);
597 
598 	/*
599 	 * Even if this buf is filesystem metadata, we only track that if we
600 	 * own the underlying data buffer, which is not true in this case.
601 	 * Therefore, we don't ever use ABD_FLAG_META here.
602 	 */
603 	abd->abd_flags |= ABD_FLAG_LINEAR;
604 	abd->abd_size = size;
605 
606 	ABD_LINEAR_BUF(abd) = buf;
607 
608 	return (abd);
609 }
610 
611 /*
612  * Get the raw buffer associated with a linear ABD.
613  */
614 void *
615 abd_to_buf(abd_t *abd)
616 {
617 	ASSERT(abd_is_linear(abd));
618 	abd_verify(abd);
619 	return (ABD_LINEAR_BUF(abd));
620 }
621 
622 /*
623  * Borrow a raw buffer from an ABD without copying the contents of the ABD
624  * into the buffer. If the ABD is scattered, this will allocate a raw buffer
625  * whose contents are undefined. To copy over the existing data in the ABD, use
626  * abd_borrow_buf_copy() instead.
627  */
628 void *
629 abd_borrow_buf(abd_t *abd, size_t n)
630 {
631 	void *buf;
632 	abd_verify(abd);
633 	ASSERT3U(abd->abd_size, >=, n);
634 	if (abd_is_linear(abd)) {
635 		buf = abd_to_buf(abd);
636 	} else {
637 		buf = zio_buf_alloc(n);
638 	}
639 #ifdef ZFS_DEBUG
640 	(void) zfs_refcount_add_many(&abd->abd_children, n, buf);
641 #endif
642 	return (buf);
643 }
644 
645 void *
646 abd_borrow_buf_copy(abd_t *abd, size_t n)
647 {
648 	void *buf = abd_borrow_buf(abd, n);
649 	if (!abd_is_linear(abd)) {
650 		abd_copy_to_buf(buf, abd, n);
651 	}
652 	return (buf);
653 }
654 
655 /*
656  * Return a borrowed raw buffer to an ABD. If the ABD is scattered, this will
657  * not change the contents of the ABD and will ASSERT that you didn't modify
658  * the buffer since it was borrowed. If you want any changes you made to buf to
659  * be copied back to abd, use abd_return_buf_copy() instead.
660  */
661 void
662 abd_return_buf(abd_t *abd, void *buf, size_t n)
663 {
664 	abd_verify(abd);
665 	ASSERT3U(abd->abd_size, >=, n);
666 	if (abd_is_linear(abd)) {
667 		ASSERT3P(buf, ==, abd_to_buf(abd));
668 	} else {
669 		ASSERT0(abd_cmp_buf(abd, buf, n));
670 		zio_buf_free(buf, n);
671 	}
672 #ifdef ZFS_DEBUG
673 	(void) zfs_refcount_remove_many(&abd->abd_children, n, buf);
674 #endif
675 }
676 
677 void
678 abd_return_buf_copy(abd_t *abd, void *buf, size_t n)
679 {
680 	if (!abd_is_linear(abd)) {
681 		abd_copy_from_buf(abd, buf, n);
682 	}
683 	abd_return_buf(abd, buf, n);
684 }
685 
686 void
687 abd_release_ownership_of_buf(abd_t *abd)
688 {
689 	ASSERT(abd_is_linear(abd));
690 	ASSERT(abd->abd_flags & ABD_FLAG_OWNER);
691 
692 	/*
693 	 * abd_free() needs to handle LINEAR_PAGE ABD's specially.
694 	 * Since that flag does not survive the
695 	 * abd_release_ownership_of_buf() -> abd_get_from_buf() ->
696 	 * abd_take_ownership_of_buf() sequence, we don't allow releasing
697 	 * these "linear but not zio_[data_]buf_alloc()'ed" ABD's.
698 	 */
699 	ASSERT(!abd_is_linear_page(abd));
700 
701 	abd_verify(abd);
702 
703 	abd->abd_flags &= ~ABD_FLAG_OWNER;
704 	/* Disable this flag since we no longer own the data buffer */
705 	abd->abd_flags &= ~ABD_FLAG_META;
706 
707 	abd_update_linear_stats(abd, ABDSTAT_DECR);
708 }
709 
710 
711 /*
712  * Give this ABD ownership of the buffer that it's storing. Can only be used on
713  * linear ABDs which were allocated via abd_get_from_buf(), or ones allocated
714  * with abd_alloc_linear() which subsequently released ownership of their buf
715  * with abd_release_ownership_of_buf().
716  */
717 void
718 abd_take_ownership_of_buf(abd_t *abd, boolean_t is_metadata)
719 {
720 	ASSERT(abd_is_linear(abd));
721 	ASSERT(!(abd->abd_flags & ABD_FLAG_OWNER));
722 	abd_verify(abd);
723 
724 	abd->abd_flags |= ABD_FLAG_OWNER;
725 	if (is_metadata) {
726 		abd->abd_flags |= ABD_FLAG_META;
727 	}
728 
729 	abd_update_linear_stats(abd, ABDSTAT_INCR);
730 }
731 
732 /*
733  * Initializes an abd_iter based on whether the abd is a gang ABD
734  * or just a single ABD.
735  */
736 static inline abd_t *
737 abd_init_abd_iter(abd_t *abd, struct abd_iter *aiter, size_t off)
738 {
739 	abd_t *cabd = NULL;
740 
741 	if (abd_is_gang(abd)) {
742 		cabd = abd_gang_get_offset(abd, &off);
743 		if (cabd) {
744 			abd_iter_init(aiter, cabd);
745 			abd_iter_advance(aiter, off);
746 		}
747 	} else {
748 		abd_iter_init(aiter, abd);
749 		abd_iter_advance(aiter, off);
750 	}
751 	return (cabd);
752 }
753 
754 /*
755  * Advances an abd_iter. We have to be careful with gang ABD as
756  * advancing could mean that we are at the end of a particular ABD and
757  * must grab the ABD in the gang ABD's list.
758  */
759 static inline abd_t *
760 abd_advance_abd_iter(abd_t *abd, abd_t *cabd, struct abd_iter *aiter,
761     size_t len)
762 {
763 	abd_iter_advance(aiter, len);
764 	if (abd_is_gang(abd) && abd_iter_at_end(aiter)) {
765 		ASSERT3P(cabd, !=, NULL);
766 		cabd = list_next(&ABD_GANG(abd).abd_gang_chain, cabd);
767 		if (cabd) {
768 			abd_iter_init(aiter, cabd);
769 			abd_iter_advance(aiter, 0);
770 		}
771 	}
772 	return (cabd);
773 }
774 
775 int
776 abd_iterate_func(abd_t *abd, size_t off, size_t size,
777     abd_iter_func_t *func, void *private)
778 {
779 	struct abd_iter aiter;
780 	int ret = 0;
781 
782 	if (size == 0)
783 		return (0);
784 
785 	abd_verify(abd);
786 	ASSERT3U(off + size, <=, abd->abd_size);
787 
788 	boolean_t gang = abd_is_gang(abd);
789 	abd_t *c_abd = abd_init_abd_iter(abd, &aiter, off);
790 
791 	while (size > 0) {
792 		/* If we are at the end of the gang ABD we are done */
793 		if (gang && !c_abd)
794 			break;
795 
796 		abd_iter_map(&aiter);
797 
798 		size_t len = MIN(aiter.iter_mapsize, size);
799 		ASSERT3U(len, >, 0);
800 
801 		ret = func(aiter.iter_mapaddr, len, private);
802 
803 		abd_iter_unmap(&aiter);
804 
805 		if (ret != 0)
806 			break;
807 
808 		size -= len;
809 		c_abd = abd_advance_abd_iter(abd, c_abd, &aiter, len);
810 	}
811 
812 	return (ret);
813 }
814 
815 struct buf_arg {
816 	void *arg_buf;
817 };
818 
819 static int
820 abd_copy_to_buf_off_cb(void *buf, size_t size, void *private)
821 {
822 	struct buf_arg *ba_ptr = private;
823 
824 	(void) memcpy(ba_ptr->arg_buf, buf, size);
825 	ba_ptr->arg_buf = (char *)ba_ptr->arg_buf + size;
826 
827 	return (0);
828 }
829 
830 /*
831  * Copy abd to buf. (off is the offset in abd.)
832  */
833 void
834 abd_copy_to_buf_off(void *buf, abd_t *abd, size_t off, size_t size)
835 {
836 	struct buf_arg ba_ptr = { buf };
837 
838 	(void) abd_iterate_func(abd, off, size, abd_copy_to_buf_off_cb,
839 	    &ba_ptr);
840 }
841 
842 static int
843 abd_cmp_buf_off_cb(void *buf, size_t size, void *private)
844 {
845 	int ret;
846 	struct buf_arg *ba_ptr = private;
847 
848 	ret = memcmp(buf, ba_ptr->arg_buf, size);
849 	ba_ptr->arg_buf = (char *)ba_ptr->arg_buf + size;
850 
851 	return (ret);
852 }
853 
854 /*
855  * Compare the contents of abd to buf. (off is the offset in abd.)
856  */
857 int
858 abd_cmp_buf_off(abd_t *abd, const void *buf, size_t off, size_t size)
859 {
860 	struct buf_arg ba_ptr = { (void *) buf };
861 
862 	return (abd_iterate_func(abd, off, size, abd_cmp_buf_off_cb, &ba_ptr));
863 }
864 
865 static int
866 abd_copy_from_buf_off_cb(void *buf, size_t size, void *private)
867 {
868 	struct buf_arg *ba_ptr = private;
869 
870 	(void) memcpy(buf, ba_ptr->arg_buf, size);
871 	ba_ptr->arg_buf = (char *)ba_ptr->arg_buf + size;
872 
873 	return (0);
874 }
875 
876 /*
877  * Copy from buf to abd. (off is the offset in abd.)
878  */
879 void
880 abd_copy_from_buf_off(abd_t *abd, const void *buf, size_t off, size_t size)
881 {
882 	struct buf_arg ba_ptr = { (void *) buf };
883 
884 	(void) abd_iterate_func(abd, off, size, abd_copy_from_buf_off_cb,
885 	    &ba_ptr);
886 }
887 
888 /*ARGSUSED*/
889 static int
890 abd_zero_off_cb(void *buf, size_t size, void *private)
891 {
892 	(void) memset(buf, 0, size);
893 	return (0);
894 }
895 
896 /*
897  * Zero out the abd from a particular offset to the end.
898  */
899 void
900 abd_zero_off(abd_t *abd, size_t off, size_t size)
901 {
902 	(void) abd_iterate_func(abd, off, size, abd_zero_off_cb, NULL);
903 }
904 
905 /*
906  * Iterate over two ABDs and call func incrementally on the two ABDs' data in
907  * equal-sized chunks (passed to func as raw buffers). func could be called many
908  * times during this iteration.
909  */
910 int
911 abd_iterate_func2(abd_t *dabd, abd_t *sabd, size_t doff, size_t soff,
912     size_t size, abd_iter_func2_t *func, void *private)
913 {
914 	int ret = 0;
915 	struct abd_iter daiter, saiter;
916 	boolean_t dabd_is_gang_abd, sabd_is_gang_abd;
917 	abd_t *c_dabd, *c_sabd;
918 
919 	if (size == 0)
920 		return (0);
921 
922 	abd_verify(dabd);
923 	abd_verify(sabd);
924 
925 	ASSERT3U(doff + size, <=, dabd->abd_size);
926 	ASSERT3U(soff + size, <=, sabd->abd_size);
927 
928 	dabd_is_gang_abd = abd_is_gang(dabd);
929 	sabd_is_gang_abd = abd_is_gang(sabd);
930 	c_dabd = abd_init_abd_iter(dabd, &daiter, doff);
931 	c_sabd = abd_init_abd_iter(sabd, &saiter, soff);
932 
933 	while (size > 0) {
934 		/* if we are at the end of the gang ABD we are done */
935 		if ((dabd_is_gang_abd && !c_dabd) ||
936 		    (sabd_is_gang_abd && !c_sabd))
937 			break;
938 
939 		abd_iter_map(&daiter);
940 		abd_iter_map(&saiter);
941 
942 		size_t dlen = MIN(daiter.iter_mapsize, size);
943 		size_t slen = MIN(saiter.iter_mapsize, size);
944 		size_t len = MIN(dlen, slen);
945 		ASSERT(dlen > 0 || slen > 0);
946 
947 		ret = func(daiter.iter_mapaddr, saiter.iter_mapaddr, len,
948 		    private);
949 
950 		abd_iter_unmap(&saiter);
951 		abd_iter_unmap(&daiter);
952 
953 		if (ret != 0)
954 			break;
955 
956 		size -= len;
957 		c_dabd =
958 		    abd_advance_abd_iter(dabd, c_dabd, &daiter, len);
959 		c_sabd =
960 		    abd_advance_abd_iter(sabd, c_sabd, &saiter, len);
961 	}
962 
963 	return (ret);
964 }
965 
966 /*ARGSUSED*/
967 static int
968 abd_copy_off_cb(void *dbuf, void *sbuf, size_t size, void *private)
969 {
970 	(void) memcpy(dbuf, sbuf, size);
971 	return (0);
972 }
973 
974 /*
975  * Copy from sabd to dabd starting from soff and doff.
976  */
977 void
978 abd_copy_off(abd_t *dabd, abd_t *sabd, size_t doff, size_t soff, size_t size)
979 {
980 	(void) abd_iterate_func2(dabd, sabd, doff, soff, size,
981 	    abd_copy_off_cb, NULL);
982 }
983 
984 /*ARGSUSED*/
985 static int
986 abd_cmp_cb(void *bufa, void *bufb, size_t size, void *private)
987 {
988 	return (memcmp(bufa, bufb, size));
989 }
990 
991 /*
992  * Compares the contents of two ABDs.
993  */
994 int
995 abd_cmp(abd_t *dabd, abd_t *sabd)
996 {
997 	ASSERT3U(dabd->abd_size, ==, sabd->abd_size);
998 	return (abd_iterate_func2(dabd, sabd, 0, 0, dabd->abd_size,
999 	    abd_cmp_cb, NULL));
1000 }
1001 
1002 /*
1003  * Iterate over code ABDs and a data ABD and call @func_raidz_gen.
1004  *
1005  * @cabds          parity ABDs, must have equal size
1006  * @dabd           data ABD. Can be NULL (in this case @dsize = 0)
1007  * @func_raidz_gen should be implemented so that its behaviour
1008  *                 is the same when taking linear and when taking scatter
1009  */
1010 void
1011 abd_raidz_gen_iterate(abd_t **cabds, abd_t *dabd,
1012     ssize_t csize, ssize_t dsize, const unsigned parity,
1013     void (*func_raidz_gen)(void **, const void *, size_t, size_t))
1014 {
1015 	int i;
1016 	ssize_t len, dlen;
1017 	struct abd_iter caiters[3];
1018 	struct abd_iter daiter = {0};
1019 	void *caddrs[3];
1020 	unsigned long flags __maybe_unused = 0;
1021 	abd_t *c_cabds[3];
1022 	abd_t *c_dabd = NULL;
1023 	boolean_t cabds_is_gang_abd[3];
1024 	boolean_t dabd_is_gang_abd = B_FALSE;
1025 
1026 	ASSERT3U(parity, <=, 3);
1027 
1028 	for (i = 0; i < parity; i++) {
1029 		cabds_is_gang_abd[i] = abd_is_gang(cabds[i]);
1030 		c_cabds[i] = abd_init_abd_iter(cabds[i], &caiters[i], 0);
1031 	}
1032 
1033 	if (dabd) {
1034 		dabd_is_gang_abd = abd_is_gang(dabd);
1035 		c_dabd = abd_init_abd_iter(dabd, &daiter, 0);
1036 	}
1037 
1038 	ASSERT3S(dsize, >=, 0);
1039 
1040 	abd_enter_critical(flags);
1041 	while (csize > 0) {
1042 		/* if we are at the end of the gang ABD we are done */
1043 		if (dabd_is_gang_abd && !c_dabd)
1044 			break;
1045 
1046 		for (i = 0; i < parity; i++) {
1047 			/*
1048 			 * If we are at the end of the gang ABD we are
1049 			 * done.
1050 			 */
1051 			if (cabds_is_gang_abd[i] && !c_cabds[i])
1052 				break;
1053 			abd_iter_map(&caiters[i]);
1054 			caddrs[i] = caiters[i].iter_mapaddr;
1055 		}
1056 
1057 		len = csize;
1058 
1059 		if (dabd && dsize > 0)
1060 			abd_iter_map(&daiter);
1061 
1062 		switch (parity) {
1063 			case 3:
1064 				len = MIN(caiters[2].iter_mapsize, len);
1065 				/* falls through */
1066 			case 2:
1067 				len = MIN(caiters[1].iter_mapsize, len);
1068 				/* falls through */
1069 			case 1:
1070 				len = MIN(caiters[0].iter_mapsize, len);
1071 		}
1072 
1073 		/* must be progressive */
1074 		ASSERT3S(len, >, 0);
1075 
1076 		if (dabd && dsize > 0) {
1077 			/* this needs precise iter.length */
1078 			len = MIN(daiter.iter_mapsize, len);
1079 			dlen = len;
1080 		} else
1081 			dlen = 0;
1082 
1083 		/* must be progressive */
1084 		ASSERT3S(len, >, 0);
1085 		/*
1086 		 * The iterated function likely will not do well if each
1087 		 * segment except the last one is not multiple of 512 (raidz).
1088 		 */
1089 		ASSERT3U(((uint64_t)len & 511ULL), ==, 0);
1090 
1091 		func_raidz_gen(caddrs, daiter.iter_mapaddr, len, dlen);
1092 
1093 		for (i = parity-1; i >= 0; i--) {
1094 			abd_iter_unmap(&caiters[i]);
1095 			c_cabds[i] =
1096 			    abd_advance_abd_iter(cabds[i], c_cabds[i],
1097 			    &caiters[i], len);
1098 		}
1099 
1100 		if (dabd && dsize > 0) {
1101 			abd_iter_unmap(&daiter);
1102 			c_dabd =
1103 			    abd_advance_abd_iter(dabd, c_dabd, &daiter,
1104 			    dlen);
1105 			dsize -= dlen;
1106 		}
1107 
1108 		csize -= len;
1109 
1110 		ASSERT3S(dsize, >=, 0);
1111 		ASSERT3S(csize, >=, 0);
1112 	}
1113 	abd_exit_critical(flags);
1114 }
1115 
1116 /*
1117  * Iterate over code ABDs and data reconstruction target ABDs and call
1118  * @func_raidz_rec. Function maps at most 6 pages atomically.
1119  *
1120  * @cabds           parity ABDs, must have equal size
1121  * @tabds           rec target ABDs, at most 3
1122  * @tsize           size of data target columns
1123  * @func_raidz_rec  expects syndrome data in target columns. Function
1124  *                  reconstructs data and overwrites target columns.
1125  */
1126 void
1127 abd_raidz_rec_iterate(abd_t **cabds, abd_t **tabds,
1128     ssize_t tsize, const unsigned parity,
1129     void (*func_raidz_rec)(void **t, const size_t tsize, void **c,
1130     const unsigned *mul),
1131     const unsigned *mul)
1132 {
1133 	int i;
1134 	ssize_t len;
1135 	struct abd_iter citers[3];
1136 	struct abd_iter xiters[3];
1137 	void *caddrs[3], *xaddrs[3];
1138 	unsigned long flags __maybe_unused = 0;
1139 	boolean_t cabds_is_gang_abd[3];
1140 	boolean_t tabds_is_gang_abd[3];
1141 	abd_t *c_cabds[3];
1142 	abd_t *c_tabds[3];
1143 
1144 	ASSERT3U(parity, <=, 3);
1145 
1146 	for (i = 0; i < parity; i++) {
1147 		cabds_is_gang_abd[i] = abd_is_gang(cabds[i]);
1148 		tabds_is_gang_abd[i] = abd_is_gang(tabds[i]);
1149 		c_cabds[i] =
1150 		    abd_init_abd_iter(cabds[i], &citers[i], 0);
1151 		c_tabds[i] =
1152 		    abd_init_abd_iter(tabds[i], &xiters[i], 0);
1153 	}
1154 
1155 	abd_enter_critical(flags);
1156 	while (tsize > 0) {
1157 
1158 		for (i = 0; i < parity; i++) {
1159 			/*
1160 			 * If we are at the end of the gang ABD we
1161 			 * are done.
1162 			 */
1163 			if (cabds_is_gang_abd[i] && !c_cabds[i])
1164 				break;
1165 			if (tabds_is_gang_abd[i] && !c_tabds[i])
1166 				break;
1167 			abd_iter_map(&citers[i]);
1168 			abd_iter_map(&xiters[i]);
1169 			caddrs[i] = citers[i].iter_mapaddr;
1170 			xaddrs[i] = xiters[i].iter_mapaddr;
1171 		}
1172 
1173 		len = tsize;
1174 		switch (parity) {
1175 			case 3:
1176 				len = MIN(xiters[2].iter_mapsize, len);
1177 				len = MIN(citers[2].iter_mapsize, len);
1178 				/* falls through */
1179 			case 2:
1180 				len = MIN(xiters[1].iter_mapsize, len);
1181 				len = MIN(citers[1].iter_mapsize, len);
1182 				/* falls through */
1183 			case 1:
1184 				len = MIN(xiters[0].iter_mapsize, len);
1185 				len = MIN(citers[0].iter_mapsize, len);
1186 		}
1187 		/* must be progressive */
1188 		ASSERT3S(len, >, 0);
1189 		/*
1190 		 * The iterated function likely will not do well if each
1191 		 * segment except the last one is not multiple of 512 (raidz).
1192 		 */
1193 		ASSERT3U(((uint64_t)len & 511ULL), ==, 0);
1194 
1195 		func_raidz_rec(xaddrs, len, caddrs, mul);
1196 
1197 		for (i = parity-1; i >= 0; i--) {
1198 			abd_iter_unmap(&xiters[i]);
1199 			abd_iter_unmap(&citers[i]);
1200 			c_tabds[i] =
1201 			    abd_advance_abd_iter(tabds[i], c_tabds[i],
1202 			    &xiters[i], len);
1203 			c_cabds[i] =
1204 			    abd_advance_abd_iter(cabds[i], c_cabds[i],
1205 			    &citers[i], len);
1206 		}
1207 
1208 		tsize -= len;
1209 		ASSERT3S(tsize, >=, 0);
1210 	}
1211 	abd_exit_critical(flags);
1212 }
1213