ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / net / wan / farsync.c
1 /*
2  *      FarSync X21 driver for Linux (generic HDLC version)
3  *
4  *      Actually sync driver for X.21, V.35 and V.24 on FarSync T-series cards
5  *
6  *      Copyright (C) 2001 FarSite Communications Ltd.
7  *      www.farsite.co.uk
8  *
9  *      This program is free software; you can redistribute it and/or
10  *      modify it under the terms of the GNU General Public License
11  *      as published by the Free Software Foundation; either version
12  *      2 of the License, or (at your option) any later version.
13  *
14  *      Author: R.J.Dunlop      <bob.dunlop@farsite.co.uk>
15  */
16
17 #include <linux/module.h>
18 #include <linux/kernel.h>
19 #include <linux/pci.h>
20 #include <linux/ioport.h>
21 #include <linux/init.h>
22 #include <asm/uaccess.h>
23 #include <linux/if.h>
24 #include <linux/hdlc.h>
25
26 #include "farsync.h"
27
28
29 /*
30  *      Module info
31  */
32 MODULE_AUTHOR("R.J.Dunlop <bob.dunlop@farsite.co.uk>");
33 MODULE_DESCRIPTION("FarSync T-Series X21 driver. FarSite Communications Ltd.");
34 MODULE_LICENSE("GPL");
35
36 /*      Driver configuration and global parameters
37  *      ==========================================
38  */
39
40 /*      Number of ports (per card) supported
41  */
42 #define FST_MAX_PORTS           4
43
44
45 /*      PCI vendor and device IDs
46  */
47 #define FSC_PCI_VENDOR_ID       0x1619  /* FarSite Communications Ltd */
48 #define T2P_PCI_DEVICE_ID       0x0400  /* T2P X21 2 port card */
49 #define T4P_PCI_DEVICE_ID       0x0440  /* T4P X21 4 port card */
50
51
52 /*      Default parameters for the link
53  */
54 #define FST_TX_QUEUE_LEN        100     /* At 8Mbps a longer queue length is
55                                          * useful, the syncppp module forces
56                                          * this down assuming a slower line I
57                                          * guess.
58                                          */
59 #define FST_MAX_MTU             8000    /* Huge but possible */
60 #define FST_DEF_MTU             1500    /* Common sane value */
61
62 #define FST_TX_TIMEOUT          (2*HZ)
63
64
65 #ifdef ARPHRD_RAWHDLC
66 #define ARPHRD_MYTYPE   ARPHRD_RAWHDLC  /* Raw frames */
67 #else
68 #define ARPHRD_MYTYPE   ARPHRD_HDLC     /* Cisco-HDLC (keepalives etc) */
69 #endif
70
71
72 /*      Card shared memory layout
73  *      =========================
74  */
75 #pragma pack(1)
76
77 /*      This information is derived in part from the FarSite FarSync Smc.h
78  *      file. Unfortunately various name clashes and the non-portability of the
79  *      bit field declarations in that file have meant that I have chosen to
80  *      recreate the information here.
81  *
82  *      The SMC (Shared Memory Configuration) has a version number that is
83  *      incremented every time there is a significant change. This number can
84  *      be used to check that we have not got out of step with the firmware
85  *      contained in the .CDE files.
86  */
87 #define SMC_VERSION 11
88
89 #define FST_MEMSIZE 0x100000    /* Size of card memory (1Mb) */
90
91 #define SMC_BASE 0x00002000L    /* Base offset of the shared memory window main
92                                  * configuration structure */
93 #define BFM_BASE 0x00010000L    /* Base offset of the shared memory window DMA
94                                  * buffers */
95
96 #define LEN_TX_BUFFER 8192      /* Size of packet buffers */
97 #define LEN_RX_BUFFER 8192
98
99 #define LEN_SMALL_TX_BUFFER 256 /* Size of obsolete buffs used for DOS diags */
100 #define LEN_SMALL_RX_BUFFER 256
101
102 #define NUM_TX_BUFFER 2         /* Must be power of 2. Fixed by firmware */
103 #define NUM_RX_BUFFER 8
104
105 /* Interrupt retry time in milliseconds */
106 #define INT_RETRY_TIME 2
107
108
109 /*      The Am186CH/CC processors support a SmartDMA mode using circular pools
110  *      of buffer descriptors. The structure is almost identical to that used
111  *      in the LANCE Ethernet controllers. Details available as PDF from the
112  *      AMD web site: http://www.amd.com/products/epd/processors/\
113  *                    2.16bitcont/3.am186cxfa/a21914/21914.pdf
114  */
115 struct txdesc {                 /* Transmit descriptor */
116         volatile u16 ladr;      /* Low order address of packet. This is a
117                                  * linear address in the Am186 memory space
118                                  */
119         volatile u8  hadr;      /* High order address. Low 4 bits only, high 4
120                                  * bits must be zero
121                                  */
122         volatile u8  bits;      /* Status and config */
123         volatile u16 bcnt;      /* 2s complement of packet size in low 15 bits.
124                                  * Transmit terminal count interrupt enable in
125                                  * top bit.
126                                  */
127                  u16 unused;    /* Not used in Tx */
128 };
129
130 struct rxdesc {                 /* Receive descriptor */
131         volatile u16 ladr;      /* Low order address of packet */
132         volatile u8  hadr;      /* High order address */
133         volatile u8  bits;      /* Status and config */
134         volatile u16 bcnt;      /* 2s complement of buffer size in low 15 bits.
135                                  * Receive terminal count interrupt enable in
136                                  * top bit.
137                                  */
138         volatile u16 mcnt;      /* Message byte count (15 bits) */
139 };
140
141 /* Convert a length into the 15 bit 2's complement */
142 /* #define cnv_bcnt(len)   (( ~(len) + 1 ) & 0x7FFF ) */
143 /* Since we need to set the high bit to enable the completion interrupt this
144  * can be made a lot simpler
145  */
146 #define cnv_bcnt(len)   (-(len))
147
148 /* Status and config bits for the above */
149 #define DMA_OWN         0x80            /* SmartDMA owns the descriptor */
150 #define TX_STP          0x02            /* Tx: start of packet */
151 #define TX_ENP          0x01            /* Tx: end of packet */
152 #define RX_ERR          0x40            /* Rx: error (OR of next 4 bits) */
153 #define RX_FRAM         0x20            /* Rx: framing error */
154 #define RX_OFLO         0x10            /* Rx: overflow error */
155 #define RX_CRC          0x08            /* Rx: CRC error */
156 #define RX_HBUF         0x04            /* Rx: buffer error */
157 #define RX_STP          0x02            /* Rx: start of packet */
158 #define RX_ENP          0x01            /* Rx: end of packet */
159
160
161 /* Interrupts from the card are caused by various events and these are presented
162  * in a circular buffer as several events may be processed on one physical int
163  */
164 #define MAX_CIRBUFF     32
165
166 struct cirbuff {
167         u8 rdindex;             /* read, then increment and wrap */
168         u8 wrindex;             /* write, then increment and wrap */
169         u8 evntbuff[MAX_CIRBUFF];
170 };
171
172 /* Interrupt event codes.
173  * Where appropriate the two low order bits indicate the port number
174  */
175 #define CTLA_CHG        0x18    /* Control signal changed */
176 #define CTLB_CHG        0x19
177 #define CTLC_CHG        0x1A
178 #define CTLD_CHG        0x1B
179
180 #define INIT_CPLT       0x20    /* Initialisation complete */
181 #define INIT_FAIL       0x21    /* Initialisation failed */
182
183 #define ABTA_SENT       0x24    /* Abort sent */
184 #define ABTB_SENT       0x25
185 #define ABTC_SENT       0x26
186 #define ABTD_SENT       0x27
187
188 #define TXA_UNDF        0x28    /* Transmission underflow */
189 #define TXB_UNDF        0x29
190 #define TXC_UNDF        0x2A
191 #define TXD_UNDF        0x2B
192
193
194 /* Port physical configuration. See farsync.h for field values */
195 struct port_cfg {
196         u16  lineInterface;     /* Physical interface type */
197         u8   x25op;             /* Unused at present */
198         u8   internalClock;     /* 1 => internal clock, 0 => external */
199         u32  lineSpeed;         /* Speed in bps */
200 };
201
202 /* Finally sling all the above together into the shared memory structure.
203  * Sorry it's a hodge podge of arrays, structures and unused bits, it's been
204  * evolving under NT for some time so I guess we're stuck with it.
205  * The structure starts at offset SMC_BASE.
206  * See farsync.h for some field values.
207  */
208 struct fst_shared {
209                                 /* DMA descriptor rings */
210         struct rxdesc rxDescrRing[FST_MAX_PORTS][NUM_RX_BUFFER];
211         struct txdesc txDescrRing[FST_MAX_PORTS][NUM_TX_BUFFER];
212
213                                 /* Obsolete small buffers */
214         u8  smallRxBuffer[FST_MAX_PORTS][NUM_RX_BUFFER][LEN_SMALL_RX_BUFFER];
215         u8  smallTxBuffer[FST_MAX_PORTS][NUM_TX_BUFFER][LEN_SMALL_TX_BUFFER];
216
217         u8  taskStatus;         /* 0x00 => initialising, 0x01 => running,
218                                  * 0xFF => halted
219                                  */
220
221         u8  interruptHandshake; /* Set to 0x01 by adapter to signal interrupt,
222                                  * set to 0xEE by host to acknowledge interrupt
223                                  */
224
225         u16 smcVersion;         /* Must match SMC_VERSION */
226
227         u32 smcFirmwareVersion; /* 0xIIVVRRBB where II = product ID, VV = major
228                                  * version, RR = revision and BB = build
229                                  */
230
231         u16 txa_done;           /* Obsolete completion flags */
232         u16 rxa_done;
233         u16 txb_done;
234         u16 rxb_done;
235         u16 txc_done;
236         u16 rxc_done;
237         u16 txd_done;
238         u16 rxd_done;
239
240         u16 mailbox[4];         /* Diagnostics mailbox. Not used */
241
242         struct cirbuff interruptEvent;  /* interrupt causes */
243
244         u32 v24IpSts[FST_MAX_PORTS];    /* V.24 control input status */
245         u32 v24OpSts[FST_MAX_PORTS];    /* V.24 control output status */
246
247         struct port_cfg portConfig[FST_MAX_PORTS];
248
249         u16 clockStatus[FST_MAX_PORTS]; /* lsb: 0=> present, 1=> absent */
250
251         u16 cableStatus;                /* lsb: 0=> present, 1=> absent */
252
253         u16 txDescrIndex[FST_MAX_PORTS]; /* transmit descriptor ring index */
254         u16 rxDescrIndex[FST_MAX_PORTS]; /* receive descriptor ring index */
255
256         u16 portMailbox[FST_MAX_PORTS][2];      /* command, modifier */
257         u16 cardMailbox[4];                     /* Not used */
258
259                                 /* Number of times that card thinks the host has
260                                  * missed an interrupt by not acknowledging
261                                  * within 2mS (I guess NT has problems)
262                                  */
263         u32 interruptRetryCount;
264
265                                 /* Driver private data used as an ID. We'll not
266                                  * use this on Linux I'd rather keep such things
267                                  * in main memory rather than on the PCI bus
268                                  */
269         u32 portHandle[FST_MAX_PORTS];
270
271                                 /* Count of Tx underflows for stats */
272         u32 transmitBufferUnderflow[FST_MAX_PORTS];
273
274                                 /* Debounced V.24 control input status */
275         u32 v24DebouncedSts[FST_MAX_PORTS];
276
277                                 /* Adapter debounce timers. Don't touch */
278         u32 ctsTimer[FST_MAX_PORTS];
279         u32 ctsTimerRun[FST_MAX_PORTS];
280         u32 dcdTimer[FST_MAX_PORTS];
281         u32 dcdTimerRun[FST_MAX_PORTS];
282
283         u32 numberOfPorts;      /* Number of ports detected at startup */
284
285         u16 _reserved[64];
286
287         u16 cardMode;           /* Bit-mask to enable features:
288                                  * Bit 0: 1 enables LED identify mode
289                                  */
290
291         u16 portScheduleOffset;
292
293         u32 endOfSmcSignature;  /* endOfSmcSignature MUST be the last member of
294                                  * the structure and marks the end of the shared
295                                  * memory. Adapter code initializes its value as
296                                  * END_SIG.
297                                  */
298 };
299
300 /* endOfSmcSignature value */
301 #define END_SIG                 0x12345678
302
303 /* Mailbox values. (portMailbox) */
304 #define NOP             0       /* No operation */
305 #define ACK             1       /* Positive acknowledgement to PC driver */
306 #define NAK             2       /* Negative acknowledgement to PC driver */
307 #define STARTPORT       3       /* Start an HDLC port */
308 #define STOPPORT        4       /* Stop an HDLC port */
309 #define ABORTTX         5       /* Abort the transmitter for a port */
310 #define SETV24O         6       /* Set V24 outputs */
311
312
313 /* Larger buffers are positioned in memory at offset BFM_BASE */
314 struct buf_window {
315         u8 txBuffer[FST_MAX_PORTS][NUM_TX_BUFFER][LEN_TX_BUFFER];
316         u8 rxBuffer[FST_MAX_PORTS][NUM_RX_BUFFER][LEN_RX_BUFFER];
317 };
318
319 /* Calculate offset of a buffer object within the shared memory window */
320 #define BUF_OFFSET(X)   offsetof(struct buf_window, X)
321
322 #pragma pack()
323
324
325 /*      Device driver private information
326  *      =================================
327  */
328 /*      Per port (line or channel) information
329  */
330 struct fst_port_info {
331         struct net_device      *dev;
332         struct fst_card_info   *card;   /* Card we're associated with */
333         int                     index;  /* Port index on the card */
334         int                     hwif;   /* Line hardware (lineInterface copy) */
335         int                     run;    /* Port is running */
336         int                     rxpos;  /* Next Rx buffer to use */
337         int                     txpos;  /* Next Tx buffer to use */
338         int                     txipos; /* Next Tx buffer to check for free */
339         int                     txcnt;  /* Count of Tx buffers in use */
340 };
341
342 /*      Per card information
343  */
344 struct fst_card_info {
345         char          *mem;             /* Card memory mapped to kernel space */
346         char          *ctlmem;          /* Control memory for PCI cards */
347         unsigned int   phys_mem;        /* Physical memory window address */
348         unsigned int   phys_ctlmem;     /* Physical control memory address */
349         unsigned int   irq;             /* Interrupt request line number */
350         unsigned int   nports;          /* Number of serial ports */
351         unsigned int   type;            /* Type index of card */
352         unsigned int   state;           /* State of card */
353         spinlock_t     card_lock;       /* Lock for SMP access */
354         unsigned short pci_conf;        /* PCI card config in I/O space */
355                                         /* Per port info */
356         struct fst_port_info ports[ FST_MAX_PORTS ];
357 };
358
359 /* Convert an HDLC device pointer into a port info pointer and similar */
360 #define dev_to_port(D)  (dev_to_hdlc(D)->priv)
361 #define port_to_dev(P)  ((P)->dev)
362
363
364 /*
365  *      Shared memory window access macros
366  *
367  *      We have a nice memory based structure above, which could be directly
368  *      mapped on i386 but might not work on other architectures unless we use
369  *      the readb,w,l and writeb,w,l macros. Unfortunately these macros take
370  *      physical offsets so we have to convert. The only saving grace is that
371  *      this should all collapse back to a simple indirection eventually.
372  */
373 #define WIN_OFFSET(X)   ((long)&(((struct fst_shared *)SMC_BASE)->X))
374
375 #define FST_RDB(C,E)    readb ((C)->mem + WIN_OFFSET(E))
376 #define FST_RDW(C,E)    readw ((C)->mem + WIN_OFFSET(E))
377 #define FST_RDL(C,E)    readl ((C)->mem + WIN_OFFSET(E))
378
379 #define FST_WRB(C,E,B)  writeb ((B), (C)->mem + WIN_OFFSET(E))
380 #define FST_WRW(C,E,W)  writew ((W), (C)->mem + WIN_OFFSET(E))
381 #define FST_WRL(C,E,L)  writel ((L), (C)->mem + WIN_OFFSET(E))
382
383
384 /*
385  *      Debug support
386  */
387 #if FST_DEBUG
388
389 static int fst_debug_mask = { FST_DEBUG };
390
391 /* Most common debug activity is to print something if the corresponding bit
392  * is set in the debug mask. Note: this uses a non-ANSI extension in GCC to
393  * support variable numbers of macro parameters. The inverted if prevents us
394  * eating someone else's else clause.
395  */
396 #define dbg(F,fmt,A...) if ( ! ( fst_debug_mask & (F))) \
397                                 ; \
398                         else \
399                                 printk ( KERN_DEBUG FST_NAME ": " fmt, ## A )
400
401 #else
402 # define dbg(X...)      /* NOP */
403 #endif
404
405
406 /*      Printing short cuts
407  */
408 #define printk_err(fmt,A...)    printk ( KERN_ERR     FST_NAME ": " fmt, ## A )
409 #define printk_warn(fmt,A...)   printk ( KERN_WARNING FST_NAME ": " fmt, ## A )
410 #define printk_info(fmt,A...)   printk ( KERN_INFO    FST_NAME ": " fmt, ## A )
411
412
413 /*
414  *      PCI ID lookup table
415  */
416 static struct pci_device_id fst_pci_dev_id[] = {
417         { FSC_PCI_VENDOR_ID, T2P_PCI_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0,
418                                         FST_TYPE_T2P },
419         { FSC_PCI_VENDOR_ID, T4P_PCI_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0,
420                                         FST_TYPE_T4P },
421         { 0, }                          /* End */
422 };
423
424 MODULE_DEVICE_TABLE ( pci, fst_pci_dev_id );
425
426
427 /*      Card control functions
428  *      ======================
429  */
430 /*      Place the processor in reset state
431  *
432  * Used to be a simple write to card control space but a glitch in the latest
433  * AMD Am186CH processor means that we now have to do it by asserting and de-
434  * asserting the PLX chip PCI Adapter Software Reset. Bit 30 in CNTRL register
435  * at offset 0x50.
436  */
437 static inline void
438 fst_cpureset ( struct fst_card_info *card )
439 {
440         unsigned int regval;
441
442         regval = inl ( card->pci_conf + 0x50 );
443
444         outl ( regval |  0x40000000, card->pci_conf + 0x50 );
445         outl ( regval & ~0x40000000, card->pci_conf + 0x50 );
446 }
447
448 /*      Release the processor from reset
449  */
450 static inline void
451 fst_cpurelease ( struct fst_card_info *card )
452 {
453         (void) readb ( card->ctlmem );
454 }
455
456 /*      Clear the cards interrupt flag
457  */
458 static inline void
459 fst_clear_intr ( struct fst_card_info *card )
460 {
461         /* Poke the appropriate PLX chip register (same as enabling interrupts)
462          */
463         outw ( 0x0543, card->pci_conf + 0x4C );
464 }
465
466 /*      Disable card interrupts
467  */
468 static inline void
469 fst_disable_intr ( struct fst_card_info *card )
470 {
471         outw ( 0x0000, card->pci_conf + 0x4C );
472 }
473
474
475 /*      Issue a Mailbox command for a port.
476  *      Note we issue them on a fire and forget basis, not expecting to see an
477  *      error and not waiting for completion.
478  */
479 static void
480 fst_issue_cmd ( struct fst_port_info *port, unsigned short cmd )
481 {
482         struct fst_card_info *card;
483         unsigned short mbval;
484         unsigned long flags;
485         int safety;
486
487         card = port->card;
488         spin_lock_irqsave ( &card->card_lock, flags );
489         mbval = FST_RDW ( card, portMailbox[port->index][0]);
490
491         safety = 0;
492         /* Wait for any previous command to complete */
493         while ( mbval > NAK )
494         {
495                 spin_unlock_irqrestore ( &card->card_lock, flags );
496                 schedule_timeout ( 1 );
497                 spin_lock_irqsave ( &card->card_lock, flags );
498
499                 if ( ++safety > 1000 )
500                 {
501                         printk_err ("Mailbox safety timeout\n");
502                         break;
503                 }
504
505                 mbval = FST_RDW ( card, portMailbox[port->index][0]);
506         }
507         if ( safety > 0 )
508         {
509                 dbg ( DBG_CMD,"Mailbox clear after %d jiffies\n", safety );
510         }
511         if ( mbval == NAK )
512         {
513                 dbg ( DBG_CMD,"issue_cmd: previous command was NAK'd\n");
514         }
515
516         FST_WRW ( card, portMailbox[port->index][0], cmd );
517
518         if ( cmd == ABORTTX || cmd == STARTPORT )
519         {
520                 port->txpos  = 0;
521                 port->txipos = 0;
522                 port->txcnt  = 0;
523         }
524
525         spin_unlock_irqrestore ( &card->card_lock, flags );
526 }
527
528
529 /*      Port output signals control
530  */
531 static inline void
532 fst_op_raise ( struct fst_port_info *port, unsigned int outputs )
533 {
534         outputs |= FST_RDL ( port->card, v24OpSts[port->index]);
535         FST_WRL ( port->card, v24OpSts[port->index], outputs );
536
537         if ( port->run )
538                 fst_issue_cmd ( port, SETV24O );
539 }
540
541 static inline void
542 fst_op_lower ( struct fst_port_info *port, unsigned int outputs )
543 {
544         outputs = ~outputs & FST_RDL ( port->card, v24OpSts[port->index]);
545         FST_WRL ( port->card, v24OpSts[port->index], outputs );
546
547         if ( port->run )
548                 fst_issue_cmd ( port, SETV24O );
549 }
550
551
552 /*
553  *      Setup port Rx buffers
554  */
555 static void
556 fst_rx_config ( struct fst_port_info *port )
557 {
558         int i;
559         int pi;
560         unsigned int offset;
561         unsigned long flags;
562         struct fst_card_info *card;
563
564         pi   = port->index;
565         card = port->card;
566         spin_lock_irqsave ( &card->card_lock, flags );
567         for ( i = 0 ; i < NUM_RX_BUFFER ; i++ )
568         {
569                 offset = BUF_OFFSET ( rxBuffer[pi][i][0]);
570
571                 FST_WRW ( card, rxDescrRing[pi][i].ladr, (u16) offset );
572                 FST_WRB ( card, rxDescrRing[pi][i].hadr, (u8)( offset >> 16 ));
573                 FST_WRW ( card, rxDescrRing[pi][i].bcnt,
574                                         cnv_bcnt ( LEN_RX_BUFFER ));
575                 FST_WRW ( card, rxDescrRing[pi][i].mcnt, 0 );
576                 FST_WRB ( card, rxDescrRing[pi][i].bits, DMA_OWN );
577         }
578         port->rxpos  = 0;
579         spin_unlock_irqrestore ( &card->card_lock, flags );
580 }
581
582
583 /*
584  *      Setup port Tx buffers
585  */
586 static void
587 fst_tx_config ( struct fst_port_info *port )
588 {
589         int i;
590         int pi;
591         unsigned int offset;
592         unsigned long flags;
593         struct fst_card_info *card;
594
595         pi   = port->index;
596         card = port->card;
597         spin_lock_irqsave ( &card->card_lock, flags );
598         for ( i = 0 ; i < NUM_TX_BUFFER ; i++ )
599         {
600                 offset = BUF_OFFSET ( txBuffer[pi][i][0]);
601
602                 FST_WRW ( card, txDescrRing[pi][i].ladr, (u16) offset );
603                 FST_WRB ( card, txDescrRing[pi][i].hadr, (u8)( offset >> 16 ));
604                 FST_WRW ( card, txDescrRing[pi][i].bcnt, 0 );
605                 FST_WRB ( card, txDescrRing[pi][i].bits, 0 );
606         }
607         port->txpos  = 0;
608         port->txipos = 0;
609         port->txcnt  = 0;
610         spin_unlock_irqrestore ( &card->card_lock, flags );
611 }
612
613
614 /*      Control signal change interrupt event
615  */
616 static irqreturn_t
617 fst_intr_ctlchg ( struct fst_card_info *card, struct fst_port_info *port )
618 {
619         int signals;
620
621         signals = FST_RDL ( card, v24DebouncedSts[port->index]);
622
623         if ( signals & (( port->hwif == X21 ) ? IPSTS_INDICATE : IPSTS_DCD ))
624         {
625                 if ( ! netif_carrier_ok ( port_to_dev ( port )))
626                 {
627                         dbg ( DBG_INTR,"DCD active\n");
628                         netif_carrier_on ( port_to_dev ( port ));
629                 }
630         }
631         else
632         {
633                 if ( netif_carrier_ok ( port_to_dev ( port )))
634                 {
635                         dbg ( DBG_INTR,"DCD lost\n");
636                         netif_carrier_off ( port_to_dev ( port ));
637                 }
638         }
639         return IRQ_HANDLED;
640 }
641
642
643 /*      Rx complete interrupt
644  */
645 static void
646 fst_intr_rx ( struct fst_card_info *card, struct fst_port_info *port )
647 {
648         unsigned char dmabits;
649         int pi;
650         int rxp;
651         unsigned short len;
652         struct sk_buff *skb;
653         struct net_device *dev = port_to_dev(port);
654         struct net_device_stats *stats = hdlc_stats(dev);
655         int i;
656
657
658         /* Check we have a buffer to process */
659         pi  = port->index;
660         rxp = port->rxpos;
661         dmabits = FST_RDB ( card, rxDescrRing[pi][rxp].bits );
662         if ( dmabits & DMA_OWN )
663         {
664                 dbg ( DBG_RX | DBG_INTR,"intr_rx: No buffer port %d pos %d\n",
665                                         pi, rxp );
666                 return;
667         }
668
669         /* Get buffer length */
670         len = FST_RDW ( card, rxDescrRing[pi][rxp].mcnt );
671         /* Discard the CRC */
672         len -= 2;
673
674         /* Check buffer length and for other errors. We insist on one packet
675          * in one buffer. This simplifies things greatly and since we've
676          * allocated 8K it shouldn't be a real world limitation
677          */
678         dbg ( DBG_RX,"intr_rx: %d,%d: flags %x len %d\n", pi, rxp, dmabits,
679                                         len );
680         if ( dmabits != ( RX_STP | RX_ENP ) || len > LEN_RX_BUFFER - 2 )
681         {
682                 stats->rx_errors++;
683
684                 /* Update error stats and discard buffer */
685                 if ( dmabits & RX_OFLO )
686                 {
687                         stats->rx_fifo_errors++;
688                 }
689                 if ( dmabits & RX_CRC )
690                 {
691                         stats->rx_crc_errors++;
692                 }
693                 if ( dmabits & RX_FRAM )
694                 {
695                         stats->rx_frame_errors++;
696                 }
697                 if ( dmabits == ( RX_STP | RX_ENP ))
698                 {
699                         stats->rx_length_errors++;
700                 }
701
702                 /* Discard buffer descriptors until we see the end of packet
703                  * marker
704                  */
705                 i = 0;
706                 while (( dmabits & ( DMA_OWN | RX_ENP )) == 0 )
707                 {
708                         FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
709                         if ( ++rxp >= NUM_RX_BUFFER )
710                                 rxp = 0;
711                         if ( ++i > NUM_RX_BUFFER )
712                         {
713                                 dbg ( DBG_ASS,"intr_rx: Discarding more bufs"
714                                                 " than we have\n");
715                                 break;
716                         }
717                         dmabits = FST_RDB ( card, rxDescrRing[pi][rxp].bits );
718                 }
719
720                 /* Discard the terminal buffer */
721                 if ( ! ( dmabits & DMA_OWN ))
722                 {
723                         FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
724                         if ( ++rxp >= NUM_RX_BUFFER )
725                                 rxp = 0;
726                 }
727                 port->rxpos = rxp;
728                 return;
729         }
730
731         /* Allocate SKB */
732         if (( skb = dev_alloc_skb ( len )) == NULL )
733         {
734                 dbg ( DBG_RX,"intr_rx: can't allocate buffer\n");
735
736                 stats->rx_dropped++;
737
738                 /* Return descriptor to card */
739                 FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
740
741                 if ( ++rxp >= NUM_RX_BUFFER )
742                         port->rxpos = 0;
743                 else
744                         port->rxpos = rxp;
745                 return;
746         }
747
748         memcpy_fromio ( skb_put ( skb, len ),
749                                 card->mem + BUF_OFFSET ( rxBuffer[pi][rxp][0]),
750                                 len );
751
752         /* Reset buffer descriptor */
753         FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
754         if ( ++rxp >= NUM_RX_BUFFER )
755                 port->rxpos = 0;
756         else
757                 port->rxpos = rxp;
758
759         /* Update stats */
760         stats->rx_packets++;
761         stats->rx_bytes += len;
762
763         /* Push upstream */
764         skb->mac.raw = skb->data;
765         skb->dev = dev;
766         skb->protocol = hdlc_type_trans(skb, skb->dev);
767         netif_rx ( skb );
768
769         dev->last_rx = jiffies;
770 }
771
772
773 /*
774  *      The interrupt service routine
775  *      Dev_id is our fst_card_info pointer
776  */
777 static irqreturn_t
778 fst_intr ( int irq, void *dev_id, struct pt_regs *regs )
779 {
780         struct fst_card_info *card;
781         struct fst_port_info *port;
782         int rdidx;                      /* Event buffer indices */
783         int wridx;
784         int event;                      /* Actual event for processing */
785         int pi;
786
787         if (( card = dev_id ) == NULL )
788         {
789                 dbg ( DBG_INTR,"intr: spurious %d\n", irq );
790                 return IRQ_NONE;
791         }
792
793         dbg ( DBG_INTR,"intr: %d %p\n", irq, card );
794
795         spin_lock ( &card->card_lock );
796
797         /* Clear and reprime the interrupt source */
798         fst_clear_intr ( card );
799
800         /* Set the software acknowledge */
801         FST_WRB ( card, interruptHandshake, 0xEE );
802
803         /* Drain the event queue */
804         rdidx = FST_RDB ( card, interruptEvent.rdindex );
805         wridx = FST_RDB ( card, interruptEvent.wrindex );
806         while ( rdidx != wridx )
807         {
808                 event = FST_RDB ( card, interruptEvent.evntbuff[rdidx]);
809
810                 port = &card->ports[event & 0x03];
811
812                 dbg ( DBG_INTR,"intr: %x\n", event );
813
814                 switch ( event )
815                 {
816                 case CTLA_CHG:
817                 case CTLB_CHG:
818                 case CTLC_CHG:
819                 case CTLD_CHG:
820                         if ( port->run )
821                                 fst_intr_ctlchg ( card, port );
822                         break;
823
824                 case ABTA_SENT:
825                 case ABTB_SENT:
826                 case ABTC_SENT:
827                 case ABTD_SENT:
828                         dbg ( DBG_TX,"Abort complete port %d\n", event & 0x03 );
829                         break;
830
831                 case TXA_UNDF:
832                 case TXB_UNDF:
833                 case TXC_UNDF:
834                 case TXD_UNDF:
835                         /* Difficult to see how we'd get this given that we
836                          * always load up the entire packet for DMA.
837                          */
838                         dbg ( DBG_TX,"Tx underflow port %d\n", event & 0x03 );
839                         hdlc_stats(port_to_dev(port))->tx_errors++;
840                         hdlc_stats(port_to_dev(port))->tx_fifo_errors++;
841                         break;
842
843                 case INIT_CPLT:
844                         dbg ( DBG_INIT,"Card init OK intr\n");
845                         break;
846
847                 case INIT_FAIL:
848                         dbg ( DBG_INIT,"Card init FAILED intr\n");
849                         card->state = FST_IFAILED;
850                         break;
851
852                 default:
853                         printk_err ("intr: unknown card event code. ignored\n");
854                         break;
855                 }
856
857                 /* Bump and wrap the index */
858                 if ( ++rdidx >= MAX_CIRBUFF )
859                         rdidx = 0;
860         }
861         FST_WRB ( card, interruptEvent.rdindex, rdidx );
862
863         for ( pi = 0, port = card->ports ; pi < card->nports ; pi++, port++ )
864         {
865                 if ( ! port->run )
866                         continue;
867
868                 /* Check for rx completions */
869                 while ( ! ( FST_RDB ( card, rxDescrRing[pi][port->rxpos].bits )
870                                                                 & DMA_OWN ))
871                 {
872                         fst_intr_rx ( card, port );
873                 }
874
875                 /* Check for Tx completions */
876                 while ( port->txcnt > 0 && ! ( FST_RDB ( card,
877                         txDescrRing[pi][port->txipos].bits ) & DMA_OWN ))
878                 {
879                         --port->txcnt;
880                         if ( ++port->txipos >= NUM_TX_BUFFER )
881                                 port->txipos = 0;
882                         netif_wake_queue ( port_to_dev ( port ));
883                 }
884         }
885
886         spin_unlock ( &card->card_lock );
887         return IRQ_HANDLED;
888 }
889
890
891 /*      Check that the shared memory configuration is one that we can handle
892  *      and that some basic parameters are correct
893  */
894 static void
895 check_started_ok ( struct fst_card_info *card )
896 {
897         int i;
898
899         /* Check structure version and end marker */
900         if ( FST_RDW ( card, smcVersion ) != SMC_VERSION )
901         {
902                 printk_err ("Bad shared memory version %d expected %d\n",
903                                 FST_RDW ( card, smcVersion ), SMC_VERSION );
904                 card->state = FST_BADVERSION;
905                 return;
906         }
907         if ( FST_RDL ( card, endOfSmcSignature ) != END_SIG )
908         {
909                 printk_err ("Missing shared memory signature\n");
910                 card->state = FST_BADVERSION;
911                 return;
912         }
913         /* Firmware status flag, 0x00 = initialising, 0x01 = OK, 0xFF = fail */
914         if (( i = FST_RDB ( card, taskStatus )) == 0x01 )
915         {
916                 card->state = FST_RUNNING;
917         }
918         else if ( i == 0xFF )
919         {
920                 printk_err ("Firmware initialisation failed. Card halted\n");
921                 card->state = FST_HALTED;
922                 return;
923         }
924         else if ( i != 0x00 )
925         {
926                 printk_err ("Unknown firmware status 0x%x\n", i );
927                 card->state = FST_HALTED;
928                 return;
929         }
930
931         /* Finally check the number of ports reported by firmware against the
932          * number we assumed at card detection. Should never happen with
933          * existing firmware etc so we just report it for the moment.
934          */
935         if ( FST_RDL ( card, numberOfPorts ) != card->nports )
936         {
937                 printk_warn ("Port count mismatch."
938                                 " Firmware thinks %d we say %d\n",
939                                 FST_RDL ( card, numberOfPorts ), card->nports );
940         }
941 }
942
943
944 static int
945 set_conf_from_info ( struct fst_card_info *card, struct fst_port_info *port,
946                 struct fstioc_info *info )
947 {
948         int err;
949
950         /* Set things according to the user set valid flags.
951          * Several of the old options have been invalidated/replaced by the
952          * generic HDLC package.
953          */
954         err = 0;
955         if ( info->valid & FSTVAL_PROTO )
956                 err = -EINVAL;
957         if ( info->valid & FSTVAL_CABLE )
958                 err = -EINVAL;
959         if ( info->valid & FSTVAL_SPEED )
960                 err = -EINVAL;
961
962         if ( info->valid & FSTVAL_MODE )
963                 FST_WRW ( card, cardMode, info->cardMode );
964 #if FST_DEBUG
965         if ( info->valid & FSTVAL_DEBUG )
966                 fst_debug_mask = info->debug;
967 #endif
968
969         return err;
970 }
971
972 static void
973 gather_conf_info ( struct fst_card_info *card, struct fst_port_info *port,
974                 struct fstioc_info *info )
975 {
976         int i;
977
978         memset ( info, 0, sizeof ( struct fstioc_info ));
979
980         i = port->index;
981         info->nports = card->nports;
982         info->type   = card->type;
983         info->state  = card->state;
984         info->proto  = FST_GEN_HDLC;
985         info->index  = i;
986 #if FST_DEBUG
987         info->debug  = fst_debug_mask;
988 #endif
989
990         /* Only mark information as valid if card is running.
991          * Copy the data anyway in case it is useful for diagnostics
992          */
993         info->valid
994                 = (( card->state == FST_RUNNING ) ? FSTVAL_ALL : FSTVAL_CARD )
995 #if FST_DEBUG
996                 | FSTVAL_DEBUG
997 #endif
998                 ;
999
1000         info->lineInterface = FST_RDW ( card, portConfig[i].lineInterface );
1001         info->internalClock = FST_RDB ( card, portConfig[i].internalClock );
1002         info->lineSpeed     = FST_RDL ( card, portConfig[i].lineSpeed );
1003         info->v24IpSts      = FST_RDL ( card, v24IpSts[i] );
1004         info->v24OpSts      = FST_RDL ( card, v24OpSts[i] );
1005         info->clockStatus   = FST_RDW ( card, clockStatus[i] );
1006         info->cableStatus   = FST_RDW ( card, cableStatus );
1007         info->cardMode      = FST_RDW ( card, cardMode );
1008         info->smcFirmwareVersion  = FST_RDL ( card, smcFirmwareVersion );
1009 }
1010
1011
1012 static int
1013 fst_set_iface ( struct fst_card_info *card, struct fst_port_info *port,
1014                 struct ifreq *ifr )
1015 {
1016         sync_serial_settings sync;
1017         int i;
1018
1019         if (copy_from_user (&sync, ifr->ifr_settings.ifs_ifsu.sync,
1020                             sizeof (sync)))
1021                 return -EFAULT;
1022
1023         if ( sync.loopback )
1024                 return -EINVAL;
1025
1026         i = port->index;
1027
1028         switch (ifr->ifr_settings.type)
1029         {
1030         case IF_IFACE_V35:
1031                 FST_WRW ( card, portConfig[i].lineInterface, V35 );
1032                 port->hwif = V35;
1033                 break;
1034
1035         case IF_IFACE_V24:
1036                 FST_WRW ( card, portConfig[i].lineInterface, V24 );
1037                 port->hwif = V24;
1038                 break;
1039
1040         case IF_IFACE_X21:
1041                 FST_WRW ( card, portConfig[i].lineInterface, X21 );
1042                 port->hwif = X21;
1043                 break;
1044
1045         case IF_IFACE_SYNC_SERIAL:
1046                 break;
1047
1048         default:
1049                 return -EINVAL;
1050         }
1051
1052         switch ( sync.clock_type )
1053         {
1054         case CLOCK_EXT:
1055                 FST_WRB ( card, portConfig[i].internalClock, EXTCLK );
1056                 break;
1057
1058         case CLOCK_INT:
1059                 FST_WRB ( card, portConfig[i].internalClock, INTCLK );
1060                 break;
1061
1062         default:
1063                 return -EINVAL;
1064         }
1065         FST_WRL ( card, portConfig[i].lineSpeed, sync.clock_rate );
1066         return 0;
1067 }
1068
1069 static int
1070 fst_get_iface ( struct fst_card_info *card, struct fst_port_info *port,
1071                 struct ifreq *ifr )
1072 {
1073         sync_serial_settings sync;
1074         int i;
1075
1076         /* First check what line type is set, we'll default to reporting X.21
1077          * if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be
1078          * changed
1079          */
1080         switch ( port->hwif )
1081         {
1082         case V35:
1083                 ifr->ifr_settings.type = IF_IFACE_V35;
1084                 break;
1085         case V24:
1086                 ifr->ifr_settings.type = IF_IFACE_V24;
1087                 break;
1088         case X21:
1089         default:
1090                 ifr->ifr_settings.type = IF_IFACE_X21;
1091                 break;
1092         }
1093
1094         if (ifr->ifr_settings.size < sizeof(sync)) {
1095                 ifr->ifr_settings.size = sizeof(sync); /* data size wanted */
1096                 return -ENOBUFS;
1097         }
1098
1099         i = port->index;
1100         sync.clock_rate = FST_RDL ( card, portConfig[i].lineSpeed );
1101         /* Lucky card and linux use same encoding here */
1102         sync.clock_type = FST_RDB ( card, portConfig[i].internalClock );
1103         sync.loopback = 0;
1104
1105         if (copy_to_user (ifr->ifr_settings.ifs_ifsu.sync, &sync,
1106                           sizeof(sync)))
1107                 return -EFAULT;
1108
1109         return 0;
1110 }
1111
1112
1113 static int
1114 fst_ioctl ( struct net_device *dev, struct ifreq *ifr, int cmd )
1115 {
1116         struct fst_card_info *card;
1117         struct fst_port_info *port;
1118         struct fstioc_write wrthdr;
1119         struct fstioc_info info;
1120         unsigned long flags;
1121
1122         dbg ( DBG_IOCTL,"ioctl: %x, %p\n", cmd, ifr->ifr_data );
1123
1124         port = dev_to_port ( dev );
1125         card = port->card;
1126
1127         if ( !capable ( CAP_NET_ADMIN ))
1128                 return -EPERM;
1129
1130         switch ( cmd )
1131         {
1132         case FSTCPURESET:
1133                 fst_cpureset ( card );
1134                 card->state = FST_RESET;
1135                 return 0;
1136
1137         case FSTCPURELEASE:
1138                 fst_cpurelease ( card );
1139                 card->state = FST_STARTING;
1140                 return 0;
1141
1142         case FSTWRITE:                  /* Code write (download) */
1143
1144                 /* First copy in the header with the length and offset of data
1145                  * to write
1146                  */
1147                 if ( ifr->ifr_data == NULL )
1148                 {
1149                         return -EINVAL;
1150                 }
1151                 if ( copy_from_user ( &wrthdr, ifr->ifr_data,
1152                                         sizeof ( struct fstioc_write )))
1153                 {
1154                         return -EFAULT;
1155                 }
1156
1157                 /* Sanity check the parameters. We don't support partial writes
1158                  * when going over the top
1159                  */
1160                 if ( wrthdr.size > FST_MEMSIZE || wrthdr.offset > FST_MEMSIZE
1161                                 || wrthdr.size + wrthdr.offset > FST_MEMSIZE )
1162                 {
1163                         return -ENXIO;
1164                 }
1165
1166                 /* Now copy the data to the card.
1167                  * This will probably break on some architectures.
1168                  * I'll fix it when I have something to test on.
1169                  */
1170                 if ( copy_from_user ( card->mem + wrthdr.offset,
1171                                 ifr->ifr_data + sizeof ( struct fstioc_write ),
1172                                 wrthdr.size ))
1173                 {
1174                         return -EFAULT;
1175                 }
1176
1177                 /* Writes to the memory of a card in the reset state constitute
1178                  * a download
1179                  */
1180                 if ( card->state == FST_RESET )
1181                 {
1182                         card->state = FST_DOWNLOAD;
1183                 }
1184                 return 0;
1185
1186         case FSTGETCONF:
1187
1188                 /* If card has just been started check the shared memory config
1189                  * version and marker
1190                  */
1191                 if ( card->state == FST_STARTING )
1192                 {
1193                         check_started_ok ( card );
1194
1195                         /* If everything checked out enable card interrupts */
1196                         if ( card->state == FST_RUNNING )
1197                         {
1198                                 spin_lock_irqsave ( &card->card_lock, flags );
1199                                 fst_clear_intr ( card );
1200                                 FST_WRB ( card, interruptHandshake, 0xEE );
1201                                 spin_unlock_irqrestore ( &card->card_lock,
1202                                                                 flags );
1203                         }
1204                 }
1205
1206                 if ( ifr->ifr_data == NULL )
1207                 {
1208                         return -EINVAL;
1209                 }
1210
1211                 gather_conf_info ( card, port, &info );
1212
1213                 if ( copy_to_user ( ifr->ifr_data, &info, sizeof ( info )))
1214                 {
1215                         return -EFAULT;
1216                 }
1217                 return 0;
1218
1219         case FSTSETCONF:
1220
1221                 /* Most of the setting have been moved to the generic ioctls
1222                  * this just covers debug and board ident mode now
1223                  */
1224                 if ( copy_from_user ( &info,  ifr->ifr_data, sizeof ( info )))
1225                 {
1226                         return -EFAULT;
1227                 }
1228
1229                 return set_conf_from_info ( card, port, &info );
1230
1231         case SIOCWANDEV:
1232                 switch (ifr->ifr_settings.type)
1233                 {
1234                 case IF_GET_IFACE:
1235                         return fst_get_iface ( card, port, ifr );
1236
1237                 case IF_IFACE_SYNC_SERIAL:
1238                 case IF_IFACE_V35:
1239                 case IF_IFACE_V24:
1240                 case IF_IFACE_X21:
1241                         return fst_set_iface ( card, port, ifr );
1242
1243                 default:
1244                         return hdlc_ioctl ( dev, ifr, cmd );
1245                 }
1246
1247         default:
1248                 /* Not one of ours. Pass through to HDLC package */
1249                 return hdlc_ioctl ( dev, ifr, cmd );
1250         }
1251 }
1252
1253
1254 static void
1255 fst_openport ( struct fst_port_info *port )
1256 {
1257         int signals;
1258
1259         /* Only init things if card is actually running. This allows open to
1260          * succeed for downloads etc.
1261          */
1262         if ( port->card->state == FST_RUNNING )
1263         {
1264                 if ( port->run )
1265                 {
1266                         dbg ( DBG_OPEN,"open: found port already running\n");
1267
1268                         fst_issue_cmd ( port, STOPPORT );
1269                         port->run = 0;
1270                 }
1271
1272                 fst_rx_config ( port );
1273                 fst_tx_config ( port );
1274                 fst_op_raise ( port, OPSTS_RTS | OPSTS_DTR );
1275
1276                 fst_issue_cmd ( port, STARTPORT );
1277                 port->run = 1;
1278
1279                 signals = FST_RDL ( port->card, v24DebouncedSts[port->index]);
1280                 if ( signals & (( port->hwif == X21 ) ? IPSTS_INDICATE
1281                                                       : IPSTS_DCD ))
1282                         netif_carrier_on ( port_to_dev ( port ));
1283                 else
1284                         netif_carrier_off ( port_to_dev ( port ));
1285         }
1286 }
1287
1288 static void
1289 fst_closeport ( struct fst_port_info *port )
1290 {
1291         if ( port->card->state == FST_RUNNING )
1292         {
1293                 if ( port->run )
1294                 {
1295                         port->run = 0;
1296                         fst_op_lower ( port, OPSTS_RTS | OPSTS_DTR );
1297
1298                         fst_issue_cmd ( port, STOPPORT );
1299                 }
1300                 else
1301                 {
1302                         dbg ( DBG_OPEN,"close: port not running\n");
1303                 }
1304         }
1305 }
1306
1307
1308 static int
1309 fst_open ( struct net_device *dev )
1310 {
1311         int err;
1312
1313         err = hdlc_open (dev);
1314         if ( err )
1315                 return err;
1316
1317         fst_openport ( dev_to_port ( dev ));
1318         netif_wake_queue ( dev );
1319         return 0;
1320 }
1321
1322 static int
1323 fst_close ( struct net_device *dev )
1324 {
1325         netif_stop_queue ( dev );
1326         fst_closeport ( dev_to_port ( dev ));
1327         hdlc_close ( dev );
1328         return 0;
1329 }
1330
1331 static int
1332 fst_attach ( struct net_device *dev, unsigned short encoding, unsigned short parity )
1333 {
1334         /* Setting currently fixed in FarSync card so we check and forget */
1335         if ( encoding != ENCODING_NRZ || parity != PARITY_CRC16_PR1_CCITT )
1336                 return -EINVAL;
1337         return 0;
1338 }
1339
1340
1341 static void
1342 fst_tx_timeout ( struct net_device *dev )
1343 {
1344         struct fst_port_info *port;
1345         struct net_device_stats *stats = hdlc_stats(dev);
1346
1347         dbg ( DBG_INTR | DBG_TX,"tx_timeout\n");
1348
1349         port = dev_to_port ( dev );
1350
1351         stats->tx_errors++;
1352         stats->tx_aborted_errors++;
1353
1354         if ( port->txcnt > 0 )
1355                 fst_issue_cmd ( port, ABORTTX );
1356
1357         dev->trans_start = jiffies;
1358         netif_wake_queue ( dev );
1359 }
1360
1361
1362 static int
1363 fst_start_xmit ( struct sk_buff *skb, struct net_device *dev )
1364 {
1365         struct net_device_stats *stats = hdlc_stats(dev);
1366         struct fst_card_info *card;
1367         struct fst_port_info *port;
1368         unsigned char dmabits;
1369         unsigned long flags;
1370         int pi;
1371         int txp;
1372
1373         port = dev_to_port ( dev );
1374         card = port->card;
1375
1376         /* Drop packet with error if we don't have carrier */
1377         if ( ! netif_carrier_ok ( dev ))
1378         {
1379                 dev_kfree_skb ( skb );
1380                 stats->tx_errors++;
1381                 stats->tx_carrier_errors++;
1382                 return 0;
1383         }
1384
1385         /* Drop it if it's too big! MTU failure ? */
1386         if ( skb->len > LEN_TX_BUFFER )
1387         {
1388                 dbg ( DBG_TX,"Packet too large %d vs %d\n", skb->len,
1389                                                 LEN_TX_BUFFER );
1390                 dev_kfree_skb ( skb );
1391                 stats->tx_errors++;
1392                 return 0;
1393         }
1394
1395         /* Check we have a buffer */
1396         pi = port->index;
1397         spin_lock_irqsave ( &card->card_lock, flags );
1398         txp = port->txpos;
1399         dmabits = FST_RDB ( card, txDescrRing[pi][txp].bits );
1400         if ( dmabits & DMA_OWN )
1401         {
1402                 spin_unlock_irqrestore ( &card->card_lock, flags );
1403                 dbg ( DBG_TX,"Out of Tx buffers\n");
1404                 dev_kfree_skb ( skb );
1405                 stats->tx_errors++;
1406                 return 0;
1407         }
1408         if ( ++port->txpos >= NUM_TX_BUFFER )
1409                 port->txpos = 0;
1410
1411         if ( ++port->txcnt >= NUM_TX_BUFFER )
1412                 netif_stop_queue ( dev );
1413
1414         /* Release the card lock before we copy the data as we now have
1415          * exclusive access to the buffer.
1416          */
1417         spin_unlock_irqrestore ( &card->card_lock, flags );
1418
1419         /* Enqueue the packet */
1420         memcpy_toio ( card->mem + BUF_OFFSET ( txBuffer[pi][txp][0]),
1421                                                 skb->data, skb->len );
1422         FST_WRW ( card, txDescrRing[pi][txp].bcnt, cnv_bcnt ( skb->len ));
1423         FST_WRB ( card, txDescrRing[pi][txp].bits, DMA_OWN | TX_STP | TX_ENP );
1424
1425         stats->tx_packets++;
1426         stats->tx_bytes += skb->len;
1427
1428         dev_kfree_skb ( skb );
1429
1430         dev->trans_start = jiffies;
1431         return 0;
1432 }
1433
1434
1435 /*
1436  *      Card setup having checked hardware resources.
1437  *      Should be pretty bizarre if we get an error here (kernel memory
1438  *      exhaustion is one possibility). If we do see a problem we report it
1439  *      via a printk and leave the corresponding interface and all that follow
1440  *      disabled.
1441  */
1442 static char *type_strings[] __devinitdata = {
1443         "no hardware",                  /* Should never be seen */
1444         "FarSync T2P",
1445         "FarSync T4P"
1446 };
1447
1448 static void __devinit
1449 fst_init_card ( struct fst_card_info *card )
1450 {
1451         int i;
1452         int err;
1453
1454         /* We're working on a number of ports based on the card ID. If the
1455          * firmware detects something different later (should never happen)
1456          * we'll have to revise it in some way then.
1457          */
1458         for ( i = 0 ; i < card->nports ; i++ ) {
1459                 err = register_hdlc_device(card->ports[i].dev);
1460                 if (err < 0) {
1461                         int j;
1462                         printk_err ("Cannot register HDLC device for port %d"
1463                                     " (errno %d)\n", i, -err );
1464                         for (j = i; j < card->nports; j++) {
1465                                 free_netdev(card->ports[j].dev);
1466                                 card->ports[j].dev = NULL;
1467                         }
1468                         card->nports = i;
1469                         break;
1470                 }
1471         }
1472
1473         printk ( KERN_INFO "%s-%s: %s IRQ%d, %d ports\n",
1474                         port_to_dev(&card->ports[0])->name,
1475                         port_to_dev(&card->ports[card->nports-1])->name,
1476                         type_strings[card->type], card->irq, card->nports );
1477 }
1478
1479
1480 /*
1481  *      Initialise card when detected.
1482  *      Returns 0 to indicate success, or errno otherwise.
1483  */
1484 static int __devinit
1485 fst_add_one ( struct pci_dev *pdev, const struct pci_device_id *ent )
1486 {
1487         static int firsttime_done = 0;
1488         struct fst_card_info *card;
1489         int err = 0;
1490         int i;
1491
1492         if ( ! firsttime_done )
1493         {
1494                 printk ( KERN_INFO "FarSync X21 driver " FST_USER_VERSION
1495                                 " (c) 2001 FarSite Communications Ltd.\n");
1496                 firsttime_done = 1;
1497         }
1498
1499         /* Allocate driver private data */
1500         card = kmalloc ( sizeof ( struct fst_card_info ),  GFP_KERNEL);
1501         if (card == NULL)
1502         {
1503                 printk_err ("FarSync card found but insufficient memory for"
1504                                 " driver storage\n");
1505                 return -ENOMEM;
1506         }
1507         memset ( card, 0, sizeof ( struct fst_card_info ));
1508
1509         /* Try to enable the device */
1510         if (( err = pci_enable_device ( pdev )) != 0 )
1511         {
1512                 printk_err ("Failed to enable card. Err %d\n", -err );
1513                 goto error_free_card;
1514         }
1515
1516         /* Record info we need*/
1517         card->irq         = pdev->irq;
1518         card->pci_conf    = pci_resource_start ( pdev, 1 );
1519         card->phys_mem    = pci_resource_start ( pdev, 2 );
1520         card->phys_ctlmem = pci_resource_start ( pdev, 3 );
1521
1522         card->type        = ent->driver_data;
1523         card->nports      = ( ent->driver_data == FST_TYPE_T2P ) ? 2 : 4;
1524
1525         card->state       = FST_UNINIT;
1526
1527         spin_lock_init ( &card->card_lock );
1528
1529         for ( i = 0 ; i < card->nports ; i++ ) {
1530                 struct net_device *dev = alloc_hdlcdev(&card->ports[i]);
1531                 hdlc_device *hdlc;
1532                 if (!dev) {
1533                         while (i--)
1534                                 free_netdev(card->ports[i].dev);
1535                         printk_err ("FarSync: out of memory\n");
1536                         goto error_free_card;
1537                 }
1538                 card->ports[i].dev    = dev;
1539                 card->ports[i].card   = card;
1540                 card->ports[i].index  = i;
1541                 card->ports[i].run    = 0;
1542
1543                 hdlc = dev_to_hdlc(dev);
1544
1545                 /* Fill in the net device info */
1546                 /* Since this is a PCI setup this is purely
1547                  * informational. Give them the buffer addresses
1548                  * and basic card I/O.
1549                  */
1550                 dev->mem_start   = card->phys_mem
1551                                  + BUF_OFFSET ( txBuffer[i][0][0]);
1552                 dev->mem_end     = card->phys_mem
1553                                  + BUF_OFFSET ( txBuffer[i][NUM_TX_BUFFER][0]);
1554                 dev->base_addr   = card->pci_conf;
1555                 dev->irq         = card->irq;
1556
1557                 dev->tx_queue_len          = FST_TX_QUEUE_LEN;
1558                 dev->open                  = fst_open;
1559                 dev->stop                  = fst_close;
1560                 dev->do_ioctl              = fst_ioctl;
1561                 dev->watchdog_timeo        = FST_TX_TIMEOUT;
1562                 dev->tx_timeout            = fst_tx_timeout;
1563                 hdlc->attach = fst_attach;
1564                 hdlc->xmit   = fst_start_xmit;
1565         }
1566
1567         dbg ( DBG_PCI,"type %d nports %d irq %d\n", card->type,
1568                         card->nports, card->irq );
1569         dbg ( DBG_PCI,"conf %04x mem %08x ctlmem %08x\n",
1570                         card->pci_conf, card->phys_mem, card->phys_ctlmem );
1571
1572         /* Check we can get access to the memory and I/O regions */
1573         if ( ! request_region ( card->pci_conf, 0x80,"PLX config regs"))
1574         {
1575                 printk_err ("Unable to get config I/O @ 0x%04X\n",
1576                                                 card->pci_conf );
1577                 err = -ENODEV;
1578                 goto error_free_ports;
1579         }
1580         if ( ! request_mem_region ( card->phys_mem, FST_MEMSIZE,"Shared RAM"))
1581         {
1582                 printk_err ("Unable to get main memory @ 0x%08X\n",
1583                                                 card->phys_mem );
1584                 err = -ENODEV;
1585                 goto error_release_io;
1586         }
1587         if ( ! request_mem_region ( card->phys_ctlmem, 0x10,"Control memory"))
1588         {
1589                 printk_err ("Unable to get control memory @ 0x%08X\n",
1590                                                 card->phys_ctlmem );
1591                 err = -ENODEV;
1592                 goto error_release_mem;
1593         }
1594
1595
1596         /* Get virtual addresses of memory regions */
1597         if (( card->mem = ioremap ( card->phys_mem, FST_MEMSIZE )) == NULL )
1598         {
1599                 printk_err ("Physical memory remap failed\n");
1600                 err = -ENODEV;
1601                 goto error_release_ctlmem;
1602         }
1603         if (( card->ctlmem = ioremap ( card->phys_ctlmem, 0x10 )) == NULL )
1604         {
1605                 printk_err ("Control memory remap failed\n");
1606                 err = -ENODEV;
1607                 goto error_unmap_mem;
1608         }
1609         dbg ( DBG_PCI,"kernel mem %p, ctlmem %p\n", card->mem, card->ctlmem);
1610
1611         /* Reset the card's processor */
1612         fst_cpureset ( card );
1613         card->state = FST_RESET;
1614
1615         /* Register the interrupt handler */
1616         if ( request_irq ( card->irq, fst_intr, SA_SHIRQ, FST_DEV_NAME, card ))
1617         {
1618
1619                 printk_err ("Unable to register interrupt %d\n", card->irq );
1620                 err = -ENODEV;
1621                 goto error_unmap_ctlmem;
1622         }
1623
1624         /* Record driver data for later use */
1625         pci_set_drvdata(pdev, card);
1626
1627         /* Remainder of card setup */
1628         fst_init_card ( card );
1629
1630         return 0;                       /* Success */
1631
1632
1633                                         /* Failure. Release resources */
1634 error_unmap_ctlmem:
1635         iounmap ( card->ctlmem );
1636
1637 error_unmap_mem:
1638         iounmap ( card->mem );
1639
1640 error_release_ctlmem:
1641         release_mem_region ( card->phys_ctlmem, 0x10 );
1642
1643 error_release_mem:
1644         release_mem_region ( card->phys_mem, FST_MEMSIZE );
1645
1646 error_release_io:
1647         release_region ( card->pci_conf, 0x80 );
1648
1649 error_free_ports:
1650         for (i = 0; i < card->nports; i++)
1651                 free_netdev(card->ports[i].dev);
1652 error_free_card:
1653         kfree ( card );
1654         return err;
1655 }
1656
1657
1658 /*
1659  *      Cleanup and close down a card
1660  */
1661 static void __devexit
1662 fst_remove_one ( struct pci_dev *pdev )
1663 {
1664         struct fst_card_info *card;
1665         int i;
1666
1667         card = pci_get_drvdata(pdev);
1668
1669         for ( i = 0 ; i < card->nports ; i++ )
1670         {
1671                 struct net_device *dev = port_to_dev(&card->ports[i]);
1672                 unregister_hdlc_device(dev);
1673         }
1674
1675         fst_disable_intr ( card );
1676         free_irq ( card->irq, card );
1677
1678         iounmap ( card->ctlmem );
1679         iounmap ( card->mem );
1680
1681         release_mem_region ( card->phys_ctlmem, 0x10 );
1682         release_mem_region ( card->phys_mem, FST_MEMSIZE );
1683         release_region ( card->pci_conf, 0x80 );
1684
1685         for (i = 0; i < card->nports; i++)
1686                 free_netdev(card->ports[i].dev);
1687
1688         kfree ( card );
1689 }
1690
1691 static struct pci_driver fst_driver = {
1692         .name           = FST_NAME,
1693         .id_table       = fst_pci_dev_id,
1694         .probe          = fst_add_one,
1695         .remove = __devexit_p(fst_remove_one),
1696         .suspend        = NULL,
1697         .resume = NULL,
1698 };
1699
1700 static int __init
1701 fst_init(void)
1702 {
1703         return pci_module_init ( &fst_driver );
1704 }
1705
1706 static void __exit
1707 fst_cleanup_module(void)
1708 {
1709         pci_unregister_driver ( &fst_driver );
1710 }
1711
1712 module_init ( fst_init );
1713 module_exit ( fst_cleanup_module );
1714