1 /*
2 * bt_matchfinder.h - Lempel-Ziv matchfinding with a hash table of binary trees
3 *
4 * Originally public domain; changes after 2016-09-07 are copyrighted.
5 *
6 * Copyright 2016 Eric Biggers
7 *
8 * Permission is hereby granted, free of charge, to any person
9 * obtaining a copy of this software and associated documentation
10 * files (the "Software"), to deal in the Software without
11 * restriction, including without limitation the rights to use,
12 * copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following
15 * conditions:
16 *
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
22 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
24 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
25 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27 * OTHER DEALINGS IN THE SOFTWARE.
28 *
29 * ----------------------------------------------------------------------------
30 *
31 * This is a Binary Trees (bt) based matchfinder.
32 *
33 * The main data structure is a hash table where each hash bucket contains a
34 * binary tree of sequences whose first 4 bytes share the same hash code. Each
35 * sequence is identified by its starting position in the input buffer. Each
36 * binary tree is always sorted such that each left child represents a sequence
37 * lexicographically lesser than its parent and each right child represents a
38 * sequence lexicographically greater than its parent.
39 *
40 * The algorithm processes the input buffer sequentially. At each byte
41 * position, the hash code of the first 4 bytes of the sequence beginning at
42 * that position (the sequence being matched against) is computed. This
43 * identifies the hash bucket to use for that position. Then, a new binary tree
44 * node is created to represent the current sequence. Then, in a single tree
45 * traversal, the hash bucket's binary tree is searched for matches and is
46 * re-rooted at the new node.
47 *
48 * Compared to the simpler algorithm that uses linked lists instead of binary
49 * trees (see hc_matchfinder.h), the binary tree version gains more information
50 * at each node visitation. Ideally, the binary tree version will examine only
51 * 'log(n)' nodes to find the same matches that the linked list version will
52 * find by examining 'n' nodes. In addition, the binary tree version can
53 * examine fewer bytes at each node by taking advantage of the common prefixes
54 * that result from the sort order, whereas the linked list version may have to
55 * examine up to the full length of the match at each node.
56 *
57 * However, it is not always best to use the binary tree version. It requires
58 * nearly twice as much memory as the linked list version, and it takes time to
59 * keep the binary trees sorted, even at positions where the compressor does not
60 * need matches. Generally, when doing fast compression on small buffers,
61 * binary trees are the wrong approach. They are best suited for thorough
62 * compression and/or large buffers.
63 *
64 * ----------------------------------------------------------------------------
65 */
66
67
68 #include "matchfinder_common.h"
69
70 #define BT_MATCHFINDER_HASH3_ORDER 16
71 #define BT_MATCHFINDER_HASH3_WAYS 2
72 #define BT_MATCHFINDER_HASH4_ORDER 16
73
74 #define BT_MATCHFINDER_TOTAL_HASH_LENGTH \
75 ((1UL << BT_MATCHFINDER_HASH3_ORDER) * BT_MATCHFINDER_HASH3_WAYS + \
76 (1UL << BT_MATCHFINDER_HASH4_ORDER))
77
78 /* Representation of a match found by the bt_matchfinder */
79 struct lz_match {
80
81 /* The number of bytes matched. */
82 u16 length;
83
84 /* The offset back from the current position that was matched. */
85 u16 offset;
86 };
87
88 struct bt_matchfinder {
89
90 /* The hash table for finding length 3 matches */
91 mf_pos_t hash3_tab[1UL << BT_MATCHFINDER_HASH3_ORDER][BT_MATCHFINDER_HASH3_WAYS];
92
93 /* The hash table which contains the roots of the binary trees for
94 * finding length 4+ matches */
95 mf_pos_t hash4_tab[1UL << BT_MATCHFINDER_HASH4_ORDER];
96
97 /* The child node references for the binary trees. The left and right
98 * children of the node for the sequence with position 'pos' are
99 * 'child_tab[pos * 2]' and 'child_tab[pos * 2 + 1]', respectively. */
100 mf_pos_t child_tab[2UL * MATCHFINDER_WINDOW_SIZE];
101
102 }
103 #ifdef _aligned_attribute
104 _aligned_attribute(MATCHFINDER_ALIGNMENT)
105 #endif
106 ;
107
108 /* Prepare the matchfinder for a new input buffer. */
109 static forceinline void
bt_matchfinder_init(struct bt_matchfinder * mf)110 bt_matchfinder_init(struct bt_matchfinder *mf)
111 {
112 matchfinder_init((mf_pos_t *)mf, BT_MATCHFINDER_TOTAL_HASH_LENGTH);
113 }
114
115 static forceinline void
bt_matchfinder_slide_window(struct bt_matchfinder * mf)116 bt_matchfinder_slide_window(struct bt_matchfinder *mf)
117 {
118 matchfinder_rebase((mf_pos_t *)mf,
119 sizeof(struct bt_matchfinder) / sizeof(mf_pos_t));
120 }
121
122 static forceinline mf_pos_t *
bt_left_child(struct bt_matchfinder * mf,s32 node)123 bt_left_child(struct bt_matchfinder *mf, s32 node)
124 {
125 return &mf->child_tab[2 * (node & (MATCHFINDER_WINDOW_SIZE - 1)) + 0];
126 }
127
128 static forceinline mf_pos_t *
bt_right_child(struct bt_matchfinder * mf,s32 node)129 bt_right_child(struct bt_matchfinder *mf, s32 node)
130 {
131 return &mf->child_tab[2 * (node & (MATCHFINDER_WINDOW_SIZE - 1)) + 1];
132 }
133
134 /* The minimum permissible value of 'max_len' for bt_matchfinder_get_matches()
135 * and bt_matchfinder_skip_position(). There must be sufficiently many bytes
136 * remaining to load a 32-bit integer from the *next* position. */
137 #define BT_MATCHFINDER_REQUIRED_NBYTES 5
138
139 /* Advance the binary tree matchfinder by one byte, optionally recording
140 * matches. @record_matches should be a compile-time constant. */
141 static forceinline struct lz_match *
bt_matchfinder_advance_one_byte(struct bt_matchfinder * const restrict mf,const u8 * const restrict in_base,const ptrdiff_t cur_pos,const u32 max_len,const u32 nice_len,const u32 max_search_depth,u32 * const restrict next_hashes,u32 * const restrict best_len_ret,struct lz_match * restrict lz_matchptr,const bool record_matches)142 bt_matchfinder_advance_one_byte(struct bt_matchfinder * const restrict mf,
143 const u8 * const restrict in_base,
144 const ptrdiff_t cur_pos,
145 const u32 max_len,
146 const u32 nice_len,
147 const u32 max_search_depth,
148 u32 * const restrict next_hashes,
149 u32 * const restrict best_len_ret,
150 struct lz_match * restrict lz_matchptr,
151 const bool record_matches)
152 {
153 const u8 *in_next = in_base + cur_pos;
154 u32 depth_remaining = max_search_depth;
155 const s32 cutoff = cur_pos - MATCHFINDER_WINDOW_SIZE;
156 u32 next_hashseq;
157 u32 hash3;
158 u32 hash4;
159 s32 cur_node;
160 #if BT_MATCHFINDER_HASH3_WAYS >= 2
161 s32 cur_node_2;
162 #endif
163 const u8 *matchptr;
164 mf_pos_t *pending_lt_ptr, *pending_gt_ptr;
165 u32 best_lt_len, best_gt_len;
166 u32 len;
167 u32 best_len = 3;
168
169 STATIC_ASSERT(BT_MATCHFINDER_HASH3_WAYS >= 1 &&
170 BT_MATCHFINDER_HASH3_WAYS <= 2);
171
172 next_hashseq = get_unaligned_le32(in_next + 1);
173
174 hash3 = next_hashes[0];
175 hash4 = next_hashes[1];
176
177 next_hashes[0] = lz_hash(next_hashseq & 0xFFFFFF, BT_MATCHFINDER_HASH3_ORDER);
178 next_hashes[1] = lz_hash(next_hashseq, BT_MATCHFINDER_HASH4_ORDER);
179 prefetchw(&mf->hash3_tab[next_hashes[0]]);
180 prefetchw(&mf->hash4_tab[next_hashes[1]]);
181
182 cur_node = mf->hash3_tab[hash3][0];
183 mf->hash3_tab[hash3][0] = cur_pos;
184 #if BT_MATCHFINDER_HASH3_WAYS >= 2
185 cur_node_2 = mf->hash3_tab[hash3][1];
186 mf->hash3_tab[hash3][1] = cur_node;
187 #endif
188 if (record_matches && cur_node > cutoff) {
189 u32 seq3 = load_u24_unaligned(in_next);
190 if (seq3 == load_u24_unaligned(&in_base[cur_node])) {
191 lz_matchptr->length = 3;
192 lz_matchptr->offset = in_next - &in_base[cur_node];
193 lz_matchptr++;
194 }
195 #if BT_MATCHFINDER_HASH3_WAYS >= 2
196 else if (cur_node_2 > cutoff &&
197 seq3 == load_u24_unaligned(&in_base[cur_node_2]))
198 {
199 lz_matchptr->length = 3;
200 lz_matchptr->offset = in_next - &in_base[cur_node_2];
201 lz_matchptr++;
202 }
203 #endif
204 }
205
206 cur_node = mf->hash4_tab[hash4];
207 mf->hash4_tab[hash4] = cur_pos;
208
209 pending_lt_ptr = bt_left_child(mf, cur_pos);
210 pending_gt_ptr = bt_right_child(mf, cur_pos);
211
212 if (cur_node <= cutoff) {
213 *pending_lt_ptr = MATCHFINDER_INITVAL;
214 *pending_gt_ptr = MATCHFINDER_INITVAL;
215 *best_len_ret = best_len;
216 return lz_matchptr;
217 }
218
219 best_lt_len = 0;
220 best_gt_len = 0;
221 len = 0;
222
223 for (;;) {
224 matchptr = &in_base[cur_node];
225
226 if (matchptr[len] == in_next[len]) {
227 len = lz_extend(in_next, matchptr, len + 1, max_len);
228 if (!record_matches || len > best_len) {
229 if (record_matches) {
230 best_len = len;
231 lz_matchptr->length = len;
232 lz_matchptr->offset = in_next - matchptr;
233 lz_matchptr++;
234 }
235 if (len >= nice_len) {
236 *pending_lt_ptr = *bt_left_child(mf, cur_node);
237 *pending_gt_ptr = *bt_right_child(mf, cur_node);
238 *best_len_ret = best_len;
239 return lz_matchptr;
240 }
241 }
242 }
243
244 if (matchptr[len] < in_next[len]) {
245 *pending_lt_ptr = cur_node;
246 pending_lt_ptr = bt_right_child(mf, cur_node);
247 cur_node = *pending_lt_ptr;
248 best_lt_len = len;
249 if (best_gt_len < len)
250 len = best_gt_len;
251 } else {
252 *pending_gt_ptr = cur_node;
253 pending_gt_ptr = bt_left_child(mf, cur_node);
254 cur_node = *pending_gt_ptr;
255 best_gt_len = len;
256 if (best_lt_len < len)
257 len = best_lt_len;
258 }
259
260 if (cur_node <= cutoff || !--depth_remaining) {
261 *pending_lt_ptr = MATCHFINDER_INITVAL;
262 *pending_gt_ptr = MATCHFINDER_INITVAL;
263 *best_len_ret = best_len;
264 return lz_matchptr;
265 }
266 }
267 }
268
269 /*
270 * Retrieve a list of matches with the current position.
271 *
272 * @mf
273 * The matchfinder structure.
274 * @in_base
275 * Pointer to the next byte in the input buffer to process _at the last
276 * time bt_matchfinder_init() or bt_matchfinder_slide_window() was called_.
277 * @cur_pos
278 * The current position in the input buffer relative to @in_base (the
279 * position of the sequence being matched against).
280 * @max_len
281 * The maximum permissible match length at this position. Must be >=
282 * BT_MATCHFINDER_REQUIRED_NBYTES.
283 * @nice_len
284 * Stop searching if a match of at least this length is found.
285 * Must be <= @max_len.
286 * @max_search_depth
287 * Limit on the number of potential matches to consider. Must be >= 1.
288 * @next_hashes
289 * The precomputed hash codes for the sequence beginning at @in_next.
290 * These will be used and then updated with the precomputed hashcodes for
291 * the sequence beginning at @in_next + 1.
292 * @best_len_ret
293 * If a match of length >= 4 was found, then the length of the longest such
294 * match is written here; otherwise 3 is written here. (Note: this is
295 * redundant with the 'struct lz_match' array, but this is easier for the
296 * compiler to optimize when inlined and the caller immediately does a
297 * check against 'best_len'.)
298 * @lz_matchptr
299 * An array in which this function will record the matches. The recorded
300 * matches will be sorted by strictly increasing length and (non-strictly)
301 * increasing offset. The maximum number of matches that may be found is
302 * 'nice_len - 2'.
303 *
304 * The return value is a pointer to the next available slot in the @lz_matchptr
305 * array. (If no matches were found, this will be the same as @lz_matchptr.)
306 */
307 static forceinline struct lz_match *
bt_matchfinder_get_matches(struct bt_matchfinder * mf,const u8 * in_base,ptrdiff_t cur_pos,u32 max_len,u32 nice_len,u32 max_search_depth,u32 next_hashes[2],u32 * best_len_ret,struct lz_match * lz_matchptr)308 bt_matchfinder_get_matches(struct bt_matchfinder *mf,
309 const u8 *in_base,
310 ptrdiff_t cur_pos,
311 u32 max_len,
312 u32 nice_len,
313 u32 max_search_depth,
314 u32 next_hashes[2],
315 u32 *best_len_ret,
316 struct lz_match *lz_matchptr)
317 {
318 return bt_matchfinder_advance_one_byte(mf,
319 in_base,
320 cur_pos,
321 max_len,
322 nice_len,
323 max_search_depth,
324 next_hashes,
325 best_len_ret,
326 lz_matchptr,
327 true);
328 }
329
330 /*
331 * Advance the matchfinder, but don't record any matches.
332 *
333 * This is very similar to bt_matchfinder_get_matches() because both functions
334 * must do hashing and tree re-rooting.
335 */
336 static forceinline void
bt_matchfinder_skip_position(struct bt_matchfinder * mf,const u8 * in_base,ptrdiff_t cur_pos,u32 nice_len,u32 max_search_depth,u32 next_hashes[2])337 bt_matchfinder_skip_position(struct bt_matchfinder *mf,
338 const u8 *in_base,
339 ptrdiff_t cur_pos,
340 u32 nice_len,
341 u32 max_search_depth,
342 u32 next_hashes[2])
343 {
344 u32 best_len;
345 bt_matchfinder_advance_one_byte(mf,
346 in_base,
347 cur_pos,
348 nice_len,
349 nice_len,
350 max_search_depth,
351 next_hashes,
352 &best_len,
353 NULL,
354 false);
355 }
356