parmesan-par2 0.6.0

Fast, standalone PAR2 (Reed-Solomon) creation, verification and repair tool
Documentation
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
use super::*;

#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
pub(super) fn pack_affine_tile(
    prepared: &[Vec<u8>],
    off: usize,
    tile_len: usize,
    block: usize,
) -> Vec<u8> {
    let n = prepared.len();
    let blocks = tile_len / block;
    let mut out = vec![0u8; n * tile_len];
    for b in 0..blocks {
        for s in 0..n {
            let src = &prepared[s][off + b * block..off + (b + 1) * block];
            let dst = &mut out[(b * n + s) * block..(b * n + s + 1) * block];
            dst.copy_from_slice(src);
        }
    }
    out
}

/// Parpar Affine AVX-512 packed: 128-byte blocks, `srcCount` 6, 4 KiB tiles.
#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
pub(super) const AFFINE512_BLOCK: usize = 128;
#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
pub(super) const AFFINE512_INTERLEAVE: usize = 6;
#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
pub(super) const AFFINE512_CHUNK: usize = 4096;

/// Prefetch one cache line from the half of the next output tile paired with
/// this six-source group. ParPar's `prefetchDownscale=1` maps the first two
/// groups onto the two 2 KiB halves of the next 4 KiB output tile.
#[cfg(target_arch = "x86_64")]
#[inline(always)]
unsafe fn affine512_prefetch_next_output(next_dst: Option<*const i8>, source: usize, block: usize) {
    let half = source / AFFINE512_INTERLEAVE;
    if half < 2 {
        if let Some(next_dst) = next_dst {
            unsafe {
                _mm_prefetch::<_MM_HINT_ET1>(
                    next_dst.add(half * (AFFINE512_CHUNK / 2) + block * 64),
                );
            }
        }
    }
}

#[cfg(target_arch = "x86_64")]
type Affine512Matrices = (__m512i, __m512i, __m512i, __m512i);

/// Load and XOR the four nibble contributions for two coefficients at once.
///
/// This mirrors ParPar's `gf16_affine_load2_matrix`: each 256-bit load gets
/// the four matrices in their packed order (`ll`, `hh`, `hl`, `lh`) for one
/// nibble contribution,
/// and the low/high 256-bit lanes carry one coefficient each.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f")]
unsafe fn affine512_load2_matrix(
    scratch: &AffineNibbleScratch,
    coeff_a: u16,
    coeff_b: u16,
) -> __m512i {
    unsafe fn load_contribution(scratch: &AffineNibbleScratch, coeff: u16, slot: usize) -> __m256i {
        let nibble = ((coeff >> (slot * 4)) & 0xf) as usize;
        let ptr = (&scratch.mats[nibble][slot] as *const (u64, u64, u64, u64)).cast::<__m256i>();
        unsafe { _mm256_load_si256(ptr) }
    }

    let load_pair = |slot| unsafe {
        _mm512_inserti64x4::<1>(
            _mm512_castsi256_si512(load_contribution(scratch, coeff_a, slot)),
            load_contribution(scratch, coeff_b, slot),
        )
    };
    let lo = _mm512_xor_si512(load_pair(0), load_pair(1));
    _mm512_ternarylogic_epi32(lo, load_pair(2), load_pair(3), 0x96)
}

