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