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