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