]> wimlib.net Git - wimlib/blob - src/lzx_compress.c
lzx lcpit
[wimlib] / src / lzx_compress.c
1 /*
2  * lzx_compress.c
3  *
4  * A compressor for the LZX compression format, as used in WIM files.
5  */
6
7 /*
8  * Copyright (C) 2012-2016 Eric Biggers
9  *
10  * This file is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; if not, see http://www.gnu.org/licenses/.
22  */
23
24
25 /*
26  * This file contains a compressor for the LZX ("Lempel-Ziv eXtended")
27  * compression format, as used in the WIM (Windows IMaging) file format.
28  *
29  * Two different parsing algorithms are implemented: "near-optimal" and "lazy".
30  * "Near-optimal" is significantly slower than "lazy", but results in a better
31  * compression ratio.  The "near-optimal" algorithm is used at the default
32  * compression level.
33  *
34  * This file may need some slight modifications to be used outside of the WIM
35  * format.  In particular, in other situations the LZX block header might be
36  * slightly different, and sliding window support might be required.
37  *
38  * Note: LZX is a compression format derived from DEFLATE, the format used by
39  * zlib and gzip.  Both LZX and DEFLATE use LZ77 matching and Huffman coding.
40  * Certain details are quite similar, such as the method for storing Huffman
41  * codes.  However, the main differences are:
42  *
43  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
44  *   compressible before attempting to compress it further.
45  *
46  * - LZX uses a "main" alphabet which combines literals and matches, with the
47  *   match symbols containing a "length header" (giving all or part of the match
48  *   length) and an "offset slot" (giving, roughly speaking, the order of
49  *   magnitude of the match offset).
50  *
51  * - LZX does not have static Huffman blocks (that is, the kind with preset
52  *   Huffman codes); however it does have two types of dynamic Huffman blocks
53  *   ("verbatim" and "aligned").
54  *
55  * - LZX has a minimum match length of 2 rather than 3.  Length 2 matches can be
56  *   useful, but generally only if the parser is smart about choosing them.
57  *
58  * - In LZX, offset slots 0 through 2 actually represent entries in an LRU queue
59  *   of match offsets.  This is very useful for certain types of files, such as
60  *   binary files that have repeating records.
61  */
62
63 #ifdef HAVE_CONFIG_H
64 #  include "config.h"
65 #endif
66
67 /*
68  * The compressor always chooses a block of at least MIN_BLOCK_LENGTH bytes,
69  * except if the last block has to be shorter.
70  */
71 #define MIN_BLOCK_LENGTH                6500
72
73 /*
74  * The compressor attempts to end blocks after SOFT_MAX_BLOCK_LENGTH bytes, but
75  * the final size might be larger due to matches extending beyond the end of the
76  * block.  Specifically:
77  *
78  *  - The greedy parser may choose an arbitrarily long match starting at the
79  *    SOFT_MAX_BLOCK_LENGTH'th byte.
80  *
81  *  - The lazy parser may choose a sequence of literals starting at the
82  *    SOFT_MAX_BLOCK_LENGTH'th byte when it sees a sequence of increasing good
83  *    matches.  The final match may be of arbitrary length.  The length of the
84  *    literal sequence is approximately limited by the "nice match length"
85  *    parameter.
86  */
87 #define SOFT_MAX_BLOCK_LENGTH   100000
88
89 /*
90  * The number of observed matches or literals that represents sufficient data to
91  * decide whether the current block should be terminated or not.
92  */
93 #define NUM_OBSERVATIONS_PER_BLOCK_CHECK        500
94
95 /*
96  * LZX_CACHE_LENGTH is the number of lz_match structures in the match cache,
97  * excluding the extra "overflow" entries.  This value should be high enough so
98  * that nearly the time, all matches found in a given block can fit in the match
99  * cache.  However, fallback behavior (immediately terminating the block) on
100  * cache overflow is still required.
101  */
102 #define LZX_CACHE_LENGTH        (SOFT_MAX_BLOCK_LENGTH * 5)
103
104 /*
105  * LZX_MAX_MATCHES_PER_POS is an upper bound on the number of matches that can
106  * ever be saved in the match cache for a single position.  Since each match we
107  * save for a single position has a distinct length, we can use the number of
108  * possible match lengths in LZX as this bound.  This bound is guaranteed to be
109  * valid in all cases, although if 'nice_match_length < LZX_MAX_MATCH_LEN', then
110  * it will never actually be reached.
111  */
112 #define LZX_MAX_MATCHES_PER_POS LZX_NUM_LENS
113
114 /*
115  * LZX_BIT_COST is a scaling factor that represents the cost to output one bit.
116  * This makes it possible to consider fractional bit costs.
117  *
118  * Note: this is only useful as a statistical trick for when the true costs are
119  * unknown.  In reality, each token in LZX requires a whole number of bits to
120  * output.
121  */
122 #define LZX_BIT_COST            64
123
124 /*
125  * Should the compressor take into account the costs of aligned offset symbols?
126  */
127 #define LZX_CONSIDER_ALIGNED_COSTS      1
128
129 /*
130  * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
131  * faster algorithm.
132  */
133 #define LZX_MAX_FAST_LEVEL      34
134
135 /*
136  * BT_MATCHFINDER_HASH2_ORDER is the log base 2 of the number of entries in the
137  * hash table for finding length 2 matches.  This could be as high as 16, but
138  * using a smaller hash table speeds up compression due to reduced cache
139  * pressure.
140  */
141 #define BT_MATCHFINDER_HASH2_ORDER      12
142
143 /*
144  * These are the compressor-side limits on the codeword lengths for each Huffman
145  * code.  To make outputting bits slightly faster, some of these limits are
146  * lower than the limits defined by the LZX format.  This does not significantly
147  * affect the compression ratio, at least for the block lengths we use.
148  */
149 #define MAIN_CODEWORD_LIMIT     16
150 #define LENGTH_CODEWORD_LIMIT   12
151 #define ALIGNED_CODEWORD_LIMIT  7
152 #define PRE_CODEWORD_LIMIT      7
153
154 #include "wimlib/compress_common.h"
155 #include "wimlib/compressor_ops.h"
156 #include "wimlib/error.h"
157 #include "wimlib/lz_extend.h"
158 #include "wimlib/lzx_common.h"
159 #include "wimlib/unaligned.h"
160 #include "wimlib/util.h"
161
162 /* Matchfinders with 16-bit positions  */
163 #define mf_pos_t        u16
164 #define MF_SUFFIX       _16
165 #include "wimlib/lcpit_matchfinder.h"
166 #include "wimlib/hc_matchfinder.h"
167
168 /* Matchfinders with 32-bit positions  */
169 #undef mf_pos_t
170 #undef MF_SUFFIX
171 #define mf_pos_t        u32
172 #define MF_SUFFIX       _32
173 #include "wimlib/lcpit_matchfinder.h"
174 #include "wimlib/hc_matchfinder.h"
175
176 struct lzx_output_bitstream;
177
178 /* Codewords for the LZX Huffman codes.  */
179 struct lzx_codewords {
180         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
181         u32 len[LZX_LENCODE_NUM_SYMBOLS];
182         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
183 };
184
185 /* Codeword lengths (in bits) for the LZX Huffman codes.
186  * A zero length means the corresponding codeword has zero frequency.  */
187 struct lzx_lens {
188         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS + 1];
189         u8 len[LZX_LENCODE_NUM_SYMBOLS + 1];
190         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
191 };
192
193 /* Cost model for near-optimal parsing  */
194 struct lzx_costs {
195
196         /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
197          * length 'len' match that has an offset belonging to 'offset_slot'.  */
198         u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
199
200         /* Cost for each symbol in the main code  */
201         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
202
203         /* Cost for each symbol in the length code  */
204         u32 len[LZX_LENCODE_NUM_SYMBOLS];
205
206 #if LZX_CONSIDER_ALIGNED_COSTS
207         /* Cost for each symbol in the aligned code  */
208         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
209 #endif
210 };
211
212 /* Codewords and lengths for the LZX Huffman codes.  */
213 struct lzx_codes {
214         struct lzx_codewords codewords;
215         struct lzx_lens lens;
216 };
217
218 /* Symbol frequency counters for the LZX Huffman codes.  */
219 struct lzx_freqs {
220         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
221         u32 len[LZX_LENCODE_NUM_SYMBOLS];
222         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
223 };
224
225 /* Block split statistics.  See "Block splitting algorithm" below. */
226 #define NUM_LITERAL_OBSERVATION_TYPES 8
227 #define NUM_MATCH_OBSERVATION_TYPES 2
228 #define NUM_OBSERVATION_TYPES (NUM_LITERAL_OBSERVATION_TYPES + NUM_MATCH_OBSERVATION_TYPES)
229 struct block_split_stats {
230         u32 new_observations[NUM_OBSERVATION_TYPES];
231         u32 observations[NUM_OBSERVATION_TYPES];
232         u32 num_new_observations;
233         u32 num_observations;
234 };
235
236 /*
237  * Represents a run of literals followed by a match or end-of-block.  This
238  * struct is needed to temporarily store items chosen by the parser, since items
239  * cannot be written until all items for the block have been chosen and the
240  * block's Huffman codes have been computed.
241  */
242 struct lzx_sequence {
243
244         /* The number of literals in the run.  This may be 0.  The literals are
245          * not stored explicitly in this structure; instead, they are read
246          * directly from the uncompressed data.  */
247         u16 litrunlen;
248
249         /* If the next field doesn't indicate end-of-block, then this is the
250          * match length minus LZX_MIN_MATCH_LEN.  */
251         u16 adjusted_length;
252
253         /* If bit 31 is clear, then this field contains the match header in bits
254          * 0-8, and either the match offset plus LZX_OFFSET_ADJUSTMENT or a
255          * recent offset code in bits 9-30.  Otherwise (if bit 31 is set), this
256          * sequence's literal run was the last literal run in the block, so
257          * there is no match that follows it.  */
258         u32 adjusted_offset_and_match_hdr;
259 };
260
261 /*
262  * This structure represents a byte position in the input buffer and a node in
263  * the graph of possible match/literal choices.
264  *
265  * Logically, each incoming edge to this node is labeled with a literal or a
266  * match that can be taken to reach this position from an earlier position; and
267  * each outgoing edge from this node is labeled with a literal or a match that
268  * can be taken to advance from this position to a later position.
269  */
270 struct lzx_optimum_node {
271
272         /* The cost, in bits, of the lowest-cost path that has been found to
273          * reach this position.  This can change as progressively lower cost
274          * paths are found to reach this position.  */
275         u32 cost;
276
277         /*
278          * The match or literal that was taken to reach this position.  This can
279          * change as progressively lower cost paths are found to reach this
280          * position.
281          *
282          * This variable is divided into two bitfields.
283          *
284          * Literals:
285          *      Low bits are 0, high bits are the literal.
286          *
287          * Explicit offset matches:
288          *      Low bits are the match length, high bits are the offset plus 2.
289          *
290          * Repeat offset matches:
291          *      Low bits are the match length, high bits are the queue index.
292          */
293         u32 item;
294 #define OPTIMUM_OFFSET_SHIFT 9
295 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
296 #define OPTIMUM_EXTRA_FLAG 0x80000000
297         u32 extra_match;
298         u32 extra_literal;
299 } _aligned_attribute(8);
300
301 /*
302  * Least-recently-used queue for match offsets.
303  *
304  * This is represented as a 64-bit integer for efficiency.  There are three
305  * offsets of 21 bits each.  Bit 64 is garbage.
306  */
307 struct lzx_lru_queue {
308         u64 R;
309 };
310
311 #define LZX_QUEUE64_OFFSET_SHIFT 21
312 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
313
314 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
315 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
316 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
317
318 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
319 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
320 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
321
322 static inline void
323 lzx_lru_queue_init(struct lzx_lru_queue *queue)
324 {
325         queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
326                    ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
327                    ((u64)1 << LZX_QUEUE64_R2_SHIFT);
328 }
329
330 static inline u64
331 lzx_lru_queue_R0(struct lzx_lru_queue queue)
332 {
333         return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
334 }
335
336 static inline u64
337 lzx_lru_queue_R1(struct lzx_lru_queue queue)
338 {
339         return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
340 }
341
342 static inline u64
343 lzx_lru_queue_R2(struct lzx_lru_queue queue)
344 {
345         return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
346 }
347
348 /* Push a match offset onto the front (most recently used) end of the queue.  */
349 static inline struct lzx_lru_queue
350 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
351 {
352         return (struct lzx_lru_queue) {
353                 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
354         };
355 }
356
357 /* Swap a match offset to the front of the queue.  */
358 static inline struct lzx_lru_queue
359 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
360 {
361         if (idx == 0)
362                 return queue;
363
364         if (idx == 1)
365                 return (struct lzx_lru_queue) {
366                         .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
367                              (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
368                              (queue.R & LZX_QUEUE64_R2_MASK),
369                 };
370
371         return (struct lzx_lru_queue) {
372                 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
373                      (queue.R & LZX_QUEUE64_R1_MASK) |
374                      (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
375         };
376 }
377
378 /* The main LZX compressor structure  */
379 struct lzx_compressor {
380
381         /* The "nice" match length: if a match of this length is found, then
382          * choose it immediately without further consideration.  */
383         unsigned nice_match_length;
384
385         /* The maximum search depth: consider at most this many potential
386          * matches at each position.  */
387         unsigned max_search_depth;
388
389         /* The log base 2 of the LZX window size for LZ match offset encoding
390          * purposes.  This will be >= LZX_MIN_WINDOW_ORDER and <=
391          * LZX_MAX_WINDOW_ORDER.  */
392         unsigned window_order;
393
394         /* The number of symbols in the main alphabet.  This depends on
395          * @window_order, since @window_order determines the maximum possible
396          * offset.  */
397         unsigned num_main_syms;
398
399         /* Number of optimization passes per block  */
400         unsigned num_optim_passes;
401
402         /* The preprocessed buffer of data being compressed  */
403         u8 *in_buffer;
404
405         /* The number of bytes of data to be compressed, which is the number of
406          * bytes of data in @in_buffer that are actually valid.  */
407         size_t in_nbytes;
408
409         /* Pointer to the compress() implementation chosen at allocation time */
410         void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
411
412         /* If true, the compressor need not preserve the input buffer if it
413          * compresses the data successfully.  */
414         bool destructive;
415
416         /* The Huffman symbol frequency counters for the current block.  */
417         struct lzx_freqs freqs;
418
419         /* Block split statistics.  */
420         struct block_split_stats split_stats;
421
422         /* The Huffman codes for the current and previous blocks.  The one with
423          * index 'codes_index' is for the current block, and the other one is
424          * for the previous block.  */
425         struct lzx_codes codes[2];
426         unsigned codes_index;
427
428         /* The matches and literals that the parser has chosen for the current
429          * block.  The required length of this array is limited by the maximum
430          * number of matches that can ever be chosen for a single block, plus
431          * one for the special entry at the end.  */
432         struct lzx_sequence chosen_sequences[
433                        DIV_ROUND_UP(SOFT_MAX_BLOCK_LENGTH, LZX_MIN_MATCH_LEN) + 1];
434
435         /* Tables for mapping adjusted offsets to offset slots  */
436
437         /* offset slots [0, 29]  */
438         u8 offset_slot_tab_1[32768];
439
440         /* offset slots [30, 49]  */
441         u8 offset_slot_tab_2[128];
442
443         union {
444                 /* Data for greedy or lazy parsing  */
445                 struct {
446                         /* Hash chains matchfinder (MUST BE LAST!!!)  */
447                         union {
448                                 struct hc_matchfinder_16 hc_mf_16;
449                                 struct hc_matchfinder_32 hc_mf_32;
450                         };
451                 };
452
453                 /* Data for near-optimal parsing  */
454                 struct {
455                         /*
456                          * Array of nodes, one per position, for running the
457                          * minimum-cost path algorithm.
458                          *
459                          * This array must be large enough to accommodate the
460                          * worst-case number of nodes, which occurs if we find a
461                          * match of length LZX_MAX_MATCH_LEN at position
462                          * SOFT_MAX_BLOCK_LENGTH - 1, producing a block of length
463                          * SOFT_MAX_BLOCK_LENGTH - 1 + LZX_MAX_MATCH_LEN.  Add one
464                          * for the end-of-block node.
465                          */
466                         struct lzx_optimum_node optimum_nodes[SOFT_MAX_BLOCK_LENGTH - 1 +
467                                                               LZX_MAX_MATCH_LEN + 1];
468
469                         /* The cost model for the current block  */
470                         struct lzx_costs costs;
471
472                         /*
473                          * Cached matches for the current block.  This array
474                          * contains the matches that were found at each position
475                          * in the block.  Specifically, for each position, there
476                          * is a special 'struct lz_match' whose 'length' field
477                          * contains the number of matches that were found at
478                          * that position; this is followed by the matches
479                          * themselves, if any, sorted by strictly increasing
480                          * length.
481                          *
482                          * Note: in rare cases, there will be a very high number
483                          * of matches in the block and this array will overflow.
484                          * If this happens, we force the end of the current
485                          * block.  LZX_CACHE_LENGTH is the length at which we
486                          * actually check for overflow.  The extra slots beyond
487                          * this are enough to absorb the worst case overflow,
488                          * which occurs if starting at
489                          * &match_cache[LZX_CACHE_LENGTH - 1], we write the
490                          * match count header, then write
491                          * LZX_MAX_MATCHES_PER_POS matches, then skip searching
492                          * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
493                          * write the match count header for each.
494                          */
495                         struct lz_match match_cache[LZX_CACHE_LENGTH +
496                                                     LZX_MAX_MATCHES_PER_POS +
497                                                     LZX_MAX_MATCH_LEN - 1];
498
499                         struct lcpit_matchfinder lcpit_mf;
500                 };
501         };
502 };
503
504 /*
505  * Will a matchfinder using 16-bit positions be sufficient for compressing
506  * buffers of up to the specified size?  The limit could be 65536 bytes, but we
507  * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
508  * This requires that the limit be no more than the length of offset_slot_tab_1
509  * (currently 32768).
510  */
511 static inline bool
512 lzx_is_16_bit(size_t max_bufsize)
513 {
514         STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
515         return max_bufsize <= 32768;
516 }
517
518 /*
519  * The following macros call either the 16-bit or the 32-bit version of a
520  * matchfinder function based on the value of 'is_16_bit', which will be known
521  * at compilation time.
522  */
523
524 #define CALL_HC_MF(is_16_bit, c, funcname, ...)                               \
525         ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
526                        CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
527
528 /*
529  * Structure to keep track of the current state of sending bits to the
530  * compressed output buffer.
531  *
532  * The LZX bitstream is encoded as a sequence of 16-bit coding units.
533  */
534 struct lzx_output_bitstream {
535
536         /* Bits that haven't yet been written to the output buffer.  */
537         machine_word_t bitbuf;
538
539         /* Number of bits currently held in @bitbuf.  */
540         u32 bitcount;
541
542         /* Pointer to the start of the output buffer.  */
543         u8 *start;
544
545         /* Pointer to the position in the output buffer at which the next coding
546          * unit should be written.  */
547         u8 *next;
548
549         /* Pointer just past the end of the output buffer, rounded down to a
550          * 2-byte boundary.  */
551         u8 *end;
552 };
553
554 /* Can the specified number of bits always be added to 'bitbuf' after any
555  * pending 16-bit coding units have been flushed?  */
556 #define CAN_BUFFER(n)   ((n) <= (8 * sizeof(machine_word_t)) - 15)
557
558 /*
559  * Initialize the output bitstream.
560  *
561  * @os
562  *      The output bitstream structure to initialize.
563  * @buffer
564  *      The buffer being written to.
565  * @size
566  *      Size of @buffer, in bytes.
567  */
568 static void
569 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
570 {
571         os->bitbuf = 0;
572         os->bitcount = 0;
573         os->start = buffer;
574         os->next = os->start;
575         os->end = os->start + (size & ~1);
576 }
577
578 /* Add some bits to the bitbuffer variable of the output bitstream.  The caller
579  * must make sure there is enough room.  */
580 static inline void
581 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
582 {
583         os->bitbuf = (os->bitbuf << num_bits) | bits;
584         os->bitcount += num_bits;
585 }
586
587 /* Flush bits from the bitbuffer variable to the output buffer.  'max_num_bits'
588  * specifies the maximum number of bits that may have been added since the last
589  * flush.  */
590 static inline void
591 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
592 {
593         /* Masking the number of bits to shift is only needed to avoid undefined
594          * behavior; we don't actually care about the results of bad shifts.  On
595          * x86, the explicit masking generates no extra code.  */
596         const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
597
598         if (os->end - os->next < 6)
599                 return;
600         put_unaligned_le16(os->bitbuf >> ((os->bitcount - 16) &
601                                             shift_mask), os->next + 0);
602         if (max_num_bits > 16)
603                 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 32) &
604                                                 shift_mask), os->next + 2);
605         if (max_num_bits > 32)
606                 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 48) &
607                                                 shift_mask), os->next + 4);
608         os->next += (os->bitcount >> 4) << 1;
609         os->bitcount &= 15;
610 }
611
612 /* Add at most 16 bits to the bitbuffer and flush it.  */
613 static inline void
614 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
615 {
616         lzx_add_bits(os, bits, num_bits);
617         lzx_flush_bits(os, 16);
618 }
619
620 /*
621  * Flush the last coding unit to the output buffer if needed.  Return the total
622  * number of bytes written to the output buffer, or 0 if an overflow occurred.
623  */
624 static u32
625 lzx_flush_output(struct lzx_output_bitstream *os)
626 {
627         if (os->end - os->next < 6)
628                 return 0;
629
630         if (os->bitcount != 0) {
631                 put_unaligned_le16(os->bitbuf << (16 - os->bitcount), os->next);
632                 os->next += 2;
633         }
634
635         return os->next - os->start;
636 }
637
638 /*
639  * Build the main, length, and aligned offset Huffman codes used in LZX.
640  *
641  * This takes as input the frequency tables for each code and produces as output
642  * a set of tables that map symbols to codewords and codeword lengths.
643  */
644 static void
645 lzx_make_huffman_codes(struct lzx_compressor *c)
646 {
647         const struct lzx_freqs *freqs = &c->freqs;
648         struct lzx_codes *codes = &c->codes[c->codes_index];
649
650         STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
651                       MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
652         STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
653                       LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
654         STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
655                       ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
656
657         make_canonical_huffman_code(c->num_main_syms,
658                                     MAIN_CODEWORD_LIMIT,
659                                     freqs->main,
660                                     codes->lens.main,
661                                     codes->codewords.main);
662
663         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
664                                     LENGTH_CODEWORD_LIMIT,
665                                     freqs->len,
666                                     codes->lens.len,
667                                     codes->codewords.len);
668
669         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
670                                     ALIGNED_CODEWORD_LIMIT,
671                                     freqs->aligned,
672                                     codes->lens.aligned,
673                                     codes->codewords.aligned);
674 }
675
676 /* Reset the symbol frequencies for the LZX Huffman codes.  */
677 static void
678 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
679 {
680         memset(&c->freqs, 0, sizeof(c->freqs));
681 }
682
683 static unsigned
684 lzx_compute_precode_items(const u8 lens[restrict],
685                           const u8 prev_lens[restrict],
686                           u32 precode_freqs[restrict],
687                           unsigned precode_items[restrict])
688 {
689         unsigned *itemptr;
690         unsigned run_start;
691         unsigned run_end;
692         unsigned extra_bits;
693         int delta;
694         u8 len;
695
696         itemptr = precode_items;
697         run_start = 0;
698
699         while (!((len = lens[run_start]) & 0x80)) {
700
701                 /* len = the length being repeated  */
702
703                 /* Find the next run of codeword lengths.  */
704
705                 run_end = run_start + 1;
706
707                 /* Fast case for a single length.  */
708                 if (likely(len != lens[run_end])) {
709                         delta = prev_lens[run_start] - len;
710                         if (delta < 0)
711                                 delta += 17;
712                         precode_freqs[delta]++;
713                         *itemptr++ = delta;
714                         run_start++;
715                         continue;
716                 }
717
718                 /* Extend the run.  */
719                 do {
720                         run_end++;
721                 } while (len == lens[run_end]);
722
723                 if (len == 0) {
724                         /* Run of zeroes.  */
725
726                         /* Symbol 18: RLE 20 to 51 zeroes at a time.  */
727                         while ((run_end - run_start) >= 20) {
728                                 extra_bits = min((run_end - run_start) - 20, 0x1f);
729                                 precode_freqs[18]++;
730                                 *itemptr++ = 18 | (extra_bits << 5);
731                                 run_start += 20 + extra_bits;
732                         }
733
734                         /* Symbol 17: RLE 4 to 19 zeroes at a time.  */
735                         if ((run_end - run_start) >= 4) {
736                                 extra_bits = min((run_end - run_start) - 4, 0xf);
737                                 precode_freqs[17]++;
738                                 *itemptr++ = 17 | (extra_bits << 5);
739                                 run_start += 4 + extra_bits;
740                         }
741                 } else {
742
743                         /* A run of nonzero lengths. */
744
745                         /* Symbol 19: RLE 4 to 5 of any length at a time.  */
746                         while ((run_end - run_start) >= 4) {
747                                 extra_bits = (run_end - run_start) > 4;
748                                 delta = prev_lens[run_start] - len;
749                                 if (delta < 0)
750                                         delta += 17;
751                                 precode_freqs[19]++;
752                                 precode_freqs[delta]++;
753                                 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
754                                 run_start += 4 + extra_bits;
755                         }
756                 }
757
758                 /* Output any remaining lengths without RLE.  */
759                 while (run_start != run_end) {
760                         delta = prev_lens[run_start] - len;
761                         if (delta < 0)
762                                 delta += 17;
763                         precode_freqs[delta]++;
764                         *itemptr++ = delta;
765                         run_start++;
766                 }
767         }
768
769         return itemptr - precode_items;
770 }
771
772 /*
773  * Output a Huffman code in the compressed form used in LZX.
774  *
775  * The Huffman code is represented in the output as a logical series of codeword
776  * lengths from which the Huffman code, which must be in canonical form, can be
777  * reconstructed.
778  *
779  * The codeword lengths are themselves compressed using a separate Huffman code,
780  * the "precode", which contains a symbol for each possible codeword length in
781  * the larger code as well as several special symbols to represent repeated
782  * codeword lengths (a form of run-length encoding).  The precode is itself
783  * constructed in canonical form, and its codeword lengths are represented
784  * literally in 20 4-bit fields that immediately precede the compressed codeword
785  * lengths of the larger code.
786  *
787  * Furthermore, the codeword lengths of the larger code are actually represented
788  * as deltas from the codeword lengths of the corresponding code in the previous
789  * block.
790  *
791  * @os:
792  *      Bitstream to which to write the compressed Huffman code.
793  * @lens:
794  *      The codeword lengths, indexed by symbol, in the Huffman code.
795  * @prev_lens:
796  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
797  *      code in the previous block, or all zeroes if this is the first block.
798  * @num_lens:
799  *      The number of symbols in the Huffman code.
800  */
801 static void
802 lzx_write_compressed_code(struct lzx_output_bitstream *os,
803                           const u8 lens[restrict],
804                           const u8 prev_lens[restrict],
805                           unsigned num_lens)
806 {
807         u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
808         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
809         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
810         unsigned precode_items[num_lens];
811         unsigned num_precode_items;
812         unsigned precode_item;
813         unsigned precode_sym;
814         unsigned i;
815         u8 saved = lens[num_lens];
816         *(u8 *)(lens + num_lens) = 0x80;
817
818         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
819                 precode_freqs[i] = 0;
820
821         /* Compute the "items" (RLE / literal tokens and extra bits) with which
822          * the codeword lengths in the larger code will be output.  */
823         num_precode_items = lzx_compute_precode_items(lens,
824                                                       prev_lens,
825                                                       precode_freqs,
826                                                       precode_items);
827
828         /* Build the precode.  */
829         STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
830                       PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
831         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
832                                     PRE_CODEWORD_LIMIT,
833                                     precode_freqs, precode_lens,
834                                     precode_codewords);
835
836         /* Output the lengths of the codewords in the precode.  */
837         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
838                 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
839
840         /* Output the encoded lengths of the codewords in the larger code.  */
841         for (i = 0; i < num_precode_items; i++) {
842                 precode_item = precode_items[i];
843                 precode_sym = precode_item & 0x1F;
844                 lzx_add_bits(os, precode_codewords[precode_sym],
845                              precode_lens[precode_sym]);
846                 if (precode_sym >= 17) {
847                         if (precode_sym == 17) {
848                                 lzx_add_bits(os, precode_item >> 5, 4);
849                         } else if (precode_sym == 18) {
850                                 lzx_add_bits(os, precode_item >> 5, 5);
851                         } else {
852                                 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
853                                 precode_sym = precode_item >> 6;
854                                 lzx_add_bits(os, precode_codewords[precode_sym],
855                                              precode_lens[precode_sym]);
856                         }
857                 }
858                 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
859                 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
860         }
861
862         *(u8 *)(lens + num_lens) = saved;
863 }
864
865 /*
866  * Write all matches and literal bytes (which were precomputed) in an LZX
867  * compressed block to the output bitstream in the final compressed
868  * representation.
869  *
870  * @os
871  *      The output bitstream.
872  * @block_type
873  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
874  *      LZX_BLOCKTYPE_VERBATIM).
875  * @block_data
876  *      The uncompressed data of the block.
877  * @sequences
878  *      The matches and literals to output, given as a series of sequences.
879  * @codes
880  *      The main, length, and aligned offset Huffman codes for the current
881  *      LZX compressed block.
882  */
883 static void
884 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
885                     const u8 *block_data, const struct lzx_sequence sequences[],
886                     const struct lzx_codes *codes)
887 {
888         const struct lzx_sequence *seq = sequences;
889         u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
890
891         for (;;) {
892                 /* Output the next sequence.  */
893
894                 unsigned litrunlen = seq->litrunlen;
895                 unsigned match_hdr;
896                 unsigned main_symbol;
897                 unsigned adjusted_length;
898                 u32 adjusted_offset;
899                 unsigned offset_slot;
900                 unsigned num_extra_bits;
901                 u32 extra_bits;
902
903                 /* Output the literal run of the sequence.  */
904
905                 if (litrunlen) {  /* Is the literal run nonempty?  */
906
907                         /* Verify optimization is enabled on 64-bit  */
908                         STATIC_ASSERT(sizeof(machine_word_t) < 8 ||
909                                       CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT));
910
911                         if (CAN_BUFFER(3 * MAIN_CODEWORD_LIMIT)) {
912
913                                 /* 64-bit: write 3 literals at a time.  */
914                                 while (litrunlen >= 3) {
915                                         unsigned lit0 = block_data[0];
916                                         unsigned lit1 = block_data[1];
917                                         unsigned lit2 = block_data[2];
918                                         lzx_add_bits(os, codes->codewords.main[lit0],
919                                                      codes->lens.main[lit0]);
920                                         lzx_add_bits(os, codes->codewords.main[lit1],
921                                                      codes->lens.main[lit1]);
922                                         lzx_add_bits(os, codes->codewords.main[lit2],
923                                                      codes->lens.main[lit2]);
924                                         lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
925                                         block_data += 3;
926                                         litrunlen -= 3;
927                                 }
928                                 if (litrunlen--) {
929                                         unsigned lit = *block_data++;
930                                         lzx_add_bits(os, codes->codewords.main[lit],
931                                                      codes->lens.main[lit]);
932                                         if (litrunlen--) {
933                                                 unsigned lit = *block_data++;
934                                                 lzx_add_bits(os, codes->codewords.main[lit],
935                                                              codes->lens.main[lit]);
936                                                 lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
937                                         } else {
938                                                 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
939                                         }
940                                 }
941                         } else {
942                                 /* 32-bit: write 1 literal at a time.  */
943                                 do {
944                                         unsigned lit = *block_data++;
945                                         lzx_add_bits(os, codes->codewords.main[lit],
946                                                      codes->lens.main[lit]);
947                                         lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
948                                 } while (--litrunlen);
949                         }
950                 }
951
952                 /* Was this the last literal run?  */
953                 if (seq->adjusted_offset_and_match_hdr & 0x80000000)
954                         return;
955
956                 /* Nope; output the match.  */
957
958                 match_hdr = seq->adjusted_offset_and_match_hdr & 0x1FF;
959                 main_symbol = LZX_NUM_CHARS + match_hdr;
960                 adjusted_length = seq->adjusted_length;
961
962                 block_data += adjusted_length + LZX_MIN_MATCH_LEN;
963
964                 offset_slot = match_hdr / LZX_NUM_LEN_HEADERS;
965                 adjusted_offset = seq->adjusted_offset_and_match_hdr >> 9;
966
967                 num_extra_bits = lzx_extra_offset_bits[offset_slot];
968                 extra_bits = adjusted_offset - lzx_offset_slot_base[offset_slot];
969
970         #define MAX_MATCH_BITS  (MAIN_CODEWORD_LIMIT + LENGTH_CODEWORD_LIMIT + \
971                                  14 + ALIGNED_CODEWORD_LIMIT)
972
973                 /* Verify optimization is enabled on 64-bit  */
974                 STATIC_ASSERT(sizeof(machine_word_t) < 8 || CAN_BUFFER(MAX_MATCH_BITS));
975
976                 /* Output the main symbol for the match.  */
977
978                 lzx_add_bits(os, codes->codewords.main[main_symbol],
979                              codes->lens.main[main_symbol]);
980                 if (!CAN_BUFFER(MAX_MATCH_BITS))
981                         lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
982
983                 /* If needed, output the length symbol for the match.  */
984
985                 if (adjusted_length >= LZX_NUM_PRIMARY_LENS) {
986                         lzx_add_bits(os, codes->codewords.len[adjusted_length -
987                                                               LZX_NUM_PRIMARY_LENS],
988                                      codes->lens.len[adjusted_length -
989                                                      LZX_NUM_PRIMARY_LENS]);
990                         if (!CAN_BUFFER(MAX_MATCH_BITS))
991                                 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
992                 }
993
994                 /* Output the extra offset bits for the match.  In aligned
995                  * offset blocks, the lowest 3 bits of the adjusted offset are
996                  * Huffman-encoded using the aligned offset code, provided that
997                  * there are at least extra 3 offset bits required.  All other
998                  * extra offset bits are output verbatim.  */
999
1000                 if ((adjusted_offset & ones_if_aligned) >= 16) {
1001
1002                         lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
1003                                      num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
1004                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1005                                 lzx_flush_bits(os, 14);
1006
1007                         lzx_add_bits(os, codes->codewords.aligned[adjusted_offset &
1008                                                                   LZX_ALIGNED_OFFSET_BITMASK],
1009                                      codes->lens.aligned[adjusted_offset &
1010                                                          LZX_ALIGNED_OFFSET_BITMASK]);
1011                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1012                                 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1013                 } else {
1014                         STATIC_ASSERT(CAN_BUFFER(17));
1015
1016                         lzx_add_bits(os, extra_bits, num_extra_bits);
1017                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1018                                 lzx_flush_bits(os, 17);
1019                 }
1020
1021                 if (CAN_BUFFER(MAX_MATCH_BITS))
1022                         lzx_flush_bits(os, MAX_MATCH_BITS);
1023
1024                 /* Advance to the next sequence.  */
1025                 seq++;
1026         }
1027 }
1028
1029 static void
1030 lzx_write_compressed_block(const u8 *block_begin,
1031                            int block_type,
1032                            u32 block_length,
1033                            unsigned window_order,
1034                            unsigned num_main_syms,
1035                            const struct lzx_sequence sequences[],
1036                            const struct lzx_codes * codes,
1037                            const struct lzx_lens * prev_lens,
1038                            struct lzx_output_bitstream * os)
1039 {
1040         /* The first three bits indicate the type of block and are one of the
1041          * LZX_BLOCKTYPE_* constants.  */
1042         lzx_write_bits(os, block_type, 3);
1043
1044         /*
1045          * Output the block length.
1046          *
1047          * The original LZX format seemed to always encode the block length in 3
1048          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
1049          * uses the first bit to indicate whether the block is the default
1050          * length (32768) or a different length given explicitly by the next 16
1051          * bits.
1052          *
1053          * By default, this compressor uses a window size of 32768 and therefore
1054          * follows the WIMGAPI behavior.  However, this compressor also supports
1055          * window sizes greater than 32768 bytes, which do not appear to be
1056          * supported by WIMGAPI.  In such cases, we retain the default size bit
1057          * to mean a size of 32768 bytes but output non-default block length in
1058          * 24 bits rather than 16.  The compatibility of this behavior is
1059          * unknown because WIMs created with chunk size greater than 32768 can
1060          * seemingly only be opened by wimlib anyway.
1061          */
1062         if (block_length == LZX_DEFAULT_BLOCK_SIZE) {
1063                 lzx_write_bits(os, 1, 1);
1064         } else {
1065                 lzx_write_bits(os, 0, 1);
1066
1067                 if (window_order >= 16)
1068                         lzx_write_bits(os, block_length >> 16, 8);
1069
1070                 lzx_write_bits(os, block_length & 0xFFFF, 16);
1071         }
1072
1073         /* If it's an aligned offset block, output the aligned offset code.  */
1074         if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1075                 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1076                         lzx_write_bits(os, codes->lens.aligned[i],
1077                                        LZX_ALIGNEDCODE_ELEMENT_SIZE);
1078                 }
1079         }
1080
1081         /* Output the main code (two parts).  */
1082         lzx_write_compressed_code(os, codes->lens.main,
1083                                   prev_lens->main,
1084                                   LZX_NUM_CHARS);
1085         lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1086                                   prev_lens->main + LZX_NUM_CHARS,
1087                                   num_main_syms - LZX_NUM_CHARS);
1088
1089         /* Output the length code.  */
1090         lzx_write_compressed_code(os, codes->lens.len,
1091                                   prev_lens->len,
1092                                   LZX_LENCODE_NUM_SYMBOLS);
1093
1094         /* Output the compressed matches and literals.  */
1095         lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1096 }
1097
1098 /* Given the frequencies of symbols in an LZX-compressed block and the
1099  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1100  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1101  * will take fewer bits to output.  */
1102 static int
1103 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1104                                const struct lzx_codes * codes)
1105 {
1106         u32 aligned_cost = 0;
1107         u32 verbatim_cost = 0;
1108
1109         /* A verbatim block requires 3 bits in each place that an aligned symbol
1110          * would be used in an aligned offset block.  */
1111         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1112                 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1113                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1114         }
1115
1116         /* Account for output of the aligned offset code.  */
1117         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1118
1119         if (aligned_cost < verbatim_cost)
1120                 return LZX_BLOCKTYPE_ALIGNED;
1121         else
1122                 return LZX_BLOCKTYPE_VERBATIM;
1123 }
1124
1125 /*
1126  * Return the offset slot for the specified adjusted match offset, using the
1127  * compressor's acceleration tables to speed up the mapping.
1128  */
1129 static inline unsigned
1130 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1131                          bool is_16_bit)
1132 {
1133         if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1134                 return c->offset_slot_tab_1[adjusted_offset];
1135         return c->offset_slot_tab_2[adjusted_offset >> 14];
1136 }
1137
1138 /*
1139  * Flush an LZX block:
1140  *
1141  * 1. Build the Huffman codes.
1142  * 2. Decide whether to output the block as VERBATIM or ALIGNED.
1143  * 3. Write the block.
1144  * 4. Swap the indices of the current and previous Huffman codes.
1145  */
1146 static void
1147 lzx_flush_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1148                 const u8 *block_begin, u32 block_length, u32 seq_idx)
1149 {
1150         int block_type;
1151
1152         lzx_make_huffman_codes(c);
1153
1154         block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1155                                                     &c->codes[c->codes_index]);
1156         lzx_write_compressed_block(block_begin,
1157                                    block_type,
1158                                    block_length,
1159                                    c->window_order,
1160                                    c->num_main_syms,
1161                                    &c->chosen_sequences[seq_idx],
1162                                    &c->codes[c->codes_index],
1163                                    &c->codes[c->codes_index ^ 1].lens,
1164                                    os);
1165         c->codes_index ^= 1;
1166 }
1167
1168 /* Tally the Huffman symbol for a literal and increment the literal run length.
1169  */
1170 static inline void
1171 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1172 {
1173         c->freqs.main[literal]++;
1174         ++*litrunlen_p;
1175 }
1176
1177 /* Tally the Huffman symbol for a match, save the match data and the length of
1178  * the preceding literal run in the next lzx_sequence, and update the recent
1179  * offsets queue.  */
1180 static inline void
1181 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1182                  u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1183                  u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1184 {
1185         u32 litrunlen = *litrunlen_p;
1186         struct lzx_sequence *next_seq = *next_seq_p;
1187         unsigned offset_slot;
1188         unsigned v;
1189
1190         v = length - LZX_MIN_MATCH_LEN;
1191
1192         /* Save the literal run length and adjusted length.  */
1193         next_seq->litrunlen = litrunlen;
1194         next_seq->adjusted_length = v;
1195
1196         /* Compute the length header and tally the length symbol if needed  */
1197         if (v >= LZX_NUM_PRIMARY_LENS) {
1198                 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1199                 v = LZX_NUM_PRIMARY_LENS;
1200         }
1201
1202         /* Compute the offset slot  */
1203         offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1204
1205         /* Compute the match header.  */
1206         v += offset_slot * LZX_NUM_LEN_HEADERS;
1207
1208         /* Save the adjusted offset and match header.  */
1209         next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1210
1211         /* Tally the main symbol.  */
1212         c->freqs.main[LZX_NUM_CHARS + v]++;
1213
1214         /* Update the recent offsets queue.  */
1215         if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1216                 /* Repeat offset match  */
1217                 swap(recent_offsets[0], recent_offsets[offset_data]);
1218         } else {
1219                 /* Explicit offset match  */
1220
1221                 /* Tally the aligned offset symbol if needed  */
1222                 if (offset_data >= 16)
1223                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1224
1225                 recent_offsets[2] = recent_offsets[1];
1226                 recent_offsets[1] = recent_offsets[0];
1227                 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1228         }
1229
1230         /* Reset the literal run length and advance to the next sequence.  */
1231         *next_seq_p = next_seq + 1;
1232         *litrunlen_p = 0;
1233 }
1234
1235 /* Finish the last lzx_sequence.  The last lzx_sequence is just a literal run;
1236  * there is no match.  This literal run may be empty.  */
1237 static inline void
1238 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1239 {
1240         last_seq->litrunlen = litrunlen;
1241
1242         /* Special value to mark last sequence  */
1243         last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1244 }
1245
1246 /******************************************************************************/
1247
1248 /*
1249  * Block splitting algorithm.  The problem is to decide when it is worthwhile to
1250  * start a new block with new entropy codes.  There is a theoretically optimal
1251  * solution: recursively consider every possible block split, considering the
1252  * exact cost of each block, and choose the minimum cost approach.  But this is
1253  * far too slow.  Instead, as an approximation, we can count symbols and after
1254  * every N symbols, compare the expected distribution of symbols based on the
1255  * previous data with the actual distribution.  If they differ "by enough", then
1256  * start a new block.
1257  *
1258  * As an optimization and heuristic, we don't distinguish between every symbol
1259  * but rather we combine many symbols into a single "observation type".  For
1260  * literals we only look at the high bits and low bits, and for matches we only
1261  * look at whether the match is long or not.  The assumption is that for typical
1262  * "real" data, places that are good block boundaries will tend to be noticable
1263  * based only on changes in these aggregate frequencies, without looking for
1264  * subtle differences in individual symbols.  For example, a change from ASCII
1265  * bytes to non-ASCII bytes, or from few matches (generally less compressible)
1266  * to many matches (generally more compressible), would be easily noticed based
1267  * on the aggregates.
1268  *
1269  * For determining whether the frequency distributions are "different enough" to
1270  * start a new block, the simply heuristic of splitting when the sum of absolute
1271  * differences exceeds a constant seems to be good enough.  We also add a number
1272  * proportional to the block length so that the algorithm is more likely to end
1273  * long blocks than short blocks.  This reflects the general expectation that it
1274  * will become increasingly beneficial to start a new block as the current
1275  * blocks grows larger.
1276  *
1277  * Finally, for an approximation, it is not strictly necessary that the exact
1278  * symbols being used are considered.  With "near-optimal parsing", for example,
1279  * the actual symbols that will be used are unknown until after the block
1280  * boundary is chosen and the block has been optimized.  Since the final choices
1281  * cannot be used, we can use preliminary "greedy" choices instead.
1282  */
1283
1284 /* Initialize the block split statistics when starting a new block. */
1285 static void
1286 init_block_split_stats(struct block_split_stats *stats)
1287 {
1288         for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1289                 stats->new_observations[i] = 0;
1290                 stats->observations[i] = 0;
1291         }
1292         stats->num_new_observations = 0;
1293         stats->num_observations = 0;
1294 }
1295
1296 /* Literal observation.  Heuristic: use the top 2 bits and low 1 bits of the
1297  * literal, for 8 possible literal observation types.  */
1298 static inline void
1299 observe_literal(struct block_split_stats *stats, u8 lit)
1300 {
1301         stats->new_observations[((lit >> 5) & 0x6) | (lit & 1)]++;
1302         stats->num_new_observations++;
1303 }
1304
1305 /* Match observation.  Heuristic: use one observation type for "short match" and
1306  * one observation type for "long match".  */
1307 static inline void
1308 observe_match(struct block_split_stats *stats, unsigned length)
1309 {
1310         stats->new_observations[NUM_LITERAL_OBSERVATION_TYPES + (length >= 5)]++;
1311         stats->num_new_observations++;
1312 }
1313
1314 static bool
1315 do_end_block_check(struct block_split_stats *stats, u32 block_length)
1316 {
1317         if (stats->num_observations > 0) {
1318
1319                 /* Note: to avoid slow divisions, we do not divide by
1320                  * 'num_observations', but rather do all math with the numbers
1321                  * multiplied by 'num_observations'.  */
1322                 u32 total_delta = 0;
1323                 for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1324                         u32 expected = stats->observations[i] * stats->num_new_observations;
1325                         u32 actual = stats->new_observations[i] * stats->num_observations;
1326                         u32 delta = (actual > expected) ? actual - expected :
1327                                                           expected - actual;
1328                         total_delta += delta;
1329                 }
1330
1331                 /* Ready to end the block? */
1332                 if (total_delta + (block_length / 1024) * stats->num_observations >=
1333                     stats->num_new_observations * 51 / 64 * stats->num_observations)
1334                         return true;
1335         }
1336
1337         for (int i = 0; i < NUM_OBSERVATION_TYPES; i++) {
1338                 stats->num_observations += stats->new_observations[i];
1339                 stats->observations[i] += stats->new_observations[i];
1340                 stats->new_observations[i] = 0;
1341         }
1342         stats->num_new_observations = 0;
1343         return false;
1344 }
1345
1346 static inline bool
1347 should_end_block(struct block_split_stats *stats,
1348                  const u8 *in_block_begin, const u8 *in_next, const u8 *in_end)
1349 {
1350         /* Ready to check block split statistics? */
1351         if (stats->num_new_observations < NUM_OBSERVATIONS_PER_BLOCK_CHECK ||
1352             in_next - in_block_begin < MIN_BLOCK_LENGTH ||
1353             in_end - in_next < MIN_BLOCK_LENGTH)
1354                 return false;
1355
1356         return do_end_block_check(stats, in_next - in_block_begin);
1357 }
1358
1359 /******************************************************************************/
1360
1361 /*
1362  * Given the minimum-cost path computed through the item graph for the current
1363  * block, walk the path and count how many of each symbol in each Huffman-coded
1364  * alphabet would be required to output the items (matches and literals) along
1365  * the path.
1366  *
1367  * Note that the path will be walked backwards (from the end of the block to the
1368  * beginning of the block), but this doesn't matter because this function only
1369  * computes frequencies.
1370  */
1371 static inline void
1372 lzx_tally_item_list(struct lzx_compressor *c, u32 block_length, bool is_16_bit)
1373 {
1374         u32 node_idx = block_length;
1375
1376         for (;;) {
1377                 u32 item;
1378                 u32 len;
1379                 u32 offset_data;
1380                 unsigned v;
1381                 unsigned offset_slot;
1382
1383                 /* Tally literals until either a match or the beginning of the
1384                  * block is reached.  */
1385                 for (;;) {
1386                         item = c->optimum_nodes[node_idx].item;
1387                         if (item & OPTIMUM_LEN_MASK)
1388                                 break;
1389                         c->freqs.main[item >> OPTIMUM_OFFSET_SHIFT]++;
1390                         node_idx--;
1391                 }
1392
1393                 if (item & OPTIMUM_EXTRA_FLAG) {
1394
1395                         if (node_idx == 0)
1396                                 break;
1397
1398                         /* Tally a rep0 match.  */
1399                         len = item & OPTIMUM_LEN_MASK;
1400                         v = len - LZX_MIN_MATCH_LEN;
1401                         if (v >= LZX_NUM_PRIMARY_LENS) {
1402                                 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1403                                 v = LZX_NUM_PRIMARY_LENS;
1404                         }
1405                         c->freqs.main[LZX_NUM_CHARS + v]++;
1406
1407                         /* Tally a literal.  */
1408                         c->freqs.main[c->optimum_nodes[node_idx].extra_literal]++;
1409
1410                         item = c->optimum_nodes[node_idx].extra_match;
1411                         node_idx -= len + 1;
1412                 }
1413
1414                 len = item & OPTIMUM_LEN_MASK;
1415                 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1416
1417                 node_idx -= len;
1418
1419                 /* Tally a match.  */
1420
1421                 /* Tally the aligned offset symbol if needed.  */
1422                 if (offset_data >= 16)
1423                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1424
1425                 /* Tally the length symbol if needed.  */
1426                 v = len - LZX_MIN_MATCH_LEN;;
1427                 if (v >= LZX_NUM_PRIMARY_LENS) {
1428                         c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1429                         v = LZX_NUM_PRIMARY_LENS;
1430                 }
1431
1432                 /* Tally the main symbol.  */
1433                 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1434                 v += offset_slot * LZX_NUM_LEN_HEADERS;
1435                 c->freqs.main[LZX_NUM_CHARS + v]++;
1436         }
1437 }
1438
1439 /*
1440  * Like lzx_tally_item_list(), but this function also generates the list of
1441  * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1442  * ready to be output to the bitstream after the Huffman codes are computed.
1443  * The lzx_sequences will be written to decreasing memory addresses as the path
1444  * is walked backwards, which means they will end up in the expected
1445  * first-to-last order.  The return value is the index in c->chosen_sequences at
1446  * which the lzx_sequences begin.
1447  */
1448 static inline u32
1449 lzx_record_item_list(struct lzx_compressor *c, u32 block_length, bool is_16_bit)
1450 {
1451         u32 node_idx = block_length;
1452         u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1453         u32 lit_start_node;
1454
1455         /* Special value to mark last sequence  */
1456         c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1457
1458         lit_start_node = node_idx;
1459         for (;;) {
1460                 u32 item;
1461                 u32 len;
1462                 u32 offset_data;
1463                 unsigned v;
1464                 unsigned offset_slot;
1465
1466                 /* Tally literals until either a match or the beginning of the
1467                  * block is reached.  */
1468                 for (;;) {
1469                         item = c->optimum_nodes[node_idx].item;
1470                         if (item & OPTIMUM_LEN_MASK)
1471                                 break;
1472                         c->freqs.main[item >> OPTIMUM_OFFSET_SHIFT]++;
1473                         node_idx--;
1474                 }
1475
1476                 if (item & OPTIMUM_EXTRA_FLAG) {
1477
1478                         if (node_idx == 0)
1479                                 break;
1480
1481                         /* Save the literal run length for the next sequence
1482                          * (the "previous sequence" when walking backwards).  */
1483                         len = item & OPTIMUM_LEN_MASK;
1484                         c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1485                         seq_idx--;
1486                         lit_start_node = node_idx - len;
1487
1488                         /* Tally a rep0 match.  */
1489                         v = len - LZX_MIN_MATCH_LEN;
1490                         c->chosen_sequences[seq_idx].adjusted_length = v;
1491                         if (v >= LZX_NUM_PRIMARY_LENS) {
1492                                 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1493                                 v = LZX_NUM_PRIMARY_LENS;
1494                         }
1495                         c->freqs.main[LZX_NUM_CHARS + v]++;
1496                         c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = v;
1497
1498                         /* Tally a literal.  */
1499                         c->freqs.main[c->optimum_nodes[node_idx].extra_literal]++;
1500
1501                         item = c->optimum_nodes[node_idx].extra_match;
1502                         node_idx -= len + 1;
1503                 }
1504
1505                 len = item & OPTIMUM_LEN_MASK;
1506                 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1507
1508                 /* Save the literal run length for the next sequence (the
1509                  * "previous sequence" when walking backwards).  */
1510                 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1511                 node_idx -= len;
1512                 lit_start_node = node_idx;
1513
1514                 /* Record a match.  */
1515
1516                 /* Tally the aligned offset symbol if needed.  */
1517                 if (offset_data >= 16)
1518                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1519
1520                 /* Save the adjusted length.  */
1521                 v = len - LZX_MIN_MATCH_LEN;
1522                 c->chosen_sequences[seq_idx].adjusted_length = v;
1523
1524                 /* Tally the length symbol if needed.  */
1525                 if (v >= LZX_NUM_PRIMARY_LENS) {
1526                         c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1527                         v = LZX_NUM_PRIMARY_LENS;
1528                 }
1529
1530                 /* Tally the main symbol.  */
1531                 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1532                 v += offset_slot * LZX_NUM_LEN_HEADERS;
1533                 c->freqs.main[LZX_NUM_CHARS + v]++;
1534
1535                 /* Save the adjusted offset and match header.  */
1536                 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1537                                 (offset_data << 9) | v;
1538         }
1539
1540         /* Save the literal run length for the first sequence.  */
1541         c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1542
1543         /* Return the index in c->chosen_sequences at which the lzx_sequences
1544          * begin.  */
1545         return seq_idx;
1546 }
1547
1548 /*
1549  * Find an inexpensive path through the graph of possible match/literal choices
1550  * for the current block.  The nodes of the graph are
1551  * c->optimum_nodes[0...block_length].  They correspond directly to the bytes in
1552  * the current block, plus one extra node for end-of-block.  The edges of the
1553  * graph are matches and literals.  The goal is to find the minimum cost path
1554  * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_length]', given the cost
1555  * model 'c->costs'.
1556  *
1557  * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1558  * proceeding forwards one node at a time.  At each node, a selection of matches
1559  * (len >= 2), as well as the literal byte (len = 1), is considered.  An item of
1560  * length 'len' provides a new path to reach the node 'len' bytes later.  If
1561  * such a path is the lowest cost found so far to reach that later node, then
1562  * that later node is updated with the new path.
1563  *
1564  * Note that although this algorithm is based on minimum cost path search, due
1565  * to various simplifying assumptions the result is not guaranteed to be the
1566  * true minimum cost, or "optimal", path over the graph of all valid LZX
1567  * representations of this block.
1568  *
1569  * Also, note that because of the presence of the recent offsets queue (which is
1570  * a type of adaptive state), the algorithm cannot work backwards and compute
1571  * "cost to end" instead of "cost to beginning".  Furthermore, the way the
1572  * algorithm handles this adaptive state in the "minimum cost" parse is actually
1573  * only an approximation.  It's possible for the globally optimal, minimum cost
1574  * path to contain a prefix, ending at a position, where that path prefix is
1575  * *not* the minimum cost path to that position.  This can happen if such a path
1576  * prefix results in a different adaptive state which results in lower costs
1577  * later.  The algorithm does not solve this problem; it only considers the
1578  * lowest cost to reach each individual position.
1579  */
1580 static inline struct lzx_lru_queue
1581 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1582                        const u8 * const restrict block_begin,
1583                        const u32 block_length,
1584                        const struct lzx_lru_queue initial_queue,
1585                        bool is_16_bit)
1586 {
1587         struct lzx_optimum_node *cur_node = c->optimum_nodes;
1588         struct lz_match *cache_ptr = c->match_cache;
1589         const u8 *in_next = block_begin;
1590         const u8 * const block_end = block_begin + block_length;
1591
1592         /* Instead of storing the match offset LRU queues in the
1593          * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1594          * storing them in a smaller array.  This works because the algorithm
1595          * only requires a limited history of the adaptive state.  Once a given
1596          * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1597          * it is no longer needed.  */
1598         struct lzx_lru_queue queues[512];
1599
1600         STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1601 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1602
1603         /* Initially, the cost to reach each node is "infinity".  */
1604         memset(c->optimum_nodes, 0xFF,
1605                (block_length + 1) * sizeof(c->optimum_nodes[0]));
1606
1607         QUEUE(block_begin) = initial_queue;
1608
1609         /* The following loop runs 'block_length' iterations, one per node.  */
1610         do {
1611                 unsigned num_matches;
1612                 unsigned literal;
1613                 u32 cost;
1614                 struct lz_match *matches;
1615
1616                 /*
1617                  * A selection of matches for the block was already saved in
1618                  * memory so that we don't have to run the uncompressed data
1619                  * through the matchfinder on every optimization pass.  However,
1620                  * we still search for repeat offset matches during each
1621                  * optimization pass because we cannot predict the state of the
1622                  * recent offsets queue.  But as a heuristic, we don't bother
1623                  * searching for repeat offset matches if the general-purpose
1624                  * matchfinder failed to find any matches.
1625                  *
1626                  * Note that a match of length n at some offset implies there is
1627                  * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1628                  * that same offset.  In other words, we don't necessarily need
1629                  * to use the full length of a match.  The key heuristic that
1630                  * saves a significicant amount of time is that for each
1631                  * distinct length, we only consider the smallest offset for
1632                  * which that length is available.  This heuristic also applies
1633                  * to repeat offsets, which we order specially: R0 < R1 < R2 <
1634                  * any explicit offset.  Of course, this heuristic may be
1635                  * produce suboptimal results because offset slots in LZX are
1636                  * subject to entropy encoding, but in practice this is a useful
1637                  * heuristic.
1638                  */
1639
1640                 num_matches = cache_ptr->length;
1641                 cache_ptr++;
1642                 matches = cache_ptr;
1643
1644                 if (num_matches) {
1645                         unsigned next_len = LZX_MIN_MATCH_LEN;
1646                         unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1647                         const u8 *matchptr;
1648
1649                         /* Consider R0 match  */
1650                         matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1651                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1652                                 goto R0_done;
1653                         STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1654                         do {
1655                                 u32 cost = cur_node->cost +
1656                                            c->costs.match_cost[0][
1657                                                         next_len - LZX_MIN_MATCH_LEN];
1658                                 if (cost <= (cur_node + next_len)->cost) {
1659                                         (cur_node + next_len)->cost = cost;
1660                                         (cur_node + next_len)->item =
1661                                                 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1662                                 }
1663                                 if (unlikely(++next_len > max_len))
1664                                         goto done_matches;
1665                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1666
1667                 R0_done:
1668
1669                         /* Consider R1 match  */
1670                         matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1671                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1672                                 goto R1_done;
1673                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1674                                 goto R1_done;
1675                         for (unsigned len = 2; len < next_len - 1; len++)
1676                                 if (matchptr[len] != in_next[len])
1677                                         goto R1_done;
1678                         do {
1679                                 u32 cost = cur_node->cost +
1680                                            c->costs.match_cost[1][
1681                                                         next_len - LZX_MIN_MATCH_LEN];
1682                                 if (cost <= (cur_node + next_len)->cost) {
1683                                         (cur_node + next_len)->cost = cost;
1684                                         (cur_node + next_len)->item =
1685                                                 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1686                                 }
1687                                 if (unlikely(++next_len > max_len))
1688                                         goto done_matches;
1689                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1690
1691                 R1_done:
1692
1693                         /* Consider R2 match  */
1694                         matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1695                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1696                                 goto R2_done;
1697                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1698                                 goto R2_done;
1699                         for (unsigned len = 2; len < next_len - 1; len++)
1700                                 if (matchptr[len] != in_next[len])
1701                                         goto R2_done;
1702                         do {
1703                                 u32 cost = cur_node->cost +
1704                                            c->costs.match_cost[2][
1705                                                         next_len - LZX_MIN_MATCH_LEN];
1706                                 if (cost <= (cur_node + next_len)->cost) {
1707                                         (cur_node + next_len)->cost = cost;
1708                                         (cur_node + next_len)->item =
1709                                                 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1710                                 }
1711                                 if (unlikely(++next_len > max_len))
1712                                         goto done_matches;
1713                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1714
1715                 R2_done:
1716                         matches = cache_ptr;
1717                         cache_ptr += num_matches - 1;
1718                         while (next_len > cache_ptr->length) {
1719                                 if (cache_ptr == matches)
1720                                         goto done_matches;
1721                                 cache_ptr--;
1722                         }
1723
1724                         /* Consider explicit offset matches  */
1725                         for (;;) {
1726                                 u32 offset = cache_ptr->offset;
1727                                 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1728                                 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1729                                                                                 is_16_bit);
1730                                 u32 base_cost = cur_node->cost;
1731                                 u32 cost;
1732
1733                         #if LZX_CONSIDER_ALIGNED_COSTS
1734                                 if (offset_data >= 16)
1735                                         base_cost += c->costs.aligned[offset_data &
1736                                                                       LZX_ALIGNED_OFFSET_BITMASK];
1737                         #endif
1738                                 do {
1739                                         cost = base_cost +
1740                                                c->costs.match_cost[offset_slot][
1741                                                                 next_len - LZX_MIN_MATCH_LEN];
1742                                         if (cost < (cur_node + next_len)->cost) {
1743                                                 (cur_node + next_len)->cost = cost;
1744                                                 (cur_node + next_len)->item =
1745                                                         (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1746                                         }
1747                                 } while (++next_len <= cache_ptr->length);
1748
1749                                 if (cache_ptr == matches) {
1750                                         /* Consider match + lit + rep0 */
1751                                         u32 remaining = block_end - (in_next + next_len);
1752                                         if (likely(remaining >= 2)) {
1753                                                 const u8 *strptr = in_next + next_len;
1754                                                 const u8 *matchptr = strptr - offset;
1755                                                 if (unlikely(load_u16_unaligned(strptr) == load_u16_unaligned(matchptr))) {
1756                                                         u32 rep0_len = lz_extend(strptr, matchptr, 2,
1757                                                                                  min(remaining, LZX_MAX_MATCH_LEN));
1758                                                         u8 lit = strptr[-1];
1759                                                         cost += c->costs.main[lit] +
1760                                                                 c->costs.match_cost[0][rep0_len - LZX_MIN_MATCH_LEN];
1761                                                         u32 total_len = next_len + rep0_len;
1762                                                         if (cost < (cur_node + total_len)->cost) {
1763                                                                 (cur_node + total_len)->cost = cost;
1764                                                                 (cur_node + total_len)->item =
1765                                                                         OPTIMUM_EXTRA_FLAG | rep0_len;
1766                                                                 (cur_node + total_len)->extra_literal = lit;
1767                                                                 (cur_node + total_len)->extra_match =
1768                                                                         (offset_data << OPTIMUM_OFFSET_SHIFT) | (next_len - 1);
1769                                                         }
1770                                                 }
1771                                         }
1772                                         break;
1773                                 }
1774                                 cache_ptr--;
1775                         }
1776                 }
1777
1778         done_matches:
1779                 cache_ptr = matches + num_matches;
1780
1781                 /* Consider coding a literal.
1782
1783                  * To avoid an extra branch, actually checking the preferability
1784                  * of coding the literal is integrated into the queue update
1785                  * code below.  */
1786                 literal = *in_next++;
1787                 cost = cur_node->cost + c->costs.main[literal];
1788
1789                 /* Advance to the next position.  */
1790                 cur_node++;
1791
1792                 /* The lowest-cost path to the current position is now known.
1793                  * Finalize the recent offsets queue that results from taking
1794                  * this lowest-cost path.  */
1795
1796                 if (cost <= cur_node->cost) {
1797                         /* Literal: queue remains unchanged.  */
1798                         cur_node->cost = cost;
1799                         cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1800                         QUEUE(in_next) = QUEUE(in_next - 1);
1801                 } else {
1802                         /* Match: queue update is needed.  */
1803                         unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1804                         u32 offset_data = (cur_node->item &
1805                                            ~OPTIMUM_EXTRA_FLAG) >> OPTIMUM_OFFSET_SHIFT;
1806                         if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1807                                 /* Explicit offset match: insert offset at front  */
1808                                 QUEUE(in_next) =
1809                                         lzx_lru_queue_push(QUEUE(in_next - len),
1810                                                            offset_data - LZX_OFFSET_ADJUSTMENT);
1811                         } else if (cur_node->item & OPTIMUM_EXTRA_FLAG) {
1812                                 /* Explicit offset match, then literal, then
1813                                  * rep0 match: insert offset at front  */
1814                                 len += 1 + (cur_node->extra_match & OPTIMUM_LEN_MASK);
1815                                 QUEUE(in_next) =
1816                                         lzx_lru_queue_push(QUEUE(in_next - len),
1817                                                            (cur_node->extra_match >> OPTIMUM_OFFSET_SHIFT) -
1818                                                            LZX_OFFSET_ADJUSTMENT);
1819                         } else {
1820                                 /* Repeat offset match: swap offset to front  */
1821                                 QUEUE(in_next) =
1822                                         lzx_lru_queue_swap(QUEUE(in_next - len),
1823                                                            offset_data);
1824                         }
1825                 }
1826         } while (in_next != block_end);
1827
1828         /* Return the match offset queue at the end of the minimum cost path. */
1829         return QUEUE(block_end);
1830 }
1831
1832 /* Given the costs for the main and length codewords, compute 'match_costs'.  */
1833 static void
1834 lzx_compute_match_costs(struct lzx_compressor *c)
1835 {
1836         unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) /
1837                                         LZX_NUM_LEN_HEADERS;
1838         struct lzx_costs *costs = &c->costs;
1839
1840         for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1841
1842                 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1843                 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot *
1844                                                         LZX_NUM_LEN_HEADERS);
1845                 unsigned i;
1846
1847         #if LZX_CONSIDER_ALIGNED_COSTS
1848                 if (offset_slot >= 8)
1849                         extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1850         #endif
1851
1852                 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1853                         costs->match_cost[offset_slot][i] =
1854                                 costs->main[main_symbol++] + extra_cost;
1855
1856                 extra_cost += costs->main[main_symbol];
1857
1858                 for (; i < LZX_NUM_LENS; i++)
1859                         costs->match_cost[offset_slot][i] =
1860                                 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1861         }
1862 }
1863
1864 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1865  * algorithm.  */
1866 static void
1867 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_length)
1868 {
1869         u32 i;
1870         bool have_byte[256];
1871         unsigned num_used_bytes;
1872
1873         /* The costs below are hard coded to use a scaling factor of 64.  */
1874         STATIC_ASSERT(LZX_BIT_COST == 64);
1875
1876         /*
1877          * Heuristics:
1878          *
1879          * - Use smaller initial costs for literal symbols when the input buffer
1880          *   contains fewer distinct bytes.
1881          *
1882          * - Assume that match symbols are more costly than literal symbols.
1883          *
1884          * - Assume that length symbols for shorter lengths are less costly than
1885          *   length symbols for longer lengths.
1886          */
1887
1888         for (i = 0; i < 256; i++)
1889                 have_byte[i] = false;
1890
1891         for (i = 0; i < block_length; i++)
1892                 have_byte[block[i]] = true;
1893
1894         num_used_bytes = 0;
1895         for (i = 0; i < 256; i++)
1896                 num_used_bytes += have_byte[i];
1897
1898         for (i = 0; i < 256; i++)
1899                 c->costs.main[i] = 560 - (256 - num_used_bytes);
1900
1901         for (; i < c->num_main_syms; i++)
1902                 c->costs.main[i] = 680;
1903
1904         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1905                 c->costs.len[i] = 412 + i;
1906
1907 #if LZX_CONSIDER_ALIGNED_COSTS
1908         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1909                 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1910 #endif
1911
1912         lzx_compute_match_costs(c);
1913 }
1914
1915 /* Update the current cost model to reflect the computed Huffman codes.  */
1916 static void
1917 lzx_set_costs_from_codes(struct lzx_compressor *c)
1918 {
1919         unsigned i;
1920         const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1921
1922         for (i = 0; i < c->num_main_syms; i++) {
1923                 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1924                                     MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1925         }
1926
1927         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1928                 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1929                                    LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1930         }
1931
1932 #if LZX_CONSIDER_ALIGNED_COSTS
1933         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1934                 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1935                                        ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1936         }
1937 #endif
1938
1939         lzx_compute_match_costs(c);
1940 }
1941
1942 /*
1943  * Choose a "near-optimal" literal/match sequence to use for the current block.
1944  * Because the cost of each Huffman symbol is unknown until the Huffman codes
1945  * have been built and the Huffman codes themselves depend on the symbol
1946  * frequencies, this uses an iterative optimization algorithm to approximate an
1947  * optimal solution.  The first optimization pass for the block uses default
1948  * costs.  Additional passes use costs taken from the Huffman codes computed in
1949  * the previous pass.
1950  */
1951 static inline struct lzx_lru_queue
1952 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1953                              struct lzx_output_bitstream * const restrict os,
1954                              const u8 * const restrict block_begin,
1955                              const u32 block_length,
1956                              const struct lzx_lru_queue initial_queue,
1957                              bool is_16_bit)
1958 {
1959         unsigned num_passes_remaining = c->num_optim_passes;
1960         struct lzx_lru_queue new_queue;
1961         u32 seq_idx;
1962
1963         lzx_set_default_costs(c, block_begin, block_length);
1964
1965         for (;;) {
1966                 new_queue = lzx_find_min_cost_path(c, block_begin, block_length,
1967                                                    initial_queue, is_16_bit);
1968
1969                 if (--num_passes_remaining == 0)
1970                         break;
1971
1972                 /* At least one iteration remains; update the costs. */
1973                 lzx_reset_symbol_frequencies(c);
1974                 lzx_tally_item_list(c, block_length, is_16_bit);
1975                 lzx_make_huffman_codes(c);
1976                 lzx_set_costs_from_codes(c);
1977         }
1978
1979         /* Done optimizing.  Generate the sequence list and flush the block. */
1980         lzx_reset_symbol_frequencies(c);
1981         seq_idx = lzx_record_item_list(c, block_length, is_16_bit);
1982         lzx_flush_block(c, os, block_begin, block_length, seq_idx);
1983         return new_queue;
1984 }
1985
1986 /*
1987  * This is the "near-optimal" LZX compressor.
1988  *
1989  * For each block, it performs a relatively thorough graph search to find an
1990  * inexpensive (in terms of compressed size) way to output that block.
1991  *
1992  * Note: there are actually many things this algorithm leaves on the table in
1993  * terms of compression ratio.  So although it may be "near-optimal", it is
1994  * certainly not "optimal".  The goal is not to produce the optimal compression
1995  * ratio, which for LZX is probably impossible within any practical amount of
1996  * time, but rather to produce a compression ratio significantly better than a
1997  * simpler "greedy" or "lazy" parse while still being relatively fast.
1998  */
1999 static inline void
2000 lzx_compress_near_optimal(struct lzx_compressor * restrict c,
2001                           const u8 * const restrict in_begin,
2002                           struct lzx_output_bitstream * restrict os,
2003                           bool is_16_bit)
2004 {
2005         const u8 *       in_next = in_begin;
2006         const u8 * const in_end  = in_begin + c->in_nbytes;
2007         struct lzx_lru_queue queue;
2008
2009         lcpit_matchfinder_load_buffer(&c->lcpit_mf, in_begin, c->in_nbytes);
2010         lzx_lru_queue_init(&queue);
2011
2012         do {
2013                 /* Starting a new block  */
2014                 const u8 * const in_block_begin = in_next;
2015                 const u8 * const in_max_block_end =
2016                         in_next + min(SOFT_MAX_BLOCK_LENGTH, in_end - in_next);
2017                 struct lz_match *cache_ptr = c->match_cache;
2018                 const u8 *next_observation = in_next;
2019                 const u8 *next_pause_point = min(in_next + MIN_BLOCK_LENGTH,
2020                                                  in_max_block_end - LZX_MAX_MATCH_LEN - 1);
2021
2022                 init_block_split_stats(&c->split_stats);
2023
2024                 /* Run the block through the matchfinder and cache the matches. */
2025         enter_mf_loop:
2026                 do {
2027                         u32 num_matches;
2028                         u32 best_len = 0;
2029
2030                         num_matches = lcpit_matchfinder_get_matches(&c->lcpit_mf, cache_ptr + 1);
2031                         cache_ptr->length = num_matches;
2032                         if (num_matches)
2033                                 best_len = cache_ptr[1].length;
2034
2035                         if (in_next >= next_observation) {
2036                                 if (best_len) {
2037                                         observe_match(&c->split_stats, best_len);
2038                                         next_observation = in_next + best_len;
2039                                 } else {
2040                                         observe_literal(&c->split_stats, *in_next);
2041                                         next_observation = in_next + 1;
2042                                 }
2043                         }
2044
2045                         /*
2046                          * If there was a very long match found, then don't
2047                          * cache any matches for the bytes covered by that
2048                          * match.  This avoids degenerate behavior when
2049                          * compressing highly redundant data, where the number
2050                          * of matches can be very large.
2051                          *
2052                          * This heuristic doesn't actually hurt the compression
2053                          * ratio very much.  If there's a long match, then the
2054                          * data must be highly compressible, so it doesn't
2055                          * matter as much what we do.
2056                          */
2057                         if (best_len >= c->nice_match_length) {
2058                                 best_len = lz_extend(in_next, in_next - cache_ptr[1].offset,
2059                                                      best_len,
2060                                                      min(LZX_MAX_MATCH_LEN,
2061                                                          in_end - in_next));
2062                                 cache_ptr[1].length = best_len;
2063                                 lcpit_matchfinder_skip_bytes(&c->lcpit_mf, best_len - 1);
2064                                 cache_ptr += 1 + num_matches;
2065                                 for (u32 i = 0; i < best_len - 1; i++) {
2066                                         cache_ptr->length = 0;
2067                                         cache_ptr++;
2068                                 }
2069                                 in_next += best_len;
2070                                 next_observation = in_next;
2071                         } else {
2072                                 cache_ptr += 1 + num_matches;
2073                                 in_next++;
2074                         }
2075                 } while (in_next < next_pause_point &&
2076                          likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
2077
2078                 if (unlikely(cache_ptr >= &c->match_cache[LZX_CACHE_LENGTH]))
2079                         goto flush_block;
2080
2081                 if (in_next >= in_max_block_end)
2082                         goto flush_block;
2083
2084                 if (c->split_stats.num_new_observations >= NUM_OBSERVATIONS_PER_BLOCK_CHECK) {
2085                         if (do_end_block_check(&c->split_stats, in_next - in_block_begin))
2086                                 goto flush_block;
2087                         if (in_max_block_end - in_next <= MIN_BLOCK_LENGTH)
2088                                 next_observation = in_max_block_end;
2089                 }
2090
2091                 next_pause_point = min(in_next +
2092                                        NUM_OBSERVATIONS_PER_BLOCK_CHECK * 2 -
2093                                        c->split_stats.num_new_observations,
2094                                        in_max_block_end - LZX_MAX_MATCH_LEN - 1);
2095                 goto enter_mf_loop;
2096
2097         flush_block:
2098                 /* We've finished running the block through the matchfinder.
2099                  * Now choose a match/literal sequence and write the block.  */
2100
2101                 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
2102                                                      in_next - in_block_begin,
2103                                                      queue, is_16_bit);
2104         } while (in_next != in_end);
2105 }
2106
2107 static void
2108 lzx_compress_near_optimal_16(struct lzx_compressor *c,
2109                              struct lzx_output_bitstream *os)
2110 {
2111         lzx_compress_near_optimal(c, c->in_buffer, os, true);
2112 }
2113
2114 static void
2115 lzx_compress_near_optimal_32(struct lzx_compressor *c,
2116                              struct lzx_output_bitstream *os)
2117 {
2118         lzx_compress_near_optimal(c, c->in_buffer, os, false);
2119 }
2120
2121 /*
2122  * Given a pointer to the current byte sequence and the current list of recent
2123  * match offsets, find the longest repeat offset match.
2124  *
2125  * If no match of at least 2 bytes is found, then return 0.
2126  *
2127  * If a match of at least 2 bytes is found, then return its length and set
2128  * *rep_max_idx_ret to the index of its offset in @queue.
2129 */
2130 static unsigned
2131 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
2132                                      const u32 bytes_remaining,
2133                                      const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
2134                                      unsigned *rep_max_idx_ret)
2135 {
2136         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2137
2138         const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
2139         const u16 next_2_bytes = load_u16_unaligned(in_next);
2140         const u8 *matchptr;
2141         unsigned rep_max_len;
2142         unsigned rep_max_idx;
2143         unsigned rep_len;
2144
2145         matchptr = in_next - recent_offsets[0];
2146         if (load_u16_unaligned(matchptr) == next_2_bytes)
2147                 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
2148         else
2149                 rep_max_len = 0;
2150         rep_max_idx = 0;
2151
2152         matchptr = in_next - recent_offsets[1];
2153         if (load_u16_unaligned(matchptr) == next_2_bytes) {
2154                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2155                 if (rep_len > rep_max_len) {
2156                         rep_max_len = rep_len;
2157                         rep_max_idx = 1;
2158                 }
2159         }
2160
2161         matchptr = in_next - recent_offsets[2];
2162         if (load_u16_unaligned(matchptr) == next_2_bytes) {
2163                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
2164                 if (rep_len > rep_max_len) {
2165                         rep_max_len = rep_len;
2166                         rep_max_idx = 2;
2167                 }
2168         }
2169
2170         *rep_max_idx_ret = rep_max_idx;
2171         return rep_max_len;
2172 }
2173
2174 /* Fast heuristic scoring for lazy parsing: how "good" is this match?  */
2175 static inline unsigned
2176 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
2177 {
2178         unsigned score = len;
2179
2180         if (adjusted_offset < 4096)
2181                 score++;
2182
2183         if (adjusted_offset < 256)
2184                 score++;
2185
2186         return score;
2187 }
2188
2189 static inline unsigned
2190 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
2191 {
2192         return rep_len + 3;
2193 }
2194
2195 /* This is the "lazy" LZX compressor.  */
2196 static inline void
2197 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
2198                   bool is_16_bit)
2199 {
2200         const u8 * const in_begin = c->in_buffer;
2201         const u8 *       in_next = in_begin;
2202         const u8 * const in_end  = in_begin + c->in_nbytes;
2203         unsigned max_len = LZX_MAX_MATCH_LEN;
2204         unsigned nice_len = min(c->nice_match_length, max_len);
2205         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2206         u32 recent_offsets[3] = {1, 1, 1};
2207         u32 next_hashes[2] = {};
2208
2209         CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2210
2211         do {
2212                 /* Starting a new block  */
2213
2214                 const u8 * const in_block_begin = in_next;
2215                 const u8 * const in_max_block_end =
2216                         in_next + min(SOFT_MAX_BLOCK_LENGTH, in_end - in_next);
2217                 struct lzx_sequence *next_seq = c->chosen_sequences;
2218                 unsigned cur_len;
2219                 u32 cur_offset;
2220                 u32 cur_offset_data;
2221                 unsigned cur_score;
2222                 unsigned next_len;
2223                 u32 next_offset;
2224                 u32 next_offset_data;
2225                 unsigned next_score;
2226                 unsigned rep_max_len;
2227                 unsigned rep_max_idx;
2228                 unsigned rep_score;
2229                 unsigned skip_len;
2230                 u32 litrunlen = 0;
2231
2232                 lzx_reset_symbol_frequencies(c);
2233                 init_block_split_stats(&c->split_stats);
2234
2235                 do {
2236                         if (unlikely(max_len > in_end - in_next)) {
2237                                 max_len = in_end - in_next;
2238                                 nice_len = min(max_len, nice_len);
2239                         }
2240
2241                         /* Find the longest match at the current position.  */
2242
2243                         cur_len = CALL_HC_MF(is_16_bit, c,
2244                                              hc_matchfinder_longest_match,
2245                                              in_begin,
2246                                              in_next - in_begin,
2247                                              2,
2248                                              max_len,
2249                                              nice_len,
2250                                              c->max_search_depth,
2251                                              next_hashes,
2252                                              &cur_offset);
2253                         if (cur_len < 3 ||
2254                             (cur_len == 3 &&
2255                              cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2256                              cur_offset != recent_offsets[0] &&
2257                              cur_offset != recent_offsets[1] &&
2258                              cur_offset != recent_offsets[2]))
2259                         {
2260                                 /* There was no match found, or the only match found
2261                                  * was a distant length 3 match.  Output a literal.  */
2262                                 lzx_record_literal(c, *in_next, &litrunlen);
2263                                 observe_literal(&c->split_stats, *in_next);
2264                                 in_next++;
2265                                 continue;
2266                         }
2267
2268                         observe_match(&c->split_stats, cur_len);
2269
2270                         if (cur_offset == recent_offsets[0]) {
2271                                 in_next++;
2272                                 cur_offset_data = 0;
2273                                 skip_len = cur_len - 1;
2274                                 goto choose_cur_match;
2275                         }
2276
2277                         cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2278                         cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2279
2280                         /* Consider a repeat offset match  */
2281                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2282                                                                            in_end - in_next,
2283                                                                            recent_offsets,
2284                                                                            &rep_max_idx);
2285                         in_next++;
2286
2287                         if (rep_max_len >= 3 &&
2288                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2289                                                                        rep_max_idx)) >= cur_score)
2290                         {
2291                                 cur_len = rep_max_len;
2292                                 cur_offset_data = rep_max_idx;
2293                                 skip_len = rep_max_len - 1;
2294                                 goto choose_cur_match;
2295                         }
2296
2297                 have_cur_match:
2298
2299                         /* We have a match at the current position.  */
2300
2301                         /* If we have a very long match, choose it immediately.  */
2302                         if (cur_len >= nice_len) {
2303                                 skip_len = cur_len - 1;
2304                                 goto choose_cur_match;
2305                         }
2306
2307                         /* See if there's a better match at the next position.  */
2308
2309                         if (unlikely(max_len > in_end - in_next)) {
2310                                 max_len = in_end - in_next;
2311                                 nice_len = min(max_len, nice_len);
2312                         }
2313
2314                         next_len = CALL_HC_MF(is_16_bit, c,
2315                                               hc_matchfinder_longest_match,
2316                                               in_begin,
2317                                               in_next - in_begin,
2318                                               cur_len - 2,
2319                                               max_len,
2320                                               nice_len,
2321                                               c->max_search_depth / 2,
2322                                               next_hashes,
2323                                               &next_offset);
2324
2325                         if (next_len <= cur_len - 2) {
2326                                 in_next++;
2327                                 skip_len = cur_len - 2;
2328                                 goto choose_cur_match;
2329                         }
2330
2331                         next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2332                         next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2333
2334                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2335                                                                            in_end - in_next,
2336                                                                            recent_offsets,
2337                                                                            &rep_max_idx);
2338                         in_next++;
2339
2340                         if (rep_max_len >= 3 &&
2341                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2342                                                                        rep_max_idx)) >= next_score)
2343                         {
2344
2345                                 if (rep_score > cur_score) {
2346                                         /* The next match is better, and it's a
2347                                          * repeat offset match.  */
2348                                         lzx_record_literal(c, *(in_next - 2),
2349                                                            &litrunlen);
2350                                         cur_len = rep_max_len;
2351                                         cur_offset_data = rep_max_idx;
2352                                         skip_len = cur_len - 1;
2353                                         goto choose_cur_match;
2354                                 }
2355                         } else {
2356                                 if (next_score > cur_score) {
2357                                         /* The next match is better, and it's an
2358                                          * explicit offset match.  */
2359                                         lzx_record_literal(c, *(in_next - 2),
2360                                                            &litrunlen);
2361                                         cur_len = next_len;
2362                                         cur_offset_data = next_offset_data;
2363                                         cur_score = next_score;
2364                                         goto have_cur_match;
2365                                 }
2366                         }
2367
2368                         /* The original match was better.  */
2369                         skip_len = cur_len - 2;
2370
2371                 choose_cur_match:
2372                         lzx_record_match(c, cur_len, cur_offset_data,
2373                                          recent_offsets, is_16_bit,
2374                                          &litrunlen, &next_seq);
2375                         in_next = CALL_HC_MF(is_16_bit, c,
2376                                              hc_matchfinder_skip_positions,
2377                                              in_begin,
2378                                              in_next - in_begin,
2379                                              in_end - in_begin,
2380                                              skip_len,
2381                                              next_hashes);
2382                 } while (in_next < in_max_block_end &&
2383                          !should_end_block(&c->split_stats, in_block_begin, in_next, in_end));
2384
2385                 lzx_finish_sequence(next_seq, litrunlen);
2386
2387                 lzx_flush_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2388
2389         } while (in_next != in_end);
2390 }
2391
2392 static void
2393 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2394 {
2395         lzx_compress_lazy(c, os, true);
2396 }
2397
2398 static void
2399 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2400 {
2401         lzx_compress_lazy(c, os, false);
2402 }
2403
2404 /* Generate the acceleration tables for offset slots.  */
2405 static void
2406 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2407 {
2408         u32 adjusted_offset = 0;
2409         unsigned slot = 0;
2410
2411         /* slots [0, 29]  */
2412         for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2413              adjusted_offset++)
2414         {
2415                 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2416                         slot++;
2417                 c->offset_slot_tab_1[adjusted_offset] = slot;
2418         }
2419
2420         /* slots [30, 49]  */
2421         for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2422              adjusted_offset += (u32)1 << 14)
2423         {
2424                 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2425                         slot++;
2426                 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2427         }
2428 }
2429
2430 static size_t
2431 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2432 {
2433         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2434                 if (lzx_is_16_bit(max_bufsize))
2435                         return offsetof(struct lzx_compressor, hc_mf_16) +
2436                                hc_matchfinder_size_16(max_bufsize);
2437                 else
2438                         return offsetof(struct lzx_compressor, hc_mf_32) +
2439                                hc_matchfinder_size_32(max_bufsize);
2440         } else {
2441                 if (lzx_is_16_bit(max_bufsize))
2442                         return offsetof(struct lzx_compressor, lcpit_mf) +
2443                                sizeof(struct lcpit_matchfinder);
2444                 else
2445                         return offsetof(struct lzx_compressor, lcpit_mf) +
2446                                sizeof(struct lcpit_matchfinder);
2447         }
2448 }
2449
2450 static u64
2451 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2452                       bool destructive)
2453 {
2454         u64 size = 0;
2455
2456         if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2457                 return 0;
2458
2459         size += lzx_get_compressor_size(max_bufsize, compression_level);
2460         if (!destructive)
2461                 size += max_bufsize; /* in_buffer */
2462         if (compression_level > LZX_MAX_FAST_LEVEL)
2463                 size += lcpit_matchfinder_get_needed_memory(max_bufsize);
2464         return size;
2465 }
2466
2467 static int
2468 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2469                       bool destructive, void **c_ret)
2470 {
2471         unsigned window_order;
2472         struct lzx_compressor *c;
2473
2474         window_order = lzx_get_window_order(max_bufsize);
2475         if (window_order == 0)
2476                 return WIMLIB_ERR_INVALID_PARAM;
2477
2478         c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2479         if (!c)
2480                 goto oom0;
2481
2482         c->destructive = destructive;
2483
2484         c->num_main_syms = lzx_get_num_main_syms(window_order);
2485         c->window_order = window_order;
2486
2487         if (!c->destructive) {
2488                 c->in_buffer = MALLOC(max_bufsize);
2489                 if (!c->in_buffer)
2490                         goto oom1;
2491         }
2492
2493         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2494
2495                 /* Fast compression: Use lazy parsing.  */
2496
2497                 if (lzx_is_16_bit(max_bufsize))
2498                         c->impl = lzx_compress_lazy_16;
2499                 else
2500                         c->impl = lzx_compress_lazy_32;
2501                 c->max_search_depth = (60 * compression_level) / 20;
2502                 c->nice_match_length = (80 * compression_level) / 20;
2503
2504                 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2505                  * halves the max_search_depth when attempting a lazy match, and
2506                  * max_search_depth cannot be 0.  */
2507                 if (c->max_search_depth < 2)
2508                         c->max_search_depth = 2;
2509         } else {
2510
2511                 /* Normal / high compression: Use near-optimal parsing.  */
2512
2513                 if (lzx_is_16_bit(max_bufsize))
2514                         c->impl = lzx_compress_near_optimal_16;
2515                 else
2516                         c->impl = lzx_compress_near_optimal_32;
2517
2518                 /* Scale nice_match_length and max_search_depth with the
2519                  * compression level.  */
2520                 c->max_search_depth = (24 * compression_level) / 50;
2521                 c->nice_match_length = (48 * compression_level) / 50;
2522
2523                 /* Set a number of optimization passes appropriate for the
2524                  * compression level.  */
2525
2526                 c->num_optim_passes = 1;
2527
2528                 if (compression_level >= 45)
2529                         c->num_optim_passes++;
2530
2531                 /* Use more optimization passes for higher compression levels.
2532                  * But the more passes there are, the less they help --- so
2533                  * don't add them linearly.  */
2534                 if (compression_level >= 70) {
2535                         c->num_optim_passes++;
2536                         if (compression_level >= 100)
2537                                 c->num_optim_passes++;
2538                         if (compression_level >= 150)
2539                                 c->num_optim_passes++;
2540                         if (compression_level >= 200)
2541                                 c->num_optim_passes++;
2542                         if (compression_level >= 300)
2543                                 c->num_optim_passes++;
2544                 }
2545         }
2546
2547         /* max_search_depth == 0 is invalid.  */
2548         if (c->max_search_depth < 1)
2549                 c->max_search_depth = 1;
2550
2551         if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2552                 c->nice_match_length = LZX_MAX_MATCH_LEN;
2553
2554         if (!lcpit_matchfinder_init(&c->lcpit_mf, max_bufsize,
2555                                     LZX_MIN_MATCH_LEN, c->nice_match_length))
2556                 goto oom2;
2557
2558         lzx_init_offset_slot_tabs(c);
2559         *c_ret = c;
2560         return 0;
2561
2562 oom2:
2563         if (!c->destructive)
2564                 FREE(c->in_buffer);
2565 oom1:
2566         FREE(c);
2567 oom0:
2568         return WIMLIB_ERR_NOMEM;
2569 }
2570
2571 static size_t
2572 lzx_compress(const void *restrict in, size_t in_nbytes,
2573              void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2574 {
2575         struct lzx_compressor *c = _c;
2576         struct lzx_output_bitstream os;
2577         size_t result;
2578
2579         /* Don't bother trying to compress very small inputs.  */
2580         if (in_nbytes < 100)
2581                 return 0;
2582
2583         /* Copy the input data into the internal buffer and preprocess it.  */
2584         if (c->destructive)
2585                 c->in_buffer = (void *)in;
2586         else
2587                 memcpy(c->in_buffer, in, in_nbytes);
2588         c->in_nbytes = in_nbytes;
2589         lzx_preprocess(c->in_buffer, in_nbytes);
2590
2591         /* Initially, the previous Huffman codeword lengths are all zeroes.  */
2592         c->codes_index = 0;
2593         memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2594
2595         /* Initialize the output bitstream.  */
2596         lzx_init_output(&os, out, out_nbytes_avail);
2597
2598         /* Call the compression level-specific compress() function.  */
2599         (*c->impl)(c, &os);
2600
2601         /* Flush the output bitstream and return the compressed size or 0.  */
2602         result = lzx_flush_output(&os);
2603         if (!result && c->destructive)
2604                 lzx_postprocess(c->in_buffer, c->in_nbytes);
2605         return result;
2606 }
2607
2608 static void
2609 lzx_free_compressor(void *_c)
2610 {
2611         struct lzx_compressor *c = _c;
2612
2613         lcpit_matchfinder_destroy(&c->lcpit_mf);
2614         if (!c->destructive)
2615                 FREE(c->in_buffer);
2616         FREE(c);
2617 }
2618
2619 const struct compressor_ops lzx_compressor_ops = {
2620         .get_needed_memory  = lzx_get_needed_memory,
2621         .create_compressor  = lzx_create_compressor,
2622         .compress           = lzx_compress,
2623         .free_compressor    = lzx_free_compressor,
2624 };