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