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