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