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