setup enviroment for compilation
[linux-2.4.21-pre4.git] / drivers / net / strip.c
1 /*
2  * Copyright 1996 The Board of Trustees of The Leland Stanford
3  * Junior University. All Rights Reserved.
4  *
5  * Permission to use, copy, modify, and distribute this
6  * software and its documentation for any purpose and without
7  * fee is hereby granted, provided that the above copyright
8  * notice appear in all copies.  Stanford University
9  * makes no representations about the suitability of this
10  * software for any purpose.  It is provided "as is" without
11  * express or implied warranty.
12  *
13  * strip.c      This module implements Starmode Radio IP (STRIP)
14  *              for kernel-based devices like TTY.  It interfaces between a
15  *              raw TTY, and the kernel's INET protocol layers (via DDI).
16  *
17  * Version:     @(#)strip.c     1.3     July 1997
18  *
19  * Author:      Stuart Cheshire <cheshire@cs.stanford.edu>
20  *
21  * Fixes:       v0.9 12th Feb 1996 (SC)
22  *              New byte stuffing (2+6 run-length encoding)
23  *              New watchdog timer task
24  *              New Protocol key (SIP0)
25  *              
26  *              v0.9.1 3rd March 1996 (SC)
27  *              Changed to dynamic device allocation -- no more compile
28  *              time (or boot time) limit on the number of STRIP devices.
29  *              
30  *              v0.9.2 13th March 1996 (SC)
31  *              Uses arp cache lookups (but doesn't send arp packets yet)
32  *              
33  *              v0.9.3 17th April 1996 (SC)
34  *              Fixed bug where STR_ERROR flag was getting set unneccessarily
35  *              (causing otherwise good packets to be unneccessarily dropped)
36  *              
37  *              v0.9.4 27th April 1996 (SC)
38  *              First attempt at using "&COMMAND" Starmode AT commands
39  *              
40  *              v0.9.5 29th May 1996 (SC)
41  *              First attempt at sending (unicast) ARP packets
42  *              
43  *              v0.9.6 5th June 1996 (Elliot)
44  *              Put "message level" tags in every "printk" statement
45  *              
46  *              v0.9.7 13th June 1996 (laik)
47  *              Added support for the /proc fs
48  *
49  *              v0.9.8 July 1996 (Mema)
50  *              Added packet logging
51  *
52  *              v1.0 November 1996 (SC)
53  *              Fixed (severe) memory leaks in the /proc fs code
54  *              Fixed race conditions in the logging code
55  *
56  *              v1.1 January 1997 (SC)
57  *              Deleted packet logging (use tcpdump instead)
58  *              Added support for Metricom Firmware v204 features
59  *              (like message checksums)
60  *
61  *              v1.2 January 1997 (SC)
62  *              Put portables list back in
63  *
64  *              v1.3 July 1997 (SC)
65  *              Made STRIP driver set the radio's baud rate automatically.
66  *              It is no longer necessarily to manually set the radio's
67  *              rate permanently to 115200 -- the driver handles setting
68  *              the rate automatically.
69  */
70
71 #ifdef MODULE
72 static const char StripVersion[] = "1.3-STUART.CHESHIRE-MODULAR";
73 #else
74 static const char StripVersion[] = "1.3-STUART.CHESHIRE";
75 #endif
76
77 #define TICKLE_TIMERS 0
78 #define EXT_COUNTERS 1
79
80
81 /************************************************************************/
82 /* Header files                                                         */
83
84 #include <linux/config.h>
85 #include <linux/module.h>
86 #include <linux/version.h>
87 #include <linux/init.h>
88 #include <asm/system.h>
89 #include <asm/uaccess.h>
90 #include <asm/segment.h>
91 #include <asm/bitops.h>
92
93 /*
94  * isdigit() and isspace() use the ctype[] array, which is not available
95  * to kernel modules.  If compiling as a module,  use  a local definition
96  * of isdigit() and isspace() until  _ctype is added to ksyms.
97  */
98 #ifdef MODULE
99 # define isdigit(c) ('0' <= (c) && (c)  <= '9')
100 # define isspace(c) ((c) == ' ' || (c)  == '\t')
101 #else
102 # include <linux/ctype.h>
103 #endif
104
105 #include <linux/string.h>
106 #include <linux/mm.h>
107 #include <linux/interrupt.h>
108 #include <linux/in.h>
109 #include <linux/tty.h>
110 #include <linux/errno.h>
111 #include <linux/netdevice.h>
112 #include <linux/inetdevice.h>
113 #include <linux/etherdevice.h>
114 #include <linux/skbuff.h>
115 #include <linux/if_arp.h>
116 #include <linux/if_strip.h>
117 #include <linux/proc_fs.h>
118 #include <linux/serial.h>
119 #include <linux/serialP.h>
120 #include <net/arp.h>
121
122 #include <linux/ip.h>
123 #include <linux/tcp.h>
124 #include <linux/time.h>
125
126
127 /************************************************************************/
128 /* Useful structures and definitions                                    */
129
130 /*
131  * A MetricomKey identifies the protocol being carried inside a Metricom
132  * Starmode packet.
133  */
134
135 typedef union
136 {
137     __u8 c[4];
138     __u32 l;
139 } MetricomKey;
140
141 /*
142  * An IP address can be viewed as four bytes in memory (which is what it is) or as
143  * a single 32-bit long (which is convenient for assignment, equality testing etc.)
144  */
145
146 typedef union
147 {
148     __u8 b[4];
149     __u32 l;
150 } IPaddr;
151
152 /*
153  * A MetricomAddressString is used to hold a printable representation of
154  * a Metricom address.
155  */
156
157 typedef struct
158 {
159     __u8 c[24];
160 } MetricomAddressString;
161
162 /* Encapsulation can expand packet of size x to 65/64x + 1
163  * Sent packet looks like "<CR>*<address>*<key><encaps payload><CR>"
164  *                           1 1   1-18  1  4         ?         1
165  * eg.                     <CR>*0000-1234*SIP0<encaps payload><CR>
166  * We allow 31 bytes for the stars, the key, the address and the <CR>s
167  */
168 #define STRIP_ENCAP_SIZE(X) (32 + (X)*65L/64L)
169
170 /*
171  * A STRIP_Header is never really sent over the radio, but making a dummy
172  * header for internal use within the kernel that looks like an Ethernet
173  * header makes certain other software happier. For example, tcpdump
174  * already understands Ethernet headers.
175  */
176
177 typedef struct
178 {
179     MetricomAddress dst_addr;           /* Destination address, e.g. "0000-1234"   */
180     MetricomAddress src_addr;           /* Source address, e.g. "0000-5678"        */
181     unsigned short  protocol;           /* The protocol type, using Ethernet codes */
182 } STRIP_Header;
183
184 typedef struct
185 {
186     char c[60];
187 } MetricomNode;
188
189 #define NODE_TABLE_SIZE 32
190 typedef struct
191 {
192     struct timeval timestamp;
193     int            num_nodes;
194     MetricomNode   node[NODE_TABLE_SIZE];
195 } MetricomNodeTable;
196
197 enum { FALSE = 0, TRUE = 1 };
198
199 /*
200  * Holds the radio's firmware version.
201  */
202 typedef struct
203 {
204     char c[50];
205 } FirmwareVersion;
206
207 /*
208  * Holds the radio's serial number.
209  */
210 typedef struct
211 {
212     char c[18];
213 } SerialNumber;
214
215 /*
216  * Holds the radio's battery voltage.
217  */
218 typedef struct
219 {
220     char c[11];
221 } BatteryVoltage;
222
223 typedef struct
224 {
225     char c[8];
226 } char8;
227
228 enum
229 {
230     NoStructure = 0,            /* Really old firmware */
231     StructuredMessages = 1,     /* Parsable AT response msgs */
232     ChecksummedMessages = 2     /* Parsable AT response msgs with checksums */
233 } FirmwareLevel;
234
235 struct strip
236 {
237     int magic;
238     /*
239      * These are pointers to the malloc()ed frame buffers.
240      */
241
242     unsigned char     *rx_buff;                 /* buffer for received IP packet*/
243     unsigned char     *sx_buff;                 /* buffer for received serial data*/
244     int                sx_count;                /* received serial data counter */
245     int                sx_size;                 /* Serial buffer size           */
246     unsigned char     *tx_buff;                 /* transmitter buffer           */
247     unsigned char     *tx_head;                 /* pointer to next byte to XMIT */
248     int                tx_left;                 /* bytes left in XMIT queue     */
249     int                tx_size;                 /* Serial buffer size           */
250
251     /*
252      * STRIP interface statistics.
253      */
254
255     unsigned long      rx_packets;              /* inbound frames counter       */
256     unsigned long      tx_packets;              /* outbound frames counter      */
257     unsigned long      rx_errors;               /* Parity, etc. errors          */
258     unsigned long      tx_errors;               /* Planned stuff                */
259     unsigned long      rx_dropped;              /* No memory for skb            */
260     unsigned long      tx_dropped;              /* When MTU change              */
261     unsigned long      rx_over_errors;          /* Frame bigger then STRIP buf. */
262
263     unsigned long      pps_timer;               /* Timer to determine pps       */
264     unsigned long      rx_pps_count;            /* Counter to determine pps     */
265     unsigned long      tx_pps_count;            /* Counter to determine pps     */
266     unsigned long      sx_pps_count;            /* Counter to determine pps     */
267     unsigned long      rx_average_pps;          /* rx packets per second * 8    */
268     unsigned long      tx_average_pps;          /* tx packets per second * 8    */
269     unsigned long      sx_average_pps;          /* sent packets per second * 8  */
270
271 #ifdef EXT_COUNTERS
272     unsigned long      rx_bytes;                /* total received bytes */
273     unsigned long      tx_bytes;                /* total received bytes */
274     unsigned long      rx_rbytes;               /* bytes thru radio i/f */
275     unsigned long      tx_rbytes;               /* bytes thru radio i/f */
276     unsigned long      rx_sbytes;               /* tot bytes thru serial i/f */
277     unsigned long      tx_sbytes;               /* tot bytes thru serial i/f */
278     unsigned long      rx_ebytes;               /* tot stat/err bytes */
279     unsigned long      tx_ebytes;               /* tot stat/err bytes */
280 #endif
281
282     /*
283      * Internal variables.
284      */
285
286     struct strip      *next;                    /* The next struct in the list  */
287     struct strip     **referrer;                /* The pointer that points to us*/
288     int                discard;                 /* Set if serial error          */
289     int                working;                 /* Is radio working correctly?  */
290     int                firmware_level;          /* Message structuring level    */
291     int                next_command;            /* Next periodic command        */
292     unsigned int       user_baud;               /* The user-selected baud rate  */
293     int                mtu;                     /* Our mtu (to spot changes!)   */
294     long               watchdog_doprobe;        /* Next time to test the radio  */
295     long               watchdog_doreset;        /* Time to do next reset        */
296     long               gratuitous_arp;          /* Time to send next ARP refresh*/
297     long               arp_interval;            /* Next ARP interval            */
298     struct timer_list  idle_timer;              /* For periodic wakeup calls    */
299     MetricomAddress    true_dev_addr;           /* True address of radio        */
300     int                manual_dev_addr;         /* Hack: See note below         */
301
302     FirmwareVersion    firmware_version;        /* The radio's firmware version */
303     SerialNumber       serial_number;           /* The radio's serial number    */
304     BatteryVoltage     battery_voltage;         /* The radio's battery voltage  */
305
306     /*
307      * Other useful structures.
308      */
309
310     struct tty_struct *tty;                     /* ptr to TTY structure         */
311     struct net_device      dev;                 /* Our device structure         */
312
313     /*
314      * Neighbour radio records
315      */
316
317     MetricomNodeTable  portables;
318     MetricomNodeTable  poletops;
319 };
320
321 /*
322  * Note: manual_dev_addr hack
323  * 
324  * It is not possible to change the hardware address of a Metricom radio,
325  * or to send packets with a user-specified hardware source address, thus
326  * trying to manually set a hardware source address is a questionable
327  * thing to do.  However, if the user *does* manually set the hardware
328  * source address of a STRIP interface, then the kernel will believe it,
329  * and use it in certain places. For example, the hardware address listed
330  * by ifconfig will be the manual address, not the true one.
331  * (Both addresses are listed in /proc/net/strip.)
332  * Also, ARP packets will be sent out giving the user-specified address as
333  * the source address, not the real address. This is dangerous, because
334  * it means you won't receive any replies -- the ARP replies will go to
335  * the specified address, which will be some other radio. The case where
336  * this is useful is when that other radio is also connected to the same
337  * machine. This allows you to connect a pair of radios to one machine,
338  * and to use one exclusively for inbound traffic, and the other
339  * exclusively for outbound traffic. Pretty neat, huh?
340  * 
341  * Here's the full procedure to set this up:
342  * 
343  * 1. "slattach" two interfaces, e.g. st0 for outgoing packets,
344  *    and st1 for incoming packets
345  * 
346  * 2. "ifconfig" st0 (outbound radio) to have the hardware address
347  *    which is the real hardware address of st1 (inbound radio).
348  *    Now when it sends out packets, it will masquerade as st1, and
349  *    replies will be sent to that radio, which is exactly what we want.
350  * 
351  * 3. Set the route table entry ("route add default ..." or
352  *    "route add -net ...", as appropriate) to send packets via the st0
353  *    interface (outbound radio). Do not add any route which sends packets
354  *    out via the st1 interface -- that radio is for inbound traffic only.
355  * 
356  * 4. "ifconfig" st1 (inbound radio) to have hardware address zero.
357  *    This tells the STRIP driver to "shut down" that interface and not
358  *    send any packets through it. In particular, it stops sending the
359  *    periodic gratuitous ARP packets that a STRIP interface normally sends.
360  *    Also, when packets arrive on that interface, it will search the
361  *    interface list to see if there is another interface who's manual
362  *    hardware address matches its own real address (i.e. st0 in this
363  *    example) and if so it will transfer ownership of the skbuff to
364  *    that interface, so that it looks to the kernel as if the packet
365  *    arrived on that interface. This is necessary because when the
366  *    kernel sends an ARP packet on st0, it expects to get a reply on
367  *    st0, and if it sees the reply come from st1 then it will ignore
368  *    it (to be accurate, it puts the entry in the ARP table, but
369  *    labelled in such a way that st0 can't use it).
370  * 
371  * Thanks to Petros Maniatis for coming up with the idea of splitting
372  * inbound and outbound traffic between two interfaces, which turned
373  * out to be really easy to implement, even if it is a bit of a hack.
374  * 
375  * Having set a manual address on an interface, you can restore it
376  * to automatic operation (where the address is automatically kept
377  * consistent with the real address of the radio) by setting a manual
378  * address of all ones, e.g. "ifconfig st0 hw strip FFFFFFFFFFFF"
379  * This 'turns off' manual override mode for the device address.
380  * 
381  * Note: The IEEE 802 headers reported in tcpdump will show the *real*
382  * radio addresses the packets were sent and received from, so that you
383  * can see what is really going on with packets, and which interfaces
384  * they are really going through.
385  */
386
387
388 /************************************************************************/
389 /* Constants                                                            */
390
391 /*
392  * CommandString1 works on all radios
393  * Other CommandStrings are only used with firmware that provides structured responses.
394  * 
395  * ats319=1 Enables Info message for node additions and deletions
396  * ats319=2 Enables Info message for a new best node
397  * ats319=4 Enables checksums
398  * ats319=8 Enables ACK messages
399  */
400
401 static const int MaxCommandStringLength = 32;
402 static const int CompatibilityCommand = 1;
403
404 static const char CommandString0[] = "*&COMMAND*ATS319=7";      /* Turn on checksums & info messages */
405 static const char CommandString1[] = "*&COMMAND*ATS305?";       /* Query radio name */
406 static const char CommandString2[] = "*&COMMAND*ATS325?";       /* Query battery voltage */
407 static const char CommandString3[] = "*&COMMAND*ATS300?";       /* Query version information */
408 static const char CommandString4[] = "*&COMMAND*ATS311?";       /* Query poletop list */
409 static const char CommandString5[] = "*&COMMAND*AT~LA";         /* Query portables list */
410 typedef struct { const char *string; long length; } StringDescriptor;
411
412 static const StringDescriptor CommandString[] =
413     {
414     { CommandString0, sizeof(CommandString0)-1 },
415     { CommandString1, sizeof(CommandString1)-1 },
416     { CommandString2, sizeof(CommandString2)-1 },
417     { CommandString3, sizeof(CommandString3)-1 },
418     { CommandString4, sizeof(CommandString4)-1 },
419     { CommandString5, sizeof(CommandString5)-1 }
420     };
421
422 #define GOT_ALL_RADIO_INFO(S)      \
423     ((S)->firmware_version.c[0] && \
424      (S)->battery_voltage.c[0]  && \
425      memcmp(&(S)->true_dev_addr, zero_address.c, sizeof(zero_address)))
426
427 static const char            hextable[16]      = "0123456789ABCDEF";
428
429 static const MetricomAddress zero_address;
430 static const MetricomAddress broadcast_address = { { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF } };
431
432 static const MetricomKey     SIP0Key           = { { "SIP0" } };
433 static const MetricomKey     ARP0Key           = { { "ARP0" } };
434 static const MetricomKey     ATR_Key           = { { "ATR " } };
435 static const MetricomKey     ACK_Key           = { { "ACK_" } };
436 static const MetricomKey     INF_Key           = { { "INF_" } };
437 static const MetricomKey     ERR_Key           = { { "ERR_" } };
438
439 static const long            MaxARPInterval    = 60 * HZ;          /* One minute */
440
441 /*
442  * Maximum Starmode packet length is 1183 bytes. Allowing 4 bytes for
443  * protocol key, 4 bytes for checksum, one byte for CR, and 65/64 expansion
444  * for STRIP encoding, that translates to a maximum payload MTU of 1155.
445  * Note: A standard NFS 1K data packet is a total of 0x480 (1152) bytes
446  * long, including IP header, UDP header, and NFS header. Setting the STRIP
447  * MTU to 1152 allows us to send default sized NFS packets without fragmentation.
448  */
449 static const unsigned short  MAX_SEND_MTU          = 1152;
450 static const unsigned short  MAX_RECV_MTU          = 1500; /* Hoping for Ethernet sized packets in the future! */
451 static const unsigned short  DEFAULT_STRIP_MTU      = 1152;
452 static const int             STRIP_MAGIC            = 0x5303;
453 static const long            LongTime               = 0x7FFFFFFF;
454
455
456 /************************************************************************/
457 /* Global variables                                                     */
458
459 static struct strip *struct_strip_list;
460
461
462 /************************************************************************/
463 /* Macros                                                               */
464
465 /* Returns TRUE if text T begins with prefix P */
466 #define has_prefix(T,L,P) (((L) >= sizeof(P)-1) && !strncmp((T), (P), sizeof(P)-1))
467
468 /* Returns TRUE if text T of length L is equal to string S */
469 #define text_equal(T,L,S) (((L) == sizeof(S)-1) && !strncmp((T), (S), sizeof(S)-1))
470
471 #define READHEX(X) ((X)>='0' && (X)<='9' ? (X)-'0' :      \
472                     (X)>='a' && (X)<='f' ? (X)-'a'+10 :   \
473                     (X)>='A' && (X)<='F' ? (X)-'A'+10 : 0 )
474
475 #define READHEX16(X) ((__u16)(READHEX(X)))
476
477 #define READDEC(X) ((X)>='0' && (X)<='9' ? (X)-'0' : 0)
478
479 #define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
480 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
481 #define ELEMENTS_OF(X) (sizeof(X) / sizeof((X)[0]))
482 #define ARRAY_END(X) (&((X)[ELEMENTS_OF(X)]))
483
484 #define JIFFIE_TO_SEC(X) ((X) / HZ)
485
486
487 /************************************************************************/
488 /* Utility routines                                                     */
489
490 typedef unsigned long InterruptStatus;
491
492 static inline InterruptStatus DisableInterrupts(void)
493 {
494     InterruptStatus x;
495     save_flags(x);
496     cli();
497     return(x);
498 }
499
500 static inline void RestoreInterrupts(InterruptStatus x)
501 {
502     restore_flags(x);
503 }
504
505 static int arp_query(unsigned char *haddr, u32 paddr, struct net_device * dev)
506 {
507     struct neighbour *neighbor_entry;
508
509     neighbor_entry = neigh_lookup(&arp_tbl, &paddr, dev);
510
511     if (neighbor_entry != NULL)
512     {
513         neighbor_entry->used = jiffies;
514         if (neighbor_entry->nud_state & NUD_VALID)
515         {
516             memcpy(haddr, neighbor_entry->ha, dev->addr_len);
517             return 1;
518         }
519     }
520     return 0;
521 }
522
523 static void DumpData(char *msg, struct strip *strip_info, __u8 *ptr, __u8 *end)
524 {
525     static const int MAX_DumpData = 80;
526     __u8 pkt_text[MAX_DumpData], *p = pkt_text;
527
528     *p++ = '\"';
529
530     while (ptr<end && p < &pkt_text[MAX_DumpData-4])
531     {
532         if (*ptr == '\\')
533         {
534             *p++ = '\\';
535             *p++ = '\\';
536         }
537         else
538         {
539             if (*ptr >= 32 && *ptr <= 126)
540             {
541                 *p++ = *ptr;
542             }
543             else
544             {
545                 sprintf(p, "\\%02X", *ptr);
546                 p+= 3;
547             }
548         }
549         ptr++;
550     }
551
552     if (ptr == end)
553     {
554         *p++ = '\"';
555     }
556
557     *p++ = 0;
558
559     printk(KERN_INFO "%s: %-13s%s\n", strip_info->dev.name, msg, pkt_text);
560 }
561
562 #if 0
563 static void HexDump(char *msg, struct strip *strip_info, __u8 *start, __u8 *end)
564 {
565     __u8 *ptr = start;
566     printk(KERN_INFO "%s: %s: %d bytes\n", strip_info->dev.name, msg, end-ptr);
567
568     while (ptr < end)
569     {
570         long offset = ptr - start;
571         __u8 text[80], *p = text;
572         while (ptr < end && p < &text[16*3])
573         {
574             *p++ = hextable[*ptr >> 4];
575             *p++ = hextable[*ptr++ & 0xF];
576             *p++ = ' ';
577         }
578         p[-1] = 0;
579         printk(KERN_INFO "%s: %4lX %s\n", strip_info->dev.name, offset, text);
580     }
581 }
582 #endif
583
584
585 /************************************************************************/
586 /* Byte stuffing/unstuffing routines                                    */
587
588 /* Stuffing scheme:
589  * 00    Unused (reserved character)
590  * 01-3F Run of 2-64 different characters
591  * 40-7F Run of 1-64 different characters plus a single zero at the end
592  * 80-BF Run of 1-64 of the same character
593  * C0-FF Run of 1-64 zeroes (ASCII 0)
594  */
595
596 typedef enum
597 {
598     Stuff_Diff      = 0x00,
599     Stuff_DiffZero  = 0x40,
600     Stuff_Same      = 0x80,
601     Stuff_Zero      = 0xC0,
602     Stuff_NoCode    = 0xFF,     /* Special code, meaning no code selected */
603
604     Stuff_CodeMask  = 0xC0,
605     Stuff_CountMask = 0x3F,
606     Stuff_MaxCount  = 0x3F,
607     Stuff_Magic     = 0x0D      /* The value we are eliminating */
608 } StuffingCode;
609
610 /* StuffData encodes the data starting at "src" for "length" bytes.
611  * It writes it to the buffer pointed to by "dst" (which must be at least
612  * as long as 1 + 65/64 of the input length). The output may be up to 1.6%
613  * larger than the input for pathological input, but will usually be smaller.
614  * StuffData returns the new value of the dst pointer as its result.
615  * "code_ptr_ptr" points to a "__u8 *" which is used to hold encoding state
616  * between calls, allowing an encoded packet to be incrementally built up
617  * from small parts. On the first call, the "__u8 *" pointed to should be
618  * initialized to NULL; between subsequent calls the calling routine should
619  * leave the value alone and simply pass it back unchanged so that the
620  * encoder can recover its current state.
621  */
622
623 #define StuffData_FinishBlock(X) \
624 (*code_ptr = (X) ^ Stuff_Magic, code = Stuff_NoCode)
625
626 static __u8 *StuffData(__u8 *src, __u32 length, __u8 *dst, __u8 **code_ptr_ptr)
627 {
628     __u8 *end = src + length;
629     __u8 *code_ptr = *code_ptr_ptr;
630      __u8 code = Stuff_NoCode, count = 0;
631
632     if (!length)
633         return(dst);
634
635     if (code_ptr)
636     {
637         /*
638          * Recover state from last call, if applicable
639          */
640         code  = (*code_ptr ^ Stuff_Magic) & Stuff_CodeMask;
641         count = (*code_ptr ^ Stuff_Magic) & Stuff_CountMask;
642     }
643
644     while (src < end)
645     {
646         switch (code)
647         {
648             /* Stuff_NoCode: If no current code, select one */
649             case Stuff_NoCode:
650                 /* Record where we're going to put this code */
651                 code_ptr = dst++;
652                 count = 0;    /* Reset the count (zero means one instance) */
653                 /* Tentatively start a new block */
654                 if (*src == 0)
655                 {
656                     code = Stuff_Zero;
657                     src++;
658                 }
659                 else
660                 {
661                     code = Stuff_Same;
662                     *dst++ = *src++ ^ Stuff_Magic;
663                 }
664                 /* Note: We optimistically assume run of same -- */
665                 /* which will be fixed later in Stuff_Same */
666                 /* if it turns out not to be true. */
667                 break;
668
669             /* Stuff_Zero: We already have at least one zero encoded */
670             case Stuff_Zero:
671                 /* If another zero, count it, else finish this code block */
672                 if (*src == 0)
673                 {
674                     count++;
675                     src++;
676                 }
677                 else
678                 {
679                     StuffData_FinishBlock(Stuff_Zero + count);
680                 }
681                 break;
682
683             /* Stuff_Same: We already have at least one byte encoded */
684             case Stuff_Same:
685                 /* If another one the same, count it */
686                 if ((*src ^ Stuff_Magic) == code_ptr[1])
687                 {
688                     count++;
689                     src++;
690                     break;
691                 }
692                 /* else, this byte does not match this block. */
693                 /* If we already have two or more bytes encoded, finish this code block */
694                 if (count)
695                 {
696                     StuffData_FinishBlock(Stuff_Same + count);
697                     break;
698                 }
699                 /* else, we only have one so far, so switch to Stuff_Diff code */
700                 code = Stuff_Diff;
701                 /* and fall through to Stuff_Diff case below
702                  * Note cunning cleverness here: case Stuff_Diff compares 
703                  * the current character with the previous two to see if it
704                  * has a run of three the same. Won't this be an error if
705                  * there aren't two previous characters stored to compare with?
706                  * No. Because we know the current character is *not* the same
707                  * as the previous one, the first test below will necessarily
708                  * fail and the send half of the "if" won't be executed.
709                  */
710
711             /* Stuff_Diff: We have at least two *different* bytes encoded */
712             case Stuff_Diff:
713                 /* If this is a zero, must encode a Stuff_DiffZero, and begin a new block */
714                 if (*src == 0)
715                 {
716                     StuffData_FinishBlock(Stuff_DiffZero + count);
717                 }
718                 /* else, if we have three in a row, it is worth starting a Stuff_Same block */
719                 else if ((*src ^ Stuff_Magic)==dst[-1] && dst[-1]==dst[-2])
720                 {
721                     /* Back off the last two characters we encoded */
722                     code += count-2;
723                     /* Note: "Stuff_Diff + 0" is an illegal code */
724                     if (code == Stuff_Diff + 0)
725                     {
726                         code = Stuff_Same + 0;
727                     }
728                     StuffData_FinishBlock(code);
729                     code_ptr = dst-2;
730                     /* dst[-1] already holds the correct value */
731                     count = 2;        /* 2 means three bytes encoded */
732                     code = Stuff_Same;
733                 }
734                 /* else, another different byte, so add it to the block */
735                 else
736                 {
737                     *dst++ = *src ^ Stuff_Magic;
738                     count++;
739                 }
740                 src++;    /* Consume the byte */
741                 break;
742         }
743         if (count == Stuff_MaxCount)
744         {
745             StuffData_FinishBlock(code + count);
746         }
747     }
748     if (code == Stuff_NoCode)
749     {
750         *code_ptr_ptr = NULL;
751     }
752     else
753     {
754         *code_ptr_ptr = code_ptr;
755         StuffData_FinishBlock(code + count);
756     }
757     return(dst);
758 }
759
760 /*
761  * UnStuffData decodes the data at "src", up to (but not including) "end".
762  * It writes the decoded data into the buffer pointed to by "dst", up to a
763  * maximum of "dst_length", and returns the new value of "src" so that a
764  * follow-on call can read more data, continuing from where the first left off.
765  * 
766  * There are three types of results:
767  * 1. The source data runs out before extracting "dst_length" bytes:
768  *    UnStuffData returns NULL to indicate failure.
769  * 2. The source data produces exactly "dst_length" bytes:
770  *    UnStuffData returns new_src = end to indicate that all bytes were consumed.
771  * 3. "dst_length" bytes are extracted, with more remaining.
772  *    UnStuffData returns new_src < end to indicate that there are more bytes
773  *    to be read.
774  * 
775  * Note: The decoding may be destructive, in that it may alter the source
776  * data in the process of decoding it (this is necessary to allow a follow-on
777  * call to resume correctly).
778  */
779
780 static __u8 *UnStuffData(__u8 *src, __u8 *end, __u8 *dst, __u32 dst_length)
781 {
782     __u8 *dst_end = dst + dst_length;
783     /* Sanity check */
784     if (!src || !end || !dst || !dst_length)
785         return(NULL);
786     while (src < end && dst < dst_end)
787     {
788         int count = (*src ^ Stuff_Magic) & Stuff_CountMask;
789         switch ((*src ^ Stuff_Magic) & Stuff_CodeMask)
790         {
791             case Stuff_Diff:
792                 if (src+1+count >= end)
793                     return(NULL);
794                 do
795                 {
796                     *dst++ = *++src ^ Stuff_Magic;
797                 }
798                 while(--count >= 0 && dst < dst_end);
799                 if (count < 0)
800                     src += 1;
801                 else
802                 {
803                     if (count == 0)
804                         *src = Stuff_Same ^ Stuff_Magic;
805                     else
806                         *src = (Stuff_Diff + count) ^ Stuff_Magic;
807                 }
808                 break;
809             case Stuff_DiffZero:
810                 if (src+1+count >= end)
811                     return(NULL);
812                 do
813                 {
814                     *dst++ = *++src ^ Stuff_Magic;
815                 }
816                 while(--count >= 0 && dst < dst_end);
817                 if (count < 0)
818                     *src = Stuff_Zero ^ Stuff_Magic;
819                 else
820                     *src = (Stuff_DiffZero + count) ^ Stuff_Magic;
821                 break;
822             case Stuff_Same:
823                 if (src+1 >= end)
824                     return(NULL);
825                 do
826                 {
827                     *dst++ = src[1] ^ Stuff_Magic;
828                 }
829                 while(--count >= 0 && dst < dst_end);
830                 if (count < 0)
831                     src += 2;
832                 else
833                     *src = (Stuff_Same + count) ^ Stuff_Magic;
834                 break;
835             case Stuff_Zero:
836                 do
837                 {
838                     *dst++ = 0;
839                 }
840                 while(--count >= 0 && dst < dst_end);
841                 if (count < 0)
842                     src += 1;
843                 else
844                     *src = (Stuff_Zero + count) ^ Stuff_Magic;
845                 break;
846         }
847     }
848     if (dst < dst_end)
849         return(NULL);
850     else
851         return(src);
852 }
853
854
855 /************************************************************************/
856 /* General routines for STRIP                                           */
857
858 /*
859  * get_baud returns the current baud rate, as one of the constants defined in
860  * termbits.h
861  * If the user has issued a baud rate override using the 'setserial' command
862  * and the logical current rate is set to 38.4, then the true baud rate
863  * currently in effect (57.6 or 115.2) is returned.
864  */
865 static unsigned int get_baud(struct tty_struct *tty)
866     {
867     if (!tty || !tty->termios) return(0);
868     if ((tty->termios->c_cflag & CBAUD) == B38400 && tty->driver_data)
869         {
870         struct async_struct *info = (struct async_struct *)tty->driver_data;
871         if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI ) return(B57600);
872         if ((info->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI) return(B115200);
873         }
874     return(tty->termios->c_cflag & CBAUD);
875     }
876
877 /*
878  * set_baud sets the baud rate to the rate defined by baudcode
879  * Note: The rate B38400 should be avoided, because the user may have
880  * issued a 'setserial' speed override to map that to a different speed.
881  * We could achieve a true rate of 38400 if we needed to by cancelling
882  * any user speed override that is in place, but that might annoy the
883  * user, so it is simplest to just avoid using 38400.
884  */
885 static void set_baud(struct tty_struct *tty, unsigned int baudcode)
886     {
887     struct termios old_termios = *(tty->termios);
888     tty->termios->c_cflag &= ~CBAUD; /* Clear the old baud setting */
889     tty->termios->c_cflag |= baudcode; /* Set the new baud setting */
890     tty->driver.set_termios(tty, &old_termios);
891     }
892
893 /*
894  * Convert a string to a Metricom Address.
895  */
896
897 #define IS_RADIO_ADDRESS(p) (                                                 \
898   isdigit((p)[0]) && isdigit((p)[1]) && isdigit((p)[2]) && isdigit((p)[3]) && \
899   (p)[4] == '-' &&                                                            \
900   isdigit((p)[5]) && isdigit((p)[6]) && isdigit((p)[7]) && isdigit((p)[8])    )
901
902 static int string_to_radio_address(MetricomAddress *addr, __u8 *p)
903 {
904     if (!IS_RADIO_ADDRESS(p)) return(1);
905     addr->c[0] = 0;
906     addr->c[1] = 0;
907     addr->c[2] = READHEX(p[0]) << 4 | READHEX(p[1]);
908     addr->c[3] = READHEX(p[2]) << 4 | READHEX(p[3]);
909     addr->c[4] = READHEX(p[5]) << 4 | READHEX(p[6]);
910     addr->c[5] = READHEX(p[7]) << 4 | READHEX(p[8]);
911     return(0);
912 }
913
914 /*
915  * Convert a Metricom Address to a string.
916  */
917
918 static __u8 *radio_address_to_string(const MetricomAddress *addr, MetricomAddressString *p)
919 {
920     sprintf(p->c, "%02X%02X-%02X%02X", addr->c[2], addr->c[3], addr->c[4], addr->c[5]);
921     return(p->c);
922 }
923
924 /*
925  * Note: Must make sure sx_size is big enough to receive a stuffed
926  * MAX_RECV_MTU packet. Additionally, we also want to ensure that it's
927  * big enough to receive a large radio neighbour list (currently 4K).
928  */
929
930 static int allocate_buffers(struct strip *strip_info)
931 {
932     struct net_device *dev = &strip_info->dev;
933     int sx_size    = MAX(STRIP_ENCAP_SIZE(MAX_RECV_MTU), 4096);
934     int tx_size    = STRIP_ENCAP_SIZE(dev->mtu) + MaxCommandStringLength;
935     __u8 *r = kmalloc(MAX_RECV_MTU, GFP_ATOMIC);
936     __u8 *s = kmalloc(sx_size,      GFP_ATOMIC);
937     __u8 *t = kmalloc(tx_size,      GFP_ATOMIC);
938     if (r && s && t)
939     {
940         strip_info->rx_buff = r;
941         strip_info->sx_buff = s;
942         strip_info->tx_buff = t;
943         strip_info->sx_size = sx_size;
944         strip_info->tx_size = tx_size;
945         strip_info->mtu     = dev->mtu;
946         return(1);
947     }
948     if (r) kfree(r);
949     if (s) kfree(s);
950     if (t) kfree(t);
951     return(0);
952 }
953
954 /*
955  * MTU has been changed by the IP layer. Unfortunately we are not told
956  * about this, but we spot it ourselves and fix things up. We could be in
957  * an upcall from the tty driver, or in an ip packet queue.
958  */
959
960 static void strip_changedmtu(struct strip *strip_info)
961 {
962     int old_mtu           = strip_info->mtu;
963     struct net_device *dev    = &strip_info->dev;
964     unsigned char *orbuff = strip_info->rx_buff;
965     unsigned char *osbuff = strip_info->sx_buff;
966     unsigned char *otbuff = strip_info->tx_buff;
967     InterruptStatus intstat;
968
969     if (dev->mtu > MAX_SEND_MTU)
970     {
971         printk(KERN_ERR "%s: MTU exceeds maximum allowable (%d), MTU change cancelled.\n",
972             strip_info->dev.name, MAX_SEND_MTU);
973         dev->mtu = old_mtu;
974         return;
975     }
976
977     /*
978      * Have to disable interrupts here because we're reallocating and resizing
979      * the serial buffers, and we can't have data arriving in them while we're
980      * moving them around in memory. This may cause data to be lost on the serial
981      * port, but hopefully people won't change MTU that often.
982      * Also note, this may not work on a symmetric multi-processor system.
983      */
984     intstat = DisableInterrupts();
985
986     if (!allocate_buffers(strip_info))
987     {
988         RestoreInterrupts(intstat);
989         printk(KERN_ERR "%s: unable to grow strip buffers, MTU change cancelled.\n",
990             strip_info->dev.name);
991         dev->mtu = old_mtu;
992         return;
993     }
994
995     if (strip_info->sx_count)
996     {
997         if (strip_info->sx_count <= strip_info->sx_size)
998             memcpy(strip_info->sx_buff, osbuff, strip_info->sx_count);
999         else
1000         {
1001             strip_info->discard = strip_info->sx_count;
1002             strip_info->rx_over_errors++;
1003         }
1004     }
1005
1006     if (strip_info->tx_left)
1007     {
1008         if (strip_info->tx_left <= strip_info->tx_size)
1009             memcpy(strip_info->tx_buff, strip_info->tx_head, strip_info->tx_left);
1010         else
1011         {
1012             strip_info->tx_left = 0;
1013             strip_info->tx_dropped++;
1014         }
1015     }
1016     strip_info->tx_head = strip_info->tx_buff;
1017
1018     RestoreInterrupts(intstat);
1019
1020     printk(KERN_NOTICE "%s: strip MTU changed fom %d to %d.\n",
1021         strip_info->dev.name, old_mtu, strip_info->mtu);
1022
1023     if (orbuff) kfree(orbuff);
1024     if (osbuff) kfree(osbuff);
1025     if (otbuff) kfree(otbuff);
1026 }
1027
1028 static void strip_unlock(struct strip *strip_info)
1029 {
1030     /*
1031      * Set the timer to go off in one second.
1032      */
1033     strip_info->idle_timer.expires = jiffies + 1*HZ;
1034     add_timer(&strip_info->idle_timer);
1035     netif_wake_queue(&strip_info->dev);
1036 }
1037
1038
1039 /************************************************************************/
1040 /* Callback routines for exporting information through /proc            */
1041
1042 /*
1043  * This function updates the total amount of data printed so far. It then
1044  * determines if the amount of data printed into a buffer  has reached the
1045  * offset requested. If it hasn't, then the buffer is shifted over so that
1046  * the next bit of data can be printed over the old bit. If the total
1047  * amount printed so far exceeds the total amount requested, then this
1048  * function returns 1, otherwise 0.
1049  */
1050 static int 
1051 shift_buffer(char *buffer, int requested_offset, int requested_len,
1052              int *total, int *slop, char **buf)
1053 {
1054     int printed;
1055
1056     /* printk(KERN_DEBUG "shift: buffer: %d o: %d l: %d t: %d buf: %d\n",
1057            (int) buffer, requested_offset, requested_len, *total,
1058            (int) *buf); */
1059     printed = *buf - buffer;
1060     if (*total + printed <= requested_offset) {
1061         *total += printed;
1062         *buf = buffer;
1063     }
1064     else {
1065         if (*total < requested_offset) {
1066             *slop = requested_offset - *total;
1067         }
1068         *total = requested_offset + printed - *slop;
1069     }
1070     if (*total > requested_offset + requested_len) {
1071         return 1;
1072     }
1073     else {
1074         return 0;
1075     }
1076 }
1077
1078 /*
1079  * This function calculates the actual start of the requested data
1080  * in the buffer. It also calculates actual length of data returned,
1081  * which could be less that the amount of data requested.
1082  */
1083 static int
1084 calc_start_len(char *buffer, char **start, int requested_offset,
1085                int requested_len, int total, char *buf)
1086 {
1087     int return_len, buffer_len;
1088
1089     buffer_len = buf - buffer;
1090     if (buffer_len >= 4095) {
1091         printk(KERN_ERR "STRIP: exceeded /proc buffer size\n");
1092     }
1093
1094     /*
1095      * There may be bytes before and after the
1096      * chunk that was actually requested.
1097      */
1098     return_len = total - requested_offset;
1099     if (return_len < 0) {
1100         return_len = 0;
1101     }
1102     *start = buf - return_len;
1103     if (return_len > requested_len) {
1104         return_len = requested_len;
1105     }
1106     /* printk(KERN_DEBUG "return_len: %d\n", return_len); */
1107     return return_len;
1108 }
1109
1110 /*
1111  * If the time is in the near future, time_delta prints the number of
1112  * seconds to go into the buffer and returns the address of the buffer.
1113  * If the time is not in the near future, it returns the address of the
1114  * string "Not scheduled" The buffer must be long enough to contain the
1115  * ascii representation of the number plus 9 charactes for the " seconds"
1116  * and the null character.
1117  */
1118 static char *time_delta(char buffer[], long time)
1119 {
1120     time -= jiffies;
1121     if (time > LongTime / 2) return("Not scheduled");
1122     if(time < 0) time = 0;  /* Don't print negative times */
1123     sprintf(buffer, "%ld seconds", time / HZ);
1124     return(buffer);
1125 }
1126
1127 static int sprintf_neighbours(char *buffer, MetricomNodeTable *table, char *title)
1128 {
1129     /* We wrap this in a do/while loop, so if the table changes */
1130     /* while we're reading it, we just go around and try again. */
1131     struct timeval t;
1132     char *ptr;
1133     do
1134         {
1135         int i;
1136         t = table->timestamp;
1137         ptr = buffer;
1138         if (table->num_nodes) ptr += sprintf(ptr, "\n %s\n", title);
1139         for (i=0; i<table->num_nodes; i++)
1140             {
1141             InterruptStatus intstat = DisableInterrupts();
1142             MetricomNode node = table->node[i];
1143             RestoreInterrupts(intstat);
1144             ptr += sprintf(ptr, "  %s\n", node.c);
1145             }
1146         } while (table->timestamp.tv_sec != t.tv_sec || table->timestamp.tv_usec != t.tv_usec);
1147     return ptr - buffer;
1148 }
1149
1150 /*
1151  * This function prints radio status information into the specified buffer.
1152  * I think the buffer size is 4K, so this routine should never print more
1153  * than 4K of data into it. With the maximum of 32 portables and 32 poletops
1154  * reported, the routine outputs 3107 bytes into the buffer.
1155  */
1156 static int
1157 sprintf_status_info(char *buffer, struct strip *strip_info)
1158 {
1159     char temp[32];
1160     char *p = buffer;
1161     MetricomAddressString addr_string;
1162
1163     /* First, we must copy all of our data to a safe place, */
1164     /* in case a serial interrupt comes in and changes it.  */
1165     InterruptStatus intstat = DisableInterrupts();
1166     int                tx_left             = strip_info->tx_left;
1167     unsigned long      rx_average_pps      = strip_info->rx_average_pps;
1168     unsigned long      tx_average_pps      = strip_info->tx_average_pps;
1169     unsigned long      sx_average_pps      = strip_info->sx_average_pps;
1170     int                working             = strip_info->working;
1171     int                firmware_level      = strip_info->firmware_level;
1172     long               watchdog_doprobe    = strip_info->watchdog_doprobe;
1173     long               watchdog_doreset    = strip_info->watchdog_doreset;
1174     long               gratuitous_arp      = strip_info->gratuitous_arp;
1175     long               arp_interval        = strip_info->arp_interval;
1176     FirmwareVersion    firmware_version    = strip_info->firmware_version;
1177     SerialNumber       serial_number       = strip_info->serial_number;
1178     BatteryVoltage     battery_voltage     = strip_info->battery_voltage;
1179     char*              if_name             = strip_info->dev.name;
1180     MetricomAddress    true_dev_addr       = strip_info->true_dev_addr;
1181     MetricomAddress    dev_dev_addr        = *(MetricomAddress*)strip_info->dev.dev_addr;
1182     int                manual_dev_addr     = strip_info->manual_dev_addr;
1183 #ifdef EXT_COUNTERS
1184     unsigned long      rx_bytes            = strip_info->rx_bytes;
1185     unsigned long      tx_bytes            = strip_info->tx_bytes;
1186     unsigned long      rx_rbytes           = strip_info->rx_rbytes;
1187     unsigned long      tx_rbytes           = strip_info->tx_rbytes;
1188     unsigned long      rx_sbytes           = strip_info->rx_sbytes;
1189     unsigned long      tx_sbytes           = strip_info->tx_sbytes;
1190     unsigned long      rx_ebytes           = strip_info->rx_ebytes;
1191     unsigned long      tx_ebytes           = strip_info->tx_ebytes;
1192 #endif
1193     RestoreInterrupts(intstat);
1194
1195     p += sprintf(p, "\nInterface name\t\t%s\n", if_name);
1196     p += sprintf(p, " Radio working:\t\t%s\n", working ? "Yes" : "No");
1197     radio_address_to_string(&true_dev_addr, &addr_string);
1198     p += sprintf(p, " Radio address:\t\t%s\n", addr_string.c);
1199     if (manual_dev_addr)
1200     {
1201         radio_address_to_string(&dev_dev_addr, &addr_string);
1202         p += sprintf(p, " Device address:\t%s\n", addr_string.c);
1203     }
1204     p += sprintf(p, " Firmware version:\t%s", !working        ? "Unknown" :
1205                                               !firmware_level ? "Should be upgraded" :
1206                                               firmware_version.c);
1207     if (firmware_level >= ChecksummedMessages) p += sprintf(p, " (Checksums Enabled)");
1208     p += sprintf(p, "\n");
1209     p += sprintf(p, " Serial number:\t\t%s\n", serial_number.c);
1210     p += sprintf(p, " Battery voltage:\t%s\n", battery_voltage.c);
1211     p += sprintf(p, " Transmit queue (bytes):%d\n", tx_left);
1212     p += sprintf(p, " Receive packet rate:   %ld packets per second\n", rx_average_pps / 8);
1213     p += sprintf(p, " Transmit packet rate:  %ld packets per second\n", tx_average_pps / 8);
1214     p += sprintf(p, " Sent packet rate:      %ld packets per second\n", sx_average_pps / 8);
1215     p += sprintf(p, " Next watchdog probe:\t%s\n", time_delta(temp, watchdog_doprobe));
1216     p += sprintf(p, " Next watchdog reset:\t%s\n", time_delta(temp, watchdog_doreset));
1217     p += sprintf(p, " Next gratuitous ARP:\t");
1218
1219     if (!memcmp(strip_info->dev.dev_addr, zero_address.c, sizeof(zero_address)))
1220         p += sprintf(p, "Disabled\n");
1221     else
1222     {
1223         p += sprintf(p, "%s\n", time_delta(temp, gratuitous_arp));
1224         p += sprintf(p, " Next ARP interval:\t%ld seconds\n", JIFFIE_TO_SEC(arp_interval));
1225     }
1226
1227     if (working)
1228         {
1229 #ifdef EXT_COUNTERS
1230           p += sprintf(p, "\n");
1231           p += sprintf(p, " Total bytes:         \trx:\t%lu\ttx:\t%lu\n", rx_bytes, tx_bytes);
1232           p += sprintf(p, "  thru radio:         \trx:\t%lu\ttx:\t%lu\n", rx_rbytes, tx_rbytes);
1233           p += sprintf(p, "  thru serial port:   \trx:\t%lu\ttx:\t%lu\n", rx_sbytes, tx_sbytes);
1234           p += sprintf(p, " Total stat/err bytes:\trx:\t%lu\ttx:\t%lu\n", rx_ebytes, tx_ebytes);
1235 #endif
1236         p += sprintf_neighbours(p, &strip_info->poletops, "Poletops:");
1237         p += sprintf_neighbours(p, &strip_info->portables, "Portables:");
1238         }
1239
1240     return p - buffer;
1241 }
1242
1243 /*
1244  * This function is exports status information from the STRIP driver through
1245  * the /proc file system.
1246  */
1247
1248 static int get_status_info(char *buffer, char **start, off_t req_offset, int req_len)
1249 {
1250     int           total = 0, slop = 0;
1251     struct strip *strip_info = struct_strip_list;
1252     char         *buf = buffer;
1253
1254     buf += sprintf(buf, "strip_version: %s\n", StripVersion);
1255     if (shift_buffer(buffer, req_offset, req_len, &total, &slop, &buf)) goto exit;
1256
1257     while (strip_info != NULL)
1258         {
1259         buf += sprintf_status_info(buf, strip_info);
1260         if (shift_buffer(buffer, req_offset, req_len, &total, &slop, &buf)) break;
1261         strip_info = strip_info->next;
1262         }
1263     exit:
1264     return(calc_start_len(buffer, start, req_offset, req_len, total, buf));
1265 }
1266
1267 /************************************************************************/
1268 /* Sending routines                                                     */
1269
1270 static void ResetRadio(struct strip *strip_info)
1271 {
1272     struct tty_struct *tty = strip_info->tty;
1273     static const char init[] = "ate0q1dt**starmode\r**";
1274     StringDescriptor s = { init, sizeof(init)-1 };
1275
1276     /* 
1277      * If the radio isn't working anymore,
1278      * we should clear the old status information.
1279      */
1280     if (strip_info->working)
1281     {
1282         printk(KERN_INFO "%s: No response: Resetting radio.\n", strip_info->dev.name);
1283         strip_info->firmware_version.c[0] = '\0';
1284         strip_info->serial_number.c[0] = '\0';
1285         strip_info->battery_voltage.c[0] = '\0';
1286         strip_info->portables.num_nodes = 0;
1287         do_gettimeofday(&strip_info->portables.timestamp);
1288         strip_info->poletops.num_nodes = 0;
1289         do_gettimeofday(&strip_info->poletops.timestamp);
1290     }
1291
1292     strip_info->pps_timer      = jiffies;
1293     strip_info->rx_pps_count   = 0;
1294     strip_info->tx_pps_count   = 0;
1295     strip_info->sx_pps_count   = 0;
1296     strip_info->rx_average_pps = 0;
1297     strip_info->tx_average_pps = 0;
1298     strip_info->sx_average_pps = 0;
1299
1300     /* Mark radio address as unknown */
1301     *(MetricomAddress*)&strip_info->true_dev_addr = zero_address;
1302     if (!strip_info->manual_dev_addr)
1303         *(MetricomAddress*)strip_info->dev.dev_addr = zero_address;
1304     strip_info->working = FALSE;
1305     strip_info->firmware_level = NoStructure;
1306     strip_info->next_command   = CompatibilityCommand;
1307     strip_info->watchdog_doprobe = jiffies + 10 * HZ;
1308     strip_info->watchdog_doreset = jiffies + 1 * HZ;
1309
1310     /* If the user has selected a baud rate above 38.4 see what magic we have to do */
1311     if (strip_info->user_baud > B38400)
1312         {
1313         /*
1314          * Subtle stuff: Pay attention :-)
1315          * If the serial port is currently at the user's selected (>38.4) rate,
1316          * then we temporarily switch to 19.2 and issue the ATS304 command
1317          * to tell the radio to switch to the user's selected rate.
1318          * If the serial port is not currently at that rate, that means we just
1319          * issued the ATS304 command last time through, so this time we restore
1320          * the user's selected rate and issue the normal starmode reset string.
1321          */
1322         if (strip_info->user_baud == get_baud(tty))
1323             {
1324             static const char b0[] = "ate0q1s304=57600\r";
1325             static const char b1[] = "ate0q1s304=115200\r";
1326             static const StringDescriptor baudstring[2] =
1327                 { { b0, sizeof(b0)-1 }, { b1, sizeof(b1)-1 } };
1328             set_baud(tty, B19200);
1329             if      (strip_info->user_baud == B57600 ) s = baudstring[0];
1330             else if (strip_info->user_baud == B115200) s = baudstring[1];
1331             else s = baudstring[1]; /* For now */
1332             }
1333         else set_baud(tty, strip_info->user_baud);
1334         }
1335
1336     tty->driver.write(tty, 0, s.string, s.length);
1337 #ifdef EXT_COUNTERS
1338     strip_info->tx_ebytes += s.length;
1339 #endif
1340 }
1341
1342 /*
1343  * Called by the driver when there's room for more data.  If we have
1344  * more packets to send, we send them here.
1345  */
1346
1347 static void strip_write_some_more(struct tty_struct *tty)
1348 {
1349     struct strip *strip_info = (struct strip *) tty->disc_data;
1350
1351     /* First make sure we're connected. */
1352     if (!strip_info || strip_info->magic != STRIP_MAGIC || 
1353         !netif_running(&strip_info->dev))
1354         return;
1355
1356     if (strip_info->tx_left > 0)
1357     {
1358         /*
1359          * If some data left, send it
1360          * Note: There's a kernel design bug here. The write_wakeup routine has to
1361          * know how many bytes were written in the previous call, but the number of
1362          * bytes written is returned as the result of the tty->driver.write call,
1363          * and there's no guarantee that the tty->driver.write routine will have
1364          * returned before the write_wakeup routine is invoked. If the PC has fast
1365          * Serial DMA hardware, then it's quite possible that the write could complete
1366          * almost instantaneously, meaning that my write_wakeup routine could be
1367          * called immediately, before tty->driver.write has had a chance to return
1368          * the number of bytes that it wrote. In an attempt to guard against this,
1369          * I disable interrupts around the call to tty->driver.write, although even
1370          * this might not work on a symmetric multi-processor system.
1371          */
1372         InterruptStatus intstat = DisableInterrupts();
1373         int num_written = tty->driver.write(tty, 0, strip_info->tx_head, strip_info->tx_left);
1374         strip_info->tx_left -= num_written;
1375         strip_info->tx_head += num_written;
1376 #ifdef EXT_COUNTERS
1377         strip_info->tx_sbytes += num_written;
1378 #endif
1379         RestoreInterrupts(intstat);
1380     }
1381     else            /* Else start transmission of another packet */
1382     {
1383         tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
1384         strip_unlock(strip_info);
1385     }
1386 }
1387
1388 static __u8 *add_checksum(__u8 *buffer, __u8 *end)
1389 {
1390     __u16 sum = 0;
1391     __u8 *p = buffer;
1392     while (p < end) sum += *p++;
1393     end[3] = hextable[sum & 0xF]; sum >>= 4;
1394     end[2] = hextable[sum & 0xF]; sum >>= 4;
1395     end[1] = hextable[sum & 0xF]; sum >>= 4;
1396     end[0] = hextable[sum & 0xF];
1397     return(end+4);
1398 }
1399
1400 static unsigned char *strip_make_packet(unsigned char *buffer, struct strip *strip_info, struct sk_buff *skb)
1401 {
1402     __u8           *ptr = buffer;
1403     __u8           *stuffstate = NULL;
1404     STRIP_Header   *header     = (STRIP_Header *)skb->data;
1405     MetricomAddress haddr      = header->dst_addr;
1406     int             len        = skb->len - sizeof(STRIP_Header);
1407     MetricomKey     key;
1408
1409     /*HexDump("strip_make_packet", strip_info, skb->data, skb->data + skb->len);*/
1410
1411     if      (header->protocol == htons(ETH_P_IP))  key = SIP0Key;
1412     else if (header->protocol == htons(ETH_P_ARP)) key = ARP0Key;
1413     else
1414     {
1415         printk(KERN_ERR "%s: strip_make_packet: Unknown packet type 0x%04X\n",
1416             strip_info->dev.name, ntohs(header->protocol));
1417         return(NULL);
1418     }
1419
1420     if (len > strip_info->mtu)
1421     {
1422         printk(KERN_ERR "%s: Dropping oversized transmit packet: %d bytes\n",
1423             strip_info->dev.name, len);
1424         return(NULL);
1425     }
1426
1427     /*
1428      * If we're sending to ourselves, discard the packet.
1429      * (Metricom radios choke if they try to send a packet to their own address.)
1430      */
1431     if (!memcmp(haddr.c, strip_info->true_dev_addr.c, sizeof(haddr)))
1432     {
1433         printk(KERN_ERR "%s: Dropping packet addressed to self\n", strip_info->dev.name);
1434         return(NULL);
1435     }
1436
1437     /*
1438      * If this is a broadcast packet, send it to our designated Metricom
1439      * 'broadcast hub' radio (First byte of address being 0xFF means broadcast)
1440      */
1441     if (haddr.c[0] == 0xFF)
1442     {
1443         u32 brd = 0;
1444         struct in_device *in_dev = in_dev_get(&strip_info->dev);
1445         if (in_dev == NULL)
1446                 return NULL;
1447         read_lock(&in_dev->lock);
1448         if (in_dev->ifa_list)
1449                 brd = in_dev->ifa_list->ifa_broadcast;
1450         read_unlock(&in_dev->lock);
1451         in_dev_put(in_dev);
1452
1453         /* arp_query returns 1 if it succeeds in looking up the address, 0 if it fails */
1454         if (!arp_query(haddr.c, brd, &strip_info->dev))
1455         {
1456             printk(KERN_ERR "%s: Unable to send packet (no broadcast hub configured)\n",
1457                 strip_info->dev.name);
1458             return(NULL);
1459         }
1460         /*
1461          * If we are the broadcast hub, don't bother sending to ourselves.
1462          * (Metricom radios choke if they try to send a packet to their own address.)
1463          */
1464         if (!memcmp(haddr.c, strip_info->true_dev_addr.c, sizeof(haddr))) return(NULL);
1465     }
1466
1467     *ptr++ = 0x0D;
1468     *ptr++ = '*';
1469     *ptr++ = hextable[haddr.c[2] >> 4];
1470     *ptr++ = hextable[haddr.c[2] & 0xF];
1471     *ptr++ = hextable[haddr.c[3] >> 4];
1472     *ptr++ = hextable[haddr.c[3] & 0xF];
1473     *ptr++ = '-';
1474     *ptr++ = hextable[haddr.c[4] >> 4];
1475     *ptr++ = hextable[haddr.c[4] & 0xF];
1476     *ptr++ = hextable[haddr.c[5] >> 4];
1477     *ptr++ = hextable[haddr.c[5] & 0xF];
1478     *ptr++ = '*';
1479     *ptr++ = key.c[0];
1480     *ptr++ = key.c[1];
1481     *ptr++ = key.c[2];
1482     *ptr++ = key.c[3];
1483
1484     ptr = StuffData(skb->data + sizeof(STRIP_Header), len, ptr, &stuffstate);
1485
1486     if (strip_info->firmware_level >= ChecksummedMessages) ptr = add_checksum(buffer+1, ptr);
1487
1488     *ptr++ = 0x0D;
1489     return(ptr);
1490 }
1491
1492 static void strip_send(struct strip *strip_info, struct sk_buff *skb)
1493 {
1494     MetricomAddress haddr;
1495     unsigned char *ptr = strip_info->tx_buff;
1496     int doreset = (long)jiffies - strip_info->watchdog_doreset >= 0;
1497     int doprobe = (long)jiffies - strip_info->watchdog_doprobe >= 0 && !doreset;
1498     u32 addr, brd;
1499
1500     /*
1501      * 1. If we have a packet, encapsulate it and put it in the buffer
1502      */
1503     if (skb)
1504     {
1505         char *newptr = strip_make_packet(ptr, strip_info, skb);
1506         strip_info->tx_pps_count++;
1507         if (!newptr) strip_info->tx_dropped++;
1508         else
1509         {
1510             ptr = newptr;
1511             strip_info->sx_pps_count++;
1512             strip_info->tx_packets++;        /* Count another successful packet */
1513 #ifdef EXT_COUNTERS
1514             strip_info->tx_bytes += skb->len;
1515             strip_info->tx_rbytes += ptr - strip_info->tx_buff;
1516 #endif
1517             /*DumpData("Sending:", strip_info, strip_info->tx_buff, ptr);*/
1518             /*HexDump("Sending", strip_info, strip_info->tx_buff, ptr);*/
1519         }
1520     }
1521
1522     /*
1523      * 2. If it is time for another tickle, tack it on, after the packet
1524      */
1525     if (doprobe)
1526     {
1527         StringDescriptor ts = CommandString[strip_info->next_command];
1528 #if TICKLE_TIMERS
1529         {
1530         struct timeval tv;
1531         do_gettimeofday(&tv);
1532         printk(KERN_INFO "**** Sending tickle string %d      at %02d.%06d\n",
1533             strip_info->next_command, tv.tv_sec % 100, tv.tv_usec);
1534         }
1535 #endif
1536         if (ptr == strip_info->tx_buff) *ptr++ = 0x0D;
1537
1538         *ptr++ = '*'; /* First send "**" to provoke an error message */
1539         *ptr++ = '*';
1540
1541         /* Then add the command */
1542         memcpy(ptr, ts.string, ts.length);
1543
1544         /* Add a checksum ? */
1545         if (strip_info->firmware_level < ChecksummedMessages) ptr += ts.length;
1546         else ptr = add_checksum(ptr, ptr + ts.length);
1547
1548         *ptr++ = 0x0D; /* Terminate the command with a <CR> */
1549
1550         /* Cycle to next periodic command? */
1551         if (strip_info->firmware_level >= StructuredMessages)
1552                 if (++strip_info->next_command >= ELEMENTS_OF(CommandString))
1553                         strip_info->next_command = 0;
1554 #ifdef EXT_COUNTERS
1555         strip_info->tx_ebytes += ts.length;
1556 #endif
1557         strip_info->watchdog_doprobe = jiffies + 10 * HZ;
1558         strip_info->watchdog_doreset = jiffies + 1 * HZ;
1559         /*printk(KERN_INFO "%s: Routine radio test.\n", strip_info->dev.name);*/
1560     }
1561
1562     /*
1563      * 3. Set up the strip_info ready to send the data (if any).
1564      */
1565     strip_info->tx_head = strip_info->tx_buff;
1566     strip_info->tx_left = ptr - strip_info->tx_buff;
1567     strip_info->tty->flags |= (1 << TTY_DO_WRITE_WAKEUP);
1568
1569     /*
1570      * 4. Debugging check to make sure we're not overflowing the buffer.
1571      */
1572     if (strip_info->tx_size - strip_info->tx_left < 20)
1573         printk(KERN_ERR "%s: Sending%5d bytes;%5d bytes free.\n", strip_info->dev.name,
1574             strip_info->tx_left, strip_info->tx_size - strip_info->tx_left);
1575
1576     /*
1577      * 5. If watchdog has expired, reset the radio. Note: if there's data waiting in
1578      * the buffer, strip_write_some_more will send it after the reset has finished
1579      */
1580     if (doreset) { ResetRadio(strip_info); return; }
1581
1582     if (1) {
1583             struct in_device *in_dev = in_dev_get(&strip_info->dev);
1584             brd = addr = 0;
1585             if (in_dev) {
1586                     read_lock(&in_dev->lock);
1587                     if (in_dev->ifa_list) {
1588                             brd = in_dev->ifa_list->ifa_broadcast;
1589                             addr = in_dev->ifa_list->ifa_local;
1590                     }
1591                     read_unlock(&in_dev->lock);
1592                     in_dev_put(in_dev);
1593             }
1594     }
1595     
1596
1597     /*
1598      * 6. If it is time for a periodic ARP, queue one up to be sent.
1599      * We only do this if:
1600      *  1. The radio is working
1601      *  2. It's time to send another periodic ARP
1602      *  3. We really know what our address is (and it is not manually set to zero)
1603      *  4. We have a designated broadcast address configured
1604      * If we queue up an ARP packet when we don't have a designated broadcast
1605      * address configured, then the packet will just have to be discarded in
1606      * strip_make_packet. This is not fatal, but it causes misleading information
1607      * to be displayed in tcpdump. tcpdump will report that periodic APRs are
1608      * being sent, when in fact they are not, because they are all being dropped
1609      * in the strip_make_packet routine.
1610      */
1611     if (strip_info->working && (long)jiffies - strip_info->gratuitous_arp >= 0 &&
1612         memcmp(strip_info->dev.dev_addr, zero_address.c, sizeof(zero_address)) &&
1613         arp_query(haddr.c, brd, &strip_info->dev))
1614     {
1615         /*printk(KERN_INFO "%s: Sending gratuitous ARP with interval %ld\n",
1616             strip_info->dev.name, strip_info->arp_interval / HZ);*/
1617         strip_info->gratuitous_arp = jiffies + strip_info->arp_interval;
1618         strip_info->arp_interval *= 2;
1619         if (strip_info->arp_interval > MaxARPInterval)
1620             strip_info->arp_interval = MaxARPInterval;
1621         if (addr)
1622             arp_send(
1623                 ARPOP_REPLY, ETH_P_ARP,
1624                 addr, /* Target address of ARP packet is our address */
1625                 &strip_info->dev,              /* Device to send packet on */
1626                 addr, /* Source IP address this ARP packet comes from */
1627                 NULL,                          /* Destination HW address is NULL (broadcast it) */
1628                 strip_info->dev.dev_addr,      /* Source HW address is our HW address */
1629                 strip_info->dev.dev_addr);     /* Target HW address is our HW address (redundant) */
1630     }
1631
1632     /*
1633      * 7. All ready. Start the transmission
1634      */
1635     strip_write_some_more(strip_info->tty);
1636 }
1637
1638 /* Encapsulate a datagram and kick it into a TTY queue. */
1639 static int strip_xmit(struct sk_buff *skb, struct net_device *dev)
1640 {
1641     struct strip *strip_info = (struct strip *)(dev->priv);
1642
1643     if (!netif_running(dev))
1644     {
1645         printk(KERN_ERR "%s: xmit call when iface is down\n", dev->name);
1646         return(1);
1647     }
1648
1649     netif_stop_queue(dev);
1650     
1651     del_timer(&strip_info->idle_timer);
1652
1653     /* See if someone has been ifconfigging */
1654     if (strip_info->mtu != strip_info->dev.mtu)
1655         strip_changedmtu(strip_info);
1656
1657     if (jiffies - strip_info->pps_timer > HZ)
1658     {
1659         unsigned long t = jiffies - strip_info->pps_timer;
1660         unsigned long rx_pps_count = (strip_info->rx_pps_count * HZ * 8 + t/2) / t;
1661         unsigned long tx_pps_count = (strip_info->tx_pps_count * HZ * 8 + t/2) / t;
1662         unsigned long sx_pps_count = (strip_info->sx_pps_count * HZ * 8 + t/2) / t;
1663
1664         strip_info->pps_timer = jiffies;
1665         strip_info->rx_pps_count = 0;
1666         strip_info->tx_pps_count = 0;
1667         strip_info->sx_pps_count = 0;
1668
1669         strip_info->rx_average_pps = (strip_info->rx_average_pps + rx_pps_count + 1) / 2;
1670         strip_info->tx_average_pps = (strip_info->tx_average_pps + tx_pps_count + 1) / 2;
1671         strip_info->sx_average_pps = (strip_info->sx_average_pps + sx_pps_count + 1) / 2;
1672
1673         if (rx_pps_count / 8 >= 10)
1674             printk(KERN_INFO "%s: WARNING: Receiving %ld packets per second.\n",
1675                 strip_info->dev.name, rx_pps_count / 8);
1676         if (tx_pps_count / 8 >= 10)
1677             printk(KERN_INFO "%s: WARNING: Tx        %ld packets per second.\n",
1678                 strip_info->dev.name, tx_pps_count / 8);
1679         if (sx_pps_count / 8 >= 10)
1680             printk(KERN_INFO "%s: WARNING: Sending   %ld packets per second.\n",
1681                 strip_info->dev.name, sx_pps_count / 8);
1682     }
1683
1684     strip_send(strip_info, skb);
1685
1686     if (skb)
1687         dev_kfree_skb(skb);
1688     return(0);
1689 }
1690
1691 /*
1692  * IdleTask periodically calls strip_xmit, so even when we have no IP packets
1693  * to send for an extended period of time, the watchdog processing still gets
1694  * done to ensure that the radio stays in Starmode
1695  */
1696
1697 static void strip_IdleTask(unsigned long parameter)
1698 {
1699     strip_xmit(NULL, (struct net_device *)parameter);
1700 }
1701
1702 /*
1703  * Create the MAC header for an arbitrary protocol layer
1704  *
1705  * saddr!=NULL        means use this specific address (n/a for Metricom)
1706  * saddr==NULL        means use default device source address
1707  * daddr!=NULL        means use this destination address
1708  * daddr==NULL        means leave destination address alone
1709  *                 (e.g. unresolved arp -- kernel will call
1710  *                 rebuild_header later to fill in the address)
1711  */
1712
1713 static int strip_header(struct sk_buff *skb, struct net_device *dev,
1714         unsigned short type, void *daddr, void *saddr, unsigned len)
1715 {
1716     struct strip *strip_info = (struct strip *)(dev->priv);
1717     STRIP_Header *header = (STRIP_Header *)skb_push(skb, sizeof(STRIP_Header));
1718
1719     /*printk(KERN_INFO "%s: strip_header 0x%04X %s\n", dev->name, type,
1720         type == ETH_P_IP ? "IP" : type == ETH_P_ARP ? "ARP" : "");*/
1721
1722     header->src_addr = strip_info->true_dev_addr;
1723     header->protocol = htons(type);
1724
1725     /*HexDump("strip_header", (struct strip *)(dev->priv), skb->data, skb->data + skb->len);*/
1726
1727     if (!daddr) return(-dev->hard_header_len);
1728
1729     header->dst_addr = *(MetricomAddress*)daddr;
1730     return(dev->hard_header_len);
1731 }
1732
1733 /*
1734  * Rebuild the MAC header. This is called after an ARP
1735  * (or in future other address resolution) has completed on this
1736  * sk_buff. We now let ARP fill in the other fields.
1737  * I think this should return zero if packet is ready to send,
1738  * or non-zero if it needs more time to do an address lookup
1739  */
1740
1741 static int strip_rebuild_header(struct sk_buff *skb)
1742 {
1743 #ifdef CONFIG_INET
1744     STRIP_Header *header = (STRIP_Header *) skb->data;
1745
1746     /* Arp find returns zero if if knows the address, */
1747     /* or if it doesn't know the address it sends an ARP packet and returns non-zero */
1748     return arp_find(header->dst_addr.c, skb)? 1 : 0;
1749 #else
1750     return 0;
1751 #endif
1752 }
1753
1754
1755 /************************************************************************/
1756 /* Receiving routines                                                   */
1757
1758 static int strip_receive_room(struct tty_struct *tty)
1759 {
1760     return 0x10000;  /* We can handle an infinite amount of data. :-) */
1761 }
1762
1763 /*
1764  * This function parses the response to the ATS300? command,
1765  * extracting the radio version and serial number.
1766  */
1767 static void get_radio_version(struct strip *strip_info, __u8 *ptr, __u8 *end)
1768 {
1769     __u8 *p, *value_begin, *value_end;
1770     int len;
1771     
1772     /* Determine the beginning of the second line of the payload */
1773     p = ptr;
1774     while (p < end && *p != 10) p++;
1775     if (p >= end) return;
1776     p++;
1777     value_begin = p;
1778     
1779     /* Determine the end of line */
1780     while (p < end && *p != 10) p++;
1781     if (p >= end) return;
1782     value_end = p;
1783     p++;
1784      
1785     len = value_end - value_begin;
1786     len = MIN(len, sizeof(FirmwareVersion) - 1);
1787     if (strip_info->firmware_version.c[0] == 0)
1788         printk(KERN_INFO "%s: Radio Firmware: %.*s\n",
1789             strip_info->dev.name, len, value_begin);
1790     sprintf(strip_info->firmware_version.c, "%.*s", len, value_begin);
1791     
1792     /* Look for the first colon */
1793     while (p < end && *p != ':') p++;
1794     if (p >= end) return;
1795     /* Skip over the space */
1796     p += 2;
1797     len = sizeof(SerialNumber) - 1;
1798     if (p + len <= end) {
1799         sprintf(strip_info->serial_number.c, "%.*s", len, p);
1800     }
1801     else {
1802         printk(KERN_DEBUG "STRIP: radio serial number shorter (%d) than expected (%d)\n",
1803                end - p, len);
1804     }
1805 }
1806
1807 /*
1808  * This function parses the response to the ATS325? command,
1809  * extracting the radio battery voltage.
1810  */
1811 static void get_radio_voltage(struct strip *strip_info, __u8 *ptr, __u8 *end)
1812 {
1813     int len;
1814
1815     len = sizeof(BatteryVoltage) - 1;
1816     if (ptr + len <= end) {
1817         sprintf(strip_info->battery_voltage.c, "%.*s", len, ptr);
1818     }
1819     else {
1820         printk(KERN_DEBUG "STRIP: radio voltage string shorter (%d) than expected (%d)\n",
1821                end - ptr, len);
1822     }
1823 }
1824
1825 /*
1826  * This function parses the responses to the AT~LA and ATS311 commands,
1827  * which list the radio's neighbours.
1828  */
1829 static void get_radio_neighbours(MetricomNodeTable *table, __u8 *ptr, __u8 *end)
1830 {
1831     table->num_nodes = 0;
1832     while (ptr < end && table->num_nodes < NODE_TABLE_SIZE)
1833         {
1834         MetricomNode *node = &table->node[table->num_nodes++];
1835         char *dst = node->c, *limit = dst + sizeof(*node) - 1;
1836         while (ptr < end && *ptr <= 32) ptr++;
1837         while (ptr < end && dst < limit && *ptr != 10) *dst++ = *ptr++;
1838         *dst++ = 0;
1839         while (ptr < end && ptr[-1] != 10) ptr++;
1840         }
1841     do_gettimeofday(&table->timestamp);
1842 }
1843
1844 static int get_radio_address(struct strip *strip_info, __u8 *p)
1845 {
1846     MetricomAddress addr;
1847
1848     if (string_to_radio_address(&addr, p)) return(1);
1849
1850     /* See if our radio address has changed */
1851     if (memcmp(strip_info->true_dev_addr.c, addr.c, sizeof(addr)))
1852     {
1853         MetricomAddressString addr_string;
1854         radio_address_to_string(&addr, &addr_string);
1855         printk(KERN_INFO "%s: Radio address = %s\n", strip_info->dev.name, addr_string.c);
1856         strip_info->true_dev_addr = addr;
1857         if (!strip_info->manual_dev_addr) *(MetricomAddress*)strip_info->dev.dev_addr = addr;
1858         /* Give the radio a few seconds to get its head straight, then send an arp */
1859         strip_info->gratuitous_arp = jiffies + 15 * HZ;
1860         strip_info->arp_interval = 1 * HZ;
1861     }
1862     return(0);
1863 }
1864
1865 static int verify_checksum(struct strip *strip_info)
1866 {
1867     __u8 *p = strip_info->sx_buff;
1868     __u8 *end = strip_info->sx_buff + strip_info->sx_count - 4;
1869     u_short sum = (READHEX16(end[0]) << 12) | (READHEX16(end[1]) << 8) |
1870                   (READHEX16(end[2]) <<  4) | (READHEX16(end[3]));
1871     while (p < end) sum -= *p++;
1872     if (sum == 0 && strip_info->firmware_level == StructuredMessages)
1873     {
1874         strip_info->firmware_level = ChecksummedMessages;
1875         printk(KERN_INFO "%s: Radio provides message checksums\n", strip_info->dev.name);
1876     }
1877     return(sum == 0);
1878 }
1879
1880 static void RecvErr(char *msg, struct strip *strip_info)
1881 {
1882     __u8 *ptr = strip_info->sx_buff;
1883     __u8 *end = strip_info->sx_buff + strip_info->sx_count;
1884     DumpData(msg, strip_info, ptr, end);
1885     strip_info->rx_errors++;
1886 }
1887
1888 static void RecvErr_Message(struct strip *strip_info, __u8 *sendername, const __u8 *msg, u_long len)
1889 {
1890     if (has_prefix(msg, len, "001")) /* Not in StarMode! */
1891     {
1892         RecvErr("Error Msg:", strip_info);
1893         printk(KERN_INFO "%s: Radio %s is not in StarMode\n",
1894             strip_info->dev.name, sendername);
1895     }
1896
1897     else if (has_prefix(msg, len, "002")) /* Remap handle */
1898     {
1899         /* We ignore "Remap handle" messages for now */
1900     }
1901
1902     else if (has_prefix(msg, len, "003")) /* Can't resolve name */
1903     {
1904         RecvErr("Error Msg:", strip_info);
1905         printk(KERN_INFO "%s: Destination radio name is unknown\n",
1906             strip_info->dev.name);
1907     }
1908
1909     else if (has_prefix(msg, len, "004")) /* Name too small or missing */
1910     {
1911         strip_info->watchdog_doreset = jiffies + LongTime;
1912 #if TICKLE_TIMERS
1913         {
1914         struct timeval tv;
1915         do_gettimeofday(&tv);
1916         printk(KERN_INFO "**** Got ERR_004 response         at %02d.%06d\n",
1917             tv.tv_sec % 100, tv.tv_usec);
1918         }
1919 #endif
1920         if (!strip_info->working)
1921         {
1922             strip_info->working = TRUE;
1923             printk(KERN_INFO "%s: Radio now in starmode\n", strip_info->dev.name);
1924             /*
1925              * If the radio has just entered a working state, we should do our first
1926              * probe ASAP, so that we find out our radio address etc. without delay.
1927              */
1928             strip_info->watchdog_doprobe = jiffies;
1929         }
1930         if (strip_info->firmware_level == NoStructure && sendername)
1931         {
1932             strip_info->firmware_level = StructuredMessages;
1933             strip_info->next_command   = 0; /* Try to enable checksums ASAP */
1934             printk(KERN_INFO "%s: Radio provides structured messages\n", strip_info->dev.name);
1935         }
1936         if (strip_info->firmware_level >= StructuredMessages)
1937         {
1938             /*
1939              * If this message has a valid checksum on the end, then the call to verify_checksum
1940              * will elevate the firmware_level to ChecksummedMessages for us. (The actual return
1941              * code from verify_checksum is ignored here.)
1942              */
1943             verify_checksum(strip_info);
1944             /*
1945              * If the radio has structured messages but we don't yet have all our information about it,
1946              * we should do probes without delay, until we have gathered all the information
1947              */
1948             if (!GOT_ALL_RADIO_INFO(strip_info)) strip_info->watchdog_doprobe = jiffies;
1949         }
1950     }
1951
1952     else if (has_prefix(msg, len, "005")) /* Bad count specification */
1953         RecvErr("Error Msg:", strip_info);
1954
1955     else if (has_prefix(msg, len, "006")) /* Header too big */
1956         RecvErr("Error Msg:", strip_info);
1957
1958     else if (has_prefix(msg, len, "007")) /* Body too big */
1959     {
1960         RecvErr("Error Msg:", strip_info);
1961         printk(KERN_ERR "%s: Error! Packet size too big for radio.\n",
1962             strip_info->dev.name);
1963     }
1964
1965     else if (has_prefix(msg, len, "008")) /* Bad character in name */
1966     {
1967         RecvErr("Error Msg:", strip_info);
1968         printk(KERN_ERR "%s: Radio name contains illegal character\n",
1969             strip_info->dev.name);
1970     }
1971
1972     else if (has_prefix(msg, len, "009")) /* No count or line terminator */
1973         RecvErr("Error Msg:", strip_info);
1974
1975     else if (has_prefix(msg, len, "010")) /* Invalid checksum */
1976         RecvErr("Error Msg:", strip_info);
1977
1978     else if (has_prefix(msg, len, "011")) /* Checksum didn't match */
1979         RecvErr("Error Msg:", strip_info);
1980
1981     else if (has_prefix(msg, len, "012")) /* Failed to transmit packet */
1982         RecvErr("Error Msg:", strip_info);
1983
1984     else
1985         RecvErr("Error Msg:", strip_info);
1986 }
1987
1988 static void process_AT_response(struct strip *strip_info, __u8 *ptr, __u8 *end)
1989 {
1990     u_long len;
1991     __u8 *p = ptr;
1992     while (p < end && p[-1] != 10) p++; /* Skip past first newline character */
1993     /* Now ptr points to the AT command, and p points to the text of the response. */
1994     len = p-ptr;
1995
1996 #if TICKLE_TIMERS
1997     {
1998     struct timeval tv;
1999     do_gettimeofday(&tv);
2000     printk(KERN_INFO "**** Got AT response %.7s      at %02d.%06d\n",
2001         ptr, tv.tv_sec % 100, tv.tv_usec);
2002     }
2003 #endif
2004
2005     if      (has_prefix(ptr, len, "ATS300?" )) get_radio_version(strip_info, p, end);
2006     else if (has_prefix(ptr, len, "ATS305?" )) get_radio_address(strip_info, p);
2007     else if (has_prefix(ptr, len, "ATS311?" )) get_radio_neighbours(&strip_info->poletops, p, end);
2008     else if (has_prefix(ptr, len, "ATS319=7")) verify_checksum(strip_info);
2009     else if (has_prefix(ptr, len, "ATS325?" )) get_radio_voltage(strip_info, p, end);
2010     else if (has_prefix(ptr, len, "AT~LA"   )) get_radio_neighbours(&strip_info->portables, p, end);
2011     else                                       RecvErr("Unknown AT Response:", strip_info);
2012 }
2013
2014 static void process_ACK(struct strip *strip_info, __u8 *ptr, __u8 *end)
2015 {
2016     /* Currently we don't do anything with ACKs from the radio */
2017 }
2018
2019 static void process_Info(struct strip *strip_info, __u8 *ptr, __u8 *end)
2020 {
2021     if (ptr+16 > end) RecvErr("Bad Info Msg:", strip_info);
2022 }
2023
2024 static struct net_device *get_strip_dev(struct strip *strip_info)
2025 {
2026     /* If our hardware address is *manually set* to zero, and we know our */
2027     /* real radio hardware address, try to find another strip device that has been */
2028     /* manually set to that address that we can 'transfer ownership' of this packet to  */
2029     if (strip_info->manual_dev_addr &&
2030         !memcmp(strip_info->dev.dev_addr, zero_address.c, sizeof(zero_address)) &&
2031         memcmp(&strip_info->true_dev_addr, zero_address.c, sizeof(zero_address)))
2032     {
2033         struct net_device *dev;
2034         read_lock_bh(&dev_base_lock);
2035         dev = dev_base;
2036         while (dev)
2037         {
2038             if (dev->type == strip_info->dev.type &&
2039                 !memcmp(dev->dev_addr, &strip_info->true_dev_addr, sizeof(MetricomAddress)))
2040             {
2041                 printk(KERN_INFO "%s: Transferred packet ownership to %s.\n",
2042                     strip_info->dev.name, dev->name);
2043                 read_unlock_bh(&dev_base_lock);
2044                 return(dev);
2045             }
2046             dev = dev->next;
2047         }
2048         read_unlock_bh(&dev_base_lock);
2049     }
2050     return(&strip_info->dev);
2051 }
2052
2053 /*
2054  * Send one completely decapsulated datagram to the next layer.
2055  */
2056
2057 static void deliver_packet(struct strip *strip_info, STRIP_Header *header, __u16 packetlen)
2058 {
2059     struct sk_buff *skb = dev_alloc_skb(sizeof(STRIP_Header) + packetlen);
2060     if (!skb)
2061     {
2062         printk(KERN_ERR "%s: memory squeeze, dropping packet.\n", strip_info->dev.name);
2063         strip_info->rx_dropped++;
2064     }
2065     else
2066     {
2067         memcpy(skb_put(skb, sizeof(STRIP_Header)), header, sizeof(STRIP_Header));
2068         memcpy(skb_put(skb, packetlen), strip_info->rx_buff, packetlen);
2069         skb->dev      = get_strip_dev(strip_info);
2070         skb->protocol = header->protocol;
2071         skb->mac.raw  = skb->data;
2072
2073         /* Having put a fake header on the front of the sk_buff for the */
2074         /* benefit of tools like tcpdump, skb_pull now 'consumes' that  */
2075         /* fake header before we hand the packet up to the next layer.  */
2076         skb_pull(skb, sizeof(STRIP_Header));
2077
2078         /* Finally, hand the packet up to the next layer (e.g. IP or ARP, etc.) */
2079         strip_info->rx_packets++;
2080         strip_info->rx_pps_count++;
2081 #ifdef EXT_COUNTERS
2082         strip_info->rx_bytes += packetlen;
2083 #endif
2084         netif_rx(skb);
2085     }
2086 }
2087
2088 static void process_IP_packet(struct strip *strip_info, STRIP_Header *header, __u8 *ptr, __u8 *end)
2089 {
2090     __u16 packetlen;
2091
2092     /* Decode start of the IP packet header */
2093     ptr = UnStuffData(ptr, end, strip_info->rx_buff, 4);
2094     if (!ptr)
2095     {
2096         RecvErr("IP Packet too short", strip_info);
2097         return;
2098     }
2099
2100     packetlen = ((__u16)strip_info->rx_buff[2] << 8) | strip_info->rx_buff[3];
2101
2102     if (packetlen > MAX_RECV_MTU)
2103     {
2104         printk(KERN_INFO "%s: Dropping oversized received IP packet: %d bytes\n",
2105             strip_info->dev.name, packetlen);
2106         strip_info->rx_dropped++;
2107         return;
2108     }
2109
2110     /*printk(KERN_INFO "%s: Got %d byte IP packet\n", strip_info->dev.name, packetlen);*/
2111
2112     /* Decode remainder of the IP packet */
2113     ptr = UnStuffData(ptr, end, strip_info->rx_buff+4, packetlen-4);
2114     if (!ptr)
2115     {
2116         RecvErr("IP Packet too short", strip_info);
2117         return;
2118     }
2119
2120     if (ptr < end)
2121     {
2122         RecvErr("IP Packet too long", strip_info);
2123         return;
2124     }
2125
2126     header->protocol = htons(ETH_P_IP);
2127
2128     deliver_packet(strip_info, header, packetlen);
2129 }
2130
2131 static void process_ARP_packet(struct strip *strip_info, STRIP_Header *header, __u8 *ptr, __u8 *end)
2132 {
2133     __u16 packetlen;
2134     struct arphdr *arphdr = (struct arphdr *)strip_info->rx_buff;
2135
2136     /* Decode start of the ARP packet */
2137     ptr = UnStuffData(ptr, end, strip_info->rx_buff, 8);
2138     if (!ptr)
2139     {
2140         RecvErr("ARP Packet too short", strip_info);
2141         return;
2142     }
2143
2144     packetlen = 8 + (arphdr->ar_hln + arphdr->ar_pln) * 2;
2145
2146     if (packetlen > MAX_RECV_MTU)
2147     {
2148         printk(KERN_INFO "%s: Dropping oversized received ARP packet: %d bytes\n",
2149             strip_info->dev.name, packetlen);
2150         strip_info->rx_dropped++;
2151         return;
2152     }
2153
2154     /*printk(KERN_INFO "%s: Got %d byte ARP %s\n",
2155         strip_info->dev.name, packetlen,
2156         ntohs(arphdr->ar_op) == ARPOP_REQUEST ? "request" : "reply");*/
2157
2158     /* Decode remainder of the ARP packet */
2159     ptr = UnStuffData(ptr, end, strip_info->rx_buff+8, packetlen-8);
2160     if (!ptr)
2161     {
2162         RecvErr("ARP Packet too short", strip_info);
2163         return;
2164     }
2165
2166     if (ptr < end)
2167     {
2168         RecvErr("ARP Packet too long", strip_info);
2169         return;
2170     }
2171
2172     header->protocol = htons(ETH_P_ARP);
2173
2174     deliver_packet(strip_info, header, packetlen);
2175 }
2176
2177 /*
2178  * process_text_message processes a <CR>-terminated block of data received
2179  * from the radio that doesn't begin with a '*' character. All normal
2180  * Starmode communication messages with the radio begin with a '*',
2181  * so any text that does not indicates a serial port error, a radio that
2182  * is in Hayes command mode instead of Starmode, or a radio with really
2183  * old firmware that doesn't frame its Starmode responses properly.
2184  */
2185 static void process_text_message(struct strip *strip_info)
2186 {
2187     __u8 *msg = strip_info->sx_buff;
2188     int len   = strip_info->sx_count;
2189
2190     /* Check for anything that looks like it might be our radio name */
2191     /* (This is here for backwards compatibility with old firmware)  */
2192     if (len == 9 && get_radio_address(strip_info, msg) == 0) return;
2193
2194     if (text_equal(msg, len, "OK"      )) return; /* Ignore 'OK' responses from prior commands */
2195     if (text_equal(msg, len, "ERROR"   )) return; /* Ignore 'ERROR' messages */
2196     if (has_prefix(msg, len, "ate0q1"  )) return; /* Ignore character echo back from the radio */
2197
2198     /* Catch other error messages */
2199     /* (This is here for backwards compatibility with old firmware) */
2200     if (has_prefix(msg, len, "ERR_")) { RecvErr_Message(strip_info, NULL, &msg[4], len-4); return; }
2201     
2202     RecvErr("No initial *", strip_info);
2203 }
2204
2205 /*
2206  * process_message processes a <CR>-terminated block of data received
2207  * from the radio. If the radio is not in Starmode or has old firmware,
2208  * it may be a line of text in response to an AT command. Ideally, with
2209  * a current radio that's properly in Starmode, all data received should
2210  * be properly framed and checksummed radio message blocks, containing
2211  * either a starmode packet, or a other communication from the radio
2212  * firmware, like "INF_" Info messages and &COMMAND responses.
2213  */
2214 static void process_message(struct strip *strip_info)
2215 {
2216     STRIP_Header header = { zero_address, zero_address, 0 };
2217     __u8 *ptr = strip_info->sx_buff;
2218     __u8 *end = strip_info->sx_buff + strip_info->sx_count;
2219     __u8 sendername[32], *sptr = sendername;
2220     MetricomKey key;
2221
2222     /*HexDump("Receiving", strip_info, ptr, end);*/
2223
2224     /* Check for start of address marker, and then skip over it */
2225     if (*ptr == '*') ptr++;
2226     else { process_text_message(strip_info); return; }
2227
2228     /* Copy out the return address */
2229     while (ptr < end && *ptr != '*' && sptr < ARRAY_END(sendername)-1) *sptr++ = *ptr++;
2230     *sptr = 0;                /* Null terminate the sender name */
2231
2232     /* Check for end of address marker, and skip over it */
2233     if (ptr >= end || *ptr != '*')
2234     {
2235         RecvErr("No second *", strip_info);
2236         return;
2237     }
2238     ptr++; /* Skip the second '*' */
2239
2240     /* If the sender name is "&COMMAND", ignore this 'packet'       */
2241     /* (This is here for backwards compatibility with old firmware) */
2242     if (!strcmp(sendername, "&COMMAND"))
2243     {
2244         strip_info->firmware_level = NoStructure;
2245         strip_info->next_command   = CompatibilityCommand;
2246         return;
2247     }
2248
2249     if (ptr+4 > end)
2250     {
2251         RecvErr("No proto key", strip_info);
2252         return;
2253     }
2254
2255     /* Get the protocol key out of the buffer */
2256     key.c[0] = *ptr++;
2257     key.c[1] = *ptr++;
2258     key.c[2] = *ptr++;
2259     key.c[3] = *ptr++;
2260
2261     /* If we're using checksums, verify the checksum at the end of the packet */
2262     if (strip_info->firmware_level >= ChecksummedMessages)
2263     {
2264         end -= 4;       /* Chop the last four bytes off the packet (they're the checksum) */
2265         if (ptr > end)
2266         {
2267             RecvErr("Missing Checksum", strip_info);
2268             return;
2269         }
2270         if (!verify_checksum(strip_info))
2271         {
2272             RecvErr("Bad Checksum", strip_info);
2273             return;
2274         }
2275     }
2276
2277     /*printk(KERN_INFO "%s: Got packet from \"%s\".\n", strip_info->dev.name, sendername);*/
2278
2279     /*
2280      * Fill in (pseudo) source and destination addresses in the packet.
2281      * We assume that the destination address was our address (the radio does not
2282      * tell us this). If the radio supplies a source address, then we use it.
2283      */
2284     header.dst_addr = strip_info->true_dev_addr;
2285     string_to_radio_address(&header.src_addr, sendername);
2286
2287 #ifdef EXT_COUNTERS
2288     if      (key.l == SIP0Key.l) {
2289       strip_info->rx_rbytes += (end - ptr);
2290       process_IP_packet(strip_info, &header, ptr, end);
2291     } else if (key.l == ARP0Key.l) {
2292       strip_info->rx_rbytes += (end - ptr);
2293       process_ARP_packet(strip_info, &header, ptr, end);
2294     } else if (key.l == ATR_Key.l) {
2295       strip_info->rx_ebytes += (end - ptr);
2296       process_AT_response(strip_info, ptr, end);
2297     } else if (key.l == ACK_Key.l) {
2298       strip_info->rx_ebytes += (end - ptr);
2299       process_ACK(strip_info, ptr, end);
2300     } else if (key.l == INF_Key.l) {
2301       strip_info->rx_ebytes += (end - ptr);
2302       process_Info(strip_info, ptr, end);
2303     } else if (key.l == ERR_Key.l) {
2304       strip_info->rx_ebytes += (end - ptr);
2305       RecvErr_Message(strip_info, sendername, ptr, end-ptr);
2306     } else RecvErr("Unrecognized protocol key", strip_info);
2307 #else
2308     if      (key.l == SIP0Key.l) process_IP_packet  (strip_info, &header, ptr, end);
2309     else if (key.l == ARP0Key.l) process_ARP_packet (strip_info, &header, ptr, end);
2310     else if (key.l == ATR_Key.l) process_AT_response(strip_info, ptr, end);
2311     else if (key.l == ACK_Key.l) process_ACK        (strip_info, ptr, end);
2312     else if (key.l == INF_Key.l) process_Info       (strip_info, ptr, end);
2313     else if (key.l == ERR_Key.l) RecvErr_Message    (strip_info, sendername, ptr, end-ptr);
2314     else                         RecvErr("Unrecognized protocol key", strip_info);
2315 #endif
2316 }
2317
2318 #define TTYERROR(X) ((X) == TTY_BREAK   ? "Break"            : \
2319                      (X) == TTY_FRAME   ? "Framing Error"    : \
2320                      (X) == TTY_PARITY  ? "Parity Error"     : \
2321                      (X) == TTY_OVERRUN ? "Hardware Overrun" : "Unknown Error")
2322
2323 /*
2324  * Handle the 'receiver data ready' interrupt.
2325  * This function is called by the 'tty_io' module in the kernel when
2326  * a block of STRIP data has been received, which can now be decapsulated
2327  * and sent on to some IP layer for further processing.
2328  */
2329
2330 static void
2331 strip_receive_buf(struct tty_struct *tty, const unsigned char *cp, char *fp, int count)
2332 {
2333     struct strip *strip_info = (struct strip *) tty->disc_data;
2334     const unsigned char *end = cp + count;
2335
2336     if (!strip_info || strip_info->magic != STRIP_MAGIC 
2337         || !netif_running(&strip_info->dev))
2338         return;
2339
2340     /* Argh! mtu change time! - costs us the packet part received at the change */
2341     if (strip_info->mtu != strip_info->dev.mtu)
2342         strip_changedmtu(strip_info);
2343
2344 #if 0
2345     {
2346     struct timeval tv;
2347     do_gettimeofday(&tv);
2348     printk(KERN_INFO "**** strip_receive_buf: %3d bytes at %02d.%06d\n",
2349         count, tv.tv_sec % 100, tv.tv_usec);
2350     }
2351 #endif
2352
2353 #ifdef EXT_COUNTERS
2354     strip_info->rx_sbytes += count;
2355 #endif
2356
2357     /* Read the characters out of the buffer */
2358     while (cp < end)
2359     {
2360         if (fp && *fp) printk(KERN_INFO "%s: %s on serial port\n", strip_info->dev.name, TTYERROR(*fp));
2361         if (fp && *fp++ && !strip_info->discard) /* If there's a serial error, record it */
2362         {
2363             /* If we have some characters in the buffer, discard them */
2364             strip_info->discard = strip_info->sx_count;
2365             strip_info->rx_errors++;
2366         }
2367
2368         /* Leading control characters (CR, NL, Tab, etc.) are ignored */
2369         if (strip_info->sx_count > 0 || *cp >= ' ')
2370         {
2371             if (*cp == 0x0D)                /* If end of packet, decide what to do with it */
2372             {
2373                 if (strip_info->sx_count > 3000)
2374                     printk(KERN_INFO "%s: Cut a %d byte packet (%d bytes remaining)%s\n",
2375                         strip_info->dev.name, strip_info->sx_count, end-cp-1,
2376                         strip_info->discard ? " (discarded)" : "");
2377                 if (strip_info->sx_count > strip_info->sx_size)
2378                 {
2379                     strip_info->rx_over_errors++;
2380                     printk(KERN_INFO "%s: sx_buff overflow (%d bytes total)\n",
2381                            strip_info->dev.name, strip_info->sx_count);
2382                 }
2383                 else if (strip_info->discard)
2384                     printk(KERN_INFO "%s: Discarding bad packet (%d/%d)\n",
2385                         strip_info->dev.name, strip_info->discard, strip_info->sx_count);
2386                 else process_message(strip_info);
2387                 strip_info->discard = 0;
2388                 strip_info->sx_count = 0;
2389             }
2390             else
2391             {
2392                 /* Make sure we have space in the buffer */
2393                 if (strip_info->sx_count < strip_info->sx_size)
2394                     strip_info->sx_buff[strip_info->sx_count] = *cp;
2395                 strip_info->sx_count++;
2396             }
2397         }
2398         cp++;
2399     }
2400 }
2401
2402
2403 /************************************************************************/
2404 /* General control routines                                             */
2405
2406 static int set_mac_address(struct strip *strip_info, MetricomAddress *addr)
2407 {
2408     /*
2409      * We're using a manually specified address if the address is set
2410      * to anything other than all ones. Setting the address to all ones
2411      * disables manual mode and goes back to automatic address determination
2412      * (tracking the true address that the radio has).
2413      */
2414     strip_info->manual_dev_addr = memcmp(addr->c, broadcast_address.c, sizeof(broadcast_address));
2415     if (strip_info->manual_dev_addr)
2416          *(MetricomAddress*)strip_info->dev.dev_addr = *addr;
2417     else *(MetricomAddress*)strip_info->dev.dev_addr = strip_info->true_dev_addr;
2418     return 0;
2419 }
2420
2421 static int dev_set_mac_address(struct net_device *dev, void *addr)
2422 {
2423     struct strip *strip_info = (struct strip *)(dev->priv);
2424     struct sockaddr *sa = addr;
2425     printk(KERN_INFO "%s: strip_set_dev_mac_address called\n", dev->name);
2426     set_mac_address(strip_info, (MetricomAddress *)sa->sa_data);
2427     return 0;
2428 }
2429
2430 static struct net_device_stats *strip_get_stats(struct net_device *dev)
2431 {
2432     static struct net_device_stats stats;
2433     struct strip *strip_info = (struct strip *)(dev->priv);
2434
2435     memset(&stats, 0, sizeof(struct net_device_stats));
2436
2437     stats.rx_packets     = strip_info->rx_packets;
2438     stats.tx_packets     = strip_info->tx_packets;
2439     stats.rx_dropped     = strip_info->rx_dropped;
2440     stats.tx_dropped     = strip_info->tx_dropped;
2441     stats.tx_errors      = strip_info->tx_errors;
2442     stats.rx_errors      = strip_info->rx_errors;
2443     stats.rx_over_errors = strip_info->rx_over_errors;
2444     return(&stats);
2445 }
2446
2447
2448 /************************************************************************/
2449 /* Opening and closing                                                  */
2450
2451 /*
2452  * Here's the order things happen:
2453  * When the user runs "slattach -p strip ..."
2454  *  1. The TTY module calls strip_open
2455  *  2. strip_open calls strip_alloc
2456  *  3.                  strip_alloc calls register_netdev
2457  *  4.                  register_netdev calls strip_dev_init
2458  *  5. then strip_open finishes setting up the strip_info
2459  *
2460  * When the user runs "ifconfig st<x> up address netmask ..."
2461  *  6. strip_open_low gets called
2462  *
2463  * When the user runs "ifconfig st<x> down"
2464  *  7. strip_close_low gets called
2465  *
2466  * When the user kills the slattach process
2467  *  8. strip_close gets called
2468  *  9. strip_close calls dev_close
2469  * 10. if the device is still up, then dev_close calls strip_close_low
2470  * 11. strip_close calls strip_free
2471  */
2472
2473 /* Open the low-level part of the STRIP channel. Easy! */
2474
2475 static int strip_open_low(struct net_device *dev)
2476 {
2477     struct strip *strip_info = (struct strip *)(dev->priv);
2478 #if 0
2479     struct in_device *in_dev = dev->ip_ptr;
2480 #endif
2481
2482     if (strip_info->tty == NULL)
2483         return(-ENODEV);
2484
2485     if (!allocate_buffers(strip_info))
2486         return(-ENOMEM);
2487
2488     strip_info->sx_count = 0;
2489     strip_info->tx_left  = 0;
2490
2491     strip_info->discard  = 0;
2492     strip_info->working  = FALSE;
2493     strip_info->firmware_level = NoStructure;
2494     strip_info->next_command   = CompatibilityCommand;
2495     strip_info->user_baud      = get_baud(strip_info->tty);
2496
2497 #if 0
2498     /*
2499      * Needed because address '0' is special
2500      *
2501      * --ANK Needed it or not needed, it does not matter at all.
2502      *       Make it at user level, guys.
2503      */
2504
2505     if (in_dev->ifa_list->ifa_address == 0)
2506         in_dev->ifa_list->ifa_address = ntohl(0xC0A80001);
2507 #endif
2508     printk(KERN_INFO "%s: Initializing Radio.\n", strip_info->dev.name);
2509     ResetRadio(strip_info);
2510     strip_info->idle_timer.expires = jiffies + 1*HZ;
2511     add_timer(&strip_info->idle_timer);
2512     netif_wake_queue(dev);
2513     return(0);
2514 }
2515
2516
2517 /*
2518  * Close the low-level part of the STRIP channel. Easy!
2519  */
2520
2521 static int strip_close_low(struct net_device *dev)
2522 {
2523     struct strip *strip_info = (struct strip *)(dev->priv);
2524
2525     if (strip_info->tty == NULL)
2526         return -EBUSY;
2527     strip_info->tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
2528
2529     netif_stop_queue(dev);
2530     
2531     /*
2532      * Free all STRIP frame buffers.
2533      */
2534     if (strip_info->rx_buff)
2535     {
2536         kfree(strip_info->rx_buff);
2537         strip_info->rx_buff = NULL;
2538     }
2539     if (strip_info->sx_buff)
2540     {
2541         kfree(strip_info->sx_buff);
2542         strip_info->sx_buff = NULL;
2543     }
2544     if (strip_info->tx_buff)
2545     {
2546         kfree(strip_info->tx_buff);
2547         strip_info->tx_buff = NULL;
2548     }
2549     del_timer(&strip_info->idle_timer);
2550     return 0;
2551 }
2552
2553 /*
2554  * This routine is called by DDI when the
2555  * (dynamically assigned) device is registered
2556  */
2557
2558 static int strip_dev_init(struct net_device *dev)
2559 {
2560     /*
2561      * Finish setting up the DEVICE info.
2562      */
2563
2564     dev->trans_start        = 0;
2565     dev->last_rx            = 0;
2566     dev->tx_queue_len       = 30;         /* Drop after 30 frames queued */
2567
2568     dev->flags              = 0;
2569     dev->mtu                = DEFAULT_STRIP_MTU;
2570     dev->type               = ARPHRD_METRICOM;        /* dtang */
2571     dev->hard_header_len    = sizeof(STRIP_Header);
2572     /*
2573      *  dev->priv             Already holds a pointer to our struct strip
2574      */
2575
2576     *(MetricomAddress*)&dev->broadcast = broadcast_address;
2577     dev->dev_addr[0]        = 0;
2578     dev->addr_len           = sizeof(MetricomAddress);
2579
2580     /*
2581      * Pointers to interface service routines.
2582      */
2583
2584     dev->open               = strip_open_low;
2585     dev->stop               = strip_close_low;
2586     dev->hard_start_xmit    = strip_xmit;
2587     dev->hard_header        = strip_header;
2588     dev->rebuild_header     = strip_rebuild_header;
2589     dev->set_mac_address    = dev_set_mac_address;
2590     dev->get_stats          = strip_get_stats;
2591     return 0;
2592 }
2593
2594 /*
2595  * Free a STRIP channel.
2596  */
2597
2598 static void strip_free(struct strip *strip_info)
2599 {
2600     *(strip_info->referrer) = strip_info->next;
2601     if (strip_info->next)
2602         strip_info->next->referrer = strip_info->referrer;
2603     strip_info->magic = 0;
2604     kfree(strip_info);
2605 }
2606
2607 /*
2608  * Allocate a new free STRIP channel
2609  */
2610
2611 static struct strip *strip_alloc(void)
2612 {
2613     int channel_id = 0;
2614     struct strip **s = &struct_strip_list;
2615     struct strip *strip_info = (struct strip *)
2616         kmalloc(sizeof(struct strip), GFP_KERNEL);
2617
2618     if (!strip_info)
2619         return(NULL);        /* If no more memory, return */
2620
2621     /*
2622      * Clear the allocated memory
2623      */
2624
2625     memset(strip_info, 0, sizeof(struct strip));
2626
2627     /*
2628      * Search the list to find where to put our new entry
2629      * (and in the process decide what channel number it is
2630      * going to be)
2631      */
2632
2633     while (*s && (*s)->dev.base_addr == channel_id)
2634     {
2635         channel_id++;
2636         s = &(*s)->next;
2637     }
2638
2639     /*
2640      * Fill in the link pointers
2641      */
2642
2643     strip_info->next = *s;
2644     if (*s)
2645         (*s)->referrer = &strip_info->next;
2646     strip_info->referrer = s;
2647     *s = strip_info;
2648
2649     strip_info->magic = STRIP_MAGIC;
2650     strip_info->tty   = NULL;
2651
2652     strip_info->gratuitous_arp   = jiffies + LongTime;
2653     strip_info->arp_interval     = 0;
2654     init_timer(&strip_info->idle_timer);
2655     strip_info->idle_timer.data     = (long)&strip_info->dev;
2656     strip_info->idle_timer.function = strip_IdleTask;
2657
2658     /* Note: strip_info->if_name is currently 8 characters long */
2659     sprintf(strip_info->dev.name, "st%d", channel_id);
2660     strip_info->dev.base_addr    = channel_id;
2661     strip_info->dev.priv         = (void*)strip_info;
2662     strip_info->dev.next         = NULL;
2663     strip_info->dev.init         = strip_dev_init;
2664
2665     return(strip_info);
2666 }
2667
2668 /*
2669  * Open the high-level part of the STRIP channel.
2670  * This function is called by the TTY module when the
2671  * STRIP line discipline is called for.  Because we are
2672  * sure the tty line exists, we only have to link it to
2673  * a free STRIP channel...
2674  */
2675
2676 static int strip_open(struct tty_struct *tty)
2677 {
2678     struct strip *strip_info = (struct strip *) tty->disc_data;
2679
2680     /*
2681      * First make sure we're not already connected.
2682      */
2683
2684     if (strip_info && strip_info->magic == STRIP_MAGIC)
2685         return -EEXIST;
2686
2687     /*
2688      * OK.  Find a free STRIP channel to use.
2689      */
2690     if ((strip_info = strip_alloc()) == NULL)
2691         return -ENFILE;
2692
2693     /*
2694      * Register our newly created device so it can be ifconfig'd
2695      * strip_dev_init() will be called as a side-effect
2696      */
2697
2698     if (register_netdev(&strip_info->dev) != 0)
2699     {
2700         printk(KERN_ERR "strip: register_netdev() failed.\n");
2701         strip_free(strip_info);
2702         return -ENFILE;
2703     }
2704
2705     strip_info->tty = tty;
2706     tty->disc_data = strip_info;
2707     if (tty->driver.flush_buffer)
2708         tty->driver.flush_buffer(tty);
2709     if (tty->ldisc.flush_buffer)
2710         tty->ldisc.flush_buffer(tty);
2711
2712     /*
2713      * Restore default settings
2714      */
2715
2716     strip_info->dev.type = ARPHRD_METRICOM;    /* dtang */
2717
2718     /*
2719      * Set tty options
2720      */
2721
2722     tty->termios->c_iflag |= IGNBRK |IGNPAR;/* Ignore breaks and parity errors. */
2723     tty->termios->c_cflag |= CLOCAL;    /* Ignore modem control signals. */
2724     tty->termios->c_cflag &= ~HUPCL;    /* Don't close on hup */
2725
2726     MOD_INC_USE_COUNT;
2727
2728     printk(KERN_INFO "STRIP: device \"%s\" activated\n", strip_info->dev.name);
2729
2730     /*
2731      * Done.  We have linked the TTY line to a channel.
2732      */
2733     return(strip_info->dev.base_addr);
2734 }
2735
2736 /*
2737  * Close down a STRIP channel.
2738  * This means flushing out any pending queues, and then restoring the
2739  * TTY line discipline to what it was before it got hooked to STRIP
2740  * (which usually is TTY again).
2741  */
2742
2743 static void strip_close(struct tty_struct *tty)
2744 {
2745     struct strip *strip_info = (struct strip *) tty->disc_data;
2746
2747     /*
2748      * First make sure we're connected.
2749      */
2750
2751     if (!strip_info || strip_info->magic != STRIP_MAGIC)
2752         return;
2753
2754     unregister_netdev(&strip_info->dev);
2755
2756     tty->disc_data = 0;
2757     strip_info->tty = NULL;
2758     printk(KERN_INFO "STRIP: device \"%s\" closed down\n", strip_info->dev.name);
2759     strip_free(strip_info);
2760     tty->disc_data = NULL;
2761     MOD_DEC_USE_COUNT;
2762 }
2763
2764
2765 /************************************************************************/
2766 /* Perform I/O control calls on an active STRIP channel.                */
2767
2768 static int strip_ioctl(struct tty_struct *tty, struct file *file,
2769     unsigned int cmd, unsigned long arg)
2770 {
2771     struct strip *strip_info = (struct strip *) tty->disc_data;
2772
2773     /*
2774      * First make sure we're connected.
2775      */
2776
2777     if (!strip_info || strip_info->magic != STRIP_MAGIC)
2778         return -EINVAL;
2779
2780     switch(cmd)
2781     {
2782         case SIOCGIFNAME:
2783             return copy_to_user((void*)arg, strip_info->dev.name,
2784                                 strlen(strip_info->dev.name) + 1) ? 
2785                 -EFAULT : 0;
2786             break;
2787         case SIOCSIFHWADDR:
2788             {
2789             MetricomAddress addr;
2790             printk(KERN_INFO "%s: SIOCSIFHWADDR\n", strip_info->dev.name);
2791             return copy_from_user(&addr, (void*)arg, sizeof(MetricomAddress)) ?
2792                 -EFAULT : set_mac_address(strip_info, &addr);
2793             break;
2794             }
2795         /*
2796          * Allow stty to read, but not set, the serial port
2797          */
2798
2799         case TCGETS:
2800         case TCGETA:
2801             return n_tty_ioctl(tty, (struct file *) file, cmd,
2802                 (unsigned long) arg);
2803             break;
2804         default:
2805             return -ENOIOCTLCMD;
2806             break;
2807     }
2808 }
2809
2810
2811 /************************************************************************/
2812 /* Initialization                                                       */
2813
2814 static struct tty_ldisc strip_ldisc = {
2815         magic:          TTY_LDISC_MAGIC,
2816         name:           "strip",
2817         open:           strip_open,
2818         close:          strip_close,
2819         ioctl:          strip_ioctl,
2820         receive_buf:    strip_receive_buf,
2821         receive_room:   strip_receive_room,
2822         write_wakeup:   strip_write_some_more,
2823 };
2824
2825 /*
2826  * Initialize the STRIP driver.
2827  * This routine is called at boot time, to bootstrap the multi-channel
2828  * STRIP driver
2829  */
2830
2831 static char signon[] __initdata = KERN_INFO "STRIP: Version %s (unlimited channels)\n";
2832
2833 static int __init strip_init_driver(void)
2834 {
2835     int status;
2836
2837     printk(signon, StripVersion);
2838
2839     /*
2840      * Fill in our line protocol discipline, and register it
2841      */
2842     if ((status = tty_register_ldisc(N_STRIP, &strip_ldisc)))
2843         printk(KERN_ERR "STRIP: can't register line discipline (err = %d)\n", status);
2844
2845     /*
2846      * Register the status file with /proc
2847      */
2848     proc_net_create("strip", S_IFREG | S_IRUGO, get_status_info);
2849
2850     return status;
2851 }
2852 module_init(strip_init_driver);
2853
2854 static const char signoff[] __exitdata = KERN_INFO "STRIP: Module Unloaded\n";
2855
2856 static void __exit strip_exit_driver(void)
2857 {
2858     int i;
2859     while (struct_strip_list)
2860         strip_free(struct_strip_list);
2861
2862     /* Unregister with the /proc/net file here. */
2863     proc_net_remove("strip");
2864
2865     if ((i = tty_register_ldisc(N_STRIP, NULL)))
2866         printk(KERN_ERR "STRIP: can't unregister line discipline (err = %d)\n", i);
2867
2868     printk(signoff);
2869 }
2870 module_exit(strip_exit_driver);
2871
2872 MODULE_AUTHOR("Stuart Cheshire <cheshire@cs.stanford.edu>");
2873 MODULE_DESCRIPTION("Starmode Radio IP (STRIP) Device Driver");
2874 MODULE_LICENSE("Dual BSD/GPL");
2875
2876 MODULE_SUPPORTED_DEVICE("Starmode Radio IP (STRIP) modem");
2877