Debian Codegraph @

reedsolomon.go

raw
1 /**
2 * Reed-Solomon Coding over 8-bit values.
3 *
4 * Copyright 2015, Klaus Post
5 * Copyright 2015, Backblaze, Inc.
6 */
7
8 // Package reedsolomon enables Erasure Coding in Go
9 //
10 // For usage and examples, see https://github.com/klauspost/reedsolomon
11 package reedsolomon
12
13 import (
14 "bytes"
15 "errors"
16 "fmt"
17 "io"
18 "runtime"
19 "sync"
20
21 "github.com/klauspost/cpuid/v2"
22 )
23
24 // Encoder is an interface to encode Reed-Salomon parity sets for your data.
25 type Encoder interface {
26 // Encode parity for a set of data shards.
27 // Input is 'shards' containing data shards followed by parity shards.
28 // The number of shards must match the number given to New().
29 // Each shard is a byte array, and they must all be the same size.
30 // The parity shards will always be overwritten and the data shards
31 // will remain the same, so it is safe for you to read from the
32 // data shards while this is running.
33 Encode(shards [][]byte) error
34
35 // EncodeIdx will add parity for a single data shard.
36 // Parity shards should start out as 0. The caller must zero them.
37 // Data shards must be delivered exactly once. There is no check for this.
38 // The parity shards will always be updated and the data shards will remain the same.
39 EncodeIdx(dataShard []byte, idx int, parity [][]byte) error
40
41 // Verify returns true if the parity shards contain correct data.
42 // The data is the same format as Encode. No data is modified, so
43 // you are allowed to read from data while this is running.
44 Verify(shards [][]byte) (bool, error)
45
46 // Reconstruct will recreate the missing shards if possible.
47 //
48 // Given a list of shards, some of which contain data, fills in the
49 // ones that don't have data.
50 //
51 // The length of the array must be equal to the total number of shards.
52 // You indicate that a shard is missing by setting it to nil or zero-length.
53 // If a shard is zero-length but has sufficient capacity, that memory will
54 // be used, otherwise a new []byte will be allocated.
55 //
56 // If there are too few shards to reconstruct the missing
57 // ones, ErrTooFewShards will be returned.
58 //
59 // The reconstructed shard set is complete, but integrity is not verified.
60 // Use the Verify function to check if data set is ok.
61 Reconstruct(shards [][]byte) error
62
63 // ReconstructData will recreate any missing data shards, if possible.
64 //
65 // Given a list of shards, some of which contain data, fills in the
66 // data shards that don't have data.
67 //
68 // The length of the array must be equal to Shards.
69 // You indicate that a shard is missing by setting it to nil or zero-length.
70 // If a shard is zero-length but has sufficient capacity, that memory will
71 // be used, otherwise a new []byte will be allocated.
72 //
73 // If there are too few shards to reconstruct the missing
74 // ones, ErrTooFewShards will be returned.
75 //
76 // As the reconstructed shard set may contain missing parity shards,
77 // calling the Verify function is likely to fail.
78 ReconstructData(shards [][]byte) error
79
80 // ReconstructSome will recreate only requested shards, if possible.
81 //
82 // Given a list of shards, some of which contain data, fills in the
83 // shards indicated by true values in the "required" parameter.
84 // The length of the "required" array must be equal to either Shards or DataShards.
85 // If the length is equal to DataShards, the reconstruction of parity shards will be ignored.
86 //
87 // The length of "shards" array must be equal to Shards.
88 // You indicate that a shard is missing by setting it to nil or zero-length.
89 // If a shard is zero-length but has sufficient capacity, that memory will
90 // be used, otherwise a new []byte will be allocated.
91 //
92 // If there are too few shards to reconstruct the missing
93 // ones, ErrTooFewShards will be returned.
94 //
95 // As the reconstructed shard set may contain missing parity shards,
96 // calling the Verify function is likely to fail.
97 ReconstructSome(shards [][]byte, required []bool) error
98
99 // Update parity is use for change a few data shards and update it's parity.
100 // Input 'newDatashards' containing data shards changed.
101 // Input 'shards' containing old data shards (if data shard not changed, it can be nil) and old parity shards.
102 // New parity shards will in shards[DataShards:]
103 // Update is very useful if DataShards much larger than ParityShards and changed data shards is few.
104 // It will be faster than Encode and will not need read all data shards to encode.
105 // Note that the data shards in shards will *not* be updated.
106 Update(shards [][]byte, newDatashards [][]byte) error
107
108 // Split a data slice into the number of shards given to the encoder,
109 // and create empty parity shards if necessary.
110 //
111 // The data will be split into equally sized shards.
112 // If the data size isn't divisible by the number of shards,
113 // the last shard will contain extra zeros.
114 //
115 // If there is extra capacity on the provided data slice
116 // it will be used instead of allocating parity shards.
117 // It will be zeroed out.
118 //
119 // There must be at least 1 byte otherwise ErrShortData will be
120 // returned.
121 //
122 // The data will not be copied, except for the last shard, so you
123 // should not modify the data of the input slice afterwards.
124 Split(data []byte) ([][]byte, error)
125
126 // Join the shards and write the data segment to dst.
127 //
128 // Only the data shards are considered.
129 // You must supply the exact output size you want.
130 // If there are to few shards given, ErrTooFewShards will be returned.
131 // If the total data size is less than outSize, ErrShortData will be returned.
132 Join(dst io.Writer, shards [][]byte, outSize int) error
133 }
134
135 // Extensions is an optional interface.
136 // All returned instances will support this interface.
137 type Extensions interface {
138 // ShardSizeMultiple will return the size the shard sizes must be a multiple of.
139 ShardSizeMultiple() int
140
141 // DataShards will return the number of data shards.
142 DataShards() int
143
144 // ParityShards will return the number of parity shards.
145 ParityShards() int
146
147 // TotalShards will return the total number of shards.
148 TotalShards() int
149
150 // AllocAligned will allocate TotalShards number of slices,
151 // aligned to reasonable memory sizes.
152 // Provide the size of each shard.
153 AllocAligned(each int) [][]byte
154
155 // DecodeIdx allows progressively decoding shards.
156 // dst slices that are non-nil will be filled with decoded data.
157 // On first call, dst non-nil slices should be zero.
158 // expectInput indicates which input shards are expected (true = shard expected).
159 // input provides the shards - non-nil slices are treated as provided data.
160 // len(dst) must equal len(input) must equal TotalShards.
161 // If expectInput == nil (merge mode): input shards are XORed into corresponding dst shards.
162 // This allows merging of partial decodings from different sources.
163 // Not all implementations supports this. ErrNotSupported will be returned if not supported.
164 DecodeIdx(dst [][]byte, expectInput []bool, input [][]byte) error
165 }
166
167 const (
168 codeGenMinSize = 64
169 codeGenMinShards = 3
170 gfniCodeGenMaxGoroutines = 4
171
172 intSize = 32 << (^uint(0) >> 63) // 32 or 64
173 maxInt = 1<<(intSize-1) - 1
174 )
175
176 // reedSolomon contains a matrix for a specific
177 // distribution of datashards and parity shards.
178 // Construct if using New()
179 type reedSolomon struct {
180 dataShards int // Number of data shards, should not be modified.
181 parityShards int // Number of parity shards, should not be modified.
182 totalShards int // Total number of shards. Calculated, and should not be modified.
183 m matrix
184 tree *inversionTree
185 parity [][]byte
186 o options
187 mPoolSz int
188 mPool sync.Pool // Pool for temp matrices, etc
189 }
190
191 var _ = Extensions(&reedSolomon{})
192
193 func (r *reedSolomon) ShardSizeMultiple() int {
194 return 1
195 }
196
197 func (r *reedSolomon) DataShards() int {
198 return r.dataShards
199 }
200
201 func (r *reedSolomon) ParityShards() int {
202 return r.parityShards
203 }
204
205 func (r *reedSolomon) TotalShards() int {
206 return r.totalShards
207 }
208
209 func (r *reedSolomon) AllocAligned(each int) [][]byte {
210 return AllocAligned(r.totalShards, each)
211 }
212
213 // ErrInvShardNum will be returned by New, if you attempt to create
214 // an Encoder with less than one data shard or less than zero parity
215 // shards.
216 var ErrInvShardNum = errors.New("cannot create Encoder with less than one data shard or less than zero parity shards")
217
218 // ErrMaxShardNum will be returned by New, if you attempt to create an
219 // Encoder where data and parity shards are bigger than the order of
220 // GF(2^8).
221 var ErrMaxShardNum = errors.New("cannot create Encoder with more than 256 data+parity shards")
222
223 // ErrNotSupported is returned when an operation is not supported.
224 var ErrNotSupported = errors.New("operation not supported")
225
226 // buildMatrix creates the matrix to use for encoding, given the
227 // number of data shards and the number of total shards.
228 //
229 // The top square of the matrix is guaranteed to be an identity
230 // matrix, which means that the data shards are unchanged after
231 // encoding.
232 func buildMatrix(dataShards, totalShards int) (matrix, error) {
233 // Start with a Vandermonde matrix. This matrix would work,
234 // in theory, but doesn't have the property that the data
235 // shards are unchanged after encoding.
236 vm, err := vandermonde(totalShards, dataShards)
237 if err != nil {
238 return nil, err
239 }
240
241 // Multiply by the inverse of the top square of the matrix.
242 // This will make the top square be the identity matrix, but
243 // preserve the property that any square subset of rows is
244 // invertible.
245 top, err := vm.SubMatrix(0, 0, dataShards, dataShards)
246 if err != nil {
247 return nil, err
248 }
249
250 topInv, err := top.Invert()
251 if err != nil {
252 return nil, err
253 }
254
255 return vm.Multiply(topInv)
256 }
257
258 // buildMatrixJerasure creates the same encoding matrix as Jerasure library
259 //
260 // The top square of the matrix is guaranteed to be an identity
261 // matrix, which means that the data shards are unchanged after
262 // encoding.
263 func buildMatrixJerasure(dataShards, totalShards int) (matrix, error) {
264 // Start with a Vandermonde matrix. This matrix would work,
265 // in theory, but doesn't have the property that the data
266 // shards are unchanged after encoding.
267 vm, err := vandermonde(totalShards, dataShards)
268 if err != nil {
269 return nil, err
270 }
271
272 // Jerasure does this:
273 // first row is always 100..00
274 vm[0][0] = 1
275 for i := 1; i < dataShards; i++ {
276 vm[0][i] = 0
277 }
278 // last row is always 000..01
279 for i := 0; i < dataShards-1; i++ {
280 vm[totalShards-1][i] = 0
281 }
282 vm[totalShards-1][dataShards-1] = 1
283
284 for i := range dataShards {
285 // Find the row where i'th col is not 0
286 r := i
287 for ; r < totalShards && vm[r][i] == 0; r++ {
288 }
289 if r != i {
290 // Swap it with i'th row if not already
291 t := vm[r]
292 vm[r] = vm[i]
293 vm[i] = t
294 }
295 // Multiply by the inverted matrix (same as vm.Multiply(vm[0:dataShards].Invert()))
296 if vm[i][i] != 1 {
297 // Make vm[i][i] = 1 by dividing the column by vm[i][i]
298 tmp := galOneOver(vm[i][i])
299 for j := range totalShards {
300 vm[j][i] = galMultiply(vm[j][i], tmp)
301 }
302 }
303 for j := range dataShards {
304 // Make vm[i][j] = 0 where j != i by adding vm[i][j]*vm[.][i] to each column
305 tmp := vm[i][j]
306 if j != i && tmp != 0 {
307 for r := range totalShards {
308 vm[r][j] = galAdd(vm[r][j], galMultiply(tmp, vm[r][i]))
309 }
310 }
311 }
312 }
313
314 // Make vm[dataShards] row all ones - divide each column j by vm[dataShards][j]
315 for j := range dataShards {
316 tmp := vm[dataShards][j]
317 if tmp != 1 {
318 tmp = galOneOver(tmp)
319 for i := dataShards; i < totalShards; i++ {
320 vm[i][j] = galMultiply(vm[i][j], tmp)
321 }
322 }
323 }
324
325 // Make vm[dataShards...totalShards-1][0] column all ones - divide each row
326 for i := dataShards + 1; i < totalShards; i++ {
327 tmp := vm[i][0]
328 if tmp != 1 {
329 tmp = galOneOver(tmp)
330 for j := range dataShards {
331 vm[i][j] = galMultiply(vm[i][j], tmp)
332 }
333 }
334 }
335
336 return vm, nil
337 }
338
339 // buildMatrixPAR1 creates the matrix to use for encoding according to
340 // the PARv1 spec, given the number of data shards and the number of
341 // total shards. Note that the method they use is buggy, and may lead
342 // to cases where recovery is impossible, even if there are enough
343 // parity shards.
344 //
345 // The top square of the matrix is guaranteed to be an identity
346 // matrix, which means that the data shards are unchanged after
347 // encoding.
348 func buildMatrixPAR1(dataShards, totalShards int) (matrix, error) {
349 result, err := newMatrix(totalShards, dataShards)
350 if err != nil {
351 return nil, err
352 }
353
354 for r, row := range result {
355 // The top portion of the matrix is the identity
356 // matrix, and the bottom is a transposed Vandermonde
357 // matrix starting at 1 instead of 0.
358 if r < dataShards {
359 result[r][r] = 1
360 } else {
361 for c := range row {
362 result[r][c] = galExp(byte(c+1), r-dataShards)
363 }
364 }
365 }
366 return result, nil
367 }
368
369 func buildMatrixCauchy(dataShards, totalShards int) (matrix, error) {
370 result, err := newMatrix(totalShards, dataShards)
371 if err != nil {
372 return nil, err
373 }
374
375 for r, row := range result {
376 // The top portion of the matrix is the identity
377 // matrix, and the bottom is a transposed Cauchy matrix.
378 if r < dataShards {
379 result[r][r] = 1
380 } else {
381 for c := range row {
382 result[r][c] = invTable[(byte(r ^ c))]
383 }
384 }
385 }
386 return result, nil
387 }
388
389 // buildXorMatrix can be used to build a matrix with pure XOR
390 // operations if there is only one parity shard.
391 func buildXorMatrix(dataShards, totalShards int) (matrix, error) {
392 if dataShards+1 != totalShards {
393 return nil, errors.New("internal error")
394 }
395 result, err := newMatrix(totalShards, dataShards)
396 if err != nil {
397 return nil, err
398 }
399
400 for r, row := range result {
401 // The top portion of the matrix is the identity
402 // matrix.
403 if r < dataShards {
404 result[r][r] = 1
405 } else {
406 // Set all values to 1 (XOR)
407 for c := range row {
408 result[r][c] = 1
409 }
410 }
411 }
412 return result, nil
413 }
414
415 // New creates a new encoder and initializes it to
416 // the number of data shards and parity shards that
417 // you want to use. You can reuse this encoder.
418 // Note that the maximum number of total shards is 65536, with some
419 // restrictions for a total larger than 256:
420 //
421 // - Shard sizes must be multiple of 64
422 // - The methods Join/Split/Update/EncodeIdx are not supported
423 //
424 // If no options are supplied, default options are used.
425 func New(dataShards, parityShards int, opts ...Option) (Encoder, error) {
426 o := defaultOptions
427 for _, opt := range opts {
428 opt(&o)
429 }
430 if o.workAlloc == nil {
431 o.workAlloc = &defaultWorkAllocator{}
432 }
433
434 totShards := dataShards + parityShards
435 switch {
436 case o.withLeopard == leopardGF16 && parityShards > 0 || totShards > 256:
437 return newFF16(dataShards, parityShards, o)
438 case o.withLeopard == leopardAlways && parityShards > 0:
439 return newFF8(dataShards, parityShards, o)
440 }
441 if totShards > 256 {
442 return nil, ErrMaxShardNum
443 }
444
445 r := reedSolomon{
446 dataShards: dataShards,
447 parityShards: parityShards,
448 totalShards: dataShards + parityShards,
449 o: o,
450 }
451
452 if dataShards <= 0 || parityShards < 0 {
453 return nil, ErrInvShardNum
454 }
455
456 if parityShards == 0 {
457 return &r, nil
458 }
459
460 var err error
461 switch {
462 case r.o.customMatrix != nil:
463 if len(r.o.customMatrix) < parityShards {
464 return nil, errors.New("coding matrix must contain at least parityShards rows")
465 }
466 r.m = make([][]byte, r.totalShards)
467 for i := range dataShards {
468 r.m[i] = make([]byte, dataShards)
469 r.m[i][i] = 1
470 }
471 for k, row := range r.o.customMatrix {
472 if len(row) < dataShards {
473 return nil, errors.New("coding matrix must contain at least dataShards columns")
474 }
475 r.m[dataShards+k] = make([]byte, dataShards)
476 copy(r.m[dataShards+k], row)
477 }
478 case r.o.fastOneParity && parityShards == 1:
479 r.m, err = buildXorMatrix(dataShards, r.totalShards)
480 case r.o.useCauchy:
481 r.m, err = buildMatrixCauchy(dataShards, r.totalShards)
482 case r.o.usePAR1Matrix:
483 r.m, err = buildMatrixPAR1(dataShards, r.totalShards)
484 case r.o.useJerasureMatrix:
485 r.m, err = buildMatrixJerasure(dataShards, r.totalShards)
486 default:
487 r.m, err = buildMatrix(dataShards, r.totalShards)
488 }
489 if err != nil {
490 return nil, err
491 }
492
493 // Calculate what we want per round
494 r.o.perRound = max(cpuid.CPU.Cache.L2, 128<<10)
495
496 _, _, useCodeGen := r.hasCodeGen(codeGenMinSize, codeGenMaxInputs, codeGenMaxOutputs)
497
498 divide := parityShards + 1
499 if codeGen && useCodeGen && (dataShards > codeGenMaxInputs || parityShards > codeGenMaxOutputs) {
500 // Base on L1 cache if we have many inputs.
501 r.o.perRound = max(cpuid.CPU.Cache.L1D, 32<<10)
502 divide = 0
503 if dataShards > codeGenMaxInputs {
504 divide += codeGenMaxInputs
505 } else {
506 divide += dataShards
507 }
508 if parityShards > codeGenMaxInputs {
509 divide += codeGenMaxOutputs
510 } else {
511 divide += parityShards
512 }
513 }
514
515 if cpuid.CPU.ThreadsPerCore > 1 && r.o.maxGoroutines > cpuid.CPU.PhysicalCores {
516 // If multiple threads per core, make sure they don't contend for cache.
517 r.o.perRound /= cpuid.CPU.ThreadsPerCore
518 }
519
520 // 1 input + parity must fit in cache, and we add one more to be safer.
521 r.o.perRound = r.o.perRound / divide
522 // Align to 64 bytes.
523 r.o.perRound = max(
524 // Final sanity check...
525 ((r.o.perRound+63)/64)*64, 1<<10)
526
527 if r.o.minSplitSize <= 0 {
528 // Set minsplit as high as we can, but still have parity in L1.
529 cacheSize := cpuid.CPU.Cache.L1D
530 if cacheSize <= 0 {
531 cacheSize = 32 << 10
532 }
533
534 r.o.minSplitSize = max(
535 // Min 1K
536 cacheSize/(parityShards+1), 1024)
537 }
538
539 if r.o.shardSize > 0 {
540 p := runtime.GOMAXPROCS(0)
541 if p == 1 || r.o.shardSize <= r.o.minSplitSize*2 {
542 // Not worth it.
543 r.o.maxGoroutines = 1
544 } else {
545 g := r.o.shardSize / r.o.perRound
546
547 // Overprovision by a factor of 2.
548 if g < p*2 && r.o.perRound > r.o.minSplitSize*2 {
549 g = p * 2
550 r.o.perRound /= 2
551 }
552
553 // Have g be multiple of p
554 g += p - 1
555 g -= g % p
556
557 r.o.maxGoroutines = g
558 }
559 }
560
561 // Generated AVX2 does not need data to stay in L1 cache between runs.
562 // We will be purely limited by RAM speed.
563 if useCodeGen && r.o.maxGoroutines > codeGenMaxGoroutines {
564 r.o.maxGoroutines = codeGenMaxGoroutines
565 }
566
567 if _, _, useGFNI := r.canGFNI(codeGenMinSize, codeGenMaxInputs, codeGenMaxOutputs); useGFNI && r.o.maxGoroutines > gfniCodeGenMaxGoroutines {
568 r.o.maxGoroutines = gfniCodeGenMaxGoroutines
569 }
570
571 // Skip 2 byte table method if we have many shards.
572 // This is the approximate switchover for Zen5.
573 r.o.skip2B = dataShards+parityShards >= 20
574
575 // Inverted matrices are cached in a tree keyed by the indices
576 // of the invalid rows of the data to reconstruct.
577 // The inversion root node will have the identity matrix as
578 // its inversion matrix because it implies there are no errors
579 // with the original data.
580 if r.o.inversionCache {
581 r.tree = newInversionTree(dataShards, parityShards)
582 }
583
584 r.parity = make([][]byte, parityShards)
585 for i := range r.parity {
586 r.parity[i] = r.m[dataShards+i]
587 }
588
589 if codeGen /* && r.o.useAVX2 */ {
590 paddedDS := r.dataShards
591 if codeGenPadInputs > 1 {
592 paddedDS = ((paddedDS + codeGenPadInputs - 1) / codeGenPadInputs) * codeGenPadInputs
593 }
594 sz := paddedDS * r.parityShards * 2 * 32
595 r.mPool.New = func() any {
596 return AllocAligned(1, sz)[0]
597 }
598 r.mPoolSz = sz
599 }
600 return &r, err
601 }
602
603 func (r *reedSolomon) getTmpSlice() []byte {
604 return r.mPool.Get().([]byte)
605 }
606
607 func (r *reedSolomon) putTmpSlice(b []byte) {
608 if b != nil && cap(b) >= r.mPoolSz {
609 r.mPool.Put(b[:r.mPoolSz])
610 return
611 }
612 if false {
613 // Sanity check
614 panic(fmt.Sprintf("got short tmp returned, want %d, got %d", r.mPoolSz, cap(b)))
615 }
616 }
617
618 // multiplyRowWithMatrix multiplies a single row with a matrix to produce a new row.
619 // result[j] = sum over i of row[i] * matrix[i][j]
620 func multiplyRowWithMatrix(row []byte, matrix [][]byte) []byte {
621 if len(row) != len(matrix) {
622 panic("row length must match matrix height")
623 }
624 result := make([]byte, len(matrix[0]))
625 for j := range result {
626 for i := range row {
627 result[j] ^= galMultiply(row[i], matrix[i][j])
628 }
629 }
630 return result
631 }
632
633 // getDecodeMatrix returns the inverted matrix for decoding, using cached version if available
634 func (r *reedSolomon) getDecodeMatrix(validIndices, invalidIndices []int) ([][]byte, error) {
635 // Attempt to get the cached inverted matrix out of the tree
636 // based on the indices of the invalid rows.
637 dataDecodeMatrix := r.tree.GetInvertedMatrix(invalidIndices)
638
639 // If the inverted matrix isn't cached in the tree yet we must
640 // construct it ourselves and insert it into the tree for the
641 // future. In this way the inversion tree is lazily loaded.
642 if dataDecodeMatrix == nil {
643 // Pull out the rows of the matrix that correspond to the
644 // shards that we have and build a square matrix. This
645 // matrix could be used to generate the shards that we have
646 // from the original data.
647 subMatrix, _ := newMatrix(r.dataShards, r.dataShards)
648 for subMatrixRow, validIndex := range validIndices[:r.dataShards] {
649 for c := 0; c < r.dataShards; c++ {
650 subMatrix[subMatrixRow][c] = r.m[validIndex][c]
651 }
652 }
653 // Invert the matrix, so we can go from the encoded shards
654 // back to the original data. Then pull out the row that
655 // generates the shard that we want to decode. Note that
656 // since this matrix maps back to the original data, it can
657 // be used to create a data shard, but not a parity shard.
658 var err error
659 dataDecodeMatrix, err = subMatrix.Invert()
660 if err != nil {
661 return nil, err
662 }
663
664 // Cache the inverted matrix in the tree for future use keyed on the
665 // indices of the invalid rows.
666 err = r.tree.InsertInvertedMatrix(invalidIndices, dataDecodeMatrix, r.totalShards)
667 if err != nil {
668 return nil, err
669 }
670 }
671
672 return dataDecodeMatrix, nil
673 }
674
675 // ErrTooFewShards is returned if too few shards where given to
676 // Encode/Verify/Reconstruct/Update. It will also be returned from Reconstruct
677 // if there were too few shards to reconstruct the missing data.
678 var ErrTooFewShards = errors.New("too few shards given")
679
680 // Encode parity for a set of data shards.
681 // An array 'shards' containing data shards followed by parity shards.
682 // The number of shards must match the number given to New.
683 // Each shard is a byte array, and they must all be the same size.
684 // The parity shards will always be overwritten and the data shards
685 // will remain the same.
686 func (r *reedSolomon) Encode(shards [][]byte) error {
687 if len(shards) != r.totalShards {
688 return ErrTooFewShards
689 }
690
691 err := checkShards(shards, false)
692 if err != nil {
693 return err
694 }
695
696 // Get the slice of output buffers.
697 output := shards[r.dataShards:]
698
699 // Do the coding.
700 r.codeSomeShards(r.parity, shards[0:r.dataShards], output[:r.parityShards], len(shards[0]), true)
701 return nil
702 }
703
704 // EncodeIdx will add parity for a single data shard.
705 // Parity shards should start out zeroed. The caller must zero them before first call.
706 // Data shards should only be delivered once. There is no check for this.
707 // The parity shards will always be updated and the data shards will remain the unchanged.
708 func (r *reedSolomon) EncodeIdx(dataShard []byte, idx int, parity [][]byte) error {
709 if len(parity) != r.parityShards {
710 return ErrTooFewShards
711 }
712 if len(parity) == 0 {
713 return nil
714 }
715 if idx < 0 || idx >= r.dataShards {
716 return ErrInvShardNum
717 }
718 err := checkShards(parity, false)
719 if err != nil {
720 return err
721 }
722 if len(parity[0]) != len(dataShard) {
723 return ErrShardSize
724 }
725
726 if codeGen && len(dataShard) >= r.o.perRound && len(parity) >= codeGenMinShards && (pshufb || r.o.useAvx512GFNI || r.o.useAvxGNFI) {
727 m := make([][]byte, r.parityShards)
728 for iRow := range m {
729 m[iRow] = r.parity[iRow][idx : idx+1]
730 }
731 if r.o.useAvx512GFNI || r.o.useAvxGNFI {
732 r.codeSomeShardsGFNI(m, [][]byte{dataShard}, parity, len(dataShard), false, nil, nil)
733 } else {
734 r.codeSomeShardsAVXP(m, [][]byte{dataShard}, parity, len(dataShard), false, nil, nil)
735 }
736 return nil
737 }
738
739 // Process using no goroutines for now.
740 start, end := 0, r.o.perRound
741 if end > len(dataShard) {
742 end = len(dataShard)
743 }
744
745 for start < len(dataShard) {
746 in := dataShard[start:end]
747 for iRow := 0; iRow < r.parityShards; iRow++ {
748 galMulSliceXor(r.parity[iRow][idx], in, parity[iRow][start:end], &r.o)
749 }
750 start = end
751 end += r.o.perRound
752 if end > len(dataShard) {
753 end = len(dataShard)
754 }
755 }
756 return nil
757 }
758
759 // ErrInvalidInput is returned if invalid input parameter of Update.
760 var ErrInvalidInput = errors.New("invalid input")
761
762 func (r *reedSolomon) Update(shards [][]byte, newDatashards [][]byte) error {
763 if len(shards) != r.totalShards {
764 return ErrTooFewShards
765 }
766
767 if len(newDatashards) != r.dataShards {
768 return ErrTooFewShards
769 }
770
771 err := checkShards(shards, true)
772 if err != nil {
773 return err
774 }
775
776 err = checkShards(newDatashards, true)
777 if err != nil {
778 return err
779 }
780
781 for i := range newDatashards {
782 if newDatashards[i] != nil && shards[i] == nil {
783 return ErrInvalidInput
784 }
785 }
786 for _, p := range shards[r.dataShards:] {
787 if p == nil {
788 return ErrInvalidInput
789 }
790 }
791
792 shardSize := shardSize(shards)
793
794 // Get the slice of output buffers.
795 output := shards[r.dataShards:]
796
797 // Do the coding.
798 r.updateParityShards(r.parity, shards[0:r.dataShards], newDatashards[0:r.dataShards], output, r.parityShards, shardSize)
799 return nil
800 }
801
802 func (r *reedSolomon) updateParityShards(matrixRows, oldinputs, newinputs, outputs [][]byte, outputCount, byteCount int) {
803 if len(outputs) == 0 {
804 return
805 }
806
807 if r.o.maxGoroutines > 1 && byteCount > r.o.minSplitSize {
808 r.updateParityShardsP(matrixRows, oldinputs, newinputs, outputs, outputCount, byteCount)
809 return
810 }
811
812 for c := 0; c < r.dataShards; c++ {
813 in := newinputs[c]
814 if in == nil {
815 continue
816 }
817 oldin := oldinputs[c]
818 // oldinputs data will be changed
819 sliceXor(in, oldin, &r.o)
820 for iRow := range outputCount {
821 galMulSliceXor(matrixRows[iRow][c], oldin, outputs[iRow], &r.o)
822 }
823 }
824 }
825
826 func (r *reedSolomon) updateParityShardsP(matrixRows, oldinputs, newinputs, outputs [][]byte, outputCount, byteCount int) {
827 var wg sync.WaitGroup
828 do := max(byteCount/r.o.maxGoroutines, r.o.minSplitSize)
829 start := 0
830 for start < byteCount {
831 if start+do > byteCount {
832 do = byteCount - start
833 }
834 wg.Add(1)
835 go func(start, stop int) {
836 for c := 0; c < r.dataShards; c++ {
837 in := newinputs[c]
838 if in == nil {
839 continue
840 }
841 oldin := oldinputs[c]
842 // oldinputs data will be change
843 sliceXor(in[start:stop], oldin[start:stop], &r.o)
844 for iRow := range outputCount {
845 galMulSliceXor(matrixRows[iRow][c], oldin[start:stop], outputs[iRow][start:stop], &r.o)
846 }
847 }
848 wg.Done()
849 }(start, start+do)
850 start += do
851 }
852 wg.Wait()
853 }
854
855 // Verify returns true if the parity shards contain the right data.
856 // The data is the same format as Encode. No data is modified.
857 func (r *reedSolomon) Verify(shards [][]byte) (bool, error) {
858 if len(shards) != r.totalShards {
859 return false, ErrTooFewShards
860 }
861 err := checkShards(shards, false)
862 if err != nil {
863 return false, err
864 }
865
866 // Slice of buffers being checked.
867 toCheck := shards[r.dataShards:]
868
869 // Do the checking.
870 return r.checkSomeShards(r.parity, shards[:r.dataShards], toCheck[:r.parityShards], len(shards[0])), nil
871 }
872
873 // Multiplies a subset of rows from a coding matrix by a full set of
874 // input totalShards to produce some output totalShards.
875 // 'matrixRows' is The rows from the matrix to use.
876 // 'inputs' An array of byte arrays, each of which is one input shard.
877 // The number of inputs used is determined by the length of each matrix row.
878 // outputs Byte arrays where the computed totalShards are stored.
879 // The number of outputs computed, and the
880 // number of matrix rows used, is determined by
881 // outputCount, which is the number of outputs to compute.
882 func (r *reedSolomon) codeSomeShards(matrixRows, inputs, outputs [][]byte, byteCount int, clear bool) {
883 if len(outputs) == 0 {
884 return
885 }
886 if r.o.maxGoroutines > 1 && byteCount > r.o.minSplitSize {
887 r.codeSomeShardsP(matrixRows, inputs, outputs, byteCount, clear)
888 return
889 }
890
891 // Process using no goroutines
892 start, end := 0, r.o.perRound
893 if end > len(inputs[0]) {
894 end = len(inputs[0])
895 }
896 if galMulGFNI, galMulGFNIXor, useGFNI := r.canGFNI(byteCount, len(inputs), len(outputs)); useGFNI {
897 var gfni [codeGenMaxInputs * codeGenMaxOutputs]uint64
898 m := genGFNIMatrix(matrixRows, len(inputs), 0, len(outputs), gfni[:])
899 if clear {
900 start += (*galMulGFNI)(m, inputs, outputs, 0, byteCount)
901 } else {
902 start += (*galMulGFNIXor)(m, inputs, outputs, 0, byteCount)
903 }
904 end = len(inputs[0])
905 } else if galMulGen, galMulGenXor, ok := r.hasCodeGen(byteCount, len(inputs), len(outputs)); ok {
906 m := genCodeGenMatrix(matrixRows, len(inputs), 0, len(outputs), r.o.vectorLength, r.getTmpSlice())
907 if clear {
908 start += (*galMulGen)(m, inputs, outputs, 0, byteCount)
909 } else {
910 start += (*galMulGenXor)(m, inputs, outputs, 0, byteCount)
911 }
912 r.putTmpSlice(m)
913 end = len(inputs[0])
914 } else if galMulGen, galMulGenXor, ok := r.hasCodeGen(byteCount, codeGenMaxInputs, codeGenMaxOutputs); len(inputs)+len(outputs) > codeGenMinShards && ok {
915 var gfni [codeGenMaxInputs * codeGenMaxOutputs]uint64
916 end = len(inputs[0])
917 inIdx := 0
918 m := r.getTmpSlice()
919 defer r.putTmpSlice(m)
920 ins := inputs
921 for len(ins) > 0 {
922 inPer := ins
923 if len(inPer) > codeGenMaxInputs {
924 inPer = inPer[:codeGenMaxInputs]
925 }
926 outs := outputs
927 outIdx := 0
928 for len(outs) > 0 {
929 outPer := outs
930 if len(outPer) > codeGenMaxOutputs {
931 outPer = outPer[:codeGenMaxOutputs]
932 }
933 if useGFNI {
934 m := genGFNIMatrix(matrixRows[outIdx:], len(inPer), inIdx, len(outPer), gfni[:])
935 if inIdx == 0 && clear {
936 start = (*galMulGFNI)(m, inPer, outPer, 0, byteCount)
937 } else {
938 start = (*galMulGFNIXor)(m, inPer, outPer, 0, byteCount)
939 }
940 } else {
941 m = genCodeGenMatrix(matrixRows[outIdx:], len(inPer), inIdx, len(outPer), r.o.vectorLength, m)
942 if inIdx == 0 && clear {
943 start = (*galMulGen)(m, inPer, outPer, 0, byteCount)
944 } else {
945 start = (*galMulGenXor)(m, inPer, outPer, 0, byteCount)
946 }
947 }
948 outIdx += len(outPer)
949 outs = outs[len(outPer):]
950 }
951 inIdx += len(inPer)
952 ins = ins[len(inPer):]
953 }
954 if start >= end {
955 return
956 }
957 }
958 for start < len(inputs[0]) {
959 for c := range inputs {
960 in := inputs[c][start:end]
961 for iRow := range outputs {
962 if c == 0 && clear {
963 galMulSlice(matrixRows[iRow][c], in, outputs[iRow][start:end], &r.o)
964 } else {
965 galMulSliceXor(matrixRows[iRow][c], in, outputs[iRow][start:end], &r.o)
966 }
967 }
968 }
969 start = end
970 end += r.o.perRound
971 if end > len(inputs[0]) {
972 end = len(inputs[0])
973 }
974 }
975 }
976
977 // Perform the same as codeSomeShards, but split the workload into
978 // several goroutines.
979 func (r *reedSolomon) codeSomeShardsP(matrixRows, inputs, outputs [][]byte, byteCount int, clear bool) {
980 var wg sync.WaitGroup
981 gor := r.o.maxGoroutines
982
983 var genMatrix []byte
984 var gfniMatrix []uint64
985 galMulGen, galMulGenXor, useCodeGen := r.hasCodeGen(byteCount, len(inputs), len(outputs))
986 galMulGFNI, galMulGFNIXor, useGFNI := r.canGFNI(byteCount, len(inputs), len(outputs))
987 if useGFNI {
988 var tmp [codeGenMaxInputs * codeGenMaxOutputs]uint64
989 gfniMatrix = genGFNIMatrix(matrixRows, len(inputs), 0, len(outputs), tmp[:])
990 } else if useCodeGen {
991 genMatrix = genCodeGenMatrix(matrixRows, len(inputs), 0, len(outputs), r.o.vectorLength, r.getTmpSlice())
992 defer r.putTmpSlice(genMatrix)
993 } else if galMulGFNI, galMulGFNIXor, useGFNI := r.canGFNI(byteCount/4, codeGenMaxInputs, codeGenMaxOutputs); useGFNI &&
994 len(inputs)+len(outputs) > codeGenMinShards {
995 // It appears there is a switchover point at around 10MB where
996 // Regular processing is faster...
997 r.codeSomeShardsGFNI(matrixRows, inputs, outputs, byteCount, clear, galMulGFNI, galMulGFNIXor)
998 return
999 } else if galMulGen, galMulGenXor, ok := r.hasCodeGen(byteCount/4, codeGenMaxInputs, codeGenMaxOutputs); ok &&
1000 len(inputs)+len(outputs) > codeGenMinShards {
1001 // It appears there is a switchover point at around 10MB where
1002 // Regular processing is faster...
1003 r.codeSomeShardsAVXP(matrixRows, inputs, outputs, byteCount, clear, galMulGen, galMulGenXor)
1004 return
1005 }
1006
1007 do := max(byteCount/gor, r.o.minSplitSize)
1008
1009 exec := func(start, stop int) {
1010 if stop-start >= 64 {
1011 if useGFNI {
1012 if clear {
1013 start += (*galMulGFNI)(gfniMatrix, inputs, outputs, start, stop)
1014 } else {
1015 start += (*galMulGFNIXor)(gfniMatrix, inputs, outputs, start, stop)
1016 }
1017 } else if useCodeGen {
1018 if clear {
1019 start += (*galMulGen)(genMatrix, inputs, outputs, start, stop)
1020 } else {
1021 start += (*galMulGenXor)(genMatrix, inputs, outputs, start, stop)
1022 }
1023 }
1024 }
1025
1026 lstart, lstop := start, start+r.o.perRound
1027 if lstop > stop {
1028 lstop = stop
1029 }
1030 for lstart < stop {
1031 for c := range inputs {
1032 in := inputs[c][lstart:lstop]
1033 for iRow := range outputs {
1034 if c == 0 && clear {
1035 galMulSlice(matrixRows[iRow][c], in, outputs[iRow][lstart:lstop], &r.o)
1036 } else {
1037 galMulSliceXor(matrixRows[iRow][c], in, outputs[iRow][lstart:lstop], &r.o)
1038 }
1039 }
1040 }
1041 lstart = lstop
1042 lstop += r.o.perRound
1043 if lstop > stop {
1044 lstop = stop
1045 }
1046 }
1047 wg.Done()
1048 }
1049 if gor <= 1 {
1050 wg.Add(1)
1051 exec(0, byteCount)
1052 return
1053 }
1054
1055 // Make sizes divisible by 64
1056 do = (do + 63) & (^63)
1057 start := 0
1058 for start < byteCount {
1059 if start+do > byteCount {
1060 do = byteCount - start
1061 }
1062
1063 wg.Add(1)
1064 go exec(start, start+do)
1065 start += do
1066 }
1067 wg.Wait()
1068 }
1069
1070 // Perform the same as codeSomeShards, but split the workload into
1071 // several goroutines.
1072 // If clear is set, the first write will overwrite the output.
1073 func (r *reedSolomon) codeSomeShardsAVXP(matrixRows, inputs, outputs [][]byte, byteCount int, clear bool, galMulGen, galMulGenXor *func(matrix []byte, in [][]byte, out [][]byte, start int, stop int) int) {
1074 var wg sync.WaitGroup
1075 gor := r.o.maxGoroutines
1076
1077 type state struct {
1078 input [][]byte
1079 output [][]byte
1080 m []byte
1081 first bool
1082 }
1083 // Make a plan...
1084 plan := make([]state, 0, ((len(inputs)+codeGenMaxInputs-1)/codeGenMaxInputs)*((len(outputs)+codeGenMaxOutputs-1)/codeGenMaxOutputs))
1085
1086 tmp := r.getTmpSlice()
1087 defer r.putTmpSlice(tmp)
1088
1089 // Flips between input first to output first.
1090 // We put the smallest data load in the inner loop.
1091 if len(inputs) > len(outputs) {
1092 inIdx := 0
1093 ins := inputs
1094 for len(ins) > 0 {
1095 inPer := ins
1096 if len(inPer) > codeGenMaxInputs {
1097 inPer = inPer[:codeGenMaxInputs]
1098 }
1099 outs := outputs
1100 outIdx := 0
1101 for len(outs) > 0 {
1102 outPer := outs
1103 if len(outPer) > codeGenMaxOutputs {
1104 outPer = outPer[:codeGenMaxOutputs]
1105 }
1106 // Generate local matrix
1107 m := genCodeGenMatrix(matrixRows[outIdx:], len(inPer), inIdx, len(outPer), r.o.vectorLength, tmp)
1108 tmp = tmp[len(m):]
1109 plan = append(plan, state{
1110 input: inPer,
1111 output: outPer,
1112 m: m,
1113 first: inIdx == 0 && clear,
1114 })
1115 outIdx += len(outPer)
1116 outs = outs[len(outPer):]
1117 }
1118 inIdx += len(inPer)
1119 ins = ins[len(inPer):]
1120 }
1121 } else {
1122 outs := outputs
1123 outIdx := 0
1124 for len(outs) > 0 {
1125 outPer := outs
1126 if len(outPer) > codeGenMaxOutputs {
1127 outPer = outPer[:codeGenMaxOutputs]
1128 }
1129
1130 inIdx := 0
1131 ins := inputs
1132 for len(ins) > 0 {
1133 inPer := ins
1134 if len(inPer) > codeGenMaxInputs {
1135 inPer = inPer[:codeGenMaxInputs]
1136 }
1137 // Generate local matrix
1138 m := genCodeGenMatrix(matrixRows[outIdx:], len(inPer), inIdx, len(outPer), r.o.vectorLength, tmp)
1139 tmp = tmp[len(m):]
1140 //fmt.Println("bytes:", len(inPer)*r.o.perRound, "out:", len(outPer)*r.o.perRound)
1141 plan = append(plan, state{
1142 input: inPer,
1143 output: outPer,
1144 m: m,
1145 first: inIdx == 0 && clear,
1146 })
1147 inIdx += len(inPer)
1148 ins = ins[len(inPer):]
1149 }
1150 outIdx += len(outPer)
1151 outs = outs[len(outPer):]
1152 }
1153 }
1154
1155 do := max(byteCount/gor, r.o.minSplitSize)
1156
1157 exec := func(start, stop int) {
1158 defer wg.Done()
1159 lstart, lstop := start, start+r.o.perRound
1160 if lstop > stop {
1161 lstop = stop
1162 }
1163 for lstart < stop {
1164 if galMulGen != nil && galMulGenXor != nil && lstop-lstart >= minCodeGenSize {
1165 // Execute plan...
1166 var n int
1167 for _, p := range plan {
1168 if p.first {
1169 n = (*galMulGen)(p.m, p.input, p.output, lstart, lstop)
1170 } else {
1171 n = (*galMulGenXor)(p.m, p.input, p.output, lstart, lstop)
1172 }
1173 }
1174 lstart += n
1175 if lstart == lstop {
1176 lstop += r.o.perRound
1177 if lstop > stop {
1178 lstop = stop
1179 }
1180 continue
1181 }
1182 }
1183
1184 for c := range inputs {
1185 in := inputs[c][lstart:lstop]
1186 for iRow := range outputs {
1187 if c == 0 && clear {
1188 galMulSlice(matrixRows[iRow][c], in, outputs[iRow][lstart:lstop], &r.o)
1189 } else {
1190 galMulSliceXor(matrixRows[iRow][c], in, outputs[iRow][lstart:lstop], &r.o)
1191 }
1192 }
1193 }
1194 lstart = lstop
1195 lstop += r.o.perRound
1196 if lstop > stop {
1197 lstop = stop
1198 }
1199 }
1200 }
1201 if gor == 1 {
1202 wg.Add(1)
1203 exec(0, byteCount)
1204 return
1205 }
1206
1207 // Make sizes divisible by 64
1208 do = (do + 63) & (^63)
1209 start := 0
1210 for start < byteCount {
1211 if start+do > byteCount {
1212 do = byteCount - start
1213 }
1214
1215 wg.Add(1)
1216 go exec(start, start+do)
1217 start += do
1218 }
1219 wg.Wait()
1220 }
1221
1222 // Perform the same as codeSomeShards, but split the workload into
1223 // several goroutines.
1224 // If clear is set, the first write will overwrite the output.
1225 func (r *reedSolomon) codeSomeShardsGFNI(matrixRows, inputs, outputs [][]byte, byteCount int, clear bool, galMulGFNI, galMulGFNIXor *func(matrix []uint64, in, out [][]byte, start, stop int) int) {
1226 var wg sync.WaitGroup
1227 gor := r.o.maxGoroutines
1228
1229 type state struct {
1230 input [][]byte
1231 output [][]byte
1232 m []uint64
1233 first bool
1234 }
1235 // Make a plan...
1236 plan := make([]state, 0, ((len(inputs)+codeGenMaxInputs-1)/codeGenMaxInputs)*((len(outputs)+codeGenMaxOutputs-1)/codeGenMaxOutputs))
1237
1238 // Flips between input first to output first.
1239 // We put the smallest data load in the inner loop.
1240 if len(inputs) > len(outputs) {
1241 inIdx := 0
1242 ins := inputs
1243 for len(ins) > 0 {
1244 inPer := ins
1245 if len(inPer) > codeGenMaxInputs {
1246 inPer = inPer[:codeGenMaxInputs]
1247 }
1248 outs := outputs
1249 outIdx := 0
1250 for len(outs) > 0 {
1251 outPer := outs
1252 if len(outPer) > codeGenMaxOutputs {
1253 outPer = outPer[:codeGenMaxOutputs]
1254 }
1255 // Generate local matrix
1256 m := genGFNIMatrix(matrixRows[outIdx:], len(inPer), inIdx, len(outPer), make([]uint64, len(inPer)*len(outPer)))
1257 plan = append(plan, state{
1258 input: inPer,
1259 output: outPer,
1260 m: m,
1261 first: inIdx == 0 && clear,
1262 })
1263 outIdx += len(outPer)
1264 outs = outs[len(outPer):]
1265 }
1266 inIdx += len(inPer)
1267 ins = ins[len(inPer):]
1268 }
1269 } else {
1270 outs := outputs
1271 outIdx := 0
1272 for len(outs) > 0 {
1273 outPer := outs
1274 if len(outPer) > codeGenMaxOutputs {
1275 outPer = outPer[:codeGenMaxOutputs]
1276 }
1277
1278 inIdx := 0
1279 ins := inputs
1280 for len(ins) > 0 {
1281 inPer := ins
1282 if len(inPer) > codeGenMaxInputs {
1283 inPer = inPer[:codeGenMaxInputs]
1284 }
1285 // Generate local matrix
1286 m := genGFNIMatrix(matrixRows[outIdx:], len(inPer), inIdx, len(outPer), make([]uint64, len(inPer)*len(outPer)))
1287 //fmt.Println("bytes:", len(inPer)*r.o.perRound, "out:", len(outPer)*r.o.perRound)
1288 plan = append(plan, state{
1289 input: inPer,
1290 output: outPer,
1291 m: m,
1292 first: inIdx == 0 && clear,
1293 })
1294 inIdx += len(inPer)
1295 ins = ins[len(inPer):]
1296 }
1297 outIdx += len(outPer)
1298 outs = outs[len(outPer):]
1299 }
1300 }
1301
1302 do := max(byteCount/gor, r.o.minSplitSize)
1303
1304 exec := func(start, stop int) {
1305 defer wg.Done()
1306 lstart, lstop := start, start+r.o.perRound
1307 if lstop > stop {
1308 lstop = stop
1309 }
1310 for lstart < stop {
1311 if galMulGFNI != nil && galMulGFNIXor != nil && lstop-lstart >= minCodeGenSize {
1312 // Execute plan...
1313 var n int
1314 for _, p := range plan {
1315 if p.first {
1316 n = (*galMulGFNI)(p.m, p.input, p.output, lstart, lstop)
1317 } else {
1318 n = (*galMulGFNIXor)(p.m, p.input, p.output, lstart, lstop)
1319 }
1320 }
1321 lstart += n
1322 if lstart == lstop {
1323 lstop += r.o.perRound
1324 if lstop > stop {
1325 lstop = stop
1326 }
1327 continue
1328 }
1329 }
1330
1331 for c := range inputs {
1332 in := inputs[c][lstart:lstop]
1333 for iRow := range outputs {
1334 if c == 0 && clear {
1335 galMulSlice(matrixRows[iRow][c], in, outputs[iRow][lstart:lstop], &r.o)
1336 } else {
1337 galMulSliceXor(matrixRows[iRow][c], in, outputs[iRow][lstart:lstop], &r.o)
1338 }
1339 }
1340 }
1341 lstart = lstop
1342 lstop += r.o.perRound
1343 if lstop > stop {
1344 lstop = stop
1345 }
1346 }
1347 }
1348
1349 if gor == 1 {
1350 wg.Add(1)
1351 exec(0, byteCount)
1352 return
1353 }
1354
1355 // Make sizes divisible by 64
1356 do = (do + 63) & (^63)
1357 start := 0
1358 for start < byteCount {
1359 if start+do > byteCount {
1360 do = byteCount - start
1361 }
1362
1363 wg.Add(1)
1364 go exec(start, start+do)
1365 start += do
1366 }
1367 wg.Wait()
1368 }
1369
1370 // checkSomeShards is mostly the same as codeSomeShards,
1371 // except this will check values and return
1372 // as soon as a difference is found.
1373 func (r *reedSolomon) checkSomeShards(matrixRows, inputs, toCheck [][]byte, byteCount int) bool {
1374 if len(toCheck) == 0 {
1375 return true
1376 }
1377
1378 outputs := AllocAligned(len(toCheck), byteCount)
1379 r.codeSomeShards(matrixRows, inputs, outputs, byteCount, true)
1380
1381 for i, calc := range outputs {
1382 if !bytes.Equal(calc, toCheck[i]) {
1383 return false
1384 }
1385 }
1386 return true
1387 }
1388
1389 // ErrShardNoData will be returned if there are no shards,
1390 // or if the length of all shards is zero.
1391 var ErrShardNoData = errors.New("no shard data")
1392
1393 // ErrShardSize is returned if shard length isn't the same for all
1394 // shards.
1395 var ErrShardSize = errors.New("shard sizes do not match")
1396
1397 // ErrInvalidShardSize is returned if shard length doesn't meet the requirements,
1398 // typically a multiple of N.
1399 var ErrInvalidShardSize = errors.New("invalid shard size")
1400
1401 // checkShards will check if shards are the same size
1402 // or 0, if allowed. An error is returned if this fails.
1403 // An error is also returned if all shards are size 0.
1404 func checkShards(shards [][]byte, nilok bool) error {
1405 size := shardSize(shards)
1406 if size == 0 {
1407 return ErrShardNoData
1408 }
1409 for _, shard := range shards {
1410 if len(shard) != size {
1411 if len(shard) != 0 || !nilok {
1412 return ErrShardSize
1413 }
1414 }
1415 }
1416 return nil
1417 }
1418
1419 // shardSize return the size of a single shard.
1420 // The first non-zero size is returned,
1421 // or 0 if all shards are size 0.
1422 func shardSize(shards [][]byte) int {
1423 for _, shard := range shards {
1424 if len(shard) != 0 {
1425 return len(shard)
1426 }
1427 }
1428 return 0
1429 }
1430
1431 // Reconstruct will recreate the missing shards, if possible.
1432 //
1433 // Given a list of shards, some of which contain data, fills in the
1434 // ones that don't have data.
1435 //
1436 // The length of the array must be equal to shards.
1437 // You indicate that a shard is missing by setting it to nil or zero-length.
1438 // If a shard is zero-length but has sufficient capacity, that memory will
1439 // be used, otherwise a new []byte will be allocated.
1440 //
1441 // If there are too few shards to reconstruct the missing
1442 // ones, ErrTooFewShards will be returned.
1443 //
1444 // The reconstructed shard set is complete, but integrity is not verified.
1445 // Use the Verify function to check if data set is ok.
1446 func (r *reedSolomon) Reconstruct(shards [][]byte) error {
1447 return r.reconstruct(shards, false, nil)
1448 }
1449
1450 // DecodeIdx allows progressively decoding shards into dst.
1451 // Dst slices to be decoded should be filled.
1452 // On the first call, dst slices should be set to all zeros.
1453 // expectInput should be the same for all calls and should
1454 // represent the inputs that are expected to be added.
1455 // The number of expected inputs should at least be the number of data shards.
1456 // Each input should be sent once - and only once.
1457 // len(dst) must be = len(input).
1458 // All sent slices must be the same length.
1459 // The caller must manage all of the above.
1460 // Merging:
1461 // If 'expectInput == nil' no new input is added, but the slices are XORed together.
1462 // This means that the same slices as dst must be set in input.
1463 // This allows merging two separate inputs where a number of inputs has been filled.
1464 func (r *reedSolomon) DecodeIdx(dst [][]byte, expectInput []bool, input [][]byte) (err error) {
1465 // Special case: merging mode when expectInput == nil
1466 if expectInput == nil {
1467 if len(dst) != len(input) {
1468 return errors.Join(ErrInvalidInput, errors.New("dst and input must have same length for merging"))
1469 }
1470 // XOR each pair of slices
1471 for i := range dst {
1472 if input[i] != nil {
1473 if dst[i] == nil {
1474 return errors.Join(ErrInvalidInput, fmt.Errorf("input[%d] provided but dst[%d] is nil", i, i))
1475 }
1476 if len(dst[i]) != len(input[i]) {
1477 return errors.Join(ErrInvalidShardSize, fmt.Errorf("dst[%d] size %d != input[%d] size %d", i, len(dst[i]), i, len(input[i])))
1478 }
1479 sliceXor(input[i], dst[i], &r.o)
1480 }
1481 }
1482 return nil
1483 }
1484
1485 // Validate expectInput length
1486 if len(expectInput) != r.totalShards {
1487 return errors.Join(ErrInvalidInput, fmt.Errorf("expectInput length %d, expected %d", len(expectInput), r.totalShards))
1488 }
1489
1490 // Validate dst and input have same length as totalShards
1491 if len(dst) != r.totalShards {
1492 return errors.Join(ErrInvalidInput, fmt.Errorf("dst length %d, expected %d (totalShards)", len(dst), r.totalShards))
1493 }
1494 if len(input) != r.totalShards {
1495 return errors.Join(ErrInvalidInput, fmt.Errorf("input length %d, expected %d (totalShards)", len(input), r.totalShards))
1496 }
1497
1498 // Check for unexpected inputs first
1499 for inputIdx := range input {
1500 if input[inputIdx] != nil && !expectInput[inputIdx] {
1501 return errors.Join(ErrInvalidInput, fmt.Errorf("unexpected input at index %d (not marked in expectInput)", inputIdx))
1502 }
1503 }
1504
1505 // Check that dst shards are not allocated for expected inputs
1506 for i := range expectInput {
1507 if expectInput[i] && dst[i] != nil {
1508 return errors.Join(ErrInvalidInput, fmt.Errorf("dst[%d] should be nil (marked as input in expectInput)", i))
1509 }
1510 }
1511
1512 // Build valid and invalid indices from expectInput
1513 validIndices := make([]int, 0)
1514 invalidIndices := make([]int, 0)
1515 for i, filled := range expectInput {
1516 if filled {
1517 validIndices = append(validIndices, i)
1518 } else {
1519 invalidIndices = append(invalidIndices, i)
1520 }
1521 }
1522
1523 // We need at least dataShards valid indices for matrix inversion
1524 if len(validIndices) < r.dataShards {
1525 return errors.Join(ErrTooFewShards, fmt.Errorf("%d valid shards marked in expectInput, need at least %d", len(validIndices), r.dataShards))
1526 }
1527
1528 // Get the inverted matrix for decoding
1529 dataDecodeMatrix, err := r.getDecodeMatrix(validIndices, invalidIndices)
1530 if err != nil {
1531 return err
1532 }
1533
1534 // Verify shard sizes are consistent
1535 shardSize := 0
1536 for i := range input {
1537 if input[i] != nil {
1538 if shardSize == 0 {
1539 shardSize = len(input[i])
1540 } else if len(input[i]) != shardSize {
1541 return errors.Join(ErrInvalidShardSize, fmt.Errorf("input[%d] size %d != expected size %d", i, len(input[i]), shardSize))
1542 }
1543 }
1544 }
1545 for i := range dst {
1546 if dst[i] != nil {
1547 if len(dst[i]) != shardSize {
1548 return errors.Join(ErrInvalidShardSize, fmt.Errorf("dst[%d] size %d != expected size %d", i, len(dst[i]), shardSize))
1549 }
1550 }
1551 }
1552
1553 // Build matrix rows and output arrays for codeSomeShards
1554 outputCount := 0
1555 outputs := make([][]byte, 0, r.totalShards)
1556 matrixRows := make([][]byte, 0, r.totalShards)
1557
1558 for dstIdx := range dst {
1559 if dst[dstIdx] == nil {
1560 continue
1561 }
1562 outputs = append(outputs, dst[dstIdx])
1563
1564 // Build matrix row for this dst shard
1565 row := make([]byte, len(validIndices))
1566 if dstIdx < r.dataShards {
1567 // Data shard: use inverted matrix row directly
1568 copy(row, dataDecodeMatrix[dstIdx])
1569 } else {
1570 // Parity shard: multiply parity row with inverted matrix
1571 parityIdx := dstIdx - r.dataShards
1572 for col := 0; col < len(validIndices) && col < r.dataShards; col++ {
1573 row[col] = 0
1574 for i := 0; i < r.dataShards; i++ {
1575 row[col] ^= galMultiply(r.parity[parityIdx][i], dataDecodeMatrix[i][col])
1576 }
1577 }
1578 }
1579 matrixRows = append(matrixRows, row)
1580 outputCount++
1581 }
1582
1583 if outputCount == 0 {
1584 return nil
1585 }
1586
1587 // Build input array from available shards
1588 inputs := make([][]byte, 0, len(validIndices))
1589 actualInputIndices := make([]int, 0, len(validIndices))
1590 for col := 0; col < len(validIndices); col++ {
1591 inputIdx := validIndices[col]
1592 if inputIdx < len(input) && input[inputIdx] != nil {
1593 inputs = append(inputs, input[inputIdx])
1594 actualInputIndices = append(actualInputIndices, col)
1595 }
1596 }
1597
1598 // If no inputs are provided in this call, nothing to do
1599 if len(inputs) == 0 {
1600 return nil
1601 }
1602
1603 // Adjust matrix rows to only include columns for available inputs
1604 adjustedMatrixRows := make([][]byte, len(matrixRows))
1605 for i, row := range matrixRows {
1606 adjustedRow := make([]byte, len(actualInputIndices))
1607 for j, colIdx := range actualInputIndices {
1608 adjustedRow[j] = row[colIdx]
1609 }
1610 adjustedMatrixRows[i] = adjustedRow
1611 }
1612
1613 // Use codeSomeShards for efficient matrix multiplication
1614 // Always accumulate (never clear) - caller provides zeroed slices
1615 r.codeSomeShards(adjustedMatrixRows, inputs, outputs, shardSize, false)
1616 return nil
1617 }
1618
1619 // ReconstructData will recreate any missing data shards, if possible.
1620 //
1621 // Given a list of shards, some of which contain data, fills in the
1622 // data shards that don't have data.
1623 //
1624 // The length of the array must be equal to shards.
1625 // You indicate that a shard is missing by setting it to nil or zero-length.
1626 // If a shard is zero-length but has sufficient capacity, that memory will
1627 // be used, otherwise a new []byte will be allocated.
1628 //
1629 // If there are too few shards to reconstruct the missing
1630 // ones, ErrTooFewShards will be returned.
1631 //
1632 // As the reconstructed shard set may contain missing parity shards,
1633 // calling the Verify function is likely to fail.
1634 func (r *reedSolomon) ReconstructData(shards [][]byte) error {
1635 return r.reconstruct(shards, true, nil)
1636 }
1637
1638 // ReconstructSome will recreate only requested shards, if possible.
1639 //
1640 // Given a list of shards, some of which contain data, fills in the
1641 // shards indicated by true values in the "required" parameter.
1642 // The length of the "required" array must be equal to either Shards or DataShards.
1643 // If the length is equal to DataShards, the reconstruction of parity shards will be ignored.
1644 //
1645 // The length of "shards" array must be equal to Shards.
1646 // You indicate that a shard is missing by setting it to nil or zero-length.
1647 // If a shard is zero-length but has sufficient capacity, that memory will
1648 // be used, otherwise a new []byte will be allocated.
1649 //
1650 // If there are too few shards to reconstruct the missing
1651 // ones, ErrTooFewShards will be returned.
1652 //
1653 // As the reconstructed shard set may contain missing parity shards,
1654 // calling the Verify function is likely to fail.
1655 func (r *reedSolomon) ReconstructSome(shards [][]byte, required []bool) error {
1656 if len(required) != r.dataShards && len(required) != r.totalShards {
1657 return ErrInvalidInput
1658 }
1659 return r.reconstruct(shards, len(required) == r.dataShards, required)
1660 }
1661
1662 // reconstruct will recreate the missing data totalShards, and unless
1663 // dataOnly is true, also the missing parity totalShards
1664 //
1665 // The length of "shards" array must be equal to totalShards.
1666 // You indicate that a shard is missing by setting it to nil.
1667 //
1668 // If there are too few totalShards to reconstruct the missing
1669 // ones, ErrTooFewShards will be returned.
1670 func (r *reedSolomon) reconstruct(shards [][]byte, dataOnly bool, required []bool) error {
1671 if len(shards) != r.totalShards || required != nil && len(required) < r.dataShards {
1672 return ErrTooFewShards
1673 }
1674 // Check arguments.
1675 err := checkShards(shards, true)
1676 if err != nil {
1677 return err
1678 }
1679
1680 shardSize := shardSize(shards)
1681
1682 // Quick check: are all of the shards present? If so, there's
1683 // nothing to do.
1684 numberPresent := 0
1685 dataPresent := 0
1686 missingRequired := 0
1687 for i := 0; i < r.totalShards; i++ {
1688 if len(shards[i]) != 0 {
1689 numberPresent++
1690 if i < r.dataShards {
1691 dataPresent++
1692 }
1693 } else if required != nil {
1694 if required[i] {
1695 missingRequired++
1696 }
1697 }
1698 }
1699 if numberPresent == r.totalShards || dataOnly && dataPresent == r.dataShards ||
1700 required != nil && missingRequired == 0 {
1701 // Cool. All of the shards have data. We don't
1702 // need to do anything.
1703 return nil
1704 }
1705
1706 // More complete sanity check
1707 if numberPresent < r.dataShards {
1708 return ErrTooFewShards
1709 }
1710
1711 // Pull out an array holding just the shards that
1712 // correspond to the rows of the submatrix. These shards
1713 // will be the input to the decoding process that re-creates
1714 // the missing data shards.
1715 //
1716 // Also, create an array of indices of the valid rows we do have
1717 // and the invalid rows we don't have up until we have enough valid rows.
1718 subShards := make([][]byte, r.dataShards)
1719 validIndices := make([]int, r.dataShards)
1720 invalidIndices := make([]int, 0)
1721 subMatrixRow := 0
1722 for matrixRow := 0; matrixRow < r.totalShards && subMatrixRow < r.dataShards; matrixRow++ {
1723 if len(shards[matrixRow]) != 0 {
1724 subShards[subMatrixRow] = shards[matrixRow]
1725 validIndices[subMatrixRow] = matrixRow
1726 subMatrixRow++
1727 } else {
1728 invalidIndices = append(invalidIndices, matrixRow)
1729 }
1730 }
1731
1732 // Get the inverted matrix for decoding
1733 dataDecodeMatrix, err := r.getDecodeMatrix(validIndices, invalidIndices)
1734 if err != nil {
1735 return err
1736 }
1737
1738 // Unified reconstruction: build a single decode matrix for all missing shards
1739 // and reconstruct them in one codeSomeShards call.
1740 outputCount := 0
1741 outputs := make([][]byte, r.totalShards)
1742 matrixRows := make([][]byte, r.totalShards)
1743
1744 // Count and prepare missing data shards
1745 for iShard := 0; iShard < r.dataShards; iShard++ {
1746 if len(shards[iShard]) == 0 && (required == nil || required[iShard]) {
1747 if cap(shards[iShard]) >= shardSize {
1748 shards[iShard] = shards[iShard][0:shardSize]
1749 } else {
1750 shards[iShard] = AllocAligned(1, shardSize)[0]
1751 }
1752 outputs[outputCount] = shards[iShard]
1753 matrixRows[outputCount] = dataDecodeMatrix[iShard]
1754 outputCount++
1755 }
1756 }
1757
1758 if !dataOnly {
1759 // Count and prepare missing parity shards
1760 for iShard := r.dataShards; iShard < r.totalShards; iShard++ {
1761 if len(shards[iShard]) == 0 && (required == nil || required[iShard]) {
1762 if cap(shards[iShard]) >= shardSize {
1763 shards[iShard] = shards[iShard][0:shardSize]
1764 } else {
1765 shards[iShard] = AllocAligned(1, shardSize)[0]
1766 }
1767 outputs[outputCount] = shards[iShard]
1768 // For parity shards, multiply parity row with inverted matrix
1769 parityIdx := iShard - r.dataShards
1770 matrixRows[outputCount] = multiplyRowWithMatrix(r.parity[parityIdx], dataDecodeMatrix)
1771 outputCount++
1772 }
1773 }
1774 }
1775
1776 // Single reconstruction call for all missing shards
1777 if outputCount > 0 {
1778 r.codeSomeShards(matrixRows[:outputCount], subShards, outputs[:outputCount], shardSize, true)
1779 }
1780 return nil
1781 }
1782
1783 // ErrShortData will be returned by Split(), if there isn't enough data
1784 // to fill the number of shards.
1785 var ErrShortData = errors.New("not enough data to fill the number of requested shards")
1786
1787 // Split a data slice into the number of shards given to the encoder,
1788 // and create empty parity shards if necessary.
1789 //
1790 // The data will be split into equally sized shards.
1791 // If the data size isn't divisible by the number of shards,
1792 // the last shard will contain extra zeros.
1793 //
1794 // If there is extra capacity on the provided data slice
1795 // it will be used instead of allocating parity shards.
1796 // It will be zeroed out.
1797 //
1798 // There must be at least 1 byte otherwise ErrShortData will be
1799 // returned.
1800 //
1801 // The data will not be copied, except for the last shard, so you
1802 // should not modify the data of the input slice afterwards.
1803 func (r *reedSolomon) Split(data []byte) ([][]byte, error) {
1804 if len(data) == 0 {
1805 return nil, ErrShortData
1806 }
1807 if r.totalShards == 1 {
1808 return [][]byte{data}, nil
1809 }
1810
1811 dataLen := len(data)
1812 // Calculate number of bytes per data shard.
1813 perShard := (len(data) + r.dataShards - 1) / r.dataShards
1814 needTotal := r.totalShards * perShard
1815
1816 if cap(data) > len(data) {
1817 if cap(data) > needTotal {
1818 data = data[:needTotal]
1819 } else {
1820 data = data[:cap(data)]
1821 }
1822 clear(data[dataLen:])
1823 }
1824
1825 // Only allocate memory if necessary
1826 var padding [][]byte
1827 if len(data) < needTotal {
1828 // calculate maximum number of full shards in `data` slice
1829 fullShards := len(data) / perShard
1830 padding = AllocAligned(r.totalShards-fullShards, perShard)
1831
1832 if dataLen > perShard*fullShards {
1833 // Copy partial shards
1834 copyFrom := data[perShard*fullShards : dataLen]
1835 for i := range padding {
1836 if len(copyFrom) == 0 {
1837 break
1838 }
1839 copyFrom = copyFrom[copy(padding[i], copyFrom):]
1840 }
1841 }
1842 }
1843
1844 // Split into equal-length shards.
1845 dst := make([][]byte, r.totalShards)
1846 i := 0
1847 for ; i < len(dst) && len(data) >= perShard; i++ {
1848 dst[i] = data[:perShard:perShard]
1849 data = data[perShard:]
1850 }
1851
1852 for j := 0; i+j < len(dst); j++ {
1853 dst[i+j] = padding[0]
1854 padding = padding[1:]
1855 }
1856
1857 return dst, nil
1858 }
1859
1860 // ErrReconstructRequired is returned if too few data shards are intact and a
1861 // reconstruction is required before you can successfully join the shards.
1862 var ErrReconstructRequired = errors.New("reconstruction required as one or more required data shards are nil")
1863
1864 // Join the shards and write the data segment to dst.
1865 //
1866 // Only the data shards are considered.
1867 // You must supply the exact output size you want.
1868 //
1869 // If there are to few shards given, ErrTooFewShards will be returned.
1870 // If the total data size is less than outSize, ErrShortData will be returned.
1871 // If one or more required data shards are nil, ErrReconstructRequired will be returned.
1872 func (r *reedSolomon) Join(dst io.Writer, shards [][]byte, outSize int) error {
1873 // Do we have enough shards?
1874 if len(shards) < r.dataShards {
1875 return ErrTooFewShards
1876 }
1877 shards = shards[:r.dataShards]
1878
1879 // Do we have enough data?
1880 size := 0
1881 for _, shard := range shards {
1882 if shard == nil {
1883 return ErrReconstructRequired
1884 }
1885 size += len(shard)
1886
1887 // Do we have enough data already?
1888 if size >= outSize {
1889 break
1890 }
1891 }
1892 if size < outSize {
1893 return ErrShortData
1894 }
1895
1896 // Copy data to dst
1897 write := outSize
1898 for _, shard := range shards {
1899 if write < len(shard) {
1900 _, err := dst.Write(shard[:write])
1901 return err
1902 }
1903 n, err := dst.Write(shard)
1904 if err != nil {
1905 return err
1906 }
1907 write -= n
1908 }
1909 return nil
1910 }
1911
1912 type indexer interface {
1913 int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
1914 }