]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zio.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25
26 #include <sys/zfs_context.h>
27 #include <sys/fm/fs/zfs.h>
28 #include <sys/spa.h>
29 #include <sys/txg.h>
30 #include <sys/spa_impl.h>
31 #include <sys/vdev_impl.h>
32 #include <sys/zio_impl.h>
33 #include <sys/zio_compress.h>
34 #include <sys/zio_checksum.h>
35
36 #if defined(__amd64__)
37 static int zio_use_uma = 1;
38 #else
39 static int zio_use_uma = 0;
40 #endif
41 SYSCTL_DECL(_vfs_zfs);
42 SYSCTL_NODE(_vfs_zfs, OID_AUTO, zio, CTLFLAG_RW, 0, "ZFS ZIO");
43 TUNABLE_INT("vfs.zfs.zio.use_uma", &zio_use_uma);
44 SYSCTL_INT(_vfs_zfs_zio, OID_AUTO, use_uma, CTLFLAG_RDTUN, &zio_use_uma, 0,
45     "Use uma(9) for ZIO allocations");
46
47 /*
48  * ==========================================================================
49  * I/O priority table
50  * ==========================================================================
51  */
52 uint8_t zio_priority_table[ZIO_PRIORITY_TABLE_SIZE] = {
53         0,      /* ZIO_PRIORITY_NOW             */
54         0,      /* ZIO_PRIORITY_SYNC_READ       */
55         0,      /* ZIO_PRIORITY_SYNC_WRITE      */
56         6,      /* ZIO_PRIORITY_ASYNC_READ      */
57         4,      /* ZIO_PRIORITY_ASYNC_WRITE     */
58         4,      /* ZIO_PRIORITY_FREE            */
59         0,      /* ZIO_PRIORITY_CACHE_FILL      */
60         0,      /* ZIO_PRIORITY_LOG_WRITE       */
61         10,     /* ZIO_PRIORITY_RESILVER        */
62         20,     /* ZIO_PRIORITY_SCRUB           */
63 };
64
65 /*
66  * ==========================================================================
67  * I/O type descriptions
68  * ==========================================================================
69  */
70 char *zio_type_name[ZIO_TYPES] = {
71         "null", "read", "write", "free", "claim", "ioctl" };
72
73 #define SYNC_PASS_DEFERRED_FREE 1       /* defer frees after this pass */
74 #define SYNC_PASS_DONT_COMPRESS 4       /* don't compress after this pass */
75 #define SYNC_PASS_REWRITE       1       /* rewrite new bps after this pass */
76
77 /*
78  * ==========================================================================
79  * I/O kmem caches
80  * ==========================================================================
81  */
82 kmem_cache_t *zio_cache;
83 kmem_cache_t *zio_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
84 kmem_cache_t *zio_data_buf_cache[SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT];
85
86 #ifdef _KERNEL
87 extern vmem_t *zio_alloc_arena;
88 #endif
89
90 /*
91  * An allocating zio is one that either currently has the DVA allocate
92  * stage set or will have it later in its lifetime.
93  */
94 #define IO_IS_ALLOCATING(zio) \
95         ((zio)->io_orig_pipeline & (1U << ZIO_STAGE_DVA_ALLOCATE))
96
97 void
98 zio_init(void)
99 {
100         size_t c;
101         zio_cache = kmem_cache_create("zio_cache", sizeof (zio_t), 0,
102             NULL, NULL, NULL, NULL, NULL, 0);
103
104         /*
105          * For small buffers, we want a cache for each multiple of
106          * SPA_MINBLOCKSIZE.  For medium-size buffers, we want a cache
107          * for each quarter-power of 2.  For large buffers, we want
108          * a cache for each multiple of PAGESIZE.
109          */
110         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
111                 size_t size = (c + 1) << SPA_MINBLOCKSHIFT;
112                 size_t p2 = size;
113                 size_t align = 0;
114
115                 while (p2 & (p2 - 1))
116                         p2 &= p2 - 1;
117
118                 if (size <= 4 * SPA_MINBLOCKSIZE) {
119                         align = SPA_MINBLOCKSIZE;
120                 } else if (P2PHASE(size, PAGESIZE) == 0) {
121                         align = PAGESIZE;
122                 } else if (P2PHASE(size, p2 >> 2) == 0) {
123                         align = p2 >> 2;
124                 }
125
126                 if (align != 0) {
127                         char name[36];
128                         (void) sprintf(name, "zio_buf_%lu", (ulong_t)size);
129                         zio_buf_cache[c] = kmem_cache_create(name, size,
130                             align, NULL, NULL, NULL, NULL, NULL, KMC_NODEBUG);
131
132                         (void) sprintf(name, "zio_data_buf_%lu", (ulong_t)size);
133                         zio_data_buf_cache[c] = kmem_cache_create(name, size,
134                             align, NULL, NULL, NULL, NULL, NULL, KMC_NODEBUG);
135                 }
136         }
137
138         while (--c != 0) {
139                 ASSERT(zio_buf_cache[c] != NULL);
140                 if (zio_buf_cache[c - 1] == NULL)
141                         zio_buf_cache[c - 1] = zio_buf_cache[c];
142
143                 ASSERT(zio_data_buf_cache[c] != NULL);
144                 if (zio_data_buf_cache[c - 1] == NULL)
145                         zio_data_buf_cache[c - 1] = zio_data_buf_cache[c];
146         }
147
148         zio_inject_init();
149 }
150
151 void
152 zio_fini(void)
153 {
154         size_t c;
155         kmem_cache_t *last_cache = NULL;
156         kmem_cache_t *last_data_cache = NULL;
157
158         for (c = 0; c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; c++) {
159                 if (zio_buf_cache[c] != last_cache) {
160                         last_cache = zio_buf_cache[c];
161                         kmem_cache_destroy(zio_buf_cache[c]);
162                 }
163                 zio_buf_cache[c] = NULL;
164
165                 if (zio_data_buf_cache[c] != last_data_cache) {
166                         last_data_cache = zio_data_buf_cache[c];
167                         kmem_cache_destroy(zio_data_buf_cache[c]);
168                 }
169                 zio_data_buf_cache[c] = NULL;
170         }
171
172         kmem_cache_destroy(zio_cache);
173
174         zio_inject_fini();
175 }
176
177 /*
178  * ==========================================================================
179  * Allocate and free I/O buffers
180  * ==========================================================================
181  */
182
183 /*
184  * Use zio_buf_alloc to allocate ZFS metadata.  This data will appear in a
185  * crashdump if the kernel panics, so use it judiciously.  Obviously, it's
186  * useful to inspect ZFS metadata, but if possible, we should avoid keeping
187  * excess / transient data in-core during a crashdump.
188  */
189 void *
190 zio_buf_alloc(size_t size)
191 {
192         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
193
194         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
195
196         if (zio_use_uma)
197                 return (kmem_cache_alloc(zio_buf_cache[c], KM_PUSHPAGE));
198         else
199                 return (kmem_alloc(size, KM_SLEEP));
200 }
201
202 /*
203  * Use zio_data_buf_alloc to allocate data.  The data will not appear in a
204  * crashdump if the kernel panics.  This exists so that we will limit the amount
205  * of ZFS data that shows up in a kernel crashdump.  (Thus reducing the amount
206  * of kernel heap dumped to disk when the kernel panics)
207  */
208 void *
209 zio_data_buf_alloc(size_t size)
210 {
211         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
212
213         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
214
215         if (zio_use_uma)
216                 return (kmem_cache_alloc(zio_data_buf_cache[c], KM_PUSHPAGE));
217         else
218                 return (kmem_alloc(size, KM_SLEEP));
219 }
220
221 void
222 zio_buf_free(void *buf, size_t size)
223 {
224         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
225
226         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
227
228         if (zio_use_uma)
229                 kmem_cache_free(zio_buf_cache[c], buf);
230         else
231                 kmem_free(buf, size);
232 }
233
234 void
235 zio_data_buf_free(void *buf, size_t size)
236 {
237         size_t c = (size - 1) >> SPA_MINBLOCKSHIFT;
238
239         ASSERT(c < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT);
240
241         if (zio_use_uma)
242                 kmem_cache_free(zio_data_buf_cache[c], buf);
243         else
244                 kmem_free(buf, size);
245 }
246
247 /*
248  * ==========================================================================
249  * Push and pop I/O transform buffers
250  * ==========================================================================
251  */
252 static void
253 zio_push_transform(zio_t *zio, void *data, uint64_t size, uint64_t bufsize,
254         zio_transform_func_t *transform)
255 {
256         zio_transform_t *zt = kmem_alloc(sizeof (zio_transform_t), KM_SLEEP);
257
258         zt->zt_orig_data = zio->io_data;
259         zt->zt_orig_size = zio->io_size;
260         zt->zt_bufsize = bufsize;
261         zt->zt_transform = transform;
262
263         zt->zt_next = zio->io_transform_stack;
264         zio->io_transform_stack = zt;
265
266         zio->io_data = data;
267         zio->io_size = size;
268 }
269
270 static void
271 zio_pop_transforms(zio_t *zio)
272 {
273         zio_transform_t *zt;
274
275         while ((zt = zio->io_transform_stack) != NULL) {
276                 if (zt->zt_transform != NULL)
277                         zt->zt_transform(zio,
278                             zt->zt_orig_data, zt->zt_orig_size);
279
280                 zio_buf_free(zio->io_data, zt->zt_bufsize);
281
282                 zio->io_data = zt->zt_orig_data;
283                 zio->io_size = zt->zt_orig_size;
284                 zio->io_transform_stack = zt->zt_next;
285
286                 kmem_free(zt, sizeof (zio_transform_t));
287         }
288 }
289
290 /*
291  * ==========================================================================
292  * I/O transform callbacks for subblocks and decompression
293  * ==========================================================================
294  */
295 static void
296 zio_subblock(zio_t *zio, void *data, uint64_t size)
297 {
298         ASSERT(zio->io_size > size);
299
300         if (zio->io_type == ZIO_TYPE_READ)
301                 bcopy(zio->io_data, data, size);
302 }
303
304 static void
305 zio_decompress(zio_t *zio, void *data, uint64_t size)
306 {
307         if (zio->io_error == 0 &&
308             zio_decompress_data(BP_GET_COMPRESS(zio->io_bp),
309             zio->io_data, zio->io_size, data, size) != 0)
310                 zio->io_error = EIO;
311 }
312
313 /*
314  * ==========================================================================
315  * I/O parent/child relationships and pipeline interlocks
316  * ==========================================================================
317  */
318
319 static void
320 zio_add_child(zio_t *pio, zio_t *zio)
321 {
322         mutex_enter(&pio->io_lock);
323         if (zio->io_stage < ZIO_STAGE_READY)
324                 pio->io_children[zio->io_child_type][ZIO_WAIT_READY]++;
325         if (zio->io_stage < ZIO_STAGE_DONE)
326                 pio->io_children[zio->io_child_type][ZIO_WAIT_DONE]++;
327         zio->io_sibling_prev = NULL;
328         zio->io_sibling_next = pio->io_child;
329         if (pio->io_child != NULL)
330                 pio->io_child->io_sibling_prev = zio;
331         pio->io_child = zio;
332         zio->io_parent = pio;
333         mutex_exit(&pio->io_lock);
334 }
335
336 static void
337 zio_remove_child(zio_t *pio, zio_t *zio)
338 {
339         zio_t *next, *prev;
340
341         ASSERT(zio->io_parent == pio);
342
343         mutex_enter(&pio->io_lock);
344         next = zio->io_sibling_next;
345         prev = zio->io_sibling_prev;
346         if (next != NULL)
347                 next->io_sibling_prev = prev;
348         if (prev != NULL)
349                 prev->io_sibling_next = next;
350         if (pio->io_child == zio)
351                 pio->io_child = next;
352         mutex_exit(&pio->io_lock);
353 }
354
355 static boolean_t
356 zio_wait_for_children(zio_t *zio, enum zio_child child, enum zio_wait_type wait)
357 {
358         uint64_t *countp = &zio->io_children[child][wait];
359         boolean_t waiting = B_FALSE;
360
361         mutex_enter(&zio->io_lock);
362         ASSERT(zio->io_stall == NULL);
363         if (*countp != 0) {
364                 zio->io_stage--;
365                 zio->io_stall = countp;
366                 waiting = B_TRUE;
367         }
368         mutex_exit(&zio->io_lock);
369
370         return (waiting);
371 }
372
373 static void
374 zio_notify_parent(zio_t *pio, zio_t *zio, enum zio_wait_type wait)
375 {
376         uint64_t *countp = &pio->io_children[zio->io_child_type][wait];
377         int *errorp = &pio->io_child_error[zio->io_child_type];
378
379         mutex_enter(&pio->io_lock);
380         if (zio->io_error && !(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
381                 *errorp = zio_worst_error(*errorp, zio->io_error);
382         pio->io_reexecute |= zio->io_reexecute;
383         ASSERT3U(*countp, >, 0);
384         if (--*countp == 0 && pio->io_stall == countp) {
385                 pio->io_stall = NULL;
386                 mutex_exit(&pio->io_lock);
387                 zio_execute(pio);
388         } else {
389                 mutex_exit(&pio->io_lock);
390         }
391 }
392
393 static void
394 zio_inherit_child_errors(zio_t *zio, enum zio_child c)
395 {
396         if (zio->io_child_error[c] != 0 && zio->io_error == 0)
397                 zio->io_error = zio->io_child_error[c];
398 }
399
400 /*
401  * ==========================================================================
402  * Create the various types of I/O (read, write, free, etc)
403  * ==========================================================================
404  */
405 static zio_t *
406 zio_create(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
407     void *data, uint64_t size, zio_done_func_t *done, void *private,
408     zio_type_t type, int priority, int flags, vdev_t *vd, uint64_t offset,
409     const zbookmark_t *zb, uint8_t stage, uint32_t pipeline)
410 {
411         zio_t *zio;
412
413         ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
414         ASSERT(P2PHASE(size, SPA_MINBLOCKSIZE) == 0);
415         ASSERT(P2PHASE(offset, SPA_MINBLOCKSIZE) == 0);
416
417         ASSERT(!vd || spa_config_held(spa, SCL_STATE_ALL, RW_READER));
418         ASSERT(!bp || !(flags & ZIO_FLAG_CONFIG_WRITER));
419         ASSERT(vd || stage == ZIO_STAGE_OPEN);
420
421         zio = kmem_cache_alloc(zio_cache, KM_SLEEP);
422         bzero(zio, sizeof (zio_t));
423
424         mutex_init(&zio->io_lock, NULL, MUTEX_DEFAULT, NULL);
425         cv_init(&zio->io_cv, NULL, CV_DEFAULT, NULL);
426
427         if (vd != NULL)
428                 zio->io_child_type = ZIO_CHILD_VDEV;
429         else if (flags & ZIO_FLAG_GANG_CHILD)
430                 zio->io_child_type = ZIO_CHILD_GANG;
431         else
432                 zio->io_child_type = ZIO_CHILD_LOGICAL;
433
434         if (bp != NULL) {
435                 zio->io_bp = bp;
436                 zio->io_bp_copy = *bp;
437                 zio->io_bp_orig = *bp;
438                 if (type != ZIO_TYPE_WRITE)
439                         zio->io_bp = &zio->io_bp_copy;  /* so caller can free */
440                 if (zio->io_child_type == ZIO_CHILD_LOGICAL) {
441                         if (BP_IS_GANG(bp))
442                                 pipeline |= ZIO_GANG_STAGES;
443                         zio->io_logical = zio;
444                 }
445         }
446
447         zio->io_spa = spa;
448         zio->io_txg = txg;
449         zio->io_data = data;
450         zio->io_size = size;
451         zio->io_done = done;
452         zio->io_private = private;
453         zio->io_type = type;
454         zio->io_priority = priority;
455         zio->io_vd = vd;
456         zio->io_offset = offset;
457         zio->io_orig_flags = zio->io_flags = flags;
458         zio->io_orig_stage = zio->io_stage = stage;
459         zio->io_orig_pipeline = zio->io_pipeline = pipeline;
460
461         if (zb != NULL)
462                 zio->io_bookmark = *zb;
463
464         if (pio != NULL) {
465                 /*
466                  * Logical I/Os can have logical, gang, or vdev children.
467                  * Gang I/Os can have gang or vdev children.
468                  * Vdev I/Os can only have vdev children.
469                  * The following ASSERT captures all of these constraints.
470                  */
471                 ASSERT(zio->io_child_type <= pio->io_child_type);
472                 if (zio->io_logical == NULL)
473                         zio->io_logical = pio->io_logical;
474                 zio_add_child(pio, zio);
475         }
476
477         return (zio);
478 }
479
480 static void
481 zio_destroy(zio_t *zio)
482 {
483         spa_t *spa = zio->io_spa;
484         uint8_t async_root = zio->io_async_root;
485
486         mutex_destroy(&zio->io_lock);
487         cv_destroy(&zio->io_cv);
488         kmem_cache_free(zio_cache, zio);
489
490         if (async_root) {
491                 mutex_enter(&spa->spa_async_root_lock);
492                 if (--spa->spa_async_root_count == 0)
493                         cv_broadcast(&spa->spa_async_root_cv);
494                 mutex_exit(&spa->spa_async_root_lock);
495         }
496 }
497
498 zio_t *
499 zio_null(zio_t *pio, spa_t *spa, zio_done_func_t *done, void *private,
500         int flags)
501 {
502         zio_t *zio;
503
504         zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
505             ZIO_TYPE_NULL, ZIO_PRIORITY_NOW, flags, NULL, 0, NULL,
506             ZIO_STAGE_OPEN, ZIO_INTERLOCK_PIPELINE);
507
508         return (zio);
509 }
510
511 zio_t *
512 zio_root(spa_t *spa, zio_done_func_t *done, void *private, int flags)
513 {
514         return (zio_null(NULL, spa, done, private, flags));
515 }
516
517 zio_t *
518 zio_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
519     void *data, uint64_t size, zio_done_func_t *done, void *private,
520     int priority, int flags, const zbookmark_t *zb)
521 {
522         zio_t *zio;
523
524         zio = zio_create(pio, spa, bp->blk_birth, (blkptr_t *)bp,
525             data, size, done, private,
526             ZIO_TYPE_READ, priority, flags, NULL, 0, zb,
527             ZIO_STAGE_OPEN, ZIO_READ_PIPELINE);
528
529         return (zio);
530 }
531
532 zio_t *
533 zio_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
534     void *data, uint64_t size, zio_prop_t *zp,
535     zio_done_func_t *ready, zio_done_func_t *done, void *private,
536     int priority, int flags, const zbookmark_t *zb)
537 {
538         zio_t *zio;
539
540         ASSERT(zp->zp_checksum >= ZIO_CHECKSUM_OFF &&
541             zp->zp_checksum < ZIO_CHECKSUM_FUNCTIONS &&
542             zp->zp_compress >= ZIO_COMPRESS_OFF &&
543             zp->zp_compress < ZIO_COMPRESS_FUNCTIONS &&
544             zp->zp_type < DMU_OT_NUMTYPES &&
545             zp->zp_level < 32 &&
546             zp->zp_ndvas > 0 &&
547             zp->zp_ndvas <= spa_max_replication(spa));
548         ASSERT(ready != NULL);
549
550         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
551             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
552             ZIO_STAGE_OPEN, ZIO_WRITE_PIPELINE);
553
554         zio->io_ready = ready;
555         zio->io_prop = *zp;
556
557         return (zio);
558 }
559
560 zio_t *
561 zio_rewrite(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, void *data,
562     uint64_t size, zio_done_func_t *done, void *private, int priority,
563     int flags, zbookmark_t *zb)
564 {
565         zio_t *zio;
566
567         zio = zio_create(pio, spa, txg, bp, data, size, done, private,
568             ZIO_TYPE_WRITE, priority, flags, NULL, 0, zb,
569             ZIO_STAGE_OPEN, ZIO_REWRITE_PIPELINE);
570
571         return (zio);
572 }
573
574 zio_t *
575 zio_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
576     zio_done_func_t *done, void *private, int flags)
577 {
578         zio_t *zio;
579
580         ASSERT(!BP_IS_HOLE(bp));
581
582         if (bp->blk_fill == BLK_FILL_ALREADY_FREED)
583                 return (zio_null(pio, spa, NULL, NULL, flags));
584
585         if (txg == spa->spa_syncing_txg &&
586             spa_sync_pass(spa) > SYNC_PASS_DEFERRED_FREE) {
587                 bplist_enqueue_deferred(&spa->spa_sync_bplist, bp);
588                 return (zio_null(pio, spa, NULL, NULL, flags));
589         }
590
591         zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
592             done, private, ZIO_TYPE_FREE, ZIO_PRIORITY_FREE, flags,
593             NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_FREE_PIPELINE);
594
595         return (zio);
596 }
597
598 zio_t *
599 zio_claim(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
600     zio_done_func_t *done, void *private, int flags)
601 {
602         zio_t *zio;
603
604         /*
605          * A claim is an allocation of a specific block.  Claims are needed
606          * to support immediate writes in the intent log.  The issue is that
607          * immediate writes contain committed data, but in a txg that was
608          * *not* committed.  Upon opening the pool after an unclean shutdown,
609          * the intent log claims all blocks that contain immediate write data
610          * so that the SPA knows they're in use.
611          *
612          * All claims *must* be resolved in the first txg -- before the SPA
613          * starts allocating blocks -- so that nothing is allocated twice.
614          */
615         ASSERT3U(spa->spa_uberblock.ub_rootbp.blk_birth, <, spa_first_txg(spa));
616         ASSERT3U(spa_first_txg(spa), <=, txg);
617
618         zio = zio_create(pio, spa, txg, bp, NULL, BP_GET_PSIZE(bp),
619             done, private, ZIO_TYPE_CLAIM, ZIO_PRIORITY_NOW, flags,
620             NULL, 0, NULL, ZIO_STAGE_OPEN, ZIO_CLAIM_PIPELINE);
621
622         return (zio);
623 }
624
625 zio_t *
626 zio_ioctl(zio_t *pio, spa_t *spa, vdev_t *vd, int cmd,
627     zio_done_func_t *done, void *private, int priority, int flags)
628 {
629         zio_t *zio;
630         int c;
631
632         if (vd->vdev_children == 0) {
633                 zio = zio_create(pio, spa, 0, NULL, NULL, 0, done, private,
634                     ZIO_TYPE_IOCTL, priority, flags, vd, 0, NULL,
635                     ZIO_STAGE_OPEN, ZIO_IOCTL_PIPELINE);
636
637                 zio->io_cmd = cmd;
638         } else {
639                 zio = zio_null(pio, spa, NULL, NULL, flags);
640
641                 for (c = 0; c < vd->vdev_children; c++)
642                         zio_nowait(zio_ioctl(zio, spa, vd->vdev_child[c], cmd,
643                             done, private, priority, flags));
644         }
645
646         return (zio);
647 }
648
649 zio_t *
650 zio_read_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
651     void *data, int checksum, zio_done_func_t *done, void *private,
652     int priority, int flags, boolean_t labels)
653 {
654         zio_t *zio;
655
656         ASSERT(vd->vdev_children == 0);
657         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
658             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
659         ASSERT3U(offset + size, <=, vd->vdev_psize);
660
661         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
662             ZIO_TYPE_READ, priority, flags, vd, offset, NULL,
663             ZIO_STAGE_OPEN, ZIO_READ_PHYS_PIPELINE);
664
665         zio->io_prop.zp_checksum = checksum;
666
667         return (zio);
668 }
669
670 zio_t *
671 zio_write_phys(zio_t *pio, vdev_t *vd, uint64_t offset, uint64_t size,
672     void *data, int checksum, zio_done_func_t *done, void *private,
673     int priority, int flags, boolean_t labels)
674 {
675         zio_t *zio;
676
677         ASSERT(vd->vdev_children == 0);
678         ASSERT(!labels || offset + size <= VDEV_LABEL_START_SIZE ||
679             offset >= vd->vdev_psize - VDEV_LABEL_END_SIZE);
680         ASSERT3U(offset + size, <=, vd->vdev_psize);
681
682         zio = zio_create(pio, vd->vdev_spa, 0, NULL, data, size, done, private,
683             ZIO_TYPE_WRITE, priority, flags, vd, offset, NULL,
684             ZIO_STAGE_OPEN, ZIO_WRITE_PHYS_PIPELINE);
685
686         zio->io_prop.zp_checksum = checksum;
687
688         if (zio_checksum_table[checksum].ci_zbt) {
689                 /*
690                  * zbt checksums are necessarily destructive -- they modify
691                  * the end of the write buffer to hold the verifier/checksum.
692                  * Therefore, we must make a local copy in case the data is
693                  * being written to multiple places in parallel.
694                  */
695                 void *wbuf = zio_buf_alloc(size);
696                 bcopy(data, wbuf, size);
697                 zio_push_transform(zio, wbuf, size, size, NULL);
698         }
699
700         return (zio);
701 }
702
703 /*
704  * Create a child I/O to do some work for us.
705  */
706 zio_t *
707 zio_vdev_child_io(zio_t *pio, blkptr_t *bp, vdev_t *vd, uint64_t offset,
708         void *data, uint64_t size, int type, int priority, int flags,
709         zio_done_func_t *done, void *private)
710 {
711         uint32_t pipeline = ZIO_VDEV_CHILD_PIPELINE;
712         zio_t *zio;
713
714         ASSERT(vd->vdev_parent ==
715             (pio->io_vd ? pio->io_vd : pio->io_spa->spa_root_vdev));
716
717         if (type == ZIO_TYPE_READ && bp != NULL) {
718                 /*
719                  * If we have the bp, then the child should perform the
720                  * checksum and the parent need not.  This pushes error
721                  * detection as close to the leaves as possible and
722                  * eliminates redundant checksums in the interior nodes.
723                  */
724                 pipeline |= 1U << ZIO_STAGE_CHECKSUM_VERIFY;
725                 pio->io_pipeline &= ~(1U << ZIO_STAGE_CHECKSUM_VERIFY);
726         }
727
728         if (vd->vdev_children == 0)
729                 offset += VDEV_LABEL_START_SIZE;
730
731         zio = zio_create(pio, pio->io_spa, pio->io_txg, bp, data, size,
732             done, private, type, priority,
733             (pio->io_flags & ZIO_FLAG_VDEV_INHERIT) |
734             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | flags,
735             vd, offset, &pio->io_bookmark,
736             ZIO_STAGE_VDEV_IO_START - 1, pipeline);
737
738         return (zio);
739 }
740
741 zio_t *
742 zio_vdev_delegated_io(vdev_t *vd, uint64_t offset, void *data, uint64_t size,
743         int type, int priority, int flags, zio_done_func_t *done, void *private)
744 {
745         zio_t *zio;
746
747         ASSERT(vd->vdev_ops->vdev_op_leaf);
748
749         zio = zio_create(NULL, vd->vdev_spa, 0, NULL,
750             data, size, done, private, type, priority,
751             flags | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY,
752             vd, offset, NULL,
753             ZIO_STAGE_VDEV_IO_START - 1, ZIO_VDEV_CHILD_PIPELINE);
754
755         return (zio);
756 }
757
758 void
759 zio_flush(zio_t *zio, vdev_t *vd)
760 {
761         zio_nowait(zio_ioctl(zio, zio->io_spa, vd, DKIOCFLUSHWRITECACHE,
762             NULL, NULL, ZIO_PRIORITY_NOW,
763             ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY));
764 }
765
766 /*
767  * ==========================================================================
768  * Prepare to read and write logical blocks
769  * ==========================================================================
770  */
771
772 static int
773 zio_read_bp_init(zio_t *zio)
774 {
775         blkptr_t *bp = zio->io_bp;
776
777         if (BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF && zio->io_logical == zio) {
778                 uint64_t csize = BP_GET_PSIZE(bp);
779                 void *cbuf = zio_buf_alloc(csize);
780
781                 zio_push_transform(zio, cbuf, csize, csize, zio_decompress);
782         }
783
784         if (!dmu_ot[BP_GET_TYPE(bp)].ot_metadata && BP_GET_LEVEL(bp) == 0)
785                 zio->io_flags |= ZIO_FLAG_DONT_CACHE;
786
787         return (ZIO_PIPELINE_CONTINUE);
788 }
789
790 static int
791 zio_write_bp_init(zio_t *zio)
792 {
793         zio_prop_t *zp = &zio->io_prop;
794         int compress = zp->zp_compress;
795         blkptr_t *bp = zio->io_bp;
796         void *cbuf;
797         uint64_t lsize = zio->io_size;
798         uint64_t csize = lsize;
799         uint64_t cbufsize = 0;
800         int pass = 1;
801
802         /*
803          * If our children haven't all reached the ready stage,
804          * wait for them and then repeat this pipeline stage.
805          */
806         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY) ||
807             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_READY))
808                 return (ZIO_PIPELINE_STOP);
809
810         if (!IO_IS_ALLOCATING(zio))
811                 return (ZIO_PIPELINE_CONTINUE);
812
813         ASSERT(compress != ZIO_COMPRESS_INHERIT);
814
815         if (bp->blk_birth == zio->io_txg) {
816                 /*
817                  * We're rewriting an existing block, which means we're
818                  * working on behalf of spa_sync().  For spa_sync() to
819                  * converge, it must eventually be the case that we don't
820                  * have to allocate new blocks.  But compression changes
821                  * the blocksize, which forces a reallocate, and makes
822                  * convergence take longer.  Therefore, after the first
823                  * few passes, stop compressing to ensure convergence.
824                  */
825                 pass = spa_sync_pass(zio->io_spa);
826                 ASSERT(pass > 1);
827
828                 if (pass > SYNC_PASS_DONT_COMPRESS)
829                         compress = ZIO_COMPRESS_OFF;
830
831                 /*
832                  * Only MOS (objset 0) data should need to be rewritten.
833                  */
834                 ASSERT(zio->io_logical->io_bookmark.zb_objset == 0);
835
836                 /* Make sure someone doesn't change their mind on overwrites */
837                 ASSERT(MIN(zp->zp_ndvas + BP_IS_GANG(bp),
838                     spa_max_replication(zio->io_spa)) == BP_GET_NDVAS(bp));
839         }
840
841         if (compress != ZIO_COMPRESS_OFF) {
842                 if (!zio_compress_data(compress, zio->io_data, zio->io_size,
843                     &cbuf, &csize, &cbufsize)) {
844                         compress = ZIO_COMPRESS_OFF;
845                 } else if (csize != 0) {
846                         zio_push_transform(zio, cbuf, csize, cbufsize, NULL);
847                 }
848         }
849
850         /*
851          * The final pass of spa_sync() must be all rewrites, but the first
852          * few passes offer a trade-off: allocating blocks defers convergence,
853          * but newly allocated blocks are sequential, so they can be written
854          * to disk faster.  Therefore, we allow the first few passes of
855          * spa_sync() to allocate new blocks, but force rewrites after that.
856          * There should only be a handful of blocks after pass 1 in any case.
857          */
858         if (bp->blk_birth == zio->io_txg && BP_GET_PSIZE(bp) == csize &&
859             pass > SYNC_PASS_REWRITE) {
860                 ASSERT(csize != 0);
861                 uint32_t gang_stages = zio->io_pipeline & ZIO_GANG_STAGES;
862                 zio->io_pipeline = ZIO_REWRITE_PIPELINE | gang_stages;
863                 zio->io_flags |= ZIO_FLAG_IO_REWRITE;
864         } else {
865                 BP_ZERO(bp);
866                 zio->io_pipeline = ZIO_WRITE_PIPELINE;
867         }
868
869         if (csize == 0) {
870                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
871         } else {
872                 ASSERT(zp->zp_checksum != ZIO_CHECKSUM_GANG_HEADER);
873                 BP_SET_LSIZE(bp, lsize);
874                 BP_SET_PSIZE(bp, csize);
875                 BP_SET_COMPRESS(bp, compress);
876                 BP_SET_CHECKSUM(bp, zp->zp_checksum);
877                 BP_SET_TYPE(bp, zp->zp_type);
878                 BP_SET_LEVEL(bp, zp->zp_level);
879                 BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
880         }
881
882         return (ZIO_PIPELINE_CONTINUE);
883 }
884
885 /*
886  * ==========================================================================
887  * Execute the I/O pipeline
888  * ==========================================================================
889  */
890
891 static void
892 zio_taskq_dispatch(zio_t *zio, enum zio_taskq_type q)
893 {
894         zio_type_t t = zio->io_type;
895
896         /*
897          * If we're a config writer, the normal issue and interrupt threads
898          * may all be blocked waiting for the config lock.  In this case,
899          * select the otherwise-unused taskq for ZIO_TYPE_NULL.
900          */
901         if (zio->io_flags & ZIO_FLAG_CONFIG_WRITER)
902                 t = ZIO_TYPE_NULL;
903
904         /*
905          * A similar issue exists for the L2ARC write thread until L2ARC 2.0.
906          */
907         if (t == ZIO_TYPE_WRITE && zio->io_vd && zio->io_vd->vdev_aux)
908                 t = ZIO_TYPE_NULL;
909
910         (void) taskq_dispatch_safe(zio->io_spa->spa_zio_taskq[t][q],
911             (task_func_t *)zio_execute, zio, &zio->io_task);
912 }
913
914 static boolean_t
915 zio_taskq_member(zio_t *zio, enum zio_taskq_type q)
916 {
917         kthread_t *executor = zio->io_executor;
918         spa_t *spa = zio->io_spa;
919
920         for (zio_type_t t = 0; t < ZIO_TYPES; t++)
921                 if (taskq_member(spa->spa_zio_taskq[t][q], executor))
922                         return (B_TRUE);
923
924         return (B_FALSE);
925 }
926
927 static int
928 zio_issue_async(zio_t *zio)
929 {
930         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE);
931
932         return (ZIO_PIPELINE_STOP);
933 }
934
935 void
936 zio_interrupt(zio_t *zio)
937 {
938         zio_taskq_dispatch(zio, ZIO_TASKQ_INTERRUPT);
939 }
940
941 /*
942  * Execute the I/O pipeline until one of the following occurs:
943  * (1) the I/O completes; (2) the pipeline stalls waiting for
944  * dependent child I/Os; (3) the I/O issues, so we're waiting
945  * for an I/O completion interrupt; (4) the I/O is delegated by
946  * vdev-level caching or aggregation; (5) the I/O is deferred
947  * due to vdev-level queueing; (6) the I/O is handed off to
948  * another thread.  In all cases, the pipeline stops whenever
949  * there's no CPU work; it never burns a thread in cv_wait().
950  *
951  * There's no locking on io_stage because there's no legitimate way
952  * for multiple threads to be attempting to process the same I/O.
953  */
954 static zio_pipe_stage_t *zio_pipeline[ZIO_STAGES];
955
956 void
957 zio_execute(zio_t *zio)
958 {
959         zio->io_executor = curthread;
960
961         while (zio->io_stage < ZIO_STAGE_DONE) {
962                 uint32_t pipeline = zio->io_pipeline;
963                 zio_stage_t stage = zio->io_stage;
964                 int rv;
965
966                 ASSERT(!MUTEX_HELD(&zio->io_lock));
967
968                 while (((1U << ++stage) & pipeline) == 0)
969                         continue;
970
971                 ASSERT(stage <= ZIO_STAGE_DONE);
972                 ASSERT(zio->io_stall == NULL);
973
974                 /*
975                  * If we are in interrupt context and this pipeline stage
976                  * will grab a config lock that is held across I/O,
977                  * issue async to avoid deadlock.
978                  */
979                 if (((1U << stage) & ZIO_CONFIG_LOCK_BLOCKING_STAGES) &&
980                     zio->io_vd == NULL &&
981                     zio_taskq_member(zio, ZIO_TASKQ_INTERRUPT)) {
982                         zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE);
983                         return;
984                 }
985
986                 zio->io_stage = stage;
987                 rv = zio_pipeline[stage](zio);
988
989                 if (rv == ZIO_PIPELINE_STOP)
990                         return;
991
992                 ASSERT(rv == ZIO_PIPELINE_CONTINUE);
993         }
994 }
995
996 /*
997  * ==========================================================================
998  * Initiate I/O, either sync or async
999  * ==========================================================================
1000  */
1001 int
1002 zio_wait(zio_t *zio)
1003 {
1004         int error;
1005
1006         ASSERT(zio->io_stage == ZIO_STAGE_OPEN);
1007         ASSERT(zio->io_executor == NULL);
1008
1009         zio->io_waiter = curthread;
1010
1011         zio_execute(zio);
1012
1013         mutex_enter(&zio->io_lock);
1014         while (zio->io_executor != NULL)
1015                 cv_wait(&zio->io_cv, &zio->io_lock);
1016         mutex_exit(&zio->io_lock);
1017
1018         error = zio->io_error;
1019         zio_destroy(zio);
1020
1021         return (error);
1022 }
1023
1024 void
1025 zio_nowait(zio_t *zio)
1026 {
1027         ASSERT(zio->io_executor == NULL);
1028
1029         if (zio->io_parent == NULL && zio->io_child_type == ZIO_CHILD_LOGICAL) {
1030                 /*
1031                  * This is a logical async I/O with no parent to wait for it.
1032                  * Attach it to the pool's global async root zio so that
1033                  * spa_unload() has a way of waiting for async I/O to finish.
1034                  */
1035                 spa_t *spa = zio->io_spa;
1036                 zio->io_async_root = B_TRUE;
1037                 mutex_enter(&spa->spa_async_root_lock);
1038                 spa->spa_async_root_count++;
1039                 mutex_exit(&spa->spa_async_root_lock);
1040         }
1041
1042         zio_execute(zio);
1043 }
1044
1045 /*
1046  * ==========================================================================
1047  * Reexecute or suspend/resume failed I/O
1048  * ==========================================================================
1049  */
1050
1051 static void
1052 zio_reexecute(zio_t *pio)
1053 {
1054         zio_t *zio, *zio_next;
1055
1056         pio->io_flags = pio->io_orig_flags;
1057         pio->io_stage = pio->io_orig_stage;
1058         pio->io_pipeline = pio->io_orig_pipeline;
1059         pio->io_reexecute = 0;
1060         pio->io_error = 0;
1061         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
1062                 pio->io_child_error[c] = 0;
1063
1064         if (IO_IS_ALLOCATING(pio)) {
1065                 /*
1066                  * Remember the failed bp so that the io_ready() callback
1067                  * can update its accounting upon reexecution.  The block
1068                  * was already freed in zio_done(); we indicate this with
1069                  * a fill count of -1 so that zio_free() knows to skip it.
1070                  */
1071                 blkptr_t *bp = pio->io_bp;
1072                 ASSERT(bp->blk_birth == 0 || bp->blk_birth == pio->io_txg);
1073                 bp->blk_fill = BLK_FILL_ALREADY_FREED;
1074                 pio->io_bp_orig = *bp;
1075                 BP_ZERO(bp);
1076         }
1077
1078         /*
1079          * As we reexecute pio's children, new children could be created.
1080          * New children go to the head of the io_child list, however,
1081          * so we will (correctly) not reexecute them.  The key is that
1082          * the remainder of the io_child list, from 'zio_next' onward,
1083          * cannot be affected by any side effects of reexecuting 'zio'.
1084          */
1085         for (zio = pio->io_child; zio != NULL; zio = zio_next) {
1086                 zio_next = zio->io_sibling_next;
1087                 mutex_enter(&pio->io_lock);
1088                 pio->io_children[zio->io_child_type][ZIO_WAIT_READY]++;
1089                 pio->io_children[zio->io_child_type][ZIO_WAIT_DONE]++;
1090                 mutex_exit(&pio->io_lock);
1091                 zio_reexecute(zio);
1092         }
1093
1094         /*
1095          * Now that all children have been reexecuted, execute the parent.
1096          */
1097         zio_execute(pio);
1098 }
1099
1100 void
1101 zio_suspend(spa_t *spa, zio_t *zio)
1102 {
1103         if (spa_get_failmode(spa) == ZIO_FAILURE_MODE_PANIC)
1104                 fm_panic("Pool '%s' has encountered an uncorrectable I/O "
1105                     "failure and the failure mode property for this pool "
1106                     "is set to panic.", spa_name(spa));
1107
1108         zfs_ereport_post(FM_EREPORT_ZFS_IO_FAILURE, spa, NULL, NULL, 0, 0);
1109
1110         mutex_enter(&spa->spa_suspend_lock);
1111
1112         if (spa->spa_suspend_zio_root == NULL)
1113                 spa->spa_suspend_zio_root = zio_root(spa, NULL, NULL, 0);
1114
1115         spa->spa_suspended = B_TRUE;
1116
1117         if (zio != NULL) {
1118                 ASSERT(zio != spa->spa_suspend_zio_root);
1119                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
1120                 ASSERT(zio->io_parent == NULL);
1121                 ASSERT(zio->io_stage == ZIO_STAGE_DONE);
1122                 zio_add_child(spa->spa_suspend_zio_root, zio);
1123         }
1124
1125         mutex_exit(&spa->spa_suspend_lock);
1126 }
1127
1128 void
1129 zio_resume(spa_t *spa)
1130 {
1131         zio_t *pio, *zio;
1132
1133         /*
1134          * Reexecute all previously suspended i/o.
1135          */
1136         mutex_enter(&spa->spa_suspend_lock);
1137         spa->spa_suspended = B_FALSE;
1138         cv_broadcast(&spa->spa_suspend_cv);
1139         pio = spa->spa_suspend_zio_root;
1140         spa->spa_suspend_zio_root = NULL;
1141         mutex_exit(&spa->spa_suspend_lock);
1142
1143         if (pio == NULL)
1144                 return;
1145
1146         while ((zio = pio->io_child) != NULL) {
1147                 zio_remove_child(pio, zio);
1148                 zio->io_parent = NULL;
1149                 zio_reexecute(zio);
1150         }
1151
1152         ASSERT(pio->io_children[ZIO_CHILD_LOGICAL][ZIO_WAIT_DONE] == 0);
1153
1154         (void) zio_wait(pio);
1155 }
1156
1157 void
1158 zio_resume_wait(spa_t *spa)
1159 {
1160         mutex_enter(&spa->spa_suspend_lock);
1161         while (spa_suspended(spa))
1162                 cv_wait(&spa->spa_suspend_cv, &spa->spa_suspend_lock);
1163         mutex_exit(&spa->spa_suspend_lock);
1164 }
1165
1166 /*
1167  * ==========================================================================
1168  * Gang blocks.
1169  *
1170  * A gang block is a collection of small blocks that looks to the DMU
1171  * like one large block.  When zio_dva_allocate() cannot find a block
1172  * of the requested size, due to either severe fragmentation or the pool
1173  * being nearly full, it calls zio_write_gang_block() to construct the
1174  * block from smaller fragments.
1175  *
1176  * A gang block consists of a gang header (zio_gbh_phys_t) and up to
1177  * three (SPA_GBH_NBLKPTRS) gang members.  The gang header is just like
1178  * an indirect block: it's an array of block pointers.  It consumes
1179  * only one sector and hence is allocatable regardless of fragmentation.
1180  * The gang header's bps point to its gang members, which hold the data.
1181  *
1182  * Gang blocks are self-checksumming, using the bp's <vdev, offset, txg>
1183  * as the verifier to ensure uniqueness of the SHA256 checksum.
1184  * Critically, the gang block bp's blk_cksum is the checksum of the data,
1185  * not the gang header.  This ensures that data block signatures (needed for
1186  * deduplication) are independent of how the block is physically stored.
1187  *
1188  * Gang blocks can be nested: a gang member may itself be a gang block.
1189  * Thus every gang block is a tree in which root and all interior nodes are
1190  * gang headers, and the leaves are normal blocks that contain user data.
1191  * The root of the gang tree is called the gang leader.
1192  *
1193  * To perform any operation (read, rewrite, free, claim) on a gang block,
1194  * zio_gang_assemble() first assembles the gang tree (minus data leaves)
1195  * in the io_gang_tree field of the original logical i/o by recursively
1196  * reading the gang leader and all gang headers below it.  This yields
1197  * an in-core tree containing the contents of every gang header and the
1198  * bps for every constituent of the gang block.
1199  *
1200  * With the gang tree now assembled, zio_gang_issue() just walks the gang tree
1201  * and invokes a callback on each bp.  To free a gang block, zio_gang_issue()
1202  * calls zio_free_gang() -- a trivial wrapper around zio_free() -- for each bp.
1203  * zio_claim_gang() provides a similarly trivial wrapper for zio_claim().
1204  * zio_read_gang() is a wrapper around zio_read() that omits reading gang
1205  * headers, since we already have those in io_gang_tree.  zio_rewrite_gang()
1206  * performs a zio_rewrite() of the data or, for gang headers, a zio_rewrite()
1207  * of the gang header plus zio_checksum_compute() of the data to update the
1208  * gang header's blk_cksum as described above.
1209  *
1210  * The two-phase assemble/issue model solves the problem of partial failure --
1211  * what if you'd freed part of a gang block but then couldn't read the
1212  * gang header for another part?  Assembling the entire gang tree first
1213  * ensures that all the necessary gang header I/O has succeeded before
1214  * starting the actual work of free, claim, or write.  Once the gang tree
1215  * is assembled, free and claim are in-memory operations that cannot fail.
1216  *
1217  * In the event that a gang write fails, zio_dva_unallocate() walks the
1218  * gang tree to immediately free (i.e. insert back into the space map)
1219  * everything we've allocated.  This ensures that we don't get ENOSPC
1220  * errors during repeated suspend/resume cycles due to a flaky device.
1221  *
1222  * Gang rewrites only happen during sync-to-convergence.  If we can't assemble
1223  * the gang tree, we won't modify the block, so we can safely defer the free
1224  * (knowing that the block is still intact).  If we *can* assemble the gang
1225  * tree, then even if some of the rewrites fail, zio_dva_unallocate() will free
1226  * each constituent bp and we can allocate a new block on the next sync pass.
1227  *
1228  * In all cases, the gang tree allows complete recovery from partial failure.
1229  * ==========================================================================
1230  */
1231
1232 static zio_t *
1233 zio_read_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1234 {
1235         if (gn != NULL)
1236                 return (pio);
1237
1238         return (zio_read(pio, pio->io_spa, bp, data, BP_GET_PSIZE(bp),
1239             NULL, NULL, pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1240             &pio->io_bookmark));
1241 }
1242
1243 zio_t *
1244 zio_rewrite_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1245 {
1246         zio_t *zio;
1247
1248         if (gn != NULL) {
1249                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1250                     gn->gn_gbh, SPA_GANGBLOCKSIZE, NULL, NULL, pio->io_priority,
1251                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1252                 /*
1253                  * As we rewrite each gang header, the pipeline will compute
1254                  * a new gang block header checksum for it; but no one will
1255                  * compute a new data checksum, so we do that here.  The one
1256                  * exception is the gang leader: the pipeline already computed
1257                  * its data checksum because that stage precedes gang assembly.
1258                  * (Presently, nothing actually uses interior data checksums;
1259                  * this is just good hygiene.)
1260                  */
1261                 if (gn != pio->io_logical->io_gang_tree) {
1262                         zio_checksum_compute(zio, BP_GET_CHECKSUM(bp),
1263                             data, BP_GET_PSIZE(bp));
1264                 }
1265         } else {
1266                 zio = zio_rewrite(pio, pio->io_spa, pio->io_txg, bp,
1267                     data, BP_GET_PSIZE(bp), NULL, NULL, pio->io_priority,
1268                     ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1269         }
1270
1271         return (zio);
1272 }
1273
1274 /* ARGSUSED */
1275 zio_t *
1276 zio_free_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1277 {
1278         return (zio_free(pio, pio->io_spa, pio->io_txg, bp,
1279             NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
1280 }
1281
1282 /* ARGSUSED */
1283 zio_t *
1284 zio_claim_gang(zio_t *pio, blkptr_t *bp, zio_gang_node_t *gn, void *data)
1285 {
1286         return (zio_claim(pio, pio->io_spa, pio->io_txg, bp,
1287             NULL, NULL, ZIO_GANG_CHILD_FLAGS(pio)));
1288 }
1289
1290 static zio_gang_issue_func_t *zio_gang_issue_func[ZIO_TYPES] = {
1291         NULL,
1292         zio_read_gang,
1293         zio_rewrite_gang,
1294         zio_free_gang,
1295         zio_claim_gang,
1296         NULL
1297 };
1298
1299 static void zio_gang_tree_assemble_done(zio_t *zio);
1300
1301 static zio_gang_node_t *
1302 zio_gang_node_alloc(zio_gang_node_t **gnpp)
1303 {
1304         zio_gang_node_t *gn;
1305
1306         ASSERT(*gnpp == NULL);
1307
1308         gn = kmem_zalloc(sizeof (*gn), KM_SLEEP);
1309         gn->gn_gbh = zio_buf_alloc(SPA_GANGBLOCKSIZE);
1310         *gnpp = gn;
1311
1312         return (gn);
1313 }
1314
1315 static void
1316 zio_gang_node_free(zio_gang_node_t **gnpp)
1317 {
1318         zio_gang_node_t *gn = *gnpp;
1319
1320         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1321                 ASSERT(gn->gn_child[g] == NULL);
1322
1323         zio_buf_free(gn->gn_gbh, SPA_GANGBLOCKSIZE);
1324         kmem_free(gn, sizeof (*gn));
1325         *gnpp = NULL;
1326 }
1327
1328 static void
1329 zio_gang_tree_free(zio_gang_node_t **gnpp)
1330 {
1331         zio_gang_node_t *gn = *gnpp;
1332
1333         if (gn == NULL)
1334                 return;
1335
1336         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++)
1337                 zio_gang_tree_free(&gn->gn_child[g]);
1338
1339         zio_gang_node_free(gnpp);
1340 }
1341
1342 static void
1343 zio_gang_tree_assemble(zio_t *lio, blkptr_t *bp, zio_gang_node_t **gnpp)
1344 {
1345         zio_gang_node_t *gn = zio_gang_node_alloc(gnpp);
1346
1347         ASSERT(lio->io_logical == lio);
1348         ASSERT(BP_IS_GANG(bp));
1349
1350         zio_nowait(zio_read(lio, lio->io_spa, bp, gn->gn_gbh,
1351             SPA_GANGBLOCKSIZE, zio_gang_tree_assemble_done, gn,
1352             lio->io_priority, ZIO_GANG_CHILD_FLAGS(lio), &lio->io_bookmark));
1353 }
1354
1355 static void
1356 zio_gang_tree_assemble_done(zio_t *zio)
1357 {
1358         zio_t *lio = zio->io_logical;
1359         zio_gang_node_t *gn = zio->io_private;
1360         blkptr_t *bp = zio->io_bp;
1361
1362         ASSERT(zio->io_parent == lio);
1363         ASSERT(zio->io_child == NULL);
1364
1365         if (zio->io_error)
1366                 return;
1367
1368         if (BP_SHOULD_BYTESWAP(bp))
1369                 byteswap_uint64_array(zio->io_data, zio->io_size);
1370
1371         ASSERT(zio->io_data == gn->gn_gbh);
1372         ASSERT(zio->io_size == SPA_GANGBLOCKSIZE);
1373         ASSERT(gn->gn_gbh->zg_tail.zbt_magic == ZBT_MAGIC);
1374
1375         for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1376                 blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1377                 if (!BP_IS_GANG(gbp))
1378                         continue;
1379                 zio_gang_tree_assemble(lio, gbp, &gn->gn_child[g]);
1380         }
1381 }
1382
1383 static void
1384 zio_gang_tree_issue(zio_t *pio, zio_gang_node_t *gn, blkptr_t *bp, void *data)
1385 {
1386         zio_t *lio = pio->io_logical;
1387         zio_t *zio;
1388
1389         ASSERT(BP_IS_GANG(bp) == !!gn);
1390         ASSERT(BP_GET_CHECKSUM(bp) == BP_GET_CHECKSUM(lio->io_bp));
1391         ASSERT(BP_GET_LSIZE(bp) == BP_GET_PSIZE(bp) || gn == lio->io_gang_tree);
1392
1393         /*
1394          * If you're a gang header, your data is in gn->gn_gbh.
1395          * If you're a gang member, your data is in 'data' and gn == NULL.
1396          */
1397         zio = zio_gang_issue_func[lio->io_type](pio, bp, gn, data);
1398
1399         if (gn != NULL) {
1400                 ASSERT(gn->gn_gbh->zg_tail.zbt_magic == ZBT_MAGIC);
1401
1402                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1403                         blkptr_t *gbp = &gn->gn_gbh->zg_blkptr[g];
1404                         if (BP_IS_HOLE(gbp))
1405                                 continue;
1406                         zio_gang_tree_issue(zio, gn->gn_child[g], gbp, data);
1407                         data = (char *)data + BP_GET_PSIZE(gbp);
1408                 }
1409         }
1410
1411         if (gn == lio->io_gang_tree)
1412                 ASSERT3P((char *)lio->io_data + lio->io_size, ==, data);
1413
1414         if (zio != pio)
1415                 zio_nowait(zio);
1416 }
1417
1418 static int
1419 zio_gang_assemble(zio_t *zio)
1420 {
1421         blkptr_t *bp = zio->io_bp;
1422
1423         ASSERT(BP_IS_GANG(bp) && zio == zio->io_logical);
1424
1425         zio_gang_tree_assemble(zio, bp, &zio->io_gang_tree);
1426
1427         return (ZIO_PIPELINE_CONTINUE);
1428 }
1429
1430 static int
1431 zio_gang_issue(zio_t *zio)
1432 {
1433         zio_t *lio = zio->io_logical;
1434         blkptr_t *bp = zio->io_bp;
1435
1436         if (zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE))
1437                 return (ZIO_PIPELINE_STOP);
1438
1439         ASSERT(BP_IS_GANG(bp) && zio == lio);
1440
1441         if (zio->io_child_error[ZIO_CHILD_GANG] == 0)
1442                 zio_gang_tree_issue(lio, lio->io_gang_tree, bp, lio->io_data);
1443         else
1444                 zio_gang_tree_free(&lio->io_gang_tree);
1445
1446         zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1447
1448         return (ZIO_PIPELINE_CONTINUE);
1449 }
1450
1451 static void
1452 zio_write_gang_member_ready(zio_t *zio)
1453 {
1454         zio_t *pio = zio->io_parent;
1455         zio_t *lio = zio->io_logical;
1456         dva_t *cdva = zio->io_bp->blk_dva;
1457         dva_t *pdva = pio->io_bp->blk_dva;
1458         uint64_t asize;
1459
1460         if (BP_IS_HOLE(zio->io_bp))
1461                 return;
1462
1463         ASSERT(BP_IS_HOLE(&zio->io_bp_orig));
1464
1465         ASSERT(zio->io_child_type == ZIO_CHILD_GANG);
1466         ASSERT3U(zio->io_prop.zp_ndvas, ==, lio->io_prop.zp_ndvas);
1467         ASSERT3U(zio->io_prop.zp_ndvas, <=, BP_GET_NDVAS(zio->io_bp));
1468         ASSERT3U(pio->io_prop.zp_ndvas, <=, BP_GET_NDVAS(pio->io_bp));
1469         ASSERT3U(BP_GET_NDVAS(zio->io_bp), <=, BP_GET_NDVAS(pio->io_bp));
1470
1471         mutex_enter(&pio->io_lock);
1472         for (int d = 0; d < BP_GET_NDVAS(zio->io_bp); d++) {
1473                 ASSERT(DVA_GET_GANG(&pdva[d]));
1474                 asize = DVA_GET_ASIZE(&pdva[d]);
1475                 asize += DVA_GET_ASIZE(&cdva[d]);
1476                 DVA_SET_ASIZE(&pdva[d], asize);
1477         }
1478         mutex_exit(&pio->io_lock);
1479 }
1480
1481 static int
1482 zio_write_gang_block(zio_t *pio)
1483 {
1484         spa_t *spa = pio->io_spa;
1485         blkptr_t *bp = pio->io_bp;
1486         zio_t *lio = pio->io_logical;
1487         zio_t *zio;
1488         zio_gang_node_t *gn, **gnpp;
1489         zio_gbh_phys_t *gbh;
1490         uint64_t txg = pio->io_txg;
1491         uint64_t resid = pio->io_size;
1492         uint64_t lsize;
1493         int ndvas = lio->io_prop.zp_ndvas;
1494         int gbh_ndvas = MIN(ndvas + 1, spa_max_replication(spa));
1495         zio_prop_t zp;
1496         int error;
1497
1498         error = metaslab_alloc(spa, spa->spa_normal_class, SPA_GANGBLOCKSIZE,
1499             bp, gbh_ndvas, txg, pio == lio ? NULL : lio->io_bp,
1500             METASLAB_HINTBP_FAVOR | METASLAB_GANG_HEADER);
1501         if (error) {
1502                 pio->io_error = error;
1503                 return (ZIO_PIPELINE_CONTINUE);
1504         }
1505
1506         if (pio == lio) {
1507                 gnpp = &lio->io_gang_tree;
1508         } else {
1509                 gnpp = pio->io_private;
1510                 ASSERT(pio->io_ready == zio_write_gang_member_ready);
1511         }
1512
1513         gn = zio_gang_node_alloc(gnpp);
1514         gbh = gn->gn_gbh;
1515         bzero(gbh, SPA_GANGBLOCKSIZE);
1516
1517         /*
1518          * Create the gang header.
1519          */
1520         zio = zio_rewrite(pio, spa, txg, bp, gbh, SPA_GANGBLOCKSIZE, NULL, NULL,
1521             pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio), &pio->io_bookmark);
1522
1523         /*
1524          * Create and nowait the gang children.
1525          */
1526         for (int g = 0; resid != 0; resid -= lsize, g++) {
1527                 lsize = P2ROUNDUP(resid / (SPA_GBH_NBLKPTRS - g),
1528                     SPA_MINBLOCKSIZE);
1529                 ASSERT(lsize >= SPA_MINBLOCKSIZE && lsize <= resid);
1530
1531                 zp.zp_checksum = lio->io_prop.zp_checksum;
1532                 zp.zp_compress = ZIO_COMPRESS_OFF;
1533                 zp.zp_type = DMU_OT_NONE;
1534                 zp.zp_level = 0;
1535                 zp.zp_ndvas = lio->io_prop.zp_ndvas;
1536
1537                 zio_nowait(zio_write(zio, spa, txg, &gbh->zg_blkptr[g],
1538                     (char *)pio->io_data + (pio->io_size - resid), lsize, &zp,
1539                     zio_write_gang_member_ready, NULL, &gn->gn_child[g],
1540                     pio->io_priority, ZIO_GANG_CHILD_FLAGS(pio),
1541                     &pio->io_bookmark));
1542         }
1543
1544         /*
1545          * Set pio's pipeline to just wait for zio to finish.
1546          */
1547         pio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1548
1549         zio_nowait(zio);
1550
1551         return (ZIO_PIPELINE_CONTINUE);
1552 }
1553
1554 /*
1555  * ==========================================================================
1556  * Allocate and free blocks
1557  * ==========================================================================
1558  */
1559
1560 static int
1561 zio_dva_allocate(zio_t *zio)
1562 {
1563         spa_t *spa = zio->io_spa;
1564         metaslab_class_t *mc = spa->spa_normal_class;
1565         blkptr_t *bp = zio->io_bp;
1566         int error;
1567
1568         ASSERT(BP_IS_HOLE(bp));
1569         ASSERT3U(BP_GET_NDVAS(bp), ==, 0);
1570         ASSERT3U(zio->io_prop.zp_ndvas, >, 0);
1571         ASSERT3U(zio->io_prop.zp_ndvas, <=, spa_max_replication(spa));
1572         ASSERT3U(zio->io_size, ==, BP_GET_PSIZE(bp));
1573
1574         error = metaslab_alloc(spa, mc, zio->io_size, bp,
1575             zio->io_prop.zp_ndvas, zio->io_txg, NULL, 0);
1576
1577         if (error) {
1578                 if (error == ENOSPC && zio->io_size > SPA_MINBLOCKSIZE)
1579                         return (zio_write_gang_block(zio));
1580                 zio->io_error = error;
1581         }
1582
1583         return (ZIO_PIPELINE_CONTINUE);
1584 }
1585
1586 static int
1587 zio_dva_free(zio_t *zio)
1588 {
1589         metaslab_free(zio->io_spa, zio->io_bp, zio->io_txg, B_FALSE);
1590
1591         return (ZIO_PIPELINE_CONTINUE);
1592 }
1593
1594 static int
1595 zio_dva_claim(zio_t *zio)
1596 {
1597         int error;
1598
1599         error = metaslab_claim(zio->io_spa, zio->io_bp, zio->io_txg);
1600         if (error)
1601                 zio->io_error = error;
1602
1603         return (ZIO_PIPELINE_CONTINUE);
1604 }
1605
1606 /*
1607  * Undo an allocation.  This is used by zio_done() when an I/O fails
1608  * and we want to give back the block we just allocated.
1609  * This handles both normal blocks and gang blocks.
1610  */
1611 static void
1612 zio_dva_unallocate(zio_t *zio, zio_gang_node_t *gn, blkptr_t *bp)
1613 {
1614         spa_t *spa = zio->io_spa;
1615         boolean_t now = !(zio->io_flags & ZIO_FLAG_IO_REWRITE);
1616
1617         ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
1618
1619         if (zio->io_bp == bp && !now) {
1620                 /*
1621                  * This is a rewrite for sync-to-convergence.
1622                  * We can't do a metaslab_free(NOW) because bp wasn't allocated
1623                  * during this sync pass, which means that metaslab_sync()
1624                  * already committed the allocation.
1625                  */
1626                 ASSERT(DVA_EQUAL(BP_IDENTITY(bp),
1627                     BP_IDENTITY(&zio->io_bp_orig)));
1628                 ASSERT(spa_sync_pass(spa) > 1);
1629
1630                 if (BP_IS_GANG(bp) && gn == NULL) {
1631                         /*
1632                          * This is a gang leader whose gang header(s) we
1633                          * couldn't read now, so defer the free until later.
1634                          * The block should still be intact because without
1635                          * the headers, we'd never even start the rewrite.
1636                          */
1637                         bplist_enqueue_deferred(&spa->spa_sync_bplist, bp);
1638                         return;
1639                 }
1640         }
1641
1642         if (!BP_IS_HOLE(bp))
1643                 metaslab_free(spa, bp, bp->blk_birth, now);
1644
1645         if (gn != NULL) {
1646                 for (int g = 0; g < SPA_GBH_NBLKPTRS; g++) {
1647                         zio_dva_unallocate(zio, gn->gn_child[g],
1648                             &gn->gn_gbh->zg_blkptr[g]);
1649                 }
1650         }
1651 }
1652
1653 /*
1654  * Try to allocate an intent log block.  Return 0 on success, errno on failure.
1655  */
1656 int
1657 zio_alloc_blk(spa_t *spa, uint64_t size, blkptr_t *new_bp, blkptr_t *old_bp,
1658     uint64_t txg)
1659 {
1660         int error;
1661
1662         error = metaslab_alloc(spa, spa->spa_log_class, size,
1663             new_bp, 1, txg, old_bp, METASLAB_HINTBP_AVOID);
1664
1665         if (error)
1666                 error = metaslab_alloc(spa, spa->spa_normal_class, size,
1667                     new_bp, 1, txg, old_bp, METASLAB_HINTBP_AVOID);
1668
1669         if (error == 0) {
1670                 BP_SET_LSIZE(new_bp, size);
1671                 BP_SET_PSIZE(new_bp, size);
1672                 BP_SET_COMPRESS(new_bp, ZIO_COMPRESS_OFF);
1673                 BP_SET_CHECKSUM(new_bp, ZIO_CHECKSUM_ZILOG);
1674                 BP_SET_TYPE(new_bp, DMU_OT_INTENT_LOG);
1675                 BP_SET_LEVEL(new_bp, 0);
1676                 BP_SET_BYTEORDER(new_bp, ZFS_HOST_BYTEORDER);
1677         }
1678
1679         return (error);
1680 }
1681
1682 /*
1683  * Free an intent log block.  We know it can't be a gang block, so there's
1684  * nothing to do except metaslab_free() it.
1685  */
1686 void
1687 zio_free_blk(spa_t *spa, blkptr_t *bp, uint64_t txg)
1688 {
1689         ASSERT(!BP_IS_GANG(bp));
1690
1691         metaslab_free(spa, bp, txg, B_FALSE);
1692 }
1693
1694 /*
1695  * ==========================================================================
1696  * Read and write to physical devices
1697  * ==========================================================================
1698  */
1699
1700 static void
1701 zio_vdev_io_probe_done(zio_t *zio)
1702 {
1703         zio_t *dio;
1704         vdev_t *vd = zio->io_private;
1705
1706         mutex_enter(&vd->vdev_probe_lock);
1707         ASSERT(vd->vdev_probe_zio == zio);
1708         vd->vdev_probe_zio = NULL;
1709         mutex_exit(&vd->vdev_probe_lock);
1710
1711         while ((dio = zio->io_delegate_list) != NULL) {
1712                 zio->io_delegate_list = dio->io_delegate_next;
1713                 dio->io_delegate_next = NULL;
1714                 if (!vdev_accessible(vd, dio))
1715                         dio->io_error = ENXIO;
1716                 zio_execute(dio);
1717         }
1718 }
1719
1720 /*
1721  * Probe the device to determine whether I/O failure is specific to this
1722  * zio (e.g. a bad sector) or affects the entire vdev (e.g. unplugged).
1723  */
1724 static int
1725 zio_vdev_io_probe(zio_t *zio)
1726 {
1727         vdev_t *vd = zio->io_vd;
1728         zio_t *pio = NULL;
1729         boolean_t created_pio = B_FALSE;
1730
1731         /*
1732          * Don't probe the probe.
1733          */
1734         if (zio->io_flags & ZIO_FLAG_PROBE)
1735                 return (ZIO_PIPELINE_CONTINUE);
1736
1737         /*
1738          * To prevent 'probe storms' when a device fails, we create
1739          * just one probe i/o at a time.  All zios that want to probe
1740          * this vdev will join the probe zio's io_delegate_list.
1741          */
1742         mutex_enter(&vd->vdev_probe_lock);
1743
1744         if ((pio = vd->vdev_probe_zio) == NULL) {
1745                 vd->vdev_probe_zio = pio = zio_root(zio->io_spa,
1746                     zio_vdev_io_probe_done, vd, ZIO_FLAG_CANFAIL);
1747                 created_pio = B_TRUE;
1748                 vd->vdev_probe_wanted = B_TRUE;
1749                 spa_async_request(zio->io_spa, SPA_ASYNC_PROBE);
1750         }
1751
1752         zio->io_delegate_next = pio->io_delegate_list;
1753         pio->io_delegate_list = zio;
1754
1755         mutex_exit(&vd->vdev_probe_lock);
1756
1757         if (created_pio) {
1758                 zio_nowait(vdev_probe(vd, pio));
1759                 zio_nowait(pio);
1760         }
1761
1762         return (ZIO_PIPELINE_STOP);
1763 }
1764
1765 static int
1766 zio_vdev_io_start(zio_t *zio)
1767 {
1768         vdev_t *vd = zio->io_vd;
1769         uint64_t align;
1770         spa_t *spa = zio->io_spa;
1771
1772         ASSERT(zio->io_error == 0);
1773         ASSERT(zio->io_child_error[ZIO_CHILD_VDEV] == 0);
1774
1775         if (vd == NULL) {
1776                 if (!(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
1777                         spa_config_enter(spa, SCL_ZIO, zio, RW_READER);
1778
1779                 /*
1780                  * The mirror_ops handle multiple DVAs in a single BP.
1781                  */
1782                 return (vdev_mirror_ops.vdev_op_io_start(zio));
1783         }
1784
1785         align = 1ULL << vd->vdev_top->vdev_ashift;
1786
1787         if (P2PHASE(zio->io_size, align) != 0) {
1788                 uint64_t asize = P2ROUNDUP(zio->io_size, align);
1789                 char *abuf = zio_buf_alloc(asize);
1790                 ASSERT(vd == vd->vdev_top);
1791                 if (zio->io_type == ZIO_TYPE_WRITE) {
1792                         bcopy(zio->io_data, abuf, zio->io_size);
1793                         bzero(abuf + zio->io_size, asize - zio->io_size);
1794                 }
1795                 zio_push_transform(zio, abuf, asize, asize, zio_subblock);
1796         }
1797
1798         ASSERT(P2PHASE(zio->io_offset, align) == 0);
1799         ASSERT(P2PHASE(zio->io_size, align) == 0);
1800         ASSERT(zio->io_type != ZIO_TYPE_WRITE || (spa_mode & FWRITE));
1801
1802         if (vd->vdev_ops->vdev_op_leaf &&
1803             (zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE)) {
1804
1805                 if (zio->io_type == ZIO_TYPE_READ && vdev_cache_read(zio) == 0)
1806                         return (ZIO_PIPELINE_STOP);
1807
1808                 if ((zio = vdev_queue_io(zio)) == NULL)
1809                         return (ZIO_PIPELINE_STOP);
1810
1811                 if (!vdev_accessible(vd, zio)) {
1812                         zio->io_error = ENXIO;
1813                         zio_interrupt(zio);
1814                         return (ZIO_PIPELINE_STOP);
1815                 }
1816
1817         }
1818
1819         return (vd->vdev_ops->vdev_op_io_start(zio));
1820 }
1821
1822 static int
1823 zio_vdev_io_done(zio_t *zio)
1824 {
1825         vdev_t *vd = zio->io_vd;
1826         vdev_ops_t *ops = vd ? vd->vdev_ops : &vdev_mirror_ops;
1827         boolean_t unexpected_error = B_FALSE;
1828
1829         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
1830                 return (ZIO_PIPELINE_STOP);
1831
1832         ASSERT(zio->io_type == ZIO_TYPE_READ || zio->io_type == ZIO_TYPE_WRITE);
1833
1834         if (vd != NULL && vd->vdev_ops->vdev_op_leaf) {
1835
1836                 vdev_queue_io_done(zio);
1837
1838                 if (zio->io_type == ZIO_TYPE_WRITE)
1839                         vdev_cache_write(zio);
1840
1841                 if (zio_injection_enabled && zio->io_error == 0)
1842                         zio->io_error = zio_handle_device_injection(vd, EIO);
1843
1844                 if (zio_injection_enabled && zio->io_error == 0)
1845                         zio->io_error = zio_handle_label_injection(zio, EIO);
1846
1847                 if (zio->io_error) {
1848                         if (!vdev_accessible(vd, zio)) {
1849                                 zio->io_error = ENXIO;
1850                         } else {
1851                                 unexpected_error = B_TRUE;
1852                         }
1853                 }
1854         }
1855
1856         ops->vdev_op_io_done(zio);
1857
1858         if (unexpected_error)
1859                 return (zio_vdev_io_probe(zio));
1860
1861         return (ZIO_PIPELINE_CONTINUE);
1862 }
1863
1864 static int
1865 zio_vdev_io_assess(zio_t *zio)
1866 {
1867         vdev_t *vd = zio->io_vd;
1868
1869         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE))
1870                 return (ZIO_PIPELINE_STOP);
1871
1872         if (vd == NULL && !(zio->io_flags & ZIO_FLAG_CONFIG_WRITER))
1873                 spa_config_exit(zio->io_spa, SCL_ZIO, zio);
1874
1875         if (zio->io_vsd != NULL) {
1876                 zio->io_vsd_free(zio);
1877                 zio->io_vsd = NULL;
1878         }
1879
1880         if (zio_injection_enabled && zio->io_error == 0)
1881                 zio->io_error = zio_handle_fault_injection(zio, EIO);
1882
1883         /*
1884          * If the I/O failed, determine whether we should attempt to retry it.
1885          */
1886         if (zio->io_error && vd == NULL &&
1887             !(zio->io_flags & (ZIO_FLAG_DONT_RETRY | ZIO_FLAG_IO_RETRY))) {
1888                 ASSERT(!(zio->io_flags & ZIO_FLAG_DONT_QUEUE)); /* not a leaf */
1889                 ASSERT(!(zio->io_flags & ZIO_FLAG_IO_BYPASS));  /* not a leaf */
1890                 zio->io_error = 0;
1891                 zio->io_flags |= ZIO_FLAG_IO_RETRY |
1892                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE;
1893                 zio->io_stage = ZIO_STAGE_VDEV_IO_START - 1;
1894                 zio_taskq_dispatch(zio, ZIO_TASKQ_ISSUE);
1895                 return (ZIO_PIPELINE_STOP);
1896         }
1897
1898         /*
1899          * If we got an error on a leaf device, convert it to ENXIO
1900          * if the device is not accessible at all.
1901          */
1902         if (zio->io_error && vd != NULL && vd->vdev_ops->vdev_op_leaf &&
1903             !vdev_accessible(vd, zio))
1904                 zio->io_error = ENXIO;
1905
1906         /*
1907          * If we can't write to an interior vdev (mirror or RAID-Z),
1908          * set vdev_cant_write so that we stop trying to allocate from it.
1909          */
1910         if (zio->io_error == ENXIO && zio->io_type == ZIO_TYPE_WRITE &&
1911             vd != NULL && !vd->vdev_ops->vdev_op_leaf)
1912                 vd->vdev_cant_write = B_TRUE;
1913
1914         if (zio->io_error)
1915                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
1916
1917         return (ZIO_PIPELINE_CONTINUE);
1918 }
1919
1920 void
1921 zio_vdev_io_reissue(zio_t *zio)
1922 {
1923         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
1924         ASSERT(zio->io_error == 0);
1925
1926         zio->io_stage--;
1927 }
1928
1929 void
1930 zio_vdev_io_redone(zio_t *zio)
1931 {
1932         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_DONE);
1933
1934         zio->io_stage--;
1935 }
1936
1937 void
1938 zio_vdev_io_bypass(zio_t *zio)
1939 {
1940         ASSERT(zio->io_stage == ZIO_STAGE_VDEV_IO_START);
1941         ASSERT(zio->io_error == 0);
1942
1943         zio->io_flags |= ZIO_FLAG_IO_BYPASS;
1944         zio->io_stage = ZIO_STAGE_VDEV_IO_ASSESS - 1;
1945 }
1946
1947 /*
1948  * ==========================================================================
1949  * Generate and verify checksums
1950  * ==========================================================================
1951  */
1952 static int
1953 zio_checksum_generate(zio_t *zio)
1954 {
1955         blkptr_t *bp = zio->io_bp;
1956         enum zio_checksum checksum;
1957
1958         if (bp == NULL) {
1959                 /*
1960                  * This is zio_write_phys().
1961                  * We're either generating a label checksum, or none at all.
1962                  */
1963                 checksum = zio->io_prop.zp_checksum;
1964
1965                 if (checksum == ZIO_CHECKSUM_OFF)
1966                         return (ZIO_PIPELINE_CONTINUE);
1967
1968                 ASSERT(checksum == ZIO_CHECKSUM_LABEL);
1969         } else {
1970                 if (BP_IS_GANG(bp) && zio->io_child_type == ZIO_CHILD_GANG) {
1971                         ASSERT(!IO_IS_ALLOCATING(zio));
1972                         checksum = ZIO_CHECKSUM_GANG_HEADER;
1973                 } else {
1974                         checksum = BP_GET_CHECKSUM(bp);
1975                 }
1976         }
1977
1978         zio_checksum_compute(zio, checksum, zio->io_data, zio->io_size);
1979
1980         return (ZIO_PIPELINE_CONTINUE);
1981 }
1982
1983 static int
1984 zio_checksum_verify(zio_t *zio)
1985 {
1986         blkptr_t *bp = zio->io_bp;
1987         int error;
1988
1989         if (bp == NULL) {
1990                 /*
1991                  * This is zio_read_phys().
1992                  * We're either verifying a label checksum, or nothing at all.
1993                  */
1994                 if (zio->io_prop.zp_checksum == ZIO_CHECKSUM_OFF)
1995                         return (ZIO_PIPELINE_CONTINUE);
1996
1997                 ASSERT(zio->io_prop.zp_checksum == ZIO_CHECKSUM_LABEL);
1998         }
1999
2000         if ((error = zio_checksum_error(zio)) != 0) {
2001                 zio->io_error = error;
2002                 if (!(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2003                         zfs_ereport_post(FM_EREPORT_ZFS_CHECKSUM,
2004                             zio->io_spa, zio->io_vd, zio, 0, 0);
2005                 }
2006         }
2007
2008         return (ZIO_PIPELINE_CONTINUE);
2009 }
2010
2011 /*
2012  * Called by RAID-Z to ensure we don't compute the checksum twice.
2013  */
2014 void
2015 zio_checksum_verified(zio_t *zio)
2016 {
2017         zio->io_pipeline &= ~(1U << ZIO_STAGE_CHECKSUM_VERIFY);
2018 }
2019
2020 /*
2021  * ==========================================================================
2022  * Error rank.  Error are ranked in the order 0, ENXIO, ECKSUM, EIO, other.
2023  * An error of 0 indictes success.  ENXIO indicates whole-device failure,
2024  * which may be transient (e.g. unplugged) or permament.  ECKSUM and EIO
2025  * indicate errors that are specific to one I/O, and most likely permanent.
2026  * Any other error is presumed to be worse because we weren't expecting it.
2027  * ==========================================================================
2028  */
2029 int
2030 zio_worst_error(int e1, int e2)
2031 {
2032         static int zio_error_rank[] = { 0, ENXIO, ECKSUM, EIO };
2033         int r1, r2;
2034
2035         for (r1 = 0; r1 < sizeof (zio_error_rank) / sizeof (int); r1++)
2036                 if (e1 == zio_error_rank[r1])
2037                         break;
2038
2039         for (r2 = 0; r2 < sizeof (zio_error_rank) / sizeof (int); r2++)
2040                 if (e2 == zio_error_rank[r2])
2041                         break;
2042
2043         return (r1 > r2 ? e1 : e2);
2044 }
2045
2046 /*
2047  * ==========================================================================
2048  * I/O completion
2049  * ==========================================================================
2050  */
2051 static int
2052 zio_ready(zio_t *zio)
2053 {
2054         blkptr_t *bp = zio->io_bp;
2055         zio_t *pio = zio->io_parent;
2056
2057         if (zio->io_ready) {
2058                 if (BP_IS_GANG(bp) &&
2059                     zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_READY))
2060                         return (ZIO_PIPELINE_STOP);
2061
2062                 ASSERT(IO_IS_ALLOCATING(zio));
2063                 ASSERT(bp->blk_birth == zio->io_txg || BP_IS_HOLE(bp));
2064                 ASSERT(zio->io_children[ZIO_CHILD_GANG][ZIO_WAIT_READY] == 0);
2065
2066                 zio->io_ready(zio);
2067         }
2068
2069         if (bp != NULL && bp != &zio->io_bp_copy)
2070                 zio->io_bp_copy = *bp;
2071
2072         if (zio->io_error)
2073                 zio->io_pipeline = ZIO_INTERLOCK_PIPELINE;
2074
2075         if (pio != NULL)
2076                 zio_notify_parent(pio, zio, ZIO_WAIT_READY);
2077
2078         return (ZIO_PIPELINE_CONTINUE);
2079 }
2080
2081 static int
2082 zio_done(zio_t *zio)
2083 {
2084         spa_t *spa = zio->io_spa;
2085         zio_t *pio = zio->io_parent;
2086         zio_t *lio = zio->io_logical;
2087         blkptr_t *bp = zio->io_bp;
2088         vdev_t *vd = zio->io_vd;
2089         uint64_t psize = zio->io_size;
2090
2091         /*
2092          * If our of children haven't all completed,
2093          * wait for them and then repeat this pipeline stage.
2094          */
2095         if (zio_wait_for_children(zio, ZIO_CHILD_VDEV, ZIO_WAIT_DONE) ||
2096             zio_wait_for_children(zio, ZIO_CHILD_GANG, ZIO_WAIT_DONE) ||
2097             zio_wait_for_children(zio, ZIO_CHILD_LOGICAL, ZIO_WAIT_DONE))
2098                 return (ZIO_PIPELINE_STOP);
2099
2100         for (int c = 0; c < ZIO_CHILD_TYPES; c++)
2101                 for (int w = 0; w < ZIO_WAIT_TYPES; w++)
2102                         ASSERT(zio->io_children[c][w] == 0);
2103
2104         if (bp != NULL) {
2105                 ASSERT(bp->blk_pad[0] == 0);
2106                 ASSERT(bp->blk_pad[1] == 0);
2107                 ASSERT(bp->blk_pad[2] == 0);
2108                 ASSERT(bcmp(bp, &zio->io_bp_copy, sizeof (blkptr_t)) == 0 ||
2109                     (pio != NULL && bp == pio->io_bp));
2110                 if (zio->io_type == ZIO_TYPE_WRITE && !BP_IS_HOLE(bp) &&
2111                     !(zio->io_flags & ZIO_FLAG_IO_REPAIR)) {
2112                         ASSERT(!BP_SHOULD_BYTESWAP(bp));
2113                         ASSERT3U(zio->io_prop.zp_ndvas, <=, BP_GET_NDVAS(bp));
2114                         ASSERT(BP_COUNT_GANG(bp) == 0 ||
2115                             (BP_COUNT_GANG(bp) == BP_GET_NDVAS(bp)));
2116                 }
2117         }
2118
2119         /*
2120          * If there were child vdev or gang errors, they apply to us now.
2121          */
2122         zio_inherit_child_errors(zio, ZIO_CHILD_VDEV);
2123         zio_inherit_child_errors(zio, ZIO_CHILD_GANG);
2124
2125         zio_pop_transforms(zio);        /* note: may set zio->io_error */
2126
2127         vdev_stat_update(zio, psize);
2128
2129         if (zio->io_error) {
2130                 /*
2131                  * If this I/O is attached to a particular vdev,
2132                  * generate an error message describing the I/O failure
2133                  * at the block level.  We ignore these errors if the
2134                  * device is currently unavailable.
2135                  */
2136                 if (zio->io_error != ECKSUM && vd != NULL && !vdev_is_dead(vd))
2137                         zfs_ereport_post(FM_EREPORT_ZFS_IO, spa, vd, zio, 0, 0);
2138
2139                 if ((zio->io_error == EIO ||
2140                     !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) && zio == lio) {
2141                         /*
2142                          * For logical I/O requests, tell the SPA to log the
2143                          * error and generate a logical data ereport.
2144                          */
2145                         spa_log_error(spa, zio);
2146                         zfs_ereport_post(FM_EREPORT_ZFS_DATA, spa, NULL, zio,
2147                             0, 0);
2148                 }
2149         }
2150
2151         if (zio->io_error && zio == lio) {
2152                 /*
2153                  * Determine whether zio should be reexecuted.  This will
2154                  * propagate all the way to the root via zio_notify_parent().
2155                  */
2156                 ASSERT(vd == NULL && bp != NULL);
2157
2158                 if (IO_IS_ALLOCATING(zio))
2159                         if (zio->io_error != ENOSPC)
2160                                 zio->io_reexecute |= ZIO_REEXECUTE_NOW;
2161                         else
2162                                 zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2163
2164                 if ((zio->io_type == ZIO_TYPE_READ ||
2165                     zio->io_type == ZIO_TYPE_FREE) &&
2166                     zio->io_error == ENXIO &&
2167                     spa_get_failmode(spa) != ZIO_FAILURE_MODE_CONTINUE)
2168                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2169
2170                 if (!(zio->io_flags & ZIO_FLAG_CANFAIL) && !zio->io_reexecute)
2171                         zio->io_reexecute |= ZIO_REEXECUTE_SUSPEND;
2172         }
2173
2174         /*
2175          * If there were logical child errors, they apply to us now.
2176          * We defer this until now to avoid conflating logical child
2177          * errors with errors that happened to the zio itself when
2178          * updating vdev stats and reporting FMA events above.
2179          */
2180         zio_inherit_child_errors(zio, ZIO_CHILD_LOGICAL);
2181
2182         if (zio->io_reexecute) {
2183                 /*
2184                  * This is a logical I/O that wants to reexecute.
2185                  *
2186                  * Reexecute is top-down.  When an i/o fails, if it's not
2187                  * the root, it simply notifies its parent and sticks around.
2188                  * The parent, seeing that it still has children in zio_done(),
2189                  * does the same.  This percolates all the way up to the root.
2190                  * The root i/o will reexecute or suspend the entire tree.
2191                  *
2192                  * This approach ensures that zio_reexecute() honors
2193                  * all the original i/o dependency relationships, e.g.
2194                  * parents not executing until children are ready.
2195                  */
2196                 ASSERT(zio->io_child_type == ZIO_CHILD_LOGICAL);
2197
2198                 if (IO_IS_ALLOCATING(zio))
2199                         zio_dva_unallocate(zio, zio->io_gang_tree, bp);
2200
2201                 zio_gang_tree_free(&zio->io_gang_tree);
2202
2203                 if (pio != NULL) {
2204                         /*
2205                          * We're not a root i/o, so there's nothing to do
2206                          * but notify our parent.  Don't propagate errors
2207                          * upward since we haven't permanently failed yet.
2208                          */
2209                         zio->io_flags |= ZIO_FLAG_DONT_PROPAGATE;
2210                         zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
2211                 } else if (zio->io_reexecute & ZIO_REEXECUTE_SUSPEND) {
2212                         /*
2213                          * We'd fail again if we reexecuted now, so suspend
2214                          * until conditions improve (e.g. device comes online).
2215                          */
2216                         zio_suspend(spa, zio);
2217                 } else {
2218                         /*
2219                          * Reexecution is potentially a huge amount of work.
2220                          * Hand it off to the otherwise-unused claim taskq.
2221                          */
2222                         (void) taskq_dispatch_safe(
2223                             spa->spa_zio_taskq[ZIO_TYPE_CLAIM][ZIO_TASKQ_ISSUE],
2224                             (task_func_t *)zio_reexecute, zio, &zio->io_task);
2225                 }
2226                 return (ZIO_PIPELINE_STOP);
2227         }
2228
2229         ASSERT(zio->io_child == NULL);
2230         ASSERT(zio->io_reexecute == 0);
2231         ASSERT(zio->io_error == 0 || (zio->io_flags & ZIO_FLAG_CANFAIL));
2232
2233         if (zio->io_done)
2234                 zio->io_done(zio);
2235
2236         zio_gang_tree_free(&zio->io_gang_tree);
2237
2238         ASSERT(zio->io_delegate_list == NULL);
2239         ASSERT(zio->io_delegate_next == NULL);
2240
2241         if (pio != NULL) {
2242                 zio_remove_child(pio, zio);
2243                 zio_notify_parent(pio, zio, ZIO_WAIT_DONE);
2244         }
2245
2246         if (zio->io_waiter != NULL) {
2247                 mutex_enter(&zio->io_lock);
2248                 zio->io_executor = NULL;
2249                 cv_broadcast(&zio->io_cv);
2250                 mutex_exit(&zio->io_lock);
2251         } else {
2252                 zio_destroy(zio);
2253         }
2254
2255         return (ZIO_PIPELINE_STOP);
2256 }
2257
2258 /*
2259  * ==========================================================================
2260  * I/O pipeline definition
2261  * ==========================================================================
2262  */
2263 static zio_pipe_stage_t *zio_pipeline[ZIO_STAGES] = {
2264         NULL,
2265         zio_issue_async,
2266         zio_read_bp_init,
2267         zio_write_bp_init,
2268         zio_checksum_generate,
2269         zio_gang_assemble,
2270         zio_gang_issue,
2271         zio_dva_allocate,
2272         zio_dva_free,
2273         zio_dva_claim,
2274         zio_ready,
2275         zio_vdev_io_start,
2276         zio_vdev_io_done,
2277         zio_vdev_io_assess,
2278         zio_checksum_verify,
2279         zio_done
2280 };