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