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