9014102be5c6938ec7b1c14b1254020cb825d037
[linux-flexiantxendom0-3.2.10.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)   ((unsigned int)&(((struct buf_window *)BFM_BASE)->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         hdlc_device             hdlc;   /* HDLC device struct - must be first */
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 hdlc_to_port(H) ((struct fst_port_info *)(H))
361 #define dev_to_port(D)  hdlc_to_port(dev_to_hdlc(D))
362 #define port_to_dev(P)  hdlc_to_dev(&(P)->hdlc)
363
364
365 /*
366  *      Shared memory window access macros
367  *
368  *      We have a nice memory based structure above, which could be directly
369  *      mapped on i386 but might not work on other architectures unless we use
370  *      the readb,w,l and writeb,w,l macros. Unfortunately these macros take
371  *      physical offsets so we have to convert. The only saving grace is that
372  *      this should all collapse back to a simple indirection eventually.
373  */
374 #define WIN_OFFSET(X)   ((long)&(((struct fst_shared *)SMC_BASE)->X))
375
376 #define FST_RDB(C,E)    readb ((C)->mem + WIN_OFFSET(E))
377 #define FST_RDW(C,E)    readw ((C)->mem + WIN_OFFSET(E))
378 #define FST_RDL(C,E)    readl ((C)->mem + WIN_OFFSET(E))
379
380 #define FST_WRB(C,E,B)  writeb ((B), (C)->mem + WIN_OFFSET(E))
381 #define FST_WRW(C,E,W)  writew ((W), (C)->mem + WIN_OFFSET(E))
382 #define FST_WRL(C,E,L)  writel ((L), (C)->mem + WIN_OFFSET(E))
383
384
385 /*
386  *      Debug support
387  */
388 #if FST_DEBUG
389
390 static int fst_debug_mask = { FST_DEBUG };
391
392 /* Most common debug activity is to print something if the corresponding bit
393  * is set in the debug mask. Note: this uses a non-ANSI extension in GCC to
394  * support variable numbers of macro parameters. The inverted if prevents us
395  * eating someone else's else clause.
396  */
397 #define dbg(F,fmt,A...) if ( ! ( fst_debug_mask & (F))) \
398                                 ; \
399                         else \
400                                 printk ( KERN_DEBUG FST_NAME ": " fmt, ## A )
401
402 #else
403 # define dbg(X...)      /* NOP */
404 #endif
405
406
407 /*      Printing short cuts
408  */
409 #define printk_err(fmt,A...)    printk ( KERN_ERR     FST_NAME ": " fmt, ## A )
410 #define printk_warn(fmt,A...)   printk ( KERN_WARNING FST_NAME ": " fmt, ## A )
411 #define printk_info(fmt,A...)   printk ( KERN_INFO    FST_NAME ": " fmt, ## A )
412
413
414 /*
415  *      PCI ID lookup table
416  */
417 static struct pci_device_id fst_pci_dev_id[] __devinitdata = {
418         { FSC_PCI_VENDOR_ID, T2P_PCI_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0,
419                                         FST_TYPE_T2P },
420         { FSC_PCI_VENDOR_ID, T4P_PCI_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0,
421                                         FST_TYPE_T4P },
422         { 0, }                          /* End */
423 };
424
425 MODULE_DEVICE_TABLE ( pci, fst_pci_dev_id );
426
427
428 /*      Card control functions
429  *      ======================
430  */
431 /*      Place the processor in reset state
432  *
433  * Used to be a simple write to card control space but a glitch in the latest
434  * AMD Am186CH processor means that we now have to do it by asserting and de-
435  * asserting the PLX chip PCI Adapter Software Reset. Bit 30 in CNTRL register
436  * at offset 0x50.
437  */
438 static inline void
439 fst_cpureset ( struct fst_card_info *card )
440 {
441         unsigned int regval;
442
443         regval = inl ( card->pci_conf + 0x50 );
444
445         outl ( regval |  0x40000000, card->pci_conf + 0x50 );
446         outl ( regval & ~0x40000000, card->pci_conf + 0x50 );
447 }
448
449 /*      Release the processor from reset
450  */
451 static inline void
452 fst_cpurelease ( struct fst_card_info *card )
453 {
454         (void) readb ( card->ctlmem );
455 }
456
457 /*      Clear the cards interrupt flag
458  */
459 static inline void
460 fst_clear_intr ( struct fst_card_info *card )
461 {
462         /* Poke the appropriate PLX chip register (same as enabling interrupts)
463          */
464         outw ( 0x0543, card->pci_conf + 0x4C );
465 }
466
467 /*      Disable card interrupts
468  */
469 static inline void
470 fst_disable_intr ( struct fst_card_info *card )
471 {
472         outw ( 0x0000, card->pci_conf + 0x4C );
473 }
474
475
476 /*      Issue a Mailbox command for a port.
477  *      Note we issue them on a fire and forget basis, not expecting to see an
478  *      error and not waiting for completion.
479  */
480 static void
481 fst_issue_cmd ( struct fst_port_info *port, unsigned short cmd )
482 {
483         struct fst_card_info *card;
484         unsigned short mbval;
485         unsigned long flags;
486         int safety;
487
488         card = port->card;
489         spin_lock_irqsave ( &card->card_lock, flags );
490         mbval = FST_RDW ( card, portMailbox[port->index][0]);
491
492         safety = 0;
493         /* Wait for any previous command to complete */
494         while ( mbval > NAK )
495         {
496                 spin_unlock_irqrestore ( &card->card_lock, flags );
497                 schedule_timeout ( 1 );
498                 spin_lock_irqsave ( &card->card_lock, flags );
499
500                 if ( ++safety > 1000 )
501                 {
502                         printk_err ("Mailbox safety timeout\n");
503                         break;
504                 }
505
506                 mbval = FST_RDW ( card, portMailbox[port->index][0]);
507         }
508         if ( safety > 0 )
509         {
510                 dbg ( DBG_CMD,"Mailbox clear after %d jiffies\n", safety );
511         }
512         if ( mbval == NAK )
513         {
514                 dbg ( DBG_CMD,"issue_cmd: previous command was NAK'd\n");
515         }
516
517         FST_WRW ( card, portMailbox[port->index][0], cmd );
518
519         if ( cmd == ABORTTX || cmd == STARTPORT )
520         {
521                 port->txpos  = 0;
522                 port->txipos = 0;
523                 port->txcnt  = 0;
524         }
525
526         spin_unlock_irqrestore ( &card->card_lock, flags );
527 }
528
529
530 /*      Port output signals control
531  */
532 static inline void
533 fst_op_raise ( struct fst_port_info *port, unsigned int outputs )
534 {
535         outputs |= FST_RDL ( port->card, v24OpSts[port->index]);
536         FST_WRL ( port->card, v24OpSts[port->index], outputs );
537
538         if ( port->run )
539                 fst_issue_cmd ( port, SETV24O );
540 }
541
542 static inline void
543 fst_op_lower ( struct fst_port_info *port, unsigned int outputs )
544 {
545         outputs = ~outputs & FST_RDL ( port->card, v24OpSts[port->index]);
546         FST_WRL ( port->card, v24OpSts[port->index], outputs );
547
548         if ( port->run )
549                 fst_issue_cmd ( port, SETV24O );
550 }
551
552
553 /*
554  *      Setup port Rx buffers
555  */
556 static void
557 fst_rx_config ( struct fst_port_info *port )
558 {
559         int i;
560         int pi;
561         unsigned int offset;
562         unsigned long flags;
563         struct fst_card_info *card;
564
565         pi   = port->index;
566         card = port->card;
567         spin_lock_irqsave ( &card->card_lock, flags );
568         for ( i = 0 ; i < NUM_RX_BUFFER ; i++ )
569         {
570                 offset = BUF_OFFSET ( rxBuffer[pi][i][0]);
571
572                 FST_WRW ( card, rxDescrRing[pi][i].ladr, (u16) offset );
573                 FST_WRB ( card, rxDescrRing[pi][i].hadr, (u8)( offset >> 16 ));
574                 FST_WRW ( card, rxDescrRing[pi][i].bcnt,
575                                         cnv_bcnt ( LEN_RX_BUFFER ));
576                 FST_WRW ( card, rxDescrRing[pi][i].mcnt, 0 );
577                 FST_WRB ( card, rxDescrRing[pi][i].bits, DMA_OWN );
578         }
579         port->rxpos  = 0;
580         spin_unlock_irqrestore ( &card->card_lock, flags );
581 }
582
583
584 /*
585  *      Setup port Tx buffers
586  */
587 static void
588 fst_tx_config ( struct fst_port_info *port )
589 {
590         int i;
591         int pi;
592         unsigned int offset;
593         unsigned long flags;
594         struct fst_card_info *card;
595
596         pi   = port->index;
597         card = port->card;
598         spin_lock_irqsave ( &card->card_lock, flags );
599         for ( i = 0 ; i < NUM_TX_BUFFER ; i++ )
600         {
601                 offset = BUF_OFFSET ( txBuffer[pi][i][0]);
602
603                 FST_WRW ( card, txDescrRing[pi][i].ladr, (u16) offset );
604                 FST_WRB ( card, txDescrRing[pi][i].hadr, (u8)( offset >> 16 ));
605                 FST_WRW ( card, txDescrRing[pi][i].bcnt, 0 );
606                 FST_WRB ( card, txDescrRing[pi][i].bits, 0 );
607         }
608         port->txpos  = 0;
609         port->txipos = 0;
610         port->txcnt  = 0;
611         spin_unlock_irqrestore ( &card->card_lock, flags );
612 }
613
614
615 /*      Control signal change interrupt event
616  */
617 static irqreturn_t
618 fst_intr_ctlchg ( struct fst_card_info *card, struct fst_port_info *port )
619 {
620         int signals;
621
622         signals = FST_RDL ( card, v24DebouncedSts[port->index]);
623
624         if ( signals & (( port->hwif == X21 ) ? IPSTS_INDICATE : IPSTS_DCD ))
625         {
626                 if ( ! netif_carrier_ok ( port_to_dev ( port )))
627                 {
628                         dbg ( DBG_INTR,"DCD active\n");
629                         netif_carrier_on ( port_to_dev ( port ));
630                 }
631         }
632         else
633         {
634                 if ( netif_carrier_ok ( port_to_dev ( port )))
635                 {
636                         dbg ( DBG_INTR,"DCD lost\n");
637                         netif_carrier_off ( port_to_dev ( port ));
638                 }
639         }
640         return IRQ_HANDLED;
641 }
642
643
644 /*      Rx complete interrupt
645  */
646 static void
647 fst_intr_rx ( struct fst_card_info *card, struct fst_port_info *port )
648 {
649         unsigned char dmabits;
650         int pi;
651         int rxp;
652         unsigned short len;
653         struct sk_buff *skb;
654         int i;
655
656
657         /* Check we have a buffer to process */
658         pi  = port->index;
659         rxp = port->rxpos;
660         dmabits = FST_RDB ( card, rxDescrRing[pi][rxp].bits );
661         if ( dmabits & DMA_OWN )
662         {
663                 dbg ( DBG_RX | DBG_INTR,"intr_rx: No buffer port %d pos %d\n",
664                                         pi, rxp );
665                 return;
666         }
667
668         /* Get buffer length */
669         len = FST_RDW ( card, rxDescrRing[pi][rxp].mcnt );
670         /* Discard the CRC */
671         len -= 2;
672
673         /* Check buffer length and for other errors. We insist on one packet
674          * in one buffer. This simplifies things greatly and since we've
675          * allocated 8K it shouldn't be a real world limitation
676          */
677         dbg ( DBG_RX,"intr_rx: %d,%d: flags %x len %d\n", pi, rxp, dmabits,
678                                         len );
679         if ( dmabits != ( RX_STP | RX_ENP ) || len > LEN_RX_BUFFER - 2 )
680         {
681                 port->hdlc.stats.rx_errors++;
682
683                 /* Update error stats and discard buffer */
684                 if ( dmabits & RX_OFLO )
685                 {
686                         port->hdlc.stats.rx_fifo_errors++;
687                 }
688                 if ( dmabits & RX_CRC )
689                 {
690                         port->hdlc.stats.rx_crc_errors++;
691                 }
692                 if ( dmabits & RX_FRAM )
693                 {
694                         port->hdlc.stats.rx_frame_errors++;
695                 }
696                 if ( dmabits == ( RX_STP | RX_ENP ))
697                 {
698                         port->hdlc.stats.rx_length_errors++;
699                 }
700
701                 /* Discard buffer descriptors until we see the end of packet
702                  * marker
703                  */
704                 i = 0;
705                 while (( dmabits & ( DMA_OWN | RX_ENP )) == 0 )
706                 {
707                         FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
708                         if ( ++rxp >= NUM_RX_BUFFER )
709                                 rxp = 0;
710                         if ( ++i > NUM_RX_BUFFER )
711                         {
712                                 dbg ( DBG_ASS,"intr_rx: Discarding more bufs"
713                                                 " than we have\n");
714                                 break;
715                         }
716                         dmabits = FST_RDB ( card, rxDescrRing[pi][rxp].bits );
717                 }
718
719                 /* Discard the terminal buffer */
720                 if ( ! ( dmabits & DMA_OWN ))
721                 {
722                         FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
723                         if ( ++rxp >= NUM_RX_BUFFER )
724                                 rxp = 0;
725                 }
726                 port->rxpos = rxp;
727                 return;
728         }
729
730         /* Allocate SKB */
731         if (( skb = dev_alloc_skb ( len )) == NULL )
732         {
733                 dbg ( DBG_RX,"intr_rx: can't allocate buffer\n");
734
735                 port->hdlc.stats.rx_dropped++;
736
737                 /* Return descriptor to card */
738                 FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
739
740                 if ( ++rxp >= NUM_RX_BUFFER )
741                         port->rxpos = 0;
742                 else
743                         port->rxpos = rxp;
744                 return;
745         }
746
747         memcpy_fromio ( skb_put ( skb, len ),
748                                 card->mem + BUF_OFFSET ( rxBuffer[pi][rxp][0]),
749                                 len );
750
751         /* Reset buffer descriptor */
752         FST_WRB ( card, rxDescrRing[pi][rxp].bits, DMA_OWN );
753         if ( ++rxp >= NUM_RX_BUFFER )
754                 port->rxpos = 0;
755         else
756                 port->rxpos = rxp;
757
758         /* Update stats */
759         port->hdlc.stats.rx_packets++;
760         port->hdlc.stats.rx_bytes += len;
761
762         /* Push upstream */
763         skb->mac.raw = skb->data;
764         skb->dev = hdlc_to_dev ( &port->hdlc );
765         skb->protocol = hdlc_type_trans(skb, skb->dev);
766         netif_rx ( skb );
767
768         port_to_dev ( port )->last_rx = jiffies;
769 }
770
771
772 /*
773  *      The interrupt service routine
774  *      Dev_id is our fst_card_info pointer
775  */
776 static irqreturn_t
777 fst_intr ( int irq, void *dev_id, struct pt_regs *regs )
778 {
779         struct fst_card_info *card;
780         struct fst_port_info *port;
781         int rdidx;                      /* Event buffer indices */
782         int wridx;
783         int event;                      /* Actual event for processing */
784         int pi;
785
786         if (( card = dev_id ) == NULL )
787         {
788                 dbg ( DBG_INTR,"intr: spurious %d\n", irq );
789                 return IRQ_NONE;
790         }
791
792         dbg ( DBG_INTR,"intr: %d %p\n", irq, card );
793
794         spin_lock ( &card->card_lock );
795
796         /* Clear and reprime the interrupt source */
797         fst_clear_intr ( card );
798
799         /* Set the software acknowledge */
800         FST_WRB ( card, interruptHandshake, 0xEE );
801
802         /* Drain the event queue */
803         rdidx = FST_RDB ( card, interruptEvent.rdindex );
804         wridx = FST_RDB ( card, interruptEvent.wrindex );
805         while ( rdidx != wridx )
806         {
807                 event = FST_RDB ( card, interruptEvent.evntbuff[rdidx]);
808
809                 port = &card->ports[event & 0x03];
810
811                 dbg ( DBG_INTR,"intr: %x\n", event );
812
813                 switch ( event )
814                 {
815                 case CTLA_CHG:
816                 case CTLB_CHG:
817                 case CTLC_CHG:
818                 case CTLD_CHG:
819                         if ( port->run )
820                                 fst_intr_ctlchg ( card, port );
821                         break;
822
823                 case ABTA_SENT:
824                 case ABTB_SENT:
825                 case ABTC_SENT:
826                 case ABTD_SENT:
827                         dbg ( DBG_TX,"Abort complete port %d\n", event & 0x03 );
828                         break;
829
830                 case TXA_UNDF:
831                 case TXB_UNDF:
832                 case TXC_UNDF:
833                 case TXD_UNDF:
834                         /* Difficult to see how we'd get this given that we
835                          * always load up the entire packet for DMA.
836                          */
837                         dbg ( DBG_TX,"Tx underflow port %d\n", event & 0x03 );
838                         port->hdlc.stats.tx_errors++;
839                         port->hdlc.stats.tx_fifo_errors++;
840                         break;
841
842                 case INIT_CPLT:
843                         dbg ( DBG_INIT,"Card init OK intr\n");
844                         break;
845
846                 case INIT_FAIL:
847                         dbg ( DBG_INIT,"Card init FAILED intr\n");
848                         card->state = FST_IFAILED;
849                         break;
850
851                 default:
852                         printk_err ("intr: unknown card event code. ignored\n");
853                         break;
854                 }
855
856                 /* Bump and wrap the index */
857                 if ( ++rdidx >= MAX_CIRBUFF )
858                         rdidx = 0;
859         }
860         FST_WRB ( card, interruptEvent.rdindex, rdidx );
861
862         for ( pi = 0, port = card->ports ; pi < card->nports ; pi++, port++ )
863         {
864                 if ( ! port->run )
865                         continue;
866
867                 /* Check for rx completions */
868                 while ( ! ( FST_RDB ( card, rxDescrRing[pi][port->rxpos].bits )
869                                                                 & DMA_OWN ))
870                 {
871                         fst_intr_rx ( card, port );
872                 }
873
874                 /* Check for Tx completions */
875                 while ( port->txcnt > 0 && ! ( FST_RDB ( card,
876                         txDescrRing[pi][port->txipos].bits ) & DMA_OWN ))
877                 {
878                         --port->txcnt;
879                         if ( ++port->txipos >= NUM_TX_BUFFER )
880                                 port->txipos = 0;
881                         netif_wake_queue ( port_to_dev ( port ));
882                 }
883         }
884
885         spin_unlock ( &card->card_lock );
886         return IRQ_HANDLED;
887 }
888
889
890 /*      Check that the shared memory configuration is one that we can handle
891  *      and that some basic parameters are correct
892  */
893 static void
894 check_started_ok ( struct fst_card_info *card )
895 {
896         int i;
897
898         /* Check structure version and end marker */
899         if ( FST_RDW ( card, smcVersion ) != SMC_VERSION )
900         {
901                 printk_err ("Bad shared memory version %d expected %d\n",
902                                 FST_RDW ( card, smcVersion ), SMC_VERSION );
903                 card->state = FST_BADVERSION;
904                 return;
905         }
906         if ( FST_RDL ( card, endOfSmcSignature ) != END_SIG )
907         {
908                 printk_err ("Missing shared memory signature\n");
909                 card->state = FST_BADVERSION;
910                 return;
911         }
912         /* Firmware status flag, 0x00 = initialising, 0x01 = OK, 0xFF = fail */
913         if (( i = FST_RDB ( card, taskStatus )) == 0x01 )
914         {
915                 card->state = FST_RUNNING;
916         }
917         else if ( i == 0xFF )
918         {
919                 printk_err ("Firmware initialisation failed. Card halted\n");
920                 card->state = FST_HALTED;
921                 return;
922         }
923         else if ( i != 0x00 )
924         {
925                 printk_err ("Unknown firmware status 0x%x\n", i );
926                 card->state = FST_HALTED;
927                 return;
928         }
929
930         /* Finally check the number of ports reported by firmware against the
931          * number we assumed at card detection. Should never happen with
932          * existing firmware etc so we just report it for the moment.
933          */
934         if ( FST_RDL ( card, numberOfPorts ) != card->nports )
935         {
936                 printk_warn ("Port count mismatch."
937                                 " Firmware thinks %d we say %d\n",
938                                 FST_RDL ( card, numberOfPorts ), card->nports );
939         }
940 }
941
942
943 static int
944 set_conf_from_info ( struct fst_card_info *card, struct fst_port_info *port,
945                 struct fstioc_info *info )
946 {
947         int err;
948
949         /* Set things according to the user set valid flags.
950          * Several of the old options have been invalidated/replaced by the
951          * generic HDLC package.
952          */
953         err = 0;
954         if ( info->valid & FSTVAL_PROTO )
955                 err = -EINVAL;
956         if ( info->valid & FSTVAL_CABLE )
957                 err = -EINVAL;
958         if ( info->valid & FSTVAL_SPEED )
959                 err = -EINVAL;
960
961         if ( info->valid & FSTVAL_MODE )
962                 FST_WRW ( card, cardMode, info->cardMode );
963 #if FST_DEBUG
964         if ( info->valid & FSTVAL_DEBUG )
965                 fst_debug_mask = info->debug;
966 #endif
967
968         return err;
969 }
970
971 static void
972 gather_conf_info ( struct fst_card_info *card, struct fst_port_info *port,
973                 struct fstioc_info *info )
974 {
975         int i;
976
977         memset ( info, 0, sizeof ( struct fstioc_info ));
978
979         i = port->index;
980         info->nports = card->nports;
981         info->type   = card->type;
982         info->state  = card->state;
983         info->proto  = FST_GEN_HDLC;
984         info->index  = i;
985 #if FST_DEBUG
986         info->debug  = fst_debug_mask;
987 #endif
988
989         /* Only mark information as valid if card is running.
990          * Copy the data anyway in case it is useful for diagnostics
991          */
992         info->valid
993                 = (( card->state == FST_RUNNING ) ? FSTVAL_ALL : FSTVAL_CARD )
994 #if FST_DEBUG
995                 | FSTVAL_DEBUG
996 #endif
997                 ;
998
999         info->lineInterface = FST_RDW ( card, portConfig[i].lineInterface );
1000         info->internalClock = FST_RDB ( card, portConfig[i].internalClock );
1001         info->lineSpeed     = FST_RDL ( card, portConfig[i].lineSpeed );
1002         info->v24IpSts      = FST_RDL ( card, v24IpSts[i] );
1003         info->v24OpSts      = FST_RDL ( card, v24OpSts[i] );
1004         info->clockStatus   = FST_RDW ( card, clockStatus[i] );
1005         info->cableStatus   = FST_RDW ( card, cableStatus );
1006         info->cardMode      = FST_RDW ( card, cardMode );
1007         info->smcFirmwareVersion  = FST_RDL ( card, smcFirmwareVersion );
1008 }
1009
1010
1011 static int
1012 fst_set_iface ( struct fst_card_info *card, struct fst_port_info *port,
1013                 struct ifreq *ifr )
1014 {
1015         sync_serial_settings sync;
1016         int i;
1017
1018         if (copy_from_user (&sync, ifr->ifr_settings.ifs_ifsu.sync,
1019                             sizeof (sync)))
1020                 return -EFAULT;
1021
1022         if ( sync.loopback )
1023                 return -EINVAL;
1024
1025         i = port->index;
1026
1027         switch (ifr->ifr_settings.type)
1028         {
1029         case IF_IFACE_V35:
1030                 FST_WRW ( card, portConfig[i].lineInterface, V35 );
1031                 port->hwif = V35;
1032                 break;
1033
1034         case IF_IFACE_V24:
1035                 FST_WRW ( card, portConfig[i].lineInterface, V24 );
1036                 port->hwif = V24;
1037                 break;
1038
1039         case IF_IFACE_X21:
1040                 FST_WRW ( card, portConfig[i].lineInterface, X21 );
1041                 port->hwif = X21;
1042                 break;
1043
1044         case IF_IFACE_SYNC_SERIAL:
1045                 break;
1046
1047         default:
1048                 return -EINVAL;
1049         }
1050
1051         switch ( sync.clock_type )
1052         {
1053         case CLOCK_EXT:
1054                 FST_WRB ( card, portConfig[i].internalClock, EXTCLK );
1055                 break;
1056
1057         case CLOCK_INT:
1058                 FST_WRB ( card, portConfig[i].internalClock, INTCLK );
1059                 break;
1060
1061         default:
1062                 return -EINVAL;
1063         }
1064         FST_WRL ( card, portConfig[i].lineSpeed, sync.clock_rate );
1065         return 0;
1066 }
1067
1068 static int
1069 fst_get_iface ( struct fst_card_info *card, struct fst_port_info *port,
1070                 struct ifreq *ifr )
1071 {
1072         sync_serial_settings sync;
1073         int i;
1074
1075         /* First check what line type is set, we'll default to reporting X.21
1076          * if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be
1077          * changed
1078          */
1079         switch ( port->hwif )
1080         {
1081         case V35:
1082                 ifr->ifr_settings.type = IF_IFACE_V35;
1083                 break;
1084         case V24:
1085                 ifr->ifr_settings.type = IF_IFACE_V24;
1086                 break;
1087         case X21:
1088         default:
1089                 ifr->ifr_settings.type = IF_IFACE_X21;
1090                 break;
1091         }
1092
1093         if (ifr->ifr_settings.size < sizeof(sync)) {
1094                 ifr->ifr_settings.size = sizeof(sync); /* data size wanted */
1095                 return -ENOBUFS;
1096         }
1097
1098         i = port->index;
1099         sync.clock_rate = FST_RDL ( card, portConfig[i].lineSpeed );
1100         /* Lucky card and linux use same encoding here */
1101         sync.clock_type = FST_RDB ( card, portConfig[i].internalClock );
1102         sync.loopback = 0;
1103
1104         if (copy_to_user (ifr->ifr_settings.ifs_ifsu.sync, &sync,
1105                           sizeof(sync)))
1106                 return -EFAULT;
1107
1108         return 0;
1109 }
1110
1111
1112 static int
1113 fst_ioctl ( struct net_device *dev, struct ifreq *ifr, int cmd )
1114 {
1115         struct fst_card_info *card;
1116         struct fst_port_info *port;
1117         struct fstioc_write wrthdr;
1118         struct fstioc_info info;
1119         unsigned long flags;
1120
1121         dbg ( DBG_IOCTL,"ioctl: %x, %p\n", cmd, ifr->ifr_data );
1122
1123         port = dev_to_port ( dev );
1124         card = port->card;
1125
1126         if ( !capable ( CAP_NET_ADMIN ))
1127                 return -EPERM;
1128
1129         switch ( cmd )
1130         {
1131         case FSTCPURESET:
1132                 fst_cpureset ( card );
1133                 card->state = FST_RESET;
1134                 return 0;
1135
1136         case FSTCPURELEASE:
1137                 fst_cpurelease ( card );
1138                 card->state = FST_STARTING;
1139                 return 0;
1140
1141         case FSTWRITE:                  /* Code write (download) */
1142
1143                 /* First copy in the header with the length and offset of data
1144                  * to write
1145                  */
1146                 if ( ifr->ifr_data == NULL )
1147                 {
1148                         return -EINVAL;
1149                 }
1150                 if ( copy_from_user ( &wrthdr, ifr->ifr_data,
1151                                         sizeof ( struct fstioc_write )))
1152                 {
1153                         return -EFAULT;
1154                 }
1155
1156                 /* Sanity check the parameters. We don't support partial writes
1157                  * when going over the top
1158                  */
1159                 if ( wrthdr.size > FST_MEMSIZE || wrthdr.offset > FST_MEMSIZE
1160                                 || wrthdr.size + wrthdr.offset > FST_MEMSIZE )
1161                 {
1162                         return -ENXIO;
1163                 }
1164
1165                 /* Now copy the data to the card.
1166                  * This will probably break on some architectures.
1167                  * I'll fix it when I have something to test on.
1168                  */
1169                 if ( copy_from_user ( card->mem + wrthdr.offset,
1170                                 ifr->ifr_data + sizeof ( struct fstioc_write ),
1171                                 wrthdr.size ))
1172                 {
1173                         return -EFAULT;
1174                 }
1175
1176                 /* Writes to the memory of a card in the reset state constitute
1177                  * a download
1178                  */
1179                 if ( card->state == FST_RESET )
1180                 {
1181                         card->state = FST_DOWNLOAD;
1182                 }
1183                 return 0;
1184
1185         case FSTGETCONF:
1186
1187                 /* If card has just been started check the shared memory config
1188                  * version and marker
1189                  */
1190                 if ( card->state == FST_STARTING )
1191                 {
1192                         check_started_ok ( card );
1193
1194                         /* If everything checked out enable card interrupts */
1195                         if ( card->state == FST_RUNNING )
1196                         {
1197                                 spin_lock_irqsave ( &card->card_lock, flags );
1198                                 fst_clear_intr ( card );
1199                                 FST_WRB ( card, interruptHandshake, 0xEE );
1200                                 spin_unlock_irqrestore ( &card->card_lock,
1201                                                                 flags );
1202                         }
1203                 }
1204
1205                 if ( ifr->ifr_data == NULL )
1206                 {
1207                         return -EINVAL;
1208                 }
1209
1210                 gather_conf_info ( card, port, &info );
1211
1212                 if ( copy_to_user ( ifr->ifr_data, &info, sizeof ( info )))
1213                 {
1214                         return -EFAULT;
1215                 }
1216                 return 0;
1217
1218         case FSTSETCONF:
1219
1220                 /* Most of the setting have been moved to the generic ioctls
1221                  * this just covers debug and board ident mode now
1222                  */
1223                 if ( copy_from_user ( &info,  ifr->ifr_data, sizeof ( info )))
1224                 {
1225                         return -EFAULT;
1226                 }
1227
1228                 return set_conf_from_info ( card, port, &info );
1229
1230         case SIOCWANDEV:
1231                 switch (ifr->ifr_settings.type)
1232                 {
1233                 case IF_GET_IFACE:
1234                         return fst_get_iface ( card, port, ifr );
1235
1236                 case IF_IFACE_SYNC_SERIAL:
1237                 case IF_IFACE_V35:
1238                 case IF_IFACE_V24:
1239                 case IF_IFACE_X21:
1240                         return fst_set_iface ( card, port, ifr );
1241
1242                 default:
1243                         return hdlc_ioctl ( dev, ifr, cmd );
1244                 }
1245
1246         default:
1247                 /* Not one of ours. Pass through to HDLC package */
1248                 return hdlc_ioctl ( dev, ifr, cmd );
1249         }
1250 }
1251
1252
1253 static void
1254 fst_openport ( struct fst_port_info *port )
1255 {
1256         int signals;
1257
1258         /* Only init things if card is actually running. This allows open to
1259          * succeed for downloads etc.
1260          */
1261         if ( port->card->state == FST_RUNNING )
1262         {
1263                 if ( port->run )
1264                 {
1265                         dbg ( DBG_OPEN,"open: found port already running\n");
1266
1267                         fst_issue_cmd ( port, STOPPORT );
1268                         port->run = 0;
1269                 }
1270
1271                 fst_rx_config ( port );
1272                 fst_tx_config ( port );
1273                 fst_op_raise ( port, OPSTS_RTS | OPSTS_DTR );
1274
1275                 fst_issue_cmd ( port, STARTPORT );
1276                 port->run = 1;
1277
1278                 signals = FST_RDL ( port->card, v24DebouncedSts[port->index]);
1279                 if ( signals & (( port->hwif == X21 ) ? IPSTS_INDICATE
1280                                                       : IPSTS_DCD ))
1281                         netif_carrier_on ( port_to_dev ( port ));
1282                 else
1283                         netif_carrier_off ( port_to_dev ( port ));
1284         }
1285 }
1286
1287 static void
1288 fst_closeport ( struct fst_port_info *port )
1289 {
1290         if ( port->card->state == FST_RUNNING )
1291         {
1292                 if ( port->run )
1293                 {
1294                         port->run = 0;
1295                         fst_op_lower ( port, OPSTS_RTS | OPSTS_DTR );
1296
1297                         fst_issue_cmd ( port, STOPPORT );
1298                 }
1299                 else
1300                 {
1301                         dbg ( DBG_OPEN,"close: port not running\n");
1302                 }
1303         }
1304 }
1305
1306
1307 static int
1308 fst_open ( struct net_device *dev )
1309 {
1310         int err;
1311
1312         err = hdlc_open ( dev_to_hdlc ( dev ));
1313         if ( err )
1314                 return err;
1315
1316         MOD_INC_USE_COUNT;
1317
1318         fst_openport ( dev_to_port ( dev ));
1319         netif_wake_queue ( dev );
1320         return 0;
1321 }
1322
1323 static int
1324 fst_close ( struct net_device *dev )
1325 {
1326         netif_stop_queue ( dev );
1327         fst_closeport ( dev_to_port ( dev ));
1328         hdlc_close ( dev_to_hdlc  ( dev ));
1329         MOD_DEC_USE_COUNT;
1330         return 0;
1331 }
1332
1333 static int
1334 fst_attach ( hdlc_device *hdlc, unsigned short encoding, unsigned short parity )
1335 {
1336         /* Setting currently fixed in FarSync card so we check and forget */
1337         if ( encoding != ENCODING_NRZ || parity != PARITY_CRC16_PR1_CCITT )
1338                 return -EINVAL;
1339         return 0;
1340 }
1341
1342
1343 static void
1344 fst_tx_timeout ( struct net_device *dev )
1345 {
1346         struct fst_port_info *port;
1347
1348         dbg ( DBG_INTR | DBG_TX,"tx_timeout\n");
1349
1350         port = dev_to_port ( dev );
1351
1352         port->hdlc.stats.tx_errors++;
1353         port->hdlc.stats.tx_aborted_errors++;
1354
1355         if ( port->txcnt > 0 )
1356                 fst_issue_cmd ( port, ABORTTX );
1357
1358         dev->trans_start = jiffies;
1359         netif_wake_queue ( dev );
1360 }
1361
1362
1363 static int
1364 fst_start_xmit ( struct sk_buff *skb, struct net_device *dev )
1365 {
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                 port->hdlc.stats.tx_errors++;
1381                 port->hdlc.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                 port->hdlc.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                 port->hdlc.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         port->hdlc.stats.tx_packets++;
1426         port->hdlc.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         struct net_device *dev;
1454
1455         /* We're working on a number of ports based on the card ID. If the
1456          * firmware detects something different later (should never happen)
1457          * we'll have to revise it in some way then.
1458          */
1459         for ( i = 0 ; i < card->nports ; i++ )
1460         {
1461                 card->ports[i].card   = card;
1462                 card->ports[i].index  = i;
1463                 card->ports[i].run    = 0;
1464
1465                 dev = hdlc_to_dev ( &card->ports[i].hdlc );
1466
1467                 /* Fill in the net device info */
1468                                 /* Since this is a PCI setup this is purely
1469                                  * informational. Give them the buffer addresses
1470                                  * and basic card I/O.
1471                                  */
1472                 dev->mem_start   = card->phys_mem
1473                                  + BUF_OFFSET ( txBuffer[i][0][0]);
1474                 dev->mem_end     = card->phys_mem
1475                                  + BUF_OFFSET ( txBuffer[i][NUM_TX_BUFFER][0]);
1476                 dev->base_addr   = card->pci_conf;
1477                 dev->irq         = card->irq;
1478
1479                 dev->tx_queue_len          = FST_TX_QUEUE_LEN;
1480                 dev->open                  = fst_open;
1481                 dev->stop                  = fst_close;
1482                 dev->do_ioctl              = fst_ioctl;
1483                 dev->watchdog_timeo        = FST_TX_TIMEOUT;
1484                 dev->tx_timeout            = fst_tx_timeout;
1485                 card->ports[i].hdlc.attach = fst_attach;
1486                 card->ports[i].hdlc.xmit   = fst_start_xmit;
1487
1488                 if (( err = register_hdlc_device ( &card->ports[i].hdlc )) < 0 )
1489                 {
1490                         printk_err ("Cannot register HDLC device for port %d"
1491                                     " (errno %d)\n", i, -err );
1492                         card->nports = i;
1493                         break;
1494                 }
1495         }
1496
1497         spin_lock_init ( &card->card_lock );
1498
1499         printk ( KERN_INFO "%s-%s: %s IRQ%d, %d ports\n",
1500                         hdlc_to_dev(&card->ports[0].hdlc)->name,
1501                         hdlc_to_dev(&card->ports[card->nports-1].hdlc)->name,
1502                         type_strings[card->type], card->irq, card->nports );
1503 }
1504
1505
1506 /*
1507  *      Initialise card when detected.
1508  *      Returns 0 to indicate success, or errno otherwise.
1509  */
1510 static int __devinit
1511 fst_add_one ( struct pci_dev *pdev, const struct pci_device_id *ent )
1512 {
1513         static int firsttime_done = 0;
1514         struct fst_card_info *card;
1515         int err = 0;
1516
1517         if ( ! firsttime_done )
1518         {
1519                 printk ( KERN_INFO "FarSync X21 driver " FST_USER_VERSION
1520                                 " (c) 2001 FarSite Communications Ltd.\n");
1521                 firsttime_done = 1;
1522         }
1523
1524         /* Allocate driver private data */
1525         card = kmalloc ( sizeof ( struct fst_card_info ),  GFP_KERNEL);
1526         if (card == NULL)
1527         {
1528                 printk_err ("FarSync card found but insufficient memory for"
1529                                 " driver storage\n");
1530                 return -ENOMEM;
1531         }
1532         memset ( card, 0, sizeof ( struct fst_card_info ));
1533
1534         /* Try to enable the device */
1535         if (( err = pci_enable_device ( pdev )) != 0 )
1536         {
1537                 printk_err ("Failed to enable card. Err %d\n", -err );
1538                 goto error_free_card;
1539         }
1540
1541         /* Record info we need*/
1542         card->irq         = pdev->irq;
1543         card->pci_conf    = pci_resource_start ( pdev, 1 );
1544         card->phys_mem    = pci_resource_start ( pdev, 2 );
1545         card->phys_ctlmem = pci_resource_start ( pdev, 3 );
1546
1547         card->type        = ent->driver_data;
1548         card->nports      = ( ent->driver_data == FST_TYPE_T2P ) ? 2 : 4;
1549
1550         card->state       = FST_UNINIT;
1551
1552         dbg ( DBG_PCI,"type %d nports %d irq %d\n", card->type,
1553                         card->nports, card->irq );
1554         dbg ( DBG_PCI,"conf %04x mem %08x ctlmem %08x\n",
1555                         card->pci_conf, card->phys_mem, card->phys_ctlmem );
1556
1557         /* Check we can get access to the memory and I/O regions */
1558         if ( ! request_region ( card->pci_conf, 0x80,"PLX config regs"))
1559         {
1560                 printk_err ("Unable to get config I/O @ 0x%04X\n",
1561                                                 card->pci_conf );
1562                 err = -ENODEV;
1563                 goto error_free_card;
1564         }
1565         if ( ! request_mem_region ( card->phys_mem, FST_MEMSIZE,"Shared RAM"))
1566         {
1567                 printk_err ("Unable to get main memory @ 0x%08X\n",
1568                                                 card->phys_mem );
1569                 err = -ENODEV;
1570                 goto error_release_io;
1571         }
1572         if ( ! request_mem_region ( card->phys_ctlmem, 0x10,"Control memory"))
1573         {
1574                 printk_err ("Unable to get control memory @ 0x%08X\n",
1575                                                 card->phys_ctlmem );
1576                 err = -ENODEV;
1577                 goto error_release_mem;
1578         }
1579
1580
1581         /* Get virtual addresses of memory regions */
1582         if (( card->mem = ioremap ( card->phys_mem, FST_MEMSIZE )) == NULL )
1583         {
1584                 printk_err ("Physical memory remap failed\n");
1585                 err = -ENODEV;
1586                 goto error_release_ctlmem;
1587         }
1588         if (( card->ctlmem = ioremap ( card->phys_ctlmem, 0x10 )) == NULL )
1589         {
1590                 printk_err ("Control memory remap failed\n");
1591                 err = -ENODEV;
1592                 goto error_unmap_mem;
1593         }
1594         dbg ( DBG_PCI,"kernel mem %p, ctlmem %p\n", card->mem, card->ctlmem);
1595
1596         /* Reset the card's processor */
1597         fst_cpureset ( card );
1598         card->state = FST_RESET;
1599
1600         /* Register the interrupt handler */
1601         if ( request_irq ( card->irq, fst_intr, SA_SHIRQ, FST_DEV_NAME, card ))
1602         {
1603
1604                 printk_err ("Unable to register interrupt %d\n", card->irq );
1605                 err = -ENODEV;
1606                 goto error_unmap_ctlmem;
1607         }
1608
1609         /* Record driver data for later use */
1610         pci_set_drvdata(pdev, card);
1611
1612         /* Remainder of card setup */
1613         fst_init_card ( card );
1614
1615         return 0;                       /* Success */
1616
1617
1618                                         /* Failure. Release resources */
1619 error_unmap_ctlmem:
1620         iounmap ( card->ctlmem );
1621
1622 error_unmap_mem:
1623         iounmap ( card->mem );
1624
1625 error_release_ctlmem:
1626         release_mem_region ( card->phys_ctlmem, 0x10 );
1627
1628 error_release_mem:
1629         release_mem_region ( card->phys_mem, FST_MEMSIZE );
1630
1631 error_release_io:
1632         release_region ( card->pci_conf, 0x80 );
1633
1634 error_free_card:
1635         kfree ( card );
1636         return err;
1637 }
1638
1639
1640 /*
1641  *      Cleanup and close down a card
1642  */
1643 static void __devexit
1644 fst_remove_one ( struct pci_dev *pdev )
1645 {
1646         struct fst_card_info *card;
1647         int i;
1648
1649         card = pci_get_drvdata(pdev);
1650
1651         for ( i = 0 ; i < card->nports ; i++ )
1652         {
1653                 unregister_hdlc_device ( &card->ports[i].hdlc );
1654         }
1655
1656         fst_disable_intr ( card );
1657         free_irq ( card->irq, card );
1658
1659         iounmap ( card->ctlmem );
1660         iounmap ( card->mem );
1661
1662         release_mem_region ( card->phys_ctlmem, 0x10 );
1663         release_mem_region ( card->phys_mem, FST_MEMSIZE );
1664         release_region ( card->pci_conf, 0x80 );
1665
1666         kfree ( card );
1667 }
1668
1669 static struct pci_driver fst_driver = {
1670         .name           = FST_NAME,
1671         .id_table       = fst_pci_dev_id,
1672         .probe          = fst_add_one,
1673         .remove = __devexit_p(fst_remove_one),
1674         .suspend        = NULL,
1675         .resume = NULL,
1676 };
1677
1678 static int __init
1679 fst_init(void)
1680 {
1681         return pci_module_init ( &fst_driver );
1682 }
1683
1684 static void __exit
1685 fst_cleanup_module(void)
1686 {
1687         pci_unregister_driver ( &fst_driver );
1688 }
1689
1690 module_init ( fst_init );
1691 module_exit ( fst_cleanup_module );
1692