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