WAN: convert drivers to use built-in netdev_stats
[linux-2.6.git] / drivers / char / synclinkmp.c
1 /*
2  * $Id: synclinkmp.c,v 4.38 2005/07/15 13:29:44 paulkf Exp $
3  *
4  * Device driver for Microgate SyncLink Multiport
5  * high speed multiprotocol serial adapter.
6  *
7  * written by Paul Fulghum for Microgate Corporation
8  * paulkf@microgate.com
9  *
10  * Microgate and SyncLink are trademarks of Microgate Corporation
11  *
12  * Derived from serial.c written by Theodore Ts'o and Linus Torvalds
13  * This code is released under the GNU General Public License (GPL)
14  *
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
16  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
19  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
23  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
25  * OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #define VERSION(ver,rel,seq) (((ver)<<16) | ((rel)<<8) | (seq))
29 #if defined(__i386__)
30 #  define BREAKPOINT() asm("   int $3");
31 #else
32 #  define BREAKPOINT() { }
33 #endif
34
35 #define MAX_DEVICES 12
36
37 #include <linux/module.h>
38 #include <linux/errno.h>
39 #include <linux/signal.h>
40 #include <linux/sched.h>
41 #include <linux/timer.h>
42 #include <linux/interrupt.h>
43 #include <linux/pci.h>
44 #include <linux/tty.h>
45 #include <linux/tty_flip.h>
46 #include <linux/serial.h>
47 #include <linux/major.h>
48 #include <linux/string.h>
49 #include <linux/fcntl.h>
50 #include <linux/ptrace.h>
51 #include <linux/ioport.h>
52 #include <linux/mm.h>
53 #include <linux/slab.h>
54 #include <linux/netdevice.h>
55 #include <linux/vmalloc.h>
56 #include <linux/init.h>
57 #include <linux/delay.h>
58 #include <linux/ioctl.h>
59
60 #include <asm/system.h>
61 #include <asm/io.h>
62 #include <asm/irq.h>
63 #include <asm/dma.h>
64 #include <linux/bitops.h>
65 #include <asm/types.h>
66 #include <linux/termios.h>
67 #include <linux/workqueue.h>
68 #include <linux/hdlc.h>
69 #include <linux/synclink.h>
70
71 #if defined(CONFIG_HDLC) || (defined(CONFIG_HDLC_MODULE) && defined(CONFIG_SYNCLINKMP_MODULE))
72 #define SYNCLINK_GENERIC_HDLC 1
73 #else
74 #define SYNCLINK_GENERIC_HDLC 0
75 #endif
76
77 #define GET_USER(error,value,addr) error = get_user(value,addr)
78 #define COPY_FROM_USER(error,dest,src,size) error = copy_from_user(dest,src,size) ? -EFAULT : 0
79 #define PUT_USER(error,value,addr) error = put_user(value,addr)
80 #define COPY_TO_USER(error,dest,src,size) error = copy_to_user(dest,src,size) ? -EFAULT : 0
81
82 #include <asm/uaccess.h>
83
84 static MGSL_PARAMS default_params = {
85         MGSL_MODE_HDLC,                 /* unsigned long mode */
86         0,                              /* unsigned char loopback; */
87         HDLC_FLAG_UNDERRUN_ABORT15,     /* unsigned short flags; */
88         HDLC_ENCODING_NRZI_SPACE,       /* unsigned char encoding; */
89         0,                              /* unsigned long clock_speed; */
90         0xff,                           /* unsigned char addr_filter; */
91         HDLC_CRC_16_CCITT,              /* unsigned short crc_type; */
92         HDLC_PREAMBLE_LENGTH_8BITS,     /* unsigned char preamble_length; */
93         HDLC_PREAMBLE_PATTERN_NONE,     /* unsigned char preamble; */
94         9600,                           /* unsigned long data_rate; */
95         8,                              /* unsigned char data_bits; */
96         1,                              /* unsigned char stop_bits; */
97         ASYNC_PARITY_NONE               /* unsigned char parity; */
98 };
99
100 /* size in bytes of DMA data buffers */
101 #define SCABUFSIZE      1024
102 #define SCA_MEM_SIZE    0x40000
103 #define SCA_BASE_SIZE   512
104 #define SCA_REG_SIZE    16
105 #define SCA_MAX_PORTS   4
106 #define SCAMAXDESC      128
107
108 #define BUFFERLISTSIZE  4096
109
110 /* SCA-I style DMA buffer descriptor */
111 typedef struct _SCADESC
112 {
113         u16     next;           /* lower l6 bits of next descriptor addr */
114         u16     buf_ptr;        /* lower 16 bits of buffer addr */
115         u8      buf_base;       /* upper 8 bits of buffer addr */
116         u8      pad1;
117         u16     length;         /* length of buffer */
118         u8      status;         /* status of buffer */
119         u8      pad2;
120 } SCADESC, *PSCADESC;
121
122 typedef struct _SCADESC_EX
123 {
124         /* device driver bookkeeping section */
125         char    *virt_addr;     /* virtual address of data buffer */
126         u16     phys_entry;     /* lower 16-bits of physical address of this descriptor */
127 } SCADESC_EX, *PSCADESC_EX;
128
129 /* The queue of BH actions to be performed */
130
131 #define BH_RECEIVE  1
132 #define BH_TRANSMIT 2
133 #define BH_STATUS   4
134
135 #define IO_PIN_SHUTDOWN_LIMIT 100
136
137 struct  _input_signal_events {
138         int     ri_up;
139         int     ri_down;
140         int     dsr_up;
141         int     dsr_down;
142         int     dcd_up;
143         int     dcd_down;
144         int     cts_up;
145         int     cts_down;
146 };
147
148 /*
149  * Device instance data structure
150  */
151 typedef struct _synclinkmp_info {
152         void *if_ptr;                           /* General purpose pointer (used by SPPP) */
153         int                     magic;
154         int                     flags;
155         int                     count;          /* count of opens */
156         int                     line;
157         unsigned short          close_delay;
158         unsigned short          closing_wait;   /* time to wait before closing */
159
160         struct mgsl_icount      icount;
161
162         struct tty_struct       *tty;
163         int                     timeout;
164         int                     x_char;         /* xon/xoff character */
165         int                     blocked_open;   /* # of blocked opens */
166         u16                     read_status_mask1;  /* break detection (SR1 indications) */
167         u16                     read_status_mask2;  /* parity/framing/overun (SR2 indications) */
168         unsigned char           ignore_status_mask1;  /* break detection (SR1 indications) */
169         unsigned char           ignore_status_mask2;  /* parity/framing/overun (SR2 indications) */
170         unsigned char           *tx_buf;
171         int                     tx_put;
172         int                     tx_get;
173         int                     tx_count;
174
175         wait_queue_head_t       open_wait;
176         wait_queue_head_t       close_wait;
177
178         wait_queue_head_t       status_event_wait_q;
179         wait_queue_head_t       event_wait_q;
180         struct timer_list       tx_timer;       /* HDLC transmit timeout timer */
181         struct _synclinkmp_info *next_device;   /* device list link */
182         struct timer_list       status_timer;   /* input signal status check timer */
183
184         spinlock_t lock;                /* spinlock for synchronizing with ISR */
185         struct work_struct task;                        /* task structure for scheduling bh */
186
187         u32 max_frame_size;                     /* as set by device config */
188
189         u32 pending_bh;
190
191         bool bh_running;                                /* Protection from multiple */
192         int isr_overflow;
193         bool bh_requested;
194
195         int dcd_chkcount;                       /* check counts to prevent */
196         int cts_chkcount;                       /* too many IRQs if a signal */
197         int dsr_chkcount;                       /* is floating */
198         int ri_chkcount;
199
200         char *buffer_list;                      /* virtual address of Rx & Tx buffer lists */
201         unsigned long buffer_list_phys;
202
203         unsigned int rx_buf_count;              /* count of total allocated Rx buffers */
204         SCADESC *rx_buf_list;                   /* list of receive buffer entries */
205         SCADESC_EX rx_buf_list_ex[SCAMAXDESC]; /* list of receive buffer entries */
206         unsigned int current_rx_buf;
207
208         unsigned int tx_buf_count;              /* count of total allocated Tx buffers */
209         SCADESC *tx_buf_list;           /* list of transmit buffer entries */
210         SCADESC_EX tx_buf_list_ex[SCAMAXDESC]; /* list of transmit buffer entries */
211         unsigned int last_tx_buf;
212
213         unsigned char *tmp_rx_buf;
214         unsigned int tmp_rx_buf_count;
215
216         bool rx_enabled;
217         bool rx_overflow;
218
219         bool tx_enabled;
220         bool tx_active;
221         u32 idle_mode;
222
223         unsigned char ie0_value;
224         unsigned char ie1_value;
225         unsigned char ie2_value;
226         unsigned char ctrlreg_value;
227         unsigned char old_signals;
228
229         char device_name[25];                   /* device instance name */
230
231         int port_count;
232         int adapter_num;
233         int port_num;
234
235         struct _synclinkmp_info *port_array[SCA_MAX_PORTS];
236
237         unsigned int bus_type;                  /* expansion bus type (ISA,EISA,PCI) */
238
239         unsigned int irq_level;                 /* interrupt level */
240         unsigned long irq_flags;
241         bool irq_requested;                     /* true if IRQ requested */
242
243         MGSL_PARAMS params;                     /* communications parameters */
244
245         unsigned char serial_signals;           /* current serial signal states */
246
247         bool irq_occurred;                      /* for diagnostics use */
248         unsigned int init_error;                /* Initialization startup error */
249
250         u32 last_mem_alloc;
251         unsigned char* memory_base;             /* shared memory address (PCI only) */
252         u32 phys_memory_base;
253         int shared_mem_requested;
254
255         unsigned char* sca_base;                /* HD64570 SCA Memory address */
256         u32 phys_sca_base;
257         u32 sca_offset;
258         bool sca_base_requested;
259
260         unsigned char* lcr_base;                /* local config registers (PCI only) */
261         u32 phys_lcr_base;
262         u32 lcr_offset;
263         int lcr_mem_requested;
264
265         unsigned char* statctrl_base;           /* status/control register memory */
266         u32 phys_statctrl_base;
267         u32 statctrl_offset;
268         bool sca_statctrl_requested;
269
270         u32 misc_ctrl_value;
271         char flag_buf[MAX_ASYNC_BUFFER_SIZE];
272         char char_buf[MAX_ASYNC_BUFFER_SIZE];
273         bool drop_rts_on_tx_done;
274
275         struct  _input_signal_events    input_signal_events;
276
277         /* SPPP/Cisco HDLC device parts */
278         int netcount;
279         int dosyncppp;
280         spinlock_t netlock;
281
282 #if SYNCLINK_GENERIC_HDLC
283         struct net_device *netdev;
284 #endif
285
286 } SLMP_INFO;
287
288 #define MGSL_MAGIC 0x5401
289
290 /*
291  * define serial signal status change macros
292  */
293 #define MISCSTATUS_DCD_LATCHED  (SerialSignal_DCD<<8)   /* indicates change in DCD */
294 #define MISCSTATUS_RI_LATCHED   (SerialSignal_RI<<8)    /* indicates change in RI */
295 #define MISCSTATUS_CTS_LATCHED  (SerialSignal_CTS<<8)   /* indicates change in CTS */
296 #define MISCSTATUS_DSR_LATCHED  (SerialSignal_DSR<<8)   /* change in DSR */
297
298 /* Common Register macros */
299 #define LPR     0x00
300 #define PABR0   0x02
301 #define PABR1   0x03
302 #define WCRL    0x04
303 #define WCRM    0x05
304 #define WCRH    0x06
305 #define DPCR    0x08
306 #define DMER    0x09
307 #define ISR0    0x10
308 #define ISR1    0x11
309 #define ISR2    0x12
310 #define IER0    0x14
311 #define IER1    0x15
312 #define IER2    0x16
313 #define ITCR    0x18
314 #define INTVR   0x1a
315 #define IMVR    0x1c
316
317 /* MSCI Register macros */
318 #define TRB     0x20
319 #define TRBL    0x20
320 #define TRBH    0x21
321 #define SR0     0x22
322 #define SR1     0x23
323 #define SR2     0x24
324 #define SR3     0x25
325 #define FST     0x26
326 #define IE0     0x28
327 #define IE1     0x29
328 #define IE2     0x2a
329 #define FIE     0x2b
330 #define CMD     0x2c
331 #define MD0     0x2e
332 #define MD1     0x2f
333 #define MD2     0x30
334 #define CTL     0x31
335 #define SA0     0x32
336 #define SA1     0x33
337 #define IDL     0x34
338 #define TMC     0x35
339 #define RXS     0x36
340 #define TXS     0x37
341 #define TRC0    0x38
342 #define TRC1    0x39
343 #define RRC     0x3a
344 #define CST0    0x3c
345 #define CST1    0x3d
346
347 /* Timer Register Macros */
348 #define TCNT    0x60
349 #define TCNTL   0x60
350 #define TCNTH   0x61
351 #define TCONR   0x62
352 #define TCONRL  0x62
353 #define TCONRH  0x63
354 #define TMCS    0x64
355 #define TEPR    0x65
356
357 /* DMA Controller Register macros */
358 #define DARL    0x80
359 #define DARH    0x81
360 #define DARB    0x82
361 #define BAR     0x80
362 #define BARL    0x80
363 #define BARH    0x81
364 #define BARB    0x82
365 #define SAR     0x84
366 #define SARL    0x84
367 #define SARH    0x85
368 #define SARB    0x86
369 #define CPB     0x86
370 #define CDA     0x88
371 #define CDAL    0x88
372 #define CDAH    0x89
373 #define EDA     0x8a
374 #define EDAL    0x8a
375 #define EDAH    0x8b
376 #define BFL     0x8c
377 #define BFLL    0x8c
378 #define BFLH    0x8d
379 #define BCR     0x8e
380 #define BCRL    0x8e
381 #define BCRH    0x8f
382 #define DSR     0x90
383 #define DMR     0x91
384 #define FCT     0x93
385 #define DIR     0x94
386 #define DCMD    0x95
387
388 /* combine with timer or DMA register address */
389 #define TIMER0  0x00
390 #define TIMER1  0x08
391 #define TIMER2  0x10
392 #define TIMER3  0x18
393 #define RXDMA   0x00
394 #define TXDMA   0x20
395
396 /* SCA Command Codes */
397 #define NOOP            0x00
398 #define TXRESET         0x01
399 #define TXENABLE        0x02
400 #define TXDISABLE       0x03
401 #define TXCRCINIT       0x04
402 #define TXCRCEXCL       0x05
403 #define TXEOM           0x06
404 #define TXABORT         0x07
405 #define MPON            0x08
406 #define TXBUFCLR        0x09
407 #define RXRESET         0x11
408 #define RXENABLE        0x12
409 #define RXDISABLE       0x13
410 #define RXCRCINIT       0x14
411 #define RXREJECT        0x15
412 #define SEARCHMP        0x16
413 #define RXCRCEXCL       0x17
414 #define RXCRCCALC       0x18
415 #define CHRESET         0x21
416 #define HUNT            0x31
417
418 /* DMA command codes */
419 #define SWABORT         0x01
420 #define FEICLEAR        0x02
421
422 /* IE0 */
423 #define TXINTE          BIT7
424 #define RXINTE          BIT6
425 #define TXRDYE          BIT1
426 #define RXRDYE          BIT0
427
428 /* IE1 & SR1 */
429 #define UDRN    BIT7
430 #define IDLE    BIT6
431 #define SYNCD   BIT4
432 #define FLGD    BIT4
433 #define CCTS    BIT3
434 #define CDCD    BIT2
435 #define BRKD    BIT1
436 #define ABTD    BIT1
437 #define GAPD    BIT1
438 #define BRKE    BIT0
439 #define IDLD    BIT0
440
441 /* IE2 & SR2 */
442 #define EOM     BIT7
443 #define PMP     BIT6
444 #define SHRT    BIT6
445 #define PE      BIT5
446 #define ABT     BIT5
447 #define FRME    BIT4
448 #define RBIT    BIT4
449 #define OVRN    BIT3
450 #define CRCE    BIT2
451
452
453 /*
454  * Global linked list of SyncLink devices
455  */
456 static SLMP_INFO *synclinkmp_device_list = NULL;
457 static int synclinkmp_adapter_count = -1;
458 static int synclinkmp_device_count = 0;
459
460 /*
461  * Set this param to non-zero to load eax with the
462  * .text section address and breakpoint on module load.
463  * This is useful for use with gdb and add-symbol-file command.
464  */
465 static int break_on_load=0;
466
467 /*
468  * Driver major number, defaults to zero to get auto
469  * assigned major number. May be forced as module parameter.
470  */
471 static int ttymajor=0;
472
473 /*
474  * Array of user specified options for ISA adapters.
475  */
476 static int debug_level = 0;
477 static int maxframe[MAX_DEVICES] = {0,};
478 static int dosyncppp[MAX_DEVICES] = {0,};
479
480 module_param(break_on_load, bool, 0);
481 module_param(ttymajor, int, 0);
482 module_param(debug_level, int, 0);
483 module_param_array(maxframe, int, NULL, 0);
484 module_param_array(dosyncppp, int, NULL, 0);
485
486 static char *driver_name = "SyncLink MultiPort driver";
487 static char *driver_version = "$Revision: 4.38 $";
488
489 static int synclinkmp_init_one(struct pci_dev *dev,const struct pci_device_id *ent);
490 static void synclinkmp_remove_one(struct pci_dev *dev);
491
492 static struct pci_device_id synclinkmp_pci_tbl[] = {
493         { PCI_VENDOR_ID_MICROGATE, PCI_DEVICE_ID_MICROGATE_SCA, PCI_ANY_ID, PCI_ANY_ID, },
494         { 0, }, /* terminate list */
495 };
496 MODULE_DEVICE_TABLE(pci, synclinkmp_pci_tbl);
497
498 MODULE_LICENSE("GPL");
499
500 static struct pci_driver synclinkmp_pci_driver = {
501         .name           = "synclinkmp",
502         .id_table       = synclinkmp_pci_tbl,
503         .probe          = synclinkmp_init_one,
504         .remove         = __devexit_p(synclinkmp_remove_one),
505 };
506
507
508 static struct tty_driver *serial_driver;
509
510 /* number of characters left in xmit buffer before we ask for more */
511 #define WAKEUP_CHARS 256
512
513
514 /* tty callbacks */
515
516 static int  open(struct tty_struct *tty, struct file * filp);
517 static void close(struct tty_struct *tty, struct file * filp);
518 static void hangup(struct tty_struct *tty);
519 static void set_termios(struct tty_struct *tty, struct ktermios *old_termios);
520
521 static int  write(struct tty_struct *tty, const unsigned char *buf, int count);
522 static int put_char(struct tty_struct *tty, unsigned char ch);
523 static void send_xchar(struct tty_struct *tty, char ch);
524 static void wait_until_sent(struct tty_struct *tty, int timeout);
525 static int  write_room(struct tty_struct *tty);
526 static void flush_chars(struct tty_struct *tty);
527 static void flush_buffer(struct tty_struct *tty);
528 static void tx_hold(struct tty_struct *tty);
529 static void tx_release(struct tty_struct *tty);
530
531 static int  ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg);
532 static int  read_proc(char *page, char **start, off_t off, int count,int *eof, void *data);
533 static int  chars_in_buffer(struct tty_struct *tty);
534 static void throttle(struct tty_struct * tty);
535 static void unthrottle(struct tty_struct * tty);
536 static void set_break(struct tty_struct *tty, int break_state);
537
538 #if SYNCLINK_GENERIC_HDLC
539 #define dev_to_port(D) (dev_to_hdlc(D)->priv)
540 static void hdlcdev_tx_done(SLMP_INFO *info);
541 static void hdlcdev_rx(SLMP_INFO *info, char *buf, int size);
542 static int  hdlcdev_init(SLMP_INFO *info);
543 static void hdlcdev_exit(SLMP_INFO *info);
544 #endif
545
546 /* ioctl handlers */
547
548 static int  get_stats(SLMP_INFO *info, struct mgsl_icount __user *user_icount);
549 static int  get_params(SLMP_INFO *info, MGSL_PARAMS __user *params);
550 static int  set_params(SLMP_INFO *info, MGSL_PARAMS __user *params);
551 static int  get_txidle(SLMP_INFO *info, int __user *idle_mode);
552 static int  set_txidle(SLMP_INFO *info, int idle_mode);
553 static int  tx_enable(SLMP_INFO *info, int enable);
554 static int  tx_abort(SLMP_INFO *info);
555 static int  rx_enable(SLMP_INFO *info, int enable);
556 static int  modem_input_wait(SLMP_INFO *info,int arg);
557 static int  wait_mgsl_event(SLMP_INFO *info, int __user *mask_ptr);
558 static int  tiocmget(struct tty_struct *tty, struct file *file);
559 static int  tiocmset(struct tty_struct *tty, struct file *file,
560                      unsigned int set, unsigned int clear);
561 static void set_break(struct tty_struct *tty, int break_state);
562
563 static void add_device(SLMP_INFO *info);
564 static void device_init(int adapter_num, struct pci_dev *pdev);
565 static int  claim_resources(SLMP_INFO *info);
566 static void release_resources(SLMP_INFO *info);
567
568 static int  startup(SLMP_INFO *info);
569 static int  block_til_ready(struct tty_struct *tty, struct file * filp,SLMP_INFO *info);
570 static void shutdown(SLMP_INFO *info);
571 static void program_hw(SLMP_INFO *info);
572 static void change_params(SLMP_INFO *info);
573
574 static bool init_adapter(SLMP_INFO *info);
575 static bool register_test(SLMP_INFO *info);
576 static bool irq_test(SLMP_INFO *info);
577 static bool loopback_test(SLMP_INFO *info);
578 static int  adapter_test(SLMP_INFO *info);
579 static bool memory_test(SLMP_INFO *info);
580
581 static void reset_adapter(SLMP_INFO *info);
582 static void reset_port(SLMP_INFO *info);
583 static void async_mode(SLMP_INFO *info);
584 static void hdlc_mode(SLMP_INFO *info);
585
586 static void rx_stop(SLMP_INFO *info);
587 static void rx_start(SLMP_INFO *info);
588 static void rx_reset_buffers(SLMP_INFO *info);
589 static void rx_free_frame_buffers(SLMP_INFO *info, unsigned int first, unsigned int last);
590 static bool rx_get_frame(SLMP_INFO *info);
591
592 static void tx_start(SLMP_INFO *info);
593 static void tx_stop(SLMP_INFO *info);
594 static void tx_load_fifo(SLMP_INFO *info);
595 static void tx_set_idle(SLMP_INFO *info);
596 static void tx_load_dma_buffer(SLMP_INFO *info, const char *buf, unsigned int count);
597
598 static void get_signals(SLMP_INFO *info);
599 static void set_signals(SLMP_INFO *info);
600 static void enable_loopback(SLMP_INFO *info, int enable);
601 static void set_rate(SLMP_INFO *info, u32 data_rate);
602
603 static int  bh_action(SLMP_INFO *info);
604 static void bh_handler(struct work_struct *work);
605 static void bh_receive(SLMP_INFO *info);
606 static void bh_transmit(SLMP_INFO *info);
607 static void bh_status(SLMP_INFO *info);
608 static void isr_timer(SLMP_INFO *info);
609 static void isr_rxint(SLMP_INFO *info);
610 static void isr_rxrdy(SLMP_INFO *info);
611 static void isr_txint(SLMP_INFO *info);
612 static void isr_txrdy(SLMP_INFO *info);
613 static void isr_rxdmaok(SLMP_INFO *info);
614 static void isr_rxdmaerror(SLMP_INFO *info);
615 static void isr_txdmaok(SLMP_INFO *info);
616 static void isr_txdmaerror(SLMP_INFO *info);
617 static void isr_io_pin(SLMP_INFO *info, u16 status);
618
619 static int  alloc_dma_bufs(SLMP_INFO *info);
620 static void free_dma_bufs(SLMP_INFO *info);
621 static int  alloc_buf_list(SLMP_INFO *info);
622 static int  alloc_frame_bufs(SLMP_INFO *info, SCADESC *list, SCADESC_EX *list_ex,int count);
623 static int  alloc_tmp_rx_buf(SLMP_INFO *info);
624 static void free_tmp_rx_buf(SLMP_INFO *info);
625
626 static void load_pci_memory(SLMP_INFO *info, char* dest, const char* src, unsigned short count);
627 static void trace_block(SLMP_INFO *info, const char* data, int count, int xmit);
628 static void tx_timeout(unsigned long context);
629 static void status_timeout(unsigned long context);
630
631 static unsigned char read_reg(SLMP_INFO *info, unsigned char addr);
632 static void write_reg(SLMP_INFO *info, unsigned char addr, unsigned char val);
633 static u16 read_reg16(SLMP_INFO *info, unsigned char addr);
634 static void write_reg16(SLMP_INFO *info, unsigned char addr, u16 val);
635 static unsigned char read_status_reg(SLMP_INFO * info);
636 static void write_control_reg(SLMP_INFO * info);
637
638
639 static unsigned char rx_active_fifo_level = 16; // rx request FIFO activation level in bytes
640 static unsigned char tx_active_fifo_level = 16; // tx request FIFO activation level in bytes
641 static unsigned char tx_negate_fifo_level = 32; // tx request FIFO negation level in bytes
642
643 static u32 misc_ctrl_value = 0x007e4040;
644 static u32 lcr1_brdr_value = 0x00800028;
645
646 static u32 read_ahead_count = 8;
647
648 /* DPCR, DMA Priority Control
649  *
650  * 07..05  Not used, must be 0
651  * 04      BRC, bus release condition: 0=all transfers complete
652  *              1=release after 1 xfer on all channels
653  * 03      CCC, channel change condition: 0=every cycle
654  *              1=after each channel completes all xfers
655  * 02..00  PR<2..0>, priority 100=round robin
656  *
657  * 00000100 = 0x00
658  */
659 static unsigned char dma_priority = 0x04;
660
661 // Number of bytes that can be written to shared RAM
662 // in a single write operation
663 static u32 sca_pci_load_interval = 64;
664
665 /*
666  * 1st function defined in .text section. Calling this function in
667  * init_module() followed by a breakpoint allows a remote debugger
668  * (gdb) to get the .text address for the add-symbol-file command.
669  * This allows remote debugging of dynamically loadable modules.
670  */
671 static void* synclinkmp_get_text_ptr(void);
672 static void* synclinkmp_get_text_ptr(void) {return synclinkmp_get_text_ptr;}
673
674 static inline int sanity_check(SLMP_INFO *info,
675                                char *name, const char *routine)
676 {
677 #ifdef SANITY_CHECK
678         static const char *badmagic =
679                 "Warning: bad magic number for synclinkmp_struct (%s) in %s\n";
680         static const char *badinfo =
681                 "Warning: null synclinkmp_struct for (%s) in %s\n";
682
683         if (!info) {
684                 printk(badinfo, name, routine);
685                 return 1;
686         }
687         if (info->magic != MGSL_MAGIC) {
688                 printk(badmagic, name, routine);
689                 return 1;
690         }
691 #else
692         if (!info)
693                 return 1;
694 #endif
695         return 0;
696 }
697
698 /**
699  * line discipline callback wrappers
700  *
701  * The wrappers maintain line discipline references
702  * while calling into the line discipline.
703  *
704  * ldisc_receive_buf  - pass receive data to line discipline
705  */
706
707 static void ldisc_receive_buf(struct tty_struct *tty,
708                               const __u8 *data, char *flags, int count)
709 {
710         struct tty_ldisc *ld;
711         if (!tty)
712                 return;
713         ld = tty_ldisc_ref(tty);
714         if (ld) {
715                 if (ld->receive_buf)
716                         ld->receive_buf(tty, data, flags, count);
717                 tty_ldisc_deref(ld);
718         }
719 }
720
721 /* tty callbacks */
722
723 /* Called when a port is opened.  Init and enable port.
724  */
725 static int open(struct tty_struct *tty, struct file *filp)
726 {
727         SLMP_INFO *info;
728         int retval, line;
729         unsigned long flags;
730
731         line = tty->index;
732         if ((line < 0) || (line >= synclinkmp_device_count)) {
733                 printk("%s(%d): open with invalid line #%d.\n",
734                         __FILE__,__LINE__,line);
735                 return -ENODEV;
736         }
737
738         info = synclinkmp_device_list;
739         while(info && info->line != line)
740                 info = info->next_device;
741         if (sanity_check(info, tty->name, "open"))
742                 return -ENODEV;
743         if ( info->init_error ) {
744                 printk("%s(%d):%s device is not allocated, init error=%d\n",
745                         __FILE__,__LINE__,info->device_name,info->init_error);
746                 return -ENODEV;
747         }
748
749         tty->driver_data = info;
750         info->tty = tty;
751
752         if (debug_level >= DEBUG_LEVEL_INFO)
753                 printk("%s(%d):%s open(), old ref count = %d\n",
754                          __FILE__,__LINE__,tty->driver->name, info->count);
755
756         /* If port is closing, signal caller to try again */
757         if (tty_hung_up_p(filp) || info->flags & ASYNC_CLOSING){
758                 if (info->flags & ASYNC_CLOSING)
759                         interruptible_sleep_on(&info->close_wait);
760                 retval = ((info->flags & ASYNC_HUP_NOTIFY) ?
761                         -EAGAIN : -ERESTARTSYS);
762                 goto cleanup;
763         }
764
765         info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
766
767         spin_lock_irqsave(&info->netlock, flags);
768         if (info->netcount) {
769                 retval = -EBUSY;
770                 spin_unlock_irqrestore(&info->netlock, flags);
771                 goto cleanup;
772         }
773         info->count++;
774         spin_unlock_irqrestore(&info->netlock, flags);
775
776         if (info->count == 1) {
777                 /* 1st open on this device, init hardware */
778                 retval = startup(info);
779                 if (retval < 0)
780                         goto cleanup;
781         }
782
783         retval = block_til_ready(tty, filp, info);
784         if (retval) {
785                 if (debug_level >= DEBUG_LEVEL_INFO)
786                         printk("%s(%d):%s block_til_ready() returned %d\n",
787                                  __FILE__,__LINE__, info->device_name, retval);
788                 goto cleanup;
789         }
790
791         if (debug_level >= DEBUG_LEVEL_INFO)
792                 printk("%s(%d):%s open() success\n",
793                          __FILE__,__LINE__, info->device_name);
794         retval = 0;
795
796 cleanup:
797         if (retval) {
798                 if (tty->count == 1)
799                         info->tty = NULL; /* tty layer will release tty struct */
800                 if(info->count)
801                         info->count--;
802         }
803
804         return retval;
805 }
806
807 /* Called when port is closed. Wait for remaining data to be
808  * sent. Disable port and free resources.
809  */
810 static void close(struct tty_struct *tty, struct file *filp)
811 {
812         SLMP_INFO * info = (SLMP_INFO *)tty->driver_data;
813
814         if (sanity_check(info, tty->name, "close"))
815                 return;
816
817         if (debug_level >= DEBUG_LEVEL_INFO)
818                 printk("%s(%d):%s close() entry, count=%d\n",
819                          __FILE__,__LINE__, info->device_name, info->count);
820
821         if (!info->count)
822                 return;
823
824         if (tty_hung_up_p(filp))
825                 goto cleanup;
826
827         if ((tty->count == 1) && (info->count != 1)) {
828                 /*
829                  * tty->count is 1 and the tty structure will be freed.
830                  * info->count should be one in this case.
831                  * if it's not, correct it so that the port is shutdown.
832                  */
833                 printk("%s(%d):%s close: bad refcount; tty->count is 1, "
834                        "info->count is %d\n",
835                          __FILE__,__LINE__, info->device_name, info->count);
836                 info->count = 1;
837         }
838
839         info->count--;
840
841         /* if at least one open remaining, leave hardware active */
842         if (info->count)
843                 goto cleanup;
844
845         info->flags |= ASYNC_CLOSING;
846
847         /* set tty->closing to notify line discipline to
848          * only process XON/XOFF characters. Only the N_TTY
849          * discipline appears to use this (ppp does not).
850          */
851         tty->closing = 1;
852
853         /* wait for transmit data to clear all layers */
854
855         if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) {
856                 if (debug_level >= DEBUG_LEVEL_INFO)
857                         printk("%s(%d):%s close() calling tty_wait_until_sent\n",
858                                  __FILE__,__LINE__, info->device_name );
859                 tty_wait_until_sent(tty, info->closing_wait);
860         }
861
862         if (info->flags & ASYNC_INITIALIZED)
863                 wait_until_sent(tty, info->timeout);
864
865         flush_buffer(tty);
866
867         tty_ldisc_flush(tty);
868
869         shutdown(info);
870
871         tty->closing = 0;
872         info->tty = NULL;
873
874         if (info->blocked_open) {
875                 if (info->close_delay) {
876                         msleep_interruptible(jiffies_to_msecs(info->close_delay));
877                 }
878                 wake_up_interruptible(&info->open_wait);
879         }
880
881         info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
882
883         wake_up_interruptible(&info->close_wait);
884
885 cleanup:
886         if (debug_level >= DEBUG_LEVEL_INFO)
887                 printk("%s(%d):%s close() exit, count=%d\n", __FILE__,__LINE__,
888                         tty->driver->name, info->count);
889 }
890
891 /* Called by tty_hangup() when a hangup is signaled.
892  * This is the same as closing all open descriptors for the port.
893  */
894 static void hangup(struct tty_struct *tty)
895 {
896         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
897
898         if (debug_level >= DEBUG_LEVEL_INFO)
899                 printk("%s(%d):%s hangup()\n",
900                          __FILE__,__LINE__, info->device_name );
901
902         if (sanity_check(info, tty->name, "hangup"))
903                 return;
904
905         flush_buffer(tty);
906         shutdown(info);
907
908         info->count = 0;
909         info->flags &= ~ASYNC_NORMAL_ACTIVE;
910         info->tty = NULL;
911
912         wake_up_interruptible(&info->open_wait);
913 }
914
915 /* Set new termios settings
916  */
917 static void set_termios(struct tty_struct *tty, struct ktermios *old_termios)
918 {
919         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
920         unsigned long flags;
921
922         if (debug_level >= DEBUG_LEVEL_INFO)
923                 printk("%s(%d):%s set_termios()\n", __FILE__,__LINE__,
924                         tty->driver->name );
925
926         change_params(info);
927
928         /* Handle transition to B0 status */
929         if (old_termios->c_cflag & CBAUD &&
930             !(tty->termios->c_cflag & CBAUD)) {
931                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
932                 spin_lock_irqsave(&info->lock,flags);
933                 set_signals(info);
934                 spin_unlock_irqrestore(&info->lock,flags);
935         }
936
937         /* Handle transition away from B0 status */
938         if (!(old_termios->c_cflag & CBAUD) &&
939             tty->termios->c_cflag & CBAUD) {
940                 info->serial_signals |= SerialSignal_DTR;
941                 if (!(tty->termios->c_cflag & CRTSCTS) ||
942                     !test_bit(TTY_THROTTLED, &tty->flags)) {
943                         info->serial_signals |= SerialSignal_RTS;
944                 }
945                 spin_lock_irqsave(&info->lock,flags);
946                 set_signals(info);
947                 spin_unlock_irqrestore(&info->lock,flags);
948         }
949
950         /* Handle turning off CRTSCTS */
951         if (old_termios->c_cflag & CRTSCTS &&
952             !(tty->termios->c_cflag & CRTSCTS)) {
953                 tty->hw_stopped = 0;
954                 tx_release(tty);
955         }
956 }
957
958 /* Send a block of data
959  *
960  * Arguments:
961  *
962  *      tty             pointer to tty information structure
963  *      buf             pointer to buffer containing send data
964  *      count           size of send data in bytes
965  *
966  * Return Value:        number of characters written
967  */
968 static int write(struct tty_struct *tty,
969                  const unsigned char *buf, int count)
970 {
971         int     c, ret = 0;
972         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
973         unsigned long flags;
974
975         if (debug_level >= DEBUG_LEVEL_INFO)
976                 printk("%s(%d):%s write() count=%d\n",
977                        __FILE__,__LINE__,info->device_name,count);
978
979         if (sanity_check(info, tty->name, "write"))
980                 goto cleanup;
981
982         if (!info->tx_buf)
983                 goto cleanup;
984
985         if (info->params.mode == MGSL_MODE_HDLC) {
986                 if (count > info->max_frame_size) {
987                         ret = -EIO;
988                         goto cleanup;
989                 }
990                 if (info->tx_active)
991                         goto cleanup;
992                 if (info->tx_count) {
993                         /* send accumulated data from send_char() calls */
994                         /* as frame and wait before accepting more data. */
995                         tx_load_dma_buffer(info, info->tx_buf, info->tx_count);
996                         goto start;
997                 }
998                 ret = info->tx_count = count;
999                 tx_load_dma_buffer(info, buf, count);
1000                 goto start;
1001         }
1002
1003         for (;;) {
1004                 c = min_t(int, count,
1005                         min(info->max_frame_size - info->tx_count - 1,
1006                             info->max_frame_size - info->tx_put));
1007                 if (c <= 0)
1008                         break;
1009                         
1010                 memcpy(info->tx_buf + info->tx_put, buf, c);
1011
1012                 spin_lock_irqsave(&info->lock,flags);
1013                 info->tx_put += c;
1014                 if (info->tx_put >= info->max_frame_size)
1015                         info->tx_put -= info->max_frame_size;
1016                 info->tx_count += c;
1017                 spin_unlock_irqrestore(&info->lock,flags);
1018
1019                 buf += c;
1020                 count -= c;
1021                 ret += c;
1022         }
1023
1024         if (info->params.mode == MGSL_MODE_HDLC) {
1025                 if (count) {
1026                         ret = info->tx_count = 0;
1027                         goto cleanup;
1028                 }
1029                 tx_load_dma_buffer(info, info->tx_buf, info->tx_count);
1030         }
1031 start:
1032         if (info->tx_count && !tty->stopped && !tty->hw_stopped) {
1033                 spin_lock_irqsave(&info->lock,flags);
1034                 if (!info->tx_active)
1035                         tx_start(info);
1036                 spin_unlock_irqrestore(&info->lock,flags);
1037         }
1038
1039 cleanup:
1040         if (debug_level >= DEBUG_LEVEL_INFO)
1041                 printk( "%s(%d):%s write() returning=%d\n",
1042                         __FILE__,__LINE__,info->device_name,ret);
1043         return ret;
1044 }
1045
1046 /* Add a character to the transmit buffer.
1047  */
1048 static int put_char(struct tty_struct *tty, unsigned char ch)
1049 {
1050         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1051         unsigned long flags;
1052         int ret = 0;
1053
1054         if ( debug_level >= DEBUG_LEVEL_INFO ) {
1055                 printk( "%s(%d):%s put_char(%d)\n",
1056                         __FILE__,__LINE__,info->device_name,ch);
1057         }
1058
1059         if (sanity_check(info, tty->name, "put_char"))
1060                 return 0;
1061
1062         if (!info->tx_buf)
1063                 return 0;
1064
1065         spin_lock_irqsave(&info->lock,flags);
1066
1067         if ( (info->params.mode != MGSL_MODE_HDLC) ||
1068              !info->tx_active ) {
1069
1070                 if (info->tx_count < info->max_frame_size - 1) {
1071                         info->tx_buf[info->tx_put++] = ch;
1072                         if (info->tx_put >= info->max_frame_size)
1073                                 info->tx_put -= info->max_frame_size;
1074                         info->tx_count++;
1075                         ret = 1;
1076                 }
1077         }
1078
1079         spin_unlock_irqrestore(&info->lock,flags);
1080         return ret;
1081 }
1082
1083 /* Send a high-priority XON/XOFF character
1084  */
1085 static void send_xchar(struct tty_struct *tty, char ch)
1086 {
1087         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1088         unsigned long flags;
1089
1090         if (debug_level >= DEBUG_LEVEL_INFO)
1091                 printk("%s(%d):%s send_xchar(%d)\n",
1092                          __FILE__,__LINE__, info->device_name, ch );
1093
1094         if (sanity_check(info, tty->name, "send_xchar"))
1095                 return;
1096
1097         info->x_char = ch;
1098         if (ch) {
1099                 /* Make sure transmit interrupts are on */
1100                 spin_lock_irqsave(&info->lock,flags);
1101                 if (!info->tx_enabled)
1102                         tx_start(info);
1103                 spin_unlock_irqrestore(&info->lock,flags);
1104         }
1105 }
1106
1107 /* Wait until the transmitter is empty.
1108  */
1109 static void wait_until_sent(struct tty_struct *tty, int timeout)
1110 {
1111         SLMP_INFO * info = (SLMP_INFO *)tty->driver_data;
1112         unsigned long orig_jiffies, char_time;
1113
1114         if (!info )
1115                 return;
1116
1117         if (debug_level >= DEBUG_LEVEL_INFO)
1118                 printk("%s(%d):%s wait_until_sent() entry\n",
1119                          __FILE__,__LINE__, info->device_name );
1120
1121         if (sanity_check(info, tty->name, "wait_until_sent"))
1122                 return;
1123
1124         lock_kernel();
1125
1126         if (!(info->flags & ASYNC_INITIALIZED))
1127                 goto exit;
1128
1129         orig_jiffies = jiffies;
1130
1131         /* Set check interval to 1/5 of estimated time to
1132          * send a character, and make it at least 1. The check
1133          * interval should also be less than the timeout.
1134          * Note: use tight timings here to satisfy the NIST-PCTS.
1135          */
1136
1137         if ( info->params.data_rate ) {
1138                 char_time = info->timeout/(32 * 5);
1139                 if (!char_time)
1140                         char_time++;
1141         } else
1142                 char_time = 1;
1143
1144         if (timeout)
1145                 char_time = min_t(unsigned long, char_time, timeout);
1146
1147         if ( info->params.mode == MGSL_MODE_HDLC ) {
1148                 while (info->tx_active) {
1149                         msleep_interruptible(jiffies_to_msecs(char_time));
1150                         if (signal_pending(current))
1151                                 break;
1152                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
1153                                 break;
1154                 }
1155         } else {
1156                 //TODO: determine if there is something similar to USC16C32
1157                 //      TXSTATUS_ALL_SENT status
1158                 while ( info->tx_active && info->tx_enabled) {
1159                         msleep_interruptible(jiffies_to_msecs(char_time));
1160                         if (signal_pending(current))
1161                                 break;
1162                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
1163                                 break;
1164                 }
1165         }
1166
1167 exit:
1168         unlock_kernel();
1169         if (debug_level >= DEBUG_LEVEL_INFO)
1170                 printk("%s(%d):%s wait_until_sent() exit\n",
1171                          __FILE__,__LINE__, info->device_name );
1172 }
1173
1174 /* Return the count of free bytes in transmit buffer
1175  */
1176 static int write_room(struct tty_struct *tty)
1177 {
1178         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1179         int ret;
1180
1181         if (sanity_check(info, tty->name, "write_room"))
1182                 return 0;
1183
1184         lock_kernel();
1185         if (info->params.mode == MGSL_MODE_HDLC) {
1186                 ret = (info->tx_active) ? 0 : HDLC_MAX_FRAME_SIZE;
1187         } else {
1188                 ret = info->max_frame_size - info->tx_count - 1;
1189                 if (ret < 0)
1190                         ret = 0;
1191         }
1192         unlock_kernel();
1193
1194         if (debug_level >= DEBUG_LEVEL_INFO)
1195                 printk("%s(%d):%s write_room()=%d\n",
1196                        __FILE__, __LINE__, info->device_name, ret);
1197
1198         return ret;
1199 }
1200
1201 /* enable transmitter and send remaining buffered characters
1202  */
1203 static void flush_chars(struct tty_struct *tty)
1204 {
1205         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1206         unsigned long flags;
1207
1208         if ( debug_level >= DEBUG_LEVEL_INFO )
1209                 printk( "%s(%d):%s flush_chars() entry tx_count=%d\n",
1210                         __FILE__,__LINE__,info->device_name,info->tx_count);
1211
1212         if (sanity_check(info, tty->name, "flush_chars"))
1213                 return;
1214
1215         if (info->tx_count <= 0 || tty->stopped || tty->hw_stopped ||
1216             !info->tx_buf)
1217                 return;
1218
1219         if ( debug_level >= DEBUG_LEVEL_INFO )
1220                 printk( "%s(%d):%s flush_chars() entry, starting transmitter\n",
1221                         __FILE__,__LINE__,info->device_name );
1222
1223         spin_lock_irqsave(&info->lock,flags);
1224
1225         if (!info->tx_active) {
1226                 if ( (info->params.mode == MGSL_MODE_HDLC) &&
1227                         info->tx_count ) {
1228                         /* operating in synchronous (frame oriented) mode */
1229                         /* copy data from circular tx_buf to */
1230                         /* transmit DMA buffer. */
1231                         tx_load_dma_buffer(info,
1232                                  info->tx_buf,info->tx_count);
1233                 }
1234                 tx_start(info);
1235         }
1236
1237         spin_unlock_irqrestore(&info->lock,flags);
1238 }
1239
1240 /* Discard all data in the send buffer
1241  */
1242 static void flush_buffer(struct tty_struct *tty)
1243 {
1244         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1245         unsigned long flags;
1246
1247         if (debug_level >= DEBUG_LEVEL_INFO)
1248                 printk("%s(%d):%s flush_buffer() entry\n",
1249                          __FILE__,__LINE__, info->device_name );
1250
1251         if (sanity_check(info, tty->name, "flush_buffer"))
1252                 return;
1253
1254         spin_lock_irqsave(&info->lock,flags);
1255         info->tx_count = info->tx_put = info->tx_get = 0;
1256         del_timer(&info->tx_timer);
1257         spin_unlock_irqrestore(&info->lock,flags);
1258
1259         tty_wakeup(tty);
1260 }
1261
1262 /* throttle (stop) transmitter
1263  */
1264 static void tx_hold(struct tty_struct *tty)
1265 {
1266         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1267         unsigned long flags;
1268
1269         if (sanity_check(info, tty->name, "tx_hold"))
1270                 return;
1271
1272         if ( debug_level >= DEBUG_LEVEL_INFO )
1273                 printk("%s(%d):%s tx_hold()\n",
1274                         __FILE__,__LINE__,info->device_name);
1275
1276         spin_lock_irqsave(&info->lock,flags);
1277         if (info->tx_enabled)
1278                 tx_stop(info);
1279         spin_unlock_irqrestore(&info->lock,flags);
1280 }
1281
1282 /* release (start) transmitter
1283  */
1284 static void tx_release(struct tty_struct *tty)
1285 {
1286         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1287         unsigned long flags;
1288
1289         if (sanity_check(info, tty->name, "tx_release"))
1290                 return;
1291
1292         if ( debug_level >= DEBUG_LEVEL_INFO )
1293                 printk("%s(%d):%s tx_release()\n",
1294                         __FILE__,__LINE__,info->device_name);
1295
1296         spin_lock_irqsave(&info->lock,flags);
1297         if (!info->tx_enabled)
1298                 tx_start(info);
1299         spin_unlock_irqrestore(&info->lock,flags);
1300 }
1301
1302 /* Service an IOCTL request
1303  *
1304  * Arguments:
1305  *
1306  *      tty     pointer to tty instance data
1307  *      file    pointer to associated file object for device
1308  *      cmd     IOCTL command code
1309  *      arg     command argument/context
1310  *
1311  * Return Value:        0 if success, otherwise error code
1312  */
1313 static int do_ioctl(struct tty_struct *tty, struct file *file,
1314                  unsigned int cmd, unsigned long arg)
1315 {
1316         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1317         int error;
1318         struct mgsl_icount cnow;        /* kernel counter temps */
1319         struct serial_icounter_struct __user *p_cuser;  /* user space */
1320         unsigned long flags;
1321         void __user *argp = (void __user *)arg;
1322
1323         if (debug_level >= DEBUG_LEVEL_INFO)
1324                 printk("%s(%d):%s ioctl() cmd=%08X\n", __FILE__,__LINE__,
1325                         info->device_name, cmd );
1326
1327         if (sanity_check(info, tty->name, "ioctl"))
1328                 return -ENODEV;
1329
1330         if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
1331             (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
1332                 if (tty->flags & (1 << TTY_IO_ERROR))
1333                     return -EIO;
1334         }
1335
1336         switch (cmd) {
1337         case MGSL_IOCGPARAMS:
1338                 return get_params(info, argp);
1339         case MGSL_IOCSPARAMS:
1340                 return set_params(info, argp);
1341         case MGSL_IOCGTXIDLE:
1342                 return get_txidle(info, argp);
1343         case MGSL_IOCSTXIDLE:
1344                 return set_txidle(info, (int)arg);
1345         case MGSL_IOCTXENABLE:
1346                 return tx_enable(info, (int)arg);
1347         case MGSL_IOCRXENABLE:
1348                 return rx_enable(info, (int)arg);
1349         case MGSL_IOCTXABORT:
1350                 return tx_abort(info);
1351         case MGSL_IOCGSTATS:
1352                 return get_stats(info, argp);
1353         case MGSL_IOCWAITEVENT:
1354                 return wait_mgsl_event(info, argp);
1355         case MGSL_IOCLOOPTXDONE:
1356                 return 0; // TODO: Not supported, need to document
1357                 /* Wait for modem input (DCD,RI,DSR,CTS) change
1358                  * as specified by mask in arg (TIOCM_RNG/DSR/CD/CTS)
1359                  */
1360         case TIOCMIWAIT:
1361                 return modem_input_wait(info,(int)arg);
1362                 
1363                 /*
1364                  * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1365                  * Return: write counters to the user passed counter struct
1366                  * NB: both 1->0 and 0->1 transitions are counted except for
1367                  *     RI where only 0->1 is counted.
1368                  */
1369         case TIOCGICOUNT:
1370                 spin_lock_irqsave(&info->lock,flags);
1371                 cnow = info->icount;
1372                 spin_unlock_irqrestore(&info->lock,flags);
1373                 p_cuser = argp;
1374                 PUT_USER(error,cnow.cts, &p_cuser->cts);
1375                 if (error) return error;
1376                 PUT_USER(error,cnow.dsr, &p_cuser->dsr);
1377                 if (error) return error;
1378                 PUT_USER(error,cnow.rng, &p_cuser->rng);
1379                 if (error) return error;
1380                 PUT_USER(error,cnow.dcd, &p_cuser->dcd);
1381                 if (error) return error;
1382                 PUT_USER(error,cnow.rx, &p_cuser->rx);
1383                 if (error) return error;
1384                 PUT_USER(error,cnow.tx, &p_cuser->tx);
1385                 if (error) return error;
1386                 PUT_USER(error,cnow.frame, &p_cuser->frame);
1387                 if (error) return error;
1388                 PUT_USER(error,cnow.overrun, &p_cuser->overrun);
1389                 if (error) return error;
1390                 PUT_USER(error,cnow.parity, &p_cuser->parity);
1391                 if (error) return error;
1392                 PUT_USER(error,cnow.brk, &p_cuser->brk);
1393                 if (error) return error;
1394                 PUT_USER(error,cnow.buf_overrun, &p_cuser->buf_overrun);
1395                 if (error) return error;
1396                 return 0;
1397         default:
1398                 return -ENOIOCTLCMD;
1399         }
1400         return 0;
1401 }
1402
1403 static int ioctl(struct tty_struct *tty, struct file *file,
1404                  unsigned int cmd, unsigned long arg)
1405 {
1406         int ret;
1407         lock_kernel();
1408         ret = do_ioctl(tty, file, cmd, arg);
1409         unlock_kernel();
1410         return ret;
1411 }
1412
1413 /*
1414  * /proc fs routines....
1415  */
1416
1417 static inline int line_info(char *buf, SLMP_INFO *info)
1418 {
1419         char    stat_buf[30];
1420         int     ret;
1421         unsigned long flags;
1422
1423         ret = sprintf(buf, "%s: SCABase=%08x Mem=%08X StatusControl=%08x LCR=%08X\n"
1424                        "\tIRQ=%d MaxFrameSize=%u\n",
1425                 info->device_name,
1426                 info->phys_sca_base,
1427                 info->phys_memory_base,
1428                 info->phys_statctrl_base,
1429                 info->phys_lcr_base,
1430                 info->irq_level,
1431                 info->max_frame_size );
1432
1433         /* output current serial signal states */
1434         spin_lock_irqsave(&info->lock,flags);
1435         get_signals(info);
1436         spin_unlock_irqrestore(&info->lock,flags);
1437
1438         stat_buf[0] = 0;
1439         stat_buf[1] = 0;
1440         if (info->serial_signals & SerialSignal_RTS)
1441                 strcat(stat_buf, "|RTS");
1442         if (info->serial_signals & SerialSignal_CTS)
1443                 strcat(stat_buf, "|CTS");
1444         if (info->serial_signals & SerialSignal_DTR)
1445                 strcat(stat_buf, "|DTR");
1446         if (info->serial_signals & SerialSignal_DSR)
1447                 strcat(stat_buf, "|DSR");
1448         if (info->serial_signals & SerialSignal_DCD)
1449                 strcat(stat_buf, "|CD");
1450         if (info->serial_signals & SerialSignal_RI)
1451                 strcat(stat_buf, "|RI");
1452
1453         if (info->params.mode == MGSL_MODE_HDLC) {
1454                 ret += sprintf(buf+ret, "\tHDLC txok:%d rxok:%d",
1455                               info->icount.txok, info->icount.rxok);
1456                 if (info->icount.txunder)
1457                         ret += sprintf(buf+ret, " txunder:%d", info->icount.txunder);
1458                 if (info->icount.txabort)
1459                         ret += sprintf(buf+ret, " txabort:%d", info->icount.txabort);
1460                 if (info->icount.rxshort)
1461                         ret += sprintf(buf+ret, " rxshort:%d", info->icount.rxshort);
1462                 if (info->icount.rxlong)
1463                         ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxlong);
1464                 if (info->icount.rxover)
1465                         ret += sprintf(buf+ret, " rxover:%d", info->icount.rxover);
1466                 if (info->icount.rxcrc)
1467                         ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxcrc);
1468         } else {
1469                 ret += sprintf(buf+ret, "\tASYNC tx:%d rx:%d",
1470                               info->icount.tx, info->icount.rx);
1471                 if (info->icount.frame)
1472                         ret += sprintf(buf+ret, " fe:%d", info->icount.frame);
1473                 if (info->icount.parity)
1474                         ret += sprintf(buf+ret, " pe:%d", info->icount.parity);
1475                 if (info->icount.brk)
1476                         ret += sprintf(buf+ret, " brk:%d", info->icount.brk);
1477                 if (info->icount.overrun)
1478                         ret += sprintf(buf+ret, " oe:%d", info->icount.overrun);
1479         }
1480
1481         /* Append serial signal status to end */
1482         ret += sprintf(buf+ret, " %s\n", stat_buf+1);
1483
1484         ret += sprintf(buf+ret, "\ttxactive=%d bh_req=%d bh_run=%d pending_bh=%x\n",
1485          info->tx_active,info->bh_requested,info->bh_running,
1486          info->pending_bh);
1487
1488         return ret;
1489 }
1490
1491 /* Called to print information about devices
1492  */
1493 static int read_proc(char *page, char **start, off_t off, int count,
1494               int *eof, void *data)
1495 {
1496         int len = 0, l;
1497         off_t   begin = 0;
1498         SLMP_INFO *info;
1499
1500         len += sprintf(page, "synclinkmp driver:%s\n", driver_version);
1501
1502         info = synclinkmp_device_list;
1503         while( info ) {
1504                 l = line_info(page + len, info);
1505                 len += l;
1506                 if (len+begin > off+count)
1507                         goto done;
1508                 if (len+begin < off) {
1509                         begin += len;
1510                         len = 0;
1511                 }
1512                 info = info->next_device;
1513         }
1514
1515         *eof = 1;
1516 done:
1517         if (off >= len+begin)
1518                 return 0;
1519         *start = page + (off-begin);
1520         return ((count < begin+len-off) ? count : begin+len-off);
1521 }
1522
1523 /* Return the count of bytes in transmit buffer
1524  */
1525 static int chars_in_buffer(struct tty_struct *tty)
1526 {
1527         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1528
1529         if (sanity_check(info, tty->name, "chars_in_buffer"))
1530                 return 0;
1531
1532         if (debug_level >= DEBUG_LEVEL_INFO)
1533                 printk("%s(%d):%s chars_in_buffer()=%d\n",
1534                        __FILE__, __LINE__, info->device_name, info->tx_count);
1535
1536         return info->tx_count;
1537 }
1538
1539 /* Signal remote device to throttle send data (our receive data)
1540  */
1541 static void throttle(struct tty_struct * tty)
1542 {
1543         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1544         unsigned long flags;
1545
1546         if (debug_level >= DEBUG_LEVEL_INFO)
1547                 printk("%s(%d):%s throttle() entry\n",
1548                          __FILE__,__LINE__, info->device_name );
1549
1550         if (sanity_check(info, tty->name, "throttle"))
1551                 return;
1552
1553         if (I_IXOFF(tty))
1554                 send_xchar(tty, STOP_CHAR(tty));
1555
1556         if (tty->termios->c_cflag & CRTSCTS) {
1557                 spin_lock_irqsave(&info->lock,flags);
1558                 info->serial_signals &= ~SerialSignal_RTS;
1559                 set_signals(info);
1560                 spin_unlock_irqrestore(&info->lock,flags);
1561         }
1562 }
1563
1564 /* Signal remote device to stop throttling send data (our receive data)
1565  */
1566 static void unthrottle(struct tty_struct * tty)
1567 {
1568         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
1569         unsigned long flags;
1570
1571         if (debug_level >= DEBUG_LEVEL_INFO)
1572                 printk("%s(%d):%s unthrottle() entry\n",
1573                          __FILE__,__LINE__, info->device_name );
1574
1575         if (sanity_check(info, tty->name, "unthrottle"))
1576                 return;
1577
1578         if (I_IXOFF(tty)) {
1579                 if (info->x_char)
1580                         info->x_char = 0;
1581                 else
1582                         send_xchar(tty, START_CHAR(tty));
1583         }
1584
1585         if (tty->termios->c_cflag & CRTSCTS) {
1586                 spin_lock_irqsave(&info->lock,flags);
1587                 info->serial_signals |= SerialSignal_RTS;
1588                 set_signals(info);
1589                 spin_unlock_irqrestore(&info->lock,flags);
1590         }
1591 }
1592
1593 /* set or clear transmit break condition
1594  * break_state  -1=set break condition, 0=clear
1595  */
1596 static void set_break(struct tty_struct *tty, int break_state)
1597 {
1598         unsigned char RegValue;
1599         SLMP_INFO * info = (SLMP_INFO *)tty->driver_data;
1600         unsigned long flags;
1601
1602         if (debug_level >= DEBUG_LEVEL_INFO)
1603                 printk("%s(%d):%s set_break(%d)\n",
1604                          __FILE__,__LINE__, info->device_name, break_state);
1605
1606         if (sanity_check(info, tty->name, "set_break"))
1607                 return;
1608
1609         spin_lock_irqsave(&info->lock,flags);
1610         RegValue = read_reg(info, CTL);
1611         if (break_state == -1)
1612                 RegValue |= BIT3;
1613         else
1614                 RegValue &= ~BIT3;
1615         write_reg(info, CTL, RegValue);
1616         spin_unlock_irqrestore(&info->lock,flags);
1617 }
1618
1619 #if SYNCLINK_GENERIC_HDLC
1620
1621 /**
1622  * called by generic HDLC layer when protocol selected (PPP, frame relay, etc.)
1623  * set encoding and frame check sequence (FCS) options
1624  *
1625  * dev       pointer to network device structure
1626  * encoding  serial encoding setting
1627  * parity    FCS setting
1628  *
1629  * returns 0 if success, otherwise error code
1630  */
1631 static int hdlcdev_attach(struct net_device *dev, unsigned short encoding,
1632                           unsigned short parity)
1633 {
1634         SLMP_INFO *info = dev_to_port(dev);
1635         unsigned char  new_encoding;
1636         unsigned short new_crctype;
1637
1638         /* return error if TTY interface open */
1639         if (info->count)
1640                 return -EBUSY;
1641
1642         switch (encoding)
1643         {
1644         case ENCODING_NRZ:        new_encoding = HDLC_ENCODING_NRZ; break;
1645         case ENCODING_NRZI:       new_encoding = HDLC_ENCODING_NRZI_SPACE; break;
1646         case ENCODING_FM_MARK:    new_encoding = HDLC_ENCODING_BIPHASE_MARK; break;
1647         case ENCODING_FM_SPACE:   new_encoding = HDLC_ENCODING_BIPHASE_SPACE; break;
1648         case ENCODING_MANCHESTER: new_encoding = HDLC_ENCODING_BIPHASE_LEVEL; break;
1649         default: return -EINVAL;
1650         }
1651
1652         switch (parity)
1653         {
1654         case PARITY_NONE:            new_crctype = HDLC_CRC_NONE; break;
1655         case PARITY_CRC16_PR1_CCITT: new_crctype = HDLC_CRC_16_CCITT; break;
1656         case PARITY_CRC32_PR1_CCITT: new_crctype = HDLC_CRC_32_CCITT; break;
1657         default: return -EINVAL;
1658         }
1659
1660         info->params.encoding = new_encoding;
1661         info->params.crc_type = new_crctype;
1662
1663         /* if network interface up, reprogram hardware */
1664         if (info->netcount)
1665                 program_hw(info);
1666
1667         return 0;
1668 }
1669
1670 /**
1671  * called by generic HDLC layer to send frame
1672  *
1673  * skb  socket buffer containing HDLC frame
1674  * dev  pointer to network device structure
1675  *
1676  * returns 0 if success, otherwise error code
1677  */
1678 static int hdlcdev_xmit(struct sk_buff *skb, struct net_device *dev)
1679 {
1680         SLMP_INFO *info = dev_to_port(dev);
1681         unsigned long flags;
1682
1683         if (debug_level >= DEBUG_LEVEL_INFO)
1684                 printk(KERN_INFO "%s:hdlc_xmit(%s)\n",__FILE__,dev->name);
1685
1686         /* stop sending until this frame completes */
1687         netif_stop_queue(dev);
1688
1689         /* copy data to device buffers */
1690         info->tx_count = skb->len;
1691         tx_load_dma_buffer(info, skb->data, skb->len);
1692
1693         /* update network statistics */
1694         dev->stats.tx_packets++;
1695         dev->stats.tx_bytes += skb->len;
1696
1697         /* done with socket buffer, so free it */
1698         dev_kfree_skb(skb);
1699
1700         /* save start time for transmit timeout detection */
1701         dev->trans_start = jiffies;
1702
1703         /* start hardware transmitter if necessary */
1704         spin_lock_irqsave(&info->lock,flags);
1705         if (!info->tx_active)
1706                 tx_start(info);
1707         spin_unlock_irqrestore(&info->lock,flags);
1708
1709         return 0;
1710 }
1711
1712 /**
1713  * called by network layer when interface enabled
1714  * claim resources and initialize hardware
1715  *
1716  * dev  pointer to network device structure
1717  *
1718  * returns 0 if success, otherwise error code
1719  */
1720 static int hdlcdev_open(struct net_device *dev)
1721 {
1722         SLMP_INFO *info = dev_to_port(dev);
1723         int rc;
1724         unsigned long flags;
1725
1726         if (debug_level >= DEBUG_LEVEL_INFO)
1727                 printk("%s:hdlcdev_open(%s)\n",__FILE__,dev->name);
1728
1729         /* generic HDLC layer open processing */
1730         if ((rc = hdlc_open(dev)))
1731                 return rc;
1732
1733         /* arbitrate between network and tty opens */
1734         spin_lock_irqsave(&info->netlock, flags);
1735         if (info->count != 0 || info->netcount != 0) {
1736                 printk(KERN_WARNING "%s: hdlc_open returning busy\n", dev->name);
1737                 spin_unlock_irqrestore(&info->netlock, flags);
1738                 return -EBUSY;
1739         }
1740         info->netcount=1;
1741         spin_unlock_irqrestore(&info->netlock, flags);
1742
1743         /* claim resources and init adapter */
1744         if ((rc = startup(info)) != 0) {
1745                 spin_lock_irqsave(&info->netlock, flags);
1746                 info->netcount=0;
1747                 spin_unlock_irqrestore(&info->netlock, flags);
1748                 return rc;
1749         }
1750
1751         /* assert DTR and RTS, apply hardware settings */
1752         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
1753         program_hw(info);
1754
1755         /* enable network layer transmit */
1756         dev->trans_start = jiffies;
1757         netif_start_queue(dev);
1758
1759         /* inform generic HDLC layer of current DCD status */
1760         spin_lock_irqsave(&info->lock, flags);
1761         get_signals(info);
1762         spin_unlock_irqrestore(&info->lock, flags);
1763         if (info->serial_signals & SerialSignal_DCD)
1764                 netif_carrier_on(dev);
1765         else
1766                 netif_carrier_off(dev);
1767         return 0;
1768 }
1769
1770 /**
1771  * called by network layer when interface is disabled
1772  * shutdown hardware and release resources
1773  *
1774  * dev  pointer to network device structure
1775  *
1776  * returns 0 if success, otherwise error code
1777  */
1778 static int hdlcdev_close(struct net_device *dev)
1779 {
1780         SLMP_INFO *info = dev_to_port(dev);
1781         unsigned long flags;
1782
1783         if (debug_level >= DEBUG_LEVEL_INFO)
1784                 printk("%s:hdlcdev_close(%s)\n",__FILE__,dev->name);
1785
1786         netif_stop_queue(dev);
1787
1788         /* shutdown adapter and release resources */
1789         shutdown(info);
1790
1791         hdlc_close(dev);
1792
1793         spin_lock_irqsave(&info->netlock, flags);
1794         info->netcount=0;
1795         spin_unlock_irqrestore(&info->netlock, flags);
1796
1797         return 0;
1798 }
1799
1800 /**
1801  * called by network layer to process IOCTL call to network device
1802  *
1803  * dev  pointer to network device structure
1804  * ifr  pointer to network interface request structure
1805  * cmd  IOCTL command code
1806  *
1807  * returns 0 if success, otherwise error code
1808  */
1809 static int hdlcdev_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
1810 {
1811         const size_t size = sizeof(sync_serial_settings);
1812         sync_serial_settings new_line;
1813         sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
1814         SLMP_INFO *info = dev_to_port(dev);
1815         unsigned int flags;
1816
1817         if (debug_level >= DEBUG_LEVEL_INFO)
1818                 printk("%s:hdlcdev_ioctl(%s)\n",__FILE__,dev->name);
1819
1820         /* return error if TTY interface open */
1821         if (info->count)
1822                 return -EBUSY;
1823
1824         if (cmd != SIOCWANDEV)
1825                 return hdlc_ioctl(dev, ifr, cmd);
1826
1827         switch(ifr->ifr_settings.type) {
1828         case IF_GET_IFACE: /* return current sync_serial_settings */
1829
1830                 ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL;
1831                 if (ifr->ifr_settings.size < size) {
1832                         ifr->ifr_settings.size = size; /* data size wanted */
1833                         return -ENOBUFS;
1834                 }
1835
1836                 flags = info->params.flags & (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1837                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1838                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1839                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
1840
1841                 switch (flags){
1842                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN): new_line.clock_type = CLOCK_EXT; break;
1843                 case (HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_INT; break;
1844                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_TXINT; break;
1845                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN): new_line.clock_type = CLOCK_TXFROMRX; break;
1846                 default: new_line.clock_type = CLOCK_DEFAULT;
1847                 }
1848
1849                 new_line.clock_rate = info->params.clock_speed;
1850                 new_line.loopback   = info->params.loopback ? 1:0;
1851
1852                 if (copy_to_user(line, &new_line, size))
1853                         return -EFAULT;
1854                 return 0;
1855
1856         case IF_IFACE_SYNC_SERIAL: /* set sync_serial_settings */
1857
1858                 if(!capable(CAP_NET_ADMIN))
1859                         return -EPERM;
1860                 if (copy_from_user(&new_line, line, size))
1861                         return -EFAULT;
1862
1863                 switch (new_line.clock_type)
1864                 {
1865                 case CLOCK_EXT:      flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN; break;
1866                 case CLOCK_TXFROMRX: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN; break;
1867                 case CLOCK_INT:      flags = HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG;    break;
1868                 case CLOCK_TXINT:    flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG;    break;
1869                 case CLOCK_DEFAULT:  flags = info->params.flags &
1870                                              (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1871                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1872                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1873                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN); break;
1874                 default: return -EINVAL;
1875                 }
1876
1877                 if (new_line.loopback != 0 && new_line.loopback != 1)
1878                         return -EINVAL;
1879
1880                 info->params.flags &= ~(HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1881                                         HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1882                                         HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1883                                         HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
1884                 info->params.flags |= flags;
1885
1886                 info->params.loopback = new_line.loopback;
1887
1888                 if (flags & (HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG))
1889                         info->params.clock_speed = new_line.clock_rate;
1890                 else
1891                         info->params.clock_speed = 0;
1892
1893                 /* if network interface up, reprogram hardware */
1894                 if (info->netcount)
1895                         program_hw(info);
1896                 return 0;
1897
1898         default:
1899                 return hdlc_ioctl(dev, ifr, cmd);
1900         }
1901 }
1902
1903 /**
1904  * called by network layer when transmit timeout is detected
1905  *
1906  * dev  pointer to network device structure
1907  */
1908 static void hdlcdev_tx_timeout(struct net_device *dev)
1909 {
1910         SLMP_INFO *info = dev_to_port(dev);
1911         unsigned long flags;
1912
1913         if (debug_level >= DEBUG_LEVEL_INFO)
1914                 printk("hdlcdev_tx_timeout(%s)\n",dev->name);
1915
1916         dev->stats.tx_errors++;
1917         dev->stats.tx_aborted_errors++;
1918
1919         spin_lock_irqsave(&info->lock,flags);
1920         tx_stop(info);
1921         spin_unlock_irqrestore(&info->lock,flags);
1922
1923         netif_wake_queue(dev);
1924 }
1925
1926 /**
1927  * called by device driver when transmit completes
1928  * reenable network layer transmit if stopped
1929  *
1930  * info  pointer to device instance information
1931  */
1932 static void hdlcdev_tx_done(SLMP_INFO *info)
1933 {
1934         if (netif_queue_stopped(info->netdev))
1935                 netif_wake_queue(info->netdev);
1936 }
1937
1938 /**
1939  * called by device driver when frame received
1940  * pass frame to network layer
1941  *
1942  * info  pointer to device instance information
1943  * buf   pointer to buffer contianing frame data
1944  * size  count of data bytes in buf
1945  */
1946 static void hdlcdev_rx(SLMP_INFO *info, char *buf, int size)
1947 {
1948         struct sk_buff *skb = dev_alloc_skb(size);
1949         struct net_device *dev = info->netdev;
1950
1951         if (debug_level >= DEBUG_LEVEL_INFO)
1952                 printk("hdlcdev_rx(%s)\n",dev->name);
1953
1954         if (skb == NULL) {
1955                 printk(KERN_NOTICE "%s: can't alloc skb, dropping packet\n",
1956                        dev->name);
1957                 dev->stats.rx_dropped++;
1958                 return;
1959         }
1960
1961         memcpy(skb_put(skb, size), buf, size);
1962
1963         skb->protocol = hdlc_type_trans(skb, dev);
1964
1965         dev->stats.rx_packets++;
1966         dev->stats.rx_bytes += size;
1967
1968         netif_rx(skb);
1969
1970         dev->last_rx = jiffies;
1971 }
1972
1973 /**
1974  * called by device driver when adding device instance
1975  * do generic HDLC initialization
1976  *
1977  * info  pointer to device instance information
1978  *
1979  * returns 0 if success, otherwise error code
1980  */
1981 static int hdlcdev_init(SLMP_INFO *info)
1982 {
1983         int rc;
1984         struct net_device *dev;
1985         hdlc_device *hdlc;
1986
1987         /* allocate and initialize network and HDLC layer objects */
1988
1989         if (!(dev = alloc_hdlcdev(info))) {
1990                 printk(KERN_ERR "%s:hdlc device allocation failure\n",__FILE__);
1991                 return -ENOMEM;
1992         }
1993
1994         /* for network layer reporting purposes only */
1995         dev->mem_start = info->phys_sca_base;
1996         dev->mem_end   = info->phys_sca_base + SCA_BASE_SIZE - 1;
1997         dev->irq       = info->irq_level;
1998
1999         /* network layer callbacks and settings */
2000         dev->do_ioctl       = hdlcdev_ioctl;
2001         dev->open           = hdlcdev_open;
2002         dev->stop           = hdlcdev_close;
2003         dev->tx_timeout     = hdlcdev_tx_timeout;
2004         dev->watchdog_timeo = 10*HZ;
2005         dev->tx_queue_len   = 50;
2006
2007         /* generic HDLC layer callbacks and settings */
2008         hdlc         = dev_to_hdlc(dev);
2009         hdlc->attach = hdlcdev_attach;
2010         hdlc->xmit   = hdlcdev_xmit;
2011
2012         /* register objects with HDLC layer */
2013         if ((rc = register_hdlc_device(dev))) {
2014                 printk(KERN_WARNING "%s:unable to register hdlc device\n",__FILE__);
2015                 free_netdev(dev);
2016                 return rc;
2017         }
2018
2019         info->netdev = dev;
2020         return 0;
2021 }
2022
2023 /**
2024  * called by device driver when removing device instance
2025  * do generic HDLC cleanup
2026  *
2027  * info  pointer to device instance information
2028  */
2029 static void hdlcdev_exit(SLMP_INFO *info)
2030 {
2031         unregister_hdlc_device(info->netdev);
2032         free_netdev(info->netdev);
2033         info->netdev = NULL;
2034 }
2035
2036 #endif /* CONFIG_HDLC */
2037
2038
2039 /* Return next bottom half action to perform.
2040  * Return Value:        BH action code or 0 if nothing to do.
2041  */
2042 static int bh_action(SLMP_INFO *info)
2043 {
2044         unsigned long flags;
2045         int rc = 0;
2046
2047         spin_lock_irqsave(&info->lock,flags);
2048
2049         if (info->pending_bh & BH_RECEIVE) {
2050                 info->pending_bh &= ~BH_RECEIVE;
2051                 rc = BH_RECEIVE;
2052         } else if (info->pending_bh & BH_TRANSMIT) {
2053                 info->pending_bh &= ~BH_TRANSMIT;
2054                 rc = BH_TRANSMIT;
2055         } else if (info->pending_bh & BH_STATUS) {
2056                 info->pending_bh &= ~BH_STATUS;
2057                 rc = BH_STATUS;
2058         }
2059
2060         if (!rc) {
2061                 /* Mark BH routine as complete */
2062                 info->bh_running = false;
2063                 info->bh_requested = false;
2064         }
2065
2066         spin_unlock_irqrestore(&info->lock,flags);
2067
2068         return rc;
2069 }
2070
2071 /* Perform bottom half processing of work items queued by ISR.
2072  */
2073 static void bh_handler(struct work_struct *work)
2074 {
2075         SLMP_INFO *info = container_of(work, SLMP_INFO, task);
2076         int action;
2077
2078         if (!info)
2079                 return;
2080
2081         if ( debug_level >= DEBUG_LEVEL_BH )
2082                 printk( "%s(%d):%s bh_handler() entry\n",
2083                         __FILE__,__LINE__,info->device_name);
2084
2085         info->bh_running = true;
2086
2087         while((action = bh_action(info)) != 0) {
2088
2089                 /* Process work item */
2090                 if ( debug_level >= DEBUG_LEVEL_BH )
2091                         printk( "%s(%d):%s bh_handler() work item action=%d\n",
2092                                 __FILE__,__LINE__,info->device_name, action);
2093
2094                 switch (action) {
2095
2096                 case BH_RECEIVE:
2097                         bh_receive(info);
2098                         break;
2099                 case BH_TRANSMIT:
2100                         bh_transmit(info);
2101                         break;
2102                 case BH_STATUS:
2103                         bh_status(info);
2104                         break;
2105                 default:
2106                         /* unknown work item ID */
2107                         printk("%s(%d):%s Unknown work item ID=%08X!\n",
2108                                 __FILE__,__LINE__,info->device_name,action);
2109                         break;
2110                 }
2111         }
2112
2113         if ( debug_level >= DEBUG_LEVEL_BH )
2114                 printk( "%s(%d):%s bh_handler() exit\n",
2115                         __FILE__,__LINE__,info->device_name);
2116 }
2117
2118 static void bh_receive(SLMP_INFO *info)
2119 {
2120         if ( debug_level >= DEBUG_LEVEL_BH )
2121                 printk( "%s(%d):%s bh_receive()\n",
2122                         __FILE__,__LINE__,info->device_name);
2123
2124         while( rx_get_frame(info) );
2125 }
2126
2127 static void bh_transmit(SLMP_INFO *info)
2128 {
2129         struct tty_struct *tty = info->tty;
2130
2131         if ( debug_level >= DEBUG_LEVEL_BH )
2132                 printk( "%s(%d):%s bh_transmit() entry\n",
2133                         __FILE__,__LINE__,info->device_name);
2134
2135         if (tty)
2136                 tty_wakeup(tty);
2137 }
2138
2139 static void bh_status(SLMP_INFO *info)
2140 {
2141         if ( debug_level >= DEBUG_LEVEL_BH )
2142                 printk( "%s(%d):%s bh_status() entry\n",
2143                         __FILE__,__LINE__,info->device_name);
2144
2145         info->ri_chkcount = 0;
2146         info->dsr_chkcount = 0;
2147         info->dcd_chkcount = 0;
2148         info->cts_chkcount = 0;
2149 }
2150
2151 static void isr_timer(SLMP_INFO * info)
2152 {
2153         unsigned char timer = (info->port_num & 1) ? TIMER2 : TIMER0;
2154
2155         /* IER2<7..4> = timer<3..0> interrupt enables (0=disabled) */
2156         write_reg(info, IER2, 0);
2157
2158         /* TMCS, Timer Control/Status Register
2159          *
2160          * 07      CMF, Compare match flag (read only) 1=match
2161          * 06      ECMI, CMF Interrupt Enable: 0=disabled
2162          * 05      Reserved, must be 0
2163          * 04      TME, Timer Enable
2164          * 03..00  Reserved, must be 0
2165          *
2166          * 0000 0000
2167          */
2168         write_reg(info, (unsigned char)(timer + TMCS), 0);
2169
2170         info->irq_occurred = true;
2171
2172         if ( debug_level >= DEBUG_LEVEL_ISR )
2173                 printk("%s(%d):%s isr_timer()\n",
2174                         __FILE__,__LINE__,info->device_name);
2175 }
2176
2177 static void isr_rxint(SLMP_INFO * info)
2178 {
2179         struct tty_struct *tty = info->tty;
2180         struct  mgsl_icount *icount = &info->icount;
2181         unsigned char status = read_reg(info, SR1) & info->ie1_value & (FLGD + IDLD + CDCD + BRKD);
2182         unsigned char status2 = read_reg(info, SR2) & info->ie2_value & OVRN;
2183
2184         /* clear status bits */
2185         if (status)
2186                 write_reg(info, SR1, status);
2187
2188         if (status2)
2189                 write_reg(info, SR2, status2);
2190         
2191         if ( debug_level >= DEBUG_LEVEL_ISR )
2192                 printk("%s(%d):%s isr_rxint status=%02X %02x\n",
2193                         __FILE__,__LINE__,info->device_name,status,status2);
2194
2195         if (info->params.mode == MGSL_MODE_ASYNC) {
2196                 if (status & BRKD) {
2197                         icount->brk++;
2198
2199                         /* process break detection if tty control
2200                          * is not set to ignore it
2201                          */
2202                         if ( tty ) {
2203                                 if (!(status & info->ignore_status_mask1)) {
2204                                         if (info->read_status_mask1 & BRKD) {
2205                                                 tty_insert_flip_char(tty, 0, TTY_BREAK);
2206                                                 if (info->flags & ASYNC_SAK)
2207                                                         do_SAK(tty);
2208                                         }
2209                                 }
2210                         }
2211                 }
2212         }
2213         else {
2214                 if (status & (FLGD|IDLD)) {
2215                         if (status & FLGD)
2216                                 info->icount.exithunt++;
2217                         else if (status & IDLD)
2218                                 info->icount.rxidle++;
2219                         wake_up_interruptible(&info->event_wait_q);
2220                 }
2221         }
2222
2223         if (status & CDCD) {
2224                 /* simulate a common modem status change interrupt
2225                  * for our handler
2226                  */
2227                 get_signals( info );
2228                 isr_io_pin(info,
2229                         MISCSTATUS_DCD_LATCHED|(info->serial_signals&SerialSignal_DCD));
2230         }
2231 }
2232
2233 /*
2234  * handle async rx data interrupts
2235  */
2236 static void isr_rxrdy(SLMP_INFO * info)
2237 {
2238         u16 status;
2239         unsigned char DataByte;
2240         struct tty_struct *tty = info->tty;
2241         struct  mgsl_icount *icount = &info->icount;
2242
2243         if ( debug_level >= DEBUG_LEVEL_ISR )
2244                 printk("%s(%d):%s isr_rxrdy\n",
2245                         __FILE__,__LINE__,info->device_name);
2246
2247         while((status = read_reg(info,CST0)) & BIT0)
2248         {
2249                 int flag = 0;
2250                 bool over = false;
2251                 DataByte = read_reg(info,TRB);
2252
2253                 icount->rx++;
2254
2255                 if ( status & (PE + FRME + OVRN) ) {
2256                         printk("%s(%d):%s rxerr=%04X\n",
2257                                 __FILE__,__LINE__,info->device_name,status);
2258
2259                         /* update error statistics */
2260                         if (status & PE)
2261                                 icount->parity++;
2262                         else if (status & FRME)
2263                                 icount->frame++;
2264                         else if (status & OVRN)
2265                                 icount->overrun++;
2266
2267                         /* discard char if tty control flags say so */
2268                         if (status & info->ignore_status_mask2)
2269                                 continue;
2270
2271                         status &= info->read_status_mask2;
2272
2273                         if ( tty ) {
2274                                 if (status & PE)
2275                                         flag = TTY_PARITY;
2276                                 else if (status & FRME)
2277                                         flag = TTY_FRAME;
2278                                 if (status & OVRN) {
2279                                         /* Overrun is special, since it's
2280                                          * reported immediately, and doesn't
2281                                          * affect the current character
2282                                          */
2283                                         over = true;
2284                                 }
2285                         }
2286                 }       /* end of if (error) */
2287
2288                 if ( tty ) {
2289                         tty_insert_flip_char(tty, DataByte, flag);
2290                         if (over)
2291                                 tty_insert_flip_char(tty, 0, TTY_OVERRUN);
2292                 }
2293         }
2294
2295         if ( debug_level >= DEBUG_LEVEL_ISR ) {
2296                 printk("%s(%d):%s rx=%d brk=%d parity=%d frame=%d overrun=%d\n",
2297                         __FILE__,__LINE__,info->device_name,
2298                         icount->rx,icount->brk,icount->parity,
2299                         icount->frame,icount->overrun);
2300         }
2301
2302         if ( tty )
2303                 tty_flip_buffer_push(tty);
2304 }
2305
2306 static void isr_txeom(SLMP_INFO * info, unsigned char status)
2307 {
2308         if ( debug_level >= DEBUG_LEVEL_ISR )
2309                 printk("%s(%d):%s isr_txeom status=%02x\n",
2310                         __FILE__,__LINE__,info->device_name,status);
2311
2312         write_reg(info, TXDMA + DIR, 0x00); /* disable Tx DMA IRQs */
2313         write_reg(info, TXDMA + DSR, 0xc0); /* clear IRQs and disable DMA */
2314         write_reg(info, TXDMA + DCMD, SWABORT); /* reset/init DMA channel */
2315
2316         if (status & UDRN) {
2317                 write_reg(info, CMD, TXRESET);
2318                 write_reg(info, CMD, TXENABLE);
2319         } else
2320                 write_reg(info, CMD, TXBUFCLR);
2321
2322         /* disable and clear tx interrupts */
2323         info->ie0_value &= ~TXRDYE;
2324         info->ie1_value &= ~(IDLE + UDRN);
2325         write_reg16(info, IE0, (unsigned short)((info->ie1_value << 8) + info->ie0_value));
2326         write_reg(info, SR1, (unsigned char)(UDRN + IDLE));
2327
2328         if ( info->tx_active ) {
2329                 if (info->params.mode != MGSL_MODE_ASYNC) {
2330                         if (status & UDRN)
2331                                 info->icount.txunder++;
2332                         else if (status & IDLE)
2333                                 info->icount.txok++;
2334                 }
2335
2336                 info->tx_active = false;
2337                 info->tx_count = info->tx_put = info->tx_get = 0;
2338
2339                 del_timer(&info->tx_timer);
2340
2341                 if (info->params.mode != MGSL_MODE_ASYNC && info->drop_rts_on_tx_done ) {
2342                         info->serial_signals &= ~SerialSignal_RTS;
2343                         info->drop_rts_on_tx_done = false;
2344                         set_signals(info);
2345                 }
2346
2347 #if SYNCLINK_GENERIC_HDLC
2348                 if (info->netcount)
2349                         hdlcdev_tx_done(info);
2350                 else
2351 #endif
2352                 {
2353                         if (info->tty && (info->tty->stopped || info->tty->hw_stopped)) {
2354                                 tx_stop(info);
2355                                 return;
2356                         }
2357                         info->pending_bh |= BH_TRANSMIT;
2358                 }
2359         }
2360 }
2361
2362
2363 /*
2364  * handle tx status interrupts
2365  */
2366 static void isr_txint(SLMP_INFO * info)
2367 {
2368         unsigned char status = read_reg(info, SR1) & info->ie1_value & (UDRN + IDLE + CCTS);
2369
2370         /* clear status bits */
2371         write_reg(info, SR1, status);
2372
2373         if ( debug_level >= DEBUG_LEVEL_ISR )
2374                 printk("%s(%d):%s isr_txint status=%02x\n",
2375                         __FILE__,__LINE__,info->device_name,status);
2376
2377         if (status & (UDRN + IDLE))
2378                 isr_txeom(info, status);
2379
2380         if (status & CCTS) {
2381                 /* simulate a common modem status change interrupt
2382                  * for our handler
2383                  */
2384                 get_signals( info );
2385                 isr_io_pin(info,
2386                         MISCSTATUS_CTS_LATCHED|(info->serial_signals&SerialSignal_CTS));
2387
2388         }
2389 }
2390
2391 /*
2392  * handle async tx data interrupts
2393  */
2394 static void isr_txrdy(SLMP_INFO * info)
2395 {
2396         if ( debug_level >= DEBUG_LEVEL_ISR )
2397                 printk("%s(%d):%s isr_txrdy() tx_count=%d\n",
2398                         __FILE__,__LINE__,info->device_name,info->tx_count);
2399
2400         if (info->params.mode != MGSL_MODE_ASYNC) {
2401                 /* disable TXRDY IRQ, enable IDLE IRQ */
2402                 info->ie0_value &= ~TXRDYE;
2403                 info->ie1_value |= IDLE;
2404                 write_reg16(info, IE0, (unsigned short)((info->ie1_value << 8) + info->ie0_value));
2405                 return;
2406         }
2407
2408         if (info->tty && (info->tty->stopped || info->tty->hw_stopped)) {
2409                 tx_stop(info);
2410                 return;
2411         }
2412
2413         if ( info->tx_count )
2414                 tx_load_fifo( info );
2415         else {
2416                 info->tx_active = false;
2417                 info->ie0_value &= ~TXRDYE;
2418                 write_reg(info, IE0, info->ie0_value);
2419         }
2420
2421         if (info->tx_count < WAKEUP_CHARS)
2422                 info->pending_bh |= BH_TRANSMIT;
2423 }
2424
2425 static void isr_rxdmaok(SLMP_INFO * info)
2426 {
2427         /* BIT7 = EOT (end of transfer)
2428          * BIT6 = EOM (end of message/frame)
2429          */
2430         unsigned char status = read_reg(info,RXDMA + DSR) & 0xc0;
2431
2432         /* clear IRQ (BIT0 must be 1 to prevent clearing DE bit) */
2433         write_reg(info, RXDMA + DSR, (unsigned char)(status | 1));
2434
2435         if ( debug_level >= DEBUG_LEVEL_ISR )
2436                 printk("%s(%d):%s isr_rxdmaok(), status=%02x\n",
2437                         __FILE__,__LINE__,info->device_name,status);
2438
2439         info->pending_bh |= BH_RECEIVE;
2440 }
2441
2442 static void isr_rxdmaerror(SLMP_INFO * info)
2443 {
2444         /* BIT5 = BOF (buffer overflow)
2445          * BIT4 = COF (counter overflow)
2446          */
2447         unsigned char status = read_reg(info,RXDMA + DSR) & 0x30;
2448
2449         /* clear IRQ (BIT0 must be 1 to prevent clearing DE bit) */
2450         write_reg(info, RXDMA + DSR, (unsigned char)(status | 1));
2451
2452         if ( debug_level >= DEBUG_LEVEL_ISR )
2453                 printk("%s(%d):%s isr_rxdmaerror(), status=%02x\n",
2454                         __FILE__,__LINE__,info->device_name,status);
2455
2456         info->rx_overflow = true;
2457         info->pending_bh |= BH_RECEIVE;
2458 }
2459
2460 static void isr_txdmaok(SLMP_INFO * info)
2461 {
2462         unsigned char status_reg1 = read_reg(info, SR1);
2463
2464         write_reg(info, TXDMA + DIR, 0x00);     /* disable Tx DMA IRQs */
2465         write_reg(info, TXDMA + DSR, 0xc0); /* clear IRQs and disable DMA */
2466         write_reg(info, TXDMA + DCMD, SWABORT); /* reset/init DMA channel */
2467
2468         if ( debug_level >= DEBUG_LEVEL_ISR )
2469                 printk("%s(%d):%s isr_txdmaok(), status=%02x\n",
2470                         __FILE__,__LINE__,info->device_name,status_reg1);
2471
2472         /* program TXRDY as FIFO empty flag, enable TXRDY IRQ */
2473         write_reg16(info, TRC0, 0);
2474         info->ie0_value |= TXRDYE;
2475         write_reg(info, IE0, info->ie0_value);
2476 }
2477
2478 static void isr_txdmaerror(SLMP_INFO * info)
2479 {
2480         /* BIT5 = BOF (buffer overflow)
2481          * BIT4 = COF (counter overflow)
2482          */
2483         unsigned char status = read_reg(info,TXDMA + DSR) & 0x30;
2484
2485         /* clear IRQ (BIT0 must be 1 to prevent clearing DE bit) */
2486         write_reg(info, TXDMA + DSR, (unsigned char)(status | 1));
2487
2488         if ( debug_level >= DEBUG_LEVEL_ISR )
2489                 printk("%s(%d):%s isr_txdmaerror(), status=%02x\n",
2490                         __FILE__,__LINE__,info->device_name,status);
2491 }
2492
2493 /* handle input serial signal changes
2494  */
2495 static void isr_io_pin( SLMP_INFO *info, u16 status )
2496 {
2497         struct  mgsl_icount *icount;
2498
2499         if ( debug_level >= DEBUG_LEVEL_ISR )
2500                 printk("%s(%d):isr_io_pin status=%04X\n",
2501                         __FILE__,__LINE__,status);
2502
2503         if (status & (MISCSTATUS_CTS_LATCHED | MISCSTATUS_DCD_LATCHED |
2504                       MISCSTATUS_DSR_LATCHED | MISCSTATUS_RI_LATCHED) ) {
2505                 icount = &info->icount;
2506                 /* update input line counters */
2507                 if (status & MISCSTATUS_RI_LATCHED) {
2508                         icount->rng++;
2509                         if ( status & SerialSignal_RI )
2510                                 info->input_signal_events.ri_up++;
2511                         else
2512                                 info->input_signal_events.ri_down++;
2513                 }
2514                 if (status & MISCSTATUS_DSR_LATCHED) {
2515                         icount->dsr++;
2516                         if ( status & SerialSignal_DSR )
2517                                 info->input_signal_events.dsr_up++;
2518                         else
2519                                 info->input_signal_events.dsr_down++;
2520                 }
2521                 if (status & MISCSTATUS_DCD_LATCHED) {
2522                         if ((info->dcd_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT) {
2523                                 info->ie1_value &= ~CDCD;
2524                                 write_reg(info, IE1, info->ie1_value);
2525                         }
2526                         icount->dcd++;
2527                         if (status & SerialSignal_DCD) {
2528                                 info->input_signal_events.dcd_up++;
2529                         } else
2530                                 info->input_signal_events.dcd_down++;
2531 #if SYNCLINK_GENERIC_HDLC
2532                         if (info->netcount) {
2533                                 if (status & SerialSignal_DCD)
2534                                         netif_carrier_on(info->netdev);
2535                                 else
2536                                         netif_carrier_off(info->netdev);
2537                         }
2538 #endif
2539                 }
2540                 if (status & MISCSTATUS_CTS_LATCHED)
2541                 {
2542                         if ((info->cts_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT) {
2543                                 info->ie1_value &= ~CCTS;
2544                                 write_reg(info, IE1, info->ie1_value);
2545                         }
2546                         icount->cts++;
2547                         if ( status & SerialSignal_CTS )
2548                                 info->input_signal_events.cts_up++;
2549                         else
2550                                 info->input_signal_events.cts_down++;
2551                 }
2552                 wake_up_interruptible(&info->status_event_wait_q);
2553                 wake_up_interruptible(&info->event_wait_q);
2554
2555                 if ( (info->flags & ASYNC_CHECK_CD) &&
2556                      (status & MISCSTATUS_DCD_LATCHED) ) {
2557                         if ( debug_level >= DEBUG_LEVEL_ISR )
2558                                 printk("%s CD now %s...", info->device_name,
2559                                        (status & SerialSignal_DCD) ? "on" : "off");
2560                         if (status & SerialSignal_DCD)
2561                                 wake_up_interruptible(&info->open_wait);
2562                         else {
2563                                 if ( debug_level >= DEBUG_LEVEL_ISR )
2564                                         printk("doing serial hangup...");
2565                                 if (info->tty)
2566                                         tty_hangup(info->tty);
2567                         }
2568                 }
2569
2570                 if ( (info->flags & ASYNC_CTS_FLOW) &&
2571                      (status & MISCSTATUS_CTS_LATCHED) ) {
2572                         if ( info->tty ) {
2573                                 if (info->tty->hw_stopped) {
2574                                         if (status & SerialSignal_CTS) {
2575                                                 if ( debug_level >= DEBUG_LEVEL_ISR )
2576                                                         printk("CTS tx start...");
2577                                                 info->tty->hw_stopped = 0;
2578                                                 tx_start(info);
2579                                                 info->pending_bh |= BH_TRANSMIT;
2580                                                 return;
2581                                         }
2582                                 } else {
2583                                         if (!(status & SerialSignal_CTS)) {
2584                                                 if ( debug_level >= DEBUG_LEVEL_ISR )
2585                                                         printk("CTS tx stop...");
2586                                                 info->tty->hw_stopped = 1;
2587                                                 tx_stop(info);
2588                                         }
2589                                 }
2590                         }
2591                 }
2592         }
2593
2594         info->pending_bh |= BH_STATUS;
2595 }
2596
2597 /* Interrupt service routine entry point.
2598  *
2599  * Arguments:
2600  *      irq             interrupt number that caused interrupt
2601  *      dev_id          device ID supplied during interrupt registration
2602  *      regs            interrupted processor context
2603  */
2604 static irqreturn_t synclinkmp_interrupt(int dummy, void *dev_id)
2605 {
2606         SLMP_INFO *info = dev_id;
2607         unsigned char status, status0, status1=0;
2608         unsigned char dmastatus, dmastatus0, dmastatus1=0;
2609         unsigned char timerstatus0, timerstatus1=0;
2610         unsigned char shift;
2611         unsigned int i;
2612         unsigned short tmp;
2613
2614         if ( debug_level >= DEBUG_LEVEL_ISR )
2615                 printk(KERN_DEBUG "%s(%d): synclinkmp_interrupt(%d)entry.\n",
2616                         __FILE__, __LINE__, info->irq_level);
2617
2618         spin_lock(&info->lock);
2619
2620         for(;;) {
2621
2622                 /* get status for SCA0 (ports 0-1) */
2623                 tmp = read_reg16(info, ISR0);   /* get ISR0 and ISR1 in one read */
2624                 status0 = (unsigned char)tmp;
2625                 dmastatus0 = (unsigned char)(tmp>>8);
2626                 timerstatus0 = read_reg(info, ISR2);
2627
2628                 if ( debug_level >= DEBUG_LEVEL_ISR )
2629                         printk(KERN_DEBUG "%s(%d):%s status0=%02x, dmastatus0=%02x, timerstatus0=%02x\n",
2630                                 __FILE__, __LINE__, info->device_name,
2631                                 status0, dmastatus0, timerstatus0);
2632
2633                 if (info->port_count == 4) {
2634                         /* get status for SCA1 (ports 2-3) */
2635                         tmp = read_reg16(info->port_array[2], ISR0);
2636                         status1 = (unsigned char)tmp;
2637                         dmastatus1 = (unsigned char)(tmp>>8);
2638                         timerstatus1 = read_reg(info->port_array[2], ISR2);
2639
2640                         if ( debug_level >= DEBUG_LEVEL_ISR )
2641                                 printk("%s(%d):%s status1=%02x, dmastatus1=%02x, timerstatus1=%02x\n",
2642                                         __FILE__,__LINE__,info->device_name,
2643                                         status1,dmastatus1,timerstatus1);
2644                 }
2645
2646                 if (!status0 && !dmastatus0 && !timerstatus0 &&
2647                          !status1 && !dmastatus1 && !timerstatus1)
2648                         break;
2649
2650                 for(i=0; i < info->port_count ; i++) {
2651                         if (info->port_array[i] == NULL)
2652                                 continue;
2653                         if (i < 2) {
2654                                 status = status0;
2655                                 dmastatus = dmastatus0;
2656                         } else {
2657                                 status = status1;
2658                                 dmastatus = dmastatus1;
2659                         }
2660
2661                         shift = i & 1 ? 4 :0;
2662
2663                         if (status & BIT0 << shift)
2664                                 isr_rxrdy(info->port_array[i]);
2665                         if (status & BIT1 << shift)
2666                                 isr_txrdy(info->port_array[i]);
2667                         if (status & BIT2 << shift)
2668                                 isr_rxint(info->port_array[i]);
2669                         if (status & BIT3 << shift)
2670                                 isr_txint(info->port_array[i]);
2671
2672                         if (dmastatus & BIT0 << shift)
2673                                 isr_rxdmaerror(info->port_array[i]);
2674                         if (dmastatus & BIT1 << shift)
2675                                 isr_rxdmaok(info->port_array[i]);
2676                         if (dmastatus & BIT2 << shift)
2677                                 isr_txdmaerror(info->port_array[i]);
2678                         if (dmastatus & BIT3 << shift)
2679                                 isr_txdmaok(info->port_array[i]);
2680                 }
2681
2682                 if (timerstatus0 & (BIT5 | BIT4))
2683                         isr_timer(info->port_array[0]);
2684                 if (timerstatus0 & (BIT7 | BIT6))
2685                         isr_timer(info->port_array[1]);
2686                 if (timerstatus1 & (BIT5 | BIT4))
2687                         isr_timer(info->port_array[2]);
2688                 if (timerstatus1 & (BIT7 | BIT6))
2689                         isr_timer(info->port_array[3]);
2690         }
2691
2692         for(i=0; i < info->port_count ; i++) {
2693                 SLMP_INFO * port = info->port_array[i];
2694
2695                 /* Request bottom half processing if there's something
2696                  * for it to do and the bh is not already running.
2697                  *
2698                  * Note: startup adapter diags require interrupts.
2699                  * do not request bottom half processing if the
2700                  * device is not open in a normal mode.
2701                  */
2702                 if ( port && (port->count || port->netcount) &&
2703                      port->pending_bh && !port->bh_running &&
2704                      !port->bh_requested ) {
2705                         if ( debug_level >= DEBUG_LEVEL_ISR )
2706                                 printk("%s(%d):%s queueing bh task.\n",
2707                                         __FILE__,__LINE__,port->device_name);
2708                         schedule_work(&port->task);
2709                         port->bh_requested = true;
2710                 }
2711         }
2712
2713         spin_unlock(&info->lock);
2714
2715         if ( debug_level >= DEBUG_LEVEL_ISR )
2716                 printk(KERN_DEBUG "%s(%d):synclinkmp_interrupt(%d)exit.\n",
2717                         __FILE__, __LINE__, info->irq_level);
2718         return IRQ_HANDLED;
2719 }
2720
2721 /* Initialize and start device.
2722  */
2723 static int startup(SLMP_INFO * info)
2724 {
2725         if ( debug_level >= DEBUG_LEVEL_INFO )
2726                 printk("%s(%d):%s tx_releaseup()\n",__FILE__,__LINE__,info->device_name);
2727
2728         if (info->flags & ASYNC_INITIALIZED)
2729                 return 0;
2730
2731         if (!info->tx_buf) {
2732                 info->tx_buf = kmalloc(info->max_frame_size, GFP_KERNEL);
2733                 if (!info->tx_buf) {
2734                         printk(KERN_ERR"%s(%d):%s can't allocate transmit buffer\n",
2735                                 __FILE__,__LINE__,info->device_name);
2736                         return -ENOMEM;
2737                 }
2738         }
2739
2740         info->pending_bh = 0;
2741
2742         memset(&info->icount, 0, sizeof(info->icount));
2743
2744         /* program hardware for current parameters */
2745         reset_port(info);
2746
2747         change_params(info);
2748
2749         mod_timer(&info->status_timer, jiffies + msecs_to_jiffies(10));
2750
2751         if (info->tty)
2752                 clear_bit(TTY_IO_ERROR, &info->tty->flags);
2753
2754         info->flags |= ASYNC_INITIALIZED;
2755
2756         return 0;
2757 }
2758
2759 /* Called by close() and hangup() to shutdown hardware
2760  */
2761 static void shutdown(SLMP_INFO * info)
2762 {
2763         unsigned long flags;
2764
2765         if (!(info->flags & ASYNC_INITIALIZED))
2766                 return;
2767
2768         if (debug_level >= DEBUG_LEVEL_INFO)
2769                 printk("%s(%d):%s synclinkmp_shutdown()\n",
2770                          __FILE__,__LINE__, info->device_name );
2771
2772         /* clear status wait queue because status changes */
2773         /* can't happen after shutting down the hardware */
2774         wake_up_interruptible(&info->status_event_wait_q);
2775         wake_up_interruptible(&info->event_wait_q);
2776
2777         del_timer(&info->tx_timer);
2778         del_timer(&info->status_timer);
2779
2780         kfree(info->tx_buf);
2781         info->tx_buf = NULL;
2782
2783         spin_lock_irqsave(&info->lock,flags);
2784
2785         reset_port(info);
2786
2787         if (!info->tty || info->tty->termios->c_cflag & HUPCL) {
2788                 info->serial_signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
2789                 set_signals(info);
2790         }
2791
2792         spin_unlock_irqrestore(&info->lock,flags);
2793
2794         if (info->tty)
2795                 set_bit(TTY_IO_ERROR, &info->tty->flags);
2796
2797         info->flags &= ~ASYNC_INITIALIZED;
2798 }
2799
2800 static void program_hw(SLMP_INFO *info)
2801 {
2802         unsigned long flags;
2803
2804         spin_lock_irqsave(&info->lock,flags);
2805
2806         rx_stop(info);
2807         tx_stop(info);
2808
2809         info->tx_count = info->tx_put = info->tx_get = 0;
2810
2811         if (info->params.mode == MGSL_MODE_HDLC || info->netcount)
2812                 hdlc_mode(info);
2813         else
2814                 async_mode(info);
2815
2816         set_signals(info);
2817
2818         info->dcd_chkcount = 0;
2819         info->cts_chkcount = 0;
2820         info->ri_chkcount = 0;
2821         info->dsr_chkcount = 0;
2822
2823         info->ie1_value |= (CDCD|CCTS);
2824         write_reg(info, IE1, info->ie1_value);
2825
2826         get_signals(info);
2827
2828         if (info->netcount || (info->tty && info->tty->termios->c_cflag & CREAD) )
2829                 rx_start(info);
2830
2831         spin_unlock_irqrestore(&info->lock,flags);
2832 }
2833
2834 /* Reconfigure adapter based on new parameters
2835  */
2836 static void change_params(SLMP_INFO *info)
2837 {
2838         unsigned cflag;
2839         int bits_per_char;
2840
2841         if (!info->tty || !info->tty->termios)
2842                 return;
2843
2844         if (debug_level >= DEBUG_LEVEL_INFO)
2845                 printk("%s(%d):%s change_params()\n",
2846                          __FILE__,__LINE__, info->device_name );
2847
2848         cflag = info->tty->termios->c_cflag;
2849
2850         /* if B0 rate (hangup) specified then negate DTR and RTS */
2851         /* otherwise assert DTR and RTS */
2852         if (cflag & CBAUD)
2853                 info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
2854         else
2855                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
2856
2857         /* byte size and parity */
2858
2859         switch (cflag & CSIZE) {
2860               case CS5: info->params.data_bits = 5; break;
2861               case CS6: info->params.data_bits = 6; break;
2862               case CS7: info->params.data_bits = 7; break;
2863               case CS8: info->params.data_bits = 8; break;
2864               /* Never happens, but GCC is too dumb to figure it out */
2865               default:  info->params.data_bits = 7; break;
2866               }
2867
2868         if (cflag & CSTOPB)
2869                 info->params.stop_bits = 2;
2870         else
2871                 info->params.stop_bits = 1;
2872
2873         info->params.parity = ASYNC_PARITY_NONE;
2874         if (cflag & PARENB) {
2875                 if (cflag & PARODD)
2876                         info->params.parity = ASYNC_PARITY_ODD;
2877                 else
2878                         info->params.parity = ASYNC_PARITY_EVEN;
2879 #ifdef CMSPAR
2880                 if (cflag & CMSPAR)
2881                         info->params.parity = ASYNC_PARITY_SPACE;
2882 #endif
2883         }
2884
2885         /* calculate number of jiffies to transmit a full
2886          * FIFO (32 bytes) at specified data rate
2887          */
2888         bits_per_char = info->params.data_bits +
2889                         info->params.stop_bits + 1;
2890
2891         /* if port data rate is set to 460800 or less then
2892          * allow tty settings to override, otherwise keep the
2893          * current data rate.
2894          */
2895         if (info->params.data_rate <= 460800) {
2896                 info->params.data_rate = tty_get_baud_rate(info->tty);
2897         }
2898
2899         if ( info->params.data_rate ) {
2900                 info->timeout = (32*HZ*bits_per_char) /
2901                                 info->params.data_rate;
2902         }
2903         info->timeout += HZ/50;         /* Add .02 seconds of slop */
2904
2905         if (cflag & CRTSCTS)
2906                 info->flags |= ASYNC_CTS_FLOW;
2907         else
2908                 info->flags &= ~ASYNC_CTS_FLOW;
2909
2910         if (cflag & CLOCAL)
2911                 info->flags &= ~ASYNC_CHECK_CD;
2912         else
2913                 info->flags |= ASYNC_CHECK_CD;
2914
2915         /* process tty input control flags */
2916
2917         info->read_status_mask2 = OVRN;
2918         if (I_INPCK(info->tty))
2919                 info->read_status_mask2 |= PE | FRME;
2920         if (I_BRKINT(info->tty) || I_PARMRK(info->tty))
2921                 info->read_status_mask1 |= BRKD;
2922         if (I_IGNPAR(info->tty))
2923                 info->ignore_status_mask2 |= PE | FRME;
2924         if (I_IGNBRK(info->tty)) {
2925                 info->ignore_status_mask1 |= BRKD;
2926                 /* If ignoring parity and break indicators, ignore
2927                  * overruns too.  (For real raw support).
2928                  */
2929                 if (I_IGNPAR(info->tty))
2930                         info->ignore_status_mask2 |= OVRN;
2931         }
2932
2933         program_hw(info);
2934 }
2935
2936 static int get_stats(SLMP_INFO * info, struct mgsl_icount __user *user_icount)
2937 {
2938         int err;
2939
2940         if (debug_level >= DEBUG_LEVEL_INFO)
2941                 printk("%s(%d):%s get_params()\n",
2942                          __FILE__,__LINE__, info->device_name);
2943
2944         if (!user_icount) {
2945                 memset(&info->icount, 0, sizeof(info->icount));
2946         } else {
2947                 COPY_TO_USER(err, user_icount, &info->icount, sizeof(struct mgsl_icount));
2948                 if (err)
2949                         return -EFAULT;
2950         }
2951
2952         return 0;
2953 }
2954
2955 static int get_params(SLMP_INFO * info, MGSL_PARAMS __user *user_params)
2956 {
2957         int err;
2958         if (debug_level >= DEBUG_LEVEL_INFO)
2959                 printk("%s(%d):%s get_params()\n",
2960                          __FILE__,__LINE__, info->device_name);
2961
2962         COPY_TO_USER(err,user_params, &info->params, sizeof(MGSL_PARAMS));
2963         if (err) {
2964                 if ( debug_level >= DEBUG_LEVEL_INFO )
2965                         printk( "%s(%d):%s get_params() user buffer copy failed\n",
2966                                 __FILE__,__LINE__,info->device_name);
2967                 return -EFAULT;
2968         }
2969
2970         return 0;
2971 }
2972
2973 static int set_params(SLMP_INFO * info, MGSL_PARAMS __user *new_params)
2974 {
2975         unsigned long flags;
2976         MGSL_PARAMS tmp_params;
2977         int err;
2978
2979         if (debug_level >= DEBUG_LEVEL_INFO)
2980                 printk("%s(%d):%s set_params\n",
2981                         __FILE__,__LINE__,info->device_name );
2982         COPY_FROM_USER(err,&tmp_params, new_params, sizeof(MGSL_PARAMS));
2983         if (err) {
2984                 if ( debug_level >= DEBUG_LEVEL_INFO )
2985                         printk( "%s(%d):%s set_params() user buffer copy failed\n",
2986                                 __FILE__,__LINE__,info->device_name);
2987                 return -EFAULT;
2988         }
2989
2990         spin_lock_irqsave(&info->lock,flags);
2991         memcpy(&info->params,&tmp_params,sizeof(MGSL_PARAMS));
2992         spin_unlock_irqrestore(&info->lock,flags);
2993
2994         change_params(info);
2995
2996         return 0;
2997 }
2998
2999 static int get_txidle(SLMP_INFO * info, int __user *idle_mode)
3000 {
3001         int err;
3002
3003         if (debug_level >= DEBUG_LEVEL_INFO)
3004                 printk("%s(%d):%s get_txidle()=%d\n",
3005                          __FILE__,__LINE__, info->device_name, info->idle_mode);
3006
3007         COPY_TO_USER(err,idle_mode, &info->idle_mode, sizeof(int));
3008         if (err) {
3009                 if ( debug_level >= DEBUG_LEVEL_INFO )
3010                         printk( "%s(%d):%s get_txidle() user buffer copy failed\n",
3011                                 __FILE__,__LINE__,info->device_name);
3012                 return -EFAULT;
3013         }
3014
3015         return 0;
3016 }
3017
3018 static int set_txidle(SLMP_INFO * info, int idle_mode)
3019 {
3020         unsigned long flags;
3021
3022         if (debug_level >= DEBUG_LEVEL_INFO)
3023                 printk("%s(%d):%s set_txidle(%d)\n",
3024                         __FILE__,__LINE__,info->device_name, idle_mode );
3025
3026         spin_lock_irqsave(&info->lock,flags);
3027         info->idle_mode = idle_mode;
3028         tx_set_idle( info );
3029         spin_unlock_irqrestore(&info->lock,flags);
3030         return 0;
3031 }
3032
3033 static int tx_enable(SLMP_INFO * info, int enable)
3034 {
3035         unsigned long flags;
3036
3037         if (debug_level >= DEBUG_LEVEL_INFO)
3038                 printk("%s(%d):%s tx_enable(%d)\n",
3039                         __FILE__,__LINE__,info->device_name, enable);
3040
3041         spin_lock_irqsave(&info->lock,flags);
3042         if ( enable ) {
3043                 if ( !info->tx_enabled ) {
3044                         tx_start(info);
3045                 }
3046         } else {
3047                 if ( info->tx_enabled )
3048                         tx_stop(info);
3049         }
3050         spin_unlock_irqrestore(&info->lock,flags);
3051         return 0;
3052 }
3053
3054 /* abort send HDLC frame
3055  */
3056 static int tx_abort(SLMP_INFO * info)
3057 {
3058         unsigned long flags;
3059
3060         if (debug_level >= DEBUG_LEVEL_INFO)
3061                 printk("%s(%d):%s tx_abort()\n",
3062                         __FILE__,__LINE__,info->device_name);
3063
3064         spin_lock_irqsave(&info->lock,flags);
3065         if ( info->tx_active && info->params.mode == MGSL_MODE_HDLC ) {
3066                 info->ie1_value &= ~UDRN;
3067                 info->ie1_value |= IDLE;
3068                 write_reg(info, IE1, info->ie1_value);  /* disable tx status interrupts */
3069                 write_reg(info, SR1, (unsigned char)(IDLE + UDRN));     /* clear pending */
3070
3071                 write_reg(info, TXDMA + DSR, 0);                /* disable DMA channel */
3072                 write_reg(info, TXDMA + DCMD, SWABORT); /* reset/init DMA channel */
3073
3074                 write_reg(info, CMD, TXABORT);
3075         }
3076         spin_unlock_irqrestore(&info->lock,flags);
3077         return 0;
3078 }
3079
3080 static int rx_enable(SLMP_INFO * info, int enable)
3081 {
3082         unsigned long flags;
3083
3084         if (debug_level >= DEBUG_LEVEL_INFO)
3085                 printk("%s(%d):%s rx_enable(%d)\n",
3086                         __FILE__,__LINE__,info->device_name,enable);
3087
3088         spin_lock_irqsave(&info->lock,flags);
3089         if ( enable ) {
3090                 if ( !info->rx_enabled )
3091                         rx_start(info);
3092         } else {
3093                 if ( info->rx_enabled )
3094                         rx_stop(info);
3095         }
3096         spin_unlock_irqrestore(&info->lock,flags);
3097         return 0;
3098 }
3099
3100 /* wait for specified event to occur
3101  */
3102 static int wait_mgsl_event(SLMP_INFO * info, int __user *mask_ptr)
3103 {
3104         unsigned long flags;
3105         int s;
3106         int rc=0;
3107         struct mgsl_icount cprev, cnow;
3108         int events;
3109         int mask;
3110         struct  _input_signal_events oldsigs, newsigs;
3111         DECLARE_WAITQUEUE(wait, current);
3112
3113         COPY_FROM_USER(rc,&mask, mask_ptr, sizeof(int));
3114         if (rc) {
3115                 return  -EFAULT;
3116         }
3117
3118         if (debug_level >= DEBUG_LEVEL_INFO)
3119                 printk("%s(%d):%s wait_mgsl_event(%d)\n",
3120                         __FILE__,__LINE__,info->device_name,mask);
3121
3122         spin_lock_irqsave(&info->lock,flags);
3123
3124         /* return immediately if state matches requested events */
3125         get_signals(info);
3126         s = info->serial_signals;
3127
3128         events = mask &
3129                 ( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) +
3130                   ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) +
3131                   ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) +
3132                   ((s & SerialSignal_RI)  ? MgslEvent_RiActive :MgslEvent_RiInactive) );
3133         if (events) {
3134                 spin_unlock_irqrestore(&info->lock,flags);
3135                 goto exit;
3136         }
3137
3138         /* save current irq counts */
3139         cprev = info->icount;
3140         oldsigs = info->input_signal_events;
3141
3142         /* enable hunt and idle irqs if needed */
3143         if (mask & (MgslEvent_ExitHuntMode+MgslEvent_IdleReceived)) {
3144                 unsigned char oldval = info->ie1_value;
3145                 unsigned char newval = oldval +
3146                          (mask & MgslEvent_ExitHuntMode ? FLGD:0) +
3147                          (mask & MgslEvent_IdleReceived ? IDLD:0);
3148                 if ( oldval != newval ) {
3149                         info->ie1_value = newval;
3150                         write_reg(info, IE1, info->ie1_value);
3151                 }
3152         }
3153
3154         set_current_state(TASK_INTERRUPTIBLE);
3155         add_wait_queue(&info->event_wait_q, &wait);
3156
3157         spin_unlock_irqrestore(&info->lock,flags);
3158
3159         for(;;) {
3160                 schedule();
3161                 if (signal_pending(current)) {
3162                         rc = -ERESTARTSYS;
3163                         break;
3164                 }
3165
3166                 /* get current irq counts */
3167                 spin_lock_irqsave(&info->lock,flags);
3168                 cnow = info->icount;
3169                 newsigs = info->input_signal_events;
3170                 set_current_state(TASK_INTERRUPTIBLE);
3171                 spin_unlock_irqrestore(&info->lock,flags);
3172
3173                 /* if no change, wait aborted for some reason */
3174                 if (newsigs.dsr_up   == oldsigs.dsr_up   &&
3175                     newsigs.dsr_down == oldsigs.dsr_down &&
3176                     newsigs.dcd_up   == oldsigs.dcd_up   &&
3177                     newsigs.dcd_down == oldsigs.dcd_down &&
3178                     newsigs.cts_up   == oldsigs.cts_up   &&
3179                     newsigs.cts_down == oldsigs.cts_down &&
3180                     newsigs.ri_up    == oldsigs.ri_up    &&
3181                     newsigs.ri_down  == oldsigs.ri_down  &&
3182                     cnow.exithunt    == cprev.exithunt   &&
3183                     cnow.rxidle      == cprev.rxidle) {
3184                         rc = -EIO;
3185                         break;
3186                 }
3187
3188                 events = mask &
3189                         ( (newsigs.dsr_up   != oldsigs.dsr_up   ? MgslEvent_DsrActive:0)   +
3190                           (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) +
3191                           (newsigs.dcd_up   != oldsigs.dcd_up   ? MgslEvent_DcdActive:0)   +
3192                           (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) +
3193                           (newsigs.cts_up   != oldsigs.cts_up   ? MgslEvent_CtsActive:0)   +
3194                           (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) +
3195                           (newsigs.ri_up    != oldsigs.ri_up    ? MgslEvent_RiActive:0)    +
3196                           (newsigs.ri_down  != oldsigs.ri_down  ? MgslEvent_RiInactive:0)  +
3197                           (cnow.exithunt    != cprev.exithunt   ? MgslEvent_ExitHuntMode:0) +
3198                           (cnow.rxidle      != cprev.rxidle     ? MgslEvent_IdleReceived:0) );
3199                 if (events)
3200                         break;
3201
3202                 cprev = cnow;
3203                 oldsigs = newsigs;
3204         }
3205
3206         remove_wait_queue(&info->event_wait_q, &wait);
3207         set_current_state(TASK_RUNNING);
3208
3209
3210         if (mask & (MgslEvent_ExitHuntMode + MgslEvent_IdleReceived)) {
3211                 spin_lock_irqsave(&info->lock,flags);
3212                 if (!waitqueue_active(&info->event_wait_q)) {
3213                         /* disable enable exit hunt mode/idle rcvd IRQs */
3214                         info->ie1_value &= ~(FLGD|IDLD);
3215                         write_reg(info, IE1, info->ie1_value);
3216                 }
3217                 spin_unlock_irqrestore(&info->lock,flags);
3218         }
3219 exit:
3220         if ( rc == 0 )
3221                 PUT_USER(rc, events, mask_ptr);
3222
3223         return rc;
3224 }
3225
3226 static int modem_input_wait(SLMP_INFO *info,int arg)
3227 {
3228         unsigned long flags;
3229         int rc;
3230         struct mgsl_icount cprev, cnow;
3231         DECLARE_WAITQUEUE(wait, current);
3232
3233         /* save current irq counts */
3234         spin_lock_irqsave(&info->lock,flags);
3235         cprev = info->icount;
3236         add_wait_queue(&info->status_event_wait_q, &wait);
3237         set_current_state(TASK_INTERRUPTIBLE);
3238         spin_unlock_irqrestore(&info->lock,flags);
3239
3240         for(;;) {
3241                 schedule();
3242                 if (signal_pending(current)) {
3243                         rc = -ERESTARTSYS;
3244                         break;
3245                 }
3246
3247                 /* get new irq counts */
3248                 spin_lock_irqsave(&info->lock,flags);
3249                 cnow = info->icount;
3250                 set_current_state(TASK_INTERRUPTIBLE);
3251                 spin_unlock_irqrestore(&info->lock,flags);
3252
3253                 /* if no change, wait aborted for some reason */
3254                 if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
3255                     cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) {
3256                         rc = -EIO;
3257                         break;
3258                 }
3259
3260                 /* check for change in caller specified modem input */
3261                 if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) ||
3262                     (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) ||
3263                     (arg & TIOCM_CD  && cnow.dcd != cprev.dcd) ||
3264                     (arg & TIOCM_CTS && cnow.cts != cprev.cts)) {
3265                         rc = 0;
3266                         break;
3267                 }
3268
3269                 cprev = cnow;
3270         }
3271         remove_wait_queue(&info->status_event_wait_q, &wait);
3272         set_current_state(TASK_RUNNING);
3273         return rc;
3274 }
3275
3276 /* return the state of the serial control and status signals
3277  */
3278 static int tiocmget(struct tty_struct *tty, struct file *file)
3279 {
3280         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
3281         unsigned int result;
3282         unsigned long flags;
3283
3284         spin_lock_irqsave(&info->lock,flags);
3285         get_signals(info);
3286         spin_unlock_irqrestore(&info->lock,flags);
3287
3288         result = ((info->serial_signals & SerialSignal_RTS) ? TIOCM_RTS:0) +
3289                 ((info->serial_signals & SerialSignal_DTR) ? TIOCM_DTR:0) +
3290                 ((info->serial_signals & SerialSignal_DCD) ? TIOCM_CAR:0) +
3291                 ((info->serial_signals & SerialSignal_RI)  ? TIOCM_RNG:0) +
3292                 ((info->serial_signals & SerialSignal_DSR) ? TIOCM_DSR:0) +
3293                 ((info->serial_signals & SerialSignal_CTS) ? TIOCM_CTS:0);
3294
3295         if (debug_level >= DEBUG_LEVEL_INFO)
3296                 printk("%s(%d):%s tiocmget() value=%08X\n",
3297                          __FILE__,__LINE__, info->device_name, result );
3298         return result;
3299 }
3300
3301 /* set modem control signals (DTR/RTS)
3302  */
3303 static int tiocmset(struct tty_struct *tty, struct file *file,
3304                     unsigned int set, unsigned int clear)
3305 {
3306         SLMP_INFO *info = (SLMP_INFO *)tty->driver_data;
3307         unsigned long flags;
3308
3309         if (debug_level >= DEBUG_LEVEL_INFO)
3310                 printk("%s(%d):%s tiocmset(%x,%x)\n",
3311                         __FILE__,__LINE__,info->device_name, set, clear);
3312
3313         if (set & TIOCM_RTS)
3314                 info->serial_signals |= SerialSignal_RTS;
3315         if (set & TIOCM_DTR)
3316                 info->serial_signals |= SerialSignal_DTR;
3317         if (clear & TIOCM_RTS)
3318                 info->serial_signals &= ~SerialSignal_RTS;
3319         if (clear & TIOCM_DTR)
3320                 info->serial_signals &= ~SerialSignal_DTR;
3321
3322         spin_lock_irqsave(&info->lock,flags);
3323         set_signals(info);
3324         spin_unlock_irqrestore(&info->lock,flags);
3325
3326         return 0;
3327 }
3328
3329
3330
3331 /* Block the current process until the specified port is ready to open.
3332  */
3333 static int block_til_ready(struct tty_struct *tty, struct file *filp,
3334                            SLMP_INFO *info)
3335 {
3336         DECLARE_WAITQUEUE(wait, current);
3337         int             retval;
3338         bool            do_clocal = false;
3339         bool            extra_count = false;
3340         unsigned long   flags;
3341
3342         if (debug_level >= DEBUG_LEVEL_INFO)
3343                 printk("%s(%d):%s block_til_ready()\n",
3344                          __FILE__,__LINE__, tty->driver->name );
3345
3346         if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){
3347                 /* nonblock mode is set or port is not enabled */
3348                 /* just verify that callout device is not active */
3349                 info->flags |= ASYNC_NORMAL_ACTIVE;
3350                 return 0;
3351         }
3352
3353         if (tty->termios->c_cflag & CLOCAL)
3354                 do_clocal = true;
3355
3356         /* Wait for carrier detect and the line to become
3357          * free (i.e., not in use by the callout).  While we are in
3358          * this loop, info->count is dropped by one, so that
3359          * close() knows when to free things.  We restore it upon
3360          * exit, either normal or abnormal.
3361          */
3362
3363         retval = 0;
3364         add_wait_queue(&info->open_wait, &wait);
3365
3366         if (debug_level >= DEBUG_LEVEL_INFO)
3367                 printk("%s(%d):%s block_til_ready() before block, count=%d\n",
3368                          __FILE__,__LINE__, tty->driver->name, info->count );
3369
3370         spin_lock_irqsave(&info->lock, flags);
3371         if (!tty_hung_up_p(filp)) {
3372                 extra_count = true;
3373                 info->count--;
3374         }
3375         spin_unlock_irqrestore(&info->lock, flags);
3376         info->blocked_open++;
3377
3378         while (1) {
3379                 if ((tty->termios->c_cflag & CBAUD)) {
3380                         spin_lock_irqsave(&info->lock,flags);
3381                         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
3382                         set_signals(info);
3383                         spin_unlock_irqrestore(&info->lock,flags);
3384                 }
3385
3386                 set_current_state(TASK_INTERRUPTIBLE);
3387
3388                 if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)){
3389                         retval = (info->flags & ASYNC_HUP_NOTIFY) ?
3390                                         -EAGAIN : -ERESTARTSYS;
3391                         break;
3392                 }
3393
3394                 spin_lock_irqsave(&info->lock,flags);
3395                 get_signals(info);
3396                 spin_unlock_irqrestore(&info->lock,flags);
3397
3398                 if (!(info->flags & ASYNC_CLOSING) &&
3399                     (do_clocal || (info->serial_signals & SerialSignal_DCD)) ) {
3400                         break;
3401                 }
3402
3403                 if (signal_pending(current)) {
3404                         retval = -ERESTARTSYS;
3405                         break;
3406                 }
3407
3408                 if (debug_level >= DEBUG_LEVEL_INFO)
3409                         printk("%s(%d):%s block_til_ready() count=%d\n",
3410                                  __FILE__,__LINE__, tty->driver->name, info->count );
3411
3412                 schedule();
3413         }
3414
3415         set_current_state(TASK_RUNNING);
3416         remove_wait_queue(&info->open_wait, &wait);
3417
3418         if (extra_count)
3419                 info->count++;
3420         info->blocked_open--;
3421
3422         if (debug_level >= DEBUG_LEVEL_INFO)
3423                 printk("%s(%d):%s block_til_ready() after, count=%d\n",
3424                          __FILE__,__LINE__, tty->driver->name, info->count );
3425
3426         if (!retval)
3427                 info->flags |= ASYNC_NORMAL_ACTIVE;
3428
3429         return retval;
3430 }
3431
3432 static int alloc_dma_bufs(SLMP_INFO *info)
3433 {
3434         unsigned short BuffersPerFrame;
3435         unsigned short BufferCount;
3436
3437         // Force allocation to start at 64K boundary for each port.
3438         // This is necessary because *all* buffer descriptors for a port
3439         // *must* be in the same 64K block. All descriptors on a port
3440         // share a common 'base' address (upper 8 bits of 24 bits) programmed
3441         // into the CBP register.
3442         info->port_array[0]->last_mem_alloc = (SCA_MEM_SIZE/4) * info->port_num;
3443
3444         /* Calculate the number of DMA buffers necessary to hold the */
3445         /* largest allowable frame size. Note: If the max frame size is */
3446         /* not an even multiple of the DMA buffer size then we need to */
3447         /* round the buffer count per frame up one. */
3448
3449         BuffersPerFrame = (unsigned short)(info->max_frame_size/SCABUFSIZE);
3450         if ( info->max_frame_size % SCABUFSIZE )
3451                 BuffersPerFrame++;
3452
3453         /* calculate total number of data buffers (SCABUFSIZE) possible
3454          * in one ports memory (SCA_MEM_SIZE/4) after allocating memory
3455          * for the descriptor list (BUFFERLISTSIZE).
3456          */
3457         BufferCount = (SCA_MEM_SIZE/4 - BUFFERLISTSIZE)/SCABUFSIZE;
3458
3459         /* limit number of buffers to maximum amount of descriptors */
3460         if (BufferCount > BUFFERLISTSIZE/sizeof(SCADESC))
3461                 BufferCount = BUFFERLISTSIZE/sizeof(SCADESC);
3462
3463         /* use enough buffers to transmit one max size frame */
3464         info->tx_buf_count = BuffersPerFrame + 1;
3465
3466         /* never use more than half the available buffers for transmit */
3467         if (info->tx_buf_count > (BufferCount/2))
3468                 info->tx_buf_count = BufferCount/2;
3469
3470         if (info->tx_buf_count > SCAMAXDESC)
3471                 info->tx_buf_count = SCAMAXDESC;
3472
3473         /* use remaining buffers for receive */
3474         info->rx_buf_count = BufferCount - info->tx_buf_count;
3475
3476         if (info->rx_buf_count > SCAMAXDESC)
3477                 info->rx_buf_count = SCAMAXDESC;
3478
3479         if ( debug_level >= DEBUG_LEVEL_INFO )
3480                 printk("%s(%d):%s Allocating %d TX and %d RX DMA buffers.\n",
3481                         __FILE__,__LINE__, info->device_name,
3482                         info->tx_buf_count,info->rx_buf_count);
3483
3484         if ( alloc_buf_list( info ) < 0 ||
3485                 alloc_frame_bufs(info,
3486                                         info->rx_buf_list,
3487                                         info->rx_buf_list_ex,
3488                                         info->rx_buf_count) < 0 ||
3489                 alloc_frame_bufs(info,
3490                                         info->tx_buf_list,
3491                                         info->tx_buf_list_ex,
3492                                         info->tx_buf_count) < 0 ||
3493                 alloc_tmp_rx_buf(info) < 0 ) {
3494                 printk("%s(%d):%s Can't allocate DMA buffer memory\n",
3495                         __FILE__,__LINE__, info->device_name);
3496                 return -ENOMEM;
3497         }
3498
3499         rx_reset_buffers( info );
3500
3501         return 0;
3502 }
3503
3504 /* Allocate DMA buffers for the transmit and receive descriptor lists.
3505  */
3506 static int alloc_buf_list(SLMP_INFO *info)
3507 {
3508         unsigned int i;
3509
3510         /* build list in adapter shared memory */
3511         info->buffer_list = info->memory_base + info->port_array[0]->last_mem_alloc;
3512         info->buffer_list_phys = info->port_array[0]->last_mem_alloc;
3513         info->port_array[0]->last_mem_alloc += BUFFERLISTSIZE;
3514
3515         memset(info->buffer_list, 0, BUFFERLISTSIZE);
3516
3517         /* Save virtual address pointers to the receive and */
3518         /* transmit buffer lists. (Receive 1st). These pointers will */
3519         /* be used by the processor to access the lists. */
3520         info->rx_buf_list = (SCADESC *)info->buffer_list;
3521
3522         info->tx_buf_list = (SCADESC *)info->buffer_list;
3523         info->tx_buf_list += info->rx_buf_count;
3524
3525         /* Build links for circular buffer entry lists (tx and rx)
3526          *
3527          * Note: links are physical addresses read by the SCA device
3528          * to determine the next buffer entry to use.
3529          */
3530
3531         for ( i = 0; i < info->rx_buf_count; i++ ) {
3532                 /* calculate and store physical address of this buffer entry */
3533                 info->rx_buf_list_ex[i].phys_entry =
3534                         info->buffer_list_phys + (i * sizeof(SCABUFSIZE));
3535
3536                 /* calculate and store physical address of */
3537                 /* next entry in cirular list of entries */
3538                 info->rx_buf_list[i].next = info->buffer_list_phys;
3539                 if ( i < info->rx_buf_count - 1 )
3540                         info->rx_buf_list[i].next += (i + 1) * sizeof(SCADESC);
3541
3542                 info->rx_buf_list[i].length = SCABUFSIZE;
3543         }
3544
3545         for ( i = 0; i < info->tx_buf_count; i++ ) {
3546                 /* calculate and store physical address of this buffer entry */
3547                 info->tx_buf_list_ex[i].phys_entry = info->buffer_list_phys +
3548                         ((info->rx_buf_count + i) * sizeof(SCADESC));
3549
3550                 /* calculate and store physical address of */
3551                 /* next entry in cirular list of entries */
3552
3553                 info->tx_buf_list[i].next = info->buffer_list_phys +
3554                         info->rx_buf_count * sizeof(SCADESC);
3555
3556                 if ( i < info->tx_buf_count - 1 )
3557                         info->tx_buf_list[i].next += (i + 1) * sizeof(SCADESC);
3558         }
3559
3560         return 0;
3561 }
3562
3563 /* Allocate the frame DMA buffers used by the specified buffer list.
3564  */
3565 static int alloc_frame_bufs(SLMP_INFO *info, SCADESC *buf_list,SCADESC_EX *buf_list_ex,int count)
3566 {
3567         int i;
3568         unsigned long phys_addr;
3569
3570         for ( i = 0; i < count; i++ ) {
3571                 buf_list_ex[i].virt_addr = info->memory_base + info->port_array[0]->last_mem_alloc;
3572                 phys_addr = info->port_array[0]->last_mem_alloc;
3573                 info->port_array[0]->last_mem_alloc += SCABUFSIZE;
3574
3575                 buf_list[i].buf_ptr  = (unsigned short)phys_addr;
3576                 buf_list[i].buf_base = (unsigned char)(phys_addr >> 16);
3577         }
3578
3579         return 0;
3580 }
3581
3582 static void free_dma_bufs(SLMP_INFO *info)
3583 {
3584         info->buffer_list = NULL;
3585         info->rx_buf_list = NULL;
3586         info->tx_buf_list = NULL;
3587 }
3588
3589 /* allocate buffer large enough to hold max_frame_size.
3590  * This buffer is used to pass an assembled frame to the line discipline.
3591  */
3592 static int alloc_tmp_rx_buf(SLMP_INFO *info)
3593 {
3594         info->tmp_rx_buf = kmalloc(info->max_frame_size, GFP_KERNEL);
3595         if (info->tmp_rx_buf == NULL)
3596                 return -ENOMEM;
3597         return 0;
3598 }
3599
3600 static void free_tmp_rx_buf(SLMP_INFO *info)
3601 {
3602         kfree(info->tmp_rx_buf);
3603         info->tmp_rx_buf = NULL;
3604 }
3605
3606 static int claim_resources(SLMP_INFO *info)
3607 {
3608         if (request_mem_region(info->phys_memory_base,SCA_MEM_SIZE,"synclinkmp") == NULL) {
3609                 printk( "%s(%d):%s mem addr conflict, Addr=%08X\n",
3610                         __FILE__,__LINE__,info->device_name, info->phys_memory_base);
3611                 info->init_error = DiagStatus_AddressConflict;
3612                 goto errout;
3613         }
3614         else
3615                 info->shared_mem_requested = true;
3616
3617         if (request_mem_region(info->phys_lcr_base + info->lcr_offset,128,"synclinkmp") == NULL) {
3618                 printk( "%s(%d):%s lcr mem addr conflict, Addr=%08X\n",
3619                         __FILE__,__LINE__,info->device_name, info->phys_lcr_base);
3620                 info->init_error = DiagStatus_AddressConflict;
3621                 goto errout;
3622         }
3623         else
3624                 info->lcr_mem_requested = true;
3625
3626         if (request_mem_region(info->phys_sca_base + info->sca_offset,SCA_BASE_SIZE,"synclinkmp") == NULL) {
3627                 printk( "%s(%d):%s sca mem addr conflict, Addr=%08X\n",
3628                         __FILE__,__LINE__,info->device_name, info->phys_sca_base);
3629                 info->init_error = DiagStatus_AddressConflict;
3630                 goto errout;
3631         }
3632         else
3633                 info->sca_base_requested = true;
3634
3635         if (request_mem_region(info->phys_statctrl_base + info->statctrl_offset,SCA_REG_SIZE,"synclinkmp") == NULL) {
3636                 printk( "%s(%d):%s stat/ctrl mem addr conflict, Addr=%08X\n",
3637                         __FILE__,__LINE__,info->device_name, info->phys_statctrl_base);
3638                 info->init_error = DiagStatus_AddressConflict;
3639                 goto errout;
3640         }
3641         else
3642                 info->sca_statctrl_requested = true;
3643
3644         info->memory_base = ioremap_nocache(info->phys_memory_base,
3645                                                                 SCA_MEM_SIZE);
3646         if (!info->memory_base) {
3647                 printk( "%s(%d):%s Cant map shared memory, MemAddr=%08X\n",
3648                         __FILE__,__LINE__,info->device_name, info->phys_memory_base );
3649                 info->init_error = DiagStatus_CantAssignPciResources;
3650                 goto errout;
3651         }
3652
3653         info->lcr_base = ioremap_nocache(info->phys_lcr_base, PAGE_SIZE);
3654         if (!info->lcr_base) {
3655                 printk( "%s(%d):%s Cant map LCR memory, MemAddr=%08X\n",
3656                         __FILE__,__LINE__,info->device_name, info->phys_lcr_base );
3657                 info->init_error = DiagStatus_CantAssignPciResources;
3658                 goto errout;
3659         }
3660         info->lcr_base += info->lcr_offset;
3661
3662         info->sca_base = ioremap_nocache(info->phys_sca_base, PAGE_SIZE);
3663         if (!info->sca_base) {
3664                 printk( "%s(%d):%s Cant map SCA memory, MemAddr=%08X\n",
3665                         __FILE__,__LINE__,info->device_name, info->phys_sca_base );
3666                 info->init_error = DiagStatus_CantAssignPciResources;
3667                 goto errout;
3668         }
3669         info->sca_base += info->sca_offset;
3670
3671         info->statctrl_base = ioremap_nocache(info->phys_statctrl_base,
3672                                                                 PAGE_SIZE);
3673         if (!info->statctrl_base) {
3674                 printk( "%s(%d):%s Cant map SCA Status/Control memory, MemAddr=%08X\n",
3675                         __FILE__,__LINE__,info->device_name, info->phys_statctrl_base );
3676                 info->init_error = DiagStatus_CantAssignPciResources;
3677                 goto errout;
3678         }
3679         info->statctrl_base += info->statctrl_offset;
3680
3681         if ( !memory_test(info) ) {
3682                 printk( "%s(%d):Shared Memory Test failed for device %s MemAddr=%08X\n",
3683                         __FILE__,__LINE__,info->device_name, info->phys_memory_base );
3684                 info->init_error = DiagStatus_MemoryError;
3685                 goto errout;
3686         }
3687
3688         return 0;
3689
3690 errout:
3691         release_resources( info );
3692         return -ENODEV;
3693 }
3694
3695 static void release_resources(SLMP_INFO *info)
3696 {
3697         if ( debug_level >= DEBUG_LEVEL_INFO )
3698                 printk( "%s(%d):%s release_resources() entry\n",
3699                         __FILE__,__LINE__,info->device_name );
3700
3701         if ( info->irq_requested ) {
3702                 free_irq(info->irq_level, info);
3703                 info->irq_requested = false;
3704         }
3705
3706         if ( info->shared_mem_requested ) {
3707                 release_mem_region(info->phys_memory_base,SCA_MEM_SIZE);
3708                 info->shared_mem_requested = false;
3709         }
3710         if ( info->lcr_mem_requested ) {
3711                 release_mem_region(info->phys_lcr_base + info->lcr_offset,128);
3712                 info->lcr_mem_requested = false;
3713         }
3714         if ( info->sca_base_requested ) {
3715                 release_mem_region(info->phys_sca_base + info->sca_offset,SCA_BASE_SIZE);
3716                 info->sca_base_requested = false;
3717         }
3718         if ( info->sca_statctrl_requested ) {
3719                 release_mem_region(info->phys_statctrl_base + info->statctrl_offset,SCA_REG_SIZE);
3720                 info->sca_statctrl_requested = false;
3721         }
3722
3723         if (info->memory_base){
3724                 iounmap(info->memory_base);
3725                 info->memory_base = NULL;
3726         }
3727
3728         if (info->sca_base) {
3729                 iounmap(info->sca_base - info->sca_offset);
3730                 info->sca_base=NULL;
3731         }
3732
3733         if (info->statctrl_base) {
3734                 iounmap(info->statctrl_base - info->statctrl_offset);
3735                 info->statctrl_base=NULL;
3736         }
3737
3738         if (info->lcr_base){
3739                 iounmap(info->lcr_base - info->lcr_offset);
3740                 info->lcr_base = NULL;
3741         }
3742
3743         if ( debug_level >= DEBUG_LEVEL_INFO )
3744                 printk( "%s(%d):%s release_resources() exit\n",
3745                         __FILE__,__LINE__,info->device_name );
3746 }
3747
3748 /* Add the specified device instance data structure to the
3749  * global linked list of devices and increment the device count.
3750  */
3751 static void add_device(SLMP_INFO *info)
3752 {
3753         info->next_device = NULL;
3754         info->line = synclinkmp_device_count;
3755         sprintf(info->device_name,"ttySLM%dp%d",info->adapter_num,info->port_num);
3756
3757         if (info->line < MAX_DEVICES) {
3758                 if (maxframe[info->line])
3759                         info->max_frame_size = maxframe[info->line];
3760                 info->dosyncppp = dosyncppp[info->line];
3761         }
3762
3763         synclinkmp_device_count++;
3764
3765         if ( !synclinkmp_device_list )
3766                 synclinkmp_device_list = info;
3767         else {
3768                 SLMP_INFO *current_dev = synclinkmp_device_list;
3769                 while( current_dev->next_device )
3770                         current_dev = current_dev->next_device;
3771                 current_dev->next_device = info;
3772         }
3773
3774         if ( info->max_frame_size < 4096 )
3775                 info->max_frame_size = 4096;
3776         else if ( info->max_frame_size > 65535 )
3777                 info->max_frame_size = 65535;
3778
3779         printk( "SyncLink MultiPort %s: "
3780                 "Mem=(%08x %08X %08x %08X) IRQ=%d MaxFrameSize=%u\n",
3781                 info->device_name,
3782                 info->phys_sca_base,
3783                 info->phys_memory_base,
3784                 info->phys_statctrl_base,
3785                 info->phys_lcr_base,
3786                 info->irq_level,
3787                 info->max_frame_size );
3788
3789 #if SYNCLINK_GENERIC_HDLC
3790         hdlcdev_init(info);
3791 #endif
3792 }
3793
3794 /* Allocate and initialize a device instance structure
3795  *
3796  * Return Value:        pointer to SLMP_INFO if success, otherwise NULL
3797  */
3798 static SLMP_INFO *alloc_dev(int adapter_num, int port_num, struct pci_dev *pdev)
3799 {
3800         SLMP_INFO *info;
3801
3802         info = kzalloc(sizeof(SLMP_INFO),
3803                  GFP_KERNEL);
3804
3805         if (!info) {
3806                 printk("%s(%d) Error can't allocate device instance data for adapter %d, port %d\n",
3807                         __FILE__,__LINE__, adapter_num, port_num);
3808         } else {
3809                 info->magic = MGSL_MAGIC;
3810                 INIT_WORK(&info->task, bh_handler);
3811                 info->max_frame_size = 4096;
3812                 info->close_delay = 5*HZ/10;
3813                 info->closing_wait = 30*HZ;
3814                 init_waitqueue_head(&info->open_wait);
3815                 init_waitqueue_head(&info->close_wait);
3816                 init_waitqueue_head(&info->status_event_wait_q);
3817                 init_waitqueue_head(&info->event_wait_q);
3818                 spin_lock_init(&info->netlock);
3819                 memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
3820                 info->idle_mode = HDLC_TXIDLE_FLAGS;
3821                 info->adapter_num = adapter_num;
3822                 info->port_num = port_num;
3823
3824                 /* Copy configuration info to device instance data */
3825                 info->irq_level = pdev->irq;
3826                 info->phys_lcr_base = pci_resource_start(pdev,0);
3827                 info->phys_sca_base = pci_resource_start(pdev,2);
3828                 info->phys_memory_base = pci_resource_start(pdev,3);
3829                 info->phys_statctrl_base = pci_resource_start(pdev,4);
3830
3831                 /* Because veremap only works on page boundaries we must map
3832                  * a larger area than is actually implemented for the LCR
3833                  * memory range. We map a full page starting at the page boundary.
3834                  */
3835                 info->lcr_offset    = info->phys_lcr_base & (PAGE_SIZE-1);
3836                 info->phys_lcr_base &= ~(PAGE_SIZE-1);
3837
3838                 info->sca_offset    = info->phys_sca_base & (PAGE_SIZE-1);
3839                 info->phys_sca_base &= ~(PAGE_SIZE-1);
3840
3841                 info->statctrl_offset    = info->phys_statctrl_base & (PAGE_SIZE-1);
3842                 info->phys_statctrl_base &= ~(PAGE_SIZE-1);
3843
3844                 info->bus_type = MGSL_BUS_TYPE_PCI;
3845                 info->irq_flags = IRQF_SHARED;
3846
3847                 setup_timer(&info->tx_timer, tx_timeout, (unsigned long)info);
3848                 setup_timer(&info->status_timer, status_timeout,
3849                                 (unsigned long)info);
3850
3851                 /* Store the PCI9050 misc control register value because a flaw
3852                  * in the PCI9050 prevents LCR registers from being read if
3853                  * BIOS assigns an LCR base address with bit 7 set.
3854                  *
3855                  * Only the misc control register is accessed for which only
3856                  * write access is needed, so set an initial value and change
3857                  * bits to the device instance data as we write the value
3858                  * to the actual misc control register.
3859                  */
3860                 info->misc_ctrl_value = 0x087e4546;
3861
3862                 /* initial port state is unknown - if startup errors
3863                  * occur, init_error will be set to indicate the
3864                  * problem. Once the port is fully initialized,
3865                  * this value will be set to 0 to indicate the
3866                  * port is available.
3867                  */
3868                 info->init_error = -1;
3869         }
3870
3871         return info;
3872 }
3873
3874 static void device_init(int adapter_num, struct pci_dev *pdev)
3875 {
3876         SLMP_INFO *port_array[SCA_MAX_PORTS];
3877         int port;
3878
3879         /* allocate device instances for up to SCA_MAX_PORTS devices */
3880         for ( port = 0; port < SCA_MAX_PORTS; ++port ) {
3881                 port_array[port] = alloc_dev(adapter_num,port,pdev);
3882                 if( port_array[port] == NULL ) {
3883                         for ( --port; port >= 0; --port )
3884                                 kfree(port_array[port]);
3885                         return;
3886                 }
3887         }
3888
3889         /* give copy of port_array to all ports and add to device list  */
3890         for ( port = 0; port < SCA_MAX_PORTS; ++port ) {
3891                 memcpy(port_array[port]->port_array,port_array,sizeof(port_array));
3892                 add_device( port_array[port] );
3893                 spin_lock_init(&port_array[port]->lock);
3894         }
3895
3896         /* Allocate and claim adapter resources */
3897         if ( !claim_resources(port_array[0]) ) {
3898
3899                 alloc_dma_bufs(port_array[0]);
3900
3901                 /* copy resource information from first port to others */
3902                 for ( port = 1; port < SCA_MAX_PORTS; ++port ) {
3903                         port_array[port]->lock  = port_array[0]->lock;
3904                         port_array[port]->irq_level     = port_array[0]->irq_level;
3905                         port_array[port]->memory_base   = port_array[0]->memory_base;
3906                         port_array[port]->sca_base      = port_array[0]->sca_base;
3907                         port_array[port]->statctrl_base = port_array[0]->statctrl_base;
3908                         port_array[port]->lcr_base      = port_array[0]->lcr_base;
3909                         alloc_dma_bufs(port_array[port]);
3910                 }
3911
3912                 if ( request_irq(port_array[0]->irq_level,
3913                                         synclinkmp_interrupt,
3914                                         port_array[0]->irq_flags,
3915                                         port_array[0]->device_name,
3916                                         port_array[0]) < 0 ) {
3917                         printk( "%s(%d):%s Cant request interrupt, IRQ=%d\n",
3918                                 __FILE__,__LINE__,
3919                                 port_array[0]->device_name,
3920                                 port_array[0]->irq_level );
3921                 }
3922                 else {
3923                         port_array[0]->irq_requested = true;
3924                         adapter_test(port_array[0]);
3925                 }
3926         }
3927 }
3928
3929 static const struct tty_operations ops = {
3930         .open = open,
3931         .close = close,
3932         .write = write,
3933         .put_char = put_char,
3934         .flush_chars = flush_chars,
3935         .write_room = write_room,
3936         .chars_in_buffer = chars_in_buffer,
3937         .flush_buffer = flush_buffer,
3938         .ioctl = ioctl,
3939         .throttle = throttle,
3940         .unthrottle = unthrottle,
3941         .send_xchar = send_xchar,
3942         .break_ctl = set_break,
3943         .wait_until_sent = wait_until_sent,
3944         .read_proc = read_proc,
3945         .set_termios = set_termios,
3946         .stop = tx_hold,
3947         .start = tx_release,
3948         .hangup = hangup,
3949         .tiocmget = tiocmget,
3950         .tiocmset = tiocmset,
3951 };
3952
3953 static void synclinkmp_cleanup(void)
3954 {
3955         int rc;
3956         SLMP_INFO *info;
3957         SLMP_INFO *tmp;
3958
3959         printk("Unloading %s %s\n", driver_name, driver_version);
3960
3961         if (serial_driver) {
3962                 if ((rc = tty_unregister_driver(serial_driver)))
3963                         printk("%s(%d) failed to unregister tty driver err=%d\n",
3964                                __FILE__,__LINE__,rc);
3965                 put_tty_driver(serial_driver);
3966         }
3967
3968         /* reset devices */
3969         info = synclinkmp_device_list;
3970         while(info) {
3971                 reset_port(info);
3972                 info = info->next_device;
3973         }
3974
3975         /* release devices */
3976         info = synclinkmp_device_list;
3977         while(info) {
3978 #if SYNCLINK_GENERIC_HDLC
3979                 hdlcdev_exit(info);
3980 #endif
3981                 free_dma_bufs(info);
3982                 free_tmp_rx_buf(info);
3983                 if ( info->port_num == 0 ) {
3984                         if (info->sca_base)
3985                                 write_reg(info, LPR, 1); /* set low power mode */
3986                         release_resources(info);
3987                 }
3988                 tmp = info;
3989                 info = info->next_device;
3990                 kfree(tmp);
3991         }
3992
3993         pci_unregister_driver(&synclinkmp_pci_driver);
3994 }
3995
3996 /* Driver initialization entry point.
3997  */
3998
3999 static int __init synclinkmp_init(void)
4000 {
4001         int rc;
4002
4003         if (break_on_load) {
4004                 synclinkmp_get_text_ptr();
4005                 BREAKPOINT();
4006         }
4007
4008         printk("%s %s\n", driver_name, driver_version);
4009
4010         if ((rc = pci_register_driver(&synclinkmp_pci_driver)) < 0) {
4011                 printk("%s:failed to register PCI driver, error=%d\n",__FILE__,rc);
4012                 return rc;
4013         }
4014
4015         serial_driver = alloc_tty_driver(128);
4016         if (!serial_driver) {
4017                 rc = -ENOMEM;
4018                 goto error;
4019         }
4020
4021         /* Initialize the tty_driver structure */
4022
4023         serial_driver->owner = THIS_MODULE;
4024         serial_driver->driver_name = "synclinkmp";
4025         serial_driver->name = "ttySLM";
4026         serial_driver->major = ttymajor;
4027         serial_driver->minor_start = 64;
4028         serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
4029         serial_driver->subtype = SERIAL_TYPE_NORMAL;
4030         serial_driver->init_termios = tty_std_termios;
4031         serial_driver->init_termios.c_cflag =
4032                 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
4033         serial_driver->init_termios.c_ispeed = 9600;
4034         serial_driver->init_termios.c_ospeed = 9600;
4035         serial_driver->flags = TTY_DRIVER_REAL_RAW;
4036         tty_set_operations(serial_driver, &ops);
4037         if ((rc = tty_register_driver(serial_driver)) < 0) {
4038                 printk("%s(%d):Couldn't register serial driver\n",
4039                         __FILE__,__LINE__);
4040                 put_tty_driver(serial_driver);
4041                 serial_driver = NULL;
4042                 goto error;
4043         }
4044
4045         printk("%s %s, tty major#%d\n",
4046                 driver_name, driver_version,
4047                 serial_driver->major);
4048
4049         return 0;
4050
4051 error:
4052         synclinkmp_cleanup();
4053         return rc;
4054 }
4055
4056 static void __exit synclinkmp_exit(void)
4057 {
4058         synclinkmp_cleanup();
4059 }
4060
4061 module_init(synclinkmp_init);
4062 module_exit(synclinkmp_exit);
4063
4064 /* Set the port for internal loopback mode.
4065  * The TxCLK and RxCLK signals are generated from the BRG and
4066  * the TxD is looped back to the RxD internally.
4067  */
4068 static void enable_loopback(SLMP_INFO *info, int enable)
4069 {
4070         if (enable) {
4071                 /* MD2 (Mode Register 2)
4072                  * 01..00  CNCT<1..0> Channel Connection 11=Local Loopback
4073                  */
4074                 write_reg(info, MD2, (unsigned char)(read_reg(info, MD2) | (BIT1 + BIT0)));
4075
4076                 /* degate external TxC clock source */
4077                 info->port_array[0]->ctrlreg_value |= (BIT0 << (info->port_num * 2));
4078                 write_control_reg(info);
4079
4080                 /* RXS/TXS (Rx/Tx clock source)
4081                  * 07      Reserved, must be 0
4082                  * 06..04  Clock Source, 100=BRG
4083                  * 03..00  Clock Divisor, 0000=1
4084                  */
4085                 write_reg(info, RXS, 0x40);
4086                 write_reg(info, TXS, 0x40);
4087
4088         } else {
4089                 /* MD2 (Mode Register 2)
4090                  * 01..00  CNCT<1..0> Channel connection, 0=normal
4091                  */
4092                 write_reg(info, MD2, (unsigned char)(read_reg(info, MD2) & ~(BIT1 + BIT0)));
4093
4094                 /* RXS/TXS (Rx/Tx clock source)
4095                  * 07      Reserved, must be 0
4096                  * 06..04  Clock Source, 000=RxC/TxC Pin
4097                  * 03..00  Clock Divisor, 0000=1
4098                  */
4099                 write_reg(info, RXS, 0x00);
4100                 write_reg(info, TXS, 0x00);
4101         }
4102
4103         /* set LinkSpeed if available, otherwise default to 2Mbps */
4104         if (info->params.clock_speed)
4105                 set_rate(info, info->params.clock_speed);
4106         else
4107                 set_rate(info, 3686400);
4108 }
4109
4110 /* Set the baud rate register to the desired speed
4111  *
4112  *      data_rate       data rate of clock in bits per second
4113  *                      A data rate of 0 disables the AUX clock.
4114  */
4115 static void set_rate( SLMP_INFO *info, u32 data_rate )
4116 {
4117         u32 TMCValue;
4118         unsigned char BRValue;
4119         u32 Divisor=0;
4120
4121         /* fBRG = fCLK/(TMC * 2^BR)
4122          */
4123         if (data_rate != 0) {
4124                 Divisor = 14745600/data_rate;
4125                 if (!Divisor)
4126                         Divisor = 1;
4127
4128                 TMCValue = Divisor;
4129
4130                 BRValue = 0;
4131                 if (TMCValue != 1 && TMCValue != 2) {
4132                         /* BRValue of 0 provides 50/50 duty cycle *only* when
4133                          * TMCValue is 1 or 2. BRValue of 1 to 9 always provides
4134                          * 50/50 duty cycle.
4135                          */
4136                         BRValue = 1;
4137                         TMCValue >>= 1;
4138                 }
4139
4140                 /* while TMCValue is too big for TMC register, divide
4141                  * by 2 and increment BR exponent.
4142                  */
4143                 for(; TMCValue > 256 && BRValue < 10; BRValue++)
4144                         TMCValue >>= 1;
4145
4146                 write_reg(info, TXS,
4147                         (unsigned char)((read_reg(info, TXS) & 0xf0) | BRValue));
4148                 write_reg(info, RXS,
4149                         (unsigned char)((read_reg(info, RXS) & 0xf0) | BRValue));
4150                 write_reg(info, TMC, (unsigned char)TMCValue);
4151         }
4152         else {
4153                 write_reg(info, TXS,0);
4154                 write_reg(info, RXS,0);
4155                 write_reg(info, TMC, 0);
4156         }
4157 }
4158
4159 /* Disable receiver
4160  */
4161 static void rx_stop(SLMP_INFO *info)
4162 {
4163         if (debug_level >= DEBUG_LEVEL_ISR)
4164                 printk("%s(%d):%s rx_stop()\n",
4165                          __FILE__,__LINE__, info->device_name );
4166
4167         write_reg(info, CMD, RXRESET);
4168
4169         info->ie0_value &= ~RXRDYE;
4170         write_reg(info, IE0, info->ie0_value);  /* disable Rx data interrupts */
4171
4172         write_reg(info, RXDMA + DSR, 0);        /* disable Rx DMA */
4173         write_reg(info, RXDMA + DCMD, SWABORT); /* reset/init Rx DMA */
4174         write_reg(info, RXDMA + DIR, 0);        /* disable Rx DMA interrupts */
4175
4176         info->rx_enabled = false;
4177         info->rx_overflow = false;
4178 }
4179
4180 /* enable the receiver
4181  */
4182 static void rx_start(SLMP_INFO *info)
4183 {
4184         int i;
4185
4186         if (debug_level >= DEBUG_LEVEL_ISR)
4187                 printk("%s(%d):%s rx_start()\n",
4188                          __FILE__,__LINE__, info->device_name );
4189
4190         write_reg(info, CMD, RXRESET);
4191
4192         if ( info->params.mode == MGSL_MODE_HDLC ) {
4193                 /* HDLC, disabe IRQ on rxdata */
4194                 info->ie0_value &= ~RXRDYE;
4195                 write_reg(info, IE0, info->ie0_value);
4196
4197                 /* Reset all Rx DMA buffers and program rx dma */
4198                 write_reg(info, RXDMA + DSR, 0);                /* disable Rx DMA */
4199                 write_reg(info, RXDMA + DCMD, SWABORT); /* reset/init Rx DMA */
4200
4201                 for (i = 0; i < info->rx_buf_count; i++) {
4202                         info->rx_buf_list[i].status = 0xff;
4203
4204                         // throttle to 4 shared memory writes at a time to prevent
4205                         // hogging local bus (keep latency time for DMA requests low).
4206                         if (!(i % 4))
4207                                 read_status_reg(info);
4208                 }
4209                 info->current_rx_buf = 0;
4210
4211                 /* set current/1st descriptor address */
4212                 write_reg16(info, RXDMA + CDA,
4213                         info->rx_buf_list_ex[0].phys_entry);
4214
4215                 /* set new last rx descriptor address */
4216                 write_reg16(info, RXDMA + EDA,
4217                         info->rx_buf_list_ex[info->rx_buf_count - 1].phys_entry);
4218
4219                 /* set buffer length (shared by all rx dma data buffers) */
4220                 write_reg16(info, RXDMA + BFL, SCABUFSIZE);
4221
4222                 write_reg(info, RXDMA + DIR, 0x60);     /* enable Rx DMA interrupts (EOM/BOF) */
4223                 write_reg(info, RXDMA + DSR, 0xf2);     /* clear Rx DMA IRQs, enable Rx DMA */
4224         } else {
4225                 /* async, enable IRQ on rxdata */
4226                 info->ie0_value |= RXRDYE;
4227                 write_reg(info, IE0, info->ie0_value);
4228         }
4229
4230         write_reg(info, CMD, RXENABLE);
4231
4232         info->rx_overflow = false;
4233         info->rx_enabled = true;
4234 }
4235
4236 /* Enable the transmitter and send a transmit frame if
4237  * one is loaded in the DMA buffers.
4238  */
4239 static void tx_start(SLMP_INFO *info)
4240 {
4241         if (debug_level >= DEBUG_LEVEL_ISR)
4242                 printk("%s(%d):%s tx_start() tx_count=%d\n",
4243                          __FILE__,__LINE__, info->device_name,info->tx_count );
4244
4245         if (!info->tx_enabled ) {
4246                 write_reg(info, CMD, TXRESET);
4247                 write_reg(info, CMD, TXENABLE);
4248                 info->tx_enabled = true;
4249         }
4250
4251         if ( info->tx_count ) {
4252
4253                 /* If auto RTS enabled and RTS is inactive, then assert */
4254                 /* RTS and set a flag indicating that the driver should */
4255                 /* negate RTS when the transmission completes. */
4256
4257                 info->drop_rts_on_tx_done = false;
4258
4259                 if (info->params.mode != MGSL_MODE_ASYNC) {
4260
4261                         if ( info->params.flags & HDLC_FLAG_AUTO_RTS ) {
4262                                 get_signals( info );
4263                                 if ( !(info->serial_signals & SerialSignal_RTS) ) {
4264                                         info->serial_signals |= SerialSignal_RTS;
4265                                         set_signals( info );
4266                                         info->drop_rts_on_tx_done = true;
4267                                 }
4268                         }
4269
4270                         write_reg16(info, TRC0,
4271                                 (unsigned short)(((tx_negate_fifo_level-1)<<8) + tx_active_fifo_level));
4272
4273                         write_reg(info, TXDMA + DSR, 0);                /* disable DMA channel */
4274                         write_reg(info, TXDMA + DCMD, SWABORT); /* reset/init DMA channel */
4275         
4276                         /* set TX CDA (current descriptor address) */
4277                         write_reg16(info, TXDMA + CDA,
4278                                 info->tx_buf_list_ex[0].phys_entry);
4279         
4280                         /* set TX EDA (last descriptor address) */
4281                         write_reg16(info, TXDMA + EDA,
4282                                 info->tx_buf_list_ex[info->last_tx_buf].phys_entry);
4283         
4284                         /* enable underrun IRQ */
4285                         info->ie1_value &= ~IDLE;
4286                         info->ie1_value |= UDRN;
4287                         write_reg(info, IE1, info->ie1_value);
4288                         write_reg(info, SR1, (unsigned char)(IDLE + UDRN));
4289         
4290                         write_reg(info, TXDMA + DIR, 0x40);             /* enable Tx DMA interrupts (EOM) */
4291                         write_reg(info, TXDMA + DSR, 0xf2);             /* clear Tx DMA IRQs, enable Tx DMA */
4292         
4293                         mod_timer(&info->tx_timer, jiffies +
4294                                         msecs_to_jiffies(5000));
4295                 }
4296                 else {
4297                         tx_load_fifo(info);
4298                         /* async, enable IRQ on txdata */
4299                         info->ie0_value |= TXRDYE;
4300                         write_reg(info, IE0, info->ie0_value);
4301                 }
4302
4303                 info->tx_active = true;
4304         }
4305 }
4306
4307 /* stop the transmitter and DMA
4308  */
4309 static void tx_stop( SLMP_INFO *info )
4310 {
4311         if (debug_level >= DEBUG_LEVEL_ISR)
4312                 printk("%s(%d):%s tx_stop()\n",
4313                          __FILE__,__LINE__, info->device_name );
4314
4315         del_timer(&info->tx_timer);
4316
4317         write_reg(info, TXDMA + DSR, 0);                /* disable DMA channel */
4318         write_reg(info, TXDMA + DCMD, SWABORT); /* reset/init DMA channel */
4319
4320         write_reg(info, CMD, TXRESET);
4321
4322         info->ie1_value &= ~(UDRN + IDLE);
4323         write_reg(info, IE1, info->ie1_value);  /* disable tx status interrupts */
4324         write_reg(info, SR1, (unsigned char)(IDLE + UDRN));     /* clear pending */
4325
4326         info->ie0_value &= ~TXRDYE;
4327         write_reg(info, IE0, info->ie0_value);  /* disable tx data interrupts */
4328
4329         info->tx_enabled = false;
4330         info->tx_active = false;
4331 }
4332
4333 /* Fill the transmit FIFO until the FIFO is full or
4334  * there is no more data to load.
4335  */
4336 static void tx_load_fifo(SLMP_INFO *info)
4337 {
4338         u8 TwoBytes[2];
4339
4340         /* do nothing is now tx data available and no XON/XOFF pending */
4341
4342         if ( !info->tx_count && !info->x_char )
4343                 return;
4344
4345         /* load the Transmit FIFO until FIFOs full or all data sent */
4346
4347         while( info->tx_count && (read_reg(info,SR0) & BIT1) ) {
4348
4349                 /* there is more space in the transmit FIFO and */
4350                 /* there is more data in transmit buffer */
4351
4352                 if ( (info->tx_count > 1) && !info->x_char ) {
4353                         /* write 16-bits */
4354                         TwoBytes[0] = info->tx_buf[info->tx_get++];
4355                         if (info->tx_get >= info->max_frame_size)
4356                                 info->tx_get -= info->max_frame_size;
4357                         TwoBytes[1] = info->tx_buf[info->tx_get++];
4358                         if (info->tx_get >= info->max_frame_size)
4359                                 info->tx_get -= info->max_frame_size;
4360
4361                         write_reg16(info, TRB, *((u16 *)TwoBytes));
4362
4363                         info->tx_count -= 2;
4364                         info->icount.tx += 2;
4365                 } else {
4366                         /* only 1 byte left to transmit or 1 FIFO slot left */
4367
4368                         if (info->x_char) {
4369                                 /* transmit pending high priority char */
4370                                 write_reg(info, TRB, info->x_char);
4371                                 info->x_char = 0;
4372                         } else {
4373                                 write_reg(info, TRB, info->tx_buf[info->tx_get++]);
4374                                 if (info->tx_get >= info->max_frame_size)
4375                                         info->tx_get -= info->max_frame_size;
4376                                 info->tx_count--;
4377                         }
4378                         info->icount.tx++;
4379                 }
4380         }
4381 }
4382
4383 /* Reset a port to a known state
4384  */
4385 static void reset_port(SLMP_INFO *info)
4386 {
4387         if (info->sca_base) {
4388
4389                 tx_stop(info);
4390                 rx_stop(info);
4391
4392                 info->serial_signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
4393                 set_signals(info);
4394
4395                 /* disable all port interrupts */
4396                 info->ie0_value = 0;
4397                 info->ie1_value = 0;
4398                 info->ie2_value = 0;
4399                 write_reg(info, IE0, info->ie0_value);
4400                 write_reg(info, IE1, info->ie1_value);
4401                 write_reg(info, IE2, info->ie2_value);
4402
4403                 write_reg(info, CMD, CHRESET);
4404         }
4405 }
4406
4407 /* Reset all the ports to a known state.
4408  */
4409 static void reset_adapter(SLMP_INFO *info)
4410 {
4411         int i;
4412
4413         for ( i=0; i < SCA_MAX_PORTS; ++i) {
4414                 if (info->port_array[i])
4415                         reset_port(info->port_array[i]);
4416         }
4417 }
4418
4419 /* Program port for asynchronous communications.
4420  */
4421 static void async_mode(SLMP_INFO *info)
4422 {
4423
4424         unsigned char RegValue;
4425
4426         tx_stop(info);
4427         rx_stop(info);
4428
4429         /* MD0, Mode Register 0
4430          *
4431          * 07..05  PRCTL<2..0>, Protocol Mode, 000=async
4432          * 04      AUTO, Auto-enable (RTS/CTS/DCD)
4433          * 03      Reserved, must be 0
4434          * 02      CRCCC, CRC Calculation, 0=disabled
4435          * 01..00  STOP<1..0> Stop bits (00=1,10=2)
4436          *
4437          * 0000 0000
4438          */
4439         RegValue = 0x00;
4440         if (info->params.stop_bits != 1)
4441                 RegValue |= BIT1;
4442         write_reg(info, MD0, RegValue);
4443
4444         /* MD1, Mode Register 1
4445          *
4446          * 07..06  BRATE<1..0>, bit rate, 00=1/1 01=1/16 10=1/32 11=1/64
4447          * 05..04  TXCHR<1..0>, tx char size, 00=8 bits,01=7,10=6,11=5
4448          * 03..02  RXCHR<1..0>, rx char size
4449          * 01..00  PMPM<1..0>, Parity mode, 00=none 10=even 11=odd
4450          *
4451          * 0100 0000
4452          */
4453         RegValue = 0x40;
4454         switch (info->params.data_bits) {
4455         case 7: RegValue |= BIT4 + BIT2; break;
4456         case 6: RegValue |= BIT5 + BIT3; break;
4457         case 5: RegValue |= BIT5 + BIT4 + BIT3 + BIT2; break;
4458         }
4459         if (info->params.parity != ASYNC_PARITY_NONE) {
4460                 RegValue |= BIT1;
4461                 if (info->params.parity == ASYNC_PARITY_ODD)
4462                         RegValue |= BIT0;
4463         }
4464         write_reg(info, MD1, RegValue);
4465
4466         /* MD2, Mode Register 2
4467          *
4468          * 07..02  Reserved, must be 0
4469          * 01..00  CNCT<1..0> Channel connection, 00=normal 11=local loopback
4470          *
4471          * 0000 0000
4472          */
4473         RegValue = 0x00;
4474         if (info->params.loopback)
4475                 RegValue |= (BIT1 + BIT0);
4476         write_reg(info, MD2, RegValue);
4477
4478         /* RXS, Receive clock source
4479          *
4480          * 07      Reserved, must be 0
4481          * 06..04  RXCS<2..0>, clock source, 000=RxC Pin, 100=BRG, 110=DPLL
4482          * 03..00  RXBR<3..0>, rate divisor, 0000=1
4483          */
4484         RegValue=BIT6;
4485         write_reg(info, RXS, RegValue);
4486
4487         /* TXS, Transmit clock source
4488          *
4489          * 07      Reserved, must be 0
4490          * 06..04  RXCS<2..0>, clock source, 000=TxC Pin, 100=BRG, 110=Receive Clock
4491          * 03..00  RXBR<3..0>, rate divisor, 0000=1
4492          */
4493         RegValue=BIT6;
4494         write_reg(info, TXS, RegValue);
4495
4496         /* Control Register
4497          *
4498          * 6,4,2,0  CLKSEL<3..0>, 0 = TcCLK in, 1 = Auxclk out
4499          */
4500         info->port_array[0]->ctrlreg_value |= (BIT0 << (info->port_num * 2));
4501         write_control_reg(info);
4502
4503         tx_set_idle(info);
4504
4505         /* RRC Receive Ready Control 0
4506          *
4507          * 07..05  Reserved, must be 0
4508          * 04..00  RRC<4..0> Rx FIFO trigger active 0x00 = 1 byte
4509          */
4510         write_reg(info, RRC, 0x00);
4511
4512         /* TRC0 Transmit Ready Control 0
4513          *
4514          * 07..05  Reserved, must be 0
4515          * 04..00  TRC<4..0> Tx FIFO trigger active 0x10 = 16 bytes
4516          */
4517         write_reg(info, TRC0, 0x10);
4518
4519         /* TRC1 Transmit Ready Control 1
4520          *
4521          * 07..05  Reserved, must be 0
4522          * 04..00  TRC<4..0> Tx FIFO trigger inactive 0x1e = 31 bytes (full-1)
4523          */
4524         write_reg(info, TRC1, 0x1e);
4525
4526         /* CTL, MSCI control register
4527          *
4528          * 07..06  Reserved, set to 0
4529          * 05      UDRNC, underrun control, 0=abort 1=CRC+flag (HDLC/BSC)
4530          * 04      IDLC, idle control, 0=mark 1=idle register
4531          * 03      BRK, break, 0=off 1 =on (async)
4532          * 02      SYNCLD, sync char load enable (BSC) 1=enabled
4533          * 01      GOP, go active on poll (LOOP mode) 1=enabled
4534          * 00      RTS, RTS output control, 0=active 1=inactive
4535          *
4536          * 0001 0001
4537          */
4538         RegValue = 0x10;
4539         if (!(info->serial_signals & SerialSignal_RTS))
4540                 RegValue |= 0x01;
4541         write_reg(info, CTL, RegValue);
4542
4543         /* enable status interrupts */
4544         info->ie0_value |= TXINTE + RXINTE;
4545         write_reg(info, IE0, info->ie0_value);
4546
4547         /* enable break detect interrupt */
4548         info->ie1_value = BRKD;
4549         write_reg(info, IE1, info->ie1_value);
4550
4551         /* enable rx overrun interrupt */
4552         info->ie2_value = OVRN;
4553         write_reg(info, IE2, info->ie2_value);
4554
4555         set_rate( info, info->params.data_rate * 16 );
4556 }
4557
4558 /* Program the SCA for HDLC communications.
4559  */
4560 static void hdlc_mode(SLMP_INFO *info)
4561 {
4562         unsigned char RegValue;
4563         u32 DpllDivisor;
4564
4565         // Can't use DPLL because SCA outputs recovered clock on RxC when
4566         // DPLL mode selected. This causes output contention with RxC receiver.
4567         // Use of DPLL would require external hardware to disable RxC receiver
4568         // when DPLL mode selected.
4569         info->params.flags &= ~(HDLC_FLAG_TXC_DPLL + HDLC_FLAG_RXC_DPLL);
4570
4571         /* disable DMA interrupts */
4572         write_reg(info, TXDMA + DIR, 0);
4573         write_reg(info, RXDMA + DIR, 0);
4574
4575         /* MD0, Mode Register 0
4576          *
4577          * 07..05  PRCTL<2..0>, Protocol Mode, 100=HDLC
4578          * 04      AUTO, Auto-enable (RTS/CTS/DCD)
4579          * 03      Reserved, must be 0
4580          * 02      CRCCC, CRC Calculation, 1=enabled
4581          * 01      CRC1, CRC selection, 0=CRC-16,1=CRC-CCITT-16
4582          * 00      CRC0, CRC initial value, 1 = all 1s
4583          *
4584          * 1000 0001
4585          */
4586         RegValue = 0x81;
4587         if (info->params.flags & HDLC_FLAG_AUTO_CTS)
4588                 RegValue |= BIT4;
4589         if (info->params.flags & HDLC_FLAG_AUTO_DCD)
4590                 RegValue |= BIT4;
4591         if (info->params.crc_type == HDLC_CRC_16_CCITT)
4592                 RegValue |= BIT2 + BIT1;
4593         write_reg(info, MD0, RegValue);
4594
4595         /* MD1, Mode Register 1
4596          *
4597          * 07..06  ADDRS<1..0>, Address detect, 00=no addr check
4598          * 05..04  TXCHR<1..0>, tx char size, 00=8 bits
4599          * 03..02  RXCHR<1..0>, rx char size, 00=8 bits
4600          * 01..00  PMPM<1..0>, Parity mode, 00=no parity
4601          *
4602          * 0000 0000
4603          */
4604         RegValue = 0x00;
4605         write_reg(info, MD1, RegValue);
4606
4607         /* MD2, Mode Register 2
4608          *
4609          * 07      NRZFM, 0=NRZ, 1=FM
4610          * 06..05  CODE<1..0> Encoding, 00=NRZ
4611          * 04..03  DRATE<1..0> DPLL Divisor, 00=8
4612          * 02      Reserved, must be 0
4613          * 01..00  CNCT<1..0> Channel connection, 0=normal
4614          *
4615          * 0000 0000
4616          */
4617         RegValue = 0x00;
4618         switch(info->params.encoding) {
4619         case HDLC_ENCODING_NRZI:          RegValue |= BIT5; break;
4620         case HDLC_ENCODING_BIPHASE_MARK:  RegValue |= BIT7 + BIT5; break; /* aka FM1 */
4621         case HDLC_ENCODING_BIPHASE_SPACE: RegValue |= BIT7 + BIT6; break; /* aka FM0 */
4622         case HDLC_ENCODING_BIPHASE_LEVEL: RegValue |= BIT7; break;      /* aka Manchester */
4623 #if 0
4624         case HDLC_ENCODING_NRZB:                                        /* not supported */
4625         case HDLC_ENCODING_NRZI_MARK:                                   /* not supported */
4626         case HDLC_ENCODING_DIFF_BIPHASE_LEVEL:                          /* not supported */
4627 #endif
4628         }
4629         if ( info->params.flags & HDLC_FLAG_DPLL_DIV16 ) {
4630                 DpllDivisor = 16;
4631                 RegValue |= BIT3;
4632         } else if ( info->params.flags & HDLC_FLAG_DPLL_DIV8 ) {
4633                 DpllDivisor = 8;
4634         } else {
4635                 DpllDivisor = 32;
4636                 RegValue |= BIT4;
4637         }
4638         write_reg(info, MD2, RegValue);
4639
4640
4641         /* RXS, Receive clock source
4642          *
4643          * 07      Reserved, must be 0
4644          * 06..04  RXCS<2..0>, clock source, 000=RxC Pin, 100=BRG, 110=DPLL
4645          * 03..00  RXBR<3..0>, rate divisor, 0000=1
4646          */
4647         RegValue=0;
4648         if (info->params.flags & HDLC_FLAG_RXC_BRG)
4649                 RegValue |= BIT6;
4650         if (info->params.flags & HDLC_FLAG_RXC_DPLL)
4651                 RegValue |= BIT6 + BIT5;
4652         write_reg(info, RXS, RegValue);
4653
4654         /* TXS, Transmit clock source
4655          *
4656          * 07      Reserved, must be 0
4657          * 06..04  RXCS<2..0>, clock source, 000=TxC Pin, 100=BRG, 110=Receive Clock
4658          * 03..00  RXBR<3..0>, rate divisor, 0000=1
4659          */
4660         RegValue=0;
4661         if (info->params.flags & HDLC_FLAG_TXC_BRG)
4662                 RegValue |= BIT6;
4663         if (info->params.flags & HDLC_FLAG_TXC_DPLL)
4664                 RegValue |= BIT6 + BIT5;
4665         write_reg(info, TXS, RegValue);
4666
4667         if (info->params.flags & HDLC_FLAG_RXC_DPLL)
4668                 set_rate(info, info->params.clock_speed * DpllDivisor);
4669         else
4670                 set_rate(info, info->params.clock_speed);
4671
4672         /* GPDATA (General Purpose I/O Data Register)
4673          *
4674          * 6,4,2,0  CLKSEL<3..0>, 0 = TcCLK in, 1 = Auxclk out
4675          */
4676         if (info->params.flags & HDLC_FLAG_TXC_BRG)
4677                 info->port_array[0]->ctrlreg_value |= (BIT0 << (info->port_num * 2));
4678         else
4679                 info->port_array[0]->ctrlreg_value &= ~(BIT0 << (info->port_num * 2));
4680         write_control_reg(info);
4681
4682         /* RRC Receive Ready Control 0
4683          *
4684          * 07..05  Reserved, must be 0
4685          * 04..00  RRC<4..0> Rx FIFO trigger active
4686          */
4687         write_reg(info, RRC, rx_active_fifo_level);
4688
4689         /* TRC0 Transmit Ready Control 0
4690          *
4691          * 07..05  Reserved, must be 0
4692          * 04..00  TRC<4..0> Tx FIFO trigger active
4693          */
4694         write_reg(info, TRC0, tx_active_fifo_level);
4695
4696         /* TRC1 Transmit Ready Control 1
4697          *
4698          * 07..05  Reserved, must be 0
4699          * 04..00  TRC<4..0> Tx FIFO trigger inactive 0x1f = 32 bytes (full)
4700          */
4701         write_reg(info, TRC1, (unsigned char)(tx_negate_fifo_level - 1));
4702
4703         /* DMR, DMA Mode Register
4704          *
4705          * 07..05  Reserved, must be 0
4706          * 04      TMOD, Transfer Mode: 1=chained-block
4707          * 03      Reserved, must be 0
4708          * 02      NF, Number of Frames: 1=multi-frame
4709          * 01      CNTE, Frame End IRQ Counter enable: 0=disabled
4710          * 00      Reserved, must be 0
4711          *
4712          * 0001 0100
4713          */
4714         write_reg(info, TXDMA + DMR, 0x14);
4715         write_reg(info, RXDMA + DMR, 0x14);
4716
4717         /* Set chain pointer base (upper 8 bits of 24 bit addr) */
4718         write_reg(info, RXDMA + CPB,
4719                 (unsigned char)(info->buffer_list_phys >> 16));
4720
4721         /* Set chain pointer base (upper 8 bits of 24 bit addr) */
4722         write_reg(info, TXDMA + CPB,
4723                 (unsigned char)(info->buffer_list_phys >> 16));
4724
4725         /* enable status interrupts. other code enables/disables
4726          * the individual sources for these two interrupt classes.
4727          */
4728         info->ie0_value |= TXINTE + RXINTE;
4729         write_reg(info, IE0, info->ie0_value);
4730
4731         /* CTL, MSCI control register
4732          *
4733          * 07..06  Reserved, set to 0
4734          * 05      UDRNC, underrun control, 0=abort 1=CRC+flag (HDLC/BSC)
4735          * 04      IDLC, idle control, 0=mark 1=idle register
4736          * 03      BRK, break, 0=off 1 =on (async)
4737          * 02      SYNCLD, sync char load enable (BSC) 1=enabled
4738          * 01      GOP, go active on poll (LOOP mode) 1=enabled
4739          * 00      RTS, RTS output control, 0=active 1=inactive
4740          *
4741          * 0001 0001
4742          */
4743         RegValue = 0x10;
4744         if (!(info->serial_signals & SerialSignal_RTS))
4745                 RegValue |= 0x01;
4746         write_reg(info, CTL, RegValue);
4747
4748         /* preamble not supported ! */
4749
4750         tx_set_idle(info);
4751         tx_stop(info);
4752         rx_stop(info);
4753
4754         set_rate(info, info->params.clock_speed);
4755
4756         if (info->params.loopback)
4757                 enable_loopback(info,1);
4758 }
4759
4760 /* Set the transmit HDLC idle mode
4761  */
4762 static void tx_set_idle(SLMP_INFO *info)
4763 {
4764         unsigned char RegValue = 0xff;
4765
4766         /* Map API idle mode to SCA register bits */
4767         switch(info->idle_mode) {
4768         case HDLC_TXIDLE_FLAGS:                 RegValue = 0x7e; break;
4769         case HDLC_TXIDLE_ALT_ZEROS_ONES:        RegValue = 0xaa; break;
4770         case HDLC_TXIDLE_ZEROS:                 RegValue = 0x00; break;
4771         case HDLC_TXIDLE_ONES:                  RegValue = 0xff; break;
4772         case HDLC_TXIDLE_ALT_MARK_SPACE:        RegValue = 0xaa; break;
4773         case HDLC_TXIDLE_SPACE:                 RegValue = 0x00; break;
4774         case HDLC_TXIDLE_MARK:                  RegValue = 0xff; break;
4775         }
4776
4777         write_reg(info, IDL, RegValue);
4778 }
4779
4780 /* Query the adapter for the state of the V24 status (input) signals.
4781  */
4782 static void get_signals(SLMP_INFO *info)
4783 {
4784         u16 status = read_reg(info, SR3);
4785         u16 gpstatus = read_status_reg(info);
4786         u16 testbit;
4787
4788         /* clear all serial signals except DTR and RTS */
4789         info->serial_signals &= SerialSignal_DTR + SerialSignal_RTS;
4790
4791         /* set serial signal bits to reflect MISR */
4792
4793         if (!(status & BIT3))
4794                 info->serial_signals |= SerialSignal_CTS;
4795
4796         if ( !(status & BIT2))
4797                 info->serial_signals |= SerialSignal_DCD;
4798
4799         testbit = BIT1 << (info->port_num * 2); // Port 0..3 RI is GPDATA<1,3,5,7>
4800         if (!(gpstatus & testbit))
4801                 info->serial_signals |= SerialSignal_RI;
4802
4803         testbit = BIT0 << (info->port_num * 2); // Port 0..3 DSR is GPDATA<0,2,4,6>
4804         if (!(gpstatus & testbit))
4805                 info->serial_signals |= SerialSignal_DSR;
4806 }
4807
4808 /* Set the state of DTR and RTS based on contents of
4809  * serial_signals member of device context.
4810  */
4811 static void set_signals(SLMP_INFO *info)
4812 {
4813         unsigned char RegValue;
4814         u16 EnableBit;
4815
4816         RegValue = read_reg(info, CTL);
4817         if (info->serial_signals & SerialSignal_RTS)
4818                 RegValue &= ~BIT0;
4819         else
4820                 RegValue |= BIT0;
4821         write_reg(info, CTL, RegValue);
4822
4823         // Port 0..3 DTR is ctrl reg <1,3,5,7>
4824         EnableBit = BIT1 << (info->port_num*2);
4825         if (info->serial_signals & SerialSignal_DTR)
4826                 info->port_array[0]->ctrlreg_value &= ~EnableBit;
4827         else
4828                 info->port_array[0]->ctrlreg_value |= EnableBit;
4829         write_control_reg(info);
4830 }
4831
4832 /*******************/
4833 /* DMA Buffer Code */
4834 /*******************/
4835
4836 /* Set the count for all receive buffers to SCABUFSIZE
4837  * and set the current buffer to the first buffer. This effectively
4838  * makes all buffers free and discards any data in buffers.
4839  */
4840 static void rx_reset_buffers(SLMP_INFO *info)
4841 {
4842         rx_free_frame_buffers(info, 0, info->rx_buf_count - 1);
4843 }
4844
4845 /* Free the buffers used by a received frame
4846  *
4847  * info   pointer to device instance data
4848  * first  index of 1st receive buffer of frame
4849  * last   index of last receive buffer of frame
4850  */
4851 static void rx_free_frame_buffers(SLMP_INFO *info, unsigned int first, unsigned int last)
4852 {
4853         bool done = false;
4854
4855         while(!done) {
4856                 /* reset current buffer for reuse */
4857                 info->rx_buf_list[first].status = 0xff;
4858
4859                 if (first == last) {
4860                         done = true;
4861                         /* set new last rx descriptor address */
4862                         write_reg16(info, RXDMA + EDA, info->rx_buf_list_ex[first].phys_entry);
4863                 }
4864
4865                 first++;
4866                 if (first == info->rx_buf_count)
4867                         first = 0;
4868         }
4869
4870         /* set current buffer to next buffer after last buffer of frame */
4871         info->current_rx_buf = first;
4872 }
4873
4874 /* Return a received frame from the receive DMA buffers.
4875  * Only frames received without errors are returned.
4876  *
4877  * Return Value:        true if frame returned, otherwise false
4878  */
4879 static bool rx_get_frame(SLMP_INFO *info)
4880 {
4881         unsigned int StartIndex, EndIndex;      /* index of 1st and last buffers of Rx frame */
4882         unsigned short status;
4883         unsigned int framesize = 0;
4884         bool ReturnCode = false;
4885         unsigned long flags;
4886         struct tty_struct *tty = info->tty;
4887         unsigned char addr_field = 0xff;
4888         SCADESC *desc;
4889         SCADESC_EX *desc_ex;
4890
4891 CheckAgain:
4892         /* assume no frame returned, set zero length */
4893         framesize = 0;
4894         addr_field = 0xff;
4895
4896         /*
4897          * current_rx_buf points to the 1st buffer of the next available
4898          * receive frame. To find the last buffer of the frame look for
4899          * a non-zero status field in the buffer entries. (The status
4900          * field is set by the 16C32 after completing a receive frame.
4901          */
4902         StartIndex = EndIndex = info->current_rx_buf;
4903
4904         for ( ;; ) {
4905                 desc = &info->rx_buf_list[EndIndex];
4906                 desc_ex = &info->rx_buf_list_ex[EndIndex];
4907
4908                 if (desc->status == 0xff)
4909                         goto Cleanup;   /* current desc still in use, no frames available */
4910
4911                 if (framesize == 0 && info->params.addr_filter != 0xff)
4912                         addr_field = desc_ex->virt_addr[0];
4913
4914                 framesize += desc->length;
4915
4916                 /* Status != 0 means last buffer of frame */
4917                 if (desc->status)
4918                         break;
4919
4920                 EndIndex++;
4921                 if (EndIndex == info->rx_buf_count)
4922                         EndIndex = 0;
4923
4924                 if (EndIndex == info->current_rx_buf) {
4925                         /* all buffers have been 'used' but none mark      */
4926                         /* the end of a frame. Reset buffers and receiver. */
4927                         if ( info->rx_enabled ){
4928                                 spin_lock_irqsave(&info->lock,flags);
4929                                 rx_start(info);
4930                                 spin_unlock_irqrestore(&info->lock,flags);
4931                         }
4932                         goto Cleanup;
4933                 }
4934
4935         }
4936
4937         /* check status of receive frame */
4938
4939         /* frame status is byte stored after frame data
4940          *
4941          * 7 EOM (end of msg), 1 = last buffer of frame
4942          * 6 Short Frame, 1 = short frame
4943          * 5 Abort, 1 = frame aborted
4944          * 4 Residue, 1 = last byte is partial
4945          * 3 Overrun, 1 = overrun occurred during frame reception
4946          * 2 CRC,     1 = CRC error detected
4947          *
4948          */
4949         status = desc->status;
4950
4951         /* ignore CRC bit if not using CRC (bit is undefined) */
4952         /* Note:CRC is not save to data buffer */
4953         if (info->params.crc_type == HDLC_CRC_NONE)
4954                 status &= ~BIT2;
4955
4956         if (framesize == 0 ||
4957                  (addr_field != 0xff && addr_field != info->params.addr_filter)) {
4958                 /* discard 0 byte frames, this seems to occur sometime
4959                  * when remote is idling flags.
4960                  */
4961                 rx_free_frame_buffers(info, StartIndex, EndIndex);
4962                 goto CheckAgain;
4963         }
4964
4965         if (framesize < 2)
4966                 status |= BIT6;
4967
4968         if (status & (BIT6+BIT5+BIT3+BIT2)) {
4969                 /* received frame has errors,
4970                  * update counts and mark frame size as 0
4971                  */
4972                 if (status & BIT6)
4973                         info->icount.rxshort++;
4974                 else if (status & BIT5)
4975                         info->icount.rxabort++;
4976                 else if (status & BIT3)
4977                         info->icount.rxover++;
4978                 else
4979                         info->icount.rxcrc++;
4980
4981                 framesize = 0;
4982 #if SYNCLINK_GENERIC_HDLC
4983                 {
4984                         info->netdev->stats.rx_errors++;
4985                         info->netdev->stats.rx_frame_errors++;
4986                 }
4987 #endif
4988         }
4989
4990         if ( debug_level >= DEBUG_LEVEL_BH )
4991                 printk("%s(%d):%s rx_get_frame() status=%04X size=%d\n",
4992                         __FILE__,__LINE__,info->device_name,status,framesize);
4993
4994         if ( debug_level >= DEBUG_LEVEL_DATA )
4995                 trace_block(info,info->rx_buf_list_ex[StartIndex].virt_addr,
4996                         min_t(int, framesize,SCABUFSIZE),0);
4997
4998         if (framesize) {
4999                 if (framesize > info->max_frame_size)
5000                         info->icount.rxlong++;
5001                 else {
5002                         /* copy dma buffer(s) to contiguous intermediate buffer */
5003                         int copy_count = framesize;
5004                         int index = StartIndex;
5005                         unsigned char *ptmp = info->tmp_rx_buf;
5006                         info->tmp_rx_buf_count = framesize;
5007
5008                         info->icount.rxok++;
5009
5010                         while(copy_count) {
5011                                 int partial_count = min(copy_count,SCABUFSIZE);
5012                                 memcpy( ptmp,
5013                                         info->rx_buf_list_ex[index].virt_addr,
5014                                         partial_count );
5015                                 ptmp += partial_count;
5016                                 copy_count -= partial_count;
5017
5018                                 if ( ++index == info->rx_buf_count )
5019                                         index = 0;
5020                         }
5021
5022 #if SYNCLINK_GENERIC_HDLC
5023                         if (info->netcount)
5024                                 hdlcdev_rx(info,info->tmp_rx_buf,framesize);
5025                         else
5026 #endif
5027                                 ldisc_receive_buf(tty,info->tmp_rx_buf,
5028                                                   info->flag_buf, framesize);
5029                 }
5030         }
5031         /* Free the buffers used by this frame. */
5032         rx_free_frame_buffers( info, StartIndex, EndIndex );
5033
5034         ReturnCode = true;
5035
5036 Cleanup:
5037         if ( info->rx_enabled && info->rx_overflow ) {
5038                 /* Receiver is enabled, but needs to restarted due to
5039                  * rx buffer overflow. If buffers are empty, restart receiver.
5040                  */
5041                 if (info->rx_buf_list[EndIndex].status == 0xff) {
5042                         spin_lock_irqsave(&info->lock,flags);
5043                         rx_start(info);
5044                         spin_unlock_irqrestore(&info->lock,flags);
5045                 }
5046         }
5047
5048         return ReturnCode;
5049 }
5050
5051 /* load the transmit DMA buffer with data
5052  */
5053 static void tx_load_dma_buffer(SLMP_INFO *info, const char *buf, unsigned int count)
5054 {
5055         unsigned short copy_count;
5056         unsigned int i = 0;
5057         SCADESC *desc;
5058         SCADESC_EX *desc_ex;
5059
5060         if ( debug_level >= DEBUG_LEVEL_DATA )
5061                 trace_block(info,buf, min_t(int, count,SCABUFSIZE), 1);
5062
5063         /* Copy source buffer to one or more DMA buffers, starting with
5064          * the first transmit dma buffer.
5065          */
5066         for(i=0;;)
5067         {
5068                 copy_count = min_t(unsigned short,count,SCABUFSIZE);
5069
5070                 desc = &info->tx_buf_list[i];
5071                 desc_ex = &info->tx_buf_list_ex[i];
5072
5073                 load_pci_memory(info, desc_ex->virt_addr,buf,copy_count);
5074
5075                 desc->length = copy_count;
5076                 desc->status = 0;
5077
5078                 buf += copy_count;
5079                 count -= copy_count;
5080
5081                 if (!count)
5082                         break;
5083
5084                 i++;
5085                 if (i >= info->tx_buf_count)
5086                         i = 0;
5087         }
5088
5089         info->tx_buf_list[i].status = 0x81;     /* set EOM and EOT status */
5090         info->last_tx_buf = ++i;
5091 }
5092
5093 static bool register_test(SLMP_INFO *info)
5094 {
5095         static unsigned char testval[] = {0x00, 0xff, 0xaa, 0x55, 0x69, 0x96};
5096         static unsigned int count = ARRAY_SIZE(testval);
5097         unsigned int i;
5098         bool rc = true;
5099         unsigned long flags;
5100
5101         spin_lock_irqsave(&info->lock,flags);
5102         reset_port(info);
5103
5104         /* assume failure */
5105         info->init_error = DiagStatus_AddressFailure;
5106
5107         /* Write bit patterns to various registers but do it out of */
5108         /* sync, then read back and verify values. */
5109
5110         for (i = 0 ; i < count ; i++) {
5111                 write_reg(info, TMC, testval[i]);
5112                 write_reg(info, IDL, testval[(i+1)%count]);
5113                 write_reg(info, SA0, testval[(i+2)%count]);
5114                 write_reg(info, SA1, testval[(i+3)%count]);
5115
5116                 if ( (read_reg(info, TMC) != testval[i]) ||
5117                           (read_reg(info, IDL) != testval[(i+1)%count]) ||
5118                           (read_reg(info, SA0) != testval[(i+2)%count]) ||
5119                           (read_reg(info, SA1) != testval[(i+3)%count]) )
5120                 {
5121                         rc = false;
5122                         break;
5123                 }
5124         }
5125
5126         reset_port(info);
5127         spin_unlock_irqrestore(&info->lock,flags);
5128
5129         return rc;
5130 }
5131
5132 static bool irq_test(SLMP_INFO *info)
5133 {
5134         unsigned long timeout;
5135         unsigned long flags;
5136
5137         unsigned char timer = (info->port_num & 1) ? TIMER2 : TIMER0;
5138
5139         spin_lock_irqsave(&info->lock,flags);
5140         reset_port(info);
5141
5142         /* assume failure */
5143         info->init_error = DiagStatus_IrqFailure;
5144         info->irq_occurred = false;
5145
5146         /* setup timer0 on SCA0 to interrupt */
5147
5148         /* IER2<7..4> = timer<3..0> interrupt enables (1=enabled) */
5149         write_reg(info, IER2, (unsigned char)((info->port_num & 1) ? BIT6 : BIT4));
5150
5151         write_reg(info, (unsigned char)(timer + TEPR), 0);      /* timer expand prescale */
5152         write_reg16(info, (unsigned char)(timer + TCONR), 1);   /* timer constant */
5153
5154
5155         /* TMCS, Timer Control/Status Register
5156          *
5157          * 07      CMF, Compare match flag (read only) 1=match
5158          * 06      ECMI, CMF Interrupt Enable: 1=enabled
5159          * 05      Reserved, must be 0
5160          * 04      TME, Timer Enable
5161          * 03..00  Reserved, must be 0
5162          *
5163          * 0101 0000
5164          */
5165         write_reg(info, (unsigned char)(timer + TMCS), 0x50);
5166
5167         spin_unlock_irqrestore(&info->lock,flags);
5168
5169         timeout=100;
5170         while( timeout-- && !info->irq_occurred ) {
5171                 msleep_interruptible(10);
5172         }
5173
5174         spin_lock_irqsave(&info->lock,flags);
5175         reset_port(info);
5176         spin_unlock_irqrestore(&info->lock,flags);
5177
5178         return info->irq_occurred;
5179 }
5180
5181 /* initialize individual SCA device (2 ports)
5182  */
5183 static bool sca_init(SLMP_INFO *info)
5184 {
5185         /* set wait controller to single mem partition (low), no wait states */
5186         write_reg(info, PABR0, 0);      /* wait controller addr boundary 0 */
5187         write_reg(info, PABR1, 0);      /* wait controller addr boundary 1 */
5188         write_reg(info, WCRL, 0);       /* wait controller low range */
5189         write_reg(info, WCRM, 0);       /* wait controller mid range */
5190         write_reg(info, WCRH, 0);       /* wait controller high range */
5191
5192         /* DPCR, DMA Priority Control
5193          *
5194          * 07..05  Not used, must be 0
5195          * 04      BRC, bus release condition: 0=all transfers complete
5196          * 03      CCC, channel change condition: 0=every cycle
5197          * 02..00  PR<2..0>, priority 100=round robin
5198          *
5199          * 00000100 = 0x04
5200          */
5201         write_reg(info, DPCR, dma_priority);
5202
5203         /* DMA Master Enable, BIT7: 1=enable all channels */
5204         write_reg(info, DMER, 0x80);
5205
5206         /* enable all interrupt classes */
5207         write_reg(info, IER0, 0xff);    /* TxRDY,RxRDY,TxINT,RxINT (ports 0-1) */
5208         write_reg(info, IER1, 0xff);    /* DMIB,DMIA (channels 0-3) */
5209         write_reg(info, IER2, 0xf0);    /* TIRQ (timers 0-3) */
5210
5211         /* ITCR, interrupt control register
5212          * 07      IPC, interrupt priority, 0=MSCI->DMA
5213          * 06..05  IAK<1..0>, Acknowledge cycle, 00=non-ack cycle
5214          * 04      VOS, Vector Output, 0=unmodified vector
5215          * 03..00  Reserved, must be 0
5216          */
5217         write_reg(info, ITCR, 0);
5218
5219         return true;
5220 }
5221
5222 /* initialize adapter hardware
5223  */
5224 static bool init_adapter(SLMP_INFO *info)
5225 {
5226         int i;
5227
5228         /* Set BIT30 of Local Control Reg 0x50 to reset SCA */
5229         volatile u32 *MiscCtrl = (u32 *)(info->lcr_base + 0x50);
5230         u32 readval;
5231
5232         info->misc_ctrl_value |= BIT30;
5233         *MiscCtrl = info->misc_ctrl_value;
5234
5235         /*
5236          * Force at least 170ns delay before clearing
5237          * reset bit. Each read from LCR takes at least
5238          * 30ns so 10 times for 300ns to be safe.
5239          */
5240         for(i=0;i<10;i++)
5241                 readval = *MiscCtrl;
5242
5243         info->misc_ctrl_value &= ~BIT30;
5244         *MiscCtrl = info->misc_ctrl_value;
5245
5246         /* init control reg (all DTRs off, all clksel=input) */
5247         info->ctrlreg_value = 0xaa;
5248         write_control_reg(info);
5249
5250         {
5251                 volatile u32 *LCR1BRDR = (u32 *)(info->lcr_base + 0x2c);
5252                 lcr1_brdr_value &= ~(BIT5 + BIT4 + BIT3);
5253
5254                 switch(read_ahead_count)
5255                 {
5256                 case 16:
5257                         lcr1_brdr_value |= BIT5 + BIT4 + BIT3;
5258                         break;
5259                 case 8:
5260                         lcr1_brdr_value |= BIT5 + BIT4;
5261                         break;
5262                 case 4:
5263                         lcr1_brdr_value |= BIT5 + BIT3;
5264                         break;
5265                 case 0:
5266                         lcr1_brdr_value |= BIT5;
5267                         break;
5268                 }
5269
5270                 *LCR1BRDR = lcr1_brdr_value;
5271                 *MiscCtrl = misc_ctrl_value;
5272         }
5273
5274         sca_init(info->port_array[0]);
5275         sca_init(info->port_array[2]);
5276
5277         return true;
5278 }
5279
5280 /* Loopback an HDLC frame to test the hardware
5281  * interrupt and DMA functions.
5282  */
5283 static bool loopback_test(SLMP_INFO *info)
5284 {
5285 #define TESTFRAMESIZE 20
5286
5287         unsigned long timeout;
5288         u16 count = TESTFRAMESIZE;
5289         unsigned char buf[TESTFRAMESIZE];
5290         bool rc = false;
5291         unsigned long flags;
5292
5293         struct tty_struct *oldtty = info->tty;
5294         u32 speed = info->params.clock_speed;
5295
5296         info->params.clock_speed = 3686400;
5297         info->tty = NULL;
5298
5299         /* assume failure */
5300         info->init_error = DiagStatus_DmaFailure;
5301
5302         /* build and send transmit frame */
5303         for (count = 0; count < TESTFRAMESIZE;++count)
5304                 buf[count] = (unsigned char)count;
5305
5306         memset(info->tmp_rx_buf,0,TESTFRAMESIZE);
5307
5308         /* program hardware for HDLC and enabled receiver */
5309         spin_lock_irqsave(&info->lock,flags);
5310         hdlc_mode(info);
5311         enable_loopback(info,1);
5312         rx_start(info);
5313         info->tx_count = count;
5314         tx_load_dma_buffer(info,buf,count);
5315         tx_start(info);
5316         spin_unlock_irqrestore(&info->lock,flags);
5317
5318         /* wait for receive complete */
5319         /* Set a timeout for waiting for interrupt. */
5320         for ( timeout = 100; timeout; --timeout ) {
5321                 msleep_interruptible(10);
5322
5323                 if (rx_get_frame(info)) {
5324                         rc = true;
5325                         break;
5326                 }
5327         }
5328
5329         /* verify received frame length and contents */
5330         if (rc &&
5331             ( info->tmp_rx_buf_count != count ||
5332               memcmp(buf, info->tmp_rx_buf,count))) {
5333                 rc = false;
5334         }
5335
5336         spin_lock_irqsave(&info->lock,flags);
5337         reset_adapter(info);
5338         spin_unlock_irqrestore(&info->lock,flags);
5339
5340         info->params.clock_speed = speed;
5341         info->tty = oldtty;
5342
5343         return rc;
5344 }
5345
5346 /* Perform diagnostics on hardware
5347  */
5348 static int adapter_test( SLMP_INFO *info )
5349 {
5350         unsigned long flags;
5351         if ( debug_level >= DEBUG_LEVEL_INFO )
5352                 printk( "%s(%d):Testing device %s\n",
5353                         __FILE__,__LINE__,info->device_name );
5354
5355         spin_lock_irqsave(&info->lock,flags);
5356         init_adapter(info);
5357         spin_unlock_irqrestore(&info->lock,flags);
5358
5359         info->port_array[0]->port_count = 0;
5360
5361         if ( register_test(info->port_array[0]) &&
5362                 register_test(info->port_array[1])) {
5363
5364                 info->port_array[0]->port_count = 2;
5365
5366                 if ( register_test(info->port_array[2]) &&
5367                         register_test(info->port_array[3]) )
5368                         info->port_array[0]->port_count += 2;
5369         }
5370         else {
5371                 printk( "%s(%d):Register test failure for device %s Addr=%08lX\n",
5372                         __FILE__,__LINE__,info->device_name, (unsigned long)(info->phys_sca_base));
5373                 return -ENODEV;
5374         }
5375
5376         if ( !irq_test(info->port_array[0]) ||
5377                 !irq_test(info->port_array[1]) ||
5378                  (info->port_count == 4 && !irq_test(info->port_array[2])) ||
5379                  (info->port_count == 4 && !irq_test(info->port_array[3]))) {
5380                 printk( "%s(%d):Interrupt test failure for device %s IRQ=%d\n",
5381                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->irq_level) );
5382                 return -ENODEV;
5383         }
5384
5385         if (!loopback_test(info->port_array[0]) ||
5386                 !loopback_test(info->port_array[1]) ||
5387                  (info->port_count == 4 && !loopback_test(info->port_array[2])) ||
5388                  (info->port_count == 4 && !loopback_test(info->port_array[3]))) {
5389                 printk( "%s(%d):DMA test failure for device %s\n",
5390                         __FILE__,__LINE__,info->device_name);
5391                 return -ENODEV;
5392         }
5393
5394         if ( debug_level >= DEBUG_LEVEL_INFO )
5395                 printk( "%s(%d):device %s passed diagnostics\n",
5396                         __FILE__,__LINE__,info->device_name );
5397
5398         info->port_array[0]->init_error = 0;
5399         info->port_array[1]->init_error = 0;
5400         if ( info->port_count > 2 ) {
5401                 info->port_array[2]->init_error = 0;
5402                 info->port_array[3]->init_error = 0;
5403         }
5404
5405         return 0;
5406 }
5407
5408 /* Test the shared memory on a PCI adapter.
5409  */
5410 static bool memory_test(SLMP_INFO *info)
5411 {
5412         static unsigned long testval[] = { 0x0, 0x55555555, 0xaaaaaaaa,
5413                 0x66666666, 0x99999999, 0xffffffff, 0x12345678 };
5414         unsigned long count = ARRAY_SIZE(testval);
5415         unsigned long i;
5416         unsigned long limit = SCA_MEM_SIZE/sizeof(unsigned long);
5417         unsigned long * addr = (unsigned long *)info->memory_base;
5418
5419         /* Test data lines with test pattern at one location. */
5420
5421         for ( i = 0 ; i < count ; i++ ) {
5422                 *addr = testval[i];
5423                 if ( *addr != testval[i] )
5424                         return false;
5425         }
5426
5427         /* Test address lines with incrementing pattern over */
5428         /* entire address range. */
5429
5430         for ( i = 0 ; i < limit ; i++ ) {
5431                 *addr = i * 4;
5432                 addr++;
5433         }
5434
5435         addr = (unsigned long *)info->memory_base;
5436
5437         for ( i = 0 ; i < limit ; i++ ) {
5438                 if ( *addr != i * 4 )
5439                         return false;
5440                 addr++;
5441         }
5442
5443         memset( info->memory_base, 0, SCA_MEM_SIZE );
5444         return true;
5445 }
5446
5447 /* Load data into PCI adapter shared memory.
5448  *
5449  * The PCI9050 releases control of the local bus
5450  * after completing the current read or write operation.
5451  *
5452  * While the PCI9050 write FIFO not empty, the
5453  * PCI9050 treats all of the writes as a single transaction
5454  * and does not release the bus. This causes DMA latency problems
5455  * at high speeds when copying large data blocks to the shared memory.
5456  *
5457  * This function breaks a write into multiple transations by
5458  * interleaving a read which flushes the write FIFO and 'completes'
5459  * the write transation. This allows any pending DMA request to gain control
5460  * of the local bus in a timely fasion.
5461  */
5462 static void load_pci_memory(SLMP_INFO *info, char* dest, const char* src, unsigned short count)
5463 {
5464         /* A load interval of 16 allows for 4 32-bit writes at */
5465         /* 136ns each for a maximum latency of 542ns on the local bus.*/
5466
5467         unsigned short interval = count / sca_pci_load_interval;
5468         unsigned short i;
5469
5470         for ( i = 0 ; i < interval ; i++ )
5471         {
5472                 memcpy(dest, src, sca_pci_load_interval);
5473                 read_status_reg(info);
5474                 dest += sca_pci_load_interval;
5475                 src += sca_pci_load_interval;
5476         }
5477
5478         memcpy(dest, src, count % sca_pci_load_interval);
5479 }
5480
5481 static void trace_block(SLMP_INFO *info,const char* data, int count, int xmit)
5482 {
5483         int i;
5484         int linecount;
5485         if (xmit)
5486                 printk("%s tx data:\n",info->device_name);
5487         else
5488                 printk("%s rx data:\n",info->device_name);
5489
5490         while(count) {
5491                 if (count > 16)
5492                         linecount = 16;
5493                 else
5494                         linecount = count;
5495
5496                 for(i=0;i<linecount;i++)
5497                         printk("%02X ",(unsigned char)data[i]);
5498                 for(;i<17;i++)
5499                         printk("   ");
5500                 for(i=0;i<linecount;i++) {
5501                         if (data[i]>=040 && data[i]<=0176)
5502                                 printk("%c",data[i]);
5503                         else
5504                                 printk(".");
5505                 }
5506                 printk("\n");
5507
5508                 data  += linecount;
5509                 count -= linecount;
5510         }
5511 }       /* end of trace_block() */
5512
5513 /* called when HDLC frame times out
5514  * update stats and do tx completion processing
5515  */
5516 static void tx_timeout(unsigned long context)
5517 {
5518         SLMP_INFO *info = (SLMP_INFO*)context;
5519         unsigned long flags;
5520
5521         if ( debug_level >= DEBUG_LEVEL_INFO )
5522                 printk( "%s(%d):%s tx_timeout()\n",
5523                         __FILE__,__LINE__,info->device_name);
5524         if(info->tx_active && info->params.mode == MGSL_MODE_HDLC) {
5525                 info->icount.txtimeout++;
5526         }
5527         spin_lock_irqsave(&info->lock,flags);
5528         info->tx_active = false;
5529         info->tx_count = info->tx_put = info->tx_get = 0;
5530
5531         spin_unlock_irqrestore(&info->lock,flags);
5532
5533 #if SYNCLINK_GENERIC_HDLC
5534         if (info->netcount)
5535                 hdlcdev_tx_done(info);
5536         else
5537 #endif
5538                 bh_transmit(info);
5539 }
5540
5541 /* called to periodically check the DSR/RI modem signal input status
5542  */
5543 static void status_timeout(unsigned long context)
5544 {
5545         u16 status = 0;
5546         SLMP_INFO *info = (SLMP_INFO*)context;
5547         unsigned long flags;
5548         unsigned char delta;
5549
5550
5551         spin_lock_irqsave(&info->lock,flags);
5552         get_signals(info);
5553         spin_unlock_irqrestore(&info->lock,flags);
5554
5555         /* check for DSR/RI state change */
5556
5557         delta = info->old_signals ^ info->serial_signals;
5558         info->old_signals = info->serial_signals;
5559
5560         if (delta & SerialSignal_DSR)
5561                 status |= MISCSTATUS_DSR_LATCHED|(info->serial_signals&SerialSignal_DSR);
5562
5563         if (delta & SerialSignal_RI)
5564                 status |= MISCSTATUS_RI_LATCHED|(info->serial_signals&SerialSignal_RI);
5565
5566         if (delta & SerialSignal_DCD)
5567                 status |= MISCSTATUS_DCD_LATCHED|(info->serial_signals&SerialSignal_DCD);
5568
5569         if (delta & SerialSignal_CTS)
5570                 status |= MISCSTATUS_CTS_LATCHED|(info->serial_signals&SerialSignal_CTS);
5571
5572         if (status)
5573                 isr_io_pin(info,status);
5574
5575         mod_timer(&info->status_timer, jiffies + msecs_to_jiffies(10));
5576 }
5577
5578
5579 /* Register Access Routines -
5580  * All registers are memory mapped
5581  */
5582 #define CALC_REGADDR() \
5583         unsigned char * RegAddr = (unsigned char*)(info->sca_base + Addr); \
5584         if (info->port_num > 1) \
5585                 RegAddr += 256;                 /* port 0-1 SCA0, 2-3 SCA1 */ \
5586         if ( info->port_num & 1) { \
5587                 if (Addr > 0x7f) \
5588                         RegAddr += 0x40;        /* DMA access */ \
5589                 else if (Addr > 0x1f && Addr < 0x60) \
5590                         RegAddr += 0x20;        /* MSCI access */ \
5591         }
5592
5593
5594 static unsigned char read_reg(SLMP_INFO * info, unsigned char Addr)
5595 {
5596         CALC_REGADDR();
5597         return *RegAddr;
5598 }
5599 static void write_reg(SLMP_INFO * info, unsigned char Addr, unsigned char Value)
5600 {
5601         CALC_REGADDR();
5602         *RegAddr = Value;
5603 }
5604
5605 static u16 read_reg16(SLMP_INFO * info, unsigned char Addr)
5606 {
5607         CALC_REGADDR();
5608         return *((u16 *)RegAddr);
5609 }
5610
5611 static void write_reg16(SLMP_INFO * info, unsigned char Addr, u16 Value)
5612 {
5613         CALC_REGADDR();
5614         *((u16 *)RegAddr) = Value;
5615 }
5616
5617 static unsigned char read_status_reg(SLMP_INFO * info)
5618 {
5619         unsigned char *RegAddr = (unsigned char *)info->statctrl_base;
5620         return *RegAddr;
5621 }
5622
5623 static void write_control_reg(SLMP_INFO * info)
5624 {
5625         unsigned char *RegAddr = (unsigned char *)info->statctrl_base;
5626         *RegAddr = info->port_array[0]->ctrlreg_value;
5627 }
5628
5629
5630 static int __devinit synclinkmp_init_one (struct pci_dev *dev,
5631                                           const struct pci_device_id *ent)
5632 {
5633         if (pci_enable_device(dev)) {
5634                 printk("error enabling pci device %p\n", dev);
5635                 return -EIO;
5636         }
5637         device_init( ++synclinkmp_adapter_count, dev );
5638         return 0;
5639 }
5640
5641 static void __devexit synclinkmp_remove_one (struct pci_dev *dev)
5642 {
5643 }