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