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