xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_raidz.c (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
25  * Copyright (c) 2016 Gvozden Nešković. All rights reserved.
26  */
27 
28 #include <sys/zfs_context.h>
29 #include <sys/spa.h>
30 #include <sys/vdev_impl.h>
31 #include <sys/zio.h>
32 #include <sys/zio_checksum.h>
33 #include <sys/abd.h>
34 #include <sys/fs/zfs.h>
35 #include <sys/fm/fs/zfs.h>
36 #include <sys/vdev_raidz.h>
37 #include <sys/vdev_raidz_impl.h>
38 #include <sys/vdev_draid.h>
39 
40 #ifdef ZFS_DEBUG
41 #include <sys/vdev.h>	/* For vdev_xlate() in vdev_raidz_io_verify() */
42 #endif
43 
44 /*
45  * Virtual device vector for RAID-Z.
46  *
47  * This vdev supports single, double, and triple parity. For single parity,
48  * we use a simple XOR of all the data columns. For double or triple parity,
49  * we use a special case of Reed-Solomon coding. This extends the
50  * technique described in "The mathematics of RAID-6" by H. Peter Anvin by
51  * drawing on the system described in "A Tutorial on Reed-Solomon Coding for
52  * Fault-Tolerance in RAID-like Systems" by James S. Plank on which the
53  * former is also based. The latter is designed to provide higher performance
54  * for writes.
55  *
56  * Note that the Plank paper claimed to support arbitrary N+M, but was then
57  * amended six years later identifying a critical flaw that invalidates its
58  * claims. Nevertheless, the technique can be adapted to work for up to
59  * triple parity. For additional parity, the amendment "Note: Correction to
60  * the 1997 Tutorial on Reed-Solomon Coding" by James S. Plank and Ying Ding
61  * is viable, but the additional complexity means that write performance will
62  * suffer.
63  *
64  * All of the methods above operate on a Galois field, defined over the
65  * integers mod 2^N. In our case we choose N=8 for GF(8) so that all elements
66  * can be expressed with a single byte. Briefly, the operations on the
67  * field are defined as follows:
68  *
69  *   o addition (+) is represented by a bitwise XOR
70  *   o subtraction (-) is therefore identical to addition: A + B = A - B
71  *   o multiplication of A by 2 is defined by the following bitwise expression:
72  *
73  *	(A * 2)_7 = A_6
74  *	(A * 2)_6 = A_5
75  *	(A * 2)_5 = A_4
76  *	(A * 2)_4 = A_3 + A_7
77  *	(A * 2)_3 = A_2 + A_7
78  *	(A * 2)_2 = A_1 + A_7
79  *	(A * 2)_1 = A_0
80  *	(A * 2)_0 = A_7
81  *
82  * In C, multiplying by 2 is therefore ((a << 1) ^ ((a & 0x80) ? 0x1d : 0)).
83  * As an aside, this multiplication is derived from the error correcting
84  * primitive polynomial x^8 + x^4 + x^3 + x^2 + 1.
85  *
86  * Observe that any number in the field (except for 0) can be expressed as a
87  * power of 2 -- a generator for the field. We store a table of the powers of
88  * 2 and logs base 2 for quick look ups, and exploit the fact that A * B can
89  * be rewritten as 2^(log_2(A) + log_2(B)) (where '+' is normal addition rather
90  * than field addition). The inverse of a field element A (A^-1) is therefore
91  * A ^ (255 - 1) = A^254.
92  *
93  * The up-to-three parity columns, P, Q, R over several data columns,
94  * D_0, ... D_n-1, can be expressed by field operations:
95  *
96  *	P = D_0 + D_1 + ... + D_n-2 + D_n-1
97  *	Q = 2^n-1 * D_0 + 2^n-2 * D_1 + ... + 2^1 * D_n-2 + 2^0 * D_n-1
98  *	  = ((...((D_0) * 2 + D_1) * 2 + ...) * 2 + D_n-2) * 2 + D_n-1
99  *	R = 4^n-1 * D_0 + 4^n-2 * D_1 + ... + 4^1 * D_n-2 + 4^0 * D_n-1
100  *	  = ((...((D_0) * 4 + D_1) * 4 + ...) * 4 + D_n-2) * 4 + D_n-1
101  *
102  * We chose 1, 2, and 4 as our generators because 1 corresponds to the trivial
103  * XOR operation, and 2 and 4 can be computed quickly and generate linearly-
104  * independent coefficients. (There are no additional coefficients that have
105  * this property which is why the uncorrected Plank method breaks down.)
106  *
107  * See the reconstruction code below for how P, Q and R can used individually
108  * or in concert to recover missing data columns.
109  */
110 
111 #define	VDEV_RAIDZ_P		0
112 #define	VDEV_RAIDZ_Q		1
113 #define	VDEV_RAIDZ_R		2
114 
115 #define	VDEV_RAIDZ_MUL_2(x)	(((x) << 1) ^ (((x) & 0x80) ? 0x1d : 0))
116 #define	VDEV_RAIDZ_MUL_4(x)	(VDEV_RAIDZ_MUL_2(VDEV_RAIDZ_MUL_2(x)))
117 
118 /*
119  * We provide a mechanism to perform the field multiplication operation on a
120  * 64-bit value all at once rather than a byte at a time. This works by
121  * creating a mask from the top bit in each byte and using that to
122  * conditionally apply the XOR of 0x1d.
123  */
124 #define	VDEV_RAIDZ_64MUL_2(x, mask) \
125 { \
126 	(mask) = (x) & 0x8080808080808080ULL; \
127 	(mask) = ((mask) << 1) - ((mask) >> 7); \
128 	(x) = (((x) << 1) & 0xfefefefefefefefeULL) ^ \
129 	    ((mask) & 0x1d1d1d1d1d1d1d1dULL); \
130 }
131 
132 #define	VDEV_RAIDZ_64MUL_4(x, mask) \
133 { \
134 	VDEV_RAIDZ_64MUL_2((x), mask); \
135 	VDEV_RAIDZ_64MUL_2((x), mask); \
136 }
137 
138 static void
139 vdev_raidz_row_free(raidz_row_t *rr)
140 {
141 	int c;
142 
143 	for (c = 0; c < rr->rr_firstdatacol && c < rr->rr_cols; c++) {
144 		abd_free(rr->rr_col[c].rc_abd);
145 
146 		if (rr->rr_col[c].rc_gdata != NULL) {
147 			abd_free(rr->rr_col[c].rc_gdata);
148 		}
149 		if (rr->rr_col[c].rc_orig_data != NULL) {
150 			zio_buf_free(rr->rr_col[c].rc_orig_data,
151 			    rr->rr_col[c].rc_size);
152 		}
153 	}
154 	for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
155 		if (rr->rr_col[c].rc_size != 0) {
156 			if (abd_is_gang(rr->rr_col[c].rc_abd))
157 				abd_free(rr->rr_col[c].rc_abd);
158 			else
159 				abd_put(rr->rr_col[c].rc_abd);
160 		}
161 		if (rr->rr_col[c].rc_orig_data != NULL) {
162 			zio_buf_free(rr->rr_col[c].rc_orig_data,
163 			    rr->rr_col[c].rc_size);
164 		}
165 	}
166 
167 	if (rr->rr_abd_copy != NULL)
168 		abd_free(rr->rr_abd_copy);
169 
170 	if (rr->rr_abd_empty != NULL)
171 		abd_free(rr->rr_abd_empty);
172 
173 	kmem_free(rr, offsetof(raidz_row_t, rr_col[rr->rr_scols]));
174 }
175 
176 void
177 vdev_raidz_map_free(raidz_map_t *rm)
178 {
179 	for (int i = 0; i < rm->rm_nrows; i++)
180 		vdev_raidz_row_free(rm->rm_row[i]);
181 
182 	kmem_free(rm, offsetof(raidz_map_t, rm_row[rm->rm_nrows]));
183 }
184 
185 static void
186 vdev_raidz_map_free_vsd(zio_t *zio)
187 {
188 	raidz_map_t *rm = zio->io_vsd;
189 
190 	ASSERT0(rm->rm_freed);
191 	rm->rm_freed = B_TRUE;
192 
193 	if (rm->rm_reports == 0) {
194 		vdev_raidz_map_free(rm);
195 	}
196 }
197 
198 /*ARGSUSED*/
199 static void
200 vdev_raidz_cksum_free(void *arg, size_t ignored)
201 {
202 	raidz_map_t *rm = arg;
203 
204 	ASSERT3U(rm->rm_reports, >, 0);
205 
206 	if (--rm->rm_reports == 0 && rm->rm_freed)
207 		vdev_raidz_map_free(rm);
208 }
209 
210 static void
211 vdev_raidz_cksum_finish(zio_cksum_report_t *zcr, const abd_t *good_data)
212 {
213 	raidz_map_t *rm = zcr->zcr_cbdata;
214 	const size_t c = zcr->zcr_cbinfo;
215 	size_t x, offset;
216 
217 	if (good_data == NULL) {
218 		zfs_ereport_finish_checksum(zcr, NULL, NULL, B_FALSE);
219 		return;
220 	}
221 
222 	ASSERT3U(rm->rm_nrows, ==, 1);
223 	raidz_row_t *rr = rm->rm_row[0];
224 
225 	const abd_t *good = NULL;
226 	const abd_t *bad = rr->rr_col[c].rc_abd;
227 
228 	if (c < rr->rr_firstdatacol) {
229 		/*
230 		 * The first time through, calculate the parity blocks for
231 		 * the good data (this relies on the fact that the good
232 		 * data never changes for a given logical ZIO)
233 		 */
234 		if (rr->rr_col[0].rc_gdata == NULL) {
235 			abd_t *bad_parity[VDEV_RAIDZ_MAXPARITY];
236 
237 			/*
238 			 * Set up the rr_col[]s to generate the parity for
239 			 * good_data, first saving the parity bufs and
240 			 * replacing them with buffers to hold the result.
241 			 */
242 			for (x = 0; x < rr->rr_firstdatacol; x++) {
243 				bad_parity[x] = rr->rr_col[x].rc_abd;
244 				rr->rr_col[x].rc_abd = rr->rr_col[x].rc_gdata =
245 				    abd_alloc_sametype(rr->rr_col[x].rc_abd,
246 				    rr->rr_col[x].rc_size);
247 			}
248 
249 			/* fill in the data columns from good_data */
250 			offset = 0;
251 			for (; x < rr->rr_cols; x++) {
252 				abd_put(rr->rr_col[x].rc_abd);
253 
254 				rr->rr_col[x].rc_abd =
255 				    abd_get_offset_size((abd_t *)good_data,
256 				    offset, rr->rr_col[x].rc_size);
257 				offset += rr->rr_col[x].rc_size;
258 			}
259 
260 			/*
261 			 * Construct the parity from the good data.
262 			 */
263 			vdev_raidz_generate_parity_row(rm, rr);
264 
265 			/* restore everything back to its original state */
266 			for (x = 0; x < rr->rr_firstdatacol; x++)
267 				rr->rr_col[x].rc_abd = bad_parity[x];
268 
269 			offset = 0;
270 			for (x = rr->rr_firstdatacol; x < rr->rr_cols; x++) {
271 				abd_put(rr->rr_col[x].rc_abd);
272 				rr->rr_col[x].rc_abd = abd_get_offset_size(
273 				    rr->rr_abd_copy, offset,
274 				    rr->rr_col[x].rc_size);
275 				offset += rr->rr_col[x].rc_size;
276 			}
277 		}
278 
279 		ASSERT3P(rr->rr_col[c].rc_gdata, !=, NULL);
280 		good = abd_get_offset_size(rr->rr_col[c].rc_gdata, 0,
281 		    rr->rr_col[c].rc_size);
282 	} else {
283 		/* adjust good_data to point at the start of our column */
284 		offset = 0;
285 		for (x = rr->rr_firstdatacol; x < c; x++)
286 			offset += rr->rr_col[x].rc_size;
287 
288 		good = abd_get_offset_size((abd_t *)good_data, offset,
289 		    rr->rr_col[c].rc_size);
290 	}
291 
292 	/* we drop the ereport if it ends up that the data was good */
293 	zfs_ereport_finish_checksum(zcr, good, bad, B_TRUE);
294 	abd_put((abd_t *)good);
295 }
296 
297 /*
298  * Invoked indirectly by zfs_ereport_start_checksum(), called
299  * below when our read operation fails completely.  The main point
300  * is to keep a copy of everything we read from disk, so that at
301  * vdev_raidz_cksum_finish() time we can compare it with the good data.
302  */
303 static void
304 vdev_raidz_cksum_report(zio_t *zio, zio_cksum_report_t *zcr, void *arg)
305 {
306 	size_t c = (size_t)(uintptr_t)arg;
307 	raidz_map_t *rm = zio->io_vsd;
308 
309 	/* set up the report and bump the refcount  */
310 	zcr->zcr_cbdata = rm;
311 	zcr->zcr_cbinfo = c;
312 	zcr->zcr_finish = vdev_raidz_cksum_finish;
313 	zcr->zcr_free = vdev_raidz_cksum_free;
314 
315 	rm->rm_reports++;
316 	ASSERT3U(rm->rm_reports, >, 0);
317 	ASSERT3U(rm->rm_nrows, ==, 1);
318 
319 	if (rm->rm_row[0]->rr_abd_copy != NULL)
320 		return;
321 
322 	/*
323 	 * It's the first time we're called for this raidz_map_t, so we need
324 	 * to copy the data aside; there's no guarantee that our zio's buffer
325 	 * won't be re-used for something else.
326 	 *
327 	 * Our parity data is already in separate buffers, so there's no need
328 	 * to copy them.
329 	 */
330 	for (int i = 0; i < rm->rm_nrows; i++) {
331 		raidz_row_t *rr = rm->rm_row[i];
332 		size_t offset = 0;
333 		size_t size = 0;
334 
335 		for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++)
336 			size += rr->rr_col[c].rc_size;
337 
338 		rr->rr_abd_copy = abd_alloc_for_io(size, B_FALSE);
339 
340 		for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
341 			raidz_col_t *col = &rr->rr_col[c];
342 			abd_t *tmp = abd_get_offset_size(rr->rr_abd_copy,
343 			    offset, col->rc_size);
344 
345 			abd_copy(tmp, col->rc_abd, col->rc_size);
346 
347 			abd_put(col->rc_abd);
348 			col->rc_abd = tmp;
349 
350 			offset += col->rc_size;
351 		}
352 		ASSERT3U(offset, ==, size);
353 	}
354 }
355 
356 static const zio_vsd_ops_t vdev_raidz_vsd_ops = {
357 	.vsd_free = vdev_raidz_map_free_vsd,
358 	.vsd_cksum_report = vdev_raidz_cksum_report
359 };
360 
361 /*
362  * Divides the IO evenly across all child vdevs; usually, dcols is
363  * the number of children in the target vdev.
364  *
365  * Avoid inlining the function to keep vdev_raidz_io_start(), which
366  * is this functions only caller, as small as possible on the stack.
367  */
368 noinline raidz_map_t *
369 vdev_raidz_map_alloc(zio_t *zio, uint64_t ashift, uint64_t dcols,
370     uint64_t nparity)
371 {
372 	raidz_row_t *rr;
373 	/* The starting RAIDZ (parent) vdev sector of the block. */
374 	uint64_t b = zio->io_offset >> ashift;
375 	/* The zio's size in units of the vdev's minimum sector size. */
376 	uint64_t s = zio->io_size >> ashift;
377 	/* The first column for this stripe. */
378 	uint64_t f = b % dcols;
379 	/* The starting byte offset on each child vdev. */
380 	uint64_t o = (b / dcols) << ashift;
381 	uint64_t q, r, c, bc, col, acols, scols, coff, devidx, asize, tot;
382 	uint64_t off = 0;
383 
384 	raidz_map_t *rm =
385 	    kmem_zalloc(offsetof(raidz_map_t, rm_row[1]), KM_SLEEP);
386 	rm->rm_nrows = 1;
387 
388 	/*
389 	 * "Quotient": The number of data sectors for this stripe on all but
390 	 * the "big column" child vdevs that also contain "remainder" data.
391 	 */
392 	q = s / (dcols - nparity);
393 
394 	/*
395 	 * "Remainder": The number of partial stripe data sectors in this I/O.
396 	 * This will add a sector to some, but not all, child vdevs.
397 	 */
398 	r = s - q * (dcols - nparity);
399 
400 	/* The number of "big columns" - those which contain remainder data. */
401 	bc = (r == 0 ? 0 : r + nparity);
402 
403 	/*
404 	 * The total number of data and parity sectors associated with
405 	 * this I/O.
406 	 */
407 	tot = s + nparity * (q + (r == 0 ? 0 : 1));
408 
409 	/*
410 	 * acols: The columns that will be accessed.
411 	 * scols: The columns that will be accessed or skipped.
412 	 */
413 	if (q == 0) {
414 		/* Our I/O request doesn't span all child vdevs. */
415 		acols = bc;
416 		scols = MIN(dcols, roundup(bc, nparity + 1));
417 	} else {
418 		acols = dcols;
419 		scols = dcols;
420 	}
421 
422 	ASSERT3U(acols, <=, scols);
423 
424 	rr = kmem_alloc(offsetof(raidz_row_t, rr_col[scols]), KM_SLEEP);
425 	rm->rm_row[0] = rr;
426 
427 	rr->rr_cols = acols;
428 	rr->rr_scols = scols;
429 	rr->rr_bigcols = bc;
430 	rr->rr_missingdata = 0;
431 	rr->rr_missingparity = 0;
432 	rr->rr_firstdatacol = nparity;
433 	rr->rr_abd_copy = NULL;
434 	rr->rr_abd_empty = NULL;
435 	rr->rr_nempty = 0;
436 #ifdef ZFS_DEBUG
437 	rr->rr_offset = zio->io_offset;
438 	rr->rr_size = zio->io_size;
439 #endif
440 
441 	asize = 0;
442 
443 	for (c = 0; c < scols; c++) {
444 		raidz_col_t *rc = &rr->rr_col[c];
445 		col = f + c;
446 		coff = o;
447 		if (col >= dcols) {
448 			col -= dcols;
449 			coff += 1ULL << ashift;
450 		}
451 		rc->rc_devidx = col;
452 		rc->rc_offset = coff;
453 		rc->rc_abd = NULL;
454 		rc->rc_gdata = NULL;
455 		rc->rc_orig_data = NULL;
456 		rc->rc_error = 0;
457 		rc->rc_tried = 0;
458 		rc->rc_skipped = 0;
459 		rc->rc_repair = 0;
460 		rc->rc_need_orig_restore = B_FALSE;
461 
462 		if (c >= acols)
463 			rc->rc_size = 0;
464 		else if (c < bc)
465 			rc->rc_size = (q + 1) << ashift;
466 		else
467 			rc->rc_size = q << ashift;
468 
469 		asize += rc->rc_size;
470 	}
471 
472 	ASSERT3U(asize, ==, tot << ashift);
473 	rm->rm_nskip = roundup(tot, nparity + 1) - tot;
474 	rm->rm_skipstart = bc;
475 
476 	for (c = 0; c < rr->rr_firstdatacol; c++)
477 		rr->rr_col[c].rc_abd =
478 		    abd_alloc_linear(rr->rr_col[c].rc_size, B_FALSE);
479 
480 	rr->rr_col[c].rc_abd = abd_get_offset_size(zio->io_abd, 0,
481 	    rr->rr_col[c].rc_size);
482 	off = rr->rr_col[c].rc_size;
483 
484 	for (c = c + 1; c < acols; c++) {
485 		raidz_col_t *rc = &rr->rr_col[c];
486 		rc->rc_abd = abd_get_offset_size(zio->io_abd, off, rc->rc_size);
487 		off += rc->rc_size;
488 	}
489 
490 	/*
491 	 * If all data stored spans all columns, there's a danger that parity
492 	 * will always be on the same device and, since parity isn't read
493 	 * during normal operation, that device's I/O bandwidth won't be
494 	 * used effectively. We therefore switch the parity every 1MB.
495 	 *
496 	 * ... at least that was, ostensibly, the theory. As a practical
497 	 * matter unless we juggle the parity between all devices evenly, we
498 	 * won't see any benefit. Further, occasional writes that aren't a
499 	 * multiple of the LCM of the number of children and the minimum
500 	 * stripe width are sufficient to avoid pessimal behavior.
501 	 * Unfortunately, this decision created an implicit on-disk format
502 	 * requirement that we need to support for all eternity, but only
503 	 * for single-parity RAID-Z.
504 	 *
505 	 * If we intend to skip a sector in the zeroth column for padding
506 	 * we must make sure to note this swap. We will never intend to
507 	 * skip the first column since at least one data and one parity
508 	 * column must appear in each row.
509 	 */
510 	ASSERT(rr->rr_cols >= 2);
511 	ASSERT(rr->rr_col[0].rc_size == rr->rr_col[1].rc_size);
512 
513 	if (rr->rr_firstdatacol == 1 && (zio->io_offset & (1ULL << 20))) {
514 		devidx = rr->rr_col[0].rc_devidx;
515 		o = rr->rr_col[0].rc_offset;
516 		rr->rr_col[0].rc_devidx = rr->rr_col[1].rc_devidx;
517 		rr->rr_col[0].rc_offset = rr->rr_col[1].rc_offset;
518 		rr->rr_col[1].rc_devidx = devidx;
519 		rr->rr_col[1].rc_offset = o;
520 
521 		if (rm->rm_skipstart == 0)
522 			rm->rm_skipstart = 1;
523 	}
524 
525 	/* init RAIDZ parity ops */
526 	rm->rm_ops = vdev_raidz_math_get_ops();
527 
528 	return (rm);
529 }
530 
531 struct pqr_struct {
532 	uint64_t *p;
533 	uint64_t *q;
534 	uint64_t *r;
535 };
536 
537 static int
538 vdev_raidz_p_func(void *buf, size_t size, void *private)
539 {
540 	struct pqr_struct *pqr = private;
541 	const uint64_t *src = buf;
542 	int i, cnt = size / sizeof (src[0]);
543 
544 	ASSERT(pqr->p && !pqr->q && !pqr->r);
545 
546 	for (i = 0; i < cnt; i++, src++, pqr->p++)
547 		*pqr->p ^= *src;
548 
549 	return (0);
550 }
551 
552 static int
553 vdev_raidz_pq_func(void *buf, size_t size, void *private)
554 {
555 	struct pqr_struct *pqr = private;
556 	const uint64_t *src = buf;
557 	uint64_t mask;
558 	int i, cnt = size / sizeof (src[0]);
559 
560 	ASSERT(pqr->p && pqr->q && !pqr->r);
561 
562 	for (i = 0; i < cnt; i++, src++, pqr->p++, pqr->q++) {
563 		*pqr->p ^= *src;
564 		VDEV_RAIDZ_64MUL_2(*pqr->q, mask);
565 		*pqr->q ^= *src;
566 	}
567 
568 	return (0);
569 }
570 
571 static int
572 vdev_raidz_pqr_func(void *buf, size_t size, void *private)
573 {
574 	struct pqr_struct *pqr = private;
575 	const uint64_t *src = buf;
576 	uint64_t mask;
577 	int i, cnt = size / sizeof (src[0]);
578 
579 	ASSERT(pqr->p && pqr->q && pqr->r);
580 
581 	for (i = 0; i < cnt; i++, src++, pqr->p++, pqr->q++, pqr->r++) {
582 		*pqr->p ^= *src;
583 		VDEV_RAIDZ_64MUL_2(*pqr->q, mask);
584 		*pqr->q ^= *src;
585 		VDEV_RAIDZ_64MUL_4(*pqr->r, mask);
586 		*pqr->r ^= *src;
587 	}
588 
589 	return (0);
590 }
591 
592 static void
593 vdev_raidz_generate_parity_p(raidz_row_t *rr)
594 {
595 	uint64_t *p = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
596 
597 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
598 		abd_t *src = rr->rr_col[c].rc_abd;
599 
600 		if (c == rr->rr_firstdatacol) {
601 			abd_copy_to_buf(p, src, rr->rr_col[c].rc_size);
602 		} else {
603 			struct pqr_struct pqr = { p, NULL, NULL };
604 			(void) abd_iterate_func(src, 0, rr->rr_col[c].rc_size,
605 			    vdev_raidz_p_func, &pqr);
606 		}
607 	}
608 }
609 
610 static void
611 vdev_raidz_generate_parity_pq(raidz_row_t *rr)
612 {
613 	uint64_t *p = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
614 	uint64_t *q = abd_to_buf(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
615 	uint64_t pcnt = rr->rr_col[VDEV_RAIDZ_P].rc_size / sizeof (p[0]);
616 	ASSERT(rr->rr_col[VDEV_RAIDZ_P].rc_size ==
617 	    rr->rr_col[VDEV_RAIDZ_Q].rc_size);
618 
619 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
620 		abd_t *src = rr->rr_col[c].rc_abd;
621 
622 		uint64_t ccnt = rr->rr_col[c].rc_size / sizeof (p[0]);
623 
624 		if (c == rr->rr_firstdatacol) {
625 			ASSERT(ccnt == pcnt || ccnt == 0);
626 			abd_copy_to_buf(p, src, rr->rr_col[c].rc_size);
627 			(void) memcpy(q, p, rr->rr_col[c].rc_size);
628 
629 			for (uint64_t i = ccnt; i < pcnt; i++) {
630 				p[i] = 0;
631 				q[i] = 0;
632 			}
633 		} else {
634 			struct pqr_struct pqr = { p, q, NULL };
635 
636 			ASSERT(ccnt <= pcnt);
637 			(void) abd_iterate_func(src, 0, rr->rr_col[c].rc_size,
638 			    vdev_raidz_pq_func, &pqr);
639 
640 			/*
641 			 * Treat short columns as though they are full of 0s.
642 			 * Note that there's therefore nothing needed for P.
643 			 */
644 			uint64_t mask;
645 			for (uint64_t i = ccnt; i < pcnt; i++) {
646 				VDEV_RAIDZ_64MUL_2(q[i], mask);
647 			}
648 		}
649 	}
650 }
651 
652 static void
653 vdev_raidz_generate_parity_pqr(raidz_row_t *rr)
654 {
655 	uint64_t *p = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
656 	uint64_t *q = abd_to_buf(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
657 	uint64_t *r = abd_to_buf(rr->rr_col[VDEV_RAIDZ_R].rc_abd);
658 	uint64_t pcnt = rr->rr_col[VDEV_RAIDZ_P].rc_size / sizeof (p[0]);
659 	ASSERT(rr->rr_col[VDEV_RAIDZ_P].rc_size ==
660 	    rr->rr_col[VDEV_RAIDZ_Q].rc_size);
661 	ASSERT(rr->rr_col[VDEV_RAIDZ_P].rc_size ==
662 	    rr->rr_col[VDEV_RAIDZ_R].rc_size);
663 
664 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
665 		abd_t *src = rr->rr_col[c].rc_abd;
666 
667 		uint64_t ccnt = rr->rr_col[c].rc_size / sizeof (p[0]);
668 
669 		if (c == rr->rr_firstdatacol) {
670 			ASSERT(ccnt == pcnt || ccnt == 0);
671 			abd_copy_to_buf(p, src, rr->rr_col[c].rc_size);
672 			(void) memcpy(q, p, rr->rr_col[c].rc_size);
673 			(void) memcpy(r, p, rr->rr_col[c].rc_size);
674 
675 			for (uint64_t i = ccnt; i < pcnt; i++) {
676 				p[i] = 0;
677 				q[i] = 0;
678 				r[i] = 0;
679 			}
680 		} else {
681 			struct pqr_struct pqr = { p, q, r };
682 
683 			ASSERT(ccnt <= pcnt);
684 			(void) abd_iterate_func(src, 0, rr->rr_col[c].rc_size,
685 			    vdev_raidz_pqr_func, &pqr);
686 
687 			/*
688 			 * Treat short columns as though they are full of 0s.
689 			 * Note that there's therefore nothing needed for P.
690 			 */
691 			uint64_t mask;
692 			for (uint64_t i = ccnt; i < pcnt; i++) {
693 				VDEV_RAIDZ_64MUL_2(q[i], mask);
694 				VDEV_RAIDZ_64MUL_4(r[i], mask);
695 			}
696 		}
697 	}
698 }
699 
700 /*
701  * Generate RAID parity in the first virtual columns according to the number of
702  * parity columns available.
703  */
704 void
705 vdev_raidz_generate_parity_row(raidz_map_t *rm, raidz_row_t *rr)
706 {
707 	ASSERT3U(rr->rr_cols, !=, 0);
708 
709 	/* Generate using the new math implementation */
710 	if (vdev_raidz_math_generate(rm, rr) != RAIDZ_ORIGINAL_IMPL)
711 		return;
712 
713 	switch (rr->rr_firstdatacol) {
714 	case 1:
715 		vdev_raidz_generate_parity_p(rr);
716 		break;
717 	case 2:
718 		vdev_raidz_generate_parity_pq(rr);
719 		break;
720 	case 3:
721 		vdev_raidz_generate_parity_pqr(rr);
722 		break;
723 	default:
724 		cmn_err(CE_PANIC, "invalid RAID-Z configuration");
725 	}
726 }
727 
728 void
729 vdev_raidz_generate_parity(raidz_map_t *rm)
730 {
731 	for (int i = 0; i < rm->rm_nrows; i++) {
732 		raidz_row_t *rr = rm->rm_row[i];
733 		vdev_raidz_generate_parity_row(rm, rr);
734 	}
735 }
736 
737 /* ARGSUSED */
738 static int
739 vdev_raidz_reconst_p_func(void *dbuf, void *sbuf, size_t size, void *private)
740 {
741 	uint64_t *dst = dbuf;
742 	uint64_t *src = sbuf;
743 	int cnt = size / sizeof (src[0]);
744 
745 	for (int i = 0; i < cnt; i++) {
746 		dst[i] ^= src[i];
747 	}
748 
749 	return (0);
750 }
751 
752 /* ARGSUSED */
753 static int
754 vdev_raidz_reconst_q_pre_func(void *dbuf, void *sbuf, size_t size,
755     void *private)
756 {
757 	uint64_t *dst = dbuf;
758 	uint64_t *src = sbuf;
759 	uint64_t mask;
760 	int cnt = size / sizeof (dst[0]);
761 
762 	for (int i = 0; i < cnt; i++, dst++, src++) {
763 		VDEV_RAIDZ_64MUL_2(*dst, mask);
764 		*dst ^= *src;
765 	}
766 
767 	return (0);
768 }
769 
770 /* ARGSUSED */
771 static int
772 vdev_raidz_reconst_q_pre_tail_func(void *buf, size_t size, void *private)
773 {
774 	uint64_t *dst = buf;
775 	uint64_t mask;
776 	int cnt = size / sizeof (dst[0]);
777 
778 	for (int i = 0; i < cnt; i++, dst++) {
779 		/* same operation as vdev_raidz_reconst_q_pre_func() on dst */
780 		VDEV_RAIDZ_64MUL_2(*dst, mask);
781 	}
782 
783 	return (0);
784 }
785 
786 struct reconst_q_struct {
787 	uint64_t *q;
788 	int exp;
789 };
790 
791 static int
792 vdev_raidz_reconst_q_post_func(void *buf, size_t size, void *private)
793 {
794 	struct reconst_q_struct *rq = private;
795 	uint64_t *dst = buf;
796 	int cnt = size / sizeof (dst[0]);
797 
798 	for (int i = 0; i < cnt; i++, dst++, rq->q++) {
799 		int j;
800 		uint8_t *b;
801 
802 		*dst ^= *rq->q;
803 		for (j = 0, b = (uint8_t *)dst; j < 8; j++, b++) {
804 			*b = vdev_raidz_exp2(*b, rq->exp);
805 		}
806 	}
807 
808 	return (0);
809 }
810 
811 struct reconst_pq_struct {
812 	uint8_t *p;
813 	uint8_t *q;
814 	uint8_t *pxy;
815 	uint8_t *qxy;
816 	int aexp;
817 	int bexp;
818 };
819 
820 static int
821 vdev_raidz_reconst_pq_func(void *xbuf, void *ybuf, size_t size, void *private)
822 {
823 	struct reconst_pq_struct *rpq = private;
824 	uint8_t *xd = xbuf;
825 	uint8_t *yd = ybuf;
826 
827 	for (int i = 0; i < size;
828 	    i++, rpq->p++, rpq->q++, rpq->pxy++, rpq->qxy++, xd++, yd++) {
829 		*xd = vdev_raidz_exp2(*rpq->p ^ *rpq->pxy, rpq->aexp) ^
830 		    vdev_raidz_exp2(*rpq->q ^ *rpq->qxy, rpq->bexp);
831 		*yd = *rpq->p ^ *rpq->pxy ^ *xd;
832 	}
833 
834 	return (0);
835 }
836 
837 static int
838 vdev_raidz_reconst_pq_tail_func(void *xbuf, size_t size, void *private)
839 {
840 	struct reconst_pq_struct *rpq = private;
841 	uint8_t *xd = xbuf;
842 
843 	for (int i = 0; i < size;
844 	    i++, rpq->p++, rpq->q++, rpq->pxy++, rpq->qxy++, xd++) {
845 		/* same operation as vdev_raidz_reconst_pq_func() on xd */
846 		*xd = vdev_raidz_exp2(*rpq->p ^ *rpq->pxy, rpq->aexp) ^
847 		    vdev_raidz_exp2(*rpq->q ^ *rpq->qxy, rpq->bexp);
848 	}
849 
850 	return (0);
851 }
852 
853 static int
854 vdev_raidz_reconstruct_p(raidz_row_t *rr, int *tgts, int ntgts)
855 {
856 	int x = tgts[0];
857 	abd_t *dst, *src;
858 
859 	ASSERT3U(ntgts, ==, 1);
860 	ASSERT3U(x, >=, rr->rr_firstdatacol);
861 	ASSERT3U(x, <, rr->rr_cols);
862 
863 	ASSERT3U(rr->rr_col[x].rc_size, <=, rr->rr_col[VDEV_RAIDZ_P].rc_size);
864 
865 	src = rr->rr_col[VDEV_RAIDZ_P].rc_abd;
866 	dst = rr->rr_col[x].rc_abd;
867 
868 	abd_copy_from_buf(dst, abd_to_buf(src), rr->rr_col[x].rc_size);
869 
870 	for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
871 		uint64_t size = MIN(rr->rr_col[x].rc_size,
872 		    rr->rr_col[c].rc_size);
873 
874 		src = rr->rr_col[c].rc_abd;
875 
876 		if (c == x)
877 			continue;
878 
879 		(void) abd_iterate_func2(dst, src, 0, 0, size,
880 		    vdev_raidz_reconst_p_func, NULL);
881 	}
882 
883 	return (1 << VDEV_RAIDZ_P);
884 }
885 
886 static int
887 vdev_raidz_reconstruct_q(raidz_row_t *rr, int *tgts, int ntgts)
888 {
889 	int x = tgts[0];
890 	int c, exp;
891 	abd_t *dst, *src;
892 
893 	ASSERT(ntgts == 1);
894 
895 	ASSERT(rr->rr_col[x].rc_size <= rr->rr_col[VDEV_RAIDZ_Q].rc_size);
896 
897 	for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
898 		uint64_t size = (c == x) ? 0 : MIN(rr->rr_col[x].rc_size,
899 		    rr->rr_col[c].rc_size);
900 
901 		src = rr->rr_col[c].rc_abd;
902 		dst = rr->rr_col[x].rc_abd;
903 
904 		if (c == rr->rr_firstdatacol) {
905 			abd_copy(dst, src, size);
906 			if (rr->rr_col[x].rc_size > size) {
907 				abd_zero_off(dst, size,
908 				    rr->rr_col[x].rc_size - size);
909 			}
910 		} else {
911 			ASSERT3U(size, <=, rr->rr_col[x].rc_size);
912 			(void) abd_iterate_func2(dst, src, 0, 0, size,
913 			    vdev_raidz_reconst_q_pre_func, NULL);
914 			(void) abd_iterate_func(dst,
915 			    size, rr->rr_col[x].rc_size - size,
916 			    vdev_raidz_reconst_q_pre_tail_func, NULL);
917 		}
918 	}
919 
920 	src = rr->rr_col[VDEV_RAIDZ_Q].rc_abd;
921 	dst = rr->rr_col[x].rc_abd;
922 	exp = 255 - (rr->rr_cols - 1 - x);
923 
924 	struct reconst_q_struct rq = { abd_to_buf(src), exp };
925 	(void) abd_iterate_func(dst, 0, rr->rr_col[x].rc_size,
926 	    vdev_raidz_reconst_q_post_func, &rq);
927 
928 	return (1 << VDEV_RAIDZ_Q);
929 }
930 
931 static int
932 vdev_raidz_reconstruct_pq(raidz_row_t *rr, int *tgts, int ntgts)
933 {
934 	uint8_t *p, *q, *pxy, *qxy, tmp, a, b, aexp, bexp;
935 	abd_t *pdata, *qdata;
936 	uint64_t xsize, ysize;
937 	int x = tgts[0];
938 	int y = tgts[1];
939 	abd_t *xd, *yd;
940 
941 	ASSERT(ntgts == 2);
942 	ASSERT(x < y);
943 	ASSERT(x >= rr->rr_firstdatacol);
944 	ASSERT(y < rr->rr_cols);
945 
946 	ASSERT(rr->rr_col[x].rc_size >= rr->rr_col[y].rc_size);
947 
948 	/*
949 	 * Move the parity data aside -- we're going to compute parity as
950 	 * though columns x and y were full of zeros -- Pxy and Qxy. We want to
951 	 * reuse the parity generation mechanism without trashing the actual
952 	 * parity so we make those columns appear to be full of zeros by
953 	 * setting their lengths to zero.
954 	 */
955 	pdata = rr->rr_col[VDEV_RAIDZ_P].rc_abd;
956 	qdata = rr->rr_col[VDEV_RAIDZ_Q].rc_abd;
957 	xsize = rr->rr_col[x].rc_size;
958 	ysize = rr->rr_col[y].rc_size;
959 
960 	rr->rr_col[VDEV_RAIDZ_P].rc_abd =
961 	    abd_alloc_linear(rr->rr_col[VDEV_RAIDZ_P].rc_size, B_TRUE);
962 	rr->rr_col[VDEV_RAIDZ_Q].rc_abd =
963 	    abd_alloc_linear(rr->rr_col[VDEV_RAIDZ_Q].rc_size, B_TRUE);
964 	rr->rr_col[x].rc_size = 0;
965 	rr->rr_col[y].rc_size = 0;
966 
967 	vdev_raidz_generate_parity_pq(rr);
968 
969 	rr->rr_col[x].rc_size = xsize;
970 	rr->rr_col[y].rc_size = ysize;
971 
972 	p = abd_to_buf(pdata);
973 	q = abd_to_buf(qdata);
974 	pxy = abd_to_buf(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
975 	qxy = abd_to_buf(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
976 	xd = rr->rr_col[x].rc_abd;
977 	yd = rr->rr_col[y].rc_abd;
978 
979 	/*
980 	 * We now have:
981 	 *	Pxy = P + D_x + D_y
982 	 *	Qxy = Q + 2^(ndevs - 1 - x) * D_x + 2^(ndevs - 1 - y) * D_y
983 	 *
984 	 * We can then solve for D_x:
985 	 *	D_x = A * (P + Pxy) + B * (Q + Qxy)
986 	 * where
987 	 *	A = 2^(x - y) * (2^(x - y) + 1)^-1
988 	 *	B = 2^(ndevs - 1 - x) * (2^(x - y) + 1)^-1
989 	 *
990 	 * With D_x in hand, we can easily solve for D_y:
991 	 *	D_y = P + Pxy + D_x
992 	 */
993 
994 	a = vdev_raidz_pow2[255 + x - y];
995 	b = vdev_raidz_pow2[255 - (rr->rr_cols - 1 - x)];
996 	tmp = 255 - vdev_raidz_log2[a ^ 1];
997 
998 	aexp = vdev_raidz_log2[vdev_raidz_exp2(a, tmp)];
999 	bexp = vdev_raidz_log2[vdev_raidz_exp2(b, tmp)];
1000 
1001 	ASSERT3U(xsize, >=, ysize);
1002 	struct reconst_pq_struct rpq = { p, q, pxy, qxy, aexp, bexp };
1003 
1004 	(void) abd_iterate_func2(xd, yd, 0, 0, ysize,
1005 	    vdev_raidz_reconst_pq_func, &rpq);
1006 	(void) abd_iterate_func(xd, ysize, xsize - ysize,
1007 	    vdev_raidz_reconst_pq_tail_func, &rpq);
1008 
1009 	abd_free(rr->rr_col[VDEV_RAIDZ_P].rc_abd);
1010 	abd_free(rr->rr_col[VDEV_RAIDZ_Q].rc_abd);
1011 
1012 	/*
1013 	 * Restore the saved parity data.
1014 	 */
1015 	rr->rr_col[VDEV_RAIDZ_P].rc_abd = pdata;
1016 	rr->rr_col[VDEV_RAIDZ_Q].rc_abd = qdata;
1017 
1018 	return ((1 << VDEV_RAIDZ_P) | (1 << VDEV_RAIDZ_Q));
1019 }
1020 
1021 /* BEGIN CSTYLED */
1022 /*
1023  * In the general case of reconstruction, we must solve the system of linear
1024  * equations defined by the coefficients used to generate parity as well as
1025  * the contents of the data and parity disks. This can be expressed with
1026  * vectors for the original data (D) and the actual data (d) and parity (p)
1027  * and a matrix composed of the identity matrix (I) and a dispersal matrix (V):
1028  *
1029  *            __   __                     __     __
1030  *            |     |         __     __   |  p_0  |
1031  *            |  V  |         |  D_0  |   | p_m-1 |
1032  *            |     |    x    |   :   | = |  d_0  |
1033  *            |  I  |         | D_n-1 |   |   :   |
1034  *            |     |         ~~     ~~   | d_n-1 |
1035  *            ~~   ~~                     ~~     ~~
1036  *
1037  * I is simply a square identity matrix of size n, and V is a vandermonde
1038  * matrix defined by the coefficients we chose for the various parity columns
1039  * (1, 2, 4). Note that these values were chosen both for simplicity, speedy
1040  * computation as well as linear separability.
1041  *
1042  *      __               __               __     __
1043  *      |   1   ..  1 1 1 |               |  p_0  |
1044  *      | 2^n-1 ..  4 2 1 |   __     __   |   :   |
1045  *      | 4^n-1 .. 16 4 1 |   |  D_0  |   | p_m-1 |
1046  *      |   1   ..  0 0 0 |   |  D_1  |   |  d_0  |
1047  *      |   0   ..  0 0 0 | x |  D_2  | = |  d_1  |
1048  *      |   :       : : : |   |   :   |   |  d_2  |
1049  *      |   0   ..  1 0 0 |   | D_n-1 |   |   :   |
1050  *      |   0   ..  0 1 0 |   ~~     ~~   |   :   |
1051  *      |   0   ..  0 0 1 |               | d_n-1 |
1052  *      ~~               ~~               ~~     ~~
1053  *
1054  * Note that I, V, d, and p are known. To compute D, we must invert the
1055  * matrix and use the known data and parity values to reconstruct the unknown
1056  * data values. We begin by removing the rows in V|I and d|p that correspond
1057  * to failed or missing columns; we then make V|I square (n x n) and d|p
1058  * sized n by removing rows corresponding to unused parity from the bottom up
1059  * to generate (V|I)' and (d|p)'. We can then generate the inverse of (V|I)'
1060  * using Gauss-Jordan elimination. In the example below we use m=3 parity
1061  * columns, n=8 data columns, with errors in d_1, d_2, and p_1:
1062  *           __                               __
1063  *           |  1   1   1   1   1   1   1   1  |
1064  *           | 128  64  32  16  8   4   2   1  | <-----+-+-- missing disks
1065  *           |  19 205 116  29  64  16  4   1  |      / /
1066  *           |  1   0   0   0   0   0   0   0  |     / /
1067  *           |  0   1   0   0   0   0   0   0  | <--' /
1068  *  (V|I)  = |  0   0   1   0   0   0   0   0  | <---'
1069  *           |  0   0   0   1   0   0   0   0  |
1070  *           |  0   0   0   0   1   0   0   0  |
1071  *           |  0   0   0   0   0   1   0   0  |
1072  *           |  0   0   0   0   0   0   1   0  |
1073  *           |  0   0   0   0   0   0   0   1  |
1074  *           ~~                               ~~
1075  *           __                               __
1076  *           |  1   1   1   1   1   1   1   1  |
1077  *           | 128  64  32  16  8   4   2   1  |
1078  *           |  19 205 116  29  64  16  4   1  |
1079  *           |  1   0   0   0   0   0   0   0  |
1080  *           |  0   1   0   0   0   0   0   0  |
1081  *  (V|I)' = |  0   0   1   0   0   0   0   0  |
1082  *           |  0   0   0   1   0   0   0   0  |
1083  *           |  0   0   0   0   1   0   0   0  |
1084  *           |  0   0   0   0   0   1   0   0  |
1085  *           |  0   0   0   0   0   0   1   0  |
1086  *           |  0   0   0   0   0   0   0   1  |
1087  *           ~~                               ~~
1088  *
1089  * Here we employ Gauss-Jordan elimination to find the inverse of (V|I)'. We
1090  * have carefully chosen the seed values 1, 2, and 4 to ensure that this
1091  * matrix is not singular.
1092  * __                                                                 __
1093  * |  1   1   1   1   1   1   1   1     1   0   0   0   0   0   0   0  |
1094  * |  19 205 116  29  64  16  4   1     0   1   0   0   0   0   0   0  |
1095  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1096  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1097  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1098  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1099  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1100  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1101  * ~~                                                                 ~~
1102  * __                                                                 __
1103  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1104  * |  1   1   1   1   1   1   1   1     1   0   0   0   0   0   0   0  |
1105  * |  19 205 116  29  64  16  4   1     0   1   0   0   0   0   0   0  |
1106  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1107  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1108  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1109  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1110  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1111  * ~~                                                                 ~~
1112  * __                                                                 __
1113  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1114  * |  0   1   1   0   0   0   0   0     1   0   1   1   1   1   1   1  |
1115  * |  0  205 116  0   0   0   0   0     0   1   19  29  64  16  4   1  |
1116  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1117  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1118  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1119  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1120  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1121  * ~~                                                                 ~~
1122  * __                                                                 __
1123  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1124  * |  0   1   1   0   0   0   0   0     1   0   1   1   1   1   1   1  |
1125  * |  0   0  185  0   0   0   0   0    205  1  222 208 141 221 201 204 |
1126  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1127  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1128  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1129  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1130  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1131  * ~~                                                                 ~~
1132  * __                                                                 __
1133  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1134  * |  0   1   1   0   0   0   0   0     1   0   1   1   1   1   1   1  |
1135  * |  0   0   1   0   0   0   0   0    166 100  4   40 158 168 216 209 |
1136  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1137  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1138  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1139  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1140  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1141  * ~~                                                                 ~~
1142  * __                                                                 __
1143  * |  1   0   0   0   0   0   0   0     0   0   1   0   0   0   0   0  |
1144  * |  0   1   0   0   0   0   0   0    167 100  5   41 159 169 217 208 |
1145  * |  0   0   1   0   0   0   0   0    166 100  4   40 158 168 216 209 |
1146  * |  0   0   0   1   0   0   0   0     0   0   0   1   0   0   0   0  |
1147  * |  0   0   0   0   1   0   0   0     0   0   0   0   1   0   0   0  |
1148  * |  0   0   0   0   0   1   0   0     0   0   0   0   0   1   0   0  |
1149  * |  0   0   0   0   0   0   1   0     0   0   0   0   0   0   1   0  |
1150  * |  0   0   0   0   0   0   0   1     0   0   0   0   0   0   0   1  |
1151  * ~~                                                                 ~~
1152  *                   __                               __
1153  *                   |  0   0   1   0   0   0   0   0  |
1154  *                   | 167 100  5   41 159 169 217 208 |
1155  *                   | 166 100  4   40 158 168 216 209 |
1156  *       (V|I)'^-1 = |  0   0   0   1   0   0   0   0  |
1157  *                   |  0   0   0   0   1   0   0   0  |
1158  *                   |  0   0   0   0   0   1   0   0  |
1159  *                   |  0   0   0   0   0   0   1   0  |
1160  *                   |  0   0   0   0   0   0   0   1  |
1161  *                   ~~                               ~~
1162  *
1163  * We can then simply compute D = (V|I)'^-1 x (d|p)' to discover the values
1164  * of the missing data.
1165  *
1166  * As is apparent from the example above, the only non-trivial rows in the
1167  * inverse matrix correspond to the data disks that we're trying to
1168  * reconstruct. Indeed, those are the only rows we need as the others would
1169  * only be useful for reconstructing data known or assumed to be valid. For
1170  * that reason, we only build the coefficients in the rows that correspond to
1171  * targeted columns.
1172  */
1173 /* END CSTYLED */
1174 
1175 static void
1176 vdev_raidz_matrix_init(raidz_row_t *rr, int n, int nmap, int *map,
1177     uint8_t **rows)
1178 {
1179 	int i, j;
1180 	int pow;
1181 
1182 	ASSERT(n == rr->rr_cols - rr->rr_firstdatacol);
1183 
1184 	/*
1185 	 * Fill in the missing rows of interest.
1186 	 */
1187 	for (i = 0; i < nmap; i++) {
1188 		ASSERT3S(0, <=, map[i]);
1189 		ASSERT3S(map[i], <=, 2);
1190 
1191 		pow = map[i] * n;
1192 		if (pow > 255)
1193 			pow -= 255;
1194 		ASSERT(pow <= 255);
1195 
1196 		for (j = 0; j < n; j++) {
1197 			pow -= map[i];
1198 			if (pow < 0)
1199 				pow += 255;
1200 			rows[i][j] = vdev_raidz_pow2[pow];
1201 		}
1202 	}
1203 }
1204 
1205 static void
1206 vdev_raidz_matrix_invert(raidz_row_t *rr, int n, int nmissing, int *missing,
1207     uint8_t **rows, uint8_t **invrows, const uint8_t *used)
1208 {
1209 	int i, j, ii, jj;
1210 	uint8_t log;
1211 
1212 	/*
1213 	 * Assert that the first nmissing entries from the array of used
1214 	 * columns correspond to parity columns and that subsequent entries
1215 	 * correspond to data columns.
1216 	 */
1217 	for (i = 0; i < nmissing; i++) {
1218 		ASSERT3S(used[i], <, rr->rr_firstdatacol);
1219 	}
1220 	for (; i < n; i++) {
1221 		ASSERT3S(used[i], >=, rr->rr_firstdatacol);
1222 	}
1223 
1224 	/*
1225 	 * First initialize the storage where we'll compute the inverse rows.
1226 	 */
1227 	for (i = 0; i < nmissing; i++) {
1228 		for (j = 0; j < n; j++) {
1229 			invrows[i][j] = (i == j) ? 1 : 0;
1230 		}
1231 	}
1232 
1233 	/*
1234 	 * Subtract all trivial rows from the rows of consequence.
1235 	 */
1236 	for (i = 0; i < nmissing; i++) {
1237 		for (j = nmissing; j < n; j++) {
1238 			ASSERT3U(used[j], >=, rr->rr_firstdatacol);
1239 			jj = used[j] - rr->rr_firstdatacol;
1240 			ASSERT3S(jj, <, n);
1241 			invrows[i][j] = rows[i][jj];
1242 			rows[i][jj] = 0;
1243 		}
1244 	}
1245 
1246 	/*
1247 	 * For each of the rows of interest, we must normalize it and subtract
1248 	 * a multiple of it from the other rows.
1249 	 */
1250 	for (i = 0; i < nmissing; i++) {
1251 		for (j = 0; j < missing[i]; j++) {
1252 			ASSERT0(rows[i][j]);
1253 		}
1254 		ASSERT3U(rows[i][missing[i]], !=, 0);
1255 
1256 		/*
1257 		 * Compute the inverse of the first element and multiply each
1258 		 * element in the row by that value.
1259 		 */
1260 		log = 255 - vdev_raidz_log2[rows[i][missing[i]]];
1261 
1262 		for (j = 0; j < n; j++) {
1263 			rows[i][j] = vdev_raidz_exp2(rows[i][j], log);
1264 			invrows[i][j] = vdev_raidz_exp2(invrows[i][j], log);
1265 		}
1266 
1267 		for (ii = 0; ii < nmissing; ii++) {
1268 			if (i == ii)
1269 				continue;
1270 
1271 			ASSERT3U(rows[ii][missing[i]], !=, 0);
1272 
1273 			log = vdev_raidz_log2[rows[ii][missing[i]]];
1274 
1275 			for (j = 0; j < n; j++) {
1276 				rows[ii][j] ^=
1277 				    vdev_raidz_exp2(rows[i][j], log);
1278 				invrows[ii][j] ^=
1279 				    vdev_raidz_exp2(invrows[i][j], log);
1280 			}
1281 		}
1282 	}
1283 
1284 	/*
1285 	 * Verify that the data that is left in the rows are properly part of
1286 	 * an identity matrix.
1287 	 */
1288 	for (i = 0; i < nmissing; i++) {
1289 		for (j = 0; j < n; j++) {
1290 			if (j == missing[i]) {
1291 				ASSERT3U(rows[i][j], ==, 1);
1292 			} else {
1293 				ASSERT0(rows[i][j]);
1294 			}
1295 		}
1296 	}
1297 }
1298 
1299 static void
1300 vdev_raidz_matrix_reconstruct(raidz_row_t *rr, int n, int nmissing,
1301     int *missing, uint8_t **invrows, const uint8_t *used)
1302 {
1303 	int i, j, x, cc, c;
1304 	uint8_t *src;
1305 	uint64_t ccount;
1306 	uint8_t *dst[VDEV_RAIDZ_MAXPARITY] = { NULL };
1307 	uint64_t dcount[VDEV_RAIDZ_MAXPARITY] = { 0 };
1308 	uint8_t log = 0;
1309 	uint8_t val;
1310 	int ll;
1311 	uint8_t *invlog[VDEV_RAIDZ_MAXPARITY];
1312 	uint8_t *p, *pp;
1313 	size_t psize;
1314 
1315 	psize = sizeof (invlog[0][0]) * n * nmissing;
1316 	p = kmem_alloc(psize, KM_SLEEP);
1317 
1318 	for (pp = p, i = 0; i < nmissing; i++) {
1319 		invlog[i] = pp;
1320 		pp += n;
1321 	}
1322 
1323 	for (i = 0; i < nmissing; i++) {
1324 		for (j = 0; j < n; j++) {
1325 			ASSERT3U(invrows[i][j], !=, 0);
1326 			invlog[i][j] = vdev_raidz_log2[invrows[i][j]];
1327 		}
1328 	}
1329 
1330 	for (i = 0; i < n; i++) {
1331 		c = used[i];
1332 		ASSERT3U(c, <, rr->rr_cols);
1333 
1334 		ccount = rr->rr_col[c].rc_size;
1335 		ASSERT(ccount >= rr->rr_col[missing[0]].rc_size || i > 0);
1336 		if (ccount == 0)
1337 			continue;
1338 		src = abd_to_buf(rr->rr_col[c].rc_abd);
1339 		for (j = 0; j < nmissing; j++) {
1340 			cc = missing[j] + rr->rr_firstdatacol;
1341 			ASSERT3U(cc, >=, rr->rr_firstdatacol);
1342 			ASSERT3U(cc, <, rr->rr_cols);
1343 			ASSERT3U(cc, !=, c);
1344 
1345 			dcount[j] = rr->rr_col[cc].rc_size;
1346 			if (dcount[j] != 0)
1347 				dst[j] = abd_to_buf(rr->rr_col[cc].rc_abd);
1348 		}
1349 
1350 		for (x = 0; x < ccount; x++, src++) {
1351 			if (*src != 0)
1352 				log = vdev_raidz_log2[*src];
1353 
1354 			for (cc = 0; cc < nmissing; cc++) {
1355 				if (x >= dcount[cc])
1356 					continue;
1357 
1358 				if (*src == 0) {
1359 					val = 0;
1360 				} else {
1361 					if ((ll = log + invlog[cc][i]) >= 255)
1362 						ll -= 255;
1363 					val = vdev_raidz_pow2[ll];
1364 				}
1365 
1366 				if (i == 0)
1367 					dst[cc][x] = val;
1368 				else
1369 					dst[cc][x] ^= val;
1370 			}
1371 		}
1372 	}
1373 
1374 	kmem_free(p, psize);
1375 }
1376 
1377 static int
1378 vdev_raidz_reconstruct_general(raidz_row_t *rr, int *tgts, int ntgts)
1379 {
1380 	int n, i, c, t, tt;
1381 	int nmissing_rows;
1382 	int missing_rows[VDEV_RAIDZ_MAXPARITY];
1383 	int parity_map[VDEV_RAIDZ_MAXPARITY];
1384 	uint8_t *p, *pp;
1385 	size_t psize;
1386 	uint8_t *rows[VDEV_RAIDZ_MAXPARITY];
1387 	uint8_t *invrows[VDEV_RAIDZ_MAXPARITY];
1388 	uint8_t *used;
1389 
1390 	abd_t **bufs = NULL;
1391 
1392 	int code = 0;
1393 
1394 	/*
1395 	 * Matrix reconstruction can't use scatter ABDs yet, so we allocate
1396 	 * temporary linear ABDs if any non-linear ABDs are found.
1397 	 */
1398 	for (i = rr->rr_firstdatacol; i < rr->rr_cols; i++) {
1399 		if (!abd_is_linear(rr->rr_col[i].rc_abd)) {
1400 			bufs = kmem_alloc(rr->rr_cols * sizeof (abd_t *),
1401 			    KM_PUSHPAGE);
1402 
1403 			for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1404 				raidz_col_t *col = &rr->rr_col[c];
1405 
1406 				bufs[c] = col->rc_abd;
1407 				if (bufs[c] != NULL) {
1408 					col->rc_abd = abd_alloc_linear(
1409 					    col->rc_size, B_TRUE);
1410 					abd_copy(col->rc_abd, bufs[c],
1411 					    col->rc_size);
1412 				}
1413 			}
1414 
1415 			break;
1416 		}
1417 	}
1418 
1419 	n = rr->rr_cols - rr->rr_firstdatacol;
1420 
1421 	/*
1422 	 * Figure out which data columns are missing.
1423 	 */
1424 	nmissing_rows = 0;
1425 	for (t = 0; t < ntgts; t++) {
1426 		if (tgts[t] >= rr->rr_firstdatacol) {
1427 			missing_rows[nmissing_rows++] =
1428 			    tgts[t] - rr->rr_firstdatacol;
1429 		}
1430 	}
1431 
1432 	/*
1433 	 * Figure out which parity columns to use to help generate the missing
1434 	 * data columns.
1435 	 */
1436 	for (tt = 0, c = 0, i = 0; i < nmissing_rows; c++) {
1437 		ASSERT(tt < ntgts);
1438 		ASSERT(c < rr->rr_firstdatacol);
1439 
1440 		/*
1441 		 * Skip any targeted parity columns.
1442 		 */
1443 		if (c == tgts[tt]) {
1444 			tt++;
1445 			continue;
1446 		}
1447 
1448 		code |= 1 << c;
1449 
1450 		parity_map[i] = c;
1451 		i++;
1452 	}
1453 
1454 	ASSERT(code != 0);
1455 	ASSERT3U(code, <, 1 << VDEV_RAIDZ_MAXPARITY);
1456 
1457 	psize = (sizeof (rows[0][0]) + sizeof (invrows[0][0])) *
1458 	    nmissing_rows * n + sizeof (used[0]) * n;
1459 	p = kmem_alloc(psize, KM_SLEEP);
1460 
1461 	for (pp = p, i = 0; i < nmissing_rows; i++) {
1462 		rows[i] = pp;
1463 		pp += n;
1464 		invrows[i] = pp;
1465 		pp += n;
1466 	}
1467 	used = pp;
1468 
1469 	for (i = 0; i < nmissing_rows; i++) {
1470 		used[i] = parity_map[i];
1471 	}
1472 
1473 	for (tt = 0, c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1474 		if (tt < nmissing_rows &&
1475 		    c == missing_rows[tt] + rr->rr_firstdatacol) {
1476 			tt++;
1477 			continue;
1478 		}
1479 
1480 		ASSERT3S(i, <, n);
1481 		used[i] = c;
1482 		i++;
1483 	}
1484 
1485 	/*
1486 	 * Initialize the interesting rows of the matrix.
1487 	 */
1488 	vdev_raidz_matrix_init(rr, n, nmissing_rows, parity_map, rows);
1489 
1490 	/*
1491 	 * Invert the matrix.
1492 	 */
1493 	vdev_raidz_matrix_invert(rr, n, nmissing_rows, missing_rows, rows,
1494 	    invrows, used);
1495 
1496 	/*
1497 	 * Reconstruct the missing data using the generated matrix.
1498 	 */
1499 	vdev_raidz_matrix_reconstruct(rr, n, nmissing_rows, missing_rows,
1500 	    invrows, used);
1501 
1502 	kmem_free(p, psize);
1503 
1504 	/*
1505 	 * copy back from temporary linear abds and free them
1506 	 */
1507 	if (bufs) {
1508 		for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1509 			raidz_col_t *col = &rr->rr_col[c];
1510 
1511 			if (bufs[c] != NULL) {
1512 				abd_copy(bufs[c], col->rc_abd, col->rc_size);
1513 				abd_free(col->rc_abd);
1514 			}
1515 			col->rc_abd = bufs[c];
1516 		}
1517 		kmem_free(bufs, rr->rr_cols * sizeof (abd_t *));
1518 	}
1519 
1520 	return (code);
1521 }
1522 
1523 static int
1524 vdev_raidz_reconstruct_row(raidz_map_t *rm, raidz_row_t *rr,
1525     const int *t, int nt)
1526 {
1527 	int tgts[VDEV_RAIDZ_MAXPARITY], *dt;
1528 	int ntgts;
1529 	int i, c, ret;
1530 	int code;
1531 	int nbadparity, nbaddata;
1532 	int parity_valid[VDEV_RAIDZ_MAXPARITY];
1533 
1534 	nbadparity = rr->rr_firstdatacol;
1535 	nbaddata = rr->rr_cols - nbadparity;
1536 	ntgts = 0;
1537 	for (i = 0, c = 0; c < rr->rr_cols; c++) {
1538 		if (c < rr->rr_firstdatacol)
1539 			parity_valid[c] = B_FALSE;
1540 
1541 		if (i < nt && c == t[i]) {
1542 			tgts[ntgts++] = c;
1543 			i++;
1544 		} else if (rr->rr_col[c].rc_error != 0) {
1545 			tgts[ntgts++] = c;
1546 		} else if (c >= rr->rr_firstdatacol) {
1547 			nbaddata--;
1548 		} else {
1549 			parity_valid[c] = B_TRUE;
1550 			nbadparity--;
1551 		}
1552 	}
1553 
1554 	ASSERT(ntgts >= nt);
1555 	ASSERT(nbaddata >= 0);
1556 	ASSERT(nbaddata + nbadparity == ntgts);
1557 
1558 	dt = &tgts[nbadparity];
1559 
1560 	/* Reconstruct using the new math implementation */
1561 	ret = vdev_raidz_math_reconstruct(rm, rr, parity_valid, dt, nbaddata);
1562 	if (ret != RAIDZ_ORIGINAL_IMPL)
1563 		return (ret);
1564 
1565 	/*
1566 	 * See if we can use any of our optimized reconstruction routines.
1567 	 */
1568 	switch (nbaddata) {
1569 	case 1:
1570 		if (parity_valid[VDEV_RAIDZ_P])
1571 			return (vdev_raidz_reconstruct_p(rr, dt, 1));
1572 
1573 		ASSERT(rr->rr_firstdatacol > 1);
1574 
1575 		if (parity_valid[VDEV_RAIDZ_Q])
1576 			return (vdev_raidz_reconstruct_q(rr, dt, 1));
1577 
1578 		ASSERT(rr->rr_firstdatacol > 2);
1579 		break;
1580 
1581 	case 2:
1582 		ASSERT(rr->rr_firstdatacol > 1);
1583 
1584 		if (parity_valid[VDEV_RAIDZ_P] &&
1585 		    parity_valid[VDEV_RAIDZ_Q])
1586 			return (vdev_raidz_reconstruct_pq(rr, dt, 2));
1587 
1588 		ASSERT(rr->rr_firstdatacol > 2);
1589 
1590 		break;
1591 	}
1592 
1593 	code = vdev_raidz_reconstruct_general(rr, tgts, ntgts);
1594 	ASSERT(code < (1 << VDEV_RAIDZ_MAXPARITY));
1595 	ASSERT(code > 0);
1596 	return (code);
1597 }
1598 
1599 static int
1600 vdev_raidz_open(vdev_t *vd, uint64_t *asize, uint64_t *max_asize,
1601     uint64_t *logical_ashift, uint64_t *physical_ashift)
1602 {
1603 	vdev_raidz_t *vdrz = vd->vdev_tsd;
1604 	uint64_t nparity = vdrz->vd_nparity;
1605 	int c;
1606 	int lasterror = 0;
1607 	int numerrors = 0;
1608 
1609 	ASSERT(nparity > 0);
1610 
1611 	if (nparity > VDEV_RAIDZ_MAXPARITY ||
1612 	    vd->vdev_children < nparity + 1) {
1613 		vd->vdev_stat.vs_aux = VDEV_AUX_BAD_LABEL;
1614 		return (SET_ERROR(EINVAL));
1615 	}
1616 
1617 	vdev_open_children(vd);
1618 
1619 	for (c = 0; c < vd->vdev_children; c++) {
1620 		vdev_t *cvd = vd->vdev_child[c];
1621 
1622 		if (cvd->vdev_open_error != 0) {
1623 			lasterror = cvd->vdev_open_error;
1624 			numerrors++;
1625 			continue;
1626 		}
1627 
1628 		*asize = MIN(*asize - 1, cvd->vdev_asize - 1) + 1;
1629 		*max_asize = MIN(*max_asize - 1, cvd->vdev_max_asize - 1) + 1;
1630 		*logical_ashift = MAX(*logical_ashift, cvd->vdev_ashift);
1631 		*physical_ashift = MAX(*physical_ashift,
1632 		    cvd->vdev_physical_ashift);
1633 	}
1634 
1635 	*asize *= vd->vdev_children;
1636 	*max_asize *= vd->vdev_children;
1637 
1638 	if (numerrors > nparity) {
1639 		vd->vdev_stat.vs_aux = VDEV_AUX_NO_REPLICAS;
1640 		return (lasterror);
1641 	}
1642 
1643 	return (0);
1644 }
1645 
1646 static void
1647 vdev_raidz_close(vdev_t *vd)
1648 {
1649 	for (int c = 0; c < vd->vdev_children; c++) {
1650 		if (vd->vdev_child[c] != NULL)
1651 			vdev_close(vd->vdev_child[c]);
1652 	}
1653 }
1654 
1655 static uint64_t
1656 vdev_raidz_asize(vdev_t *vd, uint64_t psize)
1657 {
1658 	vdev_raidz_t *vdrz = vd->vdev_tsd;
1659 	uint64_t asize;
1660 	uint64_t ashift = vd->vdev_top->vdev_ashift;
1661 	uint64_t cols = vdrz->vd_logical_width;
1662 	uint64_t nparity = vdrz->vd_nparity;
1663 
1664 	asize = ((psize - 1) >> ashift) + 1;
1665 	asize += nparity * ((asize + cols - nparity - 1) / (cols - nparity));
1666 	asize = roundup(asize, nparity + 1) << ashift;
1667 
1668 	return (asize);
1669 }
1670 
1671 /*
1672  * The allocatable space for a raidz vdev is N * sizeof(smallest child)
1673  * so each child must provide at least 1/Nth of its asize.
1674  */
1675 static uint64_t
1676 vdev_raidz_min_asize(vdev_t *vd)
1677 {
1678 	return ((vd->vdev_min_asize + vd->vdev_children - 1) /
1679 	    vd->vdev_children);
1680 }
1681 
1682 void
1683 vdev_raidz_child_done(zio_t *zio)
1684 {
1685 	raidz_col_t *rc = zio->io_private;
1686 
1687 	rc->rc_error = zio->io_error;
1688 	rc->rc_tried = 1;
1689 	rc->rc_skipped = 0;
1690 }
1691 
1692 static void
1693 vdev_raidz_io_verify(vdev_t *vd, raidz_row_t *rr, int col)
1694 {
1695 #ifdef ZFS_DEBUG
1696 	vdev_t *tvd = vd->vdev_top;
1697 
1698 	range_seg64_t logical_rs, physical_rs, remain_rs;
1699 	logical_rs.rs_start = rr->rr_offset;
1700 	logical_rs.rs_end = logical_rs.rs_start +
1701 	    vdev_raidz_asize(vd, rr->rr_size);
1702 
1703 	raidz_col_t *rc = &rr->rr_col[col];
1704 	vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
1705 
1706 	vdev_xlate(cvd, &logical_rs, &physical_rs, &remain_rs);
1707 	ASSERT(vdev_xlate_is_empty(&remain_rs));
1708 	ASSERT3U(rc->rc_offset, ==, physical_rs.rs_start);
1709 	ASSERT3U(rc->rc_offset, <, physical_rs.rs_end);
1710 	/*
1711 	 * It would be nice to assert that rs_end is equal
1712 	 * to rc_offset + rc_size but there might be an
1713 	 * optional I/O at the end that is not accounted in
1714 	 * rc_size.
1715 	 */
1716 	if (physical_rs.rs_end > rc->rc_offset + rc->rc_size) {
1717 		ASSERT3U(physical_rs.rs_end, ==, rc->rc_offset +
1718 		    rc->rc_size + (1 << tvd->vdev_ashift));
1719 	} else {
1720 		ASSERT3U(physical_rs.rs_end, ==, rc->rc_offset + rc->rc_size);
1721 	}
1722 #endif
1723 }
1724 
1725 static void
1726 vdev_raidz_io_start_write(zio_t *zio, raidz_row_t *rr, uint64_t ashift)
1727 {
1728 	vdev_t *vd = zio->io_vd;
1729 	raidz_map_t *rm = zio->io_vsd;
1730 	int c, i;
1731 
1732 	vdev_raidz_generate_parity_row(rm, rr);
1733 
1734 	for (int c = 0; c < rr->rr_cols; c++) {
1735 		raidz_col_t *rc = &rr->rr_col[c];
1736 		if (rc->rc_size == 0)
1737 			continue;
1738 
1739 		/* Verify physical to logical translation */
1740 		vdev_raidz_io_verify(vd, rr, c);
1741 
1742 		zio_nowait(zio_vdev_child_io(zio, NULL,
1743 		    vd->vdev_child[rc->rc_devidx], rc->rc_offset,
1744 		    rc->rc_abd, rc->rc_size, zio->io_type, zio->io_priority,
1745 		    0, vdev_raidz_child_done, rc));
1746 	}
1747 
1748 	/*
1749 	 * Generate optional I/Os for skip sectors to improve aggregation
1750 	 * contiguity.
1751 	 */
1752 	for (c = rm->rm_skipstart, i = 0; i < rm->rm_nskip; c++, i++) {
1753 		ASSERT(c <= rr->rr_scols);
1754 		if (c == rr->rr_scols)
1755 			c = 0;
1756 
1757 		raidz_col_t *rc = &rr->rr_col[c];
1758 		vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
1759 
1760 		zio_nowait(zio_vdev_child_io(zio, NULL, cvd,
1761 		    rc->rc_offset + rc->rc_size, NULL, 1ULL << ashift,
1762 		    zio->io_type, zio->io_priority,
1763 		    ZIO_FLAG_NODATA | ZIO_FLAG_OPTIONAL, NULL, NULL));
1764 	}
1765 }
1766 
1767 static void
1768 vdev_raidz_io_start_read(zio_t *zio, raidz_row_t *rr)
1769 {
1770 	vdev_t *vd = zio->io_vd;
1771 
1772 	/*
1773 	 * Iterate over the columns in reverse order so that we hit the parity
1774 	 * last -- any errors along the way will force us to read the parity.
1775 	 */
1776 	for (int c = rr->rr_cols - 1; c >= 0; c--) {
1777 		raidz_col_t *rc = &rr->rr_col[c];
1778 		if (rc->rc_size == 0)
1779 			continue;
1780 		vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
1781 		if (!vdev_readable(cvd)) {
1782 			if (c >= rr->rr_firstdatacol)
1783 				rr->rr_missingdata++;
1784 			else
1785 				rr->rr_missingparity++;
1786 			rc->rc_error = SET_ERROR(ENXIO);
1787 			rc->rc_tried = 1;	/* don't even try */
1788 			rc->rc_skipped = 1;
1789 			continue;
1790 		}
1791 		if (vdev_dtl_contains(cvd, DTL_MISSING, zio->io_txg, 1)) {
1792 			if (c >= rr->rr_firstdatacol)
1793 				rr->rr_missingdata++;
1794 			else
1795 				rr->rr_missingparity++;
1796 			rc->rc_error = SET_ERROR(ESTALE);
1797 			rc->rc_skipped = 1;
1798 			continue;
1799 		}
1800 		if (c >= rr->rr_firstdatacol || rr->rr_missingdata > 0 ||
1801 		    (zio->io_flags & (ZIO_FLAG_SCRUB | ZIO_FLAG_RESILVER))) {
1802 			zio_nowait(zio_vdev_child_io(zio, NULL, cvd,
1803 			    rc->rc_offset, rc->rc_abd, rc->rc_size,
1804 			    zio->io_type, zio->io_priority, 0,
1805 			    vdev_raidz_child_done, rc));
1806 		}
1807 	}
1808 }
1809 
1810 /*
1811  * Start an IO operation on a RAIDZ VDev
1812  *
1813  * Outline:
1814  * - For write operations:
1815  *   1. Generate the parity data
1816  *   2. Create child zio write operations to each column's vdev, for both
1817  *      data and parity.
1818  *   3. If the column skips any sectors for padding, create optional dummy
1819  *      write zio children for those areas to improve aggregation continuity.
1820  * - For read operations:
1821  *   1. Create child zio read operations to each data column's vdev to read
1822  *      the range of data required for zio.
1823  *   2. If this is a scrub or resilver operation, or if any of the data
1824  *      vdevs have had errors, then create zio read operations to the parity
1825  *      columns' VDevs as well.
1826  */
1827 static void
1828 vdev_raidz_io_start(zio_t *zio)
1829 {
1830 	vdev_t *vd = zio->io_vd;
1831 	vdev_t *tvd = vd->vdev_top;
1832 	vdev_raidz_t *vdrz = vd->vdev_tsd;
1833 	raidz_map_t *rm;
1834 
1835 	rm = vdev_raidz_map_alloc(zio, tvd->vdev_ashift,
1836 	    vdrz->vd_logical_width, vdrz->vd_nparity);
1837 
1838 	/*
1839 	 * Until raidz expansion is implemented all maps for a raidz vdev
1840 	 * contain a single row.
1841 	 */
1842 	ASSERT3U(rm->rm_nrows, ==, 1);
1843 	raidz_row_t *rr = rm->rm_row[0];
1844 
1845 	zio->io_vsd = rm;
1846 	zio->io_vsd_ops = &vdev_raidz_vsd_ops;
1847 
1848 	if (zio->io_type == ZIO_TYPE_WRITE) {
1849 		vdev_raidz_io_start_write(zio, rr, tvd->vdev_ashift);
1850 	} else {
1851 		ASSERT(zio->io_type == ZIO_TYPE_READ);
1852 		vdev_raidz_io_start_read(zio, rr);
1853 	}
1854 
1855 	zio_execute(zio);
1856 }
1857 
1858 /*
1859  * Report a checksum error for a child of a RAID-Z device.
1860  */
1861 static void
1862 raidz_checksum_error(zio_t *zio, raidz_col_t *rc, abd_t *bad_data)
1863 {
1864 	vdev_t *vd = zio->io_vd->vdev_child[rc->rc_devidx];
1865 
1866 	if (!(zio->io_flags & ZIO_FLAG_SPECULATIVE) &&
1867 	    zio->io_priority != ZIO_PRIORITY_REBUILD) {
1868 		zio_bad_cksum_t zbc;
1869 		raidz_map_t *rm = zio->io_vsd;
1870 
1871 		zbc.zbc_has_cksum = 0;
1872 		zbc.zbc_injected = rm->rm_ecksuminjected;
1873 
1874 		int ret = zfs_ereport_post_checksum(zio->io_spa, vd,
1875 		    &zio->io_bookmark, zio, rc->rc_offset, rc->rc_size,
1876 		    rc->rc_abd, bad_data, &zbc);
1877 		if (ret != EALREADY) {
1878 			mutex_enter(&vd->vdev_stat_lock);
1879 			vd->vdev_stat.vs_checksum_errors++;
1880 			mutex_exit(&vd->vdev_stat_lock);
1881 		}
1882 	}
1883 }
1884 
1885 /*
1886  * We keep track of whether or not there were any injected errors, so that
1887  * any ereports we generate can note it.
1888  */
1889 static int
1890 raidz_checksum_verify(zio_t *zio)
1891 {
1892 	zio_bad_cksum_t zbc;
1893 	raidz_map_t *rm = zio->io_vsd;
1894 
1895 	bzero(&zbc, sizeof (zio_bad_cksum_t));
1896 
1897 	int ret = zio_checksum_error(zio, &zbc);
1898 	if (ret != 0 && zbc.zbc_injected != 0)
1899 		rm->rm_ecksuminjected = 1;
1900 
1901 	return (ret);
1902 }
1903 
1904 /*
1905  * Generate the parity from the data columns. If we tried and were able to
1906  * read the parity without error, verify that the generated parity matches the
1907  * data we read. If it doesn't, we fire off a checksum error. Return the
1908  * number of such failures.
1909  */
1910 static int
1911 raidz_parity_verify(zio_t *zio, raidz_row_t *rr)
1912 {
1913 	abd_t *orig[VDEV_RAIDZ_MAXPARITY];
1914 	int c, ret = 0;
1915 	raidz_map_t *rm = zio->io_vsd;
1916 	raidz_col_t *rc;
1917 
1918 	blkptr_t *bp = zio->io_bp;
1919 	enum zio_checksum checksum = (bp == NULL ? zio->io_prop.zp_checksum :
1920 	    (BP_IS_GANG(bp) ? ZIO_CHECKSUM_GANG_HEADER : BP_GET_CHECKSUM(bp)));
1921 
1922 	if (checksum == ZIO_CHECKSUM_NOPARITY)
1923 		return (ret);
1924 
1925 	/*
1926 	 * All data columns must have been successfully read in order
1927 	 * to use them to generate parity columns for comparison.
1928 	 */
1929 	for (c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
1930 		rc = &rr->rr_col[c];
1931 		if (!rc->rc_tried || rc->rc_error != 0)
1932 			return (ret);
1933 	}
1934 
1935 	for (c = 0; c < rr->rr_firstdatacol; c++) {
1936 		rc = &rr->rr_col[c];
1937 		if (!rc->rc_tried || rc->rc_error != 0)
1938 			continue;
1939 
1940 		orig[c] = abd_alloc_sametype(rc->rc_abd, rc->rc_size);
1941 		abd_copy(orig[c], rc->rc_abd, rc->rc_size);
1942 	}
1943 
1944 	/*
1945 	 * Regenerates parity even for !tried||rc_error!=0 columns.  This
1946 	 * isn't harmful but it does have the side effect of fixing stuff
1947 	 * we didn't realize was necessary (i.e. even if we return 0).
1948 	 */
1949 	vdev_raidz_generate_parity_row(rm, rr);
1950 
1951 	for (c = 0; c < rr->rr_firstdatacol; c++) {
1952 		rc = &rr->rr_col[c];
1953 
1954 		if (!rc->rc_tried || rc->rc_error != 0)
1955 			continue;
1956 
1957 		if (abd_cmp(orig[c], rc->rc_abd) != 0) {
1958 			raidz_checksum_error(zio, rc, orig[c]);
1959 			rc->rc_error = SET_ERROR(ECKSUM);
1960 			ret++;
1961 		}
1962 		abd_free(orig[c]);
1963 	}
1964 
1965 	return (ret);
1966 }
1967 
1968 static int
1969 vdev_raidz_worst_error(raidz_row_t *rr)
1970 {
1971 	int error = 0;
1972 
1973 	for (int c = 0; c < rr->rr_cols; c++)
1974 		error = zio_worst_error(error, rr->rr_col[c].rc_error);
1975 
1976 	return (error);
1977 }
1978 
1979 static void
1980 vdev_raidz_io_done_verified(zio_t *zio, raidz_row_t *rr)
1981 {
1982 	int unexpected_errors = 0;
1983 	int parity_errors = 0;
1984 	int parity_untried = 0;
1985 	int data_errors = 0;
1986 
1987 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_READ);
1988 
1989 	for (int c = 0; c < rr->rr_cols; c++) {
1990 		raidz_col_t *rc = &rr->rr_col[c];
1991 
1992 		if (rc->rc_error) {
1993 			if (c < rr->rr_firstdatacol)
1994 				parity_errors++;
1995 			else
1996 				data_errors++;
1997 
1998 			if (!rc->rc_skipped)
1999 				unexpected_errors++;
2000 		} else if (c < rr->rr_firstdatacol && !rc->rc_tried) {
2001 			parity_untried++;
2002 		}
2003 	}
2004 
2005 	/*
2006 	 * If we read more parity disks than were used for
2007 	 * reconstruction, confirm that the other parity disks produced
2008 	 * correct data.
2009 	 *
2010 	 * Note that we also regenerate parity when resilvering so we
2011 	 * can write it out to failed devices later.
2012 	 */
2013 	if (parity_errors + parity_untried <
2014 	    rr->rr_firstdatacol - data_errors ||
2015 	    (zio->io_flags & ZIO_FLAG_RESILVER)) {
2016 		int n = raidz_parity_verify(zio, rr);
2017 		unexpected_errors += n;
2018 		ASSERT3U(parity_errors + n, <=, rr->rr_firstdatacol);
2019 	}
2020 
2021 	if (zio->io_error == 0 && spa_writeable(zio->io_spa) &&
2022 	    (unexpected_errors > 0 || (zio->io_flags & ZIO_FLAG_RESILVER))) {
2023 		/*
2024 		 * Use the good data we have in hand to repair damaged children.
2025 		 */
2026 		for (int c = 0; c < rr->rr_cols; c++) {
2027 			raidz_col_t *rc = &rr->rr_col[c];
2028 			vdev_t *vd = zio->io_vd;
2029 			vdev_t *cvd = vd->vdev_child[rc->rc_devidx];
2030 
2031 			if ((rc->rc_error == 0 || rc->rc_size == 0) &&
2032 			    (rc->rc_repair == 0)) {
2033 				continue;
2034 			}
2035 
2036 			zio_nowait(zio_vdev_child_io(zio, NULL, cvd,
2037 			    rc->rc_offset, rc->rc_abd, rc->rc_size,
2038 			    ZIO_TYPE_WRITE,
2039 			    zio->io_priority == ZIO_PRIORITY_REBUILD ?
2040 			    ZIO_PRIORITY_REBUILD : ZIO_PRIORITY_ASYNC_WRITE,
2041 			    ZIO_FLAG_IO_REPAIR | (unexpected_errors ?
2042 			    ZIO_FLAG_SELF_HEAL : 0), NULL, NULL));
2043 		}
2044 	}
2045 }
2046 
2047 static void
2048 raidz_restore_orig_data(raidz_map_t *rm)
2049 {
2050 	for (int i = 0; i < rm->rm_nrows; i++) {
2051 		raidz_row_t *rr = rm->rm_row[i];
2052 		for (int c = 0; c < rr->rr_cols; c++) {
2053 			raidz_col_t *rc = &rr->rr_col[c];
2054 			if (rc->rc_need_orig_restore) {
2055 				abd_copy_from_buf(rc->rc_abd,
2056 				    rc->rc_orig_data, rc->rc_size);
2057 				rc->rc_need_orig_restore = B_FALSE;
2058 			}
2059 		}
2060 	}
2061 }
2062 
2063 /*
2064  * returns EINVAL if reconstruction of the block will not be possible
2065  * returns ECKSUM if this specific reconstruction failed
2066  * returns 0 on successful reconstruction
2067  */
2068 static int
2069 raidz_reconstruct(zio_t *zio, int *ltgts, int ntgts, int nparity)
2070 {
2071 	raidz_map_t *rm = zio->io_vsd;
2072 
2073 	/* Reconstruct each row */
2074 	for (int r = 0; r < rm->rm_nrows; r++) {
2075 		raidz_row_t *rr = rm->rm_row[r];
2076 		int my_tgts[VDEV_RAIDZ_MAXPARITY]; /* value is child id */
2077 		int t = 0;
2078 		int dead = 0;
2079 		int dead_data = 0;
2080 
2081 		for (int c = 0; c < rr->rr_cols; c++) {
2082 			raidz_col_t *rc = &rr->rr_col[c];
2083 			ASSERT0(rc->rc_need_orig_restore);
2084 			if (rc->rc_error != 0) {
2085 				dead++;
2086 				if (c >= nparity)
2087 					dead_data++;
2088 				continue;
2089 			}
2090 			if (rc->rc_size == 0)
2091 				continue;
2092 			for (int lt = 0; lt < ntgts; lt++) {
2093 				if (rc->rc_devidx == ltgts[lt]) {
2094 					if (rc->rc_orig_data == NULL) {
2095 						rc->rc_orig_data =
2096 						    zio_buf_alloc(rc->rc_size);
2097 						abd_copy_to_buf(
2098 						    rc->rc_orig_data,
2099 						    rc->rc_abd, rc->rc_size);
2100 					}
2101 					rc->rc_need_orig_restore = B_TRUE;
2102 
2103 					dead++;
2104 					if (c >= nparity)
2105 						dead_data++;
2106 					my_tgts[t++] = c;
2107 					break;
2108 				}
2109 			}
2110 		}
2111 		if (dead > nparity) {
2112 			/* reconstruction not possible */
2113 			raidz_restore_orig_data(rm);
2114 			return (EINVAL);
2115 		}
2116 		rr->rr_code = 0;
2117 		if (dead_data > 0)
2118 			rr->rr_code = vdev_raidz_reconstruct_row(rm, rr,
2119 			    my_tgts, t);
2120 	}
2121 
2122 	/* Check for success */
2123 	if (raidz_checksum_verify(zio) == 0) {
2124 
2125 		/* Reconstruction succeeded - report errors */
2126 		for (int i = 0; i < rm->rm_nrows; i++) {
2127 			raidz_row_t *rr = rm->rm_row[i];
2128 
2129 			for (int c = 0; c < rr->rr_cols; c++) {
2130 				raidz_col_t *rc = &rr->rr_col[c];
2131 				if (rc->rc_need_orig_restore) {
2132 					/*
2133 					 * Note: if this is a parity column,
2134 					 * we don't really know if it's wrong.
2135 					 * We need to let
2136 					 * vdev_raidz_io_done_verified() check
2137 					 * it, and if we set rc_error, it will
2138 					 * think that it is a "known" error
2139 					 * that doesn't need to be checked
2140 					 * or corrected.
2141 					 */
2142 					if (rc->rc_error == 0 &&
2143 					    c >= rr->rr_firstdatacol) {
2144 						raidz_checksum_error(zio,
2145 						    rc, rc->rc_gdata);
2146 						rc->rc_error =
2147 						    SET_ERROR(ECKSUM);
2148 					}
2149 					rc->rc_need_orig_restore = B_FALSE;
2150 				}
2151 			}
2152 
2153 			vdev_raidz_io_done_verified(zio, rr);
2154 		}
2155 
2156 		zio_checksum_verified(zio);
2157 
2158 		return (0);
2159 	}
2160 
2161 	/* Reconstruction failed - restore original data */
2162 	raidz_restore_orig_data(rm);
2163 	return (ECKSUM);
2164 }
2165 
2166 /*
2167  * Iterate over all combinations of N bad vdevs and attempt a reconstruction.
2168  * Note that the algorithm below is non-optimal because it doesn't take into
2169  * account how reconstruction is actually performed. For example, with
2170  * triple-parity RAID-Z the reconstruction procedure is the same if column 4
2171  * is targeted as invalid as if columns 1 and 4 are targeted since in both
2172  * cases we'd only use parity information in column 0.
2173  *
2174  * The order that we find the various possible combinations of failed
2175  * disks is dictated by these rules:
2176  * - Examine each "slot" (the "i" in tgts[i])
2177  *   - Try to increment this slot (tgts[i] = tgts[i] + 1)
2178  *   - if we can't increment because it runs into the next slot,
2179  *     reset our slot to the minimum, and examine the next slot
2180  *
2181  *  For example, with a 6-wide RAIDZ3, and no known errors (so we have to choose
2182  *  3 columns to reconstruct), we will generate the following sequence:
2183  *
2184  *  STATE        ACTION
2185  *  0 1 2        special case: skip since these are all parity
2186  *  0 1   3      first slot: reset to 0; middle slot: increment to 2
2187  *  0   2 3      first slot: increment to 1
2188  *    1 2 3      first: reset to 0; middle: reset to 1; last: increment to 4
2189  *  0 1     4    first: reset to 0; middle: increment to 2
2190  *  0   2   4    first: increment to 1
2191  *    1 2   4    first: reset to 0; middle: increment to 3
2192  *  0     3 4    first: increment to 1
2193  *    1   3 4    first: increment to 2
2194  *      2 3 4    first: reset to 0; middle: reset to 1; last: increment to 5
2195  *  0 1       5  first: reset to 0; middle: increment to 2
2196  *  0   2     5  first: increment to 1
2197  *    1 2     5  first: reset to 0; middle: increment to 3
2198  *  0     3   5  first: increment to 1
2199  *    1   3   5  first: increment to 2
2200  *      2 3   5  first: reset to 0; middle: increment to 4
2201  *  0       4 5  first: increment to 1
2202  *    1     4 5  first: increment to 2
2203  *      2   4 5  first: increment to 3
2204  *        3 4 5  done
2205  *
2206  * This strategy works for dRAID but is less effecient when there are a large
2207  * number of child vdevs and therefore permutations to check. Furthermore,
2208  * since the raidz_map_t rows likely do not overlap reconstruction would be
2209  * possible as long as there are no more than nparity data errors per row.
2210  * These additional permutations are not currently checked but could be as
2211  * a future improvement.
2212  */
2213 static int
2214 vdev_raidz_combrec(zio_t *zio)
2215 {
2216 	int nparity = vdev_get_nparity(zio->io_vd);
2217 	raidz_map_t *rm = zio->io_vsd;
2218 
2219 	/* Check if there's enough data to attempt reconstrution. */
2220 	for (int i = 0; i < rm->rm_nrows; i++) {
2221 		raidz_row_t *rr = rm->rm_row[i];
2222 		int total_errors = 0;
2223 
2224 		for (int c = 0; c < rr->rr_cols; c++) {
2225 			if (rr->rr_col[c].rc_error)
2226 				total_errors++;
2227 		}
2228 
2229 		if (total_errors > nparity)
2230 			return (vdev_raidz_worst_error(rr));
2231 	}
2232 
2233 	for (int num_failures = 1; num_failures <= nparity; num_failures++) {
2234 		int tstore[VDEV_RAIDZ_MAXPARITY + 2];
2235 		int *ltgts = &tstore[1]; /* value is logical child ID */
2236 
2237 		/* Determine number of logical children, n */
2238 		int n = zio->io_vd->vdev_children;
2239 
2240 		ASSERT3U(num_failures, <=, nparity);
2241 		ASSERT3U(num_failures, <=, VDEV_RAIDZ_MAXPARITY);
2242 
2243 		/* Handle corner cases in combrec logic */
2244 		ltgts[-1] = -1;
2245 		for (int i = 0; i < num_failures; i++) {
2246 			ltgts[i] = i;
2247 		}
2248 		ltgts[num_failures] = n;
2249 
2250 		for (;;) {
2251 			int err = raidz_reconstruct(zio, ltgts, num_failures,
2252 			    nparity);
2253 			if (err == EINVAL) {
2254 				/*
2255 				 * Reconstruction not possible with this #
2256 				 * failures; try more failures.
2257 				 */
2258 				break;
2259 			} else if (err == 0)
2260 				return (0);
2261 
2262 			/* Compute next targets to try */
2263 			for (int t = 0; ; t++) {
2264 				ASSERT3U(t, <, num_failures);
2265 				ltgts[t]++;
2266 				if (ltgts[t] == n) {
2267 					/* try more failures */
2268 					ASSERT3U(t, ==, num_failures - 1);
2269 					break;
2270 				}
2271 
2272 				ASSERT3U(ltgts[t], <, n);
2273 				ASSERT3U(ltgts[t], <=, ltgts[t + 1]);
2274 
2275 				/*
2276 				 * If that spot is available, we're done here.
2277 				 * Try the next combination.
2278 				 */
2279 				if (ltgts[t] != ltgts[t + 1])
2280 					break;
2281 
2282 				/*
2283 				 * Otherwise, reset this tgt to the minimum,
2284 				 * and move on to the next tgt.
2285 				 */
2286 				ltgts[t] = ltgts[t - 1] + 1;
2287 				ASSERT3U(ltgts[t], ==, t);
2288 			}
2289 
2290 			/* Increase the number of failures and keep trying. */
2291 			if (ltgts[num_failures - 1] == n)
2292 				break;
2293 		}
2294 	}
2295 
2296 	return (ECKSUM);
2297 }
2298 
2299 void
2300 vdev_raidz_reconstruct(raidz_map_t *rm, const int *t, int nt)
2301 {
2302 	for (uint64_t row = 0; row < rm->rm_nrows; row++) {
2303 		raidz_row_t *rr = rm->rm_row[row];
2304 		vdev_raidz_reconstruct_row(rm, rr, t, nt);
2305 	}
2306 }
2307 
2308 /*
2309  * Complete a write IO operation on a RAIDZ VDev
2310  *
2311  * Outline:
2312  *   1. Check for errors on the child IOs.
2313  *   2. Return, setting an error code if too few child VDevs were written
2314  *      to reconstruct the data later.  Note that partial writes are
2315  *      considered successful if they can be reconstructed at all.
2316  */
2317 static void
2318 vdev_raidz_io_done_write_impl(zio_t *zio, raidz_row_t *rr)
2319 {
2320 	int total_errors = 0;
2321 
2322 	ASSERT3U(rr->rr_missingparity, <=, rr->rr_firstdatacol);
2323 	ASSERT3U(rr->rr_missingdata, <=, rr->rr_cols - rr->rr_firstdatacol);
2324 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_WRITE);
2325 
2326 	for (int c = 0; c < rr->rr_cols; c++) {
2327 		raidz_col_t *rc = &rr->rr_col[c];
2328 
2329 		if (rc->rc_error) {
2330 			ASSERT(rc->rc_error != ECKSUM);	/* child has no bp */
2331 
2332 			total_errors++;
2333 		}
2334 	}
2335 
2336 	/*
2337 	 * Treat partial writes as a success. If we couldn't write enough
2338 	 * columns to reconstruct the data, the I/O failed.  Otherwise,
2339 	 * good enough.
2340 	 *
2341 	 * Now that we support write reallocation, it would be better
2342 	 * to treat partial failure as real failure unless there are
2343 	 * no non-degraded top-level vdevs left, and not update DTLs
2344 	 * if we intend to reallocate.
2345 	 */
2346 	if (total_errors > rr->rr_firstdatacol) {
2347 		zio->io_error = zio_worst_error(zio->io_error,
2348 		    vdev_raidz_worst_error(rr));
2349 	}
2350 }
2351 
2352 /*
2353  * return 0 if no reconstruction occurred, otherwise the "code" from
2354  * vdev_raidz_reconstruct().
2355  */
2356 static int
2357 vdev_raidz_io_done_reconstruct_known_missing(zio_t *zio, raidz_map_t *rm,
2358     raidz_row_t *rr)
2359 {
2360 	int parity_errors = 0;
2361 	int parity_untried = 0;
2362 	int data_errors = 0;
2363 	int total_errors = 0;
2364 	int code = 0;
2365 
2366 	ASSERT3U(rr->rr_missingparity, <=, rr->rr_firstdatacol);
2367 	ASSERT3U(rr->rr_missingdata, <=, rr->rr_cols - rr->rr_firstdatacol);
2368 	ASSERT3U(zio->io_type, ==, ZIO_TYPE_READ);
2369 
2370 	for (int c = 0; c < rr->rr_cols; c++) {
2371 		raidz_col_t *rc = &rr->rr_col[c];
2372 
2373 		if (rc->rc_error) {
2374 			ASSERT(rc->rc_error != ECKSUM);	/* child has no bp */
2375 
2376 			if (c < rr->rr_firstdatacol)
2377 				parity_errors++;
2378 			else
2379 				data_errors++;
2380 
2381 			total_errors++;
2382 		} else if (c < rr->rr_firstdatacol && !rc->rc_tried) {
2383 			parity_untried++;
2384 		}
2385 	}
2386 
2387 	/*
2388 	 * If there were data errors and the number of errors we saw was
2389 	 * correctable -- less than or equal to the number of parity disks read
2390 	 * -- reconstruct based on the missing data.
2391 	 */
2392 	if (data_errors != 0 &&
2393 	    total_errors <= rr->rr_firstdatacol - parity_untried) {
2394 		/*
2395 		 * We either attempt to read all the parity columns or
2396 		 * none of them. If we didn't try to read parity, we
2397 		 * wouldn't be here in the correctable case. There must
2398 		 * also have been fewer parity errors than parity
2399 		 * columns or, again, we wouldn't be in this code path.
2400 		 */
2401 		ASSERT(parity_untried == 0);
2402 		ASSERT(parity_errors < rr->rr_firstdatacol);
2403 
2404 		/*
2405 		 * Identify the data columns that reported an error.
2406 		 */
2407 		int n = 0;
2408 		int tgts[VDEV_RAIDZ_MAXPARITY];
2409 		for (int c = rr->rr_firstdatacol; c < rr->rr_cols; c++) {
2410 			raidz_col_t *rc = &rr->rr_col[c];
2411 			if (rc->rc_error != 0) {
2412 				ASSERT(n < VDEV_RAIDZ_MAXPARITY);
2413 				tgts[n++] = c;
2414 			}
2415 		}
2416 
2417 		ASSERT(rr->rr_firstdatacol >= n);
2418 
2419 		code = vdev_raidz_reconstruct_row(rm, rr, tgts, n);
2420 	}
2421 
2422 	return (code);
2423 }
2424 
2425 /*
2426  * Return the number of reads issued.
2427  */
2428 static int
2429 vdev_raidz_read_all(zio_t *zio, raidz_row_t *rr)
2430 {
2431 	vdev_t *vd = zio->io_vd;
2432 	int nread = 0;
2433 
2434 	rr->rr_missingdata = 0;
2435 	rr->rr_missingparity = 0;
2436 
2437 	/*
2438 	 * If this rows contains empty sectors which are not required
2439 	 * for a normal read then allocate an ABD for them now so they
2440 	 * may be read, verified, and any needed repairs performed.
2441 	 */
2442 	if (rr->rr_nempty && rr->rr_abd_empty == NULL)
2443 		vdev_draid_map_alloc_empty(zio, rr);
2444 
2445 	for (int c = 0; c < rr->rr_cols; c++) {
2446 		raidz_col_t *rc = &rr->rr_col[c];
2447 		if (rc->rc_tried || rc->rc_size == 0)
2448 			continue;
2449 
2450 		zio_nowait(zio_vdev_child_io(zio, NULL,
2451 		    vd->vdev_child[rc->rc_devidx],
2452 		    rc->rc_offset, rc->rc_abd, rc->rc_size,
2453 		    zio->io_type, zio->io_priority, 0,
2454 		    vdev_raidz_child_done, rc));
2455 		nread++;
2456 	}
2457 	return (nread);
2458 }
2459 
2460 /*
2461  * We're here because either there were too many errors to even attempt
2462  * reconstruction (total_errors == rm_first_datacol), or vdev_*_combrec()
2463  * failed. In either case, there is enough bad data to prevent reconstruction.
2464  * Start checksum ereports for all children which haven't failed.
2465  */
2466 static void
2467 vdev_raidz_io_done_unrecoverable(zio_t *zio)
2468 {
2469 	raidz_map_t *rm = zio->io_vsd;
2470 
2471 	for (int i = 0; i < rm->rm_nrows; i++) {
2472 		raidz_row_t *rr = rm->rm_row[i];
2473 
2474 		for (int c = 0; c < rr->rr_cols; c++) {
2475 			raidz_col_t *rc = &rr->rr_col[c];
2476 			vdev_t *cvd = zio->io_vd->vdev_child[rc->rc_devidx];
2477 
2478 			if (rc->rc_error != 0)
2479 				continue;
2480 
2481 			zio_bad_cksum_t zbc;
2482 			zbc.zbc_has_cksum = 0;
2483 			zbc.zbc_injected = rm->rm_ecksuminjected;
2484 
2485 			int ret = zfs_ereport_start_checksum(zio->io_spa,
2486 			    cvd, &zio->io_bookmark, zio, rc->rc_offset,
2487 			    rc->rc_size, (void *)(uintptr_t)c, &zbc);
2488 			if (ret != EALREADY) {
2489 				mutex_enter(&cvd->vdev_stat_lock);
2490 				cvd->vdev_stat.vs_checksum_errors++;
2491 				mutex_exit(&cvd->vdev_stat_lock);
2492 			}
2493 		}
2494 	}
2495 }
2496 
2497 void
2498 vdev_raidz_io_done(zio_t *zio)
2499 {
2500 	raidz_map_t *rm = zio->io_vsd;
2501 
2502 	if (zio->io_type == ZIO_TYPE_WRITE) {
2503 		for (int i = 0; i < rm->rm_nrows; i++) {
2504 			vdev_raidz_io_done_write_impl(zio, rm->rm_row[i]);
2505 		}
2506 	} else {
2507 		for (int i = 0; i < rm->rm_nrows; i++) {
2508 			raidz_row_t *rr = rm->rm_row[i];
2509 			rr->rr_code =
2510 			    vdev_raidz_io_done_reconstruct_known_missing(zio,
2511 			    rm, rr);
2512 		}
2513 
2514 		if (raidz_checksum_verify(zio) == 0) {
2515 			for (int i = 0; i < rm->rm_nrows; i++) {
2516 				raidz_row_t *rr = rm->rm_row[i];
2517 				vdev_raidz_io_done_verified(zio, rr);
2518 			}
2519 			zio_checksum_verified(zio);
2520 		} else {
2521 			/*
2522 			 * A sequential resilver has no checksum which makes
2523 			 * combinatoral reconstruction impossible. This code
2524 			 * path is unreachable since raidz_checksum_verify()
2525 			 * has no checksum to verify and must succeed.
2526 			 */
2527 			ASSERT3U(zio->io_priority, !=, ZIO_PRIORITY_REBUILD);
2528 
2529 			/*
2530 			 * This isn't a typical situation -- either we got a
2531 			 * read error or a child silently returned bad data.
2532 			 * Read every block so we can try again with as much
2533 			 * data and parity as we can track down. If we've
2534 			 * already been through once before, all children will
2535 			 * be marked as tried so we'll proceed to combinatorial
2536 			 * reconstruction.
2537 			 */
2538 			int nread = 0;
2539 			for (int i = 0; i < rm->rm_nrows; i++) {
2540 				nread += vdev_raidz_read_all(zio,
2541 				    rm->rm_row[i]);
2542 			}
2543 			if (nread != 0) {
2544 				/*
2545 				 * Normally our stage is VDEV_IO_DONE, but if
2546 				 * we've already called redone(), it will have
2547 				 * changed to VDEV_IO_START, in which case we
2548 				 * don't want to call redone() again.
2549 				 */
2550 				if (zio->io_stage != ZIO_STAGE_VDEV_IO_START)
2551 					zio_vdev_io_redone(zio);
2552 				return;
2553 			}
2554 
2555 			zio->io_error = vdev_raidz_combrec(zio);
2556 			if (zio->io_error == ECKSUM &&
2557 			    !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2558 				vdev_raidz_io_done_unrecoverable(zio);
2559 			}
2560 		}
2561 	}
2562 }
2563 
2564 static void
2565 vdev_raidz_state_change(vdev_t *vd, int faulted, int degraded)
2566 {
2567 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2568 	if (faulted > vdrz->vd_nparity)
2569 		vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2570 		    VDEV_AUX_NO_REPLICAS);
2571 	else if (degraded + faulted != 0)
2572 		vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, VDEV_AUX_NONE);
2573 	else
2574 		vdev_set_state(vd, B_FALSE, VDEV_STATE_HEALTHY, VDEV_AUX_NONE);
2575 }
2576 
2577 /*
2578  * Determine if any portion of the provided block resides on a child vdev
2579  * with a dirty DTL and therefore needs to be resilvered.  The function
2580  * assumes that at least one DTL is dirty which implies that full stripe
2581  * width blocks must be resilvered.
2582  */
2583 static boolean_t
2584 vdev_raidz_need_resilver(vdev_t *vd, const dva_t *dva, size_t psize,
2585     uint64_t phys_birth)
2586 {
2587 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2588 	uint64_t dcols = vd->vdev_children;
2589 	uint64_t nparity = vdrz->vd_nparity;
2590 	uint64_t ashift = vd->vdev_top->vdev_ashift;
2591 	/* The starting RAIDZ (parent) vdev sector of the block. */
2592 	uint64_t b = DVA_GET_OFFSET(dva) >> ashift;
2593 	/* The zio's size in units of the vdev's minimum sector size. */
2594 	uint64_t s = ((psize - 1) >> ashift) + 1;
2595 	/* The first column for this stripe. */
2596 	uint64_t f = b % dcols;
2597 
2598 	/* Unreachable by sequential resilver. */
2599 	ASSERT3U(phys_birth, !=, TXG_UNKNOWN);
2600 
2601 	if (!vdev_dtl_contains(vd, DTL_PARTIAL, phys_birth, 1))
2602 		return (B_FALSE);
2603 
2604 	if (s + nparity >= dcols)
2605 		return (B_TRUE);
2606 
2607 	for (uint64_t c = 0; c < s + nparity; c++) {
2608 		uint64_t devidx = (f + c) % dcols;
2609 		vdev_t *cvd = vd->vdev_child[devidx];
2610 
2611 		/*
2612 		 * dsl_scan_need_resilver() already checked vd with
2613 		 * vdev_dtl_contains(). So here just check cvd with
2614 		 * vdev_dtl_empty(), cheaper and a good approximation.
2615 		 */
2616 		if (!vdev_dtl_empty(cvd, DTL_PARTIAL))
2617 			return (B_TRUE);
2618 	}
2619 
2620 	return (B_FALSE);
2621 }
2622 
2623 static void
2624 vdev_raidz_xlate(vdev_t *cvd, const range_seg64_t *logical_rs,
2625     range_seg64_t *physical_rs, range_seg64_t *remain_rs)
2626 {
2627 	vdev_t *raidvd = cvd->vdev_parent;
2628 	ASSERT(raidvd->vdev_ops == &vdev_raidz_ops);
2629 
2630 	uint64_t width = raidvd->vdev_children;
2631 	uint64_t tgt_col = cvd->vdev_id;
2632 	uint64_t ashift = raidvd->vdev_top->vdev_ashift;
2633 
2634 	/* make sure the offsets are block-aligned */
2635 	ASSERT0(logical_rs->rs_start % (1 << ashift));
2636 	ASSERT0(logical_rs->rs_end % (1 << ashift));
2637 	uint64_t b_start = logical_rs->rs_start >> ashift;
2638 	uint64_t b_end = logical_rs->rs_end >> ashift;
2639 
2640 	uint64_t start_row = 0;
2641 	if (b_start > tgt_col) /* avoid underflow */
2642 		start_row = ((b_start - tgt_col - 1) / width) + 1;
2643 
2644 	uint64_t end_row = 0;
2645 	if (b_end > tgt_col)
2646 		end_row = ((b_end - tgt_col - 1) / width) + 1;
2647 
2648 	physical_rs->rs_start = start_row << ashift;
2649 	physical_rs->rs_end = end_row << ashift;
2650 
2651 	ASSERT3U(physical_rs->rs_start, <=, logical_rs->rs_start);
2652 	ASSERT3U(physical_rs->rs_end - physical_rs->rs_start, <=,
2653 	    logical_rs->rs_end - logical_rs->rs_start);
2654 }
2655 
2656 /*
2657  * Initialize private RAIDZ specific fields from the nvlist.
2658  */
2659 static int
2660 vdev_raidz_init(spa_t *spa, nvlist_t *nv, void **tsd)
2661 {
2662 	vdev_raidz_t *vdrz;
2663 	uint64_t nparity;
2664 
2665 	uint_t children;
2666 	nvlist_t **child;
2667 	int error = nvlist_lookup_nvlist_array(nv,
2668 	    ZPOOL_CONFIG_CHILDREN, &child, &children);
2669 	if (error != 0)
2670 		return (SET_ERROR(EINVAL));
2671 
2672 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY, &nparity) == 0) {
2673 		if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
2674 			return (SET_ERROR(EINVAL));
2675 
2676 		/*
2677 		 * Previous versions could only support 1 or 2 parity
2678 		 * device.
2679 		 */
2680 		if (nparity > 1 && spa_version(spa) < SPA_VERSION_RAIDZ2)
2681 			return (SET_ERROR(EINVAL));
2682 		else if (nparity > 2 && spa_version(spa) < SPA_VERSION_RAIDZ3)
2683 			return (SET_ERROR(EINVAL));
2684 	} else {
2685 		/*
2686 		 * We require the parity to be specified for SPAs that
2687 		 * support multiple parity levels.
2688 		 */
2689 		if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
2690 			return (SET_ERROR(EINVAL));
2691 
2692 		/*
2693 		 * Otherwise, we default to 1 parity device for RAID-Z.
2694 		 */
2695 		nparity = 1;
2696 	}
2697 
2698 	vdrz = kmem_zalloc(sizeof (*vdrz), KM_SLEEP);
2699 	vdrz->vd_logical_width = children;
2700 	vdrz->vd_nparity = nparity;
2701 
2702 	*tsd = vdrz;
2703 
2704 	return (0);
2705 }
2706 
2707 static void
2708 vdev_raidz_fini(vdev_t *vd)
2709 {
2710 	kmem_free(vd->vdev_tsd, sizeof (vdev_raidz_t));
2711 }
2712 
2713 /*
2714  * Add RAIDZ specific fields to the config nvlist.
2715  */
2716 static void
2717 vdev_raidz_config_generate(vdev_t *vd, nvlist_t *nv)
2718 {
2719 	ASSERT3P(vd->vdev_ops, ==, &vdev_raidz_ops);
2720 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2721 
2722 	/*
2723 	 * Make sure someone hasn't managed to sneak a fancy new vdev
2724 	 * into a crufty old storage pool.
2725 	 */
2726 	ASSERT(vdrz->vd_nparity == 1 ||
2727 	    (vdrz->vd_nparity <= 2 &&
2728 	    spa_version(vd->vdev_spa) >= SPA_VERSION_RAIDZ2) ||
2729 	    (vdrz->vd_nparity <= 3 &&
2730 	    spa_version(vd->vdev_spa) >= SPA_VERSION_RAIDZ3));
2731 
2732 	/*
2733 	 * Note that we'll add these even on storage pools where they
2734 	 * aren't strictly required -- older software will just ignore
2735 	 * it.
2736 	 */
2737 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY, vdrz->vd_nparity);
2738 }
2739 
2740 static uint64_t
2741 vdev_raidz_nparity(vdev_t *vd)
2742 {
2743 	vdev_raidz_t *vdrz = vd->vdev_tsd;
2744 	return (vdrz->vd_nparity);
2745 }
2746 
2747 static uint64_t
2748 vdev_raidz_ndisks(vdev_t *vd)
2749 {
2750 	return (vd->vdev_children);
2751 }
2752 
2753 vdev_ops_t vdev_raidz_ops = {
2754 	.vdev_op_init = vdev_raidz_init,
2755 	.vdev_op_fini = vdev_raidz_fini,
2756 	.vdev_op_open = vdev_raidz_open,
2757 	.vdev_op_close = vdev_raidz_close,
2758 	.vdev_op_asize = vdev_raidz_asize,
2759 	.vdev_op_min_asize = vdev_raidz_min_asize,
2760 	.vdev_op_min_alloc = NULL,
2761 	.vdev_op_io_start = vdev_raidz_io_start,
2762 	.vdev_op_io_done = vdev_raidz_io_done,
2763 	.vdev_op_state_change = vdev_raidz_state_change,
2764 	.vdev_op_need_resilver = vdev_raidz_need_resilver,
2765 	.vdev_op_hold = NULL,
2766 	.vdev_op_rele = NULL,
2767 	.vdev_op_remap = NULL,
2768 	.vdev_op_xlate = vdev_raidz_xlate,
2769 	.vdev_op_rebuild_asize = NULL,
2770 	.vdev_op_metaslab_init = NULL,
2771 	.vdev_op_config_generate = vdev_raidz_config_generate,
2772 	.vdev_op_nparity = vdev_raidz_nparity,
2773 	.vdev_op_ndisks = vdev_raidz_ndisks,
2774 	.vdev_op_type = VDEV_TYPE_RAIDZ,	/* name of this vdev type */
2775 	.vdev_op_leaf = B_FALSE			/* not a leaf vdev */
2776 };
2777