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