]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c
Import libc++ trunk r165949. Among other improvements and bug fixes,
[FreeBSD/FreeBSD.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) 2012 by Delphix. All rights reserved.
24  */
25
26 #include <sys/zfs_context.h>
27 #include <sys/fm/fs/zfs.h>
28 #include <sys/spa.h>
29 #include <sys/txg.h>
30 #include <sys/spa_impl.h>
31 #include <sys/vdev_impl.h>
32 #include <sys/zio_impl.h>
33 #include <sys/zio_compress.h>
34 #include <sys/zio_checksum.h>
35 #include <sys/dmu_objset.h>
36 #include <sys/arc.h>
37 #include <sys/ddt.h>
38 #include <sys/trim_map.h>
39
40 SYSCTL_DECL(_vfs_zfs);
41 SYSCTL_NODE(_vfs_zfs, OID_AUTO, zio, CTLFLAG_RW, 0, "ZFS ZIO");
42 static int zio_use_uma = 0;
43 TUNABLE_INT("vfs.zfs.zio.use_uma", &zio_use_uma);
44 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, use_uma, CTLFLAG_RDTUN, &zio_use_uma, 0,
45     "Use uma(9) for ZIO allocations");
46 static int zio_exclude_metadata = 0;
47 TUNABLE_INT("vfs.zfs.zio.exclude_metadata", &zio_exclude_metadata);
48 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, exclude_metadata, CTLFLAG_RDTUN, &zio_exclude_metadata, 0,
49     "Exclude metadata buffers from dumps as well");
50
51 /*
52  * See zio.h for more information about these fields.
53  */
54 zio_trim_stats_t zio_trim_stats = {
55         { "zio_trim_bytes",             KSTAT_DATA_UINT64 },
56         { "zio_trim_success",           KSTAT_DATA_UINT64 },
57         { "zio_trim_unsupported",       KSTAT_DATA_UINT64 },
58         { "zio_trim_failed",            KSTAT_DATA_UINT64 },
59 };
60
61 static kstat_t *zio_trim_ksp;
62
63 /*
64  * ==========================================================================
65  * I/O priority table
66  * ==========================================================================
67  */
68 uint8_t zio_priority_table[ZIO_PRIORITY_TABLE_SIZE] = {
69         0,      /* ZIO_PRIORITY_NOW             */
70         0,      /* ZIO_PRIORITY_SYNC_READ       */
71         0,      /* ZIO_PRIORITY_SYNC_WRITE      */
72         0,      /* ZIO_PRIORITY_LOG_WRITE       */
73         1,      /* ZIO_PRIORITY_CACHE_FILL      */
74         1,      /* ZIO_PRIORITY_AGG             */
75         4,      /* ZIO_PRIORITY_FREE            */
76         4,      /* ZIO_PRIORITY_ASYNC_WRITE     */
77         6,      /* ZIO_PRIORITY_ASYNC_READ      */
78         10,     /* ZIO_PRIORITY_RESILVER        */
79         20,     /* ZIO_PRIORITY_SCRUB           */
80         2,      /* ZIO_PRIORITY_DDT_PREFETCH    */
81         30,     /* ZIO_PRIORITY_TRIM            */
82 };
83
84 /*
85  * ==========================================================================
86  * I/O type descriptions
87  * ==========================================================================
88  */
89 char *zio_type_name[ZIO_TYPES] = {
90         "zio_null", "zio_read", "zio_write", "zio_free", "zio_claim",
91         "zio_ioctl"
92 };
93
94 /*
95  * ==========================================================================
96  * I/O kmem caches
97  * ==========================================================================
98  */
99 kmem_cache_t *zio_cache;
100 kmem_cache_t *zio_link_cache;
101 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
102 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
103
104 #ifdef _KERNEL
105 extern vmem_t *zio_alloc_arena;
106 #endif
107 extern int zfs_mg_alloc_failures;
108
109 /*
110  * An allocating zio is one that either currently has the DVA allocate
111  * stage set or will have it later in its lifetime.
112  */
113 #define IO_IS_ALLOCATING(zio) ((zio)->io_orig_pipeline & ZIO_STAGE_DVA_ALLOCATE)
114
115 boolean_t       zio_requeue_io_start_cut_in_line = B_TRUE;
116
117 #ifdef ZFS_DEBUG
118 int zio_buf_debug_limit = 16384;
119 #else
120 int zio_buf_debug_limit = 0;
121 #endif
122
123 void
124 zio_init(void)
125 {
126         size_t c;
127         zio_cache = kmem_cache_create("zio_cache",
128             sizeof (zio_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
129         zio_link_cache = kmem_cache_create("zio_link_cache",
130             sizeof (zio_link_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
131
132         /*
133          * For small buffers, we want a cache for each multiple of
134          * SPA_MINBLOCKSIZE.  For medium-size buffers, we want a cache
135          * for each quarter-power of 2.  For large buffers, we want
136          * a cache for each multiple of PAGESIZE.
137          */
138         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
139                 size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
140                 size_t p2 = size;
141                 size_t align = 0;
142                 size_t cflags = (size > zio_buf_debug_limit) ? KMC_NODEBUG : 0;
143
144                 while (p2 & (p2 - 1))
145                         p2 &= p2 - 1;
146
147 #ifdef illumos
148 #ifndef _KERNEL
149                 /*
150                  * If we are using watchpoints, put each buffer on its own page,
151                  * to eliminate the performance overhead of trapping to the
152                  * kernel when modifying a non-watched buffer that shares the
153                  * page with a watched buffer.
154                  */
155                 if (arc_watch && !IS_P2ALIGNED(size, PAGESIZE))
156                         continue;
157 #endif
158 #endif /* illumos */
159                 if (size <= 4 * SPA_MINBLOCKSIZE) {
160                         align = SPA_MINBLOCKSIZE;
161                 } else if (IS_P2ALIGNED(size, PAGESIZE)) {
162                         align = PAGESIZE;
163                 } else if (IS_P2ALIGNED(size, p2 >> 2)) {
164                         align = p2 >> 2;
165                 }
166
167                 if (align != 0) {
168                         char name[36];
169                         (void) sprintf(name, "zio_buf_%lu", (ulong_t)size);
170                         zio_buf_cache[c] = kmem_cache_create(name, size,
171                             align, NULL, NULL, NULL, NULL, NULL, cflags);
172
173                         /*
174                          * Since zio_data bufs do not appear in crash dumps, we
175                          * pass KMC_NOTOUCH so that no allocator metadata is
176                          * stored with the buffers.
177                          */
178                         (void) sprintf(name, "zio_data_buf_%lu", (ulong_t)size);
179                         zio_data_buf_cache[c] = kmem_cache_create(name, size,
180                             align, NULL, NULL, NULL, NULL, NULL,
181                             cflags | KMC_NOTOUCH | KMC_NODEBUG);
182                 }
183         }
184
185         while (--c != 0) {
186                 ASSERT(zio_buf_cache[c] != NULL);
187                 if (zio_buf_cache[c - 1] == NULL)
188                         zio_buf_cache[c - 1] = zio_buf_cache[c];
189
190                 ASSERT(zio_data_buf_cache[c] != NULL);
191                 if (zio_data_buf_cache[c - 1] == NULL)
192                         zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
193         }
194
195         /*
196          * The zio write taskqs have 1 thread per cpu, allow 1/2 of the taskqs
197          * to fail 3 times per txg or 8 failures, whichever is greater.
198          */
199         if (zfs_mg_alloc_failures == 0)
200                 zfs_mg_alloc_failures = MAX((3 * max_ncpus / 2), 8);
201         else if (zfs_mg_alloc_failures < 8)
202                 zfs_mg_alloc_failures = 8;
203
204         zio_inject_init();
205
206         zio_trim_ksp = kstat_create("zfs", 0, "zio_trim", "misc",
207             KSTAT_TYPE_NAMED,
208             sizeof(zio_trim_stats) / sizeof(kstat_named_t),
209             KSTAT_FLAG_VIRTUAL);
210
211         if (zio_trim_ksp != NULL) {
212                 zio_trim_ksp->ks_data = &zio_trim_stats;
213                 kstat_install(zio_trim_ksp);
214         }
215 }
216
217 void
218 zio_fini(void)
219 {
220         size_t c;
221         kmem_cache_t *last_cache = NULL;
222         kmem_cache_t *last_data_cache = NULL;
223
224         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
225                 if (zio_buf_cache[c] != last_cache) {
226                         last_cache = zio_buf_cache[c];
227                         kmem_cache_destroy(zio_buf_cache[c]);
228                 }
229                 zio_buf_cache[c] = NULL;
230
231                 if (zio_data_buf_cache[c] != last_data_cache) {
232                         last_data_cache = zio_data_buf_cache[c];
233                         kmem_cache_destroy(zio_data_buf_cache[c]);
234                 }
235                 zio_data_buf_cache[c] = NULL;
236         }
237
238         kmem_cache_destroy(zio_link_cache);
239         kmem_cache_destroy(zio_cache);
240
241         zio_inject_fini();
242
243         if (zio_trim_ksp != NULL) {
244                 kstat_delete(zio_trim_ksp);
245                 zio_trim_ksp = NULL;
246         }
247 }
248
249 /*
250  * ==========================================================================
251  * Allocate and free I/O buffers
252  * ==========================================================================
253  */
254
255 /*
256  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
257  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
258  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
259  * excess / transient data in-core during a crashdump.
260  */
261 void *
262 zio_buf_alloc(size_t size)
263 {
264         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
265         int flags = zio_exclude_metadata ? KM_NODEBUG : 0;
266
267         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
268
269         if (zio_use_uma)
270                 return (kmem_cache_alloc(zio_buf_cache[c], KM_PUSHPAGE));
271         else
272                 return (kmem_alloc(size, KM_SLEEP|flags));
273 }
274
275 /*
276  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
277  * crashdump if the kernel panics.  This exists so that we will limit the amount
278  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
279  * of kernel heap dumped to disk when the kernel panics)
280  */
281 void *
282 zio_data_buf_alloc(size_t size)
283 {
284         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
285
286         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
287
288         if (zio_use_uma)
289                 return (kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE));
290         else
291                 return (kmem_alloc(size, KM_SLEEP | KM_NODEBUG));
292 }
293
294 void
295 zio_buf_free(void *buf, size_t size)
296 {
297         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
298
299         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
300
301         if (zio_use_uma)
302                 kmem_cache_free(zio_buf_cache[c], buf);
303         else
304                 kmem_free(buf, size);
305 }
306
307 void
308 zio_data_buf_free(void *buf, size_t size)
309 {
310         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
311
312         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
313
314         if (zio_use_uma)
315                 kmem_cache_free(zio_data_buf_cache[c], buf);
316         else
317                 kmem_free(buf, size);
318 }
319
320 /*
321  * ==========================================================================
322  * Push and pop I/O transform buffers
323  * ==========================================================================
324  */
325 static void
326 zio_push_transform(zio_t *zio, void *data, uint64_t size, uint64_t bufsize,
327         zio_transform_func_t *transform)
328 {
329         zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
330
331         zt->zt_orig_data = zio->io_data;
332         zt->zt_orig_size = zio->io_size;
333         zt->zt_bufsize = bufsize;
334         zt->zt_transform = transform;
335
336         zt->zt_next = zio->io_transform_stack;
337         zio->io_transform_stack = zt;
338
339         zio->io_data = data;
340         zio->io_size = size;
341 }
342
343 static void
344 zio_pop_transforms(zio_t *zio)
345 {
346         zio_transform_t *zt;
347
348         while ((zt = zio->io_transform_stack) != NULL) {
349                 if (zt->zt_transform != NULL)
350                         zt->zt_transform(zio,
351                             zt->zt_orig_data, zt->zt_orig_size);
352
353                 if (zt->zt_bufsize != 0)
354                         zio_buf_free(zio->io_data, zt->zt_bufsize);
355
356                 zio->io_data = zt->zt_orig_data;
357                 zio->io_size = zt->zt_orig_size;
358                 zio->io_transform_stack = zt->zt_next;
359
360                 kmem_free(zt, sizeof (zio_transform_t));
361         }
362 }
363
364 /*
365  * ==========================================================================
366  * I/O transform callbacks for subblocks and decompression
367  * ==========================================================================
368  */
369 static void
370 zio_subblock(zio_t *zio, void *data, uint64_t size)
371 {
372         ASSERT(zio->io_size > size);
373
374         if (zio->io_type == ZIO_TYPE_READ)
375                 bcopy(zio->io_data, data, size);
376 }
377
378 static void
379 zio_decompress(zio_t *zio, void *data, uint64_t size)
380 {
381         if (zio->io_error == 0 &&
382             zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
383             zio->io_data, data, zio->io_size, size) != 0)
384                 zio->io_error = EIO;
385 }
386
387 /*
388  * ==========================================================================
389  * I/O parent/child relationships and pipeline interlocks
390  * ==========================================================================
391  */
392 /*
393  * NOTE - Callers to zio_walk_parents() and zio_walk_children must
394  *        continue calling these functions until they return NULL.
395  *        Otherwise, the next caller will pick up the list walk in
396  *        some indeterminate state.  (Otherwise every caller would
397  *        have to pass in a cookie to keep the state represented by
398  *        io_walk_link, which gets annoying.)
399  */
400 zio_t *
401 zio_walk_parents(zio_t *cio)
402 {
403         zio_link_t *zl = cio->io_walk_link;
404         list_t *pl = &cio->io_parent_list;
405
406         zl = (zl == NULL) ? list_head(pl) : list_next(pl, zl);
407         cio->io_walk_link = zl;
408
409         if (zl == NULL)
410                 return (NULL);
411
412         ASSERT(zl->zl_child == cio);
413         return (zl->zl_parent);
414 }
415
416 zio_t *
417 zio_walk_children(zio_t *pio)
418 {
419         zio_link_t *zl = pio->io_walk_link;
420         list_t *cl = &pio->io_child_list;
421
422         zl = (zl == NULL) ? list_head(cl) : list_next(cl, zl);
423         pio->io_walk_link = zl;
424
425         if (zl == NULL)
426                 return (NULL);
427
428         ASSERT(zl->zl_parent == pio);
429         return (zl->zl_child);
430 }
431
432 zio_t *
433 zio_unique_parent(zio_t *cio)
434 {
435         zio_t *pio = zio_walk_parents(cio);
436
437         VERIFY(zio_walk_parents(cio) == NULL);
438         return (pio);
439 }
440
441 void
442 zio_add_child(zio_t *pio, zio_t *cio)
443 {
444         zio_link_t *zl = kmem_cache_alloc(zio_link_cache, KM_SLEEP);
445
446         /*
447          * Logical I/Os can have logical, gang, or vdev children.
448          * Gang I/Os can have gang or vdev children.
449          * Vdev I/Os can only have vdev children.
450          * The following ASSERT captures all of these constraints.
451          */
452         ASSERT(cio->io_child_type <= pio->io_child_type);
453
454         zl->zl_parent = pio;
455         zl->zl_child = cio;
456
457         mutex_enter(&cio->io_lock);
458         mutex_enter(&pio->io_lock);
459
460         ASSERT(pio->io_state[ZIO_WAIT_DONE] == 0);
461
462         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
463                 pio->io_children[cio->io_child_type][w] += !cio->io_state[w];
464
465         list_insert_head(&pio->io_child_list, zl);
466         list_insert_head(&cio->io_parent_list, zl);
467
468         pio->io_child_count++;
469         cio->io_parent_count++;
470
471         mutex_exit(&pio->io_lock);
472         mutex_exit(&cio->io_lock);
473 }
474
475 static void
476 zio_remove_child(zio_t *pio, zio_t *cio, zio_link_t *zl)
477 {
478         ASSERT(zl->zl_parent == pio);
479         ASSERT(zl->zl_child == cio);
480
481         mutex_enter(&cio->io_lock);
482         mutex_enter(&pio->io_lock);
483
484         list_remove(&pio->io_child_list, zl);
485         list_remove(&cio->io_parent_list, zl);
486
487         pio->io_child_count--;
488         cio->io_parent_count--;
489
490         mutex_exit(&pio->io_lock);
491         mutex_exit(&cio->io_lock);
492
493         kmem_cache_free(zio_link_cache, zl);
494 }
495
496 static boolean_t
497 zio_wait_for_children(zio_t *zio, enum zio_child child, enum zio_wait_type wait)
498 {
499         uint64_t *countp = &zio->io_children[child][wait];
500         boolean_t waiting = B_FALSE;
501
502         mutex_enter(&zio->io_lock);
503         ASSERT(zio->io_stall == NULL);
504         if (*countp != 0) {
505                 zio->io_stage >>= 1;
506                 zio->io_stall = countp;
507                 waiting = B_TRUE;
508         }
509         mutex_exit(&zio->io_lock);
510
511         return (waiting);
512 }
513
514 static void
515 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait)
516 {
517         uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
518         int *errorp = &pio->io_child_error[zio->io_child_type];
519
520         mutex_enter(&pio->io_lock);
521         if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
522                 *errorp = zio_worst_error(*errorp, zio->io_error);
523         pio->io_reexecute |= zio->io_reexecute;
524         ASSERT3U(*countp, >, 0);
525         if (--*countp == 0 && pio->io_stall == countp) {
526                 pio->io_stall = NULL;
527                 mutex_exit(&pio->io_lock);
528                 zio_execute(pio);
529         } else {
530                 mutex_exit(&pio->io_lock);
531         }
532 }
533
534 static void
535 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
536 {
537         if (zio->io_child_error[c] != 0 && zio->io_error == 0)
538                 zio->io_error = zio->io_child_error[c];
539 }
540
541 /*
542  * ==========================================================================
543  * Create the various types of I/O (read, write, free, etc)
544  * ==========================================================================
545  */
546 static zio_t *
547 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
548     void *data, uint64_t size, zio_done_func_t *done, void *private,
549     zio_type_t type, int priority, enum zio_flag flags,
550     vdev_t *vd, uint64_t offset, const zbookmark_t *zb,
551     enum zio_stage stage, enum zio_stage pipeline)
552 {
553         zio_t *zio;
554
555         ASSERT3U(type == ZIO_TYPE_FREE || size, <=, SPA_MAXBLOCKSIZE);
556         ASSERT(P2PHASE(size, SPA_MINBLOCKSIZE) == 0);
557         ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
558
559         ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
560         ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
561         ASSERT(vd || stage == ZIO_STAGE_OPEN);
562
563         zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
564         bzero(zio, sizeof (zio_t));
565
566         mutex_init(&zio->io_lock, NULL, MUTEX_DEFAULT, NULL);
567         cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
568
569         list_create(&zio->io_parent_list, sizeof (zio_link_t),
570             offsetof(zio_link_t, zl_parent_node));
571         list_create(&zio->io_child_list, sizeof (zio_link_t),
572             offsetof(zio_link_t, zl_child_node));
573
574         if (vd != NULL)
575                 zio->io_child_type = ZIO_CHILD_VDEV;
576         else if (flags & ZIO_FLAG_GANG_CHILD)
577                 zio->io_child_type = ZIO_CHILD_GANG;
578         else if (flags & ZIO_FLAG_DDT_CHILD)
579                 zio->io_child_type = ZIO_CHILD_DDT;
580         else
581                 zio->io_child_type = ZIO_CHILD_LOGICAL;
582
583         if (bp != NULL) {
584                 zio->io_bp = (blkptr_t *)bp;
585                 zio->io_bp_copy = *bp;
586                 zio->io_bp_orig = *bp;
587                 if (type != ZIO_TYPE_WRITE ||
588                     zio->io_child_type == ZIO_CHILD_DDT)
589                         zio->io_bp = &zio->io_bp_copy;  /* so caller can free */
590                 if (zio->io_child_type == ZIO_CHILD_LOGICAL)
591                         zio->io_logical = zio;
592                 if (zio->io_child_type > ZIO_CHILD_GANG && BP_IS_GANG(bp))
593                         pipeline |= ZIO_GANG_STAGES;
594         }
595
596         zio->io_spa = spa;
597         zio->io_txg = txg;
598         zio->io_done = done;
599         zio->io_private = private;
600         zio->io_type = type;
601         zio->io_priority = priority;
602         zio->io_vd = vd;
603         zio->io_offset = offset;
604         zio->io_orig_data = zio->io_data = data;
605         zio->io_orig_size = zio->io_size = size;
606         zio->io_orig_flags = zio->io_flags = flags;
607         zio->io_orig_stage = zio->io_stage = stage;
608         zio->io_orig_pipeline = zio->io_pipeline = pipeline;
609
610         zio->io_state[ZIO_WAIT_READY] = (stage >= ZIO_STAGE_READY);
611         zio->io_state[ZIO_WAIT_DONE] = (stage >= ZIO_STAGE_DONE);
612
613         if (zb != NULL)
614                 zio->io_bookmark = *zb;
615
616         if (pio != NULL) {
617                 if (zio->io_logical == NULL)
618                         zio->io_logical = pio->io_logical;
619                 if (zio->io_child_type == ZIO_CHILD_GANG)
620                         zio->io_gang_leader = pio->io_gang_leader;
621                 zio_add_child(pio, zio);
622         }
623
624         return (zio);
625 }
626
627 static void
628 zio_destroy(zio_t *zio)
629 {
630         list_destroy(&zio->io_parent_list);
631         list_destroy(&zio->io_child_list);
632         mutex_destroy(&zio->io_lock);
633         cv_destroy(&zio->io_cv);
634         kmem_cache_free(zio_cache, zio);
635 }
636
637 zio_t *
638 zio_null(zio_t *pio, spa_t *spa, vdev_t *vd, zio_done_func_t *done,
639     void *private, enum zio_flag flags)
640 {
641         zio_t *zio;
642
643         zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
644             ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, vd, 0, NULL,
645             ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
646
647         return (zio);
648 }
649
650 zio_t *
651 zio_root(spa_t *spa, zio_done_func_t *done, void *private, enum zio_flag flags)
652 {
653         return (zio_null(NULL, spa, NULL, done, private, flags));
654 }
655
656 zio_t *
657 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
658     void *data, uint64_t size, zio_done_func_t *done, void *private,
659     int priority, enum zio_flag flags, const zbookmark_t *zb)
660 {
661         zio_t *zio;
662
663         zio = zio_create(pio, spa, BP_PHYSICAL_BIRTH(bp), bp,
664             data, size, done, private,
665             ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
666             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
667             ZIO_DDT_CHILD_READ_PIPELINE : ZIO_READ_PIPELINE);
668
669         return (zio);
670 }
671
672 zio_t *
673 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
674     void *data, uint64_t size, const zio_prop_t *zp,
675     zio_done_func_t *ready, zio_done_func_t *done, void *private,
676     int priority, enum zio_flag flags, const zbookmark_t *zb)
677 {
678         zio_t *zio;
679
680         ASSERT(zp->zp_checksum >= ZIO_CHECKSUM_OFF &&
681             zp->zp_checksum < ZIO_CHECKSUM_FUNCTIONS &&
682             zp->zp_compress >= ZIO_COMPRESS_OFF &&
683             zp->zp_compress < ZIO_COMPRESS_FUNCTIONS &&
684             DMU_OT_IS_VALID(zp->zp_type) &&
685             zp->zp_level < 32 &&
686             zp->zp_copies > 0 &&
687             zp->zp_copies <= spa_max_replication(spa) &&
688             zp->zp_dedup <= 1 &&
689             zp->zp_dedup_verify <= 1);
690
691         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
692             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
693             ZIO_STAGE_OPEN, (flags & ZIO_FLAG_DDT_CHILD) ?
694             ZIO_DDT_CHILD_WRITE_PIPELINE : ZIO_WRITE_PIPELINE);
695
696         zio->io_ready = ready;
697         zio->io_prop = *zp;
698
699         return (zio);
700 }
701
702 zio_t *
703 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, void *data,
704     uint64_t size, zio_done_func_t *done, void *private, int priority,
705     enum zio_flag flags, zbookmark_t *zb)
706 {
707         zio_t *zio;
708
709         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
710             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
711             ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
712
713         return (zio);
714 }
715
716 void
717 zio_write_override(zio_t *zio, blkptr_t *bp, int copies)
718 {
719         ASSERT(zio->io_type == ZIO_TYPE_WRITE);
720         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
721         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
722         ASSERT(zio->io_txg == spa_syncing_txg(zio->io_spa));
723
724         zio->io_prop.zp_copies = copies;
725         zio->io_bp_override = bp;
726 }
727
728 void
729 zio_free(spa_t *spa, uint64_t txg, const blkptr_t *bp)
730 {
731         bplist_append(&spa->spa_free_bplist[txg & TXG_MASK], bp);
732 }
733
734 zio_t *
735 zio_free_sync(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
736     uint64_t size, enum zio_flag flags)
737 {
738         zio_t *zio;
739
740         dprintf_bp(bp, "freeing in txg %llu, pass %u",
741             (longlong_t)txg, spa->spa_sync_pass);
742
743         ASSERT(!BP_IS_HOLE(bp));
744         ASSERT(spa_syncing_txg(spa) == txg);
745         ASSERT(spa_sync_pass(spa) <= SYNC_PASS_DEFERRED_FREE);
746
747         zio = zio_create(pio, spa, txg, bp, NULL, size,
748             NULL, NULL, ZIO_TYPE_FREE, ZIO_PRIORITY_FREE, flags,
749             NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_FREE_PIPELINE);
750
751         return (zio);
752 }
753
754 zio_t *
755 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, const blkptr_t *bp,
756     zio_done_func_t *done, void *private, enum zio_flag flags)
757 {
758         zio_t *zio;
759
760         /*
761          * A claim is an allocation of a specific block.  Claims are needed
762          * to support immediate writes in the intent log.  The issue is that
763          * immediate writes contain committed data, but in a txg that was
764          * *not* committed.  Upon opening the pool after an unclean shutdown,
765          * the intent log claims all blocks that contain immediate write data
766          * so that the SPA knows they're in use.
767          *
768          * All claims *must* be resolved in the first txg -- before the SPA
769          * starts allocating blocks -- so that nothing is allocated twice.
770          * If txg == 0 we just verify that the block is claimable.
771          */
772         ASSERT3U(spa->spa_uberblock.ub_rootbp.blk_birth, <, spa_first_txg(spa));
773         ASSERT(txg == spa_first_txg(spa) || txg == 0);
774         ASSERT(!BP_GET_DEDUP(bp) || !spa_writeable(spa));       /* zdb(1M) */
775
776         zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
777             done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW, flags,
778             NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
779
780         return (zio);
781 }
782
783 zio_t *
784 zio_ioctl(zio_t *pio, spa_t *spa, vdev_t *vd, int cmd, uint64_t offset,
785     uint64_t size, zio_done_func_t *done, void *private, int priority,
786     enum zio_flag flags)
787 {
788         zio_t *zio;
789         int c;
790
791         if (vd->vdev_children == 0) {
792                 zio = zio_create(pio, spa, 0, NULL, NULL, size, done, private,
793                     ZIO_TYPE_IOCTL, priority, flags, vd, offset, NULL,
794                     ZIO_STAGE_OPEN, ZIO_IOCTL_PIPELINE);
795
796                 zio->io_cmd = cmd;
797         } else {
798                 zio = zio_null(pio, spa, NULL, NULL, NULL, flags);
799
800                 for (c = 0; c < vd->vdev_children; c++)
801                         zio_nowait(zio_ioctl(zio, spa, vd->vdev_child[c], cmd,
802                             offset, size, done, private, priority, flags));
803         }
804
805         return (zio);
806 }
807
808 zio_t *
809 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
810     void *data, int checksum, zio_done_func_t *done, void *private,
811     int priority, enum zio_flag flags, boolean_t labels)
812 {
813         zio_t *zio;
814
815         ASSERT(vd->vdev_children == 0);
816         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
817             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
818         ASSERT3U(offset + size, <=, vd->vdev_psize);
819
820         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
821             ZIO_TYPE_READ, priority, flags, vd, offset, NULL,
822             ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
823
824         zio->io_prop.zp_checksum = checksum;
825
826         return (zio);
827 }
828
829 zio_t *
830 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
831     void *data, int checksum, zio_done_func_t *done, void *private,
832     int priority, enum zio_flag flags, boolean_t labels)
833 {
834         zio_t *zio;
835
836         ASSERT(vd->vdev_children == 0);
837         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
838             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
839         ASSERT3U(offset + size, <=, vd->vdev_psize);
840
841         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
842             ZIO_TYPE_WRITE, priority, flags, vd, offset, NULL,
843             ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
844
845         zio->io_prop.zp_checksum = checksum;
846
847         if (zio_checksum_table[checksum].ci_eck) {
848                 /*
849                  * zec checksums are necessarily destructive -- they modify
850                  * the end of the write buffer to hold the verifier/checksum.
851                  * Therefore, we must make a local copy in case the data is
852                  * being written to multiple places in parallel.
853                  */
854                 void *wbuf = zio_buf_alloc(size);
855                 bcopy(data, wbuf, size);
856                 zio_push_transform(zio, wbuf, size, size, NULL);
857         }
858
859         return (zio);
860 }
861
862 /*
863  * Create a child I/O to do some work for us.
864  */
865 zio_t *
866 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
867         void *data, uint64_t size, int type, int priority, enum zio_flag flags,
868         zio_done_func_t *done, void *private)
869 {
870         enum zio_stage pipeline = ZIO_VDEV_CHILD_PIPELINE;
871         zio_t *zio;
872
873         ASSERT(vd->vdev_parent ==
874             (pio->io_vd ? pio->io_vd : pio->io_spa->spa_root_vdev));
875
876         if (type == ZIO_TYPE_READ && bp != NULL) {
877                 /*
878                  * If we have the bp, then the child should perform the
879                  * checksum and the parent need not.  This pushes error
880                  * detection as close to the leaves as possible and
881                  * eliminates redundant checksums in the interior nodes.
882                  */
883                 pipeline |= ZIO_STAGE_CHECKSUM_VERIFY;
884                 pio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
885         }
886
887         if (vd->vdev_children == 0)
888                 offset += VDEV_LABEL_START_SIZE;
889
890         flags |= ZIO_VDEV_CHILD_FLAGS(pio) | ZIO_FLAG_DONT_PROPAGATE;
891
892         /*
893          * If we've decided to do a repair, the write is not speculative --
894          * even if the original read was.
895          */
896         if (flags & ZIO_FLAG_IO_REPAIR)
897                 flags &= ~ZIO_FLAG_SPECULATIVE;
898
899         zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size,
900             done, private, type, priority, flags, vd, offset, &pio->io_bookmark,
901             ZIO_STAGE_VDEV_IO_START >> 1, pipeline);
902
903         return (zio);
904 }
905
906 zio_t *
907 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, void *data, uint64_t size,
908         int type, int priority, enum zio_flag flags,
909         zio_done_func_t *done, void *private)
910 {
911         zio_t *zio;
912
913         ASSERT(vd->vdev_ops->vdev_op_leaf);
914
915         zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
916             data, size, done, private, type, priority,
917             flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY,
918             vd, offset, NULL,
919             ZIO_STAGE_VDEV_IO_START >> 1, ZIO_VDEV_CHILD_PIPELINE);
920
921         return (zio);
922 }
923
924 void
925 zio_flush(zio_t *zio, vdev_t *vd)
926 {
927         zio_nowait(zio_ioctl(zio, zio->io_spa, vd, DKIOCFLUSHWRITECACHE, 0, 0,
928             NULL, NULL, ZIO_PRIORITY_NOW,
929             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY));
930 }
931
932 zio_t *
933 zio_trim(zio_t *zio, spa_t *spa, vdev_t *vd, uint64_t offset, uint64_t size)
934 {
935
936         ASSERT(vd->vdev_ops->vdev_op_leaf);
937
938         return zio_ioctl(zio, spa, vd, DKIOCTRIM, offset, size,
939             NULL, NULL, ZIO_PRIORITY_TRIM,
940             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY);
941 }
942
943 void
944 zio_shrink(zio_t *zio, uint64_t size)
945 {
946         ASSERT(zio->io_executor == NULL);
947         ASSERT(zio->io_orig_size == zio->io_size);
948         ASSERT(size <= zio->io_size);
949
950         /*
951          * We don't shrink for raidz because of problems with the
952          * reconstruction when reading back less than the block size.
953          * Note, BP_IS_RAIDZ() assumes no compression.
954          */
955         ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
956         if (!BP_IS_RAIDZ(zio->io_bp))
957                 zio->io_orig_size = zio->io_size = size;
958 }
959
960 /*
961  * ==========================================================================
962  * Prepare to read and write logical blocks
963  * ==========================================================================
964  */
965
966 static int
967 zio_read_bp_init(zio_t *zio)
968 {
969         blkptr_t *bp = zio->io_bp;
970
971         if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF &&
972             zio->io_child_type == ZIO_CHILD_LOGICAL &&
973             !(zio->io_flags & ZIO_FLAG_RAW)) {
974                 uint64_t psize = BP_GET_PSIZE(bp);
975                 void *cbuf = zio_buf_alloc(psize);
976
977                 zio_push_transform(zio, cbuf, psize, psize, zio_decompress);
978         }
979
980         if (!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)) && BP_GET_LEVEL(bp) == 0)
981                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
982
983         if (BP_GET_TYPE(bp) == DMU_OT_DDT_ZAP)
984                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
985
986         if (BP_GET_DEDUP(bp) && zio->io_child_type == ZIO_CHILD_LOGICAL)
987                 zio->io_pipeline = ZIO_DDT_READ_PIPELINE;
988
989         return (ZIO_PIPELINE_CONTINUE);
990 }
991
992 static int
993 zio_write_bp_init(zio_t *zio)
994 {
995         spa_t *spa = zio->io_spa;
996         zio_prop_t *zp = &zio->io_prop;
997         enum zio_compress compress = zp->zp_compress;
998         blkptr_t *bp = zio->io_bp;
999         uint64_t lsize = zio->io_size;
1000         uint64_t psize = lsize;
1001         int pass = 1;
1002
1003         /*
1004          * If our children haven't all reached the ready stage,
1005          * wait for them and then repeat this pipeline stage.
1006          */
1007         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
1008             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_READY))
1009                 return (ZIO_PIPELINE_STOP);
1010
1011         if (!IO_IS_ALLOCATING(zio))
1012                 return (ZIO_PIPELINE_CONTINUE);
1013
1014         ASSERT(zio->io_child_type != ZIO_CHILD_DDT);
1015
1016         if (zio->io_bp_override) {
1017                 ASSERT(bp->blk_birth != zio->io_txg);
1018                 ASSERT(BP_GET_DEDUP(zio->io_bp_override) == 0);
1019
1020                 *bp = *zio->io_bp_override;
1021                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1022
1023                 if (BP_IS_HOLE(bp) || !zp->zp_dedup)
1024                         return (ZIO_PIPELINE_CONTINUE);
1025
1026                 ASSERT(zio_checksum_table[zp->zp_checksum].ci_dedup ||
1027                     zp->zp_dedup_verify);
1028
1029                 if (BP_GET_CHECKSUM(bp) == zp->zp_checksum) {
1030                         BP_SET_DEDUP(bp, 1);
1031                         zio->io_pipeline |= ZIO_STAGE_DDT_WRITE;
1032                         return (ZIO_PIPELINE_CONTINUE);
1033                 }
1034                 zio->io_bp_override = NULL;
1035                 BP_ZERO(bp);
1036         }
1037
1038         if (bp->blk_birth == zio->io_txg) {
1039                 /*
1040                  * We're rewriting an existing block, which means we're
1041                  * working on behalf of spa_sync().  For spa_sync() to
1042                  * converge, it must eventually be the case that we don't
1043                  * have to allocate new blocks.  But compression changes
1044                  * the blocksize, which forces a reallocate, and makes
1045                  * convergence take longer.  Therefore, after the first
1046                  * few passes, stop compressing to ensure convergence.
1047                  */
1048                 pass = spa_sync_pass(spa);
1049
1050                 ASSERT(zio->io_txg == spa_syncing_txg(spa));
1051                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1052                 ASSERT(!BP_GET_DEDUP(bp));
1053
1054                 if (pass > SYNC_PASS_DONT_COMPRESS)
1055                         compress = ZIO_COMPRESS_OFF;
1056
1057                 /* Make sure someone doesn't change their mind on overwrites */
1058                 ASSERT(MIN(zp->zp_copies + BP_IS_GANG(bp),
1059                     spa_max_replication(spa)) == BP_GET_NDVAS(bp));
1060         }
1061
1062         if (compress != ZIO_COMPRESS_OFF) {
1063                 void *cbuf = zio_buf_alloc(lsize);
1064                 psize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1065                 if (psize == 0 || psize == lsize) {
1066                         compress = ZIO_COMPRESS_OFF;
1067                         zio_buf_free(cbuf, lsize);
1068                 } else {
1069                         ASSERT(psize < lsize);
1070                         zio_push_transform(zio, cbuf, psize, lsize, NULL);
1071                 }
1072         }
1073
1074         /*
1075          * The final pass of spa_sync() must be all rewrites, but the first
1076          * few passes offer a trade-off: allocating blocks defers convergence,
1077          * but newly allocated blocks are sequential, so they can be written
1078          * to disk faster.  Therefore, we allow the first few passes of
1079          * spa_sync() to allocate new blocks, but force rewrites after that.
1080          * There should only be a handful of blocks after pass 1 in any case.
1081          */
1082         if (bp->blk_birth == zio->io_txg && BP_GET_PSIZE(bp) == psize &&
1083             pass > SYNC_PASS_REWRITE) {
1084                 ASSERT(psize != 0);
1085                 enum zio_stage gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
1086                 zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
1087                 zio->io_flags |= ZIO_FLAG_IO_REWRITE;
1088         } else {
1089                 BP_ZERO(bp);
1090                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
1091         }
1092
1093         if (psize == 0) {
1094                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1095         } else {
1096                 ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
1097                 BP_SET_LSIZE(bp, lsize);
1098                 BP_SET_PSIZE(bp, psize);
1099                 BP_SET_COMPRESS(bp, compress);
1100                 BP_SET_CHECKSUM(bp, zp->zp_checksum);
1101                 BP_SET_TYPE(bp, zp->zp_type);
1102                 BP_SET_LEVEL(bp, zp->zp_level);
1103                 BP_SET_DEDUP(bp, zp->zp_dedup);
1104                 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
1105                 if (zp->zp_dedup) {
1106                         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1107                         ASSERT(!(zio->io_flags & ZIO_FLAG_IO_REWRITE));
1108                         zio->io_pipeline = ZIO_DDT_WRITE_PIPELINE;
1109                 }
1110         }
1111
1112         return (ZIO_PIPELINE_CONTINUE);
1113 }
1114
1115 static int
1116 zio_free_bp_init(zio_t *zio)
1117 {
1118         blkptr_t *bp = zio->io_bp;
1119
1120         if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
1121                 if (BP_GET_DEDUP(bp))
1122                         zio->io_pipeline = ZIO_DDT_FREE_PIPELINE;
1123         }
1124
1125         return (ZIO_PIPELINE_CONTINUE);
1126 }
1127
1128 /*
1129  * ==========================================================================
1130  * Execute the I/O pipeline
1131  * ==========================================================================
1132  */
1133
1134 static void
1135 zio_taskq_dispatch(zio_t *zio, enum zio_taskq_type q, boolean_t cutinline)
1136 {
1137         spa_t *spa = zio->io_spa;
1138         zio_type_t t = zio->io_type;
1139         int flags = TQ_SLEEP | (cutinline ? TQ_FRONT : 0);
1140
1141         ASSERT(q == ZIO_TASKQ_ISSUE || q == ZIO_TASKQ_INTERRUPT);
1142
1143         /*
1144          * If we're a config writer or a probe, the normal issue and
1145          * interrupt threads may all be blocked waiting for the config lock.
1146          * In this case, select the otherwise-unused taskq for ZIO_TYPE_NULL.
1147          */
1148         if (zio->io_flags & (ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_PROBE))
1149                 t = ZIO_TYPE_NULL;
1150
1151         /*
1152          * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
1153          */
1154         if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
1155                 t = ZIO_TYPE_NULL;
1156
1157         /*
1158          * If this is a high priority I/O, then use the high priority taskq.
1159          */
1160         if (zio->io_priority == ZIO_PRIORITY_NOW &&
1161             spa->spa_zio_taskq[t][q + 1] != NULL)
1162                 q++;
1163
1164         ASSERT3U(q, <, ZIO_TASKQ_TYPES);
1165 #ifdef _KERNEL
1166         (void) taskq_dispatch_safe(spa->spa_zio_taskq[t][q],
1167             (task_func_t *)zio_execute, zio, flags, &zio->io_task);
1168 #else
1169         (void) taskq_dispatch(spa->spa_zio_taskq[t][q],
1170             (task_func_t *)zio_execute, zio, flags);
1171 #endif
1172 }
1173
1174 static boolean_t
1175 zio_taskq_member(zio_t *zio, enum zio_taskq_type q)
1176 {
1177         kthread_t *executor = zio->io_executor;
1178         spa_t *spa = zio->io_spa;
1179
1180         for (zio_type_t t = 0; t < ZIO_TYPES; t++)
1181                 if (taskq_member(spa->spa_zio_taskq[t][q], executor))
1182                         return (B_TRUE);
1183
1184         return (B_FALSE);
1185 }
1186
1187 static int
1188 zio_issue_async(zio_t *zio)
1189 {
1190         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
1191
1192         return (ZIO_PIPELINE_STOP);
1193 }
1194
1195 void
1196 zio_interrupt(zio_t *zio)
1197 {
1198         zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT, B_FALSE);
1199 }
1200
1201 /*
1202  * Execute the I/O pipeline until one of the following occurs:
1203  * (1) the I/O completes; (2) the pipeline stalls waiting for
1204  * dependent child I/Os; (3) the I/O issues, so we're waiting
1205  * for an I/O completion interrupt; (4) the I/O is delegated by
1206  * vdev-level caching or aggregation; (5) the I/O is deferred
1207  * due to vdev-level queueing; (6) the I/O is handed off to
1208  * another thread.  In all cases, the pipeline stops whenever
1209  * there's no CPU work; it never burns a thread in cv_wait().
1210  *
1211  * There's no locking on io_stage because there's no legitimate way
1212  * for multiple threads to be attempting to process the same I/O.
1213  */
1214 static zio_pipe_stage_t *zio_pipeline[];
1215
1216 void
1217 zio_execute(zio_t *zio)
1218 {
1219         zio->io_executor = curthread;
1220
1221         while (zio->io_stage < ZIO_STAGE_DONE) {
1222                 enum zio_stage pipeline = zio->io_pipeline;
1223                 enum zio_stage stage = zio->io_stage;
1224                 int rv;
1225
1226                 ASSERT(!MUTEX_HELD(&zio->io_lock));
1227                 ASSERT(ISP2(stage));
1228                 ASSERT(zio->io_stall == NULL);
1229
1230                 do {
1231                         stage <<= 1;
1232                 } while ((stage & pipeline) == 0);
1233
1234                 ASSERT(stage <= ZIO_STAGE_DONE);
1235
1236                 /*
1237                  * If we are in interrupt context and this pipeline stage
1238                  * will grab a config lock that is held across I/O,
1239                  * or may wait for an I/O that needs an interrupt thread
1240                  * to complete, issue async to avoid deadlock.
1241                  *
1242                  * For VDEV_IO_START, we cut in line so that the io will
1243                  * be sent to disk promptly.
1244                  */
1245                 if ((stage & ZIO_BLOCKING_STAGES) && zio->io_vd == NULL &&
1246                     zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
1247                         boolean_t cut = (stage == ZIO_STAGE_VDEV_IO_START) ?
1248                             zio_requeue_io_start_cut_in_line : B_FALSE;
1249                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, cut);
1250                         return;
1251                 }
1252
1253                 zio->io_stage = stage;
1254                 rv = zio_pipeline[highbit(stage) - 1](zio);
1255
1256                 if (rv == ZIO_PIPELINE_STOP)
1257                         return;
1258
1259                 ASSERT(rv == ZIO_PIPELINE_CONTINUE);
1260         }
1261 }
1262
1263 /*
1264  * ==========================================================================
1265  * Initiate I/O, either sync or async
1266  * ==========================================================================
1267  */
1268 int
1269 zio_wait(zio_t *zio)
1270 {
1271         int error;
1272
1273         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
1274         ASSERT(zio->io_executor == NULL);
1275
1276         zio->io_waiter = curthread;
1277
1278         zio_execute(zio);
1279
1280         mutex_enter(&zio->io_lock);
1281         while (zio->io_executor != NULL)
1282                 cv_wait(&zio->io_cv, &zio->io_lock);
1283         mutex_exit(&zio->io_lock);
1284
1285         error = zio->io_error;
1286         zio_destroy(zio);
1287
1288         return (error);
1289 }
1290
1291 void
1292 zio_nowait(zio_t *zio)
1293 {
1294         ASSERT(zio->io_executor == NULL);
1295
1296         if (zio->io_child_type == ZIO_CHILD_LOGICAL &&
1297             zio_unique_parent(zio) == NULL) {
1298                 /*
1299                  * This is a logical async I/O with no parent to wait for it.
1300                  * We add it to the spa_async_root_zio "Godfather" I/O which
1301                  * will ensure they complete prior to unloading the pool.
1302                  */
1303                 spa_t *spa = zio->io_spa;
1304
1305                 zio_add_child(spa->spa_async_zio_root, zio);
1306         }
1307
1308         zio_execute(zio);
1309 }
1310
1311 /*
1312  * ==========================================================================
1313  * Reexecute or suspend/resume failed I/O
1314  * ==========================================================================
1315  */
1316
1317 static void
1318 zio_reexecute(zio_t *pio)
1319 {
1320         zio_t *cio, *cio_next;
1321
1322         ASSERT(pio->io_child_type == ZIO_CHILD_LOGICAL);
1323         ASSERT(pio->io_orig_stage == ZIO_STAGE_OPEN);
1324         ASSERT(pio->io_gang_leader == NULL);
1325         ASSERT(pio->io_gang_tree == NULL);
1326
1327         pio->io_flags = pio->io_orig_flags;
1328         pio->io_stage = pio->io_orig_stage;
1329         pio->io_pipeline = pio->io_orig_pipeline;
1330         pio->io_reexecute = 0;
1331         pio->io_error = 0;
1332         for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1333                 pio->io_state[w] = 0;
1334         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
1335                 pio->io_child_error[c] = 0;
1336
1337         if (IO_IS_ALLOCATING(pio))
1338                 BP_ZERO(pio->io_bp);
1339
1340         /*
1341          * As we reexecute pio's children, new children could be created.
1342          * New children go to the head of pio's io_child_list, however,
1343          * so we will (correctly) not reexecute them.  The key is that
1344          * the remainder of pio's io_child_list, from 'cio_next' onward,
1345          * cannot be affected by any side effects of reexecuting 'cio'.
1346          */
1347         for (cio = zio_walk_children(pio); cio != NULL; cio = cio_next) {
1348                 cio_next = zio_walk_children(pio);
1349                 mutex_enter(&pio->io_lock);
1350                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
1351                         pio->io_children[cio->io_child_type][w]++;
1352                 mutex_exit(&pio->io_lock);
1353                 zio_reexecute(cio);
1354         }
1355
1356         /*
1357          * Now that all children have been reexecuted, execute the parent.
1358          * We don't reexecute "The Godfather" I/O here as it's the
1359          * responsibility of the caller to wait on him.
1360          */
1361         if (!(pio->io_flags & ZIO_FLAG_GODFATHER))
1362                 zio_execute(pio);
1363 }
1364
1365 void
1366 zio_suspend(spa_t *spa, zio_t *zio)
1367 {
1368         if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
1369                 fm_panic("Pool '%s' has encountered an uncorrectable I/O "
1370                     "failure and the failure mode property for this pool "
1371                     "is set to panic.", spa_name(spa));
1372
1373         zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL, NULL, 0, 0);
1374
1375         mutex_enter(&spa->spa_suspend_lock);
1376
1377         if (spa->spa_suspend_zio_root == NULL)
1378                 spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL,
1379                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
1380                     ZIO_FLAG_GODFATHER);
1381
1382         spa->spa_suspended = B_TRUE;
1383
1384         if (zio != NULL) {
1385                 ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
1386                 ASSERT(zio != spa->spa_suspend_zio_root);
1387                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1388                 ASSERT(zio_unique_parent(zio) == NULL);
1389                 ASSERT(zio->io_stage == ZIO_STAGE_DONE);
1390                 zio_add_child(spa->spa_suspend_zio_root, zio);
1391         }
1392
1393         mutex_exit(&spa->spa_suspend_lock);
1394 }
1395
1396 int
1397 zio_resume(spa_t *spa)
1398 {
1399         zio_t *pio;
1400
1401         /*
1402          * Reexecute all previously suspended i/o.
1403          */
1404         mutex_enter(&spa->spa_suspend_lock);
1405         spa->spa_suspended = B_FALSE;
1406         cv_broadcast(&spa->spa_suspend_cv);
1407         pio = spa->spa_suspend_zio_root;
1408         spa->spa_suspend_zio_root = NULL;
1409         mutex_exit(&spa->spa_suspend_lock);
1410
1411         if (pio == NULL)
1412                 return (0);
1413
1414         zio_reexecute(pio);
1415         return (zio_wait(pio));
1416 }
1417
1418 void
1419 zio_resume_wait(spa_t *spa)
1420 {
1421         mutex_enter(&spa->spa_suspend_lock);
1422         while (spa_suspended(spa))
1423                 cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
1424         mutex_exit(&spa->spa_suspend_lock);
1425 }
1426
1427 /*
1428  * ==========================================================================
1429  * Gang blocks.
1430  *
1431  * A gang block is a collection of small blocks that looks to the DMU
1432  * like one large block.  When zio_dva_allocate() cannot find a block
1433  * of the requested size, due to either severe fragmentation or the pool
1434  * being nearly full, it calls zio_write_gang_block() to construct the
1435  * block from smaller fragments.
1436  *
1437  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
1438  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
1439  * an indirect block: it's an array of block pointers.  It consumes
1440  * only one sector and hence is allocatable regardless of fragmentation.
1441  * The gang header's bps point to its gang members, which hold the data.
1442  *
1443  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
1444  * as the verifier to ensure uniqueness of the SHA256 checksum.
1445  * Critically, the gang block bp's blk_cksum is the checksum of the data,
1446  * not the gang header.  This ensures that data block signatures (needed for
1447  * deduplication) are independent of how the block is physically stored.
1448  *
1449  * Gang blocks can be nested: a gang member may itself be a gang block.
1450  * Thus every gang block is a tree in which root and all interior nodes are
1451  * gang headers, and the leaves are normal blocks that contain user data.
1452  * The root of the gang tree is called the gang leader.
1453  *
1454  * To perform any operation (read, rewrite, free, claim) on a gang block,
1455  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
1456  * in the io_gang_tree field of the original logical i/o by recursively
1457  * reading the gang leader and all gang headers below it.  This yields
1458  * an in-core tree containing the contents of every gang header and the
1459  * bps for every constituent of the gang block.
1460  *
1461  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
1462  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
1463  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
1464  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
1465  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
1466  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
1467  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
1468  * of the gang header plus zio_checksum_compute() of the data to update the
1469  * gang header's blk_cksum as described above.
1470  *
1471  * The two-phase assemble/issue model solves the problem of partial failure --
1472  * what if you'd freed part of a gang block but then couldn't read the
1473  * gang header for another part?  Assembling the entire gang tree first
1474  * ensures that all the necessary gang header I/O has succeeded before
1475  * starting the actual work of free, claim, or write.  Once the gang tree
1476  * is assembled, free and claim are in-memory operations that cannot fail.
1477  *
1478  * In the event that a gang write fails, zio_dva_unallocate() walks the
1479  * gang tree to immediately free (i.e. insert back into the space map)
1480  * everything we've allocated.  This ensures that we don't get ENOSPC
1481  * errors during repeated suspend/resume cycles due to a flaky device.
1482  *
1483  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
1484  * the gang tree, we won't modify the block, so we can safely defer the free
1485  * (knowing that the block is still intact).  If we *can* assemble the gang
1486  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
1487  * each constituent bp and we can allocate a new block on the next sync pass.
1488  *
1489  * In all cases, the gang tree allows complete recovery from partial failure.
1490  * ==========================================================================
1491  */
1492
1493 static zio_t *
1494 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1495 {
1496         if (gn != NULL)
1497                 return (pio);
1498
1499         return (zio_read(pio, pio->io_spa, bp, data, BP_GET_PSIZE(bp),
1500             NULL, NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1501             &pio->io_bookmark));
1502 }
1503
1504 zio_t *
1505 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1506 {
1507         zio_t *zio;
1508
1509         if (gn != NULL) {
1510                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1511                     gn->gn_gbh, SPA_GANGBLOCKSIZE, NULL, NULL, pio->io_priority,
1512                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1513                 /*
1514                  * As we rewrite each gang header, the pipeline will compute
1515                  * a new gang block header checksum for it; but no one will
1516                  * compute a new data checksum, so we do that here.  The one
1517                  * exception is the gang leader: the pipeline already computed
1518                  * its data checksum because that stage precedes gang assembly.
1519                  * (Presently, nothing actually uses interior data checksums;
1520                  * this is just good hygiene.)
1521                  */
1522                 if (gn != pio->io_gang_leader->io_gang_tree) {
1523                         zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
1524                             data, BP_GET_PSIZE(bp));
1525                 }
1526                 /*
1527                  * If we are here to damage data for testing purposes,
1528                  * leave the GBH alone so that we can detect the damage.
1529                  */
1530                 if (pio->io_gang_leader->io_flags & ZIO_FLAG_INDUCE_DAMAGE)
1531                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
1532         } else {
1533                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1534                     data, BP_GET_PSIZE(bp), NULL, NULL, pio->io_priority,
1535                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1536         }
1537
1538         return (zio);
1539 }
1540
1541 /* ARGSUSED */
1542 zio_t *
1543 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1544 {
1545         return (zio_free_sync(pio, pio->io_spa, pio->io_txg, bp,
1546             BP_IS_GANG(bp) ? SPA_GANGBLOCKSIZE : BP_GET_PSIZE(bp),
1547             ZIO_GANG_CHILD_FLAGS(pio)));
1548 }
1549
1550 /* ARGSUSED */
1551 zio_t *
1552 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1553 {
1554         return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
1555             NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
1556 }
1557
1558 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
1559         NULL,
1560         zio_read_gang,
1561         zio_rewrite_gang,
1562         zio_free_gang,
1563         zio_claim_gang,
1564         NULL
1565 };
1566
1567 static void zio_gang_tree_assemble_done(zio_t *zio);
1568
1569 static zio_gang_node_t *
1570 zio_gang_node_alloc(zio_gang_node_t **gnpp)
1571 {
1572         zio_gang_node_t *gn;
1573
1574         ASSERT(*gnpp == NULL);
1575
1576         gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
1577         gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
1578         *gnpp = gn;
1579
1580         return (gn);
1581 }
1582
1583 static void
1584 zio_gang_node_free(zio_gang_node_t **gnpp)
1585 {
1586         zio_gang_node_t *gn = *gnpp;
1587
1588         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1589                 ASSERT(gn->gn_child[g] == NULL);
1590
1591         zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
1592         kmem_free(gn, sizeof (*gn));
1593         *gnpp = NULL;
1594 }
1595
1596 static void
1597 zio_gang_tree_free(zio_gang_node_t **gnpp)
1598 {
1599         zio_gang_node_t *gn = *gnpp;
1600
1601         if (gn == NULL)
1602                 return;
1603
1604         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1605                 zio_gang_tree_free(&gn->gn_child[g]);
1606
1607         zio_gang_node_free(gnpp);
1608 }
1609
1610 static void
1611 zio_gang_tree_assemble(zio_t *gio, blkptr_t *bp, zio_gang_node_t **gnpp)
1612 {
1613         zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
1614
1615         ASSERT(gio->io_gang_leader == gio);
1616         ASSERT(BP_IS_GANG(bp));
1617
1618         zio_nowait(zio_read(gio, gio->io_spa, bp, gn->gn_gbh,
1619             SPA_GANGBLOCKSIZE, zio_gang_tree_assemble_done, gn,
1620             gio->io_priority, ZIO_GANG_CHILD_FLAGS(gio), &gio->io_bookmark));
1621 }
1622
1623 static void
1624 zio_gang_tree_assemble_done(zio_t *zio)
1625 {
1626         zio_t *gio = zio->io_gang_leader;
1627         zio_gang_node_t *gn = zio->io_private;
1628         blkptr_t *bp = zio->io_bp;
1629
1630         ASSERT(gio == zio_unique_parent(zio));
1631         ASSERT(zio->io_child_count == 0);
1632
1633         if (zio->io_error)
1634                 return;
1635
1636         if (BP_SHOULD_BYTESWAP(bp))
1637                 byteswap_uint64_array(zio->io_data, zio->io_size);
1638
1639         ASSERT(zio->io_data == gn->gn_gbh);
1640         ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
1641         ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
1642
1643         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1644                 blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1645                 if (!BP_IS_GANG(gbp))
1646                         continue;
1647                 zio_gang_tree_assemble(gio, gbp, &gn->gn_child[g]);
1648         }
1649 }
1650
1651 static void
1652 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, void *data)
1653 {
1654         zio_t *gio = pio->io_gang_leader;
1655         zio_t *zio;
1656
1657         ASSERT(BP_IS_GANG(bp) == !!gn);
1658         ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(gio->io_bp));
1659         ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == gio->io_gang_tree);
1660
1661         /*
1662          * If you're a gang header, your data is in gn->gn_gbh.
1663          * If you're a gang member, your data is in 'data' and gn == NULL.
1664          */
1665         zio = zio_gang_issue_func[gio->io_type](pio, bp, gn, data);
1666
1667         if (gn != NULL) {
1668                 ASSERT(gn->gn_gbh->zg_tail.zec_magic == ZEC_MAGIC);
1669
1670                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1671                         blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1672                         if (BP_IS_HOLE(gbp))
1673                                 continue;
1674                         zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data);
1675                         data = (char *)data + BP_GET_PSIZE(gbp);
1676                 }
1677         }
1678
1679         if (gn == gio->io_gang_tree && gio->io_data != NULL)
1680                 ASSERT3P((char *)gio->io_data + gio->io_size, ==, data);
1681
1682         if (zio != pio)
1683                 zio_nowait(zio);
1684 }
1685
1686 static int
1687 zio_gang_assemble(zio_t *zio)
1688 {
1689         blkptr_t *bp = zio->io_bp;
1690
1691         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == NULL);
1692         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
1693
1694         zio->io_gang_leader = zio;
1695
1696         zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
1697
1698         return (ZIO_PIPELINE_CONTINUE);
1699 }
1700
1701 static int
1702 zio_gang_issue(zio_t *zio)
1703 {
1704         blkptr_t *bp = zio->io_bp;
1705
1706         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE))
1707                 return (ZIO_PIPELINE_STOP);
1708
1709         ASSERT(BP_IS_GANG(bp) && zio->io_gang_leader == zio);
1710         ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
1711
1712         if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
1713                 zio_gang_tree_issue(zio, zio->io_gang_tree, bp, zio->io_data);
1714         else
1715                 zio_gang_tree_free(&zio->io_gang_tree);
1716
1717         zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1718
1719         return (ZIO_PIPELINE_CONTINUE);
1720 }
1721
1722 static void
1723 zio_write_gang_member_ready(zio_t *zio)
1724 {
1725         zio_t *pio = zio_unique_parent(zio);
1726         zio_t *gio = zio->io_gang_leader;
1727         dva_t *cdva = zio->io_bp->blk_dva;
1728         dva_t *pdva = pio->io_bp->blk_dva;
1729         uint64_t asize;
1730
1731         if (BP_IS_HOLE(zio->io_bp))
1732                 return;
1733
1734         ASSERT(BP_IS_HOLE(&zio->io_bp_orig));
1735
1736         ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
1737         ASSERT3U(zio->io_prop.zp_copies, ==, gio->io_prop.zp_copies);
1738         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(zio->io_bp));
1739         ASSERT3U(pio->io_prop.zp_copies, <=, BP_GET_NDVAS(pio->io_bp));
1740         ASSERT3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
1741
1742         mutex_enter(&pio->io_lock);
1743         for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
1744                 ASSERT(DVA_GET_GANG(&pdva[d]));
1745                 asize = DVA_GET_ASIZE(&pdva[d]);
1746                 asize += DVA_GET_ASIZE(&cdva[d]);
1747                 DVA_SET_ASIZE(&pdva[d], asize);
1748         }
1749         mutex_exit(&pio->io_lock);
1750 }
1751
1752 static int
1753 zio_write_gang_block(zio_t *pio)
1754 {
1755         spa_t *spa = pio->io_spa;
1756         blkptr_t *bp = pio->io_bp;
1757         zio_t *gio = pio->io_gang_leader;
1758         zio_t *zio;
1759         zio_gang_node_t *gn, **gnpp;
1760         zio_gbh_phys_t *gbh;
1761         uint64_t txg = pio->io_txg;
1762         uint64_t resid = pio->io_size;
1763         uint64_t lsize;
1764         int copies = gio->io_prop.zp_copies;
1765         int gbh_copies = MIN(copies + 1, spa_max_replication(spa));
1766         zio_prop_t zp;
1767         int error;
1768
1769         error = metaslab_alloc(spa, spa_normal_class(spa), SPA_GANGBLOCKSIZE,
1770             bp, gbh_copies, txg, pio == gio ? NULL : gio->io_bp,
1771             METASLAB_HINTBP_FAVOR | METASLAB_GANG_HEADER);
1772         if (error) {
1773                 pio->io_error = error;
1774                 return (ZIO_PIPELINE_CONTINUE);
1775         }
1776
1777         if (pio == gio) {
1778                 gnpp = &gio->io_gang_tree;
1779         } else {
1780                 gnpp = pio->io_private;
1781                 ASSERT(pio->io_ready == zio_write_gang_member_ready);
1782         }
1783
1784         gn = zio_gang_node_alloc(gnpp);
1785         gbh = gn->gn_gbh;
1786         bzero(gbh, SPA_GANGBLOCKSIZE);
1787
1788         /*
1789          * Create the gang header.
1790          */
1791         zio = zio_rewrite(pio, spa, txg, bp, gbh, SPA_GANGBLOCKSIZE, NULL, NULL,
1792             pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1793
1794         /*
1795          * Create and nowait the gang children.
1796          */
1797         for (int g = 0; resid != 0; resid -= lsize, g++) {
1798                 lsize = P2ROUNDUP(resid / (SPA_GBH_NBLKPTRS - g),
1799                     SPA_MINBLOCKSIZE);
1800                 ASSERT(lsize >= SPA_MINBLOCKSIZE && lsize <= resid);
1801
1802                 zp.zp_checksum = gio->io_prop.zp_checksum;
1803                 zp.zp_compress = ZIO_COMPRESS_OFF;
1804                 zp.zp_type = DMU_OT_NONE;
1805                 zp.zp_level = 0;
1806                 zp.zp_copies = gio->io_prop.zp_copies;
1807                 zp.zp_dedup = 0;
1808                 zp.zp_dedup_verify = 0;
1809
1810                 zio_nowait(zio_write(zio, spa, txg, &gbh->zg_blkptr[g],
1811                     (char *)pio->io_data + (pio->io_size - resid), lsize, &zp,
1812                     zio_write_gang_member_ready, NULL, &gn->gn_child[g],
1813                     pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1814                     &pio->io_bookmark));
1815         }
1816
1817         /*
1818          * Set pio's pipeline to just wait for zio to finish.
1819          */
1820         pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1821
1822         zio_nowait(zio);
1823
1824         return (ZIO_PIPELINE_CONTINUE);
1825 }
1826
1827 /*
1828  * ==========================================================================
1829  * Dedup
1830  * ==========================================================================
1831  */
1832 static void
1833 zio_ddt_child_read_done(zio_t *zio)
1834 {
1835         blkptr_t *bp = zio->io_bp;
1836         ddt_entry_t *dde = zio->io_private;
1837         ddt_phys_t *ddp;
1838         zio_t *pio = zio_unique_parent(zio);
1839
1840         mutex_enter(&pio->io_lock);
1841         ddp = ddt_phys_select(dde, bp);
1842         if (zio->io_error == 0)
1843                 ddt_phys_clear(ddp);    /* this ddp doesn't need repair */
1844         if (zio->io_error == 0 && dde->dde_repair_data == NULL)
1845                 dde->dde_repair_data = zio->io_data;
1846         else
1847                 zio_buf_free(zio->io_data, zio->io_size);
1848         mutex_exit(&pio->io_lock);
1849 }
1850
1851 static int
1852 zio_ddt_read_start(zio_t *zio)
1853 {
1854         blkptr_t *bp = zio->io_bp;
1855
1856         ASSERT(BP_GET_DEDUP(bp));
1857         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
1858         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1859
1860         if (zio->io_child_error[ZIO_CHILD_DDT]) {
1861                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
1862                 ddt_entry_t *dde = ddt_repair_start(ddt, bp);
1863                 ddt_phys_t *ddp = dde->dde_phys;
1864                 ddt_phys_t *ddp_self = ddt_phys_select(dde, bp);
1865                 blkptr_t blk;
1866
1867                 ASSERT(zio->io_vsd == NULL);
1868                 zio->io_vsd = dde;
1869
1870                 if (ddp_self == NULL)
1871                         return (ZIO_PIPELINE_CONTINUE);
1872
1873                 for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1874                         if (ddp->ddp_phys_birth == 0 || ddp == ddp_self)
1875                                 continue;
1876                         ddt_bp_create(ddt->ddt_checksum, &dde->dde_key, ddp,
1877                             &blk);
1878                         zio_nowait(zio_read(zio, zio->io_spa, &blk,
1879                             zio_buf_alloc(zio->io_size), zio->io_size,
1880                             zio_ddt_child_read_done, dde, zio->io_priority,
1881                             ZIO_DDT_CHILD_FLAGS(zio) | ZIO_FLAG_DONT_PROPAGATE,
1882                             &zio->io_bookmark));
1883                 }
1884                 return (ZIO_PIPELINE_CONTINUE);
1885         }
1886
1887         zio_nowait(zio_read(zio, zio->io_spa, bp,
1888             zio->io_data, zio->io_size, NULL, NULL, zio->io_priority,
1889             ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark));
1890
1891         return (ZIO_PIPELINE_CONTINUE);
1892 }
1893
1894 static int
1895 zio_ddt_read_done(zio_t *zio)
1896 {
1897         blkptr_t *bp = zio->io_bp;
1898
1899         if (zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE))
1900                 return (ZIO_PIPELINE_STOP);
1901
1902         ASSERT(BP_GET_DEDUP(bp));
1903         ASSERT(BP_GET_PSIZE(bp) == zio->io_size);
1904         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1905
1906         if (zio->io_child_error[ZIO_CHILD_DDT]) {
1907                 ddt_t *ddt = ddt_select(zio->io_spa, bp);
1908                 ddt_entry_t *dde = zio->io_vsd;
1909                 if (ddt == NULL) {
1910                         ASSERT(spa_load_state(zio->io_spa) != SPA_LOAD_NONE);
1911                         return (ZIO_PIPELINE_CONTINUE);
1912                 }
1913                 if (dde == NULL) {
1914                         zio->io_stage = ZIO_STAGE_DDT_READ_START >> 1;
1915                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE, B_FALSE);
1916                         return (ZIO_PIPELINE_STOP);
1917                 }
1918                 if (dde->dde_repair_data != NULL) {
1919                         bcopy(dde->dde_repair_data, zio->io_data, zio->io_size);
1920                         zio->io_child_error[ZIO_CHILD_DDT] = 0;
1921                 }
1922                 ddt_repair_done(ddt, dde);
1923                 zio->io_vsd = NULL;
1924         }
1925
1926         ASSERT(zio->io_vsd == NULL);
1927
1928         return (ZIO_PIPELINE_CONTINUE);
1929 }
1930
1931 static boolean_t
1932 zio_ddt_collision(zio_t *zio, ddt_t *ddt, ddt_entry_t *dde)
1933 {
1934         spa_t *spa = zio->io_spa;
1935
1936         /*
1937          * Note: we compare the original data, not the transformed data,
1938          * because when zio->io_bp is an override bp, we will not have
1939          * pushed the I/O transforms.  That's an important optimization
1940          * because otherwise we'd compress/encrypt all dmu_sync() data twice.
1941          */
1942         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
1943                 zio_t *lio = dde->dde_lead_zio[p];
1944
1945                 if (lio != NULL) {
1946                         return (lio->io_orig_size != zio->io_orig_size ||
1947                             bcmp(zio->io_orig_data, lio->io_orig_data,
1948                             zio->io_orig_size) != 0);
1949                 }
1950         }
1951
1952         for (int p = DDT_PHYS_SINGLE; p <= DDT_PHYS_TRIPLE; p++) {
1953                 ddt_phys_t *ddp = &dde->dde_phys[p];
1954
1955                 if (ddp->ddp_phys_birth != 0) {
1956                         arc_buf_t *abuf = NULL;
1957                         uint32_t aflags = ARC_WAIT;
1958                         blkptr_t blk = *zio->io_bp;
1959                         int error;
1960
1961                         ddt_bp_fill(ddp, &blk, ddp->ddp_phys_birth);
1962
1963                         ddt_exit(ddt);
1964
1965                         error = arc_read_nolock(NULL, spa, &blk,
1966                             arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ,
1967                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
1968                             &aflags, &zio->io_bookmark);
1969
1970                         if (error == 0) {
1971                                 if (arc_buf_size(abuf) != zio->io_orig_size ||
1972                                     bcmp(abuf->b_data, zio->io_orig_data,
1973                                     zio->io_orig_size) != 0)
1974                                         error = EEXIST;
1975                                 VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
1976                         }
1977
1978                         ddt_enter(ddt);
1979                         return (error != 0);
1980                 }
1981         }
1982
1983         return (B_FALSE);
1984 }
1985
1986 static void
1987 zio_ddt_child_write_ready(zio_t *zio)
1988 {
1989         int p = zio->io_prop.zp_copies;
1990         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
1991         ddt_entry_t *dde = zio->io_private;
1992         ddt_phys_t *ddp = &dde->dde_phys[p];
1993         zio_t *pio;
1994
1995         if (zio->io_error)
1996                 return;
1997
1998         ddt_enter(ddt);
1999
2000         ASSERT(dde->dde_lead_zio[p] == zio);
2001
2002         ddt_phys_fill(ddp, zio->io_bp);
2003
2004         while ((pio = zio_walk_parents(zio)) != NULL)
2005                 ddt_bp_fill(ddp, pio->io_bp, zio->io_txg);
2006
2007         ddt_exit(ddt);
2008 }
2009
2010 static void
2011 zio_ddt_child_write_done(zio_t *zio)
2012 {
2013         int p = zio->io_prop.zp_copies;
2014         ddt_t *ddt = ddt_select(zio->io_spa, zio->io_bp);
2015         ddt_entry_t *dde = zio->io_private;
2016         ddt_phys_t *ddp = &dde->dde_phys[p];
2017
2018         ddt_enter(ddt);
2019
2020         ASSERT(ddp->ddp_refcnt == 0);
2021         ASSERT(dde->dde_lead_zio[p] == zio);
2022         dde->dde_lead_zio[p] = NULL;
2023
2024         if (zio->io_error == 0) {
2025                 while (zio_walk_parents(zio) != NULL)
2026                         ddt_phys_addref(ddp);
2027         } else {
2028                 ddt_phys_clear(ddp);
2029         }
2030
2031         ddt_exit(ddt);
2032 }
2033
2034 static void
2035 zio_ddt_ditto_write_done(zio_t *zio)
2036 {
2037         int p = DDT_PHYS_DITTO;
2038         zio_prop_t *zp = &zio->io_prop;
2039         blkptr_t *bp = zio->io_bp;
2040         ddt_t *ddt = ddt_select(zio->io_spa, bp);
2041         ddt_entry_t *dde = zio->io_private;
2042         ddt_phys_t *ddp = &dde->dde_phys[p];
2043         ddt_key_t *ddk = &dde->dde_key;
2044
2045         ddt_enter(ddt);
2046
2047         ASSERT(ddp->ddp_refcnt == 0);
2048         ASSERT(dde->dde_lead_zio[p] == zio);
2049         dde->dde_lead_zio[p] = NULL;
2050
2051         if (zio->io_error == 0) {
2052                 ASSERT(ZIO_CHECKSUM_EQUAL(bp->blk_cksum, ddk->ddk_cksum));
2053                 ASSERT(zp->zp_copies < SPA_DVAS_PER_BP);
2054                 ASSERT(zp->zp_copies == BP_GET_NDVAS(bp) - BP_IS_GANG(bp));
2055                 if (ddp->ddp_phys_birth != 0)
2056                         ddt_phys_free(ddt, ddk, ddp, zio->io_txg);
2057                 ddt_phys_fill(ddp, bp);
2058         }
2059
2060         ddt_exit(ddt);
2061 }
2062
2063 static int
2064 zio_ddt_write(zio_t *zio)
2065 {
2066         spa_t *spa = zio->io_spa;
2067         blkptr_t *bp = zio->io_bp;
2068         uint64_t txg = zio->io_txg;
2069         zio_prop_t *zp = &zio->io_prop;
2070         int p = zp->zp_copies;
2071         int ditto_copies;
2072         zio_t *cio = NULL;
2073         zio_t *dio = NULL;
2074         ddt_t *ddt = ddt_select(spa, bp);
2075         ddt_entry_t *dde;
2076         ddt_phys_t *ddp;
2077
2078         ASSERT(BP_GET_DEDUP(bp));
2079         ASSERT(BP_GET_CHECKSUM(bp) == zp->zp_checksum);
2080         ASSERT(BP_IS_HOLE(bp) || zio->io_bp_override);
2081
2082         ddt_enter(ddt);
2083         dde = ddt_lookup(ddt, bp, B_TRUE);
2084         ddp = &dde->dde_phys[p];
2085
2086         if (zp->zp_dedup_verify && zio_ddt_collision(zio, ddt, dde)) {
2087                 /*
2088                  * If we're using a weak checksum, upgrade to a strong checksum
2089                  * and try again.  If we're already using a strong checksum,
2090                  * we can't resolve it, so just convert to an ordinary write.
2091                  * (And automatically e-mail a paper to Nature?)
2092                  */
2093                 if (!zio_checksum_table[zp->zp_checksum].ci_dedup) {
2094                         zp->zp_checksum = spa_dedup_checksum(spa);
2095                         zio_pop_transforms(zio);
2096                         zio->io_stage = ZIO_STAGE_OPEN;
2097                         BP_ZERO(bp);
2098                 } else {
2099                         zp->zp_dedup = 0;
2100                 }
2101                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
2102                 ddt_exit(ddt);
2103                 return (ZIO_PIPELINE_CONTINUE);
2104         }
2105
2106         ditto_copies = ddt_ditto_copies_needed(ddt, dde, ddp);
2107         ASSERT(ditto_copies < SPA_DVAS_PER_BP);
2108
2109         if (ditto_copies > ddt_ditto_copies_present(dde) &&
2110             dde->dde_lead_zio[DDT_PHYS_DITTO] == NULL) {
2111                 zio_prop_t czp = *zp;
2112
2113                 czp.zp_copies = ditto_copies;
2114
2115                 /*
2116                  * If we arrived here with an override bp, we won't have run
2117                  * the transform stack, so we won't have the data we need to
2118                  * generate a child i/o.  So, toss the override bp and restart.
2119                  * This is safe, because using the override bp is just an
2120                  * optimization; and it's rare, so the cost doesn't matter.
2121                  */
2122                 if (zio->io_bp_override) {
2123                         zio_pop_transforms(zio);
2124                         zio->io_stage = ZIO_STAGE_OPEN;
2125                         zio->io_pipeline = ZIO_WRITE_PIPELINE;
2126                         zio->io_bp_override = NULL;
2127                         BP_ZERO(bp);
2128                         ddt_exit(ddt);
2129                         return (ZIO_PIPELINE_CONTINUE);
2130                 }
2131
2132                 dio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2133                     zio->io_orig_size, &czp, NULL,
2134                     zio_ddt_ditto_write_done, dde, zio->io_priority,
2135                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2136
2137                 zio_push_transform(dio, zio->io_data, zio->io_size, 0, NULL);
2138                 dde->dde_lead_zio[DDT_PHYS_DITTO] = dio;
2139         }
2140
2141         if (ddp->ddp_phys_birth != 0 || dde->dde_lead_zio[p] != NULL) {
2142                 if (ddp->ddp_phys_birth != 0)
2143                         ddt_bp_fill(ddp, bp, txg);
2144                 if (dde->dde_lead_zio[p] != NULL)
2145                         zio_add_child(zio, dde->dde_lead_zio[p]);
2146                 else
2147                         ddt_phys_addref(ddp);
2148         } else if (zio->io_bp_override) {
2149                 ASSERT(bp->blk_birth == txg);
2150                 ASSERT(BP_EQUAL(bp, zio->io_bp_override));
2151                 ddt_phys_fill(ddp, bp);
2152                 ddt_phys_addref(ddp);
2153         } else {
2154                 cio = zio_write(zio, spa, txg, bp, zio->io_orig_data,
2155                     zio->io_orig_size, zp, zio_ddt_child_write_ready,
2156                     zio_ddt_child_write_done, dde, zio->io_priority,
2157                     ZIO_DDT_CHILD_FLAGS(zio), &zio->io_bookmark);
2158
2159                 zio_push_transform(cio, zio->io_data, zio->io_size, 0, NULL);
2160                 dde->dde_lead_zio[p] = cio;
2161         }
2162
2163         ddt_exit(ddt);
2164
2165         if (cio)
2166                 zio_nowait(cio);
2167         if (dio)
2168                 zio_nowait(dio);
2169
2170         return (ZIO_PIPELINE_CONTINUE);
2171 }
2172
2173 ddt_entry_t *freedde; /* for debugging */
2174
2175 static int
2176 zio_ddt_free(zio_t *zio)
2177 {
2178         spa_t *spa = zio->io_spa;
2179         blkptr_t *bp = zio->io_bp;
2180         ddt_t *ddt = ddt_select(spa, bp);
2181         ddt_entry_t *dde;
2182         ddt_phys_t *ddp;
2183
2184         ASSERT(BP_GET_DEDUP(bp));
2185         ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2186
2187         ddt_enter(ddt);
2188         freedde = dde = ddt_lookup(ddt, bp, B_TRUE);
2189         ddp = ddt_phys_select(dde, bp);
2190         ddt_phys_decref(ddp);
2191         ddt_exit(ddt);
2192
2193         return (ZIO_PIPELINE_CONTINUE);
2194 }
2195
2196 /*
2197  * ==========================================================================
2198  * Allocate and free blocks
2199  * ==========================================================================
2200  */
2201 static int
2202 zio_dva_allocate(zio_t *zio)
2203 {
2204         spa_t *spa = zio->io_spa;
2205         metaslab_class_t *mc = spa_normal_class(spa);
2206         blkptr_t *bp = zio->io_bp;
2207         int error;
2208         int flags = 0;
2209
2210         if (zio->io_gang_leader == NULL) {
2211                 ASSERT(zio->io_child_type > ZIO_CHILD_GANG);
2212                 zio->io_gang_leader = zio;
2213         }
2214
2215         ASSERT(BP_IS_HOLE(bp));
2216         ASSERT0(BP_GET_NDVAS(bp));
2217         ASSERT3U(zio->io_prop.zp_copies, >, 0);
2218         ASSERT3U(zio->io_prop.zp_copies, <=, spa_max_replication(spa));
2219         ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
2220
2221         /*
2222          * The dump device does not support gang blocks so allocation on
2223          * behalf of the dump device (i.e. ZIO_FLAG_NODATA) must avoid
2224          * the "fast" gang feature.
2225          */
2226         flags |= (zio->io_flags & ZIO_FLAG_NODATA) ? METASLAB_GANG_AVOID : 0;
2227         flags |= (zio->io_flags & ZIO_FLAG_GANG_CHILD) ?
2228             METASLAB_GANG_CHILD : 0;
2229         error = metaslab_alloc(spa, mc, zio->io_size, bp,
2230             zio->io_prop.zp_copies, zio->io_txg, NULL, flags);
2231
2232         if (error) {
2233                 spa_dbgmsg(spa, "%s: metaslab allocation failure: zio %p, "
2234                     "size %llu, error %d", spa_name(spa), zio, zio->io_size,
2235                     error);
2236                 if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE)
2237                         return (zio_write_gang_block(zio));
2238                 zio->io_error = error;
2239         }
2240
2241         return (ZIO_PIPELINE_CONTINUE);
2242 }
2243
2244 static int
2245 zio_dva_free(zio_t *zio)
2246 {
2247         metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
2248
2249         return (ZIO_PIPELINE_CONTINUE);
2250 }
2251
2252 static int
2253 zio_dva_claim(zio_t *zio)
2254 {
2255         int error;
2256
2257         error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
2258         if (error)
2259                 zio->io_error = error;
2260
2261         return (ZIO_PIPELINE_CONTINUE);
2262 }
2263
2264 /*
2265  * Undo an allocation.  This is used by zio_done() when an I/O fails
2266  * and we want to give back the block we just allocated.
2267  * This handles both normal blocks and gang blocks.
2268  */
2269 static void
2270 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
2271 {
2272         ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
2273         ASSERT(zio->io_bp_override == NULL);
2274
2275         if (!BP_IS_HOLE(bp))
2276                 metaslab_free(zio->io_spa, bp, bp->blk_birth, B_TRUE);
2277
2278         if (gn != NULL) {
2279                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
2280                         zio_dva_unallocate(zio, gn->gn_child[g],
2281                             &gn->gn_gbh->zg_blkptr[g]);
2282                 }
2283         }
2284 }
2285
2286 /*
2287  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
2288  */
2289 int
2290 zio_alloc_zil(spa_t *spa, uint64_t txg, blkptr_t *new_bp, blkptr_t *old_bp,
2291     uint64_t size, boolean_t use_slog)
2292 {
2293         int error = 1;
2294
2295         ASSERT(txg > spa_syncing_txg(spa));
2296
2297         /*
2298          * ZIL blocks are always contiguous (i.e. not gang blocks) so we
2299          * set the METASLAB_GANG_AVOID flag so that they don't "fast gang"
2300          * when allocating them.
2301          */
2302         if (use_slog) {
2303                 error = metaslab_alloc(spa, spa_log_class(spa), size,
2304                     new_bp, 1, txg, old_bp,
2305                     METASLAB_HINTBP_AVOID | METASLAB_GANG_AVOID);
2306         }
2307
2308         if (error) {
2309                 error = metaslab_alloc(spa, spa_normal_class(spa), size,
2310                     new_bp, 1, txg, old_bp,
2311                     METASLAB_HINTBP_AVOID | METASLAB_GANG_AVOID);
2312         }
2313
2314         if (error == 0) {
2315                 BP_SET_LSIZE(new_bp, size);
2316                 BP_SET_PSIZE(new_bp, size);
2317                 BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
2318                 BP_SET_CHECKSUM(new_bp,
2319                     spa_version(spa) >= SPA_VERSION_SLIM_ZIL
2320                     ? ZIO_CHECKSUM_ZILOG2 : ZIO_CHECKSUM_ZILOG);
2321                 BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
2322                 BP_SET_LEVEL(new_bp, 0);
2323                 BP_SET_DEDUP(new_bp, 0);
2324                 BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
2325         }
2326
2327         return (error);
2328 }
2329
2330 /*
2331  * Free an intent log block.
2332  */
2333 void
2334 zio_free_zil(spa_t *spa, uint64_t txg, blkptr_t *bp)
2335 {
2336         ASSERT(BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG);
2337         ASSERT(!BP_IS_GANG(bp));
2338
2339         zio_free(spa, txg, bp);
2340 }
2341
2342 /*
2343  * ==========================================================================
2344  * Read and write to physical devices
2345  * ==========================================================================
2346  */
2347 static int
2348 zio_vdev_io_start(zio_t *zio)
2349 {
2350         vdev_t *vd = zio->io_vd;
2351         uint64_t align;
2352         spa_t *spa = zio->io_spa;
2353
2354         ASSERT(zio->io_error == 0);
2355         ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
2356
2357         if (vd == NULL) {
2358                 if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
2359                         spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
2360
2361                 /*
2362                  * The mirror_ops handle multiple DVAs in a single BP.
2363                  */
2364                 return (vdev_mirror_ops.vdev_op_io_start(zio));
2365         }
2366
2367         if (vd->vdev_ops->vdev_op_leaf && zio->io_type == ZIO_TYPE_FREE) {
2368                 trim_map_free(zio);
2369                 return (ZIO_PIPELINE_CONTINUE);
2370         }
2371
2372         /*
2373          * We keep track of time-sensitive I/Os so that the scan thread
2374          * can quickly react to certain workloads.  In particular, we care
2375          * about non-scrubbing, top-level reads and writes with the following
2376          * characteristics:
2377          *      - synchronous writes of user data to non-slog devices
2378          *      - any reads of user data
2379          * When these conditions are met, adjust the timestamp of spa_last_io
2380          * which allows the scan thread to adjust its workload accordingly.
2381          */
2382         if (!(zio->io_flags & ZIO_FLAG_SCAN_THREAD) && zio->io_bp != NULL &&
2383             vd == vd->vdev_top && !vd->vdev_islog &&
2384             zio->io_bookmark.zb_objset != DMU_META_OBJSET &&
2385             zio->io_txg != spa_syncing_txg(spa)) {
2386                 uint64_t old = spa->spa_last_io;
2387                 uint64_t new = ddi_get_lbolt64();
2388                 if (old != new)
2389                         (void) atomic_cas_64(&spa->spa_last_io, old, new);
2390         }
2391
2392         align = 1ULL << vd->vdev_top->vdev_ashift;
2393
2394         if (P2PHASE(zio->io_size, align) != 0) {
2395                 uint64_t asize = P2ROUNDUP(zio->io_size, align);
2396                 char *abuf = NULL;
2397                 if (zio->io_type == ZIO_TYPE_READ ||
2398                     zio->io_type == ZIO_TYPE_WRITE)
2399                         abuf = zio_buf_alloc(asize);
2400                 ASSERT(vd == vd->vdev_top);
2401                 if (zio->io_type == ZIO_TYPE_WRITE) {
2402                         bcopy(zio->io_data, abuf, zio->io_size);
2403                         bzero(abuf + zio->io_size, asize - zio->io_size);
2404                 }
2405                 zio_push_transform(zio, abuf, asize, abuf ? asize : 0,
2406                     zio_subblock);
2407         }
2408
2409         ASSERT(P2PHASE(zio->io_offset, align) == 0);
2410         ASSERT(P2PHASE(zio->io_size, align) == 0);
2411         VERIFY(zio->io_type == ZIO_TYPE_READ || spa_writeable(spa));
2412
2413         /*
2414          * If this is a repair I/O, and there's no self-healing involved --
2415          * that is, we're just resilvering what we expect to resilver --
2416          * then don't do the I/O unless zio's txg is actually in vd's DTL.
2417          * This prevents spurious resilvering with nested replication.
2418          * For example, given a mirror of mirrors, (A+B)+(C+D), if only
2419          * A is out of date, we'll read from C+D, then use the data to
2420          * resilver A+B -- but we don't actually want to resilver B, just A.
2421          * The top-level mirror has no way to know this, so instead we just
2422          * discard unnecessary repairs as we work our way down the vdev tree.
2423          * The same logic applies to any form of nested replication:
2424          * ditto + mirror, RAID-Z + replacing, etc.  This covers them all.
2425          */
2426         if ((zio->io_flags & ZIO_FLAG_IO_REPAIR) &&
2427             !(zio->io_flags & ZIO_FLAG_SELF_HEAL) &&
2428             zio->io_txg != 0 && /* not a delegated i/o */
2429             !vdev_dtl_contains(vd, DTL_PARTIAL, zio->io_txg, 1)) {
2430                 ASSERT(zio->io_type == ZIO_TYPE_WRITE);
2431                 zio_vdev_io_bypass(zio);
2432                 return (ZIO_PIPELINE_CONTINUE);
2433         }
2434
2435         if (vd->vdev_ops->vdev_op_leaf &&
2436             (zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE)) {
2437
2438                 if (zio->io_type == ZIO_TYPE_READ && vdev_cache_read(zio) == 0)
2439                         return (ZIO_PIPELINE_CONTINUE);
2440
2441                 if ((zio = vdev_queue_io(zio)) == NULL)
2442                         return (ZIO_PIPELINE_STOP);
2443
2444                 if (!vdev_accessible(vd, zio)) {
2445                         zio->io_error = ENXIO;
2446                         zio_interrupt(zio);
2447                         return (ZIO_PIPELINE_STOP);
2448                 }
2449         }
2450
2451         if (vd->vdev_ops->vdev_op_leaf && zio->io_type == ZIO_TYPE_WRITE) {
2452                 if (!trim_map_write_start(zio))
2453                         return (ZIO_PIPELINE_STOP);
2454         }
2455
2456         return (vd->vdev_ops->vdev_op_io_start(zio));
2457 }
2458
2459 static int
2460 zio_vdev_io_done(zio_t *zio)
2461 {
2462         vdev_t *vd = zio->io_vd;
2463         vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
2464         boolean_t unexpected_error = B_FALSE;
2465
2466         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
2467                 return (ZIO_PIPELINE_STOP);
2468
2469         ASSERT(zio->io_type == ZIO_TYPE_READ ||
2470             zio->io_type == ZIO_TYPE_WRITE || zio->io_type == ZIO_TYPE_FREE);
2471
2472         if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
2473             zio->io_type == ZIO_TYPE_WRITE) {
2474                 trim_map_write_done(zio);
2475         }
2476
2477         if (vd != NULL && vd->vdev_ops->vdev_op_leaf &&
2478             (zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE)) {
2479
2480                 vdev_queue_io_done(zio);
2481
2482                 if (zio->io_type == ZIO_TYPE_WRITE)
2483                         vdev_cache_write(zio);
2484
2485                 if (zio_injection_enabled && zio->io_error == 0)
2486                         zio->io_error = zio_handle_device_injection(vd,
2487                             zio, EIO);
2488
2489                 if (zio_injection_enabled && zio->io_error == 0)
2490                         zio->io_error = zio_handle_label_injection(zio, EIO);
2491
2492                 if (zio->io_error) {
2493                         if (!vdev_accessible(vd, zio)) {
2494                                 zio->io_error = ENXIO;
2495                         } else {
2496                                 unexpected_error = B_TRUE;
2497                         }
2498                 }
2499         }
2500
2501         ops->vdev_op_io_done(zio);
2502
2503         if (unexpected_error)
2504                 VERIFY(vdev_probe(vd, zio) == NULL);
2505
2506         return (ZIO_PIPELINE_CONTINUE);
2507 }
2508
2509 /*
2510  * For non-raidz ZIOs, we can just copy aside the bad data read from the
2511  * disk, and use that to finish the checksum ereport later.
2512  */
2513 static void
2514 zio_vsd_default_cksum_finish(zio_cksum_report_t *zcr,
2515     const void *good_buf)
2516 {
2517         /* no processing needed */
2518         zfs_ereport_finish_checksum(zcr, good_buf, zcr->zcr_cbdata, B_FALSE);
2519 }
2520
2521 /*ARGSUSED*/
2522 void
2523 zio_vsd_default_cksum_report(zio_t *zio, zio_cksum_report_t *zcr, void *ignored)
2524 {
2525         void *buf = zio_buf_alloc(zio->io_size);
2526
2527         bcopy(zio->io_data, buf, zio->io_size);
2528
2529         zcr->zcr_cbinfo = zio->io_size;
2530         zcr->zcr_cbdata = buf;
2531         zcr->zcr_finish = zio_vsd_default_cksum_finish;
2532         zcr->zcr_free = zio_buf_free;
2533 }
2534
2535 static int
2536 zio_vdev_io_assess(zio_t *zio)
2537 {
2538         vdev_t *vd = zio->io_vd;
2539
2540         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
2541                 return (ZIO_PIPELINE_STOP);
2542
2543         if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
2544                 spa_config_exit(zio->io_spa, SCL_ZIO, zio);
2545
2546         if (zio->io_vsd != NULL) {
2547                 zio->io_vsd_ops->vsd_free(zio);
2548                 zio->io_vsd = NULL;
2549         }
2550
2551         if (zio_injection_enabled && zio->io_error == 0)
2552                 zio->io_error = zio_handle_fault_injection(zio, EIO);
2553
2554         if (zio->io_type == ZIO_TYPE_IOCTL && zio->io_cmd == DKIOCTRIM)
2555                 switch (zio->io_error) {
2556                 case 0:
2557                         ZIO_TRIM_STAT_INCR(zio_trim_bytes, zio->io_size);
2558                         ZIO_TRIM_STAT_BUMP(zio_trim_success);
2559                         break;
2560                 case EOPNOTSUPP:
2561                         ZIO_TRIM_STAT_BUMP(zio_trim_unsupported);
2562                         break;
2563                 default:
2564                         ZIO_TRIM_STAT_BUMP(zio_trim_failed);
2565                         break;
2566                 }
2567
2568         /*
2569          * If the I/O failed, determine whether we should attempt to retry it.
2570          *
2571          * On retry, we cut in line in the issue queue, since we don't want
2572          * compression/checksumming/etc. work to prevent our (cheap) IO reissue.
2573          */
2574         if (zio->io_error && vd == NULL &&
2575             !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
2576                 ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE)); /* not a leaf */
2577                 ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));  /* not a leaf */
2578                 zio->io_error = 0;
2579                 zio->io_flags |= ZIO_FLAG_IO_RETRY |
2580                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE;
2581                 zio->io_stage = ZIO_STAGE_VDEV_IO_START >> 1;
2582                 zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE,
2583                     zio_requeue_io_start_cut_in_line);
2584                 return (ZIO_PIPELINE_STOP);
2585         }
2586
2587         /*
2588          * If we got an error on a leaf device, convert it to ENXIO
2589          * if the device is not accessible at all.
2590          */
2591         if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
2592             !vdev_accessible(vd, zio))
2593                 zio->io_error = ENXIO;
2594
2595         /*
2596          * If we can't write to an interior vdev (mirror or RAID-Z),
2597          * set vdev_cant_write so that we stop trying to allocate from it.
2598          */
2599         if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
2600             vd != NULL && !vd->vdev_ops->vdev_op_leaf)
2601                 vd->vdev_cant_write = B_TRUE;
2602
2603         if (zio->io_error)
2604                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2605
2606         return (ZIO_PIPELINE_CONTINUE);
2607 }
2608
2609 void
2610 zio_vdev_io_reissue(zio_t *zio)
2611 {
2612         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
2613         ASSERT(zio->io_error == 0);
2614
2615         zio->io_stage >>= 1;
2616 }
2617
2618 void
2619 zio_vdev_io_redone(zio_t *zio)
2620 {
2621         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
2622
2623         zio->io_stage >>= 1;
2624 }
2625
2626 void
2627 zio_vdev_io_bypass(zio_t *zio)
2628 {
2629         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
2630         ASSERT(zio->io_error == 0);
2631
2632         zio->io_flags |= ZIO_FLAG_IO_BYPASS;
2633         zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS >> 1;
2634 }
2635
2636 /*
2637  * ==========================================================================
2638  * Generate and verify checksums
2639  * ==========================================================================
2640  */
2641 static int
2642 zio_checksum_generate(zio_t *zio)
2643 {
2644         blkptr_t *bp = zio->io_bp;
2645         enum zio_checksum checksum;
2646
2647         if (bp == NULL) {
2648                 /*
2649                  * This is zio_write_phys().
2650                  * We're either generating a label checksum, or none at all.
2651                  */
2652                 checksum = zio->io_prop.zp_checksum;
2653
2654                 if (checksum == ZIO_CHECKSUM_OFF)
2655                         return (ZIO_PIPELINE_CONTINUE);
2656
2657                 ASSERT(checksum == ZIO_CHECKSUM_LABEL);
2658         } else {
2659                 if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
2660                         ASSERT(!IO_IS_ALLOCATING(zio));
2661                         checksum = ZIO_CHECKSUM_GANG_HEADER;
2662                 } else {
2663                         checksum = BP_GET_CHECKSUM(bp);
2664                 }
2665         }
2666
2667         zio_checksum_compute(zio, checksum, zio->io_data, zio->io_size);
2668
2669         return (ZIO_PIPELINE_CONTINUE);
2670 }
2671
2672 static int
2673 zio_checksum_verify(zio_t *zio)
2674 {
2675         zio_bad_cksum_t info;
2676         blkptr_t *bp = zio->io_bp;
2677         int error;
2678
2679         ASSERT(zio->io_vd != NULL);
2680
2681         if (bp == NULL) {
2682                 /*
2683                  * This is zio_read_phys().
2684                  * We're either verifying a label checksum, or nothing at all.
2685                  */
2686                 if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
2687                         return (ZIO_PIPELINE_CONTINUE);
2688
2689                 ASSERT(zio->io_prop.zp_checksum == ZIO_CHECKSUM_LABEL);
2690         }
2691
2692         if ((error = zio_checksum_error(zio, &info)) != 0) {
2693                 zio->io_error = error;
2694                 if (!(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2695                         zfs_ereport_start_checksum(zio->io_spa,
2696                             zio->io_vd, zio, zio->io_offset,
2697                             zio->io_size, NULL, &info);
2698                 }
2699         }
2700
2701         return (ZIO_PIPELINE_CONTINUE);
2702 }
2703
2704 /*
2705  * Called by RAID-Z to ensure we don't compute the checksum twice.
2706  */
2707 void
2708 zio_checksum_verified(zio_t *zio)
2709 {
2710         zio->io_pipeline &= ~ZIO_STAGE_CHECKSUM_VERIFY;
2711 }
2712
2713 /*
2714  * ==========================================================================
2715  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
2716  * An error of 0 indictes success.  ENXIO indicates whole-device failure,
2717  * which may be transient (e.g. unplugged) or permament.  ECKSUM and EIO
2718  * indicate errors that are specific to one I/O, and most likely permanent.
2719  * Any other error is presumed to be worse because we weren't expecting it.
2720  * ==========================================================================
2721  */
2722 int
2723 zio_worst_error(int e1, int e2)
2724 {
2725         static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
2726         int r1, r2;
2727
2728         for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
2729                 if (e1 == zio_error_rank[r1])
2730                         break;
2731
2732         for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
2733                 if (e2 == zio_error_rank[r2])
2734                         break;
2735
2736         return (r1 > r2 ? e1 : e2);
2737 }
2738
2739 /*
2740  * ==========================================================================
2741  * I/O completion
2742  * ==========================================================================
2743  */
2744 static int
2745 zio_ready(zio_t *zio)
2746 {
2747         blkptr_t *bp = zio->io_bp;
2748         zio_t *pio, *pio_next;
2749
2750         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
2751             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_READY))
2752                 return (ZIO_PIPELINE_STOP);
2753
2754         if (zio->io_ready) {
2755                 ASSERT(IO_IS_ALLOCATING(zio));
2756                 ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
2757                 ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
2758
2759                 zio->io_ready(zio);
2760         }
2761
2762         if (bp != NULL && bp != &zio->io_bp_copy)
2763                 zio->io_bp_copy = *bp;
2764
2765         if (zio->io_error)
2766                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2767
2768         mutex_enter(&zio->io_lock);
2769         zio->io_state[ZIO_WAIT_READY] = 1;
2770         pio = zio_walk_parents(zio);
2771         mutex_exit(&zio->io_lock);
2772
2773         /*
2774          * As we notify zio's parents, new parents could be added.
2775          * New parents go to the head of zio's io_parent_list, however,
2776          * so we will (correctly) not notify them.  The remainder of zio's
2777          * io_parent_list, from 'pio_next' onward, cannot change because
2778          * all parents must wait for us to be done before they can be done.
2779          */
2780         for (; pio != NULL; pio = pio_next) {
2781                 pio_next = zio_walk_parents(zio);
2782                 zio_notify_parent(pio, zio, ZIO_WAIT_READY);
2783         }
2784
2785         if (zio->io_flags & ZIO_FLAG_NODATA) {
2786                 if (BP_IS_GANG(bp)) {
2787                         zio->io_flags &= ~ZIO_FLAG_NODATA;
2788                 } else {
2789                         ASSERT((uintptr_t)zio->io_data < SPA_MAXBLOCKSIZE);
2790                         zio->io_pipeline &= ~ZIO_VDEV_IO_STAGES;
2791                 }
2792         }
2793
2794         if (zio_injection_enabled &&
2795             zio->io_spa->spa_syncing_txg == zio->io_txg)
2796                 zio_handle_ignored_writes(zio);
2797
2798         return (ZIO_PIPELINE_CONTINUE);
2799 }
2800
2801 static int
2802 zio_done(zio_t *zio)
2803 {
2804         spa_t *spa = zio->io_spa;
2805         zio_t *lio = zio->io_logical;
2806         blkptr_t *bp = zio->io_bp;
2807         vdev_t *vd = zio->io_vd;
2808         uint64_t psize = zio->io_size;
2809         zio_t *pio, *pio_next;
2810
2811         /*
2812          * If our children haven't all completed,
2813          * wait for them and then repeat this pipeline stage.
2814          */
2815         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE) ||
2816             zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE) ||
2817             zio_wait_for_children(zio, ZIO_CHILD_DDT, ZIO_WAIT_DONE) ||
2818             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_DONE))
2819                 return (ZIO_PIPELINE_STOP);
2820
2821         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
2822                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
2823                         ASSERT(zio->io_children[c][w] == 0);
2824
2825         if (bp != NULL) {
2826                 ASSERT(bp->blk_pad[0] == 0);
2827                 ASSERT(bp->blk_pad[1] == 0);
2828                 ASSERT(bcmp(bp, &zio->io_bp_copy, sizeof (blkptr_t)) == 0 ||
2829                     (bp == zio_unique_parent(zio)->io_bp));
2830                 if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(bp) &&
2831                     zio->io_bp_override == NULL &&
2832                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
2833                         ASSERT(!BP_SHOULD_BYTESWAP(bp));
2834                         ASSERT3U(zio->io_prop.zp_copies, <=, BP_GET_NDVAS(bp));
2835                         ASSERT(BP_COUNT_GANG(bp) == 0 ||
2836                             (BP_COUNT_GANG(bp) == BP_GET_NDVAS(bp)));
2837                 }
2838         }
2839
2840         /*
2841          * If there were child vdev/gang/ddt errors, they apply to us now.
2842          */
2843         zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
2844         zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
2845         zio_inherit_child_errors(zio, ZIO_CHILD_DDT);
2846
2847         /*
2848          * If the I/O on the transformed data was successful, generate any
2849          * checksum reports now while we still have the transformed data.
2850          */
2851         if (zio->io_error == 0) {
2852                 while (zio->io_cksum_report != NULL) {
2853                         zio_cksum_report_t *zcr = zio->io_cksum_report;
2854                         uint64_t align = zcr->zcr_align;
2855                         uint64_t asize = P2ROUNDUP(psize, align);
2856                         char *abuf = zio->io_data;
2857
2858                         if (asize != psize) {
2859                                 abuf = zio_buf_alloc(asize);
2860                                 bcopy(zio->io_data, abuf, psize);
2861                                 bzero(abuf + psize, asize - psize);
2862                         }
2863
2864                         zio->io_cksum_report = zcr->zcr_next;
2865                         zcr->zcr_next = NULL;
2866                         zcr->zcr_finish(zcr, abuf);
2867                         zfs_ereport_free_checksum(zcr);
2868
2869                         if (asize != psize)
2870                                 zio_buf_free(abuf, asize);
2871                 }
2872         }
2873
2874         zio_pop_transforms(zio);        /* note: may set zio->io_error */
2875
2876         vdev_stat_update(zio, psize);
2877
2878         if (zio->io_error) {
2879                 /*
2880                  * If this I/O is attached to a particular vdev,
2881                  * generate an error message describing the I/O failure
2882                  * at the block level.  We ignore these errors if the
2883                  * device is currently unavailable.
2884                  */
2885                 if (zio->io_error != ECKSUM && vd != NULL && !vdev_is_dead(vd))
2886                         zfs_ereport_post(FM_EREPORT_ZFS_IO, spa, vd, zio, 0, 0);
2887
2888                 if ((zio->io_error == EIO || !(zio->io_flags &
2889                     (ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_PROPAGATE))) &&
2890                     zio == lio) {
2891                         /*
2892                          * For logical I/O requests, tell the SPA to log the
2893                          * error and generate a logical data ereport.
2894                          */
2895                         spa_log_error(spa, zio);
2896                         zfs_ereport_post(FM_EREPORT_ZFS_DATA, spa, NULL, zio,
2897                             0, 0);
2898                 }
2899         }
2900
2901         if (zio->io_error && zio == lio) {
2902                 /*
2903                  * Determine whether zio should be reexecuted.  This will
2904                  * propagate all the way to the root via zio_notify_parent().
2905                  */
2906                 ASSERT(vd == NULL && bp != NULL);
2907                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2908
2909                 if (IO_IS_ALLOCATING(zio) &&
2910                     !(zio->io_flags & ZIO_FLAG_CANFAIL)) {
2911                         if (zio->io_error != ENOSPC)
2912                                 zio->io_reexecute |= ZIO_REEXECUTE_NOW;
2913                         else
2914                                 zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2915                 }
2916
2917                 if ((zio->io_type == ZIO_TYPE_READ ||
2918                     zio->io_type == ZIO_TYPE_FREE) &&
2919                     !(zio->io_flags & ZIO_FLAG_SCAN_THREAD) &&
2920                     zio->io_error == ENXIO &&
2921                     spa_load_state(spa) == SPA_LOAD_NONE &&
2922                     spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE)
2923                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2924
2925                 if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
2926                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2927
2928                 /*
2929                  * Here is a possibly good place to attempt to do
2930                  * either combinatorial reconstruction or error correction
2931                  * based on checksums.  It also might be a good place
2932                  * to send out preliminary ereports before we suspend
2933                  * processing.
2934                  */
2935         }
2936
2937         /*
2938          * If there were logical child errors, they apply to us now.
2939          * We defer this until now to avoid conflating logical child
2940          * errors with errors that happened to the zio itself when
2941          * updating vdev stats and reporting FMA events above.
2942          */
2943         zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
2944
2945         if ((zio->io_error || zio->io_reexecute) &&
2946             IO_IS_ALLOCATING(zio) && zio->io_gang_leader == zio &&
2947             !(zio->io_flags & ZIO_FLAG_IO_REWRITE))
2948                 zio_dva_unallocate(zio, zio->io_gang_tree, bp);
2949
2950         zio_gang_tree_free(&zio->io_gang_tree);
2951
2952         /*
2953          * Godfather I/Os should never suspend.
2954          */
2955         if ((zio->io_flags & ZIO_FLAG_GODFATHER) &&
2956             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND))
2957                 zio->io_reexecute = 0;
2958
2959         if (zio->io_reexecute) {
2960                 /*
2961                  * This is a logical I/O that wants to reexecute.
2962                  *
2963                  * Reexecute is top-down.  When an i/o fails, if it's not
2964                  * the root, it simply notifies its parent and sticks around.
2965                  * The parent, seeing that it still has children in zio_done(),
2966                  * does the same.  This percolates all the way up to the root.
2967                  * The root i/o will reexecute or suspend the entire tree.
2968                  *
2969                  * This approach ensures that zio_reexecute() honors
2970                  * all the original i/o dependency relationships, e.g.
2971                  * parents not executing until children are ready.
2972                  */
2973                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2974
2975                 zio->io_gang_leader = NULL;
2976
2977                 mutex_enter(&zio->io_lock);
2978                 zio->io_state[ZIO_WAIT_DONE] = 1;
2979                 mutex_exit(&zio->io_lock);
2980
2981                 /*
2982                  * "The Godfather" I/O monitors its children but is
2983                  * not a true parent to them. It will track them through
2984                  * the pipeline but severs its ties whenever they get into
2985                  * trouble (e.g. suspended). This allows "The Godfather"
2986                  * I/O to return status without blocking.
2987                  */
2988                 for (pio = zio_walk_parents(zio); pio != NULL; pio = pio_next) {
2989                         zio_link_t *zl = zio->io_walk_link;
2990                         pio_next = zio_walk_parents(zio);
2991
2992                         if ((pio->io_flags & ZIO_FLAG_GODFATHER) &&
2993                             (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND)) {
2994                                 zio_remove_child(pio, zio, zl);
2995                                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
2996                         }
2997                 }
2998
2999                 if ((pio = zio_unique_parent(zio)) != NULL) {
3000                         /*
3001                          * We're not a root i/o, so there's nothing to do
3002                          * but notify our parent.  Don't propagate errors
3003                          * upward since we haven't permanently failed yet.
3004                          */
3005                         ASSERT(!(zio->io_flags & ZIO_FLAG_GODFATHER));
3006                         zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
3007                         zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3008                 } else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
3009                         /*
3010                          * We'd fail again if we reexecuted now, so suspend
3011                          * until conditions improve (e.g. device comes online).
3012                          */
3013                         zio_suspend(spa, zio);
3014                 } else {
3015                         /*
3016                          * Reexecution is potentially a huge amount of work.
3017                          * Hand it off to the otherwise-unused claim taskq.
3018                          */
3019 #ifdef _KERNEL
3020                         (void) taskq_dispatch_safe(
3021                             spa->spa_zio_taskq[ZIO_TYPE_CLAIM][ZIO_TASKQ_ISSUE],
3022                             (task_func_t *)zio_reexecute, zio, TQ_SLEEP,
3023                             &zio->io_task);
3024 #else
3025                         (void) taskq_dispatch(
3026                             spa->spa_zio_taskq[ZIO_TYPE_CLAIM][ZIO_TASKQ_ISSUE],
3027                             (task_func_t *)zio_reexecute, zio, TQ_SLEEP);
3028 #endif
3029                 }
3030                 return (ZIO_PIPELINE_STOP);
3031         }
3032
3033         ASSERT(zio->io_child_count == 0);
3034         ASSERT(zio->io_reexecute == 0);
3035         ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
3036
3037         /*
3038          * Report any checksum errors, since the I/O is complete.
3039          */
3040         while (zio->io_cksum_report != NULL) {
3041                 zio_cksum_report_t *zcr = zio->io_cksum_report;
3042                 zio->io_cksum_report = zcr->zcr_next;
3043                 zcr->zcr_next = NULL;
3044                 zcr->zcr_finish(zcr, NULL);
3045                 zfs_ereport_free_checksum(zcr);
3046         }
3047
3048         /*
3049          * It is the responsibility of the done callback to ensure that this
3050          * particular zio is no longer discoverable for adoption, and as
3051          * such, cannot acquire any new parents.
3052          */
3053         if (zio->io_done)
3054                 zio->io_done(zio);
3055
3056         mutex_enter(&zio->io_lock);
3057         zio->io_state[ZIO_WAIT_DONE] = 1;
3058         mutex_exit(&zio->io_lock);
3059
3060         for (pio = zio_walk_parents(zio); pio != NULL; pio = pio_next) {
3061                 zio_link_t *zl = zio->io_walk_link;
3062                 pio_next = zio_walk_parents(zio);
3063                 zio_remove_child(pio, zio, zl);
3064                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
3065         }
3066
3067         if (zio->io_waiter != NULL) {
3068                 mutex_enter(&zio->io_lock);
3069                 zio->io_executor = NULL;
3070                 cv_broadcast(&zio->io_cv);
3071                 mutex_exit(&zio->io_lock);
3072         } else {
3073                 zio_destroy(zio);
3074         }
3075
3076         return (ZIO_PIPELINE_STOP);
3077 }
3078
3079 /*
3080  * ==========================================================================
3081  * I/O pipeline definition
3082  * ==========================================================================
3083  */
3084 static zio_pipe_stage_t *zio_pipeline[] = {
3085         NULL,
3086         zio_read_bp_init,
3087         zio_free_bp_init,
3088         zio_issue_async,
3089         zio_write_bp_init,
3090         zio_checksum_generate,
3091         zio_ddt_read_start,
3092         zio_ddt_read_done,
3093         zio_ddt_write,
3094         zio_ddt_free,
3095         zio_gang_assemble,
3096         zio_gang_issue,
3097         zio_dva_allocate,
3098         zio_dva_free,
3099         zio_dva_claim,
3100         zio_ready,
3101         zio_vdev_io_start,
3102         zio_vdev_io_done,
3103         zio_vdev_io_assess,
3104         zio_checksum_verify,
3105         zio_done
3106 };
3107
3108 /* dnp is the dnode for zb1->zb_object */
3109 boolean_t
3110 zbookmark_is_before(const dnode_phys_t *dnp, const zbookmark_t *zb1,
3111     const zbookmark_t *zb2)
3112 {
3113         uint64_t zb1nextL0, zb2thisobj;
3114
3115         ASSERT(zb1->zb_objset == zb2->zb_objset);
3116         ASSERT(zb2->zb_level == 0);
3117
3118         /*
3119          * A bookmark in the deadlist is considered to be after
3120          * everything else.
3121          */
3122         if (zb2->zb_object == DMU_DEADLIST_OBJECT)
3123                 return (B_TRUE);
3124
3125         /* The objset_phys_t isn't before anything. */
3126         if (dnp == NULL)
3127                 return (B_FALSE);
3128
3129         zb1nextL0 = (zb1->zb_blkid + 1) <<
3130             ((zb1->zb_level) * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT));
3131
3132         zb2thisobj = zb2->zb_object ? zb2->zb_object :
3133             zb2->zb_blkid << (DNODE_BLOCK_SHIFT - DNODE_SHIFT);
3134
3135         if (zb1->zb_object == DMU_META_DNODE_OBJECT) {
3136                 uint64_t nextobj = zb1nextL0 *
3137                     (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT) >> DNODE_SHIFT;
3138                 return (nextobj <= zb2thisobj);
3139         }
3140
3141         if (zb1->zb_object < zb2thisobj)
3142                 return (B_TRUE);
3143         if (zb1->zb_object > zb2thisobj)
3144                 return (B_FALSE);
3145         if (zb2->zb_object == DMU_META_DNODE_OBJECT)
3146                 return (B_FALSE);
3147         return (zb1nextL0 <= zb2->zb_blkid);
3148 }