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