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