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