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