]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c
MFC r308782:
[FreeBSD/stable/10.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zio.c
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) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2011, 2016 by Delphix. All rights reserved.
24  * Copyright (c) 2011 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  */
27
28 #include <sys/sysmacros.h>
29 #include <sys/zfs_context.h>
30 #include <sys/fm/fs/zfs.h>
31 #include <sys/spa.h>
32 #include <sys/txg.h>
33 #include <sys/spa_impl.h>
34 #include <sys/vdev_impl.h>
35 #include <sys/zio_impl.h>
36 #include <sys/zio_compress.h>
37 #include <sys/zio_checksum.h>
38 #include <sys/dmu_objset.h>
39 #include <sys/arc.h>
40 #include <sys/ddt.h>
41 #include <sys/trim_map.h>
42 #include <sys/blkptr.h>
43 #include <sys/zfeature.h>
44 #include <sys/metaslab_impl.h>
45
46 SYSCTL_DECL(_vfs_zfs);
47 SYSCTL_NODE(_vfs_zfs, OID_AUTO, zio, CTLFLAG_RW, 0, "ZFS ZIO");
48 #if defined(__amd64__)
49 static int zio_use_uma = 1;
50 #else
51 static int zio_use_uma = 0;
52 #endif
53 TUNABLE_INT("vfs.zfs.zio.use_uma", &zio_use_uma);
54 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, use_uma, CTLFLAG_RDTUN, &zio_use_uma, 0,
55     "Use uma(9) for ZIO allocations");
56 static int zio_exclude_metadata = 0;
57 TUNABLE_INT("vfs.zfs.zio.exclude_metadata", &zio_exclude_metadata);
58 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, exclude_metadata, CTLFLAG_RDTUN, &zio_exclude_metadata, 0,
59     "Exclude metadata buffers from dumps as well");
60
61 zio_trim_stats_t zio_trim_stats = {
62         { "bytes",              KSTAT_DATA_UINT64,
63           "Number of bytes successfully TRIMmed" },
64         { "success",            KSTAT_DATA_UINT64,
65           "Number of successful TRIM requests" },
66         { "unsupported",        KSTAT_DATA_UINT64,
67           "Number of TRIM requests that failed because TRIM is not supported" },
68         { "failed",             KSTAT_DATA_UINT64,
69           "Number of TRIM requests that failed for reasons other than not supported" },
70 };
71
72 static kstat_t *zio_trim_ksp;
73
74 /*
75  * ==========================================================================
76  * I/O type descriptions
77  * ==========================================================================
78  */
79 const char *zio_type_name[ZIO_TYPES] = {
80         "zio_null", "zio_read", "zio_write", "zio_free", "zio_claim",
81         "zio_ioctl"
82 };
83
84 boolean_t zio_dva_throttle_enabled = B_TRUE;
85 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, dva_throttle_enabled, CTLFLAG_RDTUN,
86     &zio_dva_throttle_enabled, 0, "");
87
88 /*
89  * ==========================================================================
90  * I/O kmem caches
91  * ==========================================================================
92  */
93 kmem_cache_t *zio_cache;
94 kmem_cache_t *zio_link_cache;
95 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
96 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
97
98 #ifdef _KERNEL
99 extern vmem_t *zio_alloc_arena;
100 #endif
101
102 #define ZIO_PIPELINE_CONTINUE           0x100
103 #define ZIO_PIPELINE_STOP               0x101
104
105 #define BP_SPANB(indblkshift, level) \
106         (((uint64_t)1) << ((level) * ((indblkshift) - SPA_BLKPTRSHIFT)))
107 #define COMPARE_META_LEVEL      0x80000000ul
108 /*
109  * The following actions directly effect the spa's sync-to-convergence logic.
110  * The values below define the sync pass when we start performing the action.
111  * Care should be taken when changing these values as they directly impact
112  * spa_sync() performance. Tuning these values may introduce subtle performance
113  * pathologies and should only be done in the context of performance analysis.
114  * These tunables will eventually be removed and replaced with #defines once
115  * enough analysis has been done to determine optimal values.
116  *
117  * The 'zfs_sync_pass_deferred_free' pass must be greater than 1 to ensure that
118  * regular blocks are not deferred.
119  */
120 int zfs_sync_pass_deferred_free = 2; /* defer frees starting in this pass */
121 TUNABLE_INT("vfs.zfs.sync_pass_deferred_free", &zfs_sync_pass_deferred_free);
122 SYSCTL_INT(_vfs_zfs, OID_AUTO, sync_pass_deferred_free, CTLFLAG_RDTUN,
123     &zfs_sync_pass_deferred_free, 0, "defer frees starting in this pass");
124 int zfs_sync_pass_dont_compress = 5; /* don't compress starting in this pass */
125 TUNABLE_INT("vfs.zfs.sync_pass_dont_compress", &zfs_sync_pass_dont_compress);
126 SYSCTL_INT(_vfs_zfs, OID_AUTO, sync_pass_dont_compress, CTLFLAG_RDTUN,
127     &zfs_sync_pass_dont_compress, 0, "don't compress starting in this pass");
128 int zfs_sync_pass_rewrite = 2; /* rewrite new bps starting in this pass */
129 TUNABLE_INT("vfs.zfs.sync_pass_rewrite", &zfs_sync_pass_rewrite);
130 SYSCTL_INT(_vfs_zfs, OID_AUTO, sync_pass_rewrite, CTLFLAG_RDTUN,
131     &zfs_sync_pass_rewrite, 0, "rewrite new bps starting in this pass");
132
133 /*
134  * An allocating zio is one that either currently has the DVA allocate
135  * stage set or will have it later in its lifetime.
136  */
137 #define IO_IS_ALLOCATING(zio) ((zio)->io_orig_pipeline & ZIO_STAGE_DVA_ALLOCATE)
138
139 boolean_t       zio_requeue_io_start_cut_in_line = B_TRUE;
140
141 #ifdef illumos
142 #ifdef ZFS_DEBUG
143 int zio_buf_debug_limit = 16384;
144 #else
145 int zio_buf_debug_limit = 0;
146 #endif
147 #endif
148
149 static void zio_taskq_dispatch(zio_t *, zio_taskq_type_t, boolean_t);
150
151 void
152 zio_init(void)
153 {
154         size_t c;
155         zio_cache = kmem_cache_create("zio_cache",
156             sizeof (zio_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
157         zio_link_cache = kmem_cache_create("zio_link_cache",
158             sizeof (zio_link_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
159         if (!zio_use_uma)
160                 goto out;
161
162         /*
163          * For small buffers, we want a cache for each multiple of
164          * SPA_MINBLOCKSIZE.  For larger buffers, we want a cache
165          * for each quarter-power of 2.
166          */
167         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
168                 size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
169                 size_t p2 = size;
170                 size_t align = 0;
171                 int cflags = zio_exclude_metadata ? KMC_NODEBUG : 0;
172
173                 while (!ISP2(p2))
174                         p2 &= p2 - 1;
175
176 #ifdef illumos
177 #ifndef _KERNEL
178                 /*
179                  * If we are using watchpoints, put each buffer on its own page,
180                  * to eliminate the performance overhead of trapping to the
181                  * kernel when modifying a non-watched buffer that shares the
182                  * page with a watched buffer.
183                  */
184                 if (arc_watch && !IS_P2ALIGNED(size, PAGESIZE))
185                         continue;
186 #endif
187 #endif /* illumos */
188                 if (size <= 4 * SPA_MINBLOCKSIZE) {
189                         align = SPA_MINBLOCKSIZE;
190                 } else if (IS_P2ALIGNED(size, p2 >> 2)) {
191                         align = MIN(p2 >> 2, PAGESIZE);
192                 }
193
194                 if (align != 0) {
195                         char name[36];
196                         (void) sprintf(name, "zio_buf_%lu", (ulong_t)size);
197                         zio_buf_cache[c] = kmem_cache_create(name, size,
198                             align, NULL, NULL, NULL, NULL, NULL, cflags);
199
200                         /*
201                          * Since zio_data bufs do not appear in crash dumps, we
202                          * pass KMC_NOTOUCH so that no allocator metadata is
203                          * stored with the buffers.
204                          */
205                         (void) sprintf(name, "zio_data_buf_%lu", (ulong_t)size);
206                         zio_data_buf_cache[c] = kmem_cache_create(name, size,
207                             align, NULL, NULL, NULL, NULL, NULL,
208                             cflags | KMC_NOTOUCH | KMC_NODEBUG);
209                 }
210         }
211
212         while (--c != 0) {
213                 ASSERT(zio_buf_cache[c] != NULL);
214                 if (zio_buf_cache[c - 1] == NULL)
215                         zio_buf_cache[c - 1] = zio_buf_cache[c];
216
217                 ASSERT(zio_data_buf_cache[c] != NULL);
218                 if (zio_data_buf_cache[c - 1] == NULL)
219                         zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
220         }
221 out:
222
223         zio_inject_init();
224
225         zio_trim_ksp = kstat_create("zfs", 0, "zio_trim", "misc",
226             KSTAT_TYPE_NAMED,
227             sizeof(zio_trim_stats) / sizeof(kstat_named_t),
228             KSTAT_FLAG_VIRTUAL);
229
230         if (zio_trim_ksp != NULL) {
231                 zio_trim_ksp->ks_data = &zio_trim_stats;
232                 kstat_install(zio_trim_ksp);
233         }
234 }
235
236 void
237 zio_fini(void)
238 {
239         size_t c;
240         kmem_cache_t *last_cache = NULL;
241         kmem_cache_t *last_data_cache = NULL;
242
243         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
244                 if (zio_buf_cache[c] != last_cache) {
245                         last_cache = zio_buf_cache[c];
246                         kmem_cache_destroy(zio_buf_cache[c]);
247                 }
248                 zio_buf_cache[c] = NULL;
249
250                 if (zio_data_buf_cache[c] != last_data_cache) {
251                         last_data_cache = zio_data_buf_cache[c];
252                         kmem_cache_destroy(zio_data_buf_cache[c]);
253                 }
254                 zio_data_buf_cache[c] = NULL;
255         }
256
257         kmem_cache_destroy(zio_link_cache);
258         kmem_cache_destroy(zio_cache);
259
260         zio_inject_fini();
261
262         if (zio_trim_ksp != NULL) {
263                 kstat_delete(zio_trim_ksp);
264                 zio_trim_ksp = NULL;
265         }
266 }
267
268 /*
269  * ==========================================================================
270  * Allocate and free I/O buffers
271  * ==========================================================================
272  */
273
274 /*
275  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
276  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
277  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
278  * excess / transient data in-core during a crashdump.
279  */
280 static void *
281 zio_buf_alloc_impl(size_t size, boolean_t canwait)
282 {
283         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
284         int flags = zio_exclude_metadata ? KM_NODEBUG : 0;
285
286         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
287
288         if (zio_use_uma) {
289                 return (kmem_cache_alloc(zio_buf_cache[c],
290                     canwait ? KM_PUSHPAGE : KM_NOSLEEP));
291         } else {
292                 return (kmem_alloc(size,
293                     (canwait ? KM_SLEEP : KM_NOSLEEP) | flags));
294         }
295 }
296
297 void *
298 zio_buf_alloc(size_t size)
299 {
300         return (zio_buf_alloc_impl(size, B_TRUE));
301 }
302
303 void *
304 zio_buf_alloc_nowait(size_t size)
305 {
306         return (zio_buf_alloc_impl(size, B_FALSE));
307 }
308
309 /*
310  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
311  * crashdump if the kernel panics.  This exists so that we will limit the amount
312  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
313  * of kernel heap dumped to disk when the kernel panics)
314  */
315 void *
316 zio_data_buf_alloc(size_t size)
317 {
318         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
319
320         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
321
322         if (zio_use_uma)
323                 return (kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE));
324         else
325                 return (kmem_alloc(size, KM_SLEEP | KM_NODEBUG));
326 }
327
328 void
329 zio_buf_free(void *buf, size_t size)
330 {
331         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
332
333         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
334
335         if (zio_use_uma)
336                 kmem_cache_free(zio_buf_cache[c], buf);
337         else
338                 kmem_free(buf, size);
339 }
340
341 void
342 zio_data_buf_free(void *buf, size_t size)
343 {
344         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
345
346         VERIFY3U(c, <, SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
347
348         if (zio_use_uma)
349                 kmem_cache_free(zio_data_buf_cache[c], buf);
350         else
351                 kmem_free(buf, size);
352 }
353
354 /*
355  * ==========================================================================
356  * Push and pop I/O transform buffers
357  * ==========================================================================
358  */
359 void
360 zio_push_transform(zio_t *zio, void *data, uint64_t size, uint64_t bufsize,
361     zio_transform_func_t *transform)
362 {
363         zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
364
365         zt->zt_orig_data = zio->io_data;
366         zt->zt_orig_size = zio->io_size;
367         zt->zt_bufsize = bufsize;
368         zt->zt_transform = transform;
369
370         zt->zt_next = zio->io_transform_stack;
371         zio->io_transform_stack = zt;
372
373         zio->io_data = data;
374         zio->io_size = size;
375 }
376
377 void
378 zio_pop_transforms(zio_t *zio)
379 {
380         zio_transform_t *zt;
381
382         while ((zt = zio->io_transform_stack) != NULL) {
383                 if (zt->zt_transform != NULL)
384                         zt->zt_transform(zio,
385                             zt->zt_orig_data, zt->zt_orig_size);
386
387                 if (zt->zt_bufsize != 0)
388                         zio_buf_free(zio->io_data, zt->zt_bufsize);
389
390                 zio->io_data = zt->zt_orig_data;
391                 zio->io_size = zt->zt_orig_size;
392                 zio->io_transform_stack = zt->zt_next;
393
394                 kmem_free(zt, sizeof (zio_transform_t));
395         }
396 }
397
398 /*
399  * ==========================================================================
400  * I/O transform callbacks for subblocks and decompression
401  * ==========================================================================
402  */
403 static void
404 zio_subblock(zio_t *zio, void *data, uint64_t size)
405 {
406         ASSERT(zio->io_size > size);
407
408         if (zio->io_type == ZIO_TYPE_READ)
409                 bcopy(zio->io_data, data, size);
410 }
411
412 static void
413 zio_decompress(zio_t *zio, void *data, uint64_t size)
414 {
415         if (zio->io_error == 0 &&
416             zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
417             zio->io_data, data, zio->io_size, size) != 0)
418                 zio->io_error = SET_ERROR(EIO);
419 }
420
421 /*
422  * ==========================================================================
423  * I/O parent/child relationships and pipeline interlocks
424  * ==========================================================================
425  */
426 zio_t *
427 zio_walk_parents(zio_t *cio, zio_link_t **zl)
428 {
429         list_t *pl = &cio->io_parent_list;
430
431         *zl = (*zl == NULL) ? list_head(pl) : list_next(pl, *zl);
432         if (*zl == NULL)
433                 return (NULL);
434
435         ASSERT((*zl)->zl_child == cio);
436         return ((*zl)->zl_parent);
437 }
438
439 zio_t *
440 zio_walk_children(zio_t *pio, zio_link_t **zl)
441 {
442         list_t *cl = &pio->io_child_list;
443
444         *zl = (*zl == NULL) ? list_head(cl) : list_next(cl, *zl);
445         if (*zl == NULL)
446                 return (NULL);
447
448         ASSERT((*zl)->zl_parent == pio);
449         return ((*zl)->zl_child);
450 }
451
452 zio_t *
453 zio_unique_parent(zio_t *cio)
454 {
455         zio_link_t *zl = NULL;
456         zio_t *pio = zio_walk_parents(cio, &zl);
457
458         VERIFY3P(zio_walk_parents(cio, &zl), ==, NULL);
459         return (pio);
460 }
461
462 void
463 zio_add_child(zio_t *pio, zio_t *cio)
464 {
465         zio_link_t *zl = kmem_cache_alloc(zio_link_cache, KM_SLEEP);
466
467         /*
468          * Logical I/Os can have logical, gang, or vdev children.
469          * Gang I/Os can have gang or vdev children.
470          * Vdev I/Os can only have vdev children.
471          * The following ASSERT captures all of these constraints.
472          */
473         ASSERT(cio->io_child_type <= pio->io_child_type);
474
475         zl->zl_parent = pio;
476         zl->zl_child = cio;
477
478         mutex_enter(&cio->io_lock);
479         mutex_enter(&pio->io_lock);
480
481         ASSERT(pio->io_state[ZIO_WAIT_DONE] == 0);
482
483         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
484                 pio->io_children[cio->io_child_type][w] += !cio->io_state[w];
485
486         list_insert_head(&pio->io_child_list, zl);
487         list_insert_head(&cio->io_parent_list, zl);
488
489         pio->io_child_count++;
490         cio->io_parent_count++;
491
492         mutex_exit(&pio->io_lock);
493         mutex_exit(&cio->io_lock);
494 }
495
496 static void
497 zio_remove_child(zio_t *pio, zio_t *cio, zio_link_t *zl)
498 {
499         ASSERT(zl->zl_parent == pio);
500         ASSERT(zl->zl_child == cio);
501
502         mutex_enter(&cio->io_lock);
503         mutex_enter(&pio->io_lock);
504
505         list_remove(&pio->io_child_list, zl);
506         list_remove(&cio->io_parent_list, zl);
507
508         pio->io_child_count--;
509         cio->io_parent_count--;
510
511         mutex_exit(&pio->io_lock);
512         mutex_exit(&cio->io_lock);
513
514         kmem_cache_free(zio_link_cache, zl);
515 }
516
517 static boolean_t
518 zio_wait_for_children(zio_t *zio, enum zio_child child, enum zio_wait_type wait)
519 {
520         uint64_t *countp = &zio->io_children[child][wait];
521         boolean_t waiting = B_FALSE;
522
523         mutex_enter(&zio->io_lock);
524         ASSERT(zio->io_stall == NULL);
525         if (*countp != 0) {
526                 zio->io_stage >>= 1;
527                 ASSERT3U(zio->io_stage, !=, ZIO_STAGE_OPEN);
528                 zio->io_stall = countp;
529                 waiting = B_TRUE;
530         }
531         mutex_exit(&zio->io_lock);
532
533         return (waiting);
534 }
535
536 static void
537 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait)
538 {
539         uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
540         int *errorp = &pio->io_child_error[zio->io_child_type];
541
542         mutex_enter(&pio->io_lock);
543         if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
544                 *errorp = zio_worst_error(*errorp, zio->io_error);
545         pio->io_reexecute |= zio->io_reexecute;
546         ASSERT3U(*countp, >, 0);
547
548         (*countp)--;
549
550         if (*countp == 0 && pio->io_stall == countp) {
551                 zio_taskq_type_t type =
552                     pio->io_stage < ZIO_STAGE_VDEV_IO_START ? ZIO_TASKQ_ISSUE :
553                     ZIO_TASKQ_INTERRUPT;
554                 pio->io_stall = NULL;
555                 mutex_exit(&pio->io_lock);
556                 /*
557                  * Dispatch the parent zio in its own taskq so that
558                  * the child can continue to make progress. This also
559                  * prevents overflowing the stack when we have deeply nested
560                  * parent-child relationships.
561                  */
562                 zio_taskq_dispatch(pio, type, B_FALSE);
563         } else {
564                 mutex_exit(&pio->io_lock);
565         }
566 }
567
568 static void
569 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
570 {
571         if (zio->io_child_error[c] != 0 && zio->io_error == 0)
572                 zio->io_error = zio->io_child_error[c];
573 }
574
575 int
576 zio_timestamp_compare(const void *x1, const void *x2)
577 {
578         const zio_t *z1 = x1;
579         const zio_t *z2 = x2;
580
581         if (z1->io_queued_timestamp < z2->io_queued_timestamp)
582                 return (-1);
583         if (z1->io_queued_timestamp > z2->io_queued_timestamp)
584                 return (1);
585
586         if (z1->io_bookmark.zb_objset < z2->io_bookmark.zb_objset)
587                 return (-1);
588         if (z1->io_bookmark.zb_objset > z2->io_bookmark.zb_objset)
589                 return (1);
590
591         if (z1->io_bookmark.zb_object < z2->io_bookmark.zb_object)
592                 return (-1);
593         if (z1->io_bookmark.zb_object > z2->io_bookmark.zb_object)
594                 return (1);
595
596         if (z1->io_bookmark.zb_level < z2->io_bookmark.zb_level)
597                 return (-1);
598         if (z1->io_bookmark.zb_level > z2->io_bookmark.zb_level)
599                 return (1);
600
601         if (z1->io_bookmark.zb_blkid < z2->io_bookmark.zb_blkid)
602                 return (-1);
603         if (z1->io_bookmark.zb_blkid > z2->io_bookmark.zb_blkid)
604                 return (1);
605
606         if (z1 < z2)
607                 return (-1);
608         if (z1 > z2)
609                 return (1);
610
611         return (0);
612 }
613
614 /*
615  * ==========================================================================
616  * Create the various types of I/O (read, write, free, etc)
617  * ==========================================================================
618  */
619 static zio_t *
620 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
621     void *data, uint64_t size, zio_done_func_t *done, void *private,
622     zio_type_t type, zio_priority_t priority, enum zio_flag flags,
623     vdev_t *vd, uint64_t offset, const zbookmark_phys_t *zb,
624     enum zio_stage stage, enum zio_stage pipeline)
625 {
626         zio_t *zio;
627
628         ASSERT3U(type == ZIO_TYPE_FREE || size, <=, SPA_MAXBLOCKSIZE);
629         ASSERT(P2PHASE(size, SPA_MINBLOCKSIZE) == 0);
630         ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
631
632         ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
633         ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
634         ASSERT(vd || stage == ZIO_STAGE_OPEN);
635
636         zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
637         bzero(zio, sizeof (zio_t));
638
639         mutex_init(&zio->io_lock, NULL, MUTEX_DEFAULT, NULL);
640         cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
641
642         list_create(&zio->io_parent_list, sizeof (zio_link_t),
643             offsetof(zio_link_t, zl_parent_node));
644         list_create(&zio->io_child_list, sizeof (zio_link_t),
645             offsetof(zio_link_t, zl_child_node));
646
647         if (vd != NULL)
648                 zio->io_child_type = ZIO_CHILD_VDEV;
649         else if (flags & ZIO_FLAG_GANG_CHILD)
650                 zio->io_child_type = ZIO_CHILD_GANG;
651         else if (flags & ZIO_FLAG_DDT_CHILD)
652                 zio->io_child_type = ZIO_CHILD_DDT;
653         else
654                 zio->io_child_type = ZIO_CHILD_LOGICAL;
655
656         if (bp != NULL) {
657                 zio->io_bp = (blkptr_t *)bp;
658                 zio->io_bp_copy = *bp;
659                 zio->io_bp_orig = *bp;
660                 if (type != ZIO_TYPE_WRITE ||
661                     zio->io_child_type == ZIO_CHILD_DDT)
662                         zio->io_bp = &zio->io_bp_copy;  /* so caller can free */
663                 if (zio->io_child_type == ZIO_CHILD_LOGICAL)
664                         zio->io_logical = zio;
665                 if (zio->io_child_type > ZIO_CHILD_GANG && BP_IS_GANG(bp))
666                         pipeline |= ZIO_GANG_STAGES;
667         }
668
669         zio->io_spa = spa;
670         zio->io_txg = txg;
671         zio->io_done = done;
672         zio->io_private = private;
673         zio->io_type = type;
674         zio->io_priority = priority;
675         zio->io_vd = vd;
676         zio->io_offset = offset;
677         zio->io_orig_data = zio->io_data = data;
678         zio->io_orig_size = zio->io_size = size;
679         zio->io_orig_flags = zio->io_flags = flags;
680         zio->io_orig_stage = zio->io_stage = stage;
681         zio->io_orig_pipeline = zio->io_pipeline = pipeline;
682         zio->io_pipeline_trace = ZIO_STAGE_OPEN;
683
684         zio->io_state[ZIO_WAIT_READY] = (stage >= ZIO_STAGE_READY);
685         zio->io_state[ZIO_WAIT_DONE] = (stage >= ZIO_STAGE_DONE);
686
687         if (zb != NULL)
688                 zio->io_bookmark = *zb;
689
690         if (pio != NULL) {
691                 if (zio->io_logical == NULL)
692                         zio->io_logical = pio->io_logical;
693                 if (zio->io_child_type == ZIO_CHILD_GANG)
694                         zio->io_gang_leader = pio->io_gang_leader;
695                 zio_add_child(pio, zio);
696         }
697
698         return (zio);
699 }
700
701 static void
702 zio_destroy(zio_t *zio)
703 {
704         list_destroy(&zio->io_parent_list);
705         list_destroy(&zio->io_child_list);
706         mutex_destroy(&zio->io_lock);
707         cv_destroy(&zio->io_cv);
708         kmem_cache_free(zio_cache, zio);
709 }
710
711 zio_t *
712 zio_null(zio_t *pio, spa_t *spa, vdev_t *vd, zio_done_func_t *done,
713     void *private, enum zio_flag flags)
714 {
715         zio_t *zio;
716
717         zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
718             ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
719             ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
720
721         return (zio);
722 }
723
724 zio_t *
725 zio_root(spa_t *spa, zio_done_func_t *done, void *private, enum zio_flag flags)
726 {
727         return (zio_null(NULL, spa, NULL, done, private, flags));
728 }
729
730 void
731 zfs_blkptr_verify(spa_t *spa, const blkptr_t *bp)
732 {
733         if (!DMU_OT_IS_VALID(BP_GET_TYPE(bp))) {
734                 zfs_panic_recover("blkptr at %p has invalid TYPE %llu",
735                     bp, (longlong_t)BP_GET_TYPE(bp));
736         }
737         if (BP_GET_CHECKSUM(bp) >= ZIO_CHECKSUM_FUNCTIONS ||
738             BP_GET_CHECKSUM(bp) <= ZIO_CHECKSUM_ON) {
739                 zfs_panic_recover("blkptr at %p has invalid CHECKSUM %llu",
740                     bp, (longlong_t)BP_GET_CHECKSUM(bp));
741         }
742         if (BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_FUNCTIONS ||
743             BP_GET_COMPRESS(bp) <= ZIO_COMPRESS_ON) {
744                 zfs_panic_recover("blkptr at %p has invalid COMPRESS %llu",
745                     bp, (longlong_t)BP_GET_COMPRESS(bp));
746         }
747         if (BP_GET_LSIZE(bp) > SPA_MAXBLOCKSIZE) {
748                 zfs_panic_recover("blkptr at %p has invalid LSIZE %llu",
749                     bp, (longlong_t)BP_GET_LSIZE(bp));
750         }
751         if (BP_GET_PSIZE(bp) > SPA_MAXBLOCKSIZE) {
752                 zfs_panic_recover("blkptr at %p has invalid PSIZE %llu",
753                     bp, (longlong_t)BP_GET_PSIZE(bp));
754         }
755
756         if (BP_IS_EMBEDDED(bp)) {
757                 if (BPE_GET_ETYPE(bp) > NUM_BP_EMBEDDED_TYPES) {
758                         zfs_panic_recover("blkptr at %p has invalid ETYPE %llu",
759                             bp, (longlong_t)BPE_GET_ETYPE(bp));
760                 }
761         }
762
763         /*
764          * Pool-specific checks.
765          *
766          * Note: it would be nice to verify that the blk_birth and
767          * BP_PHYSICAL_BIRTH() are not too large.  However, spa_freeze()
768          * allows the birth time of log blocks (and dmu_sync()-ed blocks
769          * that are in the log) to be arbitrarily large.
770          */
771         for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
772                 uint64_t vdevid = DVA_GET_VDEV(&bp->blk_dva[i]);
773                 if (vdevid >= spa->spa_root_vdev->vdev_children) {
774                         zfs_panic_recover("blkptr at %p DVA %u has invalid "
775                             "VDEV %llu",
776                             bp, i, (longlong_t)vdevid);
777                         continue;
778                 }
779                 vdev_t *vd = spa->spa_root_vdev->vdev_child[vdevid];
780                 if (vd == NULL) {
781                         zfs_panic_recover("blkptr at %p DVA %u has invalid "
782                             "VDEV %llu",
783                             bp, i, (longlong_t)vdevid);
784                         continue;
785                 }
786                 if (vd->vdev_ops == &vdev_hole_ops) {
787                         zfs_panic_recover("blkptr at %p DVA %u has hole "
788                             "VDEV %llu",
789                             bp, i, (longlong_t)vdevid);
790                         continue;
791                 }
792                 if (vd->vdev_ops == &vdev_missing_ops) {
793                         /*
794                          * "missing" vdevs are valid during import, but we
795                          * don't have their detailed info (e.g. asize), so
796                          * we can't perform any more checks on them.
797                          */
798                         continue;
799                 }
800                 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
801                 uint64_t asize = DVA_GET_ASIZE(&bp->blk_dva[i]);
802                 if (BP_IS_GANG(bp))
803                         asize = vdev_psize_to_asize(vd, SPA_GANGBLOCKSIZE);
804                 if (offset + asize > vd->vdev_asize) {
805                         zfs_panic_recover("blkptr at %p DVA %u has invalid "
806                             "OFFSET %llu",
807                             bp, i, (longlong_t)offset);
808                 }
809         }
810 }
811
812 zio_t *
813 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
814     void *data, uint64_t size, zio_done_func_t *done, void *private,
815     zio_priority_t priority, enum zio_flag flags, const zbookmark_phys_t *zb)
816 {
817         zio_t *zio;
818
819         zfs_blkptr_verify(spa, bp);
820
821         zio = zio_create(pio, spa, BP_PHYSICAL_BIRTH(bp), bp,
822             data, size, done, private,
823             ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
824             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
825             ZIO_DDT_CHILD_READ_PIPELINE : ZIO_READ_PIPELINE);
826
827         return (zio);
828 }
829
830 zio_t *
831 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
832     void *data, uint64_t size, const zio_prop_t *zp,
833     zio_done_func_t *ready, zio_done_func_t *children_ready,
834     zio_done_func_t *physdone, zio_done_func_t *done,
835     void *private, zio_priority_t priority, enum zio_flag flags,
836     const zbookmark_phys_t *zb)
837 {
838         zio_t *zio;
839
840         ASSERT(zp->zp_checksum >= ZIO_CHECKSUM_OFF &&
841             zp->zp_checksum < ZIO_CHECKSUM_FUNCTIONS &&
842             zp->zp_compress >= ZIO_COMPRESS_OFF &&
843             zp->zp_compress < ZIO_COMPRESS_FUNCTIONS &&
844             DMU_OT_IS_VALID(zp->zp_type) &&
845             zp->zp_level < 32 &&
846             zp->zp_copies > 0 &&
847             zp->zp_copies <= spa_max_replication(spa));
848
849         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
850             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
851             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
852             ZIO_DDT_CHILD_WRITE_PIPELINE : ZIO_WRITE_PIPELINE);
853
854         zio->io_ready = ready;
855         zio->io_children_ready = children_ready;
856         zio->io_physdone = physdone;
857         zio->io_prop = *zp;
858
859         /*
860          * Data can be NULL if we are going to call zio_write_override() to
861          * provide the already-allocated BP.  But we may need the data to
862          * verify a dedup hit (if requested).  In this case, don't try to
863          * dedup (just take the already-allocated BP verbatim).
864          */
865         if (data == NULL && zio->io_prop.zp_dedup_verify) {
866                 zio->io_prop.zp_dedup = zio->io_prop.zp_dedup_verify = B_FALSE;
867         }
868
869         return (zio);
870 }
871
872 zio_t *
873 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, void *data,
874     uint64_t size, zio_done_func_t *done, void *private,
875     zio_priority_t priority, enum zio_flag flags, zbookmark_phys_t *zb)
876 {
877         zio_t *zio;
878
879         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
880             ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_IO_REWRITE, NULL, 0, zb,
881             ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
882
883         return (zio);
884 }
885
886 void
887 zio_write_override(zio_t *zio, blkptr_t *bp, int copies, boolean_t nopwrite)
888 {
889         ASSERT(zio->io_type == ZIO_TYPE_WRITE);
890         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
891         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
892         ASSERT(zio->io_txg == spa_syncing_txg(zio->io_spa));
893
894         /*
895          * We must reset the io_prop to match the values that existed
896          * when the bp was first written by dmu_sync() keeping in mind
897          * that nopwrite and dedup are mutually exclusive.
898          */
899         zio->io_prop.zp_dedup = nopwrite ? B_FALSE : zio->io_prop.zp_dedup;
900         zio->io_prop.zp_nopwrite = nopwrite;
901         zio->io_prop.zp_copies = copies;
902         zio->io_bp_override = bp;
903 }
904
905 void
906 zio_free(spa_t *spa, uint64_t txg, const blkptr_t *bp)
907 {
908
909         /*
910          * The check for EMBEDDED is a performance optimization.  We
911          * process the free here (by ignoring it) rather than
912          * putting it on the list and then processing it in zio_free_sync().
913          */
914         if (BP_IS_EMBEDDED(bp))
915                 return;
916         metaslab_check_free(spa, bp);
917
918         /*
919          * Frees that are for the currently-syncing txg, are not going to be
920          * deferred, and which will not need to do a read (i.e. not GANG or
921          * DEDUP), can be processed immediately.  Otherwise, put them on the
922          * in-memory list for later processing.
923          */
924         if (zfs_trim_enabled || BP_IS_GANG(bp) || BP_GET_DEDUP(bp) ||
925             txg != spa->spa_syncing_txg ||
926             spa_sync_pass(spa) >= zfs_sync_pass_deferred_free) {
927                 bplist_append(&spa->spa_free_bplist[txg & TXG_MASK], bp);
928         } else {
929                 VERIFY0(zio_wait(zio_free_sync(NULL, spa, txg, bp,
930                     BP_GET_PSIZE(bp), 0)));
931         }
932 }
933
934 zio_t *
935 zio_free_sync(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
936     uint64_t size, enum zio_flag flags)
937 {
938         zio_t *zio;
939         enum zio_stage stage = ZIO_FREE_PIPELINE;
940
941         ASSERT(!BP_IS_HOLE(bp));
942         ASSERT(spa_syncing_txg(spa) == txg);
943         ASSERT(spa_sync_pass(spa) < zfs_sync_pass_deferred_free);
944
945         if (BP_IS_EMBEDDED(bp))
946                 return (zio_null(pio, spa, NULL, NULL, NULL, 0));
947
948         metaslab_check_free(spa, bp);
949         arc_freed(spa, bp);
950
951         if (zfs_trim_enabled)
952                 stage |= ZIO_STAGE_ISSUE_ASYNC | ZIO_STAGE_VDEV_IO_START |
953                     ZIO_STAGE_VDEV_IO_ASSESS;
954         /*
955          * GANG and DEDUP blocks can induce a read (for the gang block header,
956          * or the DDT), so issue them asynchronously so that this thread is
957          * not tied up.
958          */
959         else if (BP_IS_GANG(bp) || BP_GET_DEDUP(bp))
960                 stage |= ZIO_STAGE_ISSUE_ASYNC;
961
962         flags |= ZIO_FLAG_DONT_QUEUE;
963
964         zio = zio_create(pio, spa, txg, bp, NULL, size,
965             NULL, NULL, ZIO_TYPE_FREE, ZIO_PRIORITY_NOW, flags,
966             NULL, 0, NULL, ZIO_STAGE_OPEN, stage);
967
968         return (zio);
969 }
970
971 zio_t *
972 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
973     zio_done_func_t *done, void *private, enum zio_flag flags)
974 {
975         zio_t *zio;
976
977         dprintf_bp(bp, "claiming in txg %llu", txg);
978
979         if (BP_IS_EMBEDDED(bp))
980                 return (zio_null(pio, spa, NULL, NULL, NULL, 0));
981
982         /*
983          * A claim is an allocation of a specific block.  Claims are needed
984          * to support immediate writes in the intent log.  The issue is that
985          * immediate writes contain committed data, but in a txg that was
986          * *not* committed.  Upon opening the pool after an unclean shutdown,
987          * the intent log claims all blocks that contain immediate write data
988          * so that the SPA knows they're in use.
989          *
990          * All claims *must* be resolved in the first txg -- before the SPA
991          * starts allocating blocks -- so that nothing is allocated twice.
992          * If txg == 0 we just verify that the block is claimable.
993          */
994         ASSERT3U(spa->spa_uberblock.ub_rootbp.blk_birth, <, spa_first_txg(spa));
995         ASSERT(txg == spa_first_txg(spa) || txg == 0);
996         ASSERT(!BP_GET_DEDUP(bp) || !spa_writeable(spa));       /* zdb(1M) */
997
998         zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
999             done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW, flags,
1000             NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
1001         ASSERT0(zio->io_queued_timestamp);
1002
1003         return (zio);
1004 }
1005
1006 zio_t *
1007 zio_ioctl(zio_t *pio, spa_t *spa, vdev_t *vd, int cmd, uint64_t offset,
1008     uint64_t size, zio_done_func_t *done, void *private,
1009     zio_priority_t priority, enum zio_flag flags)
1010 {
1011         zio_t *zio;
1012         int c;
1013
1014         if (vd->vdev_children == 0) {
1015                 zio = zio_create(pio, spa, 0, NULL, NULL, size, done, private,
1016                     ZIO_TYPE_IOCTL, priority, flags, vd, offset, NULL,
1017                     ZIO_STAGE_OPEN, ZIO_IOCTL_PIPELINE);
1018
1019                 zio->io_cmd = cmd;
1020         } else {
1021                 zio = zio_null(pio, spa, NULL, NULL, NULL, flags);
1022
1023                 for (c = 0; c < vd->vdev_children; c++)
1024                         zio_nowait(zio_ioctl(zio, spa, vd->vdev_child[c], cmd,
1025                             offset, size, done, private, priority, flags));
1026         }
1027
1028         return (zio);
1029 }
1030
1031 zio_t *
1032 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1033     void *data, int checksum, zio_done_func_t *done, void *private,
1034     zio_priority_t priority, enum zio_flag flags, boolean_t labels)
1035 {
1036         zio_t *zio;
1037
1038         ASSERT(vd->vdev_children == 0);
1039         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1040             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1041         ASSERT3U(offset + size, <=, vd->vdev_psize);
1042
1043         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
1044             ZIO_TYPE_READ, priority, flags | ZIO_FLAG_PHYSICAL, vd, offset,
1045             NULL, ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
1046
1047         zio->io_prop.zp_checksum = checksum;
1048
1049         return (zio);
1050 }
1051
1052 zio_t *
1053 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
1054     void *data, int checksum, zio_done_func_t *done, void *private,
1055     zio_priority_t priority, enum zio_flag flags, boolean_t labels)
1056 {
1057         zio_t *zio;
1058
1059         ASSERT(vd->vdev_children == 0);
1060         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
1061             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
1062         ASSERT3U(offset + size, <=, vd->vdev_psize);
1063
1064         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
1065             ZIO_TYPE_WRITE, priority, flags | ZIO_FLAG_PHYSICAL, vd, offset,
1066             NULL, ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
1067
1068         zio->io_prop.zp_checksum = checksum;
1069
1070         if (zio_checksum_table[checksum].ci_flags & ZCHECKSUM_FLAG_EMBEDDED) {
1071                 /*
1072                  * zec checksums are necessarily destructive -- they modify
1073                  * the end of the write buffer to hold the verifier/checksum.
1074                  * Therefore, we must make a local copy in case the data is
1075                  * being written to multiple places in parallel.
1076                  */
1077                 void *wbuf = zio_buf_alloc(size);
1078                 bcopy(data, wbuf, size);
1079                 zio_push_transform(zio, wbuf, size, size, NULL);
1080         }
1081
1082         return (zio);
1083 }
1084
1085 /*
1086  * Create a child I/O to do some work for us.
1087  */
1088 zio_t *
1089 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
1090     void *data, uint64_t size, int type, zio_priority_t priority,
1091     enum zio_flag flags, zio_done_func_t *done, void *private)
1092 {
1093         enum zio_stage pipeline = ZIO_VDEV_CHILD_PIPELINE;
1094         zio_t *zio;
1095
1096         ASSERT(vd->vdev_parent ==
1097             (pio->io_vd ? pio->io_vd : pio->io_spa->spa_root_vdev));
1098
1099         if (type == ZIO_TYPE_READ && bp != NULL) {
1100                 /*
1101                  * If we have the bp, then the child should perform the
1102                  * checksum and the parent need not.  This pushes error
1103                  * detection as close to the leaves as possible and
1104                  * eliminates redundant checksums in the interior nodes.
1105                  */
1106                 pipeline |= ZIO_STAGE_CHECKSUM_VERIFY;
1107                 pio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
1108         }
1109
1110         /* Not all IO types require vdev io done stage e.g. free */
1111         if (!(pio->io_pipeline & ZIO_STAGE_VDEV_IO_DONE))
1112                 pipeline &= ~ZIO_STAGE_VDEV_IO_DONE;
1113
1114         if (vd->vdev_children == 0)
1115                 offset += VDEV_LABEL_START_SIZE;
1116
1117         flags |= ZIO_VDEV_CHILD_FLAGS(pio) | ZIO_FLAG_DONT_PROPAGATE;
1118
1119         /*
1120          * If we've decided to do a repair, the write is not speculative --
1121          * even if the original read was.
1122          */
1123         if (flags & ZIO_FLAG_IO_REPAIR)
1124                 flags &= ~ZIO_FLAG_SPECULATIVE;
1125
1126         /*
1127          * If we're creating a child I/O that is not associated with a
1128          * top-level vdev, then the child zio is not an allocating I/O.
1129          * If this is a retried I/O then we ignore it since we will
1130          * have already processed the original allocating I/O.
1131          */
1132         if (flags & ZIO_FLAG_IO_ALLOCATING &&
1133             (vd != vd->vdev_top || (flags & ZIO_FLAG_IO_RETRY))) {
1134                 metaslab_class_t *mc = spa_normal_class(pio->io_spa);
1135
1136                 ASSERT(mc->mc_alloc_throttle_enabled);
1137                 ASSERT(type == ZIO_TYPE_WRITE);
1138                 ASSERT(priority == ZIO_PRIORITY_ASYNC_WRITE);
1139                 ASSERT(!(flags & ZIO_FLAG_IO_REPAIR));
1140                 ASSERT(!(pio->io_flags & ZIO_FLAG_IO_REWRITE) ||
1141                     pio->io_child_type == ZIO_CHILD_GANG);
1142
1143                 flags &= ~ZIO_FLAG_IO_ALLOCATING;
1144         }
1145
1146         zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size,
1147             done, private, type, priority, flags, vd, offset, &pio->io_bookmark,
1148             ZIO_STAGE_VDEV_IO_START >> 1, pipeline);
1149         ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
1150
1151         zio->io_physdone = pio->io_physdone;
1152         if (vd->vdev_ops->vdev_op_leaf && zio->io_logical != NULL)
1153                 zio->io_logical->io_phys_children++;
1154
1155         return (zio);
1156 }
1157
1158 zio_t *
1159 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, void *data, uint64_t size,
1160     int type, zio_priority_t priority, enum zio_flag flags,
1161     zio_done_func_t *done, void *private)
1162 {
1163         zio_t *zio;
1164
1165         ASSERT(vd->vdev_ops->vdev_op_leaf);
1166
1167         zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
1168             data, size, done, private, type, priority,
1169             flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY | ZIO_FLAG_DELEGATED,
1170             vd, offset, NULL,
1171             ZIO_STAGE_VDEV_IO_START >> 1, ZIO_VDEV_CHILD_PIPELINE);
1172
1173         return (zio);
1174 }
1175
1176 void
1177 zio_flush(zio_t *zio, vdev_t *vd)
1178 {
1179         zio_nowait(zio_ioctl(zio, zio->io_spa, vd, DKIOCFLUSHWRITECACHE, 0, 0,
1180             NULL, NULL, ZIO_PRIORITY_NOW,
1181             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY));
1182 }
1183
1184 zio_t *
1185 zio_trim(zio_t *zio, spa_t *spa, vdev_t *vd, uint64_t offset, uint64_t size)
1186 {
1187
1188         ASSERT(vd->vdev_ops->vdev_op_leaf);
1189
1190         return (zio_create(zio, spa, 0, NULL, NULL, size, NULL, NULL,
1191             ZIO_TYPE_FREE, ZIO_PRIORITY_TRIM, ZIO_FLAG_DONT_AGGREGATE |
1192             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY,
1193             vd, offset, NULL, ZIO_STAGE_OPEN, ZIO_FREE_PHYS_PIPELINE));
1194 }
1195
1196 void
1197 zio_shrink(zio_t *zio, uint64_t size)
1198 {
1199         ASSERT(zio->io_executor == NULL);
1200         ASSERT(zio->io_orig_size == zio->io_size);
1201         ASSERT(size <= zio->io_size);
1202
1203         /*
1204          * We don't shrink for raidz because of problems with the
1205          * reconstruction when reading back less than the block size.
1206          * Note, BP_IS_RAIDZ() assumes no compression.
1207          */
1208         ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
1209         if (!BP_IS_RAIDZ(zio->io_bp))
1210                 zio->io_orig_size = zio->io_size = size;
1211 }
1212
1213 /*
1214  * ==========================================================================
1215  * Prepare to read and write logical blocks
1216  * ==========================================================================
1217  */
1218
1219 static int
1220 zio_read_bp_init(zio_t *zio)
1221 {
1222         blkptr_t *bp = zio->io_bp;
1223
1224         if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF &&
1225             zio->io_child_type == ZIO_CHILD_LOGICAL &&
1226             !(zio->io_flags & ZIO_FLAG_RAW)) {
1227                 uint64_t psize =
1228                     BP_IS_EMBEDDED(bp) ? BPE_GET_PSIZE(bp) : BP_GET_PSIZE(bp);
1229                 void *cbuf = zio_buf_alloc(psize);
1230
1231                 zio_push_transform(zio, cbuf, psize, psize, zio_decompress);
1232         }
1233
1234         if (BP_IS_EMBEDDED(bp) && BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA) {
1235                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1236                 decode_embedded_bp_compressed(bp, zio->io_data);
1237         } else {
1238                 ASSERT(!BP_IS_EMBEDDED(bp));
1239         }
1240
1241         if (!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) && BP_GET_LEVEL(bp) == 0)
1242                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
1243
1244         if (BP_GET_TYPE(bp) == DMU_OT_DDT_ZAP)
1245                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
1246
1247         if (BP_GET_DEDUP(bp) && zio->io_child_type == ZIO_CHILD_LOGICAL)
1248                 zio->io_pipeline = ZIO_DDT_READ_PIPELINE;
1249
1250         return (ZIO_PIPELINE_CONTINUE);
1251 }
1252
1253 static int
1254 zio_write_bp_init(zio_t *zio)
1255 {
1256         if (!IO_IS_ALLOCATING(zio))
1257                 return (ZIO_PIPELINE_CONTINUE);
1258
1259         ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1260
1261         if (zio->io_bp_override) {
1262                 blkptr_t *bp = zio->io_bp;
1263                 zio_prop_t *zp = &zio->io_prop;
1264
1265                 ASSERT(bp->blk_birth != zio->io_txg);
1266                 ASSERT(BP_GET_DEDUP(zio->io_bp_override) == 0);
1267
1268                 *bp = *zio->io_bp_override;
1269                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1270
1271                 if (BP_IS_EMBEDDED(bp))
1272                         return (ZIO_PIPELINE_CONTINUE);
1273
1274                 /*
1275                  * If we've been overridden and nopwrite is set then
1276                  * set the flag accordingly to indicate that a nopwrite
1277                  * has already occurred.
1278                  */
1279                 if (!BP_IS_HOLE(bp) && zp->zp_nopwrite) {
1280                         ASSERT(!zp->zp_dedup);
1281                         ASSERT3U(BP_GET_CHECKSUM(bp), ==, zp->zp_checksum);
1282                         zio->io_flags |= ZIO_FLAG_NOPWRITE;
1283                         return (ZIO_PIPELINE_CONTINUE);
1284                 }
1285
1286                 ASSERT(!zp->zp_nopwrite);
1287
1288                 if (BP_IS_HOLE(bp) || !zp->zp_dedup)
1289                         return (ZIO_PIPELINE_CONTINUE);
1290
1291                 ASSERT((zio_checksum_table[zp->zp_checksum].ci_flags &
1292                     ZCHECKSUM_FLAG_DEDUP) || zp->zp_dedup_verify);
1293
1294                 if (BP_GET_CHECKSUM(bp) == zp->zp_checksum) {
1295                         BP_SET_DEDUP(bp, 1);
1296                         zio->io_pipeline |= ZIO_STAGE_DDT_WRITE;
1297                         return (ZIO_PIPELINE_CONTINUE);
1298                 }
1299
1300                 /*
1301                  * We were unable to handle this as an override bp, treat
1302                  * it as a regular write I/O.
1303                  */
1304                 zio->io_bp_override = NULL;
1305                 *bp = zio->io_bp_orig;
1306                 zio->io_pipeline = zio->io_orig_pipeline;
1307         }
1308
1309         return (ZIO_PIPELINE_CONTINUE);
1310 }
1311
1312 static int
1313 zio_write_compress(zio_t *zio)
1314 {
1315         spa_t *spa = zio->io_spa;
1316         zio_prop_t *zp = &zio->io_prop;
1317         enum zio_compress compress = zp->zp_compress;
1318         blkptr_t *bp = zio->io_bp;
1319         uint64_t lsize = zio->io_size;
1320         uint64_t psize = lsize;
1321         int pass = 1;
1322
1323         /*
1324          * If our children haven't all reached the ready stage,
1325          * wait for them and then repeat this pipeline stage.
1326          */
1327         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
1328             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_READY))
1329                 return (ZIO_PIPELINE_STOP);
1330
1331         if (!IO_IS_ALLOCATING(zio))
1332                 return (ZIO_PIPELINE_CONTINUE);
1333
1334         if (zio->io_children_ready != NULL) {
1335                 /*
1336                  * Now that all our children are ready, run the callback
1337                  * associated with this zio in case it wants to modify the
1338                  * data to be written.
1339                  */
1340                 ASSERT3U(zp->zp_level, >, 0);
1341                 zio->io_children_ready(zio);
1342         }
1343
1344         ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1345         ASSERT(zio->io_bp_override == NULL);
1346
1347         if (!BP_IS_HOLE(bp) && bp->blk_birth == zio->io_txg) {
1348                 /*
1349                  * We're rewriting an existing block, which means we're
1350                  * working on behalf of spa_sync().  For spa_sync() to
1351                  * converge, it must eventually be the case that we don't
1352                  * have to allocate new blocks.  But compression changes
1353                  * the blocksize, which forces a reallocate, and makes
1354                  * convergence take longer.  Therefore, after the first
1355                  * few passes, stop compressing to ensure convergence.
1356                  */
1357                 pass = spa_sync_pass(spa);
1358
1359                 ASSERT(zio->io_txg == spa_syncing_txg(spa));
1360                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1361                 ASSERT(!BP_GET_DEDUP(bp));
1362
1363                 if (pass >= zfs_sync_pass_dont_compress)
1364                         compress = ZIO_COMPRESS_OFF;
1365
1366                 /* Make sure someone doesn't change their mind on overwrites */
1367                 ASSERT(BP_IS_EMBEDDED(bp) || MIN(zp->zp_copies + BP_IS_GANG(bp),
1368                     spa_max_replication(spa)) == BP_GET_NDVAS(bp));
1369         }
1370
1371         if (compress != ZIO_COMPRESS_OFF) {
1372                 void *cbuf = zio_buf_alloc(lsize);
1373                 psize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1374                 if (psize == 0 || psize == lsize) {
1375                         compress = ZIO_COMPRESS_OFF;
1376                         zio_buf_free(cbuf, lsize);
1377                 } else if (!zp->zp_dedup && psize <= BPE_PAYLOAD_SIZE &&
1378                     zp->zp_level == 0 && !DMU_OT_HAS_FILL(zp->zp_type) &&
1379                     spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA)) {
1380                         encode_embedded_bp_compressed(bp,
1381                             cbuf, compress, lsize, psize);
1382                         BPE_SET_ETYPE(bp, BP_EMBEDDED_TYPE_DATA);
1383                         BP_SET_TYPE(bp, zio->io_prop.zp_type);
1384                         BP_SET_LEVEL(bp, zio->io_prop.zp_level);
1385                         zio_buf_free(cbuf, lsize);
1386                         bp->blk_birth = zio->io_txg;
1387                         zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1388                         ASSERT(spa_feature_is_active(spa,
1389                             SPA_FEATURE_EMBEDDED_DATA));
1390                         return (ZIO_PIPELINE_CONTINUE);
1391                 } else {
1392                         /*
1393                          * Round up compressed size up to the ashift
1394                          * of the smallest-ashift device, and zero the tail.
1395                          * This ensures that the compressed size of the BP
1396                          * (and thus compressratio property) are correct,
1397                          * in that we charge for the padding used to fill out
1398                          * the last sector.
1399                          */
1400                         ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
1401                         size_t rounded = (size_t)P2ROUNDUP(psize,
1402                             1ULL << spa->spa_min_ashift);
1403                         if (rounded >= lsize) {
1404                                 compress = ZIO_COMPRESS_OFF;
1405                                 zio_buf_free(cbuf, lsize);
1406                                 psize = lsize;
1407                         } else {
1408                                 bzero((char *)cbuf + psize, rounded - psize);
1409                                 psize = rounded;
1410                                 zio_push_transform(zio, cbuf,
1411                                     psize, lsize, NULL);
1412                         }
1413                 }
1414
1415                 /*
1416                  * We were unable to handle this as an override bp, treat
1417                  * it as a regular write I/O.
1418                  */
1419                 zio->io_bp_override = NULL;
1420                 *bp = zio->io_bp_orig;
1421                 zio->io_pipeline = zio->io_orig_pipeline;
1422         }
1423
1424         /*
1425          * The final pass of spa_sync() must be all rewrites, but the first
1426          * few passes offer a trade-off: allocating blocks defers convergence,
1427          * but newly allocated blocks are sequential, so they can be written
1428          * to disk faster.  Therefore, we allow the first few passes of
1429          * spa_sync() to allocate new blocks, but force rewrites after that.
1430          * There should only be a handful of blocks after pass 1 in any case.
1431          */
1432         if (!BP_IS_HOLE(bp) && bp->blk_birth == zio->io_txg &&
1433             BP_GET_PSIZE(bp) == psize &&
1434             pass >= zfs_sync_pass_rewrite) {
1435                 ASSERT(psize != 0);
1436                 enum zio_stage gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
1437                 zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
1438                 zio->io_flags |= ZIO_FLAG_IO_REWRITE;
1439         } else {
1440                 BP_ZERO(bp);
1441                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
1442         }
1443
1444         if (psize == 0) {
1445                 if (zio->io_bp_orig.blk_birth != 0 &&
1446                     spa_feature_is_active(spa, SPA_FEATURE_HOLE_BIRTH)) {
1447                         BP_SET_LSIZE(bp, lsize);
1448                         BP_SET_TYPE(bp, zp->zp_type);
1449                         BP_SET_LEVEL(bp, zp->zp_level);
1450                         BP_SET_BIRTH(bp, zio->io_txg, 0);
1451                 }
1452                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1453         } else {
1454                 ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
1455                 BP_SET_LSIZE(bp, lsize);
1456                 BP_SET_TYPE(bp, zp->zp_type);
1457                 BP_SET_LEVEL(bp, zp->zp_level);
1458                 BP_SET_PSIZE(bp, psize);
1459                 BP_SET_COMPRESS(bp, compress);
1460                 BP_SET_CHECKSUM(bp, zp->zp_checksum);
1461                 BP_SET_DEDUP(bp, zp->zp_dedup);
1462                 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
1463                 if (zp->zp_dedup) {
1464                         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1465                         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1466                         zio->io_pipeline = ZIO_DDT_WRITE_PIPELINE;
1467                 }
1468                 if (zp->zp_nopwrite) {
1469                         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1470                         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1471                         zio->io_pipeline |= ZIO_STAGE_NOP_WRITE;
1472                 }
1473         }
1474         return (ZIO_PIPELINE_CONTINUE);
1475 }
1476
1477 static int
1478 zio_free_bp_init(zio_t *zio)
1479 {
1480         blkptr_t *bp = zio->io_bp;
1481
1482         if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
1483                 if (BP_GET_DEDUP(bp))
1484                         zio->io_pipeline = ZIO_DDT_FREE_PIPELINE;
1485         }
1486
1487         return (ZIO_PIPELINE_CONTINUE);
1488 }
1489
1490 /*
1491  * ==========================================================================
1492  * Execute the I/O pipeline
1493  * ==========================================================================
1494  */
1495
1496 static void
1497 zio_taskq_dispatch(zio_t *zio, zio_taskq_type_t q, boolean_t cutinline)
1498 {
1499         spa_t *spa = zio->io_spa;
1500         zio_type_t t = zio->io_type;
1501         int flags = (cutinline ? TQ_FRONT : 0);
1502
1503         ASSERT(q == ZIO_TASKQ_ISSUE || q == ZIO_TASKQ_INTERRUPT);
1504
1505         /*
1506          * If we're a config writer or a probe, the normal issue and
1507          * interrupt threads may all be blocked waiting for the config lock.
1508          * In this case, select the otherwise-unused taskq for ZIO_TYPE_NULL.
1509          */
1510         if (zio->io_flags & (ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_PROBE))
1511                 t = ZIO_TYPE_NULL;
1512
1513         /*
1514          * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
1515          */
1516         if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
1517                 t = ZIO_TYPE_NULL;
1518
1519         /*
1520          * If this is a high priority I/O, then use the high priority taskq if
1521          * available.
1522          */
1523         if (zio->io_priority == ZIO_PRIORITY_NOW &&
1524             spa->spa_zio_taskq[t][q + 1].stqs_count != 0)
1525                 q++;
1526
1527         ASSERT3U(q, <, ZIO_TASKQ_TYPES);
1528
1529         /*
1530          * NB: We are assuming that the zio can only be dispatched
1531          * to a single taskq at a time.  It would be a grievous error
1532          * to dispatch the zio to another taskq at the same time.
1533          */
1534 #if defined(illumos) || !defined(_KERNEL)
1535         ASSERT(zio->io_tqent.tqent_next == NULL);
1536 #else
1537         ASSERT(zio->io_tqent.tqent_task.ta_pending == 0);
1538 #endif
1539         spa_taskq_dispatch_ent(spa, t, q, (task_func_t *)zio_execute, zio,
1540             flags, &zio->io_tqent);
1541 }
1542
1543 static boolean_t
1544 zio_taskq_member(zio_t *zio, zio_taskq_type_t q)
1545 {
1546         kthread_t *executor = zio->io_executor;
1547         spa_t *spa = zio->io_spa;
1548
1549         for (zio_type_t t = 0; t < ZIO_TYPES; t++) {
1550                 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1551                 uint_t i;
1552                 for (i = 0; i < tqs->stqs_count; i++) {
1553                         if (taskq_member(tqs->stqs_taskq[i], executor))
1554                                 return (B_TRUE);
1555                 }
1556         }
1557
1558         return (B_FALSE);
1559 }
1560
1561 static int
1562 zio_issue_async(zio_t *zio)
1563 {
1564         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
1565
1566         return (ZIO_PIPELINE_STOP);
1567 }
1568
1569 void
1570 zio_interrupt(zio_t *zio)
1571 {
1572         zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT, B_FALSE);
1573 }
1574
1575 void
1576 zio_delay_interrupt(zio_t *zio)
1577 {
1578         /*
1579          * The timeout_generic() function isn't defined in userspace, so
1580          * rather than trying to implement the function, the zio delay
1581          * functionality has been disabled for userspace builds.
1582          */
1583
1584 #ifdef _KERNEL
1585         /*
1586          * If io_target_timestamp is zero, then no delay has been registered
1587          * for this IO, thus jump to the end of this function and "skip" the
1588          * delay; issuing it directly to the zio layer.
1589          */
1590         if (zio->io_target_timestamp != 0) {
1591                 hrtime_t now = gethrtime();
1592
1593                 if (now >= zio->io_target_timestamp) {
1594                         /*
1595                          * This IO has already taken longer than the target
1596                          * delay to complete, so we don't want to delay it
1597                          * any longer; we "miss" the delay and issue it
1598                          * directly to the zio layer. This is likely due to
1599                          * the target latency being set to a value less than
1600                          * the underlying hardware can satisfy (e.g. delay
1601                          * set to 1ms, but the disks take 10ms to complete an
1602                          * IO request).
1603                          */
1604
1605                         DTRACE_PROBE2(zio__delay__miss, zio_t *, zio,
1606                             hrtime_t, now);
1607
1608                         zio_interrupt(zio);
1609                 } else {
1610                         hrtime_t diff = zio->io_target_timestamp - now;
1611
1612                         DTRACE_PROBE3(zio__delay__hit, zio_t *, zio,
1613                             hrtime_t, now, hrtime_t, diff);
1614
1615                         (void) timeout_generic(CALLOUT_NORMAL,
1616                             (void (*)(void *))zio_interrupt, zio, diff, 1, 0);
1617                 }
1618
1619                 return;
1620         }
1621 #endif
1622
1623         DTRACE_PROBE1(zio__delay__skip, zio_t *, zio);
1624         zio_interrupt(zio);
1625 }
1626
1627 /*
1628  * Execute the I/O pipeline until one of the following occurs:
1629  *
1630  *      (1) the I/O completes
1631  *      (2) the pipeline stalls waiting for dependent child I/Os
1632  *      (3) the I/O issues, so we're waiting for an I/O completion interrupt
1633  *      (4) the I/O is delegated by vdev-level caching or aggregation
1634  *      (5) the I/O is deferred due to vdev-level queueing
1635  *      (6) the I/O is handed off to another thread.
1636  *
1637  * In all cases, the pipeline stops whenever there's no CPU work; it never
1638  * burns a thread in cv_wait().
1639  *
1640  * There's no locking on io_stage because there's no legitimate way
1641  * for multiple threads to be attempting to process the same I/O.
1642  */
1643 static zio_pipe_stage_t *zio_pipeline[];
1644
1645 void
1646 zio_execute(zio_t *zio)
1647 {
1648         zio->io_executor = curthread;
1649
1650         ASSERT3U(zio->io_queued_timestamp, >, 0);
1651
1652         while (zio->io_stage < ZIO_STAGE_DONE) {
1653                 enum zio_stage pipeline = zio->io_pipeline;
1654                 enum zio_stage stage = zio->io_stage;
1655                 int rv;
1656
1657                 ASSERT(!MUTEX_HELD(&zio->io_lock));
1658                 ASSERT(ISP2(stage));
1659                 ASSERT(zio->io_stall == NULL);
1660
1661                 do {
1662                         stage <<= 1;
1663                 } while ((stage & pipeline) == 0);
1664
1665                 ASSERT(stage <= ZIO_STAGE_DONE);
1666
1667                 /*
1668                  * If we are in interrupt context and this pipeline stage
1669                  * will grab a config lock that is held across I/O,
1670                  * or may wait for an I/O that needs an interrupt thread
1671                  * to complete, issue async to avoid deadlock.
1672                  *
1673                  * For VDEV_IO_START, we cut in line so that the io will
1674                  * be sent to disk promptly.
1675                  */
1676                 if ((stage & ZIO_BLOCKING_STAGES) && zio->io_vd == NULL &&
1677                     zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
1678                         boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
1679                             zio_requeue_io_start_cut_in_line : B_FALSE;
1680                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
1681                         return;
1682                 }
1683
1684                 zio->io_stage = stage;
1685                 zio->io_pipeline_trace |= zio->io_stage;
1686                 rv = zio_pipeline[highbit64(stage) - 1](zio);
1687
1688                 if (rv == ZIO_PIPELINE_STOP)
1689                         return;
1690
1691                 ASSERT(rv == ZIO_PIPELINE_CONTINUE);
1692         }
1693 }
1694
1695 /*
1696  * ==========================================================================
1697  * Initiate I/O, either sync or async
1698  * ==========================================================================
1699  */
1700 int
1701 zio_wait(zio_t *zio)
1702 {
1703         int error;
1704
1705         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
1706         ASSERT(zio->io_executor == NULL);
1707
1708         zio->io_waiter = curthread;
1709         ASSERT0(zio->io_queued_timestamp);
1710         zio->io_queued_timestamp = gethrtime();
1711
1712         zio_execute(zio);
1713
1714         mutex_enter(&zio->io_lock);
1715         while (zio->io_executor != NULL)
1716                 cv_wait(&zio->io_cv, &zio->io_lock);
1717         mutex_exit(&zio->io_lock);
1718
1719         error = zio->io_error;
1720         zio_destroy(zio);
1721
1722         return (error);
1723 }
1724
1725 void
1726 zio_nowait(zio_t *zio)
1727 {
1728         ASSERT(zio->io_executor == NULL);
1729
1730         if (zio->io_child_type == ZIO_CHILD_LOGICAL &&
1731             zio_unique_parent(zio) == NULL) {
1732                 /*
1733                  * This is a logical async I/O with no parent to wait for it.
1734                  * We add it to the spa_async_root_zio "Godfather" I/O which
1735                  * will ensure they complete prior to unloading the pool.
1736                  */
1737                 spa_t *spa = zio->io_spa;
1738
1739                 zio_add_child(spa->spa_async_zio_root[CPU_SEQID], zio);
1740         }
1741
1742         ASSERT0(zio->io_queued_timestamp);
1743         zio->io_queued_timestamp = gethrtime();
1744         zio_execute(zio);
1745 }
1746
1747 /*
1748  * ==========================================================================
1749  * Reexecute or suspend/resume failed I/O
1750  * ==========================================================================
1751  */
1752
1753 static void
1754 zio_reexecute(zio_t *pio)
1755 {
1756         zio_t *cio, *cio_next;
1757
1758         ASSERT(pio->io_child_type == ZIO_CHILD_LOGICAL);
1759         ASSERT(pio->io_orig_stage == ZIO_STAGE_OPEN);
1760         ASSERT(pio->io_gang_leader == NULL);
1761         ASSERT(pio->io_gang_tree == NULL);
1762
1763         pio->io_flags = pio->io_orig_flags;
1764         pio->io_stage = pio->io_orig_stage;
1765         pio->io_pipeline = pio->io_orig_pipeline;
1766         pio->io_reexecute = 0;
1767         pio->io_flags |= ZIO_FLAG_REEXECUTED;
1768         pio->io_pipeline_trace = 0;
1769         pio->io_error = 0;
1770         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1771                 pio->io_state[w] = 0;
1772         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
1773                 pio->io_child_error[c] = 0;
1774
1775         if (IO_IS_ALLOCATING(pio))
1776                 BP_ZERO(pio->io_bp);
1777
1778         /*
1779          * As we reexecute pio's children, new children could be created.
1780          * New children go to the head of pio's io_child_list, however,
1781          * so we will (correctly) not reexecute them.  The key is that
1782          * the remainder of pio's io_child_list, from 'cio_next' onward,
1783          * cannot be affected by any side effects of reexecuting 'cio'.
1784          */
1785         zio_link_t *zl = NULL;
1786         for (cio = zio_walk_children(pio, &zl); cio != NULL; cio = cio_next) {
1787                 cio_next = zio_walk_children(pio, &zl);
1788                 mutex_enter(&pio->io_lock);
1789                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1790                         pio->io_children[cio->io_child_type][w]++;
1791                 mutex_exit(&pio->io_lock);
1792                 zio_reexecute(cio);
1793         }
1794
1795         /*
1796          * Now that all children have been reexecuted, execute the parent.
1797          * We don't reexecute "The Godfather" I/O here as it's the
1798          * responsibility of the caller to wait on him.
1799          */
1800         if (!(pio->io_flags & ZIO_FLAG_GODFATHER)) {
1801                 pio->io_queued_timestamp = gethrtime();
1802                 zio_execute(pio);
1803         }
1804 }
1805
1806 void
1807 zio_suspend(spa_t *spa, zio_t *zio)
1808 {
1809         if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
1810                 fm_panic("Pool '%s' has encountered an uncorrectable I/O "
1811                     "failure and the failure mode property for this pool "
1812                     "is set to panic.", spa_name(spa));
1813
1814         zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL, NULL, 0, 0);
1815
1816         mutex_enter(&spa->spa_suspend_lock);
1817
1818         if (spa->spa_suspend_zio_root == NULL)
1819                 spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL,
1820                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
1821                     ZIO_FLAG_GODFATHER);
1822
1823         spa->spa_suspended = B_TRUE;
1824
1825         if (zio != NULL) {
1826                 ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
1827                 ASSERT(zio != spa->spa_suspend_zio_root);
1828                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1829                 ASSERT(zio_unique_parent(zio) == NULL);
1830                 ASSERT(zio->io_stage == ZIO_STAGE_DONE);
1831                 zio_add_child(spa->spa_suspend_zio_root, zio);
1832         }
1833
1834         mutex_exit(&spa->spa_suspend_lock);
1835 }
1836
1837 int
1838 zio_resume(spa_t *spa)
1839 {
1840         zio_t *pio;
1841
1842         /*
1843          * Reexecute all previously suspended i/o.
1844          */
1845         mutex_enter(&spa->spa_suspend_lock);
1846         spa->spa_suspended = B_FALSE;
1847         cv_broadcast(&spa->spa_suspend_cv);
1848         pio = spa->spa_suspend_zio_root;
1849         spa->spa_suspend_zio_root = NULL;
1850         mutex_exit(&spa->spa_suspend_lock);
1851
1852         if (pio == NULL)
1853                 return (0);
1854
1855         zio_reexecute(pio);
1856         return (zio_wait(pio));
1857 }
1858
1859 void
1860 zio_resume_wait(spa_t *spa)
1861 {
1862         mutex_enter(&spa->spa_suspend_lock);
1863         while (spa_suspended(spa))
1864                 cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
1865         mutex_exit(&spa->spa_suspend_lock);
1866 }
1867
1868 /*
1869  * ==========================================================================
1870  * Gang blocks.
1871  *
1872  * A gang block is a collection of small blocks that looks to the DMU
1873  * like one large block.  When zio_dva_allocate() cannot find a block
1874  * of the requested size, due to either severe fragmentation or the pool
1875  * being nearly full, it calls zio_write_gang_block() to construct the
1876  * block from smaller fragments.
1877  *
1878  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
1879  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
1880  * an indirect block: it's an array of block pointers.  It consumes
1881  * only one sector and hence is allocatable regardless of fragmentation.
1882  * The gang header's bps point to its gang members, which hold the data.
1883  *
1884  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
1885  * as the verifier to ensure uniqueness of the SHA256 checksum.
1886  * Critically, the gang block bp's blk_cksum is the checksum of the data,
1887  * not the gang header.  This ensures that data block signatures (needed for
1888  * deduplication) are independent of how the block is physically stored.
1889  *
1890  * Gang blocks can be nested: a gang member may itself be a gang block.
1891  * Thus every gang block is a tree in which root and all interior nodes are
1892  * gang headers, and the leaves are normal blocks that contain user data.
1893  * The root of the gang tree is called the gang leader.
1894  *
1895  * To perform any operation (read, rewrite, free, claim) on a gang block,
1896  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
1897  * in the io_gang_tree field of the original logical i/o by recursively
1898  * reading the gang leader and all gang headers below it.  This yields
1899  * an in-core tree containing the contents of every gang header and the
1900  * bps for every constituent of the gang block.
1901  *
1902  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
1903  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
1904  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
1905  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
1906  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
1907  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
1908  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
1909  * of the gang header plus zio_checksum_compute() of the data to update the
1910  * gang header's blk_cksum as described above.
1911  *
1912  * The two-phase assemble/issue model solves the problem of partial failure --
1913  * what if you'd freed part of a gang block but then couldn't read the
1914  * gang header for another part?  Assembling the entire gang tree first
1915  * ensures that all the necessary gang header I/O has succeeded before
1916  * starting the actual work of free, claim, or write.  Once the gang tree
1917  * is assembled, free and claim are in-memory operations that cannot fail.
1918  *
1919  * In the event that a gang write fails, zio_dva_unallocate() walks the
1920  * gang tree to immediately free (i.e. insert back into the space map)
1921  * everything we've allocated.  This ensures that we don't get ENOSPC
1922  * errors during repeated suspend/resume cycles due to a flaky device.
1923  *
1924  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
1925  * the gang tree, we won't modify the block, so we can safely defer the free
1926  * (knowing that the block is still intact).  If we *can* assemble the gang
1927  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
1928  * each constituent bp and we can allocate a new block on the next sync pass.
1929  *
1930  * In all cases, the gang tree allows complete recovery from partial failure.
1931  * ==========================================================================
1932  */
1933
1934 static zio_t *
1935 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1936 {
1937         if (gn != NULL)
1938                 return (pio);
1939
1940         return (zio_read(pio, pio->io_spa, bp, data, BP_GET_PSIZE(bp),
1941             NULL, NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1942             &pio->io_bookmark));
1943 }
1944
1945 zio_t *
1946 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1947 {
1948         zio_t *zio;
1949
1950         if (gn != NULL) {
1951                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1952                     gn->gn_gbh, SPA_GANGBLOCKSIZE, NULL, NULL, pio->io_priority,
1953                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1954                 /*
1955                  * As we rewrite each gang header, the pipeline will compute
1956                  * a new gang block header checksum for it; but no one will
1957                  * compute a new data checksum, so we do that here.  The one
1958                  * exception is the gang leader: the pipeline already computed
1959                  * its data checksum because that stage precedes gang assembly.
1960                  * (Presently, nothing actually uses interior data checksums;
1961                  * this is just good hygiene.)
1962                  */
1963                 if (gn != pio->io_gang_leader->io_gang_tree) {
1964                         zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
1965                             data, BP_GET_PSIZE(bp));
1966                 }
1967                 /*
1968                  * If we are here to damage data for testing purposes,
1969                  * leave the GBH alone so that we can detect the damage.
1970                  */
1971                 if (pio->io_gang_leader->io_flags & ZIO_FLAG_INDUCE_DAMAGE)
1972                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
1973         } else {
1974                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1975                     data, BP_GET_PSIZE(bp), NULL, NULL, pio->io_priority,
1976                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1977         }
1978
1979         return (zio);
1980 }
1981
1982 /* ARGSUSED */
1983 zio_t *
1984 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1985 {
1986         return (zio_free_sync(pio, pio->io_spa, pio->io_txg, bp,
1987             BP_IS_GANG(bp) ? SPA_GANGBLOCKSIZE : BP_GET_PSIZE(bp),
1988             ZIO_GANG_CHILD_FLAGS(pio)));
1989 }
1990
1991 /* ARGSUSED */
1992 zio_t *
1993 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1994 {
1995         return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
1996             NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
1997 }
1998
1999 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
2000         NULL,
2001         zio_read_gang,
2002         zio_rewrite_gang,
2003         zio_free_gang,
2004         zio_claim_gang,
2005         NULL
2006 };
2007
2008 static void zio_gang_tree_assemble_done(zio_t *zio);
2009
2010 static zio_gang_node_t *
2011 zio_gang_node_alloc(zio_gang_node_t **gnpp)
2012 {
2013         zio_gang_node_t *gn;
2014
2015         ASSERT(*gnpp == NULL);
2016
2017         gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
2018         gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
2019         *gnpp = gn;
2020
2021         return (gn);
2022 }
2023
2024 static void
2025 zio_gang_node_free(zio_gang_node_t **gnpp)
2026 {
2027         zio_gang_node_t *gn = *gnpp;
2028
2029         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2030                 ASSERT(gn->gn_child[g] == NULL);
2031
2032         zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
2033         kmem_free(gn, sizeof (*gn));
2034         *gnpp = NULL;
2035 }
2036
2037 static void
2038 zio_gang_tree_free(zio_gang_node_t **gnpp)
2039 {
2040         zio_gang_node_t *gn = *gnpp;
2041
2042         if (gn == NULL)
2043                 return;
2044
2045         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
2046                 zio_gang_tree_free(&gn->gn_child[g]);
2047
2048         zio_gang_node_free(gnpp);
2049 }
2050
2051 static void
2052 zio_gang_tree_assemble(zio_t *gio, blkptr_t *bp, zio_gang_node_t **gnpp)
2053 {
2054         zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
2055
2056         ASSERT(gio->io_gang_leader == gio);
2057         ASSERT(BP_IS_GANG(bp));
2058
2059         zio_nowait(zio_read(gio, gio->io_spa, bp, gn->gn_gbh,
2060             SPA_GANGBLOCKSIZE, zio_gang_tree_assemble_done, gn,
2061             gio->io_priority, ZIO_GANG_CHILD_FLAGS(gio), &gio->io_bookmark));
2062 }
2063
2064 static void
2065 zio_gang_tree_assemble_done(zio_t *zio)
2066 {
2067         zio_t *gio = zio->io_gang_leader;
2068         zio_gang_node_t *gn = zio->io_private;
2069         blkptr_t *bp = zio->io_bp;
2070
2071         ASSERT(gio == zio_unique_parent(zio));
2072         ASSERT(zio->io_child_count == 0);
2073
2074         if (zio->io_error)
2075                 return;
2076
2077         if (BP_SHOULD_BYTESWAP(bp))
2078                 byteswap_uint64_array(zio->io_data, zio->io_size);
2079
2080         ASSERT(zio->io_data == gn->gn_gbh);
2081         ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
2082         ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
2083
2084         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2085                 blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
2086                 if (!BP_IS_GANG(gbp))
2087                         continue;
2088                 zio_gang_tree_assemble(gio, gbp, &gn->gn_child[g]);
2089         }
2090 }
2091
2092 static void
2093 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, void *data)
2094 {
2095         zio_t *gio = pio->io_gang_leader;
2096         zio_t *zio;
2097
2098         ASSERT(BP_IS_GANG(bp) == !!gn);
2099         ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(gio->io_bp));
2100         ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == gio->io_gang_tree);
2101
2102         /*
2103          * If you're a gang header, your data is in gn->gn_gbh.
2104          * If you're a gang member, your data is in 'data' and gn == NULL.
2105          */
2106         zio = zio_gang_issue_func[gio->io_type](pio, bp, gn, data);
2107
2108         if (gn != NULL) {
2109                 ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
2110
2111                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2112                         blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
2113                         if (BP_IS_HOLE(gbp))
2114                                 continue;
2115                         zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data);
2116                         data = (char *)data + BP_GET_PSIZE(gbp);
2117                 }
2118         }
2119
2120         if (gn == gio->io_gang_tree && gio->io_data != NULL)
2121                 ASSERT3P((char *)gio->io_data + gio->io_size, ==, data);
2122
2123         if (zio != pio)
2124                 zio_nowait(zio);
2125 }
2126
2127 static int
2128 zio_gang_assemble(zio_t *zio)
2129 {
2130         blkptr_t *bp = zio->io_bp;
2131
2132         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == NULL);
2133         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2134
2135         zio->io_gang_leader = zio;
2136
2137         zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
2138
2139         return (ZIO_PIPELINE_CONTINUE);
2140 }
2141
2142 static int
2143 zio_gang_issue(zio_t *zio)
2144 {
2145         blkptr_t *bp = zio->io_bp;
2146
2147         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE))
2148                 return (ZIO_PIPELINE_STOP);
2149
2150         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == zio);
2151         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2152
2153         if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
2154                 zio_gang_tree_issue(zio, zio->io_gang_tree, bp, zio->io_data);
2155         else
2156                 zio_gang_tree_free(&zio->io_gang_tree);
2157
2158         zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2159
2160         return (ZIO_PIPELINE_CONTINUE);
2161 }
2162
2163 static void
2164 zio_write_gang_member_ready(zio_t *zio)
2165 {
2166         zio_t *pio = zio_unique_parent(zio);
2167         zio_t *gio = zio->io_gang_leader;
2168         dva_t *cdva = zio->io_bp->blk_dva;
2169         dva_t *pdva = pio->io_bp->blk_dva;
2170         uint64_t asize;
2171
2172         if (BP_IS_HOLE(zio->io_bp))
2173                 return;
2174
2175         ASSERT(BP_IS_HOLE(&zio->io_bp_orig));
2176
2177         ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
2178         ASSERT3U(zio->io_prop.zp_copies, ==, gio->io_prop.zp_copies);
2179         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(zio->io_bp));
2180         ASSERT3U(pio->io_prop.zp_copies, <=, BP_GET_NDVAS(pio->io_bp));
2181         ASSERT3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
2182
2183         mutex_enter(&pio->io_lock);
2184         for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
2185                 ASSERT(DVA_GET_GANG(&pdva[d]));
2186                 asize = DVA_GET_ASIZE(&pdva[d]);
2187                 asize += DVA_GET_ASIZE(&cdva[d]);
2188                 DVA_SET_ASIZE(&pdva[d], asize);
2189         }
2190         mutex_exit(&pio->io_lock);
2191 }
2192
2193 static int
2194 zio_write_gang_block(zio_t *pio)
2195 {
2196         spa_t *spa = pio->io_spa;
2197         metaslab_class_t *mc = spa_normal_class(spa);
2198         blkptr_t *bp = pio->io_bp;
2199         zio_t *gio = pio->io_gang_leader;
2200         zio_t *zio;
2201         zio_gang_node_t *gn, **gnpp;
2202         zio_gbh_phys_t *gbh;
2203         uint64_t txg = pio->io_txg;
2204         uint64_t resid = pio->io_size;
2205         uint64_t lsize;
2206         int copies = gio->io_prop.zp_copies;
2207         int gbh_copies = MIN(copies + 1, spa_max_replication(spa));
2208         zio_prop_t zp;
2209         int error;
2210
2211         int flags = METASLAB_HINTBP_FAVOR | METASLAB_GANG_HEADER;
2212         if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
2213                 ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
2214                 ASSERT(!(pio->io_flags & ZIO_FLAG_NODATA));
2215
2216                 flags |= METASLAB_ASYNC_ALLOC;
2217                 VERIFY(refcount_held(&mc->mc_alloc_slots, pio));
2218
2219                 /*
2220                  * The logical zio has already placed a reservation for
2221                  * 'copies' allocation slots but gang blocks may require
2222                  * additional copies. These additional copies
2223                  * (i.e. gbh_copies - copies) are guaranteed to succeed
2224                  * since metaslab_class_throttle_reserve() always allows
2225                  * additional reservations for gang blocks.
2226                  */
2227                 VERIFY(metaslab_class_throttle_reserve(mc, gbh_copies - copies,
2228                     pio, flags));
2229         }
2230
2231         error = metaslab_alloc(spa, mc, SPA_GANGBLOCKSIZE,
2232             bp, gbh_copies, txg, pio == gio ? NULL : gio->io_bp, flags, pio);
2233         if (error) {
2234                 if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
2235                         ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
2236                         ASSERT(!(pio->io_flags & ZIO_FLAG_NODATA));
2237
2238                         /*
2239                          * If we failed to allocate the gang block header then
2240                          * we remove any additional allocation reservations that
2241                          * we placed here. The original reservation will
2242                          * be removed when the logical I/O goes to the ready
2243                          * stage.
2244                          */
2245                         metaslab_class_throttle_unreserve(mc,
2246                             gbh_copies - copies, pio);
2247                 }
2248                 pio->io_error = error;
2249                 return (ZIO_PIPELINE_CONTINUE);
2250         }
2251
2252         if (pio == gio) {
2253                 gnpp = &gio->io_gang_tree;
2254         } else {
2255                 gnpp = pio->io_private;
2256                 ASSERT(pio->io_ready == zio_write_gang_member_ready);
2257         }
2258
2259         gn = zio_gang_node_alloc(gnpp);
2260         gbh = gn->gn_gbh;
2261         bzero(gbh, SPA_GANGBLOCKSIZE);
2262
2263         /*
2264          * Create the gang header.
2265          */
2266         zio = zio_rewrite(pio, spa, txg, bp, gbh, SPA_GANGBLOCKSIZE, NULL, NULL,
2267             pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
2268
2269         /*
2270          * Create and nowait the gang children.
2271          */
2272         for (int g = 0; resid != 0; resid -= lsize, g++) {
2273                 lsize = P2ROUNDUP(resid / (SPA_GBH_NBLKPTRS - g),
2274                     SPA_MINBLOCKSIZE);
2275                 ASSERT(lsize >= SPA_MINBLOCKSIZE && lsize <= resid);
2276
2277                 zp.zp_checksum = gio->io_prop.zp_checksum;
2278                 zp.zp_compress = ZIO_COMPRESS_OFF;
2279                 zp.zp_type = DMU_OT_NONE;
2280                 zp.zp_level = 0;
2281                 zp.zp_copies = gio->io_prop.zp_copies;
2282                 zp.zp_dedup = B_FALSE;
2283                 zp.zp_dedup_verify = B_FALSE;
2284                 zp.zp_nopwrite = B_FALSE;
2285
2286                 zio_t *cio = zio_write(zio, spa, txg, &gbh->zg_blkptr[g],
2287                     (char *)pio->io_data + (pio->io_size - resid), lsize, &zp,
2288                     zio_write_gang_member_ready, NULL, NULL, NULL,
2289                     &gn->gn_child[g], pio->io_priority,
2290                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
2291
2292                 if (pio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
2293                         ASSERT(pio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
2294                         ASSERT(!(pio->io_flags & ZIO_FLAG_NODATA));
2295
2296                         /*
2297                          * Gang children won't throttle but we should
2298                          * account for their work, so reserve an allocation
2299                          * slot for them here.
2300                          */
2301                         VERIFY(metaslab_class_throttle_reserve(mc,
2302                             zp.zp_copies, cio, flags));
2303                 }
2304                 zio_nowait(cio);
2305         }
2306
2307         /*
2308          * Set pio's pipeline to just wait for zio to finish.
2309          */
2310         pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2311
2312         zio_nowait(zio);
2313
2314         return (ZIO_PIPELINE_CONTINUE);
2315 }
2316
2317 /*
2318  * The zio_nop_write stage in the pipeline determines if allocating a
2319  * new bp is necessary.  The nopwrite feature can handle writes in
2320  * either syncing or open context (i.e. zil writes) and as a result is
2321  * mutually exclusive with dedup.
2322  *
2323  * By leveraging a cryptographically secure checksum, such as SHA256, we
2324  * can compare the checksums of the new data and the old to determine if
2325  * allocating a new block is required.  Note that our requirements for
2326  * cryptographic strength are fairly weak: there can't be any accidental
2327  * hash collisions, but we don't need to be secure against intentional
2328  * (malicious) collisions.  To trigger a nopwrite, you have to be able
2329  * to write the file to begin with, and triggering an incorrect (hash
2330  * collision) nopwrite is no worse than simply writing to the file.
2331  * That said, there are no known attacks against the checksum algorithms
2332  * used for nopwrite, assuming that the salt and the checksums
2333  * themselves remain secret.
2334  */
2335 static int
2336 zio_nop_write(zio_t *zio)
2337 {
2338         blkptr_t *bp = zio->io_bp;
2339         blkptr_t *bp_orig = &zio->io_bp_orig;
2340         zio_prop_t *zp = &zio->io_prop;
2341
2342         ASSERT(BP_GET_LEVEL(bp) == 0);
2343         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
2344         ASSERT(zp->zp_nopwrite);
2345         ASSERT(!zp->zp_dedup);
2346         ASSERT(zio->io_bp_override == NULL);
2347         ASSERT(IO_IS_ALLOCATING(zio));
2348
2349         /*
2350          * Check to see if the original bp and the new bp have matching
2351          * characteristics (i.e. same checksum, compression algorithms, etc).
2352          * If they don't then just continue with the pipeline which will
2353          * allocate a new bp.
2354          */
2355         if (BP_IS_HOLE(bp_orig) ||
2356             !(zio_checksum_table[BP_GET_CHECKSUM(bp)].ci_flags &
2357             ZCHECKSUM_FLAG_NOPWRITE) ||
2358             BP_GET_CHECKSUM(bp) != BP_GET_CHECKSUM(bp_orig) ||
2359             BP_GET_COMPRESS(bp) != BP_GET_COMPRESS(bp_orig) ||
2360             BP_GET_DEDUP(bp) != BP_GET_DEDUP(bp_orig) ||
2361             zp->zp_copies != BP_GET_NDVAS(bp_orig))
2362                 return (ZIO_PIPELINE_CONTINUE);
2363
2364         /*
2365          * If the checksums match then reset the pipeline so that we
2366          * avoid allocating a new bp and issuing any I/O.
2367          */
2368         if (ZIO_CHECKSUM_EQUAL(bp->blk_cksum, bp_orig->blk_cksum)) {
2369                 ASSERT(zio_checksum_table[zp->zp_checksum].ci_flags &
2370                     ZCHECKSUM_FLAG_NOPWRITE);
2371                 ASSERT3U(BP_GET_PSIZE(bp), ==, BP_GET_PSIZE(bp_orig));
2372                 ASSERT3U(BP_GET_LSIZE(bp), ==, BP_GET_LSIZE(bp_orig));
2373                 ASSERT(zp->zp_compress != ZIO_COMPRESS_OFF);
2374                 ASSERT(bcmp(&bp->blk_prop, &bp_orig->blk_prop,
2375                     sizeof (uint64_t)) == 0);
2376
2377                 *bp = *bp_orig;
2378                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2379                 zio->io_flags |= ZIO_FLAG_NOPWRITE;
2380         }
2381
2382         return (ZIO_PIPELINE_CONTINUE);
2383 }
2384
2385 /*
2386  * ==========================================================================
2387  * Dedup
2388  * ==========================================================================
2389  */
2390 static void
2391 zio_ddt_child_read_done(zio_t *zio)
2392 {
2393         blkptr_t *bp = zio->io_bp;
2394         ddt_entry_t *dde = zio->io_private;
2395         ddt_phys_t *ddp;
2396         zio_t *pio = zio_unique_parent(zio);
2397
2398         mutex_enter(&pio->io_lock);
2399         ddp = ddt_phys_select(dde, bp);
2400         if (zio->io_error == 0)
2401                 ddt_phys_clear(ddp);    /* this ddp doesn't need repair */
2402         if (zio->io_error == 0 && dde->dde_repair_data == NULL)
2403                 dde->dde_repair_data = zio->io_data;
2404         else
2405                 zio_buf_free(zio->io_data, zio->io_size);
2406         mutex_exit(&pio->io_lock);
2407 }
2408
2409 static int
2410 zio_ddt_read_start(zio_t *zio)
2411 {
2412         blkptr_t *bp = zio->io_bp;
2413
2414         ASSERT(BP_GET_DEDUP(bp));
2415         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
2416         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2417
2418         if (zio->io_child_error[ZIO_CHILD_DDT]) {
2419                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
2420                 ddt_entry_t *dde = ddt_repair_start(ddt, bp);
2421                 ddt_phys_t *ddp = dde->dde_phys;
2422                 ddt_phys_t *ddp_self = ddt_phys_select(dde, bp);
2423                 blkptr_t blk;
2424
2425                 ASSERT(zio->io_vsd == NULL);
2426                 zio->io_vsd = dde;
2427
2428                 if (ddp_self == NULL)
2429                         return (ZIO_PIPELINE_CONTINUE);
2430
2431                 for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2432                         if (ddp->ddp_phys_birth == 0 || ddp == ddp_self)
2433                                 continue;
2434                         ddt_bp_create(ddt->ddt_checksum, &dde->dde_key, ddp,
2435                             &blk);
2436                         zio_nowait(zio_read(zio, zio->io_spa, &blk,
2437                             zio_buf_alloc(zio->io_size), zio->io_size,
2438                             zio_ddt_child_read_done, dde, zio->io_priority,
2439                             ZIO_DDT_CHILD_FLAGS(zio) | ZIO_FLAG_DONT_PROPAGATE,
2440                             &zio->io_bookmark));
2441                 }
2442                 return (ZIO_PIPELINE_CONTINUE);
2443         }
2444
2445         zio_nowait(zio_read(zio, zio->io_spa, bp,
2446             zio->io_data, zio->io_size, NULL, NULL, zio->io_priority,
2447             ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark));
2448
2449         return (ZIO_PIPELINE_CONTINUE);
2450 }
2451
2452 static int
2453 zio_ddt_read_done(zio_t *zio)
2454 {
2455         blkptr_t *bp = zio->io_bp;
2456
2457         if (zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE))
2458                 return (ZIO_PIPELINE_STOP);
2459
2460         ASSERT(BP_GET_DEDUP(bp));
2461         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
2462         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2463
2464         if (zio->io_child_error[ZIO_CHILD_DDT]) {
2465                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
2466                 ddt_entry_t *dde = zio->io_vsd;
2467                 if (ddt == NULL) {
2468                         ASSERT(spa_load_state(zio->io_spa) != SPA_LOAD_NONE);
2469                         return (ZIO_PIPELINE_CONTINUE);
2470                 }
2471                 if (dde == NULL) {
2472                         zio->io_stage = ZIO_STAGE_DDT_READ_START >> 1;
2473                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
2474                         return (ZIO_PIPELINE_STOP);
2475                 }
2476                 if (dde->dde_repair_data != NULL) {
2477                         bcopy(dde->dde_repair_data, zio->io_data, zio->io_size);
2478                         zio->io_child_error[ZIO_CHILD_DDT] = 0;
2479                 }
2480                 ddt_repair_done(ddt, dde);
2481                 zio->io_vsd = NULL;
2482         }
2483
2484         ASSERT(zio->io_vsd == NULL);
2485
2486         return (ZIO_PIPELINE_CONTINUE);
2487 }
2488
2489 static boolean_t
2490 zio_ddt_collision(zio_t *zio, ddt_t *ddt, ddt_entry_t *dde)
2491 {
2492         spa_t *spa = zio->io_spa;
2493
2494         /*
2495          * Note: we compare the original data, not the transformed data,
2496          * because when zio->io_bp is an override bp, we will not have
2497          * pushed the I/O transforms.  That's an important optimization
2498          * because otherwise we'd compress/encrypt all dmu_sync() data twice.
2499          */
2500         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
2501                 zio_t *lio = dde->dde_lead_zio[p];
2502
2503                 if (lio != NULL) {
2504                         return (lio->io_orig_size != zio->io_orig_size ||
2505                             bcmp(zio->io_orig_data, lio->io_orig_data,
2506                             zio->io_orig_size) != 0);
2507                 }
2508         }
2509
2510         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
2511                 ddt_phys_t *ddp = &dde->dde_phys[p];
2512
2513                 if (ddp->ddp_phys_birth != 0) {
2514                         arc_buf_t *abuf = NULL;
2515                         arc_flags_t aflags = ARC_FLAG_WAIT;
2516                         blkptr_t blk = *zio->io_bp;
2517                         int error;
2518
2519                         ddt_bp_fill(ddp, &blk, ddp->ddp_phys_birth);
2520
2521                         ddt_exit(ddt);
2522
2523                         error = arc_read(NULL, spa, &blk,
2524                             arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ,
2525                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
2526                             &aflags, &zio->io_bookmark);
2527
2528                         if (error == 0) {
2529                                 if (arc_buf_size(abuf) != zio->io_orig_size ||
2530                                     bcmp(abuf->b_data, zio->io_orig_data,
2531                                     zio->io_orig_size) != 0)
2532                                         error = SET_ERROR(EEXIST);
2533                                 arc_buf_destroy(abuf, &abuf);
2534                         }
2535
2536                         ddt_enter(ddt);
2537                         return (error != 0);
2538                 }
2539         }
2540
2541         return (B_FALSE);
2542 }
2543
2544 static void
2545 zio_ddt_child_write_ready(zio_t *zio)
2546 {
2547         int p = zio->io_prop.zp_copies;
2548         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
2549         ddt_entry_t *dde = zio->io_private;
2550         ddt_phys_t *ddp = &dde->dde_phys[p];
2551         zio_t *pio;
2552
2553         if (zio->io_error)
2554                 return;
2555
2556         ddt_enter(ddt);
2557
2558         ASSERT(dde->dde_lead_zio[p] == zio);
2559
2560         ddt_phys_fill(ddp, zio->io_bp);
2561
2562         zio_link_t *zl = NULL;
2563         while ((pio = zio_walk_parents(zio, &zl)) != NULL)
2564                 ddt_bp_fill(ddp, pio->io_bp, zio->io_txg);
2565
2566         ddt_exit(ddt);
2567 }
2568
2569 static void
2570 zio_ddt_child_write_done(zio_t *zio)
2571 {
2572         int p = zio->io_prop.zp_copies;
2573         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
2574         ddt_entry_t *dde = zio->io_private;
2575         ddt_phys_t *ddp = &dde->dde_phys[p];
2576
2577         ddt_enter(ddt);
2578
2579         ASSERT(ddp->ddp_refcnt == 0);
2580         ASSERT(dde->dde_lead_zio[p] == zio);
2581         dde->dde_lead_zio[p] = NULL;
2582
2583         if (zio->io_error == 0) {
2584                 zio_link_t *zl = NULL;
2585                 while (zio_walk_parents(zio, &zl) != NULL)
2586                         ddt_phys_addref(ddp);
2587         } else {
2588                 ddt_phys_clear(ddp);
2589         }
2590
2591         ddt_exit(ddt);
2592 }
2593
2594 static void
2595 zio_ddt_ditto_write_done(zio_t *zio)
2596 {
2597         int p = DDT_PHYS_DITTO;
2598         zio_prop_t *zp = &zio->io_prop;
2599         blkptr_t *bp = zio->io_bp;
2600         ddt_t *ddt = ddt_select(zio->io_spa, bp);
2601         ddt_entry_t *dde = zio->io_private;
2602         ddt_phys_t *ddp = &dde->dde_phys[p];
2603         ddt_key_t *ddk = &dde->dde_key;
2604
2605         ddt_enter(ddt);
2606
2607         ASSERT(ddp->ddp_refcnt == 0);
2608         ASSERT(dde->dde_lead_zio[p] == zio);
2609         dde->dde_lead_zio[p] = NULL;
2610
2611         if (zio->io_error == 0) {
2612                 ASSERT(ZIO_CHECKSUM_EQUAL(bp->blk_cksum, ddk->ddk_cksum));
2613                 ASSERT(zp->zp_copies < SPA_DVAS_PER_BP);
2614                 ASSERT(zp->zp_copies == BP_GET_NDVAS(bp) - BP_IS_GANG(bp));
2615                 if (ddp->ddp_phys_birth != 0)
2616                         ddt_phys_free(ddt, ddk, ddp, zio->io_txg);
2617                 ddt_phys_fill(ddp, bp);
2618         }
2619
2620         ddt_exit(ddt);
2621 }
2622
2623 static int
2624 zio_ddt_write(zio_t *zio)
2625 {
2626         spa_t *spa = zio->io_spa;
2627         blkptr_t *bp = zio->io_bp;
2628         uint64_t txg = zio->io_txg;
2629         zio_prop_t *zp = &zio->io_prop;
2630         int p = zp->zp_copies;
2631         int ditto_copies;
2632         zio_t *cio = NULL;
2633         zio_t *dio = NULL;
2634         ddt_t *ddt = ddt_select(spa, bp);
2635         ddt_entry_t *dde;
2636         ddt_phys_t *ddp;
2637
2638         ASSERT(BP_GET_DEDUP(bp));
2639         ASSERT(BP_GET_CHECKSUM(bp) == zp->zp_checksum);
2640         ASSERT(BP_IS_HOLE(bp) || zio->io_bp_override);
2641
2642         ddt_enter(ddt);
2643         dde = ddt_lookup(ddt, bp, B_TRUE);
2644         ddp = &dde->dde_phys[p];
2645
2646         if (zp->zp_dedup_verify && zio_ddt_collision(zio, ddt, dde)) {
2647                 /*
2648                  * If we're using a weak checksum, upgrade to a strong checksum
2649                  * and try again.  If we're already using a strong checksum,
2650                  * we can't resolve it, so just convert to an ordinary write.
2651                  * (And automatically e-mail a paper to Nature?)
2652                  */
2653                 if (!(zio_checksum_table[zp->zp_checksum].ci_flags &
2654                     ZCHECKSUM_FLAG_DEDUP)) {
2655                         zp->zp_checksum = spa_dedup_checksum(spa);
2656                         zio_pop_transforms(zio);
2657                         zio->io_stage = ZIO_STAGE_OPEN;
2658                         BP_ZERO(bp);
2659                 } else {
2660                         zp->zp_dedup = B_FALSE;
2661                 }
2662                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
2663                 ddt_exit(ddt);
2664                 return (ZIO_PIPELINE_CONTINUE);
2665         }
2666
2667         ditto_copies = ddt_ditto_copies_needed(ddt, dde, ddp);
2668         ASSERT(ditto_copies < SPA_DVAS_PER_BP);
2669
2670         if (ditto_copies > ddt_ditto_copies_present(dde) &&
2671             dde->dde_lead_zio[DDT_PHYS_DITTO] == NULL) {
2672                 zio_prop_t czp = *zp;
2673
2674                 czp.zp_copies = ditto_copies;
2675
2676                 /*
2677                  * If we arrived here with an override bp, we won't have run
2678                  * the transform stack, so we won't have the data we need to
2679                  * generate a child i/o.  So, toss the override bp and restart.
2680                  * This is safe, because using the override bp is just an
2681                  * optimization; and it's rare, so the cost doesn't matter.
2682                  */
2683                 if (zio->io_bp_override) {
2684                         zio_pop_transforms(zio);
2685                         zio->io_stage = ZIO_STAGE_OPEN;
2686                         zio->io_pipeline = ZIO_WRITE_PIPELINE;
2687                         zio->io_bp_override = NULL;
2688                         BP_ZERO(bp);
2689                         ddt_exit(ddt);
2690                         return (ZIO_PIPELINE_CONTINUE);
2691                 }
2692
2693                 dio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2694                     zio->io_orig_size, &czp, NULL, NULL,
2695                     NULL, zio_ddt_ditto_write_done, dde, zio->io_priority,
2696                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2697
2698                 zio_push_transform(dio, zio->io_data, zio->io_size, 0, NULL);
2699                 dde->dde_lead_zio[DDT_PHYS_DITTO] = dio;
2700         }
2701
2702         if (ddp->ddp_phys_birth != 0 || dde->dde_lead_zio[p] != NULL) {
2703                 if (ddp->ddp_phys_birth != 0)
2704                         ddt_bp_fill(ddp, bp, txg);
2705                 if (dde->dde_lead_zio[p] != NULL)
2706                         zio_add_child(zio, dde->dde_lead_zio[p]);
2707                 else
2708                         ddt_phys_addref(ddp);
2709         } else if (zio->io_bp_override) {
2710                 ASSERT(bp->blk_birth == txg);
2711                 ASSERT(BP_EQUAL(bp, zio->io_bp_override));
2712                 ddt_phys_fill(ddp, bp);
2713                 ddt_phys_addref(ddp);
2714         } else {
2715                 cio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2716                     zio->io_orig_size, zp,
2717                     zio_ddt_child_write_ready, NULL, NULL,
2718                     zio_ddt_child_write_done, dde, zio->io_priority,
2719                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2720
2721                 zio_push_transform(cio, zio->io_data, zio->io_size, 0, NULL);
2722                 dde->dde_lead_zio[p] = cio;
2723         }
2724
2725         ddt_exit(ddt);
2726
2727         if (cio)
2728                 zio_nowait(cio);
2729         if (dio)
2730                 zio_nowait(dio);
2731
2732         return (ZIO_PIPELINE_CONTINUE);
2733 }
2734
2735 ddt_entry_t *freedde; /* for debugging */
2736
2737 static int
2738 zio_ddt_free(zio_t *zio)
2739 {
2740         spa_t *spa = zio->io_spa;
2741         blkptr_t *bp = zio->io_bp;
2742         ddt_t *ddt = ddt_select(spa, bp);
2743         ddt_entry_t *dde;
2744         ddt_phys_t *ddp;
2745
2746         ASSERT(BP_GET_DEDUP(bp));
2747         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2748
2749         ddt_enter(ddt);
2750         freedde = dde = ddt_lookup(ddt, bp, B_TRUE);
2751         ddp = ddt_phys_select(dde, bp);
2752         ddt_phys_decref(ddp);
2753         ddt_exit(ddt);
2754
2755         return (ZIO_PIPELINE_CONTINUE);
2756 }
2757
2758 /*
2759  * ==========================================================================
2760  * Allocate and free blocks
2761  * ==========================================================================
2762  */
2763
2764 static zio_t *
2765 zio_io_to_allocate(spa_t *spa)
2766 {
2767         zio_t *zio;
2768
2769         ASSERT(MUTEX_HELD(&spa->spa_alloc_lock));
2770
2771         zio = avl_first(&spa->spa_alloc_tree);
2772         if (zio == NULL)
2773                 return (NULL);
2774
2775         ASSERT(IO_IS_ALLOCATING(zio));
2776
2777         /*
2778          * Try to place a reservation for this zio. If we're unable to
2779          * reserve then we throttle.
2780          */
2781         if (!metaslab_class_throttle_reserve(spa_normal_class(spa),
2782             zio->io_prop.zp_copies, zio, 0)) {
2783                 return (NULL);
2784         }
2785
2786         avl_remove(&spa->spa_alloc_tree, zio);
2787         ASSERT3U(zio->io_stage, <, ZIO_STAGE_DVA_ALLOCATE);
2788
2789         return (zio);
2790 }
2791
2792 static int
2793 zio_dva_throttle(zio_t *zio)
2794 {
2795         spa_t *spa = zio->io_spa;
2796         zio_t *nio;
2797
2798         if (zio->io_priority == ZIO_PRIORITY_SYNC_WRITE ||
2799             !spa_normal_class(zio->io_spa)->mc_alloc_throttle_enabled ||
2800             zio->io_child_type == ZIO_CHILD_GANG ||
2801             zio->io_flags & ZIO_FLAG_NODATA) {
2802                 return (ZIO_PIPELINE_CONTINUE);
2803         }
2804
2805         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2806
2807         ASSERT3U(zio->io_queued_timestamp, >, 0);
2808         ASSERT(zio->io_stage == ZIO_STAGE_DVA_THROTTLE);
2809
2810         mutex_enter(&spa->spa_alloc_lock);
2811
2812         ASSERT(zio->io_type == ZIO_TYPE_WRITE);
2813         avl_add(&spa->spa_alloc_tree, zio);
2814
2815         nio = zio_io_to_allocate(zio->io_spa);
2816         mutex_exit(&spa->spa_alloc_lock);
2817
2818         if (nio == zio)
2819                 return (ZIO_PIPELINE_CONTINUE);
2820
2821         if (nio != NULL) {
2822                 ASSERT3U(nio->io_queued_timestamp, <=,
2823                     zio->io_queued_timestamp);
2824                 ASSERT(nio->io_stage == ZIO_STAGE_DVA_THROTTLE);
2825                 /*
2826                  * We are passing control to a new zio so make sure that
2827                  * it is processed by a different thread. We do this to
2828                  * avoid stack overflows that can occur when parents are
2829                  * throttled and children are making progress. We allow
2830                  * it to go to the head of the taskq since it's already
2831                  * been waiting.
2832                  */
2833                 zio_taskq_dispatch(nio, ZIO_TASKQ_ISSUE, B_TRUE);
2834         }
2835         return (ZIO_PIPELINE_STOP);
2836 }
2837
2838 void
2839 zio_allocate_dispatch(spa_t *spa)
2840 {
2841         zio_t *zio;
2842
2843         mutex_enter(&spa->spa_alloc_lock);
2844         zio = zio_io_to_allocate(spa);
2845         mutex_exit(&spa->spa_alloc_lock);
2846         if (zio == NULL)
2847                 return;
2848
2849         ASSERT3U(zio->io_stage, ==, ZIO_STAGE_DVA_THROTTLE);
2850         ASSERT0(zio->io_error);
2851         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_TRUE);
2852 }
2853
2854 static int
2855 zio_dva_allocate(zio_t *zio)
2856 {
2857         spa_t *spa = zio->io_spa;
2858         metaslab_class_t *mc = spa_normal_class(spa);
2859         blkptr_t *bp = zio->io_bp;
2860         int error;
2861         int flags = 0;
2862
2863         if (zio->io_gang_leader == NULL) {
2864                 ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2865                 zio->io_gang_leader = zio;
2866         }
2867
2868         ASSERT(BP_IS_HOLE(bp));
2869         ASSERT0(BP_GET_NDVAS(bp));
2870         ASSERT3U(zio->io_prop.zp_copies, >, 0);
2871         ASSERT3U(zio->io_prop.zp_copies, <=, spa_max_replication(spa));
2872         ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
2873
2874         if (zio->io_flags & ZIO_FLAG_NODATA) {
2875                 flags |= METASLAB_DONT_THROTTLE;
2876         }
2877         if (zio->io_flags & ZIO_FLAG_GANG_CHILD) {
2878                 flags |= METASLAB_GANG_CHILD;
2879         }
2880         if (zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE) {
2881                 flags |= METASLAB_ASYNC_ALLOC;
2882         }
2883
2884         error = metaslab_alloc(spa, mc, zio->io_size, bp,
2885             zio->io_prop.zp_copies, zio->io_txg, NULL, flags, zio);
2886
2887         if (error != 0) {
2888                 spa_dbgmsg(spa, "%s: metaslab allocation failure: zio %p, "
2889                     "size %llu, error %d", spa_name(spa), zio, zio->io_size,
2890                     error);
2891                 if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE)
2892                         return (zio_write_gang_block(zio));
2893                 zio->io_error = error;
2894         }
2895
2896         return (ZIO_PIPELINE_CONTINUE);
2897 }
2898
2899 static int
2900 zio_dva_free(zio_t *zio)
2901 {
2902         metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
2903
2904         return (ZIO_PIPELINE_CONTINUE);
2905 }
2906
2907 static int
2908 zio_dva_claim(zio_t *zio)
2909 {
2910         int error;
2911
2912         error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
2913         if (error)
2914                 zio->io_error = error;
2915
2916         return (ZIO_PIPELINE_CONTINUE);
2917 }
2918
2919 /*
2920  * Undo an allocation.  This is used by zio_done() when an I/O fails
2921  * and we want to give back the block we just allocated.
2922  * This handles both normal blocks and gang blocks.
2923  */
2924 static void
2925 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
2926 {
2927         ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
2928         ASSERT(zio->io_bp_override == NULL);
2929
2930         if (!BP_IS_HOLE(bp))
2931                 metaslab_free(zio->io_spa, bp, bp->blk_birth, B_TRUE);
2932
2933         if (gn != NULL) {
2934                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2935                         zio_dva_unallocate(zio, gn->gn_child[g],
2936                             &gn->gn_gbh->zg_blkptr[g]);
2937                 }
2938         }
2939 }
2940
2941 /*
2942  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
2943  */
2944 int
2945 zio_alloc_zil(spa_t *spa, uint64_t txg, blkptr_t *new_bp, blkptr_t *old_bp,
2946     uint64_t size, boolean_t *slog)
2947 {
2948         int error = 1;
2949
2950         ASSERT(txg > spa_syncing_txg(spa));
2951
2952         error = metaslab_alloc(spa, spa_log_class(spa), size,
2953             new_bp, 1, txg, old_bp, METASLAB_HINTBP_AVOID, NULL);
2954         if (error == 0) {
2955                 *slog = TRUE;
2956         } else {
2957                 error = metaslab_alloc(spa, spa_normal_class(spa), size,
2958                     new_bp, 1, txg, old_bp, METASLAB_HINTBP_AVOID, NULL);
2959                 if (error == 0)
2960                         *slog = FALSE;
2961         }
2962
2963         if (error == 0) {
2964                 BP_SET_LSIZE(new_bp, size);
2965                 BP_SET_PSIZE(new_bp, size);
2966                 BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
2967                 BP_SET_CHECKSUM(new_bp,
2968                     spa_version(spa) >= SPA_VERSION_SLIM_ZIL
2969                     ? ZIO_CHECKSUM_ZILOG2 : ZIO_CHECKSUM_ZILOG);
2970                 BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
2971                 BP_SET_LEVEL(new_bp, 0);
2972                 BP_SET_DEDUP(new_bp, 0);
2973                 BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
2974         }
2975
2976         return (error);
2977 }
2978
2979 /*
2980  * Free an intent log block.
2981  */
2982 void
2983 zio_free_zil(spa_t *spa, uint64_t txg, blkptr_t *bp)
2984 {
2985         ASSERT(BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG);
2986         ASSERT(!BP_IS_GANG(bp));
2987
2988         zio_free(spa, txg, bp);
2989 }
2990
2991 /*
2992  * ==========================================================================
2993  * Read, write and delete to physical devices
2994  * ==========================================================================
2995  */
2996
2997
2998 /*
2999  * Issue an I/O to the underlying vdev. Typically the issue pipeline
3000  * stops after this stage and will resume upon I/O completion.
3001  * However, there are instances where the vdev layer may need to
3002  * continue the pipeline when an I/O was not issued. Since the I/O
3003  * that was sent to the vdev layer might be different than the one
3004  * currently active in the pipeline (see vdev_queue_io()), we explicitly
3005  * force the underlying vdev layers to call either zio_execute() or
3006  * zio_interrupt() to ensure that the pipeline continues with the correct I/O.
3007  */
3008 static int
3009 zio_vdev_io_start(zio_t *zio)
3010 {
3011         vdev_t *vd = zio->io_vd;
3012         uint64_t align;
3013         spa_t *spa = zio->io_spa;
3014         int ret;
3015
3016         ASSERT(zio->io_error == 0);
3017         ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
3018
3019         if (vd == NULL) {
3020                 if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
3021                         spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
3022
3023                 /*
3024                  * The mirror_ops handle multiple DVAs in a single BP.
3025                  */
3026                 vdev_mirror_ops.vdev_op_io_start(zio);
3027                 return (ZIO_PIPELINE_STOP);
3028         }
3029
3030         if (vd->vdev_ops->vdev_op_leaf && zio->io_type == ZIO_TYPE_FREE &&
3031             zio->io_priority == ZIO_PRIORITY_NOW) {
3032                 trim_map_free(vd, zio->io_offset, zio->io_size, zio->io_txg);
3033                 return (ZIO_PIPELINE_CONTINUE);
3034         }
3035
3036         ASSERT3P(zio->io_logical, !=, zio);
3037
3038         /*
3039          * We keep track of time-sensitive I/Os so that the scan thread
3040          * can quickly react to certain workloads.  In particular, we care
3041          * about non-scrubbing, top-level reads and writes with the following
3042          * characteristics:
3043          *      - synchronous writes of user data to non-slog devices
3044          *      - any reads of user data
3045          * When these conditions are met, adjust the timestamp of spa_last_io
3046          * which allows the scan thread to adjust its workload accordingly.
3047          */
3048         if (!(zio->io_flags & ZIO_FLAG_SCAN_THREAD) && zio->io_bp != NULL &&
3049             vd == vd->vdev_top && !vd->vdev_islog &&
3050             zio->io_bookmark.zb_objset != DMU_META_OBJSET &&
3051             zio->io_txg != spa_syncing_txg(spa)) {
3052                 uint64_t old = spa->spa_last_io;
3053                 uint64_t new = ddi_get_lbolt64();
3054                 if (old != new)
3055                         (void) atomic_cas_64(&spa->spa_last_io, old, new);
3056         }
3057
3058         align = 1ULL << vd->vdev_top->vdev_ashift;
3059
3060         if (!(zio->io_flags & ZIO_FLAG_PHYSICAL) &&
3061             P2PHASE(zio->io_size, align) != 0) {
3062                 /* Transform logical writes to be a full physical block size. */
3063                 uint64_t asize = P2ROUNDUP(zio->io_size, align);
3064                 char *abuf = NULL;
3065                 if (zio->io_type == ZIO_TYPE_READ ||
3066                     zio->io_type == ZIO_TYPE_WRITE)
3067                         abuf = zio_buf_alloc(asize);
3068                 ASSERT(vd == vd->vdev_top);
3069                 if (zio->io_type == ZIO_TYPE_WRITE) {
3070                         bcopy(zio->io_data, abuf, zio->io_size);
3071                         bzero(abuf + zio->io_size, asize - zio->io_size);
3072                 }
3073                 zio_push_transform(zio, abuf, asize, abuf ? asize : 0,
3074                     zio_subblock);
3075         }
3076
3077         /*
3078          * If this is not a physical io, make sure that it is properly aligned
3079          * before proceeding.
3080          */
3081         if (!(zio->io_flags & ZIO_FLAG_PHYSICAL)) {
3082                 ASSERT0(P2PHASE(zio->io_offset, align));
3083                 ASSERT0(P2PHASE(zio->io_size, align));
3084         } else {
3085                 /*
3086                  * For the physical io we allow alignment
3087                  * to a logical block size.
3088                  */
3089                 uint64_t log_align =
3090                     1ULL << vd->vdev_top->vdev_logical_ashift;
3091                 ASSERT0(P2PHASE(zio->io_offset, log_align));
3092                 ASSERT0(P2PHASE(zio->io_size, log_align));
3093         }
3094
3095         VERIFY(zio->io_type == ZIO_TYPE_READ || spa_writeable(spa));
3096
3097         /*
3098          * If this is a repair I/O, and there's no self-healing involved --
3099          * that is, we're just resilvering what we expect to resilver --
3100          * then don't do the I/O unless zio's txg is actually in vd's DTL.
3101          * This prevents spurious resilvering with nested replication.
3102          * For example, given a mirror of mirrors, (A+B)+(C+D), if only
3103          * A is out of date, we'll read from C+D, then use the data to
3104          * resilver A+B -- but we don't actually want to resilver B, just A.
3105          * The top-level mirror has no way to know this, so instead we just
3106          * discard unnecessary repairs as we work our way down the vdev tree.
3107          * The same logic applies to any form of nested replication:
3108          * ditto + mirror, RAID-Z + replacing, etc.  This covers them all.
3109          */
3110         if ((zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
3111             !(zio->io_flags & ZIO_FLAG_SELF_HEAL) &&
3112             zio->io_txg != 0 && /* not a delegated i/o */
3113             !vdev_dtl_contains(vd, DTL_PARTIAL, zio->io_txg, 1)) {
3114                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
3115                 zio_vdev_io_bypass(zio);
3116                 return (ZIO_PIPELINE_CONTINUE);
3117         }
3118
3119         if (vd->vdev_ops->vdev_op_leaf) {
3120                 switch (zio->io_type) {
3121                 case ZIO_TYPE_READ:
3122                         if (vdev_cache_read(zio))
3123                                 return (ZIO_PIPELINE_CONTINUE);
3124                         /* FALLTHROUGH */
3125                 case ZIO_TYPE_WRITE:
3126                 case ZIO_TYPE_FREE:
3127                         if ((zio = vdev_queue_io(zio)) == NULL)
3128                                 return (ZIO_PIPELINE_STOP);
3129
3130                         if (!vdev_accessible(vd, zio)) {
3131                                 zio->io_error = SET_ERROR(ENXIO);
3132                                 zio_interrupt(zio);
3133                                 return (ZIO_PIPELINE_STOP);
3134                         }
3135                         break;
3136                 }
3137                 /*
3138                  * Note that we ignore repair writes for TRIM because they can
3139                  * conflict with normal writes. This isn't an issue because, by
3140                  * definition, we only repair blocks that aren't freed.
3141                  */
3142                 if (zio->io_type == ZIO_TYPE_WRITE &&
3143                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
3144                     !trim_map_write_start(zio))
3145                         return (ZIO_PIPELINE_STOP);
3146         }
3147
3148         vd->vdev_ops->vdev_op_io_start(zio);
3149         return (ZIO_PIPELINE_STOP);
3150 }
3151
3152 static int
3153 zio_vdev_io_done(zio_t *zio)
3154 {
3155         vdev_t *vd = zio->io_vd;
3156         vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
3157         boolean_t unexpected_error = B_FALSE;
3158
3159         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
3160                 return (ZIO_PIPELINE_STOP);
3161
3162         ASSERT(zio->io_type == ZIO_TYPE_READ ||
3163             zio->io_type == ZIO_TYPE_WRITE || zio->io_type == ZIO_TYPE_FREE);
3164
3165         if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
3166             (zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE ||
3167             zio->io_type == ZIO_TYPE_FREE)) {
3168
3169                 if (zio->io_type == ZIO_TYPE_WRITE &&
3170                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR))
3171                         trim_map_write_done(zio);
3172
3173                 vdev_queue_io_done(zio);
3174
3175                 if (zio->io_type == ZIO_TYPE_WRITE)
3176                         vdev_cache_write(zio);
3177
3178                 if (zio_injection_enabled && zio->io_error == 0)
3179                         zio->io_error = zio_handle_device_injection(vd,
3180                             zio, EIO);
3181
3182                 if (zio_injection_enabled && zio->io_error == 0)
3183                         zio->io_error = zio_handle_label_injection(zio, EIO);
3184
3185                 if (zio->io_error) {
3186                         if (zio->io_error == ENOTSUP &&
3187                             zio->io_type == ZIO_TYPE_FREE) {
3188                                 /* Not all devices support TRIM. */
3189                         } else if (!vdev_accessible(vd, zio)) {
3190                                 zio->io_error = SET_ERROR(ENXIO);
3191                         } else {
3192                                 unexpected_error = B_TRUE;
3193                         }
3194                 }
3195         }
3196
3197         ops->vdev_op_io_done(zio);
3198
3199         if (unexpected_error)
3200                 VERIFY(vdev_probe(vd, zio) == NULL);
3201
3202         return (ZIO_PIPELINE_CONTINUE);
3203 }
3204
3205 /*
3206  * For non-raidz ZIOs, we can just copy aside the bad data read from the
3207  * disk, and use that to finish the checksum ereport later.
3208  */
3209 static void
3210 zio_vsd_default_cksum_finish(zio_cksum_report_t *zcr,
3211     const void *good_buf)
3212 {
3213         /* no processing needed */
3214         zfs_ereport_finish_checksum(zcr, good_buf, zcr->zcr_cbdata, B_FALSE);
3215 }
3216
3217 /*ARGSUSED*/
3218 void
3219 zio_vsd_default_cksum_report(zio_t *zio, zio_cksum_report_t *zcr, void *ignored)
3220 {
3221         void *buf = zio_buf_alloc(zio->io_size);
3222
3223         bcopy(zio->io_data, buf, zio->io_size);
3224
3225         zcr->zcr_cbinfo = zio->io_size;
3226         zcr->zcr_cbdata = buf;
3227         zcr->zcr_finish = zio_vsd_default_cksum_finish;
3228         zcr->zcr_free = zio_buf_free;
3229 }
3230
3231 static int
3232 zio_vdev_io_assess(zio_t *zio)
3233 {
3234         vdev_t *vd = zio->io_vd;
3235
3236         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
3237                 return (ZIO_PIPELINE_STOP);
3238
3239         if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
3240                 spa_config_exit(zio->io_spa, SCL_ZIO, zio);
3241
3242         if (zio->io_vsd != NULL) {
3243                 zio->io_vsd_ops->vsd_free(zio);
3244                 zio->io_vsd = NULL;
3245         }
3246
3247         if (zio_injection_enabled && zio->io_error == 0)
3248                 zio->io_error = zio_handle_fault_injection(zio, EIO);
3249
3250         if (zio->io_type == ZIO_TYPE_FREE &&
3251             zio->io_priority != ZIO_PRIORITY_NOW) {
3252                 switch (zio->io_error) {
3253                 case 0:
3254                         ZIO_TRIM_STAT_INCR(bytes, zio->io_size);
3255                         ZIO_TRIM_STAT_BUMP(success);
3256                         break;
3257                 case EOPNOTSUPP:
3258                         ZIO_TRIM_STAT_BUMP(unsupported);
3259                         break;
3260                 default:
3261                         ZIO_TRIM_STAT_BUMP(failed);
3262                         break;
3263                 }
3264         }
3265
3266         /*
3267          * If the I/O failed, determine whether we should attempt to retry it.
3268          *
3269          * On retry, we cut in line in the issue queue, since we don't want
3270          * compression/checksumming/etc. work to prevent our (cheap) IO reissue.
3271          */
3272         if (zio->io_error && vd == NULL &&
3273             !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
3274                 ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE)); /* not a leaf */
3275                 ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));  /* not a leaf */
3276                 zio->io_error = 0;
3277                 zio->io_flags |= ZIO_FLAG_IO_RETRY |
3278                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE;
3279                 zio->io_stage = ZIO_STAGE_VDEV_IO_START >> 1;
3280                 zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE,
3281                     zio_requeue_io_start_cut_in_line);
3282                 return (ZIO_PIPELINE_STOP);
3283         }
3284
3285         /*
3286          * If we got an error on a leaf device, convert it to ENXIO
3287          * if the device is not accessible at all.
3288          */
3289         if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
3290             !vdev_accessible(vd, zio))
3291                 zio->io_error = SET_ERROR(ENXIO);
3292
3293         /*
3294          * If we can't write to an interior vdev (mirror or RAID-Z),
3295          * set vdev_cant_write so that we stop trying to allocate from it.
3296          */
3297         if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
3298             vd != NULL && !vd->vdev_ops->vdev_op_leaf) {
3299                 vd->vdev_cant_write = B_TRUE;
3300         }
3301
3302         if (zio->io_error)
3303                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3304
3305         if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
3306             zio->io_physdone != NULL) {
3307                 ASSERT(!(zio->io_flags & ZIO_FLAG_DELEGATED));
3308                 ASSERT(zio->io_child_type == ZIO_CHILD_VDEV);
3309                 zio->io_physdone(zio->io_logical);
3310         }
3311
3312         return (ZIO_PIPELINE_CONTINUE);
3313 }
3314
3315 void
3316 zio_vdev_io_reissue(zio_t *zio)
3317 {
3318         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
3319         ASSERT(zio->io_error == 0);
3320
3321         zio->io_stage >>= 1;
3322 }
3323
3324 void
3325 zio_vdev_io_redone(zio_t *zio)
3326 {
3327         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
3328
3329         zio->io_stage >>= 1;
3330 }
3331
3332 void
3333 zio_vdev_io_bypass(zio_t *zio)
3334 {
3335         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
3336         ASSERT(zio->io_error == 0);
3337
3338         zio->io_flags |= ZIO_FLAG_IO_BYPASS;
3339         zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS >> 1;
3340 }
3341
3342 /*
3343  * ==========================================================================
3344  * Generate and verify checksums
3345  * ==========================================================================
3346  */
3347 static int
3348 zio_checksum_generate(zio_t *zio)
3349 {
3350         blkptr_t *bp = zio->io_bp;
3351         enum zio_checksum checksum;
3352
3353         if (bp == NULL) {
3354                 /*
3355                  * This is zio_write_phys().
3356                  * We're either generating a label checksum, or none at all.
3357                  */
3358                 checksum = zio->io_prop.zp_checksum;
3359
3360                 if (checksum == ZIO_CHECKSUM_OFF)
3361                         return (ZIO_PIPELINE_CONTINUE);
3362
3363                 ASSERT(checksum == ZIO_CHECKSUM_LABEL);
3364         } else {
3365                 if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
3366                         ASSERT(!IO_IS_ALLOCATING(zio));
3367                         checksum = ZIO_CHECKSUM_GANG_HEADER;
3368                 } else {
3369                         checksum = BP_GET_CHECKSUM(bp);
3370                 }
3371         }
3372
3373         zio_checksum_compute(zio, checksum, zio->io_data, zio->io_size);
3374
3375         return (ZIO_PIPELINE_CONTINUE);
3376 }
3377
3378 static int
3379 zio_checksum_verify(zio_t *zio)
3380 {
3381         zio_bad_cksum_t info;
3382         blkptr_t *bp = zio->io_bp;
3383         int error;
3384
3385         ASSERT(zio->io_vd != NULL);
3386
3387         if (bp == NULL) {
3388                 /*
3389                  * This is zio_read_phys().
3390                  * We're either verifying a label checksum, or nothing at all.
3391                  */
3392                 if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
3393                         return (ZIO_PIPELINE_CONTINUE);
3394
3395                 ASSERT(zio->io_prop.zp_checksum == ZIO_CHECKSUM_LABEL);
3396         }
3397
3398         if ((error = zio_checksum_error(zio, &info)) != 0) {
3399                 zio->io_error = error;
3400                 if (error == ECKSUM &&
3401                     !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
3402                         zfs_ereport_start_checksum(zio->io_spa,
3403                             zio->io_vd, zio, zio->io_offset,
3404                             zio->io_size, NULL, &info);
3405                 }
3406         }
3407
3408         return (ZIO_PIPELINE_CONTINUE);
3409 }
3410
3411 /*
3412  * Called by RAID-Z to ensure we don't compute the checksum twice.
3413  */
3414 void
3415 zio_checksum_verified(zio_t *zio)
3416 {
3417         zio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
3418 }
3419
3420 /*
3421  * ==========================================================================
3422  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
3423  * An error of 0 indicates success.  ENXIO indicates whole-device failure,
3424  * which may be transient (e.g. unplugged) or permament.  ECKSUM and EIO
3425  * indicate errors that are specific to one I/O, and most likely permanent.
3426  * Any other error is presumed to be worse because we weren't expecting it.
3427  * ==========================================================================
3428  */
3429 int
3430 zio_worst_error(int e1, int e2)
3431 {
3432         static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
3433         int r1, r2;
3434
3435         for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
3436                 if (e1 == zio_error_rank[r1])
3437                         break;
3438
3439         for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
3440                 if (e2 == zio_error_rank[r2])
3441                         break;
3442
3443         return (r1 > r2 ? e1 : e2);
3444 }
3445
3446 /*
3447  * ==========================================================================
3448  * I/O completion
3449  * ==========================================================================
3450  */
3451 static int
3452 zio_ready(zio_t *zio)
3453 {
3454         blkptr_t *bp = zio->io_bp;
3455         zio_t *pio, *pio_next;
3456         zio_link_t *zl = NULL;
3457
3458         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
3459             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_READY))
3460                 return (ZIO_PIPELINE_STOP);
3461
3462         if (zio->io_ready) {
3463                 ASSERT(IO_IS_ALLOCATING(zio));
3464                 ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp) ||
3465                     (zio->io_flags & ZIO_FLAG_NOPWRITE));
3466                 ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
3467
3468                 zio->io_ready(zio);
3469         }
3470
3471         if (bp != NULL && bp != &zio->io_bp_copy)
3472                 zio->io_bp_copy = *bp;
3473
3474         if (zio->io_error != 0) {
3475                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
3476
3477                 if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3478                         ASSERT(IO_IS_ALLOCATING(zio));
3479                         ASSERT(zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3480                         /*
3481                          * We were unable to allocate anything, unreserve and
3482                          * issue the next I/O to allocate.
3483                          */
3484                         metaslab_class_throttle_unreserve(
3485                             spa_normal_class(zio->io_spa),
3486                             zio->io_prop.zp_copies, zio);
3487                         zio_allocate_dispatch(zio->io_spa);
3488                 }
3489         }
3490
3491         mutex_enter(&zio->io_lock);
3492         zio->io_state[ZIO_WAIT_READY] = 1;
3493         pio = zio_walk_parents(zio, &zl);
3494         mutex_exit(&zio->io_lock);
3495
3496         /*
3497          * As we notify zio's parents, new parents could be added.
3498          * New parents go to the head of zio's io_parent_list, however,
3499          * so we will (correctly) not notify them.  The remainder of zio's
3500          * io_parent_list, from 'pio_next' onward, cannot change because
3501          * all parents must wait for us to be done before they can be done.
3502          */
3503         for (; pio != NULL; pio = pio_next) {
3504                 pio_next = zio_walk_parents(zio, &zl);
3505                 zio_notify_parent(pio, zio, ZIO_WAIT_READY);
3506         }
3507
3508         if (zio->io_flags & ZIO_FLAG_NODATA) {
3509                 if (BP_IS_GANG(bp)) {
3510                         zio->io_flags &= ~ZIO_FLAG_NODATA;
3511                 } else {
3512                         ASSERT((uintptr_t)zio->io_data < SPA_MAXBLOCKSIZE);
3513                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
3514                 }
3515         }
3516
3517         if (zio_injection_enabled &&
3518             zio->io_spa->spa_syncing_txg == zio->io_txg)
3519                 zio_handle_ignored_writes(zio);
3520
3521         return (ZIO_PIPELINE_CONTINUE);
3522 }
3523
3524 /*
3525  * Update the allocation throttle accounting.
3526  */
3527 static void
3528 zio_dva_throttle_done(zio_t *zio)
3529 {
3530         zio_t *lio = zio->io_logical;
3531         zio_t *pio = zio_unique_parent(zio);
3532         vdev_t *vd = zio->io_vd;
3533         int flags = METASLAB_ASYNC_ALLOC;
3534
3535         ASSERT3P(zio->io_bp, !=, NULL);
3536         ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
3537         ASSERT3U(zio->io_priority, ==, ZIO_PRIORITY_ASYNC_WRITE);
3538         ASSERT3U(zio->io_child_type, ==, ZIO_CHILD_VDEV);
3539         ASSERT(vd != NULL);
3540         ASSERT3P(vd, ==, vd->vdev_top);
3541         ASSERT(!(zio->io_flags & (ZIO_FLAG_IO_REPAIR | ZIO_FLAG_IO_RETRY)));
3542         ASSERT(zio->io_flags & ZIO_FLAG_IO_ALLOCATING);
3543         ASSERT(!(lio->io_flags & ZIO_FLAG_IO_REWRITE));
3544         ASSERT(!(lio->io_orig_flags & ZIO_FLAG_NODATA));
3545
3546         /*
3547          * Parents of gang children can have two flavors -- ones that
3548          * allocated the gang header (will have ZIO_FLAG_IO_REWRITE set)
3549          * and ones that allocated the constituent blocks. The allocation
3550          * throttle needs to know the allocating parent zio so we must find
3551          * it here.
3552          */
3553         if (pio->io_child_type == ZIO_CHILD_GANG) {
3554                 /*
3555                  * If our parent is a rewrite gang child then our grandparent
3556                  * would have been the one that performed the allocation.
3557                  */
3558                 if (pio->io_flags & ZIO_FLAG_IO_REWRITE)
3559                         pio = zio_unique_parent(pio);
3560                 flags |= METASLAB_GANG_CHILD;
3561         }
3562
3563         ASSERT(IO_IS_ALLOCATING(pio));
3564         ASSERT3P(zio, !=, zio->io_logical);
3565         ASSERT(zio->io_logical != NULL);
3566         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REPAIR));
3567         ASSERT0(zio->io_flags & ZIO_FLAG_NOPWRITE);
3568
3569         mutex_enter(&pio->io_lock);
3570         metaslab_group_alloc_decrement(zio->io_spa, vd->vdev_id, pio, flags);
3571         mutex_exit(&pio->io_lock);
3572
3573         metaslab_class_throttle_unreserve(spa_normal_class(zio->io_spa),
3574             1, pio);
3575
3576         /*
3577          * Call into the pipeline to see if there is more work that
3578          * needs to be done. If there is work to be done it will be
3579          * dispatched to another taskq thread.
3580          */
3581         zio_allocate_dispatch(zio->io_spa);
3582 }
3583
3584 static int
3585 zio_done(zio_t *zio)
3586 {
3587         spa_t *spa = zio->io_spa;
3588         zio_t *lio = zio->io_logical;
3589         blkptr_t *bp = zio->io_bp;
3590         vdev_t *vd = zio->io_vd;
3591         uint64_t psize = zio->io_size;
3592         zio_t *pio, *pio_next;
3593         metaslab_class_t *mc = spa_normal_class(spa);
3594         zio_link_t *zl = NULL;
3595
3596         /*
3597          * If our children haven't all completed,
3598          * wait for them and then repeat this pipeline stage.
3599          */
3600         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE) ||
3601             zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE) ||
3602             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE) ||
3603             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_DONE))
3604                 return (ZIO_PIPELINE_STOP);
3605
3606         /*
3607          * If the allocation throttle is enabled, then update the accounting.
3608          * We only track child I/Os that are part of an allocating async
3609          * write. We must do this since the allocation is performed
3610          * by the logical I/O but the actual write is done by child I/Os.
3611          */
3612         if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING &&
3613             zio->io_child_type == ZIO_CHILD_VDEV) {
3614                 ASSERT(mc->mc_alloc_throttle_enabled);
3615                 zio_dva_throttle_done(zio);
3616         }
3617
3618         /*
3619          * If the allocation throttle is enabled, verify that
3620          * we have decremented the refcounts for every I/O that was throttled.
3621          */
3622         if (zio->io_flags & ZIO_FLAG_IO_ALLOCATING) {
3623                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
3624                 ASSERT(zio->io_priority == ZIO_PRIORITY_ASYNC_WRITE);
3625                 ASSERT(bp != NULL);
3626                 metaslab_group_alloc_verify(spa, zio->io_bp, zio);
3627                 VERIFY(refcount_not_held(&mc->mc_alloc_slots, zio));
3628         }
3629
3630         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
3631                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
3632                         ASSERT(zio->io_children[c][w] == 0);
3633
3634         if (bp != NULL && !BP_IS_EMBEDDED(bp)) {
3635                 ASSERT(bp->blk_pad[0] == 0);
3636                 ASSERT(bp->blk_pad[1] == 0);
3637                 ASSERT(bcmp(bp, &zio->io_bp_copy, sizeof (blkptr_t)) == 0 ||
3638                     (bp == zio_unique_parent(zio)->io_bp));
3639                 if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(bp) &&
3640                     zio->io_bp_override == NULL &&
3641                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
3642                         ASSERT(!BP_SHOULD_BYTESWAP(bp));
3643                         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(bp));
3644                         ASSERT(BP_COUNT_GANG(bp) == 0 ||
3645                             (BP_COUNT_GANG(bp) == BP_GET_NDVAS(bp)));
3646                 }
3647                 if (zio->io_flags & ZIO_FLAG_NOPWRITE)
3648                         VERIFY(BP_EQUAL(bp, &zio->io_bp_orig));
3649         }
3650
3651         /*
3652          * If there were child vdev/gang/ddt errors, they apply to us now.
3653          */
3654         zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
3655         zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
3656         zio_inherit_child_errors(zio, ZIO_CHILD_DDT);
3657
3658         /*
3659          * If the I/O on the transformed data was successful, generate any
3660          * checksum reports now while we still have the transformed data.
3661          */
3662         if (zio->io_error == 0) {
3663                 while (zio->io_cksum_report != NULL) {
3664                         zio_cksum_report_t *zcr = zio->io_cksum_report;
3665                         uint64_t align = zcr->zcr_align;
3666                         uint64_t asize = P2ROUNDUP(psize, align);
3667                         char *abuf = zio->io_data;
3668
3669                         if (asize != psize) {
3670                                 abuf = zio_buf_alloc(asize);
3671                                 bcopy(zio->io_data, abuf, psize);
3672                                 bzero(abuf + psize, asize - psize);
3673                         }
3674
3675                         zio->io_cksum_report = zcr->zcr_next;
3676                         zcr->zcr_next = NULL;
3677                         zcr->zcr_finish(zcr, abuf);
3678                         zfs_ereport_free_checksum(zcr);
3679
3680                         if (asize != psize)
3681                                 zio_buf_free(abuf, asize);
3682                 }
3683         }
3684
3685         zio_pop_transforms(zio);        /* note: may set zio->io_error */
3686
3687         vdev_stat_update(zio, psize);
3688
3689         if (zio->io_error) {
3690                 /*
3691                  * If this I/O is attached to a particular vdev,
3692                  * generate an error message describing the I/O failure
3693                  * at the block level.  We ignore these errors if the
3694                  * device is currently unavailable.
3695                  */
3696                 if (zio->io_error != ECKSUM && vd != NULL && !vdev_is_dead(vd))
3697                         zfs_ereport_post(FM_EREPORT_ZFS_IO, spa, vd, zio, 0, 0);
3698
3699                 if ((zio->io_error == EIO || !(zio->io_flags &
3700                     (ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_PROPAGATE))) &&
3701                     zio == lio) {
3702                         /*
3703                          * For logical I/O requests, tell the SPA to log the
3704                          * error and generate a logical data ereport.
3705                          */
3706                         spa_log_error(spa, zio);
3707                         zfs_ereport_post(FM_EREPORT_ZFS_DATA, spa, NULL, zio,
3708                             0, 0);
3709                 }
3710         }
3711
3712         if (zio->io_error && zio == lio) {
3713                 /*
3714                  * Determine whether zio should be reexecuted.  This will
3715                  * propagate all the way to the root via zio_notify_parent().
3716                  */
3717                 ASSERT(vd == NULL && bp != NULL);
3718                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3719
3720                 if (IO_IS_ALLOCATING(zio) &&
3721                     !(zio->io_flags & ZIO_FLAG_CANFAIL)) {
3722                         if (zio->io_error != ENOSPC)
3723                                 zio->io_reexecute |= ZIO_REEXECUTE_NOW;
3724                         else
3725                                 zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
3726                 }
3727
3728                 if ((zio->io_type == ZIO_TYPE_READ ||
3729                     zio->io_type == ZIO_TYPE_FREE) &&
3730                     !(zio->io_flags & ZIO_FLAG_SCAN_THREAD) &&
3731                     zio->io_error == ENXIO &&
3732                     spa_load_state(spa) == SPA_LOAD_NONE &&
3733                     spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE)
3734                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
3735
3736                 if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
3737                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
3738
3739                 /*
3740                  * Here is a possibly good place to attempt to do
3741                  * either combinatorial reconstruction or error correction
3742                  * based on checksums.  It also might be a good place
3743                  * to send out preliminary ereports before we suspend
3744                  * processing.
3745                  */
3746         }
3747
3748         /*
3749          * If there were logical child errors, they apply to us now.
3750          * We defer this until now to avoid conflating logical child
3751          * errors with errors that happened to the zio itself when
3752          * updating vdev stats and reporting FMA events above.
3753          */
3754         zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
3755
3756         if ((zio->io_error || zio->io_reexecute) &&
3757             IO_IS_ALLOCATING(zio) && zio->io_gang_leader == zio &&
3758             !(zio->io_flags & (ZIO_FLAG_IO_REWRITE | ZIO_FLAG_NOPWRITE)))
3759                 zio_dva_unallocate(zio, zio->io_gang_tree, bp);
3760
3761         zio_gang_tree_free(&zio->io_gang_tree);
3762
3763         /*
3764          * Godfather I/Os should never suspend.
3765          */
3766         if ((zio->io_flags & ZIO_FLAG_GODFATHER) &&
3767             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND))
3768                 zio->io_reexecute = 0;
3769
3770         if (zio->io_reexecute) {
3771                 /*
3772                  * This is a logical I/O that wants to reexecute.
3773                  *
3774                  * Reexecute is top-down.  When an i/o fails, if it's not
3775                  * the root, it simply notifies its parent and sticks around.
3776                  * The parent, seeing that it still has children in zio_done(),
3777                  * does the same.  This percolates all the way up to the root.
3778                  * The root i/o will reexecute or suspend the entire tree.
3779                  *
3780                  * This approach ensures that zio_reexecute() honors
3781                  * all the original i/o dependency relationships, e.g.
3782                  * parents not executing until children are ready.
3783                  */
3784                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
3785
3786                 zio->io_gang_leader = NULL;
3787
3788                 mutex_enter(&zio->io_lock);
3789                 zio->io_state[ZIO_WAIT_DONE] = 1;
3790                 mutex_exit(&zio->io_lock);
3791
3792                 /*
3793                  * "The Godfather" I/O monitors its children but is
3794                  * not a true parent to them. It will track them through
3795                  * the pipeline but severs its ties whenever they get into
3796                  * trouble (e.g. suspended). This allows "The Godfather"
3797                  * I/O to return status without blocking.
3798                  */
3799                 zl = NULL;
3800                 for (pio = zio_walk_parents(zio, &zl); pio != NULL;
3801                     pio = pio_next) {
3802                         zio_link_t *remove_zl = zl;
3803                         pio_next = zio_walk_parents(zio, &zl);
3804
3805                         if ((pio->io_flags & ZIO_FLAG_GODFATHER) &&
3806                             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND)) {
3807                                 zio_remove_child(pio, zio, remove_zl);
3808                                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3809                         }
3810                 }
3811
3812                 if ((pio = zio_unique_parent(zio)) != NULL) {
3813                         /*
3814                          * We're not a root i/o, so there's nothing to do
3815                          * but notify our parent.  Don't propagate errors
3816                          * upward since we haven't permanently failed yet.
3817                          */
3818                         ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
3819                         zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
3820                         zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3821                 } else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
3822                         /*
3823                          * We'd fail again if we reexecuted now, so suspend
3824                          * until conditions improve (e.g. device comes online).
3825                          */
3826                         zio_suspend(spa, zio);
3827                 } else {
3828                         /*
3829                          * Reexecution is potentially a huge amount of work.
3830                          * Hand it off to the otherwise-unused claim taskq.
3831                          */
3832 #if defined(illumos) || !defined(_KERNEL)
3833                         ASSERT(zio->io_tqent.tqent_next == NULL);
3834 #else
3835                         ASSERT(zio->io_tqent.tqent_task.ta_pending == 0);
3836 #endif
3837                         spa_taskq_dispatch_ent(spa, ZIO_TYPE_CLAIM,
3838                             ZIO_TASKQ_ISSUE, (task_func_t *)zio_reexecute, zio,
3839                             0, &zio->io_tqent);
3840                 }
3841                 return (ZIO_PIPELINE_STOP);
3842         }
3843
3844         ASSERT(zio->io_child_count == 0);
3845         ASSERT(zio->io_reexecute == 0);
3846         ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
3847
3848         /*
3849          * Report any checksum errors, since the I/O is complete.
3850          */
3851         while (zio->io_cksum_report != NULL) {
3852                 zio_cksum_report_t *zcr = zio->io_cksum_report;
3853                 zio->io_cksum_report = zcr->zcr_next;
3854                 zcr->zcr_next = NULL;
3855                 zcr->zcr_finish(zcr, NULL);
3856                 zfs_ereport_free_checksum(zcr);
3857         }
3858
3859         /*
3860          * It is the responsibility of the done callback to ensure that this
3861          * particular zio is no longer discoverable for adoption, and as
3862          * such, cannot acquire any new parents.
3863          */
3864         if (zio->io_done)
3865                 zio->io_done(zio);
3866
3867         mutex_enter(&zio->io_lock);
3868         zio->io_state[ZIO_WAIT_DONE] = 1;
3869         mutex_exit(&zio->io_lock);
3870
3871         zl = NULL;
3872         for (pio = zio_walk_parents(zio, &zl); pio != NULL; pio = pio_next) {
3873                 zio_link_t *remove_zl = zl;
3874                 pio_next = zio_walk_parents(zio, &zl);
3875                 zio_remove_child(pio, zio, remove_zl);
3876                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3877         }
3878
3879         if (zio->io_waiter != NULL) {
3880                 mutex_enter(&zio->io_lock);
3881                 zio->io_executor = NULL;
3882                 cv_broadcast(&zio->io_cv);
3883                 mutex_exit(&zio->io_lock);
3884         } else {
3885                 zio_destroy(zio);
3886         }
3887
3888         return (ZIO_PIPELINE_STOP);
3889 }
3890
3891 /*
3892  * ==========================================================================
3893  * I/O pipeline definition
3894  * ==========================================================================
3895  */
3896 static zio_pipe_stage_t *zio_pipeline[] = {
3897         NULL,
3898         zio_read_bp_init,
3899         zio_write_bp_init,
3900         zio_free_bp_init,
3901         zio_issue_async,
3902         zio_write_compress,
3903         zio_checksum_generate,
3904         zio_nop_write,
3905         zio_ddt_read_start,
3906         zio_ddt_read_done,
3907         zio_ddt_write,
3908         zio_ddt_free,
3909         zio_gang_assemble,
3910         zio_gang_issue,
3911         zio_dva_throttle,
3912         zio_dva_allocate,
3913         zio_dva_free,
3914         zio_dva_claim,
3915         zio_ready,
3916         zio_vdev_io_start,
3917         zio_vdev_io_done,
3918         zio_vdev_io_assess,
3919         zio_checksum_verify,
3920         zio_done
3921 };
3922
3923
3924
3925
3926 /*
3927  * Compare two zbookmark_phys_t's to see which we would reach first in a
3928  * pre-order traversal of the object tree.
3929  *
3930  * This is simple in every case aside from the meta-dnode object. For all other
3931  * objects, we traverse them in order (object 1 before object 2, and so on).
3932  * However, all of these objects are traversed while traversing object 0, since
3933  * the data it points to is the list of objects.  Thus, we need to convert to a
3934  * canonical representation so we can compare meta-dnode bookmarks to
3935  * non-meta-dnode bookmarks.
3936  *
3937  * We do this by calculating "equivalents" for each field of the zbookmark.
3938  * zbookmarks outside of the meta-dnode use their own object and level, and
3939  * calculate the level 0 equivalent (the first L0 blkid that is contained in the
3940  * blocks this bookmark refers to) by multiplying their blkid by their span
3941  * (the number of L0 blocks contained within one block at their level).
3942  * zbookmarks inside the meta-dnode calculate their object equivalent
3943  * (which is L0equiv * dnodes per data block), use 0 for their L0equiv, and use
3944  * level + 1<<31 (any value larger than a level could ever be) for their level.
3945  * This causes them to always compare before a bookmark in their object
3946  * equivalent, compare appropriately to bookmarks in other objects, and to
3947  * compare appropriately to other bookmarks in the meta-dnode.
3948  */
3949 int
3950 zbookmark_compare(uint16_t dbss1, uint8_t ibs1, uint16_t dbss2, uint8_t ibs2,
3951     const zbookmark_phys_t *zb1, const zbookmark_phys_t *zb2)
3952 {
3953         /*
3954          * These variables represent the "equivalent" values for the zbookmark,
3955          * after converting zbookmarks inside the meta dnode to their
3956          * normal-object equivalents.
3957          */
3958         uint64_t zb1obj, zb2obj;
3959         uint64_t zb1L0, zb2L0;
3960         uint64_t zb1level, zb2level;
3961
3962         if (zb1->zb_object == zb2->zb_object &&
3963             zb1->zb_level == zb2->zb_level &&
3964             zb1->zb_blkid == zb2->zb_blkid)
3965                 return (0);
3966
3967         /*
3968          * BP_SPANB calculates the span in blocks.
3969          */
3970         zb1L0 = (zb1->zb_blkid) * BP_SPANB(ibs1, zb1->zb_level);
3971         zb2L0 = (zb2->zb_blkid) * BP_SPANB(ibs2, zb2->zb_level);
3972
3973         if (zb1->zb_object == DMU_META_DNODE_OBJECT) {
3974                 zb1obj = zb1L0 * (dbss1 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
3975                 zb1L0 = 0;
3976                 zb1level = zb1->zb_level + COMPARE_META_LEVEL;
3977         } else {
3978                 zb1obj = zb1->zb_object;
3979                 zb1level = zb1->zb_level;
3980         }
3981
3982         if (zb2->zb_object == DMU_META_DNODE_OBJECT) {
3983                 zb2obj = zb2L0 * (dbss2 << (SPA_MINBLOCKSHIFT - DNODE_SHIFT));
3984                 zb2L0 = 0;
3985                 zb2level = zb2->zb_level + COMPARE_META_LEVEL;
3986         } else {
3987                 zb2obj = zb2->zb_object;
3988                 zb2level = zb2->zb_level;
3989         }
3990
3991         /* Now that we have a canonical representation, do the comparison. */
3992         if (zb1obj != zb2obj)
3993                 return (zb1obj < zb2obj ? -1 : 1);
3994         else if (zb1L0 != zb2L0)
3995                 return (zb1L0 < zb2L0 ? -1 : 1);
3996         else if (zb1level != zb2level)
3997                 return (zb1level > zb2level ? -1 : 1);
3998         /*
3999          * This can (theoretically) happen if the bookmarks have the same object
4000          * and level, but different blkids, if the block sizes are not the same.
4001          * There is presently no way to change the indirect block sizes
4002          */
4003         return (0);
4004 }
4005
4006 /*
4007  *  This function checks the following: given that last_block is the place that
4008  *  our traversal stopped last time, does that guarantee that we've visited
4009  *  every node under subtree_root?  Therefore, we can't just use the raw output
4010  *  of zbookmark_compare.  We have to pass in a modified version of
4011  *  subtree_root; by incrementing the block id, and then checking whether
4012  *  last_block is before or equal to that, we can tell whether or not having
4013  *  visited last_block implies that all of subtree_root's children have been
4014  *  visited.
4015  */
4016 boolean_t
4017 zbookmark_subtree_completed(const dnode_phys_t *dnp,
4018     const zbookmark_phys_t *subtree_root, const zbookmark_phys_t *last_block)
4019 {
4020         zbookmark_phys_t mod_zb = *subtree_root;
4021         mod_zb.zb_blkid++;
4022         ASSERT(last_block->zb_level == 0);
4023
4024         /* The objset_phys_t isn't before anything. */
4025         if (dnp == NULL)
4026                 return (B_FALSE);
4027
4028         /*
4029          * We pass in 1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT) for the
4030          * data block size in sectors, because that variable is only used if
4031          * the bookmark refers to a block in the meta-dnode.  Since we don't
4032          * know without examining it what object it refers to, and there's no
4033          * harm in passing in this value in other cases, we always pass it in.
4034          *
4035          * We pass in 0 for the indirect block size shift because zb2 must be
4036          * level 0.  The indirect block size is only used to calculate the span
4037          * of the bookmark, but since the bookmark must be level 0, the span is
4038          * always 1, so the math works out.
4039          *
4040          * If you make changes to how the zbookmark_compare code works, be sure
4041          * to make sure that this code still works afterwards.
4042          */
4043         return (zbookmark_compare(dnp->dn_datablkszsec, dnp->dn_indblkshift,
4044             1ULL << (DNODE_BLOCK_SHIFT - SPA_MINBLOCKSHIFT), 0, &mod_zb,
4045             last_block) <= 0);
4046 }