-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathWirehairCodec.cpp
More file actions
5920 lines (4853 loc) · 209 KB
/
Copy pathWirehairCodec.cpp
File metadata and controls
5920 lines (4853 loc) · 209 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** \file
\brief Wirehair : Codec Implementation
\copyright Copyright (c) 2012-2018 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Wirehair nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "WirehairCodec.h"
#include "WirehairEnvironment.h"
#include "WirehairHeavy.h"
#include <atomic>
#include <chrono>
#include <climits>
//------------------------------------------------------------------------------
// Precompiler-conditional console output
#if defined(CAT_DUMP_PIVOT_FAIL)
#define CAT_IF_PIVOT(x) x
#else
#define CAT_IF_PIVOT(x)
#endif
#if defined(CAT_DUMP_CODEC_DEBUG)
#define CAT_IF_DUMP(x) x
#else
#define CAT_IF_DUMP(x)
#endif
#if defined(CAT_DUMP_ROWOP_COUNTERS)
#define CAT_IF_ROWOP(x) x
#else
#define CAT_IF_ROWOP(x)
#endif
#if defined(CAT_DUMP_CODEC_DEBUG) || defined(CAT_DUMP_PIVOT_FAIL) || \
defined(CAT_DUMP_ROWOP_COUNTERS) || defined(CAT_DUMP_GE_MATRIX)
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
#endif
#ifdef WH_OPLOG
#include <cstdio>
#include <cstdlib>
#include <mutex>
#endif
#ifdef WH_SEED_KNOBS
#include <cerrno>
#include <cstdlib>
#endif
#ifdef WH_COUNT
#include <vector>
#endif
namespace wirehair {
static GF256_FORCE_INLINE int Gf256ByteCount(size_t bytes)
{
// ChooseMatrix rejects block sizes that exceed the GF256 API's int range.
CAT_DEBUG_ASSERT(bytes <= static_cast<size_t>(INT_MAX));
return static_cast<int>(bytes);
}
static GF256_FORCE_INLINE void SipRound(
uint64_t& v0,
uint64_t& v1,
uint64_t& v2,
uint64_t& v3)
{
v0 += v1;
v1 = CAT_ROL64(v1, 13);
v1 ^= v0;
v0 = CAT_ROL64(v0, 32);
v2 += v3;
v3 = CAT_ROL64(v3, 16);
v3 ^= v2;
v0 += v3;
v3 = CAT_ROL64(v3, 21);
v3 ^= v0;
v2 += v1;
v1 = CAT_ROL64(v1, 17);
v1 ^= v2;
v2 = CAT_ROL64(v2, 32);
}
static GF256_FORCE_INLINE uint64_t ReadLittleEndian64(const uint8_t* data)
{
return static_cast<uint64_t>(data[0]) |
(static_cast<uint64_t>(data[1]) << 8) |
(static_cast<uint64_t>(data[2]) << 16) |
(static_cast<uint64_t>(data[3]) << 24) |
(static_cast<uint64_t>(data[4]) << 32) |
(static_cast<uint64_t>(data[5]) << 40) |
(static_cast<uint64_t>(data[6]) << 48) |
(static_cast<uint64_t>(data[7]) << 56);
}
static void PacketFingerprint128(
const void* data,
uint32_t bytes,
uint64_t& hash0,
uint64_t& hash1)
{
// Two independent SipHash-2-4 instances are updated in one input pass.
// The keys are intentionally fixed: This fingerprint defines duplicate
// equality and collision behavior, but is not a MAC or integrity check.
const uint64_t key00 = UINT64_C(0x8f3f73b5cf1c9ade);
const uint64_t key01 = UINT64_C(0x2d4b6a9817e5c043);
const uint64_t key10 = UINT64_C(0xc6a4a7935bd1e995);
const uint64_t key11 = UINT64_C(0x9e3779b97f4a7c15);
uint64_t a0 = UINT64_C(0x736f6d6570736575) ^ key00;
uint64_t a1 = UINT64_C(0x646f72616e646f6d) ^ key01;
uint64_t a2 = UINT64_C(0x6c7967656e657261) ^ key00;
uint64_t a3 = UINT64_C(0x7465646279746573) ^ key01;
uint64_t b0 = UINT64_C(0x736f6d6570736575) ^ key10;
uint64_t b1 = UINT64_C(0x646f72616e646f6d) ^ key11;
uint64_t b2 = UINT64_C(0x6c7967656e657261) ^ key10;
uint64_t b3 = UINT64_C(0x7465646279746573) ^ key11;
const uint8_t* input = static_cast<const uint8_t*>(data);
const uint8_t* const end = input + (bytes & ~uint32_t{7});
while (input != end)
{
const uint64_t word = ReadLittleEndian64(input);
a3 ^= word;
SipRound(a0, a1, a2, a3);
SipRound(a0, a1, a2, a3);
a0 ^= word;
b3 ^= word;
SipRound(b0, b1, b2, b3);
SipRound(b0, b1, b2, b3);
b0 ^= word;
input += 8;
}
uint64_t tail = static_cast<uint64_t>(bytes) << 56;
const uint32_t tail_bytes = bytes & 7;
for (uint32_t i = 0; i < tail_bytes; ++i) {
tail |= static_cast<uint64_t>(input[i]) << (i * 8);
}
a3 ^= tail;
SipRound(a0, a1, a2, a3);
SipRound(a0, a1, a2, a3);
a0 ^= tail;
a2 ^= UINT64_C(0xff);
SipRound(a0, a1, a2, a3);
SipRound(a0, a1, a2, a3);
SipRound(a0, a1, a2, a3);
SipRound(a0, a1, a2, a3);
hash0 = a0 ^ a1 ^ a2 ^ a3;
b3 ^= tail;
SipRound(b0, b1, b2, b3);
SipRound(b0, b1, b2, b3);
b0 ^= tail;
b2 ^= UINT64_C(0xff);
SipRound(b0, b1, b2, b3);
SipRound(b0, b1, b2, b3);
SipRound(b0, b1, b2, b3);
SipRound(b0, b1, b2, b3);
hash1 = b0 ^ b1 ^ b2 ^ b3;
}
static GF256_FORCE_INLINE uint64_t MixPacketIdHash(uint64_t value)
{
value ^= value >> 30;
value *= UINT64_C(0xbf58476d1ce4e5b9);
value ^= value >> 27;
value *= UINT64_C(0x94d049bb133111eb);
value ^= value >> 31;
return value;
}
static uint64_t NewPacketIdHashSalt(const void* codec)
{
// Bucket placement is process-local and deliberately varies for each
// decoder so a remote sender cannot precompute long linear-probe clusters.
// This salt is a denial-of-service hardening measure, not a secret key or
// an authentication primitive.
static std::atomic<uint32_t> sequence(UINT32_C(0x6a09e667));
const uint64_t serial = sequence.fetch_add(
UINT32_C(0x9e3779b9), std::memory_order_relaxed);
const uint64_t ticks = static_cast<uint64_t>(
std::chrono::steady_clock::now().time_since_epoch().count());
const uint64_t address = static_cast<uint64_t>(
reinterpret_cast<uintptr_t>(codec));
return MixPacketIdHash(serial ^ ticks ^ CAT_ROL64(address, 23));
}
static GF256_FORCE_INLINE uint32_t PacketIdHash(
uint32_t id,
uint64_t salt)
{
return static_cast<uint32_t>(
MixPacketIdHash(static_cast<uint64_t>(id) ^ salt));
}
#ifdef WH_OPLOG
namespace {
thread_local const char* OpLogCurrentStage = "";
FILE*& OpLogFileRef()
{
static FILE* file = nullptr;
return file;
}
std::once_flag& OpLogInitOnce()
{
static std::once_flag once;
return once;
}
void OpLogClose()
{
FILE*& file = OpLogFileRef();
if (file) {
fclose(file);
file = nullptr;
}
}
void OpLogInit()
{
FILE*& file = OpLogFileRef();
const EnvironmentValue environment("WH_OPLOG_PATH");
const char* path = environment.Get();
if (path && path[0])
{
#if defined(_MSC_VER)
if (::fopen_s(&file, path, "w") != 0) {
file = nullptr;
}
#else
file = fopen(path, "w");
#endif
if (file)
{
fputs(
"stage,op_type,dst_kind,dst_block,dst_offset,"
"src0_kind,src0_block,src0_offset,"
"src1_kind,src1_block,src1_offset,scalar,bytes\n",
file);
atexit(OpLogClose);
}
}
}
FILE* OpLogFile()
{
std::call_once(OpLogInitOnce(), OpLogInit);
FILE*& file = OpLogFileRef();
return file;
}
} // namespace
void Codec::OpLogStage(const char* stage) const
{
(void)this;
OpLogCurrentStage = stage;
(void)OpLogFile();
}
void Codec::OpLog(
const char* op_type,
const char* dst_kind,
int dst_block,
unsigned dst_offset,
const char* src0_kind,
int src0_block,
unsigned src0_offset,
const char* src1_kind,
int src1_block,
unsigned src1_offset,
unsigned scalar,
unsigned bytes) const
{
FILE* file = OpLogFile();
if (!file) {
return;
}
fprintf(
file,
"%s,%s,%s,%d,%u,%s,%d,%u,%s,%d,%u,%u,%u\n",
OpLogCurrentStage,
op_type,
dst_kind,
dst_block,
dst_offset,
src0_kind,
src0_block,
src0_offset,
src1_kind,
src1_block,
src1_offset,
scalar,
bytes);
}
int Codec::OpLogRecoveryBlock(const void* ptr) const
{
if (!ptr || !_recovery_blocks || !_block_bytes) {
return -1;
}
const uint8_t* p = static_cast<const uint8_t*>(ptr);
if (p < _recovery_blocks) {
return -1;
}
const size_t offset = (size_t)(p - _recovery_blocks);
if (offset % _block_bytes != 0) {
return -1;
}
const size_t block = offset / _block_bytes;
if (block >= _recovery_rows) {
return -1;
}
return (int)block;
}
#endif // WH_OPLOG
#ifdef WH_OPLOG
#define WH_OPLOG_STAGE(name) OpLogStage(name)
#define WH_OPLOG_ZERO(dst_block, offset, bytes) \
OpLog("zero", "recovery", (int)(dst_block), (offset), "none", -1, 0, "none", -1, 0, 0, (bytes))
#define WH_OPLOG_MEMCPY_REC_INPUT(dst_block, src_block, bytes) \
OpLog("memcpy", "recovery", (int)(dst_block), 0, "input", (int)(src_block), 0, "none", -1, 0, 0, (bytes))
#define WH_OPLOG_MEMCPY_REC_REC(dst_block, dst_offset, src_block, src_offset, bytes) \
OpLog("memcpy", "recovery", (int)(dst_block), (dst_offset), "recovery", (int)(src_block), (src_offset), "none", -1, 0, 0, (bytes))
#define WH_OPLOG_XOR(dst_block, src_block, bytes) \
OpLog("xor", "recovery", (int)(dst_block), 0, "recovery", (int)(src_block), 0, "none", -1, 0, 1, (bytes))
#define WH_OPLOG_ADDSET_REC_INPUT(dst_block, src0_block, src1_block, bytes) \
OpLog("addset", "recovery", (int)(dst_block), 0, "recovery", (int)(src0_block), 0, "input", (int)(src1_block), 0, 1, (bytes))
#define WH_OPLOG_ADDSET_INPUT_REC(dst_block, src0_block, src1_block, bytes) \
OpLog("addset", "recovery", (int)(dst_block), 0, "input", (int)(src0_block), 0, "recovery", (int)(src1_block), 0, 1, (bytes))
#define WH_OPLOG_ADDSET_REC_REC(dst_block, src0_block, src1_block, bytes) \
OpLog("addset", "recovery", (int)(dst_block), 0, "recovery", (int)(src0_block), 0, "recovery", (int)(src1_block), 0, 1, (bytes))
#define WH_OPLOG_ADD2(dst_block, src0_block, src1_block, bytes) \
OpLog("add2", "recovery", (int)(dst_block), 0, "recovery", (int)(src0_block), 0, "recovery", (int)(src1_block), 0, 1, (bytes))
#define WH_OPLOG_MULADD(dst_block, scalar, src_block, bytes) \
OpLog("muladd", "recovery", (int)(dst_block), 0, "recovery", (int)(src_block), 0, "none", -1, 0, (unsigned)(scalar), (bytes))
#define WH_OPLOG_DIV(dst_block, scalar, bytes) \
OpLog("div", "recovery", (int)(dst_block), 0, "recovery", (int)(dst_block), 0, "none", -1, 0, (unsigned)(scalar), (bytes))
#else
#define WH_OPLOG_STAGE(name) do {} while (false)
#define WH_OPLOG_ZERO(dst_block, offset, bytes) do {} while (false)
#define WH_OPLOG_MEMCPY_REC_INPUT(dst_block, src_block, bytes) do {} while (false)
#define WH_OPLOG_MEMCPY_REC_REC(dst_block, dst_offset, src_block, src_offset, bytes) do {} while (false)
#define WH_OPLOG_XOR(dst_block, src_block, bytes) do {} while (false)
#define WH_OPLOG_ADDSET_REC_INPUT(dst_block, src0_block, src1_block, bytes) do {} while (false)
#define WH_OPLOG_ADDSET_INPUT_REC(dst_block, src0_block, src1_block, bytes) do {} while (false)
#define WH_OPLOG_ADDSET_REC_REC(dst_block, src0_block, src1_block, bytes) do {} while (false)
#define WH_OPLOG_ADD2(dst_block, src0_block, src1_block, bytes) do {} while (false)
#define WH_OPLOG_MULADD(dst_block, scalar, src_block, bytes) do {} while (false)
#define WH_OPLOG_DIV(dst_block, scalar, bytes) do {} while (false)
#endif
#if defined(WH_GATHER) && (WH_GATHER+0)
static const unsigned kGatherMaxBlockBytes = 128u * 1024u;
static GF256_FORCE_INLINE bool UseGatherXor(unsigned block_bytes)
{
return block_bytes <= kGatherMaxBlockBytes;
}
class GatherXor
{
public:
GatherXor(uint8_t* dest, unsigned bytes)
: Dest(dest)
, Bytes((int)bytes)
, Count(0)
{
}
void Add(const uint8_t* src)
{
Sources[Count++] = src;
if (Count == kMaxSources) {
Flush();
}
}
void Flush()
{
if (Count == 1) {
gf256_add_mem(Dest, Sources[0], Bytes);
}
else if (Count == 2) {
gf256_add2_mem(Dest, Sources[0], Sources[1], Bytes);
}
else if (Count > 2) {
gf256_add_multi_mem(Dest, Sources, (int)Count, Bytes);
}
Count = 0;
}
private:
static const unsigned kMaxSources = 8;
uint8_t* Dest;
int Bytes;
const void* Sources[kMaxSources];
unsigned Count;
};
#endif // WH_GATHER
//------------------------------------------------------------------------------
// Stage (1) Peeling:
bool Codec::OpportunisticPeeling(
const uint16_t row_i, ///< Row index
const uint32_t row_seed ///< Row PRNG seed
)
{
PeelRow *row = &_peel_rows[row_i];
row->RecoveryId = row_seed;
row->Params.Initialize(row_seed, _p_seed, _block_count, _mix_count);
CAT_IF_DUMP(cout << "Row " << row_seed << " in slot " << row_i << " of weight "
<< row->Params.PeelCount << " [a=" << row->Params.PeelAdd << "] : ";)
PeelRowIterator iter(row->Params, _block_count, _block_next_prime);
uint16_t unmarked_count = 0;
uint16_t unmarked[2];
// Iterate columns in peeling matrix
do
{
const uint16_t column_i = iter.GetColumn();
CAT_IF_DUMP(cout << column_i << " ";)
PeelRefs *refs = &_peel_col_refs[column_i];
// If there was not enough room in the reference list:
if (CAT_UNLIKELY(refs->RowCount >= CAT_REF_LIST_MAX))
{
CAT_IF_DUMP(cout << "OpportunisticPeeling: Failure! " \
"Ran out of space for row references. CAT_REF_LIST_MAX must be increased!" << endl;)
CAT_DEBUG_BREAK();
FixPeelFailure(row, column_i);
return false;
}
// Add row reference to column
refs->Rows[refs->RowCount++] = row_i;
// If column is unmarked:
if (_peel_cols[column_i].Mark == MARK_TODO) {
unmarked[unmarked_count++ & 1] = column_i;
}
} while (iter.Iterate());
CAT_IF_DUMP(cout << endl;)
// Initialize row state
row->UnmarkedCount = unmarked_count;
switch (unmarked_count)
{
case 0:
// Link at head of defer list
row->NextRow = _defer_head_rows;
_defer_head_rows = row_i;
break;
case 1:
// Solve only unmarked column with this row
if (!SolveWithPeel(
row,
row_i,
unmarked[0]))
{
return false;
}
break;
case 2:
// Remember which two columns were unmarked
row->Marks.Unmarked[0] = unmarked[0];
row->Marks.Unmarked[1] = unmarked[1];
// Increment weight-2 reference count for unmarked columns
_peel_cols[unmarked[0]].Weight2Refs++;
_peel_cols[unmarked[1]].Weight2Refs++;
break;
}
return true;
}
void Codec::FixPeelFailure(
PeelRow * GF256_RESTRICT row, ///< The row that failed
const uint16_t fail_column_i ///< Column end point
)
{
CAT_IF_DUMP(cout << "!!Fixing Peel Failure!! Unreferencing columns, ending at "
<< fail_column_i << " :";)
PeelRowIterator iter(row->Params, _block_count, _block_next_prime);
// Iterate columns in peeling matrix
do
{
const uint16_t column = iter.GetColumn();
if (column == fail_column_i) {
break;
}
CAT_IF_DUMP(cout << " " << column;)
PeelRefs * GF256_RESTRICT refs = &_peel_col_refs[column];
// Subtract off row count.
// This invalidates the row number that was written earlier
refs->RowCount--;
} while (iter.Iterate());
CAT_IF_DUMP(cout << endl;)
}
bool Codec::PeelAvalancheOnSolve(
uint16_t column_i, ///< Column that was solved or deferred
uint16_t solved_row_i ///< Solving row, or LIST_TERM for deferred root
)
{
CAT_DEBUG_ASSERT(_peel_avalanche != nullptr);
CAT_DEBUG_ASSERT(column_i < _block_count);
CAT_DEBUG_ASSERT(
solved_row_i == LIST_TERM ||
solved_row_i < static_cast<unsigned>(_block_count) + _extra_count);
// This explicit stack reproduces the old recursive DFS exactly: A parent
// reference-list cursor is advanced before a child frame is pushed, and
// traversal resumes at that cursor only after the child has completed.
// Each pushed child transitions a distinct TODO column to MARK_PEEL, so
// no valid avalanche can need more than one frame per peeling column.
unsigned stack_count = 1;
_peel_avalanche[0].Column = column_i;
_peel_avalanche[0].SolvedRow = solved_row_i;
_peel_avalanche[0].NextRef = 0;
_peel_avalanche[0].RefCount = _peel_col_refs[column_i].RowCount;
#if defined(WIREHAIR_TESTING)
if (_testing_peel_max_depth < stack_count) {
_testing_peel_max_depth = stack_count;
}
#endif
while (stack_count > 0)
{
PeelAvalancheFrame * GF256_RESTRICT frame =
&_peel_avalanche[stack_count - 1];
CAT_DEBUG_ASSERT(frame->Column < _block_count);
PeelRefs * GF256_RESTRICT refs =
&_peel_col_refs[frame->Column];
CAT_DEBUG_ASSERT(frame->RefCount <= refs->RowCount);
CAT_DEBUG_ASSERT(frame->NextRef <= frame->RefCount);
// Finish this simulated recursive call.
if (frame->NextRef >= frame->RefCount)
{
if (frame->SolvedRow != LIST_TERM) {
_peel_cols[frame->Column].PeelRow = frame->SolvedRow;
}
--stack_count;
continue;
}
const uint16_t active_column_i = frame->Column;
// Update unmarked row count for this referenced row
const uint16_t ref_row_i = refs->Rows[frame->NextRef++];
PeelRow * GF256_RESTRICT ref_row = &_peel_rows[ref_row_i];
const uint16_t unmarked_count = --ref_row->UnmarkedCount;
// If row may be solving a column now:
if (unmarked_count == 1)
{
uint16_t new_column_i = ref_row->Marks.Unmarked[0];
// If that is this column:
if (new_column_i == active_column_i) {
new_column_i = ref_row->Marks.Unmarked[1];
}
/*
Rows that are to be deferred will either end up
here or below where it handles the case of there
being no columns unmarked in a row.
*/
// If column is already solved:
if (_peel_cols[new_column_i].Mark == MARK_TODO)
{
CAT_DEBUG_ASSERT(stack_count < _block_count);
if (CAT_UNLIKELY(stack_count >= _block_count)) {
CAT_DEBUG_BREAK();
return false;
}
BeginPeelSolution(ref_row, ref_row_i, new_column_i);
PeelAvalancheFrame * GF256_RESTRICT child =
&_peel_avalanche[stack_count++];
child->Column = new_column_i;
child->SolvedRow = ref_row_i;
child->NextRef = 0;
child->RefCount =
_peel_col_refs[new_column_i].RowCount;
#if defined(WIREHAIR_TESTING)
if (_testing_peel_max_depth < stack_count) {
_testing_peel_max_depth = stack_count;
}
#endif
continue;
}
CAT_IF_DUMP(cout << "PeelAvalancheOnSolve: Deferred(1) with column " <<
active_column_i << " at row " << ref_row_i << endl;)
// Link at head of defer list
ref_row->NextRow = _defer_head_rows;
_defer_head_rows = ref_row_i;
}
else if (unmarked_count == 2)
{
// Regenerate the row columns to discover which are unmarked
PeelRowIterator ref_iter(ref_row->Params, _block_count, _block_next_prime);
uint16_t store_count = 0;
// For each column:
do
{
const uint16_t ref_column_i = ref_iter.GetColumn();
PeelColumn * GF256_RESTRICT ref_col = &_peel_cols[ref_column_i];
// If column is unmarked:
if (ref_col->Mark == MARK_TODO)
{
// Store the two unmarked columns in the row
ref_row->Marks.Unmarked[store_count++] = ref_column_i;
// Increment weight-2 reference count (cannot hurt even if not true)
ref_col->Weight2Refs++;
}
} while (ref_iter.Iterate());
/*
This is a little subtle, but sometimes the avalanche will
happen here, and sometimes a row will be marked deferred.
*/
if (store_count <= 1)
{
// Insure that this row won't be processed further during this recursion
ref_row->UnmarkedCount = 0;
// If row is to be deferred:
if (store_count == 1)
{
const uint16_t new_column_i =
ref_row->Marks.Unmarked[0];
CAT_DEBUG_ASSERT(stack_count < _block_count);
if (CAT_UNLIKELY(stack_count >= _block_count)) {
CAT_DEBUG_BREAK();
return false;
}
BeginPeelSolution(ref_row, ref_row_i, new_column_i);
PeelAvalancheFrame * GF256_RESTRICT child =
&_peel_avalanche[stack_count++];
child->Column = new_column_i;
child->SolvedRow = ref_row_i;
child->NextRef = 0;
child->RefCount =
_peel_col_refs[new_column_i].RowCount;
#if defined(WIREHAIR_TESTING)
if (_testing_peel_max_depth < stack_count) {
_testing_peel_max_depth = stack_count;
}
#endif
continue;
}
CAT_IF_DUMP(cout << "PeelAvalancheOnSolve: Deferred(2) with column " << active_column_i << " at row " << ref_row_i << endl;)
// Link at head of defer list
ref_row->NextRow = _defer_head_rows;
_defer_head_rows = ref_row_i;
}
}
}
return true;
}
void Codec::BeginPeelSolution(
PeelRow * GF256_RESTRICT row, ///< Pointer to row data
uint16_t row_i, ///< Row index
uint16_t column_i ///< Column that this solves
)
{
CAT_IF_DUMP(cout << "Peel: Solved column " << column_i << " with row " << row_i << endl;)
PeelColumn * GF256_RESTRICT column = &_peel_cols[column_i];
// Mark this column as solved
column->Mark = MARK_PEEL;
// Remember which column it solves
row->Marks.Result.PeelColumn = column_i;
// Link to back of the peeled list
if (_peel_tail_rows) {
_peel_tail_rows->NextRow = row_i;
}
else {
_peel_head_rows = row_i;
}
row->NextRow = LIST_TERM;
_peel_tail_rows = row;
// Indicate that this row hasn't been copied yet
row->Marks.Result.IsCopied = 0;
#if defined(WIREHAIR_TESTING)
const uint16_t values[2] = { row_i, column_i };
for (unsigned value_i = 0; value_i < 2; ++value_i)
{
const uint16_t value = values[value_i];
_testing_peel_order_hash =
(_testing_peel_order_hash ^ static_cast<uint8_t>(value)) *
UINT64_C(1099511628211);
_testing_peel_order_hash =
(_testing_peel_order_hash ^ static_cast<uint8_t>(value >> 8)) *
UINT64_C(1099511628211);
}
#endif
}
bool Codec::SolveWithPeel(
PeelRow * GF256_RESTRICT row, ///< Pointer to row data
uint16_t row_i, ///< Row index
uint16_t column_i ///< Column that this solves
)
{
BeginPeelSolution(row, row_i, column_i);
// Attempt to avalanche and solve other columns
return PeelAvalancheOnSolve(column_i, row_i);
}
bool Codec::GreedyPeeling()
{
CAT_IF_DUMP(cout << endl << "---- GreedyPeeling ----" << endl << endl;)
// Initialize list
_defer_head_columns = LIST_TERM;
_defer_count = 0;
const unsigned block_count = _block_count;
// Until all columns are marked:
for (;;)
{
uint16_t best_column_i = LIST_TERM;
unsigned best_w2_refs = 0;
unsigned best_row_count = 0;
const PeelColumn *column = _peel_cols;
// For each peel column:
for (uint16_t column_i = 0; column_i < block_count; ++column_i, ++column)
{
// If column is not marked yet:
if (column->Mark == MARK_TODO)
{
const unsigned w2_refs = column->Weight2Refs;
// If it may have the most weight-2 references:
if (w2_refs >= best_w2_refs)
{
const unsigned row_count = _peel_col_refs[column_i].RowCount;
// If it has the largest row references overall:
if (w2_refs > best_w2_refs || row_count >= best_row_count)
{
// Use that one
best_column_i = column_i;
best_w2_refs = w2_refs;
best_row_count = row_count;
}
}
}
}
// If no column was found:
if (best_column_i == LIST_TERM) {
// Peeling is complete
break;
}
// Mark column as deferred
PeelColumn *best_column = &_peel_cols[best_column_i];
best_column->Mark = MARK_DEFER;
++_defer_count;
// Add at head of deferred list
best_column->Next = _defer_head_columns;
_defer_head_columns = best_column_i;
CAT_IF_DUMP(cout << "Deferred column " << best_column_i <<
" for Gaussian elimination, which had " << best_column->Weight2Refs <<
" weight-2 row references" << endl;)
// Peel resuming from where this column left off
if (!PeelAvalancheOnSolve(best_column_i)) {
return false;
}
}
return true;
}
//------------------------------------------------------------------------------
// Stage (2) Compression
void Codec::SetDeferredColumns()
{
CAT_IF_DUMP(cout << endl << "---- SetDeferredColumns ----" << endl << endl;)
PeelColumn * GF256_RESTRICT column;
// For each deferred column:
for (uint16_t ge_column_i = 0, defer_i = _defer_head_columns;
defer_i != LIST_TERM;
defer_i = column->Next, ++ge_column_i)
{
column = &_peel_cols[defer_i];
CAT_IF_DUMP(cout << "GE column " << ge_column_i <<
" mapped to matrix column " << defer_i << " :";)
// Get pointer to this matrix row
uint64_t *matrix_row_offset = _compress_matrix + (ge_column_i >> 6);
// Get word mask for this column bit
const uint64_t ge_mask = (uint64_t)1 << (ge_column_i & 63);
// Get references for this deferred index
const PeelRefs * GF256_RESTRICT refs = &_peel_col_refs[defer_i];
// For each affected row:
for (unsigned i = 0, count = refs->RowCount; i < count; ++i)
{
const uint16_t row_i = refs->Rows[i];
CAT_IF_DUMP(cout << " " << row_i;)
matrix_row_offset[_ge_pitch * row_i] |= ge_mask;
}
CAT_IF_DUMP(cout << endl;)
// Set column map for this GE column
_ge_col_map[ge_column_i] = defer_i;
// Set reverse mapping also
column->GEColumn = ge_column_i;
}
// Set column map for each mix column:
for (uint16_t added_i = 0, count = _mix_count; added_i < count; ++added_i)
{
CAT_DEBUG_ASSERT((unsigned)_defer_count + (unsigned)added_i < 65536);
CAT_DEBUG_ASSERT((unsigned)_block_count + (unsigned)added_i < 65536);
const uint16_t ge_column_i = _defer_count + added_i;
const uint16_t column_i = _block_count + added_i;
CAT_IF_DUMP(cout << "GE column(mix) " << ge_column_i <<
" mapped to matrix column " << column_i << endl;)
_ge_col_map[ge_column_i] = column_i;
}
}
#ifdef WH_COUNT
static thread_local unsigned wh_graph_defer = 0;
static thread_local unsigned wh_graph_rows = 0;
static thread_local unsigned wh_graph_components = 0;
static thread_local unsigned wh_graph_max_component_value = 0;
static thread_local uint64_t wh_graph_sum_squares = 0;
extern "C" unsigned wh_graph_defer_count() { return wh_graph_defer; }
extern "C" unsigned wh_graph_defer_rows() { return wh_graph_rows; }
extern "C" unsigned wh_graph_component_count() { return wh_graph_components; }
extern "C" unsigned wh_graph_max_component() { return wh_graph_max_component_value; }
extern "C" uint64_t wh_graph_component_sum_squares() { return wh_graph_sum_squares; }
void Codec::MeasureDeferredComponents()
{
wh_graph_defer = _defer_count;
wh_graph_rows = 0;
wh_graph_components = 0;
wh_graph_max_component_value = 0;
wh_graph_sum_squares = 0;
if (_defer_count == 0) {
return;
}
std::vector<uint16_t> parent(_defer_count);
std::vector<uint16_t> size(_defer_count, 1);
for (uint16_t i = 0; i < _defer_count; ++i) {
parent[i] = i;
}
const auto find_root = [&](uint16_t x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
};
const auto union_roots = [&](uint16_t a, uint16_t b) {
uint16_t ra = find_root(a);
uint16_t rb = find_root(b);
if (ra == rb) {
return;
}
if (size[ra] < size[rb]) {
const uint16_t temp = ra;
ra = rb;
rb = temp;
}
parent[rb] = ra;
size[ra] = (uint16_t)(size[ra] + size[rb]);
};
for (uint16_t defer_row_i = _defer_head_rows;
defer_row_i != LIST_TERM;
defer_row_i = _peel_rows[defer_row_i].NextRow)
{
++wh_graph_rows;