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