/// Expand the packed pair returned by [`affine512_load2_matrix`] into the
/// broadcast matrices consumed by the six-source Affine512 loop.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f")]
unsafe fn affine512_expand_pair(packed: __m512i) -> [Affine512Matrices; 2] {
    let a_hi = _mm512_shuffle_i64x2::<0x11>(packed, packed);
    let a = (
        _mm512_broadcastq_epi64(_mm512_castsi512_si128(packed)),
        _mm512_broadcastq_epi64(_mm512_castsi512_si128(a_hi)),
        _mm512_permutex_epi64::<0x55>(a_hi),
        _mm512_permutex_epi64::<0xff>(a_hi),
    );

    let b_hi = _mm512_shuffle_i64x2::<0xbb>(packed, packed);
    let b = (
        _mm512_permutex_epi64::<0xaa>(b_hi),
        _mm512_broadcastq_epi64(_mm512_castsi512_si128(b_hi)),
        _mm512_permutex_epi64::<0x55>(b_hi),
        _mm512_permutex_epi64::<0xff>(b_hi),
    );
    [a, b]
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f")]
pub(super) unsafe fn affine512_load_pair(
    scratch: &AffineNibbleScratch,
    coeff_a: u16,
    coeff_b: u16,
) -> [Affine512Matrices; 2] {
    unsafe { affine512_expand_pair(affine512_load2_matrix(scratch, coeff_a, coeff_b)) }
}

#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
pub(super) fn affine512_src_scale(n_queued: usize, source: usize) -> usize {
    let il = AFFINE512_INTERLEAVE;
    let last = n_queued - n_queued % il;
    if !n_queued.is_multiple_of(il) && source >= last {
        n_queued % il
    } else {
        il
    }
}

/// Dest tile `tile`, recovery `rec`: `tile * n_rec * CHUNK + rec * CHUNK`.
#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
pub(super) fn affine512_dest_off(n_rec: usize, rec: usize, tile: usize) -> usize {
    tile * n_rec * AFFINE512_CHUNK + rec * AFFINE512_CHUNK
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw")]
pub(super) unsafe fn affine512_acc_to_slices(
    acc: Affine512Acc,
    exponent_start: u32,
) -> Vec<RecoverySlice> {
    (0..acc.n_rec)
        .into_par_iter()
        .map(|i| {
            let mut data = vec![0u8; acc.slice_len];
            let n_tiles = acc.slice_len.div_ceil(AFFINE512_CHUNK);
            for t in 0..n_tiles {
                let off = t * AFFINE512_CHUNK;
                let tile_len = (acc.slice_len - off).min(AFFINE512_CHUNK);
                let src = acc.data.as_ptr().add(affine512_dest_off(acc.n_rec, i, t));
                let dst = data.as_mut_ptr().add(off);
                for b in 0..tile_len / AFFINE512_BLOCK {
                    super::affine::affine512_finish_block(
                        src.add(b * AFFINE512_BLOCK),
                        dst.add(b * AFFINE512_BLOCK),
                    );
                }
            }
            RecoverySlice {
                exponent: exponent_start + i as u32,
                data,
            }
        })
        .collect()
}

/// Byte offset of source `s`, 128-byte block `block` inside tile `tile`.
#[cfg_attr(not(target_arch = "x86_64"), allow(dead_code))]
pub(super) fn affine512_packed_off(
    n_queued: usize,
    tile: usize,
    source: usize,
    block: usize,
) -> usize {
    let il = AFFINE512_INTERLEAVE;
    let b = AFFINE512_BLOCK;
    let chunk = AFFINE512_CHUNK;
    let group = source / il;
    let lane = source % il;
    let scale = affine512_src_scale(n_queued, source);
    tile * chunk * n_queued + group * chunk * il + lane * b + block * b * scale
}

/// Shuffle-prepare raw slices into the ParPar packed Affine512 layout (once).
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw")]
pub(super) unsafe fn prepare_packed_affine512(
    queued: &[Vec<u8>],
    packed: &mut [u8],
    slice_len: usize,
) {
    let n = queued.len();
    if n == 0 {
        return;
    }
    let n_tiles = slice_len.div_ceil(AFFINE512_CHUNK);
    let dst = packed.as_mut_ptr() as usize;
    queued.par_iter().enumerate().for_each(|(s, src)| {
        for t in 0..n_tiles {
            let off = t * AFFINE512_CHUNK;
            let tile_len = (slice_len - off).min(AFFINE512_CHUNK);
            let blocks = tile_len / AFFINE512_BLOCK;
            for b in 0..blocks {
                let src_p = src.as_ptr().add(off + b * AFFINE512_BLOCK);
                let dst_p = (dst as *mut u8).add(affine512_packed_off(n, t, s, b));
                crate::affine::affine512_prepare_block(src_p, dst_p);
            }
        }
    });
}

impl RecoveryEncoder {
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx512f,avx512bw,gfni")]
    pub(super) unsafe fn flush_avx512_affine(&mut self) {
        let start_index = self.next_index;
        let queued = std::mem::take(&mut self.queued_slices);
        self.next_index += queued.len();
        let new_cs: Vec<SliceChecksum> = if self.compute_checksums {
            slice_checksums_batch(&queued)
        } else {
            Vec::new()
        };
        let RecoveryBufferSet::Affine512(ref mut acc) = self.buffers else {
            unreachable!("flush_avx512_affine on non-Affine512 encoder");
        };
        let mut prepared = std::mem::take(&mut self.affine_prepare);
        let slice_len = acc.slice_len;
        let n_tiles = slice_len.div_ceil(AFFINE512_CHUNK);
        let packed_len = n_tiles * AFFINE512_CHUNK * queued.len();
        if prepared.is_empty() {
            prepared.push(vec![0u8; packed_len]);
        } else {
            prepared[0].resize(packed_len, 0);
        }
        unsafe {
            prepare_packed_affine512(&queued, &mut prepared[0], slice_len);
            Self::flush_avx512_affine_work(
                acc,
                &prepared[0],
                queued.len(),
                start_index,
                &self.logbases,
                self.exponent_start,
                &self.gf,
            );
        }
        self.affine_prepare = prepared;
        self.pending_checksums.extend(new_cs);
        self.recycle_queue(queued);
    }

    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx512f,avx512bw,gfni")]
    pub(super) unsafe fn flush_avx512_affine_work(
        acc: &mut Affine512Acc,
        packed: &[u8],
        n_queued: usize,
        start_index: usize,
        logbases: &[u32],
        exponent_start: u32,
        gf: &Gf16,
    ) {
        let n_rec = acc.n_rec;
        if n_queued == 0 || n_rec == 0 {
            return;
        }
        let slice_len = acc.slice_len;
        let n_tiles = slice_len.div_ceil(AFFINE512_CHUNK);
        let scratch = AffineNibbleScratch::new(gf);
        let coeffs: Vec<u16> = (0..n_rec * n_queued)
            .map(|flat| {
                let rec = flat / n_queued;
                let q_idx = flat % n_queued;
                let exponent = exponent_start + rec as u32;
                let logbase = logbases[start_index + q_idx] as u64;
                let log_coeff = ((logbase * exponent as u64) % ORDER as u64) as u32;
                gf.exp(log_coeff)
            })
            .collect();

        let dest_base = acc.data.as_mut_ptr() as usize;
        let packed_addr = packed.as_ptr() as usize;

        (0..n_tiles).into_par_iter().for_each(|t| {
            let off = t * AFFINE512_CHUNK;
            let tile_len = (slice_len - off).min(AFFINE512_CHUNK);
            let blocks = tile_len / AFFINE512_BLOCK;
            if blocks == 0 {
                return;
            }
            if t + 1 < n_tiles {
                unsafe {
                    _mm_prefetch::<_MM_HINT_T1>(
                        (packed_addr as *const i8).add(affine512_packed_off(n_queued, t + 1, 0, 0)),
                    );
                }
            }
            for rec in 0..n_rec {
                let dst = (dest_base as *mut u8).add(affine512_dest_off(n_rec, rec, t));
                let next_dst = (rec + 1 < n_rec)
                    .then(|| (dest_base as *const i8).add(affine512_dest_off(n_rec, rec + 1, t)));
                let mut q = 0usize;
                while q < n_queued {
                    let take = (n_queued - q).min(AFFINE512_INTERLEAVE);
                    let base = rec * n_queued + q;
                    // A full 12-slice queue reaches this branch twice. Keep
                    // all six matrix sets as named values: an array plus a
                    // dynamic source loop makes LLVM spill 24 ZMM registers
                    // and recalculate packed offsets inside every 128-byte
                    // block. ParPar likewise specializes its six-source call.
                    if take == AFFINE512_INTERLEAVE {
                        let [mat_a, mat_b] = unsafe {
                            affine512_load_pair(&scratch, coeffs[base], coeffs[base + 1])
                        };
                        let [mat_c, mat_d] = unsafe {
                            affine512_load_pair(&scratch, coeffs[base + 2], coeffs[base + 3])
                        };
                        let [mat_e, mat_f] = unsafe {
                            affine512_load_pair(&scratch, coeffs[base + 4], coeffs[base + 5])
                        };
                        let src = unsafe {
                            (packed_addr as *const u8).add(affine512_packed_off(n_queued, t, q, 0))
                        };

                        macro_rules! muladd_round {
                            ($source:expr, $matrix:ident, $tpl:ident, $tph:ident) => {{
                                let source = $source.cast::<__m512i>();
                                let ta = _mm512_loadu_si512(source);
                                let tb = _mm512_loadu_si512(source.add(1));
                                $tpl = _mm512_ternarylogic_epi32(
                                    _mm512_gf2p8affine_epi64_epi8(ta, $matrix.2, 0),
                                    _mm512_gf2p8affine_epi64_epi8(tb, $matrix.0, 0),
                                    $tpl,
                                    0x96,
                                );
                                $tph = _mm512_ternarylogic_epi32(
                                    _mm512_gf2p8affine_epi64_epi8(ta, $matrix.3, 0),
                                    _mm512_gf2p8affine_epi64_epi8(tb, $matrix.1, 0),
                                    $tph,
                                    0x96,
                                );
                            }};
                        }

                        unsafe {
                            for block_idx in 0..blocks {
                                affine512_prefetch_next_output(next_dst, q, block_idx);
                                let p = dst.add(block_idx * AFFINE512_BLOCK).cast::<__m512i>();
                                let sp =
                                    src.add(block_idx * AFFINE512_BLOCK * AFFINE512_INTERLEAVE);
                                let mut tph = _mm512_loadu_si512(p);
                                let mut tpl = _mm512_loadu_si512(p.add(1));
                                muladd_round!(sp, mat_a, tpl, tph);
                                muladd_round!(sp.add(AFFINE512_BLOCK), mat_b, tpl, tph);
                                muladd_round!(sp.add(AFFINE512_BLOCK * 2), mat_c, tpl, tph);
                                muladd_round!(sp.add(AFFINE512_BLOCK * 3), mat_d, tpl, tph);
                                muladd_round!(sp.add(AFFINE512_BLOCK * 4), mat_e, tpl, tph);
                                muladd_round!(sp.add(AFFINE512_BLOCK * 5), mat_f, tpl, tph);
                                _mm512_storeu_si512(p, tph);
                                _mm512_storeu_si512(p.add(1), tpl);
                            }
                        }
                        q += AFFINE512_INTERLEAVE;
                        continue;
                    }

                    let mut mats = [(
                        _mm512_setzero_si512(),
                        _mm512_setzero_si512(),
                        _mm512_setzero_si512(),
                        _mm512_setzero_si512(),
                    ); 6];
                    let paired = take - take % 2;
                    for s in (0..paired).step_by(2) {
                        let pair = unsafe {
                            affine512_load_pair(&scratch, coeffs[base + s], coeffs[base + s + 1])
                        };
                        mats[s] = pair[0];
                        mats[s + 1] = pair[1];
                    }
                    for s in paired..take {
                        let (m_ll, m_lh, m_hl, m_hh) = scratch.load(coeffs[base + s]);
                        mats[s] = (
                            _mm512_set1_epi64(m_ll as i64),
                            _mm512_set1_epi64(m_hl as i64),
                            _mm512_set1_epi64(m_lh as i64),
                            _mm512_set1_epi64(m_hh as i64),
                        );
                    }
                    unsafe {
                        for b in 0..blocks {
                            affine512_prefetch_next_output(next_dst, q, b);
                            let p = dst.add(b * AFFINE512_BLOCK).cast::<__m512i>();
                            let mut tph = _mm512_loadu_si512(p);
                            let mut tpl = _mm512_loadu_si512(p.add(1));
                            for (s, &(mll, mhl, mlh, mhh)) in mats.iter().enumerate().take(take) {
                                let sp = (packed_addr as *const u8)
                                    .add(affine512_packed_off(n_queued, t, q + s, b))
                                    .cast::<__m512i>();
                                let ta = _mm512_loadu_si512(sp);
                                let tb = _mm512_loadu_si512(sp.add(1));
                                tpl = _mm512_ternarylogic_epi32(
                                    _mm512_gf2p8affine_epi64_epi8(ta, mlh, 0),
                                    _mm512_gf2p8affine_epi64_epi8(tb, mll, 0),
                                    tpl,
                                    0x96,
                                );
                                tph = _mm512_ternarylogic_epi32(
                                    _mm512_gf2p8affine_epi64_epi8(ta, mhh, 0),
                                    _mm512_gf2p8affine_epi64_epi8(tb, mhl, 0),
                                    tph,
                                    0x96,
                                );
                            }
                            _mm512_storeu_si512(p, tph);
                            _mm512_storeu_si512(p.add(1), tpl);
                        }
                    }
                    q += take;
                }
            }
        });
    }
}