Repository navigation
Expand file tree
/
Copy pathrzip.c
More file actions
1789 lines (1562 loc) · 50.8 KB
/
Copy pathrzip.c
File metadata and controls
1789 lines (1562 loc) · 50.8 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
/*
Copyright (C) 2006-2016,2018,2022,2026 Con Kolivas
Copyright (C) 1998 Andrew Tridgell
Modified to use flat hash, memory limit and variable hash culling
by Rusty Russell copyright (C) 2003.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* rzip compression algorithm */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef HAVE_SYS_MMAN_H
# include <sys/mman.h>
#endif
#include <sys/statvfs.h>
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <lzo/lzoconf.h>
#include <lzo/lzo1x.h>
#ifdef HAVE_ERRNO_H
# include <errno.h>
#endif
#ifdef HAVE_ENDIAN_H
# include <endian.h>
#elif HAVE_SYS_ENDIAN_H
# include <sys/endian.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#include <inttypes.h>
#include <string.h>
#include "md5.h"
#include "match.h"
#include "stream.h"
#include "util.h"
#include "filters.h"
#include "lrzip_core.h"
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif
#define CHUNK_MULTIPLE (100 * 1024 * 1024)
#define CKSUM_CHUNK 1024*1024
#define GREAT_MATCH 1024
#define MINIMUM_MATCH 31
/* Hash table works as follows. We start by throwing tags at every
* offset into the table. As it fills, we start eliminating tags
* which don't have lower bits set to one (ie. first we eliminate all
* even tags, then all tags divisible by four, etc.). This ensures
* that on average, all parts of the file are covered by the hash, if
* sparsely.
*
* Slot size is 8 bytes (uint32 tag + uint32 offset) when the chunk fits
* in 32 bits, else 16-byte wide entries. The retained-entry budget comes
* from rzip-2.1's slot count for a given mb_used, capped by chunk size.
* When memory permits, spare buckets shorten the collision chains.
*/
/* Levels control hashtable size. mb_used is the historical "megabytes of
* hash" knob from rzip (8-byte entries); it sets the entry budget while
* bucket allocation also accounts for entry size and spare capacity. */
static struct level {
unsigned long mb_used;
unsigned initial_freq;
unsigned max_chain_len;
} levels[10] = {
{ 1, 4, 1 },
{ 2, 4, 2 },
{ 4, 4, 2 },
{ 8, 4, 2 },
{ 16, 4, 3 },
{ 32, 4, 4 },
{ 32, 2, 6 },
{ 64, 1, 16 }, /* More MB makes sense, but need bigger test files */
{ 64, 1, 32 },
{ 64, 1, 128 },
};
#define HASH_ENTRY_SIZE_NARROW 8
/* rzip-2.1 entry was u32+u32 = 8 bytes; use that for target slot density */
static void remap_low_sb(rzip_control *control, struct sliding_buffer *sb)
{
i64 new_offset;
new_offset = sb->offset_search;
round_to_page(&new_offset);
print_maxverbose("Sliding main buffer to offset %"PRId64"\n", new_offset);
if (unlikely(munmap(sb->buf_low, sb->size_low)))
failure("Failed to munmap in remap_low_sb\n");
if (new_offset + sb->size_low > sb->orig_size)
sb->size_low = sb->orig_size - new_offset;
sb->offset_low = new_offset;
sb->buf_low = (uchar *)mmap(sb->buf_low, sb->size_low, PROT_READ, MAP_SHARED, sb->fd, sb->orig_offset + sb->offset_low);
if (unlikely(sb->buf_low == MAP_FAILED))
failure("Failed to re mmap in remap_low_sb\n");
}
static inline unsigned history_page_slot(i64 offset)
{
/* Mix aligned offsets so regular page strides use different slots. */
return ((uint64_t)offset * UINT64_C(11400714819323198485)) >>
(64 - RZIP_HISTORY_CACHE_BITS);
}
static void read_history_page(rzip_control *control, struct sliding_buffer *sb,
uchar *buf, i64 offset, i64 len)
{
while (len) {
ssize_t n = pread(sb->fd, buf, (size_t)len, sb->orig_offset + offset);
if (n < 0 && errno == EINTR)
continue;
if (unlikely(n <= 0))
failure("Failed to read history page\n");
buf += n;
offset += n;
len -= n;
}
}
static inline void load_high_sb(rzip_control *control, struct sliding_buffer *sb, i64 p)
{
uchar *new_buf = NULL, *reuse;
i64 new_offset = p, new_size = 0;
struct history_page *page;
if (unlikely(!sb->history_cache)) {
sb->history_cache = calloc(RZIP_HISTORY_CACHE_SIZE, sizeof(*sb->history_cache));
sb->history_mask = RZIP_HISTORY_CACHE_SIZE - 1;
if (unlikely(!sb->history_cache)) {
/* A single spare page still keeps both operands alive. */
sb->history_cache = &sb->history_fallback;
sb->history_mask = 0;
}
}
new_offset -= (new_offset + sb->orig_offset) % control->page_size;
page = &sb->history_cache[history_page_slot(new_offset) & sb->history_mask];
if (page->buf && page->offset == new_offset && p < page->offset + page->size) {
new_buf = page->buf;
new_size = page->size;
page->buf = NULL;
}
/* Keep the current operand alive even when both page keys collide.
* Extract the requested page before caching the current one. */
page = &sb->history_cache[history_page_slot(sb->offset_high) & sb->history_mask];
reuse = page->buf;
page->buf = sb->buf_high;
page->offset = sb->offset_high;
page->size = sb->size_high;
sb->offset_high = new_offset;
if (new_buf) {
free(reuse);
sb->buf_high = new_buf;
sb->size_high = new_size;
return;
}
sb->size_high = MIN(sb->high_length, sb->orig_size - new_offset);
sb->buf_high = reuse ? reuse : malloc(sb->high_length);
if (unlikely(!sb->buf_high))
failure("Failed to allocate history page\n");
read_history_page(control, sb, sb->buf_high, new_offset, sb->size_high);
}
/* We use a "sliding mmap" to effectively read more than we can fit into the
* compression window. This is done by using a maximally sized lower mmap at
* the beginning of the block which slides up once the hash search moves beyond
* it, and a page-sized read cache for offsets outside the lower one.
* Both history operands stay valid during comparisons. This is slower than mmap
* but makes it possible to have unlimited sized compression windows. */
/* True if [p, p+len) lies entirely in the low map (len may be 0). */
static inline int sliding_in_low(const struct sliding_buffer *sb, i64 p, i64 len)
{
return p >= sb->offset_low && len >= 0 &&
p + len <= sb->offset_low + sb->size_low;
}
static uchar *sliding_get_sb(rzip_control *control, i64 p)
{
struct sliding_buffer *sb = &control->sb;
i64 sbo, sbs;
sbo = sb->offset_low;
sbs = sb->size_low;
if (p >= sbo && p < sbo + sbs)
return sb->buf_low + (p - sbo);
sbo = sb->offset_high;
sbs = sb->size_high;
if (p >= sbo && p < sbo + sbs)
return sb->buf_high + (p - sbo);
/* p is not within the low or high buffer range */
load_high_sb(control, sb, p);
return sb->buf_high + (p - sb->offset_high);
}
/* Ensure p is mapped; return pointer and contiguous forward length from p. */
static inline uchar *sliding_map_fwd(rzip_control *control, i64 p, i64 *contig)
{
struct sliding_buffer *sb = &control->sb;
i64 sbo, sbs;
sbo = sb->offset_low;
sbs = sb->size_low;
if (p >= sbo && p < sbo + sbs) {
*contig = sbs - (p - sbo);
return sb->buf_low + (p - sbo);
}
sbo = sb->offset_high;
sbs = sb->size_high;
if (p >= sbo && p < sbo + sbs) {
*contig = sbs - (p - sbo);
return sb->buf_high + (p - sbo);
}
load_high_sb(control, sb, p);
*contig = sb->size_high - (p - sb->offset_high);
return sb->buf_high + (p - sb->offset_high);
}
/* Contiguous bytes available strictly before p (for reverse matching). */
static inline i64 sliding_contig_before(rzip_control *control, i64 p)
{
struct sliding_buffer *sb = &control->sb;
i64 pm1, sbo, sbs;
if (p <= 0)
return 0;
pm1 = p - 1;
sbo = sb->offset_low;
sbs = sb->size_low;
if (pm1 >= sbo && pm1 < sbo + sbs)
return pm1 - sbo + 1;
sbo = sb->offset_high;
sbs = sb->size_high;
if (pm1 >= sbo && pm1 < sbo + sbs)
return pm1 - sbo + 1;
/* Map the byte we need, then recompute. */
sliding_get_sb(control, pm1);
sbo = sb->offset_high;
sbs = sb->size_high;
if (pm1 >= sbo && pm1 < sbo + sbs)
return pm1 - sbo + 1;
sbo = sb->offset_low;
sbs = sb->size_low;
if (pm1 >= sbo && pm1 < sbo + sbs)
return pm1 - sbo + 1;
return 1;
}
/* The length of continuous range of the sliding buffer starting at P.
* P must already be mapped (via sliding_get_sb / sliding_map_fwd). */
static inline i64 sliding_get_sb_range(rzip_control *control, i64 p)
{
struct sliding_buffer *sb = &control->sb;
i64 sbo, sbs;
sbo = sb->offset_low;
sbs = sb->size_low;
if (p >= sbo && p < sbo + sbs)
return sbs - (p - sbo);
sbo = sb->offset_high;
sbs = sb->size_high;
if (likely(p >= sbo && p < sbo + sbs))
return sbs - (p - sbo);
fatal_return(("sliding_get_sb_range: the pointer is out of range\n"), 0);
}
/* Since the sliding get_sb only allows us to access one byte at a time, we
* do the same as we did with get_sb with the memcpy since one memcpy is much
* faster than numerous memcpys 1 byte at a time */
static void single_mcpy(rzip_control *control, unsigned char *buf, i64 offset, i64 len)
{
memcpy(buf, control->sb.buf_low + offset, len);
}
static void sliding_mcpy(rzip_control *control, unsigned char *buf, i64 offset, i64 len)
{
i64 n = 0;
while (n < len) {
uchar *srcbuf = sliding_get_sb(control, offset + n);
i64 m = MIN(sliding_get_sb_range(control, offset + n), len - n);
memcpy(buf + n, srcbuf, m);
n += m;
}
}
/* ---- Stream 0 (rzip control) write batching ---- */
static void s0_flush(rzip_control *control, struct rzip_state *st)
{
if (st->s0_len) {
write_stream(control, st->ss, 0, st->s0_buf, st->s0_len);
st->s0_len = 0;
}
}
static void s0_write(rzip_control *control, struct rzip_state *st,
const uchar *p, unsigned len)
{
while (len) {
unsigned n = RZIP_S0_BUFSIZE - st->s0_len;
if (n > len)
n = len;
memcpy(st->s0_buf + st->s0_len, p, n);
st->s0_len += n;
p += n;
len -= n;
if (st->s0_len == RZIP_S0_BUFSIZE)
s0_flush(control, st);
}
}
static inline void put_u8(rzip_control *control, struct rzip_state *st, uchar b)
{
s0_write(control, st, &b, 1);
}
/* Put a variable length of bytes dependant on how big the chunk is */
static void put_vchars(rzip_control *control, struct rzip_state *st, i64 s, int length)
{
s = htole64(s);
s0_write(control, st, (uchar *)&s, (unsigned)length);
}
static void put_header(rzip_control *control, struct rzip_state *st, uchar head, i64 len)
{
put_u8(control, st, head);
put_vchars(control, st, len, 2);
}
static inline void put_match(rzip_control *control, struct rzip_state *st,
i64 p, i64 offset, i64 len)
{
do {
i64 ofs;
i64 n = len;
if (n > 0xFFFF)
n = 0xFFFF;
ofs = (p - offset);
put_header(control, st, 1, n);
put_vchars(control, st, ofs, st->chunk_bytes);
st->stats.matches++;
st->stats.match_bytes += n;
len -= n;
p += n;
offset += n;
} while (len);
}
/* write some data to a stream mmap encoded. Return -1 on failure */
static inline void write_sbstream(rzip_control *control, void *ss, int stream,
i64 p, i64 len)
{
struct stream_info *sinfo = ss;
while (len) {
i64 n = MIN(sinfo->bufsize - sinfo->s[stream].buflen, len);
control->do_mcpy(control, sinfo->s[stream].buf + sinfo->s[stream].buflen, p, n);
sinfo->s[stream].buflen += n;
p += n;
len -= n;
if (sinfo->s[stream].buflen == sinfo->bufsize)
flush_buffer(control, sinfo, stream);
}
}
static void put_literal(rzip_control *control, struct rzip_state *st, i64 last, i64 p)
{
do {
i64 len = p - last;
if (len > 0xFFFF)
len = 0xFFFF;
st->stats.literals++;
st->stats.literal_bytes += len;
put_header(control, st, 0, len);
if (len)
write_sbstream(control, st->ss, 1, last, len);
last += len;
} while (p > last);
}
/* All zero means empty. We might miss the first chunk this way. */
static inline bool empty_hash_n(uint32_t t, i64 offset)
{
return !(offset | t);
}
static i64 primary_hash(struct rzip_state *st, tag t)
{
return t & ((1U << st->hash_bits) - 1);
}
static inline tag increase_mask(tag tag_mask)
{
/* Get more precise. */
return (tag_mask << 1) | 1;
}
static inline bool minimum_bitness(struct rzip_state *st, tag t)
{
tag better_than_min = increase_mask(st->minimum_tag_mask);
return (t & better_than_min) != better_than_min;
}
/* Is a going to be cleaned before b? ie. does a have fewer low bits set? */
static inline bool lesser_bitness(tag a, tag b)
{
a = ~a;
b = ~b;
return (__builtin_ffs((int)a) < __builtin_ffs((int)b));
}
static inline size_t hash_entry_bytes(struct rzip_state *st)
{
return st->hash_wide ? sizeof(struct hash_entry_wide) : sizeof(struct hash_entry);
}
static inline void hash_get(struct rzip_state *st, i64 h, tag *t, i64 *offset)
{
if (st->hash_wide) {
struct hash_entry_wide *he = &((struct hash_entry_wide *)st->hash_table)[h];
*t = he->t;
*offset = he->offset;
} else {
struct hash_entry *he = &((struct hash_entry *)st->hash_table)[h];
*t = he->t;
*offset = he->offset;
}
}
static inline void hash_set(struct rzip_state *st, i64 h, tag t, i64 offset)
{
if (st->hash_wide) {
struct hash_entry_wide *he = &((struct hash_entry_wide *)st->hash_table)[h];
he->t = t;
he->offset = offset;
} else {
struct hash_entry *he = &((struct hash_entry *)st->hash_table)[h];
he->t = t;
he->offset = (uint32_t)offset;
}
}
static inline void hash_clear_slot(struct rzip_state *st, i64 h)
{
hash_set(st, h, 0, 0);
}
/* If hash bucket is taken, we spill into next bucket(s). Secondary hashing
works better in theory, but modern caches make this 20% faster. */
static void insert_hash(struct rzip_state *st, tag t, i64 offset)
{
i64 h, victim_h = 0, round = 0;
/* If we need to kill one, this will be it. */
static i64 victim_round = 0;
i64 mask = (1U << st->hash_bits) - 1;
tag he_t;
i64 he_off;
h = primary_hash(st, t);
hash_get(st, h, &he_t, &he_off);
while (!empty_hash_n(he_t, he_off)) {
/* If this due for cleaning anyway, just replace it:
rehashing might move it behind tag_clean_ptr. */
if (minimum_bitness(st, he_t)) {
st->hash_count--;
break;
}
/* If we are better than current occupant, we can't
jump over it: it will be cleaned before us, and
noone would then find us in the hash table. Rehash
it, then take its place. */
if (lesser_bitness(he_t, t)) {
insert_hash(st, he_t, he_off);
break;
}
/* If we have lots of identical patterns, we end up
with lots of the same hash number. Discard random. */
if (he_t == t) {
if (round == victim_round)
victim_h = h;
if (++round == st->level->max_chain_len) {
h = victim_h;
st->hash_count--;
victim_round++;
if (victim_round == st->level->max_chain_len)
victim_round = 0;
break;
}
}
h = (h + 1) & mask;
hash_get(st, h, &he_t, &he_off);
}
hash_set(st, h, t, offset);
}
/* Eliminate one hash entry with minimum number of lower bits set.
Returns tag requirement for any new entries. */
static inline tag clean_one_from_hash(rzip_control *control, struct rzip_state *st)
{
tag better_than_min;
tag he_t;
i64 he_off;
again:
better_than_min = increase_mask(st->minimum_tag_mask);
if (!st->tag_clean_ptr)
print_maxverbose("Starting sweep for mask %u\n", (unsigned int)st->minimum_tag_mask);
for (; st->tag_clean_ptr < (1U << st->hash_bits); st->tag_clean_ptr++) {
hash_get(st, st->tag_clean_ptr, &he_t, &he_off);
if (empty_hash_n(he_t, he_off))
continue;
if ((he_t & better_than_min) != better_than_min) {
hash_clear_slot(st, st->tag_clean_ptr);
st->hash_count--;
return better_than_min;
}
}
/* We hit the end: everthing in hash satisfies the better mask. */
st->minimum_tag_mask = better_than_min;
st->tag_clean_ptr = 0;
goto again;
}
static inline void single_next_tag(rzip_control *control, struct rzip_state *st, i64 p, tag *t)
{
uchar u;
u = control->sb.buf_low[p - 1];
*t ^= st->hash_index[u];
u = control->sb.buf_low[p + MINIMUM_MATCH - 1];
*t ^= st->hash_index[u];
}
static inline void sliding_next_tag(rzip_control *control, struct rzip_state *st, i64 p, tag *t)
{
struct sliding_buffer *sb = &control->sb;
i64 p1 = p - 1;
i64 p2 = p + MINIMUM_MATCH - 1;
/* Common case: both tag bytes sit in the low map — no high remap. */
if (sliding_in_low(sb, p1, 1) && sliding_in_low(sb, p2, 1)) {
*t ^= st->hash_index[sb->buf_low[p1 - sb->offset_low]];
*t ^= st->hash_index[sb->buf_low[p2 - sb->offset_low]];
return;
}
*t ^= st->hash_index[*sliding_get_sb(control, p1)];
*t ^= st->hash_index[*sliding_get_sb(control, p2)];
}
static inline tag single_full_tag(rzip_control *control, struct rzip_state *st, i64 p)
{
tag ret = 0;
int i;
for (i = 0; i < MINIMUM_MATCH; i++)
ret ^= st->hash_index[control->sb.buf_low[p + i]];
return ret;
}
static inline tag sliding_full_tag(rzip_control *control, struct rzip_state *st, i64 p)
{
struct sliding_buffer *sb = &control->sb;
tag ret = 0;
int i;
i64 contig;
uchar *s;
/* Whole MINIMUM_MATCH window in the low map. */
if (sliding_in_low(sb, p, MINIMUM_MATCH)) {
s = sb->buf_low + (p - sb->offset_low);
for (i = 0; i < MINIMUM_MATCH; i++)
ret ^= st->hash_index[s[i]];
return ret;
}
/* Prefer one contiguous high/low span when possible. */
s = sliding_map_fwd(control, p, &contig);
if (contig >= MINIMUM_MATCH) {
for (i = 0; i < MINIMUM_MATCH; i++)
ret ^= st->hash_index[s[i]];
return ret;
}
for (i = 0; i < MINIMUM_MATCH; ) {
i64 n;
s = sliding_map_fwd(control, p + i, &contig);
n = contig;
if (n > MINIMUM_MATCH - i)
n = MINIMUM_MATCH - i;
while (n--) {
ret ^= st->hash_index[s[0]];
s++;
i++;
}
}
return ret;
}
/*
* Core match on a linear buffer where absolute position q is at
* base[q - base_off]. Used for the non-sliding path and the sliding
* fast path when both sides lie in the low map.
*/
static i64
match_len_linear(const uchar *base, i64 base_off, struct rzip_state *st,
i64 p0, i64 op, i64 end, i64 *rev, i64 best)
{
const uchar *a, *b;
i64 max_fwd, f, max_rev, rev_end, op0, len;
if (op >= p0)
return 0;
op0 = op;
max_fwd = end - p0;
a = base + (p0 - base_off);
b = base + (op0 - base_off);
f = match_forward(a, b, max_fwd);
rev_end = MAX((i64)0, st->last_match);
max_rev = p0 - rev_end;
if (max_rev > op0)
max_rev = op0;
if (f + max_rev < MINIMUM_MATCH || f + max_rev <= best)
return 0;
*rev = match_reverse(a, b, max_rev);
len = f + *rev;
if (len < MINIMUM_MATCH || len <= best)
return 0;
return len;
}
static i64
single_match_len(rzip_control *control, struct rzip_state *st, i64 p0, i64 op,
i64 end, i64 *rev, i64 best)
{
return match_len_linear(control->sb.buf_low, 0, st, p0, op, end, rev, best);
}
/* Sliding match: low-map fast path, else span-wise forward/reverse compares. */
static i64
sliding_match_len(rzip_control *control, struct rzip_state *st, i64 p0, i64 op,
i64 end, i64 *rev, i64 best)
{
struct sliding_buffer *sb = &control->sb;
i64 max_fwd, f, max_rev, rev_end, p, o, len, op0;
i64 low = sb->offset_low, lsz = sb->size_low;
if (op >= p0)
return 0;
rev_end = MAX((i64)0, st->last_match);
max_fwd = end - p0;
/* Both sides fully in the low map (forward + reverse extent). */
if (rev_end >= low && p0 >= low && end <= low + lsz &&
op - MIN(p0 - rev_end, op) >= low && op + max_fwd <= low + lsz) {
return match_len_linear(sb->buf_low, low, st, p0, op, end, rev, best);
}
op0 = op;
f = 0;
while (f < max_fwd) {
i64 c1, c2, n, m;
uchar *a = sliding_map_fwd(control, p0 + f, &c1);
uchar *b = sliding_map_fwd(control, op0 + f, &c2);
n = c1 < c2 ? c1 : c2;
if (n > max_fwd - f)
n = max_fwd - f;
if (n <= 0)
break;
if (memcmp(a, b, (size_t)n) == 0) {
f += n;
continue;
}
m = match_forward(a, b, n);
f += m;
break;
}
max_rev = p0 - rev_end;
if (max_rev > op0)
max_rev = op0;
if (f + max_rev < MINIMUM_MATCH || f + max_rev <= best)
return 0;
/* Reverse-extend using contiguous runs ending at p-1 / o-1. */
p = p0;
o = op0;
while (p > rev_end && o > 0) {
i64 n1 = sliding_contig_before(control, p);
i64 n2 = sliding_contig_before(control, o);
i64 n = n1 < n2 ? n1 : n2;
uchar *a, *b;
i64 m;
if (n > p - rev_end)
n = p - rev_end;
if (n > o)
n = o;
if (n <= 0)
break;
a = sliding_get_sb(control, p - 1);
b = sliding_get_sb(control, o - 1);
m = match_reverse(a + 1, b + 1, n);
p -= m;
o -= m;
if (m < n)
break;
}
*rev = p0 - p;
len = f + *rev;
if (len < MINIMUM_MATCH || len <= best)
return 0;
return len;
}
static inline i64
match_len(rzip_control *control, struct rzip_state *st, i64 p0, i64 op,
i64 end, i64 *rev, i64 best)
{
if (st->sliding)
return sliding_match_len(control, st, p0, op, end, rev, best);
return single_match_len(control, st, p0, op, end, rev, best);
}
static inline void
next_tag(rzip_control *control, struct rzip_state *st, i64 p, tag *t)
{
if (st->sliding)
sliding_next_tag(control, st, p, t);
else
single_next_tag(control, st, p, t);
}
static inline tag
full_tag(rzip_control *control, struct rzip_state *st, i64 p)
{
if (st->sliding)
return sliding_full_tag(control, st, p);
return single_full_tag(control, st, p);
}
static inline i64
find_best_match(rzip_control *control, struct rzip_state *st, tag t, i64 p,
i64 end, i64 *offset, i64 *reverse)
{
i64 length = 0;
i64 rev = 0;
i64 h, probes = 0, tag_hits = 0;
i64 mask = (1U << st->hash_bits) - 1;
/* Cap probes: same-tag hits like insert_hash, plus a modest total walk. */
const i64 max_tag = st->level->max_chain_len;
const i64 max_probes = max_tag * 4 + 16;
tag he_t;
i64 he_off;
*reverse = 0;
*offset = 0;
h = primary_hash(st, t);
hash_get(st, h, &he_t, &he_off);
while (!empty_hash_n(he_t, he_off) && probes < max_probes) {
probes++;
if (t == he_t) {
i64 mlen;
if (tag_hits >= max_tag)
break;
tag_hits++;
mlen = match_len(control, st, p, he_off, end, &rev, length);
if (mlen) {
length = mlen;
*offset = he_off - rev;
*reverse = rev;
st->stats.tag_hits++;
} else
st->stats.tag_misses++;
}
h = (h + 1) & mask;
hash_get(st, h, &he_t, &he_off);
}
return length;
}
static void show_distrib(rzip_control *control, struct rzip_state *st)
{
i64 primary = 0;
i64 total = 0;
i64 i;
tag he_t;
i64 he_off;
for (i = 0; i < (1U << st->hash_bits); i++) {
hash_get(st, i, &he_t, &he_off);
if (empty_hash_n(he_t, he_off))
continue;
total++;
if (primary_hash(st, he_t) == i)
primary++;
}
if (total != st->hash_count)
print_err("WARNING: hash_count says total %"PRId64"\n", st->hash_count);
if (!total)
print_output("0 total hashes\n");
else {
print_output("%"PRId64" total hashes -- %"PRId64" in primary bucket (%-2.3f%%)\n",
total, primary, primary * 100.0 / total);
}
}
/* Dedicated MD5 worker: one long-lived thread, large batches, reused buffer. */
static void *md5_worker(void *data)
{
rzip_control *control = (rzip_control *)data;
while (42) {
cksem_wait(control, &control->cksum_worksem);
if (control->checksum.shutdown) {
cksem_post(control, &control->cksumsem);
break;
}
if (control->checksum.len > 0)
md5_process_bytes(control->checksum.input, control->checksum.len,
&control->ctx);
cksem_post(control, &control->cksumsem);
}
return NULL;
}
static void md5_thread_start(rzip_control *control)
{
i64 cap = CKSUM_CHUNK;
round_to_page(&cap);
control->checksum.capacity = cap;
control->checksum.buf = malloc((size_t)cap);
control->checksum.fill_buf = malloc((size_t)cap);
if (unlikely(!control->checksum.buf || !control->checksum.fill_buf))
failure("Failed to allocate MD5 batch buffer\n");
control->checksum.len = 0;
control->checksum.shutdown = 0;
cksem_init(control, &control->cksumsem);
cksem_post(control, &control->cksumsem);
cksem_init(control, &control->cksum_worksem);
if (unlikely(!create_pthread(control, &control->md5_thread, NULL, md5_worker, control)))
failure("Failed to start MD5 worker thread\n");
}
static void md5_thread_stop(rzip_control *control)
{
/* Wait until the worker is idle, then ask it to exit. */
cksem_wait(control, &control->cksumsem);
control->checksum.shutdown = 1;
control->checksum.len = 0;
cksem_post(control, &control->cksum_worksem);
if (unlikely(!join_pthread(control, control->md5_thread, NULL)))
failure("Failed to join MD5 worker thread\n");
dealloc(control->checksum.buf);
dealloc(control->checksum.fill_buf);
control->checksum.capacity = 0;
}
/* Queue [offset, offset+len) from the sliding/single map for MD5. */
static void md5_queue(rzip_control *control, i64 offset, i64 len)
{
while (len > 0) {
i64 n = MIN(len, control->checksum.capacity);
uchar *buf;
/* The complete input mapping remains immutable until this pass drains. */
if (control->sb.offset_low == 0 && control->sb.size_low == control->sb.orig_size) {
cksem_wait(control, &control->cksumsem);
control->checksum.input = control->sb.buf_low + offset;
} else {
/* Sliding mappings may be replaced while the worker runs. */
control->do_mcpy(control, control->checksum.fill_buf, offset, n);
cksem_wait(control, &control->cksumsem);
buf = control->checksum.buf;
control->checksum.buf = control->checksum.fill_buf;
control->checksum.fill_buf = buf;
control->checksum.input = control->checksum.buf;
}
control->checksum.len = n;
cksem_post(control, &control->cksum_worksem);
offset += n;
len -= n;
}
}
/* Wait until all submitted MD5 work is finished. */
static void md5_drain(rzip_control *control)
{
cksem_wait(control, &control->cksumsem);
cksem_post(control, &control->cksumsem);
}
static inline void hash_search(rzip_control *control, struct rzip_state *st,
double pct_base, double pct_multiple)
{
i64 cksum_limit = 0, p, end, progress_at;
tag t = 0, tag_mask = (1 << st->level->initial_freq) - 1;
struct sliding_buffer *sb = &control->sb;
int lastpct = 0, last_chunkpct = 0;
struct {
i64 p;
i64 ofs;
i64 len;
} current;
/* Progress at most every 64KiB or each 1% of the chunk. */
const i64 progress_bytes = 64 * 1024;
{
/* Target slot count as in rzip-2.1 (8-byte entries per mb_used). */
i64 hashsize = (i64)st->level->mb_used *
(1024 * 1024 / HASH_ENTRY_SIZE_NARROW);
/* Limit the entry budget to what the chunk can use. */
i64 cap = st->chunk_size;
int bits, base_bits;
int wide;
size_t esize;
i64 nslots, mem;
if (cap < (1 << 16))
cap = 1 << 16;
if (hashsize > cap)
hashsize = cap;
wide = (st->chunk_size > (i64)UINT32_MAX);
esize = wide ? sizeof(struct hash_entry_wide) : sizeof(struct hash_entry);
for (bits = 0; (1U << bits) < hashsize; bits++)
;
base_bits = bits;
nslots = (i64)1 << bits;
st->hash_limit = nslots / 3 * 2;