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