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