xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_raidz.c (revision d0b3ecdc274930e190ea233b6b69ff03782eaf8d)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
26  * Copyright (c) 2016 Gvozden Nešković. All rights reserved.
27  * Copyright (c) 2025, Klara, Inc.
28  * Copyright (c) 2026, Wasabi Technologies, Inc.
29  */
30 
31 #include <sys/zfs_context.h>
32 #include <sys/spa.h>
33 #include <sys/spa_impl.h>
34 #include <sys/zap.h>
35 #include <sys/vdev_impl.h>
36 #include <sys/metaslab_impl.h>
37 #include <sys/zio.h>
38 #include <sys/zio_checksum.h>
39 #include <sys/dmu_tx.h>
40 #include <sys/abd.h>
41 #include <sys/zfs_rlock.h>
42 #include <sys/fs/zfs.h>
43 #include <sys/fm/fs/zfs.h>
44 #include <sys/vdev_raidz.h>
45 #include <sys/vdev_raidz_impl.h>
46 #include <sys/vdev_draid.h>
47 #include <sys/uberblock_impl.h>
48 #include <sys/dsl_scan.h>
49 
50 #ifdef ZFS_DEBUG
51 #include <sys/vdev.h>	/* For vdev_xlate() in vdev_raidz_io_verify() */
52 #endif
53 
54 /*
55  * Virtual device vector for RAID-Z.
56  *
57  * This vdev supports single, double, and triple parity. For single parity,
58  * we use a simple XOR of all the data columns. For double or triple parity,
59  * we use a special case of Reed-Solomon coding. This extends the
60  * technique described in "The mathematics of RAID-6" by H. Peter Anvin by
61  * drawing on the system described in "A Tutorial on Reed-Solomon Coding for
62  * Fault-Tolerance in RAID-like Systems" by James S. Plank on which the
63  * former is also based. The latter is designed to provide higher performance
64  * for writes.
65  *
66  * Note that the Plank paper claimed to support arbitrary N+M, but was then
67  * amended six years later identifying a critical flaw that invalidates its
68  * claims. Nevertheless, the technique can be adapted to work for up to
69  * triple parity. For additional parity, the amendment "Note: Correction to
70  * the 1997 Tutorial on Reed-Solomon Coding" by James S. Plank and Ying Ding
71  * is viable, but the additional complexity means that write performance will
72  * suffer.
73  *
74  * All of the methods above operate on a Galois field, defined over the
75  * integers mod 2^N. In our case we choose N=8 for GF(8) so that all elements
76  * can be expressed with a single byte. Briefly, the operations on the
77  * field are defined as follows:
78  *
79  *   o addition (+) is represented by a bitwise XOR
80  *   o subtraction (-) is therefore identical to addition: A + B = A - B
81  *   o multiplication of A by 2 is defined by the following bitwise expression:
82  *
83  *	(A * 2)_7 = A_6
84  *	(A * 2)_6 = A_5
85  *	(A * 2)_5 = A_4
86  *	(A * 2)_4 = A_3 + A_7
87  *	(A * 2)_3 = A_2 + A_7
88  *	(A * 2)_2 = A_1 + A_7
89  *	(A * 2)_1 = A_0
90  *	(A * 2)_0 = A_7
91  *
92  * In C, multiplying by 2 is therefore ((a << 1) ^ ((a & 0x80) ? 0x1d : 0)).
93  * As an aside, this multiplication is derived from the error correcting
94  * primitive polynomial x^8 + x^4 + x^3 + x^2 + 1.
95  *
96  * Observe that any number in the field (except for 0) can be expressed as a
97  * power of 2 -- a generator for the field. We store a table of the powers of
98  * 2 and logs base 2 for quick look ups, and exploit the fact that A * B can
99  * be rewritten as 2^(log_2(A) + log_2(B)) (where '+' is normal addition rather
100  * than field addition). The inverse of a field element A (A^-1) is therefore
101  * A ^ (255 - 1) = A^254.
102  *
103  * The up-to-three parity columns, P, Q, R over several data columns,
104  * D_0, ... D_n-1, can be expressed by field operations:
105  *
106  *	P = D_0 + D_1 + ... + D_n-2 + D_n-1
107  *	Q = 2^n-1 * D_0 + 2^n-2 * D_1 + ... + 2^1 * D_n-2 + 2^0 * D_n-1
108  *	  = ((...((D_0) * 2 + D_1) * 2 + ...) * 2 + D_n-2) * 2 + D_n-1
109  *	R = 4^n-1 * D_0 + 4^n-2 * D_1 + ... + 4^1 * D_n-2 + 4^0 * D_n-1
110  *	  = ((...((D_0) * 4 + D_1) * 4 + ...) * 4 + D_n-2) * 4 + D_n-1
111  *
112  * We chose 1, 2, and 4 as our generators because 1 corresponds to the trivial
113  * XOR operation, and 2 and 4 can be computed quickly and generate linearly-
114  * independent coefficients. (There are no additional coefficients that have
115  * this property which is why the uncorrected Plank method breaks down.)
116  *
117  * See the reconstruction code below for how P, Q and R can used individually
118  * or in concert to recover missing data columns.
119  */
120 
121 #define	VDEV_RAIDZ_P		0
122 #define	VDEV_RAIDZ_Q		1
123 #define	VDEV_RAIDZ_R		2
124 
125 #define	VDEV_RAIDZ_MUL_2(x)	(((x) << 1) ^ (((x) & 0x80) ? 0x1d : 0))
126 #define	VDEV_RAIDZ_MUL_4(x)	(VDEV_RAIDZ_MUL_2(VDEV_RAIDZ_MUL_2(x)))
127 
128 /*
129  * We provide a mechanism to perform the field multiplication operation on a
130  * 64-bit value all at once rather than a byte at a time. This works by
131  * creating a mask from the top bit in each byte and using that to
132  * conditionally apply the XOR of 0x1d.
133  */
134 #define	VDEV_RAIDZ_64MUL_2(x, mask) \
135 { \
136 	(mask) = (x) & 0x8080808080808080ULL; \
137 	(mask) = ((mask) << 1) - ((mask) >> 7); \
138 	(x) = (((x) << 1) & 0xfefefefefefefefeULL) ^ \
139 	    ((mask) & 0x1d1d1d1d1d1d1d1dULL); \
140 }
141 
142 #define	VDEV_RAIDZ_64MUL_4(x, mask) \
143 { \
144 	VDEV_RAIDZ_64MUL_2((x), mask); \
145 	VDEV_RAIDZ_64MUL_2((x), mask); \
146 }
147 
148 
149 /*
150  * Big Theory Statement for how a RAIDZ VDEV is expanded
151  *
152  * An existing RAIDZ VDEV can be expanded by attaching a new disk. Expansion
153  * works with all three RAIDZ parity choices, including RAIDZ1, 2, or 3. VDEVs
154  * that have been previously expanded can be expanded again.
155  *
156  * The RAIDZ VDEV must be healthy (must be able to write to all the drives in
157  * the VDEV) when an expansion starts.  And the expansion will pause if any
158  * disk in the VDEV fails, and resume once the VDEV is healthy again. All other
159  * operations on the pool can continue while an expansion is in progress (e.g.
160  * read/write, snapshot, zpool add, etc). Except zpool checkpoint, zpool trim,
161  * and zpool initialize which can't be run during an expansion.  Following a
162  * reboot or export/import, the expansion resumes where it left off.
163  *
164  * == Reflowing the Data ==
165  *
166  * The expansion involves reflowing (copying) the data from the current set
167  * of disks to spread it across the new set which now has one more disk. This
168  * reflow operation is similar to reflowing text when the column width of a
169  * text editor window is expanded. The text doesn’t change but the location of
170  * the text changes to accommodate the new width. An example reflow result for
171  * a 4-wide RAIDZ1 to a 5-wide is shown below.
172  *
173  *                            Reflow End State
174  *            Each letter indicates a parity group (logical stripe)
175  *
176  *         Before expansion                         After Expansion
177  *     D1     D2     D3     D4               D1     D2     D3     D4     D5
178  *  +------+------+------+------+         +------+------+------+------+------+
179  *  |      |      |      |      |         |      |      |      |      |      |
180  *  |  A   |  A   |  A   |  A   |         |  A   |  A   |  A   |  A   |  B   |
181  *  |     1|     2|     3|     4|         |     1|     2|     3|     4|     5|
182  *  +------+------+------+------+         +------+------+------+------+------+
183  *  |      |      |      |      |         |      |      |      |      |      |
184  *  |  B   |  B   |  C   |  C   |         |  B   |  C   |  C   |  C   |  C   |
185  *  |     5|     6|     7|     8|         |     6|     7|     8|     9|    10|
186  *  +------+------+------+------+         +------+------+------+------+------+
187  *  |      |      |      |      |         |      |      |      |      |      |
188  *  |  C   |  C   |  D   |  D   |         |  D   |  D   |  E   |  E   |  E   |
189  *  |     9|    10|    11|    12|         |    11|    12|    13|    14|    15|
190  *  +------+------+------+------+         +------+------+------+------+------+
191  *  |      |      |      |      |         |      |      |      |      |      |
192  *  |  E   |  E   |  E   |  E   |   -->   |  E   |  F   |  F   |  G   |  G   |
193  *  |    13|    14|    15|    16|         |    16|    17|    18|p   19|    20|
194  *  +------+------+------+------+         +------+------+------+------+------+
195  *  |      |      |      |      |         |      |      |      |      |      |
196  *  |  F   |  F   |  G   |  G   |         |  G   |  G   |  H   |  H   |  H   |
197  *  |    17|    18|    19|    20|         |    21|    22|    23|    24|    25|
198  *  +------+------+------+------+         +------+------+------+------+------+
199  *  |      |      |      |      |         |      |      |      |      |      |
200  *  |  G   |  G   |  H   |  H   |         |  H   |  I   |  I   |  J   |  J   |
201  *  |    21|    22|    23|    24|         |    26|    27|    28|    29|    30|
202  *  +------+------+------+------+         +------+------+------+------+------+
203  *  |      |      |      |      |         |      |      |      |      |      |
204  *  |  H   |  H   |  I   |  I   |         |  J   |  J   |      |      |  K   |
205  *  |    25|    26|    27|    28|         |    31|    32|    33|    34|    35|
206  *  +------+------+------+------+         +------+------+------+------+------+
207  *
208  * This reflow approach has several advantages. There is no need to read or
209  * modify the block pointers or recompute any block checksums.  The reflow
210  * doesn’t need to know where the parity sectors reside. We can read and write
211  * data sequentially and the copy can occur in a background thread in open
212  * context. The design also allows for fast discovery of what data to copy.
213  *
214  * The VDEV metaslabs are processed, one at a time, to copy the block data to
215  * have it flow across all the disks. The metaslab is disabled for allocations
216  * during the copy. As an optimization, we only copy the allocated data which
217  * can be determined by looking at the metaslab range tree. During the copy we
218  * must maintain the redundancy guarantees of the RAIDZ VDEV (i.e., we still
219  * need to be able to survive losing parity count disks).  This means we
220  * cannot overwrite data during the reflow that would be needed if a disk is
221  * lost.
222  *
223  * After the reflow completes, all newly-written blocks will have the new
224  * layout, i.e., they will have the parity to data ratio implied by the new
225  * number of disks in the RAIDZ group.  Even though the reflow copies all of
226  * the allocated space (data and parity), it is only rearranged, not changed.
227  *
228  * This act of reflowing the data has a few implications about blocks
229  * that were written before the reflow completes:
230  *
231  *  - Old blocks will still use the same amount of space (i.e., they will have
232  *    the parity to data ratio implied by the old number of disks in the RAIDZ
233  *    group).
234  *  - Reading old blocks will be slightly slower than before the reflow, for
235  *    two reasons. First, we will have to read from all disks in the RAIDZ
236  *    VDEV, rather than being able to skip the children that contain only
237  *    parity of this block (because the data of a single block is now spread
238  *    out across all the disks).  Second, in most cases there will be an extra
239  *    bcopy, needed to rearrange the data back to its original layout in memory.
240  *
241  * == Scratch Area ==
242  *
243  * As we copy the block data, we can only progress to the point that writes
244  * will not overlap with blocks whose progress has not yet been recorded on
245  * disk.  Since partially-copied rows are always read from the old location,
246  * we need to stop one row before the sector-wise overlap, to prevent any
247  * row-wise overlap. For example, in the diagram above, when we reflow sector
248  * B6 it will overwite the original location for B5.
249  *
250  * To get around this, a scratch space is used so that we can start copying
251  * without risking data loss by overlapping the row. As an added benefit, it
252  * improves performance at the beginning of the reflow, but that small perf
253  * boost wouldn't be worth the complexity on its own.
254  *
255  * Ideally we want to copy at least 2 * (new_width)^2 so that we have a
256  * separation of 2*(new_width+1) and a chunk size of new_width+2. With the max
257  * RAIDZ width of 255 and 4K sectors this would be 2MB per disk. In practice
258  * the widths will likely be single digits so we can get a substantial chuck
259  * size using only a few MB of scratch per disk.
260  *
261  * The scratch area is persisted to disk which holds a large amount of reflowed
262  * state. We can always read the partially written stripes when a disk fails or
263  * the copy is interrupted (crash) during the initial copying phase and also
264  * get past a small chunk size restriction.  At a minimum, the scratch space
265  * must be large enough to get us to the point that one row does not overlap
266  * itself when moved (i.e new_width^2).  But going larger is even better. We
267  * use the 3.5 MiB reserved "boot" space that resides after the ZFS disk labels
268  * as our scratch space to handle overwriting the initial part of the VDEV.
269  *
270  *	0     256K   512K                    4M
271  *	+------+------+-----------------------+-----------------------------
272  *	| VDEV | VDEV |   Boot Block (3.5M)   |  Allocatable space ...
273  *	|  L0  |  L1  |       Reserved        |     (Metaslabs)
274  *	+------+------+-----------------------+-------------------------------
275  *                        Scratch Area
276  *
277  * == Reflow Progress Updates ==
278  * After the initial scratch-based reflow, the expansion process works
279  * similarly to device removal. We create a new open context thread which
280  * reflows the data, and periodically kicks off sync tasks to update logical
281  * state. In this case, state is the committed progress (offset of next data
282  * to copy). We need to persist the completed offset on disk, so that if we
283  * crash we know which format each VDEV offset is in.
284  *
285  * == Time Dependent Geometry ==
286  *
287  * In non-expanded RAIDZ, blocks are read from disk in a column by column
288  * fashion. For a multi-row block, the second sector is in the first column
289  * not in the second column. This allows us to issue full reads for each
290  * column directly into the request buffer. The block data is thus laid out
291  * sequentially in a column-by-column fashion.
292  *
293  * For example, in the before expansion diagram above, one logical block might
294  * be sectors G19-H26. The parity is in G19,H23; and the data is in
295  * G20,H24,G21,H25,G22,H26.
296  *
297  * After a block is reflowed, the sectors that were all in the original column
298  * data can now reside in different columns. When reading from an expanded
299  * VDEV, we need to know the logical stripe width for each block so we can
300  * reconstitute the block’s data after the reads are completed. Likewise,
301  * when we perform the combinatorial reconstruction we need to know the
302  * original width so we can retry combinations from the past layouts.
303  *
304  * Time dependent geometry is what we call having blocks with different layouts
305  * (stripe widths) in the same VDEV. This time-dependent geometry uses the
306  * block’s birth time (+ the time expansion ended) to establish the correct
307  * width for a given block. After an expansion completes, we record the time
308  * for blocks written with a particular width (geometry).
309  *
310  * == On Disk Format Changes ==
311  *
312  * New pool feature flag, 'raidz_expansion' whose reference count is the number
313  * of RAIDZ VDEVs that have been expanded.
314  *
315  * The blocks on expanded RAIDZ VDEV can have different logical stripe widths.
316  *
317  * Since the uberblock can point to arbitrary blocks, which might be on the
318  * expanding RAIDZ, and might or might not have been expanded. We need to know
319  * which way a block is laid out before reading it. This info is the next
320  * offset that needs to be reflowed and we persist that in the uberblock, in
321  * the new ub_raidz_reflow_info field, as opposed to the MOS or the vdev label.
322  * After the expansion is complete, we then use the raidz_expand_txgs array
323  * (see below) to determine how to read a block and the ub_raidz_reflow_info
324  * field no longer required.
325  *
326  * The uberblock's ub_raidz_reflow_info field also holds the scratch space
327  * state (i.e., active or not) which is also required before reading a block
328  * during the initial phase of reflowing the data.
329  *
330  * The top-level RAIDZ VDEV has two new entries in the nvlist:
331  *
332  * 'raidz_expand_txgs' array: logical stripe widths by txg are recorded here
333  *                            and used after the expansion is complete to
334  *                            determine how to read a raidz block
335  * 'raidz_expanding' boolean: present during reflow and removed after completion
336  *                            used during a spa import to resume an unfinished
337  *                            expansion
338  *
339  * And finally the VDEVs top zap adds the following informational entries:
340  *   VDEV_TOP_ZAP_RAIDZ_EXPAND_STATE
341  *   VDEV_TOP_ZAP_RAIDZ_EXPAND_START_TIME
342  *   VDEV_TOP_ZAP_RAIDZ_EXPAND_END_TIME
343  *   VDEV_TOP_ZAP_RAIDZ_EXPAND_BYTES_COPIED
344  */
345 
346 /*
347  * For testing only: pause the raidz expansion after reflowing this amount.
348  * (accessed by ZTS and ztest)
349  */
350 #ifdef	_KERNEL
351 static
352 #endif	/* _KERNEL */
353 unsigned long raidz_expand_max_reflow_bytes = 0;
354 
355 /*
356  * For testing only: pause the raidz expansion at a certain point.
357  */
358 uint_t raidz_expand_pause_point = 0;
359 
360 /*
361  * This represents the duration for a slow drive read sit out.
362  */
363 static unsigned long vdev_read_sit_out_secs = 600;
364 
365 /*
366  * How often each RAID-Z and dRAID vdev will check for slow disk outliers.
367  * Increasing this interval will reduce the sensitivity of detection (since all
368  * I/Os since the last check are included in the statistics), but will slow the
369  * response to a disk developing a problem.
370  *
371  * Defaults to once per second; setting extremely small values may cause
372  * negative performance effects.
373  */
374 static hrtime_t vdev_raidz_outlier_check_interval_ms = 1000;
375 
376 /*
377  * When performing slow outlier checks for RAID-Z and dRAID vdevs, this value is
378  * used to determine how far out an outlier must be before it counts as an event
379  * worth consdering.
380  *
381  * Smaller values will result in more aggressive sitting out of disks that may
382  * have problems, but may significantly increase the rate of spurious sit-outs.
383  */
384 static uint32_t vdev_raidz_outlier_insensitivity = 50;
385 
386 /*
387  * Maximum amount of copy io's outstanding at once.
388  */
389 #ifdef _ILP32
390 static unsigned long raidz_expand_max_copy_bytes = SPA_MAXBLOCKSIZE;
391 #else
392 static unsigned long raidz_expand_max_copy_bytes = 10 * SPA_MAXBLOCKSIZE;
393 #endif
394 
395 /*
396  * Apply raidz map abds aggregation if the number of rows in the map is equal
397  * or greater than the value below.
398  */
399 static unsigned long raidz_io_aggregate_rows = 4;
400 
401 /*
402  * Automatically start a pool scrub when a RAIDZ expansion completes in
403  * order to verify the checksums of all blocks which have been copied
404  * during the expansion.  Automatic scrubbing is enabled by default and
405  * is strongly recommended.
406  */
407 static int zfs_scrub_after_expand = 1;
408 
409 /*
410  * If there are errors when writing, but few enough that the data is
411  * recoverable, then ZFS used to silently move on, leaving the data not 100%
412  * redundant. If this tunable is set, we issue a read after that case occurs,
413  * allowing the normal error recovery process to handle it.
414  *
415  * NOTE: Currently applies only to raidz and draid.
416  */
417 static int zfs_scrub_partial_writes = 1;
418 
419 static void
vdev_raidz_row_free(raidz_row_t * rr)420 vdev_raidz_row_free(raidz_row_t *rr)
421 {
422 	abd_t *dabd = rr->rr_col[rr->rr_firstdatacol].rc_abd;
423 	for (int c = 0; c < rr->rr_firstdatacol; c++) {
424 		raidz_col_t *rc = &rr->rr_col[c];
425 
426 		if (rc->rc_size != 0 && rc->rc_abd != dabd)
427 			abd_free(rc->rc_abd);
428 		if (rc->rc_orig_data != NULL)
429 			abd_free(rc->rc_orig_data);
430 	}
431 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
432 		raidz_col_t *rc = &rr->rr_col[c];
433 
434 		if (rc->rc_size != 0)
435 			abd_free(rc->rc_abd);
436 		if (rc->rc_orig_data != NULL)
437 			abd_free(rc->rc_orig_data);
438 	}
439 
440 	if (rr->rr_abd_empty != NULL)
441 		abd_free(rr->rr_abd_empty);
442 
443 	kmem_free(rr, offsetof(raidz_row_t, rr_col[rr->rr_scols]));
444 }
445 
446 void
vdev_raidz_map_free(raidz_map_t * rm)447 vdev_raidz_map_free(raidz_map_t *rm)
448 {
449 	for (int i = 0; i < rm->rm_nrows; i++)
450 		vdev_raidz_row_free(rm->rm_row[i]);
451 
452 	if (rm->rm_nphys_cols) {
453 		for (int i = 0; i < rm->rm_nphys_cols; i++) {
454 			if (rm->rm_phys_col[i].rc_abd != NULL)
455 				abd_free(rm->rm_phys_col[i].rc_abd);
456 		}
457 
458 		kmem_free(rm->rm_phys_col, sizeof (raidz_col_t) *
459 		    rm->rm_nphys_cols);
460 	}
461 
462 	ASSERT0P(rm->rm_lr);
463 	kmem_free(rm, offsetof(raidz_map_t, rm_row[rm->rm_nrows]));
464 }
465 
466 static void
vdev_raidz_map_free_vsd(zio_t * zio)467 vdev_raidz_map_free_vsd(zio_t *zio)
468 {
469 	raidz_map_t *rm = zio->io_vsd;
470 
471 	vdev_raidz_map_free(rm);
472 }
473 
474 static int
vdev_raidz_reflow_compare(const void * x1,const void * x2)475 vdev_raidz_reflow_compare(const void *x1, const void *x2)
476 {
477 	const reflow_node_t *l = x1;
478 	const reflow_node_t *r = x2;
479 
480 	return (TREE_CMP(l->re_txg, r->re_txg));
481 }
482 
483 const zio_vsd_ops_t vdev_raidz_vsd_ops = {
484 	.vsd_free = vdev_raidz_map_free_vsd,
485 };
486 
487 raidz_row_t *
vdev_raidz_row_alloc(int cols,zio_t * zio)488 vdev_raidz_row_alloc(int cols, zio_t *zio)
489 {
490 	raidz_row_t *rr =
491 	    kmem_zalloc(offsetof(raidz_row_t, rr_col[cols]), KM_SLEEP);
492 
493 	rr->rr_cols = cols;
494 	rr->rr_scols = cols;
495 
496 	for (int c = 0; c < cols; c++) {
497 		raidz_col_t *rc = &rr->rr_col[c];
498 		rc->rc_shadow_devidx = INT_MAX;
499 		rc->rc_shadow_offset = UINT64_MAX;
500 		/*
501 		 * We can not allow self healing to take place for Direct I/O
502 		 * reads. There is nothing that stops the buffer contents from
503 		 * being manipulated while the I/O is in flight. It is possible
504 		 * that the checksum could be verified on the buffer and then
505 		 * the contents of that buffer are manipulated afterwards. This
506 		 * could lead to bad data being written out during self
507 		 * healing.
508 		 */
509 		if (!(zio->io_flags & ZIO_FLAG_DIO_READ))
510 			rc->rc_allow_repair = 1;
511 	}
512 	return (rr);
513 }
514 
515 static void
vdev_raidz_map_alloc_write(zio_t * zio,raidz_map_t * rm,uint64_t ashift)516 vdev_raidz_map_alloc_write(zio_t *zio, raidz_map_t *rm, uint64_t ashift)
517 {
518 	int c;
519 	int nwrapped = 0;
520 	uint64_t off = 0;
521 	raidz_row_t *rr = rm->rm_row[0];
522 
523 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
524 	ASSERT3U(rm->rm_nrows, ==, 1);
525 
526 	/*
527 	 * Pad any parity columns with additional space to account for skip
528 	 * sectors.
529 	 */
530 	if (rm->rm_skipstart < rr->rr_firstdatacol) {
531 		ASSERT0(rm->rm_skipstart);
532 		nwrapped = rm->rm_nskip;
533 	} else if (rr->rr_scols < (rm->rm_skipstart + rm->rm_nskip)) {
534 		nwrapped =
535 		    (rm->rm_skipstart + rm->rm_nskip) % rr->rr_scols;
536 	}
537 
538 	/*
539 	 * Optional single skip sectors (rc_size == 0) will be handled in
540 	 * vdev_raidz_io_start_write().
541 	 */
542 	int skipped = rr->rr_scols - rr->rr_cols;
543 
544 	/*
545 	 * When there is only a single data column the parity is a copy of
546 	 * it, so point all parity columns at the data ABD directly to avoid
547 	 * allocating buffers and computing parity.
548 	 */
549 	if (rr->rr_cols == rr->rr_firstdatacol + 1) {
550 		ASSERT0(nwrapped);
551 		ASSERT0(rm->rm_nskip);
552 		raidz_col_t *dc = &rr->rr_col[rr->rr_firstdatacol];
553 		dc->rc_abd = abd_get_offset_struct(&dc->rc_abdstruct,
554 		    zio->io_abd, 0, dc->rc_size);
555 		for (c = 0; c < rr->rr_firstdatacol; c++)
556 			rr->rr_col[c].rc_abd = dc->rc_abd;
557 		return;
558 	}
559 
560 	/* Allocate buffers for the parity columns */
561 	for (c = 0; c < rr->rr_firstdatacol; c++) {
562 		raidz_col_t *rc = &rr->rr_col[c];
563 
564 		/*
565 		 * Parity columns will pad out a linear ABD to account for
566 		 * the skip sector. A linear ABD is used here because
567 		 * parity calculations use the ABD buffer directly to calculate
568 		 * parity. This avoids doing a memcpy back to the ABD after the
569 		 * parity has been calculated. By issuing the parity column
570 		 * with the skip sector we can reduce contention on the child
571 		 * VDEV queue locks (vq_lock).
572 		 */
573 		if (c < nwrapped) {
574 			rc->rc_abd = abd_alloc_linear_struct(&rc->rc_abdstruct,
575 			    rc->rc_size + (1ULL << ashift), B_FALSE);
576 			abd_zero_off(rc->rc_abd, rc->rc_size, 1ULL << ashift);
577 			skipped++;
578 		} else {
579 			rc->rc_abd = abd_alloc_linear_struct(&rc->rc_abdstruct,
580 			    rc->rc_size, B_FALSE);
581 		}
582 	}
583 
584 	for (off = 0; c < rr->rr_cols; c++) {
585 		raidz_col_t *rc = &rr->rr_col[c];
586 		abd_t *abd = abd_get_offset_struct(&rc->rc_abdstruct,
587 		    zio->io_abd, off, rc->rc_size);
588 
589 		/*
590 		 * Generate I/O for skip sectors to improve aggregation
591 		 * continuity. We will use gang ABD's to reduce contention
592 		 * on the child VDEV queue locks (vq_lock) by issuing
593 		 * a single I/O that contains the data and skip sector.
594 		 *
595 		 * It is important to make sure that rc_size is not updated
596 		 * even though we are adding a skip sector to the ABD. When
597 		 * calculating the parity in vdev_raidz_generate_parity_row()
598 		 * the rc_size is used to iterate through the ABD's. We can
599 		 * not have zero'd out skip sectors used for calculating
600 		 * parity for raidz, because those same sectors are not used
601 		 * during reconstruction.
602 		 */
603 		if (c >= rm->rm_skipstart && skipped < rm->rm_nskip) {
604 			rc->rc_abd = abd_alloc_gang();
605 			abd_gang_add(rc->rc_abd, abd, B_TRUE);
606 			abd_gang_add(rc->rc_abd,
607 			    abd_get_zeros(1ULL << ashift), B_TRUE);
608 			skipped++;
609 		} else {
610 			rc->rc_abd = abd;
611 		}
612 		off += rc->rc_size;
613 	}
614 
615 	ASSERT3U(off, ==, zio->io_size);
616 	ASSERT3S(skipped, ==, rm->rm_nskip);
617 }
618 
619 static void
vdev_raidz_map_alloc_read(zio_t * zio,raidz_map_t * rm)620 vdev_raidz_map_alloc_read(zio_t *zio, raidz_map_t *rm)
621 {
622 	int c;
623 	raidz_row_t *rr = rm->rm_row[0];
624 
625 	ASSERT3U(rm->rm_nrows, ==, 1);
626 
627 	/* Allocate buffers for the parity columns */
628 	for (c = 0; c < rr->rr_firstdatacol; c++) {
629 		raidz_col_t *rc = &rr->rr_col[c];
630 		rc->rc_abd = abd_alloc_linear_struct(&rc->rc_abdstruct,
631 		    rc->rc_size, B_FALSE);
632 	}
633 
634 	for (uint64_t off = 0; c < rr->rr_cols; c++) {
635 		raidz_col_t *rc = &rr->rr_col[c];
636 		rc->rc_abd = abd_get_offset_struct(&rc->rc_abdstruct,
637 		    zio->io_abd, off, rc->rc_size);
638 		off += rc->rc_size;
639 	}
640 }
641 
642 /*
643  * Divides the IO evenly across all child vdevs; usually, dcols is
644  * the number of children in the target vdev.
645  *
646  * Avoid inlining the function to keep vdev_raidz_io_start(), which
647  * is this functions only caller, as small as possible on the stack.
648  */
649 noinline raidz_map_t *
vdev_raidz_map_alloc(zio_t * zio,uint64_t ashift,uint64_t dcols,uint64_t nparity)650 vdev_raidz_map_alloc(zio_t *zio, uint64_t ashift, uint64_t dcols,
651     uint64_t nparity)
652 {
653 	raidz_row_t *rr;
654 	/* The starting RAIDZ (parent) vdev sector of the block. */
655 	uint64_t b = zio->io_offset >> ashift;
656 	/* The zio's size in units of the vdev's minimum sector size. */
657 	uint64_t s = zio->io_size >> ashift;
658 	/* The first column for this stripe. */
659 	uint64_t f = b % dcols;
660 	/* The starting byte offset on each child vdev. */
661 	uint64_t o = (b / dcols) << ashift;
662 	uint64_t acols, scols;
663 
664 	raidz_map_t *rm =
665 	    kmem_zalloc(offsetof(raidz_map_t, rm_row[1]), KM_SLEEP);
666 	rm->rm_nrows = 1;
667 
668 	/*
669 	 * "Quotient": The number of data sectors for this stripe on all but
670 	 * the "big column" child vdevs that also contain "remainder" data.
671 	 */
672 	uint64_t q = s / (dcols - nparity);
673 
674 	/*
675 	 * "Remainder": The number of partial stripe data sectors in this I/O.
676 	 * This will add a sector to some, but not all, child vdevs.
677 	 */
678 	uint64_t r = s - q * (dcols - nparity);
679 
680 	/* The number of "big columns" - those which contain remainder data. */
681 	uint64_t bc = (r == 0 ? 0 : r + nparity);
682 
683 	/*
684 	 * The total number of data and parity sectors associated with
685 	 * this I/O.
686 	 */
687 	uint64_t tot = s + nparity * (q + (r == 0 ? 0 : 1));
688 
689 	/*
690 	 * acols: The columns that will be accessed.
691 	 * scols: The columns that will be accessed or skipped.
692 	 */
693 	if (q == 0) {
694 		/* Our I/O request doesn't span all child vdevs. */
695 		acols = bc;
696 		scols = MIN(dcols, roundup(bc, nparity + 1));
697 	} else {
698 		acols = dcols;
699 		scols = dcols;
700 	}
701 
702 	ASSERT3U(acols, <=, scols);
703 	rr = vdev_raidz_row_alloc(scols, zio);
704 	rm->rm_row[0] = rr;
705 	rr->rr_cols = acols;
706 	rr->rr_bigcols = bc;
707 	rr->rr_firstdatacol = nparity;
708 #ifdef ZFS_DEBUG
709 	rr->rr_offset = zio->io_offset;
710 	rr->rr_size = zio->io_size;
711 #endif
712 
713 	uint64_t asize = 0;
714 
715 	for (uint64_t c = 0; c < scols; c++) {
716 		raidz_col_t *rc = &rr->rr_col[c];
717 		uint64_t col = f + c;
718 		uint64_t coff = o;
719 		if (col >= dcols) {
720 			col -= dcols;
721 			coff += 1ULL << ashift;
722 		}
723 		rc->rc_devidx = col;
724 		rc->rc_offset = coff;
725 
726 		if (c >= acols)
727 			rc->rc_size = 0;
728 		else if (c < bc)
729 			rc->rc_size = (q + 1) << ashift;
730 		else
731 			rc->rc_size = q << ashift;
732 
733 		asize += rc->rc_size;
734 	}
735 
736 	ASSERT3U(asize, ==, tot << ashift);
737 	rm->rm_nskip = roundup(tot, nparity + 1) - tot;
738 	rm->rm_skipstart = bc;
739 
740 	/*
741 	 * If all data stored spans all columns, there's a danger that parity
742 	 * will always be on the same device and, since parity isn't read
743 	 * during normal operation, that device's I/O bandwidth won't be
744 	 * used effectively. We therefore switch the parity every 1MB.
745 	 *
746 	 * ... at least that was, ostensibly, the theory. As a practical
747 	 * matter unless we juggle the parity between all devices evenly, we
748 	 * won't see any benefit. Further, occasional writes that aren't a
749 	 * multiple of the LCM of the number of children and the minimum
750 	 * stripe width are sufficient to avoid pessimal behavior.
751 	 * Unfortunately, this decision created an implicit on-disk format
752 	 * requirement that we need to support for all eternity, but only
753 	 * for single-parity RAID-Z.
754 	 *
755 	 * If we intend to skip a sector in the zeroth column for padding
756 	 * we must make sure to note this swap. We will never intend to
757 	 * skip the first column since at least one data and one parity
758 	 * column must appear in each row.
759 	 */
760 	ASSERT(rr->rr_cols >= 2);
761 	ASSERT(rr->rr_col[0].rc_size == rr->rr_col[1].rc_size);
762 
763 	if (rr->rr_firstdatacol == 1 && (zio->io_offset & (1ULL << 20))) {
764 		uint64_t devidx = rr->rr_col[0].rc_devidx;
765 		o = rr->rr_col[0].rc_offset;
766 		rr->rr_col[0].rc_devidx = rr->rr_col[1].rc_devidx;
767 		rr->rr_col[0].rc_offset = rr->rr_col[1].rc_offset;
768 		rr->rr_col[1].rc_devidx = devidx;
769 		rr->rr_col[1].rc_offset = o;
770 		if (rm->rm_skipstart == 0)
771 			rm->rm_skipstart = 1;
772 	}
773 
774 	if (zio->io_type == ZIO_TYPE_WRITE) {
775 		vdev_raidz_map_alloc_write(zio, rm, ashift);
776 	} else {
777 		vdev_raidz_map_alloc_read(zio, rm);
778 	}
779 	/* init RAIDZ parity ops */
780 	rm->rm_ops = vdev_raidz_math_get_ops();
781 
782 	return (rm);
783 }
784 
785 /*
786  * Everything before reflow_offset_synced should have been moved to the new
787  * location (read and write completed).  However, this may not yet be reflected
788  * in the on-disk format (e.g. raidz_reflow_sync() has been called but the
789  * uberblock has not yet been written). If reflow is not in progress,
790  * reflow_offset_synced should be UINT64_MAX. For each row, if the row is
791  * entirely before reflow_offset_synced, it will come from the new location.
792  * Otherwise this row will come from the old location.  Therefore, rows that
793  * straddle the reflow_offset_synced will come from the old location.
794  *
795  * For writes, reflow_offset_next is the next offset to copy.  If a sector has
796  * been copied, but not yet reflected in the on-disk progress
797  * (reflow_offset_synced), it will also be written to the new (already copied)
798  * offset.
799  */
800 noinline raidz_map_t *
vdev_raidz_map_alloc_expanded(zio_t * zio,uint64_t ashift,uint64_t physical_cols,uint64_t logical_cols,uint64_t nparity,uint64_t reflow_offset_synced,uint64_t reflow_offset_next,boolean_t use_scratch)801 vdev_raidz_map_alloc_expanded(zio_t *zio,
802     uint64_t ashift, uint64_t physical_cols, uint64_t logical_cols,
803     uint64_t nparity, uint64_t reflow_offset_synced,
804     uint64_t reflow_offset_next, boolean_t use_scratch)
805 {
806 	abd_t *abd = zio->io_abd;
807 	uint64_t offset = zio->io_offset;
808 	uint64_t size = zio->io_size;
809 
810 	/* The zio's size in units of the vdev's minimum sector size. */
811 	uint64_t s = size >> ashift;
812 
813 	/*
814 	 * "Quotient": The number of data sectors for this stripe on all but
815 	 * the "big column" child vdevs that also contain "remainder" data.
816 	 * AKA "full rows"
817 	 */
818 	uint64_t q = s / (logical_cols - nparity);
819 
820 	/*
821 	 * "Remainder": The number of partial stripe data sectors in this I/O.
822 	 * This will add a sector to some, but not all, child vdevs.
823 	 */
824 	uint64_t r = s - q * (logical_cols - nparity);
825 
826 	/* The number of "big columns" - those which contain remainder data. */
827 	uint64_t bc = (r == 0 ? 0 : r + nparity);
828 
829 	/*
830 	 * The total number of data and parity sectors associated with
831 	 * this I/O.
832 	 */
833 	uint64_t tot = s + nparity * (q + (r == 0 ? 0 : 1));
834 
835 	/* How many rows contain data (not skip) */
836 	uint64_t rows = howmany(tot, logical_cols);
837 	int cols = MIN(tot, logical_cols);
838 
839 	raidz_map_t *rm =
840 	    kmem_zalloc(offsetof(raidz_map_t, rm_row[rows]),
841 	    KM_SLEEP);
842 	rm->rm_nrows = rows;
843 	rm->rm_nskip = roundup(tot, nparity + 1) - tot;
844 	rm->rm_skipstart = bc;
845 	uint64_t asize = 0;
846 
847 	for (uint64_t row = 0; row < rows; row++) {
848 		boolean_t row_use_scratch = B_FALSE;
849 		raidz_row_t *rr = vdev_raidz_row_alloc(cols, zio);
850 		rm->rm_row[row] = rr;
851 
852 		/* The starting RAIDZ (parent) vdev sector of the row. */
853 		uint64_t b = (offset >> ashift) + row * logical_cols;
854 
855 		/*
856 		 * If we are in the middle of a reflow, and the copying has
857 		 * not yet completed for any part of this row, then use the
858 		 * old location of this row.  Note that reflow_offset_synced
859 		 * reflects the i/o that's been completed, because it's
860 		 * updated by a synctask, after zio_wait(spa_txg_zio[]).
861 		 * This is sufficient for our check, even if that progress
862 		 * has not yet been recorded to disk (reflected in
863 		 * spa_ubsync).  Also note that we consider the last row to
864 		 * be "full width" (`cols`-wide rather than `bc`-wide) for
865 		 * this calculation. This causes a tiny bit of unnecessary
866 		 * double-writes but is safe and simpler to calculate.
867 		 */
868 		int row_phys_cols = physical_cols;
869 		if (b + cols > reflow_offset_synced >> ashift)
870 			row_phys_cols--;
871 		else if (use_scratch)
872 			row_use_scratch = B_TRUE;
873 
874 		/* starting child of this row */
875 		uint64_t child_id = b % row_phys_cols;
876 		/* The starting byte offset on each child vdev. */
877 		uint64_t child_offset = (b / row_phys_cols) << ashift;
878 
879 		/*
880 		 * Note, rr_cols is the entire width of the block, even
881 		 * if this row is shorter.  This is needed because parity
882 		 * generation (for Q and R) needs to know the entire width,
883 		 * because it treats the short row as though it was
884 		 * full-width (and the "phantom" sectors were zero-filled).
885 		 *
886 		 * Another approach to this would be to set cols shorter
887 		 * (to just the number of columns that we might do i/o to)
888 		 * and have another mechanism to tell the parity generation
889 		 * about the "entire width".  Reconstruction (at least
890 		 * vdev_raidz_reconstruct_general()) would also need to
891 		 * know about the "entire width".
892 		 */
893 		rr->rr_firstdatacol = nparity;
894 #ifdef ZFS_DEBUG
895 		/*
896 		 * note: rr_size is PSIZE, not ASIZE
897 		 */
898 		rr->rr_offset = b << ashift;
899 		rr->rr_size = (rr->rr_cols - rr->rr_firstdatacol) << ashift;
900 #endif
901 
902 		for (int c = 0; c < rr->rr_cols; c++, child_id++) {
903 			if (child_id >= row_phys_cols) {
904 				child_id -= row_phys_cols;
905 				child_offset += 1ULL << ashift;
906 			}
907 			raidz_col_t *rc = &rr->rr_col[c];
908 			rc->rc_devidx = child_id;
909 			rc->rc_offset = child_offset;
910 
911 			/*
912 			 * Get this from the scratch space if appropriate.
913 			 * This only happens if we crashed in the middle of
914 			 * raidz_reflow_scratch_sync() (while it's running,
915 			 * the rangelock prevents us from doing concurrent
916 			 * io), and even then only during zpool import or
917 			 * when the pool is imported readonly.
918 			 */
919 			if (row_use_scratch)
920 				rc->rc_offset -= VDEV_BOOT_SIZE;
921 
922 			uint64_t dc = c - rr->rr_firstdatacol;
923 			if (c < rr->rr_firstdatacol) {
924 				rc->rc_size = 1ULL << ashift;
925 
926 				/*
927 				 * Parity sectors' rc_abd's are set below
928 				 * after determining if this is an aggregation.
929 				 */
930 			} else if (row == rows - 1 && bc != 0 && c >= bc) {
931 				/*
932 				 * Past the end of the block (even including
933 				 * skip sectors).  This sector is part of the
934 				 * map so that we have full rows for p/q parity
935 				 * generation.
936 				 */
937 				rc->rc_size = 0;
938 				rc->rc_abd = NULL;
939 			} else {
940 				/* "data column" (col excluding parity) */
941 				uint64_t off;
942 
943 				if (c < bc || r == 0) {
944 					off = dc * rows + row;
945 				} else {
946 					off = r * rows +
947 					    (dc - r) * (rows - 1) + row;
948 				}
949 				rc->rc_size = 1ULL << ashift;
950 				rc->rc_abd = abd_get_offset_struct(
951 				    &rc->rc_abdstruct, abd, off << ashift,
952 				    rc->rc_size);
953 			}
954 
955 			if (rc->rc_size == 0)
956 				continue;
957 
958 			/*
959 			 * If any part of this row is in both old and new
960 			 * locations, the primary location is the old
961 			 * location. If this sector was already copied to the
962 			 * new location, we need to also write to the new,
963 			 * "shadow" location.
964 			 *
965 			 * Note, `row_phys_cols != physical_cols` indicates
966 			 * that the primary location is the old location.
967 			 * `b+c < reflow_offset_next` indicates that the copy
968 			 * to the new location has been initiated. We know
969 			 * that the copy has completed because we have the
970 			 * rangelock, which is held exclusively while the
971 			 * copy is in progress.
972 			 */
973 			if (row_use_scratch ||
974 			    (row_phys_cols != physical_cols &&
975 			    b + c < reflow_offset_next >> ashift)) {
976 				rc->rc_shadow_devidx = (b + c) % physical_cols;
977 				rc->rc_shadow_offset =
978 				    ((b + c) / physical_cols) << ashift;
979 				if (row_use_scratch)
980 					rc->rc_shadow_offset -= VDEV_BOOT_SIZE;
981 			}
982 
983 			asize += rc->rc_size;
984 		}
985 
986 		/*
987 		 * See comment in vdev_raidz_map_alloc()
988 		 */
989 		if (rr->rr_firstdatacol == 1 && rr->rr_cols > 1 &&
990 		    (offset & (1ULL << 20))) {
991 			ASSERT(rr->rr_cols >= 2);
992 			ASSERT(rr->rr_col[0].rc_size == rr->rr_col[1].rc_size);
993 
994 			int devidx0 = rr->rr_col[0].rc_devidx;
995 			uint64_t offset0 = rr->rr_col[0].rc_offset;
996 			int shadow_devidx0 = rr->rr_col[0].rc_shadow_devidx;
997 			uint64_t shadow_offset0 =
998 			    rr->rr_col[0].rc_shadow_offset;
999 
1000 			rr->rr_col[0].rc_devidx = rr->rr_col[1].rc_devidx;
1001 			rr->rr_col[0].rc_offset = rr->rr_col[1].rc_offset;
1002 			rr->rr_col[0].rc_shadow_devidx =
1003 			    rr->rr_col[1].rc_shadow_devidx;
1004 			rr->rr_col[0].rc_shadow_offset =
1005 			    rr->rr_col[1].rc_shadow_offset;
1006 
1007 			rr->rr_col[1].rc_devidx = devidx0;
1008 			rr->rr_col[1].rc_offset = offset0;
1009 			rr->rr_col[1].rc_shadow_devidx = shadow_devidx0;
1010 			rr->rr_col[1].rc_shadow_offset = shadow_offset0;
1011 		}
1012 	}
1013 	ASSERT3U(asize, ==, tot << ashift);
1014 
1015 	/*
1016 	 * Determine if the block is contiguous, in which case we can use
1017 	 * an aggregation.
1018 	 */
1019 	if (rows >= raidz_io_aggregate_rows) {
1020 		rm->rm_nphys_cols = physical_cols;
1021 		rm->rm_phys_col =
1022 		    kmem_zalloc(sizeof (raidz_col_t) * rm->rm_nphys_cols,
1023 		    KM_SLEEP);
1024 
1025 		/*
1026 		 * Determine the aggregate io's offset and size, and check
1027 		 * that the io is contiguous.
1028 		 */
1029 		for (int i = 0;
1030 		    i < rm->rm_nrows && rm->rm_phys_col != NULL; i++) {
1031 			raidz_row_t *rr = rm->rm_row[i];
1032 			for (int c = 0; c < rr->rr_cols; c++) {
1033 				raidz_col_t *rc = &rr->rr_col[c];
1034 				raidz_col_t *prc =
1035 				    &rm->rm_phys_col[rc->rc_devidx];
1036 
1037 				if (rc->rc_size == 0)
1038 					continue;
1039 
1040 				if (prc->rc_size == 0) {
1041 					ASSERT0(prc->rc_offset);
1042 					prc->rc_offset = rc->rc_offset;
1043 				} else if (prc->rc_offset + prc->rc_size !=
1044 				    rc->rc_offset) {
1045 					/*
1046 					 * This block is not contiguous and
1047 					 * therefore can't be aggregated.
1048 					 * This is expected to be rare, so
1049 					 * the cost of allocating and then
1050 					 * freeing rm_phys_col is not
1051 					 * significant.
1052 					 */
1053 					kmem_free(rm->rm_phys_col,
1054 					    sizeof (raidz_col_t) *
1055 					    rm->rm_nphys_cols);
1056 					rm->rm_phys_col = NULL;
1057 					rm->rm_nphys_cols = 0;
1058 					break;
1059 				}
1060 				prc->rc_size += rc->rc_size;
1061 			}
1062 		}
1063 	}
1064 	if (rm->rm_phys_col != NULL) {
1065 		/*
1066 		 * Allocate aggregate ABD's.
1067 		 */
1068 		for (int i = 0; i < rm->rm_nphys_cols; i++) {
1069 			raidz_col_t *prc = &rm->rm_phys_col[i];
1070 
1071 			prc->rc_devidx = i;
1072 
1073 			if (prc->rc_size == 0)
1074 				continue;
1075 
1076 			prc->rc_abd =
1077 			    abd_alloc_linear_struct(&prc->rc_abdstruct,
1078 			    prc->rc_size, B_FALSE);
1079 		}
1080 
1081 		/*
1082 		 * Point the parity abd's into the aggregate abd's.
1083 		 */
1084 		for (int i = 0; i < rm->rm_nrows; i++) {
1085 			raidz_row_t *rr = rm->rm_row[i];
1086 			for (int c = 0; c < rr->rr_firstdatacol; c++) {
1087 				raidz_col_t *rc = &rr->rr_col[c];
1088 				raidz_col_t *prc =
1089 				    &rm->rm_phys_col[rc->rc_devidx];
1090 				rc->rc_abd =
1091 				    abd_get_offset_struct(&rc->rc_abdstruct,
1092 				    prc->rc_abd,
1093 				    rc->rc_offset - prc->rc_offset,
1094 				    rc->rc_size);
1095 			}
1096 		}
1097 	} else {
1098 		/*
1099 		 * Allocate new abd's for the parity sectors.
1100 		 */
1101 		for (int i = 0; i < rm->rm_nrows; i++) {
1102 			raidz_row_t *rr = rm->rm_row[i];
1103 			for (int c = 0; c < rr->rr_firstdatacol; c++) {
1104 				raidz_col_t *rc = &rr->rr_col[c];
1105 				rc->rc_abd =
1106 				    abd_alloc_linear_struct(&rc->rc_abdstruct,
1107 				    rc->rc_size, B_TRUE);
1108 			}
1109 		}
1110 	}
1111 	/* init RAIDZ parity ops */
1112 	rm->rm_ops = vdev_raidz_math_get_ops();
1113 
1114 	return (rm);
1115 }
1116 
1117 struct pqr_struct {
1118 	uint64_t *p;
1119 	uint64_t *q;
1120 	uint64_t *r;
1121 };
1122 
1123 static int
vdev_raidz_p_func(void * buf,size_t size,void * private)1124 vdev_raidz_p_func(void *buf, size_t size, void *private)
1125 {
1126 	struct pqr_struct *pqr = private;
1127 	const uint64_t *src = buf;
1128 	int cnt = size / sizeof (src[0]);
1129 
1130 	ASSERT(pqr->p && !pqr->q && !pqr->r);
1131 
1132 	for (int i = 0; i < cnt; i++, src++, pqr->p++)
1133 		*pqr->p ^= *src;
1134 
1135 	return (0);
1136 }
1137 
1138 static int
vdev_raidz_pq_func(void * buf,size_t size,void * private)1139 vdev_raidz_pq_func(void *buf, size_t size, void *private)
1140 {
1141 	struct pqr_struct *pqr = private;
1142 	const uint64_t *src = buf;
1143 	uint64_t mask;
1144 	int cnt = size / sizeof (src[0]);
1145 
1146 	ASSERT(pqr->p && pqr->q && !pqr->r);
1147 
1148 	for (int i = 0; i < cnt; i++, src++, pqr->p++, pqr->q++) {
1149 		*pqr->p ^= *src;
1150 		VDEV_RAIDZ_64MUL_2(*pqr->q, mask);
1151 		*pqr->q ^= *src;
1152 	}
1153 
1154 	return (0);
1155 }
1156 
1157 static int
vdev_raidz_pqr_func(void * buf,size_t size,void * private)1158 vdev_raidz_pqr_func(void *buf, size_t size, void *private)
1159 {
1160 	struct pqr_struct *pqr = private;
1161 	const uint64_t *src = buf;
1162 	uint64_t mask;
1163 	int cnt = size / sizeof (src[0]);
1164 
1165 	ASSERT(pqr->p && pqr->q && pqr->r);
1166 
1167 	for (int i = 0; i < cnt; i++, src++, pqr->p++, pqr->q++, pqr->r++) {
1168 		*pqr->p ^= *src;
1169 		VDEV_RAIDZ_64MUL_2(*pqr->q, mask);
1170 		*pqr->q ^= *src;
1171 		VDEV_RAIDZ_64MUL_4(*pqr->r, mask);
1172 		*pqr->r ^= *src;
1173 	}
1174 
1175 	return (0);
1176 }
1177 
1178 static void
vdev_raidz_generate_parity_p(raidz_row_t * rr)1179 vdev_raidz_generate_parity_p(raidz_row_t *rr)
1180 {
1181 	uint64_t *p = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
1182 
1183 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1184 		abd_t *src = rr->rr_col[c].rc_abd;
1185 
1186 		if (c == rr->rr_firstdatacol) {
1187 			abd_copy_to_buf(p, src, rr->rr_col[c].rc_size);
1188 		} else {
1189 			struct pqr_struct pqr = { p, NULL, NULL };
1190 			(void) abd_iterate_func(src, 0, rr->rr_col[c].rc_size,
1191 			    vdev_raidz_p_func, &pqr);
1192 		}
1193 	}
1194 }
1195 
1196 static void
vdev_raidz_generate_parity_pq(raidz_row_t * rr)1197 vdev_raidz_generate_parity_pq(raidz_row_t *rr)
1198 {
1199 	uint64_t *p = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
1200 	uint64_t *q = abd_to_buf(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
1201 	uint64_t pcnt = rr->rr_col[VDEV_RAIDZ_P].rc_size / sizeof (p[0]);
1202 	ASSERT(rr->rr_col[VDEV_RAIDZ_P].rc_size ==
1203 	    rr->rr_col[VDEV_RAIDZ_Q].rc_size);
1204 
1205 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1206 		abd_t *src = rr->rr_col[c].rc_abd;
1207 
1208 		uint64_t ccnt = rr->rr_col[c].rc_size / sizeof (p[0]);
1209 
1210 		if (c == rr->rr_firstdatacol) {
1211 			ASSERT(ccnt == pcnt || ccnt == 0);
1212 			abd_copy_to_buf(p, src, rr->rr_col[c].rc_size);
1213 			(void) memcpy(q, p, rr->rr_col[c].rc_size);
1214 
1215 			for (uint64_t i = ccnt; i < pcnt; i++) {
1216 				p[i] = 0;
1217 				q[i] = 0;
1218 			}
1219 		} else {
1220 			struct pqr_struct pqr = { p, q, NULL };
1221 
1222 			ASSERT(ccnt <= pcnt);
1223 			(void) abd_iterate_func(src, 0, rr->rr_col[c].rc_size,
1224 			    vdev_raidz_pq_func, &pqr);
1225 
1226 			/*
1227 			 * Treat short columns as though they are full of 0s.
1228 			 * Note that there's therefore nothing needed for P.
1229 			 */
1230 			uint64_t mask;
1231 			for (uint64_t i = ccnt; i < pcnt; i++) {
1232 				VDEV_RAIDZ_64MUL_2(q[i], mask);
1233 			}
1234 		}
1235 	}
1236 }
1237 
1238 static void
vdev_raidz_generate_parity_pqr(raidz_row_t * rr)1239 vdev_raidz_generate_parity_pqr(raidz_row_t *rr)
1240 {
1241 	uint64_t *p = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
1242 	uint64_t *q = abd_to_buf(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
1243 	uint64_t *r = abd_to_buf(rr->rr_col[VDEV_RAIDZ_R].rc_abd);
1244 	uint64_t pcnt = rr->rr_col[VDEV_RAIDZ_P].rc_size / sizeof (p[0]);
1245 	ASSERT(rr->rr_col[VDEV_RAIDZ_P].rc_size ==
1246 	    rr->rr_col[VDEV_RAIDZ_Q].rc_size);
1247 	ASSERT(rr->rr_col[VDEV_RAIDZ_P].rc_size ==
1248 	    rr->rr_col[VDEV_RAIDZ_R].rc_size);
1249 
1250 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1251 		abd_t *src = rr->rr_col[c].rc_abd;
1252 
1253 		uint64_t ccnt = rr->rr_col[c].rc_size / sizeof (p[0]);
1254 
1255 		if (c == rr->rr_firstdatacol) {
1256 			ASSERT(ccnt == pcnt || ccnt == 0);
1257 			abd_copy_to_buf(p, src, rr->rr_col[c].rc_size);
1258 			(void) memcpy(q, p, rr->rr_col[c].rc_size);
1259 			(void) memcpy(r, p, rr->rr_col[c].rc_size);
1260 
1261 			for (uint64_t i = ccnt; i < pcnt; i++) {
1262 				p[i] = 0;
1263 				q[i] = 0;
1264 				r[i] = 0;
1265 			}
1266 		} else {
1267 			struct pqr_struct pqr = { p, q, r };
1268 
1269 			ASSERT(ccnt <= pcnt);
1270 			(void) abd_iterate_func(src, 0, rr->rr_col[c].rc_size,
1271 			    vdev_raidz_pqr_func, &pqr);
1272 
1273 			/*
1274 			 * Treat short columns as though they are full of 0s.
1275 			 * Note that there's therefore nothing needed for P.
1276 			 */
1277 			uint64_t mask;
1278 			for (uint64_t i = ccnt; i < pcnt; i++) {
1279 				VDEV_RAIDZ_64MUL_2(q[i], mask);
1280 				VDEV_RAIDZ_64MUL_4(r[i], mask);
1281 			}
1282 		}
1283 	}
1284 }
1285 
1286 /*
1287  * Generate RAID parity in the first virtual columns according to the number of
1288  * parity columns available.
1289  */
1290 void
vdev_raidz_generate_parity_row(raidz_map_t * rm,raidz_row_t * rr)1291 vdev_raidz_generate_parity_row(raidz_map_t *rm, raidz_row_t *rr)
1292 {
1293 	if (rr->rr_cols == 0) {
1294 		/*
1295 		 * We are handling this block one row at a time (because
1296 		 * this block has a different logical vs physical width,
1297 		 * due to RAIDZ expansion), and this is a pad-only row,
1298 		 * which has no parity.
1299 		 */
1300 		return;
1301 	}
1302 
1303 	/*
1304 	 * Single data column: parity is the data itself.
1305 	 */
1306 	if (rr->rr_col[VDEV_RAIDZ_P].rc_abd ==
1307 	    rr->rr_col[rr->rr_firstdatacol].rc_abd)
1308 		return;
1309 
1310 	/* Generate using the new math implementation */
1311 	if (vdev_raidz_math_generate(rm, rr) != RAIDZ_ORIGINAL_IMPL)
1312 		return;
1313 
1314 	switch (rr->rr_firstdatacol) {
1315 	case 1:
1316 		vdev_raidz_generate_parity_p(rr);
1317 		break;
1318 	case 2:
1319 		vdev_raidz_generate_parity_pq(rr);
1320 		break;
1321 	case 3:
1322 		vdev_raidz_generate_parity_pqr(rr);
1323 		break;
1324 	default:
1325 		cmn_err(CE_PANIC, "invalid RAID-Z configuration");
1326 	}
1327 }
1328 
1329 void
vdev_raidz_generate_parity(raidz_map_t * rm)1330 vdev_raidz_generate_parity(raidz_map_t *rm)
1331 {
1332 	for (int i = 0; i < rm->rm_nrows; i++) {
1333 		raidz_row_t *rr = rm->rm_row[i];
1334 		vdev_raidz_generate_parity_row(rm, rr);
1335 	}
1336 }
1337 
1338 static int
vdev_raidz_reconst_p_func(void * dbuf,void * sbuf,size_t size,void * private)1339 vdev_raidz_reconst_p_func(void *dbuf, void *sbuf, size_t size, void *private)
1340 {
1341 	(void) private;
1342 	uint64_t *dst = dbuf;
1343 	uint64_t *src = sbuf;
1344 	int cnt = size / sizeof (src[0]);
1345 
1346 	for (int i = 0; i < cnt; i++) {
1347 		dst[i] ^= src[i];
1348 	}
1349 
1350 	return (0);
1351 }
1352 
1353 static int
vdev_raidz_reconst_q_pre_func(void * dbuf,void * sbuf,size_t size,void * private)1354 vdev_raidz_reconst_q_pre_func(void *dbuf, void *sbuf, size_t size,
1355     void *private)
1356 {
1357 	(void) private;
1358 	uint64_t *dst = dbuf;
1359 	uint64_t *src = sbuf;
1360 	uint64_t mask;
1361 	int cnt = size / sizeof (dst[0]);
1362 
1363 	for (int i = 0; i < cnt; i++, dst++, src++) {
1364 		VDEV_RAIDZ_64MUL_2(*dst, mask);
1365 		*dst ^= *src;
1366 	}
1367 
1368 	return (0);
1369 }
1370 
1371 static int
vdev_raidz_reconst_q_pre_tail_func(void * buf,size_t size,void * private)1372 vdev_raidz_reconst_q_pre_tail_func(void *buf, size_t size, void *private)
1373 {
1374 	(void) private;
1375 	uint64_t *dst = buf;
1376 	uint64_t mask;
1377 	int cnt = size / sizeof (dst[0]);
1378 
1379 	for (int i = 0; i < cnt; i++, dst++) {
1380 		/* same operation as vdev_raidz_reconst_q_pre_func() on dst */
1381 		VDEV_RAIDZ_64MUL_2(*dst, mask);
1382 	}
1383 
1384 	return (0);
1385 }
1386 
1387 struct reconst_q_struct {
1388 	uint64_t *q;
1389 	int exp;
1390 };
1391 
1392 static int
vdev_raidz_reconst_q_post_func(void * buf,size_t size,void * private)1393 vdev_raidz_reconst_q_post_func(void *buf, size_t size, void *private)
1394 {
1395 	struct reconst_q_struct *rq = private;
1396 	uint64_t *dst = buf;
1397 	int cnt = size / sizeof (dst[0]);
1398 
1399 	for (int i = 0; i < cnt; i++, dst++, rq->q++) {
1400 		int j;
1401 		uint8_t *b;
1402 
1403 		*dst ^= *rq->q;
1404 		for (j = 0, b = (uint8_t *)dst; j < 8; j++, b++) {
1405 			*b = vdev_raidz_exp2(*b, rq->exp);
1406 		}
1407 	}
1408 
1409 	return (0);
1410 }
1411 
1412 struct reconst_pq_struct {
1413 	uint8_t *p;
1414 	uint8_t *q;
1415 	uint8_t *pxy;
1416 	uint8_t *qxy;
1417 	int aexp;
1418 	int bexp;
1419 };
1420 
1421 static int
vdev_raidz_reconst_pq_func(void * xbuf,void * ybuf,size_t size,void * private)1422 vdev_raidz_reconst_pq_func(void *xbuf, void *ybuf, size_t size, void *private)
1423 {
1424 	struct reconst_pq_struct *rpq = private;
1425 	uint8_t *xd = xbuf;
1426 	uint8_t *yd = ybuf;
1427 
1428 	for (int i = 0; i < size;
1429 	    i++, rpq->p++, rpq->q++, rpq->pxy++, rpq->qxy++, xd++, yd++) {
1430 		*xd = vdev_raidz_exp2(*rpq->p ^ *rpq->pxy, rpq->aexp) ^
1431 		    vdev_raidz_exp2(*rpq->q ^ *rpq->qxy, rpq->bexp);
1432 		*yd = *rpq->p ^ *rpq->pxy ^ *xd;
1433 	}
1434 
1435 	return (0);
1436 }
1437 
1438 static int
vdev_raidz_reconst_pq_tail_func(void * xbuf,size_t size,void * private)1439 vdev_raidz_reconst_pq_tail_func(void *xbuf, size_t size, void *private)
1440 {
1441 	struct reconst_pq_struct *rpq = private;
1442 	uint8_t *xd = xbuf;
1443 
1444 	for (int i = 0; i < size;
1445 	    i++, rpq->p++, rpq->q++, rpq->pxy++, rpq->qxy++, xd++) {
1446 		/* same operation as vdev_raidz_reconst_pq_func() on xd */
1447 		*xd = vdev_raidz_exp2(*rpq->p ^ *rpq->pxy, rpq->aexp) ^
1448 		    vdev_raidz_exp2(*rpq->q ^ *rpq->qxy, rpq->bexp);
1449 	}
1450 
1451 	return (0);
1452 }
1453 
1454 static void
vdev_raidz_reconstruct_p(raidz_row_t * rr,int * tgts,int ntgts)1455 vdev_raidz_reconstruct_p(raidz_row_t *rr, int *tgts, int ntgts)
1456 {
1457 	int x = tgts[0];
1458 	abd_t *dst, *src;
1459 
1460 	if (zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT)
1461 		zfs_dbgmsg("reconstruct_p(rm=%px x=%u)", rr, x);
1462 
1463 	ASSERT3U(ntgts, ==, 1);
1464 	ASSERT3U(x, >=, rr->rr_firstdatacol);
1465 	ASSERT3U(x, <, rr->rr_cols);
1466 
1467 	ASSERT3U(rr->rr_col[x].rc_size, <=, rr->rr_col[VDEV_RAIDZ_P].rc_size);
1468 
1469 	src = rr->rr_col[VDEV_RAIDZ_P].rc_abd;
1470 	dst = rr->rr_col[x].rc_abd;
1471 
1472 	abd_copy_from_buf(dst, abd_to_buf(src), rr->rr_col[x].rc_size);
1473 
1474 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1475 		uint64_t size = MIN(rr->rr_col[x].rc_size,
1476 		    rr->rr_col[c].rc_size);
1477 
1478 		src = rr->rr_col[c].rc_abd;
1479 
1480 		if (c == x)
1481 			continue;
1482 
1483 		(void) abd_iterate_func2(dst, src, 0, 0, size,
1484 		    vdev_raidz_reconst_p_func, NULL);
1485 	}
1486 }
1487 
1488 static void
vdev_raidz_reconstruct_q(raidz_row_t * rr,int * tgts,int ntgts)1489 vdev_raidz_reconstruct_q(raidz_row_t *rr, int *tgts, int ntgts)
1490 {
1491 	int x = tgts[0];
1492 	int c, exp;
1493 	abd_t *dst, *src;
1494 
1495 	if (zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT)
1496 		zfs_dbgmsg("reconstruct_q(rm=%px x=%u)", rr, x);
1497 
1498 	ASSERT(ntgts == 1);
1499 
1500 	ASSERT(rr->rr_col[x].rc_size <= rr->rr_col[VDEV_RAIDZ_Q].rc_size);
1501 
1502 	for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1503 		uint64_t size = (c == x) ? 0 : MIN(rr->rr_col[x].rc_size,
1504 		    rr->rr_col[c].rc_size);
1505 
1506 		src = rr->rr_col[c].rc_abd;
1507 		dst = rr->rr_col[x].rc_abd;
1508 
1509 		if (c == rr->rr_firstdatacol) {
1510 			abd_copy(dst, src, size);
1511 			if (rr->rr_col[x].rc_size > size) {
1512 				abd_zero_off(dst, size,
1513 				    rr->rr_col[x].rc_size - size);
1514 			}
1515 		} else {
1516 			ASSERT3U(size, <=, rr->rr_col[x].rc_size);
1517 			(void) abd_iterate_func2(dst, src, 0, 0, size,
1518 			    vdev_raidz_reconst_q_pre_func, NULL);
1519 			(void) abd_iterate_func(dst,
1520 			    size, rr->rr_col[x].rc_size - size,
1521 			    vdev_raidz_reconst_q_pre_tail_func, NULL);
1522 		}
1523 	}
1524 
1525 	src = rr->rr_col[VDEV_RAIDZ_Q].rc_abd;
1526 	dst = rr->rr_col[x].rc_abd;
1527 	exp = 255 - (rr->rr_cols - 1 - x);
1528 
1529 	struct reconst_q_struct rq = { abd_to_buf(src), exp };
1530 	(void) abd_iterate_func(dst, 0, rr->rr_col[x].rc_size,
1531 	    vdev_raidz_reconst_q_post_func, &rq);
1532 }
1533 
1534 static void
vdev_raidz_reconstruct_pq(raidz_row_t * rr,int * tgts,int ntgts)1535 vdev_raidz_reconstruct_pq(raidz_row_t *rr, int *tgts, int ntgts)
1536 {
1537 	uint8_t *p, *q, *pxy, *qxy, tmp, a, b, aexp, bexp;
1538 	abd_t *pdata, *qdata;
1539 	uint64_t xsize, ysize;
1540 	int x = tgts[0];
1541 	int y = tgts[1];
1542 	abd_t *xd, *yd;
1543 
1544 	if (zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT)
1545 		zfs_dbgmsg("reconstruct_pq(rm=%px x=%u y=%u)", rr, x, y);
1546 
1547 	ASSERT(ntgts == 2);
1548 	ASSERT(x < y);
1549 	ASSERT(x >= rr->rr_firstdatacol);
1550 	ASSERT(y < rr->rr_cols);
1551 
1552 	ASSERT(rr->rr_col[x].rc_size >= rr->rr_col[y].rc_size);
1553 
1554 	/*
1555 	 * Move the parity data aside -- we're going to compute parity as
1556 	 * though columns x and y were full of zeros -- Pxy and Qxy. We want to
1557 	 * reuse the parity generation mechanism without trashing the actual
1558 	 * parity so we make those columns appear to be full of zeros by
1559 	 * setting their lengths to zero.
1560 	 */
1561 	pdata = rr->rr_col[VDEV_RAIDZ_P].rc_abd;
1562 	qdata = rr->rr_col[VDEV_RAIDZ_Q].rc_abd;
1563 	xsize = rr->rr_col[x].rc_size;
1564 	ysize = rr->rr_col[y].rc_size;
1565 
1566 	rr->rr_col[VDEV_RAIDZ_P].rc_abd =
1567 	    abd_alloc_linear(rr->rr_col[VDEV_RAIDZ_P].rc_size, B_TRUE);
1568 	rr->rr_col[VDEV_RAIDZ_Q].rc_abd =
1569 	    abd_alloc_linear(rr->rr_col[VDEV_RAIDZ_Q].rc_size, B_TRUE);
1570 	rr->rr_col[x].rc_size = 0;
1571 	rr->rr_col[y].rc_size = 0;
1572 
1573 	vdev_raidz_generate_parity_pq(rr);
1574 
1575 	rr->rr_col[x].rc_size = xsize;
1576 	rr->rr_col[y].rc_size = ysize;
1577 
1578 	p = abd_to_buf(pdata);
1579 	q = abd_to_buf(qdata);
1580 	pxy = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
1581 	qxy = abd_to_buf(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
1582 	xd = rr->rr_col[x].rc_abd;
1583 	yd = rr->rr_col[y].rc_abd;
1584 
1585 	/*
1586 	 * We now have:
1587 	 *	Pxy = P + D_x + D_y
1588 	 *	Qxy = Q + 2^(ndevs - 1 - x) * D_x + 2^(ndevs - 1 - y) * D_y
1589 	 *
1590 	 * We can then solve for D_x:
1591 	 *	D_x = A * (P + Pxy) + B * (Q + Qxy)
1592 	 * where
1593 	 *	A = 2^(x - y) * (2^(x - y) + 1)^-1
1594 	 *	B = 2^(ndevs - 1 - x) * (2^(x - y) + 1)^-1
1595 	 *
1596 	 * With D_x in hand, we can easily solve for D_y:
1597 	 *	D_y = P + Pxy + D_x
1598 	 */
1599 
1600 	a = vdev_raidz_pow2[255 + x - y];
1601 	b = vdev_raidz_pow2[255 - (rr->rr_cols - 1 - x)];
1602 	tmp = 255 - vdev_raidz_log2[a ^ 1];
1603 
1604 	aexp = vdev_raidz_log2[vdev_raidz_exp2(a, tmp)];
1605 	bexp = vdev_raidz_log2[vdev_raidz_exp2(b, tmp)];
1606 
1607 	ASSERT3U(xsize, >=, ysize);
1608 	struct reconst_pq_struct rpq = { p, q, pxy, qxy, aexp, bexp };
1609 
1610 	(void) abd_iterate_func2(xd, yd, 0, 0, ysize,
1611 	    vdev_raidz_reconst_pq_func, &rpq);
1612 	(void) abd_iterate_func(xd, ysize, xsize - ysize,
1613 	    vdev_raidz_reconst_pq_tail_func, &rpq);
1614 
1615 	abd_free(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
1616 	abd_free(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
1617 
1618 	/*
1619 	 * Restore the saved parity data.
1620 	 */
1621 	rr->rr_col[VDEV_RAIDZ_P].rc_abd = pdata;
1622 	rr->rr_col[VDEV_RAIDZ_Q].rc_abd = qdata;
1623 }
1624 
1625 /*
1626  * In the general case of reconstruction, we must solve the system of linear
1627  * equations defined by the coefficients used to generate parity as well as
1628  * the contents of the data and parity disks. This can be expressed with
1629  * vectors for the original data (D) and the actual data (d) and parity (p)
1630  * and a matrix composed of the identity matrix (I) and a dispersal matrix (V):
1631  *
1632  *            __   __                     __     __
1633  *            |     |         __     __   |  p_0  |
1634  *            |  V  |         |  D_0  |   | p_m-1 |
1635  *            |     |    x    |   :   | = |  d_0  |
1636  *            |  I  |         | D_n-1 |   |   :   |
1637  *            |     |         ~~     ~~   | d_n-1 |
1638  *            ~~   ~~                     ~~     ~~
1639  *
1640  * I is simply a square identity matrix of size n, and V is a vandermonde
1641  * matrix defined by the coefficients we chose for the various parity columns
1642  * (1, 2, 4). Note that these values were chosen both for simplicity, speedy
1643  * computation as well as linear separability.
1644  *
1645  *      __               __               __     __
1646  *      |   1   ..  1 1 1 |               |  p_0  |
1647  *      | 2^n-1 ..  4 2 1 |   __     __   |   :   |
1648  *      | 4^n-1 .. 16 4 1 |   |  D_0  |   | p_m-1 |
1649  *      |   1   ..  0 0 0 |   |  D_1  |   |  d_0  |
1650  *      |   0   ..  0 0 0 | x |  D_2  | = |  d_1  |
1651  *      |   :       : : : |   |   :   |   |  d_2  |
1652  *      |   0   ..  1 0 0 |   | D_n-1 |   |   :   |
1653  *      |   0   ..  0 1 0 |   ~~     ~~   |   :   |
1654  *      |   0   ..  0 0 1 |               | d_n-1 |
1655  *      ~~               ~~               ~~     ~~
1656  *
1657  * Note that I, V, d, and p are known. To compute D, we must invert the
1658  * matrix and use the known data and parity values to reconstruct the unknown
1659  * data values. We begin by removing the rows in V|I and d|p that correspond
1660  * to failed or missing columns; we then make V|I square (n x n) and d|p
1661  * sized n by removing rows corresponding to unused parity from the bottom up
1662  * to generate (V|I)' and (d|p)'. We can then generate the inverse of (V|I)'
1663  * using Gauss-Jordan elimination. In the example below we use m=3 parity
1664  * columns, n=8 data columns, with errors in d_1, d_2, and p_1:
1665  *           __                               __
1666  *           |  1   1   1   1   1   1   1   1  |
1667  *           | 128  64  32  16  8   4   2   1  | <-----+-+-- missing disks
1668  *           |  19 205 116  29  64  16  4   1  |      / /
1669  *           |  1   0   0   0   0   0   0   0  |     / /
1670  *           |  0   1   0   0   0   0   0   0  | <--' /
1671  *  (V|I)  = |  0   0   1   0   0   0   0   0  | <---'
1672  *           |  0   0   0   1   0   0   0   0  |
1673  *           |  0   0   0   0   1   0   0   0  |
1674  *           |  0   0   0   0   0   1   0   0  |
1675  *           |  0   0   0   0   0   0   1   0  |
1676  *           |  0   0   0   0   0   0   0   1  |
1677  *           ~~                               ~~
1678  *           __                               __
1679  *           |  1   1   1   1   1   1   1   1  |
1680  *           | 128  64  32  16  8   4   2   1  |
1681  *           |  19 205 116  29  64  16  4   1  |
1682  *           |  1   0   0   0   0   0   0   0  |
1683  *           |  0   1   0   0   0   0   0   0  |
1684  *  (V|I)' = |  0   0   1   0   0   0   0   0  |
1685  *           |  0   0   0   1   0   0   0   0  |
1686  *           |  0   0   0   0   1   0   0   0  |
1687  *           |  0   0   0   0   0   1   0   0  |
1688  *           |  0   0   0   0   0   0   1   0  |
1689  *           |  0   0   0   0   0   0   0   1  |
1690  *           ~~                               ~~
1691  *
1692  * Here we employ Gauss-Jordan elimination to find the inverse of (V|I)'. We
1693  * have carefully chosen the seed values 1, 2, and 4 to ensure that this
1694  * matrix is not singular.
1695  * __                                                                 __
1696  * |  1   1   1   1   1   1   1   1     1   0   0   0   0   0   0   0  |
1697  * |  19 205 116  29  64  16  4   1     0   1   0   0   0   0   0   0  |
1698  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1699  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1700  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1701  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1702  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1703  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1704  * ~~                                                                 ~~
1705  * __                                                                 __
1706  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1707  * |  1   1   1   1   1   1   1   1     1   0   0   0   0   0   0   0  |
1708  * |  19 205 116  29  64  16  4   1     0   1   0   0   0   0   0   0  |
1709  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1710  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1711  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1712  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1713  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1714  * ~~                                                                 ~~
1715  * __                                                                 __
1716  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1717  * |  0   1   1   0   0   0   0   0     1   0   1   1   1   1   1   1  |
1718  * |  0  205 116  0   0   0   0   0     0   1   19  29  64  16  4   1  |
1719  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1720  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1721  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1722  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1723  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1724  * ~~                                                                 ~~
1725  * __                                                                 __
1726  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1727  * |  0   1   1   0   0   0   0   0     1   0   1   1   1   1   1   1  |
1728  * |  0   0  185  0   0   0   0   0    205  1  222 208 141 221 201 204 |
1729  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1730  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1731  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1732  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1733  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1734  * ~~                                                                 ~~
1735  * __                                                                 __
1736  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1737  * |  0   1   1   0   0   0   0   0     1   0   1   1   1   1   1   1  |
1738  * |  0   0   1   0   0   0   0   0    166 100  4   40 158 168 216 209 |
1739  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1740  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1741  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1742  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1743  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1744  * ~~                                                                 ~~
1745  * __                                                                 __
1746  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1747  * |  0   1   0   0   0   0   0   0    167 100  5   41 159 169 217 208 |
1748  * |  0   0   1   0   0   0   0   0    166 100  4   40 158 168 216 209 |
1749  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1750  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1751  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1752  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1753  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1754  * ~~                                                                 ~~
1755  *                   __                               __
1756  *                   |  0   0   1   0   0   0   0   0  |
1757  *                   | 167 100  5   41 159 169 217 208 |
1758  *                   | 166 100  4   40 158 168 216 209 |
1759  *       (V|I)'^-1 = |  0   0   0   1   0   0   0   0  |
1760  *                   |  0   0   0   0   1   0   0   0  |
1761  *                   |  0   0   0   0   0   1   0   0  |
1762  *                   |  0   0   0   0   0   0   1   0  |
1763  *                   |  0   0   0   0   0   0   0   1  |
1764  *                   ~~                               ~~
1765  *
1766  * We can then simply compute D = (V|I)'^-1 x (d|p)' to discover the values
1767  * of the missing data.
1768  *
1769  * As is apparent from the example above, the only non-trivial rows in the
1770  * inverse matrix correspond to the data disks that we're trying to
1771  * reconstruct. Indeed, those are the only rows we need as the others would
1772  * only be useful for reconstructing data known or assumed to be valid. For
1773  * that reason, we only build the coefficients in the rows that correspond to
1774  * targeted columns.
1775  */
1776 
1777 static void
vdev_raidz_matrix_init(raidz_row_t * rr,int n,int nmap,int * map,uint8_t ** rows)1778 vdev_raidz_matrix_init(raidz_row_t *rr, int n, int nmap, int *map,
1779     uint8_t **rows)
1780 {
1781 	int i, j;
1782 	int pow;
1783 
1784 	ASSERT(n == rr->rr_cols - rr->rr_firstdatacol);
1785 
1786 	/*
1787 	 * Fill in the missing rows of interest.
1788 	 */
1789 	for (i = 0; i < nmap; i++) {
1790 		ASSERT3S(0, <=, map[i]);
1791 		ASSERT3S(map[i], <=, 2);
1792 
1793 		pow = map[i] * n;
1794 		if (pow > 255)
1795 			pow -= 255;
1796 		ASSERT(pow <= 255);
1797 
1798 		for (j = 0; j < n; j++) {
1799 			pow -= map[i];
1800 			if (pow < 0)
1801 				pow += 255;
1802 			rows[i][j] = vdev_raidz_pow2[pow];
1803 		}
1804 	}
1805 }
1806 
1807 static void
vdev_raidz_matrix_invert(raidz_row_t * rr,int n,int nmissing,int * missing,uint8_t ** rows,uint8_t ** invrows,const uint8_t * used)1808 vdev_raidz_matrix_invert(raidz_row_t *rr, int n, int nmissing, int *missing,
1809     uint8_t **rows, uint8_t **invrows, const uint8_t *used)
1810 {
1811 	int i, j, ii, jj;
1812 	uint8_t log;
1813 
1814 	/*
1815 	 * Assert that the first nmissing entries from the array of used
1816 	 * columns correspond to parity columns and that subsequent entries
1817 	 * correspond to data columns.
1818 	 */
1819 	for (i = 0; i < nmissing; i++) {
1820 		ASSERT3S(used[i], <, rr->rr_firstdatacol);
1821 	}
1822 	for (; i < n; i++) {
1823 		ASSERT3S(used[i], >=, rr->rr_firstdatacol);
1824 	}
1825 
1826 	/*
1827 	 * First initialize the storage where we'll compute the inverse rows.
1828 	 */
1829 	for (i = 0; i < nmissing; i++) {
1830 		for (j = 0; j < n; j++) {
1831 			invrows[i][j] = (i == j) ? 1 : 0;
1832 		}
1833 	}
1834 
1835 	/*
1836 	 * Subtract all trivial rows from the rows of consequence.
1837 	 */
1838 	for (i = 0; i < nmissing; i++) {
1839 		for (j = nmissing; j < n; j++) {
1840 			ASSERT3U(used[j], >=, rr->rr_firstdatacol);
1841 			jj = used[j] - rr->rr_firstdatacol;
1842 			ASSERT3S(jj, <, n);
1843 			invrows[i][j] = rows[i][jj];
1844 			rows[i][jj] = 0;
1845 		}
1846 	}
1847 
1848 	/*
1849 	 * For each of the rows of interest, we must normalize it and subtract
1850 	 * a multiple of it from the other rows.
1851 	 */
1852 	for (i = 0; i < nmissing; i++) {
1853 		for (j = 0; j < missing[i]; j++) {
1854 			ASSERT0(rows[i][j]);
1855 		}
1856 		ASSERT3U(rows[i][missing[i]], !=, 0);
1857 
1858 		/*
1859 		 * Compute the inverse of the first element and multiply each
1860 		 * element in the row by that value.
1861 		 */
1862 		log = 255 - vdev_raidz_log2[rows[i][missing[i]]];
1863 
1864 		for (j = 0; j < n; j++) {
1865 			rows[i][j] = vdev_raidz_exp2(rows[i][j], log);
1866 			invrows[i][j] = vdev_raidz_exp2(invrows[i][j], log);
1867 		}
1868 
1869 		for (ii = 0; ii < nmissing; ii++) {
1870 			if (i == ii)
1871 				continue;
1872 
1873 			ASSERT3U(rows[ii][missing[i]], !=, 0);
1874 
1875 			log = vdev_raidz_log2[rows[ii][missing[i]]];
1876 
1877 			for (j = 0; j < n; j++) {
1878 				rows[ii][j] ^=
1879 				    vdev_raidz_exp2(rows[i][j], log);
1880 				invrows[ii][j] ^=
1881 				    vdev_raidz_exp2(invrows[i][j], log);
1882 			}
1883 		}
1884 	}
1885 
1886 	/*
1887 	 * Verify that the data that is left in the rows are properly part of
1888 	 * an identity matrix.
1889 	 */
1890 	for (i = 0; i < nmissing; i++) {
1891 		for (j = 0; j < n; j++) {
1892 			if (j == missing[i]) {
1893 				ASSERT3U(rows[i][j], ==, 1);
1894 			} else {
1895 				ASSERT0(rows[i][j]);
1896 			}
1897 		}
1898 	}
1899 }
1900 
1901 static void
vdev_raidz_matrix_reconstruct(raidz_row_t * rr,int n,int nmissing,int * missing,uint8_t ** invrows,const uint8_t * used)1902 vdev_raidz_matrix_reconstruct(raidz_row_t *rr, int n, int nmissing,
1903     int *missing, uint8_t **invrows, const uint8_t *used)
1904 {
1905 	int i, j, x, cc, c;
1906 	uint8_t *src;
1907 	uint64_t ccount;
1908 	uint8_t *dst[VDEV_RAIDZ_MAXPARITY] = { NULL };
1909 	uint64_t dcount[VDEV_RAIDZ_MAXPARITY] = { 0 };
1910 	uint8_t log = 0;
1911 	uint8_t val;
1912 	int ll;
1913 	uint8_t *invlog[VDEV_RAIDZ_MAXPARITY];
1914 	uint8_t *p, *pp;
1915 	size_t psize;
1916 
1917 	psize = sizeof (invlog[0][0]) * n * nmissing;
1918 	p = kmem_alloc(psize, KM_SLEEP);
1919 
1920 	for (pp = p, i = 0; i < nmissing; i++) {
1921 		invlog[i] = pp;
1922 		pp += n;
1923 	}
1924 
1925 	for (i = 0; i < nmissing; i++) {
1926 		for (j = 0; j < n; j++) {
1927 			ASSERT3U(invrows[i][j], !=, 0);
1928 			invlog[i][j] = vdev_raidz_log2[invrows[i][j]];
1929 		}
1930 	}
1931 
1932 	for (i = 0; i < n; i++) {
1933 		c = used[i];
1934 		ASSERT3U(c, <, rr->rr_cols);
1935 
1936 		ccount = rr->rr_col[c].rc_size;
1937 		ASSERT(ccount >= rr->rr_col[missing[0]].rc_size || i > 0);
1938 		if (ccount == 0)
1939 			continue;
1940 		src = abd_to_buf(rr->rr_col[c].rc_abd);
1941 		for (j = 0; j < nmissing; j++) {
1942 			cc = missing[j] + rr->rr_firstdatacol;
1943 			ASSERT3U(cc, >=, rr->rr_firstdatacol);
1944 			ASSERT3U(cc, <, rr->rr_cols);
1945 			ASSERT3U(cc, !=, c);
1946 
1947 			dcount[j] = rr->rr_col[cc].rc_size;
1948 			if (dcount[j] != 0)
1949 				dst[j] = abd_to_buf(rr->rr_col[cc].rc_abd);
1950 		}
1951 
1952 		for (x = 0; x < ccount; x++, src++) {
1953 			if (*src != 0)
1954 				log = vdev_raidz_log2[*src];
1955 
1956 			for (cc = 0; cc < nmissing; cc++) {
1957 				if (x >= dcount[cc])
1958 					continue;
1959 
1960 				if (*src == 0) {
1961 					val = 0;
1962 				} else {
1963 					if ((ll = log + invlog[cc][i]) >= 255)
1964 						ll -= 255;
1965 					val = vdev_raidz_pow2[ll];
1966 				}
1967 
1968 				if (i == 0)
1969 					dst[cc][x] = val;
1970 				else
1971 					dst[cc][x] ^= val;
1972 			}
1973 		}
1974 	}
1975 
1976 	kmem_free(p, psize);
1977 }
1978 
1979 static void
vdev_raidz_reconstruct_general(raidz_row_t * rr,int * tgts,int ntgts)1980 vdev_raidz_reconstruct_general(raidz_row_t *rr, int *tgts, int ntgts)
1981 {
1982 	int i, c, t, tt;
1983 	unsigned int n;
1984 	unsigned int nmissing_rows;
1985 	int missing_rows[VDEV_RAIDZ_MAXPARITY];
1986 	int parity_map[VDEV_RAIDZ_MAXPARITY];
1987 	uint8_t *p, *pp;
1988 	size_t psize;
1989 	uint8_t *rows[VDEV_RAIDZ_MAXPARITY];
1990 	uint8_t *invrows[VDEV_RAIDZ_MAXPARITY];
1991 	uint8_t *used;
1992 
1993 	abd_t **bufs = NULL;
1994 
1995 	if (zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT)
1996 		zfs_dbgmsg("reconstruct_general(rm=%px ntgts=%u)", rr, ntgts);
1997 	/*
1998 	 * Matrix reconstruction can't use scatter ABDs yet, so we allocate
1999 	 * temporary linear ABDs if any non-linear ABDs are found.
2000 	 */
2001 	for (i = rr->rr_firstdatacol; i < rr->rr_cols; i++) {
2002 		ASSERT(rr->rr_col[i].rc_abd != NULL);
2003 		if (!abd_is_linear(rr->rr_col[i].rc_abd)) {
2004 			bufs = kmem_alloc(rr->rr_cols * sizeof (abd_t *),
2005 			    KM_PUSHPAGE);
2006 
2007 			for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
2008 				raidz_col_t *col = &rr->rr_col[c];
2009 
2010 				bufs[c] = col->rc_abd;
2011 				if (bufs[c] != NULL) {
2012 					col->rc_abd = abd_alloc_linear(
2013 					    col->rc_size, B_TRUE);
2014 					abd_copy(col->rc_abd, bufs[c],
2015 					    col->rc_size);
2016 				}
2017 			}
2018 
2019 			break;
2020 		}
2021 	}
2022 
2023 	n = rr->rr_cols - rr->rr_firstdatacol;
2024 
2025 	/*
2026 	 * Figure out which data columns are missing.
2027 	 */
2028 	nmissing_rows = 0;
2029 	for (t = 0; t < ntgts; t++) {
2030 		if (tgts[t] >= rr->rr_firstdatacol) {
2031 			missing_rows[nmissing_rows++] =
2032 			    tgts[t] - rr->rr_firstdatacol;
2033 		}
2034 	}
2035 
2036 	/*
2037 	 * Figure out which parity columns to use to help generate the missing
2038 	 * data columns.
2039 	 */
2040 	for (tt = 0, c = 0, i = 0; i < nmissing_rows; c++) {
2041 		ASSERT(tt < ntgts);
2042 		ASSERT(c < rr->rr_firstdatacol);
2043 
2044 		/*
2045 		 * Skip any targeted parity columns.
2046 		 */
2047 		if (c == tgts[tt]) {
2048 			tt++;
2049 			continue;
2050 		}
2051 
2052 		parity_map[i] = c;
2053 		i++;
2054 	}
2055 
2056 	psize = (sizeof (rows[0][0]) + sizeof (invrows[0][0])) *
2057 	    nmissing_rows * n + sizeof (used[0]) * n;
2058 	p = kmem_alloc(psize, KM_SLEEP);
2059 
2060 	for (pp = p, i = 0; i < nmissing_rows; i++) {
2061 		rows[i] = pp;
2062 		pp += n;
2063 		invrows[i] = pp;
2064 		pp += n;
2065 	}
2066 	used = pp;
2067 
2068 	for (i = 0; i < nmissing_rows; i++) {
2069 		used[i] = parity_map[i];
2070 	}
2071 
2072 	for (tt = 0, c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
2073 		if (tt < nmissing_rows &&
2074 		    c == missing_rows[tt] + rr->rr_firstdatacol) {
2075 			tt++;
2076 			continue;
2077 		}
2078 
2079 		ASSERT3S(i, <, n);
2080 		used[i] = c;
2081 		i++;
2082 	}
2083 
2084 	/*
2085 	 * Initialize the interesting rows of the matrix.
2086 	 */
2087 	vdev_raidz_matrix_init(rr, n, nmissing_rows, parity_map, rows);
2088 
2089 	/*
2090 	 * Invert the matrix.
2091 	 */
2092 	vdev_raidz_matrix_invert(rr, n, nmissing_rows, missing_rows, rows,
2093 	    invrows, used);
2094 
2095 	/*
2096 	 * Reconstruct the missing data using the generated matrix.
2097 	 */
2098 	vdev_raidz_matrix_reconstruct(rr, n, nmissing_rows, missing_rows,
2099 	    invrows, used);
2100 
2101 	kmem_free(p, psize);
2102 
2103 	/*
2104 	 * copy back from temporary linear abds and free them
2105 	 */
2106 	if (bufs) {
2107 		for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
2108 			raidz_col_t *col = &rr->rr_col[c];
2109 
2110 			if (bufs[c] != NULL) {
2111 				abd_copy(bufs[c], col->rc_abd, col->rc_size);
2112 				abd_free(col->rc_abd);
2113 			}
2114 			col->rc_abd = bufs[c];
2115 		}
2116 		kmem_free(bufs, rr->rr_cols * sizeof (abd_t *));
2117 	}
2118 }
2119 
2120 static void
vdev_raidz_reconstruct_row(raidz_map_t * rm,raidz_row_t * rr,const int * t,int nt)2121 vdev_raidz_reconstruct_row(raidz_map_t *rm, raidz_row_t *rr,
2122     const int *t, int nt)
2123 {
2124 	int tgts[VDEV_RAIDZ_MAXPARITY], *dt;
2125 	int ntgts;
2126 	int i, c, ret;
2127 	int nbadparity, nbaddata;
2128 	int parity_valid[VDEV_RAIDZ_MAXPARITY];
2129 
2130 	if (zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT) {
2131 		zfs_dbgmsg("reconstruct(rm=%px nt=%u cols=%u md=%u mp=%u)",
2132 		    rr, nt, (int)rr->rr_cols, (int)rr->rr_missingdata,
2133 		    (int)rr->rr_missingparity);
2134 	}
2135 
2136 	nbadparity = rr->rr_firstdatacol;
2137 	nbaddata = rr->rr_cols - nbadparity;
2138 	ntgts = 0;
2139 	for (i = 0, c = 0; c < rr->rr_cols; c++) {
2140 		if (zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT) {
2141 			zfs_dbgmsg("reconstruct(rm=%px col=%u devid=%u "
2142 			    "offset=%llx error=%u)",
2143 			    rr, c, (int)rr->rr_col[c].rc_devidx,
2144 			    (long long)rr->rr_col[c].rc_offset,
2145 			    (int)rr->rr_col[c].rc_error);
2146 		}
2147 		if (c < rr->rr_firstdatacol)
2148 			parity_valid[c] = B_FALSE;
2149 
2150 		if (i < nt && c == t[i]) {
2151 			tgts[ntgts++] = c;
2152 			i++;
2153 		} else if (rr->rr_col[c].rc_error != 0) {
2154 			tgts[ntgts++] = c;
2155 		} else if (c >= rr->rr_firstdatacol) {
2156 			nbaddata--;
2157 		} else {
2158 			parity_valid[c] = B_TRUE;
2159 			nbadparity--;
2160 		}
2161 	}
2162 
2163 	ASSERT(ntgts >= nt);
2164 	ASSERT(nbaddata >= 0);
2165 	ASSERT(nbaddata + nbadparity == ntgts);
2166 
2167 	dt = &tgts[nbadparity];
2168 
2169 	/* Reconstruct using the new math implementation */
2170 	ret = vdev_raidz_math_reconstruct(rm, rr, parity_valid, dt, nbaddata);
2171 	if (ret != RAIDZ_ORIGINAL_IMPL)
2172 		return;
2173 
2174 	/*
2175 	 * See if we can use any of our optimized reconstruction routines.
2176 	 */
2177 	switch (nbaddata) {
2178 	case 1:
2179 		if (parity_valid[VDEV_RAIDZ_P]) {
2180 			vdev_raidz_reconstruct_p(rr, dt, 1);
2181 			return;
2182 		}
2183 
2184 		ASSERT(rr->rr_firstdatacol > 1);
2185 
2186 		if (parity_valid[VDEV_RAIDZ_Q]) {
2187 			vdev_raidz_reconstruct_q(rr, dt, 1);
2188 			return;
2189 		}
2190 
2191 		ASSERT(rr->rr_firstdatacol > 2);
2192 		break;
2193 
2194 	case 2:
2195 		ASSERT(rr->rr_firstdatacol > 1);
2196 
2197 		if (parity_valid[VDEV_RAIDZ_P] &&
2198 		    parity_valid[VDEV_RAIDZ_Q]) {
2199 			vdev_raidz_reconstruct_pq(rr, dt, 2);
2200 			return;
2201 		}
2202 
2203 		ASSERT(rr->rr_firstdatacol > 2);
2204 
2205 		break;
2206 	}
2207 
2208 	vdev_raidz_reconstruct_general(rr, tgts, ntgts);
2209 }
2210 
2211 static int
vdev_raidz_open(vdev_t * vd,uint64_t * asize,uint64_t * max_asize,uint64_t * logical_ashift,uint64_t * physical_ashift)2212 vdev_raidz_open(vdev_t *vd, uint64_t *asize, uint64_t *max_asize,
2213     uint64_t *logical_ashift, uint64_t *physical_ashift)
2214 {
2215 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2216 	uint64_t nparity = vdrz->vd_nparity;
2217 	int c;
2218 	int lasterror = 0;
2219 	int numerrors = 0;
2220 
2221 	ASSERT(nparity > 0);
2222 
2223 	if (nparity > VDEV_RAIDZ_MAXPARITY ||
2224 	    vd->vdev_children < nparity + 1) {
2225 		vd->vdev_stat.vs_aux = VDEV_AUX_BAD_LABEL;
2226 		return (SET_ERROR(EINVAL));
2227 	}
2228 
2229 	vdev_open_children(vd);
2230 
2231 	for (c = 0; c < vd->vdev_children; c++) {
2232 		vdev_t *cvd = vd->vdev_child[c];
2233 
2234 		if (cvd->vdev_open_error != 0) {
2235 			lasterror = cvd->vdev_open_error;
2236 			numerrors++;
2237 			continue;
2238 		}
2239 
2240 		*asize = MIN(*asize - 1, cvd->vdev_asize - 1) + 1;
2241 		*max_asize = MIN(*max_asize - 1, cvd->vdev_max_asize - 1) + 1;
2242 		*logical_ashift = MAX(*logical_ashift, cvd->vdev_ashift);
2243 	}
2244 	for (c = 0; c < vd->vdev_children; c++) {
2245 		vdev_t *cvd = vd->vdev_child[c];
2246 
2247 		if (cvd->vdev_open_error != 0)
2248 			continue;
2249 		*physical_ashift = vdev_best_ashift(*logical_ashift,
2250 		    *physical_ashift, cvd->vdev_physical_ashift);
2251 	}
2252 
2253 	if (vd->vdev_rz_expanding) {
2254 		*asize *= vd->vdev_children - 1;
2255 		*max_asize *= vd->vdev_children - 1;
2256 
2257 		vd->vdev_min_asize = *asize;
2258 	} else {
2259 		*asize *= vd->vdev_children;
2260 		*max_asize *= vd->vdev_children;
2261 	}
2262 
2263 	if (numerrors > nparity) {
2264 		vd->vdev_stat.vs_aux = VDEV_AUX_NO_REPLICAS;
2265 		return (lasterror);
2266 	}
2267 
2268 	return (0);
2269 }
2270 
2271 static void
vdev_raidz_close(vdev_t * vd)2272 vdev_raidz_close(vdev_t *vd)
2273 {
2274 	for (int c = 0; c < vd->vdev_children; c++) {
2275 		if (vd->vdev_child[c] != NULL)
2276 			vdev_close(vd->vdev_child[c]);
2277 	}
2278 }
2279 
2280 /*
2281  * Return the logical width to use, given the txg in which the allocation
2282  * happened.
2283  */
2284 static uint64_t
vdev_raidz_get_logical_width(vdev_raidz_t * vdrz,uint64_t txg)2285 vdev_raidz_get_logical_width(vdev_raidz_t *vdrz, uint64_t txg)
2286 {
2287 	reflow_node_t lookup = {
2288 		.re_txg = txg,
2289 	};
2290 	avl_index_t where;
2291 
2292 	uint64_t width;
2293 	mutex_enter(&vdrz->vd_expand_lock);
2294 	reflow_node_t *re = avl_find(&vdrz->vd_expand_txgs, &lookup, &where);
2295 	if (re != NULL) {
2296 		width = re->re_logical_width;
2297 	} else {
2298 		re = avl_nearest(&vdrz->vd_expand_txgs, where, AVL_BEFORE);
2299 		if (re != NULL)
2300 			width = re->re_logical_width;
2301 		else
2302 			width = vdrz->vd_original_width;
2303 	}
2304 	mutex_exit(&vdrz->vd_expand_lock);
2305 	return (width);
2306 }
2307 /*
2308  * This code converts an asize into the largest psize that can safely be written
2309  * to an allocation of that size for this vdev.
2310  *
2311  * Note that this function will not take into account the effect of gang
2312  * headers, which also modify the ASIZE of the DVAs. It is purely a reverse of
2313  * the psize_to_asize function.
2314  */
2315 static uint64_t
vdev_raidz_asize_to_psize(vdev_t * vd,uint64_t asize,uint64_t txg)2316 vdev_raidz_asize_to_psize(vdev_t *vd, uint64_t asize, uint64_t txg)
2317 {
2318 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2319 	uint64_t psize;
2320 	uint64_t ashift = vd->vdev_top->vdev_ashift;
2321 	uint64_t nparity = vdrz->vd_nparity;
2322 
2323 	uint64_t cols = vdev_raidz_get_logical_width(vdrz, txg);
2324 
2325 	ASSERT0(asize % (1 << ashift));
2326 
2327 	psize = (asize >> ashift);
2328 	/*
2329 	 * If the roundup to nparity + 1 caused us to spill into a new row, we
2330 	 * need to ignore that row entirely (since it can't store data or
2331 	 * parity).
2332 	 */
2333 	uint64_t rows = psize / cols;
2334 	psize = psize - (rows * cols) <= nparity ? rows * cols : psize;
2335 	/*  Subtract out parity sectors for each row storing data. */
2336 	psize -= nparity * DIV_ROUND_UP(psize, cols);
2337 	psize <<= ashift;
2338 
2339 	return (psize);
2340 }
2341 
2342 /*
2343  * Note: If the RAIDZ vdev has been expanded, older BP's may have allocated
2344  * more space due to the lower data-to-parity ratio.  In this case it's
2345  * important to pass in the correct txg.  Note that vdev_gang_header_asize()
2346  * relies on a constant asize for psize=SPA_GANGBLOCKSIZE=SPA_MINBLOCKSIZE,
2347  * regardless of txg.  This is assured because for a single data sector, we
2348  * allocate P+1 sectors regardless of width ("cols", which is at least P+1).
2349  */
2350 static uint64_t
vdev_raidz_psize_to_asize(vdev_t * vd,uint64_t psize,uint64_t txg)2351 vdev_raidz_psize_to_asize(vdev_t *vd, uint64_t psize, uint64_t txg)
2352 {
2353 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2354 	uint64_t asize;
2355 	uint64_t ashift = vd->vdev_top->vdev_ashift;
2356 	uint64_t nparity = vdrz->vd_nparity;
2357 
2358 	uint64_t cols = vdev_raidz_get_logical_width(vdrz, txg);
2359 
2360 	asize = ((psize - 1) >> ashift) + 1;
2361 	asize += nparity * ((asize + cols - nparity - 1) / (cols - nparity));
2362 	asize = roundup(asize, nparity + 1) << ashift;
2363 
2364 #ifdef ZFS_DEBUG
2365 	uint64_t asize_new = ((psize - 1) >> ashift) + 1;
2366 	uint64_t ncols_new = vdrz->vd_physical_width;
2367 	asize_new += nparity * ((asize_new + ncols_new - nparity - 1) /
2368 	    (ncols_new - nparity));
2369 	asize_new = roundup(asize_new, nparity + 1) << ashift;
2370 	VERIFY3U(asize_new, <=, asize);
2371 #endif
2372 
2373 	return (asize);
2374 }
2375 
2376 /*
2377  * The allocatable space for a raidz vdev is N * sizeof(smallest child)
2378  * so each child must provide at least 1/Nth of its asize.
2379  */
2380 static uint64_t
vdev_raidz_min_asize(vdev_t * vd)2381 vdev_raidz_min_asize(vdev_t *vd)
2382 {
2383 	return ((vd->vdev_min_asize + vd->vdev_children - 1) /
2384 	    vd->vdev_children);
2385 }
2386 
2387 /*
2388  * return B_TRUE if a read should be skipped due to being too slow.
2389  *
2390  * In vdev_child_slow_outlier() it looks for outliers based on disk
2391  * latency from the most recent child reads.  Here we're checking if,
2392  * over time, a disk has has been an outlier too many times and is
2393  * now in a sit out period.
2394  */
2395 boolean_t
vdev_sit_out_reads(vdev_t * vd,zio_flag_t io_flags)2396 vdev_sit_out_reads(vdev_t *vd, zio_flag_t io_flags)
2397 {
2398 	if (vdev_read_sit_out_secs == 0)
2399 		return (B_FALSE);
2400 
2401 	/* Avoid skipping a data column read when scrubbing */
2402 	if (io_flags & ZIO_FLAG_SCRUB)
2403 		return (B_FALSE);
2404 
2405 	if (!vd->vdev_ops->vdev_op_leaf) {
2406 		boolean_t sitting = B_FALSE;
2407 		for (int c = 0; c < vd->vdev_children; c++) {
2408 			sitting |= vdev_sit_out_reads(vd->vdev_child[c],
2409 			    io_flags);
2410 		}
2411 		return (sitting);
2412 	}
2413 
2414 	if (vd->vdev_read_sit_out_expire >= gethrestime_sec())
2415 		return (B_TRUE);
2416 
2417 	vd->vdev_read_sit_out_expire = 0;
2418 
2419 	return (B_FALSE);
2420 }
2421 
2422 void
vdev_raidz_child_done(zio_t * zio)2423 vdev_raidz_child_done(zio_t *zio)
2424 {
2425 	raidz_col_t *rc = zio->io_private;
2426 
2427 	ASSERT3P(rc->rc_abd, !=, NULL);
2428 	rc->rc_error = zio->io_error;
2429 	rc->rc_tried = 1;
2430 	rc->rc_skipped = 0;
2431 }
2432 
2433 static void
vdev_raidz_shadow_child_done(zio_t * zio)2434 vdev_raidz_shadow_child_done(zio_t *zio)
2435 {
2436 	raidz_col_t *rc = zio->io_private;
2437 
2438 	rc->rc_shadow_error = zio->io_error;
2439 }
2440 
2441 static void
vdev_raidz_io_verify(zio_t * zio,raidz_map_t * rm,raidz_row_t * rr,int col)2442 vdev_raidz_io_verify(zio_t *zio, raidz_map_t *rm, raidz_row_t *rr, int col)
2443 {
2444 	(void) rm;
2445 #ifdef ZFS_DEBUG
2446 	zfs_range_seg64_t logical_rs, physical_rs, remain_rs;
2447 	logical_rs.rs_start = rr->rr_offset;
2448 	logical_rs.rs_end = logical_rs.rs_start +
2449 	    vdev_raidz_psize_to_asize(zio->io_vd, rr->rr_size,
2450 	    BP_GET_PHYSICAL_BIRTH(zio->io_bp));
2451 
2452 	raidz_col_t *rc = &rr->rr_col[col];
2453 	vdev_t *cvd = zio->io_vd->vdev_child[rc->rc_devidx];
2454 
2455 	vdev_xlate(cvd, &logical_rs, &physical_rs, &remain_rs);
2456 	ASSERT(vdev_xlate_is_empty(&remain_rs));
2457 	if (vdev_xlate_is_empty(&physical_rs)) {
2458 		/*
2459 		 * If we are in the middle of expansion, the
2460 		 * physical->logical mapping is changing so vdev_xlate()
2461 		 * can't give us a reliable answer.
2462 		 */
2463 		return;
2464 	}
2465 	ASSERT3U(rc->rc_offset, ==, physical_rs.rs_start);
2466 	ASSERT3U(rc->rc_offset, <, physical_rs.rs_end);
2467 	/*
2468 	 * It would be nice to assert that rs_end is equal
2469 	 * to rc_offset + rc_size but there might be an
2470 	 * optional I/O at the end that is not accounted in
2471 	 * rc_size.
2472 	 */
2473 	if (physical_rs.rs_end > rc->rc_offset + rc->rc_size) {
2474 		ASSERT3U(physical_rs.rs_end, ==, rc->rc_offset +
2475 		    rc->rc_size + (1 << zio->io_vd->vdev_top->vdev_ashift));
2476 	} else {
2477 		ASSERT3U(physical_rs.rs_end, ==, rc->rc_offset + rc->rc_size);
2478 	}
2479 #endif
2480 }
2481 
2482 static void
vdev_raidz_io_start_write(zio_t * zio,raidz_row_t * rr)2483 vdev_raidz_io_start_write(zio_t *zio, raidz_row_t *rr)
2484 {
2485 	vdev_t *vd = zio->io_vd;
2486 	raidz_map_t *rm = zio->io_vsd;
2487 
2488 	vdev_raidz_generate_parity_row(rm, rr);
2489 
2490 	for (int c = 0; c < rr->rr_scols; c++) {
2491 		raidz_col_t *rc = &rr->rr_col[c];
2492 		vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
2493 
2494 		/* Verify physical to logical translation */
2495 		vdev_raidz_io_verify(zio, rm, rr, c);
2496 
2497 		if (rc->rc_size == 0)
2498 			continue;
2499 
2500 		ASSERT3U(rc->rc_offset + rc->rc_size, <,
2501 		    cvd->vdev_psize - VDEV_LABEL_END_SIZE);
2502 
2503 		ASSERT3P(rc->rc_abd, !=, NULL);
2504 		zio_nowait(zio_vdev_child_io(zio, NULL, cvd,
2505 		    rc->rc_offset, rc->rc_abd,
2506 		    abd_get_size(rc->rc_abd), zio->io_type,
2507 		    zio->io_priority, 0, vdev_raidz_child_done, rc));
2508 
2509 		if (rc->rc_shadow_devidx != INT_MAX) {
2510 			vdev_t *cvd2 = vd->vdev_child[rc->rc_shadow_devidx];
2511 
2512 			ASSERT3U(
2513 			    rc->rc_shadow_offset + abd_get_size(rc->rc_abd), <,
2514 			    cvd2->vdev_psize - VDEV_LABEL_END_SIZE);
2515 
2516 			zio_nowait(zio_vdev_child_io(zio, NULL, cvd2,
2517 			    rc->rc_shadow_offset, rc->rc_abd,
2518 			    abd_get_size(rc->rc_abd),
2519 			    zio->io_type, zio->io_priority, 0,
2520 			    vdev_raidz_shadow_child_done, rc));
2521 		}
2522 	}
2523 }
2524 
2525 /*
2526  * Generate optional I/Os for skip sectors to improve aggregation contiguity.
2527  * This only works for vdev_raidz_map_alloc() (not _expanded()).
2528  */
2529 static void
raidz_start_skip_writes(zio_t * zio)2530 raidz_start_skip_writes(zio_t *zio)
2531 {
2532 	vdev_t *vd = zio->io_vd;
2533 	uint64_t ashift = vd->vdev_top->vdev_ashift;
2534 	raidz_map_t *rm = zio->io_vsd;
2535 	ASSERT3U(rm->rm_nrows, ==, 1);
2536 	raidz_row_t *rr = rm->rm_row[0];
2537 	for (int c = 0; c < rr->rr_scols; c++) {
2538 		raidz_col_t *rc = &rr->rr_col[c];
2539 		vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
2540 		if (rc->rc_size != 0)
2541 			continue;
2542 		ASSERT0P(rc->rc_abd);
2543 
2544 		ASSERT3U(rc->rc_offset, <,
2545 		    cvd->vdev_psize - VDEV_LABEL_END_SIZE);
2546 
2547 		zio_nowait(zio_vdev_child_io(zio, NULL, cvd, rc->rc_offset,
2548 		    NULL, 1ULL << ashift, zio->io_type, zio->io_priority,
2549 		    ZIO_FLAG_NODATA | ZIO_FLAG_OPTIONAL, NULL, NULL));
2550 	}
2551 }
2552 
2553 static void
vdev_raidz_io_start_read_row(zio_t * zio,raidz_row_t * rr,boolean_t forceparity)2554 vdev_raidz_io_start_read_row(zio_t *zio, raidz_row_t *rr, boolean_t forceparity)
2555 {
2556 	vdev_t *vd = zio->io_vd;
2557 
2558 	/*
2559 	 * Iterate over the columns in reverse order so that we hit the parity
2560 	 * last -- any errors along the way will force us to read the parity.
2561 	 */
2562 	for (int c = rr->rr_cols - 1; c >= 0; c--) {
2563 		raidz_col_t *rc = &rr->rr_col[c];
2564 		if (rc->rc_size == 0)
2565 			continue;
2566 		vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
2567 		if (!vdev_readable(cvd)) {
2568 			if (c >= rr->rr_firstdatacol)
2569 				rr->rr_missingdata++;
2570 			else
2571 				rr->rr_missingparity++;
2572 			rc->rc_error = SET_ERROR(ENXIO);
2573 			rc->rc_tried = 1;	/* don't even try */
2574 			rc->rc_skipped = 1;
2575 			continue;
2576 		}
2577 		if (vdev_dtl_contains(cvd, DTL_MISSING, zio->io_txg, 1)) {
2578 			if (c >= rr->rr_firstdatacol)
2579 				rr->rr_missingdata++;
2580 			else
2581 				rr->rr_missingparity++;
2582 			rc->rc_error = SET_ERROR(ESTALE);
2583 			rc->rc_skipped = 1;
2584 			continue;
2585 		}
2586 
2587 		if (vdev_sit_out_reads(cvd, zio->io_flags)) {
2588 			rr->rr_outlier_cnt++;
2589 			ASSERT0(rc->rc_latency_outlier);
2590 			rc->rc_latency_outlier = 1;
2591 		}
2592 	}
2593 
2594 	/*
2595 	 * When the row contains a latency outlier and sufficient parity
2596 	 * exists to reconstruct the column data, then skip reading the
2597 	 * known slow child vdev as a performance optimization.
2598 	 */
2599 	if (rr->rr_outlier_cnt > 0 &&
2600 	    (rr->rr_firstdatacol - rr->rr_missingparity) >=
2601 	    (rr->rr_missingdata + 1)) {
2602 
2603 		for (int c = rr->rr_cols - 1; c >= 0; c--) {
2604 			raidz_col_t *rc = &rr->rr_col[c];
2605 
2606 			if (rc->rc_error == 0 && rc->rc_latency_outlier) {
2607 				if (c >= rr->rr_firstdatacol)
2608 					rr->rr_missingdata++;
2609 				else
2610 					rr->rr_missingparity++;
2611 				rc->rc_error = SET_ERROR(EAGAIN);
2612 				rc->rc_skipped = 1;
2613 				break;
2614 			}
2615 		}
2616 	}
2617 
2618 	for (int c = rr->rr_cols - 1; c >= 0; c--) {
2619 		raidz_col_t *rc = &rr->rr_col[c];
2620 		vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
2621 
2622 		if (rc->rc_error || rc->rc_size == 0)
2623 			continue;
2624 
2625 		if (forceparity ||
2626 		    c >= rr->rr_firstdatacol || rr->rr_missingdata > 0 ||
2627 		    (zio->io_flags & (ZIO_FLAG_SCRUB | ZIO_FLAG_RESILVER))) {
2628 			zio_nowait(zio_vdev_child_io(zio, NULL, cvd,
2629 			    rc->rc_offset, rc->rc_abd, rc->rc_size,
2630 			    zio->io_type, zio->io_priority, 0,
2631 			    vdev_raidz_child_done, rc));
2632 		}
2633 	}
2634 }
2635 
2636 static void
vdev_raidz_io_start_read_phys_cols(zio_t * zio,raidz_map_t * rm)2637 vdev_raidz_io_start_read_phys_cols(zio_t *zio, raidz_map_t *rm)
2638 {
2639 	vdev_t *vd = zio->io_vd;
2640 
2641 	for (int i = 0; i < rm->rm_nphys_cols; i++) {
2642 		raidz_col_t *prc = &rm->rm_phys_col[i];
2643 		if (prc->rc_size == 0)
2644 			continue;
2645 
2646 		ASSERT3U(prc->rc_devidx, ==, i);
2647 		vdev_t *cvd = vd->vdev_child[i];
2648 
2649 		if (!vdev_readable(cvd)) {
2650 			prc->rc_error = SET_ERROR(ENXIO);
2651 			prc->rc_tried = 1;	/* don't even try */
2652 			prc->rc_skipped = 1;
2653 			continue;
2654 		}
2655 		if (vdev_dtl_contains(cvd, DTL_MISSING, zio->io_txg, 1)) {
2656 			prc->rc_error = SET_ERROR(ESTALE);
2657 			prc->rc_skipped = 1;
2658 			continue;
2659 		}
2660 		zio_nowait(zio_vdev_child_io(zio, NULL, cvd,
2661 		    prc->rc_offset, prc->rc_abd, prc->rc_size,
2662 		    zio->io_type, zio->io_priority, 0,
2663 		    vdev_raidz_child_done, prc));
2664 	}
2665 }
2666 
2667 static void
vdev_raidz_io_start_read(zio_t * zio,raidz_map_t * rm)2668 vdev_raidz_io_start_read(zio_t *zio, raidz_map_t *rm)
2669 {
2670 	/*
2671 	 * If there are multiple rows, we will be hitting
2672 	 * all disks, so go ahead and read the parity so
2673 	 * that we are reading in decent size chunks.
2674 	 */
2675 	boolean_t forceparity = rm->rm_nrows > 1;
2676 
2677 	if (rm->rm_phys_col) {
2678 		vdev_raidz_io_start_read_phys_cols(zio, rm);
2679 	} else {
2680 		for (int i = 0; i < rm->rm_nrows; i++) {
2681 			raidz_row_t *rr = rm->rm_row[i];
2682 			vdev_raidz_io_start_read_row(zio, rr, forceparity);
2683 		}
2684 	}
2685 }
2686 
2687 /*
2688  * Start an IO operation on a RAIDZ VDev
2689  *
2690  * Outline:
2691  * - For write operations:
2692  *   1. Generate the parity data
2693  *   2. Create child zio write operations to each column's vdev, for both
2694  *      data and parity.
2695  *   3. If the column skips any sectors for padding, create optional dummy
2696  *      write zio children for those areas to improve aggregation continuity.
2697  * - For read operations:
2698  *   1. Create child zio read operations to each data column's vdev to read
2699  *      the range of data required for zio.
2700  *   2. If this is a scrub or resilver operation, or if any of the data
2701  *      vdevs have had errors, then create zio read operations to the parity
2702  *      columns' VDevs as well.
2703  */
2704 static void
vdev_raidz_io_start(zio_t * zio)2705 vdev_raidz_io_start(zio_t *zio)
2706 {
2707 	vdev_t *vd = zio->io_vd;
2708 	vdev_t *tvd = vd->vdev_top;
2709 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2710 	raidz_map_t *rm;
2711 
2712 	uint64_t logical_width = vdev_raidz_get_logical_width(vdrz,
2713 	    BP_GET_PHYSICAL_BIRTH(zio->io_bp));
2714 	if (logical_width != vdrz->vd_physical_width) {
2715 		zfs_locked_range_t *lr = NULL;
2716 		uint64_t synced_offset = UINT64_MAX;
2717 		uint64_t next_offset = UINT64_MAX;
2718 		boolean_t use_scratch = B_FALSE;
2719 		/*
2720 		 * Note: when the expansion is completing, we set
2721 		 * vre_state=DSS_FINISHED (in raidz_reflow_complete_sync())
2722 		 * in a later txg than when we last update spa_ubsync's state
2723 		 * (see the end of spa_raidz_expand_thread()).  Therefore we
2724 		 * may see vre_state!=SCANNING before
2725 		 * VDEV_TOP_ZAP_RAIDZ_EXPAND_STATE=DSS_FINISHED is reflected
2726 		 * on disk, but the copying progress has been synced to disk
2727 		 * (and reflected in spa_ubsync).  In this case it's fine to
2728 		 * treat the expansion as completed, since if we crash there's
2729 		 * no additional copying to do.
2730 		 */
2731 		if (vdrz->vn_vre.vre_state == DSS_SCANNING) {
2732 			ASSERT3P(vd->vdev_spa->spa_raidz_expand, ==,
2733 			    &vdrz->vn_vre);
2734 			lr = zfs_rangelock_enter(&vdrz->vn_vre.vre_rangelock,
2735 			    zio->io_offset, zio->io_size, RL_READER);
2736 			use_scratch =
2737 			    (RRSS_GET_STATE(&vd->vdev_spa->spa_ubsync) ==
2738 			    RRSS_SCRATCH_VALID);
2739 			synced_offset =
2740 			    RRSS_GET_OFFSET(&vd->vdev_spa->spa_ubsync);
2741 			next_offset = vdrz->vn_vre.vre_offset;
2742 			/*
2743 			 * If we haven't resumed expanding since importing the
2744 			 * pool, vre_offset won't have been set yet.  In
2745 			 * this case the next offset to be copied is the same
2746 			 * as what was synced.
2747 			 */
2748 			if (next_offset == UINT64_MAX) {
2749 				next_offset = synced_offset;
2750 			}
2751 		}
2752 
2753 		rm = vdev_raidz_map_alloc_expanded(zio,
2754 		    tvd->vdev_ashift, vdrz->vd_physical_width,
2755 		    logical_width, vdrz->vd_nparity,
2756 		    synced_offset, next_offset, use_scratch);
2757 		rm->rm_lr = lr;
2758 	} else {
2759 		rm = vdev_raidz_map_alloc(zio,
2760 		    tvd->vdev_ashift, logical_width, vdrz->vd_nparity);
2761 	}
2762 	rm->rm_original_width = vdrz->vd_original_width;
2763 
2764 	zio->io_vsd = rm;
2765 	zio->io_vsd_ops = &vdev_raidz_vsd_ops;
2766 	if (zio->io_type == ZIO_TYPE_WRITE) {
2767 		for (int i = 0; i < rm->rm_nrows; i++) {
2768 			vdev_raidz_io_start_write(zio, rm->rm_row[i]);
2769 		}
2770 
2771 		if (logical_width == vdrz->vd_physical_width) {
2772 			raidz_start_skip_writes(zio);
2773 		}
2774 	} else {
2775 		ASSERT(zio->io_type == ZIO_TYPE_READ);
2776 		vdev_raidz_io_start_read(zio, rm);
2777 	}
2778 
2779 	zio_execute(zio);
2780 }
2781 
2782 /*
2783  * Report a checksum error for a child of a RAID-Z device.
2784  */
2785 void
vdev_raidz_checksum_error(zio_t * zio,raidz_col_t * rc,abd_t * bad_data)2786 vdev_raidz_checksum_error(zio_t *zio, raidz_col_t *rc, abd_t *bad_data)
2787 {
2788 	vdev_t *vd = zio->io_vd->vdev_child[rc->rc_devidx];
2789 
2790 	if (!(zio->io_flags & ZIO_FLAG_SPECULATIVE) &&
2791 	    zio->io_priority != ZIO_PRIORITY_REBUILD) {
2792 		zio_bad_cksum_t zbc;
2793 		raidz_map_t *rm = zio->io_vsd;
2794 
2795 		zbc.zbc_has_cksum = 0;
2796 		zbc.zbc_injected = rm->rm_ecksuminjected;
2797 
2798 		mutex_enter(&vd->vdev_stat_lock);
2799 		vd->vdev_stat.vs_checksum_errors++;
2800 		mutex_exit(&vd->vdev_stat_lock);
2801 		(void) zfs_ereport_post_checksum(zio->io_spa, vd,
2802 		    &zio->io_bookmark, zio, rc->rc_offset, rc->rc_size,
2803 		    rc->rc_abd, bad_data, &zbc);
2804 	}
2805 }
2806 
2807 /*
2808  * We keep track of whether or not there were any injected errors, so that
2809  * any ereports we generate can note it.
2810  */
2811 static int
raidz_checksum_verify(zio_t * zio)2812 raidz_checksum_verify(zio_t *zio)
2813 {
2814 	zio_bad_cksum_t zbc = {0};
2815 	raidz_map_t *rm = zio->io_vsd;
2816 
2817 	int ret = zio_checksum_error(zio, &zbc);
2818 	/*
2819 	 * Any Direct I/O read that has a checksum error must be treated as
2820 	 * suspicious as the contents of the buffer could be getting
2821 	 * manipulated while the I/O is taking place. The checksum verify error
2822 	 * will be reported to the top-level RAIDZ VDEV.
2823 	 */
2824 	if (zio->io_flags & ZIO_FLAG_DIO_READ && ret == ECKSUM) {
2825 		zio->io_error = ret;
2826 		zio->io_post |= ZIO_POST_DIO_CHKSUM_ERR;
2827 		zio_dio_chksum_verify_error_report(zio);
2828 		zio_checksum_verified(zio);
2829 		return (0);
2830 	}
2831 
2832 	if (ret != 0 && zbc.zbc_injected != 0)
2833 		rm->rm_ecksuminjected = 1;
2834 
2835 	return (ret);
2836 }
2837 
2838 /*
2839  * Generate the parity from the data columns. If we tried and were able to
2840  * read the parity without error, verify that the generated parity matches the
2841  * data we read. If it doesn't, we fire off a checksum error. Return the
2842  * number of such failures.
2843  */
2844 static int
raidz_parity_verify(zio_t * zio,raidz_row_t * rr)2845 raidz_parity_verify(zio_t *zio, raidz_row_t *rr)
2846 {
2847 	abd_t *orig[VDEV_RAIDZ_MAXPARITY];
2848 	int c, ret = 0;
2849 	raidz_map_t *rm = zio->io_vsd;
2850 	raidz_col_t *rc;
2851 
2852 	blkptr_t *bp = zio->io_bp;
2853 	enum zio_checksum checksum = (bp == NULL ? zio->io_prop.zp_checksum :
2854 	    (BP_IS_GANG(bp) ? ZIO_CHECKSUM_GANG_HEADER : BP_GET_CHECKSUM(bp)));
2855 
2856 	if (checksum == ZIO_CHECKSUM_NOPARITY)
2857 		return (ret);
2858 
2859 	for (c = 0; c < rr->rr_firstdatacol; c++) {
2860 		rc = &rr->rr_col[c];
2861 		if (!rc->rc_tried || rc->rc_error != 0)
2862 			continue;
2863 
2864 		orig[c] = rc->rc_abd;
2865 		ASSERT3U(abd_get_size(rc->rc_abd), ==, rc->rc_size);
2866 		rc->rc_abd = abd_alloc_linear(rc->rc_size, B_FALSE);
2867 	}
2868 
2869 	/*
2870 	 * Verify any empty sectors are zero filled to ensure the parity
2871 	 * is calculated correctly even if these non-data sectors are damaged.
2872 	 */
2873 	if (rr->rr_nempty && rr->rr_abd_empty != NULL)
2874 		ret += vdev_draid_map_verify_empty(zio, rr);
2875 
2876 	/*
2877 	 * Regenerates parity even for !tried||rc_error!=0 columns.  This
2878 	 * isn't harmful but it does have the side effect of fixing stuff
2879 	 * we didn't realize was necessary (i.e. even if we return 0).
2880 	 */
2881 	vdev_raidz_generate_parity_row(rm, rr);
2882 
2883 	for (c = 0; c < rr->rr_firstdatacol; c++) {
2884 		rc = &rr->rr_col[c];
2885 
2886 		if (!rc->rc_tried || rc->rc_error != 0)
2887 			continue;
2888 
2889 		if (abd_cmp(orig[c], rc->rc_abd) != 0) {
2890 			vdev_raidz_checksum_error(zio, rc, orig[c]);
2891 			rc->rc_error = SET_ERROR(ECKSUM);
2892 			ret++;
2893 		}
2894 		abd_free(orig[c]);
2895 	}
2896 
2897 	return (ret);
2898 }
2899 
2900 static int
vdev_raidz_worst_error(raidz_row_t * rr)2901 vdev_raidz_worst_error(raidz_row_t *rr)
2902 {
2903 	int error = 0;
2904 
2905 	for (int c = 0; c < rr->rr_cols; c++) {
2906 		error = zio_worst_error(error, rr->rr_col[c].rc_error);
2907 		error = zio_worst_error(error, rr->rr_col[c].rc_shadow_error);
2908 	}
2909 
2910 	return (error);
2911 }
2912 
2913 /*
2914  * Find the median value from a set of n values
2915  */
2916 static uint64_t
latency_median_value(const uint64_t * data,size_t n)2917 latency_median_value(const uint64_t *data, size_t n)
2918 {
2919 	uint64_t m;
2920 
2921 	if (n % 2 == 0)
2922 		m = (data[(n >> 1) - 1] + data[n >> 1]) >> 1;
2923 	else
2924 		m = data[((n + 1) >> 1) - 1];
2925 
2926 	return (m);
2927 }
2928 
2929 /*
2930  * Calculate the outlier fence from a set of n latency values
2931  *
2932  * fence = Q3 + vdev_raidz_outlier_insensitivity x (Q3 - Q1)
2933  */
2934 static uint64_t
latency_quartiles_fence(const uint64_t * data,size_t n,uint64_t * iqr)2935 latency_quartiles_fence(const uint64_t *data, size_t n, uint64_t *iqr)
2936 {
2937 	uint64_t q1 = latency_median_value(&data[0], n >> 1);
2938 	uint64_t q3 = latency_median_value(&data[(n + 1) >> 1], n >> 1);
2939 
2940 	/*
2941 	 * To avoid detecting false positive outliers when N is small and
2942 	 * and the latencies values are very close, make sure the IQR
2943 	 * is at least 25% larger than Q1.
2944 	 */
2945 	*iqr = MAX(q3 - q1, q1 / 4);
2946 
2947 	return (q3 + (*iqr * vdev_raidz_outlier_insensitivity));
2948 }
2949 #define	LAT_CHILDREN_MIN	5
2950 #define	LAT_OUTLIER_LIMIT	20
2951 
2952 static int
latency_compare(const void * arg1,const void * arg2)2953 latency_compare(const void *arg1, const void *arg2)
2954 {
2955 	const uint64_t *l1 = (uint64_t *)arg1;
2956 	const uint64_t *l2 = (uint64_t *)arg2;
2957 
2958 	return (TREE_CMP(*l1, *l2));
2959 }
2960 
2961 void
vdev_raidz_sit_child(vdev_t * svd,uint64_t secs)2962 vdev_raidz_sit_child(vdev_t *svd, uint64_t secs)
2963 {
2964 	for (int c = 0; c < svd->vdev_children; c++)
2965 		vdev_raidz_sit_child(svd->vdev_child[c], secs);
2966 
2967 	if (!svd->vdev_ops->vdev_op_leaf)
2968 		return;
2969 
2970 	/* Begin a sit out period for this slow drive */
2971 	svd->vdev_read_sit_out_expire = gethrestime_sec() +
2972 	    secs;
2973 
2974 	/* Count each slow io period */
2975 	mutex_enter(&svd->vdev_stat_lock);
2976 	svd->vdev_stat.vs_slow_ios++;
2977 	mutex_exit(&svd->vdev_stat_lock);
2978 }
2979 
2980 void
vdev_raidz_unsit_child(vdev_t * vd)2981 vdev_raidz_unsit_child(vdev_t *vd)
2982 {
2983 	for (int c = 0; c < vd->vdev_children; c++)
2984 		vdev_raidz_unsit_child(vd->vdev_child[c]);
2985 
2986 	if (!vd->vdev_ops->vdev_op_leaf)
2987 		return;
2988 
2989 	vd->vdev_read_sit_out_expire = 0;
2990 }
2991 
2992 /*
2993  * Check for any latency outlier from latest set of child reads.
2994  *
2995  * Uses a Tukey's fence, with K = 50, for detecting extreme outliers. This
2996  * rule defines extreme outliers as data points outside the fence of the
2997  * third quartile plus fifty times the Interquartile Range (IQR). This range
2998  * is the distance between the first and third quartile.
2999  *
3000  * Fifty is an extremely large value for Tukey's fence, but the outliers we're
3001  * attempting to detect here are orders of magnitude times larger than the
3002  * median. This large value should capture any truly fault disk quickly,
3003  * without causing spurious sit-outs.
3004  *
3005  * To further avoid spurious sit-outs, vdevs must be detected multiple times
3006  * as an outlier before they are sat, and outlier counts will gradually decay.
3007  * Every nchildren times we have detected an outlier, we subtract 2 from the
3008  * outlier count of all children. If detected outliers are close to uniformly
3009  * distributed, this will result in the outlier count remaining close to 0
3010  * (in expectation; over long enough time-scales, spurious sit-outs are still
3011  * possible).
3012  */
3013 static void
vdev_child_slow_outlier(zio_t * zio)3014 vdev_child_slow_outlier(zio_t *zio)
3015 {
3016 	vdev_t *vd = zio->io_vd;
3017 	if (!vd->vdev_autosit || vdev_read_sit_out_secs == 0 ||
3018 	    vd->vdev_children < LAT_CHILDREN_MIN)
3019 		return;
3020 
3021 	hrtime_t now = getlrtime();
3022 	uint64_t last = atomic_load_64(&vd->vdev_last_latency_check);
3023 
3024 	if ((now - last) < MSEC2NSEC(vdev_raidz_outlier_check_interval_ms))
3025 		return;
3026 
3027 	/* Allow a single winner when there are racing callers. */
3028 	if (atomic_cas_64(&vd->vdev_last_latency_check, last, now) != last)
3029 		return;
3030 
3031 	int children = vd->vdev_children;
3032 	uint64_t *lat_data = kmem_alloc(sizeof (uint64_t) * children, KM_SLEEP);
3033 
3034 	for (int c = 0; c < children; c++) {
3035 		vdev_t *cvd = vd->vdev_child[c];
3036 		if (cvd->vdev_prev_histo == NULL) {
3037 			mutex_enter(&cvd->vdev_stat_lock);
3038 			size_t size =
3039 			    sizeof (cvd->vdev_stat_ex.vsx_disk_histo[0]);
3040 			cvd->vdev_prev_histo = kmem_zalloc(size, KM_SLEEP);
3041 			memcpy(cvd->vdev_prev_histo,
3042 			    cvd->vdev_stat_ex.vsx_disk_histo[ZIO_TYPE_READ],
3043 			    size);
3044 			mutex_exit(&cvd->vdev_stat_lock);
3045 		}
3046 	}
3047 	uint64_t max = 0;
3048 	vdev_t *svd = NULL;
3049 	uint_t sitouts = 0;
3050 	boolean_t skip = B_FALSE, svd_sitting = B_FALSE;
3051 	for (int c = 0; c < children; c++) {
3052 		vdev_t *cvd = vd->vdev_child[c];
3053 		boolean_t sitting = vdev_sit_out_reads(cvd, 0) ||
3054 		    cvd->vdev_state != VDEV_STATE_HEALTHY;
3055 
3056 		/* We can't sit out more disks than we have parity */
3057 		if (sitting && ++sitouts >= vdev_get_nparity(vd))
3058 			skip = B_TRUE;
3059 
3060 		mutex_enter(&cvd->vdev_stat_lock);
3061 
3062 		uint64_t *prev_histo = cvd->vdev_prev_histo;
3063 		uint64_t *histo =
3064 		    cvd->vdev_stat_ex.vsx_disk_histo[ZIO_TYPE_READ];
3065 		if (skip) {
3066 			size_t size =
3067 			    sizeof (cvd->vdev_stat_ex.vsx_disk_histo[0]);
3068 			memcpy(prev_histo, histo, size);
3069 			mutex_exit(&cvd->vdev_stat_lock);
3070 			continue;
3071 		}
3072 		uint64_t count = 0;
3073 		lat_data[c] = 0;
3074 		for (int i = 0; i < VDEV_L_HISTO_BUCKETS; i++) {
3075 			uint64_t this_count = histo[i] - prev_histo[i];
3076 			lat_data[c] += (1ULL << i) * this_count;
3077 			count += this_count;
3078 		}
3079 		size_t size = sizeof (cvd->vdev_stat_ex.vsx_disk_histo[0]);
3080 		memcpy(prev_histo, histo, size);
3081 		mutex_exit(&cvd->vdev_stat_lock);
3082 		lat_data[c] /= MAX(1, count);
3083 
3084 		/* Wait until all disks have been read from */
3085 		if (lat_data[c] == 0 && !sitting) {
3086 			skip = B_TRUE;
3087 			continue;
3088 		}
3089 
3090 		/* Keep track of the vdev with largest value */
3091 		if (lat_data[c] > max) {
3092 			max = lat_data[c];
3093 			svd = cvd;
3094 			svd_sitting = sitting;
3095 		}
3096 	}
3097 
3098 	if (skip) {
3099 		kmem_free(lat_data, sizeof (uint64_t) * children);
3100 		return;
3101 	}
3102 
3103 	qsort((void *)lat_data, children, sizeof (uint64_t), latency_compare);
3104 
3105 	uint64_t iqr;
3106 	uint64_t fence = latency_quartiles_fence(lat_data, children, &iqr);
3107 
3108 	ASSERT3U(lat_data[children - 1], ==, max);
3109 	if (max > fence && !svd_sitting) {
3110 		ASSERT3U(iqr, >, 0);
3111 		uint64_t incr = MAX(1, MIN((max - fence) / iqr,
3112 		    LAT_OUTLIER_LIMIT / 4));
3113 		vd->vdev_outlier_count += incr;
3114 		if (vd->vdev_outlier_count >= children) {
3115 			for (int c = 0; c < children; c++) {
3116 				vdev_t *cvd = vd->vdev_child[c];
3117 				cvd->vdev_outlier_count -= 2;
3118 				cvd->vdev_outlier_count = MAX(0,
3119 				    cvd->vdev_outlier_count);
3120 			}
3121 			vd->vdev_outlier_count = 0;
3122 		}
3123 		/*
3124 		 * Keep track of how many times this child has had
3125 		 * an outlier read. A disk that persitently has a
3126 		 * higher than peers outlier count will be considered
3127 		 * a slow disk.
3128 		 */
3129 		svd->vdev_outlier_count += incr;
3130 		if (svd->vdev_outlier_count > LAT_OUTLIER_LIMIT) {
3131 			ASSERT0(svd->vdev_read_sit_out_expire);
3132 			vdev_raidz_sit_child(svd, vdev_read_sit_out_secs);
3133 			(void) zfs_ereport_post(FM_EREPORT_ZFS_SITOUT,
3134 			    zio->io_spa, svd, NULL, NULL, 0);
3135 			vdev_dbgmsg(svd, "begin read sit out for %d secs",
3136 			    (int)vdev_read_sit_out_secs);
3137 
3138 			for (int c = 0; c < vd->vdev_children; c++)
3139 				vd->vdev_child[c]->vdev_outlier_count = 0;
3140 		}
3141 	}
3142 
3143 	kmem_free(lat_data, sizeof (uint64_t) * children);
3144 }
3145 
3146 static void
vdev_raidz_io_done_verified(zio_t * zio,raidz_row_t * rr)3147 vdev_raidz_io_done_verified(zio_t *zio, raidz_row_t *rr)
3148 {
3149 	int unexpected_errors = 0;
3150 	int parity_errors = 0;
3151 	int parity_untried = 0;
3152 	int data_errors = 0;
3153 	zio_flag_t add_flags = 0;
3154 
3155 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_READ);
3156 
3157 	for (int c = 0; c < rr->rr_cols; c++) {
3158 		raidz_col_t *rc = &rr->rr_col[c];
3159 
3160 		if (rc->rc_error) {
3161 			if (c < rr->rr_firstdatacol)
3162 				parity_errors++;
3163 			else
3164 				data_errors++;
3165 
3166 			if (!rc->rc_skipped)
3167 				unexpected_errors++;
3168 		} else if (c < rr->rr_firstdatacol && !rc->rc_tried) {
3169 			parity_untried++;
3170 		}
3171 
3172 		if (rc->rc_force_repair)
3173 			unexpected_errors++;
3174 	}
3175 
3176 	/*
3177 	 * If we read more parity disks than were used for
3178 	 * reconstruction, confirm that the other parity disks produced
3179 	 * correct data.
3180 	 *
3181 	 * Note that we also regenerate parity when resilvering so we
3182 	 * can write it out to failed devices later.
3183 	 */
3184 	boolean_t parity_verify = (parity_errors + parity_untried) <
3185 	    (rr->rr_firstdatacol - data_errors);
3186 	if (parity_verify || (zio->io_flags & ZIO_FLAG_RESILVER)) {
3187 		int n = raidz_parity_verify(zio, rr);
3188 		/*
3189 		 * In, Reed-Solomon encoding, if we have ndata+1 columns and
3190 		 * the parity doesn't match, it means the data integrity is
3191 		 * compromised. We shouldn't try to repair anything in this
3192 		 * case.
3193 		 */
3194 		if (parity_verify && n > 0 &&
3195 		    zio->io_priority == ZIO_PRIORITY_REBUILD)
3196 			return;
3197 		/*
3198 		 * If we have only ndata columns, the data integrity will
3199 		 * be checked by the checksums normally, but not in case
3200 		 * of rebuild when we don't have checksums. In this case,
3201 		 * we add ZIO_FLAG_SPECULATIVE and try to not spread
3202 		 * unverified data. For example, when the target vdev happens
3203 		 * to be the mirroring spare vdev, we would repair only that
3204 		 * child in it which is being rebuilt.
3205 		 */
3206 		if (!parity_verify && zio->io_priority == ZIO_PRIORITY_REBUILD)
3207 			add_flags |= ZIO_FLAG_SPECULATIVE;
3208 		unexpected_errors += n;
3209 	}
3210 
3211 	if (zio->io_error == 0 && spa_writeable(zio->io_spa) &&
3212 	    (unexpected_errors > 0 || (zio->io_flags & ZIO_FLAG_RESILVER))) {
3213 		/*
3214 		 * Use the good data we have in hand to repair damaged children.
3215 		 */
3216 		for (int c = 0; c < rr->rr_cols; c++) {
3217 			raidz_col_t *rc = &rr->rr_col[c];
3218 			vdev_t *vd = zio->io_vd;
3219 			vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
3220 
3221 			if (!rc->rc_allow_repair) {
3222 				continue;
3223 			} else if (!rc->rc_force_repair &&
3224 			    (rc->rc_error == 0 || rc->rc_size == 0)) {
3225 				continue;
3226 			}
3227 			/*
3228 			 * We do not allow self healing for Direct I/O reads.
3229 			 * See comment in vdev_raid_row_alloc().
3230 			 */
3231 			ASSERT0(zio->io_flags & ZIO_FLAG_DIO_READ);
3232 
3233 			/*
3234 			 * When the target vdev is draid spare, we should clear
3235 			 * ZIO_FLAG_SPECULATIVE. First, if that draid spare maps
3236 			 * to another spare having an online/degraded disk, that
3237 			 * disk must be repaired also. Otherwise, the scrub will
3238 			 * detect a lot of cksum errors later. Second, since it
3239 			 * is draid spare, there is no harm in updating its
3240 			 * content on any vdev it maps to because the space is
3241 			 * reserved as a spare anyway.
3242 			 */
3243 			zio_flag_t aflags = add_flags;
3244 			if (rc->rc_tgt_is_dspare)
3245 				aflags &= ~ZIO_FLAG_SPECULATIVE;
3246 
3247 			zio_nowait(zio_vdev_child_io(zio, NULL, cvd,
3248 			    rc->rc_offset, rc->rc_abd, rc->rc_size,
3249 			    ZIO_TYPE_WRITE,
3250 			    zio->io_priority == ZIO_PRIORITY_REBUILD ?
3251 			    ZIO_PRIORITY_REBUILD : ZIO_PRIORITY_ASYNC_WRITE,
3252 			    ZIO_FLAG_IO_REPAIR | (unexpected_errors ?
3253 			    ZIO_FLAG_SELF_HEAL : 0) | aflags, NULL, NULL));
3254 		}
3255 	}
3256 
3257 	/*
3258 	 * Scrub or resilver i/o's: overwrite any shadow locations with the
3259 	 * good data.  This ensures that if we've already copied this sector,
3260 	 * it will be corrected if it was damaged.  This writes more than is
3261 	 * necessary, but since expansion is paused during scrub/resilver, at
3262 	 * most a single row will have a shadow location.
3263 	 */
3264 	if (zio->io_error == 0 && spa_writeable(zio->io_spa) &&
3265 	    (zio->io_flags & (ZIO_FLAG_RESILVER | ZIO_FLAG_SCRUB))) {
3266 		for (int c = 0; c < rr->rr_cols; c++) {
3267 			raidz_col_t *rc = &rr->rr_col[c];
3268 			vdev_t *vd = zio->io_vd;
3269 
3270 			if (rc->rc_shadow_devidx == INT_MAX || rc->rc_size == 0)
3271 				continue;
3272 			vdev_t *cvd = vd->vdev_child[rc->rc_shadow_devidx];
3273 
3274 			/*
3275 			 * Note: We don't want to update the repair stats
3276 			 * because that would incorrectly indicate that there
3277 			 * was bad data to repair, which we aren't sure about.
3278 			 * By clearing the SCAN_THREAD flag, we prevent this
3279 			 * from happening, despite having the REPAIR flag set.
3280 			 * We need to set SELF_HEAL so that this i/o can't be
3281 			 * bypassed by zio_vdev_io_start().
3282 			 */
3283 			zio_t *cio = zio_vdev_child_io(zio, NULL, cvd,
3284 			    rc->rc_shadow_offset, rc->rc_abd, rc->rc_size,
3285 			    ZIO_TYPE_WRITE, ZIO_PRIORITY_ASYNC_WRITE,
3286 			    ZIO_FLAG_IO_REPAIR | ZIO_FLAG_SELF_HEAL,
3287 			    NULL, NULL);
3288 			cio->io_flags &= ~ZIO_FLAG_SCAN_THREAD;
3289 			zio_nowait(cio);
3290 		}
3291 	}
3292 }
3293 
3294 static void
raidz_restore_orig_data(raidz_map_t * rm)3295 raidz_restore_orig_data(raidz_map_t *rm)
3296 {
3297 	for (int i = 0; i < rm->rm_nrows; i++) {
3298 		raidz_row_t *rr = rm->rm_row[i];
3299 		for (int c = 0; c < rr->rr_cols; c++) {
3300 			raidz_col_t *rc = &rr->rr_col[c];
3301 			if (rc->rc_need_orig_restore) {
3302 				abd_copy(rc->rc_abd,
3303 				    rc->rc_orig_data, rc->rc_size);
3304 				rc->rc_need_orig_restore = B_FALSE;
3305 			}
3306 		}
3307 	}
3308 }
3309 
3310 /*
3311  * During raidz_reconstruct() for expanded VDEV, we need special consideration
3312  * failure simulations.  See note in raidz_reconstruct() on simulating failure
3313  * of a pre-expansion device.
3314  *
3315  * Treating logical child i as failed, return TRUE if the given column should
3316  * be treated as failed.  The idea of logical children allows us to imagine
3317  * that a disk silently failed before a RAIDZ expansion (reads from this disk
3318  * succeed but return the wrong data).  Since the expansion doesn't verify
3319  * checksums, the incorrect data will be moved to new locations spread among
3320  * the children (going diagonally across them).
3321  *
3322  * Higher "logical child failures" (values of `i`) indicate these
3323  * "pre-expansion failures".  The first physical_width values imagine that a
3324  * current child failed; the next physical_width-1 values imagine that a
3325  * child failed before the most recent expansion; the next physical_width-2
3326  * values imagine a child failed in the expansion before that, etc.
3327  */
3328 static boolean_t
raidz_simulate_failure(int physical_width,int original_width,int ashift,int i,raidz_col_t * rc)3329 raidz_simulate_failure(int physical_width, int original_width, int ashift,
3330     int i, raidz_col_t *rc)
3331 {
3332 	uint64_t sector_id =
3333 	    physical_width * (rc->rc_offset >> ashift) +
3334 	    rc->rc_devidx;
3335 
3336 	for (int w = physical_width; w >= original_width; w--) {
3337 		if (i < w) {
3338 			return (sector_id % w == i);
3339 		} else {
3340 			i -= w;
3341 		}
3342 	}
3343 	ASSERT(!"invalid logical child id");
3344 	return (B_FALSE);
3345 }
3346 
3347 /*
3348  * returns EINVAL if reconstruction of the block will not be possible
3349  * returns ECKSUM if this specific reconstruction failed
3350  * returns 0 on successful reconstruction
3351  */
3352 static int
raidz_reconstruct(zio_t * zio,int * ltgts,int ntgts,int nparity)3353 raidz_reconstruct(zio_t *zio, int *ltgts, int ntgts, int nparity)
3354 {
3355 	vdev_t *vd = zio->io_vd;
3356 	raidz_map_t *rm = zio->io_vsd;
3357 	int physical_width = vd->vdev_children;
3358 	int dbgmsg = zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT;
3359 
3360 	if (vd->vdev_ops == &vdev_draid_ops) {
3361 		vdev_draid_config_t *vdc = vd->vdev_tsd;
3362 		physical_width = vdc->vdc_children;
3363 	}
3364 
3365 	int original_width = (rm->rm_original_width != 0) ?
3366 	    rm->rm_original_width : physical_width;
3367 
3368 	if (dbgmsg) {
3369 		zfs_dbgmsg("raidz_reconstruct_expanded(zio=%px ltgts=%u,%u,%u "
3370 		    "ntgts=%u", zio, ltgts[0], ltgts[1], ltgts[2], ntgts);
3371 	}
3372 
3373 	/* Reconstruct each row */
3374 	for (int r = 0; r < rm->rm_nrows; r++) {
3375 		raidz_row_t *rr = rm->rm_row[r];
3376 		int my_tgts[VDEV_RAIDZ_MAXPARITY]; /* value is child id */
3377 		int t = 0;
3378 		int dead = 0;
3379 		int dead_data = 0;
3380 
3381 		if (dbgmsg)
3382 			zfs_dbgmsg("raidz_reconstruct_expanded(row=%u)", r);
3383 
3384 		for (int c = 0; c < rr->rr_cols; c++) {
3385 			raidz_col_t *rc = &rr->rr_col[c];
3386 			ASSERT0(rc->rc_need_orig_restore);
3387 			if (rc->rc_error != 0) {
3388 				dead++;
3389 				if (c >= nparity)
3390 					dead_data++;
3391 				continue;
3392 			}
3393 			if (rc->rc_size == 0)
3394 				continue;
3395 			for (int lt = 0; lt < ntgts; lt++) {
3396 				if (raidz_simulate_failure(physical_width,
3397 				    original_width,
3398 				    zio->io_vd->vdev_top->vdev_ashift,
3399 				    ltgts[lt], rc)) {
3400 					if (rc->rc_orig_data == NULL) {
3401 						rc->rc_orig_data =
3402 						    abd_alloc_linear(
3403 						    rc->rc_size, B_TRUE);
3404 						abd_copy(rc->rc_orig_data,
3405 						    rc->rc_abd, rc->rc_size);
3406 					}
3407 					rc->rc_need_orig_restore = B_TRUE;
3408 
3409 					dead++;
3410 					if (c >= nparity)
3411 						dead_data++;
3412 					/*
3413 					 * Note: simulating failure of a
3414 					 * pre-expansion device can hit more
3415 					 * than one column, in which case we
3416 					 * might try to simulate more failures
3417 					 * than can be reconstructed, which is
3418 					 * also more than the size of my_tgts.
3419 					 * This check prevents accessing past
3420 					 * the end of my_tgts.  The "dead >
3421 					 * nparity" check below will fail this
3422 					 * reconstruction attempt.
3423 					 */
3424 					if (t < VDEV_RAIDZ_MAXPARITY) {
3425 						my_tgts[t++] = c;
3426 						if (dbgmsg) {
3427 							zfs_dbgmsg("simulating "
3428 							    "failure of col %u "
3429 							    "devidx %u", c,
3430 							    (int)rc->rc_devidx);
3431 						}
3432 					}
3433 					break;
3434 				}
3435 			}
3436 		}
3437 		if (dead > nparity) {
3438 			/* reconstruction not possible */
3439 			if (dbgmsg) {
3440 				zfs_dbgmsg("reconstruction not possible; "
3441 				    "too many failures");
3442 			}
3443 			raidz_restore_orig_data(rm);
3444 			return (EINVAL);
3445 		}
3446 		if (dead_data > 0)
3447 			vdev_raidz_reconstruct_row(rm, rr, my_tgts, t);
3448 	}
3449 
3450 	/* Check for success */
3451 	if (raidz_checksum_verify(zio) == 0) {
3452 		if (zio->io_post & ZIO_POST_DIO_CHKSUM_ERR)
3453 			return (0);
3454 
3455 		/* Reconstruction succeeded - report errors */
3456 		for (int i = 0; i < rm->rm_nrows; i++) {
3457 			raidz_row_t *rr = rm->rm_row[i];
3458 
3459 			for (int c = 0; c < rr->rr_cols; c++) {
3460 				raidz_col_t *rc = &rr->rr_col[c];
3461 				if (rc->rc_need_orig_restore) {
3462 					/*
3463 					 * Note: if this is a parity column,
3464 					 * we don't really know if it's wrong.
3465 					 * We need to let
3466 					 * vdev_raidz_io_done_verified() check
3467 					 * it, and if we set rc_error, it will
3468 					 * think that it is a "known" error
3469 					 * that doesn't need to be checked
3470 					 * or corrected.
3471 					 */
3472 					if (rc->rc_error == 0 &&
3473 					    c >= rr->rr_firstdatacol) {
3474 						vdev_raidz_checksum_error(zio,
3475 						    rc, rc->rc_orig_data);
3476 						rc->rc_error =
3477 						    SET_ERROR(ECKSUM);
3478 					}
3479 					rc->rc_need_orig_restore = B_FALSE;
3480 				}
3481 			}
3482 
3483 			vdev_raidz_io_done_verified(zio, rr);
3484 		}
3485 
3486 		zio_checksum_verified(zio);
3487 
3488 		if (dbgmsg) {
3489 			zfs_dbgmsg("reconstruction successful "
3490 			    "(checksum verified)");
3491 		}
3492 		return (0);
3493 	}
3494 
3495 	/* Reconstruction failed - restore original data */
3496 	raidz_restore_orig_data(rm);
3497 	if (dbgmsg) {
3498 		zfs_dbgmsg("raidz_reconstruct_expanded(zio=%px) checksum "
3499 		    "failed", zio);
3500 	}
3501 	return (ECKSUM);
3502 }
3503 
3504 /*
3505  * Iterate over all combinations of N bad vdevs and attempt a reconstruction.
3506  * Note that the algorithm below is non-optimal because it doesn't take into
3507  * account how reconstruction is actually performed. For example, with
3508  * triple-parity RAID-Z the reconstruction procedure is the same if column 4
3509  * is targeted as invalid as if columns 1 and 4 are targeted since in both
3510  * cases we'd only use parity information in column 0.
3511  *
3512  * The order that we find the various possible combinations of failed
3513  * disks is dictated by these rules:
3514  * - Examine each "slot" (the "i" in tgts[i])
3515  *   - Try to increment this slot (tgts[i] += 1)
3516  *   - if we can't increment because it runs into the next slot,
3517  *     reset our slot to the minimum, and examine the next slot
3518  *
3519  *  For example, with a 6-wide RAIDZ3, and no known errors (so we have to choose
3520  *  3 columns to reconstruct), we will generate the following sequence:
3521  *
3522  *  STATE        ACTION
3523  *  0 1 2        special case: skip since these are all parity
3524  *  0 1   3      first slot: reset to 0; middle slot: increment to 2
3525  *  0   2 3      first slot: increment to 1
3526  *    1 2 3      first: reset to 0; middle: reset to 1; last: increment to 4
3527  *  0 1     4    first: reset to 0; middle: increment to 2
3528  *  0   2   4    first: increment to 1
3529  *    1 2   4    first: reset to 0; middle: increment to 3
3530  *  0     3 4    first: increment to 1
3531  *    1   3 4    first: increment to 2
3532  *      2 3 4    first: reset to 0; middle: reset to 1; last: increment to 5
3533  *  0 1       5  first: reset to 0; middle: increment to 2
3534  *  0   2     5  first: increment to 1
3535  *    1 2     5  first: reset to 0; middle: increment to 3
3536  *  0     3   5  first: increment to 1
3537  *    1   3   5  first: increment to 2
3538  *      2 3   5  first: reset to 0; middle: increment to 4
3539  *  0       4 5  first: increment to 1
3540  *    1     4 5  first: increment to 2
3541  *      2   4 5  first: increment to 3
3542  *        3 4 5  done
3543  *
3544  * This strategy works for dRAID but is less efficient when there are a large
3545  * number of child vdevs and therefore permutations to check. Furthermore,
3546  * since the raidz_map_t rows likely do not overlap, reconstruction would be
3547  * possible as long as there are no more than nparity data errors per row.
3548  * These additional permutations are not currently checked but could be as
3549  * a future improvement.
3550  *
3551  * Returns 0 on success, ECKSUM on failure.
3552  */
3553 static int
vdev_raidz_combrec(zio_t * zio)3554 vdev_raidz_combrec(zio_t *zio)
3555 {
3556 	vdev_t *vd = zio->io_vd;
3557 	int nparity = vdev_get_nparity(vd);
3558 	raidz_map_t *rm = zio->io_vsd;
3559 	int physical_width = zio->io_vd->vdev_children;
3560 
3561 	if (vd->vdev_ops == &vdev_draid_ops) {
3562 		vdev_draid_config_t *vdc = vd->vdev_tsd;
3563 		nparity = vdc->vdc_nparity;
3564 		physical_width = vdc->vdc_children;
3565 	}
3566 
3567 	int original_width = (rm->rm_original_width != 0) ?
3568 	    rm->rm_original_width : physical_width;
3569 
3570 	for (int i = 0; i < rm->rm_nrows; i++) {
3571 		raidz_row_t *rr = rm->rm_row[i];
3572 		int total_errors = 0;
3573 
3574 		for (int c = 0; c < rr->rr_cols; c++) {
3575 			if (rr->rr_col[c].rc_error)
3576 				total_errors++;
3577 		}
3578 
3579 		if (total_errors > nparity)
3580 			return (vdev_raidz_worst_error(rr));
3581 	}
3582 
3583 	for (int num_failures = 1; num_failures <= nparity; num_failures++) {
3584 		int tstore[VDEV_RAIDZ_MAXPARITY + 2];
3585 		int *ltgts = &tstore[1]; /* value is logical child ID */
3586 
3587 
3588 		/*
3589 		 * Determine number of logical children, n.  See comment
3590 		 * above raidz_simulate_failure().
3591 		 */
3592 		int n = 0;
3593 		for (int w = physical_width;
3594 		    w >= original_width; w--) {
3595 			n += w;
3596 		}
3597 
3598 		ASSERT3U(num_failures, <=, nparity);
3599 		ASSERT3U(num_failures, <=, VDEV_RAIDZ_MAXPARITY);
3600 
3601 		/* Handle corner cases in combrec logic */
3602 		ltgts[-1] = -1;
3603 		for (int i = 0; i < num_failures; i++) {
3604 			ltgts[i] = i;
3605 		}
3606 		ltgts[num_failures] = n;
3607 
3608 		for (;;) {
3609 			int err = raidz_reconstruct(zio, ltgts, num_failures,
3610 			    nparity);
3611 			if (err == EINVAL) {
3612 				/*
3613 				 * Reconstruction not possible with this #
3614 				 * failures; try more failures.
3615 				 */
3616 				break;
3617 			} else if (err == 0)
3618 				return (0);
3619 
3620 			/* Compute next targets to try */
3621 			for (int t = 0; ; t++) {
3622 				ASSERT3U(t, <, num_failures);
3623 				ltgts[t]++;
3624 				if (ltgts[t] == n) {
3625 					/* try more failures */
3626 					ASSERT3U(t, ==, num_failures - 1);
3627 					if (zfs_flags &
3628 					    ZFS_DEBUG_RAIDZ_RECONSTRUCT) {
3629 						zfs_dbgmsg("reconstruction "
3630 						    "failed for num_failures="
3631 						    "%u; tried all "
3632 						    "combinations",
3633 						    num_failures);
3634 					}
3635 					break;
3636 				}
3637 
3638 				ASSERT3U(ltgts[t], <, n);
3639 				ASSERT3U(ltgts[t], <=, ltgts[t + 1]);
3640 
3641 				/*
3642 				 * If that spot is available, we're done here.
3643 				 * Try the next combination.
3644 				 */
3645 				if (ltgts[t] != ltgts[t + 1])
3646 					break; // found next combination
3647 
3648 				/*
3649 				 * Otherwise, reset this tgt to the minimum,
3650 				 * and move on to the next tgt.
3651 				 */
3652 				ltgts[t] = ltgts[t - 1] + 1;
3653 				ASSERT3U(ltgts[t], ==, t);
3654 			}
3655 
3656 			/* Increase the number of failures and keep trying. */
3657 			if (ltgts[num_failures - 1] == n)
3658 				break;
3659 		}
3660 	}
3661 	if (zfs_flags & ZFS_DEBUG_RAIDZ_RECONSTRUCT)
3662 		zfs_dbgmsg("reconstruction failed for all num_failures");
3663 	return (ECKSUM);
3664 }
3665 
3666 void
vdev_raidz_reconstruct(raidz_map_t * rm,const int * t,int nt)3667 vdev_raidz_reconstruct(raidz_map_t *rm, const int *t, int nt)
3668 {
3669 	for (uint64_t row = 0; row < rm->rm_nrows; row++) {
3670 		raidz_row_t *rr = rm->rm_row[row];
3671 		vdev_raidz_reconstruct_row(rm, rr, t, nt);
3672 	}
3673 }
3674 
3675 /*
3676  * Complete a write IO operation on a RAIDZ VDev
3677  *
3678  * Outline:
3679  *   1. Check for errors on the child IOs.
3680  *   2. Return, setting an error code if too few child VDevs were written
3681  *      to reconstruct the data later.  Note that partial writes are
3682  *      considered successful if they can be reconstructed at all.
3683  */
3684 static void
vdev_raidz_io_done_write_impl(zio_t * zio,raidz_row_t * rr)3685 vdev_raidz_io_done_write_impl(zio_t *zio, raidz_row_t *rr)
3686 {
3687 	int normal_errors = 0;
3688 	int shadow_errors = 0;
3689 	int retryable_errors = 0;
3690 
3691 	ASSERT3U(rr->rr_missingparity, <=, rr->rr_firstdatacol);
3692 	ASSERT3U(rr->rr_missingdata, <=, rr->rr_cols - rr->rr_firstdatacol);
3693 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
3694 
3695 	for (int c = 0; c < rr->rr_cols; c++) {
3696 		raidz_col_t *rc = &rr->rr_col[c];
3697 
3698 		if (rc->rc_error != 0) {
3699 			ASSERT(rc->rc_error != ECKSUM);	/* child has no bp */
3700 			normal_errors++;
3701 		}
3702 		if (rc->rc_shadow_error != 0) {
3703 			ASSERT(rc->rc_shadow_error != ECKSUM);
3704 			shadow_errors++;
3705 		}
3706 		if (rc->rc_error || rc->rc_shadow_error) {
3707 			vdev_t *cvd = zio->io_vd->vdev_child[rc->rc_devidx];
3708 			if (!(vdev_is_dead(cvd) || cvd->vdev_cant_write))
3709 				retryable_errors++;
3710 		}
3711 	}
3712 
3713 	/*
3714 	 * Treat partial writes as a success. If we couldn't write enough
3715 	 * columns to reconstruct the data, the I/O failed.  Otherwise, good
3716 	 * enough.  Note that in the case of a shadow write (during raidz
3717 	 * expansion), depending on if we crash, either the normal (old) or
3718 	 * shadow (new) location may become the "real" version of the block,
3719 	 * so both locations must have sufficient redundancy.
3720 	 *
3721 	 * Now that we support write reallocation, it would be better
3722 	 * to treat partial failure as real failure unless there are
3723 	 * no non-degraded top-level vdevs left, and not update DTLs
3724 	 * if we intend to reallocate.
3725 	 */
3726 	if (normal_errors > rr->rr_firstdatacol ||
3727 	    shadow_errors > rr->rr_firstdatacol) {
3728 		zio->io_error = zio_worst_error(zio->io_error,
3729 		    vdev_raidz_worst_error(rr));
3730 	} else if (retryable_errors && zfs_scrub_partial_writes) {
3731 		zio->io_flags |= ZIO_FLAG_POSTREAD;
3732 	}
3733 }
3734 
3735 static void
vdev_raidz_io_done_reconstruct_known_missing(zio_t * zio,raidz_map_t * rm,raidz_row_t * rr)3736 vdev_raidz_io_done_reconstruct_known_missing(zio_t *zio, raidz_map_t *rm,
3737     raidz_row_t *rr)
3738 {
3739 	int parity_errors = 0;
3740 	int parity_untried = 0;
3741 	int data_errors = 0;
3742 	int total_errors = 0;
3743 
3744 	ASSERT3U(rr->rr_missingparity, <=, rr->rr_firstdatacol);
3745 	ASSERT3U(rr->rr_missingdata, <=, rr->rr_cols - rr->rr_firstdatacol);
3746 
3747 	for (int c = 0; c < rr->rr_cols; c++) {
3748 		raidz_col_t *rc = &rr->rr_col[c];
3749 
3750 		/*
3751 		 * If scrubbing and a replacing/sparing child vdev determined
3752 		 * that not all of its children have an identical copy of the
3753 		 * data, then clear the error so the column is treated like
3754 		 * any other read and force a repair to correct the damage.
3755 		 */
3756 		if (rc->rc_error == ECKSUM) {
3757 			ASSERT(zio->io_flags & ZIO_FLAG_SCRUB);
3758 			vdev_raidz_checksum_error(zio, rc, rc->rc_abd);
3759 			rc->rc_force_repair = 1;
3760 			rc->rc_error = 0;
3761 		}
3762 
3763 		if (rc->rc_error) {
3764 			if (c < rr->rr_firstdatacol)
3765 				parity_errors++;
3766 			else
3767 				data_errors++;
3768 
3769 			total_errors++;
3770 		} else if (c < rr->rr_firstdatacol && !rc->rc_tried) {
3771 			parity_untried++;
3772 		}
3773 	}
3774 
3775 	/*
3776 	 * If there were data errors and the number of errors we saw was
3777 	 * correctable -- less than or equal to the number of parity disks read
3778 	 * -- reconstruct based on the missing data.
3779 	 */
3780 	if (data_errors != 0 &&
3781 	    total_errors <= rr->rr_firstdatacol - parity_untried) {
3782 		/*
3783 		 * We either attempt to read all the parity columns or
3784 		 * none of them. If we didn't try to read parity, we
3785 		 * wouldn't be here in the correctable case. There must
3786 		 * also have been fewer parity errors than parity
3787 		 * columns or, again, we wouldn't be in this code path.
3788 		 */
3789 		ASSERT0(parity_untried);
3790 		ASSERT(parity_errors < rr->rr_firstdatacol);
3791 
3792 		/*
3793 		 * Identify the data columns that reported an error.
3794 		 */
3795 		int n = 0;
3796 		int tgts[VDEV_RAIDZ_MAXPARITY];
3797 		for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
3798 			raidz_col_t *rc = &rr->rr_col[c];
3799 			if (rc->rc_error != 0) {
3800 				ASSERT(n < VDEV_RAIDZ_MAXPARITY);
3801 				tgts[n++] = c;
3802 			}
3803 		}
3804 
3805 		ASSERT(rr->rr_firstdatacol >= n);
3806 
3807 		vdev_raidz_reconstruct_row(rm, rr, tgts, n);
3808 	}
3809 }
3810 
3811 /*
3812  * Return the number of reads issued.
3813  */
3814 static int
vdev_raidz_read_all(zio_t * zio,raidz_row_t * rr)3815 vdev_raidz_read_all(zio_t *zio, raidz_row_t *rr)
3816 {
3817 	vdev_t *vd = zio->io_vd;
3818 	int nread = 0;
3819 
3820 	rr->rr_missingdata = 0;
3821 	rr->rr_missingparity = 0;
3822 
3823 	/*
3824 	 * If this rows contains empty sectors which are not required
3825 	 * for a normal read then allocate an ABD for them now so they
3826 	 * may be read, verified, and any needed repairs performed.
3827 	 */
3828 	if (rr->rr_nempty != 0 && rr->rr_abd_empty == NULL)
3829 		vdev_draid_map_alloc_empty(zio, rr);
3830 
3831 	for (int c = 0; c < rr->rr_cols; c++) {
3832 		raidz_col_t *rc = &rr->rr_col[c];
3833 		if (rc->rc_tried || rc->rc_size == 0)
3834 			continue;
3835 
3836 		zio_nowait(zio_vdev_child_io(zio, NULL,
3837 		    vd->vdev_child[rc->rc_devidx],
3838 		    rc->rc_offset, rc->rc_abd, rc->rc_size,
3839 		    zio->io_type, zio->io_priority, 0,
3840 		    vdev_raidz_child_done, rc));
3841 		nread++;
3842 	}
3843 	return (nread);
3844 }
3845 
3846 /*
3847  * We're here because either there were too many errors to even attempt
3848  * reconstruction (total_errors == rm_first_datacol), or vdev_*_combrec()
3849  * failed. In either case, there is enough bad data to prevent reconstruction.
3850  * Start checksum ereports for all children which haven't failed.
3851  */
3852 static void
vdev_raidz_io_done_unrecoverable(zio_t * zio)3853 vdev_raidz_io_done_unrecoverable(zio_t *zio)
3854 {
3855 	raidz_map_t *rm = zio->io_vsd;
3856 
3857 	for (int i = 0; i < rm->rm_nrows; i++) {
3858 		raidz_row_t *rr = rm->rm_row[i];
3859 
3860 		for (int c = 0; c < rr->rr_cols; c++) {
3861 			raidz_col_t *rc = &rr->rr_col[c];
3862 			vdev_t *cvd = zio->io_vd->vdev_child[rc->rc_devidx];
3863 
3864 			if (rc->rc_error != 0)
3865 				continue;
3866 
3867 			zio_bad_cksum_t zbc;
3868 			zbc.zbc_has_cksum = 0;
3869 			zbc.zbc_injected = rm->rm_ecksuminjected;
3870 			mutex_enter(&cvd->vdev_stat_lock);
3871 			cvd->vdev_stat.vs_checksum_errors++;
3872 			mutex_exit(&cvd->vdev_stat_lock);
3873 			(void) zfs_ereport_start_checksum(zio->io_spa,
3874 			    cvd, &zio->io_bookmark, zio, rc->rc_offset,
3875 			    rc->rc_size, &zbc);
3876 		}
3877 	}
3878 }
3879 
3880 void
vdev_raidz_io_done(zio_t * zio)3881 vdev_raidz_io_done(zio_t *zio)
3882 {
3883 	raidz_map_t *rm = zio->io_vsd;
3884 
3885 	ASSERT(zio->io_bp != NULL);
3886 	if (zio->io_type == ZIO_TYPE_WRITE) {
3887 		for (int i = 0; i < rm->rm_nrows; i++) {
3888 			vdev_raidz_io_done_write_impl(zio, rm->rm_row[i]);
3889 		}
3890 	} else {
3891 		if (rm->rm_phys_col) {
3892 			/*
3893 			 * This is an aggregated read.  Copy the data and status
3894 			 * from the aggregate abd's to the individual rows.
3895 			 */
3896 			for (int i = 0; i < rm->rm_nrows; i++) {
3897 				raidz_row_t *rr = rm->rm_row[i];
3898 
3899 				for (int c = 0; c < rr->rr_cols; c++) {
3900 					raidz_col_t *rc = &rr->rr_col[c];
3901 					if (rc->rc_tried || rc->rc_size == 0)
3902 						continue;
3903 
3904 					raidz_col_t *prc =
3905 					    &rm->rm_phys_col[rc->rc_devidx];
3906 					rc->rc_error = prc->rc_error;
3907 					rc->rc_tried = prc->rc_tried;
3908 					rc->rc_skipped = prc->rc_skipped;
3909 					if (c >= rr->rr_firstdatacol) {
3910 						/*
3911 						 * Note: this is slightly faster
3912 						 * than using abd_copy_off().
3913 						 */
3914 						char *physbuf = abd_to_buf(
3915 						    prc->rc_abd);
3916 						void *physloc = physbuf +
3917 						    rc->rc_offset -
3918 						    prc->rc_offset;
3919 
3920 						abd_copy_from_buf(rc->rc_abd,
3921 						    physloc, rc->rc_size);
3922 					}
3923 				}
3924 			}
3925 		}
3926 
3927 		for (int i = 0; i < rm->rm_nrows; i++) {
3928 			raidz_row_t *rr = rm->rm_row[i];
3929 			vdev_raidz_io_done_reconstruct_known_missing(zio,
3930 			    rm, rr);
3931 		}
3932 
3933 		if (raidz_checksum_verify(zio) == 0) {
3934 			if (zio->io_post & ZIO_POST_DIO_CHKSUM_ERR)
3935 				goto done;
3936 
3937 			for (int i = 0; i < rm->rm_nrows; i++) {
3938 				raidz_row_t *rr = rm->rm_row[i];
3939 				vdev_raidz_io_done_verified(zio, rr);
3940 			}
3941 			/* Periodically check for a read outlier */
3942 			if (zio->io_type == ZIO_TYPE_READ)
3943 				vdev_child_slow_outlier(zio);
3944 			zio_checksum_verified(zio);
3945 		} else {
3946 			/*
3947 			 * A sequential resilver has no checksum which makes
3948 			 * combinatoral reconstruction impossible. This code
3949 			 * path is unreachable since raidz_checksum_verify()
3950 			 * has no checksum to verify and must succeed.
3951 			 */
3952 			ASSERT3U(zio->io_priority, !=, ZIO_PRIORITY_REBUILD);
3953 
3954 			/*
3955 			 * This isn't a typical situation -- either we got a
3956 			 * read error or a child silently returned bad data.
3957 			 * Read every block so we can try again with as much
3958 			 * data and parity as we can track down. If we've
3959 			 * already been through once before, all children will
3960 			 * be marked as tried so we'll proceed to combinatorial
3961 			 * reconstruction.
3962 			 */
3963 			int nread = 0;
3964 			for (int i = 0; i < rm->rm_nrows; i++) {
3965 				nread += vdev_raidz_read_all(zio,
3966 				    rm->rm_row[i]);
3967 			}
3968 			if (nread != 0) {
3969 				/*
3970 				 * Normally our stage is VDEV_IO_DONE, but if
3971 				 * we've already called redone(), it will have
3972 				 * changed to VDEV_IO_START, in which case we
3973 				 * don't want to call redone() again.
3974 				 */
3975 				if (zio->io_stage != ZIO_STAGE_VDEV_IO_START)
3976 					zio_vdev_io_redone(zio);
3977 				return;
3978 			}
3979 			/*
3980 			 * It would be too expensive to try every possible
3981 			 * combination of failed sectors in every row, so
3982 			 * instead we try every combination of failed current or
3983 			 * past physical disk. This means that if the incorrect
3984 			 * sectors were all on Nparity disks at any point in the
3985 			 * past, we will find the correct data.  The only known
3986 			 * case where this is less durable than a non-expanded
3987 			 * RAIDZ, is if we have a silent failure during
3988 			 * expansion.  In that case, one block could be
3989 			 * partially in the old format and partially in the
3990 			 * new format, so we'd lost some sectors from the old
3991 			 * format and some from the new format.
3992 			 *
3993 			 * e.g. logical_width=4 physical_width=6
3994 			 * the 15 (6+5+4) possible failed disks are:
3995 			 * width=6 child=0
3996 			 * width=6 child=1
3997 			 * width=6 child=2
3998 			 * width=6 child=3
3999 			 * width=6 child=4
4000 			 * width=6 child=5
4001 			 * width=5 child=0
4002 			 * width=5 child=1
4003 			 * width=5 child=2
4004 			 * width=5 child=3
4005 			 * width=5 child=4
4006 			 * width=4 child=0
4007 			 * width=4 child=1
4008 			 * width=4 child=2
4009 			 * width=4 child=3
4010 			 * And we will try every combination of Nparity of these
4011 			 * failing.
4012 			 *
4013 			 * As a first pass, we can generate every combo,
4014 			 * and try reconstructing, ignoring any known
4015 			 * failures.  If any row has too many known + simulated
4016 			 * failures, then we bail on reconstructing with this
4017 			 * number of simulated failures.  As an improvement,
4018 			 * we could detect the number of whole known failures
4019 			 * (i.e. we have known failures on these disks for
4020 			 * every row; the disks never succeeded), and
4021 			 * subtract that from the max # failures to simulate.
4022 			 * We could go even further like the current
4023 			 * combrec code, but that doesn't seem like it
4024 			 * gains us very much.  If we simulate a failure
4025 			 * that is also a known failure, that's fine.
4026 			 */
4027 			zio->io_error = vdev_raidz_combrec(zio);
4028 			if (zio->io_error == ECKSUM &&
4029 			    !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
4030 				vdev_raidz_io_done_unrecoverable(zio);
4031 			}
4032 		}
4033 	}
4034 done:
4035 	if (rm->rm_lr != NULL) {
4036 		zfs_rangelock_exit(rm->rm_lr);
4037 		rm->rm_lr = NULL;
4038 	}
4039 }
4040 
4041 static void
vdev_raidz_state_change(vdev_t * vd,int faulted,int degraded)4042 vdev_raidz_state_change(vdev_t *vd, int faulted, int degraded)
4043 {
4044 	vdev_raidz_t *vdrz = vd->vdev_tsd;
4045 	if (faulted > vdrz->vd_nparity)
4046 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
4047 		    VDEV_AUX_NO_REPLICAS);
4048 	else if (degraded + faulted != 0)
4049 		vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, VDEV_AUX_NONE);
4050 	else
4051 		vdev_set_state(vd, B_FALSE, VDEV_STATE_HEALTHY, VDEV_AUX_NONE);
4052 }
4053 
4054 /*
4055  * Determine if any portion of the provided block resides on a child vdev
4056  * with a dirty DTL and therefore needs to be resilvered.  The function
4057  * assumes that at least one DTL is dirty which implies that full stripe
4058  * width blocks must be resilvered.
4059  */
4060 static boolean_t
vdev_raidz_need_resilver(vdev_t * vd,const dva_t * dva,size_t psize,uint64_t phys_birth)4061 vdev_raidz_need_resilver(vdev_t *vd, const dva_t *dva, size_t psize,
4062     uint64_t phys_birth)
4063 {
4064 	vdev_raidz_t *vdrz = vd->vdev_tsd;
4065 
4066 	/*
4067 	 * If we're in the middle of a RAIDZ expansion, this block may be in
4068 	 * the old and/or new location.  For simplicity, always resilver it.
4069 	 */
4070 	if (vdrz->vn_vre.vre_state == DSS_SCANNING)
4071 		return (B_TRUE);
4072 
4073 	uint64_t dcols = vd->vdev_children;
4074 	uint64_t nparity = vdrz->vd_nparity;
4075 	uint64_t ashift = vd->vdev_top->vdev_ashift;
4076 	/* The starting RAIDZ (parent) vdev sector of the block. */
4077 	uint64_t b = DVA_GET_OFFSET(dva) >> ashift;
4078 	/* The zio's size in units of the vdev's minimum sector size. */
4079 	uint64_t s = ((psize - 1) >> ashift) + 1;
4080 	/* The first column for this stripe. */
4081 	uint64_t f = b % dcols;
4082 
4083 	/* Unreachable by sequential resilver. */
4084 	ASSERT3U(phys_birth, !=, TXG_UNKNOWN);
4085 
4086 	if (!vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1))
4087 		return (B_FALSE);
4088 
4089 	if (s + nparity >= dcols)
4090 		return (B_TRUE);
4091 
4092 	for (uint64_t c = 0; c < s + nparity; c++) {
4093 		uint64_t devidx = (f + c) % dcols;
4094 		vdev_t *cvd = vd->vdev_child[devidx];
4095 
4096 		/*
4097 		 * dsl_scan_need_resilver() already checked vd with
4098 		 * vdev_dtl_contains(). So here just check cvd with
4099 		 * vdev_dtl_empty(), cheaper and a good approximation.
4100 		 */
4101 		if (!vdev_dtl_empty(cvd, DTL_PARTIAL))
4102 			return (B_TRUE);
4103 	}
4104 
4105 	return (B_FALSE);
4106 }
4107 
4108 static void
vdev_raidz_xlate(vdev_t * cvd,const zfs_range_seg64_t * logical_rs,zfs_range_seg64_t * physical_rs,zfs_range_seg64_t * remain_rs)4109 vdev_raidz_xlate(vdev_t *cvd, const zfs_range_seg64_t *logical_rs,
4110     zfs_range_seg64_t *physical_rs, zfs_range_seg64_t *remain_rs)
4111 {
4112 	(void) remain_rs;
4113 
4114 	vdev_t *raidvd = cvd->vdev_parent;
4115 	ASSERT(raidvd->vdev_ops == &vdev_raidz_ops);
4116 
4117 	vdev_raidz_t *vdrz = raidvd->vdev_tsd;
4118 
4119 	if (vdrz->vn_vre.vre_state == DSS_SCANNING) {
4120 		/*
4121 		 * We're in the middle of expansion, in which case the
4122 		 * translation is in flux.  Any answer we give may be wrong
4123 		 * by the time we return, so it isn't safe for the caller to
4124 		 * act on it.  Therefore we say that this range isn't present
4125 		 * on any children.  The only consumers of this are "zpool
4126 		 * initialize" and trimming, both of which are "best effort"
4127 		 * anyway.
4128 		 */
4129 		physical_rs->rs_start = physical_rs->rs_end = 0;
4130 		remain_rs->rs_start = remain_rs->rs_end = 0;
4131 		return;
4132 	}
4133 
4134 	uint64_t width = vdrz->vd_physical_width;
4135 	uint64_t tgt_col = cvd->vdev_id;
4136 	uint64_t ashift = raidvd->vdev_top->vdev_ashift;
4137 
4138 	/* make sure the offsets are block-aligned */
4139 	ASSERT0(logical_rs->rs_start % (1 << ashift));
4140 	ASSERT0(logical_rs->rs_end % (1 << ashift));
4141 	uint64_t b_start = logical_rs->rs_start >> ashift;
4142 	uint64_t b_end = logical_rs->rs_end >> ashift;
4143 
4144 	uint64_t start_row = 0;
4145 	if (b_start > tgt_col) /* avoid underflow */
4146 		start_row = ((b_start - tgt_col - 1) / width) + 1;
4147 
4148 	uint64_t end_row = 0;
4149 	if (b_end > tgt_col)
4150 		end_row = ((b_end - tgt_col - 1) / width) + 1;
4151 
4152 	physical_rs->rs_start = start_row << ashift;
4153 	physical_rs->rs_end = end_row << ashift;
4154 
4155 	ASSERT3U(physical_rs->rs_start, <=, logical_rs->rs_start);
4156 	ASSERT3U(physical_rs->rs_end - physical_rs->rs_start, <=,
4157 	    logical_rs->rs_end - logical_rs->rs_start);
4158 }
4159 
4160 static void
raidz_reflow_sync(void * arg,dmu_tx_t * tx)4161 raidz_reflow_sync(void *arg, dmu_tx_t *tx)
4162 {
4163 	spa_t *spa = arg;
4164 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
4165 	vdev_raidz_expand_t *vre = spa->spa_raidz_expand;
4166 
4167 	/*
4168 	 * Ensure there are no i/os to the range that is being committed.
4169 	 */
4170 	uint64_t old_offset = RRSS_GET_OFFSET(&spa->spa_uberblock);
4171 	ASSERT3U(vre->vre_offset_pertxg[txgoff], >=, old_offset);
4172 
4173 	mutex_enter(&vre->vre_lock);
4174 	uint64_t new_offset =
4175 	    MIN(vre->vre_offset_pertxg[txgoff], vre->vre_failed_offset);
4176 	/*
4177 	 * We should not have committed anything that failed.
4178 	 */
4179 	VERIFY3U(vre->vre_failed_offset, >=, old_offset);
4180 	mutex_exit(&vre->vre_lock);
4181 
4182 	zfs_locked_range_t *lr = zfs_rangelock_enter(&vre->vre_rangelock,
4183 	    old_offset, new_offset - old_offset,
4184 	    RL_WRITER);
4185 
4186 	/*
4187 	 * Update the uberblock that will be written when this txg completes.
4188 	 */
4189 	RAIDZ_REFLOW_SET(&spa->spa_uberblock,
4190 	    RRSS_SCRATCH_INVALID_SYNCED_REFLOW, new_offset);
4191 	vre->vre_offset_pertxg[txgoff] = 0;
4192 	zfs_rangelock_exit(lr);
4193 
4194 	mutex_enter(&vre->vre_lock);
4195 	vre->vre_bytes_copied += vre->vre_bytes_copied_pertxg[txgoff];
4196 	vre->vre_bytes_copied_pertxg[txgoff] = 0;
4197 	mutex_exit(&vre->vre_lock);
4198 
4199 	vdev_t *vd = vdev_lookup_top(spa, vre->vre_vdev_id);
4200 	VERIFY0(zap_update(spa->spa_meta_objset,
4201 	    vd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_BYTES_COPIED,
4202 	    sizeof (vre->vre_bytes_copied), 1, &vre->vre_bytes_copied, tx));
4203 }
4204 
4205 static void
raidz_reflow_complete_sync(void * arg,dmu_tx_t * tx)4206 raidz_reflow_complete_sync(void *arg, dmu_tx_t *tx)
4207 {
4208 	spa_t *spa = arg;
4209 	vdev_raidz_expand_t *vre = spa->spa_raidz_expand;
4210 	vdev_t *raidvd = vdev_lookup_top(spa, vre->vre_vdev_id);
4211 	vdev_raidz_t *vdrz = raidvd->vdev_tsd;
4212 
4213 	for (int i = 0; i < TXG_SIZE; i++)
4214 		VERIFY0(vre->vre_offset_pertxg[i]);
4215 
4216 	reflow_node_t *re = kmem_zalloc(sizeof (*re), KM_SLEEP);
4217 	re->re_txg = tx->tx_txg + TXG_CONCURRENT_STATES;
4218 	re->re_logical_width = vdrz->vd_physical_width;
4219 	mutex_enter(&vdrz->vd_expand_lock);
4220 	avl_add(&vdrz->vd_expand_txgs, re);
4221 	mutex_exit(&vdrz->vd_expand_lock);
4222 
4223 	vdev_t *vd = vdev_lookup_top(spa, vre->vre_vdev_id);
4224 
4225 	/*
4226 	 * Dirty the config so that the updated ZPOOL_CONFIG_RAIDZ_EXPAND_TXGS
4227 	 * will get written (based on vd_expand_txgs).
4228 	 */
4229 	vdev_config_dirty(vd);
4230 
4231 	/*
4232 	 * Before we change vre_state, the on-disk state must reflect that we
4233 	 * have completed all copying, so that vdev_raidz_io_start() can use
4234 	 * vre_state to determine if the reflow is in progress.  See also the
4235 	 * end of spa_raidz_expand_thread().
4236 	 */
4237 	VERIFY3U(RRSS_GET_OFFSET(&spa->spa_ubsync), ==,
4238 	    raidvd->vdev_ms_count << raidvd->vdev_ms_shift);
4239 
4240 	vre->vre_end_time = gethrestime_sec();
4241 	vre->vre_state = DSS_FINISHED;
4242 
4243 	uint64_t state = vre->vre_state;
4244 	VERIFY0(zap_update(spa->spa_meta_objset,
4245 	    vd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_STATE,
4246 	    sizeof (state), 1, &state, tx));
4247 
4248 	uint64_t end_time = vre->vre_end_time;
4249 	VERIFY0(zap_update(spa->spa_meta_objset,
4250 	    vd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_END_TIME,
4251 	    sizeof (end_time), 1, &end_time, tx));
4252 
4253 	spa->spa_uberblock.ub_raidz_reflow_info = 0;
4254 
4255 	spa_history_log_internal(spa, "raidz vdev expansion completed",  tx,
4256 	    "%s vdev %llu new width %llu", spa_name(spa),
4257 	    (unsigned long long)vd->vdev_id,
4258 	    (unsigned long long)vd->vdev_children);
4259 
4260 	spa->spa_raidz_expand = NULL;
4261 	raidvd->vdev_rz_expanding = B_FALSE;
4262 
4263 	spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
4264 	spa_async_request(spa, SPA_ASYNC_TRIM_RESTART);
4265 	spa_async_request(spa, SPA_ASYNC_AUTOTRIM_RESTART);
4266 
4267 	spa_notify_waiters(spa);
4268 
4269 	/*
4270 	 * While we're in syncing context take the opportunity to
4271 	 * setup a scrub. All the data has been sucessfully copied
4272 	 * but we have not validated any checksums.
4273 	 */
4274 	setup_sync_arg_t setup_sync_arg = {
4275 		.func = POOL_SCAN_SCRUB,
4276 		.txgstart = 0,
4277 		.txgend = 0,
4278 	};
4279 	if (zfs_scrub_after_expand &&
4280 	    dsl_scan_setup_check(&setup_sync_arg.func, tx) == 0) {
4281 		dsl_scan_setup_sync(&setup_sync_arg, tx);
4282 	}
4283 }
4284 
4285 /*
4286  * State of one copy batch.
4287  */
4288 typedef struct raidz_reflow_arg {
4289 	vdev_raidz_expand_t *rra_vre;	/* Global expantion state. */
4290 	zfs_locked_range_t *rra_lr;	/* Range lock of this batch. */
4291 	uint64_t rra_txg;	/* TXG of this batch. */
4292 	uint_t rra_ashift;	/* Ashift of the vdev. */
4293 	uint32_t rra_tbd;	/* Number of in-flight ZIOs. */
4294 	uint32_t rra_writes;	/* Number of write ZIOs. */
4295 	zio_t *rra_zio[];	/* Write ZIO pointers. */
4296 } raidz_reflow_arg_t;
4297 
4298 /*
4299  * Write of the new location on one child is done.  Once all of them are done
4300  * we can unlock and free everything.
4301  */
4302 static void
raidz_reflow_write_done(zio_t * zio)4303 raidz_reflow_write_done(zio_t *zio)
4304 {
4305 	raidz_reflow_arg_t *rra = zio->io_private;
4306 	vdev_raidz_expand_t *vre = rra->rra_vre;
4307 
4308 	abd_free(zio->io_abd);
4309 
4310 	mutex_enter(&vre->vre_lock);
4311 	if (zio->io_error != 0) {
4312 		/* Force a reflow pause on errors */
4313 		vre->vre_failed_offset =
4314 		    MIN(vre->vre_failed_offset, rra->rra_lr->lr_offset);
4315 	}
4316 	ASSERT3U(vre->vre_outstanding_bytes, >=, zio->io_size);
4317 	vre->vre_outstanding_bytes -= zio->io_size;
4318 	if (rra->rra_lr->lr_offset + rra->rra_lr->lr_length <
4319 	    vre->vre_failed_offset) {
4320 		vre->vre_bytes_copied_pertxg[rra->rra_txg & TXG_MASK] +=
4321 		    zio->io_size;
4322 	}
4323 	cv_signal(&vre->vre_cv);
4324 	boolean_t done = (--rra->rra_tbd == 0);
4325 	mutex_exit(&vre->vre_lock);
4326 
4327 	if (!done)
4328 		return;
4329 	spa_config_exit(zio->io_spa, SCL_STATE, zio->io_spa);
4330 	zfs_rangelock_exit(rra->rra_lr);
4331 	kmem_free(rra, sizeof (*rra) + sizeof (zio_t *) * rra->rra_writes);
4332 }
4333 
4334 /*
4335  * Read of the old location on one child is done.  Once all of them are done
4336  * writes should have all the data and we can issue them.
4337  */
4338 static void
raidz_reflow_read_done(zio_t * zio)4339 raidz_reflow_read_done(zio_t *zio)
4340 {
4341 	raidz_reflow_arg_t *rra = zio->io_private;
4342 	vdev_raidz_expand_t *vre = rra->rra_vre;
4343 
4344 	/* Reads of only one block use write ABDs.  For bigger free gangs. */
4345 	if (zio->io_size > (1 << rra->rra_ashift))
4346 		abd_free(zio->io_abd);
4347 
4348 	/*
4349 	 * If the read failed, or if it was done on a vdev that is not fully
4350 	 * healthy (e.g. a child that has a resilver in progress), we may not
4351 	 * have the correct data.  Note that it's OK if the write proceeds.
4352 	 * It may write garbage but the location is otherwise unused and we
4353 	 * will retry later due to vre_failed_offset.
4354 	 */
4355 	if (zio->io_error != 0 || !vdev_dtl_empty(zio->io_vd, DTL_MISSING)) {
4356 		zfs_dbgmsg("reflow read failed off=%llu size=%llu txg=%llu "
4357 		    "err=%u partial_dtl_empty=%u missing_dtl_empty=%u",
4358 		    (long long)rra->rra_lr->lr_offset,
4359 		    (long long)rra->rra_lr->lr_length,
4360 		    (long long)rra->rra_txg,
4361 		    zio->io_error,
4362 		    vdev_dtl_empty(zio->io_vd, DTL_PARTIAL),
4363 		    vdev_dtl_empty(zio->io_vd, DTL_MISSING));
4364 		mutex_enter(&vre->vre_lock);
4365 		/* Force a reflow pause on errors */
4366 		vre->vre_failed_offset =
4367 		    MIN(vre->vre_failed_offset, rra->rra_lr->lr_offset);
4368 		mutex_exit(&vre->vre_lock);
4369 	}
4370 
4371 	if (atomic_dec_32_nv(&rra->rra_tbd) > 0)
4372 		return;
4373 	uint32_t writes = rra->rra_tbd = rra->rra_writes;
4374 	for (uint64_t i = 0; i < writes; i++)
4375 		zio_nowait(rra->rra_zio[i]);
4376 }
4377 
4378 static void
raidz_reflow_record_progress(vdev_raidz_expand_t * vre,uint64_t offset,dmu_tx_t * tx)4379 raidz_reflow_record_progress(vdev_raidz_expand_t *vre, uint64_t offset,
4380     dmu_tx_t *tx)
4381 {
4382 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
4383 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4384 
4385 	if (offset == 0)
4386 		return;
4387 
4388 	mutex_enter(&vre->vre_lock);
4389 	ASSERT3U(vre->vre_offset, <=, offset);
4390 	vre->vre_offset = offset;
4391 	mutex_exit(&vre->vre_lock);
4392 
4393 	if (vre->vre_offset_pertxg[txgoff] == 0) {
4394 		dsl_sync_task_nowait(dmu_tx_pool(tx), raidz_reflow_sync,
4395 		    spa, tx);
4396 	}
4397 	vre->vre_offset_pertxg[txgoff] = offset;
4398 }
4399 
4400 static boolean_t
vdev_raidz_expand_child_replacing(vdev_t * raidz_vd)4401 vdev_raidz_expand_child_replacing(vdev_t *raidz_vd)
4402 {
4403 	for (int i = 0; i < raidz_vd->vdev_children; i++) {
4404 		/* Quick check if a child is being replaced */
4405 		if (!raidz_vd->vdev_child[i]->vdev_ops->vdev_op_leaf)
4406 			return (B_TRUE);
4407 	}
4408 	return (B_FALSE);
4409 }
4410 
4411 static boolean_t
raidz_reflow_impl(vdev_t * vd,vdev_raidz_expand_t * vre,zfs_range_tree_t * rt,dmu_tx_t * tx)4412 raidz_reflow_impl(vdev_t *vd, vdev_raidz_expand_t *vre, zfs_range_tree_t *rt,
4413     dmu_tx_t *tx)
4414 {
4415 	spa_t *spa = vd->vdev_spa;
4416 	uint_t ashift = vd->vdev_top->vdev_ashift;
4417 
4418 	zfs_range_seg_t *rs = zfs_range_tree_first(rt);
4419 	if (rt == NULL)
4420 		return (B_FALSE);
4421 	uint64_t offset = zfs_rs_get_start(rs, rt);
4422 	ASSERT(IS_P2ALIGNED(offset, 1 << ashift));
4423 	uint64_t size = zfs_rs_get_end(rs, rt) - offset;
4424 	ASSERT3U(size, >=, 1 << ashift);
4425 	ASSERT(IS_P2ALIGNED(size, 1 << ashift));
4426 
4427 	uint64_t blkid = offset >> ashift;
4428 	uint_t old_children = vd->vdev_children - 1;
4429 
4430 	/*
4431 	 * We can only progress to the point that writes will not overlap
4432 	 * with blocks whose progress has not yet been recorded on disk.
4433 	 * Since partially-copied rows are still read from the old location,
4434 	 * we need to stop one row before the sector-wise overlap, to prevent
4435 	 * row-wise overlap.
4436 	 *
4437 	 * Note that even if we are skipping over a large unallocated region,
4438 	 * we can't move the on-disk progress to `offset`, because concurrent
4439 	 * writes/allocations could still use the currently-unallocated
4440 	 * region.
4441 	 */
4442 	uint64_t ubsync_blkid =
4443 	    RRSS_GET_OFFSET(&spa->spa_ubsync) >> ashift;
4444 	uint64_t next_overwrite_blkid = ubsync_blkid +
4445 	    ubsync_blkid / old_children - old_children;
4446 	VERIFY3U(next_overwrite_blkid, >, ubsync_blkid);
4447 	if (blkid >= next_overwrite_blkid) {
4448 		raidz_reflow_record_progress(vre,
4449 		    next_overwrite_blkid << ashift, tx);
4450 		return (B_TRUE);
4451 	}
4452 
4453 	size = MIN(size, raidz_expand_max_copy_bytes);
4454 	size = MIN(size, (uint64_t)old_children *
4455 	    MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE));
4456 	size = MAX(size, 1 << ashift);
4457 	uint_t blocks = MIN(size >> ashift, next_overwrite_blkid - blkid);
4458 	size = (uint64_t)blocks << ashift;
4459 
4460 	zfs_range_tree_remove(rt, offset, size);
4461 
4462 	uint_t reads = MIN(blocks, old_children);
4463 	uint_t writes = MIN(blocks, vd->vdev_children);
4464 	raidz_reflow_arg_t *rra = kmem_zalloc(sizeof (*rra) +
4465 	    sizeof (zio_t *) * writes, KM_SLEEP);
4466 	rra->rra_vre = vre;
4467 	rra->rra_lr = zfs_rangelock_enter(&vre->vre_rangelock,
4468 	    offset, size, RL_WRITER);
4469 	rra->rra_txg = dmu_tx_get_txg(tx);
4470 	rra->rra_ashift = ashift;
4471 	rra->rra_tbd = reads;
4472 	rra->rra_writes = writes;
4473 
4474 	raidz_reflow_record_progress(vre, offset + size, tx);
4475 
4476 	/*
4477 	 * SCL_STATE will be released when the read and write are done,
4478 	 * by raidz_reflow_write_done().
4479 	 */
4480 	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4481 
4482 	/* check if a replacing vdev was added, if so treat it as an error */
4483 	if (vdev_raidz_expand_child_replacing(vd)) {
4484 		zfs_dbgmsg("replacing vdev encountered, reflow paused at "
4485 		    "offset=%llu txg=%llu",
4486 		    (long long)rra->rra_lr->lr_offset,
4487 		    (long long)rra->rra_txg);
4488 
4489 		mutex_enter(&vre->vre_lock);
4490 		vre->vre_failed_offset =
4491 		    MIN(vre->vre_failed_offset, rra->rra_lr->lr_offset);
4492 		cv_signal(&vre->vre_cv);
4493 		mutex_exit(&vre->vre_lock);
4494 
4495 		/* drop everything we acquired */
4496 		spa_config_exit(spa, SCL_STATE, spa);
4497 		zfs_rangelock_exit(rra->rra_lr);
4498 		kmem_free(rra, sizeof (*rra) + sizeof (zio_t *) * writes);
4499 		return (B_TRUE);
4500 	}
4501 
4502 	mutex_enter(&vre->vre_lock);
4503 	vre->vre_outstanding_bytes += size;
4504 	mutex_exit(&vre->vre_lock);
4505 
4506 	/* Allocate ABD and ZIO for each child we write. */
4507 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
4508 	zio_t *pio = spa->spa_txg_zio[txgoff];
4509 	uint_t b = blocks / vd->vdev_children;
4510 	uint_t bb = blocks % vd->vdev_children;
4511 	for (uint_t i = 0; i < writes; i++) {
4512 		uint_t n = b + (i < bb);
4513 		abd_t *abd = abd_alloc_for_io(n << ashift, B_FALSE);
4514 		rra->rra_zio[i] = zio_vdev_child_io(pio, NULL,
4515 		    vd->vdev_child[(blkid + i) % vd->vdev_children],
4516 		    ((blkid + i) / vd->vdev_children) << ashift,
4517 		    abd, n << ashift, ZIO_TYPE_WRITE, ZIO_PRIORITY_REMOVAL,
4518 		    ZIO_FLAG_CANFAIL, raidz_reflow_write_done, rra);
4519 	}
4520 
4521 	/*
4522 	 * Allocate and issue ZIO for each child we read.  For reads of only
4523 	 * one block we can use respective writer ABDs, since they will also
4524 	 * have only one block.  For bigger reads create gang ABDs and fill
4525 	 * them with respective blocks from writer ABDs.
4526 	 */
4527 	b = blocks / old_children;
4528 	bb = blocks % old_children;
4529 	for (uint_t i = 0; i < reads; i++) {
4530 		uint_t n = b + (i < bb);
4531 		abd_t *abd;
4532 		if (n > 1) {
4533 			abd = abd_alloc_gang();
4534 			for (uint_t j = 0; j < n; j++) {
4535 				uint_t b = j * old_children + i;
4536 				abd_t *cabd = abd_get_offset_size(
4537 				    rra->rra_zio[b % vd->vdev_children]->io_abd,
4538 				    (b / vd->vdev_children) << ashift,
4539 				    1 << ashift);
4540 				abd_gang_add(abd, cabd, B_TRUE);
4541 			}
4542 		} else {
4543 			abd = rra->rra_zio[i]->io_abd;
4544 		}
4545 		zio_nowait(zio_vdev_child_io(pio, NULL,
4546 		    vd->vdev_child[(blkid + i) % old_children],
4547 		    ((blkid + i) / old_children) << ashift, abd,
4548 		    n << ashift, ZIO_TYPE_READ, ZIO_PRIORITY_REMOVAL,
4549 		    ZIO_FLAG_CANFAIL, raidz_reflow_read_done, rra));
4550 	}
4551 
4552 	return (B_FALSE);
4553 }
4554 
4555 /*
4556  * For testing (ztest specific)
4557  */
4558 static void
raidz_expand_pause(uint_t pause_point)4559 raidz_expand_pause(uint_t pause_point)
4560 {
4561 	while (raidz_expand_pause_point != 0 &&
4562 	    raidz_expand_pause_point <= pause_point)
4563 		delay(hz);
4564 }
4565 
4566 static void
raidz_scratch_child_done(zio_t * zio)4567 raidz_scratch_child_done(zio_t *zio)
4568 {
4569 	zio_t *pio = zio->io_private;
4570 
4571 	mutex_enter(&pio->io_lock);
4572 	pio->io_error = zio_worst_error(pio->io_error, zio->io_error);
4573 	mutex_exit(&pio->io_lock);
4574 }
4575 
4576 /*
4577  * Reflow the beginning portion of the vdev into an intermediate scratch area
4578  * in memory and on disk. This operation must be persisted on disk before we
4579  * proceed to overwrite the beginning portion with the reflowed data.
4580  *
4581  * This multi-step task can fail to complete if disk errors are encountered
4582  * and we can return here after a pause (waiting for disk to become healthy).
4583  */
4584 static void
raidz_reflow_scratch_sync(void * arg,dmu_tx_t * tx)4585 raidz_reflow_scratch_sync(void *arg, dmu_tx_t *tx)
4586 {
4587 	vdev_raidz_expand_t *vre = arg;
4588 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4589 	zio_t *pio;
4590 	int error;
4591 
4592 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
4593 	vdev_t *raidvd = vdev_lookup_top(spa, vre->vre_vdev_id);
4594 	int ashift = raidvd->vdev_ashift;
4595 	uint64_t write_size = P2ALIGN_TYPED(VDEV_BOOT_SIZE, 1 << ashift,
4596 	    uint64_t);
4597 	uint64_t logical_size = write_size * raidvd->vdev_children;
4598 	uint64_t read_size =
4599 	    P2ROUNDUP(DIV_ROUND_UP(logical_size, (raidvd->vdev_children - 1)),
4600 	    1 << ashift);
4601 
4602 	/*
4603 	 * The scratch space must be large enough to get us to the point
4604 	 * that one row does not overlap itself when moved.  This is checked
4605 	 * by vdev_raidz_attach_check().
4606 	 */
4607 	VERIFY3U(write_size, >=, raidvd->vdev_children << ashift);
4608 	VERIFY3U(write_size, <=, VDEV_BOOT_SIZE);
4609 	VERIFY3U(write_size, <=, read_size);
4610 
4611 	zfs_locked_range_t *lr = zfs_rangelock_enter(&vre->vre_rangelock,
4612 	    0, logical_size, RL_WRITER);
4613 
4614 	abd_t **abds = kmem_alloc(raidvd->vdev_children * sizeof (abd_t *),
4615 	    KM_SLEEP);
4616 	for (int i = 0; i < raidvd->vdev_children; i++) {
4617 		abds[i] = abd_alloc_linear(read_size, B_FALSE);
4618 	}
4619 
4620 	raidz_expand_pause(RAIDZ_EXPAND_PAUSE_PRE_SCRATCH_1);
4621 
4622 	/*
4623 	 * If we have already written the scratch area then we must read from
4624 	 * there, since new writes were redirected there while we were paused
4625 	 * or the original location may have been partially overwritten with
4626 	 * reflowed data.
4627 	 */
4628 	if (RRSS_GET_STATE(&spa->spa_ubsync) == RRSS_SCRATCH_VALID) {
4629 		VERIFY3U(RRSS_GET_OFFSET(&spa->spa_ubsync), ==, logical_size);
4630 		/*
4631 		 * Read from scratch space.
4632 		 */
4633 		pio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
4634 		for (int i = 0; i < raidvd->vdev_children; i++) {
4635 			/*
4636 			 * Note: zio_vdev_child_io() adds VDEV_LABEL_START_SIZE
4637 			 * to the offset to calculate the physical offset to
4638 			 * write to.  Passing in a negative offset makes us
4639 			 * access the scratch area.
4640 			 */
4641 			zio_nowait(zio_vdev_child_io(pio, NULL,
4642 			    raidvd->vdev_child[i],
4643 			    VDEV_BOOT_OFFSET - VDEV_LABEL_START_SIZE, abds[i],
4644 			    write_size, ZIO_TYPE_READ, ZIO_PRIORITY_REMOVAL,
4645 			    ZIO_FLAG_CANFAIL, raidz_scratch_child_done, pio));
4646 		}
4647 		error = zio_wait(pio);
4648 		if (error != 0) {
4649 			zfs_dbgmsg("reflow: error %d reading scratch location",
4650 			    error);
4651 			goto io_error_exit;
4652 		}
4653 		goto overwrite;
4654 	}
4655 
4656 	/*
4657 	 * Read from original location.
4658 	 */
4659 	pio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
4660 	for (int i = 0; i < raidvd->vdev_children - 1; i++) {
4661 		ASSERT0(vdev_is_dead(raidvd->vdev_child[i]));
4662 		zio_nowait(zio_vdev_child_io(pio, NULL, raidvd->vdev_child[i],
4663 		    0, abds[i], read_size, ZIO_TYPE_READ,
4664 		    ZIO_PRIORITY_REMOVAL, ZIO_FLAG_CANFAIL,
4665 		    raidz_scratch_child_done, pio));
4666 	}
4667 	error = zio_wait(pio);
4668 	if (error != 0) {
4669 		zfs_dbgmsg("reflow: error %d reading original location", error);
4670 io_error_exit:
4671 		for (int i = 0; i < raidvd->vdev_children; i++)
4672 			abd_free(abds[i]);
4673 		kmem_free(abds, raidvd->vdev_children * sizeof (abd_t *));
4674 		zfs_rangelock_exit(lr);
4675 		spa_config_exit(spa, SCL_STATE, FTAG);
4676 		return;
4677 	}
4678 
4679 	raidz_expand_pause(RAIDZ_EXPAND_PAUSE_PRE_SCRATCH_2);
4680 
4681 	/*
4682 	 * Reflow in memory.
4683 	 */
4684 	uint64_t logical_sectors = logical_size >> ashift;
4685 	for (int i = raidvd->vdev_children - 1; i < logical_sectors; i++) {
4686 		int oldchild = i % (raidvd->vdev_children - 1);
4687 		uint64_t oldoff = (i / (raidvd->vdev_children - 1)) << ashift;
4688 
4689 		int newchild = i % raidvd->vdev_children;
4690 		uint64_t newoff = (i / raidvd->vdev_children) << ashift;
4691 
4692 		/* a single sector should not be copying over itself */
4693 		ASSERT(!(newchild == oldchild && newoff == oldoff));
4694 
4695 		abd_copy_off(abds[newchild], abds[oldchild],
4696 		    newoff, oldoff, 1 << ashift);
4697 	}
4698 
4699 	/*
4700 	 * Verify that we filled in everything we intended to (write_size on
4701 	 * each child).
4702 	 */
4703 	VERIFY0(logical_sectors % raidvd->vdev_children);
4704 	VERIFY3U((logical_sectors / raidvd->vdev_children) << ashift, ==,
4705 	    write_size);
4706 
4707 	/*
4708 	 * Write to scratch location (boot area).
4709 	 */
4710 	pio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
4711 	for (int i = 0; i < raidvd->vdev_children; i++) {
4712 		/*
4713 		 * Note: zio_vdev_child_io() adds VDEV_LABEL_START_SIZE to
4714 		 * the offset to calculate the physical offset to write to.
4715 		 * Passing in a negative offset lets us access the boot area.
4716 		 */
4717 		zio_nowait(zio_vdev_child_io(pio, NULL, raidvd->vdev_child[i],
4718 		    VDEV_BOOT_OFFSET - VDEV_LABEL_START_SIZE, abds[i],
4719 		    write_size, ZIO_TYPE_WRITE, ZIO_PRIORITY_REMOVAL,
4720 		    ZIO_FLAG_CANFAIL, raidz_scratch_child_done, pio));
4721 	}
4722 	error = zio_wait(pio);
4723 	if (error != 0) {
4724 		zfs_dbgmsg("reflow: error %d writing scratch location", error);
4725 		goto io_error_exit;
4726 	}
4727 	pio = zio_root(spa, NULL, NULL, 0);
4728 	zio_flush(pio, raidvd);
4729 	zio_wait(pio);
4730 
4731 	zfs_dbgmsg("reflow: wrote %llu bytes (logical) to scratch area",
4732 	    (long long)logical_size);
4733 
4734 	raidz_expand_pause(RAIDZ_EXPAND_PAUSE_PRE_SCRATCH_3);
4735 
4736 	/*
4737 	 * Update uberblock to indicate that scratch space is valid.  This is
4738 	 * needed because after this point, the real location may be
4739 	 * overwritten.  If we crash, we need to get the data from the
4740 	 * scratch space, rather than the real location.
4741 	 *
4742 	 * Note: ub_timestamp is bumped so that vdev_uberblock_compare()
4743 	 * will prefer this uberblock.
4744 	 */
4745 	RAIDZ_REFLOW_SET(&spa->spa_ubsync, RRSS_SCRATCH_VALID, logical_size);
4746 	spa->spa_ubsync.ub_timestamp++;
4747 	ASSERT0(vdev_uberblock_sync_list(&spa->spa_root_vdev, 1,
4748 	    &spa->spa_ubsync, ZIO_FLAG_CONFIG_WRITER));
4749 	if (spa_multihost(spa))
4750 		mmp_update_uberblock(spa, &spa->spa_ubsync);
4751 
4752 	zfs_dbgmsg("reflow: uberblock updated "
4753 	    "(txg %llu, SCRATCH_VALID, size %llu, ts %llu)",
4754 	    (long long)spa->spa_ubsync.ub_txg,
4755 	    (long long)logical_size,
4756 	    (long long)spa->spa_ubsync.ub_timestamp);
4757 
4758 	raidz_expand_pause(RAIDZ_EXPAND_PAUSE_SCRATCH_VALID);
4759 
4760 	/*
4761 	 * Overwrite with reflow'ed data.
4762 	 */
4763 overwrite:
4764 	pio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
4765 	for (int i = 0; i < raidvd->vdev_children; i++) {
4766 		zio_nowait(zio_vdev_child_io(pio, NULL, raidvd->vdev_child[i],
4767 		    0, abds[i], write_size, ZIO_TYPE_WRITE,
4768 		    ZIO_PRIORITY_REMOVAL, ZIO_FLAG_CANFAIL,
4769 		    raidz_scratch_child_done, pio));
4770 	}
4771 	error = zio_wait(pio);
4772 	if (error != 0) {
4773 		/*
4774 		 * When we exit early here and drop the range lock, new
4775 		 * writes will go into the scratch area so we'll need to
4776 		 * read from there when we return after pausing.
4777 		 */
4778 		zfs_dbgmsg("reflow: error %d writing real location", error);
4779 		/*
4780 		 * Update the uberblock that is written when this txg completes.
4781 		 */
4782 		RAIDZ_REFLOW_SET(&spa->spa_uberblock, RRSS_SCRATCH_VALID,
4783 		    logical_size);
4784 		goto io_error_exit;
4785 	}
4786 	pio = zio_root(spa, NULL, NULL, 0);
4787 	zio_flush(pio, raidvd);
4788 	zio_wait(pio);
4789 
4790 	zfs_dbgmsg("reflow: overwrote %llu bytes (logical) to real location",
4791 	    (long long)logical_size);
4792 	for (int i = 0; i < raidvd->vdev_children; i++)
4793 		abd_free(abds[i]);
4794 	kmem_free(abds, raidvd->vdev_children * sizeof (abd_t *));
4795 
4796 	raidz_expand_pause(RAIDZ_EXPAND_PAUSE_SCRATCH_REFLOWED);
4797 
4798 	/*
4799 	 * Update uberblock to indicate that the initial part has been
4800 	 * reflow'ed.  This is needed because after this point (when we exit
4801 	 * the rangelock), we allow regular writes to this region, which will
4802 	 * be written to the new location only (because reflow_offset_next ==
4803 	 * reflow_offset_synced).  If we crashed and re-copied from the
4804 	 * scratch space, we would lose the regular writes.
4805 	 */
4806 	RAIDZ_REFLOW_SET(&spa->spa_ubsync, RRSS_SCRATCH_INVALID_SYNCED,
4807 	    logical_size);
4808 	spa->spa_ubsync.ub_timestamp++;
4809 	ASSERT0(vdev_uberblock_sync_list(&spa->spa_root_vdev, 1,
4810 	    &spa->spa_ubsync, ZIO_FLAG_CONFIG_WRITER));
4811 	if (spa_multihost(spa))
4812 		mmp_update_uberblock(spa, &spa->spa_ubsync);
4813 
4814 	zfs_dbgmsg("reflow: uberblock updated "
4815 	    "(txg %llu, SCRATCH_NOT_IN_USE, size %llu, ts %llu)",
4816 	    (long long)spa->spa_ubsync.ub_txg,
4817 	    (long long)logical_size,
4818 	    (long long)spa->spa_ubsync.ub_timestamp);
4819 
4820 	raidz_expand_pause(RAIDZ_EXPAND_PAUSE_SCRATCH_POST_REFLOW_1);
4821 
4822 	/*
4823 	 * Update progress.
4824 	 */
4825 	vre->vre_offset = logical_size;
4826 	zfs_rangelock_exit(lr);
4827 	spa_config_exit(spa, SCL_STATE, FTAG);
4828 
4829 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
4830 	vre->vre_offset_pertxg[txgoff] = vre->vre_offset;
4831 	vre->vre_bytes_copied_pertxg[txgoff] = vre->vre_bytes_copied;
4832 	/*
4833 	 * Note - raidz_reflow_sync() will update the uberblock state to
4834 	 * RRSS_SCRATCH_INVALID_SYNCED_REFLOW
4835 	 */
4836 	raidz_reflow_sync(spa, tx);
4837 
4838 	raidz_expand_pause(RAIDZ_EXPAND_PAUSE_SCRATCH_POST_REFLOW_2);
4839 }
4840 
4841 /*
4842  * We crashed in the middle of raidz_reflow_scratch_sync(); complete its work
4843  * here.  No other i/o can be in progress, so we don't need the vre_rangelock.
4844  */
4845 void
vdev_raidz_reflow_copy_scratch(spa_t * spa)4846 vdev_raidz_reflow_copy_scratch(spa_t *spa)
4847 {
4848 	vdev_raidz_expand_t *vre = spa->spa_raidz_expand;
4849 	uint64_t logical_size = RRSS_GET_OFFSET(&spa->spa_uberblock);
4850 	ASSERT3U(RRSS_GET_STATE(&spa->spa_uberblock), ==, RRSS_SCRATCH_VALID);
4851 
4852 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
4853 	vdev_t *raidvd = vdev_lookup_top(spa, vre->vre_vdev_id);
4854 	ASSERT0(logical_size % raidvd->vdev_children);
4855 	uint64_t write_size = logical_size / raidvd->vdev_children;
4856 
4857 	zio_t *pio;
4858 
4859 	/*
4860 	 * Read from scratch space.
4861 	 */
4862 	abd_t **abds = kmem_alloc(raidvd->vdev_children * sizeof (abd_t *),
4863 	    KM_SLEEP);
4864 	for (int i = 0; i < raidvd->vdev_children; i++) {
4865 		abds[i] = abd_alloc_linear(write_size, B_FALSE);
4866 	}
4867 
4868 	pio = zio_root(spa, NULL, NULL, 0);
4869 	for (int i = 0; i < raidvd->vdev_children; i++) {
4870 		/*
4871 		 * Note: zio_vdev_child_io() adds VDEV_LABEL_START_SIZE to
4872 		 * the offset to calculate the physical offset to write to.
4873 		 * Passing in a negative offset lets us access the boot area.
4874 		 */
4875 		zio_nowait(zio_vdev_child_io(pio, NULL, raidvd->vdev_child[i],
4876 		    VDEV_BOOT_OFFSET - VDEV_LABEL_START_SIZE, abds[i],
4877 		    write_size, ZIO_TYPE_READ, ZIO_PRIORITY_REMOVAL, 0,
4878 		    raidz_scratch_child_done, pio));
4879 	}
4880 	zio_wait(pio);
4881 
4882 	/*
4883 	 * Overwrite real location with reflow'ed data.
4884 	 */
4885 	pio = zio_root(spa, NULL, NULL, 0);
4886 	for (int i = 0; i < raidvd->vdev_children; i++) {
4887 		zio_nowait(zio_vdev_child_io(pio, NULL, raidvd->vdev_child[i],
4888 		    0, abds[i], write_size, ZIO_TYPE_WRITE,
4889 		    ZIO_PRIORITY_REMOVAL, 0,
4890 		    raidz_scratch_child_done, pio));
4891 	}
4892 	zio_wait(pio);
4893 	pio = zio_root(spa, NULL, NULL, 0);
4894 	zio_flush(pio, raidvd);
4895 	zio_wait(pio);
4896 
4897 	zfs_dbgmsg("reflow recovery: overwrote %llu bytes (logical) "
4898 	    "to real location", (long long)logical_size);
4899 
4900 	for (int i = 0; i < raidvd->vdev_children; i++)
4901 		abd_free(abds[i]);
4902 	kmem_free(abds, raidvd->vdev_children * sizeof (abd_t *));
4903 
4904 	/*
4905 	 * Update uberblock.
4906 	 */
4907 	RAIDZ_REFLOW_SET(&spa->spa_ubsync,
4908 	    RRSS_SCRATCH_INVALID_SYNCED_ON_IMPORT, logical_size);
4909 	spa->spa_ubsync.ub_timestamp++;
4910 	VERIFY0(vdev_uberblock_sync_list(&spa->spa_root_vdev, 1,
4911 	    &spa->spa_ubsync, ZIO_FLAG_CONFIG_WRITER));
4912 	if (spa_multihost(spa))
4913 		mmp_update_uberblock(spa, &spa->spa_ubsync);
4914 
4915 	zfs_dbgmsg("reflow recovery: uberblock updated "
4916 	    "(txg %llu, SCRATCH_NOT_IN_USE, size %llu, ts %llu)",
4917 	    (long long)spa->spa_ubsync.ub_txg,
4918 	    (long long)logical_size,
4919 	    (long long)spa->spa_ubsync.ub_timestamp);
4920 
4921 	dmu_tx_t *tx = dmu_tx_create_assigned(spa->spa_dsl_pool,
4922 	    spa_first_txg(spa));
4923 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
4924 	vre->vre_offset = logical_size;
4925 	vre->vre_offset_pertxg[txgoff] = vre->vre_offset;
4926 	vre->vre_bytes_copied_pertxg[txgoff] = vre->vre_bytes_copied;
4927 	/*
4928 	 * Note that raidz_reflow_sync() will update the uberblock once more
4929 	 */
4930 	raidz_reflow_sync(spa, tx);
4931 
4932 	dmu_tx_commit(tx);
4933 
4934 	spa_config_exit(spa, SCL_STATE, FTAG);
4935 }
4936 
4937 static boolean_t
spa_raidz_expand_thread_check(void * arg,zthr_t * zthr)4938 spa_raidz_expand_thread_check(void *arg, zthr_t *zthr)
4939 {
4940 	(void) zthr;
4941 	spa_t *spa = arg;
4942 
4943 	return (spa->spa_raidz_expand != NULL &&
4944 	    !spa->spa_raidz_expand->vre_waiting_for_resilver);
4945 }
4946 
4947 /*
4948  * RAIDZ expansion background thread
4949  *
4950  * Can be called multiple times if the reflow is paused
4951  */
4952 static void
spa_raidz_expand_thread(void * arg,zthr_t * zthr)4953 spa_raidz_expand_thread(void *arg, zthr_t *zthr)
4954 {
4955 	spa_t *spa = arg;
4956 	vdev_raidz_expand_t *vre = spa->spa_raidz_expand;
4957 
4958 	if (RRSS_GET_STATE(&spa->spa_ubsync) == RRSS_SCRATCH_VALID)
4959 		vre->vre_offset = 0;
4960 	else
4961 		vre->vre_offset = RRSS_GET_OFFSET(&spa->spa_ubsync);
4962 
4963 	/* Reflow the beginning portion using the scratch area */
4964 	if (vre->vre_offset == 0) {
4965 		VERIFY0(dsl_sync_task(spa_name(spa),
4966 		    NULL, raidz_reflow_scratch_sync,
4967 		    vre, 0, ZFS_SPACE_CHECK_NONE));
4968 
4969 		/* if we encountered errors then pause */
4970 		if (vre->vre_offset == 0) {
4971 			mutex_enter(&vre->vre_lock);
4972 			vre->vre_waiting_for_resilver = B_TRUE;
4973 			mutex_exit(&vre->vre_lock);
4974 			return;
4975 		}
4976 	}
4977 
4978 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4979 	vdev_t *raidvd = vdev_lookup_top(spa, vre->vre_vdev_id);
4980 
4981 	uint64_t guid = raidvd->vdev_guid;
4982 
4983 	/* Iterate over all the remaining metaslabs */
4984 	for (uint64_t i = vre->vre_offset >> raidvd->vdev_ms_shift;
4985 	    i < raidvd->vdev_ms_count &&
4986 	    !zthr_iscancelled(zthr) &&
4987 	    vre->vre_failed_offset == UINT64_MAX; i++) {
4988 		metaslab_t *msp = raidvd->vdev_ms[i];
4989 
4990 		metaslab_disable(msp);
4991 		mutex_enter(&msp->ms_lock);
4992 
4993 		/*
4994 		 * The metaslab may be newly created (for the expanded
4995 		 * space), in which case its trees won't exist yet,
4996 		 * so we need to bail out early.
4997 		 */
4998 		if (msp->ms_new) {
4999 			mutex_exit(&msp->ms_lock);
5000 			metaslab_enable(msp, B_FALSE, B_FALSE);
5001 			continue;
5002 		}
5003 
5004 		VERIFY0(metaslab_load(msp));
5005 
5006 		/*
5007 		 * We want to copy everything except the free (allocatable)
5008 		 * space.  Note that there may be a little bit more free
5009 		 * space (e.g. in ms_defer), and it's fine to copy that too.
5010 		 */
5011 		uint64_t shift, start;
5012 		zfs_range_seg_type_t type = metaslab_calculate_range_tree_type(
5013 		    raidvd, msp, &start, &shift);
5014 		zfs_range_tree_t *rt = zfs_range_tree_create_flags(
5015 		    NULL, type, NULL, start, shift, ZFS_RT_F_DYN_NAME,
5016 		    metaslab_rt_name(msp->ms_group, msp,
5017 		    "spa_raidz_expand_thread:rt"));
5018 		zfs_range_tree_add(rt, msp->ms_start, msp->ms_size);
5019 		zfs_range_tree_walk(msp->ms_allocatable, zfs_range_tree_remove,
5020 		    rt);
5021 		mutex_exit(&msp->ms_lock);
5022 
5023 		/*
5024 		 * Force the last sector of each metaslab to be copied.  This
5025 		 * ensures that we advance the on-disk progress to the end of
5026 		 * this metaslab while the metaslab is disabled.  Otherwise, we
5027 		 * could move past this metaslab without advancing the on-disk
5028 		 * progress, and then an allocation to this metaslab would not
5029 		 * be copied.
5030 		 */
5031 		int sectorsz = 1 << raidvd->vdev_ashift;
5032 		uint64_t ms_last_offset = msp->ms_start +
5033 		    msp->ms_size - sectorsz;
5034 		if (!zfs_range_tree_contains(rt, ms_last_offset, sectorsz)) {
5035 			zfs_range_tree_add(rt, ms_last_offset, sectorsz);
5036 		}
5037 
5038 		/*
5039 		 * When we are resuming from a paused expansion (i.e.
5040 		 * when importing a pool with a expansion in progress),
5041 		 * discard any state that we have already processed.
5042 		 */
5043 		if (vre->vre_offset > msp->ms_start) {
5044 			zfs_range_tree_clear(rt, msp->ms_start,
5045 			    vre->vre_offset - msp->ms_start);
5046 		}
5047 
5048 		while (!zthr_iscancelled(zthr) &&
5049 		    !zfs_range_tree_is_empty(rt) &&
5050 		    vre->vre_failed_offset == UINT64_MAX) {
5051 
5052 			/*
5053 			 * We need to periodically drop the config lock so that
5054 			 * writers can get in.  Additionally, we can't wait
5055 			 * for a txg to sync while holding a config lock
5056 			 * (since a waiting writer could cause a 3-way deadlock
5057 			 * with the sync thread, which also gets a config
5058 			 * lock for reader).  So we can't hold the config lock
5059 			 * while calling dmu_tx_assign().
5060 			 */
5061 			spa_config_exit(spa, SCL_CONFIG, FTAG);
5062 
5063 			/*
5064 			 * If requested, pause the reflow when the amount
5065 			 * specified by raidz_expand_max_reflow_bytes is reached
5066 			 *
5067 			 * This pause is only used during testing or debugging.
5068 			 */
5069 			while (raidz_expand_max_reflow_bytes != 0 &&
5070 			    raidz_expand_max_reflow_bytes <=
5071 			    vre->vre_bytes_copied && !zthr_iscancelled(zthr)) {
5072 				delay(hz);
5073 			}
5074 
5075 			mutex_enter(&vre->vre_lock);
5076 			while (vre->vre_outstanding_bytes >
5077 			    raidz_expand_max_copy_bytes) {
5078 				cv_wait(&vre->vre_cv, &vre->vre_lock);
5079 			}
5080 			mutex_exit(&vre->vre_lock);
5081 
5082 			dmu_tx_t *tx =
5083 			    dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
5084 
5085 			VERIFY0(dmu_tx_assign(tx,
5086 			    DMU_TX_WAIT | DMU_TX_SUSPEND));
5087 			uint64_t txg = dmu_tx_get_txg(tx);
5088 
5089 			/*
5090 			 * Reacquire the vdev_config lock.  Theoretically, the
5091 			 * vdev_t that we're expanding may have changed.
5092 			 */
5093 			spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5094 			raidvd = vdev_lookup_top(spa, vre->vre_vdev_id);
5095 
5096 			boolean_t needsync =
5097 			    raidz_reflow_impl(raidvd, vre, rt, tx);
5098 
5099 			dmu_tx_commit(tx);
5100 
5101 			if (needsync) {
5102 				spa_config_exit(spa, SCL_CONFIG, FTAG);
5103 				txg_wait_synced(spa->spa_dsl_pool, txg);
5104 				spa_config_enter(spa, SCL_CONFIG, FTAG,
5105 				    RW_READER);
5106 			}
5107 		}
5108 
5109 		spa_config_exit(spa, SCL_CONFIG, FTAG);
5110 
5111 		metaslab_enable(msp, B_FALSE, B_FALSE);
5112 		zfs_range_tree_vacate(rt, NULL, NULL);
5113 		zfs_range_tree_destroy(rt);
5114 
5115 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
5116 		raidvd = vdev_lookup_top(spa, vre->vre_vdev_id);
5117 	}
5118 
5119 	spa_config_exit(spa, SCL_CONFIG, FTAG);
5120 
5121 	/*
5122 	 * The txg_wait_synced() here ensures that all reflow zio's have
5123 	 * completed, and vre_failed_offset has been set if necessary.  It
5124 	 * also ensures that the progress of the last raidz_reflow_sync() is
5125 	 * written to disk before raidz_reflow_complete_sync() changes the
5126 	 * in-memory vre_state.  vdev_raidz_io_start() uses vre_state to
5127 	 * determine if a reflow is in progress, in which case we may need to
5128 	 * write to both old and new locations.  Therefore we can only change
5129 	 * vre_state once this is not necessary, which is once the on-disk
5130 	 * progress (in spa_ubsync) has been set past any possible writes (to
5131 	 * the end of the last metaslab).
5132 	 */
5133 	txg_wait_synced(spa->spa_dsl_pool, 0);
5134 
5135 	if (!zthr_iscancelled(zthr) &&
5136 	    vre->vre_offset == raidvd->vdev_ms_count << raidvd->vdev_ms_shift) {
5137 		/*
5138 		 * We are not being canceled or paused, so the reflow must be
5139 		 * complete. In that case also mark it as completed on disk.
5140 		 */
5141 		ASSERT3U(vre->vre_failed_offset, ==, UINT64_MAX);
5142 		VERIFY0(dsl_sync_task(spa_name(spa), NULL,
5143 		    raidz_reflow_complete_sync, spa,
5144 		    0, ZFS_SPACE_CHECK_NONE));
5145 		(void) vdev_online(spa, guid, ZFS_ONLINE_EXPAND, NULL);
5146 	} else {
5147 		/*
5148 		 * Wait for all copy zio's to complete and for all the
5149 		 * raidz_reflow_sync() synctasks to be run.
5150 		 */
5151 		spa_history_log_internal(spa, "reflow pause",
5152 		    NULL, "offset=%llu failed_offset=%lld",
5153 		    (long long)vre->vre_offset,
5154 		    (long long)vre->vre_failed_offset);
5155 		mutex_enter(&vre->vre_lock);
5156 		if (vre->vre_failed_offset != UINT64_MAX) {
5157 			/*
5158 			 * Reset progress so that we will retry everything
5159 			 * after the point that something failed.
5160 			 */
5161 			vre->vre_offset = vre->vre_failed_offset;
5162 			vre->vre_failed_offset = UINT64_MAX;
5163 			vre->vre_waiting_for_resilver = B_TRUE;
5164 		}
5165 		mutex_exit(&vre->vre_lock);
5166 	}
5167 }
5168 
5169 void
spa_start_raidz_expansion_thread(spa_t * spa)5170 spa_start_raidz_expansion_thread(spa_t *spa)
5171 {
5172 	ASSERT0P(spa->spa_raidz_expand_zthr);
5173 	spa->spa_raidz_expand_zthr = zthr_create("raidz_expand",
5174 	    spa_raidz_expand_thread_check, spa_raidz_expand_thread,
5175 	    spa, defclsyspri);
5176 }
5177 
5178 void
raidz_dtl_reassessed(vdev_t * vd)5179 raidz_dtl_reassessed(vdev_t *vd)
5180 {
5181 	spa_t *spa = vd->vdev_spa;
5182 	if (spa->spa_raidz_expand != NULL) {
5183 		vdev_raidz_expand_t *vre = spa->spa_raidz_expand;
5184 		/*
5185 		 * we get called often from vdev_dtl_reassess() so make
5186 		 * sure it's our vdev and any replacing is complete
5187 		 */
5188 		if (vd->vdev_top->vdev_id == vre->vre_vdev_id &&
5189 		    !vdev_raidz_expand_child_replacing(vd->vdev_top)) {
5190 			mutex_enter(&vre->vre_lock);
5191 			if (vre->vre_waiting_for_resilver) {
5192 				vdev_dbgmsg(vd, "DTL reassessed, "
5193 				    "continuing raidz expansion");
5194 				vre->vre_waiting_for_resilver = B_FALSE;
5195 				zthr_wakeup(spa->spa_raidz_expand_zthr);
5196 			}
5197 			mutex_exit(&vre->vre_lock);
5198 		}
5199 	}
5200 }
5201 
5202 int
vdev_raidz_attach_check(vdev_t * new_child)5203 vdev_raidz_attach_check(vdev_t *new_child)
5204 {
5205 	vdev_t *raidvd = new_child->vdev_parent;
5206 	uint64_t new_children = raidvd->vdev_children;
5207 
5208 	/*
5209 	 * We use the "boot" space as scratch space to handle overwriting the
5210 	 * initial part of the vdev.  If it is too small, then this expansion
5211 	 * is not allowed.  This would be very unusual (e.g. ashift > 13 and
5212 	 * >200 children).
5213 	 */
5214 	if (new_children << raidvd->vdev_ashift > VDEV_BOOT_SIZE) {
5215 		return (EINVAL);
5216 	}
5217 	return (0);
5218 }
5219 
5220 void
vdev_raidz_attach_sync(void * arg,dmu_tx_t * tx)5221 vdev_raidz_attach_sync(void *arg, dmu_tx_t *tx)
5222 {
5223 	vdev_t *new_child = arg;
5224 	spa_t *spa = new_child->vdev_spa;
5225 	vdev_t *raidvd = new_child->vdev_parent;
5226 	vdev_raidz_t *vdrz = raidvd->vdev_tsd;
5227 	ASSERT3P(raidvd->vdev_ops, ==, &vdev_raidz_ops);
5228 	ASSERT3P(raidvd->vdev_top, ==, raidvd);
5229 	ASSERT3U(raidvd->vdev_children, >, vdrz->vd_original_width);
5230 	ASSERT3U(raidvd->vdev_children, ==, vdrz->vd_physical_width + 1);
5231 	ASSERT3P(raidvd->vdev_child[raidvd->vdev_children - 1], ==,
5232 	    new_child);
5233 
5234 	spa_feature_incr(spa, SPA_FEATURE_RAIDZ_EXPANSION, tx);
5235 
5236 	vdrz->vd_physical_width++;
5237 
5238 	VERIFY0(spa->spa_uberblock.ub_raidz_reflow_info);
5239 	vdrz->vn_vre.vre_vdev_id = raidvd->vdev_id;
5240 	vdrz->vn_vre.vre_offset = 0;
5241 	vdrz->vn_vre.vre_failed_offset = UINT64_MAX;
5242 	spa->spa_raidz_expand = &vdrz->vn_vre;
5243 	zthr_wakeup(spa->spa_raidz_expand_zthr);
5244 
5245 	/*
5246 	 * Dirty the config so that ZPOOL_CONFIG_RAIDZ_EXPANDING will get
5247 	 * written to the config.
5248 	 */
5249 	vdev_config_dirty(raidvd);
5250 
5251 	vdrz->vn_vre.vre_start_time = gethrestime_sec();
5252 	vdrz->vn_vre.vre_end_time = 0;
5253 	vdrz->vn_vre.vre_state = DSS_SCANNING;
5254 	vdrz->vn_vre.vre_bytes_copied = 0;
5255 
5256 	uint64_t state = vdrz->vn_vre.vre_state;
5257 	VERIFY0(zap_update(spa->spa_meta_objset,
5258 	    raidvd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_STATE,
5259 	    sizeof (state), 1, &state, tx));
5260 
5261 	uint64_t start_time = vdrz->vn_vre.vre_start_time;
5262 	VERIFY0(zap_update(spa->spa_meta_objset,
5263 	    raidvd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_START_TIME,
5264 	    sizeof (start_time), 1, &start_time, tx));
5265 
5266 	(void) zap_remove(spa->spa_meta_objset,
5267 	    raidvd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_END_TIME, tx);
5268 	(void) zap_remove(spa->spa_meta_objset,
5269 	    raidvd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_BYTES_COPIED, tx);
5270 
5271 	spa_history_log_internal(spa, "raidz vdev expansion started",  tx,
5272 	    "%s vdev %llu new width %llu", spa_name(spa),
5273 	    (unsigned long long)raidvd->vdev_id,
5274 	    (unsigned long long)raidvd->vdev_children);
5275 }
5276 
5277 int
vdev_raidz_load(vdev_t * vd)5278 vdev_raidz_load(vdev_t *vd)
5279 {
5280 	vdev_raidz_t *vdrz = vd->vdev_tsd;
5281 	int err;
5282 
5283 	uint64_t state = DSS_NONE;
5284 	uint64_t start_time = 0;
5285 	uint64_t end_time = 0;
5286 	uint64_t bytes_copied = 0;
5287 
5288 	if (vd->vdev_top_zap != 0) {
5289 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
5290 		    vd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_STATE,
5291 		    sizeof (state), 1, &state);
5292 		if (err != 0 && err != ENOENT)
5293 			return (err);
5294 
5295 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
5296 		    vd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_START_TIME,
5297 		    sizeof (start_time), 1, &start_time);
5298 		if (err != 0 && err != ENOENT)
5299 			return (err);
5300 
5301 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
5302 		    vd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_END_TIME,
5303 		    sizeof (end_time), 1, &end_time);
5304 		if (err != 0 && err != ENOENT)
5305 			return (err);
5306 
5307 		err = zap_lookup(vd->vdev_spa->spa_meta_objset,
5308 		    vd->vdev_top_zap, VDEV_TOP_ZAP_RAIDZ_EXPAND_BYTES_COPIED,
5309 		    sizeof (bytes_copied), 1, &bytes_copied);
5310 		if (err != 0 && err != ENOENT)
5311 			return (err);
5312 	}
5313 
5314 	/*
5315 	 * If we are in the middle of expansion, vre_state should have
5316 	 * already been set by vdev_raidz_init().
5317 	 */
5318 	EQUIV(vdrz->vn_vre.vre_state == DSS_SCANNING, state == DSS_SCANNING);
5319 	vdrz->vn_vre.vre_state = (dsl_scan_state_t)state;
5320 	vdrz->vn_vre.vre_start_time = start_time;
5321 	vdrz->vn_vre.vre_end_time = end_time;
5322 	vdrz->vn_vre.vre_bytes_copied = bytes_copied;
5323 
5324 	return (0);
5325 }
5326 
5327 int
spa_raidz_expand_get_stats(spa_t * spa,pool_raidz_expand_stat_t * pres)5328 spa_raidz_expand_get_stats(spa_t *spa, pool_raidz_expand_stat_t *pres)
5329 {
5330 	vdev_raidz_expand_t *vre = spa->spa_raidz_expand;
5331 
5332 	if (vre == NULL) {
5333 		/* no removal in progress; find most recent completed */
5334 		for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++) {
5335 			vdev_t *vd = spa->spa_root_vdev->vdev_child[c];
5336 			if (vd->vdev_ops == &vdev_raidz_ops) {
5337 				vdev_raidz_t *vdrz = vd->vdev_tsd;
5338 
5339 				if (vdrz->vn_vre.vre_end_time != 0 &&
5340 				    (vre == NULL ||
5341 				    vdrz->vn_vre.vre_end_time >
5342 				    vre->vre_end_time)) {
5343 					vre = &vdrz->vn_vre;
5344 				}
5345 			}
5346 		}
5347 	}
5348 
5349 	if (vre == NULL) {
5350 		return (SET_ERROR(ENOENT));
5351 	}
5352 
5353 	pres->pres_state = vre->vre_state;
5354 	pres->pres_expanding_vdev = vre->vre_vdev_id;
5355 
5356 	vdev_t *vd = vdev_lookup_top(spa, vre->vre_vdev_id);
5357 	pres->pres_to_reflow = vd->vdev_stat.vs_alloc;
5358 
5359 	mutex_enter(&vre->vre_lock);
5360 	pres->pres_reflowed = vre->vre_bytes_copied;
5361 	for (int i = 0; i < TXG_SIZE; i++)
5362 		pres->pres_reflowed += vre->vre_bytes_copied_pertxg[i];
5363 	mutex_exit(&vre->vre_lock);
5364 
5365 	pres->pres_start_time = vre->vre_start_time;
5366 	pres->pres_end_time = vre->vre_end_time;
5367 	pres->pres_waiting_for_resilver = vre->vre_waiting_for_resilver;
5368 
5369 	return (0);
5370 }
5371 
5372 /*
5373  * Initialize private RAIDZ specific fields from the nvlist.
5374  */
5375 static int
vdev_raidz_init(spa_t * spa,nvlist_t * nv,void ** tsd)5376 vdev_raidz_init(spa_t *spa, nvlist_t *nv, void **tsd)
5377 {
5378 	uint_t children;
5379 	nvlist_t **child;
5380 	int error = nvlist_lookup_nvlist_array(nv,
5381 	    ZPOOL_CONFIG_CHILDREN, &child, &children);
5382 	if (error != 0)
5383 		return (SET_ERROR(EINVAL));
5384 
5385 	uint64_t nparity;
5386 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY, &nparity) == 0) {
5387 		if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
5388 			return (SET_ERROR(EINVAL));
5389 
5390 		/*
5391 		 * Previous versions could only support 1 or 2 parity
5392 		 * device.
5393 		 */
5394 		if (nparity > 1 && spa_version(spa) < SPA_VERSION_RAIDZ2)
5395 			return (SET_ERROR(EINVAL));
5396 		else if (nparity > 2 && spa_version(spa) < SPA_VERSION_RAIDZ3)
5397 			return (SET_ERROR(EINVAL));
5398 	} else {
5399 		/*
5400 		 * We require the parity to be specified for SPAs that
5401 		 * support multiple parity levels.
5402 		 */
5403 		if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
5404 			return (SET_ERROR(EINVAL));
5405 
5406 		/*
5407 		 * Otherwise, we default to 1 parity device for RAID-Z.
5408 		 */
5409 		nparity = 1;
5410 	}
5411 
5412 	vdev_raidz_t *vdrz = kmem_zalloc(sizeof (*vdrz), KM_SLEEP);
5413 	vdrz->vn_vre.vre_vdev_id = -1;
5414 	vdrz->vn_vre.vre_offset = UINT64_MAX;
5415 	vdrz->vn_vre.vre_failed_offset = UINT64_MAX;
5416 	mutex_init(&vdrz->vn_vre.vre_lock, NULL, MUTEX_DEFAULT, NULL);
5417 	cv_init(&vdrz->vn_vre.vre_cv, NULL, CV_DEFAULT, NULL);
5418 	zfs_rangelock_init(&vdrz->vn_vre.vre_rangelock, NULL, NULL);
5419 	mutex_init(&vdrz->vd_expand_lock, NULL, MUTEX_DEFAULT, NULL);
5420 	avl_create(&vdrz->vd_expand_txgs, vdev_raidz_reflow_compare,
5421 	    sizeof (reflow_node_t), offsetof(reflow_node_t, re_link));
5422 
5423 	vdrz->vd_physical_width = children;
5424 	vdrz->vd_nparity = nparity;
5425 
5426 	/* note, the ID does not exist when creating a pool */
5427 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
5428 	    &vdrz->vn_vre.vre_vdev_id);
5429 
5430 	boolean_t reflow_in_progress =
5431 	    nvlist_exists(nv, ZPOOL_CONFIG_RAIDZ_EXPANDING);
5432 	if (reflow_in_progress) {
5433 		spa->spa_raidz_expand = &vdrz->vn_vre;
5434 		vdrz->vn_vre.vre_state = DSS_SCANNING;
5435 	}
5436 
5437 	vdrz->vd_original_width = children;
5438 	uint64_t *txgs;
5439 	unsigned int txgs_size = 0;
5440 	error = nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_RAIDZ_EXPAND_TXGS,
5441 	    &txgs, &txgs_size);
5442 	if (error == 0) {
5443 		for (int i = 0; i < txgs_size; i++) {
5444 			reflow_node_t *re = kmem_zalloc(sizeof (*re), KM_SLEEP);
5445 			re->re_txg = txgs[txgs_size - i - 1];
5446 			re->re_logical_width = vdrz->vd_physical_width - i;
5447 
5448 			if (reflow_in_progress)
5449 				re->re_logical_width--;
5450 
5451 			avl_add(&vdrz->vd_expand_txgs, re);
5452 		}
5453 
5454 		vdrz->vd_original_width = vdrz->vd_physical_width - txgs_size;
5455 	}
5456 	if (reflow_in_progress) {
5457 		vdrz->vd_original_width--;
5458 		zfs_dbgmsg("reflow_in_progress, %u wide, %d prior expansions",
5459 		    children, txgs_size);
5460 	}
5461 
5462 	*tsd = vdrz;
5463 
5464 	return (0);
5465 }
5466 
5467 static void
vdev_raidz_fini(vdev_t * vd)5468 vdev_raidz_fini(vdev_t *vd)
5469 {
5470 	vdev_raidz_t *vdrz = vd->vdev_tsd;
5471 	if (vd->vdev_spa->spa_raidz_expand == &vdrz->vn_vre)
5472 		vd->vdev_spa->spa_raidz_expand = NULL;
5473 	reflow_node_t *re;
5474 	void *cookie = NULL;
5475 	avl_tree_t *tree = &vdrz->vd_expand_txgs;
5476 	while ((re = avl_destroy_nodes(tree, &cookie)) != NULL)
5477 		kmem_free(re, sizeof (*re));
5478 	avl_destroy(&vdrz->vd_expand_txgs);
5479 	mutex_destroy(&vdrz->vd_expand_lock);
5480 	mutex_destroy(&vdrz->vn_vre.vre_lock);
5481 	cv_destroy(&vdrz->vn_vre.vre_cv);
5482 	zfs_rangelock_fini(&vdrz->vn_vre.vre_rangelock);
5483 	kmem_free(vdrz, sizeof (*vdrz));
5484 }
5485 
5486 /*
5487  * Add RAIDZ specific fields to the config nvlist.
5488  */
5489 static void
vdev_raidz_config_generate(vdev_t * vd,nvlist_t * nv)5490 vdev_raidz_config_generate(vdev_t *vd, nvlist_t *nv)
5491 {
5492 	ASSERT3P(vd->vdev_ops, ==, &vdev_raidz_ops);
5493 	vdev_raidz_t *vdrz = vd->vdev_tsd;
5494 
5495 	/*
5496 	 * Make sure someone hasn't managed to sneak a fancy new vdev
5497 	 * into a crufty old storage pool.
5498 	 */
5499 	ASSERT(vdrz->vd_nparity == 1 ||
5500 	    (vdrz->vd_nparity <= 2 &&
5501 	    spa_version(vd->vdev_spa) >= SPA_VERSION_RAIDZ2) ||
5502 	    (vdrz->vd_nparity <= 3 &&
5503 	    spa_version(vd->vdev_spa) >= SPA_VERSION_RAIDZ3));
5504 
5505 	/*
5506 	 * Note that we'll add these even on storage pools where they
5507 	 * aren't strictly required -- older software will just ignore
5508 	 * it.
5509 	 */
5510 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY, vdrz->vd_nparity);
5511 
5512 	if (vdrz->vn_vre.vre_state == DSS_SCANNING) {
5513 		fnvlist_add_boolean(nv, ZPOOL_CONFIG_RAIDZ_EXPANDING);
5514 	}
5515 
5516 	mutex_enter(&vdrz->vd_expand_lock);
5517 	if (!avl_is_empty(&vdrz->vd_expand_txgs)) {
5518 		uint64_t count = avl_numnodes(&vdrz->vd_expand_txgs);
5519 		uint64_t *txgs = kmem_alloc(sizeof (uint64_t) * count,
5520 		    KM_SLEEP);
5521 		uint64_t i = 0;
5522 
5523 		for (reflow_node_t *re = avl_first(&vdrz->vd_expand_txgs);
5524 		    re != NULL; re = AVL_NEXT(&vdrz->vd_expand_txgs, re)) {
5525 			txgs[i++] = re->re_txg;
5526 		}
5527 
5528 		fnvlist_add_uint64_array(nv, ZPOOL_CONFIG_RAIDZ_EXPAND_TXGS,
5529 		    txgs, count);
5530 
5531 		kmem_free(txgs, sizeof (uint64_t) * count);
5532 	}
5533 	mutex_exit(&vdrz->vd_expand_lock);
5534 }
5535 
5536 static uint64_t
vdev_raidz_nparity(vdev_t * vd)5537 vdev_raidz_nparity(vdev_t *vd)
5538 {
5539 	vdev_raidz_t *vdrz = vd->vdev_tsd;
5540 	return (vdrz->vd_nparity);
5541 }
5542 
5543 static uint64_t
vdev_raidz_ndisks(vdev_t * vd)5544 vdev_raidz_ndisks(vdev_t *vd)
5545 {
5546 	return (vd->vdev_children);
5547 }
5548 
5549 vdev_ops_t vdev_raidz_ops = {
5550 	.vdev_op_init = vdev_raidz_init,
5551 	.vdev_op_fini = vdev_raidz_fini,
5552 	.vdev_op_open = vdev_raidz_open,
5553 	.vdev_op_close = vdev_raidz_close,
5554 	.vdev_op_psize_to_asize = vdev_raidz_psize_to_asize,
5555 	.vdev_op_asize_to_psize = vdev_raidz_asize_to_psize,
5556 	.vdev_op_min_asize = vdev_raidz_min_asize,
5557 	.vdev_op_min_alloc = NULL,
5558 	.vdev_op_io_start = vdev_raidz_io_start,
5559 	.vdev_op_io_done = vdev_raidz_io_done,
5560 	.vdev_op_state_change = vdev_raidz_state_change,
5561 	.vdev_op_need_resilver = vdev_raidz_need_resilver,
5562 	.vdev_op_hold = NULL,
5563 	.vdev_op_rele = NULL,
5564 	.vdev_op_remap = NULL,
5565 	.vdev_op_xlate = vdev_raidz_xlate,
5566 	.vdev_op_rebuild_asize = NULL,
5567 	.vdev_op_metaslab_init = NULL,
5568 	.vdev_op_config_generate = vdev_raidz_config_generate,
5569 	.vdev_op_nparity = vdev_raidz_nparity,
5570 	.vdev_op_ndisks = vdev_raidz_ndisks,
5571 	.vdev_op_type = VDEV_TYPE_RAIDZ,	/* name of this vdev type */
5572 	.vdev_op_leaf = B_FALSE			/* not a leaf vdev */
5573 };
5574 
5575 ZFS_MODULE_PARAM(zfs_vdev, raidz_, expand_max_reflow_bytes, ULONG, ZMOD_RW,
5576 	"For testing, pause RAIDZ expansion after reflowing this many bytes");
5577 ZFS_MODULE_PARAM(zfs_vdev, raidz_, expand_max_copy_bytes, ULONG, ZMOD_RW,
5578 	"Max amount of concurrent i/o for RAIDZ expansion");
5579 ZFS_MODULE_PARAM(zfs_vdev, raidz_, io_aggregate_rows, ULONG, ZMOD_RW,
5580 	"For expanded RAIDZ, aggregate reads that have more rows than this");
5581 ZFS_MODULE_PARAM(zfs, zfs_, scrub_after_expand, INT, ZMOD_RW,
5582 	"For expanded RAIDZ, automatically start a pool scrub when expansion "
5583 	"completes");
5584 ZFS_MODULE_PARAM(zfs, zfs_, scrub_partial_writes, INT, ZMOD_RW,
5585 	"Issue reads after writes with recoverable failures to ensure "
5586 	"integrity");
5587 ZFS_MODULE_PARAM(zfs_vdev, vdev_, read_sit_out_secs, ULONG, ZMOD_RW,
5588 	"Raidz/draid slow disk sit out time period in seconds");
5589 ZFS_MODULE_PARAM(zfs_vdev, vdev_, raidz_outlier_check_interval_ms, U64,
5590 	ZMOD_RW, "Interval to check for slow raidz/draid children");
5591 ZFS_MODULE_PARAM(zfs_vdev, vdev_, raidz_outlier_insensitivity, UINT,
5592 	ZMOD_RW, "How insensitive the slow raidz/draid child check should be");
5593 /* END CSTYLED */
5594