Ensure validity of max_search_depth
[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, 2013, 2014, 2015 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  * Start a new LZX block (with new Huffman codes) after this many bytes.
69  *
70  * Note: actual block sizes may slightly exceed this value.
71  *
72  * TODO: recursive splitting and cost evaluation might be good for an extremely
73  * high compression mode, but otherwise it is almost always far too slow for how
74  * much it helps.  Perhaps some sort of heuristic would be useful?
75  */
76 #define LZX_DIV_BLOCK_SIZE      32768
77
78 /*
79  * LZX_CACHE_PER_POS is the number of lz_match structures to reserve in the
80  * match cache for each byte position.  This value should be high enough so that
81  * nearly the time, all matches found in a given block can fit in the match
82  * cache.  However, fallback behavior (immediately terminating the block) on
83  * cache overflow is still required.
84  */
85 #define LZX_CACHE_PER_POS       6
86
87 /*
88  * LZX_CACHE_LENGTH is the number of lz_match structures in the match cache,
89  * excluding the extra "overflow" entries.  The per-position multiplier is '1 +
90  * LZX_CACHE_PER_POS' instead of 'LZX_CACHE_PER_POS' because there is an
91  * overhead of one lz_match per position, used to hold the match count at that
92  * position.
93  */
94 #define LZX_CACHE_LENGTH        (LZX_DIV_BLOCK_SIZE * (1 + LZX_CACHE_PER_POS))
95
96 /*
97  * LZX_MAX_MATCHES_PER_POS is an upper bound on the number of matches that can
98  * ever be saved in the match cache for a single position.  Since each match we
99  * save for a single position has a distinct length, we can use the number of
100  * possible match lengths in LZX as this bound.  This bound is guaranteed to be
101  * valid in all cases, although if 'nice_match_length < LZX_MAX_MATCH_LEN', then
102  * it will never actually be reached.
103  */
104 #define LZX_MAX_MATCHES_PER_POS LZX_NUM_LENS
105
106 /*
107  * LZX_BIT_COST is a scaling factor that represents the cost to output one bit.
108  * THis makes it possible to consider fractional bit costs.
109  *
110  * Note: this is only useful as a statistical trick for when the true costs are
111  * unknown.  In reality, each token in LZX requires a whole number of bits to
112  * output.
113  */
114 #define LZX_BIT_COST            16
115
116 /*
117  * Consideration of aligned offset costs is disabled for now, due to
118  * insufficient benefit gained from the time spent.
119  */
120 #define LZX_CONSIDER_ALIGNED_COSTS      0
121
122 /*
123  * The maximum compression level at which we use the faster algorithm.
124  */
125 #define LZX_MAX_FAST_LEVEL      34
126
127 /*
128  * LZX_HASH2_ORDER is the log base 2 of the number of entries in the hash table
129  * for finding length 2 matches.  This can be as high as 16 (in which case the
130  * hash function is trivial), but using a smaller hash table actually speeds up
131  * compression due to reduced cache pressure.
132  */
133 #define LZX_HASH2_ORDER         12
134 #define LZX_HASH2_LENGTH        (1UL << LZX_HASH2_ORDER)
135
136 #include "wimlib/lzx_common.h"
137
138 /*
139  * The maximum allowed window order for the matchfinder.
140  */
141 #define MATCHFINDER_MAX_WINDOW_ORDER    LZX_MAX_WINDOW_ORDER
142
143 #include <string.h>
144
145 #include "wimlib/bt_matchfinder.h"
146 #include "wimlib/compress_common.h"
147 #include "wimlib/compressor_ops.h"
148 #include "wimlib/endianness.h"
149 #include "wimlib/error.h"
150 #include "wimlib/hc_matchfinder.h"
151 #include "wimlib/lz_extend.h"
152 #include "wimlib/unaligned.h"
153 #include "wimlib/util.h"
154
155 struct lzx_output_bitstream;
156
157 /* Codewords for the LZX Huffman codes.  */
158 struct lzx_codewords {
159         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
160         u32 len[LZX_LENCODE_NUM_SYMBOLS];
161         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
162 };
163
164 /* Codeword lengths (in bits) for the LZX Huffman codes.
165  * A zero length means the corresponding codeword has zero frequency.  */
166 struct lzx_lens {
167         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
168         u8 len[LZX_LENCODE_NUM_SYMBOLS];
169         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
170 };
171
172 /* Cost model for near-optimal parsing  */
173 struct lzx_costs {
174
175         /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
176          * length 'len' match that has an offset belonging to 'offset_slot'.  */
177         u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
178
179         /* Cost for each symbol in the main code  */
180         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
181
182         /* Cost for each symbol in the length code  */
183         u32 len[LZX_LENCODE_NUM_SYMBOLS];
184
185 #if LZX_CONSIDER_ALIGNED_COSTS
186         /* Cost for each symbol in the aligned code  */
187         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
188 #endif
189 };
190
191 /* Codewords and lengths for the LZX Huffman codes.  */
192 struct lzx_codes {
193         struct lzx_codewords codewords;
194         struct lzx_lens lens;
195 };
196
197 /* Symbol frequency counters for the LZX Huffman codes.  */
198 struct lzx_freqs {
199         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
200         u32 len[LZX_LENCODE_NUM_SYMBOLS];
201         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
202 };
203
204 /* Intermediate LZX match/literal format  */
205 struct lzx_item {
206
207         /* Bits 0  -  9: Main symbol
208          * Bits 10 - 17: Length symbol
209          * Bits 18 - 22: Number of extra offset bits
210          * Bits 23+    : Extra offset bits  */
211         u64 data;
212 };
213
214 /*
215  * This structure represents a byte position in the input buffer and a node in
216  * the graph of possible match/literal choices.
217  *
218  * Logically, each incoming edge to this node is labeled with a literal or a
219  * match that can be taken to reach this position from an earlier position; and
220  * each outgoing edge from this node is labeled with a literal or a match that
221  * can be taken to advance from this position to a later position.
222  */
223 struct lzx_optimum_node {
224
225         /* The cost, in bits, of the lowest-cost path that has been found to
226          * reach this position.  This can change as progressively lower cost
227          * paths are found to reach this position.  */
228         u32 cost;
229
230         /*
231          * The match or literal that was taken to reach this position.  This can
232          * change as progressively lower cost paths are found to reach this
233          * position.
234          *
235          * This variable is divided into two bitfields.
236          *
237          * Literals:
238          *      Low bits are 1, high bits are the literal.
239          *
240          * Explicit offset matches:
241          *      Low bits are the match length, high bits are the offset plus 2.
242          *
243          * Repeat offset matches:
244          *      Low bits are the match length, high bits are the queue index.
245          */
246         u32 item;
247 #define OPTIMUM_OFFSET_SHIFT 9
248 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
249 } _aligned_attribute(8);
250
251 /*
252  * Least-recently-used queue for match offsets.
253  *
254  * This is represented as a 64-bit integer for efficiency.  There are three
255  * offsets of 21 bits each.  Bit 64 is garbage.
256  */
257 struct lzx_lru_queue {
258         u64 R;
259 };
260
261 #define LZX_QUEUE64_OFFSET_SHIFT 21
262 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
263
264 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
265 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
266 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
267
268 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
269 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
270 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
271
272 static inline void
273 lzx_lru_queue_init(struct lzx_lru_queue *queue)
274 {
275         queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
276                    ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
277                    ((u64)1 << LZX_QUEUE64_R2_SHIFT);
278 }
279
280 static inline u64
281 lzx_lru_queue_R0(struct lzx_lru_queue queue)
282 {
283         return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
284 }
285
286 static inline u64
287 lzx_lru_queue_R1(struct lzx_lru_queue queue)
288 {
289         return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
290 }
291
292 static inline u64
293 lzx_lru_queue_R2(struct lzx_lru_queue queue)
294 {
295         return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
296 }
297
298 /* Push a match offset onto the front (most recently used) end of the queue.  */
299 static inline struct lzx_lru_queue
300 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
301 {
302         return (struct lzx_lru_queue) {
303                 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
304         };
305 }
306
307 /* Pop a match offset off the front (most recently used) end of the queue.  */
308 static inline u32
309 lzx_lru_queue_pop(struct lzx_lru_queue *queue_p)
310 {
311         u32 offset = queue_p->R & LZX_QUEUE64_OFFSET_MASK;
312         queue_p->R >>= LZX_QUEUE64_OFFSET_SHIFT;
313         return offset;
314 }
315
316 /* Swap a match offset to the front of the queue.  */
317 static inline struct lzx_lru_queue
318 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
319 {
320         if (idx == 0)
321                 return queue;
322
323         if (idx == 1)
324                 return (struct lzx_lru_queue) {
325                         .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
326                              (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
327                              (queue.R & LZX_QUEUE64_R2_MASK),
328                 };
329
330         return (struct lzx_lru_queue) {
331                 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
332                      (queue.R & LZX_QUEUE64_R1_MASK) |
333                      (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
334         };
335 }
336
337 /* The main LZX compressor structure  */
338 struct lzx_compressor {
339
340         /* The "nice" match length: if a match of this length is found, then
341          * choose it immediately without further consideration.  */
342         unsigned nice_match_length;
343
344         /* The maximum search depth: consider at most this many potential
345          * matches at each position.  */
346         unsigned max_search_depth;
347
348         /* The log base 2 of the LZX window size for LZ match offset encoding
349          * purposes.  This will be >= LZX_MIN_WINDOW_ORDER and <=
350          * LZX_MAX_WINDOW_ORDER.  */
351         unsigned window_order;
352
353         /* The number of symbols in the main alphabet.  This depends on
354          * @window_order, since @window_order determines the maximum possible
355          * offset.  */
356         unsigned num_main_syms;
357
358         /* Number of optimization passes per block  */
359         unsigned num_optim_passes;
360
361         /* The preprocessed buffer of data being compressed  */
362         u8 *in_buffer;
363
364         /* The number of bytes of data to be compressed, which is the number of
365          * bytes of data in @in_buffer that are actually valid.  */
366         size_t in_nbytes;
367
368         /* Pointer to the compress() implementation chosen at allocation time */
369         void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
370
371         /* The Huffman symbol frequency counters for the current block.  */
372         struct lzx_freqs freqs;
373
374         /* The Huffman codes for the current and previous blocks.  The one with
375          * index 'codes_index' is for the current block, and the other one is
376          * for the previous block.  */
377         struct lzx_codes codes[2];
378         unsigned codes_index;
379
380         /*
381          * The match/literal sequence the algorithm chose for the current block.
382          *
383          * Notes on how large this array actually needs to be:
384          *
385          * - In lzx_compress_near_optimal(), the maximum block size is
386          *   'LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1' bytes.  This occurs if
387          *   a match of the maximum length is found on the last byte.  Although
388          *   it is impossible for this particular case to actually result in a
389          *   parse of all literals, we reserve this many spaces anyway.
390          *
391          * - The worst case for lzx_compress_lazy() is a block of almost all
392          *   literals that ends with a series of matches of increasing scores,
393          *   causing a sequence of literals to be chosen before the last match
394          *   is finally chosen.  The number of items actually chosen in this
395          *   scenario is limited by the number of distinct match scores that
396          *   exist for matches shorter than 'nice_match_length'.  Having
397          *   'LZX_MAX_MATCH_LEN - 1' extra spaces is plenty for now.
398          */
399         struct lzx_item chosen_items[LZX_DIV_BLOCK_SIZE + LZX_MAX_MATCH_LEN - 1];
400
401         /* Table mapping match offset => offset slot for small offsets  */
402 #define LZX_NUM_FAST_OFFSETS 32768
403         u8 offset_slot_fast[LZX_NUM_FAST_OFFSETS];
404
405         union {
406                 /* Data for greedy or lazy parsing  */
407                 struct {
408                         /* Hash chains matchfinder (MUST BE LAST!!!)  */
409                         struct hc_matchfinder hc_mf;
410                 };
411
412                 /* Data for near-optimal parsing  */
413                 struct {
414                         /*
415                          * The graph nodes for the current block.
416                          *
417                          * We need at least 'LZX_DIV_BLOCK_SIZE +
418                          * LZX_MAX_MATCH_LEN - 1' nodes because that is the
419                          * maximum block size that may be used.  Add 1 because
420                          * we need a node to represent end-of-block.
421                          *
422                          * It is possible that nodes past end-of-block are
423                          * accessed during match consideration, but this can
424                          * only occur if the block was truncated at
425                          * LZX_DIV_BLOCK_SIZE.  So the same bound still applies.
426                          * Note that since nodes past the end of the block will
427                          * never actually have an effect on the items that are
428                          * chosen for the block, it makes no difference what
429                          * their costs are initialized to (if anything).
430                          */
431                         struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
432                                                               LZX_MAX_MATCH_LEN - 1 + 1];
433
434                         /* The cost model for the current block  */
435                         struct lzx_costs costs;
436
437                         /*
438                          * Cached matches for the current block.  This array
439                          * contains the matches that were found at each position
440                          * in the block.  Specifically, for each position, there
441                          * is a special 'struct lz_match' whose 'length' field
442                          * contains the number of matches that were found at
443                          * that position; this is followed by the matches
444                          * themselves, if any, sorted by strictly increasing
445                          * length and strictly increasing offset.
446                          *
447                          * Note: in rare cases, there will be a very high number
448                          * of matches in the block and this array will overflow.
449                          * If this happens, we force the end of the current
450                          * block.  LZX_CACHE_LENGTH is the length at which we
451                          * actually check for overflow.  The extra slots beyond
452                          * this are enough to absorb the worst case overflow,
453                          * which occurs if starting at
454                          * &match_cache[LZX_CACHE_LENGTH - 1], we write the
455                          * match count header, then write
456                          * LZX_MAX_MATCHES_PER_POS matches, then skip searching
457                          * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
458                          * write the match count header for each.
459                          */
460                         struct lz_match match_cache[LZX_CACHE_LENGTH +
461                                                     LZX_MAX_MATCHES_PER_POS +
462                                                     LZX_MAX_MATCH_LEN - 1];
463
464                         /* Hash table for finding length 2 matches  */
465                         pos_t hash2_tab[LZX_HASH2_LENGTH]
466                                 _aligned_attribute(MATCHFINDER_ALIGNMENT);
467
468                         /* Binary trees matchfinder (MUST BE LAST!!!)  */
469                         struct bt_matchfinder bt_mf;
470                 };
471         };
472 };
473
474 /* Compute a hash value for the next 2 bytes of uncompressed data.  */
475 static inline u32
476 lz_hash_2_bytes(const u8 *in_next)
477 {
478         u16 next_2_bytes = load_u16_unaligned(in_next);
479         if (LZX_HASH2_ORDER == 16)
480                 return next_2_bytes;
481         else
482                 return lz_hash(next_2_bytes, LZX_HASH2_ORDER);
483 }
484
485 /*
486  * Structure to keep track of the current state of sending bits to the
487  * compressed output buffer.
488  *
489  * The LZX bitstream is encoded as a sequence of 16-bit coding units.
490  */
491 struct lzx_output_bitstream {
492
493         /* Bits that haven't yet been written to the output buffer.  */
494         u32 bitbuf;
495
496         /* Number of bits currently held in @bitbuf.  */
497         u32 bitcount;
498
499         /* Pointer to the start of the output buffer.  */
500         le16 *start;
501
502         /* Pointer to the position in the output buffer at which the next coding
503          * unit should be written.  */
504         le16 *next;
505
506         /* Pointer past the end of the output buffer.  */
507         le16 *end;
508 };
509
510 /*
511  * Initialize the output bitstream.
512  *
513  * @os
514  *      The output bitstream structure to initialize.
515  * @buffer
516  *      The buffer being written to.
517  * @size
518  *      Size of @buffer, in bytes.
519  */
520 static void
521 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
522 {
523         os->bitbuf = 0;
524         os->bitcount = 0;
525         os->start = buffer;
526         os->next = os->start;
527         os->end = os->start + size / sizeof(le16);
528 }
529
530 /*
531  * Write some bits to the output bitstream.
532  *
533  * The bits are given by the low-order @num_bits bits of @bits.  Higher-order
534  * bits in @bits cannot be set.  At most 17 bits can be written at once.
535  *
536  * @max_num_bits is a compile-time constant that specifies the maximum number of
537  * bits that can ever be written at the call site.  Currently, it is used to
538  * optimize away the conditional code for writing a second 16-bit coding unit
539  * when writing fewer than 17 bits.
540  *
541  * If the output buffer space is exhausted, then the bits will be ignored, and
542  * lzx_flush_output() will return 0 when it gets called.
543  */
544 static inline void
545 lzx_write_varbits(struct lzx_output_bitstream *os,
546                   const u32 bits, const unsigned num_bits,
547                   const unsigned max_num_bits)
548 {
549         /* This code is optimized for LZX, which never needs to write more than
550          * 17 bits at once.  */
551         LZX_ASSERT(num_bits <= 17);
552         LZX_ASSERT(num_bits <= max_num_bits);
553         LZX_ASSERT(os->bitcount <= 15);
554
555         /* Add the bits to the bit buffer variable.  @bitcount will be at most
556          * 15, so there will be just enough space for the maximum possible
557          * @num_bits of 17.  */
558         os->bitcount += num_bits;
559         os->bitbuf = (os->bitbuf << num_bits) | bits;
560
561         /* Check whether any coding units need to be written.  */
562         if (os->bitcount >= 16) {
563
564                 os->bitcount -= 16;
565
566                 /* Write a coding unit, unless it would overflow the buffer.  */
567                 if (os->next != os->end)
568                         put_unaligned_u16_le(os->bitbuf >> os->bitcount, os->next++);
569
570                 /* If writing 17 bits, a second coding unit might need to be
571                  * written.  But because 'max_num_bits' is a compile-time
572                  * constant, the compiler will optimize away this code at most
573                  * call sites.  */
574                 if (max_num_bits == 17 && os->bitcount == 16) {
575                         if (os->next != os->end)
576                                 put_unaligned_u16_le(os->bitbuf, os->next++);
577                         os->bitcount = 0;
578                 }
579         }
580 }
581
582 /* Use when @num_bits is a compile-time constant.  Otherwise use
583  * lzx_write_varbits().  */
584 static inline void
585 lzx_write_bits(struct lzx_output_bitstream *os,
586                const u32 bits, const unsigned num_bits)
587 {
588         lzx_write_varbits(os, bits, num_bits, num_bits);
589 }
590
591 /*
592  * Flush the last coding unit to the output buffer if needed.  Return the total
593  * number of bytes written to the output buffer, or 0 if an overflow occurred.
594  */
595 static u32
596 lzx_flush_output(struct lzx_output_bitstream *os)
597 {
598         if (os->next == os->end)
599                 return 0;
600
601         if (os->bitcount != 0)
602                 put_unaligned_u16_le(os->bitbuf << (16 - os->bitcount), os->next++);
603
604         return (const u8 *)os->next - (const u8 *)os->start;
605 }
606
607 /* Build the main, length, and aligned offset Huffman codes used in LZX.
608  *
609  * This takes as input the frequency tables for each code and produces as output
610  * a set of tables that map symbols to codewords and codeword lengths.  */
611 static void
612 lzx_make_huffman_codes(struct lzx_compressor *c)
613 {
614         const struct lzx_freqs *freqs = &c->freqs;
615         struct lzx_codes *codes = &c->codes[c->codes_index];
616
617         make_canonical_huffman_code(c->num_main_syms,
618                                     LZX_MAX_MAIN_CODEWORD_LEN,
619                                     freqs->main,
620                                     codes->lens.main,
621                                     codes->codewords.main);
622
623         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
624                                     LZX_MAX_LEN_CODEWORD_LEN,
625                                     freqs->len,
626                                     codes->lens.len,
627                                     codes->codewords.len);
628
629         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
630                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
631                                     freqs->aligned,
632                                     codes->lens.aligned,
633                                     codes->codewords.aligned);
634 }
635
636 /* Reset the symbol frequencies for the LZX Huffman codes.  */
637 static void
638 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
639 {
640         memset(&c->freqs, 0, sizeof(c->freqs));
641 }
642
643 static unsigned
644 lzx_compute_precode_items(const u8 lens[restrict],
645                           const u8 prev_lens[restrict],
646                           const unsigned num_lens,
647                           u32 precode_freqs[restrict],
648                           unsigned precode_items[restrict])
649 {
650         unsigned *itemptr;
651         unsigned run_start;
652         unsigned run_end;
653         unsigned extra_bits;
654         int delta;
655         u8 len;
656
657         itemptr = precode_items;
658         run_start = 0;
659         do {
660                 /* Find the next run of codeword lengths.  */
661
662                 /* len = the length being repeated  */
663                 len = lens[run_start];
664
665                 run_end = run_start + 1;
666
667                 /* Fast case for a single length.  */
668                 if (likely(run_end == num_lens || len != lens[run_end])) {
669                         delta = prev_lens[run_start] - len;
670                         if (delta < 0)
671                                 delta += 17;
672                         precode_freqs[delta]++;
673                         *itemptr++ = delta;
674                         run_start++;
675                         continue;
676                 }
677
678                 /* Extend the run.  */
679                 do {
680                         run_end++;
681                 } while (run_end != num_lens && len == lens[run_end]);
682
683                 if (len == 0) {
684                         /* Run of zeroes.  */
685
686                         /* Symbol 18: RLE 20 to 51 zeroes at a time.  */
687                         while ((run_end - run_start) >= 20) {
688                                 extra_bits = min((run_end - run_start) - 20, 0x1f);
689                                 precode_freqs[18]++;
690                                 *itemptr++ = 18 | (extra_bits << 5);
691                                 run_start += 20 + extra_bits;
692                         }
693
694                         /* Symbol 17: RLE 4 to 19 zeroes at a time.  */
695                         if ((run_end - run_start) >= 4) {
696                                 extra_bits = min((run_end - run_start) - 4, 0xf);
697                                 precode_freqs[17]++;
698                                 *itemptr++ = 17 | (extra_bits << 5);
699                                 run_start += 4 + extra_bits;
700                         }
701                 } else {
702
703                         /* A run of nonzero lengths. */
704
705                         /* Symbol 19: RLE 4 to 5 of any length at a time.  */
706                         while ((run_end - run_start) >= 4) {
707                                 extra_bits = (run_end - run_start) > 4;
708                                 delta = prev_lens[run_start] - len;
709                                 if (delta < 0)
710                                         delta += 17;
711                                 precode_freqs[19]++;
712                                 precode_freqs[delta]++;
713                                 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
714                                 run_start += 4 + extra_bits;
715                         }
716                 }
717
718                 /* Output any remaining lengths without RLE.  */
719                 while (run_start != run_end) {
720                         delta = prev_lens[run_start] - len;
721                         if (delta < 0)
722                                 delta += 17;
723                         precode_freqs[delta]++;
724                         *itemptr++ = delta;
725                         run_start++;
726                 }
727         } while (run_start != num_lens);
728
729         return itemptr - precode_items;
730 }
731
732 /*
733  * Output a Huffman code in the compressed form used in LZX.
734  *
735  * The Huffman code is represented in the output as a logical series of codeword
736  * lengths from which the Huffman code, which must be in canonical form, can be
737  * reconstructed.
738  *
739  * The codeword lengths are themselves compressed using a separate Huffman code,
740  * the "precode", which contains a symbol for each possible codeword length in
741  * the larger code as well as several special symbols to represent repeated
742  * codeword lengths (a form of run-length encoding).  The precode is itself
743  * constructed in canonical form, and its codeword lengths are represented
744  * literally in 20 4-bit fields that immediately precede the compressed codeword
745  * lengths of the larger code.
746  *
747  * Furthermore, the codeword lengths of the larger code are actually represented
748  * as deltas from the codeword lengths of the corresponding code in the previous
749  * block.
750  *
751  * @os:
752  *      Bitstream to which to write the compressed Huffman code.
753  * @lens:
754  *      The codeword lengths, indexed by symbol, in the Huffman code.
755  * @prev_lens:
756  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
757  *      code in the previous block, or all zeroes if this is the first block.
758  * @num_lens:
759  *      The number of symbols in the Huffman code.
760  */
761 static void
762 lzx_write_compressed_code(struct lzx_output_bitstream *os,
763                           const u8 lens[restrict],
764                           const u8 prev_lens[restrict],
765                           unsigned num_lens)
766 {
767         u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
768         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
769         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
770         unsigned precode_items[num_lens];
771         unsigned num_precode_items;
772         unsigned precode_item;
773         unsigned precode_sym;
774         unsigned i;
775
776         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
777                 precode_freqs[i] = 0;
778
779         /* Compute the "items" (RLE / literal tokens and extra bits) with which
780          * the codeword lengths in the larger code will be output.  */
781         num_precode_items = lzx_compute_precode_items(lens,
782                                                       prev_lens,
783                                                       num_lens,
784                                                       precode_freqs,
785                                                       precode_items);
786
787         /* Build the precode.  */
788         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
789                                     LZX_MAX_PRE_CODEWORD_LEN,
790                                     precode_freqs, precode_lens,
791                                     precode_codewords);
792
793         /* Output the lengths of the codewords in the precode.  */
794         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
795                 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
796
797         /* Output the encoded lengths of the codewords in the larger code.  */
798         for (i = 0; i < num_precode_items; i++) {
799                 precode_item = precode_items[i];
800                 precode_sym = precode_item & 0x1F;
801                 lzx_write_varbits(os, precode_codewords[precode_sym],
802                                   precode_lens[precode_sym],
803                                   LZX_MAX_PRE_CODEWORD_LEN);
804                 if (precode_sym >= 17) {
805                         if (precode_sym == 17) {
806                                 lzx_write_bits(os, precode_item >> 5, 4);
807                         } else if (precode_sym == 18) {
808                                 lzx_write_bits(os, precode_item >> 5, 5);
809                         } else {
810                                 lzx_write_bits(os, (precode_item >> 5) & 1, 1);
811                                 precode_sym = precode_item >> 6;
812                                 lzx_write_varbits(os, precode_codewords[precode_sym],
813                                                   precode_lens[precode_sym],
814                                                   LZX_MAX_PRE_CODEWORD_LEN);
815                         }
816                 }
817         }
818 }
819
820 /* Output a match or literal.  */
821 static inline void
822 lzx_write_item(struct lzx_output_bitstream *os, struct lzx_item item,
823                unsigned ones_if_aligned, const struct lzx_codes *codes)
824 {
825         u64 data = item.data;
826         unsigned main_symbol;
827         unsigned len_symbol;
828         unsigned num_extra_bits;
829         u32 extra_bits;
830
831         main_symbol = data & 0x3FF;
832
833         lzx_write_varbits(os, codes->codewords.main[main_symbol],
834                           codes->lens.main[main_symbol],
835                           LZX_MAX_MAIN_CODEWORD_LEN);
836
837         if (main_symbol < LZX_NUM_CHARS)  /* Literal?  */
838                 return;
839
840         len_symbol = (data >> 10) & 0xFF;
841
842         if (len_symbol != LZX_LENCODE_NUM_SYMBOLS) {
843                 lzx_write_varbits(os, codes->codewords.len[len_symbol],
844                                   codes->lens.len[len_symbol],
845                                   LZX_MAX_LEN_CODEWORD_LEN);
846         }
847
848         num_extra_bits = (data >> 18) & 0x1F;
849         if (num_extra_bits == 0)  /* Small offset or repeat offset match?  */
850                 return;
851
852         extra_bits = data >> 23;
853
854         if ((num_extra_bits & ones_if_aligned) >= LZX_NUM_ALIGNED_OFFSET_BITS) {
855
856                 /* Aligned offset blocks: The low 3 bits of the extra offset
857                  * bits are Huffman-encoded using the aligned offset code.  The
858                  * remaining bits are output literally.  */
859
860                 lzx_write_varbits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
861                                   num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS,
862                                   17 - LZX_NUM_ALIGNED_OFFSET_BITS);
863
864                 lzx_write_varbits(os,
865                                   codes->codewords.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
866                                   codes->lens.aligned[extra_bits & LZX_ALIGNED_OFFSET_BITMASK],
867                                   LZX_MAX_ALIGNED_CODEWORD_LEN);
868         } else {
869                 /* Verbatim blocks, or fewer than 3 extra bits:  All extra
870                  * offset bits are output literally.  */
871                 lzx_write_varbits(os, extra_bits, num_extra_bits, 17);
872         }
873 }
874
875 /*
876  * Write all matches and literal bytes (which were precomputed) in an LZX
877  * compressed block to the output bitstream in the final compressed
878  * representation.
879  *
880  * @os
881  *      The output bitstream.
882  * @block_type
883  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
884  *      LZX_BLOCKTYPE_VERBATIM).
885  * @items
886  *      The array of matches/literals to output.
887  * @num_items
888  *      Number of matches/literals to output (length of @items).
889  * @codes
890  *      The main, length, and aligned offset Huffman codes for the current
891  *      LZX compressed block.
892  */
893 static void
894 lzx_write_items(struct lzx_output_bitstream *os, int block_type,
895                 const struct lzx_item items[], u32 num_items,
896                 const struct lzx_codes *codes)
897 {
898         unsigned ones_if_aligned = 0U - (block_type == LZX_BLOCKTYPE_ALIGNED);
899
900         for (u32 i = 0; i < num_items; i++)
901                 lzx_write_item(os, items[i], ones_if_aligned, codes);
902 }
903
904 static void
905 lzx_write_compressed_block(int block_type,
906                            u32 block_size,
907                            unsigned window_order,
908                            unsigned num_main_syms,
909                            const struct lzx_item chosen_items[],
910                            u32 num_chosen_items,
911                            const struct lzx_codes * codes,
912                            const struct lzx_lens * prev_lens,
913                            struct lzx_output_bitstream * os)
914 {
915         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
916                    block_type == LZX_BLOCKTYPE_VERBATIM);
917
918         /* The first three bits indicate the type of block and are one of the
919          * LZX_BLOCKTYPE_* constants.  */
920         lzx_write_bits(os, block_type, 3);
921
922         /* Output the block size.
923          *
924          * The original LZX format seemed to always encode the block size in 3
925          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
926          * uses the first bit to indicate whether the block is the default size
927          * (32768) or a different size given explicitly by the next 16 bits.
928          *
929          * By default, this compressor uses a window size of 32768 and therefore
930          * follows the WIMGAPI behavior.  However, this compressor also supports
931          * window sizes greater than 32768 bytes, which do not appear to be
932          * supported by WIMGAPI.  In such cases, we retain the default size bit
933          * to mean a size of 32768 bytes but output non-default block size in 24
934          * bits rather than 16.  The compatibility of this behavior is unknown
935          * because WIMs created with chunk size greater than 32768 can seemingly
936          * only be opened by wimlib anyway.  */
937         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
938                 lzx_write_bits(os, 1, 1);
939         } else {
940                 lzx_write_bits(os, 0, 1);
941
942                 if (window_order >= 16)
943                         lzx_write_bits(os, block_size >> 16, 8);
944
945                 lzx_write_bits(os, block_size & 0xFFFF, 16);
946         }
947
948         /* If it's an aligned offset block, output the aligned offset code.  */
949         if (block_type == LZX_BLOCKTYPE_ALIGNED) {
950                 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
951                         lzx_write_bits(os, codes->lens.aligned[i],
952                                        LZX_ALIGNEDCODE_ELEMENT_SIZE);
953                 }
954         }
955
956         /* Output the main code (two parts).  */
957         lzx_write_compressed_code(os, codes->lens.main,
958                                   prev_lens->main,
959                                   LZX_NUM_CHARS);
960         lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
961                                   prev_lens->main + LZX_NUM_CHARS,
962                                   num_main_syms - LZX_NUM_CHARS);
963
964         /* Output the length code.  */
965         lzx_write_compressed_code(os, codes->lens.len,
966                                   prev_lens->len,
967                                   LZX_LENCODE_NUM_SYMBOLS);
968
969         /* Output the compressed matches and literals.  */
970         lzx_write_items(os, block_type, chosen_items, num_chosen_items, codes);
971 }
972
973 /* Given the frequencies of symbols in an LZX-compressed block and the
974  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
975  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
976  * will take fewer bits to output.  */
977 static int
978 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
979                                const struct lzx_codes * codes)
980 {
981         u32 aligned_cost = 0;
982         u32 verbatim_cost = 0;
983
984         /* A verbatim block requires 3 bits in each place that an aligned symbol
985          * would be used in an aligned offset block.  */
986         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
987                 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
988                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
989         }
990
991         /* Account for output of the aligned offset code.  */
992         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
993
994         if (aligned_cost < verbatim_cost)
995                 return LZX_BLOCKTYPE_ALIGNED;
996         else
997                 return LZX_BLOCKTYPE_VERBATIM;
998 }
999
1000 /*
1001  * Finish an LZX block:
1002  *
1003  * - build the Huffman codes
1004  * - decide whether to output the block as VERBATIM or ALIGNED
1005  * - output the block
1006  * - swap the indices of the current and previous Huffman codes
1007  */
1008 static void
1009 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1010                  u32 block_size, u32 num_chosen_items)
1011 {
1012         int block_type;
1013
1014         lzx_make_huffman_codes(c);
1015
1016         block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1017                                                     &c->codes[c->codes_index]);
1018         lzx_write_compressed_block(block_type,
1019                                    block_size,
1020                                    c->window_order,
1021                                    c->num_main_syms,
1022                                    c->chosen_items,
1023                                    num_chosen_items,
1024                                    &c->codes[c->codes_index],
1025                                    &c->codes[c->codes_index ^ 1].lens,
1026                                    os);
1027         c->codes_index ^= 1;
1028 }
1029
1030 /* Return the offset slot for the specified offset, which must be
1031  * less than LZX_NUM_FAST_OFFSETS.  */
1032 static inline unsigned
1033 lzx_get_offset_slot_fast(struct lzx_compressor *c, u32 offset)
1034 {
1035         LZX_ASSERT(offset < LZX_NUM_FAST_OFFSETS);
1036         return c->offset_slot_fast[offset];
1037 }
1038
1039 /* Tally, and optionally record, the specified literal byte.  */
1040 static inline void
1041 lzx_declare_literal(struct lzx_compressor *c, unsigned literal,
1042                     struct lzx_item **next_chosen_item)
1043 {
1044         unsigned main_symbol = lzx_main_symbol_for_literal(literal);
1045
1046         c->freqs.main[main_symbol]++;
1047
1048         if (next_chosen_item) {
1049                 *(*next_chosen_item)++ = (struct lzx_item) {
1050                         .data = main_symbol,
1051                 };
1052         }
1053 }
1054
1055 /* Tally, and optionally record, the specified repeat offset match.  */
1056 static inline void
1057 lzx_declare_repeat_offset_match(struct lzx_compressor *c,
1058                                 unsigned len, unsigned rep_index,
1059                                 struct lzx_item **next_chosen_item)
1060 {
1061         unsigned len_header;
1062         unsigned len_symbol;
1063         unsigned main_symbol;
1064
1065         if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1066                 len_header = len - LZX_MIN_MATCH_LEN;
1067                 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1068         } else {
1069                 len_header = LZX_NUM_PRIMARY_LENS;
1070                 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1071                 c->freqs.len[len_symbol]++;
1072         }
1073
1074         main_symbol = lzx_main_symbol_for_match(rep_index, len_header);
1075
1076         c->freqs.main[main_symbol]++;
1077
1078         if (next_chosen_item) {
1079                 *(*next_chosen_item)++ = (struct lzx_item) {
1080                         .data = (u64)main_symbol | ((u64)len_symbol << 10),
1081                 };
1082         }
1083 }
1084
1085 /* Tally, and optionally record, the specified explicit offset match.  */
1086 static inline void
1087 lzx_declare_explicit_offset_match(struct lzx_compressor *c, unsigned len, u32 offset,
1088                                   struct lzx_item **next_chosen_item)
1089 {
1090         unsigned len_header;
1091         unsigned len_symbol;
1092         unsigned main_symbol;
1093         unsigned offset_slot;
1094         unsigned num_extra_bits;
1095         u32 extra_bits;
1096
1097         if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1098                 len_header = len - LZX_MIN_MATCH_LEN;
1099                 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1100         } else {
1101                 len_header = LZX_NUM_PRIMARY_LENS;
1102                 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1103                 c->freqs.len[len_symbol]++;
1104         }
1105
1106         offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1107                         lzx_get_offset_slot_fast(c, offset) :
1108                         lzx_get_offset_slot(offset);
1109
1110         main_symbol = lzx_main_symbol_for_match(offset_slot, len_header);
1111
1112         c->freqs.main[main_symbol]++;
1113
1114         num_extra_bits = lzx_extra_offset_bits[offset_slot];
1115
1116         if (num_extra_bits >= LZX_NUM_ALIGNED_OFFSET_BITS)
1117                 c->freqs.aligned[(offset + LZX_OFFSET_ADJUSTMENT) &
1118                                  LZX_ALIGNED_OFFSET_BITMASK]++;
1119
1120         if (next_chosen_item) {
1121
1122                 extra_bits = (offset + LZX_OFFSET_ADJUSTMENT) -
1123                              lzx_offset_slot_base[offset_slot];
1124
1125                 BUILD_BUG_ON(LZX_MAINCODE_MAX_NUM_SYMBOLS > (1 << 10));
1126                 BUILD_BUG_ON(LZX_LENCODE_NUM_SYMBOLS > (1 << 8));
1127                 *(*next_chosen_item)++ = (struct lzx_item) {
1128                         .data = (u64)main_symbol |
1129                                 ((u64)len_symbol << 10) |
1130                                 ((u64)num_extra_bits << 18) |
1131                                 ((u64)extra_bits << 23),
1132                 };
1133         }
1134 }
1135
1136
1137 /* Tally, and optionally record, the specified match or literal.  */
1138 static inline void
1139 lzx_declare_item(struct lzx_compressor *c, u32 item,
1140                  struct lzx_item **next_chosen_item)
1141 {
1142         u32 len = item & OPTIMUM_LEN_MASK;
1143         u32 offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1144
1145         if (len == 1)
1146                 lzx_declare_literal(c, offset_data, next_chosen_item);
1147         else if (offset_data < LZX_NUM_RECENT_OFFSETS)
1148                 lzx_declare_repeat_offset_match(c, len, offset_data,
1149                                                 next_chosen_item);
1150         else
1151                 lzx_declare_explicit_offset_match(c, len,
1152                                                   offset_data - LZX_OFFSET_ADJUSTMENT,
1153                                                   next_chosen_item);
1154 }
1155
1156 static inline void
1157 lzx_record_item_list(struct lzx_compressor *c,
1158                      struct lzx_optimum_node *cur_node,
1159                      struct lzx_item **next_chosen_item)
1160 {
1161         struct lzx_optimum_node *end_node;
1162         u32 saved_item;
1163         u32 item;
1164
1165         /* The list is currently in reverse order (last item to first item).
1166          * Reverse it.  */
1167         end_node = cur_node;
1168         saved_item = cur_node->item;
1169         do {
1170                 item = saved_item;
1171                 cur_node -= item & OPTIMUM_LEN_MASK;
1172                 saved_item = cur_node->item;
1173                 cur_node->item = item;
1174         } while (cur_node != c->optimum_nodes);
1175
1176         /* Walk the list of items from beginning to end, tallying and recording
1177          * each item.  */
1178         do {
1179                 lzx_declare_item(c, cur_node->item, next_chosen_item);
1180                 cur_node += (cur_node->item) & OPTIMUM_LEN_MASK;
1181         } while (cur_node != end_node);
1182 }
1183
1184 static inline void
1185 lzx_tally_item_list(struct lzx_compressor *c, struct lzx_optimum_node *cur_node)
1186 {
1187         /* Since we're just tallying the items, we don't need to reverse the
1188          * list.  Processing the items in reverse order is fine.  */
1189         do {
1190                 lzx_declare_item(c, cur_node->item, NULL);
1191                 cur_node -= (cur_node->item & OPTIMUM_LEN_MASK);
1192         } while (cur_node != c->optimum_nodes);
1193 }
1194
1195 /*
1196  * Find an inexpensive path through the graph of possible match/literal choices
1197  * for the current block.  The nodes of the graph are
1198  * c->optimum_nodes[0...block_size].  They correspond directly to the bytes in
1199  * the current block, plus one extra node for end-of-block.  The edges of the
1200  * graph are matches and literals.  The goal is to find the minimum cost path
1201  * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1202  *
1203  * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1204  * proceeding forwards one node at a time.  At each node, a selection of matches
1205  * (len >= 2), as well as the literal byte (len = 1), is considered.  An item of
1206  * length 'len' provides a new path to reach the node 'len' bytes later.  If
1207  * such a path is the lowest cost found so far to reach that later node, then
1208  * that later node is updated with the new path.
1209  *
1210  * Note that although this algorithm is based on minimum cost path search, due
1211  * to various simplifying assumptions the result is not guaranteed to be the
1212  * true minimum cost, or "optimal", path over the graph of all valid LZX
1213  * representations of this block.
1214  *
1215  * Also, note that because of the presence of the recent offsets queue (which is
1216  * a type of adaptive state), the algorithm cannot work backwards and compute
1217  * "cost to end" instead of "cost to beginning".  Furthermore, the way the
1218  * algorithm handles this adaptive state in the "minimum-cost" parse is actually
1219  * only an approximation.  It's possible for the globally optimal, minimum cost
1220  * path to contain a prefix, ending at a position, where that path prefix is
1221  * *not* the minimum cost path to that position.  This can happen if such a path
1222  * prefix results in a different adaptive state which results in lower costs
1223  * later.  The algorithm does not solve this problem; it only considers the
1224  * lowest cost to reach each individual position.
1225  */
1226 static struct lzx_lru_queue
1227 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1228                        const u8 * const restrict block_begin,
1229                        const u32 block_size,
1230                        const struct lzx_lru_queue initial_queue)
1231 {
1232         struct lzx_optimum_node *cur_node = c->optimum_nodes;
1233         struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1234         struct lz_match *cache_ptr = c->match_cache;
1235         const u8 *in_next = block_begin;
1236         const u8 * const block_end = block_begin + block_size;
1237
1238         /* Instead of storing the match offset LRU queues in the
1239          * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1240          * storing them in a smaller array.  This works because the algorithm
1241          * only requires a limited history of the adaptive state.  Once a given
1242          * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1243          * it is no longer needed.  */
1244         struct lzx_lru_queue queues[512];
1245
1246         BUILD_BUG_ON(ARRAY_LEN(queues) < LZX_MAX_MATCH_LEN + 1);
1247 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1248
1249         /* Initially, the cost to reach each node is "infinity".  */
1250         memset(c->optimum_nodes, 0xFF,
1251                (block_size + 1) * sizeof(c->optimum_nodes[0]));
1252
1253         QUEUE(block_begin) = initial_queue;
1254
1255         /* The following loop runs 'block_size' iterations, one per node.  */
1256         do {
1257                 unsigned num_matches;
1258                 unsigned literal;
1259                 u32 cost;
1260
1261                 /*
1262                  * A selection of matches for the block was already saved in
1263                  * memory so that we don't have to run the uncompressed data
1264                  * through the matchfinder on every optimization pass.  However,
1265                  * we still search for repeat offset matches during each
1266                  * optimization pass because we cannot predict the state of the
1267                  * recent offsets queue.  But as a heuristic, we don't bother
1268                  * searching for repeat offset matches if the general-purpose
1269                  * matchfinder failed to find any matches.
1270                  *
1271                  * Note that a match of length n at some offset implies there is
1272                  * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1273                  * that same offset.  In other words, we don't necessarily need
1274                  * to use the full length of a match.  The key heuristic that
1275                  * saves a significicant amount of time is that for each
1276                  * distinct length, we only consider the smallest offset for
1277                  * which that length is available.  This heuristic also applies
1278                  * to repeat offsets, which we order specially: R0 < R1 < R2 <
1279                  * any explicit offset.  Of course, this heuristic may be
1280                  * produce suboptimal results because offset slots in LZX are
1281                  * subject to entropy encoding, but in practice this is a useful
1282                  * heuristic.
1283                  */
1284
1285                 num_matches = cache_ptr->length;
1286                 cache_ptr++;
1287
1288                 if (num_matches) {
1289                         struct lz_match *end_matches = cache_ptr + num_matches;
1290                         unsigned next_len = LZX_MIN_MATCH_LEN;
1291                         unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1292                         const u8 *matchptr;
1293
1294                         /* Consider R0 match  */
1295                         matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1296                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1297                                 goto R0_done;
1298                         BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1299                         do {
1300                                 u32 cost = cur_node->cost +
1301                                            c->costs.match_cost[0][
1302                                                         next_len - LZX_MIN_MATCH_LEN];
1303                                 if (cost <= (cur_node + next_len)->cost) {
1304                                         (cur_node + next_len)->cost = cost;
1305                                         (cur_node + next_len)->item =
1306                                                 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1307                                 }
1308                                 if (unlikely(++next_len > max_len)) {
1309                                         cache_ptr = end_matches;
1310                                         goto done_matches;
1311                                 }
1312                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1313
1314                 R0_done:
1315
1316                         /* Consider R1 match  */
1317                         matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1318                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1319                                 goto R1_done;
1320                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1321                                 goto R1_done;
1322                         for (unsigned len = 2; len < next_len - 1; len++)
1323                                 if (matchptr[len] != in_next[len])
1324                                         goto R1_done;
1325                         do {
1326                                 u32 cost = cur_node->cost +
1327                                            c->costs.match_cost[1][
1328                                                         next_len - LZX_MIN_MATCH_LEN];
1329                                 if (cost <= (cur_node + next_len)->cost) {
1330                                         (cur_node + next_len)->cost = cost;
1331                                         (cur_node + next_len)->item =
1332                                                 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1333                                 }
1334                                 if (unlikely(++next_len > max_len)) {
1335                                         cache_ptr = end_matches;
1336                                         goto done_matches;
1337                                 }
1338                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1339
1340                 R1_done:
1341
1342                         /* Consider R2 match  */
1343                         matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1344                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1345                                 goto R2_done;
1346                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1347                                 goto R2_done;
1348                         for (unsigned len = 2; len < next_len - 1; len++)
1349                                 if (matchptr[len] != in_next[len])
1350                                         goto R2_done;
1351                         do {
1352                                 u32 cost = cur_node->cost +
1353                                            c->costs.match_cost[2][
1354                                                         next_len - LZX_MIN_MATCH_LEN];
1355                                 if (cost <= (cur_node + next_len)->cost) {
1356                                         (cur_node + next_len)->cost = cost;
1357                                         (cur_node + next_len)->item =
1358                                                 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1359                                 }
1360                                 if (unlikely(++next_len > max_len)) {
1361                                         cache_ptr = end_matches;
1362                                         goto done_matches;
1363                                 }
1364                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1365
1366                 R2_done:
1367
1368                         while (next_len > cache_ptr->length)
1369                                 if (++cache_ptr == end_matches)
1370                                         goto done_matches;
1371
1372                         /* Consider explicit offset matches  */
1373                         do {
1374                                 u32 offset = cache_ptr->offset;
1375                                 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1376                                 unsigned offset_slot = (offset < LZX_NUM_FAST_OFFSETS) ?
1377                                                 lzx_get_offset_slot_fast(c, offset) :
1378                                                 lzx_get_offset_slot(offset);
1379                                 do {
1380                                         u32 cost = cur_node->cost +
1381                                                    c->costs.match_cost[offset_slot][
1382                                                                 next_len - LZX_MIN_MATCH_LEN];
1383                                 #if LZX_CONSIDER_ALIGNED_COSTS
1384                                         if (lzx_extra_offset_bits[offset_slot] >=
1385                                             LZX_NUM_ALIGNED_OFFSET_BITS)
1386                                                 cost += c->costs.aligned[offset_data &
1387                                                                          LZX_ALIGNED_OFFSET_BITMASK];
1388                                 #endif
1389                                         if (cost < (cur_node + next_len)->cost) {
1390                                                 (cur_node + next_len)->cost = cost;
1391                                                 (cur_node + next_len)->item =
1392                                                         (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1393                                         }
1394                                 } while (++next_len <= cache_ptr->length);
1395                         } while (++cache_ptr != end_matches);
1396                 }
1397
1398         done_matches:
1399
1400                 /* Consider coding a literal.
1401
1402                  * To avoid an extra branch, actually checking the preferability
1403                  * of coding the literal is integrated into the queue update
1404                  * code below.  */
1405                 literal = *in_next++;
1406                 cost = cur_node->cost +
1407                        c->costs.main[lzx_main_symbol_for_literal(literal)];
1408
1409                 /* Advance to the next position.  */
1410                 cur_node++;
1411
1412                 /* The lowest-cost path to the current position is now known.
1413                  * Finalize the recent offsets queue that results from taking
1414                  * this lowest-cost path.  */
1415
1416                 if (cost <= cur_node->cost) {
1417                         /* Literal: queue remains unchanged.  */
1418                         cur_node->cost = cost;
1419                         cur_node->item = (literal << OPTIMUM_OFFSET_SHIFT) | 1;
1420                         QUEUE(in_next) = QUEUE(in_next - 1);
1421                 } else {
1422                         /* Match: queue update is needed.  */
1423                         unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1424                         u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1425                         if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1426                                 /* Explicit offset match: insert offset at front  */
1427                                 QUEUE(in_next) =
1428                                         lzx_lru_queue_push(QUEUE(in_next - len),
1429                                                            offset_data - LZX_OFFSET_ADJUSTMENT);
1430                         } else {
1431                                 /* Repeat offset match: swap offset to front  */
1432                                 QUEUE(in_next) =
1433                                         lzx_lru_queue_swap(QUEUE(in_next - len),
1434                                                            offset_data);
1435                         }
1436                 }
1437         } while (cur_node != end_node);
1438
1439         /* Return the match offset queue at the end of the minimum-cost path. */
1440         return QUEUE(block_end);
1441 }
1442
1443 /* Given the costs for the main and length codewords, compute 'match_costs'.  */
1444 static void
1445 lzx_compute_match_costs(struct lzx_compressor *c)
1446 {
1447         unsigned num_offset_slots = lzx_get_num_offset_slots(c->window_order);
1448         struct lzx_costs *costs = &c->costs;
1449
1450         for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1451
1452                 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1453                 unsigned main_symbol = lzx_main_symbol_for_match(offset_slot, 0);
1454                 unsigned i;
1455
1456         #if LZX_CONSIDER_ALIGNED_COSTS
1457                 if (lzx_extra_offset_bits[offset_slot] >= LZX_NUM_ALIGNED_OFFSET_BITS)
1458                         extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1459         #endif
1460
1461                 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1462                         costs->match_cost[offset_slot][i] =
1463                                 costs->main[main_symbol++] + extra_cost;
1464
1465                 extra_cost += costs->main[main_symbol];
1466
1467                 for (; i < LZX_NUM_LENS; i++)
1468                         costs->match_cost[offset_slot][i] =
1469                                 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1470         }
1471 }
1472
1473 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1474  * algorithm.  */
1475 static void
1476 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1477 {
1478         u32 i;
1479         bool have_byte[256];
1480         unsigned num_used_bytes;
1481
1482         /* The costs below are hard coded to use a scaling factor of 16.  */
1483         BUILD_BUG_ON(LZX_BIT_COST != 16);
1484
1485         /*
1486          * Heuristics:
1487          *
1488          * - Use smaller initial costs for literal symbols when the input buffer
1489          *   contains fewer distinct bytes.
1490          *
1491          * - Assume that match symbols are more costly than literal symbols.
1492          *
1493          * - Assume that length symbols for shorter lengths are less costly than
1494          *   length symbols for longer lengths.
1495          */
1496
1497         for (i = 0; i < 256; i++)
1498                 have_byte[i] = false;
1499
1500         for (i = 0; i < block_size; i++)
1501                 have_byte[block[i]] = true;
1502
1503         num_used_bytes = 0;
1504         for (i = 0; i < 256; i++)
1505                 num_used_bytes += have_byte[i];
1506
1507         for (i = 0; i < 256; i++)
1508                 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1509
1510         for (; i < c->num_main_syms; i++)
1511                 c->costs.main[i] = 170;
1512
1513         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1514                 c->costs.len[i] = 103 + (i / 4);
1515
1516 #if LZX_CONSIDER_ALIGNED_COSTS
1517         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1518                 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1519 #endif
1520
1521         lzx_compute_match_costs(c);
1522 }
1523
1524 /* Update the current cost model to reflect the computed Huffman codes.  */
1525 static void
1526 lzx_update_costs(struct lzx_compressor *c)
1527 {
1528         unsigned i;
1529         const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1530
1531         for (i = 0; i < c->num_main_syms; i++)
1532                 c->costs.main[i] = (lens->main[i] ? lens->main[i] : 15) * LZX_BIT_COST;
1533
1534         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1535                 c->costs.len[i] = (lens->len[i] ? lens->len[i] : 15) * LZX_BIT_COST;
1536
1537 #if LZX_CONSIDER_ALIGNED_COSTS
1538         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1539                 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] : 7) * LZX_BIT_COST;
1540 #endif
1541
1542         lzx_compute_match_costs(c);
1543 }
1544
1545 static struct lzx_lru_queue
1546 lzx_optimize_and_write_block(struct lzx_compressor *c,
1547                              struct lzx_output_bitstream *os,
1548                              const u8 *block_begin, const u32 block_size,
1549                              const struct lzx_lru_queue initial_queue)
1550 {
1551         unsigned num_passes_remaining = c->num_optim_passes;
1552         struct lzx_item *next_chosen_item;
1553         struct lzx_lru_queue new_queue;
1554
1555         /* The first optimization pass uses a default cost model.  Each
1556          * additional optimization pass uses a cost model derived from the
1557          * Huffman code computed in the previous pass.  */
1558
1559         lzx_set_default_costs(c, block_begin, block_size);
1560         lzx_reset_symbol_frequencies(c);
1561         do {
1562                 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1563                                                    initial_queue);
1564                 if (num_passes_remaining > 1) {
1565                         lzx_tally_item_list(c, c->optimum_nodes + block_size);
1566                         lzx_make_huffman_codes(c);
1567                         lzx_update_costs(c);
1568                         lzx_reset_symbol_frequencies(c);
1569                 }
1570         } while (--num_passes_remaining);
1571
1572         next_chosen_item = c->chosen_items;
1573         lzx_record_item_list(c, c->optimum_nodes + block_size, &next_chosen_item);
1574         lzx_finish_block(c, os, block_size, next_chosen_item - c->chosen_items);
1575         return new_queue;
1576 }
1577
1578 /*
1579  * This is the "near-optimal" LZX compressor.
1580  *
1581  * For each block, it performs a relatively thorough graph search to find an
1582  * inexpensive (in terms of compressed size) way to output that block.
1583  *
1584  * Note: there are actually many things this algorithm leaves on the table in
1585  * terms of compression ratio.  So although it may be "near-optimal", it is
1586  * certainly not "optimal".  The goal is not to produce the optimal compression
1587  * ratio, which for LZX is probably impossible within any practical amount of
1588  * time, but rather to produce a compression ratio significantly better than a
1589  * simpler "greedy" or "lazy" parse while still being relatively fast.
1590  */
1591 static void
1592 lzx_compress_near_optimal(struct lzx_compressor *c,
1593                           struct lzx_output_bitstream *os)
1594 {
1595         const u8 * const in_begin = c->in_buffer;
1596         const u8 *       in_next = in_begin;
1597         const u8 * const in_end  = in_begin + c->in_nbytes;
1598         unsigned max_len = LZX_MAX_MATCH_LEN;
1599         unsigned nice_len = min(c->nice_match_length, max_len);
1600         u32 next_hash;
1601         struct lzx_lru_queue queue;
1602
1603         bt_matchfinder_init(&c->bt_mf);
1604         matchfinder_init(c->hash2_tab, LZX_HASH2_LENGTH);
1605         next_hash = bt_matchfinder_hash_3_bytes(in_next);
1606         lzx_lru_queue_init(&queue);
1607
1608         do {
1609                 /* Starting a new block  */
1610                 const u8 * const in_block_begin = in_next;
1611                 const u8 * const in_block_end =
1612                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1613
1614                 /* Run the block through the matchfinder and cache the matches. */
1615                 struct lz_match *cache_ptr = c->match_cache;
1616                 do {
1617                         struct lz_match *lz_matchptr;
1618                         u32 hash2;
1619                         pos_t cur_match;
1620                         unsigned best_len;
1621
1622                         /* If approaching the end of the input buffer, adjust
1623                          * 'max_len' and 'nice_len' accordingly.  */
1624                         if (unlikely(max_len > in_end - in_next)) {
1625                                 max_len = in_end - in_next;
1626                                 nice_len = min(max_len, nice_len);
1627
1628                                 /* This extra check is needed to ensure that
1629                                  * reading the next 3 bytes when looking for a
1630                                  * length 2 match is valid.  In addition, we
1631                                  * cannot allow ourselves to find a length 2
1632                                  * match of the very last two bytes with the
1633                                  * very first two bytes, since such a match has
1634                                  * an offset too large to be represented.  */
1635                                 if (unlikely(max_len <
1636                                              max(LZ_HASH_REQUIRED_NBYTES, 3)))
1637                                 {
1638                                         in_next++;
1639                                         cache_ptr->length = 0;
1640                                         cache_ptr++;
1641                                         continue;
1642                                 }
1643                         }
1644
1645                         lz_matchptr = cache_ptr + 1;
1646
1647                         /* Check for a length 2 match.  */
1648                         hash2 = lz_hash_2_bytes(in_next);
1649                         cur_match = c->hash2_tab[hash2];
1650                         c->hash2_tab[hash2] = in_next - in_begin;
1651                         if (matchfinder_node_valid(cur_match) &&
1652                             (LZX_HASH2_ORDER == 16 ||
1653                              load_u16_unaligned(&in_begin[cur_match]) ==
1654                              load_u16_unaligned(in_next)) &&
1655                             in_begin[cur_match + 2] != in_next[2])
1656                         {
1657                                 lz_matchptr->length = 2;
1658                                 lz_matchptr->offset = in_next - &in_begin[cur_match];
1659                                 lz_matchptr++;
1660                         }
1661
1662                         /* Check for matches of length >= 3.  */
1663                         lz_matchptr = bt_matchfinder_get_matches(&c->bt_mf,
1664                                                                  in_begin,
1665                                                                  in_next,
1666                                                                  3,
1667                                                                  max_len,
1668                                                                  nice_len,
1669                                                                  c->max_search_depth,
1670                                                                  &next_hash,
1671                                                                  &best_len,
1672                                                                  lz_matchptr);
1673                         in_next++;
1674                         cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1675                         cache_ptr = lz_matchptr;
1676
1677                         /*
1678                          * If there was a very long match found, then don't
1679                          * cache any matches for the bytes covered by that
1680                          * match.  This avoids degenerate behavior when
1681                          * compressing highly redundant data, where the number
1682                          * of matches can be very large.
1683                          *
1684                          * This heuristic doesn't actually hurt the compression
1685                          * ratio very much.  If there's a long match, then the
1686                          * data must be highly compressible, so it doesn't
1687                          * matter as much what we do.
1688                          */
1689                         if (best_len >= nice_len) {
1690                                 --best_len;
1691                                 do {
1692                                         if (unlikely(max_len > in_end - in_next)) {
1693                                                 max_len = in_end - in_next;
1694                                                 nice_len = min(max_len, nice_len);
1695                                                 if (unlikely(max_len <
1696                                                              max(LZ_HASH_REQUIRED_NBYTES, 3)))
1697                                                 {
1698                                                         in_next++;
1699                                                         cache_ptr->length = 0;
1700                                                         cache_ptr++;
1701                                                         continue;
1702                                                 }
1703                                         }
1704                                         c->hash2_tab[lz_hash_2_bytes(in_next)] =
1705                                                 in_next - in_begin;
1706                                         bt_matchfinder_skip_position(&c->bt_mf,
1707                                                                      in_begin,
1708                                                                      in_next,
1709                                                                      in_end,
1710                                                                      nice_len,
1711                                                                      c->max_search_depth,
1712                                                                      &next_hash);
1713                                         in_next++;
1714                                         cache_ptr->length = 0;
1715                                         cache_ptr++;
1716                                 } while (--best_len);
1717                         }
1718                 } while (in_next < in_block_end &&
1719                          likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1720
1721                 /* We've finished running the block through the matchfinder.
1722                  * Now choose a match/literal sequence and write the block.  */
1723
1724                 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1725                                                      in_next - in_block_begin,
1726                                                      queue);
1727         } while (in_next != in_end);
1728 }
1729
1730 /*
1731  * Given a pointer to the current byte sequence and the current list of recent
1732  * match offsets, find the longest repeat offset match.
1733  *
1734  * If no match of at least 2 bytes is found, then return 0.
1735  *
1736  * If a match of at least 2 bytes is found, then return its length and set
1737  * *rep_max_idx_ret to the index of its offset in @queue.
1738 */
1739 static unsigned
1740 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1741                                      const u32 bytes_remaining,
1742                                      struct lzx_lru_queue queue,
1743                                      unsigned *rep_max_idx_ret)
1744 {
1745         BUILD_BUG_ON(LZX_NUM_RECENT_OFFSETS != 3);
1746         LZX_ASSERT(bytes_remaining >= 2);
1747
1748         const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1749         const u16 next_2_bytes = load_u16_unaligned(in_next);
1750         const u8 *matchptr;
1751         unsigned rep_max_len;
1752         unsigned rep_max_idx;
1753         unsigned rep_len;
1754
1755         matchptr = in_next - lzx_lru_queue_pop(&queue);
1756         if (load_u16_unaligned(matchptr) == next_2_bytes)
1757                 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1758         else
1759                 rep_max_len = 0;
1760         rep_max_idx = 0;
1761
1762         matchptr = in_next - lzx_lru_queue_pop(&queue);
1763         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1764                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1765                 if (rep_len > rep_max_len) {
1766                         rep_max_len = rep_len;
1767                         rep_max_idx = 1;
1768                 }
1769         }
1770
1771         matchptr = in_next - lzx_lru_queue_pop(&queue);
1772         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1773                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1774                 if (rep_len > rep_max_len) {
1775                         rep_max_len = rep_len;
1776                         rep_max_idx = 2;
1777                 }
1778         }
1779
1780         *rep_max_idx_ret = rep_max_idx;
1781         return rep_max_len;
1782 }
1783
1784 /* Fast heuristic scoring for lazy parsing: how "good" is this match?  */
1785 static inline unsigned
1786 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1787 {
1788         unsigned score = len;
1789
1790         if (adjusted_offset < 4096)
1791                 score++;
1792
1793         if (adjusted_offset < 256)
1794                 score++;
1795
1796         return score;
1797 }
1798
1799 static inline unsigned
1800 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1801 {
1802         return rep_len + 3;
1803 }
1804
1805 /* This is the "lazy" LZX compressor.  */
1806 static void
1807 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os)
1808 {
1809         const u8 * const in_begin = c->in_buffer;
1810         const u8 *       in_next = in_begin;
1811         const u8 * const in_end  = in_begin + c->in_nbytes;
1812         unsigned max_len = LZX_MAX_MATCH_LEN;
1813         unsigned nice_len = min(c->nice_match_length, max_len);
1814         struct lzx_lru_queue queue;
1815
1816         hc_matchfinder_init(&c->hc_mf);
1817         lzx_lru_queue_init(&queue);
1818
1819         do {
1820                 /* Starting a new block  */
1821
1822                 const u8 * const in_block_begin = in_next;
1823                 const u8 * const in_block_end =
1824                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1825                 struct lzx_item *next_chosen_item = c->chosen_items;
1826                 unsigned cur_len;
1827                 u32 cur_offset;
1828                 u32 cur_offset_data;
1829                 unsigned cur_score;
1830                 unsigned next_len;
1831                 u32 next_offset;
1832                 u32 next_offset_data;
1833                 unsigned next_score;
1834                 unsigned rep_max_len;
1835                 unsigned rep_max_idx;
1836                 unsigned rep_score;
1837                 unsigned skip_len;
1838
1839                 lzx_reset_symbol_frequencies(c);
1840
1841                 do {
1842                         if (unlikely(max_len > in_end - in_next)) {
1843                                 max_len = in_end - in_next;
1844                                 nice_len = min(max_len, nice_len);
1845                         }
1846
1847                         /* Find the longest match at the current position.  */
1848
1849                         cur_len = hc_matchfinder_longest_match(&c->hc_mf,
1850                                                                in_begin,
1851                                                                in_next,
1852                                                                2,
1853                                                                max_len,
1854                                                                nice_len,
1855                                                                c->max_search_depth,
1856                                                                &cur_offset);
1857                         if (cur_len < 3 ||
1858                             (cur_len == 3 &&
1859                              cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
1860                              cur_offset != lzx_lru_queue_R0(queue) &&
1861                              cur_offset != lzx_lru_queue_R1(queue) &&
1862                              cur_offset != lzx_lru_queue_R2(queue)))
1863                         {
1864                                 /* There was no match found, or the only match found
1865                                  * was a distant length 3 match.  Output a literal.  */
1866                                 lzx_declare_literal(c, *in_next++,
1867                                                     &next_chosen_item);
1868                                 continue;
1869                         }
1870
1871                         if (cur_offset == lzx_lru_queue_R0(queue)) {
1872                                 in_next++;
1873                                 cur_offset_data = 0;
1874                                 skip_len = cur_len - 1;
1875                                 goto choose_cur_match;
1876                         }
1877
1878                         cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
1879                         cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
1880
1881                         /* Consider a repeat offset match  */
1882                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1883                                                                            in_end - in_next,
1884                                                                            queue,
1885                                                                            &rep_max_idx);
1886                         in_next++;
1887
1888                         if (rep_max_len >= 3 &&
1889                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1890                                                                        rep_max_idx)) >= cur_score)
1891                         {
1892                                 cur_len = rep_max_len;
1893                                 cur_offset_data = rep_max_idx;
1894                                 skip_len = rep_max_len - 1;
1895                                 goto choose_cur_match;
1896                         }
1897
1898                 have_cur_match:
1899
1900                         /* We have a match at the current position.  */
1901
1902                         /* If we have a very long match, choose it immediately.  */
1903                         if (cur_len >= nice_len) {
1904                                 skip_len = cur_len - 1;
1905                                 goto choose_cur_match;
1906                         }
1907
1908                         /* See if there's a better match at the next position.  */
1909
1910                         if (unlikely(max_len > in_end - in_next)) {
1911                                 max_len = in_end - in_next;
1912                                 nice_len = min(max_len, nice_len);
1913                         }
1914
1915                         next_len = hc_matchfinder_longest_match(&c->hc_mf,
1916                                                                 in_begin,
1917                                                                 in_next,
1918                                                                 cur_len - 2,
1919                                                                 max_len,
1920                                                                 nice_len,
1921                                                                 c->max_search_depth / 2,
1922                                                                 &next_offset);
1923
1924                         if (next_len <= cur_len - 2) {
1925                                 in_next++;
1926                                 skip_len = cur_len - 2;
1927                                 goto choose_cur_match;
1928                         }
1929
1930                         next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
1931                         next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
1932
1933                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
1934                                                                            in_end - in_next,
1935                                                                            queue,
1936                                                                            &rep_max_idx);
1937                         in_next++;
1938
1939                         if (rep_max_len >= 3 &&
1940                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1941                                                                        rep_max_idx)) >= next_score)
1942                         {
1943
1944                                 if (rep_score > cur_score) {
1945                                         /* The next match is better, and it's a
1946                                          * repeat offset match.  */
1947                                         lzx_declare_literal(c, *(in_next - 2),
1948                                                             &next_chosen_item);
1949                                         cur_len = rep_max_len;
1950                                         cur_offset_data = rep_max_idx;
1951                                         skip_len = cur_len - 1;
1952                                         goto choose_cur_match;
1953                                 }
1954                         } else {
1955                                 if (next_score > cur_score) {
1956                                         /* The next match is better, and it's an
1957                                          * explicit offset match.  */
1958                                         lzx_declare_literal(c, *(in_next - 2),
1959                                                             &next_chosen_item);
1960                                         cur_len = next_len;
1961                                         cur_offset_data = next_offset_data;
1962                                         cur_score = next_score;
1963                                         goto have_cur_match;
1964                                 }
1965                         }
1966
1967                         /* The original match was better.  */
1968                         skip_len = cur_len - 2;
1969
1970                 choose_cur_match:
1971                         if (cur_offset_data < LZX_NUM_RECENT_OFFSETS) {
1972                                 lzx_declare_repeat_offset_match(c, cur_len,
1973                                                                 cur_offset_data,
1974                                                                 &next_chosen_item);
1975                                 queue = lzx_lru_queue_swap(queue, cur_offset_data);
1976                         } else {
1977                                 lzx_declare_explicit_offset_match(c, cur_len,
1978                                                                   cur_offset_data - LZX_OFFSET_ADJUSTMENT,
1979                                                                   &next_chosen_item);
1980                                 queue = lzx_lru_queue_push(queue, cur_offset_data - LZX_OFFSET_ADJUSTMENT);
1981                         }
1982
1983                         hc_matchfinder_skip_positions(&c->hc_mf,
1984                                                       in_begin,
1985                                                       in_next,
1986                                                       in_end,
1987                                                       skip_len);
1988                         in_next += skip_len;
1989                 } while (in_next < in_block_end);
1990
1991                 lzx_finish_block(c, os, in_next - in_block_begin,
1992                                  next_chosen_item - c->chosen_items);
1993         } while (in_next != in_end);
1994 }
1995
1996 static void
1997 lzx_init_offset_slot_fast(struct lzx_compressor *c)
1998 {
1999         u8 slot = 0;
2000
2001         for (u32 offset = 0; offset < LZX_NUM_FAST_OFFSETS; offset++) {
2002
2003                 while (offset + LZX_OFFSET_ADJUSTMENT >= lzx_offset_slot_base[slot + 1])
2004                         slot++;
2005
2006                 c->offset_slot_fast[offset] = slot;
2007         }
2008 }
2009
2010 static size_t
2011 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2012 {
2013         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2014                 return offsetof(struct lzx_compressor, hc_mf) +
2015                         hc_matchfinder_size(max_bufsize);
2016         } else {
2017                 return offsetof(struct lzx_compressor, bt_mf) +
2018                         bt_matchfinder_size(max_bufsize);
2019         }
2020 }
2021
2022 static u64
2023 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level)
2024 {
2025         u64 size = 0;
2026
2027         if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2028                 return 0;
2029
2030         size += lzx_get_compressor_size(max_bufsize, compression_level);
2031         size += max_bufsize; /* in_buffer */
2032         return size;
2033 }
2034
2035 static int
2036 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2037                       void **c_ret)
2038 {
2039         unsigned window_order;
2040         struct lzx_compressor *c;
2041
2042         window_order = lzx_get_window_order(max_bufsize);
2043         if (window_order == 0)
2044                 return WIMLIB_ERR_INVALID_PARAM;
2045
2046         c = ALIGNED_MALLOC(lzx_get_compressor_size(max_bufsize,
2047                                                    compression_level),
2048                            MATCHFINDER_ALIGNMENT);
2049         if (!c)
2050                 goto oom0;
2051
2052         c->num_main_syms = lzx_get_num_main_syms(window_order);
2053         c->window_order = window_order;
2054
2055         c->in_buffer = MALLOC(max_bufsize);
2056         if (!c->in_buffer)
2057                 goto oom1;
2058
2059         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2060
2061                 /* Fast compression: Use lazy parsing.  */
2062
2063                 c->impl = lzx_compress_lazy;
2064                 c->max_search_depth = (36 * compression_level) / 20;
2065                 c->nice_match_length = (72 * compression_level) / 20;
2066
2067                 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2068                  * halves the max_search_depth when attempting a lazy match, and
2069                  * max_search_depth cannot be 0.  */
2070                 if (c->max_search_depth < 2)
2071                         c->max_search_depth = 2;
2072         } else {
2073
2074                 /* Normal / high compression: Use near-optimal parsing.  */
2075
2076                 c->impl = lzx_compress_near_optimal;
2077
2078                 /* Scale nice_match_length and max_search_depth with the
2079                  * compression level.  */
2080                 c->max_search_depth = (24 * compression_level) / 50;
2081                 c->nice_match_length = (32 * compression_level) / 50;
2082
2083                 /* Set a number of optimization passes appropriate for the
2084                  * compression level.  */
2085
2086                 c->num_optim_passes = 1;
2087
2088                 if (compression_level >= 45)
2089                         c->num_optim_passes++;
2090
2091                 /* Use more optimization passes for higher compression levels.
2092                  * But the more passes there are, the less they help --- so
2093                  * don't add them linearly.  */
2094                 if (compression_level >= 70) {
2095                         c->num_optim_passes++;
2096                         if (compression_level >= 100)
2097                                 c->num_optim_passes++;
2098                         if (compression_level >= 150)
2099                                 c->num_optim_passes++;
2100                         if (compression_level >= 200)
2101                                 c->num_optim_passes++;
2102                         if (compression_level >= 300)
2103                                 c->num_optim_passes++;
2104                 }
2105         }
2106
2107         /* max_search_depth == 0 is invalid.  */
2108         if (c->max_search_depth < 1)
2109                 c->max_search_depth = 1;
2110
2111         if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2112                 c->nice_match_length = LZX_MAX_MATCH_LEN;
2113
2114         lzx_init_offset_slot_fast(c);
2115         *c_ret = c;
2116         return 0;
2117
2118 oom1:
2119         ALIGNED_FREE(c);
2120 oom0:
2121         return WIMLIB_ERR_NOMEM;
2122 }
2123
2124 static size_t
2125 lzx_compress(const void *in, size_t in_nbytes,
2126              void *out, size_t out_nbytes_avail, void *_c)
2127 {
2128         struct lzx_compressor *c = _c;
2129         struct lzx_output_bitstream os;
2130
2131         /* Don't bother trying to compress very small inputs.  */
2132         if (in_nbytes < 100)
2133                 return 0;
2134
2135         /* Copy the input data into the internal buffer and preprocess it.  */
2136         memcpy(c->in_buffer, in, in_nbytes);
2137         c->in_nbytes = in_nbytes;
2138         lzx_do_e8_preprocessing(c->in_buffer, in_nbytes);
2139
2140         /* Initially, the previous Huffman codeword lengths are all zeroes.  */
2141         c->codes_index = 0;
2142         memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2143
2144         /* Initialize the output bitstream.  */
2145         lzx_init_output(&os, out, out_nbytes_avail);
2146
2147         /* Call the compression level-specific compress() function.  */
2148         (*c->impl)(c, &os);
2149
2150         /* Flush the output bitstream and return the compressed size or 0.  */
2151         return lzx_flush_output(&os);
2152 }
2153
2154 static void
2155 lzx_free_compressor(void *_c)
2156 {
2157         struct lzx_compressor *c = _c;
2158
2159         FREE(c->in_buffer);
2160         ALIGNED_FREE(c);
2161 }
2162
2163 const struct compressor_ops lzx_compressor_ops = {
2164         .get_needed_memory  = lzx_get_needed_memory,
2165         .create_compressor  = lzx_create_compressor,
2166         .compress           = lzx_compress,
2167         .free_compressor    = lzx_free_compressor,
2168 };