OpenCores
URL https://opencores.org/ocsvn/or1k/or1k/trunk

Subversion Repositories or1k

[/] [or1k/] [trunk/] [rc203soc/] [sw/] [uClinux/] [drivers/] [net/] [strip.c] - Blame information for rev 1765

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.