xref: /openbmc/linux/lib/zlib_deflate/deflate.c (revision 5b828263)
1 /* +++ deflate.c */
2 /* deflate.c -- compress data using the deflation algorithm
3  * Copyright (C) 1995-1996 Jean-loup Gailly.
4  * For conditions of distribution and use, see copyright notice in zlib.h
5  */
6 
7 /*
8  *  ALGORITHM
9  *
10  *      The "deflation" process depends on being able to identify portions
11  *      of the input text which are identical to earlier input (within a
12  *      sliding window trailing behind the input currently being processed).
13  *
14  *      The most straightforward technique turns out to be the fastest for
15  *      most input files: try all possible matches and select the longest.
16  *      The key feature of this algorithm is that insertions into the string
17  *      dictionary are very simple and thus fast, and deletions are avoided
18  *      completely. Insertions are performed at each input character, whereas
19  *      string matches are performed only when the previous match ends. So it
20  *      is preferable to spend more time in matches to allow very fast string
21  *      insertions and avoid deletions. The matching algorithm for small
22  *      strings is inspired from that of Rabin & Karp. A brute force approach
23  *      is used to find longer strings when a small match has been found.
24  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
25  *      (by Leonid Broukhis).
26  *         A previous version of this file used a more sophisticated algorithm
27  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
28  *      time, but has a larger average cost, uses more memory and is patented.
29  *      However the F&G algorithm may be faster for some highly redundant
30  *      files if the parameter max_chain_length (described below) is too large.
31  *
32  *  ACKNOWLEDGEMENTS
33  *
34  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
35  *      I found it in 'freeze' written by Leonid Broukhis.
36  *      Thanks to many people for bug reports and testing.
37  *
38  *  REFERENCES
39  *
40  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
41  *      Available in ftp://ds.internic.net/rfc/rfc1951.txt
42  *
43  *      A description of the Rabin and Karp algorithm is given in the book
44  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
45  *
46  *      Fiala,E.R., and Greene,D.H.
47  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
48  *
49  */
50 
51 #include <linux/module.h>
52 #include <linux/zutil.h>
53 #include "defutil.h"
54 
55 /* architecture-specific bits */
56 #ifdef CONFIG_ZLIB_DFLTCC
57 #  include "../zlib_dfltcc/dfltcc.h"
58 #else
59 #define DEFLATE_RESET_HOOK(strm) do {} while (0)
60 #define DEFLATE_HOOK(strm, flush, bstate) 0
61 #define DEFLATE_NEED_CHECKSUM(strm) 1
62 #define DEFLATE_DFLTCC_ENABLED() 0
63 #endif
64 
65 /* ===========================================================================
66  *  Function prototypes.
67  */
68 
69 typedef block_state (*compress_func) (deflate_state *s, int flush);
70 /* Compression function. Returns the block state after the call. */
71 
72 static void fill_window    (deflate_state *s);
73 static block_state deflate_stored (deflate_state *s, int flush);
74 static block_state deflate_fast   (deflate_state *s, int flush);
75 static block_state deflate_slow   (deflate_state *s, int flush);
76 static void lm_init        (deflate_state *s);
77 static void putShortMSB    (deflate_state *s, uInt b);
78 static int read_buf        (z_streamp strm, Byte *buf, unsigned size);
79 static uInt longest_match  (deflate_state *s, IPos cur_match);
80 
81 #ifdef DEBUG_ZLIB
82 static  void check_match (deflate_state *s, IPos start, IPos match,
83                          int length);
84 #endif
85 
86 /* ===========================================================================
87  * Local data
88  */
89 
90 #define NIL 0
91 /* Tail of hash chains */
92 
93 #ifndef TOO_FAR
94 #  define TOO_FAR 4096
95 #endif
96 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
97 
98 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
99 /* Minimum amount of lookahead, except at the end of the input file.
100  * See deflate.c for comments about the MIN_MATCH+1.
101  */
102 
103 /* Workspace to be allocated for deflate processing */
104 typedef struct deflate_workspace {
105     /* State memory for the deflator */
106     deflate_state deflate_memory;
107 #ifdef CONFIG_ZLIB_DFLTCC
108     /* State memory for s390 hardware deflate */
109     struct dfltcc_state dfltcc_memory;
110 #endif
111     Byte *window_memory;
112     Pos *prev_memory;
113     Pos *head_memory;
114     char *overlay_memory;
115 } deflate_workspace;
116 
117 #ifdef CONFIG_ZLIB_DFLTCC
118 /* dfltcc_state must be doubleword aligned for DFLTCC call */
119 static_assert(offsetof(struct deflate_workspace, dfltcc_memory) % 8 == 0);
120 #endif
121 
122 /* Values for max_lazy_match, good_match and max_chain_length, depending on
123  * the desired pack level (0..9). The values given below have been tuned to
124  * exclude worst case performance for pathological files. Better values may be
125  * found for specific files.
126  */
127 typedef struct config_s {
128    ush good_length; /* reduce lazy search above this match length */
129    ush max_lazy;    /* do not perform lazy search above this match length */
130    ush nice_length; /* quit search above this match length */
131    ush max_chain;
132    compress_func func;
133 } config;
134 
135 static const config configuration_table[10] = {
136 /*      good lazy nice chain */
137 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
138 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* maximum speed, no lazy matches */
139 /* 2 */ {4,    5, 16,    8, deflate_fast},
140 /* 3 */ {4,    6, 32,   32, deflate_fast},
141 
142 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
143 /* 5 */ {8,   16, 32,   32, deflate_slow},
144 /* 6 */ {8,   16, 128, 128, deflate_slow},
145 /* 7 */ {8,   32, 128, 256, deflate_slow},
146 /* 8 */ {32, 128, 258, 1024, deflate_slow},
147 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
148 
149 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
150  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
151  * meaning.
152  */
153 
154 #define EQUAL 0
155 /* result of memcmp for equal strings */
156 
157 /* ===========================================================================
158  * Update a hash value with the given input byte
159  * IN  assertion: all calls to UPDATE_HASH are made with consecutive
160  *    input characters, so that a running hash key can be computed from the
161  *    previous key instead of complete recalculation each time.
162  */
163 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
164 
165 
166 /* ===========================================================================
167  * Insert string str in the dictionary and set match_head to the previous head
168  * of the hash chain (the most recent string with same hash key). Return
169  * the previous length of the hash chain.
170  * IN  assertion: all calls to INSERT_STRING are made with consecutive
171  *    input characters and the first MIN_MATCH bytes of str are valid
172  *    (except for the last MIN_MATCH-1 bytes of the input file).
173  */
174 #define INSERT_STRING(s, str, match_head) \
175    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
176     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
177     s->head[s->ins_h] = (Pos)(str))
178 
179 /* ===========================================================================
180  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
181  * prev[] will be initialized on the fly.
182  */
183 #define CLEAR_HASH(s) \
184     s->head[s->hash_size-1] = NIL; \
185     memset((char *)s->head, 0, (unsigned)(s->hash_size-1)*sizeof(*s->head));
186 
187 /* ========================================================================= */
188 int zlib_deflateInit2(
189 	z_streamp strm,
190 	int  level,
191 	int  method,
192 	int  windowBits,
193 	int  memLevel,
194 	int  strategy
195 )
196 {
197     deflate_state *s;
198     int noheader = 0;
199     deflate_workspace *mem;
200     char *next;
201 
202     ush *overlay;
203     /* We overlay pending_buf and d_buf+l_buf. This works since the average
204      * output size for (length,distance) codes is <= 24 bits.
205      */
206 
207     if (strm == NULL) return Z_STREAM_ERROR;
208 
209     strm->msg = NULL;
210 
211     if (level == Z_DEFAULT_COMPRESSION) level = 6;
212 
213     mem = (deflate_workspace *) strm->workspace;
214 
215     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
216         noheader = 1;
217         windowBits = -windowBits;
218     }
219     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
220         windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
221 	strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
222         return Z_STREAM_ERROR;
223     }
224 
225     /*
226      * Direct the workspace's pointers to the chunks that were allocated
227      * along with the deflate_workspace struct.
228      */
229     next = (char *) mem;
230     next += sizeof(*mem);
231 #ifdef CONFIG_ZLIB_DFLTCC
232     /*
233      *  DFLTCC requires the window to be page aligned.
234      *  Thus, we overallocate and take the aligned portion of the buffer.
235      */
236     mem->window_memory = (Byte *) PTR_ALIGN(next, PAGE_SIZE);
237 #else
238     mem->window_memory = (Byte *) next;
239 #endif
240     next += zlib_deflate_window_memsize(windowBits);
241     mem->prev_memory = (Pos *) next;
242     next += zlib_deflate_prev_memsize(windowBits);
243     mem->head_memory = (Pos *) next;
244     next += zlib_deflate_head_memsize(memLevel);
245     mem->overlay_memory = next;
246 
247     s = (deflate_state *) &(mem->deflate_memory);
248     strm->state = (struct internal_state *)s;
249     s->strm = strm;
250 
251     s->noheader = noheader;
252     s->w_bits = windowBits;
253     s->w_size = 1 << s->w_bits;
254     s->w_mask = s->w_size - 1;
255 
256     s->hash_bits = memLevel + 7;
257     s->hash_size = 1 << s->hash_bits;
258     s->hash_mask = s->hash_size - 1;
259     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
260 
261     s->window = (Byte *) mem->window_memory;
262     s->prev   = (Pos *)  mem->prev_memory;
263     s->head   = (Pos *)  mem->head_memory;
264 
265     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
266 
267     overlay = (ush *) mem->overlay_memory;
268     s->pending_buf = (uch *) overlay;
269     s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
270 
271     s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
272     s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
273 
274     s->level = level;
275     s->strategy = strategy;
276     s->method = (Byte)method;
277 
278     return zlib_deflateReset(strm);
279 }
280 
281 /* ========================================================================= */
282 int zlib_deflateReset(
283 	z_streamp strm
284 )
285 {
286     deflate_state *s;
287 
288     if (strm == NULL || strm->state == NULL)
289         return Z_STREAM_ERROR;
290 
291     strm->total_in = strm->total_out = 0;
292     strm->msg = NULL;
293     strm->data_type = Z_UNKNOWN;
294 
295     s = (deflate_state *)strm->state;
296     s->pending = 0;
297     s->pending_out = s->pending_buf;
298 
299     if (s->noheader < 0) {
300         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
301     }
302     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
303     strm->adler = 1;
304     s->last_flush = Z_NO_FLUSH;
305 
306     zlib_tr_init(s);
307     lm_init(s);
308 
309     DEFLATE_RESET_HOOK(strm);
310 
311     return Z_OK;
312 }
313 
314 /* =========================================================================
315  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
316  * IN assertion: the stream state is correct and there is enough room in
317  * pending_buf.
318  */
319 static void putShortMSB(
320 	deflate_state *s,
321 	uInt b
322 )
323 {
324     put_byte(s, (Byte)(b >> 8));
325     put_byte(s, (Byte)(b & 0xff));
326 }
327 
328 /* ========================================================================= */
329 int zlib_deflate(
330 	z_streamp strm,
331 	int flush
332 )
333 {
334     int old_flush; /* value of flush param for previous deflate call */
335     deflate_state *s;
336 
337     if (strm == NULL || strm->state == NULL ||
338 	flush > Z_FINISH || flush < 0) {
339         return Z_STREAM_ERROR;
340     }
341     s = (deflate_state *) strm->state;
342 
343     if ((strm->next_in == NULL && strm->avail_in != 0) ||
344 	(s->status == FINISH_STATE && flush != Z_FINISH)) {
345         return Z_STREAM_ERROR;
346     }
347     if (strm->avail_out == 0) return Z_BUF_ERROR;
348 
349     s->strm = strm; /* just in case */
350     old_flush = s->last_flush;
351     s->last_flush = flush;
352 
353     /* Write the zlib header */
354     if (s->status == INIT_STATE) {
355 
356         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
357         uInt level_flags = (s->level-1) >> 1;
358 
359         if (level_flags > 3) level_flags = 3;
360         header |= (level_flags << 6);
361 	if (s->strstart != 0) header |= PRESET_DICT;
362         header += 31 - (header % 31);
363 
364         s->status = BUSY_STATE;
365         putShortMSB(s, header);
366 
367 	/* Save the adler32 of the preset dictionary: */
368 	if (s->strstart != 0) {
369 	    putShortMSB(s, (uInt)(strm->adler >> 16));
370 	    putShortMSB(s, (uInt)(strm->adler & 0xffff));
371 	}
372 	strm->adler = 1L;
373     }
374 
375     /* Flush as much pending output as possible */
376     if (s->pending != 0) {
377         flush_pending(strm);
378         if (strm->avail_out == 0) {
379 	    /* Since avail_out is 0, deflate will be called again with
380 	     * more output space, but possibly with both pending and
381 	     * avail_in equal to zero. There won't be anything to do,
382 	     * but this is not an error situation so make sure we
383 	     * return OK instead of BUF_ERROR at next call of deflate:
384              */
385 	    s->last_flush = -1;
386 	    return Z_OK;
387 	}
388 
389     /* Make sure there is something to do and avoid duplicate consecutive
390      * flushes. For repeated and useless calls with Z_FINISH, we keep
391      * returning Z_STREAM_END instead of Z_BUFF_ERROR.
392      */
393     } else if (strm->avail_in == 0 && flush <= old_flush &&
394 	       flush != Z_FINISH) {
395         return Z_BUF_ERROR;
396     }
397 
398     /* User must not provide more input after the first FINISH: */
399     if (s->status == FINISH_STATE && strm->avail_in != 0) {
400         return Z_BUF_ERROR;
401     }
402 
403     /* Start a new block or continue the current one.
404      */
405     if (strm->avail_in != 0 || s->lookahead != 0 ||
406         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
407         block_state bstate;
408 
409 	bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate :
410 		 (*(configuration_table[s->level].func))(s, flush);
411 
412         if (bstate == finish_started || bstate == finish_done) {
413             s->status = FINISH_STATE;
414         }
415         if (bstate == need_more || bstate == finish_started) {
416 	    if (strm->avail_out == 0) {
417 	        s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
418 	    }
419 	    return Z_OK;
420 	    /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
421 	     * of deflate should use the same flush parameter to make sure
422 	     * that the flush is complete. So we don't have to output an
423 	     * empty block here, this will be done at next call. This also
424 	     * ensures that for a very small output buffer, we emit at most
425 	     * one empty block.
426 	     */
427 	}
428         if (bstate == block_done) {
429             if (flush == Z_PARTIAL_FLUSH) {
430                 zlib_tr_align(s);
431 	    } else if (flush == Z_PACKET_FLUSH) {
432 		/* Output just the 3-bit `stored' block type value,
433 		   but not a zero length. */
434 		zlib_tr_stored_type_only(s);
435             } else { /* FULL_FLUSH or SYNC_FLUSH */
436                 zlib_tr_stored_block(s, (char*)0, 0L, 0);
437                 /* For a full flush, this empty block will be recognized
438                  * as a special marker by inflate_sync().
439                  */
440                 if (flush == Z_FULL_FLUSH) {
441                     CLEAR_HASH(s);             /* forget history */
442                 }
443             }
444             flush_pending(strm);
445 	    if (strm->avail_out == 0) {
446 	      s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
447 	      return Z_OK;
448 	    }
449         }
450     }
451     Assert(strm->avail_out > 0, "bug2");
452 
453     if (flush != Z_FINISH) return Z_OK;
454     if (s->noheader) return Z_STREAM_END;
455 
456     /* Write the zlib trailer (adler32) */
457     putShortMSB(s, (uInt)(strm->adler >> 16));
458     putShortMSB(s, (uInt)(strm->adler & 0xffff));
459     flush_pending(strm);
460     /* If avail_out is zero, the application will call deflate again
461      * to flush the rest.
462      */
463     s->noheader = -1; /* write the trailer only once! */
464     return s->pending != 0 ? Z_OK : Z_STREAM_END;
465 }
466 
467 /* ========================================================================= */
468 int zlib_deflateEnd(
469 	z_streamp strm
470 )
471 {
472     int status;
473     deflate_state *s;
474 
475     if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
476     s = (deflate_state *) strm->state;
477 
478     status = s->status;
479     if (status != INIT_STATE && status != BUSY_STATE &&
480 	status != FINISH_STATE) {
481       return Z_STREAM_ERROR;
482     }
483 
484     strm->state = NULL;
485 
486     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
487 }
488 
489 /* ===========================================================================
490  * Read a new buffer from the current input stream, update the adler32
491  * and total number of bytes read.  All deflate() input goes through
492  * this function so some applications may wish to modify it to avoid
493  * allocating a large strm->next_in buffer and copying from it.
494  * (See also flush_pending()).
495  */
496 static int read_buf(
497 	z_streamp strm,
498 	Byte *buf,
499 	unsigned size
500 )
501 {
502     unsigned len = strm->avail_in;
503 
504     if (len > size) len = size;
505     if (len == 0) return 0;
506 
507     strm->avail_in  -= len;
508 
509     if (!DEFLATE_NEED_CHECKSUM(strm)) {}
510     else if (!((deflate_state *)(strm->state))->noheader) {
511         strm->adler = zlib_adler32(strm->adler, strm->next_in, len);
512     }
513     memcpy(buf, strm->next_in, len);
514     strm->next_in  += len;
515     strm->total_in += len;
516 
517     return (int)len;
518 }
519 
520 /* ===========================================================================
521  * Initialize the "longest match" routines for a new zlib stream
522  */
523 static void lm_init(
524 	deflate_state *s
525 )
526 {
527     s->window_size = (ulg)2L*s->w_size;
528 
529     CLEAR_HASH(s);
530 
531     /* Set the default configuration parameters:
532      */
533     s->max_lazy_match   = configuration_table[s->level].max_lazy;
534     s->good_match       = configuration_table[s->level].good_length;
535     s->nice_match       = configuration_table[s->level].nice_length;
536     s->max_chain_length = configuration_table[s->level].max_chain;
537 
538     s->strstart = 0;
539     s->block_start = 0L;
540     s->lookahead = 0;
541     s->match_length = s->prev_length = MIN_MATCH-1;
542     s->match_available = 0;
543     s->ins_h = 0;
544 }
545 
546 /* ===========================================================================
547  * Set match_start to the longest match starting at the given string and
548  * return its length. Matches shorter or equal to prev_length are discarded,
549  * in which case the result is equal to prev_length and match_start is
550  * garbage.
551  * IN assertions: cur_match is the head of the hash chain for the current
552  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
553  * OUT assertion: the match length is not greater than s->lookahead.
554  */
555 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
556  * match.S. The code will be functionally equivalent.
557  */
558 static uInt longest_match(
559 	deflate_state *s,
560 	IPos cur_match			/* current match */
561 )
562 {
563     unsigned chain_length = s->max_chain_length;/* max hash chain length */
564     register Byte *scan = s->window + s->strstart; /* current string */
565     register Byte *match;                       /* matched string */
566     register int len;                           /* length of current match */
567     int best_len = s->prev_length;              /* best match length so far */
568     int nice_match = s->nice_match;             /* stop if match long enough */
569     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
570         s->strstart - (IPos)MAX_DIST(s) : NIL;
571     /* Stop when cur_match becomes <= limit. To simplify the code,
572      * we prevent matches with the string of window index 0.
573      */
574     Pos *prev = s->prev;
575     uInt wmask = s->w_mask;
576 
577 #ifdef UNALIGNED_OK
578     /* Compare two bytes at a time. Note: this is not always beneficial.
579      * Try with and without -DUNALIGNED_OK to check.
580      */
581     register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
582     register ush scan_start = *(ush*)scan;
583     register ush scan_end   = *(ush*)(scan+best_len-1);
584 #else
585     register Byte *strend = s->window + s->strstart + MAX_MATCH;
586     register Byte scan_end1  = scan[best_len-1];
587     register Byte scan_end   = scan[best_len];
588 #endif
589 
590     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
591      * It is easy to get rid of this optimization if necessary.
592      */
593     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
594 
595     /* Do not waste too much time if we already have a good match: */
596     if (s->prev_length >= s->good_match) {
597         chain_length >>= 2;
598     }
599     /* Do not look for matches beyond the end of the input. This is necessary
600      * to make deflate deterministic.
601      */
602     if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
603 
604     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
605 
606     do {
607         Assert(cur_match < s->strstart, "no future");
608         match = s->window + cur_match;
609 
610         /* Skip to next match if the match length cannot increase
611          * or if the match length is less than 2:
612          */
613 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
614         /* This code assumes sizeof(unsigned short) == 2. Do not use
615          * UNALIGNED_OK if your compiler uses a different size.
616          */
617         if (*(ush*)(match+best_len-1) != scan_end ||
618             *(ush*)match != scan_start) continue;
619 
620         /* It is not necessary to compare scan[2] and match[2] since they are
621          * always equal when the other bytes match, given that the hash keys
622          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
623          * strstart+3, +5, ... up to strstart+257. We check for insufficient
624          * lookahead only every 4th comparison; the 128th check will be made
625          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
626          * necessary to put more guard bytes at the end of the window, or
627          * to check more often for insufficient lookahead.
628          */
629         Assert(scan[2] == match[2], "scan[2]?");
630         scan++, match++;
631         do {
632         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
633                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
634                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
635                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
636                  scan < strend);
637         /* The funny "do {}" generates better code on most compilers */
638 
639         /* Here, scan <= window+strstart+257 */
640         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
641         if (*scan == *match) scan++;
642 
643         len = (MAX_MATCH - 1) - (int)(strend-scan);
644         scan = strend - (MAX_MATCH-1);
645 
646 #else /* UNALIGNED_OK */
647 
648         if (match[best_len]   != scan_end  ||
649             match[best_len-1] != scan_end1 ||
650             *match            != *scan     ||
651             *++match          != scan[1])      continue;
652 
653         /* The check at best_len-1 can be removed because it will be made
654          * again later. (This heuristic is not always a win.)
655          * It is not necessary to compare scan[2] and match[2] since they
656          * are always equal when the other bytes match, given that
657          * the hash keys are equal and that HASH_BITS >= 8.
658          */
659         scan += 2, match++;
660         Assert(*scan == *match, "match[2]?");
661 
662         /* We check for insufficient lookahead only every 8th comparison;
663          * the 256th check will be made at strstart+258.
664          */
665         do {
666         } while (*++scan == *++match && *++scan == *++match &&
667                  *++scan == *++match && *++scan == *++match &&
668                  *++scan == *++match && *++scan == *++match &&
669                  *++scan == *++match && *++scan == *++match &&
670                  scan < strend);
671 
672         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
673 
674         len = MAX_MATCH - (int)(strend - scan);
675         scan = strend - MAX_MATCH;
676 
677 #endif /* UNALIGNED_OK */
678 
679         if (len > best_len) {
680             s->match_start = cur_match;
681             best_len = len;
682             if (len >= nice_match) break;
683 #ifdef UNALIGNED_OK
684             scan_end = *(ush*)(scan+best_len-1);
685 #else
686             scan_end1  = scan[best_len-1];
687             scan_end   = scan[best_len];
688 #endif
689         }
690     } while ((cur_match = prev[cur_match & wmask]) > limit
691              && --chain_length != 0);
692 
693     if ((uInt)best_len <= s->lookahead) return best_len;
694     return s->lookahead;
695 }
696 
697 #ifdef DEBUG_ZLIB
698 /* ===========================================================================
699  * Check that the match at match_start is indeed a match.
700  */
701 static void check_match(
702 	deflate_state *s,
703 	IPos start,
704 	IPos match,
705 	int length
706 )
707 {
708     /* check that the match is indeed a match */
709     if (memcmp((char *)s->window + match,
710                 (char *)s->window + start, length) != EQUAL) {
711         fprintf(stderr, " start %u, match %u, length %d\n",
712 		start, match, length);
713         do {
714 	    fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
715 	} while (--length != 0);
716         z_error("invalid match");
717     }
718     if (z_verbose > 1) {
719         fprintf(stderr,"\\[%d,%d]", start-match, length);
720         do { putc(s->window[start++], stderr); } while (--length != 0);
721     }
722 }
723 #else
724 #  define check_match(s, start, match, length)
725 #endif
726 
727 /* ===========================================================================
728  * Fill the window when the lookahead becomes insufficient.
729  * Updates strstart and lookahead.
730  *
731  * IN assertion: lookahead < MIN_LOOKAHEAD
732  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
733  *    At least one byte has been read, or avail_in == 0; reads are
734  *    performed for at least two bytes (required for the zip translate_eol
735  *    option -- not supported here).
736  */
737 static void fill_window(
738 	deflate_state *s
739 )
740 {
741     register unsigned n, m;
742     register Pos *p;
743     unsigned more;    /* Amount of free space at the end of the window. */
744     uInt wsize = s->w_size;
745 
746     do {
747         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
748 
749         /* Deal with !@#$% 64K limit: */
750         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
751             more = wsize;
752 
753         } else if (more == (unsigned)(-1)) {
754             /* Very unlikely, but possible on 16 bit machine if strstart == 0
755              * and lookahead == 1 (input done one byte at time)
756              */
757             more--;
758 
759         /* If the window is almost full and there is insufficient lookahead,
760          * move the upper half to the lower one to make room in the upper half.
761          */
762         } else if (s->strstart >= wsize+MAX_DIST(s)) {
763 
764             memcpy((char *)s->window, (char *)s->window+wsize,
765                    (unsigned)wsize);
766             s->match_start -= wsize;
767             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
768             s->block_start -= (long) wsize;
769 
770             /* Slide the hash table (could be avoided with 32 bit values
771                at the expense of memory usage). We slide even when level == 0
772                to keep the hash table consistent if we switch back to level > 0
773                later. (Using level 0 permanently is not an optimal usage of
774                zlib, so we don't care about this pathological case.)
775              */
776             n = s->hash_size;
777             p = &s->head[n];
778             do {
779                 m = *--p;
780                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
781             } while (--n);
782 
783             n = wsize;
784             p = &s->prev[n];
785             do {
786                 m = *--p;
787                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
788                 /* If n is not on any hash chain, prev[n] is garbage but
789                  * its value will never be used.
790                  */
791             } while (--n);
792             more += wsize;
793         }
794         if (s->strm->avail_in == 0) return;
795 
796         /* If there was no sliding:
797          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
798          *    more == window_size - lookahead - strstart
799          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
800          * => more >= window_size - 2*WSIZE + 2
801          * In the BIG_MEM or MMAP case (not yet supported),
802          *   window_size == input_size + MIN_LOOKAHEAD  &&
803          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
804          * Otherwise, window_size == 2*WSIZE so more >= 2.
805          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
806          */
807         Assert(more >= 2, "more < 2");
808 
809         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
810         s->lookahead += n;
811 
812         /* Initialize the hash value now that we have some input: */
813         if (s->lookahead >= MIN_MATCH) {
814             s->ins_h = s->window[s->strstart];
815             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
816 #if MIN_MATCH != 3
817             Call UPDATE_HASH() MIN_MATCH-3 more times
818 #endif
819         }
820         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
821          * but this is not important since only literal bytes will be emitted.
822          */
823 
824     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
825 }
826 
827 /* ===========================================================================
828  * Flush the current block, with given end-of-file flag.
829  * IN assertion: strstart is set to the end of the current match.
830  */
831 #define FLUSH_BLOCK_ONLY(s, eof) { \
832    zlib_tr_flush_block(s, (s->block_start >= 0L ? \
833                    (char *)&s->window[(unsigned)s->block_start] : \
834                    NULL), \
835 		(ulg)((long)s->strstart - s->block_start), \
836 		(eof)); \
837    s->block_start = s->strstart; \
838    flush_pending(s->strm); \
839    Tracev((stderr,"[FLUSH]")); \
840 }
841 
842 /* Same but force premature exit if necessary. */
843 #define FLUSH_BLOCK(s, eof) { \
844    FLUSH_BLOCK_ONLY(s, eof); \
845    if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
846 }
847 
848 /* ===========================================================================
849  * Copy without compression as much as possible from the input stream, return
850  * the current block state.
851  * This function does not insert new strings in the dictionary since
852  * uncompressible data is probably not useful. This function is used
853  * only for the level=0 compression option.
854  * NOTE: this function should be optimized to avoid extra copying from
855  * window to pending_buf.
856  */
857 static block_state deflate_stored(
858 	deflate_state *s,
859 	int flush
860 )
861 {
862     /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
863      * to pending_buf_size, and each stored block has a 5 byte header:
864      */
865     ulg max_block_size = 0xffff;
866     ulg max_start;
867 
868     if (max_block_size > s->pending_buf_size - 5) {
869         max_block_size = s->pending_buf_size - 5;
870     }
871 
872     /* Copy as much as possible from input to output: */
873     for (;;) {
874         /* Fill the window as much as possible: */
875         if (s->lookahead <= 1) {
876 
877             Assert(s->strstart < s->w_size+MAX_DIST(s) ||
878 		   s->block_start >= (long)s->w_size, "slide too late");
879 
880             fill_window(s);
881             if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
882 
883             if (s->lookahead == 0) break; /* flush the current block */
884         }
885 	Assert(s->block_start >= 0L, "block gone");
886 
887 	s->strstart += s->lookahead;
888 	s->lookahead = 0;
889 
890 	/* Emit a stored block if pending_buf will be full: */
891  	max_start = s->block_start + max_block_size;
892         if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
893 	    /* strstart == 0 is possible when wraparound on 16-bit machine */
894 	    s->lookahead = (uInt)(s->strstart - max_start);
895 	    s->strstart = (uInt)max_start;
896             FLUSH_BLOCK(s, 0);
897 	}
898 	/* Flush if we may have to slide, otherwise block_start may become
899          * negative and the data will be gone:
900          */
901         if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
902             FLUSH_BLOCK(s, 0);
903 	}
904     }
905     FLUSH_BLOCK(s, flush == Z_FINISH);
906     return flush == Z_FINISH ? finish_done : block_done;
907 }
908 
909 /* ===========================================================================
910  * Compress as much as possible from the input stream, return the current
911  * block state.
912  * This function does not perform lazy evaluation of matches and inserts
913  * new strings in the dictionary only for unmatched strings or for short
914  * matches. It is used only for the fast compression options.
915  */
916 static block_state deflate_fast(
917 	deflate_state *s,
918 	int flush
919 )
920 {
921     IPos hash_head = NIL; /* head of the hash chain */
922     int bflush;           /* set if current block must be flushed */
923 
924     for (;;) {
925         /* Make sure that we always have enough lookahead, except
926          * at the end of the input file. We need MAX_MATCH bytes
927          * for the next match, plus MIN_MATCH bytes to insert the
928          * string following the next match.
929          */
930         if (s->lookahead < MIN_LOOKAHEAD) {
931             fill_window(s);
932             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
933 	        return need_more;
934 	    }
935             if (s->lookahead == 0) break; /* flush the current block */
936         }
937 
938         /* Insert the string window[strstart .. strstart+2] in the
939          * dictionary, and set hash_head to the head of the hash chain:
940          */
941         if (s->lookahead >= MIN_MATCH) {
942             INSERT_STRING(s, s->strstart, hash_head);
943         }
944 
945         /* Find the longest match, discarding those <= prev_length.
946          * At this point we have always match_length < MIN_MATCH
947          */
948         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
949             /* To simplify the code, we prevent matches with the string
950              * of window index 0 (in particular we have to avoid a match
951              * of the string with itself at the start of the input file).
952              */
953             if (s->strategy != Z_HUFFMAN_ONLY) {
954                 s->match_length = longest_match (s, hash_head);
955             }
956             /* longest_match() sets match_start */
957         }
958         if (s->match_length >= MIN_MATCH) {
959             check_match(s, s->strstart, s->match_start, s->match_length);
960 
961             bflush = zlib_tr_tally(s, s->strstart - s->match_start,
962                                s->match_length - MIN_MATCH);
963 
964             s->lookahead -= s->match_length;
965 
966             /* Insert new strings in the hash table only if the match length
967              * is not too large. This saves time but degrades compression.
968              */
969             if (s->match_length <= s->max_insert_length &&
970                 s->lookahead >= MIN_MATCH) {
971                 s->match_length--; /* string at strstart already in hash table */
972                 do {
973                     s->strstart++;
974                     INSERT_STRING(s, s->strstart, hash_head);
975                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
976                      * always MIN_MATCH bytes ahead.
977                      */
978                 } while (--s->match_length != 0);
979                 s->strstart++;
980             } else {
981                 s->strstart += s->match_length;
982                 s->match_length = 0;
983                 s->ins_h = s->window[s->strstart];
984                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
985 #if MIN_MATCH != 3
986                 Call UPDATE_HASH() MIN_MATCH-3 more times
987 #endif
988                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
989                  * matter since it will be recomputed at next deflate call.
990                  */
991             }
992         } else {
993             /* No match, output a literal byte */
994             Tracevv((stderr,"%c", s->window[s->strstart]));
995             bflush = zlib_tr_tally (s, 0, s->window[s->strstart]);
996             s->lookahead--;
997             s->strstart++;
998         }
999         if (bflush) FLUSH_BLOCK(s, 0);
1000     }
1001     FLUSH_BLOCK(s, flush == Z_FINISH);
1002     return flush == Z_FINISH ? finish_done : block_done;
1003 }
1004 
1005 /* ===========================================================================
1006  * Same as above, but achieves better compression. We use a lazy
1007  * evaluation for matches: a match is finally adopted only if there is
1008  * no better match at the next window position.
1009  */
1010 static block_state deflate_slow(
1011 	deflate_state *s,
1012 	int flush
1013 )
1014 {
1015     IPos hash_head = NIL;    /* head of hash chain */
1016     int bflush;              /* set if current block must be flushed */
1017 
1018     /* Process the input block. */
1019     for (;;) {
1020         /* Make sure that we always have enough lookahead, except
1021          * at the end of the input file. We need MAX_MATCH bytes
1022          * for the next match, plus MIN_MATCH bytes to insert the
1023          * string following the next match.
1024          */
1025         if (s->lookahead < MIN_LOOKAHEAD) {
1026             fill_window(s);
1027             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1028 	        return need_more;
1029 	    }
1030             if (s->lookahead == 0) break; /* flush the current block */
1031         }
1032 
1033         /* Insert the string window[strstart .. strstart+2] in the
1034          * dictionary, and set hash_head to the head of the hash chain:
1035          */
1036         if (s->lookahead >= MIN_MATCH) {
1037             INSERT_STRING(s, s->strstart, hash_head);
1038         }
1039 
1040         /* Find the longest match, discarding those <= prev_length.
1041          */
1042         s->prev_length = s->match_length, s->prev_match = s->match_start;
1043         s->match_length = MIN_MATCH-1;
1044 
1045         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1046             s->strstart - hash_head <= MAX_DIST(s)) {
1047             /* To simplify the code, we prevent matches with the string
1048              * of window index 0 (in particular we have to avoid a match
1049              * of the string with itself at the start of the input file).
1050              */
1051             if (s->strategy != Z_HUFFMAN_ONLY) {
1052                 s->match_length = longest_match (s, hash_head);
1053             }
1054             /* longest_match() sets match_start */
1055 
1056             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
1057                  (s->match_length == MIN_MATCH &&
1058                   s->strstart - s->match_start > TOO_FAR))) {
1059 
1060                 /* If prev_match is also MIN_MATCH, match_start is garbage
1061                  * but we will ignore the current match anyway.
1062                  */
1063                 s->match_length = MIN_MATCH-1;
1064             }
1065         }
1066         /* If there was a match at the previous step and the current
1067          * match is not better, output the previous match:
1068          */
1069         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1070             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1071             /* Do not insert strings in hash table beyond this. */
1072 
1073             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1074 
1075             bflush = zlib_tr_tally(s, s->strstart -1 - s->prev_match,
1076 				   s->prev_length - MIN_MATCH);
1077 
1078             /* Insert in hash table all strings up to the end of the match.
1079              * strstart-1 and strstart are already inserted. If there is not
1080              * enough lookahead, the last two strings are not inserted in
1081              * the hash table.
1082              */
1083             s->lookahead -= s->prev_length-1;
1084             s->prev_length -= 2;
1085             do {
1086                 if (++s->strstart <= max_insert) {
1087                     INSERT_STRING(s, s->strstart, hash_head);
1088                 }
1089             } while (--s->prev_length != 0);
1090             s->match_available = 0;
1091             s->match_length = MIN_MATCH-1;
1092             s->strstart++;
1093 
1094             if (bflush) FLUSH_BLOCK(s, 0);
1095 
1096         } else if (s->match_available) {
1097             /* If there was no match at the previous position, output a
1098              * single literal. If there was a match but the current match
1099              * is longer, truncate the previous match to a single literal.
1100              */
1101             Tracevv((stderr,"%c", s->window[s->strstart-1]));
1102             if (zlib_tr_tally (s, 0, s->window[s->strstart-1])) {
1103                 FLUSH_BLOCK_ONLY(s, 0);
1104             }
1105             s->strstart++;
1106             s->lookahead--;
1107             if (s->strm->avail_out == 0) return need_more;
1108         } else {
1109             /* There is no previous match to compare with, wait for
1110              * the next step to decide.
1111              */
1112             s->match_available = 1;
1113             s->strstart++;
1114             s->lookahead--;
1115         }
1116     }
1117     Assert (flush != Z_NO_FLUSH, "no flush?");
1118     if (s->match_available) {
1119         Tracevv((stderr,"%c", s->window[s->strstart-1]));
1120         zlib_tr_tally (s, 0, s->window[s->strstart-1]);
1121         s->match_available = 0;
1122     }
1123     FLUSH_BLOCK(s, flush == Z_FINISH);
1124     return flush == Z_FINISH ? finish_done : block_done;
1125 }
1126 
1127 int zlib_deflate_workspacesize(int windowBits, int memLevel)
1128 {
1129     if (windowBits < 0) /* undocumented feature: suppress zlib header */
1130         windowBits = -windowBits;
1131 
1132     /* Since the return value is typically passed to vmalloc() unchecked... */
1133     BUG_ON(memLevel < 1 || memLevel > MAX_MEM_LEVEL || windowBits < 9 ||
1134 							windowBits > 15);
1135 
1136     return sizeof(deflate_workspace)
1137         + zlib_deflate_window_memsize(windowBits)
1138         + zlib_deflate_prev_memsize(windowBits)
1139         + zlib_deflate_head_memsize(memLevel)
1140         + zlib_deflate_overlay_memsize(memLevel);
1141 }
1142 
1143 int zlib_deflate_dfltcc_enabled(void)
1144 {
1145 	return DEFLATE_DFLTCC_ENABLED();
1146 }
1147