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