]> git.ozlabs.org Git - ppp.git/blob - linux/bsd_comp.c
*** empty log message ***
[ppp.git] / linux / bsd_comp.c
1 /* Because this code is derived from the 4.3BSD compress source:
2  *
3  * Copyright (c) 1985, 1986 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * James A. Woods, derived from original work by Spencer Thomas
8  * and Joseph Orost.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38
39 /*
40  * This version is for use with contiguous buffers on Linux-derived systems.
41  *
42  *  ==FILEVERSION 5==
43  *
44  *  NOTE TO MAINTAINERS:
45  *     If you modify this file at all, increment the number above.
46  *     bsd_comp.c is shipped with a PPP distribution as well as with
47  *     the kernel; if everyone increases the FILEVERSION number above,
48  *     then scripts can do the right thing when deciding whether to
49  *     install a new bsd_comp.c file. Don't change the format of that
50  *     line otherwise, so the installation script can recognize it.
51  *
52  * From: bsd_comp.c,v 1.3 1994/12/08 01:59:58 paulus Exp
53  */
54
55 #ifndef MODULE
56 #error This file must be compiled as a module.
57 #endif
58
59 #include <linux/module.h>
60
61 #include <endian.h>
62 #include <linux/kernel.h>
63 #include <linux/sched.h>
64 #include <linux/types.h>
65 #include <linux/fcntl.h>
66 #include <linux/interrupt.h>
67 #include <linux/ptrace.h>
68 #include <linux/ioport.h>
69 #include <linux/in.h>
70 #include <linux/malloc.h>
71 #include <linux/tty.h>
72 #include <linux/errno.h>
73 #include <linux/sched.h>        /* to get the struct task_struct */
74 #include <linux/string.h>       /* used in new tty drivers */
75 #include <linux/signal.h>       /* used in new tty drivers */
76
77 #include <asm/system.h>
78 #include <asm/bitops.h>
79 #include <asm/segment.h>
80
81 #include <linux/if.h>
82
83 #include <linux/if_ether.h>
84 #include <linux/netdevice.h>
85 #include <linux/skbuff.h>
86 #include <linux/inet.h>
87 #include <linux/ioctl.h>
88
89 #include <linux/ppp_defs.h>
90
91 #ifdef NEW_SKBUFF
92 #include <linux/netprotocol.h>
93 #endif
94
95 #include <linux/ip.h>
96 #include <linux/tcp.h>
97 #include <linux/if_arp.h>
98
99 #undef   PACKETPTR
100 #define  PACKETPTR 1
101 #include <linux/ppp-comp.h>
102 #undef   PACKETPTR
103
104 /*
105  * PPP "BSD compress" compression
106  *  The differences between this compression and the classic BSD LZW
107  *  source are obvious from the requirement that the classic code worked
108  *  with files while this handles arbitrarily long streams that
109  *  are broken into packets.  They are:
110  *
111  *      When the code size expands, a block of junk is not emitted by
112  *          the compressor and not expected by the decompressor.
113  *
114  *      New codes are not necessarily assigned every time an old
115  *          code is output by the compressor.  This is because a packet
116  *          end forces a code to be emitted, but does not imply that a
117  *          new sequence has been seen.
118  *
119  *      The compression ratio is checked at the first end of a packet
120  *          after the appropriate gap.  Besides simplifying and speeding
121  *          things up, this makes it more likely that the transmitter
122  *          and receiver will agree when the dictionary is cleared when
123  *          compression is not going well.
124  */
125
126 /*
127  * Macros to extract protocol version and number of bits
128  * from the third byte of the BSD Compress CCP configuration option.
129  */
130
131 #define BSD_VERSION(x)  ((x) >> 5)
132 #define BSD_NBITS(x)    ((x) & 0x1F)
133
134 #define BSD_CURRENT_VERSION     1
135
136 /*
137  * A dictionary for doing BSD compress.
138  */
139
140 struct bsd_dict {
141     union {                             /* hash value */
142         unsigned long   fcode;
143         struct {
144 #ifndef BIG_ENDIAN_BITFIELD /* Little endian order */
145             unsigned short      prefix; /* preceding code */
146             unsigned char       suffix; /* last character of new code */
147             unsigned char       pad;
148 #else /* Big endian order */
149             unsigned char       pad;
150             unsigned char       suffix; /* last character of new code */
151             unsigned short      prefix; /* preceding code */
152 #endif
153         } hs;
154     } f;
155     unsigned short codem1;              /* output of hash table -1 */
156     unsigned short cptr;                /* map code to hash table entry */
157 };
158
159 struct bsd_db {
160     int     totlen;                     /* length of this structure */
161     unsigned int   hsize;               /* size of the hash table */
162     unsigned char  hshift;              /* used in hash function */
163     unsigned char  n_bits;              /* current bits/code */
164     unsigned char  maxbits;             /* maximum bits/code */
165     unsigned char  debug;               /* non-zero if debug desired */
166     unsigned char  unit;                /* ppp unit number */
167     unsigned short seqno;               /* sequence # of next packet */
168     unsigned int   mru;                 /* size of receive (decompress) bufr */
169     unsigned int   maxmaxcode;          /* largest valid code */
170     unsigned int   max_ent;             /* largest code in use */
171     unsigned int   in_count;            /* uncompressed bytes, aged */
172     unsigned int   bytes_out;           /* compressed bytes, aged */
173     unsigned int   ratio;               /* recent compression ratio */
174     unsigned int   checkpoint;          /* when to next check the ratio */
175     unsigned int   clear_count;         /* times dictionary cleared */
176     unsigned int   incomp_count;        /* incompressible packets */
177     unsigned int   incomp_bytes;        /* incompressible bytes */
178     unsigned int   uncomp_count;        /* uncompressed packets */
179     unsigned int   uncomp_bytes;        /* uncompressed bytes */
180     unsigned int   comp_count;          /* compressed packets */
181     unsigned int   comp_bytes;          /* compressed bytes */
182     unsigned short  *lens;              /* array of lengths of codes */
183     struct bsd_dict *dict;              /* dictionary */
184 };
185
186 #define BSD_OVHD        2               /* BSD compress overhead/packet */
187 #define MIN_BSD_BITS    9
188 #define BSD_INIT_BITS   MIN_BSD_BITS
189 #define MAX_BSD_BITS    15
190
191 static void     bsd_free (void *state);
192 static void     *bsd_alloc(unsigned char *options, int opt_len, int decomp);
193 static void     *bsd_comp_alloc (unsigned char *options, int opt_len);
194 static void     *bsd_decomp_alloc (unsigned char *options, int opt_len);
195
196 static int      bsd_init        (void *db, unsigned char *options,
197                                  int opt_len, int unit, int debug, int decomp);
198 static int      bsd_comp_init   (void *state, unsigned char *options,
199                                  int opt_len, int unit, int opthdr, int debug);
200 static int      bsd_decomp_init (void *state, unsigned char *options,
201                                  int opt_len, int unit, int opthdr, int mru,
202                                  int debug);
203
204 static void     bsd_reset (void *state);
205 static void     bsd_comp_stats (void *state, struct compstat *stats);
206
207 static int      bsd_compress (void *state, unsigned char *rptr,
208                               unsigned char *obuf, int isize, int osize);
209 static void     bsd_incomp (void *state, unsigned char *ibuf, int icnt);
210
211 static int      bsd_decompress (void *state, unsigned char *ibuf, int isize,
212                                 unsigned char *obuf, int osize);
213
214 /* These are in ppp.c */
215 extern int  ppp_register_compressor   (struct compressor *cp);
216 extern void ppp_unregister_compressor (struct compressor *cp);
217
218 /*
219  * the next two codes should not be changed lightly, as they must not
220  * lie within the contiguous general code space.
221  */
222 #define CLEAR   256                     /* table clear output code */
223 #define FIRST   257                     /* first free entry */
224 #define LAST    255
225
226 #define MAXCODE(b)      ((1 << (b)) - 1)
227 #define BADCODEM1       MAXCODE(MAX_BSD_BITS);
228
229 #define BSD_HASH(prefix,suffix,hshift) ((((unsigned long)(suffix))<<(hshift)) \
230                                          ^ (unsigned long)(prefix))
231 #define BSD_KEY(prefix,suffix)          ((((unsigned long)(suffix)) << 16) \
232                                          + (unsigned long)(prefix))
233
234 #define CHECK_GAP       10000           /* Ratio check interval */
235
236 #define RATIO_SCALE_LOG 8
237 #define RATIO_SCALE     (1<<RATIO_SCALE_LOG)
238 #define RATIO_MAX       (0x7fffffff>>RATIO_SCALE_LOG)
239
240 /*
241  * clear the dictionary
242  */
243
244 static void
245 bsd_clear(struct bsd_db *db)
246 {
247     db->clear_count++;
248     db->max_ent      = FIRST-1;
249     db->n_bits       = BSD_INIT_BITS;
250     db->bytes_out    = 0;
251     db->in_count     = 0;
252     db->ratio        = 0;
253     db->checkpoint   = CHECK_GAP;
254 }
255
256 /*
257  * If the dictionary is full, then see if it is time to reset it.
258  *
259  * Compute the compression ratio using fixed-point arithmetic
260  * with 8 fractional bits.
261  *
262  * Since we have an infinite stream instead of a single file,
263  * watch only the local compression ratio.
264  *
265  * Since both peers must reset the dictionary at the same time even in
266  * the absence of CLEAR codes (while packets are incompressible), they
267  * must compute the same ratio.
268  */
269
270 static int bsd_check (struct bsd_db *db)        /* 1=output CLEAR */
271   {
272     unsigned int new_ratio;
273
274     if (db->in_count >= db->checkpoint)
275       {
276         /* age the ratio by limiting the size of the counts */
277         if (db->in_count >= RATIO_MAX || db->bytes_out >= RATIO_MAX)
278           {
279             db->in_count  -= (db->in_count  >> 2);
280             db->bytes_out -= (db->bytes_out >> 2);
281           }
282         
283         db->checkpoint = db->in_count + CHECK_GAP;
284         
285         if (db->max_ent >= db->maxmaxcode)
286           {
287             /* Reset the dictionary only if the ratio is worse,
288              * or if it looks as if it has been poisoned
289              * by incompressible data.
290              *
291              * This does not overflow, because
292              *  db->in_count <= RATIO_MAX.
293              */
294
295             new_ratio = db->in_count << RATIO_SCALE_LOG;
296             if (db->bytes_out != 0)
297               {
298                 new_ratio /= db->bytes_out;
299               }
300             
301             if (new_ratio < db->ratio || new_ratio < 1 * RATIO_SCALE)
302               {
303                 bsd_clear (db);
304                 return 1;
305               }
306             db->ratio = new_ratio;
307           }
308       }
309     return 0;
310   }
311
312 /*
313  * Return statistics.
314  */
315
316 static void bsd_comp_stats (void *state, struct compstat *stats)
317   {
318     struct bsd_db *db = (struct bsd_db *) state;
319     
320     stats->unc_bytes    = db->uncomp_bytes;
321     stats->unc_packets  = db->uncomp_count;
322     stats->comp_bytes   = db->comp_bytes;
323     stats->comp_packets = db->comp_count;
324     stats->inc_bytes    = db->incomp_bytes;
325     stats->inc_packets  = db->incomp_count;
326     stats->in_count     = db->in_count;
327     stats->bytes_out    = db->bytes_out;
328   }
329
330 /*
331  * Reset state, as on a CCP ResetReq.
332  */
333
334 static void bsd_reset (void *state)
335   {
336     struct bsd_db *db = (struct bsd_db *) state;
337
338     bsd_clear(db);
339
340     db->seqno       = 0;
341     db->clear_count = 0;
342   }
343
344 /*
345  * Release the compression structure
346  */
347
348 static void bsd_free (void *state)
349   {
350     struct bsd_db *db = (struct bsd_db *) state;
351     
352     if (db)
353       {
354 /*
355  * Release the dictionary
356  */
357         if (db->dict)
358           {
359             vfree (db->dict);
360             db->dict = NULL;
361           }
362 /*
363  * Release the string buffer
364  */
365         if (db->lens)
366           {
367             vfree (db->lens);
368             db->lens = NULL;
369           }
370 /*
371  * Finally release the structure itself.
372  */
373         kfree (db);
374         MOD_DEC_USE_COUNT;
375       }
376   }
377
378 /*
379  * Allocate space for a (de) compressor.
380  */
381
382 static void *bsd_alloc (unsigned char *options, int opt_len, int decomp)
383   {
384     int bits;
385     unsigned int hsize, hshift, maxmaxcode;
386     struct bsd_db *db;
387
388     if (opt_len != 3 || options[0] != CI_BSD_COMPRESS || options[1] != 3
389         || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION)
390       {
391         return NULL;
392       }
393
394     bits = BSD_NBITS(options[2]);
395
396     switch (bits)
397       {
398     case 9:                     /* needs 82152 for both directions */
399     case 10:                    /* needs 84144 */
400     case 11:                    /* needs 88240 */
401     case 12:                    /* needs 96432 */
402         hsize = 5003;
403         hshift = 4;
404         break;
405     case 13:                    /* needs 176784 */
406         hsize = 9001;
407         hshift = 5;
408         break;
409     case 14:                    /* needs 353744 */
410         hsize = 18013;
411         hshift = 6;
412         break;
413     case 15:                    /* needs 691440 */
414         hsize = 35023;
415         hshift = 7;
416         break;
417     case 16:                    /* needs 1366160--far too much, */
418         /* hsize = 69001; */    /* and 69001 is too big for cptr */
419         /* hshift = 8; */       /* in struct bsd_db */
420         /* break; */
421     default:
422         return NULL;
423       }
424 /*
425  * Allocate the main control structure for this instance.
426  */
427     maxmaxcode = MAXCODE(bits);
428     db         = (struct bsd_db *) kmalloc (sizeof (struct bsd_db),
429                                             GFP_KERNEL);
430     if (!db)
431       {
432         return NULL;
433       }
434
435     memset (db, 0, sizeof(struct bsd_db));
436 /*
437  * Allocate space for the dictionary. This may be more than one page in
438  * length.
439  */
440     db->dict = (struct bsd_dict *) vmalloc (hsize *
441                                             sizeof (struct bsd_dict));
442     if (!db->dict)
443       {
444         bsd_free (db);
445         return NULL;
446       }
447
448     MOD_INC_USE_COUNT;
449 /*
450  * If this is the compression buffer then there is no length data.
451  */
452     if (!decomp)
453       {
454         db->lens = NULL;
455       }
456 /*
457  * For decompression, the length information is needed as well.
458  */
459     else
460       {
461         db->lens = (unsigned short *) vmalloc ((maxmaxcode + 1) *
462                                                sizeof (db->lens[0]));
463         if (!db->lens)
464           {
465             bsd_free (db);
466             return (NULL);
467           }
468       }
469 /*
470  * Initialize the data information for the compression code
471  */
472     db->totlen     = sizeof (struct bsd_db)   +
473                     (sizeof (struct bsd_dict) * hsize);
474
475     db->hsize      = hsize;
476     db->hshift     = hshift;
477     db->maxmaxcode = maxmaxcode;
478     db->maxbits    = bits;
479
480     return (void *) db;
481   }
482
483 static void *bsd_comp_alloc (unsigned char *options, int opt_len)
484   {
485     return bsd_alloc (options, opt_len, 0);
486   }
487
488 static void *bsd_decomp_alloc (unsigned char *options, int opt_len)
489   {
490     return bsd_alloc (options, opt_len, 1);
491   }
492
493 /*
494  * Initialize the database.
495  */
496
497 static int bsd_init (void *state, unsigned char *options,
498                      int opt_len, int unit, int debug, int decomp)
499   {
500     struct bsd_db *db = state;
501     int indx;
502     
503     if ((opt_len != 3) || (options[0] != CI_BSD_COMPRESS) || (options[1] != 3)
504         || (BSD_VERSION(options[2]) != BSD_CURRENT_VERSION)
505         || (BSD_NBITS(options[2]) != db->maxbits)
506         || (decomp && db->lens == NULL))
507       {
508         return 0;
509       }
510
511     if (decomp)
512       {
513         indx = LAST;
514         do
515           {
516             db->lens[indx] = 1;
517           }
518         while (indx-- > 0);
519       }
520
521     indx = db->hsize;
522     while (indx-- != 0)
523       {
524         db->dict[indx].codem1 = BADCODEM1;
525         db->dict[indx].cptr   = 0;
526       }
527
528     db->unit = unit;
529     db->mru  = 0;
530 #ifndef DEBUG
531     if (debug)
532 #endif
533       db->debug = 1;
534     
535     bsd_reset(db);
536     
537     return 1;
538   }
539
540 static int bsd_comp_init (void *state, unsigned char *options,
541                           int opt_len, int unit, int opthdr, int debug)
542   {
543     return bsd_init (state, options, opt_len, unit, debug, 0);
544   }
545
546 static int bsd_decomp_init (void *state, unsigned char *options,
547                             int opt_len, int unit, int opthdr, int mru,
548                             int debug)
549   {
550     return bsd_init (state, options, opt_len, unit, debug, 1);
551   }
552
553 /*
554  * Obtain pointers to the various structures in the compression tables
555  */
556
557 #define dict_ptrx(p,idx) &(p->dict[idx])
558 #define lens_ptrx(p,idx) &(p->lens[idx])
559
560 #ifdef DEBUG
561 static unsigned short *lens_ptr(struct bsd_db *db, int idx)
562   {
563     if ((unsigned int) idx > (unsigned int) db->maxmaxcode)
564       {
565         printk ("<9>ppp: lens_ptr(%d) > max\n", idx);
566         idx = 0;
567       }
568     return lens_ptrx (db, idx);
569   }
570
571 static struct bsd_dict *dict_ptr(struct bsd_db *db, int idx)
572   {
573     if ((unsigned int) idx >= (unsigned int) db->hsize)
574       {
575         printk ("<9>ppp: dict_ptr(%d) > max\n", idx);
576         idx = 0;
577       }
578     return dict_ptrx (db, idx);
579   }
580
581 #else
582 #define lens_ptr(db,idx) lens_ptrx(db,idx)
583 #define dict_ptr(db,idx) dict_ptrx(db,idx)
584 #endif
585
586 /*
587  * compress a packet
588  *
589  *      The result of this function is the size of the compressed
590  *      packet. A zero is returned if the packet was not compressed
591  *      for some reason, such as the size being larger than uncompressed.
592  *
593  *      One change from the BSD compress command is that when the
594  *      code size expands, we do not output a bunch of padding.
595  */
596
597 static int bsd_compress (void *state, unsigned char *rptr, unsigned char *obuf,
598                          int isize, int osize)
599   {
600     struct bsd_db *db;
601     int hshift;
602     unsigned int max_ent;
603     unsigned int n_bits;
604     unsigned int bitno;
605     unsigned long accm;
606     int ent;
607     unsigned long fcode;
608     struct bsd_dict *dictp;
609     unsigned char c;
610     int hval;
611     int disp;
612     int ilen;
613     int mxcode;
614     unsigned char *wptr;
615     int olen;
616
617 #define PUTBYTE(v)                      \
618   {                                     \
619     ++olen;                             \
620     if (wptr)                           \
621       {                                 \
622         *wptr++ = (unsigned char) (v);  \
623         if (olen >= osize)              \
624           {                             \
625             wptr = NULL;                \
626           }                             \
627       }                                 \
628   }
629
630 #define OUTPUT(ent)                     \
631   {                                     \
632     bitno -= n_bits;                    \
633     accm |= ((ent) << bitno);           \
634     do                                  \
635       {                                 \
636         PUTBYTE(accm >> 24);            \
637         accm <<= 8;                     \
638         bitno += 8;                     \
639       }                                 \
640     while (bitno <= 24);                \
641   }
642
643   /*
644    * If the protocol is not in the range we're interested in,
645    * just return without compressing the packet.  If it is,
646    * the protocol becomes the first byte to compress.
647    */
648
649     ent = PPP_PROTOCOL(rptr);
650     if (ent < 0x21 || ent > 0xf9)
651       {
652         return 0;
653       }
654
655     db      = (struct bsd_db *) state;
656     hshift  = db->hshift;
657     max_ent = db->max_ent;
658     n_bits  = db->n_bits;
659     bitno   = 32;
660     accm    = 0;
661     mxcode  = MAXCODE (n_bits);
662
663     /* Initialize the output pointers */
664     wptr  = obuf;
665     olen  = PPP_HDRLEN + BSD_OVHD;
666
667     if (osize > isize)
668       {
669         osize = isize;
670       }
671
672     /* This is the PPP header information */
673     if (wptr)
674       {
675         *wptr++ = PPP_ADDRESS(rptr);
676         *wptr++ = PPP_CONTROL(rptr);
677         *wptr++ = 0;
678         *wptr++ = PPP_COMP;
679         *wptr++ = db->seqno >> 8;
680         *wptr++ = db->seqno;
681       }
682
683     /* Skip the input header */
684     rptr  += PPP_HDRLEN;
685     isize -= PPP_HDRLEN;
686     ilen   = ++isize;   /* Low byte of protocol is counted as input */
687
688     while (--ilen > 0)
689       {
690         c     = *rptr++;
691         fcode = BSD_KEY  (ent, c);
692         hval  = BSD_HASH (ent, c, hshift);
693         dictp = dict_ptr (db, hval);
694         
695         /* Validate and then check the entry. */
696         if (dictp->codem1 >= max_ent)
697           {
698             goto nomatch;
699           }
700
701         if (dictp->f.fcode == fcode)
702           {
703             ent = dictp->codem1 + 1;
704             continue;   /* found (prefix,suffix) */
705           }
706         
707         /* continue probing until a match or invalid entry */
708         disp = (hval == 0) ? 1 : hval;
709
710         do
711           {
712             hval += disp;
713             if (hval >= db->hsize)
714               {
715                 hval -= db->hsize;
716               }
717             dictp = dict_ptr (db, hval);
718             if (dictp->codem1 >= max_ent)
719               {
720                 goto nomatch;
721               }
722           }
723         while (dictp->f.fcode != fcode);
724
725         ent = dictp->codem1 + 1;        /* finally found (prefix,suffix) */
726         continue;
727         
728 nomatch:
729         OUTPUT(ent);            /* output the prefix */
730         
731         /* code -> hashtable */
732         if (max_ent < db->maxmaxcode)
733           {
734             struct bsd_dict *dictp2;
735             struct bsd_dict *dictp3;
736             int    indx;
737
738             /* expand code size if needed */
739             if (max_ent >= mxcode)
740               {
741                 db->n_bits = ++n_bits;
742                 mxcode     = MAXCODE (n_bits);
743               }
744             
745             /* Invalidate old hash table entry using
746              * this code, and then take it over.
747              */
748
749             dictp2 = dict_ptr (db, max_ent + 1);
750             indx   = dictp2->cptr;
751             dictp3 = dict_ptr (db, indx);
752
753             if (dictp3->codem1 == max_ent)
754               {
755                 dictp3->codem1 = BADCODEM1;
756               }
757
758             dictp2->cptr   = hval;
759             dictp->codem1  = max_ent;
760             dictp->f.fcode = fcode;
761             db->max_ent    = ++max_ent;
762
763             if (db->lens)
764               {
765                 unsigned short *len1 = lens_ptr (db, max_ent);
766                 unsigned short *len2 = lens_ptr (db, ent);
767                 *len1 = *len2 + 1;
768               }
769           }
770         ent = c;
771       }
772     
773     OUTPUT(ent);                /* output the last code */
774
775     db->bytes_out    += olen - PPP_HDRLEN - BSD_OVHD;
776     db->uncomp_bytes += isize;
777     db->in_count     += isize;
778     ++db->uncomp_count;
779     ++db->seqno;
780
781     if (bitno < 32)
782       {
783         ++db->bytes_out; /* must be set before calling bsd_check */
784       }
785
786     /*
787      * Generate the clear command if needed
788      */
789
790     if (bsd_check(db))
791       {
792         OUTPUT (CLEAR);
793       }
794     
795     /*
796      * Pad dribble bits of last code with ones.
797      * Do not emit a completely useless byte of ones.
798      */
799
800     if (bitno != 32)
801       {
802         PUTBYTE((accm | (0xff << (bitno-8))) >> 24);
803       }
804     
805     /*
806      * Increase code size if we would have without the packet
807      * boundary because the decompressor will do so.
808      */
809
810     if (max_ent >= mxcode && max_ent < db->maxmaxcode)
811       {
812         db->n_bits++;
813       }
814
815     /* If output length is too large then this is an incomplete frame. */
816     if (wptr == NULL)
817       {
818         ++db->incomp_count;
819         db->incomp_bytes += isize;
820         olen              = 0;
821       }
822     else /* Count the number of compressed frames */
823       {
824         ++db->comp_count;
825         db->comp_bytes += olen;
826       }
827
828     /* Return the resulting output length */
829     return olen;
830 #undef OUTPUT
831 #undef PUTBYTE
832   }
833
834 /*
835  * Update the "BSD Compress" dictionary on the receiver for
836  * incompressible data by pretending to compress the incoming data.
837  */
838
839 static void bsd_incomp (void *state, unsigned char *ibuf, int icnt)
840   {
841     (void) bsd_compress (state, ibuf, (char *) 0, icnt, 0);
842   }
843
844 /*
845  * Decompress "BSD Compress".
846  *
847  * Because of patent problems, we return DECOMP_ERROR for errors
848  * found by inspecting the input data and for system problems, but
849  * DECOMP_FATALERROR for any errors which could possibly be said to
850  * be being detected "after" decompression.  For DECOMP_ERROR,
851  * we can issue a CCP reset-request; for DECOMP_FATALERROR, we may be
852  * infringing a patent of Motorola's if we do, so we take CCP down
853  * instead.
854  *
855  * Given that the frame has the correct sequence number and a good FCS,
856  * errors such as invalid codes in the input most likely indicate a
857  * bug, so we return DECOMP_FATALERROR for them in order to turn off
858  * compression, even though they are detected by inspecting the input.
859  */
860
861 static int bsd_decompress (void *state, unsigned char *ibuf, int isize,
862                            unsigned char *obuf, int osize)
863   {
864     struct bsd_db *db;
865     unsigned int max_ent;
866     unsigned long accm;
867     unsigned int bitno;         /* 1st valid bit in accm */
868     unsigned int n_bits;
869     unsigned int tgtbitno;      /* bitno when we have a code */
870     struct bsd_dict *dictp;
871     int explen;
872     int seq;
873     unsigned int incode;
874     unsigned int oldcode;
875     unsigned int finchar;
876     unsigned char *p;
877     unsigned char *wptr;
878     int adrs;
879     int ctrl;
880     int ilen;
881     int codelen;
882     int extra;
883
884     db       = (struct bsd_db *) state;
885     max_ent  = db->max_ent;
886     accm     = 0;
887     bitno    = 32;              /* 1st valid bit in accm */
888     n_bits   = db->n_bits;
889     tgtbitno = 32 - n_bits;     /* bitno when we have a code */
890     
891     /*
892      * Save the address/control from the PPP header
893      * and then get the sequence number.
894      */
895
896     adrs  = PPP_ADDRESS (ibuf);
897     ctrl  = PPP_CONTROL (ibuf);
898
899     seq   = (ibuf[4] << 8) + ibuf[5];
900
901     ibuf += (PPP_HDRLEN + 2);
902     ilen  = isize - (PPP_HDRLEN + 2);
903     
904     /*
905      * Check the sequence number and give up if it differs from
906      * the value we're expecting.
907      */
908
909     if (seq != db->seqno)
910       {
911         if (db->debug)
912           {
913             printk("bsd_decomp%d: bad sequence # %d, expected %d\n",
914                    db->unit, seq, db->seqno - 1);
915           }
916         return DECOMP_ERROR;
917       }
918
919     ++db->seqno;
920     db->bytes_out += ilen;
921
922     /*
923      * Fill in the ppp header, but not the last byte of the protocol
924      * (that comes from the decompressed data).
925      */
926
927     wptr    = obuf;
928     *wptr++ = adrs;
929     *wptr++ = ctrl;
930     *wptr++ = 0;
931     
932     oldcode = CLEAR;
933     explen  = 3;
934
935     /*
936      * Keep the checkpoint correctly so that incompressible packets
937      * clear the dictionary at the proper times.
938      */
939
940     for (;;)
941       {
942         if (ilen-- <= 0)
943           {
944             db->in_count += (explen - 3); /* don't count the header */
945             break;
946           }
947
948         /*
949          * Accumulate bytes until we have a complete code.
950          * Then get the next code, relying on the 32-bit,
951          * unsigned accm to mask the result.
952          */
953
954         bitno -= 8;
955         accm  |= *ibuf++ << bitno;
956         if (tgtbitno < bitno)
957           {
958             continue;
959           }
960
961         incode = accm >> tgtbitno;
962         accm <<= n_bits;
963         bitno += n_bits;
964
965         /*
966          * The dictionary must only be cleared at the end of a packet.
967          */
968         
969         if (incode == CLEAR)
970           {
971             if (ilen > 0)
972               {
973                 if (db->debug)
974                   {
975                     printk("bsd_decomp%d: bad CLEAR\n", db->unit);
976                   }
977                 return DECOMP_FATALERROR;       /* probably a bug */
978               }
979             
980             bsd_clear(db);
981             break;
982           }
983
984         if ((incode > max_ent + 2) || (incode > db->maxmaxcode)
985             || (incode > max_ent && oldcode == CLEAR))
986           {
987             if (db->debug)
988               {
989                 printk("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
990                        db->unit, incode, oldcode);
991                 printk("max_ent=0x%x explen=%d seqno=%d\n",
992                        max_ent, explen, db->seqno);
993               }
994             return DECOMP_FATALERROR;   /* probably a bug */
995           }
996         
997         /* Special case for KwKwK string. */
998         if (incode > max_ent)
999           {
1000             finchar = oldcode;
1001             extra   = 1;
1002           }
1003         else
1004           {
1005             finchar = incode;
1006             extra   = 0;
1007           }
1008         
1009         codelen = *(lens_ptr (db, finchar));
1010         explen += codelen + extra;
1011         if (explen > osize)
1012           {
1013             if (db->debug)
1014               {
1015                 printk("bsd_decomp%d: ran out of mru\n", db->unit);
1016 #ifdef DEBUG
1017                 printk("  len=%d, finchar=0x%x, codelen=%d, explen=%d\n",
1018                        ilen, finchar, codelen, explen);
1019 #endif
1020               }
1021             return DECOMP_FATALERROR;
1022           }
1023         
1024         /*
1025          * Decode this code and install it in the decompressed buffer.
1026          */
1027
1028         wptr += codelen;
1029         p     = wptr;
1030         while (finchar > LAST)
1031           {
1032             struct bsd_dict *dictp2 = dict_ptr (db, finchar);
1033             
1034             dictp = dict_ptr (db, dictp2->cptr);
1035 #ifdef DEBUG
1036             if (--codelen <= 0 || dictp->codem1 != finchar-1)
1037               {
1038                 if (codelen <= 0)
1039                   {
1040                     printk("bsd_decomp%d: fell off end of chain ", db->unit);
1041                     printk("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
1042                            incode, finchar, dictp2->cptr, max_ent);
1043                   }
1044                 else
1045                   {
1046                     if (dictp->codem1 != finchar-1)
1047                       {
1048                         printk("bsd_decomp%d: bad code chain 0x%x "
1049                                "finchar=0x%x ",
1050                                db->unit, incode, finchar);
1051
1052                         printk("oldcode=0x%x cptr=0x%x codem1=0x%x\n",
1053                                oldcode, dictp2->cptr, dictp->codem1);
1054                       }
1055                   }
1056                 return DECOMP_FATALERROR;
1057               }
1058 #endif
1059             *--p    = dictp->f.hs.suffix;
1060             finchar = dictp->f.hs.prefix;
1061           }
1062         *--p = finchar;
1063         
1064 #ifdef DEBUG
1065         if (--codelen != 0)
1066           {
1067             printk("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
1068                    db->unit, codelen, incode, max_ent);
1069           }
1070 #endif
1071         
1072         if (extra)              /* the KwKwK case again */
1073           {
1074             *wptr++ = finchar;
1075           }
1076         
1077         /*
1078          * If not first code in a packet, and
1079          * if not out of code space, then allocate a new code.
1080          *
1081          * Keep the hash table correct so it can be used
1082          * with uncompressed packets.
1083          */
1084
1085         if (oldcode != CLEAR && max_ent < db->maxmaxcode)
1086           {
1087             struct bsd_dict *dictp2, *dictp3;
1088             unsigned short  *lens1,  *lens2;
1089             unsigned long fcode;
1090             int hval, disp, indx;
1091             
1092             fcode = BSD_KEY(oldcode,finchar);
1093             hval  = BSD_HASH(oldcode,finchar,db->hshift);
1094             dictp = dict_ptr (db, hval);
1095             
1096             /* look for a free hash table entry */
1097             if (dictp->codem1 < max_ent)
1098               {
1099                 disp = (hval == 0) ? 1 : hval;
1100                 do
1101                   {
1102                     hval += disp;
1103                     if (hval >= db->hsize)
1104                       {
1105                         hval -= db->hsize;
1106                       }
1107                     dictp = dict_ptr (db, hval);
1108                   }
1109                 while (dictp->codem1 < max_ent);
1110               }
1111             
1112             /*
1113              * Invalidate previous hash table entry
1114              * assigned this code, and then take it over
1115              */
1116
1117             dictp2 = dict_ptr (db, max_ent + 1);
1118             indx   = dictp2->cptr;
1119             dictp3 = dict_ptr (db, indx);
1120
1121             if (dictp3->codem1 == max_ent)
1122               {
1123                 dictp3->codem1 = BADCODEM1;
1124               }
1125
1126             dictp2->cptr   = hval;
1127             dictp->codem1  = max_ent;
1128             dictp->f.fcode = fcode;
1129             db->max_ent    = ++max_ent;
1130
1131             /* Update the length of this string. */
1132             lens1  = lens_ptr (db, max_ent);
1133             lens2  = lens_ptr (db, oldcode);
1134             *lens1 = *lens2 + 1;
1135             
1136             /* Expand code size if needed. */
1137             if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
1138               {
1139                 db->n_bits = ++n_bits;
1140                 tgtbitno   = 32-n_bits;
1141               }
1142           }
1143         oldcode = incode;
1144       }
1145
1146     ++db->comp_count;
1147     ++db->uncomp_count;
1148     db->comp_bytes   += isize - BSD_OVHD - PPP_HDRLEN;
1149     db->uncomp_bytes += explen;
1150
1151     if (bsd_check(db))
1152       {
1153         if (db->debug)
1154           {
1155             printk("bsd_decomp%d: peer should have cleared dictionary on %d\n",
1156                    db->unit, db->seqno - 1);
1157           }
1158       }
1159     return explen;
1160   }
1161      
1162 /*************************************************************
1163  * Table of addresses for the BSD compression module
1164  *************************************************************/
1165
1166 static struct compressor ppp_bsd_compress = {
1167     CI_BSD_COMPRESS,            /* compress_proto */
1168     bsd_comp_alloc,             /* comp_alloc */
1169     bsd_free,                   /* comp_free */
1170     bsd_comp_init,              /* comp_init */
1171     bsd_reset,                  /* comp_reset */
1172     bsd_compress,               /* compress */
1173     bsd_comp_stats,             /* comp_stat */
1174     bsd_decomp_alloc,           /* decomp_alloc */
1175     bsd_free,                   /* decomp_free */
1176     bsd_decomp_init,            /* decomp_init */
1177     bsd_reset,                  /* decomp_reset */
1178     bsd_decompress,             /* decompress */
1179     bsd_incomp,                 /* incomp */
1180     bsd_comp_stats              /* decomp_stat */
1181 };
1182
1183 /*************************************************************
1184  * Module support routines
1185  *************************************************************/
1186
1187 int
1188 init_module(void)
1189 {
1190         int answer = ppp_register_compressor (&ppp_bsd_compress);
1191         if (answer == 0)
1192                 printk (KERN_INFO "PPP BSD Compression module registered\n");
1193         return answer;
1194 }
1195
1196 void
1197 cleanup_module(void)
1198 {
1199         ppp_unregister_compressor (&ppp_bsd_compress);
1200 }