Debian Codegraph @

leopard.go

raw
1 package reedsolomon
2
3 // This is a O(n*log n) implementation of Reed-Solomon
4 // codes, ported from the C++ library https://github.com/catid/leopard.
5 //
6 // The implementation is based on the paper
7 //
8 // S.-J. Lin, T. Y. Al-Naffouri, Y. S. Han, and W.-H. Chung,
9 // "Novel Polynomial Basis with Fast Fourier Transform
10 // and Its Application to Reed-Solomon Erasure Codes"
11 // IEEE Trans. on Information Theory, pp. 6284-6299, November, 2016.
12
13 import (
14 "bytes"
15 "io"
16 "math/bits"
17 "sync"
18 "unsafe"
19
20 "github.com/klauspost/cpuid/v2"
21 )
22
23 const maxWorkSize16 = 64 << 10 // Cap for GF16 chunk size.
24 const maxZeroBufferSize16 = maxWorkSize16
25
26 var zeroBufferPool16Once sync.Once
27 var zeroBufferPool16Buf *[maxZeroBufferSize16]byte
28 var zeroBufferPool16 = func() *[maxZeroBufferSize16]byte {
29 zeroBufferPool16Once.Do(func() {
30 zeroBufferPool16Buf = &[maxZeroBufferSize16]byte{}
31 })
32 return zeroBufferPool16Buf
33 }
34
35 // leopardFF16 is like reedSolomon but for more than 256 total shards.
36 type leopardFF16 struct {
37 dataShards int // Number of data shards, should not be modified.
38 parityShards int // Number of parity shards, should not be modified.
39 totalShards int // Total number of shards. Calculated, and should not be modified.
40
41 workAlloc WorkAllocator
42
43 // Pools for slice header arrays, avoiding per-call allocations.
44 shardSlicePool sync.Pool // [][]byte of len totalShards
45 workSlicePool sync.Pool // [][]byte — sized at first use
46
47 o options
48 }
49
50 // newFF16 is like New, but for more than 256 total shards.
51 func newFF16(dataShards, parityShards int, opt options) (*leopardFF16, error) {
52 initConstants()
53
54 if dataShards <= 0 || parityShards <= 0 {
55 return nil, ErrInvShardNum
56 }
57
58 if dataShards+parityShards > 65536 {
59 return nil, ErrMaxShardNum
60 }
61
62 r := &leopardFF16{
63 dataShards: dataShards,
64 parityShards: parityShards,
65 totalShards: dataShards + parityShards,
66 workAlloc: opt.workAlloc,
67 o: opt,
68 }
69 return r, nil
70 }
71
72 var _ = Extensions(&leopardFF16{})
73
74 func (r *leopardFF16) ShardSizeMultiple() int {
75 return 64
76 }
77
78 func (r *leopardFF16) DataShards() int {
79 return r.dataShards
80 }
81
82 func (r *leopardFF16) ParityShards() int {
83 return r.parityShards
84 }
85
86 func (r *leopardFF16) TotalShards() int {
87 return r.totalShards
88 }
89
90 func (r *leopardFF16) AllocAligned(each int) [][]byte {
91 return AllocAligned(r.totalShards, each)
92 }
93
94 func (r *leopardFF16) DecodeIdx(dst [][]byte, expectInput []bool, input [][]byte) error {
95 return ErrNotSupported
96 }
97
98 type ffe uint16
99
100 const (
101 bitwidth = 16
102 order = 1 << bitwidth
103 modulus = order - 1
104 polynomial = 0x1002D
105 )
106
107 var (
108 fftSkew *[modulus]ffe
109 logWalsh *[order]ffe
110 )
111
112 // Logarithm Tables
113 var (
114 logLUT *[order]ffe
115 expLUT *[order]ffe
116 )
117
118 // Stores the partial products of x * y at offset x + y * 65536
119 // Repeated accesses from the same y value are faster
120 var mul16LUTs *[order]mul16LUT
121
122 type mul16LUT struct {
123 // Contains Lo product as a single lookup.
124 // Should be XORed with Hi lookup for result.
125 Lo [256]ffe
126 Hi [256]ffe
127 }
128
129 // Stores lookup for avx2
130 var multiply256LUT *[order][8 * 16]byte
131
132 // Stores GFNI transformation matrices for GF16.
133 // Each entry contains 4 uint64 matrices [A, B, C, D] representing:
134 //
135 // [out_lo] [A B] [in_lo]
136 // [out_hi] = [C D] [in_hi]
137 var gf2p811dMulMatrices16 *[order][4]uint64
138
139 func (r *leopardFF16) Encode(shards [][]byte) error {
140 if len(shards) != r.totalShards {
141 return ErrTooFewShards
142 }
143
144 if err := checkShards(shards, false); err != nil {
145 return err
146 }
147 return r.encode(shards)
148 }
149
150 // encodeChunkSize returns the chunk size for the given shard size and
151 // number of work buffers. It tries to keep the working set in L3 cache,
152 // capped at maxWorkSize16.
153 func encodeChunkSize(shardSize, workBufs int) int {
154 l3 := cpuid.CPU.Cache.L3
155 if l3 <= 0 {
156 // Assume 16MB L3 if not detected.
157 l3 = 16 << 20
158 }
159 // Target: workBufs * chunkSize fits in ~2/3 of L3.
160 chunkSize := l3 * 2 / (workBufs * 3)
161 chunkSize = min(chunkSize, maxWorkSize16)
162 chunkSize &^= 63 // 64-byte alignment
163 if chunkSize < 4<<10 {
164 chunkSize = 4 << 10
165 }
166 return min(chunkSize, shardSize)
167 }
168
169 func (r *leopardFF16) encode(shards [][]byte) error {
170 shardSize := shardSize(shards)
171 if shardSize%64 != 0 {
172 return ErrInvalidShardSize
173 }
174
175 m := ceilPow2(r.parityShards)
176 mtrunc := min(r.dataShards, m)
177 lastCount := r.dataShards % m
178 chunkSize := encodeChunkSize(shardSize, m*2)
179
180 work := r.workAlloc.Get(m*2, chunkSize)
181 defer r.workAlloc.Put(work)
182
183 skewLUT := fftSkew[m-1:]
184
185 sh := r.getShardSlice()
186 defer r.putShardSlice(sh)
187 wMod := r.getWorkSlice(len(work))
188 defer r.putWorkSlice(wMod)
189 copy(wMod, work)
190 for off := 0; off < shardSize; off += chunkSize {
191 work := wMod
192 sh := sh
193 end := off + chunkSize
194 if end > shardSize {
195 end = shardSize
196 sz := end - off
197 for i := range work {
198 work[i] = work[i][:sz]
199 }
200 }
201 for i := range shards {
202 sh[i] = shards[i][off:end]
203 }
204
205 // Write parity directly into output slices.
206 res := shards[r.dataShards:r.totalShards]
207 for i := range res {
208 work[i] = res[i][off:end]
209 }
210
211 r.encodeChunk(sh[:r.dataShards], sh, mtrunc, lastCount, m, work, skewLUT)
212 }
213 return nil
214 }
215
216 func (r *leopardFF16) encodeChunk(data [][]byte, sh [][]byte, mtrunc, lastCount, m int, work [][]byte, skewLUT []ffe) {
217 ifftDITEncoder(
218 data,
219 mtrunc,
220 work,
221 nil,
222 m,
223 skewLUT,
224 &r.o,
225 )
226
227 if m >= r.dataShards {
228 goto skip_body
229 }
230
231 {
232 sh := sh
233 skewLUT := skewLUT
234 // For sets of m data pieces:
235 for i := m; i+m <= r.dataShards; i += m {
236 sh = sh[m:]
237 skewLUT = skewLUT[m:]
238
239 // work <- work xor IFFT(data + i, m, m + i)
240 ifftDITEncoder(
241 sh,
242 m,
243 work[m:],
244 work,
245 m,
246 skewLUT,
247 &r.o,
248 )
249 }
250
251 // Handle final partial set of m pieces:
252 if lastCount != 0 {
253 sh = sh[m:]
254 skewLUT = skewLUT[m:]
255
256 ifftDITEncoder(
257 sh,
258 lastCount,
259 work[m:],
260 work,
261 m,
262 skewLUT,
263 &r.o,
264 )
265 }
266 }
267
268 skip_body:
269 fftDIT(work, r.parityShards, m, fftSkew[:], &r.o)
270 }
271
272 func (r *leopardFF16) EncodeIdx(dataShard []byte, idx int, parity [][]byte) error {
273 return ErrNotSupported
274 }
275
276 func (r *leopardFF16) Join(dst io.Writer, shards [][]byte, outSize int) error {
277 // Do we have enough shards?
278 if len(shards) < r.dataShards {
279 return ErrTooFewShards
280 }
281 shards = shards[:r.dataShards]
282
283 // Do we have enough data?
284 size := 0
285 for _, shard := range shards {
286 if shard == nil {
287 return ErrReconstructRequired
288 }
289 size += len(shard)
290
291 // Do we have enough data already?
292 if size >= outSize {
293 break
294 }
295 }
296 if size < outSize {
297 return ErrShortData
298 }
299
300 // Copy data to dst
301 write := outSize
302 for _, shard := range shards {
303 if write < len(shard) {
304 _, err := dst.Write(shard[:write])
305 return err
306 }
307 n, err := dst.Write(shard)
308 if err != nil {
309 return err
310 }
311 write -= n
312 }
313 return nil
314 }
315
316 func (r *leopardFF16) Update(shards [][]byte, newDatashards [][]byte) error {
317 return ErrNotSupported
318 }
319
320 func (r *leopardFF16) Split(data []byte) ([][]byte, error) {
321 if len(data) == 0 {
322 return nil, ErrShortData
323 }
324 if r.totalShards == 1 && len(data)&63 == 0 {
325 return [][]byte{data}, nil
326 }
327 dataLen := len(data)
328 // Calculate number of bytes per data shard.
329 perShard := (len(data) + r.dataShards - 1) / r.dataShards
330 perShard = ((perShard + 63) / 64) * 64
331 needTotal := r.totalShards * perShard
332
333 if cap(data) > len(data) {
334 if cap(data) > needTotal {
335 data = data[:needTotal]
336 } else {
337 data = data[:cap(data)]
338 }
339 clear(data[dataLen:])
340 }
341
342 // Only allocate memory if necessary
343 var padding [][]byte
344 if len(data) < needTotal {
345 // calculate maximum number of full shards in `data` slice
346 fullShards := len(data) / perShard
347 padding = AllocAligned(r.totalShards-fullShards, perShard)
348 if dataLen > perShard*fullShards {
349 // Copy partial shards
350 copyFrom := data[perShard*fullShards : dataLen]
351 for i := range padding {
352 if len(copyFrom) == 0 {
353 break
354 }
355 copyFrom = copyFrom[copy(padding[i], copyFrom):]
356 }
357 }
358 } else {
359 clear(data[dataLen : r.totalShards*perShard])
360 }
361
362 // Split into equal-length shards.
363 dst := make([][]byte, r.totalShards)
364 i := 0
365 for ; i < len(dst) && len(data) >= perShard; i++ {
366 dst[i] = data[:perShard:perShard]
367 data = data[perShard:]
368 }
369
370 for j := 0; i+j < len(dst); j++ {
371 dst[i+j] = padding[0]
372 padding = padding[1:]
373 }
374
375 return dst, nil
376 }
377
378 func (r *leopardFF16) ReconstructSome(shards [][]byte, required []bool) error {
379 if len(required) == r.totalShards {
380 return r.reconstruct(shards, true)
381 }
382 return r.reconstruct(shards, false)
383 }
384
385 func (r *leopardFF16) Reconstruct(shards [][]byte) error {
386 return r.reconstruct(shards, true)
387 }
388
389 func (r *leopardFF16) ReconstructData(shards [][]byte) error {
390 return r.reconstruct(shards, false)
391 }
392
393 func (r *leopardFF16) Verify(shards [][]byte) (bool, error) {
394 if len(shards) != r.totalShards {
395 return false, ErrTooFewShards
396 }
397 if err := checkShards(shards, false); err != nil {
398 return false, err
399 }
400
401 // Re-encode parity shards to temporary storage.
402 shardSize := len(shards[0])
403 outputs := make([][]byte, r.totalShards)
404 copy(outputs, shards[:r.dataShards])
405 for i := r.dataShards; i < r.totalShards; i++ {
406 outputs[i] = make([]byte, shardSize)
407 }
408 if err := r.Encode(outputs); err != nil {
409 return false, err
410 }
411
412 // Compare.
413 for i := r.dataShards; i < r.totalShards; i++ {
414 if !bytes.Equal(outputs[i], shards[i]) {
415 return false, nil
416 }
417 }
418 return true, nil
419 }
420
421 func (r *leopardFF16) reconstruct(shards [][]byte, recoverAll bool) error {
422 if len(shards) != r.totalShards {
423 return ErrTooFewShards
424 }
425
426 if err := checkShards(shards, true); err != nil {
427 return err
428 }
429
430 // Quick check: are all of the shards present? If so, there's
431 // nothing to do.
432 numberPresent := 0
433 dataPresent := 0
434 for i := 0; i < r.totalShards; i++ {
435 if len(shards[i]) != 0 {
436 numberPresent++
437 if i < r.dataShards {
438 dataPresent++
439 }
440 }
441 }
442 if numberPresent == r.totalShards || !recoverAll && dataPresent == r.dataShards {
443 // Cool. All of the shards have data. We don't
444 // need to do anything.
445 return nil
446 }
447
448 // Use only if the requested reconstruction set is sparse. ReconstructData
449 // ignores missing parity shards, so gating this on total missing shards
450 // disables the sparse FFT path for data-only recovery with many absent
451 // parity shards. Data-only recovery computes at most dataShards outputs
452 // from m+dataShards possible FFT outputs, so use the sparse path there.
453 useBits := !recoverAll || r.totalShards-numberPresent <= r.parityShards/4
454
455 // Check if we have enough to reconstruct.
456 if numberPresent < r.dataShards {
457 return ErrTooFewShards
458 }
459
460 shardSize := shardSize(shards)
461 if shardSize%64 != 0 {
462 return ErrInvalidShardSize
463 }
464
465 m := ceilPow2(r.parityShards)
466 n := ceilPow2(m + r.dataShards)
467
468 const LEO_ERROR_BITFIELD_OPT = true
469
470 // Fill in error locations.
471 var errorBits errorBitfield
472 var errLocs [order]ffe
473 inputCount := r.parityShards
474 for i := 0; i < r.parityShards; i++ {
475 if len(shards[i+r.dataShards]) == 0 {
476 errLocs[i] = 1
477 if LEO_ERROR_BITFIELD_OPT && recoverAll {
478 errorBits.set(i)
479 }
480 }
481 }
482 for i := r.parityShards; i < m; i++ {
483 errLocs[i] = 1
484 if LEO_ERROR_BITFIELD_OPT && recoverAll {
485 errorBits.set(i)
486 }
487 }
488 for i := 0; i < r.dataShards; i++ {
489 if len(shards[i]) == 0 {
490 errLocs[i+m] = 1
491 if LEO_ERROR_BITFIELD_OPT {
492 errorBits.set(i + m)
493 }
494 } else {
495 inputCount = m + i + 1
496 }
497 }
498
499 if LEO_ERROR_BITFIELD_OPT && useBits {
500 errorBits.prepare(n)
501 }
502
503 // Evaluate error locator polynomial
504 fwht(&errLocs, m+r.dataShards)
505
506 for i := range order {
507 errLocs[i] = ffe((uint(errLocs[i]) * uint(logWalsh[i])) % modulus)
508 }
509
510 fwht(&errLocs, order)
511
512 chunkSize := encodeChunkSize(shardSize, n)
513
514 work := r.workAlloc.Get(n, chunkSize)
515 defer r.workAlloc.Put(work)
516
517 // sh preserves the original nil entries so reconstructChunk can
518 // distinguish present vs missing shards after pre-allocation.
519 sh := r.getShardSlice()
520 defer r.putShardSlice(sh)
521 copy(sh, shards)
522
523 // Pre-allocate missing output shards.
524 end := r.dataShards
525 if recoverAll {
526 end = r.totalShards
527 }
528 for i := 0; i < end; i++ {
529 if len(shards[i]) != 0 {
530 continue
531 }
532 if cap(shards[i]) >= shardSize {
533 shards[i] = shards[i][:shardSize]
534 } else {
535 shards[i] = make([]byte, shardSize)
536 }
537 }
538
539 if chunkSize >= shardSize {
540 r.reconstructChunk(sh, shards, work, m, n, inputCount, &errLocs, useBits, &errorBits, recoverAll)
541 return nil
542 }
543
544 // Process in cache-friendly chunks.
545 wMod := r.getWorkSlice(len(work))
546 defer r.putWorkSlice(wMod)
547 copy(wMod, work)
548 shChunk := r.getShardSlice()
549 defer r.putShardSlice(shChunk)
550 copy(shChunk, sh)
551 outChunk := r.getShardSlice()
552 defer r.putShardSlice(outChunk)
553 for off := 0; off < shardSize; off += chunkSize {
554 work := wMod
555 shChunk := shChunk
556 outChunk := outChunk
557 endSlice := off + chunkSize
558 if endSlice > shardSize {
559 endSlice = shardSize
560 sz := endSlice - off
561 for i := range work {
562 work[i] = work[i][:sz]
563 }
564 }
565 for i := range shards {
566 if len(sh[i]) != 0 {
567 shChunk[i] = shards[i][off:endSlice]
568 }
569 if len(shards[i]) != 0 {
570 outChunk[i] = shards[i][off:endSlice]
571 }
572 }
573
574 r.reconstructChunk(shChunk, outChunk, work, m, n, inputCount, &errLocs, useBits, &errorBits, recoverAll)
575 }
576 return nil
577 }
578
579 // reconstructChunk processes one chunk of the reconstruct pipeline.
580 // sh has nil entries for missing shards (used for presence checks).
581 // out has allocated entries for all shards (used for writing output).
582 func (r *leopardFF16) reconstructChunk(sh, out [][]byte, work [][]byte, m, n, inputCount int, errLocs *[order]ffe, useBits bool, errorBits *errorBitfield, recoverAll bool) {
583 const LEO_ERROR_BITFIELD_OPT = true
584 outputCount := m + r.dataShards
585
586 // work <- recovery data
587 for i := 0; i < r.parityShards; i++ {
588 if len(sh[i+r.dataShards]) != 0 {
589 mulgf16(work[i], sh[i+r.dataShards], errLocs[i], &r.o)
590 } else {
591 clear(work[i])
592 }
593 }
594 for i := r.parityShards; i < m; i++ {
595 clear(work[i])
596 }
597
598 // work <- original data
599 for i := 0; i < r.dataShards; i++ {
600 if len(sh[i]) != 0 {
601 mulgf16(work[m+i], sh[i], errLocs[m+i], &r.o)
602 } else {
603 clear(work[m+i])
604 }
605 }
606 for i := m + r.dataShards; i < n; i++ {
607 clear(work[i])
608 }
609
610 // work <- IFFT(work, n, 0)
611 ifftDITDecoder(
612 inputCount,
613 work,
614 n,
615 fftSkew[:],
616 &r.o,
617 )
618
619 // work <- FormalDerivative(work, n)
620 for i := 1; i < n; i++ {
621 width := ((i ^ (i - 1)) + 1) >> 1
622 slicesXor(work[i-width:i], work[i:i+width], &r.o)
623 }
624
625 // work <- FFT(work, n, 0) truncated to m + dataShards
626 if LEO_ERROR_BITFIELD_OPT && useBits {
627 errorBits.fftDIT(work, outputCount, n, fftSkew[:], &r.o)
628 } else {
629 fftDIT(work, outputCount, n, fftSkew[:], &r.o)
630 }
631
632 // Reveal erasures
633 end := r.dataShards
634 if recoverAll {
635 end = r.totalShards
636 }
637 for i := 0; i < end; i++ {
638 if len(sh[i]) != 0 {
639 continue
640 }
641 if i >= r.dataShards {
642 mulgf16(out[i], work[i-r.dataShards], modulus-errLocs[i-r.dataShards], &r.o)
643 } else {
644 mulgf16(out[i], work[i+m], modulus-errLocs[i+m], &r.o)
645 }
646 }
647 }
648
649 // Basic no-frills version for decoder
650 func ifftDITDecoder(mtrunc int, work [][]byte, m int, skewLUT []ffe, o *options) {
651 // Decimation in time: Unroll 2 layers at a time
652 dist := 1
653 dist4 := 4
654 for dist4 <= m {
655 // For each set of dist*4 elements:
656 for r := 0; r < mtrunc; r += dist4 {
657 iend := r + dist
658 log_m01 := skewLUT[iend-1]
659 log_m02 := skewLUT[iend+dist-1]
660 log_m23 := skewLUT[iend+dist*2-1]
661
662 // For each set of dist elements:
663 for i := r; i < iend; i++ {
664 ifftDIT4(work[i:], dist, log_m01, log_m23, log_m02, o)
665 }
666 }
667 dist = dist4
668 dist4 <<= 2
669 }
670
671 // If there is one layer left:
672 if dist < m {
673 // Assuming that dist = m / 2
674 if dist*2 != m {
675 panic("internal error")
676 }
677
678 log_m := skewLUT[dist-1]
679
680 if log_m == modulus {
681 slicesXor(work[dist:2*dist], work[:dist], o)
682 } else {
683 for i := 0; i < dist; i++ {
684 ifftDIT2(
685 work[i],
686 work[i+dist],
687 log_m,
688 o,
689 )
690 }
691 }
692 }
693 }
694
695 // In-place FFT for encoder and decoder
696 func fftDIT(work [][]byte, mtrunc, m int, skewLUT []ffe, o *options) {
697 // Decimation in time: Unroll 2 layers at a time
698 dist4 := m
699 dist := m >> 2
700 for dist != 0 {
701 // For each set of dist*4 elements:
702 for r := 0; r < mtrunc; r += dist4 {
703 iend := r + dist
704 log_m01 := skewLUT[iend-1]
705 log_m02 := skewLUT[iend+dist-1]
706 log_m23 := skewLUT[iend+dist*2-1]
707
708 // For each set of dist elements:
709 for i := r; i < iend; i++ {
710 fftDIT4(
711 work[i:],
712 dist,
713 log_m01,
714 log_m23,
715 log_m02,
716 o,
717 )
718 }
719 }
720 dist4 = dist
721 dist >>= 2
722 }
723
724 // If there is one layer left:
725 if dist4 == 2 {
726 for r := 0; r < mtrunc; r += 2 {
727 log_m := skewLUT[r+1-1]
728
729 if log_m == modulus {
730 sliceXor(work[r], work[r+1], o)
731 } else {
732 fftDIT2(work[r], work[r+1], log_m, o)
733 }
734 }
735 }
736 }
737
738 // 4-way butterfly
739 func fftDIT4Ref(work [][]byte, dist int, log_m01, log_m23, log_m02 ffe, o *options) {
740 // First layer:
741 if log_m02 == modulus {
742 sliceXor(work[0], work[dist*2], o)
743 sliceXor(work[dist], work[dist*3], o)
744 } else {
745 fftDIT2(work[0], work[dist*2], log_m02, o)
746 fftDIT2(work[dist], work[dist*3], log_m02, o)
747 }
748
749 // Second layer:
750 if log_m01 == modulus {
751 sliceXor(work[0], work[dist], o)
752 } else {
753 fftDIT2(work[0], work[dist], log_m01, o)
754 }
755
756 if log_m23 == modulus {
757 sliceXor(work[dist*2], work[dist*3], o)
758 } else {
759 fftDIT2(work[dist*2], work[dist*3], log_m23, o)
760 }
761 }
762
763 // Unrolled IFFT for encoder
764 func ifftDITEncoder(data [][]byte, mtrunc int, work [][]byte, xorRes [][]byte, m int, skewLUT []ffe, o *options) {
765 dist := 1
766 dist4 := 4
767
768 if dist4 <= m {
769 shardSize := len(data[0])
770 canUseFused := (o.useAvx512GFNI || o.useAvxGNFI || o.useAVX512 || o.useAVX2) && shardSize <= maxZeroBufferSize16
771
772 if canUseFused {
773 // SIMD path: fuse copy with first layer butterfly
774 fullGroups := mtrunc &^ 3
775 zb := zeroBufferPool16()[:shardSize]
776
777 for r := 0; r < fullGroups; r += dist4 {
778 iend := r + dist
779 log_m01 := skewLUT[iend]
780 log_m02 := skewLUT[iend+dist]
781 log_m23 := skewLUT[iend+dist*2]
782 ifftDIT4Dst(work[r:], data[r:], dist, log_m01, log_m23, log_m02, o)
783 }
784
785 if fullGroups < mtrunc {
786 r := fullGroups
787 iend := r + dist
788 log_m01 := skewLUT[iend]
789 log_m02 := skewLUT[iend+dist]
790 log_m23 := skewLUT[iend+dist*2]
791
792 src := [4][]byte{zb, zb, zb, zb}
793 for i := 0; i < mtrunc-fullGroups; i++ {
794 src[i] = data[fullGroups+i]
795 }
796 ifftDIT4Dst(work[r:], src[:], dist, log_m01, log_m23, log_m02, o)
797 }
798
799 clearStart := (mtrunc + 3) &^ 3
800 for i := clearStart; i < m; i++ {
801 clear(work[i])
802 }
803 } else {
804 // Non-SIMD or large shards: original approach
805 for i := range mtrunc {
806 copy(work[i], data[i])
807 }
808 for i := mtrunc; i < m; i++ {
809 clear(work[i])
810 }
811
812 for r := 0; r < mtrunc; r += dist4 {
813 iend := r + dist
814 log_m01 := skewLUT[iend]
815 log_m02 := skewLUT[iend+dist]
816 log_m23 := skewLUT[iend+dist*2]
817 for i := r; i < iend; i++ {
818 ifftDIT4(work[i:], dist, log_m01, log_m23, log_m02, o)
819 }
820 }
821 }
822
823 dist = dist4
824 dist4 <<= 2
825
826 // Subsequent layers: in-place (same for both paths)
827 for dist4 <= m {
828 for r := 0; r < mtrunc; r += dist4 {
829 iend := r + dist
830 log_m01 := skewLUT[iend]
831 log_m02 := skewLUT[iend+dist]
832 log_m23 := skewLUT[iend+dist*2]
833 for i := r; i < iend; i++ {
834 ifftDIT4(work[i:], dist, log_m01, log_m23, log_m02, o)
835 }
836 }
837 dist = dist4
838 dist4 <<= 2
839 }
840 } else {
841 // m < 4: fallback
842 for i := range mtrunc {
843 copy(work[i], data[i])
844 }
845 for i := mtrunc; i < m; i++ {
846 clear(work[i])
847 }
848 }
849
850 // If there is one layer left:
851 if dist < m {
852 // Assuming that dist = m / 2
853 if dist*2 != m {
854 panic("internal error")
855 }
856
857 logm := skewLUT[dist]
858
859 if logm == modulus {
860 slicesXor(work[dist:dist*2], work[:dist], o)
861 } else {
862 for i := 0; i < dist; i++ {
863 ifftDIT2(work[i], work[i+dist], logm, o)
864 }
865 }
866 }
867
868 // I tried unrolling this but it does not provide more than 5% performance
869 // improvement for 16-bit finite fields, so it's not worth the complexity.
870 if xorRes != nil {
871 slicesXor(xorRes[:m], work[:m], o)
872 }
873 }
874
875 func ifftDIT4Ref(work [][]byte, dist int, log_m01, log_m23, log_m02 ffe, o *options) {
876 // First layer:
877 if log_m01 == modulus {
878 sliceXor(work[0], work[dist], o)
879 } else {
880 ifftDIT2(work[0], work[dist], log_m01, o)
881 }
882
883 if log_m23 == modulus {
884 sliceXor(work[dist*2], work[dist*3], o)
885 } else {
886 ifftDIT2(work[dist*2], work[dist*3], log_m23, o)
887 }
888
889 // Second layer:
890 if log_m02 == modulus {
891 sliceXor(work[0], work[dist*2], o)
892 sliceXor(work[dist], work[dist*3], o)
893 } else {
894 ifftDIT2(work[0], work[dist*2], log_m02, o)
895 ifftDIT2(work[dist], work[dist*3], log_m02, o)
896 }
897 }
898
899 func ifftDIT4DstRef(dst, work [][]byte, dist int, log_m01, log_m23, log_m02 ffe, o *options) {
900 for i := range 4 {
901 copy(dst[i*dist], work[i*dist])
902 }
903 ifftDIT4Ref(dst, dist, log_m01, log_m23, log_m02, o)
904 }
905
906 // Reference version of muladd: x[] ^= y[] * log_m
907 func refMulAdd(x, y []byte, log_m ffe) {
908 lut := &mul16LUTs[log_m]
909
910 for len(x) >= 64 {
911 // Assert sizes for no bounds checks in loop
912 hiA := y[32:64]
913 loA := y[:32]
914 dst := x[:64] // Needed, but not checked...
915 for i, lo := range loA {
916 hi := hiA[i]
917 prod := lut.Lo[lo] ^ lut.Hi[hi]
918
919 dst[i] ^= byte(prod)
920 dst[i+32] ^= byte(prod >> 8)
921 }
922 x = x[64:]
923 y = y[64:]
924 }
925 }
926
927 // refMulAdd8x performs 8 mul-add accumulates sharing the same input,
928 // reading in once per 64-byte chunk. Pure Go fallback for mulgf16Xor8.
929 func refMulAdd8x(scalars *[8]uint16, in []byte, outs *[8][]byte) {
930 var luts [8]*mul16LUT
931 for k, c := range scalars {
932 if c != 0 {
933 luts[k] = &mul16LUTs[logLUT[ffe(c)]]
934 }
935 }
936 out := *outs // local copy so we can re-slice without mutating caller
937 for len(in) >= 64 {
938 hiIn := in[32:64]
939 loIn := in[:32]
940 for i, lo := range loIn {
941 hi := hiIn[i]
942 for k := 0; k < 8; k++ {
943 if luts[k] == nil {
944 continue
945 }
946 prod := luts[k].Lo[lo] ^ luts[k].Hi[hi]
947 out[k][i] ^= byte(prod)
948 out[k][i+32] ^= byte(prod >> 8)
949 }
950 }
951 in = in[64:]
952 for k := range out {
953 out[k] = out[k][64:]
954 }
955 }
956 }
957
958 // slicesXor calls xor for every slice pair in v1, v2.
959 func slicesXor(v1, v2 [][]byte, o *options) {
960 for i, v := range v1 {
961 sliceXor(v2[i], v, o)
962 }
963 }
964
965 // Reference version of mul: x[] = y[] * log_m
966 func refMul(x, y []byte, log_m ffe) {
967 lut := &mul16LUTs[log_m]
968
969 for off := 0; off < len(x); off += 64 {
970 loA := y[off : off+32]
971 hiA := y[off+32:]
972 hiA = hiA[:len(loA)]
973 for i, lo := range loA {
974 hi := hiA[i]
975 prod := lut.Lo[lo] ^ lut.Hi[hi]
976
977 x[off+i] = byte(prod)
978 x[off+i+32] = byte(prod >> 8)
979 }
980 }
981 }
982
983 // Returns a * Log(b)
984 func mulLog(a, log_b ffe) ffe {
985 /*
986 Note that this operation is not a normal multiplication in a finite
987 field because the right operand is already a logarithm. This is done
988 because it moves K table lookups from the Decode() method into the
989 initialization step that is less performance critical. The LogWalsh[]
990 table below contains precalculated logarithms so it is easier to do
991 all the other multiplies in that form as well.
992 */
993 if a == 0 {
994 return 0
995 }
996 return expLUT[addMod(logLUT[a], log_b)]
997 }
998
999 // addMod returns the sum of a and b modulo modulus. This can return modulus but
1000 // it is expected that callers will convert modulus to 0.
1001 func addMod(a, b ffe) ffe {
1002 sum := uint(a) + uint(b)
1003
1004 // Partial reduction step which allows for modulus to be returned.
1005 return ffe(sum + sum>>bitwidth)
1006 }
1007
1008 // z = x - y (mod kModulus)
1009 func subMod(a, b ffe) ffe {
1010 dif := uint(a) - uint(b)
1011
1012 // Partial reduction step, allowing for kModulus to be returned
1013 return ffe(dif + dif>>bitwidth)
1014 }
1015
1016 // ceilPow2 returns power of two at or above n.
1017 func ceilPow2(n int) int {
1018 const w = int(unsafe.Sizeof(n) * 8)
1019 return 1 << (w - bits.LeadingZeros(uint(n-1)))
1020 }
1021
1022 // Decimation in time (DIT) Fast Walsh-Hadamard Transform
1023 // Unrolls pairs of layers to perform cross-layer operations in registers
1024 // mtrunc: Number of elements that are non-zero at the front of data
1025 func fwht(data *[order]ffe, mtrunc int) {
1026 // Decimation in time: Unroll 2 layers at a time
1027 dist := 1
1028 dist4 := 4
1029 for dist4 <= order {
1030 // For each set of dist*4 elements:
1031 for r := 0; r < mtrunc; r += dist4 {
1032 // For each set of dist elements:
1033 // Use 16 bit indices to avoid bounds check on [65536]ffe.
1034 dist := uint16(dist)
1035 off := uint16(r)
1036 for range dist {
1037 // fwht4(data[i:], dist) inlined...
1038 // Reading values appear faster than updating pointers.
1039 // Casting to uint is not faster.
1040 t0 := data[off]
1041 t1 := data[off+dist]
1042 t2 := data[off+dist*2]
1043 t3 := data[off+dist*3]
1044
1045 t0, t1 = fwht2alt(t0, t1)
1046 t2, t3 = fwht2alt(t2, t3)
1047 t0, t2 = fwht2alt(t0, t2)
1048 t1, t3 = fwht2alt(t1, t3)
1049
1050 data[off] = t0
1051 data[off+dist] = t1
1052 data[off+dist*2] = t2
1053 data[off+dist*3] = t3
1054 off++
1055 }
1056 }
1057 dist = dist4
1058 dist4 <<= 2
1059 }
1060 }
1061
1062 func fwht4(data []ffe, s int) {
1063 s2 := s << 1
1064
1065 t0 := &data[0]
1066 t1 := &data[s]
1067 t2 := &data[s2]
1068 t3 := &data[s2+s]
1069
1070 fwht2(t0, t1)
1071 fwht2(t2, t3)
1072 fwht2(t0, t2)
1073 fwht2(t1, t3)
1074 }
1075
1076 // {a, b} = {a + b, a - b} (Mod Q)
1077 func fwht2(a, b *ffe) {
1078 sum := addMod(*a, *b)
1079 dif := subMod(*a, *b)
1080 *a = sum
1081 *b = dif
1082 }
1083
1084 // fwht2alt is as fwht2, but returns result.
1085 func fwht2alt(a, b ffe) (ffe, ffe) {
1086 sum := uint(a) + uint(b)
1087 dif := uint(a) - uint(b)
1088 sum = sum + sum>>bitwidth
1089 dif = dif + dif>>bitwidth
1090 return ffe(sum), ffe(dif)
1091 }
1092
1093 var initOnce sync.Once
1094
1095 func initConstants() {
1096 initOnce.Do(func() {
1097 initLUTs()
1098 initFFTSkew()
1099 initMul16LUT()
1100 })
1101 }
1102
1103 // Initialize logLUT, expLUT.
1104 func initLUTs() {
1105 cantorBasis := [bitwidth]ffe{
1106 0x0001, 0xACCA, 0x3C0E, 0x163E,
1107 0xC582, 0xED2E, 0x914C, 0x4012,
1108 0x6C98, 0x10D8, 0x6A72, 0xB900,
1109 0xFDB8, 0xFB34, 0xFF38, 0x991E,
1110 }
1111
1112 expLUT = &[order]ffe{}
1113 logLUT = &[order]ffe{}
1114
1115 // LFSR table generation:
1116 state := 1
1117 for i := range ffe(modulus) {
1118 expLUT[state] = i
1119 state <<= 1
1120 if state >= order {
1121 state ^= polynomial
1122 }
1123 }
1124 expLUT[0] = modulus
1125
1126 // Conversion to Cantor basis:
1127
1128 logLUT[0] = 0
1129 for i := range bitwidth {
1130 basis := cantorBasis[i]
1131 width := 1 << i
1132
1133 for j := range width {
1134 logLUT[j+width] = logLUT[j] ^ basis
1135 }
1136 }
1137
1138 for i := range order {
1139 logLUT[i] = expLUT[logLUT[i]]
1140 }
1141
1142 for i := range order {
1143 expLUT[logLUT[i]] = ffe(i)
1144 }
1145
1146 expLUT[modulus] = expLUT[0]
1147 }
1148
1149 // Initialize fftSkew.
1150 func initFFTSkew() {
1151 var temp [bitwidth - 1]ffe
1152
1153 // Generate FFT skew vector {1}:
1154
1155 for i := 1; i < bitwidth; i++ {
1156 temp[i-1] = ffe(1 << i)
1157 }
1158
1159 fftSkew = &[modulus]ffe{}
1160 logWalsh = &[order]ffe{}
1161
1162 for m := range bitwidth - 1 {
1163 step := 1 << (m + 1)
1164
1165 fftSkew[1<<m-1] = 0
1166
1167 for i := m; i < bitwidth-1; i++ {
1168 s := 1 << (i + 1)
1169
1170 for j := 1<<m - 1; j < s; j += step {
1171 fftSkew[j+s] = fftSkew[j] ^ temp[i]
1172 }
1173 }
1174
1175 temp[m] = modulus - logLUT[mulLog(temp[m], logLUT[temp[m]^1])]
1176
1177 for i := m + 1; i < bitwidth-1; i++ {
1178 sum := addMod(logLUT[temp[i]^1], temp[m])
1179 temp[i] = mulLog(temp[i], sum)
1180 }
1181 }
1182
1183 for i := range modulus {
1184 fftSkew[i] = logLUT[fftSkew[i]]
1185 }
1186
1187 // Precalculate FWHT(Log[i]):
1188
1189 for i := range order {
1190 logWalsh[i] = logLUT[i]
1191 }
1192 logWalsh[0] = 0
1193
1194 fwht(logWalsh, order)
1195 }
1196
1197 func initMul16LUT() {
1198 mul16LUTs = &[order]mul16LUT{}
1199
1200 // For each log_m multiplicand:
1201 for log_m := range order {
1202 var tmp [64]ffe
1203 for nibble, shift := 0, 0; nibble < 4; {
1204 nibble_lut := tmp[nibble*16:]
1205
1206 for xnibble := range 16 {
1207 prod := mulLog(ffe(xnibble<<shift), ffe(log_m))
1208 nibble_lut[xnibble] = prod
1209 }
1210 nibble++
1211 shift += 4
1212 }
1213 lut := &mul16LUTs[log_m]
1214 for i := range lut.Lo[:] {
1215 lut.Lo[i] = tmp[i&15] ^ tmp[((i>>4)+16)]
1216 lut.Hi[i] = tmp[((i&15)+32)] ^ tmp[((i>>4)+48)]
1217 }
1218 }
1219 if cpuid.CPU.Has(cpuid.SSSE3) || cpuid.CPU.Has(cpuid.AVX2) || cpuid.CPU.Has(cpuid.AVX512F) {
1220 multiply256LUT = &[order][16 * 8]byte{}
1221
1222 for logM := range multiply256LUT[:] {
1223 // For each 4 bits of the finite field width in bits:
1224 shift := 0
1225 for i := range 4 {
1226 // Construct 16 entry LUT for PSHUFB
1227 prodLo := multiply256LUT[logM][i*16 : i*16+16]
1228 prodHi := multiply256LUT[logM][4*16+i*16 : 4*16+i*16+16]
1229 for x := range prodLo[:] {
1230 prod := mulLog(ffe(x<<shift), ffe(logM))
1231 prodLo[x] = byte(prod)
1232 prodHi[x] = byte(prod >> 8)
1233 }
1234 shift += 4
1235 }
1236 }
1237 }
1238 if cpuid.CPU.Has(cpuid.GFNI) {
1239 gf2p811dMulMatrices16 = &[order][4]uint64{}
1240 for logM := range gf2p811dMulMatrices16[:] {
1241 var A, B, C, D uint64
1242
1243 // A, C: effect of input lo_byte bits on output
1244 // VGF2P8AFFINEQB accesses byte (7-j) for output bit j, so we need:
1245 // position = (7-outputBit)*8 + inputBit
1246 for inputBit := range 8 {
1247 result := mulLog(ffe(1<<inputBit), ffe(logM))
1248 for outputBit := range 8 {
1249 if (byte(result)>>outputBit)&1 == 1 {
1250 A |= 1 << ((7-outputBit)*8 + inputBit)
1251 }
1252 if (byte(result>>8)>>outputBit)&1 == 1 {
1253 C |= 1 << ((7-outputBit)*8 + inputBit)
1254 }
1255 }
1256 }
1257
1258 // B, D: effect of input hi_byte bits on output
1259 for inputBit := range 8 {
1260 result := mulLog(ffe(1<<(inputBit+8)), ffe(logM))
1261 for outputBit := range 8 {
1262 if (byte(result)>>outputBit)&1 == 1 {
1263 B |= 1 << ((7-outputBit)*8 + inputBit)
1264 }
1265 if (byte(result>>8)>>outputBit)&1 == 1 {
1266 D |= 1 << ((7-outputBit)*8 + inputBit)
1267 }
1268 }
1269 }
1270
1271 gf2p811dMulMatrices16[logM] = [4]uint64{A, B, C, D}
1272 }
1273 }
1274 }
1275
1276 func (r *leopardFF16) getShardSlice() [][]byte {
1277 if s, ok := r.shardSlicePool.Get().([][]byte); ok {
1278 return s[:r.totalShards]
1279 }
1280 return make([][]byte, r.totalShards)
1281 }
1282
1283 func (r *leopardFF16) putShardSlice(s [][]byte) {
1284 clear(s[:cap(s)])
1285 r.shardSlicePool.Put(s)
1286 }
1287
1288 func (r *leopardFF16) getWorkSlice(n int) [][]byte {
1289 if s, ok := r.workSlicePool.Get().([][]byte); ok && cap(s) >= n {
1290 return s[:n]
1291 }
1292 return make([][]byte, n)
1293 }
1294
1295 func (r *leopardFF16) putWorkSlice(s [][]byte) {
1296 clear(s[:cap(s)])
1297 r.workSlicePool.Put(s)
1298 }
1299
1300 const kWordMips = 5
1301 const kWords = order / 64
1302 const kBigMips = 6
1303 const kBigWords = (kWords + 63) / 64
1304 const kBiggestMips = 4
1305
1306 // errorBitfield contains progressive errors to help indicate which
1307 // shards need reconstruction.
1308 type errorBitfield struct {
1309 Words [kWordMips][kWords]uint64
1310 BigWords [kBigMips][kBigWords]uint64
1311 BiggestWords [kBiggestMips]uint64
1312 // neededFns holds pre-computed needed-check functions indexed sequentially
1313 // for each FFT layer, allocated once in prepare to avoid per-call closure allocs.
1314 // Max 9 entries: mipLevel 16 down to 0 by 2.
1315 neededFns [9]func(int) bool
1316 }
1317
1318 func (e *errorBitfield) set(i int) {
1319 e.Words[0][i/64] |= uint64(1) << (i & 63)
1320 }
1321
1322 func (e *errorBitfield) isNeededFn(mipLevel int) func(bit int) bool {
1323 if mipLevel >= 16 {
1324 return func(bit int) bool {
1325 return true
1326 }
1327 }
1328 if mipLevel >= 12 {
1329 w := e.BiggestWords[mipLevel-12]
1330 return func(bit int) bool {
1331 bit /= 4096
1332 return 0 != (w & (uint64(1) << bit))
1333 }
1334 }
1335 if mipLevel >= 6 {
1336 w := e.BigWords[mipLevel-6][:]
1337 return func(bit int) bool {
1338 bit /= 64
1339 return 0 != (w[bit/64] & (uint64(1) << (bit & 63)))
1340 }
1341 }
1342 if mipLevel > 0 {
1343 w := e.Words[mipLevel-1][:]
1344 return func(bit int) bool {
1345 return 0 != (w[bit/64] & (uint64(1) << (bit & 63)))
1346 }
1347 }
1348 return nil
1349 }
1350
1351 func (e *errorBitfield) isNeeded(mipLevel int, bit uint) bool {
1352 if mipLevel >= 16 {
1353 return true
1354 }
1355 if mipLevel >= 12 {
1356 bit /= 4096
1357 return 0 != (e.BiggestWords[mipLevel-12] & (uint64(1) << bit))
1358 }
1359 if mipLevel >= 6 {
1360 bit /= 64
1361 return 0 != (e.BigWords[mipLevel-6][bit/64] & (uint64(1) << (bit % 64)))
1362 }
1363 return 0 != (e.Words[mipLevel-1][bit/64] & (uint64(1) << (bit % 64)))
1364 }
1365
1366 var kHiMasks = [5]uint64{
1367 0xAAAAAAAAAAAAAAAA,
1368 0xCCCCCCCCCCCCCCCC,
1369 0xF0F0F0F0F0F0F0F0,
1370 0xFF00FF00FF00FF00,
1371 0xFFFF0000FFFF0000,
1372 }
1373
1374 func (e *errorBitfield) prepare(m int) {
1375 for i := range kWords {
1376 w_i := e.Words[0][i]
1377 hi2lo0 := w_i | ((w_i & kHiMasks[0]) >> 1)
1378 lo2hi0 := (w_i & (kHiMasks[0] >> 1)) << 1
1379 w_i = hi2lo0 | lo2hi0
1380 e.Words[0][i] = w_i
1381
1382 bits := 2
1383 for j := 1; j < kWordMips; j++ {
1384 hi2lo_j := w_i | ((w_i & kHiMasks[j]) >> bits)
1385 lo2hi_j := (w_i & (kHiMasks[j] >> bits)) << bits
1386 w_i = hi2lo_j | lo2hi_j
1387 e.Words[j][i] = w_i
1388 bits <<= 1
1389 }
1390 }
1391
1392 for i := range kBigWords {
1393 w_i := uint64(0)
1394 bit := uint64(1)
1395 src := e.Words[kWordMips-1][i*64 : i*64+64]
1396 for _, w := range src {
1397 w_i |= (w | (w >> 32) | (w << 32)) & bit
1398 bit <<= 1
1399 }
1400 e.BigWords[0][i] = w_i
1401
1402 shift := 1
1403 for j := 1; j < kBigMips; j++ {
1404 hi2lo_j := w_i | ((w_i & kHiMasks[j-1]) >> shift)
1405 lo2hi_j := (w_i & (kHiMasks[j-1] >> shift)) << shift
1406 w_i = hi2lo_j | lo2hi_j
1407 e.BigWords[j][i] = w_i
1408 shift <<= 1
1409 }
1410 }
1411
1412 w_i := uint64(0)
1413 bit := uint64(1)
1414 for _, w := range e.BigWords[kBigMips-1][:kBigWords] {
1415 w_i |= (w | (w >> 32) | (w << 32)) & bit
1416 bit <<= 1
1417 }
1418 e.BiggestWords[0] = w_i
1419
1420 shift := uint64(1)
1421 for j := 1; j < kBiggestMips; j++ {
1422 hi2lo_j := w_i | ((w_i & kHiMasks[j-1]) >> shift)
1423 lo2hi_j := (w_i & (kHiMasks[j-1] >> shift)) << shift
1424 w_i = hi2lo_j | lo2hi_j
1425 e.BiggestWords[j] = w_i
1426 shift <<= 1
1427 }
1428
1429 // Pre-compute needed-check functions for used mip levels.
1430 // fftDIT starts at bits.Len32(n)-1 and decrements by 2.
1431 // We store them sequentially from index 0.
1432 startLevel := bits.Len32(uint32(m)) - 1
1433 for i, ml := 0, startLevel; ml >= 0; i, ml = i+1, ml-2 {
1434 e.neededFns[i] = e.isNeededFn(ml)
1435 }
1436 }
1437
1438 func (e *errorBitfield) fftDIT(work [][]byte, mtrunc, m int, skewLUT []ffe, o *options) {
1439 // Decimation in time: Unroll 2 layers at a time
1440 fnIdx := 0
1441
1442 dist4 := m
1443 dist := m >> 2
1444 for dist != 0 {
1445 needed := e.neededFns[fnIdx]
1446 fnIdx++
1447 // For each set of dist*4 elements:
1448 for r := 0; r < mtrunc; r += dist4 {
1449 if !needed(r) {
1450 continue
1451 }
1452 iEnd := r + dist
1453 logM01 := skewLUT[iEnd-1]
1454 logM02 := skewLUT[iEnd+dist-1]
1455 logM23 := skewLUT[iEnd+dist*2-1]
1456
1457 // For each set of dist elements:
1458 for i := r; i < iEnd; i++ {
1459 fftDIT4(
1460 work[i:],
1461 dist,
1462 logM01,
1463 logM23,
1464 logM02,
1465 o)
1466 }
1467 }
1468 dist4 = dist
1469 dist >>= 2
1470 }
1471
1472 // If there is one layer left:
1473 if dist4 == 2 {
1474 needed := e.neededFns[fnIdx]
1475 for r := 0; r < mtrunc; r += 2 {
1476 if !needed(r) {
1477 continue
1478 }
1479 logM := skewLUT[r+1-1]
1480
1481 if logM == modulus {
1482 sliceXor(work[r], work[r+1], o)
1483 } else {
1484 fftDIT2(work[r], work[r+1], logM, o)
1485 }
1486 }
1487 }
1488 }