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