Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6
[pandora-kernel.git] / drivers / char / pcmcia / synclink_cs.c
1 /*
2  * linux/drivers/char/pcmcia/synclink_cs.c
3  *
4  * $Id: synclink_cs.c,v 4.34 2005/09/08 13:20:54 paulkf Exp $
5  *
6  * Device driver for Microgate SyncLink PC Card
7  * multiprotocol serial adapter.
8  *
9  * written by Paul Fulghum for Microgate Corporation
10  * paulkf@microgate.com
11  *
12  * Microgate and SyncLink are trademarks of Microgate Corporation
13  *
14  * This code is released under the GNU General Public License (GPL)
15  *
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
20  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
26  * OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #define VERSION(ver,rel,seq) (((ver)<<16) | ((rel)<<8) | (seq))
30 #if defined(__i386__)
31 #  define BREAKPOINT() asm("   int $3");
32 #else
33 #  define BREAKPOINT() { }
34 #endif
35
36 #define MAX_DEVICE_COUNT 4
37
38 #include <linux/config.h>       
39 #include <linux/module.h>
40 #include <linux/errno.h>
41 #include <linux/signal.h>
42 #include <linux/sched.h>
43 #include <linux/timer.h>
44 #include <linux/time.h>
45 #include <linux/interrupt.h>
46 #include <linux/pci.h>
47 #include <linux/tty.h>
48 #include <linux/tty_flip.h>
49 #include <linux/serial.h>
50 #include <linux/major.h>
51 #include <linux/string.h>
52 #include <linux/fcntl.h>
53 #include <linux/ptrace.h>
54 #include <linux/ioport.h>
55 #include <linux/mm.h>
56 #include <linux/slab.h>
57 #include <linux/netdevice.h>
58 #include <linux/vmalloc.h>
59 #include <linux/init.h>
60 #include <asm/serial.h>
61 #include <linux/delay.h>
62 #include <linux/ioctl.h>
63
64 #include <asm/system.h>
65 #include <asm/io.h>
66 #include <asm/irq.h>
67 #include <asm/dma.h>
68 #include <linux/bitops.h>
69 #include <asm/types.h>
70 #include <linux/termios.h>
71 #include <linux/workqueue.h>
72 #include <linux/hdlc.h>
73
74 #include <pcmcia/cs_types.h>
75 #include <pcmcia/cs.h>
76 #include <pcmcia/cistpl.h>
77 #include <pcmcia/cisreg.h>
78 #include <pcmcia/ds.h>
79
80 #ifdef CONFIG_HDLC_MODULE
81 #define CONFIG_HDLC 1
82 #endif
83
84 #define GET_USER(error,value,addr) error = get_user(value,addr)
85 #define COPY_FROM_USER(error,dest,src,size) error = copy_from_user(dest,src,size) ? -EFAULT : 0
86 #define PUT_USER(error,value,addr) error = put_user(value,addr)
87 #define COPY_TO_USER(error,dest,src,size) error = copy_to_user(dest,src,size) ? -EFAULT : 0
88
89 #include <asm/uaccess.h>
90
91 #include "linux/synclink.h"
92
93 static MGSL_PARAMS default_params = {
94         MGSL_MODE_HDLC,                 /* unsigned long mode */
95         0,                              /* unsigned char loopback; */
96         HDLC_FLAG_UNDERRUN_ABORT15,     /* unsigned short flags; */
97         HDLC_ENCODING_NRZI_SPACE,       /* unsigned char encoding; */
98         0,                              /* unsigned long clock_speed; */
99         0xff,                           /* unsigned char addr_filter; */
100         HDLC_CRC_16_CCITT,              /* unsigned short crc_type; */
101         HDLC_PREAMBLE_LENGTH_8BITS,     /* unsigned char preamble_length; */
102         HDLC_PREAMBLE_PATTERN_NONE,     /* unsigned char preamble; */
103         9600,                           /* unsigned long data_rate; */
104         8,                              /* unsigned char data_bits; */
105         1,                              /* unsigned char stop_bits; */
106         ASYNC_PARITY_NONE               /* unsigned char parity; */
107 };
108
109 typedef struct
110 {
111         int count;
112         unsigned char status;
113         char data[1];
114 } RXBUF;
115
116 /* The queue of BH actions to be performed */
117
118 #define BH_RECEIVE  1
119 #define BH_TRANSMIT 2
120 #define BH_STATUS   4
121
122 #define IO_PIN_SHUTDOWN_LIMIT 100
123
124 #define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
125
126 struct _input_signal_events {
127         int     ri_up;  
128         int     ri_down;
129         int     dsr_up;
130         int     dsr_down;
131         int     dcd_up;
132         int     dcd_down;
133         int     cts_up;
134         int     cts_down;
135 };
136
137
138 /*
139  * Device instance data structure
140  */
141  
142 typedef struct _mgslpc_info {
143         void *if_ptr;   /* General purpose pointer (used by SPPP) */
144         int                     magic;
145         int                     flags;
146         int                     count;          /* count of opens */
147         int                     line;
148         unsigned short          close_delay;
149         unsigned short          closing_wait;   /* time to wait before closing */
150         
151         struct mgsl_icount      icount;
152         
153         struct tty_struct       *tty;
154         int                     timeout;
155         int                     x_char;         /* xon/xoff character */
156         int                     blocked_open;   /* # of blocked opens */
157         unsigned char           read_status_mask;
158         unsigned char           ignore_status_mask;     
159
160         unsigned char *tx_buf;
161         int            tx_put;
162         int            tx_get;
163         int            tx_count;
164
165         /* circular list of fixed length rx buffers */
166
167         unsigned char  *rx_buf;        /* memory allocated for all rx buffers */
168         int            rx_buf_total_size; /* size of memory allocated for rx buffers */
169         int            rx_put;         /* index of next empty rx buffer */
170         int            rx_get;         /* index of next full rx buffer */
171         int            rx_buf_size;    /* size in bytes of single rx buffer */
172         int            rx_buf_count;   /* total number of rx buffers */
173         int            rx_frame_count; /* number of full rx buffers */
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 _mgslpc_info     *next_device;   /* device list link */
182
183         unsigned short imra_value;
184         unsigned short imrb_value;
185         unsigned char  pim_value;
186
187         spinlock_t lock;
188         struct work_struct task;                /* task structure for scheduling bh */
189
190         u32 max_frame_size;
191
192         u32 pending_bh;
193
194         int bh_running;
195         int bh_requested;
196         
197         int dcd_chkcount; /* check counts to prevent */
198         int cts_chkcount; /* too many IRQs if a signal */
199         int dsr_chkcount; /* is floating */
200         int ri_chkcount;
201
202         int rx_enabled;
203         int rx_overflow;
204
205         int tx_enabled;
206         int tx_active;
207         int tx_aborting;
208         u32 idle_mode;
209
210         int if_mode; /* serial interface selection (RS-232, v.35 etc) */
211
212         char device_name[25];           /* device instance name */
213
214         unsigned int io_base;   /* base I/O address of adapter */
215         unsigned int irq_level;
216         
217         MGSL_PARAMS params;             /* communications parameters */
218
219         unsigned char serial_signals;   /* current serial signal states */
220
221         char irq_occurred;              /* for diagnostics use */
222         char testing_irq;
223         unsigned int init_error;        /* startup error (DIAGS)        */
224
225         char flag_buf[MAX_ASYNC_BUFFER_SIZE];
226         BOOLEAN drop_rts_on_tx_done;
227
228         struct  _input_signal_events    input_signal_events;
229
230         /* PCMCIA support */
231         struct pcmcia_device    *p_dev;
232         dev_node_t            node;
233         int                   stop;
234
235         /* SPPP/Cisco HDLC device parts */
236         int netcount;
237         int dosyncppp;
238         spinlock_t netlock;
239
240 #ifdef CONFIG_HDLC
241         struct net_device *netdev;
242 #endif
243
244 } MGSLPC_INFO;
245
246 #define MGSLPC_MAGIC 0x5402
247
248 /*
249  * The size of the serial xmit buffer is 1 page, or 4096 bytes
250  */
251 #define TXBUFSIZE 4096
252
253     
254 #define CHA     0x00   /* channel A offset */
255 #define CHB     0x40   /* channel B offset */
256
257 /*
258  *  FIXME: PPC has PVR defined in asm/reg.h.  For now we just undef it.
259  */
260 #undef PVR
261
262 #define RXFIFO  0
263 #define TXFIFO  0
264 #define STAR    0x20
265 #define CMDR    0x20
266 #define RSTA    0x21
267 #define PRE     0x21
268 #define MODE    0x22
269 #define TIMR    0x23
270 #define XAD1    0x24
271 #define XAD2    0x25
272 #define RAH1    0x26
273 #define RAH2    0x27
274 #define DAFO    0x27
275 #define RAL1    0x28
276 #define RFC     0x28
277 #define RHCR    0x29
278 #define RAL2    0x29
279 #define RBCL    0x2a
280 #define XBCL    0x2a
281 #define RBCH    0x2b
282 #define XBCH    0x2b
283 #define CCR0    0x2c
284 #define CCR1    0x2d
285 #define CCR2    0x2e
286 #define CCR3    0x2f
287 #define VSTR    0x34
288 #define BGR     0x34
289 #define RLCR    0x35
290 #define AML     0x36
291 #define AMH     0x37
292 #define GIS     0x38
293 #define IVA     0x38
294 #define IPC     0x39
295 #define ISR     0x3a
296 #define IMR     0x3a
297 #define PVR     0x3c
298 #define PIS     0x3d
299 #define PIM     0x3d
300 #define PCR     0x3e
301 #define CCR4    0x3f
302     
303 // IMR/ISR
304     
305 #define IRQ_BREAK_ON    BIT15   // rx break detected
306 #define IRQ_DATAOVERRUN BIT14   // receive data overflow
307 #define IRQ_ALLSENT     BIT13   // all sent
308 #define IRQ_UNDERRUN    BIT12   // transmit data underrun
309 #define IRQ_TIMER       BIT11   // timer interrupt
310 #define IRQ_CTS         BIT10   // CTS status change
311 #define IRQ_TXREPEAT    BIT9    // tx message repeat
312 #define IRQ_TXFIFO      BIT8    // transmit pool ready
313 #define IRQ_RXEOM       BIT7    // receive message end
314 #define IRQ_EXITHUNT    BIT6    // receive frame start
315 #define IRQ_RXTIME      BIT6    // rx char timeout
316 #define IRQ_DCD         BIT2    // carrier detect status change
317 #define IRQ_OVERRUN     BIT1    // receive frame overflow
318 #define IRQ_RXFIFO      BIT0    // receive pool full
319     
320 // STAR
321     
322 #define XFW   BIT6              // transmit FIFO write enable
323 #define CEC   BIT2              // command executing
324 #define CTS   BIT1              // CTS state
325     
326 #define PVR_DTR      BIT0
327 #define PVR_DSR      BIT1
328 #define PVR_RI       BIT2
329 #define PVR_AUTOCTS  BIT3
330 #define PVR_RS232    0x20   /* 0010b */
331 #define PVR_V35      0xe0   /* 1110b */
332 #define PVR_RS422    0x40   /* 0100b */
333     
334 /* Register access functions */ 
335     
336 #define write_reg(info, reg, val) outb((val),(info)->io_base + (reg))
337 #define read_reg(info, reg) inb((info)->io_base + (reg))
338
339 #define read_reg16(info, reg) inw((info)->io_base + (reg))  
340 #define write_reg16(info, reg, val) outw((val), (info)->io_base + (reg))
341     
342 #define set_reg_bits(info, reg, mask) \
343     write_reg(info, (reg), \
344                  (unsigned char) (read_reg(info, (reg)) | (mask)))  
345 #define clear_reg_bits(info, reg, mask) \
346     write_reg(info, (reg), \
347                  (unsigned char) (read_reg(info, (reg)) & ~(mask)))  
348 /*
349  * interrupt enable/disable routines
350  */ 
351 static void irq_disable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) 
352 {
353         if (channel == CHA) {
354                 info->imra_value |= mask;
355                 write_reg16(info, CHA + IMR, info->imra_value);
356         } else {
357                 info->imrb_value |= mask;
358                 write_reg16(info, CHB + IMR, info->imrb_value);
359         }
360 }
361 static void irq_enable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) 
362 {
363         if (channel == CHA) {
364                 info->imra_value &= ~mask;
365                 write_reg16(info, CHA + IMR, info->imra_value);
366         } else {
367                 info->imrb_value &= ~mask;
368                 write_reg16(info, CHB + IMR, info->imrb_value);
369         }
370 }
371
372 #define port_irq_disable(info, mask) \
373   { info->pim_value |= (mask); write_reg(info, PIM, info->pim_value); }
374
375 #define port_irq_enable(info, mask) \
376   { info->pim_value &= ~(mask); write_reg(info, PIM, info->pim_value); }
377
378 static void rx_start(MGSLPC_INFO *info);
379 static void rx_stop(MGSLPC_INFO *info);
380
381 static void tx_start(MGSLPC_INFO *info);
382 static void tx_stop(MGSLPC_INFO *info);
383 static void tx_set_idle(MGSLPC_INFO *info);
384
385 static void get_signals(MGSLPC_INFO *info);
386 static void set_signals(MGSLPC_INFO *info);
387
388 static void reset_device(MGSLPC_INFO *info);
389
390 static void hdlc_mode(MGSLPC_INFO *info);
391 static void async_mode(MGSLPC_INFO *info);
392
393 static void tx_timeout(unsigned long context);
394
395 static int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg);
396
397 #ifdef CONFIG_HDLC
398 #define dev_to_port(D) (dev_to_hdlc(D)->priv)
399 static void hdlcdev_tx_done(MGSLPC_INFO *info);
400 static void hdlcdev_rx(MGSLPC_INFO *info, char *buf, int size);
401 static int  hdlcdev_init(MGSLPC_INFO *info);
402 static void hdlcdev_exit(MGSLPC_INFO *info);
403 #endif
404
405 static void trace_block(MGSLPC_INFO *info,const char* data, int count, int xmit);
406
407 static BOOLEAN register_test(MGSLPC_INFO *info);
408 static BOOLEAN irq_test(MGSLPC_INFO *info);
409 static int adapter_test(MGSLPC_INFO *info);
410
411 static int claim_resources(MGSLPC_INFO *info);
412 static void release_resources(MGSLPC_INFO *info);
413 static void mgslpc_add_device(MGSLPC_INFO *info);
414 static void mgslpc_remove_device(MGSLPC_INFO *info);
415
416 static int  rx_get_frame(MGSLPC_INFO *info);
417 static void rx_reset_buffers(MGSLPC_INFO *info);
418 static int  rx_alloc_buffers(MGSLPC_INFO *info);
419 static void rx_free_buffers(MGSLPC_INFO *info);
420
421 static irqreturn_t mgslpc_isr(int irq, void *dev_id, struct pt_regs * regs);
422
423 /*
424  * Bottom half interrupt handlers
425  */
426 static void bh_handler(void* Context);
427 static void bh_transmit(MGSLPC_INFO *info);
428 static void bh_status(MGSLPC_INFO *info);
429
430 /*
431  * ioctl handlers
432  */
433 static int tiocmget(struct tty_struct *tty, struct file *file);
434 static int tiocmset(struct tty_struct *tty, struct file *file,
435                     unsigned int set, unsigned int clear);
436 static int get_stats(MGSLPC_INFO *info, struct mgsl_icount __user *user_icount);
437 static int get_params(MGSLPC_INFO *info, MGSL_PARAMS __user *user_params);
438 static int set_params(MGSLPC_INFO *info, MGSL_PARAMS __user *new_params);
439 static int get_txidle(MGSLPC_INFO *info, int __user *idle_mode);
440 static int set_txidle(MGSLPC_INFO *info, int idle_mode);
441 static int set_txenable(MGSLPC_INFO *info, int enable);
442 static int tx_abort(MGSLPC_INFO *info);
443 static int set_rxenable(MGSLPC_INFO *info, int enable);
444 static int wait_events(MGSLPC_INFO *info, int __user *mask);
445
446 static MGSLPC_INFO *mgslpc_device_list = NULL;
447 static int mgslpc_device_count = 0;
448
449 /*
450  * Set this param to non-zero to load eax with the
451  * .text section address and breakpoint on module load.
452  * This is useful for use with gdb and add-symbol-file command.
453  */
454 static int break_on_load=0;
455
456 /*
457  * Driver major number, defaults to zero to get auto
458  * assigned major number. May be forced as module parameter.
459  */
460 static int ttymajor=0;
461
462 static int debug_level = 0;
463 static int maxframe[MAX_DEVICE_COUNT] = {0,};
464 static int dosyncppp[MAX_DEVICE_COUNT] = {1,1,1,1};
465
466 module_param(break_on_load, bool, 0);
467 module_param(ttymajor, int, 0);
468 module_param(debug_level, int, 0);
469 module_param_array(maxframe, int, NULL, 0);
470 module_param_array(dosyncppp, int, NULL, 0);
471
472 MODULE_LICENSE("GPL");
473
474 static char *driver_name = "SyncLink PC Card driver";
475 static char *driver_version = "$Revision: 4.34 $";
476
477 static struct tty_driver *serial_driver;
478
479 /* number of characters left in xmit buffer before we ask for more */
480 #define WAKEUP_CHARS 256
481
482 static void mgslpc_change_params(MGSLPC_INFO *info);
483 static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout);
484
485 /* PCMCIA prototypes */
486
487 static int mgslpc_config(struct pcmcia_device *link);
488 static void mgslpc_release(u_long arg);
489 static void mgslpc_detach(struct pcmcia_device *p_dev);
490
491 /*
492  * 1st function defined in .text section. Calling this function in
493  * init_module() followed by a breakpoint allows a remote debugger
494  * (gdb) to get the .text address for the add-symbol-file command.
495  * This allows remote debugging of dynamically loadable modules.
496  */
497 static void* mgslpc_get_text_ptr(void)
498 {
499         return mgslpc_get_text_ptr;
500 }
501
502 /**
503  * line discipline callback wrappers
504  *
505  * The wrappers maintain line discipline references
506  * while calling into the line discipline.
507  *
508  * ldisc_flush_buffer - flush line discipline receive buffers
509  * ldisc_receive_buf  - pass receive data to line discipline
510  */
511
512 static void ldisc_flush_buffer(struct tty_struct *tty)
513 {
514         struct tty_ldisc *ld = tty_ldisc_ref(tty);
515         if (ld) {
516                 if (ld->flush_buffer)
517                         ld->flush_buffer(tty);
518                 tty_ldisc_deref(ld);
519         }
520 }
521
522 static void ldisc_receive_buf(struct tty_struct *tty,
523                               const __u8 *data, char *flags, int count)
524 {
525         struct tty_ldisc *ld;
526         if (!tty)
527                 return;
528         ld = tty_ldisc_ref(tty);
529         if (ld) {
530                 if (ld->receive_buf)
531                         ld->receive_buf(tty, data, flags, count);
532                 tty_ldisc_deref(ld);
533         }
534 }
535
536 static int mgslpc_probe(struct pcmcia_device *link)
537 {
538     MGSLPC_INFO *info;
539     int ret;
540
541     if (debug_level >= DEBUG_LEVEL_INFO)
542             printk("mgslpc_attach\n");
543
544     info = (MGSLPC_INFO *)kmalloc(sizeof(MGSLPC_INFO), GFP_KERNEL);
545     if (!info) {
546             printk("Error can't allocate device instance data\n");
547             return -ENOMEM;
548     }
549
550     memset(info, 0, sizeof(MGSLPC_INFO));
551     info->magic = MGSLPC_MAGIC;
552     INIT_WORK(&info->task, bh_handler, info);
553     info->max_frame_size = 4096;
554     info->close_delay = 5*HZ/10;
555     info->closing_wait = 30*HZ;
556     init_waitqueue_head(&info->open_wait);
557     init_waitqueue_head(&info->close_wait);
558     init_waitqueue_head(&info->status_event_wait_q);
559     init_waitqueue_head(&info->event_wait_q);
560     spin_lock_init(&info->lock);
561     spin_lock_init(&info->netlock);
562     memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
563     info->idle_mode = HDLC_TXIDLE_FLAGS;                
564     info->imra_value = 0xffff;
565     info->imrb_value = 0xffff;
566     info->pim_value = 0xff;
567
568     info->p_dev = link;
569     link->priv = info;
570
571     /* Initialize the struct pcmcia_device structure */
572
573     /* Interrupt setup */
574     link->irq.Attributes = IRQ_TYPE_EXCLUSIVE;
575     link->irq.IRQInfo1   = IRQ_LEVEL_ID;
576     link->irq.Handler = NULL;
577
578     link->conf.Attributes = 0;
579     link->conf.IntType = INT_MEMORY_AND_IO;
580
581     ret = mgslpc_config(link);
582     if (ret)
583             return ret;
584
585     mgslpc_add_device(info);
586
587     return 0;
588 }
589
590 /* Card has been inserted.
591  */
592
593 #define CS_CHECK(fn, ret) \
594 do { last_fn = (fn); if ((last_ret = (ret)) != 0) goto cs_failed; } while (0)
595
596 static int mgslpc_config(struct pcmcia_device *link)
597 {
598     MGSLPC_INFO *info = link->priv;
599     tuple_t tuple;
600     cisparse_t parse;
601     int last_fn, last_ret;
602     u_char buf[64];
603     cistpl_cftable_entry_t dflt = { 0 };
604     cistpl_cftable_entry_t *cfg;
605     
606     if (debug_level >= DEBUG_LEVEL_INFO)
607             printk("mgslpc_config(0x%p)\n", link);
608
609     /* read CONFIG tuple to find its configuration registers */
610     tuple.DesiredTuple = CISTPL_CONFIG;
611     tuple.Attributes = 0;
612     tuple.TupleData = buf;
613     tuple.TupleDataMax = sizeof(buf);
614     tuple.TupleOffset = 0;
615     CS_CHECK(GetFirstTuple, pcmcia_get_first_tuple(link, &tuple));
616     CS_CHECK(GetTupleData, pcmcia_get_tuple_data(link, &tuple));
617     CS_CHECK(ParseTuple, pcmcia_parse_tuple(link, &tuple, &parse));
618     link->conf.ConfigBase = parse.config.base;
619     link->conf.Present = parse.config.rmask[0];
620
621     /* get CIS configuration entry */
622
623     tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
624     CS_CHECK(GetFirstTuple, pcmcia_get_first_tuple(link, &tuple));
625
626     cfg = &(parse.cftable_entry);
627     CS_CHECK(GetTupleData, pcmcia_get_tuple_data(link, &tuple));
628     CS_CHECK(ParseTuple, pcmcia_parse_tuple(link, &tuple, &parse));
629
630     if (cfg->flags & CISTPL_CFTABLE_DEFAULT) dflt = *cfg;
631     if (cfg->index == 0)
632             goto cs_failed;
633
634     link->conf.ConfigIndex = cfg->index;
635     link->conf.Attributes |= CONF_ENABLE_IRQ;
636         
637     /* IO window settings */
638     link->io.NumPorts1 = 0;
639     if ((cfg->io.nwin > 0) || (dflt.io.nwin > 0)) {
640             cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt.io;
641             link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO;
642             if (!(io->flags & CISTPL_IO_8BIT))
643                     link->io.Attributes1 = IO_DATA_PATH_WIDTH_16;
644             if (!(io->flags & CISTPL_IO_16BIT))
645                     link->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
646             link->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK;
647             link->io.BasePort1 = io->win[0].base;
648             link->io.NumPorts1 = io->win[0].len;
649             CS_CHECK(RequestIO, pcmcia_request_io(link, &link->io));
650     }
651
652     link->conf.Attributes = CONF_ENABLE_IRQ;
653     link->conf.IntType = INT_MEMORY_AND_IO;
654     link->conf.ConfigIndex = 8;
655     link->conf.Present = PRESENT_OPTION;
656     
657     link->irq.Attributes |= IRQ_HANDLE_PRESENT;
658     link->irq.Handler     = mgslpc_isr;
659     link->irq.Instance    = info;
660     CS_CHECK(RequestIRQ, pcmcia_request_irq(link, &link->irq));
661
662     CS_CHECK(RequestConfiguration, pcmcia_request_configuration(link, &link->conf));
663
664     info->io_base = link->io.BasePort1;
665     info->irq_level = link->irq.AssignedIRQ;
666
667     /* add to linked list of devices */
668     sprintf(info->node.dev_name, "mgslpc0");
669     info->node.major = info->node.minor = 0;
670     link->dev_node = &info->node;
671
672     printk(KERN_INFO "%s: index 0x%02x:",
673            info->node.dev_name, link->conf.ConfigIndex);
674     if (link->conf.Attributes & CONF_ENABLE_IRQ)
675             printk(", irq %d", link->irq.AssignedIRQ);
676     if (link->io.NumPorts1)
677             printk(", io 0x%04x-0x%04x", link->io.BasePort1,
678                    link->io.BasePort1+link->io.NumPorts1-1);
679     printk("\n");
680     return 0;
681
682 cs_failed:
683     cs_error(link, last_fn, last_ret);
684     mgslpc_release((u_long)link);
685     return -ENODEV;
686 }
687
688 /* Card has been removed.
689  * Unregister device and release PCMCIA configuration.
690  * If device is open, postpone until it is closed.
691  */
692 static void mgslpc_release(u_long arg)
693 {
694         struct pcmcia_device *link = (struct pcmcia_device *)arg;
695
696         if (debug_level >= DEBUG_LEVEL_INFO)
697                 printk("mgslpc_release(0x%p)\n", link);
698
699         pcmcia_disable_device(link);
700 }
701
702 static void mgslpc_detach(struct pcmcia_device *link)
703 {
704         if (debug_level >= DEBUG_LEVEL_INFO)
705                 printk("mgslpc_detach(0x%p)\n", link);
706
707         ((MGSLPC_INFO *)link->priv)->stop = 1;
708         mgslpc_release((u_long)link);
709
710         mgslpc_remove_device((MGSLPC_INFO *)link->priv);
711 }
712
713 static int mgslpc_suspend(struct pcmcia_device *link)
714 {
715         MGSLPC_INFO *info = link->priv;
716
717         info->stop = 1;
718
719         return 0;
720 }
721
722 static int mgslpc_resume(struct pcmcia_device *link)
723 {
724         MGSLPC_INFO *info = link->priv;
725
726         info->stop = 0;
727
728         return 0;
729 }
730
731
732 static inline int mgslpc_paranoia_check(MGSLPC_INFO *info,
733                                         char *name, const char *routine)
734 {
735 #ifdef MGSLPC_PARANOIA_CHECK
736         static const char *badmagic =
737                 "Warning: bad magic number for mgsl struct (%s) in %s\n";
738         static const char *badinfo =
739                 "Warning: null mgslpc_info for (%s) in %s\n";
740
741         if (!info) {
742                 printk(badinfo, name, routine);
743                 return 1;
744         }
745         if (info->magic != MGSLPC_MAGIC) {
746                 printk(badmagic, name, routine);
747                 return 1;
748         }
749 #else
750         if (!info)
751                 return 1;
752 #endif
753         return 0;
754 }
755
756
757 #define CMD_RXFIFO      BIT7    // release current rx FIFO
758 #define CMD_RXRESET     BIT6    // receiver reset
759 #define CMD_RXFIFO_READ BIT5
760 #define CMD_START_TIMER BIT4
761 #define CMD_TXFIFO      BIT3    // release current tx FIFO
762 #define CMD_TXEOM       BIT1    // transmit end message
763 #define CMD_TXRESET     BIT0    // transmit reset
764
765 static BOOLEAN wait_command_complete(MGSLPC_INFO *info, unsigned char channel) 
766 {
767         int i = 0;
768         /* wait for command completion */ 
769         while (read_reg(info, (unsigned char)(channel+STAR)) & BIT2) {
770                 udelay(1);
771                 if (i++ == 1000)
772                         return FALSE;
773         }
774         return TRUE;
775 }
776
777 static void issue_command(MGSLPC_INFO *info, unsigned char channel, unsigned char cmd) 
778 {
779         wait_command_complete(info, channel);
780         write_reg(info, (unsigned char) (channel + CMDR), cmd);
781 }
782
783 static void tx_pause(struct tty_struct *tty)
784 {
785         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
786         unsigned long flags;
787         
788         if (mgslpc_paranoia_check(info, tty->name, "tx_pause"))
789                 return;
790         if (debug_level >= DEBUG_LEVEL_INFO)
791                 printk("tx_pause(%s)\n",info->device_name);     
792                 
793         spin_lock_irqsave(&info->lock,flags);
794         if (info->tx_enabled)
795                 tx_stop(info);
796         spin_unlock_irqrestore(&info->lock,flags);
797 }
798
799 static void tx_release(struct tty_struct *tty)
800 {
801         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
802         unsigned long flags;
803         
804         if (mgslpc_paranoia_check(info, tty->name, "tx_release"))
805                 return;
806         if (debug_level >= DEBUG_LEVEL_INFO)
807                 printk("tx_release(%s)\n",info->device_name);   
808                 
809         spin_lock_irqsave(&info->lock,flags);
810         if (!info->tx_enabled)
811                 tx_start(info);
812         spin_unlock_irqrestore(&info->lock,flags);
813 }
814
815 /* Return next bottom half action to perform.
816  * or 0 if nothing to do.
817  */
818 static int bh_action(MGSLPC_INFO *info)
819 {
820         unsigned long flags;
821         int rc = 0;
822         
823         spin_lock_irqsave(&info->lock,flags);
824
825         if (info->pending_bh & BH_RECEIVE) {
826                 info->pending_bh &= ~BH_RECEIVE;
827                 rc = BH_RECEIVE;
828         } else if (info->pending_bh & BH_TRANSMIT) {
829                 info->pending_bh &= ~BH_TRANSMIT;
830                 rc = BH_TRANSMIT;
831         } else if (info->pending_bh & BH_STATUS) {
832                 info->pending_bh &= ~BH_STATUS;
833                 rc = BH_STATUS;
834         }
835
836         if (!rc) {
837                 /* Mark BH routine as complete */
838                 info->bh_running   = 0;
839                 info->bh_requested = 0;
840         }
841         
842         spin_unlock_irqrestore(&info->lock,flags);
843         
844         return rc;
845 }
846
847 static void bh_handler(void* Context)
848 {
849         MGSLPC_INFO *info = (MGSLPC_INFO*)Context;
850         int action;
851
852         if (!info)
853                 return;
854                 
855         if (debug_level >= DEBUG_LEVEL_BH)
856                 printk( "%s(%d):bh_handler(%s) entry\n",
857                         __FILE__,__LINE__,info->device_name);
858         
859         info->bh_running = 1;
860
861         while((action = bh_action(info)) != 0) {
862         
863                 /* Process work item */
864                 if ( debug_level >= DEBUG_LEVEL_BH )
865                         printk( "%s(%d):bh_handler() work item action=%d\n",
866                                 __FILE__,__LINE__,action);
867
868                 switch (action) {
869                 
870                 case BH_RECEIVE:
871                         while(rx_get_frame(info));
872                         break;
873                 case BH_TRANSMIT:
874                         bh_transmit(info);
875                         break;
876                 case BH_STATUS:
877                         bh_status(info);
878                         break;
879                 default:
880                         /* unknown work item ID */
881                         printk("Unknown work item ID=%08X!\n", action);
882                         break;
883                 }
884         }
885
886         if (debug_level >= DEBUG_LEVEL_BH)
887                 printk( "%s(%d):bh_handler(%s) exit\n",
888                         __FILE__,__LINE__,info->device_name);
889 }
890
891 static void bh_transmit(MGSLPC_INFO *info)
892 {
893         struct tty_struct *tty = info->tty;
894         if (debug_level >= DEBUG_LEVEL_BH)
895                 printk("bh_transmit() entry on %s\n", info->device_name);
896
897         if (tty) {
898                 tty_wakeup(tty);
899                 wake_up_interruptible(&tty->write_wait);
900         }
901 }
902
903 static void bh_status(MGSLPC_INFO *info)
904 {
905         info->ri_chkcount = 0;
906         info->dsr_chkcount = 0;
907         info->dcd_chkcount = 0;
908         info->cts_chkcount = 0;
909 }
910
911 /* eom: non-zero = end of frame */ 
912 static void rx_ready_hdlc(MGSLPC_INFO *info, int eom)
913 {
914         unsigned char data[2];
915         unsigned char fifo_count, read_count, i;
916         RXBUF *buf = (RXBUF*)(info->rx_buf + (info->rx_put * info->rx_buf_size));
917
918         if (debug_level >= DEBUG_LEVEL_ISR)
919                 printk("%s(%d):rx_ready_hdlc(eom=%d)\n",__FILE__,__LINE__,eom);
920         
921         if (!info->rx_enabled)
922                 return;
923
924         if (info->rx_frame_count >= info->rx_buf_count) {
925                 /* no more free buffers */
926                 issue_command(info, CHA, CMD_RXRESET);
927                 info->pending_bh |= BH_RECEIVE;
928                 info->rx_overflow = 1;
929                 info->icount.buf_overrun++;
930                 return;
931         }
932
933         if (eom) {
934                 /* end of frame, get FIFO count from RBCL register */ 
935                 if (!(fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f)))
936                         fifo_count = 32;
937         } else
938                 fifo_count = 32;
939         
940         do {
941                 if (fifo_count == 1) {
942                         read_count = 1;
943                         data[0] = read_reg(info, CHA + RXFIFO);
944                 } else {
945                         read_count = 2;
946                         *((unsigned short *) data) = read_reg16(info, CHA + RXFIFO);
947                 }
948                 fifo_count -= read_count;
949                 if (!fifo_count && eom)
950                         buf->status = data[--read_count];
951
952                 for (i = 0; i < read_count; i++) {
953                         if (buf->count >= info->max_frame_size) {
954                                 /* frame too large, reset receiver and reset current buffer */
955                                 issue_command(info, CHA, CMD_RXRESET);
956                                 buf->count = 0;
957                                 return;
958                         }
959                         *(buf->data + buf->count) = data[i];
960                         buf->count++;
961                 }
962         } while (fifo_count);
963
964         if (eom) {
965                 info->pending_bh |= BH_RECEIVE;
966                 info->rx_frame_count++;
967                 info->rx_put++;
968                 if (info->rx_put >= info->rx_buf_count)
969                         info->rx_put = 0;
970         }
971         issue_command(info, CHA, CMD_RXFIFO);
972 }
973
974 static void rx_ready_async(MGSLPC_INFO *info, int tcd)
975 {
976         unsigned char data, status, flag;
977         int fifo_count;
978         int work = 0;
979         struct tty_struct *tty = info->tty;
980         struct mgsl_icount *icount = &info->icount;
981
982         if (tcd) {
983                 /* early termination, get FIFO count from RBCL register */ 
984                 fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f);
985
986                 /* Zero fifo count could mean 0 or 32 bytes available.
987                  * If BIT5 of STAR is set then at least 1 byte is available.
988                  */
989                 if (!fifo_count && (read_reg(info,CHA+STAR) & BIT5))
990                         fifo_count = 32;
991         } else
992                 fifo_count = 32;
993
994         tty_buffer_request_room(tty, fifo_count);
995         /* Flush received async data to receive data buffer. */ 
996         while (fifo_count) {
997                 data   = read_reg(info, CHA + RXFIFO);
998                 status = read_reg(info, CHA + RXFIFO);
999                 fifo_count -= 2;
1000
1001                 icount->rx++;
1002                 flag = TTY_NORMAL;
1003
1004                 // if no frameing/crc error then save data
1005                 // BIT7:parity error
1006                 // BIT6:framing error
1007
1008                 if (status & (BIT7 + BIT6)) {
1009                         if (status & BIT7) 
1010                                 icount->parity++;
1011                         else
1012                                 icount->frame++;
1013
1014                         /* discard char if tty control flags say so */
1015                         if (status & info->ignore_status_mask)
1016                                 continue;
1017                                 
1018                         status &= info->read_status_mask;
1019
1020                         if (status & BIT7)
1021                                 flag = TTY_PARITY;
1022                         else if (status & BIT6)
1023                                 flag = TTY_FRAME;
1024                 }
1025                 work += tty_insert_flip_char(tty, data, flag);
1026         }
1027         issue_command(info, CHA, CMD_RXFIFO);
1028
1029         if (debug_level >= DEBUG_LEVEL_ISR) {
1030                 printk("%s(%d):rx_ready_async",
1031                         __FILE__,__LINE__);
1032                 printk("%s(%d):rx=%d brk=%d parity=%d frame=%d overrun=%d\n",
1033                         __FILE__,__LINE__,icount->rx,icount->brk,
1034                         icount->parity,icount->frame,icount->overrun);
1035         }
1036                         
1037         if (work)
1038                 tty_flip_buffer_push(tty);
1039 }
1040
1041
1042 static void tx_done(MGSLPC_INFO *info)
1043 {
1044         if (!info->tx_active)
1045                 return;
1046                         
1047         info->tx_active = 0;
1048         info->tx_aborting = 0;
1049
1050         if (info->params.mode == MGSL_MODE_ASYNC)
1051                 return;
1052
1053         info->tx_count = info->tx_put = info->tx_get = 0;
1054         del_timer(&info->tx_timer);     
1055         
1056         if (info->drop_rts_on_tx_done) {
1057                 get_signals(info);
1058                 if (info->serial_signals & SerialSignal_RTS) {
1059                         info->serial_signals &= ~SerialSignal_RTS;
1060                         set_signals(info);
1061                 }
1062                 info->drop_rts_on_tx_done = 0;
1063         }
1064
1065 #ifdef CONFIG_HDLC
1066         if (info->netcount)
1067                 hdlcdev_tx_done(info);
1068         else 
1069 #endif
1070         {
1071                 if (info->tty->stopped || info->tty->hw_stopped) {
1072                         tx_stop(info);
1073                         return;
1074                 }
1075                 info->pending_bh |= BH_TRANSMIT;
1076         }
1077 }
1078
1079 static void tx_ready(MGSLPC_INFO *info)
1080 {
1081         unsigned char fifo_count = 32;
1082         int c;
1083
1084         if (debug_level >= DEBUG_LEVEL_ISR)
1085                 printk("%s(%d):tx_ready(%s)\n", __FILE__,__LINE__,info->device_name);
1086
1087         if (info->params.mode == MGSL_MODE_HDLC) {
1088                 if (!info->tx_active)
1089                         return;
1090         } else {
1091                 if (info->tty->stopped || info->tty->hw_stopped) {
1092                         tx_stop(info);
1093                         return;
1094                 }
1095                 if (!info->tx_count)
1096                         info->tx_active = 0;
1097         }
1098
1099         if (!info->tx_count)
1100                 return;
1101
1102         while (info->tx_count && fifo_count) {
1103                 c = min(2, min_t(int, fifo_count, min(info->tx_count, TXBUFSIZE - info->tx_get)));
1104                 
1105                 if (c == 1) {
1106                         write_reg(info, CHA + TXFIFO, *(info->tx_buf + info->tx_get));
1107                 } else {
1108                         write_reg16(info, CHA + TXFIFO,
1109                                           *((unsigned short*)(info->tx_buf + info->tx_get)));
1110                 }
1111                 info->tx_count -= c;
1112                 info->tx_get = (info->tx_get + c) & (TXBUFSIZE - 1);
1113                 fifo_count -= c;
1114         }
1115
1116         if (info->params.mode == MGSL_MODE_ASYNC) {
1117                 if (info->tx_count < WAKEUP_CHARS)
1118                         info->pending_bh |= BH_TRANSMIT;
1119                 issue_command(info, CHA, CMD_TXFIFO);
1120         } else {
1121                 if (info->tx_count)
1122                         issue_command(info, CHA, CMD_TXFIFO);
1123                 else
1124                         issue_command(info, CHA, CMD_TXFIFO + CMD_TXEOM);
1125         }
1126 }
1127
1128 static void cts_change(MGSLPC_INFO *info)
1129 {
1130         get_signals(info);
1131         if ((info->cts_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1132                 irq_disable(info, CHB, IRQ_CTS);
1133         info->icount.cts++;
1134         if (info->serial_signals & SerialSignal_CTS)
1135                 info->input_signal_events.cts_up++;
1136         else
1137                 info->input_signal_events.cts_down++;
1138         wake_up_interruptible(&info->status_event_wait_q);
1139         wake_up_interruptible(&info->event_wait_q);
1140
1141         if (info->flags & ASYNC_CTS_FLOW) {
1142                 if (info->tty->hw_stopped) {
1143                         if (info->serial_signals & SerialSignal_CTS) {
1144                                 if (debug_level >= DEBUG_LEVEL_ISR)
1145                                         printk("CTS tx start...");
1146                                 if (info->tty)
1147                                         info->tty->hw_stopped = 0;
1148                                 tx_start(info);
1149                                 info->pending_bh |= BH_TRANSMIT;
1150                                 return;
1151                         }
1152                 } else {
1153                         if (!(info->serial_signals & SerialSignal_CTS)) {
1154                                 if (debug_level >= DEBUG_LEVEL_ISR)
1155                                         printk("CTS tx stop...");
1156                                 if (info->tty)
1157                                         info->tty->hw_stopped = 1;
1158                                 tx_stop(info);
1159                         }
1160                 }
1161         }
1162         info->pending_bh |= BH_STATUS;
1163 }
1164
1165 static void dcd_change(MGSLPC_INFO *info)
1166 {
1167         get_signals(info);
1168         if ((info->dcd_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1169                 irq_disable(info, CHB, IRQ_DCD);
1170         info->icount.dcd++;
1171         if (info->serial_signals & SerialSignal_DCD) {
1172                 info->input_signal_events.dcd_up++;
1173         }
1174         else
1175                 info->input_signal_events.dcd_down++;
1176 #ifdef CONFIG_HDLC
1177         if (info->netcount)
1178                 hdlc_set_carrier(info->serial_signals & SerialSignal_DCD, info->netdev);
1179 #endif
1180         wake_up_interruptible(&info->status_event_wait_q);
1181         wake_up_interruptible(&info->event_wait_q);
1182
1183         if (info->flags & ASYNC_CHECK_CD) {
1184                 if (debug_level >= DEBUG_LEVEL_ISR)
1185                         printk("%s CD now %s...", info->device_name,
1186                                (info->serial_signals & SerialSignal_DCD) ? "on" : "off");
1187                 if (info->serial_signals & SerialSignal_DCD)
1188                         wake_up_interruptible(&info->open_wait);
1189                 else {
1190                         if (debug_level >= DEBUG_LEVEL_ISR)
1191                                 printk("doing serial hangup...");
1192                         if (info->tty)
1193                                 tty_hangup(info->tty);
1194                 }
1195         }
1196         info->pending_bh |= BH_STATUS;
1197 }
1198
1199 static void dsr_change(MGSLPC_INFO *info)
1200 {
1201         get_signals(info);
1202         if ((info->dsr_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1203                 port_irq_disable(info, PVR_DSR);
1204         info->icount.dsr++;
1205         if (info->serial_signals & SerialSignal_DSR)
1206                 info->input_signal_events.dsr_up++;
1207         else
1208                 info->input_signal_events.dsr_down++;
1209         wake_up_interruptible(&info->status_event_wait_q);
1210         wake_up_interruptible(&info->event_wait_q);
1211         info->pending_bh |= BH_STATUS;
1212 }
1213
1214 static void ri_change(MGSLPC_INFO *info)
1215 {
1216         get_signals(info);
1217         if ((info->ri_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1218                 port_irq_disable(info, PVR_RI);
1219         info->icount.rng++;
1220         if (info->serial_signals & SerialSignal_RI)
1221                 info->input_signal_events.ri_up++;
1222         else
1223                 info->input_signal_events.ri_down++;
1224         wake_up_interruptible(&info->status_event_wait_q);
1225         wake_up_interruptible(&info->event_wait_q);
1226         info->pending_bh |= BH_STATUS;
1227 }
1228
1229 /* Interrupt service routine entry point.
1230  *      
1231  * Arguments:
1232  * 
1233  * irq     interrupt number that caused interrupt
1234  * dev_id  device ID supplied during interrupt registration
1235  * regs    interrupted processor context
1236  */
1237 static irqreturn_t mgslpc_isr(int irq, void *dev_id, struct pt_regs * regs)
1238 {
1239         MGSLPC_INFO * info = (MGSLPC_INFO *)dev_id;
1240         unsigned short isr;
1241         unsigned char gis, pis;
1242         int count=0;
1243
1244         if (debug_level >= DEBUG_LEVEL_ISR)     
1245                 printk("mgslpc_isr(%d) entry.\n", irq);
1246         if (!info)
1247                 return IRQ_NONE;
1248                 
1249         if (!(info->p_dev->_locked))
1250                 return IRQ_HANDLED;
1251
1252         spin_lock(&info->lock);
1253
1254         while ((gis = read_reg(info, CHA + GIS))) {
1255                 if (debug_level >= DEBUG_LEVEL_ISR)     
1256                         printk("mgslpc_isr %s gis=%04X\n", info->device_name,gis);
1257
1258                 if ((gis & 0x70) || count > 1000) {
1259                         printk("synclink_cs:hardware failed or ejected\n");
1260                         break;
1261                 }
1262                 count++;
1263
1264                 if (gis & (BIT1 + BIT0)) {
1265                         isr = read_reg16(info, CHB + ISR);
1266                         if (isr & IRQ_DCD)
1267                                 dcd_change(info);
1268                         if (isr & IRQ_CTS)
1269                                 cts_change(info);
1270                 }
1271                 if (gis & (BIT3 + BIT2))
1272                 {
1273                         isr = read_reg16(info, CHA + ISR);
1274                         if (isr & IRQ_TIMER) {
1275                                 info->irq_occurred = 1;
1276                                 irq_disable(info, CHA, IRQ_TIMER);
1277                         }
1278
1279                         /* receive IRQs */ 
1280                         if (isr & IRQ_EXITHUNT) {
1281                                 info->icount.exithunt++;
1282                                 wake_up_interruptible(&info->event_wait_q);
1283                         }
1284                         if (isr & IRQ_BREAK_ON) {
1285                                 info->icount.brk++;
1286                                 if (info->flags & ASYNC_SAK)
1287                                         do_SAK(info->tty);
1288                         }
1289                         if (isr & IRQ_RXTIME) {
1290                                 issue_command(info, CHA, CMD_RXFIFO_READ);
1291                         }
1292                         if (isr & (IRQ_RXEOM + IRQ_RXFIFO)) {
1293                                 if (info->params.mode == MGSL_MODE_HDLC)
1294                                         rx_ready_hdlc(info, isr & IRQ_RXEOM); 
1295                                 else
1296                                         rx_ready_async(info, isr & IRQ_RXEOM);
1297                         }
1298
1299                         /* transmit IRQs */ 
1300                         if (isr & IRQ_UNDERRUN) {
1301                                 if (info->tx_aborting)
1302                                         info->icount.txabort++;
1303                                 else
1304                                         info->icount.txunder++;
1305                                 tx_done(info);
1306                         }
1307                         else if (isr & IRQ_ALLSENT) {
1308                                 info->icount.txok++;
1309                                 tx_done(info);
1310                         }
1311                         else if (isr & IRQ_TXFIFO)
1312                                 tx_ready(info);
1313                 }
1314                 if (gis & BIT7) {
1315                         pis = read_reg(info, CHA + PIS);
1316                         if (pis & BIT1)
1317                                 dsr_change(info);
1318                         if (pis & BIT2)
1319                                 ri_change(info);
1320                 }
1321         }
1322         
1323         /* Request bottom half processing if there's something 
1324          * for it to do and the bh is not already running
1325          */
1326
1327         if (info->pending_bh && !info->bh_running && !info->bh_requested) {
1328                 if ( debug_level >= DEBUG_LEVEL_ISR )   
1329                         printk("%s(%d):%s queueing bh task.\n",
1330                                 __FILE__,__LINE__,info->device_name);
1331                 schedule_work(&info->task);
1332                 info->bh_requested = 1;
1333         }
1334
1335         spin_unlock(&info->lock);
1336         
1337         if (debug_level >= DEBUG_LEVEL_ISR)     
1338                 printk("%s(%d):mgslpc_isr(%d)exit.\n",
1339                        __FILE__,__LINE__,irq);
1340
1341         return IRQ_HANDLED;
1342 }
1343
1344 /* Initialize and start device.
1345  */
1346 static int startup(MGSLPC_INFO * info)
1347 {
1348         int retval = 0;
1349         
1350         if (debug_level >= DEBUG_LEVEL_INFO)
1351                 printk("%s(%d):startup(%s)\n",__FILE__,__LINE__,info->device_name);
1352                 
1353         if (info->flags & ASYNC_INITIALIZED)
1354                 return 0;
1355         
1356         if (!info->tx_buf) {
1357                 /* allocate a page of memory for a transmit buffer */
1358                 info->tx_buf = (unsigned char *)get_zeroed_page(GFP_KERNEL);
1359                 if (!info->tx_buf) {
1360                         printk(KERN_ERR"%s(%d):%s can't allocate transmit buffer\n",
1361                                 __FILE__,__LINE__,info->device_name);
1362                         return -ENOMEM;
1363                 }
1364         }
1365
1366         info->pending_bh = 0;
1367         
1368         memset(&info->icount, 0, sizeof(info->icount));
1369
1370         init_timer(&info->tx_timer);
1371         info->tx_timer.data = (unsigned long)info;
1372         info->tx_timer.function = tx_timeout;
1373
1374         /* Allocate and claim adapter resources */
1375         retval = claim_resources(info);
1376         
1377         /* perform existance check and diagnostics */
1378         if ( !retval )
1379                 retval = adapter_test(info);
1380                 
1381         if ( retval ) {
1382                 if (capable(CAP_SYS_ADMIN) && info->tty)
1383                         set_bit(TTY_IO_ERROR, &info->tty->flags);
1384                 release_resources(info);
1385                 return retval;
1386         }
1387
1388         /* program hardware for current parameters */
1389         mgslpc_change_params(info);
1390         
1391         if (info->tty)
1392                 clear_bit(TTY_IO_ERROR, &info->tty->flags);
1393
1394         info->flags |= ASYNC_INITIALIZED;
1395         
1396         return 0;
1397 }
1398
1399 /* Called by mgslpc_close() and mgslpc_hangup() to shutdown hardware
1400  */
1401 static void shutdown(MGSLPC_INFO * info)
1402 {
1403         unsigned long flags;
1404         
1405         if (!(info->flags & ASYNC_INITIALIZED))
1406                 return;
1407
1408         if (debug_level >= DEBUG_LEVEL_INFO)
1409                 printk("%s(%d):mgslpc_shutdown(%s)\n",
1410                          __FILE__,__LINE__, info->device_name );
1411
1412         /* clear status wait queue because status changes */
1413         /* can't happen after shutting down the hardware */
1414         wake_up_interruptible(&info->status_event_wait_q);
1415         wake_up_interruptible(&info->event_wait_q);
1416
1417         del_timer(&info->tx_timer);     
1418
1419         if (info->tx_buf) {
1420                 free_page((unsigned long) info->tx_buf);
1421                 info->tx_buf = NULL;
1422         }
1423
1424         spin_lock_irqsave(&info->lock,flags);
1425
1426         rx_stop(info);
1427         tx_stop(info);
1428
1429         /* TODO:disable interrupts instead of reset to preserve signal states */
1430         reset_device(info);
1431         
1432         if (!info->tty || info->tty->termios->c_cflag & HUPCL) {
1433                 info->serial_signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
1434                 set_signals(info);
1435         }
1436         
1437         spin_unlock_irqrestore(&info->lock,flags);
1438
1439         release_resources(info);        
1440         
1441         if (info->tty)
1442                 set_bit(TTY_IO_ERROR, &info->tty->flags);
1443
1444         info->flags &= ~ASYNC_INITIALIZED;
1445 }
1446
1447 static void mgslpc_program_hw(MGSLPC_INFO *info)
1448 {
1449         unsigned long flags;
1450
1451         spin_lock_irqsave(&info->lock,flags);
1452         
1453         rx_stop(info);
1454         tx_stop(info);
1455         info->tx_count = info->tx_put = info->tx_get = 0;
1456         
1457         if (info->params.mode == MGSL_MODE_HDLC || info->netcount)
1458                 hdlc_mode(info);
1459         else
1460                 async_mode(info);
1461                 
1462         set_signals(info);
1463         
1464         info->dcd_chkcount = 0;
1465         info->cts_chkcount = 0;
1466         info->ri_chkcount = 0;
1467         info->dsr_chkcount = 0;
1468
1469         irq_enable(info, CHB, IRQ_DCD | IRQ_CTS);
1470         port_irq_enable(info, (unsigned char) PVR_DSR | PVR_RI);
1471         get_signals(info);
1472                 
1473         if (info->netcount || info->tty->termios->c_cflag & CREAD)
1474                 rx_start(info);
1475                 
1476         spin_unlock_irqrestore(&info->lock,flags);
1477 }
1478
1479 /* Reconfigure adapter based on new parameters
1480  */
1481 static void mgslpc_change_params(MGSLPC_INFO *info)
1482 {
1483         unsigned cflag;
1484         int bits_per_char;
1485
1486         if (!info->tty || !info->tty->termios)
1487                 return;
1488                 
1489         if (debug_level >= DEBUG_LEVEL_INFO)
1490                 printk("%s(%d):mgslpc_change_params(%s)\n",
1491                          __FILE__,__LINE__, info->device_name );
1492                          
1493         cflag = info->tty->termios->c_cflag;
1494
1495         /* if B0 rate (hangup) specified then negate DTR and RTS */
1496         /* otherwise assert DTR and RTS */
1497         if (cflag & CBAUD)
1498                 info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
1499         else
1500                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
1501         
1502         /* byte size and parity */
1503         
1504         switch (cflag & CSIZE) {
1505         case CS5: info->params.data_bits = 5; break;
1506         case CS6: info->params.data_bits = 6; break;
1507         case CS7: info->params.data_bits = 7; break;
1508         case CS8: info->params.data_bits = 8; break;
1509         default:  info->params.data_bits = 7; break;
1510         }
1511               
1512         if (cflag & CSTOPB)
1513                 info->params.stop_bits = 2;
1514         else
1515                 info->params.stop_bits = 1;
1516
1517         info->params.parity = ASYNC_PARITY_NONE;
1518         if (cflag & PARENB) {
1519                 if (cflag & PARODD)
1520                         info->params.parity = ASYNC_PARITY_ODD;
1521                 else
1522                         info->params.parity = ASYNC_PARITY_EVEN;
1523 #ifdef CMSPAR
1524                 if (cflag & CMSPAR)
1525                         info->params.parity = ASYNC_PARITY_SPACE;
1526 #endif
1527         }
1528
1529         /* calculate number of jiffies to transmit a full
1530          * FIFO (32 bytes) at specified data rate
1531          */
1532         bits_per_char = info->params.data_bits + 
1533                         info->params.stop_bits + 1;
1534
1535         /* if port data rate is set to 460800 or less then
1536          * allow tty settings to override, otherwise keep the
1537          * current data rate.
1538          */
1539         if (info->params.data_rate <= 460800) {
1540                 info->params.data_rate = tty_get_baud_rate(info->tty);
1541         }
1542         
1543         if ( info->params.data_rate ) {
1544                 info->timeout = (32*HZ*bits_per_char) / 
1545                                 info->params.data_rate;
1546         }
1547         info->timeout += HZ/50;         /* Add .02 seconds of slop */
1548
1549         if (cflag & CRTSCTS)
1550                 info->flags |= ASYNC_CTS_FLOW;
1551         else
1552                 info->flags &= ~ASYNC_CTS_FLOW;
1553                 
1554         if (cflag & CLOCAL)
1555                 info->flags &= ~ASYNC_CHECK_CD;
1556         else
1557                 info->flags |= ASYNC_CHECK_CD;
1558
1559         /* process tty input control flags */
1560         
1561         info->read_status_mask = 0;
1562         if (I_INPCK(info->tty))
1563                 info->read_status_mask |= BIT7 | BIT6;
1564         if (I_IGNPAR(info->tty))
1565                 info->ignore_status_mask |= BIT7 | BIT6;
1566
1567         mgslpc_program_hw(info);
1568 }
1569
1570 /* Add a character to the transmit buffer
1571  */
1572 static void mgslpc_put_char(struct tty_struct *tty, unsigned char ch)
1573 {
1574         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1575         unsigned long flags;
1576
1577         if (debug_level >= DEBUG_LEVEL_INFO) {
1578                 printk( "%s(%d):mgslpc_put_char(%d) on %s\n",
1579                         __FILE__,__LINE__,ch,info->device_name);
1580         }
1581
1582         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_put_char"))
1583                 return;
1584
1585         if (!info->tx_buf)
1586                 return;
1587
1588         spin_lock_irqsave(&info->lock,flags);
1589         
1590         if (info->params.mode == MGSL_MODE_ASYNC || !info->tx_active) {
1591                 if (info->tx_count < TXBUFSIZE - 1) {
1592                         info->tx_buf[info->tx_put++] = ch;
1593                         info->tx_put &= TXBUFSIZE-1;
1594                         info->tx_count++;
1595                 }
1596         }
1597         
1598         spin_unlock_irqrestore(&info->lock,flags);
1599 }
1600
1601 /* Enable transmitter so remaining characters in the
1602  * transmit buffer are sent.
1603  */
1604 static void mgslpc_flush_chars(struct tty_struct *tty)
1605 {
1606         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1607         unsigned long flags;
1608                                 
1609         if (debug_level >= DEBUG_LEVEL_INFO)
1610                 printk( "%s(%d):mgslpc_flush_chars() entry on %s tx_count=%d\n",
1611                         __FILE__,__LINE__,info->device_name,info->tx_count);
1612         
1613         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_chars"))
1614                 return;
1615
1616         if (info->tx_count <= 0 || tty->stopped ||
1617             tty->hw_stopped || !info->tx_buf)
1618                 return;
1619
1620         if (debug_level >= DEBUG_LEVEL_INFO)
1621                 printk( "%s(%d):mgslpc_flush_chars() entry on %s starting transmitter\n",
1622                         __FILE__,__LINE__,info->device_name);
1623
1624         spin_lock_irqsave(&info->lock,flags);
1625         if (!info->tx_active)
1626                 tx_start(info);
1627         spin_unlock_irqrestore(&info->lock,flags);
1628 }
1629
1630 /* Send a block of data
1631  *      
1632  * Arguments:
1633  * 
1634  * tty        pointer to tty information structure
1635  * buf        pointer to buffer containing send data
1636  * count      size of send data in bytes
1637  *      
1638  * Returns: number of characters written
1639  */
1640 static int mgslpc_write(struct tty_struct * tty,
1641                         const unsigned char *buf, int count)
1642 {
1643         int c, ret = 0;
1644         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1645         unsigned long flags;
1646         
1647         if (debug_level >= DEBUG_LEVEL_INFO)
1648                 printk( "%s(%d):mgslpc_write(%s) count=%d\n",
1649                         __FILE__,__LINE__,info->device_name,count);
1650         
1651         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write") ||
1652                 !info->tx_buf)
1653                 goto cleanup;
1654
1655         if (info->params.mode == MGSL_MODE_HDLC) {
1656                 if (count > TXBUFSIZE) {
1657                         ret = -EIO;
1658                         goto cleanup;
1659                 }
1660                 if (info->tx_active)
1661                         goto cleanup;
1662                 else if (info->tx_count)
1663                         goto start;
1664         }
1665
1666         for (;;) {
1667                 c = min(count,
1668                         min(TXBUFSIZE - info->tx_count - 1,
1669                             TXBUFSIZE - info->tx_put));
1670                 if (c <= 0)
1671                         break;
1672                         
1673                 memcpy(info->tx_buf + info->tx_put, buf, c);
1674
1675                 spin_lock_irqsave(&info->lock,flags);
1676                 info->tx_put = (info->tx_put + c) & (TXBUFSIZE-1);
1677                 info->tx_count += c;
1678                 spin_unlock_irqrestore(&info->lock,flags);
1679
1680                 buf += c;
1681                 count -= c;
1682                 ret += c;
1683         }
1684 start:
1685         if (info->tx_count && !tty->stopped && !tty->hw_stopped) {
1686                 spin_lock_irqsave(&info->lock,flags);
1687                 if (!info->tx_active)
1688                         tx_start(info);
1689                 spin_unlock_irqrestore(&info->lock,flags);
1690         }
1691 cleanup:        
1692         if (debug_level >= DEBUG_LEVEL_INFO)
1693                 printk( "%s(%d):mgslpc_write(%s) returning=%d\n",
1694                         __FILE__,__LINE__,info->device_name,ret);
1695         return ret;
1696 }
1697
1698 /* Return the count of free bytes in transmit buffer
1699  */
1700 static int mgslpc_write_room(struct tty_struct *tty)
1701 {
1702         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1703         int ret;
1704                                 
1705         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write_room"))
1706                 return 0;
1707
1708         if (info->params.mode == MGSL_MODE_HDLC) {
1709                 /* HDLC (frame oriented) mode */
1710                 if (info->tx_active)
1711                         return 0;
1712                 else
1713                         return HDLC_MAX_FRAME_SIZE;
1714         } else {
1715                 ret = TXBUFSIZE - info->tx_count - 1;
1716                 if (ret < 0)
1717                         ret = 0;
1718         }
1719         
1720         if (debug_level >= DEBUG_LEVEL_INFO)
1721                 printk("%s(%d):mgslpc_write_room(%s)=%d\n",
1722                          __FILE__,__LINE__, info->device_name, ret);
1723         return ret;
1724 }
1725
1726 /* Return the count of bytes in transmit buffer
1727  */
1728 static int mgslpc_chars_in_buffer(struct tty_struct *tty)
1729 {
1730         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1731         int rc;
1732                  
1733         if (debug_level >= DEBUG_LEVEL_INFO)
1734                 printk("%s(%d):mgslpc_chars_in_buffer(%s)\n",
1735                          __FILE__,__LINE__, info->device_name );
1736                          
1737         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_chars_in_buffer"))
1738                 return 0;
1739                 
1740         if (info->params.mode == MGSL_MODE_HDLC)
1741                 rc = info->tx_active ? info->max_frame_size : 0;
1742         else
1743                 rc = info->tx_count;
1744
1745         if (debug_level >= DEBUG_LEVEL_INFO)
1746                 printk("%s(%d):mgslpc_chars_in_buffer(%s)=%d\n",
1747                          __FILE__,__LINE__, info->device_name, rc);
1748                          
1749         return rc;
1750 }
1751
1752 /* Discard all data in the send buffer
1753  */
1754 static void mgslpc_flush_buffer(struct tty_struct *tty)
1755 {
1756         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1757         unsigned long flags;
1758         
1759         if (debug_level >= DEBUG_LEVEL_INFO)
1760                 printk("%s(%d):mgslpc_flush_buffer(%s) entry\n",
1761                          __FILE__,__LINE__, info->device_name );
1762         
1763         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_buffer"))
1764                 return;
1765                 
1766         spin_lock_irqsave(&info->lock,flags); 
1767         info->tx_count = info->tx_put = info->tx_get = 0;
1768         del_timer(&info->tx_timer);     
1769         spin_unlock_irqrestore(&info->lock,flags);
1770
1771         wake_up_interruptible(&tty->write_wait);
1772         tty_wakeup(tty);
1773 }
1774
1775 /* Send a high-priority XON/XOFF character
1776  */
1777 static void mgslpc_send_xchar(struct tty_struct *tty, char ch)
1778 {
1779         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1780         unsigned long flags;
1781
1782         if (debug_level >= DEBUG_LEVEL_INFO)
1783                 printk("%s(%d):mgslpc_send_xchar(%s,%d)\n",
1784                          __FILE__,__LINE__, info->device_name, ch );
1785                          
1786         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_send_xchar"))
1787                 return;
1788
1789         info->x_char = ch;
1790         if (ch) {
1791                 spin_lock_irqsave(&info->lock,flags);
1792                 if (!info->tx_enabled)
1793                         tx_start(info);
1794                 spin_unlock_irqrestore(&info->lock,flags);
1795         }
1796 }
1797
1798 /* Signal remote device to throttle send data (our receive data)
1799  */
1800 static void mgslpc_throttle(struct tty_struct * tty)
1801 {
1802         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1803         unsigned long flags;
1804         
1805         if (debug_level >= DEBUG_LEVEL_INFO)
1806                 printk("%s(%d):mgslpc_throttle(%s) entry\n",
1807                          __FILE__,__LINE__, info->device_name );
1808
1809         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_throttle"))
1810                 return;
1811         
1812         if (I_IXOFF(tty))
1813                 mgslpc_send_xchar(tty, STOP_CHAR(tty));
1814  
1815         if (tty->termios->c_cflag & CRTSCTS) {
1816                 spin_lock_irqsave(&info->lock,flags);
1817                 info->serial_signals &= ~SerialSignal_RTS;
1818                 set_signals(info);
1819                 spin_unlock_irqrestore(&info->lock,flags);
1820         }
1821 }
1822
1823 /* Signal remote device to stop throttling send data (our receive data)
1824  */
1825 static void mgslpc_unthrottle(struct tty_struct * tty)
1826 {
1827         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1828         unsigned long flags;
1829         
1830         if (debug_level >= DEBUG_LEVEL_INFO)
1831                 printk("%s(%d):mgslpc_unthrottle(%s) entry\n",
1832                          __FILE__,__LINE__, info->device_name );
1833
1834         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_unthrottle"))
1835                 return;
1836         
1837         if (I_IXOFF(tty)) {
1838                 if (info->x_char)
1839                         info->x_char = 0;
1840                 else
1841                         mgslpc_send_xchar(tty, START_CHAR(tty));
1842         }
1843         
1844         if (tty->termios->c_cflag & CRTSCTS) {
1845                 spin_lock_irqsave(&info->lock,flags);
1846                 info->serial_signals |= SerialSignal_RTS;
1847                 set_signals(info);
1848                 spin_unlock_irqrestore(&info->lock,flags);
1849         }
1850 }
1851
1852 /* get the current serial statistics
1853  */
1854 static int get_stats(MGSLPC_INFO * info, struct mgsl_icount __user *user_icount)
1855 {
1856         int err;
1857         if (debug_level >= DEBUG_LEVEL_INFO)
1858                 printk("get_params(%s)\n", info->device_name);
1859         if (!user_icount) {
1860                 memset(&info->icount, 0, sizeof(info->icount));
1861         } else {
1862                 COPY_TO_USER(err, user_icount, &info->icount, sizeof(struct mgsl_icount));
1863                 if (err)
1864                         return -EFAULT;
1865         }
1866         return 0;
1867 }
1868
1869 /* get the current serial parameters
1870  */
1871 static int get_params(MGSLPC_INFO * info, MGSL_PARAMS __user *user_params)
1872 {
1873         int err;
1874         if (debug_level >= DEBUG_LEVEL_INFO)
1875                 printk("get_params(%s)\n", info->device_name);
1876         COPY_TO_USER(err,user_params, &info->params, sizeof(MGSL_PARAMS));
1877         if (err)
1878                 return -EFAULT;
1879         return 0;
1880 }
1881
1882 /* set the serial parameters
1883  *      
1884  * Arguments:
1885  * 
1886  *      info            pointer to device instance data
1887  *      new_params      user buffer containing new serial params
1888  *
1889  * Returns:     0 if success, otherwise error code
1890  */
1891 static int set_params(MGSLPC_INFO * info, MGSL_PARAMS __user *new_params)
1892 {
1893         unsigned long flags;
1894         MGSL_PARAMS tmp_params;
1895         int err;
1896  
1897         if (debug_level >= DEBUG_LEVEL_INFO)
1898                 printk("%s(%d):set_params %s\n", __FILE__,__LINE__,
1899                         info->device_name );
1900         COPY_FROM_USER(err,&tmp_params, new_params, sizeof(MGSL_PARAMS));
1901         if (err) {
1902                 if ( debug_level >= DEBUG_LEVEL_INFO )
1903                         printk( "%s(%d):set_params(%s) user buffer copy failed\n",
1904                                 __FILE__,__LINE__,info->device_name);
1905                 return -EFAULT;
1906         }
1907         
1908         spin_lock_irqsave(&info->lock,flags);
1909         memcpy(&info->params,&tmp_params,sizeof(MGSL_PARAMS));
1910         spin_unlock_irqrestore(&info->lock,flags);
1911         
1912         mgslpc_change_params(info);
1913         
1914         return 0;
1915 }
1916
1917 static int get_txidle(MGSLPC_INFO * info, int __user *idle_mode)
1918 {
1919         int err;
1920         if (debug_level >= DEBUG_LEVEL_INFO)
1921                 printk("get_txidle(%s)=%d\n", info->device_name, info->idle_mode);
1922         COPY_TO_USER(err,idle_mode, &info->idle_mode, sizeof(int));
1923         if (err)
1924                 return -EFAULT;
1925         return 0;
1926 }
1927
1928 static int set_txidle(MGSLPC_INFO * info, int idle_mode)
1929 {
1930         unsigned long flags;
1931         if (debug_level >= DEBUG_LEVEL_INFO)
1932                 printk("set_txidle(%s,%d)\n", info->device_name, idle_mode);
1933         spin_lock_irqsave(&info->lock,flags);
1934         info->idle_mode = idle_mode;
1935         tx_set_idle(info);
1936         spin_unlock_irqrestore(&info->lock,flags);
1937         return 0;
1938 }
1939
1940 static int get_interface(MGSLPC_INFO * info, int __user *if_mode)
1941 {
1942         int err;
1943         if (debug_level >= DEBUG_LEVEL_INFO)
1944                 printk("get_interface(%s)=%d\n", info->device_name, info->if_mode);
1945         COPY_TO_USER(err,if_mode, &info->if_mode, sizeof(int));
1946         if (err)
1947                 return -EFAULT;
1948         return 0;
1949 }
1950
1951 static int set_interface(MGSLPC_INFO * info, int if_mode)
1952 {
1953         unsigned long flags;
1954         unsigned char val;
1955         if (debug_level >= DEBUG_LEVEL_INFO)
1956                 printk("set_interface(%s,%d)\n", info->device_name, if_mode);
1957         spin_lock_irqsave(&info->lock,flags);
1958         info->if_mode = if_mode;
1959
1960         val = read_reg(info, PVR) & 0x0f;
1961         switch (info->if_mode)
1962         {
1963         case MGSL_INTERFACE_RS232: val |= PVR_RS232; break;
1964         case MGSL_INTERFACE_V35:   val |= PVR_V35;   break;
1965         case MGSL_INTERFACE_RS422: val |= PVR_RS422; break;
1966         }
1967         write_reg(info, PVR, val);
1968
1969         spin_unlock_irqrestore(&info->lock,flags);
1970         return 0;
1971 }
1972
1973 static int set_txenable(MGSLPC_INFO * info, int enable)
1974 {
1975         unsigned long flags;
1976  
1977         if (debug_level >= DEBUG_LEVEL_INFO)
1978                 printk("set_txenable(%s,%d)\n", info->device_name, enable);
1979                         
1980         spin_lock_irqsave(&info->lock,flags);
1981         if (enable) {
1982                 if (!info->tx_enabled)
1983                         tx_start(info);
1984         } else {
1985                 if (info->tx_enabled)
1986                         tx_stop(info);
1987         }
1988         spin_unlock_irqrestore(&info->lock,flags);
1989         return 0;
1990 }
1991
1992 static int tx_abort(MGSLPC_INFO * info)
1993 {
1994         unsigned long flags;
1995  
1996         if (debug_level >= DEBUG_LEVEL_INFO)
1997                 printk("tx_abort(%s)\n", info->device_name);
1998                         
1999         spin_lock_irqsave(&info->lock,flags);
2000         if (info->tx_active && info->tx_count &&
2001             info->params.mode == MGSL_MODE_HDLC) {
2002                 /* clear data count so FIFO is not filled on next IRQ.
2003                  * This results in underrun and abort transmission.
2004                  */
2005                 info->tx_count = info->tx_put = info->tx_get = 0;
2006                 info->tx_aborting = TRUE;
2007         }
2008         spin_unlock_irqrestore(&info->lock,flags);
2009         return 0;
2010 }
2011
2012 static int set_rxenable(MGSLPC_INFO * info, int enable)
2013 {
2014         unsigned long flags;
2015  
2016         if (debug_level >= DEBUG_LEVEL_INFO)
2017                 printk("set_rxenable(%s,%d)\n", info->device_name, enable);
2018                         
2019         spin_lock_irqsave(&info->lock,flags);
2020         if (enable) {
2021                 if (!info->rx_enabled)
2022                         rx_start(info);
2023         } else {
2024                 if (info->rx_enabled)
2025                         rx_stop(info);
2026         }
2027         spin_unlock_irqrestore(&info->lock,flags);
2028         return 0;
2029 }
2030
2031 /* wait for specified event to occur
2032  *      
2033  * Arguments:           info    pointer to device instance data
2034  *                      mask    pointer to bitmask of events to wait for
2035  * Return Value:        0       if successful and bit mask updated with
2036  *                              of events triggerred,
2037  *                      otherwise error code
2038  */
2039 static int wait_events(MGSLPC_INFO * info, int __user *mask_ptr)
2040 {
2041         unsigned long flags;
2042         int s;
2043         int rc=0;
2044         struct mgsl_icount cprev, cnow;
2045         int events;
2046         int mask;
2047         struct  _input_signal_events oldsigs, newsigs;
2048         DECLARE_WAITQUEUE(wait, current);
2049
2050         COPY_FROM_USER(rc,&mask, mask_ptr, sizeof(int));
2051         if (rc)
2052                 return  -EFAULT;
2053                  
2054         if (debug_level >= DEBUG_LEVEL_INFO)
2055                 printk("wait_events(%s,%d)\n", info->device_name, mask);
2056
2057         spin_lock_irqsave(&info->lock,flags);
2058
2059         /* return immediately if state matches requested events */
2060         get_signals(info);
2061         s = info->serial_signals;
2062         events = mask &
2063                 ( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) +
2064                   ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) +
2065                   ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) +
2066                   ((s & SerialSignal_RI)  ? MgslEvent_RiActive :MgslEvent_RiInactive) );
2067         if (events) {
2068                 spin_unlock_irqrestore(&info->lock,flags);
2069                 goto exit;
2070         }
2071
2072         /* save current irq counts */
2073         cprev = info->icount;
2074         oldsigs = info->input_signal_events;
2075         
2076         if ((info->params.mode == MGSL_MODE_HDLC) &&
2077             (mask & MgslEvent_ExitHuntMode))
2078                 irq_enable(info, CHA, IRQ_EXITHUNT);
2079         
2080         set_current_state(TASK_INTERRUPTIBLE);
2081         add_wait_queue(&info->event_wait_q, &wait);
2082         
2083         spin_unlock_irqrestore(&info->lock,flags);
2084         
2085         
2086         for(;;) {
2087                 schedule();
2088                 if (signal_pending(current)) {
2089                         rc = -ERESTARTSYS;
2090                         break;
2091                 }
2092                         
2093                 /* get current irq counts */
2094                 spin_lock_irqsave(&info->lock,flags);
2095                 cnow = info->icount;
2096                 newsigs = info->input_signal_events;
2097                 set_current_state(TASK_INTERRUPTIBLE);
2098                 spin_unlock_irqrestore(&info->lock,flags);
2099
2100                 /* if no change, wait aborted for some reason */
2101                 if (newsigs.dsr_up   == oldsigs.dsr_up   &&
2102                     newsigs.dsr_down == oldsigs.dsr_down &&
2103                     newsigs.dcd_up   == oldsigs.dcd_up   &&
2104                     newsigs.dcd_down == oldsigs.dcd_down &&
2105                     newsigs.cts_up   == oldsigs.cts_up   &&
2106                     newsigs.cts_down == oldsigs.cts_down &&
2107                     newsigs.ri_up    == oldsigs.ri_up    &&
2108                     newsigs.ri_down  == oldsigs.ri_down  &&
2109                     cnow.exithunt    == cprev.exithunt   &&
2110                     cnow.rxidle      == cprev.rxidle) {
2111                         rc = -EIO;
2112                         break;
2113                 }
2114
2115                 events = mask &
2116                         ( (newsigs.dsr_up   != oldsigs.dsr_up   ? MgslEvent_DsrActive:0)   +
2117                           (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) +
2118                           (newsigs.dcd_up   != oldsigs.dcd_up   ? MgslEvent_DcdActive:0)   +
2119                           (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) +
2120                           (newsigs.cts_up   != oldsigs.cts_up   ? MgslEvent_CtsActive:0)   +
2121                           (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) +
2122                           (newsigs.ri_up    != oldsigs.ri_up    ? MgslEvent_RiActive:0)    +
2123                           (newsigs.ri_down  != oldsigs.ri_down  ? MgslEvent_RiInactive:0)  +
2124                           (cnow.exithunt    != cprev.exithunt   ? MgslEvent_ExitHuntMode:0) +
2125                           (cnow.rxidle      != cprev.rxidle     ? MgslEvent_IdleReceived:0) );
2126                 if (events)
2127                         break;
2128                 
2129                 cprev = cnow;
2130                 oldsigs = newsigs;
2131         }
2132         
2133         remove_wait_queue(&info->event_wait_q, &wait);
2134         set_current_state(TASK_RUNNING);
2135
2136         if (mask & MgslEvent_ExitHuntMode) {
2137                 spin_lock_irqsave(&info->lock,flags);
2138                 if (!waitqueue_active(&info->event_wait_q))
2139                         irq_disable(info, CHA, IRQ_EXITHUNT);
2140                 spin_unlock_irqrestore(&info->lock,flags);
2141         }
2142 exit:
2143         if (rc == 0)
2144                 PUT_USER(rc, events, mask_ptr);
2145         return rc;
2146 }
2147
2148 static int modem_input_wait(MGSLPC_INFO *info,int arg)
2149 {
2150         unsigned long flags;
2151         int rc;
2152         struct mgsl_icount cprev, cnow;
2153         DECLARE_WAITQUEUE(wait, current);
2154
2155         /* save current irq counts */
2156         spin_lock_irqsave(&info->lock,flags);
2157         cprev = info->icount;
2158         add_wait_queue(&info->status_event_wait_q, &wait);
2159         set_current_state(TASK_INTERRUPTIBLE);
2160         spin_unlock_irqrestore(&info->lock,flags);
2161
2162         for(;;) {
2163                 schedule();
2164                 if (signal_pending(current)) {
2165                         rc = -ERESTARTSYS;
2166                         break;
2167                 }
2168
2169                 /* get new irq counts */
2170                 spin_lock_irqsave(&info->lock,flags);
2171                 cnow = info->icount;
2172                 set_current_state(TASK_INTERRUPTIBLE);
2173                 spin_unlock_irqrestore(&info->lock,flags);
2174
2175                 /* if no change, wait aborted for some reason */
2176                 if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
2177                     cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) {
2178                         rc = -EIO;
2179                         break;
2180                 }
2181
2182                 /* check for change in caller specified modem input */
2183                 if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) ||
2184                     (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) ||
2185                     (arg & TIOCM_CD  && cnow.dcd != cprev.dcd) ||
2186                     (arg & TIOCM_CTS && cnow.cts != cprev.cts)) {
2187                         rc = 0;
2188                         break;
2189                 }
2190
2191                 cprev = cnow;
2192         }
2193         remove_wait_queue(&info->status_event_wait_q, &wait);
2194         set_current_state(TASK_RUNNING);
2195         return rc;
2196 }
2197
2198 /* return the state of the serial control and status signals
2199  */
2200 static int tiocmget(struct tty_struct *tty, struct file *file)
2201 {
2202         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2203         unsigned int result;
2204         unsigned long flags;
2205
2206         spin_lock_irqsave(&info->lock,flags);
2207         get_signals(info);
2208         spin_unlock_irqrestore(&info->lock,flags);
2209
2210         result = ((info->serial_signals & SerialSignal_RTS) ? TIOCM_RTS:0) +
2211                 ((info->serial_signals & SerialSignal_DTR) ? TIOCM_DTR:0) +
2212                 ((info->serial_signals & SerialSignal_DCD) ? TIOCM_CAR:0) +
2213                 ((info->serial_signals & SerialSignal_RI)  ? TIOCM_RNG:0) +
2214                 ((info->serial_signals & SerialSignal_DSR) ? TIOCM_DSR:0) +
2215                 ((info->serial_signals & SerialSignal_CTS) ? TIOCM_CTS:0);
2216
2217         if (debug_level >= DEBUG_LEVEL_INFO)
2218                 printk("%s(%d):%s tiocmget() value=%08X\n",
2219                          __FILE__,__LINE__, info->device_name, result );
2220         return result;
2221 }
2222
2223 /* set modem control signals (DTR/RTS)
2224  */
2225 static int tiocmset(struct tty_struct *tty, struct file *file,
2226                     unsigned int set, unsigned int clear)
2227 {
2228         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2229         unsigned long flags;
2230
2231         if (debug_level >= DEBUG_LEVEL_INFO)
2232                 printk("%s(%d):%s tiocmset(%x,%x)\n",
2233                         __FILE__,__LINE__,info->device_name, set, clear);
2234
2235         if (set & TIOCM_RTS)
2236                 info->serial_signals |= SerialSignal_RTS;
2237         if (set & TIOCM_DTR)
2238                 info->serial_signals |= SerialSignal_DTR;
2239         if (clear & TIOCM_RTS)
2240                 info->serial_signals &= ~SerialSignal_RTS;
2241         if (clear & TIOCM_DTR)
2242                 info->serial_signals &= ~SerialSignal_DTR;
2243
2244         spin_lock_irqsave(&info->lock,flags);
2245         set_signals(info);
2246         spin_unlock_irqrestore(&info->lock,flags);
2247
2248         return 0;
2249 }
2250
2251 /* Set or clear transmit break condition
2252  *
2253  * Arguments:           tty             pointer to tty instance data
2254  *                      break_state     -1=set break condition, 0=clear
2255  */
2256 static void mgslpc_break(struct tty_struct *tty, int break_state)
2257 {
2258         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2259         unsigned long flags;
2260         
2261         if (debug_level >= DEBUG_LEVEL_INFO)
2262                 printk("%s(%d):mgslpc_break(%s,%d)\n",
2263                          __FILE__,__LINE__, info->device_name, break_state);
2264                          
2265         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_break"))
2266                 return;
2267
2268         spin_lock_irqsave(&info->lock,flags);
2269         if (break_state == -1)
2270                 set_reg_bits(info, CHA+DAFO, BIT6);
2271         else 
2272                 clear_reg_bits(info, CHA+DAFO, BIT6);
2273         spin_unlock_irqrestore(&info->lock,flags);
2274 }
2275
2276 /* Service an IOCTL request
2277  *      
2278  * Arguments:
2279  * 
2280  *      tty     pointer to tty instance data
2281  *      file    pointer to associated file object for device
2282  *      cmd     IOCTL command code
2283  *      arg     command argument/context
2284  *      
2285  * Return Value:        0 if success, otherwise error code
2286  */
2287 static int mgslpc_ioctl(struct tty_struct *tty, struct file * file,
2288                         unsigned int cmd, unsigned long arg)
2289 {
2290         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2291         
2292         if (debug_level >= DEBUG_LEVEL_INFO)
2293                 printk("%s(%d):mgslpc_ioctl %s cmd=%08X\n", __FILE__,__LINE__,
2294                         info->device_name, cmd );
2295         
2296         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_ioctl"))
2297                 return -ENODEV;
2298
2299         if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
2300             (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
2301                 if (tty->flags & (1 << TTY_IO_ERROR))
2302                     return -EIO;
2303         }
2304
2305         return ioctl_common(info, cmd, arg);
2306 }
2307
2308 static int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg)
2309 {
2310         int error;
2311         struct mgsl_icount cnow;        /* kernel counter temps */
2312         struct serial_icounter_struct __user *p_cuser;  /* user space */
2313         void __user *argp = (void __user *)arg;
2314         unsigned long flags;
2315         
2316         switch (cmd) {
2317         case MGSL_IOCGPARAMS:
2318                 return get_params(info, argp);
2319         case MGSL_IOCSPARAMS:
2320                 return set_params(info, argp);
2321         case MGSL_IOCGTXIDLE:
2322                 return get_txidle(info, argp);
2323         case MGSL_IOCSTXIDLE:
2324                 return set_txidle(info, (int)arg);
2325         case MGSL_IOCGIF:
2326                 return get_interface(info, argp);
2327         case MGSL_IOCSIF:
2328                 return set_interface(info,(int)arg);
2329         case MGSL_IOCTXENABLE:
2330                 return set_txenable(info,(int)arg);
2331         case MGSL_IOCRXENABLE:
2332                 return set_rxenable(info,(int)arg);
2333         case MGSL_IOCTXABORT:
2334                 return tx_abort(info);
2335         case MGSL_IOCGSTATS:
2336                 return get_stats(info, argp);
2337         case MGSL_IOCWAITEVENT:
2338                 return wait_events(info, argp);
2339         case TIOCMIWAIT:
2340                 return modem_input_wait(info,(int)arg);
2341         case TIOCGICOUNT:
2342                 spin_lock_irqsave(&info->lock,flags);
2343                 cnow = info->icount;
2344                 spin_unlock_irqrestore(&info->lock,flags);
2345                 p_cuser = argp;
2346                 PUT_USER(error,cnow.cts, &p_cuser->cts);
2347                 if (error) return error;
2348                 PUT_USER(error,cnow.dsr, &p_cuser->dsr);
2349                 if (error) return error;
2350                 PUT_USER(error,cnow.rng, &p_cuser->rng);
2351                 if (error) return error;
2352                 PUT_USER(error,cnow.dcd, &p_cuser->dcd);
2353                 if (error) return error;
2354                 PUT_USER(error,cnow.rx, &p_cuser->rx);
2355                 if (error) return error;
2356                 PUT_USER(error,cnow.tx, &p_cuser->tx);
2357                 if (error) return error;
2358                 PUT_USER(error,cnow.frame, &p_cuser->frame);
2359                 if (error) return error;
2360                 PUT_USER(error,cnow.overrun, &p_cuser->overrun);
2361                 if (error) return error;
2362                 PUT_USER(error,cnow.parity, &p_cuser->parity);
2363                 if (error) return error;
2364                 PUT_USER(error,cnow.brk, &p_cuser->brk);
2365                 if (error) return error;
2366                 PUT_USER(error,cnow.buf_overrun, &p_cuser->buf_overrun);
2367                 if (error) return error;
2368                 return 0;
2369         default:
2370                 return -ENOIOCTLCMD;
2371         }
2372         return 0;
2373 }
2374
2375 /* Set new termios settings
2376  *      
2377  * Arguments:
2378  * 
2379  *      tty             pointer to tty structure
2380  *      termios         pointer to buffer to hold returned old termios
2381  */
2382 static void mgslpc_set_termios(struct tty_struct *tty, struct termios *old_termios)
2383 {
2384         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2385         unsigned long flags;
2386         
2387         if (debug_level >= DEBUG_LEVEL_INFO)
2388                 printk("%s(%d):mgslpc_set_termios %s\n", __FILE__,__LINE__,
2389                         tty->driver->name );
2390         
2391         /* just return if nothing has changed */
2392         if ((tty->termios->c_cflag == old_termios->c_cflag)
2393             && (RELEVANT_IFLAG(tty->termios->c_iflag) 
2394                 == RELEVANT_IFLAG(old_termios->c_iflag)))
2395           return;
2396
2397         mgslpc_change_params(info);
2398
2399         /* Handle transition to B0 status */
2400         if (old_termios->c_cflag & CBAUD &&
2401             !(tty->termios->c_cflag & CBAUD)) {
2402                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
2403                 spin_lock_irqsave(&info->lock,flags);
2404                 set_signals(info);
2405                 spin_unlock_irqrestore(&info->lock,flags);
2406         }
2407         
2408         /* Handle transition away from B0 status */
2409         if (!(old_termios->c_cflag & CBAUD) &&
2410             tty->termios->c_cflag & CBAUD) {
2411                 info->serial_signals |= SerialSignal_DTR;
2412                 if (!(tty->termios->c_cflag & CRTSCTS) || 
2413                     !test_bit(TTY_THROTTLED, &tty->flags)) {
2414                         info->serial_signals |= SerialSignal_RTS;
2415                 }
2416                 spin_lock_irqsave(&info->lock,flags);
2417                 set_signals(info);
2418                 spin_unlock_irqrestore(&info->lock,flags);
2419         }
2420         
2421         /* Handle turning off CRTSCTS */
2422         if (old_termios->c_cflag & CRTSCTS &&
2423             !(tty->termios->c_cflag & CRTSCTS)) {
2424                 tty->hw_stopped = 0;
2425                 tx_release(tty);
2426         }
2427 }
2428
2429 static void mgslpc_close(struct tty_struct *tty, struct file * filp)
2430 {
2431         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2432
2433         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_close"))
2434                 return;
2435         
2436         if (debug_level >= DEBUG_LEVEL_INFO)
2437                 printk("%s(%d):mgslpc_close(%s) entry, count=%d\n",
2438                          __FILE__,__LINE__, info->device_name, info->count);
2439                          
2440         if (!info->count)
2441                 return;
2442
2443         if (tty_hung_up_p(filp))
2444                 goto cleanup;
2445                         
2446         if ((tty->count == 1) && (info->count != 1)) {
2447                 /*
2448                  * tty->count is 1 and the tty structure will be freed.
2449                  * info->count should be one in this case.
2450                  * if it's not, correct it so that the port is shutdown.
2451                  */
2452                 printk("mgslpc_close: bad refcount; tty->count is 1, "
2453                        "info->count is %d\n", info->count);
2454                 info->count = 1;
2455         }
2456         
2457         info->count--;
2458         
2459         /* if at least one open remaining, leave hardware active */
2460         if (info->count)
2461                 goto cleanup;
2462         
2463         info->flags |= ASYNC_CLOSING;
2464         
2465         /* set tty->closing to notify line discipline to 
2466          * only process XON/XOFF characters. Only the N_TTY
2467          * discipline appears to use this (ppp does not).
2468          */
2469         tty->closing = 1;
2470         
2471         /* wait for transmit data to clear all layers */
2472         
2473         if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) {
2474                 if (debug_level >= DEBUG_LEVEL_INFO)
2475                         printk("%s(%d):mgslpc_close(%s) calling tty_wait_until_sent\n",
2476                                  __FILE__,__LINE__, info->device_name );
2477                 tty_wait_until_sent(tty, info->closing_wait);
2478         }
2479                 
2480         if (info->flags & ASYNC_INITIALIZED)
2481                 mgslpc_wait_until_sent(tty, info->timeout);
2482
2483         if (tty->driver->flush_buffer)
2484                 tty->driver->flush_buffer(tty);
2485
2486         ldisc_flush_buffer(tty);
2487                 
2488         shutdown(info);
2489         
2490         tty->closing = 0;
2491         info->tty = NULL;
2492         
2493         if (info->blocked_open) {
2494                 if (info->close_delay) {
2495                         msleep_interruptible(jiffies_to_msecs(info->close_delay));
2496                 }
2497                 wake_up_interruptible(&info->open_wait);
2498         }
2499         
2500         info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
2501                          
2502         wake_up_interruptible(&info->close_wait);
2503         
2504 cleanup:                        
2505         if (debug_level >= DEBUG_LEVEL_INFO)
2506                 printk("%s(%d):mgslpc_close(%s) exit, count=%d\n", __FILE__,__LINE__,
2507                         tty->driver->name, info->count);
2508 }
2509
2510 /* Wait until the transmitter is empty.
2511  */
2512 static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout)
2513 {
2514         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2515         unsigned long orig_jiffies, char_time;
2516
2517         if (!info )
2518                 return;
2519
2520         if (debug_level >= DEBUG_LEVEL_INFO)
2521                 printk("%s(%d):mgslpc_wait_until_sent(%s) entry\n",
2522                          __FILE__,__LINE__, info->device_name );
2523       
2524         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_wait_until_sent"))
2525                 return;
2526
2527         if (!(info->flags & ASYNC_INITIALIZED))
2528                 goto exit;
2529          
2530         orig_jiffies = jiffies;
2531       
2532         /* Set check interval to 1/5 of estimated time to
2533          * send a character, and make it at least 1. The check
2534          * interval should also be less than the timeout.
2535          * Note: use tight timings here to satisfy the NIST-PCTS.
2536          */ 
2537        
2538         if ( info->params.data_rate ) {
2539                 char_time = info->timeout/(32 * 5);
2540                 if (!char_time)
2541                         char_time++;
2542         } else
2543                 char_time = 1;
2544                 
2545         if (timeout)
2546                 char_time = min_t(unsigned long, char_time, timeout);
2547                 
2548         if (info->params.mode == MGSL_MODE_HDLC) {
2549                 while (info->tx_active) {
2550                         msleep_interruptible(jiffies_to_msecs(char_time));
2551                         if (signal_pending(current))
2552                                 break;
2553                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
2554                                 break;
2555                 }
2556         } else {
2557                 while ((info->tx_count || info->tx_active) &&
2558                         info->tx_enabled) {
2559                         msleep_interruptible(jiffies_to_msecs(char_time));
2560                         if (signal_pending(current))
2561                                 break;
2562                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
2563                                 break;
2564                 }
2565         }
2566       
2567 exit:
2568         if (debug_level >= DEBUG_LEVEL_INFO)
2569                 printk("%s(%d):mgslpc_wait_until_sent(%s) exit\n",
2570                          __FILE__,__LINE__, info->device_name );
2571 }
2572
2573 /* Called by tty_hangup() when a hangup is signaled.
2574  * This is the same as closing all open files for the port.
2575  */
2576 static void mgslpc_hangup(struct tty_struct *tty)
2577 {
2578         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2579         
2580         if (debug_level >= DEBUG_LEVEL_INFO)
2581                 printk("%s(%d):mgslpc_hangup(%s)\n",
2582                          __FILE__,__LINE__, info->device_name );
2583                          
2584         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_hangup"))
2585                 return;
2586
2587         mgslpc_flush_buffer(tty);
2588         shutdown(info);
2589         
2590         info->count = 0;        
2591         info->flags &= ~ASYNC_NORMAL_ACTIVE;
2592         info->tty = NULL;
2593
2594         wake_up_interruptible(&info->open_wait);
2595 }
2596
2597 /* Block the current process until the specified port
2598  * is ready to be opened.
2599  */
2600 static int block_til_ready(struct tty_struct *tty, struct file *filp,
2601                            MGSLPC_INFO *info)
2602 {
2603         DECLARE_WAITQUEUE(wait, current);
2604         int             retval;
2605         int             do_clocal = 0, extra_count = 0;
2606         unsigned long   flags;
2607         
2608         if (debug_level >= DEBUG_LEVEL_INFO)
2609                 printk("%s(%d):block_til_ready on %s\n",
2610                          __FILE__,__LINE__, tty->driver->name );
2611
2612         if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){
2613                 /* nonblock mode is set or port is not enabled */
2614                 /* just verify that callout device is not active */
2615                 info->flags |= ASYNC_NORMAL_ACTIVE;
2616                 return 0;
2617         }
2618
2619         if (tty->termios->c_cflag & CLOCAL)
2620                 do_clocal = 1;
2621
2622         /* Wait for carrier detect and the line to become
2623          * free (i.e., not in use by the callout).  While we are in
2624          * this loop, info->count is dropped by one, so that
2625          * mgslpc_close() knows when to free things.  We restore it upon
2626          * exit, either normal or abnormal.
2627          */
2628          
2629         retval = 0;
2630         add_wait_queue(&info->open_wait, &wait);
2631         
2632         if (debug_level >= DEBUG_LEVEL_INFO)
2633                 printk("%s(%d):block_til_ready before block on %s count=%d\n",
2634                          __FILE__,__LINE__, tty->driver->name, info->count );
2635
2636         spin_lock_irqsave(&info->lock, flags);
2637         if (!tty_hung_up_p(filp)) {
2638                 extra_count = 1;
2639                 info->count--;
2640         }
2641         spin_unlock_irqrestore(&info->lock, flags);
2642         info->blocked_open++;
2643         
2644         while (1) {
2645                 if ((tty->termios->c_cflag & CBAUD)) {
2646                         spin_lock_irqsave(&info->lock,flags);
2647                         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
2648                         set_signals(info);
2649                         spin_unlock_irqrestore(&info->lock,flags);
2650                 }
2651                 
2652                 set_current_state(TASK_INTERRUPTIBLE);
2653                 
2654                 if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)){
2655                         retval = (info->flags & ASYNC_HUP_NOTIFY) ?
2656                                         -EAGAIN : -ERESTARTSYS;
2657                         break;
2658                 }
2659                 
2660                 spin_lock_irqsave(&info->lock,flags);
2661                 get_signals(info);
2662                 spin_unlock_irqrestore(&info->lock,flags);
2663                 
2664                 if (!(info->flags & ASYNC_CLOSING) &&
2665                     (do_clocal || (info->serial_signals & SerialSignal_DCD)) ) {
2666                         break;
2667                 }
2668                         
2669                 if (signal_pending(current)) {
2670                         retval = -ERESTARTSYS;
2671                         break;
2672                 }
2673                 
2674                 if (debug_level >= DEBUG_LEVEL_INFO)
2675                         printk("%s(%d):block_til_ready blocking on %s count=%d\n",
2676                                  __FILE__,__LINE__, tty->driver->name, info->count );
2677                                  
2678                 schedule();
2679         }
2680         
2681         set_current_state(TASK_RUNNING);
2682         remove_wait_queue(&info->open_wait, &wait);
2683         
2684         if (extra_count)
2685                 info->count++;
2686         info->blocked_open--;
2687         
2688         if (debug_level >= DEBUG_LEVEL_INFO)
2689                 printk("%s(%d):block_til_ready after blocking on %s count=%d\n",
2690                          __FILE__,__LINE__, tty->driver->name, info->count );
2691                          
2692         if (!retval)
2693                 info->flags |= ASYNC_NORMAL_ACTIVE;
2694                 
2695         return retval;
2696 }
2697
2698 static int mgslpc_open(struct tty_struct *tty, struct file * filp)
2699 {
2700         MGSLPC_INFO     *info;
2701         int                     retval, line;
2702         unsigned long flags;
2703
2704         /* verify range of specified line number */     
2705         line = tty->index;
2706         if ((line < 0) || (line >= mgslpc_device_count)) {
2707                 printk("%s(%d):mgslpc_open with invalid line #%d.\n",
2708                         __FILE__,__LINE__,line);
2709                 return -ENODEV;
2710         }
2711
2712         /* find the info structure for the specified line */
2713         info = mgslpc_device_list;
2714         while(info && info->line != line)
2715                 info = info->next_device;
2716         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_open"))
2717                 return -ENODEV;
2718         
2719         tty->driver_data = info;
2720         info->tty = tty;
2721                 
2722         if (debug_level >= DEBUG_LEVEL_INFO)
2723                 printk("%s(%d):mgslpc_open(%s), old ref count = %d\n",
2724                          __FILE__,__LINE__,tty->driver->name, info->count);
2725
2726         /* If port is closing, signal caller to try again */
2727         if (tty_hung_up_p(filp) || info->flags & ASYNC_CLOSING){
2728                 if (info->flags & ASYNC_CLOSING)
2729                         interruptible_sleep_on(&info->close_wait);
2730                 retval = ((info->flags & ASYNC_HUP_NOTIFY) ?
2731                         -EAGAIN : -ERESTARTSYS);
2732                 goto cleanup;
2733         }
2734         
2735         info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
2736
2737         spin_lock_irqsave(&info->netlock, flags);
2738         if (info->netcount) {
2739                 retval = -EBUSY;
2740                 spin_unlock_irqrestore(&info->netlock, flags);
2741                 goto cleanup;
2742         }
2743         info->count++;
2744         spin_unlock_irqrestore(&info->netlock, flags);
2745
2746         if (info->count == 1) {
2747                 /* 1st open on this device, init hardware */
2748                 retval = startup(info);
2749                 if (retval < 0)
2750                         goto cleanup;
2751         }
2752
2753         retval = block_til_ready(tty, filp, info);
2754         if (retval) {
2755                 if (debug_level >= DEBUG_LEVEL_INFO)
2756                         printk("%s(%d):block_til_ready(%s) returned %d\n",
2757                                  __FILE__,__LINE__, info->device_name, retval);
2758                 goto cleanup;
2759         }
2760
2761         if (debug_level >= DEBUG_LEVEL_INFO)
2762                 printk("%s(%d):mgslpc_open(%s) success\n",
2763                          __FILE__,__LINE__, info->device_name);
2764         retval = 0;
2765         
2766 cleanup:                        
2767         if (retval) {
2768                 if (tty->count == 1)
2769                         info->tty = NULL; /* tty layer will release tty struct */
2770                 if(info->count)
2771                         info->count--;
2772         }
2773         
2774         return retval;
2775 }
2776
2777 /*
2778  * /proc fs routines....
2779  */
2780
2781 static inline int line_info(char *buf, MGSLPC_INFO *info)
2782 {
2783         char    stat_buf[30];
2784         int     ret;
2785         unsigned long flags;
2786
2787         ret = sprintf(buf, "%s:io:%04X irq:%d",
2788                       info->device_name, info->io_base, info->irq_level);
2789
2790         /* output current serial signal states */
2791         spin_lock_irqsave(&info->lock,flags);
2792         get_signals(info);
2793         spin_unlock_irqrestore(&info->lock,flags);
2794         
2795         stat_buf[0] = 0;
2796         stat_buf[1] = 0;
2797         if (info->serial_signals & SerialSignal_RTS)
2798                 strcat(stat_buf, "|RTS");
2799         if (info->serial_signals & SerialSignal_CTS)
2800                 strcat(stat_buf, "|CTS");
2801         if (info->serial_signals & SerialSignal_DTR)
2802                 strcat(stat_buf, "|DTR");
2803         if (info->serial_signals & SerialSignal_DSR)
2804                 strcat(stat_buf, "|DSR");
2805         if (info->serial_signals & SerialSignal_DCD)
2806                 strcat(stat_buf, "|CD");
2807         if (info->serial_signals & SerialSignal_RI)
2808                 strcat(stat_buf, "|RI");
2809
2810         if (info->params.mode == MGSL_MODE_HDLC) {
2811                 ret += sprintf(buf+ret, " HDLC txok:%d rxok:%d",
2812                               info->icount.txok, info->icount.rxok);
2813                 if (info->icount.txunder)
2814                         ret += sprintf(buf+ret, " txunder:%d", info->icount.txunder);
2815                 if (info->icount.txabort)
2816                         ret += sprintf(buf+ret, " txabort:%d", info->icount.txabort);
2817                 if (info->icount.rxshort)
2818                         ret += sprintf(buf+ret, " rxshort:%d", info->icount.rxshort);   
2819                 if (info->icount.rxlong)
2820                         ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxlong);
2821                 if (info->icount.rxover)
2822                         ret += sprintf(buf+ret, " rxover:%d", info->icount.rxover);
2823                 if (info->icount.rxcrc)
2824                         ret += sprintf(buf+ret, " rxcrc:%d", info->icount.rxcrc);
2825         } else {
2826                 ret += sprintf(buf+ret, " ASYNC tx:%d rx:%d",
2827                               info->icount.tx, info->icount.rx);
2828                 if (info->icount.frame)
2829                         ret += sprintf(buf+ret, " fe:%d", info->icount.frame);
2830                 if (info->icount.parity)
2831                         ret += sprintf(buf+ret, " pe:%d", info->icount.parity);
2832                 if (info->icount.brk)
2833                         ret += sprintf(buf+ret, " brk:%d", info->icount.brk);   
2834                 if (info->icount.overrun)
2835                         ret += sprintf(buf+ret, " oe:%d", info->icount.overrun);
2836         }
2837         
2838         /* Append serial signal status to end */
2839         ret += sprintf(buf+ret, " %s\n", stat_buf+1);
2840         
2841         ret += sprintf(buf+ret, "txactive=%d bh_req=%d bh_run=%d pending_bh=%x\n",
2842                        info->tx_active,info->bh_requested,info->bh_running,
2843                        info->pending_bh);
2844         
2845         return ret;
2846 }
2847
2848 /* Called to print information about devices
2849  */
2850 static int mgslpc_read_proc(char *page, char **start, off_t off, int count,
2851                  int *eof, void *data)
2852 {
2853         int len = 0, l;
2854         off_t   begin = 0;
2855         MGSLPC_INFO *info;
2856         
2857         len += sprintf(page, "synclink driver:%s\n", driver_version);
2858         
2859         info = mgslpc_device_list;
2860         while( info ) {
2861                 l = line_info(page + len, info);
2862                 len += l;
2863                 if (len+begin > off+count)
2864                         goto done;
2865                 if (len+begin < off) {
2866                         begin += len;
2867                         len = 0;
2868                 }
2869                 info = info->next_device;
2870         }
2871
2872         *eof = 1;
2873 done:
2874         if (off >= len+begin)
2875                 return 0;
2876         *start = page + (off-begin);
2877         return ((count < begin+len-off) ? count : begin+len-off);
2878 }
2879
2880 static int rx_alloc_buffers(MGSLPC_INFO *info)
2881 {
2882         /* each buffer has header and data */
2883         info->rx_buf_size = sizeof(RXBUF) + info->max_frame_size;
2884
2885         /* calculate total allocation size for 8 buffers */
2886         info->rx_buf_total_size = info->rx_buf_size * 8;
2887
2888         /* limit total allocated memory */
2889         if (info->rx_buf_total_size > 0x10000)
2890                 info->rx_buf_total_size = 0x10000;
2891
2892         /* calculate number of buffers */
2893         info->rx_buf_count = info->rx_buf_total_size / info->rx_buf_size;
2894
2895         info->rx_buf = kmalloc(info->rx_buf_total_size, GFP_KERNEL);
2896         if (info->rx_buf == NULL)
2897                 return -ENOMEM;
2898
2899         rx_reset_buffers(info);
2900         return 0;
2901 }
2902
2903 static void rx_free_buffers(MGSLPC_INFO *info)
2904 {
2905         kfree(info->rx_buf);
2906         info->rx_buf = NULL;
2907 }
2908
2909 static int claim_resources(MGSLPC_INFO *info)
2910 {
2911         if (rx_alloc_buffers(info) < 0 ) {
2912                 printk( "Cant allocate rx buffer %s\n", info->device_name);
2913                 release_resources(info);
2914                 return -ENODEV;
2915         }       
2916         return 0;
2917 }
2918
2919 static void release_resources(MGSLPC_INFO *info)
2920 {
2921         if (debug_level >= DEBUG_LEVEL_INFO)
2922                 printk("release_resources(%s)\n", info->device_name);
2923         rx_free_buffers(info);
2924 }
2925
2926 /* Add the specified device instance data structure to the
2927  * global linked list of devices and increment the device count.
2928  *      
2929  * Arguments:           info    pointer to device instance data
2930  */
2931 static void mgslpc_add_device(MGSLPC_INFO *info)
2932 {
2933         info->next_device = NULL;
2934         info->line = mgslpc_device_count;
2935         sprintf(info->device_name,"ttySLP%d",info->line);
2936         
2937         if (info->line < MAX_DEVICE_COUNT) {
2938                 if (maxframe[info->line])
2939                         info->max_frame_size = maxframe[info->line];
2940                 info->dosyncppp = dosyncppp[info->line];
2941         }
2942
2943         mgslpc_device_count++;
2944         
2945         if (!mgslpc_device_list)
2946                 mgslpc_device_list = info;
2947         else {  
2948                 MGSLPC_INFO *current_dev = mgslpc_device_list;
2949                 while( current_dev->next_device )
2950                         current_dev = current_dev->next_device;
2951                 current_dev->next_device = info;
2952         }
2953         
2954         if (info->max_frame_size < 4096)
2955                 info->max_frame_size = 4096;
2956         else if (info->max_frame_size > 65535)
2957                 info->max_frame_size = 65535;
2958         
2959         printk( "SyncLink PC Card %s:IO=%04X IRQ=%d\n",
2960                 info->device_name, info->io_base, info->irq_level);
2961
2962 #ifdef CONFIG_HDLC
2963         hdlcdev_init(info);
2964 #endif
2965 }
2966
2967 static void mgslpc_remove_device(MGSLPC_INFO *remove_info)
2968 {
2969         MGSLPC_INFO *info = mgslpc_device_list;
2970         MGSLPC_INFO *last = NULL;
2971
2972         while(info) {
2973                 if (info == remove_info) {
2974                         if (last)
2975                                 last->next_device = info->next_device;
2976                         else
2977                                 mgslpc_device_list = info->next_device;
2978 #ifdef CONFIG_HDLC
2979                         hdlcdev_exit(info);
2980 #endif
2981                         release_resources(info);
2982                         kfree(info);
2983                         mgslpc_device_count--;
2984                         return;
2985                 }
2986                 last = info;
2987                 info = info->next_device;
2988         }
2989 }
2990
2991 static struct pcmcia_device_id mgslpc_ids[] = {
2992         PCMCIA_DEVICE_MANF_CARD(0x02c5, 0x0050),
2993         PCMCIA_DEVICE_NULL
2994 };
2995 MODULE_DEVICE_TABLE(pcmcia, mgslpc_ids);
2996
2997 static struct pcmcia_driver mgslpc_driver = {
2998         .owner          = THIS_MODULE,
2999         .drv            = {
3000                 .name   = "synclink_cs",
3001         },
3002         .probe          = mgslpc_probe,
3003         .remove         = mgslpc_detach,
3004         .id_table       = mgslpc_ids,
3005         .suspend        = mgslpc_suspend,
3006         .resume         = mgslpc_resume,
3007 };
3008
3009 static struct tty_operations mgslpc_ops = {
3010         .open = mgslpc_open,
3011         .close = mgslpc_close,
3012         .write = mgslpc_write,
3013         .put_char = mgslpc_put_char,
3014         .flush_chars = mgslpc_flush_chars,
3015         .write_room = mgslpc_write_room,
3016         .chars_in_buffer = mgslpc_chars_in_buffer,
3017         .flush_buffer = mgslpc_flush_buffer,
3018         .ioctl = mgslpc_ioctl,
3019         .throttle = mgslpc_throttle,
3020         .unthrottle = mgslpc_unthrottle,
3021         .send_xchar = mgslpc_send_xchar,
3022         .break_ctl = mgslpc_break,
3023         .wait_until_sent = mgslpc_wait_until_sent,
3024         .read_proc = mgslpc_read_proc,
3025         .set_termios = mgslpc_set_termios,
3026         .stop = tx_pause,
3027         .start = tx_release,
3028         .hangup = mgslpc_hangup,
3029         .tiocmget = tiocmget,
3030         .tiocmset = tiocmset,
3031 };
3032
3033 static void synclink_cs_cleanup(void)
3034 {
3035         int rc;
3036
3037         printk("Unloading %s: version %s\n", driver_name, driver_version);
3038
3039         while(mgslpc_device_list)
3040                 mgslpc_remove_device(mgslpc_device_list);
3041
3042         if (serial_driver) {
3043                 if ((rc = tty_unregister_driver(serial_driver)))
3044                         printk("%s(%d) failed to unregister tty driver err=%d\n",
3045                                __FILE__,__LINE__,rc);
3046                 put_tty_driver(serial_driver);
3047         }
3048
3049         pcmcia_unregister_driver(&mgslpc_driver);
3050 }
3051
3052 static int __init synclink_cs_init(void)
3053 {
3054     int rc;
3055
3056     if (break_on_load) {
3057             mgslpc_get_text_ptr();
3058             BREAKPOINT();
3059     }
3060
3061     printk("%s %s\n", driver_name, driver_version);
3062
3063     if ((rc = pcmcia_register_driver(&mgslpc_driver)) < 0)
3064             return rc;
3065
3066     serial_driver = alloc_tty_driver(MAX_DEVICE_COUNT);
3067     if (!serial_driver) {
3068             rc = -ENOMEM;
3069             goto error;
3070     }
3071
3072     /* Initialize the tty_driver structure */
3073         
3074     serial_driver->owner = THIS_MODULE;
3075     serial_driver->driver_name = "synclink_cs";
3076     serial_driver->name = "ttySLP";
3077     serial_driver->major = ttymajor;
3078     serial_driver->minor_start = 64;
3079     serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
3080     serial_driver->subtype = SERIAL_TYPE_NORMAL;
3081     serial_driver->init_termios = tty_std_termios;
3082     serial_driver->init_termios.c_cflag =
3083             B9600 | CS8 | CREAD | HUPCL | CLOCAL;
3084     serial_driver->flags = TTY_DRIVER_REAL_RAW;
3085     tty_set_operations(serial_driver, &mgslpc_ops);
3086
3087     if ((rc = tty_register_driver(serial_driver)) < 0) {
3088             printk("%s(%d):Couldn't register serial driver\n",
3089                    __FILE__,__LINE__);
3090             put_tty_driver(serial_driver);
3091             serial_driver = NULL;
3092             goto error;
3093     }
3094                         
3095     printk("%s %s, tty major#%d\n",
3096            driver_name, driver_version,
3097            serial_driver->major);
3098         
3099     return 0;
3100
3101 error:
3102     synclink_cs_cleanup();
3103     return rc;
3104 }
3105
3106 static void __exit synclink_cs_exit(void) 
3107 {
3108         synclink_cs_cleanup();
3109 }
3110
3111 module_init(synclink_cs_init);
3112 module_exit(synclink_cs_exit);
3113
3114 static void mgslpc_set_rate(MGSLPC_INFO *info, unsigned char channel, unsigned int rate)
3115 {
3116         unsigned int M, N;
3117         unsigned char val;
3118
3119         /* note:standard BRG mode is broken in V3.2 chip 
3120          * so enhanced mode is always used 
3121          */
3122
3123         if (rate) {
3124                 N = 3686400 / rate;
3125                 if (!N)
3126                         N = 1;
3127                 N >>= 1;
3128                 for (M = 1; N > 64 && M < 16; M++)
3129                         N >>= 1;
3130                 N--;
3131
3132                 /* BGR[5..0] = N
3133                  * BGR[9..6] = M
3134                  * BGR[7..0] contained in BGR register
3135                  * BGR[9..8] contained in CCR2[7..6]
3136                  * divisor = (N+1)*2^M
3137                  *
3138                  * Note: M *must* not be zero (causes asymetric duty cycle)
3139                  */ 
3140                 write_reg(info, (unsigned char) (channel + BGR),
3141                                   (unsigned char) ((M << 6) + N));
3142                 val = read_reg(info, (unsigned char) (channel + CCR2)) & 0x3f;
3143                 val |= ((M << 4) & 0xc0);
3144                 write_reg(info, (unsigned char) (channel + CCR2), val);
3145         }
3146 }
3147
3148 /* Enabled the AUX clock output at the specified frequency.
3149  */
3150 static void enable_auxclk(MGSLPC_INFO *info)
3151 {
3152         unsigned char val;
3153         
3154         /* MODE
3155          *
3156          * 07..06  MDS[1..0] 10 = transparent HDLC mode
3157          * 05      ADM Address Mode, 0 = no addr recognition
3158          * 04      TMD Timer Mode, 0 = external
3159          * 03      RAC Receiver Active, 0 = inactive
3160          * 02      RTS 0=RTS active during xmit, 1=RTS always active
3161          * 01      TRS Timer Resolution, 1=512
3162          * 00      TLP Test Loop, 0 = no loop
3163          *
3164          * 1000 0010
3165          */ 
3166         val = 0x82;
3167         
3168         /* channel B RTS is used to enable AUXCLK driver on SP505 */ 
3169         if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed)
3170                 val |= BIT2;
3171         write_reg(info, CHB + MODE, val);
3172         
3173         /* CCR0
3174          *
3175          * 07      PU Power Up, 1=active, 0=power down
3176          * 06      MCE Master Clock Enable, 1=enabled
3177          * 05      Reserved, 0
3178          * 04..02  SC[2..0] Encoding
3179          * 01..00  SM[1..0] Serial Mode, 00=HDLC
3180          *
3181          * 11000000
3182          */ 
3183         write_reg(info, CHB + CCR0, 0xc0);
3184         
3185         /* CCR1
3186          *
3187          * 07      SFLG Shared Flag, 0 = disable shared flags
3188          * 06      GALP Go Active On Loop, 0 = not used
3189          * 05      GLP Go On Loop, 0 = not used
3190          * 04      ODS Output Driver Select, 1=TxD is push-pull output
3191          * 03      ITF Interframe Time Fill, 0=mark, 1=flag
3192          * 02..00  CM[2..0] Clock Mode
3193          *
3194          * 0001 0111
3195          */ 
3196         write_reg(info, CHB + CCR1, 0x17);
3197         
3198         /* CCR2 (Channel B)
3199          *
3200          * 07..06  BGR[9..8] Baud rate bits 9..8
3201          * 05      BDF Baud rate divisor factor, 0=1, 1=BGR value
3202          * 04      SSEL Clock source select, 1=submode b
3203          * 03      TOE 0=TxCLK is input, 1=TxCLK is output
3204          * 02      RWX Read/Write Exchange 0=disabled
3205          * 01      C32, CRC select, 0=CRC-16, 1=CRC-32
3206          * 00      DIV, data inversion 0=disabled, 1=enabled
3207          *
3208          * 0011 1000
3209          */ 
3210         if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed)
3211                 write_reg(info, CHB + CCR2, 0x38);
3212         else
3213                 write_reg(info, CHB + CCR2, 0x30);
3214         
3215         /* CCR4
3216          *
3217          * 07      MCK4 Master Clock Divide by 4, 1=enabled
3218          * 06      EBRG Enhanced Baud Rate Generator Mode, 1=enabled
3219          * 05      TST1 Test Pin, 0=normal operation
3220          * 04      ICD Ivert Carrier Detect, 1=enabled (active low)
3221          * 03..02  Reserved, must be 0
3222          * 01..00  RFT[1..0] RxFIFO Threshold 00=32 bytes
3223          *
3224          * 0101 0000
3225          */ 
3226         write_reg(info, CHB + CCR4, 0x50);
3227         
3228         /* if auxclk not enabled, set internal BRG so
3229          * CTS transitions can be detected (requires TxC)
3230          */ 
3231         if (info->params.mode == MGSL_MODE_HDLC && info->params.clock_speed)
3232                 mgslpc_set_rate(info, CHB, info->params.clock_speed);
3233         else
3234                 mgslpc_set_rate(info, CHB, 921600);
3235 }
3236
3237 static void loopback_enable(MGSLPC_INFO *info) 
3238 {
3239         unsigned char val;
3240         
3241         /* CCR1:02..00  CM[2..0] Clock Mode = 111 (clock mode 7) */ 
3242         val = read_reg(info, CHA + CCR1) | (BIT2 + BIT1 + BIT0);
3243         write_reg(info, CHA + CCR1, val);
3244         
3245         /* CCR2:04 SSEL Clock source select, 1=submode b */ 
3246         val = read_reg(info, CHA + CCR2) | (BIT4 + BIT5);
3247         write_reg(info, CHA + CCR2, val);
3248         
3249         /* set LinkSpeed if available, otherwise default to 2Mbps */ 
3250         if (info->params.clock_speed)
3251                 mgslpc_set_rate(info, CHA, info->params.clock_speed);
3252         else
3253                 mgslpc_set_rate(info, CHA, 1843200);
3254         
3255         /* MODE:00 TLP Test Loop, 1=loopback enabled */ 
3256         val = read_reg(info, CHA + MODE) | BIT0;
3257         write_reg(info, CHA + MODE, val);
3258 }
3259
3260 static void hdlc_mode(MGSLPC_INFO *info)
3261 {
3262         unsigned char val;
3263         unsigned char clkmode, clksubmode;
3264
3265         /* disable all interrupts */ 
3266         irq_disable(info, CHA, 0xffff);
3267         irq_disable(info, CHB, 0xffff);
3268         port_irq_disable(info, 0xff);
3269         
3270         /* assume clock mode 0a, rcv=RxC xmt=TxC */ 
3271         clkmode = clksubmode = 0;
3272         if (info->params.flags & HDLC_FLAG_RXC_DPLL
3273             && info->params.flags & HDLC_FLAG_TXC_DPLL) {
3274                 /* clock mode 7a, rcv = DPLL, xmt = DPLL */ 
3275                 clkmode = 7;
3276         } else if (info->params.flags & HDLC_FLAG_RXC_BRG
3277                  && info->params.flags & HDLC_FLAG_TXC_BRG) {
3278                 /* clock mode 7b, rcv = BRG, xmt = BRG */ 
3279                 clkmode = 7;
3280                 clksubmode = 1;
3281         } else if (info->params.flags & HDLC_FLAG_RXC_DPLL) {
3282                 if (info->params.flags & HDLC_FLAG_TXC_BRG) {
3283                         /* clock mode 6b, rcv = DPLL, xmt = BRG/16 */ 
3284                         clkmode = 6;
3285                         clksubmode = 1;
3286                 } else {
3287                         /* clock mode 6a, rcv = DPLL, xmt = TxC */ 
3288                         clkmode = 6;
3289                 }
3290         } else if (info->params.flags & HDLC_FLAG_TXC_BRG) {
3291                 /* clock mode 0b, rcv = RxC, xmt = BRG */ 
3292                 clksubmode = 1;
3293         }
3294         
3295         /* MODE
3296          *
3297          * 07..06  MDS[1..0] 10 = transparent HDLC mode
3298          * 05      ADM Address Mode, 0 = no addr recognition
3299          * 04      TMD Timer Mode, 0 = external
3300          * 03      RAC Receiver Active, 0 = inactive
3301          * 02      RTS 0=RTS active during xmit, 1=RTS always active
3302          * 01      TRS Timer Resolution, 1=512
3303          * 00      TLP Test Loop, 0 = no loop
3304          *
3305          * 1000 0010
3306          */ 
3307         val = 0x82;
3308         if (info->params.loopback)
3309                 val |= BIT0;
3310         
3311         /* preserve RTS state */ 
3312         if (info->serial_signals & SerialSignal_RTS)
3313                 val |= BIT2;
3314         write_reg(info, CHA + MODE, val);
3315         
3316         /* CCR0
3317          *
3318          * 07      PU Power Up, 1=active, 0=power down
3319          * 06      MCE Master Clock Enable, 1=enabled
3320          * 05      Reserved, 0
3321          * 04..02  SC[2..0] Encoding
3322          * 01..00  SM[1..0] Serial Mode, 00=HDLC
3323          *
3324          * 11000000
3325          */ 
3326         val = 0xc0;
3327         switch (info->params.encoding)
3328         {
3329         case HDLC_ENCODING_NRZI:
3330                 val |= BIT3;
3331                 break;
3332         case HDLC_ENCODING_BIPHASE_SPACE:
3333                 val |= BIT4;
3334                 break;          // FM0
3335         case HDLC_ENCODING_BIPHASE_MARK:
3336                 val |= BIT4 + BIT2;
3337                 break;          // FM1
3338         case HDLC_ENCODING_BIPHASE_LEVEL:
3339                 val |= BIT4 + BIT3;
3340                 break;          // Manchester
3341         }
3342         write_reg(info, CHA + CCR0, val);
3343         
3344         /* CCR1
3345          *
3346          * 07      SFLG Shared Flag, 0 = disable shared flags
3347          * 06      GALP Go Active On Loop, 0 = not used
3348          * 05      GLP Go On Loop, 0 = not used
3349          * 04      ODS Output Driver Select, 1=TxD is push-pull output
3350          * 03      ITF Interframe Time Fill, 0=mark, 1=flag
3351          * 02..00  CM[2..0] Clock Mode
3352          *
3353          * 0001 0000
3354          */ 
3355         val = 0x10 + clkmode;
3356         write_reg(info, CHA + CCR1, val);
3357         
3358         /* CCR2
3359          *
3360          * 07..06  BGR[9..8] Baud rate bits 9..8
3361          * 05      BDF Baud rate divisor factor, 0=1, 1=BGR value
3362          * 04      SSEL Clock source select, 1=submode b
3363          * 03      TOE 0=TxCLK is input, 0=TxCLK is input
3364          * 02      RWX Read/Write Exchange 0=disabled
3365          * 01      C32, CRC select, 0=CRC-16, 1=CRC-32
3366          * 00      DIV, data inversion 0=disabled, 1=enabled
3367          *
3368          * 0000 0000
3369          */ 
3370         val = 0x00;
3371         if (clkmode == 2 || clkmode == 3 || clkmode == 6
3372             || clkmode == 7 || (clkmode == 0 && clksubmode == 1))
3373                 val |= BIT5;
3374         if (clksubmode)
3375                 val |= BIT4;
3376         if (info->params.crc_type == HDLC_CRC_32_CCITT)
3377                 val |= BIT1;
3378         if (info->params.encoding == HDLC_ENCODING_NRZB)
3379                 val |= BIT0;
3380         write_reg(info, CHA + CCR2, val);
3381         
3382         /* CCR3
3383          *
3384          * 07..06  PRE[1..0] Preamble count 00=1, 01=2, 10=4, 11=8
3385          * 05      EPT Enable preamble transmission, 1=enabled
3386          * 04      RADD Receive address pushed to FIFO, 0=disabled
3387          * 03      CRL CRC Reset Level, 0=FFFF
3388          * 02      RCRC Rx CRC 0=On 1=Off
3389          * 01      TCRC Tx CRC 0=On 1=Off
3390          * 00      PSD DPLL Phase Shift Disable
3391          *
3392          * 0000 0000
3393          */ 
3394         val = 0x00;
3395         if (info->params.crc_type == HDLC_CRC_NONE)
3396                 val |= BIT2 + BIT1;
3397         if (info->params.preamble != HDLC_PREAMBLE_PATTERN_NONE)
3398                 val |= BIT5;
3399         switch (info->params.preamble_length)
3400         {
3401         case HDLC_PREAMBLE_LENGTH_16BITS:
3402                 val |= BIT6;
3403                 break;
3404         case HDLC_PREAMBLE_LENGTH_32BITS:
3405                 val |= BIT6;
3406                 break;
3407         case HDLC_PREAMBLE_LENGTH_64BITS:
3408                 val |= BIT7 + BIT6;
3409                 break;
3410         }
3411         write_reg(info, CHA + CCR3, val);
3412         
3413         /* PRE - Preamble pattern */ 
3414         val = 0;
3415         switch (info->params.preamble)
3416         {
3417         case HDLC_PREAMBLE_PATTERN_FLAGS: val = 0x7e; break;
3418         case HDLC_PREAMBLE_PATTERN_10:    val = 0xaa; break;
3419         case HDLC_PREAMBLE_PATTERN_01:    val = 0x55; break;
3420         case HDLC_PREAMBLE_PATTERN_ONES:  val = 0xff; break;
3421         }
3422         write_reg(info, CHA + PRE, val);
3423         
3424         /* CCR4
3425          *
3426          * 07      MCK4 Master Clock Divide by 4, 1=enabled
3427          * 06      EBRG Enhanced Baud Rate Generator Mode, 1=enabled
3428          * 05      TST1 Test Pin, 0=normal operation
3429          * 04      ICD Ivert Carrier Detect, 1=enabled (active low)
3430          * 03..02  Reserved, must be 0
3431          * 01..00  RFT[1..0] RxFIFO Threshold 00=32 bytes
3432          *
3433          * 0101 0000
3434          */ 
3435         val = 0x50;
3436         write_reg(info, CHA + CCR4, val);
3437         if (info->params.flags & HDLC_FLAG_RXC_DPLL)
3438                 mgslpc_set_rate(info, CHA, info->params.clock_speed * 16);
3439         else
3440                 mgslpc_set_rate(info, CHA, info->params.clock_speed);
3441         
3442         /* RLCR Receive length check register
3443          *
3444          * 7     1=enable receive length check
3445          * 6..0  Max frame length = (RL + 1) * 32
3446          */ 
3447         write_reg(info, CHA + RLCR, 0);
3448         
3449         /* XBCH Transmit Byte Count High
3450          *
3451          * 07      DMA mode, 0 = interrupt driven
3452          * 06      NRM, 0=ABM (ignored)
3453          * 05      CAS Carrier Auto Start
3454          * 04      XC Transmit Continuously (ignored)
3455          * 03..00  XBC[10..8] Transmit byte count bits 10..8
3456          *
3457          * 0000 0000
3458          */ 
3459         val = 0x00;
3460         if (info->params.flags & HDLC_FLAG_AUTO_DCD)
3461                 val |= BIT5;
3462         write_reg(info, CHA + XBCH, val);
3463         enable_auxclk(info);
3464         if (info->params.loopback || info->testing_irq)
3465                 loopback_enable(info);
3466         if (info->params.flags & HDLC_FLAG_AUTO_CTS)
3467         {
3468                 irq_enable(info, CHB, IRQ_CTS);
3469                 /* PVR[3] 1=AUTO CTS active */ 
3470                 set_reg_bits(info, CHA + PVR, BIT3);
3471         } else
3472                 clear_reg_bits(info, CHA + PVR, BIT3);
3473
3474         irq_enable(info, CHA,
3475                          IRQ_RXEOM + IRQ_RXFIFO + IRQ_ALLSENT +
3476                          IRQ_UNDERRUN + IRQ_TXFIFO);
3477         issue_command(info, CHA, CMD_TXRESET + CMD_RXRESET);
3478         wait_command_complete(info, CHA);
3479         read_reg16(info, CHA + ISR);    /* clear pending IRQs */
3480         
3481         /* Master clock mode enabled above to allow reset commands
3482          * to complete even if no data clocks are present.
3483          *
3484          * Disable master clock mode for normal communications because
3485          * V3.2 of the ESCC2 has a bug that prevents the transmit all sent
3486          * IRQ when in master clock mode.
3487          *
3488          * Leave master clock mode enabled for IRQ test because the
3489          * timer IRQ used by the test can only happen in master clock mode.
3490          */ 
3491         if (!info->testing_irq)
3492                 clear_reg_bits(info, CHA + CCR0, BIT6);
3493
3494         tx_set_idle(info);
3495
3496         tx_stop(info);
3497         rx_stop(info);
3498 }
3499
3500 static void rx_stop(MGSLPC_INFO *info)
3501 {
3502         if (debug_level >= DEBUG_LEVEL_ISR)
3503                 printk("%s(%d):rx_stop(%s)\n",
3504                          __FILE__,__LINE__, info->device_name );
3505                          
3506         /* MODE:03 RAC Receiver Active, 0=inactive */ 
3507         clear_reg_bits(info, CHA + MODE, BIT3);
3508
3509         info->rx_enabled = 0;
3510         info->rx_overflow = 0;
3511 }
3512
3513 static void rx_start(MGSLPC_INFO *info)
3514 {
3515         if (debug_level >= DEBUG_LEVEL_ISR)
3516                 printk("%s(%d):rx_start(%s)\n",
3517                          __FILE__,__LINE__, info->device_name );
3518
3519         rx_reset_buffers(info);
3520         info->rx_enabled = 0;
3521         info->rx_overflow = 0;
3522
3523         /* MODE:03 RAC Receiver Active, 1=active */ 
3524         set_reg_bits(info, CHA + MODE, BIT3);
3525
3526         info->rx_enabled = 1;
3527 }
3528
3529 static void tx_start(MGSLPC_INFO *info)
3530 {
3531         if (debug_level >= DEBUG_LEVEL_ISR)
3532                 printk("%s(%d):tx_start(%s)\n",
3533                          __FILE__,__LINE__, info->device_name );
3534                          
3535         if (info->tx_count) {
3536                 /* If auto RTS enabled and RTS is inactive, then assert */
3537                 /* RTS and set a flag indicating that the driver should */
3538                 /* negate RTS when the transmission completes. */
3539                 info->drop_rts_on_tx_done = 0;
3540
3541                 if (info->params.flags & HDLC_FLAG_AUTO_RTS) {
3542                         get_signals(info);
3543                         if (!(info->serial_signals & SerialSignal_RTS)) {
3544                                 info->serial_signals |= SerialSignal_RTS;
3545                                 set_signals(info);
3546                                 info->drop_rts_on_tx_done = 1;
3547                         }
3548                 }
3549
3550                 if (info->params.mode == MGSL_MODE_ASYNC) {
3551                         if (!info->tx_active) {
3552                                 info->tx_active = 1;
3553                                 tx_ready(info);
3554                         }
3555                 } else {
3556                         info->tx_active = 1;
3557                         tx_ready(info);
3558                         info->tx_timer.expires = jiffies + msecs_to_jiffies(5000);
3559                         add_timer(&info->tx_timer);     
3560                 }
3561         }
3562
3563         if (!info->tx_enabled)
3564                 info->tx_enabled = 1;
3565 }
3566
3567 static void tx_stop(MGSLPC_INFO *info)
3568 {
3569         if (debug_level >= DEBUG_LEVEL_ISR)
3570                 printk("%s(%d):tx_stop(%s)\n",
3571                          __FILE__,__LINE__, info->device_name );
3572                          
3573         del_timer(&info->tx_timer);     
3574
3575         info->tx_enabled = 0;
3576         info->tx_active  = 0;
3577 }
3578
3579 /* Reset the adapter to a known state and prepare it for further use.
3580  */
3581 static void reset_device(MGSLPC_INFO *info)
3582 {
3583         /* power up both channels (set BIT7) */ 
3584         write_reg(info, CHA + CCR0, 0x80);
3585         write_reg(info, CHB + CCR0, 0x80);
3586         write_reg(info, CHA + MODE, 0);
3587         write_reg(info, CHB + MODE, 0);
3588         
3589         /* disable all interrupts */ 
3590         irq_disable(info, CHA, 0xffff);
3591         irq_disable(info, CHB, 0xffff);
3592         port_irq_disable(info, 0xff);
3593         
3594         /* PCR Port Configuration Register
3595          *
3596          * 07..04  DEC[3..0] Serial I/F select outputs
3597          * 03      output, 1=AUTO CTS control enabled
3598          * 02      RI Ring Indicator input 0=active
3599          * 01      DSR input 0=active
3600          * 00      DTR output 0=active
3601          *
3602          * 0000 0110
3603          */ 
3604         write_reg(info, PCR, 0x06);
3605         
3606         /* PVR Port Value Register
3607          *
3608          * 07..04  DEC[3..0] Serial I/F select (0000=disabled)
3609          * 03      AUTO CTS output 1=enabled
3610          * 02      RI Ring Indicator input
3611          * 01      DSR input
3612          * 00      DTR output (1=inactive)
3613          *
3614          * 0000 0001
3615          */
3616 //      write_reg(info, PVR, PVR_DTR);
3617         
3618         /* IPC Interrupt Port Configuration
3619          *
3620          * 07      VIS 1=Masked interrupts visible
3621          * 06..05  Reserved, 0
3622          * 04..03  SLA Slave address, 00 ignored
3623          * 02      CASM Cascading Mode, 1=daisy chain
3624          * 01..00  IC[1..0] Interrupt Config, 01=push-pull output, active low
3625          *
3626          * 0000 0101
3627          */ 
3628         write_reg(info, IPC, 0x05);
3629 }
3630
3631 static void async_mode(MGSLPC_INFO *info)
3632 {
3633         unsigned char val;
3634
3635         /* disable all interrupts */ 
3636         irq_disable(info, CHA, 0xffff);
3637         irq_disable(info, CHB, 0xffff);
3638         port_irq_disable(info, 0xff);
3639         
3640         /* MODE
3641          *
3642          * 07      Reserved, 0
3643          * 06      FRTS RTS State, 0=active
3644          * 05      FCTS Flow Control on CTS
3645          * 04      FLON Flow Control Enable
3646          * 03      RAC Receiver Active, 0 = inactive
3647          * 02      RTS 0=Auto RTS, 1=manual RTS
3648          * 01      TRS Timer Resolution, 1=512
3649          * 00      TLP Test Loop, 0 = no loop
3650          *
3651          * 0000 0110
3652          */ 
3653         val = 0x06;
3654         if (info->params.loopback)
3655                 val |= BIT0;
3656         
3657         /* preserve RTS state */ 
3658         if (!(info->serial_signals & SerialSignal_RTS))
3659                 val |= BIT6;
3660         write_reg(info, CHA + MODE, val);
3661         
3662         /* CCR0
3663          *
3664          * 07      PU Power Up, 1=active, 0=power down
3665          * 06      MCE Master Clock Enable, 1=enabled
3666          * 05      Reserved, 0
3667          * 04..02  SC[2..0] Encoding, 000=NRZ
3668          * 01..00  SM[1..0] Serial Mode, 11=Async
3669          *
3670          * 1000 0011
3671          */ 
3672         write_reg(info, CHA + CCR0, 0x83);
3673         
3674         /* CCR1
3675          *
3676          * 07..05  Reserved, 0
3677          * 04      ODS Output Driver Select, 1=TxD is push-pull output
3678          * 03      BCR Bit Clock Rate, 1=16x
3679          * 02..00  CM[2..0] Clock Mode, 111=BRG
3680          *
3681          * 0001 1111
3682          */ 
3683         write_reg(info, CHA + CCR1, 0x1f);
3684         
3685         /* CCR2 (channel A)
3686          *
3687          * 07..06  BGR[9..8] Baud rate bits 9..8
3688          * 05      BDF Baud rate divisor factor, 0=1, 1=BGR value
3689          * 04      SSEL Clock source select, 1=submode b
3690          * 03      TOE 0=TxCLK is input, 0=TxCLK is input
3691          * 02      RWX Read/Write Exchange 0=disabled
3692          * 01      Reserved, 0
3693          * 00      DIV, data inversion 0=disabled, 1=enabled
3694          *
3695          * 0001 0000
3696          */ 
3697         write_reg(info, CHA + CCR2, 0x10);
3698         
3699         /* CCR3
3700          *
3701          * 07..01  Reserved, 0
3702          * 00      PSD DPLL Phase Shift Disable
3703          *
3704          * 0000 0000
3705          */ 
3706         write_reg(info, CHA + CCR3, 0);
3707         
3708         /* CCR4
3709          *
3710          * 07      MCK4 Master Clock Divide by 4, 1=enabled
3711          * 06      EBRG Enhanced Baud Rate Generator Mode, 1=enabled
3712          * 05      TST1 Test Pin, 0=normal operation
3713          * 04      ICD Ivert Carrier Detect, 1=enabled (active low)
3714          * 03..00  Reserved, must be 0
3715          *
3716          * 0101 0000
3717          */ 
3718         write_reg(info, CHA + CCR4, 0x50);
3719         mgslpc_set_rate(info, CHA, info->params.data_rate * 16);
3720         
3721         /* DAFO Data Format
3722          *
3723          * 07      Reserved, 0
3724          * 06      XBRK transmit break, 0=normal operation
3725          * 05      Stop bits (0=1, 1=2)
3726          * 04..03  PAR[1..0] Parity (01=odd, 10=even)
3727          * 02      PAREN Parity Enable
3728          * 01..00  CHL[1..0] Character Length (00=8, 01=7)
3729          *
3730          */ 
3731         val = 0x00;
3732         if (info->params.data_bits != 8)
3733                 val |= BIT0;    /* 7 bits */
3734         if (info->params.stop_bits != 1)
3735                 val |= BIT5;
3736         if (info->params.parity != ASYNC_PARITY_NONE)
3737         {
3738                 val |= BIT2;    /* Parity enable */
3739                 if (info->params.parity == ASYNC_PARITY_ODD)
3740                         val |= BIT3;
3741                 else
3742                         val |= BIT4;
3743         }
3744         write_reg(info, CHA + DAFO, val);
3745         
3746         /* RFC Rx FIFO Control
3747          *
3748          * 07      Reserved, 0
3749          * 06      DPS, 1=parity bit not stored in data byte
3750          * 05      DXS, 0=all data stored in FIFO (including XON/XOFF)
3751          * 04      RFDF Rx FIFO Data Format, 1=status byte stored in FIFO
3752          * 03..02  RFTH[1..0], rx threshold, 11=16 status + 16 data byte
3753          * 01      Reserved, 0
3754          * 00      TCDE Terminate Char Detect Enable, 0=disabled
3755          *
3756          * 0101 1100
3757          */ 
3758         write_reg(info, CHA + RFC, 0x5c);
3759         
3760         /* RLCR Receive length check register
3761          *
3762          * Max frame length = (RL + 1) * 32
3763          */ 
3764         write_reg(info, CHA + RLCR, 0);
3765         
3766         /* XBCH Transmit Byte Count High
3767          *
3768          * 07      DMA mode, 0 = interrupt driven
3769          * 06      NRM, 0=ABM (ignored)
3770          * 05      CAS Carrier Auto Start
3771          * 04      XC Transmit Continuously (ignored)
3772          * 03..00  XBC[10..8] Transmit byte count bits 10..8
3773          *
3774          * 0000 0000
3775          */ 
3776         val = 0x00;
3777         if (info->params.flags & HDLC_FLAG_AUTO_DCD)
3778                 val |= BIT5;
3779         write_reg(info, CHA + XBCH, val);
3780         if (info->params.flags & HDLC_FLAG_AUTO_CTS)
3781                 irq_enable(info, CHA, IRQ_CTS);
3782         
3783         /* MODE:03 RAC Receiver Active, 1=active */ 
3784         set_reg_bits(info, CHA + MODE, BIT3);
3785         enable_auxclk(info);
3786         if (info->params.flags & HDLC_FLAG_AUTO_CTS) {
3787                 irq_enable(info, CHB, IRQ_CTS);
3788                 /* PVR[3] 1=AUTO CTS active */ 
3789                 set_reg_bits(info, CHA + PVR, BIT3);
3790         } else
3791                 clear_reg_bits(info, CHA + PVR, BIT3);
3792         irq_enable(info, CHA,
3793                           IRQ_RXEOM + IRQ_RXFIFO + IRQ_BREAK_ON + IRQ_RXTIME +
3794                           IRQ_ALLSENT + IRQ_TXFIFO);
3795         issue_command(info, CHA, CMD_TXRESET + CMD_RXRESET);
3796         wait_command_complete(info, CHA);
3797         read_reg16(info, CHA + ISR);    /* clear pending IRQs */
3798 }
3799
3800 /* Set the HDLC idle mode for the transmitter.
3801  */
3802 static void tx_set_idle(MGSLPC_INFO *info)
3803 {
3804         /* Note: ESCC2 only supports flags and one idle modes */ 
3805         if (info->idle_mode == HDLC_TXIDLE_FLAGS)
3806                 set_reg_bits(info, CHA + CCR1, BIT3);
3807         else
3808                 clear_reg_bits(info, CHA + CCR1, BIT3);
3809 }
3810
3811 /* get state of the V24 status (input) signals.
3812  */
3813 static void get_signals(MGSLPC_INFO *info)
3814 {
3815         unsigned char status = 0;
3816         
3817         /* preserve DTR and RTS */ 
3818         info->serial_signals &= SerialSignal_DTR + SerialSignal_RTS;
3819
3820         if (read_reg(info, CHB + VSTR) & BIT7)
3821                 info->serial_signals |= SerialSignal_DCD;
3822         if (read_reg(info, CHB + STAR) & BIT1)
3823                 info->serial_signals |= SerialSignal_CTS;
3824
3825         status = read_reg(info, CHA + PVR);
3826         if (!(status & PVR_RI))
3827                 info->serial_signals |= SerialSignal_RI;
3828         if (!(status & PVR_DSR))
3829                 info->serial_signals |= SerialSignal_DSR;
3830 }
3831
3832 /* Set the state of DTR and RTS based on contents of
3833  * serial_signals member of device extension.
3834  */
3835 static void set_signals(MGSLPC_INFO *info)
3836 {
3837         unsigned char val;
3838
3839         val = read_reg(info, CHA + MODE);
3840         if (info->params.mode == MGSL_MODE_ASYNC) {
3841                 if (info->serial_signals & SerialSignal_RTS)
3842                         val &= ~BIT6;
3843                 else
3844                         val |= BIT6;
3845         } else {
3846                 if (info->serial_signals & SerialSignal_RTS)
3847                         val |= BIT2;
3848                 else
3849                         val &= ~BIT2;
3850         }
3851         write_reg(info, CHA + MODE, val);
3852
3853         if (info->serial_signals & SerialSignal_DTR)
3854                 clear_reg_bits(info, CHA + PVR, PVR_DTR);
3855         else
3856                 set_reg_bits(info, CHA + PVR, PVR_DTR);
3857 }
3858
3859 static void rx_reset_buffers(MGSLPC_INFO *info)
3860 {
3861         RXBUF *buf;
3862         int i;
3863
3864         info->rx_put = 0;
3865         info->rx_get = 0;
3866         info->rx_frame_count = 0;
3867         for (i=0 ; i < info->rx_buf_count ; i++) {
3868                 buf = (RXBUF*)(info->rx_buf + (i * info->rx_buf_size));
3869                 buf->status = buf->count = 0;
3870         }
3871 }
3872
3873 /* Attempt to return a received HDLC frame
3874  * Only frames received without errors are returned.
3875  *
3876  * Returns 1 if frame returned, otherwise 0
3877  */
3878 static int rx_get_frame(MGSLPC_INFO *info)
3879 {
3880         unsigned short status;
3881         RXBUF *buf;
3882         unsigned int framesize = 0;
3883         unsigned long flags;
3884         struct tty_struct *tty = info->tty;
3885         int return_frame = 0;
3886         
3887         if (info->rx_frame_count == 0)
3888                 return 0;
3889
3890         buf = (RXBUF*)(info->rx_buf + (info->rx_get * info->rx_buf_size));
3891
3892         status = buf->status;
3893
3894         /* 07  VFR  1=valid frame
3895          * 06  RDO  1=data overrun
3896          * 05  CRC  1=OK, 0=error
3897          * 04  RAB  1=frame aborted
3898          */
3899         if ((status & 0xf0) != 0xA0) {
3900                 if (!(status & BIT7) || (status & BIT4))
3901                         info->icount.rxabort++;
3902                 else if (status & BIT6)
3903                         info->icount.rxover++;
3904                 else if (!(status & BIT5)) {
3905                         info->icount.rxcrc++;
3906                         if (info->params.crc_type & HDLC_CRC_RETURN_EX)
3907                                 return_frame = 1;
3908                 }
3909                 framesize = 0;
3910 #ifdef CONFIG_HDLC
3911                 {
3912                         struct net_device_stats *stats = hdlc_stats(info->netdev);
3913                         stats->rx_errors++;
3914                         stats->rx_frame_errors++;
3915                 }
3916 #endif
3917         } else
3918                 return_frame = 1;
3919
3920         if (return_frame)
3921                 framesize = buf->count;
3922
3923         if (debug_level >= DEBUG_LEVEL_BH)
3924                 printk("%s(%d):rx_get_frame(%s) status=%04X size=%d\n",
3925                         __FILE__,__LINE__,info->device_name,status,framesize);
3926                         
3927         if (debug_level >= DEBUG_LEVEL_DATA)
3928                 trace_block(info, buf->data, framesize, 0);     
3929                 
3930         if (framesize) {
3931                 if ((info->params.crc_type & HDLC_CRC_RETURN_EX &&
3932                       framesize+1 > info->max_frame_size) ||
3933                     framesize > info->max_frame_size)
3934                         info->icount.rxlong++;
3935                 else {
3936                         if (status & BIT5)
3937                                 info->icount.rxok++;
3938
3939                         if (info->params.crc_type & HDLC_CRC_RETURN_EX) {
3940                                 *(buf->data + framesize) = status & BIT5 ? RX_OK:RX_CRC_ERROR;
3941                                 ++framesize;
3942                         }
3943
3944 #ifdef CONFIG_HDLC
3945                         if (info->netcount)
3946                                 hdlcdev_rx(info, buf->data, framesize);
3947                         else
3948 #endif
3949                                 ldisc_receive_buf(tty, buf->data, info->flag_buf, framesize);
3950                 }
3951         }
3952
3953         spin_lock_irqsave(&info->lock,flags);
3954         buf->status = buf->count = 0;
3955         info->rx_frame_count--;
3956         info->rx_get++;
3957         if (info->rx_get >= info->rx_buf_count)
3958                 info->rx_get = 0;
3959         spin_unlock_irqrestore(&info->lock,flags);
3960
3961         return 1;
3962 }
3963
3964 static BOOLEAN register_test(MGSLPC_INFO *info)
3965 {
3966         static unsigned char patterns[] = 
3967             { 0x00, 0xff, 0xaa, 0x55, 0x69, 0x96, 0x0f };
3968         static unsigned int count = ARRAY_SIZE(patterns);
3969         unsigned int i;
3970         BOOLEAN rc = TRUE;
3971         unsigned long flags;
3972
3973         spin_lock_irqsave(&info->lock,flags);
3974         reset_device(info);
3975
3976         for (i = 0; i < count; i++) {
3977                 write_reg(info, XAD1, patterns[i]);
3978                 write_reg(info, XAD2, patterns[(i + 1) % count]);
3979                 if ((read_reg(info, XAD1) != patterns[i]) ||
3980                     (read_reg(info, XAD2) != patterns[(i + 1) % count])) {
3981                         rc = FALSE;
3982                         break;
3983                 }
3984         }
3985
3986         spin_unlock_irqrestore(&info->lock,flags);
3987         return rc;
3988 }
3989
3990 static BOOLEAN irq_test(MGSLPC_INFO *info)
3991 {
3992         unsigned long end_time;
3993         unsigned long flags;
3994
3995         spin_lock_irqsave(&info->lock,flags);
3996         reset_device(info);
3997
3998         info->testing_irq = TRUE;
3999         hdlc_mode(info);
4000
4001         info->irq_occurred = FALSE;
4002
4003         /* init hdlc mode */
4004
4005         irq_enable(info, CHA, IRQ_TIMER);
4006         write_reg(info, CHA + TIMR, 0); /* 512 cycles */
4007         issue_command(info, CHA, CMD_START_TIMER);
4008
4009         spin_unlock_irqrestore(&info->lock,flags);
4010
4011         end_time=100;
4012         while(end_time-- && !info->irq_occurred) {
4013                 msleep_interruptible(10);
4014         }
4015         
4016         info->testing_irq = FALSE;
4017
4018         spin_lock_irqsave(&info->lock,flags);
4019         reset_device(info);
4020         spin_unlock_irqrestore(&info->lock,flags);
4021         
4022         return info->irq_occurred ? TRUE : FALSE;
4023 }
4024
4025 static int adapter_test(MGSLPC_INFO *info)
4026 {
4027         if (!register_test(info)) {
4028                 info->init_error = DiagStatus_AddressFailure;
4029                 printk( "%s(%d):Register test failure for device %s Addr=%04X\n",
4030                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->io_base) );
4031                 return -ENODEV;
4032         }
4033
4034         if (!irq_test(info)) {
4035                 info->init_error = DiagStatus_IrqFailure;
4036                 printk( "%s(%d):Interrupt test failure for device %s IRQ=%d\n",
4037                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->irq_level) );
4038                 return -ENODEV;
4039         }
4040
4041         if (debug_level >= DEBUG_LEVEL_INFO)
4042                 printk("%s(%d):device %s passed diagnostics\n",
4043                         __FILE__,__LINE__,info->device_name);
4044         return 0;
4045 }
4046
4047 static void trace_block(MGSLPC_INFO *info,const char* data, int count, int xmit)
4048 {
4049         int i;
4050         int linecount;
4051         if (xmit)
4052                 printk("%s tx data:\n",info->device_name);
4053         else
4054                 printk("%s rx data:\n",info->device_name);
4055                 
4056         while(count) {
4057                 if (count > 16)
4058                         linecount = 16;
4059                 else
4060                         linecount = count;
4061                         
4062                 for(i=0;i<linecount;i++)
4063                         printk("%02X ",(unsigned char)data[i]);
4064                 for(;i<17;i++)
4065                         printk("   ");
4066                 for(i=0;i<linecount;i++) {
4067                         if (data[i]>=040 && data[i]<=0176)
4068                                 printk("%c",data[i]);
4069                         else
4070                                 printk(".");
4071                 }
4072                 printk("\n");
4073                 
4074                 data  += linecount;
4075                 count -= linecount;
4076         }
4077 }
4078
4079 /* HDLC frame time out
4080  * update stats and do tx completion processing
4081  */
4082 static void tx_timeout(unsigned long context)
4083 {
4084         MGSLPC_INFO *info = (MGSLPC_INFO*)context;
4085         unsigned long flags;
4086         
4087         if ( debug_level >= DEBUG_LEVEL_INFO )
4088                 printk( "%s(%d):tx_timeout(%s)\n",
4089                         __FILE__,__LINE__,info->device_name);
4090         if(info->tx_active &&
4091            info->params.mode == MGSL_MODE_HDLC) {
4092                 info->icount.txtimeout++;
4093         }
4094         spin_lock_irqsave(&info->lock,flags);
4095         info->tx_active = 0;
4096         info->tx_count = info->tx_put = info->tx_get = 0;
4097
4098         spin_unlock_irqrestore(&info->lock,flags);
4099         
4100 #ifdef CONFIG_HDLC
4101         if (info->netcount)
4102                 hdlcdev_tx_done(info);
4103         else
4104 #endif
4105                 bh_transmit(info);
4106 }
4107
4108 #ifdef CONFIG_HDLC
4109
4110 /**
4111  * called by generic HDLC layer when protocol selected (PPP, frame relay, etc.)
4112  * set encoding and frame check sequence (FCS) options
4113  *
4114  * dev       pointer to network device structure
4115  * encoding  serial encoding setting
4116  * parity    FCS setting
4117  *
4118  * returns 0 if success, otherwise error code
4119  */
4120 static int hdlcdev_attach(struct net_device *dev, unsigned short encoding,
4121                           unsigned short parity)
4122 {
4123         MGSLPC_INFO *info = dev_to_port(dev);
4124         unsigned char  new_encoding;
4125         unsigned short new_crctype;
4126
4127         /* return error if TTY interface open */
4128         if (info->count)
4129                 return -EBUSY;
4130
4131         switch (encoding)
4132         {
4133         case ENCODING_NRZ:        new_encoding = HDLC_ENCODING_NRZ; break;
4134         case ENCODING_NRZI:       new_encoding = HDLC_ENCODING_NRZI_SPACE; break;
4135         case ENCODING_FM_MARK:    new_encoding = HDLC_ENCODING_BIPHASE_MARK; break;
4136         case ENCODING_FM_SPACE:   new_encoding = HDLC_ENCODING_BIPHASE_SPACE; break;
4137         case ENCODING_MANCHESTER: new_encoding = HDLC_ENCODING_BIPHASE_LEVEL; break;
4138         default: return -EINVAL;
4139         }
4140
4141         switch (parity)
4142         {
4143         case PARITY_NONE:            new_crctype = HDLC_CRC_NONE; break;
4144         case PARITY_CRC16_PR1_CCITT: new_crctype = HDLC_CRC_16_CCITT; break;
4145         case PARITY_CRC32_PR1_CCITT: new_crctype = HDLC_CRC_32_CCITT; break;
4146         default: return -EINVAL;
4147         }
4148
4149         info->params.encoding = new_encoding;
4150         info->params.crc_type = new_crctype;
4151
4152         /* if network interface up, reprogram hardware */
4153         if (info->netcount)
4154                 mgslpc_program_hw(info);
4155
4156         return 0;
4157 }
4158
4159 /**
4160  * called by generic HDLC layer to send frame
4161  *
4162  * skb  socket buffer containing HDLC frame
4163  * dev  pointer to network device structure
4164  *
4165  * returns 0 if success, otherwise error code
4166  */
4167 static int hdlcdev_xmit(struct sk_buff *skb, struct net_device *dev)
4168 {
4169         MGSLPC_INFO *info = dev_to_port(dev);
4170         struct net_device_stats *stats = hdlc_stats(dev);
4171         unsigned long flags;
4172
4173         if (debug_level >= DEBUG_LEVEL_INFO)
4174                 printk(KERN_INFO "%s:hdlc_xmit(%s)\n",__FILE__,dev->name);
4175
4176         /* stop sending until this frame completes */
4177         netif_stop_queue(dev);
4178
4179         /* copy data to device buffers */
4180         memcpy(info->tx_buf, skb->data, skb->len);
4181         info->tx_get = 0;
4182         info->tx_put = info->tx_count = skb->len;
4183
4184         /* update network statistics */
4185         stats->tx_packets++;
4186         stats->tx_bytes += skb->len;
4187
4188         /* done with socket buffer, so free it */
4189         dev_kfree_skb(skb);
4190
4191         /* save start time for transmit timeout detection */
4192         dev->trans_start = jiffies;
4193
4194         /* start hardware transmitter if necessary */
4195         spin_lock_irqsave(&info->lock,flags);
4196         if (!info->tx_active)
4197                 tx_start(info);
4198         spin_unlock_irqrestore(&info->lock,flags);
4199
4200         return 0;
4201 }
4202
4203 /**
4204  * called by network layer when interface enabled
4205  * claim resources and initialize hardware
4206  *
4207  * dev  pointer to network device structure
4208  *
4209  * returns 0 if success, otherwise error code
4210  */
4211 static int hdlcdev_open(struct net_device *dev)
4212 {
4213         MGSLPC_INFO *info = dev_to_port(dev);
4214         int rc;
4215         unsigned long flags;
4216
4217         if (debug_level >= DEBUG_LEVEL_INFO)
4218                 printk("%s:hdlcdev_open(%s)\n",__FILE__,dev->name);
4219
4220         /* generic HDLC layer open processing */
4221         if ((rc = hdlc_open(dev)))
4222                 return rc;
4223
4224         /* arbitrate between network and tty opens */
4225         spin_lock_irqsave(&info->netlock, flags);
4226         if (info->count != 0 || info->netcount != 0) {
4227                 printk(KERN_WARNING "%s: hdlc_open returning busy\n", dev->name);
4228                 spin_unlock_irqrestore(&info->netlock, flags);
4229                 return -EBUSY;
4230         }
4231         info->netcount=1;
4232         spin_unlock_irqrestore(&info->netlock, flags);
4233
4234         /* claim resources and init adapter */
4235         if ((rc = startup(info)) != 0) {
4236                 spin_lock_irqsave(&info->netlock, flags);
4237                 info->netcount=0;
4238                 spin_unlock_irqrestore(&info->netlock, flags);
4239                 return rc;
4240         }
4241
4242         /* assert DTR and RTS, apply hardware settings */
4243         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
4244         mgslpc_program_hw(info);
4245
4246         /* enable network layer transmit */
4247         dev->trans_start = jiffies;
4248         netif_start_queue(dev);
4249
4250         /* inform generic HDLC layer of current DCD status */
4251         spin_lock_irqsave(&info->lock, flags);
4252         get_signals(info);
4253         spin_unlock_irqrestore(&info->lock, flags);
4254         hdlc_set_carrier(info->serial_signals & SerialSignal_DCD, dev);
4255
4256         return 0;
4257 }
4258
4259 /**
4260  * called by network layer when interface is disabled
4261  * shutdown hardware and release resources
4262  *
4263  * dev  pointer to network device structure
4264  *
4265  * returns 0 if success, otherwise error code
4266  */
4267 static int hdlcdev_close(struct net_device *dev)
4268 {
4269         MGSLPC_INFO *info = dev_to_port(dev);
4270         unsigned long flags;
4271
4272         if (debug_level >= DEBUG_LEVEL_INFO)
4273                 printk("%s:hdlcdev_close(%s)\n",__FILE__,dev->name);
4274
4275         netif_stop_queue(dev);
4276
4277         /* shutdown adapter and release resources */
4278         shutdown(info);
4279
4280         hdlc_close(dev);
4281
4282         spin_lock_irqsave(&info->netlock, flags);
4283         info->netcount=0;
4284         spin_unlock_irqrestore(&info->netlock, flags);
4285
4286         return 0;
4287 }
4288
4289 /**
4290  * called by network layer to process IOCTL call to network device
4291  *
4292  * dev  pointer to network device structure
4293  * ifr  pointer to network interface request structure
4294  * cmd  IOCTL command code
4295  *
4296  * returns 0 if success, otherwise error code
4297  */
4298 static int hdlcdev_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
4299 {
4300         const size_t size = sizeof(sync_serial_settings);
4301         sync_serial_settings new_line;
4302         sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
4303         MGSLPC_INFO *info = dev_to_port(dev);
4304         unsigned int flags;
4305
4306         if (debug_level >= DEBUG_LEVEL_INFO)
4307                 printk("%s:hdlcdev_ioctl(%s)\n",__FILE__,dev->name);
4308
4309         /* return error if TTY interface open */
4310         if (info->count)
4311                 return -EBUSY;
4312
4313         if (cmd != SIOCWANDEV)
4314                 return hdlc_ioctl(dev, ifr, cmd);
4315
4316         switch(ifr->ifr_settings.type) {
4317         case IF_GET_IFACE: /* return current sync_serial_settings */
4318
4319                 ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL;
4320                 if (ifr->ifr_settings.size < size) {
4321                         ifr->ifr_settings.size = size; /* data size wanted */
4322                         return -ENOBUFS;
4323                 }
4324
4325                 flags = info->params.flags & (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
4326                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
4327                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
4328                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
4329
4330                 switch (flags){
4331                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN): new_line.clock_type = CLOCK_EXT; break;
4332                 case (HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_INT; break;
4333                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_TXINT; break;
4334                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN): new_line.clock_type = CLOCK_TXFROMRX; break;
4335                 default: new_line.clock_type = CLOCK_DEFAULT;
4336                 }
4337
4338                 new_line.clock_rate = info->params.clock_speed;
4339                 new_line.loopback   = info->params.loopback ? 1:0;
4340
4341                 if (copy_to_user(line, &new_line, size))
4342                         return -EFAULT;
4343                 return 0;
4344
4345         case IF_IFACE_SYNC_SERIAL: /* set sync_serial_settings */
4346
4347                 if(!capable(CAP_NET_ADMIN))
4348                         return -EPERM;
4349                 if (copy_from_user(&new_line, line, size))
4350                         return -EFAULT;
4351
4352                 switch (new_line.clock_type)
4353                 {
4354                 case CLOCK_EXT:      flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN; break;
4355                 case CLOCK_TXFROMRX: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN; break;
4356                 case CLOCK_INT:      flags = HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG;    break;
4357                 case CLOCK_TXINT:    flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG;    break;
4358                 case CLOCK_DEFAULT:  flags = info->params.flags &
4359                                              (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
4360                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
4361                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
4362                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN); break;
4363                 default: return -EINVAL;
4364                 }
4365
4366                 if (new_line.loopback != 0 && new_line.loopback != 1)
4367                         return -EINVAL;
4368
4369                 info->params.flags &= ~(HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
4370                                         HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
4371                                         HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
4372                                         HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
4373                 info->params.flags |= flags;
4374
4375                 info->params.loopback = new_line.loopback;
4376
4377                 if (flags & (HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG))
4378                         info->params.clock_speed = new_line.clock_rate;
4379                 else
4380                         info->params.clock_speed = 0;
4381
4382                 /* if network interface up, reprogram hardware */
4383                 if (info->netcount)
4384                         mgslpc_program_hw(info);
4385                 return 0;
4386
4387         default:
4388                 return hdlc_ioctl(dev, ifr, cmd);
4389         }
4390 }
4391
4392 /**
4393  * called by network layer when transmit timeout is detected
4394  *
4395  * dev  pointer to network device structure
4396  */
4397 static void hdlcdev_tx_timeout(struct net_device *dev)
4398 {
4399         MGSLPC_INFO *info = dev_to_port(dev);
4400         struct net_device_stats *stats = hdlc_stats(dev);
4401         unsigned long flags;
4402
4403         if (debug_level >= DEBUG_LEVEL_INFO)
4404                 printk("hdlcdev_tx_timeout(%s)\n",dev->name);
4405
4406         stats->tx_errors++;
4407         stats->tx_aborted_errors++;
4408
4409         spin_lock_irqsave(&info->lock,flags);
4410         tx_stop(info);
4411         spin_unlock_irqrestore(&info->lock,flags);
4412
4413         netif_wake_queue(dev);
4414 }
4415
4416 /**
4417  * called by device driver when transmit completes
4418  * reenable network layer transmit if stopped
4419  *
4420  * info  pointer to device instance information
4421  */
4422 static void hdlcdev_tx_done(MGSLPC_INFO *info)
4423 {
4424         if (netif_queue_stopped(info->netdev))
4425                 netif_wake_queue(info->netdev);
4426 }
4427
4428 /**
4429  * called by device driver when frame received
4430  * pass frame to network layer
4431  *
4432  * info  pointer to device instance information
4433  * buf   pointer to buffer contianing frame data
4434  * size  count of data bytes in buf
4435  */
4436 static void hdlcdev_rx(MGSLPC_INFO *info, char *buf, int size)
4437 {
4438         struct sk_buff *skb = dev_alloc_skb(size);
4439         struct net_device *dev = info->netdev;
4440         struct net_device_stats *stats = hdlc_stats(dev);
4441
4442         if (debug_level >= DEBUG_LEVEL_INFO)
4443                 printk("hdlcdev_rx(%s)\n",dev->name);
4444
4445         if (skb == NULL) {
4446                 printk(KERN_NOTICE "%s: can't alloc skb, dropping packet\n", dev->name);
4447                 stats->rx_dropped++;
4448                 return;
4449         }
4450
4451         memcpy(skb_put(skb, size),buf,size);
4452
4453         skb->protocol = hdlc_type_trans(skb, info->netdev);
4454
4455         stats->rx_packets++;
4456         stats->rx_bytes += size;
4457
4458         netif_rx(skb);
4459
4460         info->netdev->last_rx = jiffies;
4461 }
4462
4463 /**
4464  * called by device driver when adding device instance
4465  * do generic HDLC initialization
4466  *
4467  * info  pointer to device instance information
4468  *
4469  * returns 0 if success, otherwise error code
4470  */
4471 static int hdlcdev_init(MGSLPC_INFO *info)
4472 {
4473         int rc;
4474         struct net_device *dev;
4475         hdlc_device *hdlc;
4476
4477         /* allocate and initialize network and HDLC layer objects */
4478
4479         if (!(dev = alloc_hdlcdev(info))) {
4480                 printk(KERN_ERR "%s:hdlc device allocation failure\n",__FILE__);
4481                 return -ENOMEM;
4482         }
4483
4484         /* for network layer reporting purposes only */
4485         dev->base_addr = info->io_base;
4486         dev->irq       = info->irq_level;
4487
4488         /* network layer callbacks and settings */
4489         dev->do_ioctl       = hdlcdev_ioctl;
4490         dev->open           = hdlcdev_open;
4491         dev->stop           = hdlcdev_close;
4492         dev->tx_timeout     = hdlcdev_tx_timeout;
4493         dev->watchdog_timeo = 10*HZ;
4494         dev->tx_queue_len   = 50;
4495
4496         /* generic HDLC layer callbacks and settings */
4497         hdlc         = dev_to_hdlc(dev);
4498         hdlc->attach = hdlcdev_attach;
4499         hdlc->xmit   = hdlcdev_xmit;
4500
4501         /* register objects with HDLC layer */
4502         if ((rc = register_hdlc_device(dev))) {
4503                 printk(KERN_WARNING "%s:unable to register hdlc device\n",__FILE__);
4504                 free_netdev(dev);
4505                 return rc;
4506         }
4507
4508         info->netdev = dev;
4509         return 0;
4510 }
4511
4512 /**
4513  * called by device driver when removing device instance
4514  * do generic HDLC cleanup
4515  *
4516  * info  pointer to device instance information
4517  */
4518 static void hdlcdev_exit(MGSLPC_INFO *info)
4519 {
4520         unregister_hdlc_device(info->netdev);
4521         free_netdev(info->netdev);
4522         info->netdev = NULL;
4523 }
4524
4525 #endif /* CONFIG_HDLC */
4526