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