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