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