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