]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/abd.c
Import lua 5.3.4 to contrib
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / abd.c
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11
12 /*
13  * Copyright (c) 2014 by Chunwei Chen. All rights reserved.
14  * Copyright (c) 2016 by Delphix. All rights reserved.
15  */
16
17 /*
18  * ARC buffer data (ABD).
19  *
20  * ABDs are an abstract data structure for the ARC which can use two
21  * different ways of storing the underlying data:
22  *
23  * (a) Linear buffer. In this case, all the data in the ABD is stored in one
24  *     contiguous buffer in memory (from a zio_[data_]buf_* kmem cache).
25  *
26  *         +-------------------+
27  *         | ABD (linear)      |
28  *         |   abd_flags = ... |
29  *         |   abd_size = ...  |     +--------------------------------+
30  *         |   abd_buf ------------->| raw buffer of size abd_size    |
31  *         +-------------------+     +--------------------------------+
32  *              no abd_chunks
33  *
34  * (b) Scattered buffer. In this case, the data in the ABD is split into
35  *     equal-sized chunks (from the abd_chunk_cache kmem_cache), with pointers
36  *     to the chunks recorded in an array at the end of the ABD structure.
37  *
38  *         +-------------------+
39  *         | ABD (scattered)   |
40  *         |   abd_flags = ... |
41  *         |   abd_size = ...  |
42  *         |   abd_offset = 0  |                           +-----------+
43  *         |   abd_chunks[0] ----------------------------->| chunk 0   |
44  *         |   abd_chunks[1] ---------------------+        +-----------+
45  *         |   ...             |                  |        +-----------+
46  *         |   abd_chunks[N-1] ---------+         +------->| chunk 1   |
47  *         +-------------------+        |                  +-----------+
48  *                                      |                      ...
49  *                                      |                  +-----------+
50  *                                      +----------------->| chunk N-1 |
51  *                                                         +-----------+
52  *
53  * Using a large proportion of scattered ABDs decreases ARC fragmentation since
54  * when we are at the limit of allocatable space, using equal-size chunks will
55  * allow us to quickly reclaim enough space for a new large allocation (assuming
56  * it is also scattered).
57  *
58  * In addition to directly allocating a linear or scattered ABD, it is also
59  * possible to create an ABD by requesting the "sub-ABD" starting at an offset
60  * within an existing ABD. In linear buffers this is simple (set abd_buf of
61  * the new ABD to the starting point within the original raw buffer), but
62  * scattered ABDs are a little more complex. The new ABD makes a copy of the
63  * relevant abd_chunks pointers (but not the underlying data). However, to
64  * provide arbitrary rather than only chunk-aligned starting offsets, it also
65  * tracks an abd_offset field which represents the starting point of the data
66  * within the first chunk in abd_chunks. For both linear and scattered ABDs,
67  * creating an offset ABD marks the original ABD as the offset's parent, and the
68  * original ABD's abd_children refcount is incremented. This data allows us to
69  * ensure the root ABD isn't deleted before its children.
70  *
71  * Most consumers should never need to know what type of ABD they're using --
72  * the ABD public API ensures that it's possible to transparently switch from
73  * using a linear ABD to a scattered one when doing so would be beneficial.
74  *
75  * If you need to use the data within an ABD directly, if you know it's linear
76  * (because you allocated it) you can use abd_to_buf() to access the underlying
77  * raw buffer. Otherwise, you should use one of the abd_borrow_buf* functions
78  * which will allocate a raw buffer if necessary. Use the abd_return_buf*
79  * functions to return any raw buffers that are no longer necessary when you're
80  * done using them.
81  *
82  * There are a variety of ABD APIs that implement basic buffer operations:
83  * compare, copy, read, write, and fill with zeroes. If you need a custom
84  * function which progressively accesses the whole ABD, use the abd_iterate_*
85  * functions.
86  */
87
88 #include <sys/abd.h>
89 #include <sys/param.h>
90 #include <sys/zio.h>
91 #include <sys/zfs_context.h>
92 #include <sys/zfs_znode.h>
93
94 typedef struct abd_stats {
95         kstat_named_t abdstat_struct_size;
96         kstat_named_t abdstat_scatter_cnt;
97         kstat_named_t abdstat_scatter_data_size;
98         kstat_named_t abdstat_scatter_chunk_waste;
99         kstat_named_t abdstat_linear_cnt;
100         kstat_named_t abdstat_linear_data_size;
101 } abd_stats_t;
102
103 static abd_stats_t abd_stats = {
104         /* Amount of memory occupied by all of the abd_t struct allocations */
105         { "struct_size",                        KSTAT_DATA_UINT64 },
106         /*
107          * The number of scatter ABDs which are currently allocated, excluding
108          * ABDs which don't own their data (for instance the ones which were
109          * allocated through abd_get_offset()).
110          */
111         { "scatter_cnt",                        KSTAT_DATA_UINT64 },
112         /* Amount of data stored in all scatter ABDs tracked by scatter_cnt */
113         { "scatter_data_size",                  KSTAT_DATA_UINT64 },
114         /*
115          * The amount of space wasted at the end of the last chunk across all
116          * scatter ABDs tracked by scatter_cnt.
117          */
118         { "scatter_chunk_waste",                KSTAT_DATA_UINT64 },
119         /*
120          * The number of linear ABDs which are currently allocated, excluding
121          * ABDs which don't own their data (for instance the ones which were
122          * allocated through abd_get_offset() and abd_get_from_buf()). If an
123          * ABD takes ownership of its buf then it will become tracked.
124          */
125         { "linear_cnt",                         KSTAT_DATA_UINT64 },
126         /* Amount of data stored in all linear ABDs tracked by linear_cnt */
127         { "linear_data_size",                   KSTAT_DATA_UINT64 },
128 };
129
130 #define ABDSTAT(stat)           (abd_stats.stat.value.ui64)
131 #define ABDSTAT_INCR(stat, val) \
132         atomic_add_64(&abd_stats.stat.value.ui64, (val))
133 #define ABDSTAT_BUMP(stat)      ABDSTAT_INCR(stat, 1)
134 #define ABDSTAT_BUMPDOWN(stat)  ABDSTAT_INCR(stat, -1)
135
136 /*
137  * It is possible to make all future ABDs be linear by setting this to B_FALSE.
138  * Otherwise, ABDs are allocated scattered by default unless the caller uses
139  * abd_alloc_linear().
140  */
141 boolean_t zfs_abd_scatter_enabled = B_TRUE;
142
143 /*
144  * The size of the chunks ABD allocates. Because the sizes allocated from the
145  * kmem_cache can't change, this tunable can only be modified at boot. Changing
146  * it at runtime would cause ABD iteration to work incorrectly for ABDs which
147  * were allocated with the old size, so a safeguard has been put in place which
148  * will cause the machine to panic if you change it and try to access the data
149  * within a scattered ABD.
150  */
151 size_t zfs_abd_chunk_size = 4096;
152
153 #if defined(__FreeBSD__) && defined(_KERNEL)
154 SYSCTL_DECL(_vfs_zfs);
155
156 SYSCTL_ULONG(_vfs_zfs, OID_AUTO, abd_chunk_size, CTLFLAG_RDTUN,
157     &zfs_abd_chunk_size, 0, "The size of the chunks ABD allocates");
158 #endif
159
160 #ifdef _KERNEL
161 extern vmem_t *zio_alloc_arena;
162 #endif
163
164 kmem_cache_t *abd_chunk_cache;
165 static kstat_t *abd_ksp;
166
167 extern inline boolean_t abd_is_linear(abd_t *abd);
168 extern inline void abd_copy(abd_t *dabd, abd_t *sabd, size_t size);
169 extern inline void abd_copy_from_buf(abd_t *abd, const void *buf, size_t size);
170 extern inline void abd_copy_to_buf(void* buf, abd_t *abd, size_t size);
171 extern inline int abd_cmp_buf(abd_t *abd, const void *buf, size_t size);
172 extern inline void abd_zero(abd_t *abd, size_t size);
173
174 static void *
175 abd_alloc_chunk()
176 {
177         void *c = kmem_cache_alloc(abd_chunk_cache, KM_PUSHPAGE);
178         ASSERT3P(c, !=, NULL);
179         return (c);
180 }
181
182 static void
183 abd_free_chunk(void *c)
184 {
185         kmem_cache_free(abd_chunk_cache, c);
186 }
187
188 void
189 abd_init(void)
190 {
191 #ifdef illumos
192         vmem_t *data_alloc_arena = NULL;
193
194 #ifdef _KERNEL
195         data_alloc_arena = zio_alloc_arena;
196 #endif
197
198         /*
199          * Since ABD chunks do not appear in crash dumps, we pass KMC_NOTOUCH
200          * so that no allocator metadata is stored with the buffers.
201          */
202         abd_chunk_cache = kmem_cache_create("abd_chunk", zfs_abd_chunk_size, 0,
203             NULL, NULL, NULL, NULL, data_alloc_arena, KMC_NOTOUCH);
204 #else
205         abd_chunk_cache = kmem_cache_create("abd_chunk", zfs_abd_chunk_size, 0,
206             NULL, NULL, NULL, NULL, 0, KMC_NOTOUCH | KMC_NODEBUG);
207 #endif
208         abd_ksp = kstat_create("zfs", 0, "abdstats", "misc", KSTAT_TYPE_NAMED,
209             sizeof (abd_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
210         if (abd_ksp != NULL) {
211                 abd_ksp->ks_data = &abd_stats;
212                 kstat_install(abd_ksp);
213         }
214 }
215
216 void
217 abd_fini(void)
218 {
219         if (abd_ksp != NULL) {
220                 kstat_delete(abd_ksp);
221                 abd_ksp = NULL;
222         }
223
224         kmem_cache_destroy(abd_chunk_cache);
225         abd_chunk_cache = NULL;
226 }
227
228 static inline size_t
229 abd_chunkcnt_for_bytes(size_t size)
230 {
231         return (P2ROUNDUP(size, zfs_abd_chunk_size) / zfs_abd_chunk_size);
232 }
233
234 static inline size_t
235 abd_scatter_chunkcnt(abd_t *abd)
236 {
237         ASSERT(!abd_is_linear(abd));
238         return (abd_chunkcnt_for_bytes(
239             abd->abd_u.abd_scatter.abd_offset + abd->abd_size));
240 }
241
242 static inline void
243 abd_verify(abd_t *abd)
244 {
245         ASSERT3U(abd->abd_size, >, 0);
246         ASSERT3U(abd->abd_size, <=, SPA_MAXBLOCKSIZE);
247         ASSERT3U(abd->abd_flags, ==, abd->abd_flags & (ABD_FLAG_LINEAR |
248             ABD_FLAG_OWNER | ABD_FLAG_META));
249         IMPLY(abd->abd_parent != NULL, !(abd->abd_flags & ABD_FLAG_OWNER));
250         IMPLY(abd->abd_flags & ABD_FLAG_META, abd->abd_flags & ABD_FLAG_OWNER);
251         if (abd_is_linear(abd)) {
252                 ASSERT3P(abd->abd_u.abd_linear.abd_buf, !=, NULL);
253         } else {
254                 ASSERT3U(abd->abd_u.abd_scatter.abd_offset, <,
255                     zfs_abd_chunk_size);
256                 size_t n = abd_scatter_chunkcnt(abd);
257                 for (int i = 0; i < n; i++) {
258                         ASSERT3P(
259                             abd->abd_u.abd_scatter.abd_chunks[i], !=, NULL);
260                 }
261         }
262 }
263
264 static inline abd_t *
265 abd_alloc_struct(size_t chunkcnt)
266 {
267         size_t size = offsetof(abd_t, abd_u.abd_scatter.abd_chunks[chunkcnt]);
268         abd_t *abd = kmem_alloc(size, KM_PUSHPAGE);
269         ASSERT3P(abd, !=, NULL);
270         ABDSTAT_INCR(abdstat_struct_size, size);
271
272         return (abd);
273 }
274
275 static inline void
276 abd_free_struct(abd_t *abd)
277 {
278         size_t chunkcnt = abd_is_linear(abd) ? 0 : abd_scatter_chunkcnt(abd);
279         int size = offsetof(abd_t, abd_u.abd_scatter.abd_chunks[chunkcnt]);
280         kmem_free(abd, size);
281         ABDSTAT_INCR(abdstat_struct_size, -size);
282 }
283
284 /*
285  * Allocate an ABD, along with its own underlying data buffers. Use this if you
286  * don't care whether the ABD is linear or not.
287  */
288 abd_t *
289 abd_alloc(size_t size, boolean_t is_metadata)
290 {
291         if (!zfs_abd_scatter_enabled)
292                 return (abd_alloc_linear(size, is_metadata));
293
294         VERIFY3U(size, <=, SPA_MAXBLOCKSIZE);
295
296         size_t n = abd_chunkcnt_for_bytes(size);
297         abd_t *abd = abd_alloc_struct(n);
298
299         abd->abd_flags = ABD_FLAG_OWNER;
300         if (is_metadata) {
301                 abd->abd_flags |= ABD_FLAG_META;
302         }
303         abd->abd_size = size;
304         abd->abd_parent = NULL;
305         refcount_create(&abd->abd_children);
306
307         abd->abd_u.abd_scatter.abd_offset = 0;
308         abd->abd_u.abd_scatter.abd_chunk_size = zfs_abd_chunk_size;
309
310         for (int i = 0; i < n; i++) {
311                 void *c = abd_alloc_chunk();
312                 ASSERT3P(c, !=, NULL);
313                 abd->abd_u.abd_scatter.abd_chunks[i] = c;
314         }
315
316         ABDSTAT_BUMP(abdstat_scatter_cnt);
317         ABDSTAT_INCR(abdstat_scatter_data_size, size);
318         ABDSTAT_INCR(abdstat_scatter_chunk_waste,
319             n * zfs_abd_chunk_size - size);
320
321         return (abd);
322 }
323
324 static void
325 abd_free_scatter(abd_t *abd)
326 {
327         size_t n = abd_scatter_chunkcnt(abd);
328         for (int i = 0; i < n; i++) {
329                 abd_free_chunk(abd->abd_u.abd_scatter.abd_chunks[i]);
330         }
331
332         refcount_destroy(&abd->abd_children);
333         ABDSTAT_BUMPDOWN(abdstat_scatter_cnt);
334         ABDSTAT_INCR(abdstat_scatter_data_size, -(int)abd->abd_size);
335         ABDSTAT_INCR(abdstat_scatter_chunk_waste,
336             abd->abd_size - n * zfs_abd_chunk_size);
337
338         abd_free_struct(abd);
339 }
340
341 /*
342  * Allocate an ABD that must be linear, along with its own underlying data
343  * buffer. Only use this when it would be very annoying to write your ABD
344  * consumer with a scattered ABD.
345  */
346 abd_t *
347 abd_alloc_linear(size_t size, boolean_t is_metadata)
348 {
349         abd_t *abd = abd_alloc_struct(0);
350
351         VERIFY3U(size, <=, SPA_MAXBLOCKSIZE);
352
353         abd->abd_flags = ABD_FLAG_LINEAR | ABD_FLAG_OWNER;
354         if (is_metadata) {
355                 abd->abd_flags |= ABD_FLAG_META;
356         }
357         abd->abd_size = size;
358         abd->abd_parent = NULL;
359         refcount_create(&abd->abd_children);
360
361         if (is_metadata) {
362                 abd->abd_u.abd_linear.abd_buf = zio_buf_alloc(size);
363         } else {
364                 abd->abd_u.abd_linear.abd_buf = zio_data_buf_alloc(size);
365         }
366
367         ABDSTAT_BUMP(abdstat_linear_cnt);
368         ABDSTAT_INCR(abdstat_linear_data_size, size);
369
370         return (abd);
371 }
372
373 static void
374 abd_free_linear(abd_t *abd)
375 {
376         if (abd->abd_flags & ABD_FLAG_META) {
377                 zio_buf_free(abd->abd_u.abd_linear.abd_buf, abd->abd_size);
378         } else {
379                 zio_data_buf_free(abd->abd_u.abd_linear.abd_buf, abd->abd_size);
380         }
381
382         refcount_destroy(&abd->abd_children);
383         ABDSTAT_BUMPDOWN(abdstat_linear_cnt);
384         ABDSTAT_INCR(abdstat_linear_data_size, -(int)abd->abd_size);
385
386         abd_free_struct(abd);
387 }
388
389 /*
390  * Free an ABD. Only use this on ABDs allocated with abd_alloc() or
391  * abd_alloc_linear().
392  */
393 void
394 abd_free(abd_t *abd)
395 {
396         abd_verify(abd);
397         ASSERT3P(abd->abd_parent, ==, NULL);
398         ASSERT(abd->abd_flags & ABD_FLAG_OWNER);
399         if (abd_is_linear(abd))
400                 abd_free_linear(abd);
401         else
402                 abd_free_scatter(abd);
403 }
404
405 /*
406  * Allocate an ABD of the same format (same metadata flag, same scatterize
407  * setting) as another ABD.
408  */
409 abd_t *
410 abd_alloc_sametype(abd_t *sabd, size_t size)
411 {
412         boolean_t is_metadata = (sabd->abd_flags & ABD_FLAG_META) != 0;
413         if (abd_is_linear(sabd)) {
414                 return (abd_alloc_linear(size, is_metadata));
415         } else {
416                 return (abd_alloc(size, is_metadata));
417         }
418 }
419
420 /*
421  * If we're going to use this ABD for doing I/O using the block layer, the
422  * consumer of the ABD data doesn't care if it's scattered or not, and we don't
423  * plan to store this ABD in memory for a long period of time, we should
424  * allocate the ABD type that requires the least data copying to do the I/O.
425  *
426  * Currently this is linear ABDs, however if ldi_strategy() can ever issue I/Os
427  * using a scatter/gather list we should switch to that and replace this call
428  * with vanilla abd_alloc().
429  */
430 abd_t *
431 abd_alloc_for_io(size_t size, boolean_t is_metadata)
432 {
433         return (abd_alloc_linear(size, is_metadata));
434 }
435
436 /*
437  * Allocate a new ABD to point to offset off of sabd. It shares the underlying
438  * buffer data with sabd. Use abd_put() to free. sabd must not be freed while
439  * any derived ABDs exist.
440  */
441 abd_t *
442 abd_get_offset(abd_t *sabd, size_t off)
443 {
444         abd_t *abd;
445
446         abd_verify(sabd);
447         ASSERT3U(off, <=, sabd->abd_size);
448
449         if (abd_is_linear(sabd)) {
450                 abd = abd_alloc_struct(0);
451
452                 /*
453                  * Even if this buf is filesystem metadata, we only track that
454                  * if we own the underlying data buffer, which is not true in
455                  * this case. Therefore, we don't ever use ABD_FLAG_META here.
456                  */
457                 abd->abd_flags = ABD_FLAG_LINEAR;
458
459                 abd->abd_u.abd_linear.abd_buf =
460                     (char *)sabd->abd_u.abd_linear.abd_buf + off;
461         } else {
462                 size_t new_offset = sabd->abd_u.abd_scatter.abd_offset + off;
463                 size_t chunkcnt = abd_scatter_chunkcnt(sabd) -
464                     (new_offset / zfs_abd_chunk_size);
465
466                 abd = abd_alloc_struct(chunkcnt);
467
468                 /*
469                  * Even if this buf is filesystem metadata, we only track that
470                  * if we own the underlying data buffer, which is not true in
471                  * this case. Therefore, we don't ever use ABD_FLAG_META here.
472                  */
473                 abd->abd_flags = 0;
474
475                 abd->abd_u.abd_scatter.abd_offset =
476                     new_offset % zfs_abd_chunk_size;
477                 abd->abd_u.abd_scatter.abd_chunk_size = zfs_abd_chunk_size;
478
479                 /* Copy the scatterlist starting at the correct offset */
480                 (void) memcpy(&abd->abd_u.abd_scatter.abd_chunks,
481                     &sabd->abd_u.abd_scatter.abd_chunks[new_offset /
482                     zfs_abd_chunk_size],
483                     chunkcnt * sizeof (void *));
484         }
485
486         abd->abd_size = sabd->abd_size - off;
487         abd->abd_parent = sabd;
488         refcount_create(&abd->abd_children);
489         (void) refcount_add_many(&sabd->abd_children, abd->abd_size, abd);
490
491         return (abd);
492 }
493
494 /*
495  * Allocate a linear ABD structure for buf. You must free this with abd_put()
496  * since the resulting ABD doesn't own its own buffer.
497  */
498 abd_t *
499 abd_get_from_buf(void *buf, size_t size)
500 {
501         abd_t *abd = abd_alloc_struct(0);
502
503         VERIFY3U(size, <=, SPA_MAXBLOCKSIZE);
504
505         /*
506          * Even if this buf is filesystem metadata, we only track that if we
507          * own the underlying data buffer, which is not true in this case.
508          * Therefore, we don't ever use ABD_FLAG_META here.
509          */
510         abd->abd_flags = ABD_FLAG_LINEAR;
511         abd->abd_size = size;
512         abd->abd_parent = NULL;
513         refcount_create(&abd->abd_children);
514
515         abd->abd_u.abd_linear.abd_buf = buf;
516
517         return (abd);
518 }
519
520 /*
521  * Free an ABD allocated from abd_get_offset() or abd_get_from_buf(). Will not
522  * free the underlying scatterlist or buffer.
523  */
524 void
525 abd_put(abd_t *abd)
526 {
527         abd_verify(abd);
528         ASSERT(!(abd->abd_flags & ABD_FLAG_OWNER));
529
530         if (abd->abd_parent != NULL) {
531                 (void) refcount_remove_many(&abd->abd_parent->abd_children,
532                     abd->abd_size, abd);
533         }
534
535         refcount_destroy(&abd->abd_children);
536         abd_free_struct(abd);
537 }
538
539 /*
540  * Get the raw buffer associated with a linear ABD.
541  */
542 void *
543 abd_to_buf(abd_t *abd)
544 {
545         ASSERT(abd_is_linear(abd));
546         abd_verify(abd);
547         return (abd->abd_u.abd_linear.abd_buf);
548 }
549
550 /*
551  * Borrow a raw buffer from an ABD without copying the contents of the ABD
552  * into the buffer. If the ABD is scattered, this will allocate a raw buffer
553  * whose contents are undefined. To copy over the existing data in the ABD, use
554  * abd_borrow_buf_copy() instead.
555  */
556 void *
557 abd_borrow_buf(abd_t *abd, size_t n)
558 {
559         void *buf;
560         abd_verify(abd);
561         ASSERT3U(abd->abd_size, >=, n);
562         if (abd_is_linear(abd)) {
563                 buf = abd_to_buf(abd);
564         } else {
565                 buf = zio_buf_alloc(n);
566         }
567         (void) refcount_add_many(&abd->abd_children, n, buf);
568
569         return (buf);
570 }
571
572 void *
573 abd_borrow_buf_copy(abd_t *abd, size_t n)
574 {
575         void *buf = abd_borrow_buf(abd, n);
576         if (!abd_is_linear(abd)) {
577                 abd_copy_to_buf(buf, abd, n);
578         }
579         return (buf);
580 }
581
582 /*
583  * Return a borrowed raw buffer to an ABD. If the ABD is scattered, this will
584  * not change the contents of the ABD and will ASSERT that you didn't modify
585  * the buffer since it was borrowed. If you want any changes you made to buf to
586  * be copied back to abd, use abd_return_buf_copy() instead.
587  */
588 void
589 abd_return_buf(abd_t *abd, void *buf, size_t n)
590 {
591         abd_verify(abd);
592         ASSERT3U(abd->abd_size, >=, n);
593         if (abd_is_linear(abd)) {
594                 ASSERT3P(buf, ==, abd_to_buf(abd));
595         } else {
596                 ASSERT0(abd_cmp_buf(abd, buf, n));
597                 zio_buf_free(buf, n);
598         }
599         (void) refcount_remove_many(&abd->abd_children, n, buf);
600 }
601
602 void
603 abd_return_buf_copy(abd_t *abd, void *buf, size_t n)
604 {
605         if (!abd_is_linear(abd)) {
606                 abd_copy_from_buf(abd, buf, n);
607         }
608         abd_return_buf(abd, buf, n);
609 }
610
611 /*
612  * Give this ABD ownership of the buffer that it's storing. Can only be used on
613  * linear ABDs which were allocated via abd_get_from_buf(), or ones allocated
614  * with abd_alloc_linear() which subsequently released ownership of their buf
615  * with abd_release_ownership_of_buf().
616  */
617 void
618 abd_take_ownership_of_buf(abd_t *abd, boolean_t is_metadata)
619 {
620         ASSERT(abd_is_linear(abd));
621         ASSERT(!(abd->abd_flags & ABD_FLAG_OWNER));
622         abd_verify(abd);
623
624         abd->abd_flags |= ABD_FLAG_OWNER;
625         if (is_metadata) {
626                 abd->abd_flags |= ABD_FLAG_META;
627         }
628
629         ABDSTAT_BUMP(abdstat_linear_cnt);
630         ABDSTAT_INCR(abdstat_linear_data_size, abd->abd_size);
631 }
632
633 void
634 abd_release_ownership_of_buf(abd_t *abd)
635 {
636         ASSERT(abd_is_linear(abd));
637         ASSERT(abd->abd_flags & ABD_FLAG_OWNER);
638         abd_verify(abd);
639
640         abd->abd_flags &= ~ABD_FLAG_OWNER;
641         /* Disable this flag since we no longer own the data buffer */
642         abd->abd_flags &= ~ABD_FLAG_META;
643
644         ABDSTAT_BUMPDOWN(abdstat_linear_cnt);
645         ABDSTAT_INCR(abdstat_linear_data_size, -(int)abd->abd_size);
646 }
647
648 struct abd_iter {
649         abd_t           *iter_abd;      /* ABD being iterated through */
650         size_t          iter_pos;       /* position (relative to abd_offset) */
651         void            *iter_mapaddr;  /* addr corresponding to iter_pos */
652         size_t          iter_mapsize;   /* length of data valid at mapaddr */
653 };
654
655 static inline size_t
656 abd_iter_scatter_chunk_offset(struct abd_iter *aiter)
657 {
658         ASSERT(!abd_is_linear(aiter->iter_abd));
659         return ((aiter->iter_abd->abd_u.abd_scatter.abd_offset +
660             aiter->iter_pos) % zfs_abd_chunk_size);
661 }
662
663 static inline size_t
664 abd_iter_scatter_chunk_index(struct abd_iter *aiter)
665 {
666         ASSERT(!abd_is_linear(aiter->iter_abd));
667         return ((aiter->iter_abd->abd_u.abd_scatter.abd_offset +
668             aiter->iter_pos) / zfs_abd_chunk_size);
669 }
670
671 /*
672  * Initialize the abd_iter.
673  */
674 static void
675 abd_iter_init(struct abd_iter *aiter, abd_t *abd)
676 {
677         abd_verify(abd);
678         aiter->iter_abd = abd;
679         aiter->iter_pos = 0;
680         aiter->iter_mapaddr = NULL;
681         aiter->iter_mapsize = 0;
682 }
683
684 /*
685  * Advance the iterator by a certain amount. Cannot be called when a chunk is
686  * in use. This can be safely called when the aiter has already exhausted, in
687  * which case this does nothing.
688  */
689 static void
690 abd_iter_advance(struct abd_iter *aiter, size_t amount)
691 {
692         ASSERT3P(aiter->iter_mapaddr, ==, NULL);
693         ASSERT0(aiter->iter_mapsize);
694
695         /* There's nothing left to advance to, so do nothing */
696         if (aiter->iter_pos == aiter->iter_abd->abd_size)
697                 return;
698
699         aiter->iter_pos += amount;
700 }
701
702 /*
703  * Map the current chunk into aiter. This can be safely called when the aiter
704  * has already exhausted, in which case this does nothing.
705  */
706 static void
707 abd_iter_map(struct abd_iter *aiter)
708 {
709         void *paddr;
710         size_t offset = 0;
711
712         ASSERT3P(aiter->iter_mapaddr, ==, NULL);
713         ASSERT0(aiter->iter_mapsize);
714
715         /* Panic if someone has changed zfs_abd_chunk_size */
716         IMPLY(!abd_is_linear(aiter->iter_abd), zfs_abd_chunk_size ==
717             aiter->iter_abd->abd_u.abd_scatter.abd_chunk_size);
718
719         /* There's nothing left to iterate over, so do nothing */
720         if (aiter->iter_pos == aiter->iter_abd->abd_size)
721                 return;
722
723         if (abd_is_linear(aiter->iter_abd)) {
724                 offset = aiter->iter_pos;
725                 aiter->iter_mapsize = aiter->iter_abd->abd_size - offset;
726                 paddr = aiter->iter_abd->abd_u.abd_linear.abd_buf;
727         } else {
728                 size_t index = abd_iter_scatter_chunk_index(aiter);
729                 offset = abd_iter_scatter_chunk_offset(aiter);
730                 aiter->iter_mapsize = zfs_abd_chunk_size - offset;
731                 paddr = aiter->iter_abd->abd_u.abd_scatter.abd_chunks[index];
732         }
733         aiter->iter_mapaddr = (char *)paddr + offset;
734 }
735
736 /*
737  * Unmap the current chunk from aiter. This can be safely called when the aiter
738  * has already exhausted, in which case this does nothing.
739  */
740 static void
741 abd_iter_unmap(struct abd_iter *aiter)
742 {
743         /* There's nothing left to unmap, so do nothing */
744         if (aiter->iter_pos == aiter->iter_abd->abd_size)
745                 return;
746
747         ASSERT3P(aiter->iter_mapaddr, !=, NULL);
748         ASSERT3U(aiter->iter_mapsize, >, 0);
749
750         aiter->iter_mapaddr = NULL;
751         aiter->iter_mapsize = 0;
752 }
753
754 int
755 abd_iterate_func(abd_t *abd, size_t off, size_t size,
756     abd_iter_func_t *func, void *private)
757 {
758         int ret = 0;
759         struct abd_iter aiter;
760
761         abd_verify(abd);
762         ASSERT3U(off + size, <=, abd->abd_size);
763
764         abd_iter_init(&aiter, abd);
765         abd_iter_advance(&aiter, off);
766
767         while (size > 0) {
768                 abd_iter_map(&aiter);
769
770                 size_t len = MIN(aiter.iter_mapsize, size);
771                 ASSERT3U(len, >, 0);
772
773                 ret = func(aiter.iter_mapaddr, len, private);
774
775                 abd_iter_unmap(&aiter);
776
777                 if (ret != 0)
778                         break;
779
780                 size -= len;
781                 abd_iter_advance(&aiter, len);
782         }
783
784         return (ret);
785 }
786
787 struct buf_arg {
788         void *arg_buf;
789 };
790
791 static int
792 abd_copy_to_buf_off_cb(void *buf, size_t size, void *private)
793 {
794         struct buf_arg *ba_ptr = private;
795
796         (void) memcpy(ba_ptr->arg_buf, buf, size);
797         ba_ptr->arg_buf = (char *)ba_ptr->arg_buf + size;
798
799         return (0);
800 }
801
802 /*
803  * Copy abd to buf. (off is the offset in abd.)
804  */
805 void
806 abd_copy_to_buf_off(void *buf, abd_t *abd, size_t off, size_t size)
807 {
808         struct buf_arg ba_ptr = { buf };
809
810         (void) abd_iterate_func(abd, off, size, abd_copy_to_buf_off_cb,
811             &ba_ptr);
812 }
813
814 static int
815 abd_cmp_buf_off_cb(void *buf, size_t size, void *private)
816 {
817         int ret;
818         struct buf_arg *ba_ptr = private;
819
820         ret = memcmp(buf, ba_ptr->arg_buf, size);
821         ba_ptr->arg_buf = (char *)ba_ptr->arg_buf + size;
822
823         return (ret);
824 }
825
826 /*
827  * Compare the contents of abd to buf. (off is the offset in abd.)
828  */
829 int
830 abd_cmp_buf_off(abd_t *abd, const void *buf, size_t off, size_t size)
831 {
832         struct buf_arg ba_ptr = { (void *) buf };
833
834         return (abd_iterate_func(abd, off, size, abd_cmp_buf_off_cb, &ba_ptr));
835 }
836
837 static int
838 abd_copy_from_buf_off_cb(void *buf, size_t size, void *private)
839 {
840         struct buf_arg *ba_ptr = private;
841
842         (void) memcpy(buf, ba_ptr->arg_buf, size);
843         ba_ptr->arg_buf = (char *)ba_ptr->arg_buf + size;
844
845         return (0);
846 }
847
848 /*
849  * Copy from buf to abd. (off is the offset in abd.)
850  */
851 void
852 abd_copy_from_buf_off(abd_t *abd, const void *buf, size_t off, size_t size)
853 {
854         struct buf_arg ba_ptr = { (void *) buf };
855
856         (void) abd_iterate_func(abd, off, size, abd_copy_from_buf_off_cb,
857             &ba_ptr);
858 }
859
860 /*ARGSUSED*/
861 static int
862 abd_zero_off_cb(void *buf, size_t size, void *private)
863 {
864         (void) memset(buf, 0, size);
865         return (0);
866 }
867
868 /*
869  * Zero out the abd from a particular offset to the end.
870  */
871 void
872 abd_zero_off(abd_t *abd, size_t off, size_t size)
873 {
874         (void) abd_iterate_func(abd, off, size, abd_zero_off_cb, NULL);
875 }
876
877 /*
878  * Iterate over two ABDs and call func incrementally on the two ABDs' data in
879  * equal-sized chunks (passed to func as raw buffers). func could be called many
880  * times during this iteration.
881  */
882 int
883 abd_iterate_func2(abd_t *dabd, abd_t *sabd, size_t doff, size_t soff,
884     size_t size, abd_iter_func2_t *func, void *private)
885 {
886         int ret = 0;
887         struct abd_iter daiter, saiter;
888
889         abd_verify(dabd);
890         abd_verify(sabd);
891
892         ASSERT3U(doff + size, <=, dabd->abd_size);
893         ASSERT3U(soff + size, <=, sabd->abd_size);
894
895         abd_iter_init(&daiter, dabd);
896         abd_iter_init(&saiter, sabd);
897         abd_iter_advance(&daiter, doff);
898         abd_iter_advance(&saiter, soff);
899
900         while (size > 0) {
901                 abd_iter_map(&daiter);
902                 abd_iter_map(&saiter);
903
904                 size_t dlen = MIN(daiter.iter_mapsize, size);
905                 size_t slen = MIN(saiter.iter_mapsize, size);
906                 size_t len = MIN(dlen, slen);
907                 ASSERT(dlen > 0 || slen > 0);
908
909                 ret = func(daiter.iter_mapaddr, saiter.iter_mapaddr, len,
910                     private);
911
912                 abd_iter_unmap(&saiter);
913                 abd_iter_unmap(&daiter);
914
915                 if (ret != 0)
916                         break;
917
918                 size -= len;
919                 abd_iter_advance(&daiter, len);
920                 abd_iter_advance(&saiter, len);
921         }
922
923         return (ret);
924 }
925
926 /*ARGSUSED*/
927 static int
928 abd_copy_off_cb(void *dbuf, void *sbuf, size_t size, void *private)
929 {
930         (void) memcpy(dbuf, sbuf, size);
931         return (0);
932 }
933
934 /*
935  * Copy from sabd to dabd starting from soff and doff.
936  */
937 void
938 abd_copy_off(abd_t *dabd, abd_t *sabd, size_t doff, size_t soff, size_t size)
939 {
940         (void) abd_iterate_func2(dabd, sabd, doff, soff, size,
941             abd_copy_off_cb, NULL);
942 }
943
944 /*ARGSUSED*/
945 static int
946 abd_cmp_cb(void *bufa, void *bufb, size_t size, void *private)
947 {
948         return (memcmp(bufa, bufb, size));
949 }
950
951 /*
952  * Compares the first size bytes of two ABDs.
953  */
954 int
955 abd_cmp(abd_t *dabd, abd_t *sabd, size_t size)
956 {
957         return (abd_iterate_func2(dabd, sabd, 0, 0, size, abd_cmp_cb, NULL));
958 }