1 /* Because this code is derived from the 4.3BSD compress source:
4 * Copyright (c) 1985, 1986 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
8 * James A. Woods, derived from original work by Spencer Thomas
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 * This version is for use with STREAMS under SunOS 4.x.
44 #include <sys/param.h>
45 #include <sys/types.h>
46 #include <sys/stream.h>
47 #include <sys/kmem_alloc.h>
48 #include <net/ppp_str.h>
51 #include <net/ppp-comp.h>
54 * PPP "BSD compress" compression
55 * The differences between this compression and the classic BSD LZW
56 * source are obvious from the requirement that the classic code worked
57 * with files while this handles arbitrarily long streams that
58 * are broken into packets. They are:
60 * When the code size expands, a block of junk is not emitted by
61 * the compressor and not expected by the decompressor.
63 * New codes are not necessarily assigned every time an old
64 * code is output by the compressor. This is because a packet
65 * end forces a code to be emitted, but does not imply that a
66 * new sequence has been seen.
68 * The compression ratio is checked at the first end of a packet
69 * after the appropriate gap. Besides simplifying and speeding
70 * things up, this makes it more likely that the transmitter
71 * and receiver will agree when the dictionary is cleared when
72 * compression is not going well.
76 * A dictionary for doing BSD compress.
79 int totlen; /* length of this structure */
80 u_int hsize; /* size of the hash table */
81 u_char hshift; /* used in hash function */
82 u_char n_bits; /* current bits/code */
86 u_int maxmaxcode; /* largest valid code */
87 u_int max_ent; /* largest code in use */
88 u_long seqno; /* # of last byte of packet */
89 u_long in_count; /* uncompressed bytes */
90 u_long bytes_out; /* compressed bytes */
91 u_long ratio; /* recent compression ratio */
92 u_long checkpoint; /* when to next check the ratio */
93 int clear_count; /* times dictionary cleared */
94 int incomp_count; /* incompressible packets */
95 u_short *lens; /* array of lengths of codes */
97 union { /* hash value */
100 #ifdef BSD_LITTLE_ENDIAN
101 u_short prefix; /* preceding code */
102 u_char suffix; /* last character of new code */
106 u_char suffix; /* last character of new code */
107 u_short prefix; /* preceding code */
111 u_short codem1; /* output of hash table -1 */
112 u_short cptr; /* map code to hash table entry */
116 #define BSD_OVHD 3 /* BSD compress overhead/packet */
117 #define MIN_BSD_BITS 9
118 #define BSD_INIT_BITS MIN_BSD_BITS
119 #define MAX_BSD_BITS 15
121 static void *bsd_comp_alloc __P((u_char *options, int opt_len));
122 static void *bsd_decomp_alloc __P((u_char *options, int opt_len));
123 static void bsd_free __P((void *state));
124 static int bsd_comp_init __P((void *state, u_char *options, int opt_len,
125 int unit, int debug));
126 static int bsd_decomp_init __P((void *state, u_char *options, int opt_len,
127 int unit, int mru, int debug));
128 static int bsd_compress __P((void *state, mblk_t **mret,
129 mblk_t *mp, int slen, int maxolen));
130 static void bsd_incomp __P((void *state, mblk_t *dmsg));
131 static mblk_t *bsd_decompress __P((void *state, mblk_t *cmp, int hdroff));
132 static void bsd_reset __P((void *state));
135 * Procedures exported to ppp_comp.c.
137 struct compressor ppp_bsd_compress = {
138 0x21, /* compress_proto */
139 bsd_comp_alloc, /* comp_alloc */
140 bsd_free, /* comp_free */
141 bsd_comp_init, /* comp_init */
142 bsd_reset, /* comp_reset */
143 bsd_compress, /* compress */
144 bsd_decomp_alloc, /* decomp_alloc */
145 bsd_free, /* decomp_free */
146 bsd_decomp_init, /* decomp_init */
147 bsd_reset, /* decomp_reset */
148 bsd_decompress, /* decompress */
149 bsd_incomp, /* incomp */
153 * the next two codes should not be changed lightly, as they must not
154 * lie within the contiguous general code space.
156 #define CLEAR 256 /* table clear output code */
157 #define FIRST 257 /* first free entry */
160 #define MAXCODE(b) ((1 << (b)) - 1)
161 #define BADCODEM1 MAXCODE(MAX_BSD_BITS);
163 #define BSD_HASH(prefix,suffix,hshift) ((((u_long)(suffix)) << (hshift)) \
165 #define BSD_KEY(prefix,suffix) ((((u_long)(suffix)) << 16) + (u_long)(prefix))
167 #define CHECK_GAP 10000 /* Ratio check interval */
171 * clear the dictionary
178 db->max_ent = FIRST-1;
179 db->n_bits = BSD_INIT_BITS;
183 db->incomp_count = 0;
184 db->checkpoint = CHECK_GAP;
188 * If the dictionary is full, then see if it is time to reset it.
190 * Compute the compression ratio using fixed-point arithmetic
191 * with 8 fractional bits.
193 * Since we have an infinite stream instead of a single file,
194 * watch only the local compression ratio.
196 * Since both peers must reset the dictionary at the same time even in
197 * the absence of CLEAR codes (while packets are incompressible), they
198 * must compute the same ratio.
200 static int /* 1=output CLEAR */
206 if (db->in_count >= db->checkpoint) {
207 /* age the ratio by limiting the size of the counts */
208 if (db->in_count >= 0x7fffff
209 || db->bytes_out >= 0x7fffff) {
210 db->in_count -= db->in_count/4;
211 db->bytes_out -= db->bytes_out/4;
214 db->checkpoint = db->in_count + CHECK_GAP;
216 if (db->max_ent >= db->maxmaxcode) {
217 /* Reset the dictionary only if the ratio is worse,
218 * or if it looks as if it has been poisoned
219 * by incompressible data.
221 * This does not overflow, because
222 * db->in_count <= 0x7fffff.
224 new_ratio = db->in_count<<8;
225 if (db->bytes_out != 0)
226 new_ratio /= db->bytes_out;
228 if (new_ratio < db->ratio || new_ratio < 256) {
232 db->ratio = new_ratio;
239 * Reset state, as on a CCP ResetReq.
245 struct bsd_db *db = (struct bsd_db *) state;
253 * Allocate space for a (de) compressor.
256 bsd_alloc(options, opt_len, decomp)
261 u_int newlen, hsize, hshift, maxmaxcode;
264 if (opt_len != 3 || options[0] != 0x21 || options[1] != 3)
268 case 9: /* needs 82152 for both directions */
269 case 10: /* needs 84144 */
270 case 11: /* needs 88240 */
271 case 12: /* needs 96432 */
275 case 13: /* needs 176784 */
279 case 14: /* needs 353744 */
283 case 15: /* needs 691440 */
287 case 16: /* needs 1366160--far too much, */
288 /* hsize = 69001; */ /* and 69001 is too big for cptr */
289 /* hshift = 8; */ /* in struct bsd_db */
295 maxmaxcode = MAXCODE(bits);
296 newlen = sizeof(*db) + (hsize-1) * (sizeof(db->dict[0]));
297 db = (struct bsd_db *) kmem_alloc(newlen, KMEM_NOSLEEP);
300 bzero(db, sizeof(*db) - sizeof(db->dict));
305 db->lens = (u_short *) kmem_alloc((maxmaxcode+1) * sizeof(db->lens[0]),
308 kmem_free(db, newlen);
316 db->maxmaxcode = maxmaxcode;
325 struct bsd_db *db = (struct bsd_db *) state;
328 kmem_free(db->lens, (db->maxmaxcode+1) * sizeof(db->lens[0]));
329 kmem_free(db, db->totlen);
333 bsd_comp_alloc(options, opt_len)
337 return bsd_alloc(options, opt_len, 0);
341 bsd_decomp_alloc(options, opt_len)
345 return bsd_alloc(options, opt_len, 1);
349 * Initialize the database.
352 bsd_init(db, options, opt_len, unit, mru, debug, decomp)
355 int opt_len, unit, mru, debug, decomp;
359 if (opt_len != 3 || options[0] != 0x21 || options[1] != 3
360 || MAXCODE(options[2]) != db->maxmaxcode
361 || decomp && db->lens == NULL)
371 db->dict[--i].codem1 = BADCODEM1;
372 db->dict[i].cptr = 0;
377 db->clear_count = -1;
387 bsd_comp_init(state, options, opt_len, unit, debug)
390 int opt_len, unit, debug;
392 return bsd_init((struct bsd_db *) state, options, opt_len,
397 bsd_decomp_init(state, options, opt_len, unit, mru, debug)
400 int opt_len, unit, mru, debug;
402 return bsd_init((struct bsd_db *) state, options, opt_len,
403 unit, mru, debug, 1);
410 * Assume the protocol is known to be >= 0x21 and < 0xff.
411 * One change from the BSD compress command is that when the
412 * code size expands, we do not output a bunch of padding.
414 static int /* new slen */
415 bsd_compress(state, mret, mp, slen, maxolen)
417 mblk_t **mret; /* return compressed mbuf chain here */
418 mblk_t *mp; /* from here */
419 int slen; /* uncompressed length */
420 int maxolen; /* max compressed length */
422 struct bsd_db *db = (struct bsd_db *) state;
423 int hshift = db->hshift;
424 u_int max_ent = db->max_ent;
425 u_int n_bits = db->n_bits;
428 struct bsd_dict *dictp;
431 long hval, disp, ent;
439 #define PUTBYTE(v) { \
442 if (wptr >= cp_end) { \
447 cp_end = m->b_datap->db_lim; \
455 #define OUTPUT(ent) { \
457 accm |= ((ent) << bitno); \
459 PUTBYTE(accm >> 24); \
462 } while (bitno <= 24); \
465 /* Don't generate compressed packets which are larger than
466 the uncompressed packet. */
470 /* Allocate enough message blocks to give maxolen total space. */
472 for (olen = maxolen; olen > 0; ) {
473 m = allocb((olen < 4096? olen: 4096), BPRI_MED);
483 olen -= m->b_datap->db_lim - m->b_wptr;
488 if ((m = *mret) != NULL) {
490 cp_end = m->b_datap->db_lim;
492 wptr = cp_end = NULL;
495 /* Copy the PPP header over, changing the protocol */
497 *wptr++ = rptr[0]; /* assumes the ppp header is */
498 *wptr++ = rptr[1]; /* all in one mblk */
499 *wptr++ = 0; /* change the protocol */
503 /* install the 3-byte sequence number */
504 slen += db->seqno - PPP_HDRLEN + 1;
510 /* start with the protocol byte */
513 slen = mp->b_wptr - rptr;
514 db->in_count += slen + 1;
521 slen = np->b_wptr - rptr;
524 continue; /* handle 0-length buffers */
525 db->in_count += slen;
530 fcode = BSD_KEY(ent, c);
531 hval = BSD_HASH(ent, c, hshift);
532 dictp = &db->dict[hval];
534 /* Validate and then check the entry. */
535 if (dictp->codem1 >= max_ent)
537 if (dictp->f.fcode == fcode) {
538 ent = dictp->codem1+1;
539 continue; /* found (prefix,suffix) */
542 /* continue probing until a match or invalid entry */
543 disp = (hval == 0) ? 1 : hval;
546 if (hval >= db->hsize)
548 dictp = &db->dict[hval];
549 if (dictp->codem1 >= max_ent)
551 } while (dictp->f.fcode != fcode);
552 ent = dictp->codem1+1; /* finally found (prefix,suffix) */
556 OUTPUT(ent); /* output the prefix */
558 /* code -> hashtable */
559 if (max_ent < db->maxmaxcode) {
560 struct bsd_dict *dictp2;
561 /* expand code size if needed */
562 if (max_ent >= MAXCODE(n_bits))
563 db->n_bits = ++n_bits;
565 /* Invalidate old hash table entry using
566 * this code, and then take it over.
568 dictp2 = &db->dict[max_ent+1];
569 if (db->dict[dictp2->cptr].codem1 == max_ent)
570 db->dict[dictp2->cptr].codem1 = BADCODEM1;
572 dictp->codem1 = max_ent;
573 dictp->f.fcode = fcode;
575 db->max_ent = ++max_ent;
580 OUTPUT(ent); /* output the last code */
581 db->bytes_out += olen;
584 OUTPUT(CLEAR); /* do not count the CLEAR */
586 /* Pad dribble bits of last code with ones.
587 * Do not emit a completely useless byte of ones.
590 PUTBYTE((accm | (0xff << (bitno-8))) >> 24);
592 /* Increase code size if we would have without the packet
593 * boundary and as the decompressor will.
595 if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
598 if (olen + PPP_HDRLEN + BSD_OVHD > maxolen && *mret != NULL) {
599 /* throw away the compressed stuff if it is longer than uncompressed */
602 } else if (wptr != NULL) {
610 return olen + PPP_HDRLEN + BSD_OVHD;
617 * Update the "BSD Compress" dictionary on the receiver for
618 * incompressible data by pretending to compress the incoming data.
619 * The protocol is assumed to be < 0x100.
622 bsd_incomp(state, dmsg)
626 struct bsd_db *db = (struct bsd_db *) state;
627 u_int hshift = db->hshift;
628 u_int max_ent = db->max_ent;
629 u_int n_bits = db->n_bits;
630 struct bsd_dict *dictp;
642 db->in_count++; /* count the protocol as 1 byte */
644 ent = rptr[3]; /* get the protocol */
647 slen = dmsg->b_wptr - rptr;
653 continue; /* skip zero-length buffers */
655 db->in_count += slen;
660 fcode = BSD_KEY(ent, c);
661 hval = BSD_HASH(ent, c, hshift);
662 dictp = &db->dict[hval];
664 /* validate and then check the entry */
665 if (dictp->codem1 >= max_ent)
667 if (dictp->f.fcode == fcode) {
668 ent = dictp->codem1+1;
669 continue; /* found (prefix,suffix) */
672 /* continue probing until a match or invalid entry */
673 disp = (hval == 0) ? 1 : hval;
676 if (hval >= db->hsize)
678 dictp = &db->dict[hval];
679 if (dictp->codem1 >= max_ent)
681 } while (dictp->f.fcode != fcode);
682 ent = dictp->codem1+1;
683 continue; /* finally found (prefix,suffix) */
685 nomatch: /* output (count) the prefix */
688 /* code -> hashtable */
689 if (max_ent < db->maxmaxcode) {
690 struct bsd_dict *dictp2;
691 /* expand code size if needed */
692 if (max_ent >= MAXCODE(n_bits))
693 db->n_bits = ++n_bits;
695 /* Invalidate previous hash table entry
696 * assigned this code, and then take it over.
698 dictp2 = &db->dict[max_ent+1];
699 if (db->dict[dictp2->cptr].codem1 == max_ent)
700 db->dict[dictp2->cptr].codem1 = BADCODEM1;
702 dictp->codem1 = max_ent;
703 dictp->f.fcode = fcode;
705 db->max_ent = ++max_ent;
706 db->lens[max_ent] = db->lens[ent]+1;
709 } while (--slen != 0);
711 bitno += n_bits; /* output (count) the last code */
712 db->bytes_out += bitno/8;
715 /* Increase code size if we would have without the packet
716 * boundary and as the decompressor will.
718 if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
724 * Decompress "BSD Compress"
726 static mblk_t * /* 0=failed, so zap CCP */
727 bsd_decompress(state, cmsg, hdroff)
732 struct bsd_db *db = (struct bsd_db *) state;
733 u_int max_ent = db->max_ent;
735 u_int bitno = 32; /* 1st valid bit in accm */
736 u_int n_bits = db->n_bits;
737 u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
738 struct bsd_dict *dictp;
739 int explen, i, seq, len;
740 u_int incode, oldcode, finchar;
741 u_char *p, *rptr, *wptr;
744 int dlen, space, codelen;
747 * Get at least the BSD Compress header in the first buffer
750 if (rptr + PPP_HDRLEN + BSD_OVHD <= cmsg->b_wptr) {
751 if (!pullupmsg(cmsg, PPP_HDRLEN + BSD_OVHD + 1)) {
753 printf("bsd_decomp%d: failed to pullup\n", db->unit);
760 * Save the address/control from the PPP header
761 * and then get the sequence number.
763 adrs = PPP_ADDRESS(rptr);
764 ctrl = PPP_CONTROL(rptr);
766 seq = (rptr[0] << 16) + (rptr[1] << 8) + rptr[2];
768 len = cmsg->b_wptr - rptr;
770 /* check the sequence number and give up if the length is nonsense */
771 explen = (seq - db->seqno) & 0xffffff;
773 if (explen > db->mru || explen < 1) {
775 printf("bsd_decomp%d: bad length 0x%x\n", db->unit, explen);
779 /* allocate enough message blocks for the decompressed message */
780 dlen = explen + PPP_HDRLEN - 1 + hdroff;
781 /* XXX assume decompressed packet fits in a single block */
782 dmsg = allocb(dlen, BPRI_HI);
784 /* give up if cannot get an uncompressed buffer */
789 /* Fill in the ppp header, but not the last byte of the protocol
790 (that comes from the decompressed data). */
794 wptr += PPP_HDRLEN - 1;
795 space = dmsg->b_datap->db_lim - wptr;
797 db->bytes_out += len;
803 if (!cmsg) { /* quit at end of message */
807 printf("bsd_decomp%d: lost %d bytes\n",
814 len = cmsg->b_wptr - rptr;
815 db->bytes_out += len;
816 continue; /* handle 0-length buffers */
819 /* Accumulate bytes until we have a complete code.
820 * Then get the next code, relying on the 32-bit,
821 * unsigned accm to mask the result.
824 accm |= *rptr++ << bitno;
826 if (tgtbitno < bitno)
828 incode = accm >> tgtbitno;
832 if (incode == CLEAR) {
833 /* The dictionary must only be cleared at
834 * the end of a packet. But there could be an
835 * empty message block at the end.
837 if (len > 0 || cmsg->b_cont != 0) {
839 len += msgdsize(cmsg->b_cont);
843 printf("bsd_decomp%d: bad CLEAR\n", db->unit);
852 /* Special case for KwKwK string. */
853 if (incode > max_ent) {
854 if (incode > max_ent+2 || incode > db->maxmaxcode
855 || oldcode == CLEAR) {
858 printf("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
859 db->unit, incode, oldcode);
860 printf("max_ent=0x%x dlen=%d seqno=%d\n",
861 max_ent, dlen, db->seqno);
870 codelen = db->lens[finchar];
875 printf("bsd_decomp%d: ran out of buffer\n", db->unit);
879 /* decode code and install in decompressed buffer */
884 len += msgdsize(cmsg->b_cont);
885 printf("bsd_decomp%d: overran output by %d with %d bytes left\n",
886 db->unit, -space, len);
891 p = (wptr += codelen);
892 while (finchar > LAST) {
893 dictp = &db->dict[db->dict[finchar].cptr];
898 printf("bsd_decomp%d: fell off end of chain ", db->unit);
899 printf("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
900 incode, finchar, db->dict[finchar].cptr, max_ent);
903 if (dictp->codem1 != finchar-1) {
905 printf("bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",
906 db->unit, incode, finchar);
907 printf("oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode,
908 db->dict[finchar].cptr, dictp->codem1);
912 *--p = dictp->f.hs.suffix;
913 finchar = dictp->f.hs.prefix;
919 printf("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
920 db->unit, codelen, incode, max_ent);
923 if (incode > max_ent) { /* the KwKwK case again */
929 * If not first code in a packet, and
930 * if not out of code space, then allocate a new code.
932 * Keep the hash table correct so it can be used
933 * with uncompressed packets.
935 if (oldcode != CLEAR && max_ent < db->maxmaxcode) {
936 struct bsd_dict *dictp2;
940 fcode = BSD_KEY(oldcode,finchar);
941 hval = BSD_HASH(oldcode,finchar,db->hshift);
942 dictp = &db->dict[hval];
944 /* look for a free hash table entry */
945 if (dictp->codem1 < max_ent) {
946 disp = (hval == 0) ? 1 : hval;
949 if (hval >= db->hsize)
951 dictp = &db->dict[hval];
952 } while (dictp->codem1 < max_ent);
955 /* Invalidate previous hash table entry
956 * assigned this code, and then take it over
958 dictp2 = &db->dict[max_ent+1];
959 if (db->dict[dictp2->cptr].codem1 == max_ent) {
960 db->dict[dictp2->cptr].codem1 = BADCODEM1;
963 dictp->codem1 = max_ent;
964 dictp->f.fcode = fcode;
966 db->max_ent = ++max_ent;
967 db->lens[max_ent] = db->lens[oldcode]+1;
969 /* Expand code size if needed. */
970 if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) {
971 db->n_bits = ++n_bits;
972 tgtbitno = 32-n_bits;
979 /* fail on packets with bad lengths/sequence numbers */
985 /* Keep the checkpoint right so that incompressible packets
986 * clear the dictionary at the right times.
988 db->in_count += explen;
989 if (bsd_check(db) && db->debug) {
990 printf("bsd_decomp%d: peer should have cleared dictionary\n",