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