Merge branch 'devel' of master.kernel.org:/home/rmk/linux-2.6-serial
[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 <linux/delay.h>
61 #include <linux/ioctl.h>
62
63 #include <asm/system.h>
64 #include <asm/io.h>
65 #include <asm/irq.h>
66 #include <asm/dma.h>
67 #include <linux/bitops.h>
68 #include <asm/types.h>
69 #include <linux/termios.h>
70 #include <linux/workqueue.h>
71 #include <linux/hdlc.h>
72
73 #include <pcmcia/cs_types.h>
74 #include <pcmcia/cs.h>
75 #include <pcmcia/cistpl.h>
76 #include <pcmcia/cisreg.h>
77 #include <pcmcia/ds.h>
78
79 #ifdef CONFIG_HDLC_MODULE
80 #define CONFIG_HDLC 1
81 #endif
82
83 #define GET_USER(error,value,addr) error = get_user(value,addr)
84 #define COPY_FROM_USER(error,dest,src,size) error = copy_from_user(dest,src,size) ? -EFAULT : 0
85 #define PUT_USER(error,value,addr) error = put_user(value,addr)
86 #define COPY_TO_USER(error,dest,src,size) error = copy_to_user(dest,src,size) ? -EFAULT : 0
87
88 #include <asm/uaccess.h>
89
90 #include "linux/synclink.h"
91
92 static MGSL_PARAMS default_params = {
93         MGSL_MODE_HDLC,                 /* unsigned long mode */
94         0,                              /* unsigned char loopback; */
95         HDLC_FLAG_UNDERRUN_ABORT15,     /* unsigned short flags; */
96         HDLC_ENCODING_NRZI_SPACE,       /* unsigned char encoding; */
97         0,                              /* unsigned long clock_speed; */
98         0xff,                           /* unsigned char addr_filter; */
99         HDLC_CRC_16_CCITT,              /* unsigned short crc_type; */
100         HDLC_PREAMBLE_LENGTH_8BITS,     /* unsigned char preamble_length; */
101         HDLC_PREAMBLE_PATTERN_NONE,     /* unsigned char preamble; */
102         9600,                           /* unsigned long data_rate; */
103         8,                              /* unsigned char data_bits; */
104         1,                              /* unsigned char stop_bits; */
105         ASYNC_PARITY_NONE               /* unsigned char parity; */
106 };
107
108 typedef struct
109 {
110         int count;
111         unsigned char status;
112         char data[1];
113 } RXBUF;
114
115 /* The queue of BH actions to be performed */
116
117 #define BH_RECEIVE  1
118 #define BH_TRANSMIT 2
119 #define BH_STATUS   4
120
121 #define IO_PIN_SHUTDOWN_LIMIT 100
122
123 #define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
124
125 struct _input_signal_events {
126         int     ri_up;  
127         int     ri_down;
128         int     dsr_up;
129         int     dsr_down;
130         int     dcd_up;
131         int     dcd_down;
132         int     cts_up;
133         int     cts_down;
134 };
135
136
137 /*
138  * Device instance data structure
139  */
140  
141 typedef struct _mgslpc_info {
142         void *if_ptr;   /* General purpose pointer (used by SPPP) */
143         int                     magic;
144         int                     flags;
145         int                     count;          /* count of opens */
146         int                     line;
147         unsigned short          close_delay;
148         unsigned short          closing_wait;   /* time to wait before closing */
149         
150         struct mgsl_icount      icount;
151         
152         struct tty_struct       *tty;
153         int                     timeout;
154         int                     x_char;         /* xon/xoff character */
155         int                     blocked_open;   /* # of blocked opens */
156         unsigned char           read_status_mask;
157         unsigned char           ignore_status_mask;     
158
159         unsigned char *tx_buf;
160         int            tx_put;
161         int            tx_get;
162         int            tx_count;
163
164         /* circular list of fixed length rx buffers */
165
166         unsigned char  *rx_buf;        /* memory allocated for all rx buffers */
167         int            rx_buf_total_size; /* size of memory allocated for rx buffers */
168         int            rx_put;         /* index of next empty rx buffer */
169         int            rx_get;         /* index of next full rx buffer */
170         int            rx_buf_size;    /* size in bytes of single rx buffer */
171         int            rx_buf_count;   /* total number of rx buffers */
172         int            rx_frame_count; /* number of full rx buffers */
173         
174         wait_queue_head_t       open_wait;
175         wait_queue_head_t       close_wait;
176         
177         wait_queue_head_t       status_event_wait_q;
178         wait_queue_head_t       event_wait_q;
179         struct timer_list       tx_timer;       /* HDLC transmit timeout timer */
180         struct _mgslpc_info     *next_device;   /* device list link */
181
182         unsigned short imra_value;
183         unsigned short imrb_value;
184         unsigned char  pim_value;
185
186         spinlock_t lock;
187         struct work_struct task;                /* task structure for scheduling bh */
188
189         u32 max_frame_size;
190
191         u32 pending_bh;
192
193         int bh_running;
194         int bh_requested;
195         
196         int dcd_chkcount; /* check counts to prevent */
197         int cts_chkcount; /* too many IRQs if a signal */
198         int dsr_chkcount; /* is floating */
199         int ri_chkcount;
200
201         int rx_enabled;
202         int rx_overflow;
203
204         int tx_enabled;
205         int tx_active;
206         int tx_aborting;
207         u32 idle_mode;
208
209         int if_mode; /* serial interface selection (RS-232, v.35 etc) */
210
211         char device_name[25];           /* device instance name */
212
213         unsigned int io_base;   /* base I/O address of adapter */
214         unsigned int irq_level;
215         
216         MGSL_PARAMS params;             /* communications parameters */
217
218         unsigned char serial_signals;   /* current serial signal states */
219
220         char irq_occurred;              /* for diagnostics use */
221         char testing_irq;
222         unsigned int init_error;        /* startup error (DIAGS)        */
223
224         char flag_buf[MAX_ASYNC_BUFFER_SIZE];
225         BOOLEAN drop_rts_on_tx_done;
226
227         struct  _input_signal_events    input_signal_events;
228
229         /* PCMCIA support */
230         struct pcmcia_device    *p_dev;
231         dev_node_t            node;
232         int                   stop;
233
234         /* SPPP/Cisco HDLC device parts */
235         int netcount;
236         int dosyncppp;
237         spinlock_t netlock;
238
239 #ifdef CONFIG_HDLC
240         struct net_device *netdev;
241 #endif
242
243 } MGSLPC_INFO;
244
245 #define MGSLPC_MAGIC 0x5402
246
247 /*
248  * The size of the serial xmit buffer is 1 page, or 4096 bytes
249  */
250 #define TXBUFSIZE 4096
251
252     
253 #define CHA     0x00   /* channel A offset */
254 #define CHB     0x40   /* channel B offset */
255
256 /*
257  *  FIXME: PPC has PVR defined in asm/reg.h.  For now we just undef it.
258  */
259 #undef PVR
260
261 #define RXFIFO  0
262 #define TXFIFO  0
263 #define STAR    0x20
264 #define CMDR    0x20
265 #define RSTA    0x21
266 #define PRE     0x21
267 #define MODE    0x22
268 #define TIMR    0x23
269 #define XAD1    0x24
270 #define XAD2    0x25
271 #define RAH1    0x26
272 #define RAH2    0x27
273 #define DAFO    0x27
274 #define RAL1    0x28
275 #define RFC     0x28
276 #define RHCR    0x29
277 #define RAL2    0x29
278 #define RBCL    0x2a
279 #define XBCL    0x2a
280 #define RBCH    0x2b
281 #define XBCH    0x2b
282 #define CCR0    0x2c
283 #define CCR1    0x2d
284 #define CCR2    0x2e
285 #define CCR3    0x2f
286 #define VSTR    0x34
287 #define BGR     0x34
288 #define RLCR    0x35
289 #define AML     0x36
290 #define AMH     0x37
291 #define GIS     0x38
292 #define IVA     0x38
293 #define IPC     0x39
294 #define ISR     0x3a
295 #define IMR     0x3a
296 #define PVR     0x3c
297 #define PIS     0x3d
298 #define PIM     0x3d
299 #define PCR     0x3e
300 #define CCR4    0x3f
301     
302 // IMR/ISR
303     
304 #define IRQ_BREAK_ON    BIT15   // rx break detected
305 #define IRQ_DATAOVERRUN BIT14   // receive data overflow
306 #define IRQ_ALLSENT     BIT13   // all sent
307 #define IRQ_UNDERRUN    BIT12   // transmit data underrun
308 #define IRQ_TIMER       BIT11   // timer interrupt
309 #define IRQ_CTS         BIT10   // CTS status change
310 #define IRQ_TXREPEAT    BIT9    // tx message repeat
311 #define IRQ_TXFIFO      BIT8    // transmit pool ready
312 #define IRQ_RXEOM       BIT7    // receive message end
313 #define IRQ_EXITHUNT    BIT6    // receive frame start
314 #define IRQ_RXTIME      BIT6    // rx char timeout
315 #define IRQ_DCD         BIT2    // carrier detect status change
316 #define IRQ_OVERRUN     BIT1    // receive frame overflow
317 #define IRQ_RXFIFO      BIT0    // receive pool full
318     
319 // STAR
320     
321 #define XFW   BIT6              // transmit FIFO write enable
322 #define CEC   BIT2              // command executing
323 #define CTS   BIT1              // CTS state
324     
325 #define PVR_DTR      BIT0
326 #define PVR_DSR      BIT1
327 #define PVR_RI       BIT2
328 #define PVR_AUTOCTS  BIT3
329 #define PVR_RS232    0x20   /* 0010b */
330 #define PVR_V35      0xe0   /* 1110b */
331 #define PVR_RS422    0x40   /* 0100b */
332     
333 /* Register access functions */ 
334     
335 #define write_reg(info, reg, val) outb((val),(info)->io_base + (reg))
336 #define read_reg(info, reg) inb((info)->io_base + (reg))
337
338 #define read_reg16(info, reg) inw((info)->io_base + (reg))  
339 #define write_reg16(info, reg, val) outw((val), (info)->io_base + (reg))
340     
341 #define set_reg_bits(info, reg, mask) \
342     write_reg(info, (reg), \
343                  (unsigned char) (read_reg(info, (reg)) | (mask)))  
344 #define clear_reg_bits(info, reg, mask) \
345     write_reg(info, (reg), \
346                  (unsigned char) (read_reg(info, (reg)) & ~(mask)))  
347 /*
348  * interrupt enable/disable routines
349  */ 
350 static void irq_disable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) 
351 {
352         if (channel == CHA) {
353                 info->imra_value |= mask;
354                 write_reg16(info, CHA + IMR, info->imra_value);
355         } else {
356                 info->imrb_value |= mask;
357                 write_reg16(info, CHB + IMR, info->imrb_value);
358         }
359 }
360 static void irq_enable(MGSLPC_INFO *info, unsigned char channel, unsigned short mask) 
361 {
362         if (channel == CHA) {
363                 info->imra_value &= ~mask;
364                 write_reg16(info, CHA + IMR, info->imra_value);
365         } else {
366                 info->imrb_value &= ~mask;
367                 write_reg16(info, CHB + IMR, info->imrb_value);
368         }
369 }
370
371 #define port_irq_disable(info, mask) \
372   { info->pim_value |= (mask); write_reg(info, PIM, info->pim_value); }
373
374 #define port_irq_enable(info, mask) \
375   { info->pim_value &= ~(mask); write_reg(info, PIM, info->pim_value); }
376
377 static void rx_start(MGSLPC_INFO *info);
378 static void rx_stop(MGSLPC_INFO *info);
379
380 static void tx_start(MGSLPC_INFO *info);
381 static void tx_stop(MGSLPC_INFO *info);
382 static void tx_set_idle(MGSLPC_INFO *info);
383
384 static void get_signals(MGSLPC_INFO *info);
385 static void set_signals(MGSLPC_INFO *info);
386
387 static void reset_device(MGSLPC_INFO *info);
388
389 static void hdlc_mode(MGSLPC_INFO *info);
390 static void async_mode(MGSLPC_INFO *info);
391
392 static void tx_timeout(unsigned long context);
393
394 static int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg);
395
396 #ifdef CONFIG_HDLC
397 #define dev_to_port(D) (dev_to_hdlc(D)->priv)
398 static void hdlcdev_tx_done(MGSLPC_INFO *info);
399 static void hdlcdev_rx(MGSLPC_INFO *info, char *buf, int size);
400 static int  hdlcdev_init(MGSLPC_INFO *info);
401 static void hdlcdev_exit(MGSLPC_INFO *info);
402 #endif
403
404 static void trace_block(MGSLPC_INFO *info,const char* data, int count, int xmit);
405
406 static BOOLEAN register_test(MGSLPC_INFO *info);
407 static BOOLEAN irq_test(MGSLPC_INFO *info);
408 static int adapter_test(MGSLPC_INFO *info);
409
410 static int claim_resources(MGSLPC_INFO *info);
411 static void release_resources(MGSLPC_INFO *info);
412 static void mgslpc_add_device(MGSLPC_INFO *info);
413 static void mgslpc_remove_device(MGSLPC_INFO *info);
414
415 static int  rx_get_frame(MGSLPC_INFO *info);
416 static void rx_reset_buffers(MGSLPC_INFO *info);
417 static int  rx_alloc_buffers(MGSLPC_INFO *info);
418 static void rx_free_buffers(MGSLPC_INFO *info);
419
420 static irqreturn_t mgslpc_isr(int irq, void *dev_id, struct pt_regs * regs);
421
422 /*
423  * Bottom half interrupt handlers
424  */
425 static void bh_handler(void* Context);
426 static void bh_transmit(MGSLPC_INFO *info);
427 static void bh_status(MGSLPC_INFO *info);
428
429 /*
430  * ioctl handlers
431  */
432 static int tiocmget(struct tty_struct *tty, struct file *file);
433 static int tiocmset(struct tty_struct *tty, struct file *file,
434                     unsigned int set, unsigned int clear);
435 static int get_stats(MGSLPC_INFO *info, struct mgsl_icount __user *user_icount);
436 static int get_params(MGSLPC_INFO *info, MGSL_PARAMS __user *user_params);
437 static int set_params(MGSLPC_INFO *info, MGSL_PARAMS __user *new_params);
438 static int get_txidle(MGSLPC_INFO *info, int __user *idle_mode);
439 static int set_txidle(MGSLPC_INFO *info, int idle_mode);
440 static int set_txenable(MGSLPC_INFO *info, int enable);
441 static int tx_abort(MGSLPC_INFO *info);
442 static int set_rxenable(MGSLPC_INFO *info, int enable);
443 static int wait_events(MGSLPC_INFO *info, int __user *mask);
444
445 static MGSLPC_INFO *mgslpc_device_list = NULL;
446 static int mgslpc_device_count = 0;
447
448 /*
449  * Set this param to non-zero to load eax with the
450  * .text section address and breakpoint on module load.
451  * This is useful for use with gdb and add-symbol-file command.
452  */
453 static int break_on_load=0;
454
455 /*
456  * Driver major number, defaults to zero to get auto
457  * assigned major number. May be forced as module parameter.
458  */
459 static int ttymajor=0;
460
461 static int debug_level = 0;
462 static int maxframe[MAX_DEVICE_COUNT] = {0,};
463 static int dosyncppp[MAX_DEVICE_COUNT] = {1,1,1,1};
464
465 module_param(break_on_load, bool, 0);
466 module_param(ttymajor, int, 0);
467 module_param(debug_level, int, 0);
468 module_param_array(maxframe, int, NULL, 0);
469 module_param_array(dosyncppp, int, NULL, 0);
470
471 MODULE_LICENSE("GPL");
472
473 static char *driver_name = "SyncLink PC Card driver";
474 static char *driver_version = "$Revision: 4.34 $";
475
476 static struct tty_driver *serial_driver;
477
478 /* number of characters left in xmit buffer before we ask for more */
479 #define WAKEUP_CHARS 256
480
481 static void mgslpc_change_params(MGSLPC_INFO *info);
482 static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout);
483
484 /* PCMCIA prototypes */
485
486 static int mgslpc_config(struct pcmcia_device *link);
487 static void mgslpc_release(u_long arg);
488 static void mgslpc_detach(struct pcmcia_device *p_dev);
489
490 /*
491  * 1st function defined in .text section. Calling this function in
492  * init_module() followed by a breakpoint allows a remote debugger
493  * (gdb) to get the .text address for the add-symbol-file command.
494  * This allows remote debugging of dynamically loadable modules.
495  */
496 static void* mgslpc_get_text_ptr(void)
497 {
498         return mgslpc_get_text_ptr;
499 }
500
501 /**
502  * line discipline callback wrappers
503  *
504  * The wrappers maintain line discipline references
505  * while calling into the line discipline.
506  *
507  * ldisc_flush_buffer - flush line discipline receive buffers
508  * ldisc_receive_buf  - pass receive data to line discipline
509  */
510
511 static void ldisc_flush_buffer(struct tty_struct *tty)
512 {
513         struct tty_ldisc *ld = tty_ldisc_ref(tty);
514         if (ld) {
515                 if (ld->flush_buffer)
516                         ld->flush_buffer(tty);
517                 tty_ldisc_deref(ld);
518         }
519 }
520
521 static void ldisc_receive_buf(struct tty_struct *tty,
522                               const __u8 *data, char *flags, int count)
523 {
524         struct tty_ldisc *ld;
525         if (!tty)
526                 return;
527         ld = tty_ldisc_ref(tty);
528         if (ld) {
529                 if (ld->receive_buf)
530                         ld->receive_buf(tty, data, flags, count);
531                 tty_ldisc_deref(ld);
532         }
533 }
534
535 static int mgslpc_probe(struct pcmcia_device *link)
536 {
537     MGSLPC_INFO *info;
538     int ret;
539
540     if (debug_level >= DEBUG_LEVEL_INFO)
541             printk("mgslpc_attach\n");
542
543     info = (MGSLPC_INFO *)kmalloc(sizeof(MGSLPC_INFO), GFP_KERNEL);
544     if (!info) {
545             printk("Error can't allocate device instance data\n");
546             return -ENOMEM;
547     }
548
549     memset(info, 0, sizeof(MGSLPC_INFO));
550     info->magic = MGSLPC_MAGIC;
551     INIT_WORK(&info->task, bh_handler, info);
552     info->max_frame_size = 4096;
553     info->close_delay = 5*HZ/10;
554     info->closing_wait = 30*HZ;
555     init_waitqueue_head(&info->open_wait);
556     init_waitqueue_head(&info->close_wait);
557     init_waitqueue_head(&info->status_event_wait_q);
558     init_waitqueue_head(&info->event_wait_q);
559     spin_lock_init(&info->lock);
560     spin_lock_init(&info->netlock);
561     memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
562     info->idle_mode = HDLC_TXIDLE_FLAGS;                
563     info->imra_value = 0xffff;
564     info->imrb_value = 0xffff;
565     info->pim_value = 0xff;
566
567     info->p_dev = link;
568     link->priv = info;
569
570     /* Initialize the struct pcmcia_device structure */
571
572     /* Interrupt setup */
573     link->irq.Attributes = IRQ_TYPE_EXCLUSIVE;
574     link->irq.IRQInfo1   = IRQ_LEVEL_ID;
575     link->irq.Handler = NULL;
576
577     link->conf.Attributes = 0;
578     link->conf.IntType = INT_MEMORY_AND_IO;
579
580     ret = mgslpc_config(link);
581     if (ret)
582             return ret;
583
584     mgslpc_add_device(info);
585
586     return 0;
587 }
588
589 /* Card has been inserted.
590  */
591
592 #define CS_CHECK(fn, ret) \
593 do { last_fn = (fn); if ((last_ret = (ret)) != 0) goto cs_failed; } while (0)
594
595 static int mgslpc_config(struct pcmcia_device *link)
596 {
597     MGSLPC_INFO *info = link->priv;
598     tuple_t tuple;
599     cisparse_t parse;
600     int last_fn, last_ret;
601     u_char buf[64];
602     cistpl_cftable_entry_t dflt = { 0 };
603     cistpl_cftable_entry_t *cfg;
604     
605     if (debug_level >= DEBUG_LEVEL_INFO)
606             printk("mgslpc_config(0x%p)\n", link);
607
608     /* read CONFIG tuple to find its configuration registers */
609     tuple.DesiredTuple = CISTPL_CONFIG;
610     tuple.Attributes = 0;
611     tuple.TupleData = buf;
612     tuple.TupleDataMax = sizeof(buf);
613     tuple.TupleOffset = 0;
614     CS_CHECK(GetFirstTuple, pcmcia_get_first_tuple(link, &tuple));
615     CS_CHECK(GetTupleData, pcmcia_get_tuple_data(link, &tuple));
616     CS_CHECK(ParseTuple, pcmcia_parse_tuple(link, &tuple, &parse));
617     link->conf.ConfigBase = parse.config.base;
618     link->conf.Present = parse.config.rmask[0];
619
620     /* get CIS configuration entry */
621
622     tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
623     CS_CHECK(GetFirstTuple, pcmcia_get_first_tuple(link, &tuple));
624
625     cfg = &(parse.cftable_entry);
626     CS_CHECK(GetTupleData, pcmcia_get_tuple_data(link, &tuple));
627     CS_CHECK(ParseTuple, pcmcia_parse_tuple(link, &tuple, &parse));
628
629     if (cfg->flags & CISTPL_CFTABLE_DEFAULT) dflt = *cfg;
630     if (cfg->index == 0)
631             goto cs_failed;
632
633     link->conf.ConfigIndex = cfg->index;
634     link->conf.Attributes |= CONF_ENABLE_IRQ;
635         
636     /* IO window settings */
637     link->io.NumPorts1 = 0;
638     if ((cfg->io.nwin > 0) || (dflt.io.nwin > 0)) {
639             cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt.io;
640             link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO;
641             if (!(io->flags & CISTPL_IO_8BIT))
642                     link->io.Attributes1 = IO_DATA_PATH_WIDTH_16;
643             if (!(io->flags & CISTPL_IO_16BIT))
644                     link->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
645             link->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK;
646             link->io.BasePort1 = io->win[0].base;
647             link->io.NumPorts1 = io->win[0].len;
648             CS_CHECK(RequestIO, pcmcia_request_io(link, &link->io));
649     }
650
651     link->conf.Attributes = CONF_ENABLE_IRQ;
652     link->conf.IntType = INT_MEMORY_AND_IO;
653     link->conf.ConfigIndex = 8;
654     link->conf.Present = PRESENT_OPTION;
655     
656     link->irq.Attributes |= IRQ_HANDLE_PRESENT;
657     link->irq.Handler     = mgslpc_isr;
658     link->irq.Instance    = info;
659     CS_CHECK(RequestIRQ, pcmcia_request_irq(link, &link->irq));
660
661     CS_CHECK(RequestConfiguration, pcmcia_request_configuration(link, &link->conf));
662
663     info->io_base = link->io.BasePort1;
664     info->irq_level = link->irq.AssignedIRQ;
665
666     /* add to linked list of devices */
667     sprintf(info->node.dev_name, "mgslpc0");
668     info->node.major = info->node.minor = 0;
669     link->dev_node = &info->node;
670
671     printk(KERN_INFO "%s: index 0x%02x:",
672            info->node.dev_name, link->conf.ConfigIndex);
673     if (link->conf.Attributes & CONF_ENABLE_IRQ)
674             printk(", irq %d", link->irq.AssignedIRQ);
675     if (link->io.NumPorts1)
676             printk(", io 0x%04x-0x%04x", link->io.BasePort1,
677                    link->io.BasePort1+link->io.NumPorts1-1);
678     printk("\n");
679     return 0;
680
681 cs_failed:
682     cs_error(link, last_fn, last_ret);
683     mgslpc_release((u_long)link);
684     return -ENODEV;
685 }
686
687 /* Card has been removed.
688  * Unregister device and release PCMCIA configuration.
689  * If device is open, postpone until it is closed.
690  */
691 static void mgslpc_release(u_long arg)
692 {
693         struct pcmcia_device *link = (struct pcmcia_device *)arg;
694
695         if (debug_level >= DEBUG_LEVEL_INFO)
696                 printk("mgslpc_release(0x%p)\n", link);
697
698         pcmcia_disable_device(link);
699 }
700
701 static void mgslpc_detach(struct pcmcia_device *link)
702 {
703         if (debug_level >= DEBUG_LEVEL_INFO)
704                 printk("mgslpc_detach(0x%p)\n", link);
705
706         ((MGSLPC_INFO *)link->priv)->stop = 1;
707         mgslpc_release((u_long)link);
708
709         mgslpc_remove_device((MGSLPC_INFO *)link->priv);
710 }
711
712 static int mgslpc_suspend(struct pcmcia_device *link)
713 {
714         MGSLPC_INFO *info = link->priv;
715
716         info->stop = 1;
717
718         return 0;
719 }
720
721 static int mgslpc_resume(struct pcmcia_device *link)
722 {
723         MGSLPC_INFO *info = link->priv;
724
725         info->stop = 0;
726
727         return 0;
728 }
729
730
731 static inline int mgslpc_paranoia_check(MGSLPC_INFO *info,
732                                         char *name, const char *routine)
733 {
734 #ifdef MGSLPC_PARANOIA_CHECK
735         static const char *badmagic =
736                 "Warning: bad magic number for mgsl struct (%s) in %s\n";
737         static const char *badinfo =
738                 "Warning: null mgslpc_info for (%s) in %s\n";
739
740         if (!info) {
741                 printk(badinfo, name, routine);
742                 return 1;
743         }
744         if (info->magic != MGSLPC_MAGIC) {
745                 printk(badmagic, name, routine);
746                 return 1;
747         }
748 #else
749         if (!info)
750                 return 1;
751 #endif
752         return 0;
753 }
754
755
756 #define CMD_RXFIFO      BIT7    // release current rx FIFO
757 #define CMD_RXRESET     BIT6    // receiver reset
758 #define CMD_RXFIFO_READ BIT5
759 #define CMD_START_TIMER BIT4
760 #define CMD_TXFIFO      BIT3    // release current tx FIFO
761 #define CMD_TXEOM       BIT1    // transmit end message
762 #define CMD_TXRESET     BIT0    // transmit reset
763
764 static BOOLEAN wait_command_complete(MGSLPC_INFO *info, unsigned char channel) 
765 {
766         int i = 0;
767         /* wait for command completion */ 
768         while (read_reg(info, (unsigned char)(channel+STAR)) & BIT2) {
769                 udelay(1);
770                 if (i++ == 1000)
771                         return FALSE;
772         }
773         return TRUE;
774 }
775
776 static void issue_command(MGSLPC_INFO *info, unsigned char channel, unsigned char cmd) 
777 {
778         wait_command_complete(info, channel);
779         write_reg(info, (unsigned char) (channel + CMDR), cmd);
780 }
781
782 static void tx_pause(struct tty_struct *tty)
783 {
784         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
785         unsigned long flags;
786         
787         if (mgslpc_paranoia_check(info, tty->name, "tx_pause"))
788                 return;
789         if (debug_level >= DEBUG_LEVEL_INFO)
790                 printk("tx_pause(%s)\n",info->device_name);     
791                 
792         spin_lock_irqsave(&info->lock,flags);
793         if (info->tx_enabled)
794                 tx_stop(info);
795         spin_unlock_irqrestore(&info->lock,flags);
796 }
797
798 static void tx_release(struct tty_struct *tty)
799 {
800         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
801         unsigned long flags;
802         
803         if (mgslpc_paranoia_check(info, tty->name, "tx_release"))
804                 return;
805         if (debug_level >= DEBUG_LEVEL_INFO)
806                 printk("tx_release(%s)\n",info->device_name);   
807                 
808         spin_lock_irqsave(&info->lock,flags);
809         if (!info->tx_enabled)
810                 tx_start(info);
811         spin_unlock_irqrestore(&info->lock,flags);
812 }
813
814 /* Return next bottom half action to perform.
815  * or 0 if nothing to do.
816  */
817 static int bh_action(MGSLPC_INFO *info)
818 {
819         unsigned long flags;
820         int rc = 0;
821         
822         spin_lock_irqsave(&info->lock,flags);
823
824         if (info->pending_bh & BH_RECEIVE) {
825                 info->pending_bh &= ~BH_RECEIVE;
826                 rc = BH_RECEIVE;
827         } else if (info->pending_bh & BH_TRANSMIT) {
828                 info->pending_bh &= ~BH_TRANSMIT;
829                 rc = BH_TRANSMIT;
830         } else if (info->pending_bh & BH_STATUS) {
831                 info->pending_bh &= ~BH_STATUS;
832                 rc = BH_STATUS;
833         }
834
835         if (!rc) {
836                 /* Mark BH routine as complete */
837                 info->bh_running   = 0;
838                 info->bh_requested = 0;
839         }
840         
841         spin_unlock_irqrestore(&info->lock,flags);
842         
843         return rc;
844 }
845
846 static void bh_handler(void* Context)
847 {
848         MGSLPC_INFO *info = (MGSLPC_INFO*)Context;
849         int action;
850
851         if (!info)
852                 return;
853                 
854         if (debug_level >= DEBUG_LEVEL_BH)
855                 printk( "%s(%d):bh_handler(%s) entry\n",
856                         __FILE__,__LINE__,info->device_name);
857         
858         info->bh_running = 1;
859
860         while((action = bh_action(info)) != 0) {
861         
862                 /* Process work item */
863                 if ( debug_level >= DEBUG_LEVEL_BH )
864                         printk( "%s(%d):bh_handler() work item action=%d\n",
865                                 __FILE__,__LINE__,action);
866
867                 switch (action) {
868                 
869                 case BH_RECEIVE:
870                         while(rx_get_frame(info));
871                         break;
872                 case BH_TRANSMIT:
873                         bh_transmit(info);
874                         break;
875                 case BH_STATUS:
876                         bh_status(info);
877                         break;
878                 default:
879                         /* unknown work item ID */
880                         printk("Unknown work item ID=%08X!\n", action);
881                         break;
882                 }
883         }
884
885         if (debug_level >= DEBUG_LEVEL_BH)
886                 printk( "%s(%d):bh_handler(%s) exit\n",
887                         __FILE__,__LINE__,info->device_name);
888 }
889
890 static void bh_transmit(MGSLPC_INFO *info)
891 {
892         struct tty_struct *tty = info->tty;
893         if (debug_level >= DEBUG_LEVEL_BH)
894                 printk("bh_transmit() entry on %s\n", info->device_name);
895
896         if (tty) {
897                 tty_wakeup(tty);
898                 wake_up_interruptible(&tty->write_wait);
899         }
900 }
901
902 static void bh_status(MGSLPC_INFO *info)
903 {
904         info->ri_chkcount = 0;
905         info->dsr_chkcount = 0;
906         info->dcd_chkcount = 0;
907         info->cts_chkcount = 0;
908 }
909
910 /* eom: non-zero = end of frame */ 
911 static void rx_ready_hdlc(MGSLPC_INFO *info, int eom)
912 {
913         unsigned char data[2];
914         unsigned char fifo_count, read_count, i;
915         RXBUF *buf = (RXBUF*)(info->rx_buf + (info->rx_put * info->rx_buf_size));
916
917         if (debug_level >= DEBUG_LEVEL_ISR)
918                 printk("%s(%d):rx_ready_hdlc(eom=%d)\n",__FILE__,__LINE__,eom);
919         
920         if (!info->rx_enabled)
921                 return;
922
923         if (info->rx_frame_count >= info->rx_buf_count) {
924                 /* no more free buffers */
925                 issue_command(info, CHA, CMD_RXRESET);
926                 info->pending_bh |= BH_RECEIVE;
927                 info->rx_overflow = 1;
928                 info->icount.buf_overrun++;
929                 return;
930         }
931
932         if (eom) {
933                 /* end of frame, get FIFO count from RBCL register */ 
934                 if (!(fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f)))
935                         fifo_count = 32;
936         } else
937                 fifo_count = 32;
938         
939         do {
940                 if (fifo_count == 1) {
941                         read_count = 1;
942                         data[0] = read_reg(info, CHA + RXFIFO);
943                 } else {
944                         read_count = 2;
945                         *((unsigned short *) data) = read_reg16(info, CHA + RXFIFO);
946                 }
947                 fifo_count -= read_count;
948                 if (!fifo_count && eom)
949                         buf->status = data[--read_count];
950
951                 for (i = 0; i < read_count; i++) {
952                         if (buf->count >= info->max_frame_size) {
953                                 /* frame too large, reset receiver and reset current buffer */
954                                 issue_command(info, CHA, CMD_RXRESET);
955                                 buf->count = 0;
956                                 return;
957                         }
958                         *(buf->data + buf->count) = data[i];
959                         buf->count++;
960                 }
961         } while (fifo_count);
962
963         if (eom) {
964                 info->pending_bh |= BH_RECEIVE;
965                 info->rx_frame_count++;
966                 info->rx_put++;
967                 if (info->rx_put >= info->rx_buf_count)
968                         info->rx_put = 0;
969         }
970         issue_command(info, CHA, CMD_RXFIFO);
971 }
972
973 static void rx_ready_async(MGSLPC_INFO *info, int tcd)
974 {
975         unsigned char data, status, flag;
976         int fifo_count;
977         int work = 0;
978         struct tty_struct *tty = info->tty;
979         struct mgsl_icount *icount = &info->icount;
980
981         if (tcd) {
982                 /* early termination, get FIFO count from RBCL register */ 
983                 fifo_count = (unsigned char)(read_reg(info, CHA+RBCL) & 0x1f);
984
985                 /* Zero fifo count could mean 0 or 32 bytes available.
986                  * If BIT5 of STAR is set then at least 1 byte is available.
987                  */
988                 if (!fifo_count && (read_reg(info,CHA+STAR) & BIT5))
989                         fifo_count = 32;
990         } else
991                 fifo_count = 32;
992
993         tty_buffer_request_room(tty, fifo_count);
994         /* Flush received async data to receive data buffer. */ 
995         while (fifo_count) {
996                 data   = read_reg(info, CHA + RXFIFO);
997                 status = read_reg(info, CHA + RXFIFO);
998                 fifo_count -= 2;
999
1000                 icount->rx++;
1001                 flag = TTY_NORMAL;
1002
1003                 // if no frameing/crc error then save data
1004                 // BIT7:parity error
1005                 // BIT6:framing error
1006
1007                 if (status & (BIT7 + BIT6)) {
1008                         if (status & BIT7) 
1009                                 icount->parity++;
1010                         else
1011                                 icount->frame++;
1012
1013                         /* discard char if tty control flags say so */
1014                         if (status & info->ignore_status_mask)
1015                                 continue;
1016                                 
1017                         status &= info->read_status_mask;
1018
1019                         if (status & BIT7)
1020                                 flag = TTY_PARITY;
1021                         else if (status & BIT6)
1022                                 flag = TTY_FRAME;
1023                 }
1024                 work += tty_insert_flip_char(tty, data, flag);
1025         }
1026         issue_command(info, CHA, CMD_RXFIFO);
1027
1028         if (debug_level >= DEBUG_LEVEL_ISR) {
1029                 printk("%s(%d):rx_ready_async",
1030                         __FILE__,__LINE__);
1031                 printk("%s(%d):rx=%d brk=%d parity=%d frame=%d overrun=%d\n",
1032                         __FILE__,__LINE__,icount->rx,icount->brk,
1033                         icount->parity,icount->frame,icount->overrun);
1034         }
1035                         
1036         if (work)
1037                 tty_flip_buffer_push(tty);
1038 }
1039
1040
1041 static void tx_done(MGSLPC_INFO *info)
1042 {
1043         if (!info->tx_active)
1044                 return;
1045                         
1046         info->tx_active = 0;
1047         info->tx_aborting = 0;
1048
1049         if (info->params.mode == MGSL_MODE_ASYNC)
1050                 return;
1051
1052         info->tx_count = info->tx_put = info->tx_get = 0;
1053         del_timer(&info->tx_timer);     
1054         
1055         if (info->drop_rts_on_tx_done) {
1056                 get_signals(info);
1057                 if (info->serial_signals & SerialSignal_RTS) {
1058                         info->serial_signals &= ~SerialSignal_RTS;
1059                         set_signals(info);
1060                 }
1061                 info->drop_rts_on_tx_done = 0;
1062         }
1063
1064 #ifdef CONFIG_HDLC
1065         if (info->netcount)
1066                 hdlcdev_tx_done(info);
1067         else 
1068 #endif
1069         {
1070                 if (info->tty->stopped || info->tty->hw_stopped) {
1071                         tx_stop(info);
1072                         return;
1073                 }
1074                 info->pending_bh |= BH_TRANSMIT;
1075         }
1076 }
1077
1078 static void tx_ready(MGSLPC_INFO *info)
1079 {
1080         unsigned char fifo_count = 32;
1081         int c;
1082
1083         if (debug_level >= DEBUG_LEVEL_ISR)
1084                 printk("%s(%d):tx_ready(%s)\n", __FILE__,__LINE__,info->device_name);
1085
1086         if (info->params.mode == MGSL_MODE_HDLC) {
1087                 if (!info->tx_active)
1088                         return;
1089         } else {
1090                 if (info->tty->stopped || info->tty->hw_stopped) {
1091                         tx_stop(info);
1092                         return;
1093                 }
1094                 if (!info->tx_count)
1095                         info->tx_active = 0;
1096         }
1097
1098         if (!info->tx_count)
1099                 return;
1100
1101         while (info->tx_count && fifo_count) {
1102                 c = min(2, min_t(int, fifo_count, min(info->tx_count, TXBUFSIZE - info->tx_get)));
1103                 
1104                 if (c == 1) {
1105                         write_reg(info, CHA + TXFIFO, *(info->tx_buf + info->tx_get));
1106                 } else {
1107                         write_reg16(info, CHA + TXFIFO,
1108                                           *((unsigned short*)(info->tx_buf + info->tx_get)));
1109                 }
1110                 info->tx_count -= c;
1111                 info->tx_get = (info->tx_get + c) & (TXBUFSIZE - 1);
1112                 fifo_count -= c;
1113         }
1114
1115         if (info->params.mode == MGSL_MODE_ASYNC) {
1116                 if (info->tx_count < WAKEUP_CHARS)
1117                         info->pending_bh |= BH_TRANSMIT;
1118                 issue_command(info, CHA, CMD_TXFIFO);
1119         } else {
1120                 if (info->tx_count)
1121                         issue_command(info, CHA, CMD_TXFIFO);
1122                 else
1123                         issue_command(info, CHA, CMD_TXFIFO + CMD_TXEOM);
1124         }
1125 }
1126
1127 static void cts_change(MGSLPC_INFO *info)
1128 {
1129         get_signals(info);
1130         if ((info->cts_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1131                 irq_disable(info, CHB, IRQ_CTS);
1132         info->icount.cts++;
1133         if (info->serial_signals & SerialSignal_CTS)
1134                 info->input_signal_events.cts_up++;
1135         else
1136                 info->input_signal_events.cts_down++;
1137         wake_up_interruptible(&info->status_event_wait_q);
1138         wake_up_interruptible(&info->event_wait_q);
1139
1140         if (info->flags & ASYNC_CTS_FLOW) {
1141                 if (info->tty->hw_stopped) {
1142                         if (info->serial_signals & SerialSignal_CTS) {
1143                                 if (debug_level >= DEBUG_LEVEL_ISR)
1144                                         printk("CTS tx start...");
1145                                 if (info->tty)
1146                                         info->tty->hw_stopped = 0;
1147                                 tx_start(info);
1148                                 info->pending_bh |= BH_TRANSMIT;
1149                                 return;
1150                         }
1151                 } else {
1152                         if (!(info->serial_signals & SerialSignal_CTS)) {
1153                                 if (debug_level >= DEBUG_LEVEL_ISR)
1154                                         printk("CTS tx stop...");
1155                                 if (info->tty)
1156                                         info->tty->hw_stopped = 1;
1157                                 tx_stop(info);
1158                         }
1159                 }
1160         }
1161         info->pending_bh |= BH_STATUS;
1162 }
1163
1164 static void dcd_change(MGSLPC_INFO *info)
1165 {
1166         get_signals(info);
1167         if ((info->dcd_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1168                 irq_disable(info, CHB, IRQ_DCD);
1169         info->icount.dcd++;
1170         if (info->serial_signals & SerialSignal_DCD) {
1171                 info->input_signal_events.dcd_up++;
1172         }
1173         else
1174                 info->input_signal_events.dcd_down++;
1175 #ifdef CONFIG_HDLC
1176         if (info->netcount) {
1177                 if (info->serial_signals & SerialSignal_DCD)
1178                         netif_carrier_on(info->netdev);
1179                 else
1180                         netif_carrier_off(info->netdev);
1181         }
1182 #endif
1183         wake_up_interruptible(&info->status_event_wait_q);
1184         wake_up_interruptible(&info->event_wait_q);
1185
1186         if (info->flags & ASYNC_CHECK_CD) {
1187                 if (debug_level >= DEBUG_LEVEL_ISR)
1188                         printk("%s CD now %s...", info->device_name,
1189                                (info->serial_signals & SerialSignal_DCD) ? "on" : "off");
1190                 if (info->serial_signals & SerialSignal_DCD)
1191                         wake_up_interruptible(&info->open_wait);
1192                 else {
1193                         if (debug_level >= DEBUG_LEVEL_ISR)
1194                                 printk("doing serial hangup...");
1195                         if (info->tty)
1196                                 tty_hangup(info->tty);
1197                 }
1198         }
1199         info->pending_bh |= BH_STATUS;
1200 }
1201
1202 static void dsr_change(MGSLPC_INFO *info)
1203 {
1204         get_signals(info);
1205         if ((info->dsr_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1206                 port_irq_disable(info, PVR_DSR);
1207         info->icount.dsr++;
1208         if (info->serial_signals & SerialSignal_DSR)
1209                 info->input_signal_events.dsr_up++;
1210         else
1211                 info->input_signal_events.dsr_down++;
1212         wake_up_interruptible(&info->status_event_wait_q);
1213         wake_up_interruptible(&info->event_wait_q);
1214         info->pending_bh |= BH_STATUS;
1215 }
1216
1217 static void ri_change(MGSLPC_INFO *info)
1218 {
1219         get_signals(info);
1220         if ((info->ri_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1221                 port_irq_disable(info, PVR_RI);
1222         info->icount.rng++;
1223         if (info->serial_signals & SerialSignal_RI)
1224                 info->input_signal_events.ri_up++;
1225         else
1226                 info->input_signal_events.ri_down++;
1227         wake_up_interruptible(&info->status_event_wait_q);
1228         wake_up_interruptible(&info->event_wait_q);
1229         info->pending_bh |= BH_STATUS;
1230 }
1231
1232 /* Interrupt service routine entry point.
1233  *      
1234  * Arguments:
1235  * 
1236  * irq     interrupt number that caused interrupt
1237  * dev_id  device ID supplied during interrupt registration
1238  * regs    interrupted processor context
1239  */
1240 static irqreturn_t mgslpc_isr(int irq, void *dev_id, struct pt_regs * regs)
1241 {
1242         MGSLPC_INFO * info = (MGSLPC_INFO *)dev_id;
1243         unsigned short isr;
1244         unsigned char gis, pis;
1245         int count=0;
1246
1247         if (debug_level >= DEBUG_LEVEL_ISR)     
1248                 printk("mgslpc_isr(%d) entry.\n", irq);
1249         if (!info)
1250                 return IRQ_NONE;
1251                 
1252         if (!(info->p_dev->_locked))
1253                 return IRQ_HANDLED;
1254
1255         spin_lock(&info->lock);
1256
1257         while ((gis = read_reg(info, CHA + GIS))) {
1258                 if (debug_level >= DEBUG_LEVEL_ISR)     
1259                         printk("mgslpc_isr %s gis=%04X\n", info->device_name,gis);
1260
1261                 if ((gis & 0x70) || count > 1000) {
1262                         printk("synclink_cs:hardware failed or ejected\n");
1263                         break;
1264                 }
1265                 count++;
1266
1267                 if (gis & (BIT1 + BIT0)) {
1268                         isr = read_reg16(info, CHB + ISR);
1269                         if (isr & IRQ_DCD)
1270                                 dcd_change(info);
1271                         if (isr & IRQ_CTS)
1272                                 cts_change(info);
1273                 }
1274                 if (gis & (BIT3 + BIT2))
1275                 {
1276                         isr = read_reg16(info, CHA + ISR);
1277                         if (isr & IRQ_TIMER) {
1278                                 info->irq_occurred = 1;
1279                                 irq_disable(info, CHA, IRQ_TIMER);
1280                         }
1281
1282                         /* receive IRQs */ 
1283                         if (isr & IRQ_EXITHUNT) {
1284                                 info->icount.exithunt++;
1285                                 wake_up_interruptible(&info->event_wait_q);
1286                         }
1287                         if (isr & IRQ_BREAK_ON) {
1288                                 info->icount.brk++;
1289                                 if (info->flags & ASYNC_SAK)
1290                                         do_SAK(info->tty);
1291                         }
1292                         if (isr & IRQ_RXTIME) {
1293                                 issue_command(info, CHA, CMD_RXFIFO_READ);
1294                         }
1295                         if (isr & (IRQ_RXEOM + IRQ_RXFIFO)) {
1296                                 if (info->params.mode == MGSL_MODE_HDLC)
1297                                         rx_ready_hdlc(info, isr & IRQ_RXEOM); 
1298                                 else
1299                                         rx_ready_async(info, isr & IRQ_RXEOM);
1300                         }
1301
1302                         /* transmit IRQs */ 
1303                         if (isr & IRQ_UNDERRUN) {
1304                                 if (info->tx_aborting)
1305                                         info->icount.txabort++;
1306                                 else
1307                                         info->icount.txunder++;
1308                                 tx_done(info);
1309                         }
1310                         else if (isr & IRQ_ALLSENT) {
1311                                 info->icount.txok++;
1312                                 tx_done(info);
1313                         }
1314                         else if (isr & IRQ_TXFIFO)
1315                                 tx_ready(info);
1316                 }
1317                 if (gis & BIT7) {
1318                         pis = read_reg(info, CHA + PIS);
1319                         if (pis & BIT1)
1320                                 dsr_change(info);
1321                         if (pis & BIT2)
1322                                 ri_change(info);
1323                 }
1324         }
1325         
1326         /* Request bottom half processing if there's something 
1327          * for it to do and the bh is not already running
1328          */
1329
1330         if (info->pending_bh && !info->bh_running && !info->bh_requested) {
1331                 if ( debug_level >= DEBUG_LEVEL_ISR )   
1332                         printk("%s(%d):%s queueing bh task.\n",
1333                                 __FILE__,__LINE__,info->device_name);
1334                 schedule_work(&info->task);
1335                 info->bh_requested = 1;
1336         }
1337
1338         spin_unlock(&info->lock);
1339         
1340         if (debug_level >= DEBUG_LEVEL_ISR)     
1341                 printk("%s(%d):mgslpc_isr(%d)exit.\n",
1342                        __FILE__,__LINE__,irq);
1343
1344         return IRQ_HANDLED;
1345 }
1346
1347 /* Initialize and start device.
1348  */
1349 static int startup(MGSLPC_INFO * info)
1350 {
1351         int retval = 0;
1352         
1353         if (debug_level >= DEBUG_LEVEL_INFO)
1354                 printk("%s(%d):startup(%s)\n",__FILE__,__LINE__,info->device_name);
1355                 
1356         if (info->flags & ASYNC_INITIALIZED)
1357                 return 0;
1358         
1359         if (!info->tx_buf) {
1360                 /* allocate a page of memory for a transmit buffer */
1361                 info->tx_buf = (unsigned char *)get_zeroed_page(GFP_KERNEL);
1362                 if (!info->tx_buf) {
1363                         printk(KERN_ERR"%s(%d):%s can't allocate transmit buffer\n",
1364                                 __FILE__,__LINE__,info->device_name);
1365                         return -ENOMEM;
1366                 }
1367         }
1368
1369         info->pending_bh = 0;
1370         
1371         memset(&info->icount, 0, sizeof(info->icount));
1372
1373         init_timer(&info->tx_timer);
1374         info->tx_timer.data = (unsigned long)info;
1375         info->tx_timer.function = tx_timeout;
1376
1377         /* Allocate and claim adapter resources */
1378         retval = claim_resources(info);
1379         
1380         /* perform existance check and diagnostics */
1381         if ( !retval )
1382                 retval = adapter_test(info);
1383                 
1384         if ( retval ) {
1385                 if (capable(CAP_SYS_ADMIN) && info->tty)
1386                         set_bit(TTY_IO_ERROR, &info->tty->flags);
1387                 release_resources(info);
1388                 return retval;
1389         }
1390
1391         /* program hardware for current parameters */
1392         mgslpc_change_params(info);
1393         
1394         if (info->tty)
1395                 clear_bit(TTY_IO_ERROR, &info->tty->flags);
1396
1397         info->flags |= ASYNC_INITIALIZED;
1398         
1399         return 0;
1400 }
1401
1402 /* Called by mgslpc_close() and mgslpc_hangup() to shutdown hardware
1403  */
1404 static void shutdown(MGSLPC_INFO * info)
1405 {
1406         unsigned long flags;
1407         
1408         if (!(info->flags & ASYNC_INITIALIZED))
1409                 return;
1410
1411         if (debug_level >= DEBUG_LEVEL_INFO)
1412                 printk("%s(%d):mgslpc_shutdown(%s)\n",
1413                          __FILE__,__LINE__, info->device_name );
1414
1415         /* clear status wait queue because status changes */
1416         /* can't happen after shutting down the hardware */
1417         wake_up_interruptible(&info->status_event_wait_q);
1418         wake_up_interruptible(&info->event_wait_q);
1419
1420         del_timer(&info->tx_timer);     
1421
1422         if (info->tx_buf) {
1423                 free_page((unsigned long) info->tx_buf);
1424                 info->tx_buf = NULL;
1425         }
1426
1427         spin_lock_irqsave(&info->lock,flags);
1428
1429         rx_stop(info);
1430         tx_stop(info);
1431
1432         /* TODO:disable interrupts instead of reset to preserve signal states */
1433         reset_device(info);
1434         
1435         if (!info->tty || info->tty->termios->c_cflag & HUPCL) {
1436                 info->serial_signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
1437                 set_signals(info);
1438         }
1439         
1440         spin_unlock_irqrestore(&info->lock,flags);
1441
1442         release_resources(info);        
1443         
1444         if (info->tty)
1445                 set_bit(TTY_IO_ERROR, &info->tty->flags);
1446
1447         info->flags &= ~ASYNC_INITIALIZED;
1448 }
1449
1450 static void mgslpc_program_hw(MGSLPC_INFO *info)
1451 {
1452         unsigned long flags;
1453
1454         spin_lock_irqsave(&info->lock,flags);
1455         
1456         rx_stop(info);
1457         tx_stop(info);
1458         info->tx_count = info->tx_put = info->tx_get = 0;
1459         
1460         if (info->params.mode == MGSL_MODE_HDLC || info->netcount)
1461                 hdlc_mode(info);
1462         else
1463                 async_mode(info);
1464                 
1465         set_signals(info);
1466         
1467         info->dcd_chkcount = 0;
1468         info->cts_chkcount = 0;
1469         info->ri_chkcount = 0;
1470         info->dsr_chkcount = 0;
1471
1472         irq_enable(info, CHB, IRQ_DCD | IRQ_CTS);
1473         port_irq_enable(info, (unsigned char) PVR_DSR | PVR_RI);
1474         get_signals(info);
1475                 
1476         if (info->netcount || info->tty->termios->c_cflag & CREAD)
1477                 rx_start(info);
1478                 
1479         spin_unlock_irqrestore(&info->lock,flags);
1480 }
1481
1482 /* Reconfigure adapter based on new parameters
1483  */
1484 static void mgslpc_change_params(MGSLPC_INFO *info)
1485 {
1486         unsigned cflag;
1487         int bits_per_char;
1488
1489         if (!info->tty || !info->tty->termios)
1490                 return;
1491                 
1492         if (debug_level >= DEBUG_LEVEL_INFO)
1493                 printk("%s(%d):mgslpc_change_params(%s)\n",
1494                          __FILE__,__LINE__, info->device_name );
1495                          
1496         cflag = info->tty->termios->c_cflag;
1497
1498         /* if B0 rate (hangup) specified then negate DTR and RTS */
1499         /* otherwise assert DTR and RTS */
1500         if (cflag & CBAUD)
1501                 info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
1502         else
1503                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
1504         
1505         /* byte size and parity */
1506         
1507         switch (cflag & CSIZE) {
1508         case CS5: info->params.data_bits = 5; break;
1509         case CS6: info->params.data_bits = 6; break;
1510         case CS7: info->params.data_bits = 7; break;
1511         case CS8: info->params.data_bits = 8; break;
1512         default:  info->params.data_bits = 7; break;
1513         }
1514               
1515         if (cflag & CSTOPB)
1516                 info->params.stop_bits = 2;
1517         else
1518                 info->params.stop_bits = 1;
1519
1520         info->params.parity = ASYNC_PARITY_NONE;
1521         if (cflag & PARENB) {
1522                 if (cflag & PARODD)
1523                         info->params.parity = ASYNC_PARITY_ODD;
1524                 else
1525                         info->params.parity = ASYNC_PARITY_EVEN;
1526 #ifdef CMSPAR
1527                 if (cflag & CMSPAR)
1528                         info->params.parity = ASYNC_PARITY_SPACE;
1529 #endif
1530         }
1531
1532         /* calculate number of jiffies to transmit a full
1533          * FIFO (32 bytes) at specified data rate
1534          */
1535         bits_per_char = info->params.data_bits + 
1536                         info->params.stop_bits + 1;
1537
1538         /* if port data rate is set to 460800 or less then
1539          * allow tty settings to override, otherwise keep the
1540          * current data rate.
1541          */
1542         if (info->params.data_rate <= 460800) {
1543                 info->params.data_rate = tty_get_baud_rate(info->tty);
1544         }
1545         
1546         if ( info->params.data_rate ) {
1547                 info->timeout = (32*HZ*bits_per_char) / 
1548                                 info->params.data_rate;
1549         }
1550         info->timeout += HZ/50;         /* Add .02 seconds of slop */
1551
1552         if (cflag & CRTSCTS)
1553                 info->flags |= ASYNC_CTS_FLOW;
1554         else
1555                 info->flags &= ~ASYNC_CTS_FLOW;
1556                 
1557         if (cflag & CLOCAL)
1558                 info->flags &= ~ASYNC_CHECK_CD;
1559         else
1560                 info->flags |= ASYNC_CHECK_CD;
1561
1562         /* process tty input control flags */
1563         
1564         info->read_status_mask = 0;
1565         if (I_INPCK(info->tty))
1566                 info->read_status_mask |= BIT7 | BIT6;
1567         if (I_IGNPAR(info->tty))
1568                 info->ignore_status_mask |= BIT7 | BIT6;
1569
1570         mgslpc_program_hw(info);
1571 }
1572
1573 /* Add a character to the transmit buffer
1574  */
1575 static void mgslpc_put_char(struct tty_struct *tty, unsigned char ch)
1576 {
1577         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1578         unsigned long flags;
1579
1580         if (debug_level >= DEBUG_LEVEL_INFO) {
1581                 printk( "%s(%d):mgslpc_put_char(%d) on %s\n",
1582                         __FILE__,__LINE__,ch,info->device_name);
1583         }
1584
1585         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_put_char"))
1586                 return;
1587
1588         if (!info->tx_buf)
1589                 return;
1590
1591         spin_lock_irqsave(&info->lock,flags);
1592         
1593         if (info->params.mode == MGSL_MODE_ASYNC || !info->tx_active) {
1594                 if (info->tx_count < TXBUFSIZE - 1) {
1595                         info->tx_buf[info->tx_put++] = ch;
1596                         info->tx_put &= TXBUFSIZE-1;
1597                         info->tx_count++;
1598                 }
1599         }
1600         
1601         spin_unlock_irqrestore(&info->lock,flags);
1602 }
1603
1604 /* Enable transmitter so remaining characters in the
1605  * transmit buffer are sent.
1606  */
1607 static void mgslpc_flush_chars(struct tty_struct *tty)
1608 {
1609         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1610         unsigned long flags;
1611                                 
1612         if (debug_level >= DEBUG_LEVEL_INFO)
1613                 printk( "%s(%d):mgslpc_flush_chars() entry on %s tx_count=%d\n",
1614                         __FILE__,__LINE__,info->device_name,info->tx_count);
1615         
1616         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_chars"))
1617                 return;
1618
1619         if (info->tx_count <= 0 || tty->stopped ||
1620             tty->hw_stopped || !info->tx_buf)
1621                 return;
1622
1623         if (debug_level >= DEBUG_LEVEL_INFO)
1624                 printk( "%s(%d):mgslpc_flush_chars() entry on %s starting transmitter\n",
1625                         __FILE__,__LINE__,info->device_name);
1626
1627         spin_lock_irqsave(&info->lock,flags);
1628         if (!info->tx_active)
1629                 tx_start(info);
1630         spin_unlock_irqrestore(&info->lock,flags);
1631 }
1632
1633 /* Send a block of data
1634  *      
1635  * Arguments:
1636  * 
1637  * tty        pointer to tty information structure
1638  * buf        pointer to buffer containing send data
1639  * count      size of send data in bytes
1640  *      
1641  * Returns: number of characters written
1642  */
1643 static int mgslpc_write(struct tty_struct * tty,
1644                         const unsigned char *buf, int count)
1645 {
1646         int c, ret = 0;
1647         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1648         unsigned long flags;
1649         
1650         if (debug_level >= DEBUG_LEVEL_INFO)
1651                 printk( "%s(%d):mgslpc_write(%s) count=%d\n",
1652                         __FILE__,__LINE__,info->device_name,count);
1653         
1654         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write") ||
1655                 !info->tx_buf)
1656                 goto cleanup;
1657
1658         if (info->params.mode == MGSL_MODE_HDLC) {
1659                 if (count > TXBUFSIZE) {
1660                         ret = -EIO;
1661                         goto cleanup;
1662                 }
1663                 if (info->tx_active)
1664                         goto cleanup;
1665                 else if (info->tx_count)
1666                         goto start;
1667         }
1668
1669         for (;;) {
1670                 c = min(count,
1671                         min(TXBUFSIZE - info->tx_count - 1,
1672                             TXBUFSIZE - info->tx_put));
1673                 if (c <= 0)
1674                         break;
1675                         
1676                 memcpy(info->tx_buf + info->tx_put, buf, c);
1677
1678                 spin_lock_irqsave(&info->lock,flags);
1679                 info->tx_put = (info->tx_put + c) & (TXBUFSIZE-1);
1680                 info->tx_count += c;
1681                 spin_unlock_irqrestore(&info->lock,flags);
1682
1683                 buf += c;
1684                 count -= c;
1685                 ret += c;
1686         }
1687 start:
1688         if (info->tx_count && !tty->stopped && !tty->hw_stopped) {
1689                 spin_lock_irqsave(&info->lock,flags);
1690                 if (!info->tx_active)
1691                         tx_start(info);
1692                 spin_unlock_irqrestore(&info->lock,flags);
1693         }
1694 cleanup:        
1695         if (debug_level >= DEBUG_LEVEL_INFO)
1696                 printk( "%s(%d):mgslpc_write(%s) returning=%d\n",
1697                         __FILE__,__LINE__,info->device_name,ret);
1698         return ret;
1699 }
1700
1701 /* Return the count of free bytes in transmit buffer
1702  */
1703 static int mgslpc_write_room(struct tty_struct *tty)
1704 {
1705         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1706         int ret;
1707                                 
1708         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_write_room"))
1709                 return 0;
1710
1711         if (info->params.mode == MGSL_MODE_HDLC) {
1712                 /* HDLC (frame oriented) mode */
1713                 if (info->tx_active)
1714                         return 0;
1715                 else
1716                         return HDLC_MAX_FRAME_SIZE;
1717         } else {
1718                 ret = TXBUFSIZE - info->tx_count - 1;
1719                 if (ret < 0)
1720                         ret = 0;
1721         }
1722         
1723         if (debug_level >= DEBUG_LEVEL_INFO)
1724                 printk("%s(%d):mgslpc_write_room(%s)=%d\n",
1725                          __FILE__,__LINE__, info->device_name, ret);
1726         return ret;
1727 }
1728
1729 /* Return the count of bytes in transmit buffer
1730  */
1731 static int mgslpc_chars_in_buffer(struct tty_struct *tty)
1732 {
1733         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1734         int rc;
1735                  
1736         if (debug_level >= DEBUG_LEVEL_INFO)
1737                 printk("%s(%d):mgslpc_chars_in_buffer(%s)\n",
1738                          __FILE__,__LINE__, info->device_name );
1739                          
1740         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_chars_in_buffer"))
1741                 return 0;
1742                 
1743         if (info->params.mode == MGSL_MODE_HDLC)
1744                 rc = info->tx_active ? info->max_frame_size : 0;
1745         else
1746                 rc = info->tx_count;
1747
1748         if (debug_level >= DEBUG_LEVEL_INFO)
1749                 printk("%s(%d):mgslpc_chars_in_buffer(%s)=%d\n",
1750                          __FILE__,__LINE__, info->device_name, rc);
1751                          
1752         return rc;
1753 }
1754
1755 /* Discard all data in the send buffer
1756  */
1757 static void mgslpc_flush_buffer(struct tty_struct *tty)
1758 {
1759         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1760         unsigned long flags;
1761         
1762         if (debug_level >= DEBUG_LEVEL_INFO)
1763                 printk("%s(%d):mgslpc_flush_buffer(%s) entry\n",
1764                          __FILE__,__LINE__, info->device_name );
1765         
1766         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_flush_buffer"))
1767                 return;
1768                 
1769         spin_lock_irqsave(&info->lock,flags); 
1770         info->tx_count = info->tx_put = info->tx_get = 0;
1771         del_timer(&info->tx_timer);     
1772         spin_unlock_irqrestore(&info->lock,flags);
1773
1774         wake_up_interruptible(&tty->write_wait);
1775         tty_wakeup(tty);
1776 }
1777
1778 /* Send a high-priority XON/XOFF character
1779  */
1780 static void mgslpc_send_xchar(struct tty_struct *tty, char ch)
1781 {
1782         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1783         unsigned long flags;
1784
1785         if (debug_level >= DEBUG_LEVEL_INFO)
1786                 printk("%s(%d):mgslpc_send_xchar(%s,%d)\n",
1787                          __FILE__,__LINE__, info->device_name, ch );
1788                          
1789         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_send_xchar"))
1790                 return;
1791
1792         info->x_char = ch;
1793         if (ch) {
1794                 spin_lock_irqsave(&info->lock,flags);
1795                 if (!info->tx_enabled)
1796                         tx_start(info);
1797                 spin_unlock_irqrestore(&info->lock,flags);
1798         }
1799 }
1800
1801 /* Signal remote device to throttle send data (our receive data)
1802  */
1803 static void mgslpc_throttle(struct tty_struct * tty)
1804 {
1805         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1806         unsigned long flags;
1807         
1808         if (debug_level >= DEBUG_LEVEL_INFO)
1809                 printk("%s(%d):mgslpc_throttle(%s) entry\n",
1810                          __FILE__,__LINE__, info->device_name );
1811
1812         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_throttle"))
1813                 return;
1814         
1815         if (I_IXOFF(tty))
1816                 mgslpc_send_xchar(tty, STOP_CHAR(tty));
1817  
1818         if (tty->termios->c_cflag & CRTSCTS) {
1819                 spin_lock_irqsave(&info->lock,flags);
1820                 info->serial_signals &= ~SerialSignal_RTS;
1821                 set_signals(info);
1822                 spin_unlock_irqrestore(&info->lock,flags);
1823         }
1824 }
1825
1826 /* Signal remote device to stop throttling send data (our receive data)
1827  */
1828 static void mgslpc_unthrottle(struct tty_struct * tty)
1829 {
1830         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
1831         unsigned long flags;
1832         
1833         if (debug_level >= DEBUG_LEVEL_INFO)
1834                 printk("%s(%d):mgslpc_unthrottle(%s) entry\n",
1835                          __FILE__,__LINE__, info->device_name );
1836
1837         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_unthrottle"))
1838                 return;
1839         
1840         if (I_IXOFF(tty)) {
1841                 if (info->x_char)
1842                         info->x_char = 0;
1843                 else
1844                         mgslpc_send_xchar(tty, START_CHAR(tty));
1845         }
1846         
1847         if (tty->termios->c_cflag & CRTSCTS) {
1848                 spin_lock_irqsave(&info->lock,flags);
1849                 info->serial_signals |= SerialSignal_RTS;
1850                 set_signals(info);
1851                 spin_unlock_irqrestore(&info->lock,flags);
1852         }
1853 }
1854
1855 /* get the current serial statistics
1856  */
1857 static int get_stats(MGSLPC_INFO * info, struct mgsl_icount __user *user_icount)
1858 {
1859         int err;
1860         if (debug_level >= DEBUG_LEVEL_INFO)
1861                 printk("get_params(%s)\n", info->device_name);
1862         if (!user_icount) {
1863                 memset(&info->icount, 0, sizeof(info->icount));
1864         } else {
1865                 COPY_TO_USER(err, user_icount, &info->icount, sizeof(struct mgsl_icount));
1866                 if (err)
1867                         return -EFAULT;
1868         }
1869         return 0;
1870 }
1871
1872 /* get the current serial parameters
1873  */
1874 static int get_params(MGSLPC_INFO * info, MGSL_PARAMS __user *user_params)
1875 {
1876         int err;
1877         if (debug_level >= DEBUG_LEVEL_INFO)
1878                 printk("get_params(%s)\n", info->device_name);
1879         COPY_TO_USER(err,user_params, &info->params, sizeof(MGSL_PARAMS));
1880         if (err)
1881                 return -EFAULT;
1882         return 0;
1883 }
1884
1885 /* set the serial parameters
1886  *      
1887  * Arguments:
1888  * 
1889  *      info            pointer to device instance data
1890  *      new_params      user buffer containing new serial params
1891  *
1892  * Returns:     0 if success, otherwise error code
1893  */
1894 static int set_params(MGSLPC_INFO * info, MGSL_PARAMS __user *new_params)
1895 {
1896         unsigned long flags;
1897         MGSL_PARAMS tmp_params;
1898         int err;
1899  
1900         if (debug_level >= DEBUG_LEVEL_INFO)
1901                 printk("%s(%d):set_params %s\n", __FILE__,__LINE__,
1902                         info->device_name );
1903         COPY_FROM_USER(err,&tmp_params, new_params, sizeof(MGSL_PARAMS));
1904         if (err) {
1905                 if ( debug_level >= DEBUG_LEVEL_INFO )
1906                         printk( "%s(%d):set_params(%s) user buffer copy failed\n",
1907                                 __FILE__,__LINE__,info->device_name);
1908                 return -EFAULT;
1909         }
1910         
1911         spin_lock_irqsave(&info->lock,flags);
1912         memcpy(&info->params,&tmp_params,sizeof(MGSL_PARAMS));
1913         spin_unlock_irqrestore(&info->lock,flags);
1914         
1915         mgslpc_change_params(info);
1916         
1917         return 0;
1918 }
1919
1920 static int get_txidle(MGSLPC_INFO * info, int __user *idle_mode)
1921 {
1922         int err;
1923         if (debug_level >= DEBUG_LEVEL_INFO)
1924                 printk("get_txidle(%s)=%d\n", info->device_name, info->idle_mode);
1925         COPY_TO_USER(err,idle_mode, &info->idle_mode, sizeof(int));
1926         if (err)
1927                 return -EFAULT;
1928         return 0;
1929 }
1930
1931 static int set_txidle(MGSLPC_INFO * info, int idle_mode)
1932 {
1933         unsigned long flags;
1934         if (debug_level >= DEBUG_LEVEL_INFO)
1935                 printk("set_txidle(%s,%d)\n", info->device_name, idle_mode);
1936         spin_lock_irqsave(&info->lock,flags);
1937         info->idle_mode = idle_mode;
1938         tx_set_idle(info);
1939         spin_unlock_irqrestore(&info->lock,flags);
1940         return 0;
1941 }
1942
1943 static int get_interface(MGSLPC_INFO * info, int __user *if_mode)
1944 {
1945         int err;
1946         if (debug_level >= DEBUG_LEVEL_INFO)
1947                 printk("get_interface(%s)=%d\n", info->device_name, info->if_mode);
1948         COPY_TO_USER(err,if_mode, &info->if_mode, sizeof(int));
1949         if (err)
1950                 return -EFAULT;
1951         return 0;
1952 }
1953
1954 static int set_interface(MGSLPC_INFO * info, int if_mode)
1955 {
1956         unsigned long flags;
1957         unsigned char val;
1958         if (debug_level >= DEBUG_LEVEL_INFO)
1959                 printk("set_interface(%s,%d)\n", info->device_name, if_mode);
1960         spin_lock_irqsave(&info->lock,flags);
1961         info->if_mode = if_mode;
1962
1963         val = read_reg(info, PVR) & 0x0f;
1964         switch (info->if_mode)
1965         {
1966         case MGSL_INTERFACE_RS232: val |= PVR_RS232; break;
1967         case MGSL_INTERFACE_V35:   val |= PVR_V35;   break;
1968         case MGSL_INTERFACE_RS422: val |= PVR_RS422; break;
1969         }
1970         write_reg(info, PVR, val);
1971
1972         spin_unlock_irqrestore(&info->lock,flags);
1973         return 0;
1974 }
1975
1976 static int set_txenable(MGSLPC_INFO * info, int enable)
1977 {
1978         unsigned long flags;
1979  
1980         if (debug_level >= DEBUG_LEVEL_INFO)
1981                 printk("set_txenable(%s,%d)\n", info->device_name, enable);
1982                         
1983         spin_lock_irqsave(&info->lock,flags);
1984         if (enable) {
1985                 if (!info->tx_enabled)
1986                         tx_start(info);
1987         } else {
1988                 if (info->tx_enabled)
1989                         tx_stop(info);
1990         }
1991         spin_unlock_irqrestore(&info->lock,flags);
1992         return 0;
1993 }
1994
1995 static int tx_abort(MGSLPC_INFO * info)
1996 {
1997         unsigned long flags;
1998  
1999         if (debug_level >= DEBUG_LEVEL_INFO)
2000                 printk("tx_abort(%s)\n", info->device_name);
2001                         
2002         spin_lock_irqsave(&info->lock,flags);
2003         if (info->tx_active && info->tx_count &&
2004             info->params.mode == MGSL_MODE_HDLC) {
2005                 /* clear data count so FIFO is not filled on next IRQ.
2006                  * This results in underrun and abort transmission.
2007                  */
2008                 info->tx_count = info->tx_put = info->tx_get = 0;
2009                 info->tx_aborting = TRUE;
2010         }
2011         spin_unlock_irqrestore(&info->lock,flags);
2012         return 0;
2013 }
2014
2015 static int set_rxenable(MGSLPC_INFO * info, int enable)
2016 {
2017         unsigned long flags;
2018  
2019         if (debug_level >= DEBUG_LEVEL_INFO)
2020                 printk("set_rxenable(%s,%d)\n", info->device_name, enable);
2021                         
2022         spin_lock_irqsave(&info->lock,flags);
2023         if (enable) {
2024                 if (!info->rx_enabled)
2025                         rx_start(info);
2026         } else {
2027                 if (info->rx_enabled)
2028                         rx_stop(info);
2029         }
2030         spin_unlock_irqrestore(&info->lock,flags);
2031         return 0;
2032 }
2033
2034 /* wait for specified event to occur
2035  *      
2036  * Arguments:           info    pointer to device instance data
2037  *                      mask    pointer to bitmask of events to wait for
2038  * Return Value:        0       if successful and bit mask updated with
2039  *                              of events triggerred,
2040  *                      otherwise error code
2041  */
2042 static int wait_events(MGSLPC_INFO * info, int __user *mask_ptr)
2043 {
2044         unsigned long flags;
2045         int s;
2046         int rc=0;
2047         struct mgsl_icount cprev, cnow;
2048         int events;
2049         int mask;
2050         struct  _input_signal_events oldsigs, newsigs;
2051         DECLARE_WAITQUEUE(wait, current);
2052
2053         COPY_FROM_USER(rc,&mask, mask_ptr, sizeof(int));
2054         if (rc)
2055                 return  -EFAULT;
2056                  
2057         if (debug_level >= DEBUG_LEVEL_INFO)
2058                 printk("wait_events(%s,%d)\n", info->device_name, mask);
2059
2060         spin_lock_irqsave(&info->lock,flags);
2061
2062         /* return immediately if state matches requested events */
2063         get_signals(info);
2064         s = info->serial_signals;
2065         events = mask &
2066                 ( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) +
2067                   ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) +
2068                   ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) +
2069                   ((s & SerialSignal_RI)  ? MgslEvent_RiActive :MgslEvent_RiInactive) );
2070         if (events) {
2071                 spin_unlock_irqrestore(&info->lock,flags);
2072                 goto exit;
2073         }
2074
2075         /* save current irq counts */
2076         cprev = info->icount;
2077         oldsigs = info->input_signal_events;
2078         
2079         if ((info->params.mode == MGSL_MODE_HDLC) &&
2080             (mask & MgslEvent_ExitHuntMode))
2081                 irq_enable(info, CHA, IRQ_EXITHUNT);
2082         
2083         set_current_state(TASK_INTERRUPTIBLE);
2084         add_wait_queue(&info->event_wait_q, &wait);
2085         
2086         spin_unlock_irqrestore(&info->lock,flags);
2087         
2088         
2089         for(;;) {
2090                 schedule();
2091                 if (signal_pending(current)) {
2092                         rc = -ERESTARTSYS;
2093                         break;
2094                 }
2095                         
2096                 /* get current irq counts */
2097                 spin_lock_irqsave(&info->lock,flags);
2098                 cnow = info->icount;
2099                 newsigs = info->input_signal_events;
2100                 set_current_state(TASK_INTERRUPTIBLE);
2101                 spin_unlock_irqrestore(&info->lock,flags);
2102
2103                 /* if no change, wait aborted for some reason */
2104                 if (newsigs.dsr_up   == oldsigs.dsr_up   &&
2105                     newsigs.dsr_down == oldsigs.dsr_down &&
2106                     newsigs.dcd_up   == oldsigs.dcd_up   &&
2107                     newsigs.dcd_down == oldsigs.dcd_down &&
2108                     newsigs.cts_up   == oldsigs.cts_up   &&
2109                     newsigs.cts_down == oldsigs.cts_down &&
2110                     newsigs.ri_up    == oldsigs.ri_up    &&
2111                     newsigs.ri_down  == oldsigs.ri_down  &&
2112                     cnow.exithunt    == cprev.exithunt   &&
2113                     cnow.rxidle      == cprev.rxidle) {
2114                         rc = -EIO;
2115                         break;
2116                 }
2117
2118                 events = mask &
2119                         ( (newsigs.dsr_up   != oldsigs.dsr_up   ? MgslEvent_DsrActive:0)   +
2120                           (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) +
2121                           (newsigs.dcd_up   != oldsigs.dcd_up   ? MgslEvent_DcdActive:0)   +
2122                           (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) +
2123                           (newsigs.cts_up   != oldsigs.cts_up   ? MgslEvent_CtsActive:0)   +
2124                           (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) +
2125                           (newsigs.ri_up    != oldsigs.ri_up    ? MgslEvent_RiActive:0)    +
2126                           (newsigs.ri_down  != oldsigs.ri_down  ? MgslEvent_RiInactive:0)  +
2127                           (cnow.exithunt    != cprev.exithunt   ? MgslEvent_ExitHuntMode:0) +
2128                           (cnow.rxidle      != cprev.rxidle     ? MgslEvent_IdleReceived:0) );
2129                 if (events)
2130                         break;
2131                 
2132                 cprev = cnow;
2133                 oldsigs = newsigs;
2134         }
2135         
2136         remove_wait_queue(&info->event_wait_q, &wait);
2137         set_current_state(TASK_RUNNING);
2138
2139         if (mask & MgslEvent_ExitHuntMode) {
2140                 spin_lock_irqsave(&info->lock,flags);
2141                 if (!waitqueue_active(&info->event_wait_q))
2142                         irq_disable(info, CHA, IRQ_EXITHUNT);
2143                 spin_unlock_irqrestore(&info->lock,flags);
2144         }
2145 exit:
2146         if (rc == 0)
2147                 PUT_USER(rc, events, mask_ptr);
2148         return rc;
2149 }
2150
2151 static int modem_input_wait(MGSLPC_INFO *info,int arg)
2152 {
2153         unsigned long flags;
2154         int rc;
2155         struct mgsl_icount cprev, cnow;
2156         DECLARE_WAITQUEUE(wait, current);
2157
2158         /* save current irq counts */
2159         spin_lock_irqsave(&info->lock,flags);
2160         cprev = info->icount;
2161         add_wait_queue(&info->status_event_wait_q, &wait);
2162         set_current_state(TASK_INTERRUPTIBLE);
2163         spin_unlock_irqrestore(&info->lock,flags);
2164
2165         for(;;) {
2166                 schedule();
2167                 if (signal_pending(current)) {
2168                         rc = -ERESTARTSYS;
2169                         break;
2170                 }
2171
2172                 /* get new irq counts */
2173                 spin_lock_irqsave(&info->lock,flags);
2174                 cnow = info->icount;
2175                 set_current_state(TASK_INTERRUPTIBLE);
2176                 spin_unlock_irqrestore(&info->lock,flags);
2177
2178                 /* if no change, wait aborted for some reason */
2179                 if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
2180                     cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) {
2181                         rc = -EIO;
2182                         break;
2183                 }
2184
2185                 /* check for change in caller specified modem input */
2186                 if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) ||
2187                     (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) ||
2188                     (arg & TIOCM_CD  && cnow.dcd != cprev.dcd) ||
2189                     (arg & TIOCM_CTS && cnow.cts != cprev.cts)) {
2190                         rc = 0;
2191                         break;
2192                 }
2193
2194                 cprev = cnow;
2195         }
2196         remove_wait_queue(&info->status_event_wait_q, &wait);
2197         set_current_state(TASK_RUNNING);
2198         return rc;
2199 }
2200
2201 /* return the state of the serial control and status signals
2202  */
2203 static int tiocmget(struct tty_struct *tty, struct file *file)
2204 {
2205         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2206         unsigned int result;
2207         unsigned long flags;
2208
2209         spin_lock_irqsave(&info->lock,flags);
2210         get_signals(info);
2211         spin_unlock_irqrestore(&info->lock,flags);
2212
2213         result = ((info->serial_signals & SerialSignal_RTS) ? TIOCM_RTS:0) +
2214                 ((info->serial_signals & SerialSignal_DTR) ? TIOCM_DTR:0) +
2215                 ((info->serial_signals & SerialSignal_DCD) ? TIOCM_CAR:0) +
2216                 ((info->serial_signals & SerialSignal_RI)  ? TIOCM_RNG:0) +
2217                 ((info->serial_signals & SerialSignal_DSR) ? TIOCM_DSR:0) +
2218                 ((info->serial_signals & SerialSignal_CTS) ? TIOCM_CTS:0);
2219
2220         if (debug_level >= DEBUG_LEVEL_INFO)
2221                 printk("%s(%d):%s tiocmget() value=%08X\n",
2222                          __FILE__,__LINE__, info->device_name, result );
2223         return result;
2224 }
2225
2226 /* set modem control signals (DTR/RTS)
2227  */
2228 static int tiocmset(struct tty_struct *tty, struct file *file,
2229                     unsigned int set, unsigned int clear)
2230 {
2231         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2232         unsigned long flags;
2233
2234         if (debug_level >= DEBUG_LEVEL_INFO)
2235                 printk("%s(%d):%s tiocmset(%x,%x)\n",
2236                         __FILE__,__LINE__,info->device_name, set, clear);
2237
2238         if (set & TIOCM_RTS)
2239                 info->serial_signals |= SerialSignal_RTS;
2240         if (set & TIOCM_DTR)
2241                 info->serial_signals |= SerialSignal_DTR;
2242         if (clear & TIOCM_RTS)
2243                 info->serial_signals &= ~SerialSignal_RTS;
2244         if (clear & TIOCM_DTR)
2245                 info->serial_signals &= ~SerialSignal_DTR;
2246
2247         spin_lock_irqsave(&info->lock,flags);
2248         set_signals(info);
2249         spin_unlock_irqrestore(&info->lock,flags);
2250
2251         return 0;
2252 }
2253
2254 /* Set or clear transmit break condition
2255  *
2256  * Arguments:           tty             pointer to tty instance data
2257  *                      break_state     -1=set break condition, 0=clear
2258  */
2259 static void mgslpc_break(struct tty_struct *tty, int break_state)
2260 {
2261         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2262         unsigned long flags;
2263         
2264         if (debug_level >= DEBUG_LEVEL_INFO)
2265                 printk("%s(%d):mgslpc_break(%s,%d)\n",
2266                          __FILE__,__LINE__, info->device_name, break_state);
2267                          
2268         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_break"))
2269                 return;
2270
2271         spin_lock_irqsave(&info->lock,flags);
2272         if (break_state == -1)
2273                 set_reg_bits(info, CHA+DAFO, BIT6);
2274         else 
2275                 clear_reg_bits(info, CHA+DAFO, BIT6);
2276         spin_unlock_irqrestore(&info->lock,flags);
2277 }
2278
2279 /* Service an IOCTL request
2280  *      
2281  * Arguments:
2282  * 
2283  *      tty     pointer to tty instance data
2284  *      file    pointer to associated file object for device
2285  *      cmd     IOCTL command code
2286  *      arg     command argument/context
2287  *      
2288  * Return Value:        0 if success, otherwise error code
2289  */
2290 static int mgslpc_ioctl(struct tty_struct *tty, struct file * file,
2291                         unsigned int cmd, unsigned long arg)
2292 {
2293         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2294         
2295         if (debug_level >= DEBUG_LEVEL_INFO)
2296                 printk("%s(%d):mgslpc_ioctl %s cmd=%08X\n", __FILE__,__LINE__,
2297                         info->device_name, cmd );
2298         
2299         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_ioctl"))
2300                 return -ENODEV;
2301
2302         if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
2303             (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
2304                 if (tty->flags & (1 << TTY_IO_ERROR))
2305                     return -EIO;
2306         }
2307
2308         return ioctl_common(info, cmd, arg);
2309 }
2310
2311 static int ioctl_common(MGSLPC_INFO *info, unsigned int cmd, unsigned long arg)
2312 {
2313         int error;
2314         struct mgsl_icount cnow;        /* kernel counter temps */
2315         struct serial_icounter_struct __user *p_cuser;  /* user space */
2316         void __user *argp = (void __user *)arg;
2317         unsigned long flags;
2318         
2319         switch (cmd) {
2320         case MGSL_IOCGPARAMS:
2321                 return get_params(info, argp);
2322         case MGSL_IOCSPARAMS:
2323                 return set_params(info, argp);
2324         case MGSL_IOCGTXIDLE:
2325                 return get_txidle(info, argp);
2326         case MGSL_IOCSTXIDLE:
2327                 return set_txidle(info, (int)arg);
2328         case MGSL_IOCGIF:
2329                 return get_interface(info, argp);
2330         case MGSL_IOCSIF:
2331                 return set_interface(info,(int)arg);
2332         case MGSL_IOCTXENABLE:
2333                 return set_txenable(info,(int)arg);
2334         case MGSL_IOCRXENABLE:
2335                 return set_rxenable(info,(int)arg);
2336         case MGSL_IOCTXABORT:
2337                 return tx_abort(info);
2338         case MGSL_IOCGSTATS:
2339                 return get_stats(info, argp);
2340         case MGSL_IOCWAITEVENT:
2341                 return wait_events(info, argp);
2342         case TIOCMIWAIT:
2343                 return modem_input_wait(info,(int)arg);
2344         case TIOCGICOUNT:
2345                 spin_lock_irqsave(&info->lock,flags);
2346                 cnow = info->icount;
2347                 spin_unlock_irqrestore(&info->lock,flags);
2348                 p_cuser = argp;
2349                 PUT_USER(error,cnow.cts, &p_cuser->cts);
2350                 if (error) return error;
2351                 PUT_USER(error,cnow.dsr, &p_cuser->dsr);
2352                 if (error) return error;
2353                 PUT_USER(error,cnow.rng, &p_cuser->rng);
2354                 if (error) return error;
2355                 PUT_USER(error,cnow.dcd, &p_cuser->dcd);
2356                 if (error) return error;
2357                 PUT_USER(error,cnow.rx, &p_cuser->rx);
2358                 if (error) return error;
2359                 PUT_USER(error,cnow.tx, &p_cuser->tx);
2360                 if (error) return error;
2361                 PUT_USER(error,cnow.frame, &p_cuser->frame);
2362                 if (error) return error;
2363                 PUT_USER(error,cnow.overrun, &p_cuser->overrun);
2364                 if (error) return error;
2365                 PUT_USER(error,cnow.parity, &p_cuser->parity);
2366                 if (error) return error;
2367                 PUT_USER(error,cnow.brk, &p_cuser->brk);
2368                 if (error) return error;
2369                 PUT_USER(error,cnow.buf_overrun, &p_cuser->buf_overrun);
2370                 if (error) return error;
2371                 return 0;
2372         default:
2373                 return -ENOIOCTLCMD;
2374         }
2375         return 0;
2376 }
2377
2378 /* Set new termios settings
2379  *      
2380  * Arguments:
2381  * 
2382  *      tty             pointer to tty structure
2383  *      termios         pointer to buffer to hold returned old termios
2384  */
2385 static void mgslpc_set_termios(struct tty_struct *tty, struct termios *old_termios)
2386 {
2387         MGSLPC_INFO *info = (MGSLPC_INFO *)tty->driver_data;
2388         unsigned long flags;
2389         
2390         if (debug_level >= DEBUG_LEVEL_INFO)
2391                 printk("%s(%d):mgslpc_set_termios %s\n", __FILE__,__LINE__,
2392                         tty->driver->name );
2393         
2394         /* just return if nothing has changed */
2395         if ((tty->termios->c_cflag == old_termios->c_cflag)
2396             && (RELEVANT_IFLAG(tty->termios->c_iflag) 
2397                 == RELEVANT_IFLAG(old_termios->c_iflag)))
2398           return;
2399
2400         mgslpc_change_params(info);
2401
2402         /* Handle transition to B0 status */
2403         if (old_termios->c_cflag & CBAUD &&
2404             !(tty->termios->c_cflag & CBAUD)) {
2405                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
2406                 spin_lock_irqsave(&info->lock,flags);
2407                 set_signals(info);
2408                 spin_unlock_irqrestore(&info->lock,flags);
2409         }
2410         
2411         /* Handle transition away from B0 status */
2412         if (!(old_termios->c_cflag & CBAUD) &&
2413             tty->termios->c_cflag & CBAUD) {
2414                 info->serial_signals |= SerialSignal_DTR;
2415                 if (!(tty->termios->c_cflag & CRTSCTS) || 
2416                     !test_bit(TTY_THROTTLED, &tty->flags)) {
2417                         info->serial_signals |= SerialSignal_RTS;
2418                 }
2419                 spin_lock_irqsave(&info->lock,flags);
2420                 set_signals(info);
2421                 spin_unlock_irqrestore(&info->lock,flags);
2422         }
2423         
2424         /* Handle turning off CRTSCTS */
2425         if (old_termios->c_cflag & CRTSCTS &&
2426             !(tty->termios->c_cflag & CRTSCTS)) {
2427                 tty->hw_stopped = 0;
2428                 tx_release(tty);
2429         }
2430 }
2431
2432 static void mgslpc_close(struct tty_struct *tty, struct file * filp)
2433 {
2434         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2435
2436         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_close"))
2437                 return;
2438         
2439         if (debug_level >= DEBUG_LEVEL_INFO)
2440                 printk("%s(%d):mgslpc_close(%s) entry, count=%d\n",
2441                          __FILE__,__LINE__, info->device_name, info->count);
2442                          
2443         if (!info->count)
2444                 return;
2445
2446         if (tty_hung_up_p(filp))
2447                 goto cleanup;
2448                         
2449         if ((tty->count == 1) && (info->count != 1)) {
2450                 /*
2451                  * tty->count is 1 and the tty structure will be freed.
2452                  * info->count should be one in this case.
2453                  * if it's not, correct it so that the port is shutdown.
2454                  */
2455                 printk("mgslpc_close: bad refcount; tty->count is 1, "
2456                        "info->count is %d\n", info->count);
2457                 info->count = 1;
2458         }
2459         
2460         info->count--;
2461         
2462         /* if at least one open remaining, leave hardware active */
2463         if (info->count)
2464                 goto cleanup;
2465         
2466         info->flags |= ASYNC_CLOSING;
2467         
2468         /* set tty->closing to notify line discipline to 
2469          * only process XON/XOFF characters. Only the N_TTY
2470          * discipline appears to use this (ppp does not).
2471          */
2472         tty->closing = 1;
2473         
2474         /* wait for transmit data to clear all layers */
2475         
2476         if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) {
2477                 if (debug_level >= DEBUG_LEVEL_INFO)
2478                         printk("%s(%d):mgslpc_close(%s) calling tty_wait_until_sent\n",
2479                                  __FILE__,__LINE__, info->device_name );
2480                 tty_wait_until_sent(tty, info->closing_wait);
2481         }
2482                 
2483         if (info->flags & ASYNC_INITIALIZED)
2484                 mgslpc_wait_until_sent(tty, info->timeout);
2485
2486         if (tty->driver->flush_buffer)
2487                 tty->driver->flush_buffer(tty);
2488
2489         ldisc_flush_buffer(tty);
2490                 
2491         shutdown(info);
2492         
2493         tty->closing = 0;
2494         info->tty = NULL;
2495         
2496         if (info->blocked_open) {
2497                 if (info->close_delay) {
2498                         msleep_interruptible(jiffies_to_msecs(info->close_delay));
2499                 }
2500                 wake_up_interruptible(&info->open_wait);
2501         }
2502         
2503         info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
2504                          
2505         wake_up_interruptible(&info->close_wait);
2506         
2507 cleanup:                        
2508         if (debug_level >= DEBUG_LEVEL_INFO)
2509                 printk("%s(%d):mgslpc_close(%s) exit, count=%d\n", __FILE__,__LINE__,
2510                         tty->driver->name, info->count);
2511 }
2512
2513 /* Wait until the transmitter is empty.
2514  */
2515 static void mgslpc_wait_until_sent(struct tty_struct *tty, int timeout)
2516 {
2517         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2518         unsigned long orig_jiffies, char_time;
2519
2520         if (!info )
2521                 return;
2522
2523         if (debug_level >= DEBUG_LEVEL_INFO)
2524                 printk("%s(%d):mgslpc_wait_until_sent(%s) entry\n",
2525                          __FILE__,__LINE__, info->device_name );
2526       
2527         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_wait_until_sent"))
2528                 return;
2529
2530         if (!(info->flags & ASYNC_INITIALIZED))
2531                 goto exit;
2532          
2533         orig_jiffies = jiffies;
2534       
2535         /* Set check interval to 1/5 of estimated time to
2536          * send a character, and make it at least 1. The check
2537          * interval should also be less than the timeout.
2538          * Note: use tight timings here to satisfy the NIST-PCTS.
2539          */ 
2540        
2541         if ( info->params.data_rate ) {
2542                 char_time = info->timeout/(32 * 5);
2543                 if (!char_time)
2544                         char_time++;
2545         } else
2546                 char_time = 1;
2547                 
2548         if (timeout)
2549                 char_time = min_t(unsigned long, char_time, timeout);
2550                 
2551         if (info->params.mode == MGSL_MODE_HDLC) {
2552                 while (info->tx_active) {
2553                         msleep_interruptible(jiffies_to_msecs(char_time));
2554                         if (signal_pending(current))
2555                                 break;
2556                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
2557                                 break;
2558                 }
2559         } else {
2560                 while ((info->tx_count || info->tx_active) &&
2561                         info->tx_enabled) {
2562                         msleep_interruptible(jiffies_to_msecs(char_time));
2563                         if (signal_pending(current))
2564                                 break;
2565                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
2566                                 break;
2567                 }
2568         }
2569       
2570 exit:
2571         if (debug_level >= DEBUG_LEVEL_INFO)
2572                 printk("%s(%d):mgslpc_wait_until_sent(%s) exit\n",
2573                          __FILE__,__LINE__, info->device_name );
2574 }
2575
2576 /* Called by tty_hangup() when a hangup is signaled.
2577  * This is the same as closing all open files for the port.
2578  */
2579 static void mgslpc_hangup(struct tty_struct *tty)
2580 {
2581         MGSLPC_INFO * info = (MGSLPC_INFO *)tty->driver_data;
2582         
2583         if (debug_level >= DEBUG_LEVEL_INFO)
2584                 printk("%s(%d):mgslpc_hangup(%s)\n",
2585                          __FILE__,__LINE__, info->device_name );
2586                          
2587         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_hangup"))
2588                 return;
2589
2590         mgslpc_flush_buffer(tty);
2591         shutdown(info);
2592         
2593         info->count = 0;        
2594         info->flags &= ~ASYNC_NORMAL_ACTIVE;
2595         info->tty = NULL;
2596
2597         wake_up_interruptible(&info->open_wait);
2598 }
2599
2600 /* Block the current process until the specified port
2601  * is ready to be opened.
2602  */
2603 static int block_til_ready(struct tty_struct *tty, struct file *filp,
2604                            MGSLPC_INFO *info)
2605 {
2606         DECLARE_WAITQUEUE(wait, current);
2607         int             retval;
2608         int             do_clocal = 0, extra_count = 0;
2609         unsigned long   flags;
2610         
2611         if (debug_level >= DEBUG_LEVEL_INFO)
2612                 printk("%s(%d):block_til_ready on %s\n",
2613                          __FILE__,__LINE__, tty->driver->name );
2614
2615         if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){
2616                 /* nonblock mode is set or port is not enabled */
2617                 /* just verify that callout device is not active */
2618                 info->flags |= ASYNC_NORMAL_ACTIVE;
2619                 return 0;
2620         }
2621
2622         if (tty->termios->c_cflag & CLOCAL)
2623                 do_clocal = 1;
2624
2625         /* Wait for carrier detect and the line to become
2626          * free (i.e., not in use by the callout).  While we are in
2627          * this loop, info->count is dropped by one, so that
2628          * mgslpc_close() knows when to free things.  We restore it upon
2629          * exit, either normal or abnormal.
2630          */
2631          
2632         retval = 0;
2633         add_wait_queue(&info->open_wait, &wait);
2634         
2635         if (debug_level >= DEBUG_LEVEL_INFO)
2636                 printk("%s(%d):block_til_ready before block on %s count=%d\n",
2637                          __FILE__,__LINE__, tty->driver->name, info->count );
2638
2639         spin_lock_irqsave(&info->lock, flags);
2640         if (!tty_hung_up_p(filp)) {
2641                 extra_count = 1;
2642                 info->count--;
2643         }
2644         spin_unlock_irqrestore(&info->lock, flags);
2645         info->blocked_open++;
2646         
2647         while (1) {
2648                 if ((tty->termios->c_cflag & CBAUD)) {
2649                         spin_lock_irqsave(&info->lock,flags);
2650                         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
2651                         set_signals(info);
2652                         spin_unlock_irqrestore(&info->lock,flags);
2653                 }
2654                 
2655                 set_current_state(TASK_INTERRUPTIBLE);
2656                 
2657                 if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)){
2658                         retval = (info->flags & ASYNC_HUP_NOTIFY) ?
2659                                         -EAGAIN : -ERESTARTSYS;
2660                         break;
2661                 }
2662                 
2663                 spin_lock_irqsave(&info->lock,flags);
2664                 get_signals(info);
2665                 spin_unlock_irqrestore(&info->lock,flags);
2666                 
2667                 if (!(info->flags & ASYNC_CLOSING) &&
2668                     (do_clocal || (info->serial_signals & SerialSignal_DCD)) ) {
2669                         break;
2670                 }
2671                         
2672                 if (signal_pending(current)) {
2673                         retval = -ERESTARTSYS;
2674                         break;
2675                 }
2676                 
2677                 if (debug_level >= DEBUG_LEVEL_INFO)
2678                         printk("%s(%d):block_til_ready blocking on %s count=%d\n",
2679                                  __FILE__,__LINE__, tty->driver->name, info->count );
2680                                  
2681                 schedule();
2682         }
2683         
2684         set_current_state(TASK_RUNNING);
2685         remove_wait_queue(&info->open_wait, &wait);
2686         
2687         if (extra_count)
2688                 info->count++;
2689         info->blocked_open--;
2690         
2691         if (debug_level >= DEBUG_LEVEL_INFO)
2692                 printk("%s(%d):block_til_ready after blocking on %s count=%d\n",
2693                          __FILE__,__LINE__, tty->driver->name, info->count );
2694                          
2695         if (!retval)
2696                 info->flags |= ASYNC_NORMAL_ACTIVE;
2697                 
2698         return retval;
2699 }
2700
2701 static int mgslpc_open(struct tty_struct *tty, struct file * filp)
2702 {
2703         MGSLPC_INFO     *info;
2704         int                     retval, line;
2705         unsigned long flags;
2706
2707         /* verify range of specified line number */     
2708         line = tty->index;
2709         if ((line < 0) || (line >= mgslpc_device_count)) {
2710                 printk("%s(%d):mgslpc_open with invalid line #%d.\n",
2711                         __FILE__,__LINE__,line);
2712                 return -ENODEV;
2713         }
2714
2715         /* find the info structure for the specified line */
2716         info = mgslpc_device_list;
2717         while(info && info->line != line)
2718                 info = info->next_device;
2719         if (mgslpc_paranoia_check(info, tty->name, "mgslpc_open"))
2720                 return -ENODEV;
2721         
2722         tty->driver_data = info;
2723         info->tty = tty;
2724                 
2725         if (debug_level >= DEBUG_LEVEL_INFO)
2726                 printk("%s(%d):mgslpc_open(%s), old ref count = %d\n",
2727                          __FILE__,__LINE__,tty->driver->name, info->count);
2728
2729         /* If port is closing, signal caller to try again */
2730         if (tty_hung_up_p(filp) || info->flags & ASYNC_CLOSING){
2731                 if (info->flags & ASYNC_CLOSING)
2732                         interruptible_sleep_on(&info->close_wait);
2733                 retval = ((info->flags & ASYNC_HUP_NOTIFY) ?
2734                         -EAGAIN : -ERESTARTSYS);
2735                 goto cleanup;
2736         }
2737         
2738         info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
2739
2740         spin_lock_irqsave(&info->netlock, flags);
2741         if (info->netcount) {
2742                 retval = -EBUSY;
2743                 spin_unlock_irqrestore(&info->netlock, flags);
2744                 goto cleanup;
2745         }
2746         info->count++;
2747         spin_unlock_irqrestore(&info->netlock, flags);
2748
2749         if (info->count == 1) {
2750                 /* 1st open on this device, init hardware */
2751                 retval = startup(info);
2752                 if (retval < 0)
2753                         goto cleanup;
2754         }
2755
2756         retval = block_til_ready(tty, filp, info);
2757         if (retval) {
2758                 if (debug_level >= DEBUG_LEVEL_INFO)
2759                         printk("%s(%d):block_til_ready(%s) returned %d\n",
2760                                  __FILE__,__LINE__, info->device_name, retval);
2761                 goto cleanup;
2762         }
2763
2764         if (debug_level >= DEBUG_LEVEL_INFO)
2765                 printk("%s(%d):mgslpc_open(%s) success\n",
2766                          __FILE__,__LINE__, info->device_name);
2767         retval = 0;
2768         
2769 cleanup:                        
2770         if (retval) {
2771                 if (tty->count == 1)
2772                         info->tty = NULL; /* tty layer will release tty struct */
2773                 if(info->count)
2774                         info->count--;
2775         }
2776         
2777         return retval;
2778 }
2779
2780 /*
2781  * /proc fs routines....
2782  */
2783
2784 static inline int line_info(char *buf, MGSLPC_INFO *info)
2785 {
2786         char    stat_buf[30];
2787         int     ret;
2788         unsigned long flags;
2789
2790         ret = sprintf(buf, "%s:io:%04X irq:%d",
2791                       info->device_name, info->io_base, info->irq_level);
2792
2793         /* output current serial signal states */
2794         spin_lock_irqsave(&info->lock,flags);
2795         get_signals(info);
2796         spin_unlock_irqrestore(&info->lock,flags);
2797         
2798         stat_buf[0] = 0;
2799         stat_buf[1] = 0;
2800         if (info->serial_signals & SerialSignal_RTS)
2801                 strcat(stat_buf, "|RTS");
2802         if (info->serial_signals & SerialSignal_CTS)
2803                 strcat(stat_buf, "|CTS");
2804         if (info->serial_signals & SerialSignal_DTR)
2805                 strcat(stat_buf, "|DTR");
2806         if (info->serial_signals & SerialSignal_DSR)
2807                 strcat(stat_buf, "|DSR");
2808         if (info->serial_signals & SerialSignal_DCD)
2809                 strcat(stat_buf, "|CD");
2810         if (info->serial_signals & SerialSignal_RI)
2811                 strcat(stat_buf, "|RI");
2812
2813         if (info->params.mode == MGSL_MODE_HDLC) {
2814                 ret += sprintf(buf+ret, " HDLC txok:%d rxok:%d",
2815                               info->icount.txok, info->icount.rxok);
2816                 if (info->icount.txunder)
2817                         ret += sprintf(buf+ret, " txunder:%d", info->icount.txunder);
2818                 if (info->icount.txabort)
2819                         ret += sprintf(buf+ret, " txabort:%d", info->icount.txabort);
2820                 if (info->icount.rxshort)
2821                         ret += sprintf(buf+ret, " rxshort:%d", info->icount.rxshort);   
2822                 if (info->icount.rxlong)
2823                         ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxlong);
2824                 if (info->icount.rxover)
2825                         ret += sprintf(buf+ret, " rxover:%d", info->icount.rxover);
2826                 if (info->icount.rxcrc)
2827                         ret += sprintf(buf+ret, " rxcrc:%d", info->icount.rxcrc);
2828         } else {
2829                 ret += sprintf(buf+ret, " ASYNC tx:%d rx:%d",
2830                               info->icount.tx, info->icount.rx);
2831                 if (info->icount.frame)
2832                         ret += sprintf(buf+ret, " fe:%d", info->icount.frame);
2833                 if (info->icount.parity)
2834                         ret += sprintf(buf+ret, " pe:%d", info->icount.parity);
2835                 if (info->icount.brk)
2836                         ret += sprintf(buf+ret, " brk:%d", info->icount.brk);   
2837                 if (info->icount.overrun)
2838                         ret += sprintf(buf+ret, " oe:%d", info->icount.overrun);
2839         }
2840         
2841         /* Append serial signal status to end */
2842         ret += sprintf(buf+ret, " %s\n", stat_buf+1);
2843         
2844         ret += sprintf(buf+ret, "txactive=%d bh_req=%d bh_run=%d pending_bh=%x\n",
2845                        info->tx_active,info->bh_requested,info->bh_running,
2846                        info->pending_bh);
2847         
2848         return ret;
2849 }
2850
2851 /* Called to print information about devices
2852  */
2853 static int mgslpc_read_proc(char *page, char **start, off_t off, int count,
2854                  int *eof, void *data)
2855 {
2856         int len = 0, l;
2857         off_t   begin = 0;
2858         MGSLPC_INFO *info;
2859         
2860         len += sprintf(page, "synclink driver:%s\n", driver_version);
2861         
2862         info = mgslpc_device_list;
2863         while( info ) {
2864                 l = line_info(page + len, info);
2865                 len += l;
2866                 if (len+begin > off+count)
2867                         goto done;
2868                 if (len+begin < off) {
2869                         begin += len;
2870                         len = 0;
2871                 }
2872                 info = info->next_device;
2873         }
2874
2875         *eof = 1;
2876 done:
2877         if (off >= len+begin)
2878                 return 0;
2879         *start = page + (off-begin);
2880         return ((count < begin+len-off) ? count : begin+len-off);
2881 }
2882
2883 static int rx_alloc_buffers(MGSLPC_INFO *info)
2884 {
2885         /* each buffer has header and data */
2886         info->rx_buf_size = sizeof(RXBUF) + info->max_frame_size;
2887
2888         /* calculate total allocation size for 8 buffers */
2889         info->rx_buf_total_size = info->rx_buf_size * 8;
2890
2891         /* limit total allocated memory */
2892         if (info->rx_buf_total_size > 0x10000)
2893                 info->rx_buf_total_size = 0x10000;
2894
2895         /* calculate number of buffers */
2896         info->rx_buf_count = info->rx_buf_total_size / info->rx_buf_size;
2897
2898         info->rx_buf = kmalloc(info->rx_buf_total_size, GFP_KERNEL);
2899         if (info->rx_buf == NULL)
2900                 return -ENOMEM;
2901
2902         rx_reset_buffers(info);
2903         return 0;
2904 }
2905
2906 static void rx_free_buffers(MGSLPC_INFO *info)
2907 {
2908         kfree(info->rx_buf);
2909         info->rx_buf = NULL;
2910 }
2911
2912 static int claim_resources(MGSLPC_INFO *info)
2913 {
2914         if (rx_alloc_buffers(info) < 0 ) {
2915                 printk( "Cant allocate rx buffer %s\n", info->device_name);
2916                 release_resources(info);
2917                 return -ENODEV;
2918         }       
2919         return 0;
2920 }
2921
2922 static void release_resources(MGSLPC_INFO *info)
2923 {
2924         if (debug_level >= DEBUG_LEVEL_INFO)
2925                 printk("release_resources(%s)\n", info->device_name);
2926         rx_free_buffers(info);
2927 }
2928
2929 /* Add the specified device instance data structure to the
2930  * global linked list of devices and increment the device count.
2931  *      
2932  * Arguments:           info    pointer to device instance data
2933  */
2934 static void mgslpc_add_device(MGSLPC_INFO *info)
2935 {
2936         info->next_device = NULL;
2937         info->line = mgslpc_device_count;
2938         sprintf(info->device_name,"ttySLP%d",info->line);
2939         
2940         if (info->line < MAX_DEVICE_COUNT) {
2941                 if (maxframe[info->line])
2942                         info->max_frame_size = maxframe[info->line];
2943                 info->dosyncppp = dosyncppp[info->line];
2944         }
2945
2946         mgslpc_device_count++;
2947         
2948         if (!mgslpc_device_list)
2949                 mgslpc_device_list = info;
2950         else {  
2951                 MGSLPC_INFO *current_dev = mgslpc_device_list;
2952                 while( current_dev->next_device )
2953                         current_dev = current_dev->next_device;
2954                 current_dev->next_device = info;
2955         }
2956         
2957         if (info->max_frame_size < 4096)
2958                 info->max_frame_size = 4096;
2959         else if (info->max_frame_size > 65535)
2960                 info->max_frame_size = 65535;
2961         
2962         printk( "SyncLink PC Card %s:IO=%04X IRQ=%d\n",
2963                 info->device_name, info->io_base, info->irq_level);
2964
2965 #ifdef CONFIG_HDLC
2966         hdlcdev_init(info);
2967 #endif
2968 }
2969
2970 static void mgslpc_remove_device(MGSLPC_INFO *remove_info)
2971 {
2972         MGSLPC_INFO *info = mgslpc_device_list;
2973         MGSLPC_INFO *last = NULL;
2974
2975         while(info) {
2976                 if (info == remove_info) {
2977                         if (last)
2978                                 last->next_device = info->next_device;
2979                         else
2980                                 mgslpc_device_list = info->next_device;
2981 #ifdef CONFIG_HDLC
2982                         hdlcdev_exit(info);
2983 #endif
2984                         release_resources(info);
2985                         kfree(info);
2986                         mgslpc_device_count--;
2987                         return;
2988                 }
2989                 last = info;
2990                 info = info->next_device;
2991         }
2992 }
2993
2994 static struct pcmcia_device_id mgslpc_ids[] = {
2995         PCMCIA_DEVICE_MANF_CARD(0x02c5, 0x0050),
2996         PCMCIA_DEVICE_NULL
2997 };
2998 MODULE_DEVICE_TABLE(pcmcia, mgslpc_ids);
2999
3000 static struct pcmcia_driver mgslpc_driver = {
3001         .owner          = THIS_MODULE,
3002         .drv            = {
3003                 .name   = "synclink_cs",
3004         },
3005         .probe          = mgslpc_probe,
3006         .remove         = mgslpc_detach,
3007         .id_table       = mgslpc_ids,
3008         .suspend        = mgslpc_suspend,
3009         .resume         = mgslpc_resume,
3010 };
3011
3012 static const struct tty_operations mgslpc_ops = {
3013         .open = mgslpc_open,
3014         .close = mgslpc_close,
3015         .write = mgslpc_write,
3016         .put_char = mgslpc_put_char,
3017         .flush_chars = mgslpc_flush_chars,
3018         .write_room = mgslpc_write_room,
3019         .chars_in_buffer = mgslpc_chars_in_buffer,
3020         .flush_buffer = mgslpc_flush_buffer,
3021         .ioctl = mgslpc_ioctl,
3022         .throttle = mgslpc_throttle,
3023         .unthrottle = mgslpc_unthrottle,
3024         .send_xchar = mgslpc_send_xchar,
3025         .break_ctl = mgslpc_break,
3026         .wait_until_sent = mgslpc_wait_until_sent,
3027         .read_proc = mgslpc_read_proc,
3028         .set_termios = mgslpc_set_termios,
3029         .stop = tx_pause,
3030         .start = tx_release,
3031         .hangup = mgslpc_hangup,
3032         .tiocmget = tiocmget,
3033         .tiocmset = tiocmset,
3034 };
3035
3036 static void synclink_cs_cleanup(void)
3037 {
3038         int rc;
3039
3040         printk("Unloading %s: version %s\n", driver_name, driver_version);
3041
3042         while(mgslpc_device_list)
3043                 mgslpc_remove_device(mgslpc_device_list);
3044
3045         if (serial_driver) {
3046                 if ((rc = tty_unregister_driver(serial_driver)))
3047                         printk("%s(%d) failed to unregister tty driver err=%d\n",
3048                                __FILE__,__LINE__,rc);
3049                 put_tty_driver(serial_driver);
3050         }
3051
3052         pcmcia_unregister_driver(&mgslpc_driver);
3053 }
3054
3055 static int __init synclink_cs_init(void)
3056 {
3057     int rc;
3058
3059     if (break_on_load) {
3060             mgslpc_get_text_ptr();
3061             BREAKPOINT();
3062     }
3063
3064     printk("%s %s\n", driver_name, driver_version);
3065
3066     if ((rc = pcmcia_register_driver(&mgslpc_driver)) < 0)
3067             return rc;
3068
3069     serial_driver = alloc_tty_driver(MAX_DEVICE_COUNT);
3070     if (!serial_driver) {
3071             rc = -ENOMEM;
3072             goto error;
3073     }
3074
3075     /* Initialize the tty_driver structure */
3076         
3077     serial_driver->owner = THIS_MODULE;
3078     serial_driver->driver_name = "synclink_cs";
3079     serial_driver->name = "ttySLP";
3080     serial_driver->major = ttymajor;
3081     serial_driver->minor_start = 64;
3082     serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
3083     serial_driver->subtype = SERIAL_TYPE_NORMAL;
3084     serial_driver->init_termios = tty_std_termios;
3085     serial_driver->init_termios.c_cflag =
3086             B9600 | CS8 | CREAD | HUPCL | CLOCAL;
3087     serial_driver->flags = TTY_DRIVER_REAL_RAW;
3088     tty_set_operations(serial_driver, &mgslpc_ops);
3089
3090     if ((rc = tty_register_driver(serial_driver)) < 0) {
3091             printk("%s(%d):Couldn't register serial driver\n",
3092                    __FILE__,__LINE__);
3093             put_tty_driver(serial_driver);
3094             serial_driver = NULL;
3095             goto error;
3096     }
3097                         
3098     printk("%s %s, tty&