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