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