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