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