Merge branch 'clk-imx' into clk-next
[platform/kernel/linux-starfive.git] / drivers / tty / synclink_gt.c
1 // SPDX-License-Identifier: GPL-1.0+
2 /*
3  * Device driver for Microgate SyncLink GT serial adapters.
4  *
5  * written by Paul Fulghum for Microgate Corporation
6  * paulkf@microgate.com
7  *
8  * Microgate and SyncLink are trademarks of Microgate Corporation
9  *
10  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
11  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
12  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
14  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
15  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
16  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
17  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
18  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
19  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
20  * OF THE POSSIBILITY OF SUCH DAMAGE.
21  */
22
23 /*
24  * DEBUG OUTPUT DEFINITIONS
25  *
26  * uncomment lines below to enable specific types of debug output
27  *
28  * DBGINFO   information - most verbose output
29  * DBGERR    serious errors
30  * DBGBH     bottom half service routine debugging
31  * DBGISR    interrupt service routine debugging
32  * DBGDATA   output receive and transmit data
33  * DBGTBUF   output transmit DMA buffers and registers
34  * DBGRBUF   output receive DMA buffers and registers
35  */
36
37 #define DBGINFO(fmt) if (debug_level >= DEBUG_LEVEL_INFO) printk fmt
38 #define DBGERR(fmt) if (debug_level >= DEBUG_LEVEL_ERROR) printk fmt
39 #define DBGBH(fmt) if (debug_level >= DEBUG_LEVEL_BH) printk fmt
40 #define DBGISR(fmt) if (debug_level >= DEBUG_LEVEL_ISR) printk fmt
41 #define DBGDATA(info, buf, size, label) if (debug_level >= DEBUG_LEVEL_DATA) trace_block((info), (buf), (size), (label))
42 /*#define DBGTBUF(info) dump_tbufs(info)*/
43 /*#define DBGRBUF(info) dump_rbufs(info)*/
44
45
46 #include <linux/module.h>
47 #include <linux/errno.h>
48 #include <linux/signal.h>
49 #include <linux/sched.h>
50 #include <linux/timer.h>
51 #include <linux/interrupt.h>
52 #include <linux/pci.h>
53 #include <linux/tty.h>
54 #include <linux/tty_flip.h>
55 #include <linux/serial.h>
56 #include <linux/major.h>
57 #include <linux/string.h>
58 #include <linux/fcntl.h>
59 #include <linux/ptrace.h>
60 #include <linux/ioport.h>
61 #include <linux/mm.h>
62 #include <linux/seq_file.h>
63 #include <linux/slab.h>
64 #include <linux/netdevice.h>
65 #include <linux/vmalloc.h>
66 #include <linux/init.h>
67 #include <linux/delay.h>
68 #include <linux/ioctl.h>
69 #include <linux/termios.h>
70 #include <linux/bitops.h>
71 #include <linux/workqueue.h>
72 #include <linux/hdlc.h>
73 #include <linux/synclink.h>
74
75 #include <asm/io.h>
76 #include <asm/irq.h>
77 #include <asm/dma.h>
78 #include <asm/types.h>
79 #include <linux/uaccess.h>
80
81 #if defined(CONFIG_HDLC) || (defined(CONFIG_HDLC_MODULE) && defined(CONFIG_SYNCLINK_GT_MODULE))
82 #define SYNCLINK_GENERIC_HDLC 1
83 #else
84 #define SYNCLINK_GENERIC_HDLC 0
85 #endif
86
87 /*
88  * module identification
89  */
90 static char *driver_name     = "SyncLink GT";
91 static char *slgt_driver_name = "synclink_gt";
92 static char *tty_dev_prefix  = "ttySLG";
93 MODULE_LICENSE("GPL");
94 #define MAX_DEVICES 32
95
96 static const struct pci_device_id pci_table[] = {
97         {PCI_VENDOR_ID_MICROGATE, SYNCLINK_GT_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
98         {PCI_VENDOR_ID_MICROGATE, SYNCLINK_GT2_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
99         {PCI_VENDOR_ID_MICROGATE, SYNCLINK_GT4_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
100         {PCI_VENDOR_ID_MICROGATE, SYNCLINK_AC_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
101         {0,}, /* terminate list */
102 };
103 MODULE_DEVICE_TABLE(pci, pci_table);
104
105 static int  init_one(struct pci_dev *dev,const struct pci_device_id *ent);
106 static void remove_one(struct pci_dev *dev);
107 static struct pci_driver pci_driver = {
108         .name           = "synclink_gt",
109         .id_table       = pci_table,
110         .probe          = init_one,
111         .remove         = remove_one,
112 };
113
114 static bool pci_registered;
115
116 /*
117  * module configuration and status
118  */
119 static struct slgt_info *slgt_device_list;
120 static int slgt_device_count;
121
122 static int ttymajor;
123 static int debug_level;
124 static int maxframe[MAX_DEVICES];
125
126 module_param(ttymajor, int, 0);
127 module_param(debug_level, int, 0);
128 module_param_array(maxframe, int, NULL, 0);
129
130 MODULE_PARM_DESC(ttymajor, "TTY major device number override: 0=auto assigned");
131 MODULE_PARM_DESC(debug_level, "Debug syslog output: 0=disabled, 1 to 5=increasing detail");
132 MODULE_PARM_DESC(maxframe, "Maximum frame size used by device (4096 to 65535)");
133
134 /*
135  * tty support and callbacks
136  */
137 static struct tty_driver *serial_driver;
138
139 static void wait_until_sent(struct tty_struct *tty, int timeout);
140 static void flush_buffer(struct tty_struct *tty);
141 static void tx_release(struct tty_struct *tty);
142
143 /*
144  * generic HDLC support
145  */
146 #define dev_to_port(D) (dev_to_hdlc(D)->priv)
147
148
149 /*
150  * device specific structures, macros and functions
151  */
152
153 #define SLGT_MAX_PORTS 4
154 #define SLGT_REG_SIZE  256
155
156 /*
157  * conditional wait facility
158  */
159 struct cond_wait {
160         struct cond_wait *next;
161         wait_queue_head_t q;
162         wait_queue_entry_t wait;
163         unsigned int data;
164 };
165 static void flush_cond_wait(struct cond_wait **head);
166
167 /*
168  * DMA buffer descriptor and access macros
169  */
170 struct slgt_desc
171 {
172         __le16 count;
173         __le16 status;
174         __le32 pbuf;  /* physical address of data buffer */
175         __le32 next;  /* physical address of next descriptor */
176
177         /* driver book keeping */
178         char *buf;          /* virtual  address of data buffer */
179         unsigned int pdesc; /* physical address of this descriptor */
180         dma_addr_t buf_dma_addr;
181         unsigned short buf_count;
182 };
183
184 #define set_desc_buffer(a,b) (a).pbuf = cpu_to_le32((unsigned int)(b))
185 #define set_desc_next(a,b) (a).next   = cpu_to_le32((unsigned int)(b))
186 #define set_desc_count(a,b)(a).count  = cpu_to_le16((unsigned short)(b))
187 #define set_desc_eof(a,b)  (a).status = cpu_to_le16((b) ? (le16_to_cpu((a).status) | BIT0) : (le16_to_cpu((a).status) & ~BIT0))
188 #define set_desc_status(a, b) (a).status = cpu_to_le16((unsigned short)(b))
189 #define desc_count(a)      (le16_to_cpu((a).count))
190 #define desc_status(a)     (le16_to_cpu((a).status))
191 #define desc_complete(a)   (le16_to_cpu((a).status) & BIT15)
192 #define desc_eof(a)        (le16_to_cpu((a).status) & BIT2)
193 #define desc_crc_error(a)  (le16_to_cpu((a).status) & BIT1)
194 #define desc_abort(a)      (le16_to_cpu((a).status) & BIT0)
195 #define desc_residue(a)    ((le16_to_cpu((a).status) & 0x38) >> 3)
196
197 struct _input_signal_events {
198         int ri_up;
199         int ri_down;
200         int dsr_up;
201         int dsr_down;
202         int dcd_up;
203         int dcd_down;
204         int cts_up;
205         int cts_down;
206 };
207
208 /*
209  * device instance data structure
210  */
211 struct slgt_info {
212         void *if_ptr;           /* General purpose pointer (used by SPPP) */
213         struct tty_port port;
214
215         struct slgt_info *next_device;  /* device list link */
216
217         char device_name[25];
218         struct pci_dev *pdev;
219
220         int port_count;  /* count of ports on adapter */
221         int adapter_num; /* adapter instance number */
222         int port_num;    /* port instance number */
223
224         /* array of pointers to port contexts on this adapter */
225         struct slgt_info *port_array[SLGT_MAX_PORTS];
226
227         int                     line;           /* tty line instance number */
228
229         struct mgsl_icount      icount;
230
231         int                     timeout;
232         int                     x_char;         /* xon/xoff character */
233         unsigned int            read_status_mask;
234         unsigned int            ignore_status_mask;
235
236         wait_queue_head_t       status_event_wait_q;
237         wait_queue_head_t       event_wait_q;
238         struct timer_list       tx_timer;
239         struct timer_list       rx_timer;
240
241         unsigned int            gpio_present;
242         struct cond_wait        *gpio_wait_q;
243
244         spinlock_t lock;        /* spinlock for synchronizing with ISR */
245
246         struct work_struct task;
247         u32 pending_bh;
248         bool bh_requested;
249         bool bh_running;
250
251         int isr_overflow;
252         bool irq_requested;     /* true if IRQ requested */
253         bool irq_occurred;      /* for diagnostics use */
254
255         /* device configuration */
256
257         unsigned int bus_type;
258         unsigned int irq_level;
259         unsigned long irq_flags;
260
261         unsigned char __iomem * reg_addr;  /* memory mapped registers address */
262         u32 phys_reg_addr;
263         bool reg_addr_requested;
264
265         MGSL_PARAMS params;       /* communications parameters */
266         u32 idle_mode;
267         u32 max_frame_size;       /* as set by device config */
268
269         unsigned int rbuf_fill_level;
270         unsigned int rx_pio;
271         unsigned int if_mode;
272         unsigned int base_clock;
273         unsigned int xsync;
274         unsigned int xctrl;
275
276         /* device status */
277
278         bool rx_enabled;
279         bool rx_restart;
280
281         bool tx_enabled;
282         bool tx_active;
283
284         unsigned char signals;    /* serial signal states */
285         int init_error;  /* initialization error */
286
287         unsigned char *tx_buf;
288         int tx_count;
289
290         char *flag_buf;
291         bool drop_rts_on_tx_done;
292         struct  _input_signal_events    input_signal_events;
293
294         int dcd_chkcount;       /* check counts to prevent */
295         int cts_chkcount;       /* too many IRQs if a signal */
296         int dsr_chkcount;       /* is floating */
297         int ri_chkcount;
298
299         char *bufs;             /* virtual address of DMA buffer lists */
300         dma_addr_t bufs_dma_addr; /* physical address of buffer descriptors */
301
302         unsigned int rbuf_count;
303         struct slgt_desc *rbufs;
304         unsigned int rbuf_current;
305         unsigned int rbuf_index;
306         unsigned int rbuf_fill_index;
307         unsigned short rbuf_fill_count;
308
309         unsigned int tbuf_count;
310         struct slgt_desc *tbufs;
311         unsigned int tbuf_current;
312         unsigned int tbuf_start;
313
314         unsigned char *tmp_rbuf;
315         unsigned int tmp_rbuf_count;
316
317         /* SPPP/Cisco HDLC device parts */
318
319         int netcount;
320         spinlock_t netlock;
321 #if SYNCLINK_GENERIC_HDLC
322         struct net_device *netdev;
323 #endif
324
325 };
326
327 static MGSL_PARAMS default_params = {
328         .mode            = MGSL_MODE_HDLC,
329         .loopback        = 0,
330         .flags           = HDLC_FLAG_UNDERRUN_ABORT15,
331         .encoding        = HDLC_ENCODING_NRZI_SPACE,
332         .clock_speed     = 0,
333         .addr_filter     = 0xff,
334         .crc_type        = HDLC_CRC_16_CCITT,
335         .preamble_length = HDLC_PREAMBLE_LENGTH_8BITS,
336         .preamble        = HDLC_PREAMBLE_PATTERN_NONE,
337         .data_rate       = 9600,
338         .data_bits       = 8,
339         .stop_bits       = 1,
340         .parity          = ASYNC_PARITY_NONE
341 };
342
343
344 #define BH_RECEIVE  1
345 #define BH_TRANSMIT 2
346 #define BH_STATUS   4
347 #define IO_PIN_SHUTDOWN_LIMIT 100
348
349 #define DMABUFSIZE 256
350 #define DESC_LIST_SIZE 4096
351
352 #define MASK_PARITY  BIT1
353 #define MASK_FRAMING BIT0
354 #define MASK_BREAK   BIT14
355 #define MASK_OVERRUN BIT4
356
357 #define GSR   0x00 /* global status */
358 #define JCR   0x04 /* JTAG control */
359 #define IODR  0x08 /* GPIO direction */
360 #define IOER  0x0c /* GPIO interrupt enable */
361 #define IOVR  0x10 /* GPIO value */
362 #define IOSR  0x14 /* GPIO interrupt status */
363 #define TDR   0x80 /* tx data */
364 #define RDR   0x80 /* rx data */
365 #define TCR   0x82 /* tx control */
366 #define TIR   0x84 /* tx idle */
367 #define TPR   0x85 /* tx preamble */
368 #define RCR   0x86 /* rx control */
369 #define VCR   0x88 /* V.24 control */
370 #define CCR   0x89 /* clock control */
371 #define BDR   0x8a /* baud divisor */
372 #define SCR   0x8c /* serial control */
373 #define SSR   0x8e /* serial status */
374 #define RDCSR 0x90 /* rx DMA control/status */
375 #define TDCSR 0x94 /* tx DMA control/status */
376 #define RDDAR 0x98 /* rx DMA descriptor address */
377 #define TDDAR 0x9c /* tx DMA descriptor address */
378 #define XSR   0x40 /* extended sync pattern */
379 #define XCR   0x44 /* extended control */
380
381 #define RXIDLE      BIT14
382 #define RXBREAK     BIT14
383 #define IRQ_TXDATA  BIT13
384 #define IRQ_TXIDLE  BIT12
385 #define IRQ_TXUNDER BIT11 /* HDLC */
386 #define IRQ_RXDATA  BIT10
387 #define IRQ_RXIDLE  BIT9  /* HDLC */
388 #define IRQ_RXBREAK BIT9  /* async */
389 #define IRQ_RXOVER  BIT8
390 #define IRQ_DSR     BIT7
391 #define IRQ_CTS     BIT6
392 #define IRQ_DCD     BIT5
393 #define IRQ_RI      BIT4
394 #define IRQ_ALL     0x3ff0
395 #define IRQ_MASTER  BIT0
396
397 #define slgt_irq_on(info, mask) \
398         wr_reg16((info), SCR, (unsigned short)(rd_reg16((info), SCR) | (mask)))
399 #define slgt_irq_off(info, mask) \
400         wr_reg16((info), SCR, (unsigned short)(rd_reg16((info), SCR) & ~(mask)))
401
402 static __u8  rd_reg8(struct slgt_info *info, unsigned int addr);
403 static void  wr_reg8(struct slgt_info *info, unsigned int addr, __u8 value);
404 static __u16 rd_reg16(struct slgt_info *info, unsigned int addr);
405 static void  wr_reg16(struct slgt_info *info, unsigned int addr, __u16 value);
406 static __u32 rd_reg32(struct slgt_info *info, unsigned int addr);
407 static void  wr_reg32(struct slgt_info *info, unsigned int addr, __u32 value);
408
409 static void  msc_set_vcr(struct slgt_info *info);
410
411 static int  startup(struct slgt_info *info);
412 static int  block_til_ready(struct tty_struct *tty, struct file * filp,struct slgt_info *info);
413 static void shutdown(struct slgt_info *info);
414 static void program_hw(struct slgt_info *info);
415 static void change_params(struct slgt_info *info);
416
417 static int  adapter_test(struct slgt_info *info);
418
419 static void reset_port(struct slgt_info *info);
420 static void async_mode(struct slgt_info *info);
421 static void sync_mode(struct slgt_info *info);
422
423 static void rx_stop(struct slgt_info *info);
424 static void rx_start(struct slgt_info *info);
425 static void reset_rbufs(struct slgt_info *info);
426 static void free_rbufs(struct slgt_info *info, unsigned int first, unsigned int last);
427 static bool rx_get_frame(struct slgt_info *info);
428 static bool rx_get_buf(struct slgt_info *info);
429
430 static void tx_start(struct slgt_info *info);
431 static void tx_stop(struct slgt_info *info);
432 static void tx_set_idle(struct slgt_info *info);
433 static unsigned int tbuf_bytes(struct slgt_info *info);
434 static void reset_tbufs(struct slgt_info *info);
435 static void tdma_reset(struct slgt_info *info);
436 static bool tx_load(struct slgt_info *info, const char *buf, unsigned int count);
437
438 static void get_gtsignals(struct slgt_info *info);
439 static void set_gtsignals(struct slgt_info *info);
440 static void set_rate(struct slgt_info *info, u32 data_rate);
441
442 static void bh_transmit(struct slgt_info *info);
443 static void isr_txeom(struct slgt_info *info, unsigned short status);
444
445 static void tx_timeout(struct timer_list *t);
446 static void rx_timeout(struct timer_list *t);
447
448 /*
449  * ioctl handlers
450  */
451 static int  get_stats(struct slgt_info *info, struct mgsl_icount __user *user_icount);
452 static int  get_params(struct slgt_info *info, MGSL_PARAMS __user *params);
453 static int  set_params(struct slgt_info *info, MGSL_PARAMS __user *params);
454 static int  get_txidle(struct slgt_info *info, int __user *idle_mode);
455 static int  set_txidle(struct slgt_info *info, int idle_mode);
456 static int  tx_enable(struct slgt_info *info, int enable);
457 static int  tx_abort(struct slgt_info *info);
458 static int  rx_enable(struct slgt_info *info, int enable);
459 static int  modem_input_wait(struct slgt_info *info,int arg);
460 static int  wait_mgsl_event(struct slgt_info *info, int __user *mask_ptr);
461 static int  get_interface(struct slgt_info *info, int __user *if_mode);
462 static int  set_interface(struct slgt_info *info, int if_mode);
463 static int  set_gpio(struct slgt_info *info, struct gpio_desc __user *gpio);
464 static int  get_gpio(struct slgt_info *info, struct gpio_desc __user *gpio);
465 static int  wait_gpio(struct slgt_info *info, struct gpio_desc __user *gpio);
466 static int  get_xsync(struct slgt_info *info, int __user *if_mode);
467 static int  set_xsync(struct slgt_info *info, int if_mode);
468 static int  get_xctrl(struct slgt_info *info, int __user *if_mode);
469 static int  set_xctrl(struct slgt_info *info, int if_mode);
470
471 /*
472  * driver functions
473  */
474 static void release_resources(struct slgt_info *info);
475
476 /*
477  * DEBUG OUTPUT CODE
478  */
479 #ifndef DBGINFO
480 #define DBGINFO(fmt)
481 #endif
482 #ifndef DBGERR
483 #define DBGERR(fmt)
484 #endif
485 #ifndef DBGBH
486 #define DBGBH(fmt)
487 #endif
488 #ifndef DBGISR
489 #define DBGISR(fmt)
490 #endif
491
492 #ifdef DBGDATA
493 static void trace_block(struct slgt_info *info, const char *data, int count, const char *label)
494 {
495         int i;
496         int linecount;
497         printk("%s %s data:\n",info->device_name, label);
498         while(count) {
499                 linecount = (count > 16) ? 16 : count;
500                 for(i=0; i < linecount; i++)
501                         printk("%02X ",(unsigned char)data[i]);
502                 for(;i<17;i++)
503                         printk("   ");
504                 for(i=0;i<linecount;i++) {
505                         if (data[i]>=040 && data[i]<=0176)
506                                 printk("%c",data[i]);
507                         else
508                                 printk(".");
509                 }
510                 printk("\n");
511                 data  += linecount;
512                 count -= linecount;
513         }
514 }
515 #else
516 #define DBGDATA(info, buf, size, label)
517 #endif
518
519 #ifdef DBGTBUF
520 static void dump_tbufs(struct slgt_info *info)
521 {
522         int i;
523         printk("tbuf_current=%d\n", info->tbuf_current);
524         for (i=0 ; i < info->tbuf_count ; i++) {
525                 printk("%d: count=%04X status=%04X\n",
526                         i, le16_to_cpu(info->tbufs[i].count), le16_to_cpu(info->tbufs[i].status));
527         }
528 }
529 #else
530 #define DBGTBUF(info)
531 #endif
532
533 #ifdef DBGRBUF
534 static void dump_rbufs(struct slgt_info *info)
535 {
536         int i;
537         printk("rbuf_current=%d\n", info->rbuf_current);
538         for (i=0 ; i < info->rbuf_count ; i++) {
539                 printk("%d: count=%04X status=%04X\n",
540                         i, le16_to_cpu(info->rbufs[i].count), le16_to_cpu(info->rbufs[i].status));
541         }
542 }
543 #else
544 #define DBGRBUF(info)
545 #endif
546
547 static inline int sanity_check(struct slgt_info *info, char *devname, const char *name)
548 {
549 #ifdef SANITY_CHECK
550         if (!info) {
551                 printk("null struct slgt_info for (%s) in %s\n", devname, name);
552                 return 1;
553         }
554 #else
555         if (!info)
556                 return 1;
557 #endif
558         return 0;
559 }
560
561 /*
562  * line discipline callback wrappers
563  *
564  * The wrappers maintain line discipline references
565  * while calling into the line discipline.
566  *
567  * ldisc_receive_buf  - pass receive data to line discipline
568  */
569 static void ldisc_receive_buf(struct tty_struct *tty,
570                               const __u8 *data, char *flags, int count)
571 {
572         struct tty_ldisc *ld;
573         if (!tty)
574                 return;
575         ld = tty_ldisc_ref(tty);
576         if (ld) {
577                 if (ld->ops->receive_buf)
578                         ld->ops->receive_buf(tty, data, flags, count);
579                 tty_ldisc_deref(ld);
580         }
581 }
582
583 /* tty callbacks */
584
585 static int open(struct tty_struct *tty, struct file *filp)
586 {
587         struct slgt_info *info;
588         int retval, line;
589         unsigned long flags;
590
591         line = tty->index;
592         if (line >= slgt_device_count) {
593                 DBGERR(("%s: open with invalid line #%d.\n", driver_name, line));
594                 return -ENODEV;
595         }
596
597         info = slgt_device_list;
598         while(info && info->line != line)
599                 info = info->next_device;
600         if (sanity_check(info, tty->name, "open"))
601                 return -ENODEV;
602         if (info->init_error) {
603                 DBGERR(("%s init error=%d\n", info->device_name, info->init_error));
604                 return -ENODEV;
605         }
606
607         tty->driver_data = info;
608         info->port.tty = tty;
609
610         DBGINFO(("%s open, old ref count = %d\n", info->device_name, info->port.count));
611
612         mutex_lock(&info->port.mutex);
613
614         spin_lock_irqsave(&info->netlock, flags);
615         if (info->netcount) {
616                 retval = -EBUSY;
617                 spin_unlock_irqrestore(&info->netlock, flags);
618                 mutex_unlock(&info->port.mutex);
619                 goto cleanup;
620         }
621         info->port.count++;
622         spin_unlock_irqrestore(&info->netlock, flags);
623
624         if (info->port.count == 1) {
625                 /* 1st open on this device, init hardware */
626                 retval = startup(info);
627                 if (retval < 0) {
628                         mutex_unlock(&info->port.mutex);
629                         goto cleanup;
630                 }
631         }
632         mutex_unlock(&info->port.mutex);
633         retval = block_til_ready(tty, filp, info);
634         if (retval) {
635                 DBGINFO(("%s block_til_ready rc=%d\n", info->device_name, retval));
636                 goto cleanup;
637         }
638
639         retval = 0;
640
641 cleanup:
642         if (retval) {
643                 if (tty->count == 1)
644                         info->port.tty = NULL; /* tty layer will release tty struct */
645                 if(info->port.count)
646                         info->port.count--;
647         }
648
649         DBGINFO(("%s open rc=%d\n", info->device_name, retval));
650         return retval;
651 }
652
653 static void close(struct tty_struct *tty, struct file *filp)
654 {
655         struct slgt_info *info = tty->driver_data;
656
657         if (sanity_check(info, tty->name, "close"))
658                 return;
659         DBGINFO(("%s close entry, count=%d\n", info->device_name, info->port.count));
660
661         if (tty_port_close_start(&info->port, tty, filp) == 0)
662                 goto cleanup;
663
664         mutex_lock(&info->port.mutex);
665         if (tty_port_initialized(&info->port))
666                 wait_until_sent(tty, info->timeout);
667         flush_buffer(tty);
668         tty_ldisc_flush(tty);
669
670         shutdown(info);
671         mutex_unlock(&info->port.mutex);
672
673         tty_port_close_end(&info->port, tty);
674         info->port.tty = NULL;
675 cleanup:
676         DBGINFO(("%s close exit, count=%d\n", tty->driver->name, info->port.count));
677 }
678
679 static void hangup(struct tty_struct *tty)
680 {
681         struct slgt_info *info = tty->driver_data;
682         unsigned long flags;
683
684         if (sanity_check(info, tty->name, "hangup"))
685                 return;
686         DBGINFO(("%s hangup\n", info->device_name));
687
688         flush_buffer(tty);
689
690         mutex_lock(&info->port.mutex);
691         shutdown(info);
692
693         spin_lock_irqsave(&info->port.lock, flags);
694         info->port.count = 0;
695         info->port.tty = NULL;
696         spin_unlock_irqrestore(&info->port.lock, flags);
697         tty_port_set_active(&info->port, false);
698         mutex_unlock(&info->port.mutex);
699
700         wake_up_interruptible(&info->port.open_wait);
701 }
702
703 static void set_termios(struct tty_struct *tty,
704                         const struct ktermios *old_termios)
705 {
706         struct slgt_info *info = tty->driver_data;
707         unsigned long flags;
708
709         DBGINFO(("%s set_termios\n", tty->driver->name));
710
711         change_params(info);
712
713         /* Handle transition to B0 status */
714         if ((old_termios->c_cflag & CBAUD) && !C_BAUD(tty)) {
715                 info->signals &= ~(SerialSignal_RTS | SerialSignal_DTR);
716                 spin_lock_irqsave(&info->lock,flags);
717                 set_gtsignals(info);
718                 spin_unlock_irqrestore(&info->lock,flags);
719         }
720
721         /* Handle transition away from B0 status */
722         if (!(old_termios->c_cflag & CBAUD) && C_BAUD(tty)) {
723                 info->signals |= SerialSignal_DTR;
724                 if (!C_CRTSCTS(tty) || !tty_throttled(tty))
725                         info->signals |= SerialSignal_RTS;
726                 spin_lock_irqsave(&info->lock,flags);
727                 set_gtsignals(info);
728                 spin_unlock_irqrestore(&info->lock,flags);
729         }
730
731         /* Handle turning off CRTSCTS */
732         if ((old_termios->c_cflag & CRTSCTS) && !C_CRTSCTS(tty)) {
733                 tty->hw_stopped = 0;
734                 tx_release(tty);
735         }
736 }
737
738 static void update_tx_timer(struct slgt_info *info)
739 {
740         /*
741          * use worst case speed of 1200bps to calculate transmit timeout
742          * based on data in buffers (tbuf_bytes) and FIFO (128 bytes)
743          */
744         if (info->params.mode == MGSL_MODE_HDLC) {
745                 int timeout  = (tbuf_bytes(info) * 7) + 1000;
746                 mod_timer(&info->tx_timer, jiffies + msecs_to_jiffies(timeout));
747         }
748 }
749
750 static int write(struct tty_struct *tty,
751                  const unsigned char *buf, int count)
752 {
753         int ret = 0;
754         struct slgt_info *info = tty->driver_data;
755         unsigned long flags;
756
757         if (sanity_check(info, tty->name, "write"))
758                 return -EIO;
759
760         DBGINFO(("%s write count=%d\n", info->device_name, count));
761
762         if (!info->tx_buf || (count > info->max_frame_size))
763                 return -EIO;
764
765         if (!count || tty->flow.stopped || tty->hw_stopped)
766                 return 0;
767
768         spin_lock_irqsave(&info->lock, flags);
769
770         if (info->tx_count) {
771                 /* send accumulated data from send_char() */
772                 if (!tx_load(info, info->tx_buf, info->tx_count))
773                         goto cleanup;
774                 info->tx_count = 0;
775         }
776
777         if (tx_load(info, buf, count))
778                 ret = count;
779
780 cleanup:
781         spin_unlock_irqrestore(&info->lock, flags);
782         DBGINFO(("%s write rc=%d\n", info->device_name, ret));
783         return ret;
784 }
785
786 static int put_char(struct tty_struct *tty, unsigned char ch)
787 {
788         struct slgt_info *info = tty->driver_data;
789         unsigned long flags;
790         int ret = 0;
791
792         if (sanity_check(info, tty->name, "put_char"))
793                 return 0;
794         DBGINFO(("%s put_char(%d)\n", info->device_name, ch));
795         if (!info->tx_buf)
796                 return 0;
797         spin_lock_irqsave(&info->lock,flags);
798         if (info->tx_count < info->max_frame_size) {
799                 info->tx_buf[info->tx_count++] = ch;
800                 ret = 1;
801         }
802         spin_unlock_irqrestore(&info->lock,flags);
803         return ret;
804 }
805
806 static void send_xchar(struct tty_struct *tty, char ch)
807 {
808         struct slgt_info *info = tty->driver_data;
809         unsigned long flags;
810
811         if (sanity_check(info, tty->name, "send_xchar"))
812                 return;
813         DBGINFO(("%s send_xchar(%d)\n", info->device_name, ch));
814         info->x_char = ch;
815         if (ch) {
816                 spin_lock_irqsave(&info->lock,flags);
817                 if (!info->tx_enabled)
818                         tx_start(info);
819                 spin_unlock_irqrestore(&info->lock,flags);
820         }
821 }
822
823 static void wait_until_sent(struct tty_struct *tty, int timeout)
824 {
825         struct slgt_info *info = tty->driver_data;
826         unsigned long orig_jiffies, char_time;
827
828         if (!info )
829                 return;
830         if (sanity_check(info, tty->name, "wait_until_sent"))
831                 return;
832         DBGINFO(("%s wait_until_sent entry\n", info->device_name));
833         if (!tty_port_initialized(&info->port))
834                 goto exit;
835
836         orig_jiffies = jiffies;
837
838         /* Set check interval to 1/5 of estimated time to
839          * send a character, and make it at least 1. The check
840          * interval should also be less than the timeout.
841          * Note: use tight timings here to satisfy the NIST-PCTS.
842          */
843
844         if (info->params.data_rate) {
845                 char_time = info->timeout/(32 * 5);
846                 if (!char_time)
847                         char_time++;
848         } else
849                 char_time = 1;
850
851         if (timeout)
852                 char_time = min_t(unsigned long, char_time, timeout);
853
854         while (info->tx_active) {
855                 msleep_interruptible(jiffies_to_msecs(char_time));
856                 if (signal_pending(current))
857                         break;
858                 if (timeout && time_after(jiffies, orig_jiffies + timeout))
859                         break;
860         }
861 exit:
862         DBGINFO(("%s wait_until_sent exit\n", info->device_name));
863 }
864
865 static unsigned int write_room(struct tty_struct *tty)
866 {
867         struct slgt_info *info = tty->driver_data;
868         unsigned int ret;
869
870         if (sanity_check(info, tty->name, "write_room"))
871                 return 0;
872         ret = (info->tx_active) ? 0 : HDLC_MAX_FRAME_SIZE;
873         DBGINFO(("%s write_room=%u\n", info->device_name, ret));
874         return ret;
875 }
876
877 static void flush_chars(struct tty_struct *tty)
878 {
879         struct slgt_info *info = tty->driver_data;
880         unsigned long flags;
881
882         if (sanity_check(info, tty->name, "flush_chars"))
883                 return;
884         DBGINFO(("%s flush_chars entry tx_count=%d\n", info->device_name, info->tx_count));
885
886         if (info->tx_count <= 0 || tty->flow.stopped ||
887             tty->hw_stopped || !info->tx_buf)
888                 return;
889
890         DBGINFO(("%s flush_chars start transmit\n", info->device_name));
891
892         spin_lock_irqsave(&info->lock,flags);
893         if (info->tx_count && tx_load(info, info->tx_buf, info->tx_count))
894                 info->tx_count = 0;
895         spin_unlock_irqrestore(&info->lock,flags);
896 }
897
898 static void flush_buffer(struct tty_struct *tty)
899 {
900         struct slgt_info *info = tty->driver_data;
901         unsigned long flags;
902
903         if (sanity_check(info, tty->name, "flush_buffer"))
904                 return;
905         DBGINFO(("%s flush_buffer\n", info->device_name));
906
907         spin_lock_irqsave(&info->lock, flags);
908         info->tx_count = 0;
909         spin_unlock_irqrestore(&info->lock, flags);
910
911         tty_wakeup(tty);
912 }
913
914 /*
915  * throttle (stop) transmitter
916  */
917 static void tx_hold(struct tty_struct *tty)
918 {
919         struct slgt_info *info = tty->driver_data;
920         unsigned long flags;
921
922         if (sanity_check(info, tty->name, "tx_hold"))
923                 return;
924         DBGINFO(("%s tx_hold\n", info->device_name));
925         spin_lock_irqsave(&info->lock,flags);
926         if (info->tx_enabled && info->params.mode == MGSL_MODE_ASYNC)
927                 tx_stop(info);
928         spin_unlock_irqrestore(&info->lock,flags);
929 }
930
931 /*
932  * release (start) transmitter
933  */
934 static void tx_release(struct tty_struct *tty)
935 {
936         struct slgt_info *info = tty->driver_data;
937         unsigned long flags;
938
939         if (sanity_check(info, tty->name, "tx_release"))
940                 return;
941         DBGINFO(("%s tx_release\n", info->device_name));
942         spin_lock_irqsave(&info->lock, flags);
943         if (info->tx_count && tx_load(info, info->tx_buf, info->tx_count))
944                 info->tx_count = 0;
945         spin_unlock_irqrestore(&info->lock, flags);
946 }
947
948 /*
949  * Service an IOCTL request
950  *
951  * Arguments
952  *
953  *      tty     pointer to tty instance data
954  *      cmd     IOCTL command code
955  *      arg     command argument/context
956  *
957  * Return 0 if success, otherwise error code
958  */
959 static int ioctl(struct tty_struct *tty,
960                  unsigned int cmd, unsigned long arg)
961 {
962         struct slgt_info *info = tty->driver_data;
963         void __user *argp = (void __user *)arg;
964         int ret;
965
966         if (sanity_check(info, tty->name, "ioctl"))
967                 return -ENODEV;
968         DBGINFO(("%s ioctl() cmd=%08X\n", info->device_name, cmd));
969
970         if (cmd != TIOCMIWAIT) {
971                 if (tty_io_error(tty))
972                     return -EIO;
973         }
974
975         switch (cmd) {
976         case MGSL_IOCWAITEVENT:
977                 return wait_mgsl_event(info, argp);
978         case TIOCMIWAIT:
979                 return modem_input_wait(info,(int)arg);
980         case MGSL_IOCSGPIO:
981                 return set_gpio(info, argp);
982         case MGSL_IOCGGPIO:
983                 return get_gpio(info, argp);
984         case MGSL_IOCWAITGPIO:
985                 return wait_gpio(info, argp);
986         case MGSL_IOCGXSYNC:
987                 return get_xsync(info, argp);
988         case MGSL_IOCSXSYNC:
989                 return set_xsync(info, (int)arg);
990         case MGSL_IOCGXCTRL:
991                 return get_xctrl(info, argp);
992         case MGSL_IOCSXCTRL:
993                 return set_xctrl(info, (int)arg);
994         }
995         mutex_lock(&info->port.mutex);
996         switch (cmd) {
997         case MGSL_IOCGPARAMS:
998                 ret = get_params(info, argp);
999                 break;
1000         case MGSL_IOCSPARAMS:
1001                 ret = set_params(info, argp);
1002                 break;
1003         case MGSL_IOCGTXIDLE:
1004                 ret = get_txidle(info, argp);
1005                 break;
1006         case MGSL_IOCSTXIDLE:
1007                 ret = set_txidle(info, (int)arg);
1008                 break;
1009         case MGSL_IOCTXENABLE:
1010                 ret = tx_enable(info, (int)arg);
1011                 break;
1012         case MGSL_IOCRXENABLE:
1013                 ret = rx_enable(info, (int)arg);
1014                 break;
1015         case MGSL_IOCTXABORT:
1016                 ret = tx_abort(info);
1017                 break;
1018         case MGSL_IOCGSTATS:
1019                 ret = get_stats(info, argp);
1020                 break;
1021         case MGSL_IOCGIF:
1022                 ret = get_interface(info, argp);
1023                 break;
1024         case MGSL_IOCSIF:
1025                 ret = set_interface(info,(int)arg);
1026                 break;
1027         default:
1028                 ret = -ENOIOCTLCMD;
1029         }
1030         mutex_unlock(&info->port.mutex);
1031         return ret;
1032 }
1033
1034 static int get_icount(struct tty_struct *tty,
1035                                 struct serial_icounter_struct *icount)
1036
1037 {
1038         struct slgt_info *info = tty->driver_data;
1039         struct mgsl_icount cnow;        /* kernel counter temps */
1040         unsigned long flags;
1041
1042         spin_lock_irqsave(&info->lock,flags);
1043         cnow = info->icount;
1044         spin_unlock_irqrestore(&info->lock,flags);
1045
1046         icount->cts = cnow.cts;
1047         icount->dsr = cnow.dsr;
1048         icount->rng = cnow.rng;
1049         icount->dcd = cnow.dcd;
1050         icount->rx = cnow.rx;
1051         icount->tx = cnow.tx;
1052         icount->frame = cnow.frame;
1053         icount->overrun = cnow.overrun;
1054         icount->parity = cnow.parity;
1055         icount->brk = cnow.brk;
1056         icount->buf_overrun = cnow.buf_overrun;
1057
1058         return 0;
1059 }
1060
1061 /*
1062  * support for 32 bit ioctl calls on 64 bit systems
1063  */
1064 #ifdef CONFIG_COMPAT
1065 static long get_params32(struct slgt_info *info, struct MGSL_PARAMS32 __user *user_params)
1066 {
1067         struct MGSL_PARAMS32 tmp_params;
1068
1069         DBGINFO(("%s get_params32\n", info->device_name));
1070         memset(&tmp_params, 0, sizeof(tmp_params));
1071         tmp_params.mode            = (compat_ulong_t)info->params.mode;
1072         tmp_params.loopback        = info->params.loopback;
1073         tmp_params.flags           = info->params.flags;
1074         tmp_params.encoding        = info->params.encoding;
1075         tmp_params.clock_speed     = (compat_ulong_t)info->params.clock_speed;
1076         tmp_params.addr_filter     = info->params.addr_filter;
1077         tmp_params.crc_type        = info->params.crc_type;
1078         tmp_params.preamble_length = info->params.preamble_length;
1079         tmp_params.preamble        = info->params.preamble;
1080         tmp_params.data_rate       = (compat_ulong_t)info->params.data_rate;
1081         tmp_params.data_bits       = info->params.data_bits;
1082         tmp_params.stop_bits       = info->params.stop_bits;
1083         tmp_params.parity          = info->params.parity;
1084         if (copy_to_user(user_params, &tmp_params, sizeof(struct MGSL_PARAMS32)))
1085                 return -EFAULT;
1086         return 0;
1087 }
1088
1089 static long set_params32(struct slgt_info *info, struct MGSL_PARAMS32 __user *new_params)
1090 {
1091         struct MGSL_PARAMS32 tmp_params;
1092
1093         DBGINFO(("%s set_params32\n", info->device_name));
1094         if (copy_from_user(&tmp_params, new_params, sizeof(struct MGSL_PARAMS32)))
1095                 return -EFAULT;
1096
1097         spin_lock(&info->lock);
1098         if (tmp_params.mode == MGSL_MODE_BASE_CLOCK) {
1099                 info->base_clock = tmp_params.clock_speed;
1100         } else {
1101                 info->params.mode            = tmp_params.mode;
1102                 info->params.loopback        = tmp_params.loopback;
1103                 info->params.flags           = tmp_params.flags;
1104                 info->params.encoding        = tmp_params.encoding;
1105                 info->params.clock_speed     = tmp_params.clock_speed;
1106                 info->params.addr_filter     = tmp_params.addr_filter;
1107                 info->params.crc_type        = tmp_params.crc_type;
1108                 info->params.preamble_length = tmp_params.preamble_length;
1109                 info->params.preamble        = tmp_params.preamble;
1110                 info->params.data_rate       = tmp_params.data_rate;
1111                 info->params.data_bits       = tmp_params.data_bits;
1112                 info->params.stop_bits       = tmp_params.stop_bits;
1113                 info->params.parity          = tmp_params.parity;
1114         }
1115         spin_unlock(&info->lock);
1116
1117         program_hw(info);
1118
1119         return 0;
1120 }
1121
1122 static long slgt_compat_ioctl(struct tty_struct *tty,
1123                          unsigned int cmd, unsigned long arg)
1124 {
1125         struct slgt_info *info = tty->driver_data;
1126         int rc;
1127
1128         if (sanity_check(info, tty->name, "compat_ioctl"))
1129                 return -ENODEV;
1130         DBGINFO(("%s compat_ioctl() cmd=%08X\n", info->device_name, cmd));
1131
1132         switch (cmd) {
1133         case MGSL_IOCSPARAMS32:
1134                 rc = set_params32(info, compat_ptr(arg));
1135                 break;
1136
1137         case MGSL_IOCGPARAMS32:
1138                 rc = get_params32(info, compat_ptr(arg));
1139                 break;
1140
1141         case MGSL_IOCGPARAMS:
1142         case MGSL_IOCSPARAMS:
1143         case MGSL_IOCGTXIDLE:
1144         case MGSL_IOCGSTATS:
1145         case MGSL_IOCWAITEVENT:
1146         case MGSL_IOCGIF:
1147         case MGSL_IOCSGPIO:
1148         case MGSL_IOCGGPIO:
1149         case MGSL_IOCWAITGPIO:
1150         case MGSL_IOCGXSYNC:
1151         case MGSL_IOCGXCTRL:
1152                 rc = ioctl(tty, cmd, (unsigned long)compat_ptr(arg));
1153                 break;
1154         default:
1155                 rc = ioctl(tty, cmd, arg);
1156         }
1157         DBGINFO(("%s compat_ioctl() cmd=%08X rc=%d\n", info->device_name, cmd, rc));
1158         return rc;
1159 }
1160 #else
1161 #define slgt_compat_ioctl NULL
1162 #endif /* ifdef CONFIG_COMPAT */
1163
1164 /*
1165  * proc fs support
1166  */
1167 static inline void line_info(struct seq_file *m, struct slgt_info *info)
1168 {
1169         char stat_buf[30];
1170         unsigned long flags;
1171
1172         seq_printf(m, "%s: IO=%08X IRQ=%d MaxFrameSize=%u\n",
1173                       info->device_name, info->phys_reg_addr,
1174                       info->irq_level, info->max_frame_size);
1175
1176         /* output current serial signal states */
1177         spin_lock_irqsave(&info->lock,flags);
1178         get_gtsignals(info);
1179         spin_unlock_irqrestore(&info->lock,flags);
1180
1181         stat_buf[0] = 0;
1182         stat_buf[1] = 0;
1183         if (info->signals & SerialSignal_RTS)
1184                 strcat(stat_buf, "|RTS");
1185         if (info->signals & SerialSignal_CTS)
1186                 strcat(stat_buf, "|CTS");
1187         if (info->signals & SerialSignal_DTR)
1188                 strcat(stat_buf, "|DTR");
1189         if (info->signals & SerialSignal_DSR)
1190                 strcat(stat_buf, "|DSR");
1191         if (info->signals & SerialSignal_DCD)
1192                 strcat(stat_buf, "|CD");
1193         if (info->signals & SerialSignal_RI)
1194                 strcat(stat_buf, "|RI");
1195
1196         if (info->params.mode != MGSL_MODE_ASYNC) {
1197                 seq_printf(m, "\tHDLC txok:%d rxok:%d",
1198                                info->icount.txok, info->icount.rxok);
1199                 if (info->icount.txunder)
1200                         seq_printf(m, " txunder:%d", info->icount.txunder);
1201                 if (info->icount.txabort)
1202                         seq_printf(m, " txabort:%d", info->icount.txabort);
1203                 if (info->icount.rxshort)
1204                         seq_printf(m, " rxshort:%d", info->icount.rxshort);
1205                 if (info->icount.rxlong)
1206                         seq_printf(m, " rxlong:%d", info->icount.rxlong);
1207                 if (info->icount.rxover)
1208                         seq_printf(m, " rxover:%d", info->icount.rxover);
1209                 if (info->icount.rxcrc)
1210                         seq_printf(m, " rxcrc:%d", info->icount.rxcrc);
1211         } else {
1212                 seq_printf(m, "\tASYNC tx:%d rx:%d",
1213                                info->icount.tx, info->icount.rx);
1214                 if (info->icount.frame)
1215                         seq_printf(m, " fe:%d", info->icount.frame);
1216                 if (info->icount.parity)
1217                         seq_printf(m, " pe:%d", info->icount.parity);
1218                 if (info->icount.brk)
1219                         seq_printf(m, " brk:%d", info->icount.brk);
1220                 if (info->icount.overrun)
1221                         seq_printf(m, " oe:%d", info->icount.overrun);
1222         }
1223
1224         /* Append serial signal status to end */
1225         seq_printf(m, " %s\n", stat_buf+1);
1226
1227         seq_printf(m, "\ttxactive=%d bh_req=%d bh_run=%d pending_bh=%x\n",
1228                        info->tx_active,info->bh_requested,info->bh_running,
1229                        info->pending_bh);
1230 }
1231
1232 /* Called to print information about devices
1233  */
1234 static int synclink_gt_proc_show(struct seq_file *m, void *v)
1235 {
1236         struct slgt_info *info;
1237
1238         seq_puts(m, "synclink_gt driver\n");
1239
1240         info = slgt_device_list;
1241         while( info ) {
1242                 line_info(m, info);
1243                 info = info->next_device;
1244         }
1245         return 0;
1246 }
1247
1248 /*
1249  * return count of bytes in transmit buffer
1250  */
1251 static unsigned int chars_in_buffer(struct tty_struct *tty)
1252 {
1253         struct slgt_info *info = tty->driver_data;
1254         unsigned int count;
1255         if (sanity_check(info, tty->name, "chars_in_buffer"))
1256                 return 0;
1257         count = tbuf_bytes(info);
1258         DBGINFO(("%s chars_in_buffer()=%u\n", info->device_name, count));
1259         return count;
1260 }
1261
1262 /*
1263  * signal remote device to throttle send data (our receive data)
1264  */
1265 static void throttle(struct tty_struct * tty)
1266 {
1267         struct slgt_info *info = tty->driver_data;
1268         unsigned long flags;
1269
1270         if (sanity_check(info, tty->name, "throttle"))
1271                 return;
1272         DBGINFO(("%s throttle\n", info->device_name));
1273         if (I_IXOFF(tty))
1274                 send_xchar(tty, STOP_CHAR(tty));
1275         if (C_CRTSCTS(tty)) {
1276                 spin_lock_irqsave(&info->lock,flags);
1277                 info->signals &= ~SerialSignal_RTS;
1278                 set_gtsignals(info);
1279                 spin_unlock_irqrestore(&info->lock,flags);
1280         }
1281 }
1282
1283 /*
1284  * signal remote device to stop throttling send data (our receive data)
1285  */
1286 static void unthrottle(struct tty_struct * tty)
1287 {
1288         struct slgt_info *info = tty->driver_data;
1289         unsigned long flags;
1290
1291         if (sanity_check(info, tty->name, "unthrottle"))
1292                 return;
1293         DBGINFO(("%s unthrottle\n", info->device_name));
1294         if (I_IXOFF(tty)) {
1295                 if (info->x_char)
1296                         info->x_char = 0;
1297                 else
1298                         send_xchar(tty, START_CHAR(tty));
1299         }
1300         if (C_CRTSCTS(tty)) {
1301                 spin_lock_irqsave(&info->lock,flags);
1302                 info->signals |= SerialSignal_RTS;
1303                 set_gtsignals(info);
1304                 spin_unlock_irqrestore(&info->lock,flags);
1305         }
1306 }
1307
1308 /*
1309  * set or clear transmit break condition
1310  * break_state  -1=set break condition, 0=clear
1311  */
1312 static int set_break(struct tty_struct *tty, int break_state)
1313 {
1314         struct slgt_info *info = tty->driver_data;
1315         unsigned short value;
1316         unsigned long flags;
1317
1318         if (sanity_check(info, tty->name, "set_break"))
1319                 return -EINVAL;
1320         DBGINFO(("%s set_break(%d)\n", info->device_name, break_state));
1321
1322         spin_lock_irqsave(&info->lock,flags);
1323         value = rd_reg16(info, TCR);
1324         if (break_state == -1)
1325                 value |= BIT6;
1326         else
1327                 value &= ~BIT6;
1328         wr_reg16(info, TCR, value);
1329         spin_unlock_irqrestore(&info->lock,flags);
1330         return 0;
1331 }
1332
1333 #if SYNCLINK_GENERIC_HDLC
1334
1335 /**
1336  * hdlcdev_attach - called by generic HDLC layer when protocol selected (PPP, frame relay, etc.)
1337  * @dev:      pointer to network device structure
1338  * @encoding: serial encoding setting
1339  * @parity:   FCS setting
1340  *
1341  * Set encoding and frame check sequence (FCS) options.
1342  *
1343  * Return: 0 if success, otherwise error code
1344  */
1345 static int hdlcdev_attach(struct net_device *dev, unsigned short encoding,
1346                           unsigned short parity)
1347 {
1348         struct slgt_info *info = dev_to_port(dev);
1349         unsigned char  new_encoding;
1350         unsigned short new_crctype;
1351
1352         /* return error if TTY interface open */
1353         if (info->port.count)
1354                 return -EBUSY;
1355
1356         DBGINFO(("%s hdlcdev_attach\n", info->device_name));
1357
1358         switch (encoding)
1359         {
1360         case ENCODING_NRZ:        new_encoding = HDLC_ENCODING_NRZ; break;
1361         case ENCODING_NRZI:       new_encoding = HDLC_ENCODING_NRZI_SPACE; break;
1362         case ENCODING_FM_MARK:    new_encoding = HDLC_ENCODING_BIPHASE_MARK; break;
1363         case ENCODING_FM_SPACE:   new_encoding = HDLC_ENCODING_BIPHASE_SPACE; break;
1364         case ENCODING_MANCHESTER: new_encoding = HDLC_ENCODING_BIPHASE_LEVEL; break;
1365         default: return -EINVAL;
1366         }
1367
1368         switch (parity)
1369         {
1370         case PARITY_NONE:            new_crctype = HDLC_CRC_NONE; break;
1371         case PARITY_CRC16_PR1_CCITT: new_crctype = HDLC_CRC_16_CCITT; break;
1372         case PARITY_CRC32_PR1_CCITT: new_crctype = HDLC_CRC_32_CCITT; break;
1373         default: return -EINVAL;
1374         }
1375
1376         info->params.encoding = new_encoding;
1377         info->params.crc_type = new_crctype;
1378
1379         /* if network interface up, reprogram hardware */
1380         if (info->netcount)
1381                 program_hw(info);
1382
1383         return 0;
1384 }
1385
1386 /**
1387  * hdlcdev_xmit - called by generic HDLC layer to send a frame
1388  * @skb: socket buffer containing HDLC frame
1389  * @dev: pointer to network device structure
1390  */
1391 static netdev_tx_t hdlcdev_xmit(struct sk_buff *skb,
1392                                       struct net_device *dev)
1393 {
1394         struct slgt_info *info = dev_to_port(dev);
1395         unsigned long flags;
1396
1397         DBGINFO(("%s hdlc_xmit\n", dev->name));
1398
1399         if (!skb->len)
1400                 return NETDEV_TX_OK;
1401
1402         /* stop sending until this frame completes */
1403         netif_stop_queue(dev);
1404
1405         /* update network statistics */
1406         dev->stats.tx_packets++;
1407         dev->stats.tx_bytes += skb->len;
1408
1409         /* save start time for transmit timeout detection */
1410         netif_trans_update(dev);
1411
1412         spin_lock_irqsave(&info->lock, flags);
1413         tx_load(info, skb->data, skb->len);
1414         spin_unlock_irqrestore(&info->lock, flags);
1415
1416         /* done with socket buffer, so free it */
1417         dev_kfree_skb(skb);
1418
1419         return NETDEV_TX_OK;
1420 }
1421
1422 /**
1423  * hdlcdev_open - called by network layer when interface enabled
1424  * @dev: pointer to network device structure
1425  *
1426  * Claim resources and initialize hardware.
1427  *
1428  * Return: 0 if success, otherwise error code
1429  */
1430 static int hdlcdev_open(struct net_device *dev)
1431 {
1432         struct slgt_info *info = dev_to_port(dev);
1433         int rc;
1434         unsigned long flags;
1435
1436         DBGINFO(("%s hdlcdev_open\n", dev->name));
1437
1438         /* arbitrate between network and tty opens */
1439         spin_lock_irqsave(&info->netlock, flags);
1440         if (info->port.count != 0 || info->netcount != 0) {
1441                 DBGINFO(("%s hdlc_open busy\n", dev->name));
1442                 spin_unlock_irqrestore(&info->netlock, flags);
1443                 return -EBUSY;
1444         }
1445         info->netcount=1;
1446         spin_unlock_irqrestore(&info->netlock, flags);
1447
1448         /* claim resources and init adapter */
1449         if ((rc = startup(info)) != 0) {
1450                 spin_lock_irqsave(&info->netlock, flags);
1451                 info->netcount=0;
1452                 spin_unlock_irqrestore(&info->netlock, flags);
1453                 return rc;
1454         }
1455
1456         /* generic HDLC layer open processing */
1457         rc = hdlc_open(dev);
1458         if (rc) {
1459                 shutdown(info);
1460                 spin_lock_irqsave(&info->netlock, flags);
1461                 info->netcount = 0;
1462                 spin_unlock_irqrestore(&info->netlock, flags);
1463                 return rc;
1464         }
1465
1466         /* assert RTS and DTR, apply hardware settings */
1467         info->signals |= SerialSignal_RTS | SerialSignal_DTR;
1468         program_hw(info);
1469
1470         /* enable network layer transmit */
1471         netif_trans_update(dev);
1472         netif_start_queue(dev);
1473
1474         /* inform generic HDLC layer of current DCD status */
1475         spin_lock_irqsave(&info->lock, flags);
1476         get_gtsignals(info);
1477         spin_unlock_irqrestore(&info->lock, flags);
1478         if (info->signals & SerialSignal_DCD)
1479                 netif_carrier_on(dev);
1480         else
1481                 netif_carrier_off(dev);
1482         return 0;
1483 }
1484
1485 /**
1486  * hdlcdev_close - called by network layer when interface is disabled
1487  * @dev:  pointer to network device structure
1488  *
1489  * Shutdown hardware and release resources.
1490  *
1491  * Return: 0 if success, otherwise error code
1492  */
1493 static int hdlcdev_close(struct net_device *dev)
1494 {
1495         struct slgt_info *info = dev_to_port(dev);
1496         unsigned long flags;
1497
1498         DBGINFO(("%s hdlcdev_close\n", dev->name));
1499
1500         netif_stop_queue(dev);
1501
1502         /* shutdown adapter and release resources */
1503         shutdown(info);
1504
1505         hdlc_close(dev);
1506
1507         spin_lock_irqsave(&info->netlock, flags);
1508         info->netcount=0;
1509         spin_unlock_irqrestore(&info->netlock, flags);
1510
1511         return 0;
1512 }
1513
1514 /**
1515  * hdlcdev_ioctl - called by network layer to process IOCTL call to network device
1516  * @dev: pointer to network device structure
1517  * @ifr: pointer to network interface request structure
1518  * @cmd: IOCTL command code
1519  *
1520  * Return: 0 if success, otherwise error code
1521  */
1522 static int hdlcdev_ioctl(struct net_device *dev, struct if_settings *ifs)
1523 {
1524         const size_t size = sizeof(sync_serial_settings);
1525         sync_serial_settings new_line;
1526         sync_serial_settings __user *line = ifs->ifs_ifsu.sync;
1527         struct slgt_info *info = dev_to_port(dev);
1528         unsigned int flags;
1529
1530         DBGINFO(("%s hdlcdev_ioctl\n", dev->name));
1531
1532         /* return error if TTY interface open */
1533         if (info->port.count)
1534                 return -EBUSY;
1535
1536         memset(&new_line, 0, sizeof(new_line));
1537
1538         switch (ifs->type) {
1539         case IF_GET_IFACE: /* return current sync_serial_settings */
1540
1541                 ifs->type = IF_IFACE_SYNC_SERIAL;
1542                 if (ifs->size < size) {
1543                         ifs->size = size; /* data size wanted */
1544                         return -ENOBUFS;
1545                 }
1546
1547                 flags = info->params.flags & (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1548                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1549                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1550                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
1551
1552                 switch (flags){
1553                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN): new_line.clock_type = CLOCK_EXT; break;
1554                 case (HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_INT; break;
1555                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_TXINT; break;
1556                 case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN): new_line.clock_type = CLOCK_TXFROMRX; break;
1557                 default: new_line.clock_type = CLOCK_DEFAULT;
1558                 }
1559
1560                 new_line.clock_rate = info->params.clock_speed;
1561                 new_line.loopback   = info->params.loopback ? 1:0;
1562
1563                 if (copy_to_user(line, &new_line, size))
1564                         return -EFAULT;
1565                 return 0;
1566
1567         case IF_IFACE_SYNC_SERIAL: /* set sync_serial_settings */
1568
1569                 if(!capable(CAP_NET_ADMIN))
1570                         return -EPERM;
1571                 if (copy_from_user(&new_line, line, size))
1572                         return -EFAULT;
1573
1574                 switch (new_line.clock_type)
1575                 {
1576                 case CLOCK_EXT:      flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN; break;
1577                 case CLOCK_TXFROMRX: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN; break;
1578                 case CLOCK_INT:      flags = HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG;    break;
1579                 case CLOCK_TXINT:    flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG;    break;
1580                 case CLOCK_DEFAULT:  flags = info->params.flags &
1581                                              (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1582                                               HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1583                                               HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1584                                               HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN); break;
1585                 default: return -EINVAL;
1586                 }
1587
1588                 if (new_line.loopback != 0 && new_line.loopback != 1)
1589                         return -EINVAL;
1590
1591                 info->params.flags &= ~(HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1592                                         HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1593                                         HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1594                                         HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
1595                 info->params.flags |= flags;
1596
1597                 info->params.loopback = new_line.loopback;
1598
1599                 if (flags & (HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG))
1600                         info->params.clock_speed = new_line.clock_rate;
1601                 else
1602                         info->params.clock_speed = 0;
1603
1604                 /* if network interface up, reprogram hardware */
1605                 if (info->netcount)
1606                         program_hw(info);
1607                 return 0;
1608
1609         default:
1610                 return hdlc_ioctl(dev, ifs);
1611         }
1612 }
1613
1614 /**
1615  * hdlcdev_tx_timeout - called by network layer when transmit timeout is detected
1616  * @dev: pointer to network device structure
1617  * @txqueue: unused
1618  */
1619 static void hdlcdev_tx_timeout(struct net_device *dev, unsigned int txqueue)
1620 {
1621         struct slgt_info *info = dev_to_port(dev);
1622         unsigned long flags;
1623
1624         DBGINFO(("%s hdlcdev_tx_timeout\n", dev->name));
1625
1626         dev->stats.tx_errors++;
1627         dev->stats.tx_aborted_errors++;
1628
1629         spin_lock_irqsave(&info->lock,flags);
1630         tx_stop(info);
1631         spin_unlock_irqrestore(&info->lock,flags);
1632
1633         netif_wake_queue(dev);
1634 }
1635
1636 /**
1637  * hdlcdev_tx_done - called by device driver when transmit completes
1638  * @info: pointer to device instance information
1639  *
1640  * Reenable network layer transmit if stopped.
1641  */
1642 static void hdlcdev_tx_done(struct slgt_info *info)
1643 {
1644         if (netif_queue_stopped(info->netdev))
1645                 netif_wake_queue(info->netdev);
1646 }
1647
1648 /**
1649  * hdlcdev_rx - called by device driver when frame received
1650  * @info: pointer to device instance information
1651  * @buf:  pointer to buffer contianing frame data
1652  * @size: count of data bytes in buf
1653  *
1654  * Pass frame to network layer.
1655  */
1656 static void hdlcdev_rx(struct slgt_info *info, char *buf, int size)
1657 {
1658         struct sk_buff *skb = dev_alloc_skb(size);
1659         struct net_device *dev = info->netdev;
1660
1661         DBGINFO(("%s hdlcdev_rx\n", dev->name));
1662
1663         if (skb == NULL) {
1664                 DBGERR(("%s: can't alloc skb, drop packet\n", dev->name));
1665                 dev->stats.rx_dropped++;
1666                 return;
1667         }
1668
1669         skb_put_data(skb, buf, size);
1670
1671         skb->protocol = hdlc_type_trans(skb, dev);
1672
1673         dev->stats.rx_packets++;
1674         dev->stats.rx_bytes += size;
1675
1676         netif_rx(skb);
1677 }
1678
1679 static const struct net_device_ops hdlcdev_ops = {
1680         .ndo_open       = hdlcdev_open,
1681         .ndo_stop       = hdlcdev_close,
1682         .ndo_start_xmit = hdlc_start_xmit,
1683         .ndo_siocwandev = hdlcdev_ioctl,
1684         .ndo_tx_timeout = hdlcdev_tx_timeout,
1685 };
1686
1687 /**
1688  * hdlcdev_init - called by device driver when adding device instance
1689  * @info: pointer to device instance information
1690  *
1691  * Do generic HDLC initialization.
1692  *
1693  * Return: 0 if success, otherwise error code
1694  */
1695 static int hdlcdev_init(struct slgt_info *info)
1696 {
1697         int rc;
1698         struct net_device *dev;
1699         hdlc_device *hdlc;
1700
1701         /* allocate and initialize network and HDLC layer objects */
1702
1703         dev = alloc_hdlcdev(info);
1704         if (!dev) {
1705                 printk(KERN_ERR "%s hdlc device alloc failure\n", info->device_name);
1706                 return -ENOMEM;
1707         }
1708
1709         /* for network layer reporting purposes only */
1710         dev->mem_start = info->phys_reg_addr;
1711         dev->mem_end   = info->phys_reg_addr + SLGT_REG_SIZE - 1;
1712         dev->irq       = info->irq_level;
1713
1714         /* network layer callbacks and settings */
1715         dev->netdev_ops     = &hdlcdev_ops;
1716         dev->watchdog_timeo = 10 * HZ;
1717         dev->tx_queue_len   = 50;
1718
1719         /* generic HDLC layer callbacks and settings */
1720         hdlc         = dev_to_hdlc(dev);
1721         hdlc->attach = hdlcdev_attach;
1722         hdlc->xmit   = hdlcdev_xmit;
1723
1724         /* register objects with HDLC layer */
1725         rc = register_hdlc_device(dev);
1726         if (rc) {
1727                 printk(KERN_WARNING "%s:unable to register hdlc device\n",__FILE__);
1728                 free_netdev(dev);
1729                 return rc;
1730         }
1731
1732         info->netdev = dev;
1733         return 0;
1734 }
1735
1736 /**
1737  * hdlcdev_exit - called by device driver when removing device instance
1738  * @info: pointer to device instance information
1739  *
1740  * Do generic HDLC cleanup.
1741  */
1742 static void hdlcdev_exit(struct slgt_info *info)
1743 {
1744         if (!info->netdev)
1745                 return;
1746         unregister_hdlc_device(info->netdev);
1747         free_netdev(info->netdev);
1748         info->netdev = NULL;
1749 }
1750
1751 #endif /* ifdef CONFIG_HDLC */
1752
1753 /*
1754  * get async data from rx DMA buffers
1755  */
1756 static void rx_async(struct slgt_info *info)
1757 {
1758         struct mgsl_icount *icount = &info->icount;
1759         unsigned int start, end;
1760         unsigned char *p;
1761         unsigned char status;
1762         struct slgt_desc *bufs = info->rbufs;
1763         int i, count;
1764         int chars = 0;
1765         int stat;
1766         unsigned char ch;
1767
1768         start = end = info->rbuf_current;
1769
1770         while(desc_complete(bufs[end])) {
1771                 count = desc_count(bufs[end]) - info->rbuf_index;
1772                 p     = bufs[end].buf + info->rbuf_index;
1773
1774                 DBGISR(("%s rx_async count=%d\n", info->device_name, count));
1775                 DBGDATA(info, p, count, "rx");
1776
1777                 for(i=0 ; i < count; i+=2, p+=2) {
1778                         ch = *p;
1779                         icount->rx++;
1780
1781                         stat = 0;
1782
1783                         status = *(p + 1) & (BIT1 + BIT0);
1784                         if (status) {
1785                                 if (status & BIT1)
1786                                         icount->parity++;
1787                                 else if (status & BIT0)
1788                                         icount->frame++;
1789                                 /* discard char if tty control flags say so */
1790                                 if (status & info->ignore_status_mask)
1791                                         continue;
1792                                 if (status & BIT1)
1793                                         stat = TTY_PARITY;
1794                                 else if (status & BIT0)
1795                                         stat = TTY_FRAME;
1796                         }
1797                         tty_insert_flip_char(&info->port, ch, stat);
1798                         chars++;
1799                 }
1800
1801                 if (i < count) {
1802                         /* receive buffer not completed */
1803                         info->rbuf_index += i;
1804                         mod_timer(&info->rx_timer, jiffies + 1);
1805                         break;
1806                 }
1807
1808                 info->rbuf_index = 0;
1809                 free_rbufs(info, end, end);
1810
1811                 if (++end == info->rbuf_count)
1812                         end = 0;
1813
1814                 /* if entire list searched then no frame available */
1815                 if (end == start)
1816                         break;
1817         }
1818
1819         if (chars)
1820                 tty_flip_buffer_push(&info->port);
1821 }
1822
1823 /*
1824  * return next bottom half action to perform
1825  */
1826 static int bh_action(struct slgt_info *info)
1827 {
1828         unsigned long flags;
1829         int rc;
1830
1831         spin_lock_irqsave(&info->lock,flags);
1832
1833         if (info->pending_bh & BH_RECEIVE) {
1834                 info->pending_bh &= ~BH_RECEIVE;
1835                 rc = BH_RECEIVE;
1836         } else if (info->pending_bh & BH_TRANSMIT) {
1837                 info->pending_bh &= ~BH_TRANSMIT;
1838                 rc = BH_TRANSMIT;
1839         } else if (info->pending_bh & BH_STATUS) {
1840                 info->pending_bh &= ~BH_STATUS;
1841                 rc = BH_STATUS;
1842         } else {
1843                 /* Mark BH routine as complete */
1844                 info->bh_running = false;
1845                 info->bh_requested = false;
1846                 rc = 0;
1847         }
1848
1849         spin_unlock_irqrestore(&info->lock,flags);
1850
1851         return rc;
1852 }
1853
1854 /*
1855  * perform bottom half processing
1856  */
1857 static void bh_handler(struct work_struct *work)
1858 {
1859         struct slgt_info *info = container_of(work, struct slgt_info, task);
1860         int action;
1861
1862         info->bh_running = true;
1863
1864         while((action = bh_action(info))) {
1865                 switch (action) {
1866                 case BH_RECEIVE:
1867                         DBGBH(("%s bh receive\n", info->device_name));
1868                         switch(info->params.mode) {
1869                         case MGSL_MODE_ASYNC:
1870                                 rx_async(info);
1871                                 break;
1872                         case MGSL_MODE_HDLC:
1873                                 while(rx_get_frame(info));
1874                                 break;
1875                         case MGSL_MODE_RAW:
1876                         case MGSL_MODE_MONOSYNC:
1877                         case MGSL_MODE_BISYNC:
1878                         case MGSL_MODE_XSYNC:
1879                                 while(rx_get_buf(info));
1880                                 break;
1881                         }
1882                         /* restart receiver if rx DMA buffers exhausted */
1883                         if (info->rx_restart)
1884                                 rx_start(info);
1885                         break;
1886                 case BH_TRANSMIT:
1887                         bh_transmit(info);
1888                         break;
1889                 case BH_STATUS:
1890                         DBGBH(("%s bh status\n", info->device_name));
1891                         info->ri_chkcount = 0;
1892                         info->dsr_chkcount = 0;
1893                         info->dcd_chkcount = 0;
1894                         info->cts_chkcount = 0;
1895                         break;
1896                 default:
1897                         DBGBH(("%s unknown action\n", info->device_name));
1898                         break;
1899                 }
1900         }
1901         DBGBH(("%s bh_handler exit\n", info->device_name));
1902 }
1903
1904 static void bh_transmit(struct slgt_info *info)
1905 {
1906         struct tty_struct *tty = info->port.tty;
1907
1908         DBGBH(("%s bh_transmit\n", info->device_name));
1909         if (tty)
1910                 tty_wakeup(tty);
1911 }
1912
1913 static void dsr_change(struct slgt_info *info, unsigned short status)
1914 {
1915         if (status & BIT3) {
1916                 info->signals |= SerialSignal_DSR;
1917                 info->input_signal_events.dsr_up++;
1918         } else {
1919                 info->signals &= ~SerialSignal_DSR;
1920                 info->input_signal_events.dsr_down++;
1921         }
1922         DBGISR(("dsr_change %s signals=%04X\n", info->device_name, info->signals));
1923         if ((info->dsr_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
1924                 slgt_irq_off(info, IRQ_DSR);
1925                 return;
1926         }
1927         info->icount.dsr++;
1928         wake_up_interruptible(&info->status_event_wait_q);
1929         wake_up_interruptible(&info->event_wait_q);
1930         info->pending_bh |= BH_STATUS;
1931 }
1932
1933 static void cts_change(struct slgt_info *info, unsigned short status)
1934 {
1935         if (status & BIT2) {
1936                 info->signals |= SerialSignal_CTS;
1937                 info->input_signal_events.cts_up++;
1938         } else {
1939                 info->signals &= ~SerialSignal_CTS;
1940                 info->input_signal_events.cts_down++;
1941         }
1942         DBGISR(("cts_change %s signals=%04X\n", info->device_name, info->signals));
1943         if ((info->cts_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
1944                 slgt_irq_off(info, IRQ_CTS);
1945                 return;
1946         }
1947         info->icount.cts++;
1948         wake_up_interruptible(&info->status_event_wait_q);
1949         wake_up_interruptible(&info->event_wait_q);
1950         info->pending_bh |= BH_STATUS;
1951
1952         if (tty_port_cts_enabled(&info->port)) {
1953                 if (info->port.tty) {
1954                         if (info->port.tty->hw_stopped) {
1955                                 if (info->signals & SerialSignal_CTS) {
1956                                         info->port.tty->hw_stopped = 0;
1957                                         info->pending_bh |= BH_TRANSMIT;
1958                                         return;
1959                                 }
1960                         } else {
1961                                 if (!(info->signals & SerialSignal_CTS))
1962                                         info->port.tty->hw_stopped = 1;
1963                         }
1964                 }
1965         }
1966 }
1967
1968 static void dcd_change(struct slgt_info *info, unsigned short status)
1969 {
1970         if (status & BIT1) {
1971                 info->signals |= SerialSignal_DCD;
1972                 info->input_signal_events.dcd_up++;
1973         } else {
1974                 info->signals &= ~SerialSignal_DCD;
1975                 info->input_signal_events.dcd_down++;
1976         }
1977         DBGISR(("dcd_change %s signals=%04X\n", info->device_name, info->signals));
1978         if ((info->dcd_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
1979                 slgt_irq_off(info, IRQ_DCD);
1980                 return;
1981         }
1982         info->icount.dcd++;
1983 #if SYNCLINK_GENERIC_HDLC
1984         if (info->netcount) {
1985                 if (info->signals & SerialSignal_DCD)
1986                         netif_carrier_on(info->netdev);
1987                 else
1988                         netif_carrier_off(info->netdev);
1989         }
1990 #endif
1991         wake_up_interruptible(&info->status_event_wait_q);
1992         wake_up_interruptible(&info->event_wait_q);
1993         info->pending_bh |= BH_STATUS;
1994
1995         if (tty_port_check_carrier(&info->port)) {
1996                 if (info->signals & SerialSignal_DCD)
1997                         wake_up_interruptible(&info->port.open_wait);
1998                 else {
1999                         if (info->port.tty)
2000                                 tty_hangup(info->port.tty);
2001                 }
2002         }
2003 }
2004
2005 static void ri_change(struct slgt_info *info, unsigned short status)
2006 {
2007         if (status & BIT0) {
2008                 info->signals |= SerialSignal_RI;
2009                 info->input_signal_events.ri_up++;
2010         } else {
2011                 info->signals &= ~SerialSignal_RI;
2012                 info->input_signal_events.ri_down++;
2013         }
2014         DBGISR(("ri_change %s signals=%04X\n", info->device_name, info->signals));
2015         if ((info->ri_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
2016                 slgt_irq_off(info, IRQ_RI);
2017                 return;
2018         }
2019         info->icount.rng++;
2020         wake_up_interruptible(&info->status_event_wait_q);
2021         wake_up_interruptible(&info->event_wait_q);
2022         info->pending_bh |= BH_STATUS;
2023 }
2024
2025 static void isr_rxdata(struct slgt_info *info)
2026 {
2027         unsigned int count = info->rbuf_fill_count;
2028         unsigned int i = info->rbuf_fill_index;
2029         unsigned short reg;
2030
2031         while (rd_reg16(info, SSR) & IRQ_RXDATA) {
2032                 reg = rd_reg16(info, RDR);
2033                 DBGISR(("isr_rxdata %s RDR=%04X\n", info->device_name, reg));
2034                 if (desc_complete(info->rbufs[i])) {
2035                         /* all buffers full */
2036                         rx_stop(info);
2037                         info->rx_restart = true;
2038                         continue;
2039                 }
2040                 info->rbufs[i].buf[count++] = (unsigned char)reg;
2041                 /* async mode saves status byte to buffer for each data byte */
2042                 if (info->params.mode == MGSL_MODE_ASYNC)
2043                         info->rbufs[i].buf[count++] = (unsigned char)(reg >> 8);
2044                 if (count == info->rbuf_fill_level || (reg & BIT10)) {
2045                         /* buffer full or end of frame */
2046                         set_desc_count(info->rbufs[i], count);
2047                         set_desc_status(info->rbufs[i], BIT15 | (reg >> 8));
2048                         info->rbuf_fill_count = count = 0;
2049                         if (++i == info->rbuf_count)
2050                                 i = 0;
2051                         info->pending_bh |= BH_RECEIVE;
2052                 }
2053         }
2054
2055         info->rbuf_fill_index = i;
2056         info->rbuf_fill_count = count;
2057 }
2058
2059 static void isr_serial(struct slgt_info *info)
2060 {
2061         unsigned short status = rd_reg16(info, SSR);
2062
2063         DBGISR(("%s isr_serial status=%04X\n", info->device_name, status));
2064
2065         wr_reg16(info, SSR, status); /* clear pending */
2066
2067         info->irq_occurred = true;
2068
2069         if (info->params.mode == MGSL_MODE_ASYNC) {
2070                 if (status & IRQ_TXIDLE) {
2071                         if (info->tx_active)
2072                                 isr_txeom(info, status);
2073                 }
2074                 if (info->rx_pio && (status & IRQ_RXDATA))
2075                         isr_rxdata(info);
2076                 if ((status & IRQ_RXBREAK) && (status & RXBREAK)) {
2077                         info->icount.brk++;
2078                         /* process break detection if tty control allows */
2079                         if (info->port.tty) {
2080                                 if (!(status & info->ignore_status_mask)) {
2081                                         if (info->read_status_mask & MASK_BREAK) {
2082                                                 tty_insert_flip_char(&info->port, 0, TTY_BREAK);
2083                                                 if (info->port.flags & ASYNC_SAK)
2084                                                         do_SAK(info->port.tty);
2085                                         }
2086                                 }
2087                         }
2088                 }
2089         } else {
2090                 if (status & (IRQ_TXIDLE + IRQ_TXUNDER))
2091                         isr_txeom(info, status);
2092                 if (info->rx_pio && (status & IRQ_RXDATA))
2093                         isr_rxdata(info);
2094                 if (status & IRQ_RXIDLE) {
2095                         if (status & RXIDLE)
2096                                 info->icount.rxidle++;
2097                         else
2098                                 info->icount.exithunt++;
2099                         wake_up_interruptible(&info->event_wait_q);
2100                 }
2101
2102                 if (status & IRQ_RXOVER)
2103                         rx_start(info);
2104         }
2105
2106         if (status & IRQ_DSR)
2107                 dsr_change(info, status);
2108         if (status & IRQ_CTS)
2109                 cts_change(info, status);
2110         if (status & IRQ_DCD)
2111                 dcd_change(info, status);
2112         if (status & IRQ_RI)
2113                 ri_change(info, status);
2114 }
2115
2116 static void isr_rdma(struct slgt_info *info)
2117 {
2118         unsigned int status = rd_reg32(info, RDCSR);
2119
2120         DBGISR(("%s isr_rdma status=%08x\n", info->device_name, status));
2121
2122         /* RDCSR (rx DMA control/status)
2123          *
2124          * 31..07  reserved
2125          * 06      save status byte to DMA buffer
2126          * 05      error
2127          * 04      eol (end of list)
2128          * 03      eob (end of buffer)
2129          * 02      IRQ enable
2130          * 01      reset
2131          * 00      enable
2132          */
2133         wr_reg32(info, RDCSR, status);  /* clear pending */
2134
2135         if (status & (BIT5 + BIT4)) {
2136                 DBGISR(("%s isr_rdma rx_restart=1\n", info->device_name));
2137                 info->rx_restart = true;
2138         }
2139         info->pending_bh |= BH_RECEIVE;
2140 }
2141
2142 static void isr_tdma(struct slgt_info *info)
2143 {
2144         unsigned int status = rd_reg32(info, TDCSR);
2145
2146         DBGISR(("%s isr_tdma status=%08x\n", info->device_name, status));
2147
2148         /* TDCSR (tx DMA control/status)
2149          *
2150          * 31..06  reserved
2151          * 05      error
2152          * 04      eol (end of list)
2153          * 03      eob (end of buffer)
2154          * 02      IRQ enable
2155          * 01      reset
2156          * 00      enable
2157          */
2158         wr_reg32(info, TDCSR, status);  /* clear pending */
2159
2160         if (status & (BIT5 + BIT4 + BIT3)) {
2161                 // another transmit buffer has completed
2162                 // run bottom half to get more send data from user
2163                 info->pending_bh |= BH_TRANSMIT;
2164         }
2165 }
2166
2167 /*
2168  * return true if there are unsent tx DMA buffers, otherwise false
2169  *
2170  * if there are unsent buffers then info->tbuf_start
2171  * is set to index of first unsent buffer
2172  */
2173 static bool unsent_tbufs(struct slgt_info *info)
2174 {
2175         unsigned int i = info->tbuf_current;
2176         bool rc = false;
2177
2178         /*
2179          * search backwards from last loaded buffer (precedes tbuf_current)
2180          * for first unsent buffer (desc_count > 0)
2181          */
2182
2183         do {
2184                 if (i)
2185                         i--;
2186                 else
2187                         i = info->tbuf_count - 1;
2188                 if (!desc_count(info->tbufs[i]))
2189                         break;
2190                 info->tbuf_start = i;
2191                 rc = true;
2192         } while (i != info->tbuf_current);
2193
2194         return rc;
2195 }
2196
2197 static void isr_txeom(struct slgt_info *info, unsigned short status)
2198 {
2199         DBGISR(("%s txeom status=%04x\n", info->device_name, status));
2200
2201         slgt_irq_off(info, IRQ_TXDATA + IRQ_TXIDLE + IRQ_TXUNDER);
2202         tdma_reset(info);
2203         if (status & IRQ_TXUNDER) {
2204                 unsigned short val = rd_reg16(info, TCR);
2205                 wr_reg16(info, TCR, (unsigned short)(val | BIT2)); /* set reset bit */
2206                 wr_reg16(info, TCR, val); /* clear reset bit */
2207         }
2208
2209         if (info->tx_active) {
2210                 if (info->params.mode != MGSL_MODE_ASYNC) {
2211                         if (status & IRQ_TXUNDER)
2212                                 info->icount.txunder++;
2213                         else if (status & IRQ_TXIDLE)
2214                                 info->icount.txok++;
2215                 }
2216
2217                 if (unsent_tbufs(info)) {
2218                         tx_start(info);
2219                         update_tx_timer(info);
2220                         return;
2221                 }
2222                 info->tx_active = false;
2223
2224                 del_timer(&info->tx_timer);
2225
2226                 if (info->params.mode != MGSL_MODE_ASYNC && info->drop_rts_on_tx_done) {
2227                         info->signals &= ~SerialSignal_RTS;
2228                         info->drop_rts_on_tx_done = false;
2229                         set_gtsignals(info);
2230                 }
2231
2232 #if SYNCLINK_GENERIC_HDLC
2233                 if (info->netcount)
2234                         hdlcdev_tx_done(info);
2235                 else
2236 #endif
2237                 {
2238                         if (info->port.tty && (info->port.tty->flow.stopped || info->port.tty->hw_stopped)) {
2239                                 tx_stop(info);
2240                                 return;
2241                         }
2242                         info->pending_bh |= BH_TRANSMIT;
2243                 }
2244         }
2245 }
2246
2247 static void isr_gpio(struct slgt_info *info, unsigned int changed, unsigned int state)
2248 {
2249         struct cond_wait *w, *prev;
2250
2251         /* wake processes waiting for specific transitions */
2252         for (w = info->gpio_wait_q, prev = NULL ; w != NULL ; w = w->next) {
2253                 if (w->data & changed) {
2254                         w->data = state;
2255                         wake_up_interruptible(&w->q);
2256                         if (prev != NULL)
2257                                 prev->next = w->next;
2258                         else
2259                                 info->gpio_wait_q = w->next;
2260                 } else
2261                         prev = w;
2262         }
2263 }
2264
2265 /* interrupt service routine
2266  *
2267  *      irq     interrupt number
2268  *      dev_id  device ID supplied during interrupt registration
2269  */
2270 static irqreturn_t slgt_interrupt(int dummy, void *dev_id)
2271 {
2272         struct slgt_info *info = dev_id;
2273         unsigned int gsr;
2274         unsigned int i;
2275
2276         DBGISR(("slgt_interrupt irq=%d entry\n", info->irq_level));
2277
2278         while((gsr = rd_reg32(info, GSR) & 0xffffff00)) {
2279                 DBGISR(("%s gsr=%08x\n", info->device_name, gsr));
2280                 info->irq_occurred = true;
2281                 for(i=0; i < info->port_count ; i++) {
2282                         if (info->port_array[i] == NULL)
2283                                 continue;
2284                         spin_lock(&info->port_array[i]->lock);
2285                         if (gsr & (BIT8 << i))
2286                                 isr_serial(info->port_array[i]);
2287                         if (gsr & (BIT16 << (i*2)))
2288                                 isr_rdma(info->port_array[i]);
2289                         if (gsr & (BIT17 << (i*2)))
2290                                 isr_tdma(info->port_array[i]);
2291                         spin_unlock(&info->port_array[i]->lock);
2292                 }
2293         }
2294
2295         if (info->gpio_present) {
2296                 unsigned int state;
2297                 unsigned int changed;
2298                 spin_lock(&info->lock);
2299                 while ((changed = rd_reg32(info, IOSR)) != 0) {
2300                         DBGISR(("%s iosr=%08x\n", info->device_name, changed));
2301                         /* read latched state of GPIO signals */
2302                         state = rd_reg32(info, IOVR);
2303                         /* clear pending GPIO interrupt bits */
2304                         wr_reg32(info, IOSR, changed);
2305                         for (i=0 ; i < info->port_count ; i++) {
2306                                 if (info->port_array[i] != NULL)
2307                                         isr_gpio(info->port_array[i], changed, state);
2308                         }
2309                 }
2310                 spin_unlock(&info->lock);
2311         }
2312
2313         for(i=0; i < info->port_count ; i++) {
2314                 struct slgt_info *port = info->port_array[i];
2315                 if (port == NULL)
2316                         continue;
2317                 spin_lock(&port->lock);
2318                 if ((port->port.count || port->netcount) &&
2319                     port->pending_bh && !port->bh_running &&
2320                     !port->bh_requested) {
2321                         DBGISR(("%s bh queued\n", port->device_name));
2322                         schedule_work(&port->task);
2323                         port->bh_requested = true;
2324                 }
2325                 spin_unlock(&port->lock);
2326         }
2327
2328         DBGISR(("slgt_interrupt irq=%d exit\n", info->irq_level));
2329         return IRQ_HANDLED;
2330 }
2331
2332 static int startup(struct slgt_info *info)
2333 {
2334         DBGINFO(("%s startup\n", info->device_name));
2335
2336         if (tty_port_initialized(&info->port))
2337                 return 0;
2338
2339         if (!info->tx_buf) {
2340                 info->tx_buf = kmalloc(info->max_frame_size, GFP_KERNEL);
2341                 if (!info->tx_buf) {
2342                         DBGERR(("%s can't allocate tx buffer\n", info->device_name));
2343                         return -ENOMEM;
2344                 }
2345         }
2346
2347         info->pending_bh = 0;
2348
2349         memset(&info->icount, 0, sizeof(info->icount));
2350
2351         /* program hardware for current parameters */
2352         change_params(info);
2353
2354         if (info->port.tty)
2355                 clear_bit(TTY_IO_ERROR, &info->port.tty->flags);
2356
2357         tty_port_set_initialized(&info->port, true);
2358
2359         return 0;
2360 }
2361
2362 /*
2363  *  called by close() and hangup() to shutdown hardware
2364  */
2365 static void shutdown(struct slgt_info *info)
2366 {
2367         unsigned long flags;
2368
2369         if (!tty_port_initialized(&info->port))
2370                 return;
2371
2372         DBGINFO(("%s shutdown\n", info->device_name));
2373
2374         /* clear status wait queue because status changes */
2375         /* can't happen after shutting down the hardware */
2376         wake_up_interruptible(&info->status_event_wait_q);
2377         wake_up_interruptible(&info->event_wait_q);
2378
2379         del_timer_sync(&info->tx_timer);
2380         del_timer_sync(&info->rx_timer);
2381
2382         kfree(info->tx_buf);
2383         info->tx_buf = NULL;
2384
2385         spin_lock_irqsave(&info->lock,flags);
2386
2387         tx_stop(info);
2388         rx_stop(info);
2389
2390         slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
2391
2392         if (!info->port.tty || info->port.tty->termios.c_cflag & HUPCL) {
2393                 info->signals &= ~(SerialSignal_RTS | SerialSignal_DTR);
2394                 set_gtsignals(info);
2395         }
2396
2397         flush_cond_wait(&info->gpio_wait_q);
2398
2399         spin_unlock_irqrestore(&info->lock,flags);
2400
2401         if (info->port.tty)
2402                 set_bit(TTY_IO_ERROR, &info->port.tty->flags);
2403
2404         tty_port_set_initialized(&info->port, false);
2405 }
2406
2407 static void program_hw(struct slgt_info *info)
2408 {
2409         unsigned long flags;
2410
2411         spin_lock_irqsave(&info->lock,flags);
2412
2413         rx_stop(info);
2414         tx_stop(info);
2415
2416         if (info->params.mode != MGSL_MODE_ASYNC ||
2417             info->netcount)
2418                 sync_mode(info);
2419         else
2420                 async_mode(info);
2421
2422         set_gtsignals(info);
2423
2424         info->dcd_chkcount = 0;
2425         info->cts_chkcount = 0;
2426         info->ri_chkcount = 0;
2427         info->dsr_chkcount = 0;
2428
2429         slgt_irq_on(info, IRQ_DCD | IRQ_CTS | IRQ_DSR | IRQ_RI);
2430         get_gtsignals(info);
2431
2432         if (info->netcount ||
2433             (info->port.tty && info->port.tty->termios.c_cflag & CREAD))
2434                 rx_start(info);
2435
2436         spin_unlock_irqrestore(&info->lock,flags);
2437 }
2438
2439 /*
2440  * reconfigure adapter based on new parameters
2441  */
2442 static void change_params(struct slgt_info *info)
2443 {
2444         unsigned cflag;
2445         int bits_per_char;
2446
2447         if (!info->port.tty)
2448                 return;
2449         DBGINFO(("%s change_params\n", info->device_name));
2450
2451         cflag = info->port.tty->termios.c_cflag;
2452
2453         /* if B0 rate (hangup) specified then negate RTS and DTR */
2454         /* otherwise assert RTS and DTR */
2455         if (cflag & CBAUD)
2456                 info->signals |= SerialSignal_RTS | SerialSignal_DTR;
2457         else
2458                 info->signals &= ~(SerialSignal_RTS | SerialSignal_DTR);
2459
2460         /* byte size and parity */
2461
2462         info->params.data_bits = tty_get_char_size(cflag);
2463         info->params.stop_bits = (cflag & CSTOPB) ? 2 : 1;
2464
2465         if (cflag & PARENB)
2466                 info->params.parity = (cflag & PARODD) ? ASYNC_PARITY_ODD : ASYNC_PARITY_EVEN;
2467         else
2468                 info->params.parity = ASYNC_PARITY_NONE;
2469
2470         /* calculate number of jiffies to transmit a full
2471          * FIFO (32 bytes) at specified data rate
2472          */
2473         bits_per_char = info->params.data_bits +
2474                         info->params.stop_bits + 1;
2475
2476         info->params.data_rate = tty_get_baud_rate(info->port.tty);
2477
2478         if (info->params.data_rate) {
2479                 info->timeout = (32*HZ*bits_per_char) /
2480                                 info->params.data_rate;
2481         }
2482         info->timeout += HZ/50;         /* Add .02 seconds of slop */
2483
2484         tty_port_set_cts_flow(&info->port, cflag & CRTSCTS);
2485         tty_port_set_check_carrier(&info->port, ~cflag & CLOCAL);
2486
2487         /* process tty input control flags */
2488
2489         info->read_status_mask = IRQ_RXOVER;
2490         if (I_INPCK(info->port.tty))
2491                 info->read_status_mask |= MASK_PARITY | MASK_FRAMING;
2492         if (I_BRKINT(info->port.tty) || I_PARMRK(info->port.tty))
2493                 info->read_status_mask |= MASK_BREAK;
2494         if (I_IGNPAR(info->port.tty))
2495                 info->ignore_status_mask |= MASK_PARITY | MASK_FRAMING;
2496         if (I_IGNBRK(info->port.tty)) {
2497                 info->ignore_status_mask |= MASK_BREAK;
2498                 /* If ignoring parity and break indicators, ignore
2499                  * overruns too.  (For real raw support).
2500                  */
2501                 if (I_IGNPAR(info->port.tty))
2502                         info->ignore_status_mask |= MASK_OVERRUN;
2503         }
2504
2505         program_hw(info);
2506 }
2507
2508 static int get_stats(struct slgt_info *info, struct mgsl_icount __user *user_icount)
2509 {
2510         DBGINFO(("%s get_stats\n",  info->device_name));
2511         if (!user_icount) {
2512                 memset(&info->icount, 0, sizeof(info->icount));
2513         } else {
2514                 if (copy_to_user(user_icount, &info->icount, sizeof(struct mgsl_icount)))
2515                         return -EFAULT;
2516         }
2517         return 0;
2518 }
2519
2520 static int get_params(struct slgt_info *info, MGSL_PARAMS __user *user_params)
2521 {
2522         DBGINFO(("%s get_params\n", info->device_name));
2523         if (copy_to_user(user_params, &info->params, sizeof(MGSL_PARAMS)))
2524                 return -EFAULT;
2525         return 0;
2526 }
2527
2528 static int set_params(struct slgt_info *info, MGSL_PARAMS __user *new_params)
2529 {
2530         unsigned long flags;
2531         MGSL_PARAMS tmp_params;
2532
2533         DBGINFO(("%s set_params\n", info->device_name));
2534         if (copy_from_user(&tmp_params, new_params, sizeof(MGSL_PARAMS)))
2535                 return -EFAULT;
2536
2537         spin_lock_irqsave(&info->lock, flags);
2538         if (tmp_params.mode == MGSL_MODE_BASE_CLOCK)
2539                 info->base_clock = tmp_params.clock_speed;
2540         else
2541                 memcpy(&info->params, &tmp_params, sizeof(MGSL_PARAMS));
2542         spin_unlock_irqrestore(&info->lock, flags);
2543
2544         program_hw(info);
2545
2546         return 0;
2547 }
2548
2549 static int get_txidle(struct slgt_info *info, int __user *idle_mode)
2550 {
2551         DBGINFO(("%s get_txidle=%d\n", info->device_name, info->idle_mode));
2552         if (put_user(info->idle_mode, idle_mode))
2553                 return -EFAULT;
2554         return 0;
2555 }
2556
2557 static int set_txidle(struct slgt_info *info, int idle_mode)
2558 {
2559         unsigned long flags;
2560         DBGINFO(("%s set_txidle(%d)\n", info->device_name, idle_mode));
2561         spin_lock_irqsave(&info->lock,flags);
2562         info->idle_mode = idle_mode;
2563         if (info->params.mode != MGSL_MODE_ASYNC)
2564                 tx_set_idle(info);
2565         spin_unlock_irqrestore(&info->lock,flags);
2566         return 0;
2567 }
2568
2569 static int tx_enable(struct slgt_info *info, int enable)
2570 {
2571         unsigned long flags;
2572         DBGINFO(("%s tx_enable(%d)\n", info->device_name, enable));
2573         spin_lock_irqsave(&info->lock,flags);
2574         if (enable) {
2575                 if (!info->tx_enabled)
2576                         tx_start(info);
2577         } else {
2578                 if (info->tx_enabled)
2579                         tx_stop(info);
2580         }
2581         spin_unlock_irqrestore(&info->lock,flags);
2582         return 0;
2583 }
2584
2585 /*
2586  * abort transmit HDLC frame
2587  */
2588 static int tx_abort(struct slgt_info *info)
2589 {
2590         unsigned long flags;
2591         DBGINFO(("%s tx_abort\n", info->device_name));
2592         spin_lock_irqsave(&info->lock,flags);
2593         tdma_reset(info);
2594         spin_unlock_irqrestore(&info->lock,flags);
2595         return 0;
2596 }
2597
2598 static int rx_enable(struct slgt_info *info, int enable)
2599 {
2600         unsigned long flags;
2601         unsigned int rbuf_fill_level;
2602         DBGINFO(("%s rx_enable(%08x)\n", info->device_name, enable));
2603         spin_lock_irqsave(&info->lock,flags);
2604         /*
2605          * enable[31..16] = receive DMA buffer fill level
2606          * 0 = noop (leave fill level unchanged)
2607          * fill level must be multiple of 4 and <= buffer size
2608          */
2609         rbuf_fill_level = ((unsigned int)enable) >> 16;
2610         if (rbuf_fill_level) {
2611                 if ((rbuf_fill_level > DMABUFSIZE) || (rbuf_fill_level % 4)) {
2612                         spin_unlock_irqrestore(&info->lock, flags);
2613                         return -EINVAL;
2614                 }
2615                 info->rbuf_fill_level = rbuf_fill_level;
2616                 if (rbuf_fill_level < 128)
2617                         info->rx_pio = 1; /* PIO mode */
2618                 else
2619                         info->rx_pio = 0; /* DMA mode */
2620                 rx_stop(info); /* restart receiver to use new fill level */
2621         }
2622
2623         /*
2624          * enable[1..0] = receiver enable command
2625          * 0 = disable
2626          * 1 = enable
2627          * 2 = enable or force hunt mode if already enabled
2628          */
2629         enable &= 3;
2630         if (enable) {
2631                 if (!info->rx_enabled)
2632                         rx_start(info);
2633                 else if (enable == 2) {
2634                         /* force hunt mode (write 1 to RCR[3]) */
2635                         wr_reg16(info, RCR, rd_reg16(info, RCR) | BIT3);
2636                 }
2637         } else {
2638                 if (info->rx_enabled)
2639                         rx_stop(info);
2640         }
2641         spin_unlock_irqrestore(&info->lock,flags);
2642         return 0;
2643 }
2644
2645 /*
2646  *  wait for specified event to occur
2647  */
2648 static int wait_mgsl_event(struct slgt_info *info, int __user *mask_ptr)
2649 {
2650         unsigned long flags;
2651         int s;
2652         int rc=0;
2653         struct mgsl_icount cprev, cnow;
2654         int events;
2655         int mask;
2656         struct  _input_signal_events oldsigs, newsigs;
2657         DECLARE_WAITQUEUE(wait, current);
2658
2659         if (get_user(mask, mask_ptr))
2660                 return -EFAULT;
2661
2662         DBGINFO(("%s wait_mgsl_event(%d)\n", info->device_name, mask));
2663
2664         spin_lock_irqsave(&info->lock,flags);
2665
2666         /* return immediately if state matches requested events */
2667         get_gtsignals(info);
2668         s = info->signals;
2669
2670         events = mask &
2671                 ( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) +
2672                   ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) +
2673                   ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) +
2674                   ((s & SerialSignal_RI)  ? MgslEvent_RiActive :MgslEvent_RiInactive) );
2675         if (events) {
2676                 spin_unlock_irqrestore(&info->lock,flags);
2677                 goto exit;
2678         }
2679
2680         /* save current irq counts */
2681         cprev = info->icount;
2682         oldsigs = info->input_signal_events;
2683
2684         /* enable hunt and idle irqs if needed */
2685         if (mask & (MgslEvent_ExitHuntMode+MgslEvent_IdleReceived)) {
2686                 unsigned short val = rd_reg16(info, SCR);
2687                 if (!(val & IRQ_RXIDLE))
2688                         wr_reg16(info, SCR, (unsigned short)(val | IRQ_RXIDLE));
2689         }
2690
2691         set_current_state(TASK_INTERRUPTIBLE);
2692         add_wait_queue(&info->event_wait_q, &wait);
2693
2694         spin_unlock_irqrestore(&info->lock,flags);
2695
2696         for(;;) {
2697                 schedule();
2698                 if (signal_pending(current)) {
2699                         rc = -ERESTARTSYS;
2700                         break;
2701                 }
2702
2703                 /* get current irq counts */
2704                 spin_lock_irqsave(&info->lock,flags);
2705                 cnow = info->icount;
2706                 newsigs = info->input_signal_events;
2707                 set_current_state(TASK_INTERRUPTIBLE);
2708                 spin_unlock_irqrestore(&info->lock,flags);
2709
2710                 /* if no change, wait aborted for some reason */
2711                 if (newsigs.dsr_up   == oldsigs.dsr_up   &&
2712                     newsigs.dsr_down == oldsigs.dsr_down &&
2713                     newsigs.dcd_up   == oldsigs.dcd_up   &&
2714                     newsigs.dcd_down == oldsigs.dcd_down &&
2715                     newsigs.cts_up   == oldsigs.cts_up   &&
2716                     newsigs.cts_down == oldsigs.cts_down &&
2717                     newsigs.ri_up    == oldsigs.ri_up    &&
2718                     newsigs.ri_down  == oldsigs.ri_down  &&
2719                     cnow.exithunt    == cprev.exithunt   &&
2720                     cnow.rxidle      == cprev.rxidle) {
2721                         rc = -EIO;
2722                         break;
2723                 }
2724
2725                 events = mask &
2726                         ( (newsigs.dsr_up   != oldsigs.dsr_up   ? MgslEvent_DsrActive:0)   +
2727                           (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) +
2728                           (newsigs.dcd_up   != oldsigs.dcd_up   ? MgslEvent_DcdActive:0)   +
2729                           (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) +
2730                           (newsigs.cts_up   != oldsigs.cts_up   ? MgslEvent_CtsActive:0)   +
2731                           (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) +
2732                           (newsigs.ri_up    != oldsigs.ri_up    ? MgslEvent_RiActive:0)    +
2733                           (newsigs.ri_down  != oldsigs.ri_down  ? MgslEvent_RiInactive:0)  +
2734                           (cnow.exithunt    != cprev.exithunt   ? MgslEvent_ExitHuntMode:0) +
2735                           (cnow.rxidle      != cprev.rxidle     ? MgslEvent_IdleReceived:0) );
2736                 if (events)
2737                         break;
2738
2739                 cprev = cnow;
2740                 oldsigs = newsigs;
2741         }
2742
2743         remove_wait_queue(&info->event_wait_q, &wait);
2744         set_current_state(TASK_RUNNING);
2745
2746
2747         if (mask & (MgslEvent_ExitHuntMode + MgslEvent_IdleReceived)) {
2748                 spin_lock_irqsave(&info->lock,flags);
2749                 if (!waitqueue_active(&info->event_wait_q)) {
2750                         /* disable enable exit hunt mode/idle rcvd IRQs */
2751                         wr_reg16(info, SCR,
2752                                 (unsigned short)(rd_reg16(info, SCR) & ~IRQ_RXIDLE));
2753                 }
2754                 spin_unlock_irqrestore(&info->lock,flags);
2755         }
2756 exit:
2757         if (rc == 0)
2758                 rc = put_user(events, mask_ptr);
2759         return rc;
2760 }
2761
2762 static int get_interface(struct slgt_info *info, int __user *if_mode)
2763 {
2764         DBGINFO(("%s get_interface=%x\n", info->device_name, info->if_mode));
2765         if (put_user(info->if_mode, if_mode))
2766                 return -EFAULT;
2767         return 0;
2768 }
2769
2770 static int set_interface(struct slgt_info *info, int if_mode)
2771 {
2772         unsigned long flags;
2773         unsigned short val;
2774
2775         DBGINFO(("%s set_interface=%x)\n", info->device_name, if_mode));
2776         spin_lock_irqsave(&info->lock,flags);
2777         info->if_mode = if_mode;
2778
2779         msc_set_vcr(info);
2780
2781         /* TCR (tx control) 07  1=RTS driver control */
2782         val = rd_reg16(info, TCR);
2783         if (info->if_mode & MGSL_INTERFACE_RTS_EN)
2784                 val |= BIT7;
2785         else
2786                 val &= ~BIT7;
2787         wr_reg16(info, TCR, val);
2788
2789         spin_unlock_irqrestore(&info->lock,flags);
2790         return 0;
2791 }
2792
2793 static int get_xsync(struct slgt_info *info, int __user *xsync)
2794 {
2795         DBGINFO(("%s get_xsync=%x\n", info->device_name, info->xsync));
2796         if (put_user(info->xsync, xsync))
2797                 return -EFAULT;
2798         return 0;
2799 }
2800
2801 /*
2802  * set extended sync pattern (1 to 4 bytes) for extended sync mode
2803  *
2804  * sync pattern is contained in least significant bytes of value
2805  * most significant byte of sync pattern is oldest (1st sent/detected)
2806  */
2807 static int set_xsync(struct slgt_info *info, int xsync)
2808 {
2809         unsigned long flags;
2810
2811         DBGINFO(("%s set_xsync=%x)\n", info->device_name, xsync));
2812         spin_lock_irqsave(&info->lock, flags);
2813         info->xsync = xsync;
2814         wr_reg32(info, XSR, xsync);
2815         spin_unlock_irqrestore(&info->lock, flags);
2816         return 0;
2817 }
2818
2819 static int get_xctrl(struct slgt_info *info, int __user *xctrl)
2820 {
2821         DBGINFO(("%s get_xctrl=%x\n", info->device_name, info->xctrl));
2822         if (put_user(info->xctrl, xctrl))
2823                 return -EFAULT;
2824         return 0;
2825 }
2826
2827 /*
2828  * set extended control options
2829  *
2830  * xctrl[31:19] reserved, must be zero
2831  * xctrl[18:17] extended sync pattern length in bytes
2832  *              00 = 1 byte  in xsr[7:0]
2833  *              01 = 2 bytes in xsr[15:0]
2834  *              10 = 3 bytes in xsr[23:0]
2835  *              11 = 4 bytes in xsr[31:0]
2836  * xctrl[16]    1 = enable terminal count, 0=disabled
2837  * xctrl[15:0]  receive terminal count for fixed length packets
2838  *              value is count minus one (0 = 1 byte packet)
2839  *              when terminal count is reached, receiver
2840  *              automatically returns to hunt mode and receive
2841  *              FIFO contents are flushed to DMA buffers with
2842  *              end of frame (EOF) status
2843  */
2844 static int set_xctrl(struct slgt_info *info, int xctrl)
2845 {
2846         unsigned long flags;
2847
2848         DBGINFO(("%s set_xctrl=%x)\n", info->device_name, xctrl));
2849         spin_lock_irqsave(&info->lock, flags);
2850         info->xctrl = xctrl;
2851         wr_reg32(info, XCR, xctrl);
2852         spin_unlock_irqrestore(&info->lock, flags);
2853         return 0;
2854 }
2855
2856 /*
2857  * set general purpose IO pin state and direction
2858  *
2859  * user_gpio fields:
2860  * state   each bit indicates a pin state
2861  * smask   set bit indicates pin state to set
2862  * dir     each bit indicates a pin direction (0=input, 1=output)
2863  * dmask   set bit indicates pin direction to set
2864  */
2865 static int set_gpio(struct slgt_info *info, struct gpio_desc __user *user_gpio)
2866 {
2867         unsigned long flags;
2868         struct gpio_desc gpio;
2869         __u32 data;
2870
2871         if (!info->gpio_present)
2872                 return -EINVAL;
2873         if (copy_from_user(&gpio, user_gpio, sizeof(gpio)))
2874                 return -EFAULT;
2875         DBGINFO(("%s set_gpio state=%08x smask=%08x dir=%08x dmask=%08x\n",
2876                  info->device_name, gpio.state, gpio.smask,
2877                  gpio.dir, gpio.dmask));
2878
2879         spin_lock_irqsave(&info->port_array[0]->lock, flags);
2880         if (gpio.dmask) {
2881                 data = rd_reg32(info, IODR);
2882                 data |= gpio.dmask & gpio.dir;
2883                 data &= ~(gpio.dmask & ~gpio.dir);
2884                 wr_reg32(info, IODR, data);
2885         }
2886         if (gpio.smask) {
2887                 data = rd_reg32(info, IOVR);
2888                 data |= gpio.smask & gpio.state;
2889                 data &= ~(gpio.smask & ~gpio.state);
2890                 wr_reg32(info, IOVR, data);
2891         }
2892         spin_unlock_irqrestore(&info->port_array[0]->lock, flags);
2893
2894         return 0;
2895 }
2896
2897 /*
2898  * get general purpose IO pin state and direction
2899  */
2900 static int get_gpio(struct slgt_info *info, struct gpio_desc __user *user_gpio)
2901 {
2902         struct gpio_desc gpio;
2903         if (!info->gpio_present)
2904                 return -EINVAL;
2905         gpio.state = rd_reg32(info, IOVR);
2906         gpio.smask = 0xffffffff;
2907         gpio.dir   = rd_reg32(info, IODR);
2908         gpio.dmask = 0xffffffff;
2909         if (copy_to_user(user_gpio, &gpio, sizeof(gpio)))
2910                 return -EFAULT;
2911         DBGINFO(("%s get_gpio state=%08x dir=%08x\n",
2912                  info->device_name, gpio.state, gpio.dir));
2913         return 0;
2914 }
2915
2916 /*
2917  * conditional wait facility
2918  */
2919 static void init_cond_wait(struct cond_wait *w, unsigned int data)
2920 {
2921         init_waitqueue_head(&w->q);
2922         init_waitqueue_entry(&w->wait, current);
2923         w->data = data;
2924 }
2925
2926 static void add_cond_wait(struct cond_wait **head, struct cond_wait *w)
2927 {
2928         set_current_state(TASK_INTERRUPTIBLE);
2929         add_wait_queue(&w->q, &w->wait);
2930         w->next = *head;
2931         *head = w;
2932 }
2933
2934 static void remove_cond_wait(struct cond_wait **head, struct cond_wait *cw)
2935 {
2936         struct cond_wait *w, *prev;
2937         remove_wait_queue(&cw->q, &cw->wait);
2938         set_current_state(TASK_RUNNING);
2939         for (w = *head, prev = NULL ; w != NULL ; prev = w, w = w->next) {
2940                 if (w == cw) {
2941                         if (prev != NULL)
2942                                 prev->next = w->next;
2943                         else
2944                                 *head = w->next;
2945                         break;
2946                 }
2947         }
2948 }
2949
2950 static void flush_cond_wait(struct cond_wait **head)
2951 {
2952         while (*head != NULL) {
2953                 wake_up_interruptible(&(*head)->q);
2954                 *head = (*head)->next;
2955         }
2956 }
2957
2958 /*
2959  * wait for general purpose I/O pin(s) to enter specified state
2960  *
2961  * user_gpio fields:
2962  * state - bit indicates target pin state
2963  * smask - set bit indicates watched pin
2964  *
2965  * The wait ends when at least one watched pin enters the specified
2966  * state. When 0 (no error) is returned, user_gpio->state is set to the
2967  * state of all GPIO pins when the wait ends.
2968  *
2969  * Note: Each pin may be a dedicated input, dedicated output, or
2970  * configurable input/output. The number and configuration of pins
2971  * varies with the specific adapter model. Only input pins (dedicated
2972  * or configured) can be monitored with this function.
2973  */
2974 static int wait_gpio(struct slgt_info *info, struct gpio_desc __user *user_gpio)
2975 {
2976         unsigned long flags;
2977         int rc = 0;
2978         struct gpio_desc gpio;
2979         struct cond_wait wait;
2980         u32 state;
2981
2982         if (!info->gpio_present)
2983                 return -EINVAL;
2984         if (copy_from_user(&gpio, user_gpio, sizeof(gpio)))
2985                 return -EFAULT;
2986         DBGINFO(("%s wait_gpio() state=%08x smask=%08x\n",
2987                  info->device_name, gpio.state, gpio.smask));
2988         /* ignore output pins identified by set IODR bit */
2989         if ((gpio.smask &= ~rd_reg32(info, IODR)) == 0)
2990                 return -EINVAL;
2991         init_cond_wait(&wait, gpio.smask);
2992
2993         spin_lock_irqsave(&info->port_array[0]->lock, flags);
2994         /* enable interrupts for watched pins */
2995         wr_reg32(info, IOER, rd_reg32(info, IOER) | gpio.smask);
2996         /* get current pin states */
2997         state = rd_reg32(info, IOVR);
2998
2999         if (gpio.smask & ~(state ^ gpio.state)) {
3000                 /* already in target state */
3001                 gpio.state = state;
3002         } else {
3003                 /* wait for target state */
3004                 add_cond_wait(&info->gpio_wait_q, &wait);
3005                 spin_unlock_irqrestore(&info->port_array[0]->lock, flags);
3006                 schedule();
3007                 if (signal_pending(current))
3008                         rc = -ERESTARTSYS;
3009                 else
3010                         gpio.state = wait.data;
3011                 spin_lock_irqsave(&info->port_array[0]->lock, flags);
3012                 remove_cond_wait(&info->gpio_wait_q, &wait);
3013         }
3014
3015         /* disable all GPIO interrupts if no waiting processes */
3016         if (info->gpio_wait_q == NULL)
3017                 wr_reg32(info, IOER, 0);
3018         spin_unlock_irqrestore(&info->port_array[0]->lock, flags);
3019
3020         if ((rc == 0) && copy_to_user(user_gpio, &gpio, sizeof(gpio)))
3021                 rc = -EFAULT;
3022         return rc;
3023 }
3024
3025 static int modem_input_wait(struct slgt_info *info,int arg)
3026 {
3027         unsigned long flags;
3028         int rc;
3029         struct mgsl_icount cprev, cnow;
3030         DECLARE_WAITQUEUE(wait, current);
3031
3032         /* save current irq counts */
3033         spin_lock_irqsave(&info->lock,flags);
3034         cprev = info->icount;
3035         add_wait_queue(&info->status_event_wait_q, &wait);
3036         set_current_state(TASK_INTERRUPTIBLE);
3037         spin_unlock_irqrestore(&info->lock,flags);
3038
3039         for(;;) {
3040                 schedule();
3041                 if (signal_pending(current)) {
3042                         rc = -ERESTARTSYS;
3043                         break;
3044                 }
3045
3046                 /* get new irq counts */
3047                 spin_lock_irqsave(&info->lock,flags);
3048                 cnow = info->icount;
3049                 set_current_state(TASK_INTERRUPTIBLE);
3050                 spin_unlock_irqrestore(&info->lock,flags);
3051
3052                 /* if no change, wait aborted for some reason */
3053                 if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
3054                     cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) {
3055                         rc = -EIO;
3056                         break;
3057                 }
3058
3059                 /* check for change in caller specified modem input */
3060                 if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) ||
3061                     (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) ||
3062                     (arg & TIOCM_CD  && cnow.dcd != cprev.dcd) ||
3063                     (arg & TIOCM_CTS && cnow.cts != cprev.cts)) {
3064                         rc = 0;
3065                         break;
3066                 }
3067
3068                 cprev = cnow;
3069         }
3070         remove_wait_queue(&info->status_event_wait_q, &wait);
3071         set_current_state(TASK_RUNNING);
3072         return rc;
3073 }
3074
3075 /*
3076  *  return state of serial control and status signals
3077  */
3078 static int tiocmget(struct tty_struct *tty)
3079 {
3080         struct slgt_info *info = tty->driver_data;
3081         unsigned int result;
3082         unsigned long flags;
3083
3084         spin_lock_irqsave(&info->lock,flags);
3085         get_gtsignals(info);
3086         spin_unlock_irqrestore(&info->lock,flags);
3087
3088         result = ((info->signals & SerialSignal_RTS) ? TIOCM_RTS:0) +
3089                 ((info->signals & SerialSignal_DTR) ? TIOCM_DTR:0) +
3090                 ((info->signals & SerialSignal_DCD) ? TIOCM_CAR:0) +
3091                 ((info->signals & SerialSignal_RI)  ? TIOCM_RNG:0) +
3092                 ((info->signals & SerialSignal_DSR) ? TIOCM_DSR:0) +
3093                 ((info->signals & SerialSignal_CTS) ? TIOCM_CTS:0);
3094
3095         DBGINFO(("%s tiocmget value=%08X\n", info->device_name, result));
3096         return result;
3097 }
3098
3099 /*
3100  * set modem control signals (DTR/RTS)
3101  *
3102  *      cmd     signal command: TIOCMBIS = set bit TIOCMBIC = clear bit
3103  *              TIOCMSET = set/clear signal values
3104  *      value   bit mask for command
3105  */
3106 static int tiocmset(struct tty_struct *tty,
3107                     unsigned int set, unsigned int clear)
3108 {
3109         struct slgt_info *info = tty->driver_data;
3110         unsigned long flags;
3111
3112         DBGINFO(("%s tiocmset(%x,%x)\n", info->device_name, set, clear));
3113
3114         if (set & TIOCM_RTS)
3115                 info->signals |= SerialSignal_RTS;
3116         if (set & TIOCM_DTR)
3117                 info->signals |= SerialSignal_DTR;
3118         if (clear & TIOCM_RTS)
3119                 info->signals &= ~SerialSignal_RTS;
3120         if (clear & TIOCM_DTR)
3121                 info->signals &= ~SerialSignal_DTR;
3122
3123         spin_lock_irqsave(&info->lock,flags);
3124         set_gtsignals(info);
3125         spin_unlock_irqrestore(&info->lock,flags);
3126         return 0;
3127 }
3128
3129 static bool carrier_raised(struct tty_port *port)
3130 {
3131         unsigned long flags;
3132         struct slgt_info *info = container_of(port, struct slgt_info, port);
3133
3134         spin_lock_irqsave(&info->lock,flags);
3135         get_gtsignals(info);
3136         spin_unlock_irqrestore(&info->lock,flags);
3137
3138         return info->signals & SerialSignal_DCD;
3139 }
3140
3141 static void dtr_rts(struct tty_port *port, bool active)
3142 {
3143         unsigned long flags;
3144         struct slgt_info *info = container_of(port, struct slgt_info, port);
3145
3146         spin_lock_irqsave(&info->lock,flags);
3147         if (active)
3148                 info->signals |= SerialSignal_RTS | SerialSignal_DTR;
3149         else
3150                 info->signals &= ~(SerialSignal_RTS | SerialSignal_DTR);
3151         set_gtsignals(info);
3152         spin_unlock_irqrestore(&info->lock,flags);
3153 }
3154
3155
3156 /*
3157  *  block current process until the device is ready to open
3158  */
3159 static int block_til_ready(struct tty_struct *tty, struct file *filp,
3160                            struct slgt_info *info)
3161 {
3162         DECLARE_WAITQUEUE(wait, current);
3163         int             retval;
3164         bool            do_clocal = false;
3165         unsigned long   flags;
3166         bool            cd;
3167         struct tty_port *port = &info->port;
3168
3169         DBGINFO(("%s block_til_ready\n", tty->driver->name));
3170
3171         if (filp->f_flags & O_NONBLOCK || tty_io_error(tty)) {
3172                 /* nonblock mode is set or port is not enabled */
3173                 tty_port_set_active(port, true);
3174                 return 0;
3175         }
3176
3177         if (C_CLOCAL(tty))
3178                 do_clocal = true;
3179
3180         /* Wait for carrier detect and the line to become
3181          * free (i.e., not in use by the callout).  While we are in
3182          * this loop, port->count is dropped by one, so that
3183          * close() knows when to free things.  We restore it upon
3184          * exit, either normal or abnormal.
3185          */
3186
3187         retval = 0;
3188         add_wait_queue(&port->open_wait, &wait);
3189
3190         spin_lock_irqsave(&info->lock, flags);
3191         port->count--;
3192         spin_unlock_irqrestore(&info->lock, flags);
3193         port->blocked_open++;
3194
3195         while (1) {
3196                 if (C_BAUD(tty) && tty_port_initialized(port))
3197                         tty_port_raise_dtr_rts(port);
3198
3199                 set_current_state(TASK_INTERRUPTIBLE);
3200
3201                 if (tty_hung_up_p(filp) || !tty_port_initialized(port)) {
3202                         retval = (port->flags & ASYNC_HUP_NOTIFY) ?
3203                                         -EAGAIN : -ERESTARTSYS;
3204                         break;
3205                 }
3206
3207                 cd = tty_port_carrier_raised(port);
3208                 if (do_clocal || cd)
3209                         break;
3210
3211                 if (signal_pending(current)) {
3212                         retval = -ERESTARTSYS;
3213                         break;
3214                 }
3215
3216                 DBGINFO(("%s block_til_ready wait\n", tty->driver->name));
3217                 tty_unlock(tty);
3218                 schedule();
3219                 tty_lock(tty);
3220         }
3221
3222         set_current_state(TASK_RUNNING);
3223         remove_wait_queue(&port->open_wait, &wait);
3224
3225         if (!tty_hung_up_p(filp))
3226                 port->count++;
3227         port->blocked_open--;
3228
3229         if (!retval)
3230                 tty_port_set_active(port, true);
3231
3232         DBGINFO(("%s block_til_ready ready, rc=%d\n", tty->driver->name, retval));
3233         return retval;
3234 }
3235
3236 /*
3237  * allocate buffers used for calling line discipline receive_buf
3238  * directly in synchronous mode
3239  * note: add 5 bytes to max frame size to allow appending
3240  * 32-bit CRC and status byte when configured to do so
3241  */
3242 static int alloc_tmp_rbuf(struct slgt_info *info)
3243 {
3244         info->tmp_rbuf = kmalloc(info->max_frame_size + 5, GFP_KERNEL);
3245         if (info->tmp_rbuf == NULL)
3246                 return -ENOMEM;
3247         /* unused flag buffer to satisfy receive_buf calling interface */
3248         info->flag_buf = kzalloc(info->max_frame_size + 5, GFP_KERNEL);
3249         if (!info->flag_buf) {
3250                 kfree(info->tmp_rbuf);
3251                 info->tmp_rbuf = NULL;
3252                 return -ENOMEM;
3253         }
3254         return 0;
3255 }
3256
3257 static void free_tmp_rbuf(struct slgt_info *info)
3258 {
3259         kfree(info->tmp_rbuf);
3260         info->tmp_rbuf = NULL;
3261         kfree(info->flag_buf);
3262         info->flag_buf = NULL;
3263 }
3264
3265 /*
3266  * allocate DMA descriptor lists.
3267  */
3268 static int alloc_desc(struct slgt_info *info)
3269 {
3270         unsigned int i;
3271         unsigned int pbufs;
3272
3273         /* allocate memory to hold descriptor lists */
3274         info->bufs = dma_alloc_coherent(&info->pdev->dev, DESC_LIST_SIZE,
3275                                         &info->bufs_dma_addr, GFP_KERNEL);
3276         if (info->bufs == NULL)
3277                 return -ENOMEM;
3278
3279         info->rbufs = (struct slgt_desc*)info->bufs;
3280         info->tbufs = ((struct slgt_desc*)info->bufs) + info->rbuf_count;
3281
3282         pbufs = (unsigned int)info->bufs_dma_addr;
3283
3284         /*
3285          * Build circular lists of descriptors
3286          */
3287
3288         for (i=0; i < info->rbuf_count; i++) {
3289                 /* physical address of this descriptor */
3290                 info->rbufs[i].pdesc = pbufs + (i * sizeof(struct slgt_desc));
3291
3292                 /* physical address of next descriptor */
3293                 if (i == info->rbuf_count - 1)
3294                         info->rbufs[i].next = cpu_to_le32(pbufs);
3295                 else
3296                         info->rbufs[i].next = cpu_to_le32(pbufs + ((i+1) * sizeof(struct slgt_desc)));
3297                 set_desc_count(info->rbufs[i], DMABUFSIZE);
3298         }
3299
3300         for (i=0; i < info->tbuf_count; i++) {
3301                 /* physical address of this descriptor */
3302                 info->tbufs[i].pdesc = pbufs + ((info->rbuf_count + i) * sizeof(struct slgt_desc));
3303
3304                 /* physical address of next descriptor */
3305                 if (i == info->tbuf_count - 1)
3306                         info->tbufs[i].next = cpu_to_le32(pbufs + info->rbuf_count * sizeof(struct slgt_desc));
3307                 else
3308                         info->tbufs[i].next = cpu_to_le32(pbufs + ((info->rbuf_count + i + 1) * sizeof(struct slgt_desc)));
3309         }
3310
3311         return 0;
3312 }
3313
3314 static void free_desc(struct slgt_info *info)
3315 {
3316         if (info->bufs != NULL) {
3317                 dma_free_coherent(&info->pdev->dev, DESC_LIST_SIZE,
3318                                   info->bufs, info->bufs_dma_addr);
3319                 info->bufs  = NULL;
3320                 info->rbufs = NULL;
3321                 info->tbufs = NULL;
3322         }
3323 }
3324
3325 static int alloc_bufs(struct slgt_info *info, struct slgt_desc *bufs, int count)
3326 {
3327         int i;
3328         for (i=0; i < count; i++) {
3329                 bufs[i].buf = dma_alloc_coherent(&info->pdev->dev, DMABUFSIZE,
3330                                                  &bufs[i].buf_dma_addr, GFP_KERNEL);
3331                 if (!bufs[i].buf)
3332                         return -ENOMEM;
3333                 bufs[i].pbuf  = cpu_to_le32((unsigned int)bufs[i].buf_dma_addr);
3334         }
3335         return 0;
3336 }
3337
3338 static void free_bufs(struct slgt_info *info, struct slgt_desc *bufs, int count)
3339 {
3340         int i;
3341         for (i=0; i < count; i++) {
3342                 if (bufs[i].buf == NULL)
3343                         continue;
3344                 dma_free_coherent(&info->pdev->dev, DMABUFSIZE, bufs[i].buf,
3345                                   bufs[i].buf_dma_addr);
3346                 bufs[i].buf = NULL;
3347         }
3348 }
3349
3350 static int alloc_dma_bufs(struct slgt_info *info)
3351 {
3352         info->rbuf_count = 32;
3353         info->tbuf_count = 32;
3354
3355         if (alloc_desc(info) < 0 ||
3356             alloc_bufs(info, info->rbufs, info->rbuf_count) < 0 ||
3357             alloc_bufs(info, info->tbufs, info->tbuf_count) < 0 ||
3358             alloc_tmp_rbuf(info) < 0) {
3359                 DBGERR(("%s DMA buffer alloc fail\n", info->device_name));
3360                 return -ENOMEM;
3361         }
3362         reset_rbufs(info);
3363         return 0;
3364 }
3365
3366 static void free_dma_bufs(struct slgt_info *info)
3367 {
3368         if (info->bufs) {
3369                 free_bufs(info, info->rbufs, info->rbuf_count);
3370                 free_bufs(info, info->tbufs, info->tbuf_count);
3371                 free_desc(info);
3372         }
3373         free_tmp_rbuf(info);
3374 }
3375
3376 static int claim_resources(struct slgt_info *info)
3377 {
3378         if (request_mem_region(info->phys_reg_addr, SLGT_REG_SIZE, "synclink_gt") == NULL) {
3379                 DBGERR(("%s reg addr conflict, addr=%08X\n",
3380                         info->device_name, info->phys_reg_addr));
3381                 info->init_error = DiagStatus_AddressConflict;
3382                 goto errout;
3383         }
3384         else
3385                 info->reg_addr_requested = true;
3386
3387         info->reg_addr = ioremap(info->phys_reg_addr, SLGT_REG_SIZE);
3388         if (!info->reg_addr) {
3389                 DBGERR(("%s can't map device registers, addr=%08X\n",
3390                         info->device_name, info->phys_reg_addr));
3391                 info->init_error = DiagStatus_CantAssignPciResources;
3392                 goto errout;
3393         }
3394         return 0;
3395
3396 errout:
3397         release_resources(info);
3398         return -ENODEV;
3399 }
3400
3401 static void release_resources(struct slgt_info *info)
3402 {
3403         if (info->irq_requested) {
3404                 free_irq(info->irq_level, info);
3405                 info->irq_requested = false;
3406         }
3407
3408         if (info->reg_addr_requested) {
3409                 release_mem_region(info->phys_reg_addr, SLGT_REG_SIZE);
3410                 info->reg_addr_requested = false;
3411         }
3412
3413         if (info->reg_addr) {
3414                 iounmap(info->reg_addr);
3415                 info->reg_addr = NULL;
3416         }
3417 }
3418
3419 /* Add the specified device instance data structure to the
3420  * global linked list of devices and increment the device count.
3421  */
3422 static void add_device(struct slgt_info *info)
3423 {
3424         char *devstr;
3425
3426         info->next_device = NULL;
3427         info->line = slgt_device_count;
3428         sprintf(info->device_name, "%s%d", tty_dev_prefix, info->line);
3429
3430         if (info->line < MAX_DEVICES) {
3431                 if (maxframe[info->line])
3432                         info->max_frame_size = maxframe[info->line];
3433         }
3434
3435         slgt_device_count++;
3436
3437         if (!slgt_device_list)
3438                 slgt_device_list = info;
3439         else {
3440                 struct slgt_info *current_dev = slgt_device_list;
3441                 while(current_dev->next_device)
3442                         current_dev = current_dev->next_device;
3443                 current_dev->next_device = info;
3444         }
3445
3446         if (info->max_frame_size < 4096)
3447                 info->max_frame_size = 4096;
3448         else if (info->max_frame_size > 65535)
3449                 info->max_frame_size = 65535;
3450
3451         switch(info->pdev->device) {
3452         case SYNCLINK_GT_DEVICE_ID:
3453                 devstr = "GT";
3454                 break;
3455         case SYNCLINK_GT2_DEVICE_ID:
3456                 devstr = "GT2";
3457                 break;
3458         case SYNCLINK_GT4_DEVICE_ID:
3459                 devstr = "GT4";
3460                 break;
3461         case SYNCLINK_AC_DEVICE_ID:
3462                 devstr = "AC";
3463                 info->params.mode = MGSL_MODE_ASYNC;
3464                 break;
3465         default:
3466                 devstr = "(unknown model)";
3467         }
3468         printk("SyncLink %s %s IO=%08x IRQ=%d MaxFrameSize=%u\n",
3469                 devstr, info->device_name, info->phys_reg_addr,
3470                 info->irq_level, info->max_frame_size);
3471
3472 #if SYNCLINK_GENERIC_HDLC
3473         hdlcdev_init(info);
3474 #endif
3475 }
3476
3477 static const struct tty_port_operations slgt_port_ops = {
3478         .carrier_raised = carrier_raised,
3479         .dtr_rts = dtr_rts,
3480 };
3481
3482 /*
3483  *  allocate device instance structure, return NULL on failure
3484  */
3485 static struct slgt_info *alloc_dev(int adapter_num, int port_num, struct pci_dev *pdev)
3486 {
3487         struct slgt_info *info;
3488
3489         info = kzalloc(sizeof(struct slgt_info), GFP_KERNEL);
3490
3491         if (!info) {
3492                 DBGERR(("%s device alloc failed adapter=%d port=%d\n",
3493                         driver_name, adapter_num, port_num));
3494         } else {
3495                 tty_port_init(&info->port);
3496                 info->port.ops = &slgt_port_ops;
3497                 INIT_WORK(&info->task, bh_handler);
3498                 info->max_frame_size = 4096;
3499                 info->base_clock = 14745600;
3500                 info->rbuf_fill_level = DMABUFSIZE;
3501                 init_waitqueue_head(&info->status_event_wait_q);
3502                 init_waitqueue_head(&info->event_wait_q);
3503                 spin_lock_init(&info->netlock);
3504                 memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
3505                 info->idle_mode = HDLC_TXIDLE_FLAGS;
3506                 info->adapter_num = adapter_num;
3507                 info->port_num = port_num;
3508
3509                 timer_setup(&info->tx_timer, tx_timeout, 0);
3510                 timer_setup(&info->rx_timer, rx_timeout, 0);
3511
3512                 /* Copy configuration info to device instance data */
3513                 info->pdev = pdev;
3514                 info->irq_level = pdev->irq;
3515                 info->phys_reg_addr = pci_resource_start(pdev,0);
3516
3517                 info->bus_type = MGSL_BUS_TYPE_PCI;
3518                 info->irq_flags = IRQF_SHARED;
3519
3520                 info->init_error = -1; /* assume error, set to 0 on successful init */
3521         }
3522
3523         return info;
3524 }
3525
3526 static void device_init(int adapter_num, struct pci_dev *pdev)
3527 {
3528         struct slgt_info *port_array[SLGT_MAX_PORTS];
3529         int i;
3530         int port_count = 1;
3531
3532         if (pdev->device == SYNCLINK_GT2_DEVICE_ID)
3533                 port_count = 2;
3534         else if (pdev->device == SYNCLINK_GT4_DEVICE_ID)
3535                 port_count = 4;
3536
3537         /* allocate device instances for all ports */
3538         for (i=0; i < port_count; ++i) {
3539                 port_array[i] = alloc_dev(adapter_num, i, pdev);
3540                 if (port_array[i] == NULL) {
3541                         for (--i; i >= 0; --i) {
3542                                 tty_port_destroy(&port_array[i]->port);
3543                                 kfree(port_array[i]);
3544                         }
3545                         return;
3546                 }
3547         }
3548
3549         /* give copy of port_array to all ports and add to device list  */
3550         for (i=0; i < port_count; ++i) {
3551                 memcpy(port_array[i]->port_array, port_array, sizeof(port_array));
3552                 add_device(port_array[i]);
3553                 port_array[i]->port_count = port_count;
3554                 spin_lock_init(&port_array[i]->lock);
3555         }
3556
3557         /* Allocate and claim adapter resources */
3558         if (!claim_resources(port_array[0])) {
3559
3560                 alloc_dma_bufs(port_array[0]);
3561
3562                 /* copy resource information from first port to others */
3563                 for (i = 1; i < port_count; ++i) {
3564                         port_array[i]->irq_level = port_array[0]->irq_level;
3565                         port_array[i]->reg_addr  = port_array[0]->reg_addr;
3566                         alloc_dma_bufs(port_array[i]);
3567                 }
3568
3569                 if (request_irq(port_array[0]->irq_level,
3570                                         slgt_interrupt,
3571                                         port_array[0]->irq_flags,
3572                                         port_array[0]->device_name,
3573                                         port_array[0]) < 0) {
3574                         DBGERR(("%s request_irq failed IRQ=%d\n",
3575                                 port_array[0]->device_name,
3576                                 port_array[0]->irq_level));
3577                 } else {
3578                         port_array[0]->irq_requested = true;
3579                         adapter_test(port_array[0]);
3580                         for (i=1 ; i < port_count ; i++) {
3581                                 port_array[i]->init_error = port_array[0]->init_error;
3582                                 port_array[i]->gpio_present = port_array[0]->gpio_present;
3583                         }
3584                 }
3585         }
3586
3587         for (i = 0; i < port_count; ++i) {
3588                 struct slgt_info *info = port_array[i];
3589                 tty_port_register_device(&info->port, serial_driver, info->line,
3590                                 &info->pdev->dev);
3591         }
3592 }
3593
3594 static int init_one(struct pci_dev *dev,
3595                               const struct pci_device_id *ent)
3596 {
3597         if (pci_enable_device(dev)) {
3598                 printk("error enabling pci device %p\n", dev);
3599                 return -EIO;
3600         }
3601         pci_set_master(dev);
3602         device_init(slgt_device_count, dev);
3603         return 0;
3604 }
3605
3606 static void remove_one(struct pci_dev *dev)
3607 {
3608 }
3609
3610 static const struct tty_operations ops = {
3611         .open = open,
3612         .close = close,
3613         .write = write,
3614         .put_char = put_char,
3615         .flush_chars = flush_chars,
3616         .write_room = write_room,
3617         .chars_in_buffer = chars_in_buffer,
3618         .flush_buffer = flush_buffer,
3619         .ioctl = ioctl,
3620         .compat_ioctl = slgt_compat_ioctl,
3621         .throttle = throttle,
3622         .unthrottle = unthrottle,
3623         .send_xchar = send_xchar,
3624         .break_ctl = set_break,
3625         .wait_until_sent = wait_until_sent,
3626         .set_termios = set_termios,
3627         .stop = tx_hold,
3628         .start = tx_release,
3629         .hangup = hangup,
3630         .tiocmget = tiocmget,
3631         .tiocmset = tiocmset,
3632         .get_icount = get_icount,
3633         .proc_show = synclink_gt_proc_show,
3634 };
3635
3636 static void slgt_cleanup(void)
3637 {
3638         struct slgt_info *info;
3639         struct slgt_info *tmp;
3640
3641         printk(KERN_INFO "unload %s\n", driver_name);
3642
3643         if (serial_driver) {
3644                 for (info=slgt_device_list ; info != NULL ; info=info->next_device)
3645                         tty_unregister_device(serial_driver, info->line);
3646                 tty_unregister_driver(serial_driver);
3647                 tty_driver_kref_put(serial_driver);
3648         }
3649
3650         /* reset devices */
3651         info = slgt_device_list;
3652         while(info) {
3653                 reset_port(info);
3654                 info = info->next_device;
3655         }
3656
3657         /* release devices */
3658         info = slgt_device_list;
3659         while(info) {
3660 #if SYNCLINK_GENERIC_HDLC
3661                 hdlcdev_exit(info);
3662 #endif
3663                 free_dma_bufs(info);
3664                 free_tmp_rbuf(info);
3665                 if (info->port_num == 0)
3666                         release_resources(info);
3667                 tmp = info;
3668                 info = info->next_device;
3669                 tty_port_destroy(&tmp->port);
3670                 kfree(tmp);
3671         }
3672
3673         if (pci_registered)
3674                 pci_unregister_driver(&pci_driver);
3675 }
3676
3677 /*
3678  *  Driver initialization entry point.
3679  */
3680 static int __init slgt_init(void)
3681 {
3682         int rc;
3683
3684         printk(KERN_INFO "%s\n", driver_name);
3685
3686         serial_driver = tty_alloc_driver(MAX_DEVICES, TTY_DRIVER_REAL_RAW |
3687                         TTY_DRIVER_DYNAMIC_DEV);
3688         if (IS_ERR(serial_driver)) {
3689                 printk("%s can't allocate tty driver\n", driver_name);
3690                 return PTR_ERR(serial_driver);
3691         }
3692
3693         /* Initialize the tty_driver structure */
3694
3695         serial_driver->driver_name = slgt_driver_name;
3696         serial_driver->name = tty_dev_prefix;
3697         serial_driver->major = ttymajor;
3698         serial_driver->minor_start = 64;
3699         serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
3700         serial_driver->subtype = SERIAL_TYPE_NORMAL;
3701         serial_driver->init_termios = tty_std_termios;
3702         serial_driver->init_termios.c_cflag =
3703                 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
3704         serial_driver->init_termios.c_ispeed = 9600;
3705         serial_driver->init_termios.c_ospeed = 9600;
3706         tty_set_operations(serial_driver, &ops);
3707         if ((rc = tty_register_driver(serial_driver)) < 0) {
3708                 DBGERR(("%s can't register serial driver\n", driver_name));
3709                 tty_driver_kref_put(serial_driver);
3710                 serial_driver = NULL;
3711                 goto error;
3712         }
3713
3714         printk(KERN_INFO "%s, tty major#%d\n",
3715                driver_name, serial_driver->major);
3716
3717         slgt_device_count = 0;
3718         if ((rc = pci_register_driver(&pci_driver)) < 0) {
3719                 printk("%s pci_register_driver error=%d\n", driver_name, rc);
3720                 goto error;
3721         }
3722         pci_registered = true;
3723
3724         if (!slgt_device_list)
3725                 printk("%s no devices found\n",driver_name);
3726
3727         return 0;
3728
3729 error:
3730         slgt_cleanup();
3731         return rc;
3732 }
3733
3734 static void __exit slgt_exit(void)
3735 {
3736         slgt_cleanup();
3737 }
3738
3739 module_init(slgt_init);
3740 module_exit(slgt_exit);
3741
3742 /*
3743  * register access routines
3744  */
3745
3746 #define CALC_REGADDR() \
3747         unsigned long reg_addr = ((unsigned long)info->reg_addr) + addr; \
3748         if (addr >= 0x80) \
3749                 reg_addr += (info->port_num) * 32; \
3750         else if (addr >= 0x40)  \
3751                 reg_addr += (info->port_num) * 16;
3752
3753 static __u8 rd_reg8(struct slgt_info *info, unsigned int addr)
3754 {
3755         CALC_REGADDR();
3756         return readb((void __iomem *)reg_addr);
3757 }
3758
3759 static void wr_reg8(struct slgt_info *info, unsigned int addr, __u8 value)
3760 {
3761         CALC_REGADDR();
3762         writeb(value, (void __iomem *)reg_addr);
3763 }
3764
3765 static __u16 rd_reg16(struct slgt_info *info, unsigned int addr)
3766 {
3767         CALC_REGADDR();
3768         return readw((void __iomem *)reg_addr);
3769 }
3770
3771 static void wr_reg16(struct slgt_info *info, unsigned int addr, __u16 value)
3772 {
3773         CALC_REGADDR();
3774         writew(value, (void __iomem *)reg_addr);
3775 }
3776
3777 static __u32 rd_reg32(struct slgt_info *info, unsigned int addr)
3778 {
3779         CALC_REGADDR();
3780         return readl((void __iomem *)reg_addr);
3781 }
3782
3783 static void wr_reg32(struct slgt_info *info, unsigned int addr, __u32 value)
3784 {
3785         CALC_REGADDR();
3786         writel(value, (void __iomem *)reg_addr);
3787 }
3788
3789 static void rdma_reset(struct slgt_info *info)
3790 {
3791         unsigned int i;
3792
3793         /* set reset bit */
3794         wr_reg32(info, RDCSR, BIT1);
3795
3796         /* wait for enable bit cleared */
3797         for(i=0 ; i < 1000 ; i++)
3798                 if (!(rd_reg32(info, RDCSR) & BIT0))
3799                         break;
3800 }
3801
3802 static void tdma_reset(struct slgt_info *info)
3803 {
3804         unsigned int i;
3805
3806         /* set reset bit */
3807         wr_reg32(info, TDCSR, BIT1);
3808
3809         /* wait for enable bit cleared */
3810         for(i=0 ; i < 1000 ; i++)
3811                 if (!(rd_reg32(info, TDCSR) & BIT0))
3812                         break;
3813 }
3814
3815 /*
3816  * enable internal loopback
3817  * TxCLK and RxCLK are generated from BRG
3818  * and TxD is looped back to RxD internally.
3819  */
3820 static void enable_loopback(struct slgt_info *info)
3821 {
3822         /* SCR (serial control) BIT2=loopback enable */
3823         wr_reg16(info, SCR, (unsigned short)(rd_reg16(info, SCR) | BIT2));
3824
3825         if (info->params.mode != MGSL_MODE_ASYNC) {
3826                 /* CCR (clock control)
3827                  * 07..05  tx clock source (010 = BRG)
3828                  * 04..02  rx clock source (010 = BRG)
3829                  * 01      auxclk enable   (0 = disable)
3830                  * 00      BRG enable      (1 = enable)
3831                  *
3832                  * 0100 1001
3833                  */
3834                 wr_reg8(info, CCR, 0x49);
3835
3836                 /* set speed if available, otherwise use default */
3837                 if (info->params.clock_speed)
3838                         set_rate(info, info->params.clock_speed);
3839                 else
3840                         set_rate(info, 3686400);
3841         }
3842 }
3843
3844 /*
3845  *  set baud rate generator to specified rate
3846  */
3847 static void set_rate(struct slgt_info *info, u32 rate)
3848 {
3849         unsigned int div;
3850         unsigned int osc = info->base_clock;
3851
3852         /* div = osc/rate - 1
3853          *
3854          * Round div up if osc/rate is not integer to
3855          * force to next slowest rate.
3856          */
3857
3858         if (rate) {
3859                 div = osc/rate;
3860                 if (!(osc % rate) && div)
3861                         div--;
3862                 wr_reg16(info, BDR, (unsigned short)div);
3863         }
3864 }
3865
3866 static void rx_stop(struct slgt_info *info)
3867 {
3868         unsigned short val;
3869
3870         /* disable and reset receiver */
3871         val = rd_reg16(info, RCR) & ~BIT1;          /* clear enable bit */
3872         wr_reg16(info, RCR, (unsigned short)(val | BIT2)); /* set reset bit */
3873         wr_reg16(info, RCR, val);                  /* clear reset bit */
3874
3875         slgt_irq_off(info, IRQ_RXOVER + IRQ_RXDATA + IRQ_RXIDLE);
3876
3877         /* clear pending rx interrupts */
3878         wr_reg16(info, SSR, IRQ_RXIDLE + IRQ_RXOVER);
3879
3880         rdma_reset(info);
3881
3882         info->rx_enabled = false;
3883         info->rx_restart = false;
3884 }
3885
3886 static void rx_start(struct slgt_info *info)
3887 {
3888         unsigned short val;
3889
3890         slgt_irq_off(info, IRQ_RXOVER + IRQ_RXDATA);
3891
3892         /* clear pending rx overrun IRQ */
3893         wr_reg16(info, SSR, IRQ_RXOVER);
3894
3895         /* reset and disable receiver */
3896         val = rd_reg16(info, RCR) & ~BIT1; /* clear enable bit */
3897         wr_reg16(info, RCR, (unsigned short)(val | BIT2)); /* set reset bit */
3898         wr_reg16(info, RCR, val);                  /* clear reset bit */
3899
3900         rdma_reset(info);
3901         reset_rbufs(info);
3902
3903         if (info->rx_pio) {
3904                 /* rx request when rx FIFO not empty */
3905                 wr_reg16(info, SCR, (unsigned short)(rd_reg16(info, SCR) & ~BIT14));
3906                 slgt_irq_on(info, IRQ_RXDATA);
3907                 if (info->params.mode == MGSL_MODE_ASYNC) {
3908                         /* enable saving of rx status */
3909                         wr_reg32(info, RDCSR, BIT6);
3910                 }
3911         } else {
3912                 /* rx request when rx FIFO half full */
3913                 wr_reg16(info, SCR, (unsigned short)(rd_reg16(info, SCR) | BIT14));
3914                 /* set 1st descriptor address */
3915                 wr_reg32(info, RDDAR, info->rbufs[0].pdesc);
3916
3917                 if (info->params.mode != MGSL_MODE_ASYNC) {
3918                         /* enable rx DMA and DMA interrupt */
3919                         wr_reg32(info, RDCSR, (BIT2 + BIT0));
3920                 } else {
3921                         /* enable saving of rx status, rx DMA and DMA interrupt */
3922                         wr_reg32(info, RDCSR, (BIT6 + BIT2 + BIT0));
3923                 }
3924         }
3925
3926         slgt_irq_on(info, IRQ_RXOVER);
3927
3928         /* enable receiver */
3929         wr_reg16(info, RCR, (unsigned short)(rd_reg16(info, RCR) | BIT1));
3930
3931         info->rx_restart = false;
3932         info->rx_enabled = true;
3933 }
3934
3935 static void tx_start(struct slgt_info *info)
3936 {
3937         if (!info->tx_enabled) {
3938                 wr_reg16(info, TCR,
3939                          (unsigned short)((rd_reg16(info, TCR) | BIT1) & ~BIT2));
3940                 info->tx_enabled = true;
3941         }
3942
3943         if (desc_count(info->tbufs[info->tbuf_start])) {
3944                 info->drop_rts_on_tx_done = false;
3945
3946                 if (info->params.mode != MGSL_MODE_ASYNC) {
3947                         if (info->params.flags & HDLC_FLAG_AUTO_RTS) {
3948                                 get_gtsignals(info);
3949                                 if (!(info->signals & SerialSignal_RTS)) {
3950                                         info->signals |= SerialSignal_RTS;
3951                                         set_gtsignals(info);
3952                                         info->drop_rts_on_tx_done = true;
3953                                 }
3954                         }
3955
3956                         slgt_irq_off(info, IRQ_TXDATA);
3957                         slgt_irq_on(info, IRQ_TXUNDER + IRQ_TXIDLE);
3958                         /* clear tx idle and underrun status bits */
3959                         wr_reg16(info, SSR, (unsigned short)(IRQ_TXIDLE + IRQ_TXUNDER));
3960                 } else {
3961                         slgt_irq_off(info, IRQ_TXDATA);
3962                         slgt_irq_on(info, IRQ_TXIDLE);
3963                         /* clear tx idle status bit */
3964                         wr_reg16(info, SSR, IRQ_TXIDLE);
3965                 }
3966                 /* set 1st descriptor address and start DMA */
3967                 wr_reg32(info, TDDAR, info->tbufs[info->tbuf_start].pdesc);
3968                 wr_reg32(info, TDCSR, BIT2 + BIT0);
3969                 info->tx_active = true;
3970         }
3971 }
3972
3973 static void tx_stop(struct slgt_info *info)
3974 {
3975         unsigned short val;
3976
3977         del_timer(&info->tx_timer);
3978
3979         tdma_reset(info);
3980
3981         /* reset and disable transmitter */
3982         val = rd_reg16(info, TCR) & ~BIT1;          /* clear enable bit */
3983         wr_reg16(info, TCR, (unsigned short)(val | BIT2)); /* set reset bit */
3984
3985         slgt_irq_off(info, IRQ_TXDATA + IRQ_TXIDLE + IRQ_TXUNDER);
3986
3987         /* clear tx idle and underrun status bit */
3988         wr_reg16(info, SSR, (unsigned short)(IRQ_TXIDLE + IRQ_TXUNDER));
3989
3990         reset_tbufs(info);
3991
3992         info->tx_enabled = false;
3993         info->tx_active = false;
3994 }
3995
3996 static void reset_port(struct slgt_info *info)
3997 {
3998         if (!info->reg_addr)
3999                 return;
4000
4001         tx_stop(info);
4002         rx_stop(info);
4003
4004         info->signals &= ~(SerialSignal_RTS | SerialSignal_DTR);
4005         set_gtsignals(info);
4006
4007         slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
4008 }
4009
4010 static void reset_adapter(struct slgt_info *info)
4011 {
4012         int i;
4013         for (i=0; i < info->port_count; ++i) {
4014                 if (info->port_array[i])
4015                         reset_port(info->port_array[i]);
4016         }
4017 }
4018
4019 static void async_mode(struct slgt_info *info)
4020 {
4021         unsigned short val;
4022
4023         slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
4024         tx_stop(info);
4025         rx_stop(info);
4026
4027         /* TCR (tx control)
4028          *
4029          * 15..13  mode, 010=async
4030          * 12..10  encoding, 000=NRZ
4031          * 09      parity enable
4032          * 08      1=odd parity, 0=even parity
4033          * 07      1=RTS driver control
4034          * 06      1=break enable
4035          * 05..04  character length
4036          *         00=5 bits
4037          *         01=6 bits
4038          *         10=7 bits
4039          *         11=8 bits
4040          * 03      0=1 stop bit, 1=2 stop bits
4041          * 02      reset
4042          * 01      enable
4043          * 00      auto-CTS enable
4044          */
4045         val = 0x4000;
4046
4047         if (info->if_mode & MGSL_INTERFACE_RTS_EN)
4048                 val |= BIT7;
4049
4050         if (info->params.parity != ASYNC_PARITY_NONE) {
4051                 val |= BIT9;
4052                 if (info->params.parity == ASYNC_PARITY_ODD)
4053                         val |= BIT8;
4054         }
4055
4056         switch (info->params.data_bits)
4057         {
4058         case 6: val |= BIT4; break;
4059         case 7: val |= BIT5; break;
4060         case 8: val |= BIT5 + BIT4; break;
4061         }
4062
4063         if (info->params.stop_bits != 1)
4064                 val |= BIT3;
4065
4066         if (info->params.flags & HDLC_FLAG_AUTO_CTS)
4067                 val |= BIT0;
4068
4069         wr_reg16(info, TCR, val);
4070
4071         /* RCR (rx control)
4072          *
4073          * 15..13  mode, 010=async
4074          * 12..10  encoding, 000=NRZ
4075          * 09      parity enable
4076          * 08      1=odd parity, 0=even parity
4077          * 07..06  reserved, must be 0
4078          * 05..04  character length
4079          *         00=5 bits
4080          *         01=6 bits
4081          *         10=7 bits
4082          *         11=8 bits
4083          * 03      reserved, must be zero
4084          * 02      reset
4085          * 01      enable
4086          * 00      auto-DCD enable
4087          */
4088         val = 0x4000;
4089
4090         if (info->params.parity != ASYNC_PARITY_NONE) {
4091                 val |= BIT9;
4092                 if (info->params.parity == ASYNC_PARITY_ODD)
4093                         val |= BIT8;
4094         }
4095
4096         switch (info->params.data_bits)
4097         {
4098         case 6: val |= BIT4; break;
4099         case 7: val |= BIT5; break;
4100         case 8: val |= BIT5 + BIT4; break;
4101         }
4102
4103         if (info->params.flags & HDLC_FLAG_AUTO_DCD)
4104                 val |= BIT0;
4105
4106         wr_reg16(info, RCR, val);
4107
4108         /* CCR (clock control)
4109          *
4110          * 07..05  011 = tx clock source is BRG/16
4111          * 04..02  010 = rx clock source is BRG
4112          * 01      0 = auxclk disabled
4113          * 00      1 = BRG enabled
4114          *
4115          * 0110 1001
4116          */
4117         wr_reg8(info, CCR, 0x69);
4118
4119         msc_set_vcr(info);
4120
4121         /* SCR (serial control)
4122          *
4123          * 15  1=tx req on FIFO half empty
4124          * 14  1=rx req on FIFO half full
4125          * 13  tx data  IRQ enable
4126          * 12  tx idle  IRQ enable
4127          * 11  rx break on IRQ enable
4128          * 10  rx data  IRQ enable
4129          * 09  rx break off IRQ enable
4130          * 08  overrun  IRQ enable
4131          * 07  DSR      IRQ enable
4132          * 06  CTS      IRQ enable
4133          * 05  DCD      IRQ enable
4134          * 04  RI       IRQ enable
4135          * 03  0=16x sampling, 1=8x sampling
4136          * 02  1=txd->rxd internal loopback enable
4137          * 01  reserved, must be zero
4138          * 00  1=master IRQ enable
4139          */
4140         val = BIT15 + BIT14 + BIT0;
4141         /* JCR[8] : 1 = x8 async mode feature available */
4142         if ((rd_reg32(info, JCR) & BIT8) && info->params.data_rate &&
4143             ((info->base_clock < (info->params.data_rate * 16)) ||
4144              (info->base_clock % (info->params.data_rate * 16)))) {
4145                 /* use 8x sampling */
4146                 val |= BIT3;
4147                 set_rate(info, info->params.data_rate * 8);
4148         } else {
4149                 /* use 16x sampling */
4150                 set_rate(info, info->params.data_rate * 16);
4151         }
4152         wr_reg16(info, SCR, val);
4153
4154         slgt_irq_on(info, IRQ_RXBREAK | IRQ_RXOVER);
4155
4156         if (info->params.loopback)
4157                 enable_loopback(info);
4158 }
4159
4160 static void sync_mode(struct slgt_info *info)
4161 {
4162         unsigned short val;
4163
4164         slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
4165         tx_stop(info);
4166         rx_stop(info);
4167
4168         /* TCR (tx control)
4169          *
4170          * 15..13  mode
4171          *         000=HDLC/SDLC
4172          *         001=raw bit synchronous
4173          *         010=asynchronous/isochronous
4174          *         011=monosync byte synchronous
4175          *         100=bisync byte synchronous
4176          *         101=xsync byte synchronous
4177          * 12..10  encoding
4178          * 09      CRC enable
4179          * 08      CRC32
4180          * 07      1=RTS driver control
4181          * 06      preamble enable
4182          * 05..04  preamble length
4183          * 03      share open/close flag
4184          * 02      reset
4185          * 01      enable
4186          * 00      auto-CTS enable
4187          */
4188         val = BIT2;
4189
4190         switch(info->params.mode) {
4191         case MGSL_MODE_XSYNC:
4192                 val |= BIT15 + BIT13;
4193                 break;
4194         case MGSL_MODE_MONOSYNC: val |= BIT14 + BIT13; break;
4195         case MGSL_MODE_BISYNC:   val |= BIT15; break;
4196         case MGSL_MODE_RAW:      val |= BIT13; break;
4197         }
4198         if (info->if_mode & MGSL_INTERFACE_RTS_EN)
4199                 val |= BIT7;
4200
4201         switch(info->params.encoding)
4202         {
4203         case HDLC_ENCODING_NRZB:          val |= BIT10; break;
4204         case HDLC_ENCODING_NRZI_MARK:     val |= BIT11; break;
4205         case HDLC_ENCODING_NRZI:          val |= BIT11 + BIT10; break;
4206         case HDLC_ENCODING_BIPHASE_MARK:  val |= BIT12; break;
4207         case HDLC_ENCODING_BIPHASE_SPACE: val |= BIT12 + BIT10; break;
4208         case HDLC_ENCODING_BIPHASE_LEVEL: val |= BIT12 + BIT11; break;
4209         case HDLC_ENCODING_DIFF_BIPHASE_LEVEL: val |= BIT12 + BIT11 + BIT10; break;
4210         }
4211
4212         switch (info->params.crc_type & HDLC_CRC_MASK)
4213         {
4214         case HDLC_CRC_16_CCITT: val |= BIT9; break;
4215         case HDLC_CRC_32_CCITT: val |= BIT9 + BIT8; break;
4216         }
4217
4218         if (info->params.preamble != HDLC_PREAMBLE_PATTERN_NONE)
4219                 val |= BIT6;
4220
4221         switch (info->params.preamble_length)
4222         {
4223         case HDLC_PREAMBLE_LENGTH_16BITS: val |= BIT5; break;
4224         case HDLC_PREAMBLE_LENGTH_32BITS: val |= BIT4; break;
4225         case HDLC_PREAMBLE_LENGTH_64BITS: val |= BIT5 + BIT4; break;
4226         }
4227
4228         if (info->params.flags & HDLC_FLAG_AUTO_CTS)
4229                 val |= BIT0;
4230
4231         wr_reg16(info, TCR, val);
4232
4233         /* TPR (transmit preamble) */
4234
4235         switch (info->params.preamble)
4236         {
4237         case HDLC_PREAMBLE_PATTERN_FLAGS: val = 0x7e; break;
4238         case HDLC_PREAMBLE_PATTERN_ONES:  val = 0xff; break;
4239         case HDLC_PREAMBLE_PATTERN_ZEROS: val = 0x00; break;
4240         case HDLC_PREAMBLE_PATTERN_10:    val = 0x55; break;
4241         case HDLC_PREAMBLE_PATTERN_01:    val = 0xaa; break;
4242         default:                          val = 0x7e; break;
4243         }
4244         wr_reg8(info, TPR, (unsigned char)val);
4245
4246         /* RCR (rx control)
4247          *
4248          * 15..13  mode
4249          *         000=HDLC/SDLC
4250          *         001=raw bit synchronous
4251          *         010=asynchronous/isochronous
4252          *         011=monosync byte synchronous
4253          *         100=bisync byte synchronous
4254          *         101=xsync byte synchronous
4255          * 12..10  encoding
4256          * 09      CRC enable
4257          * 08      CRC32
4258          * 07..03  reserved, must be 0
4259          * 02      reset
4260          * 01      enable
4261          * 00      auto-DCD enable
4262          */
4263         val = 0;
4264
4265         switch(info->params.mode) {
4266         case MGSL_MODE_XSYNC:
4267                 val |= BIT15 + BIT13;
4268                 break;
4269         case MGSL_MODE_MONOSYNC: val |= BIT14 + BIT13; break;
4270         case MGSL_MODE_BISYNC:   val |= BIT15; break;
4271         case MGSL_MODE_RAW:      val |= BIT13; break;
4272         }
4273
4274         switch(info->params.encoding)
4275         {
4276         case HDLC_ENCODING_NRZB:          val |= BIT10; break;
4277         case HDLC_ENCODING_NRZI_MARK:     val |= BIT11; break;
4278         case HDLC_ENCODING_NRZI:          val |= BIT11 + BIT10; break;
4279         case HDLC_ENCODING_BIPHASE_MARK:  val |= BIT12; break;
4280         case HDLC_ENCODING_BIPHASE_SPACE: val |= BIT12 + BIT10; break;
4281         case HDLC_ENCODING_BIPHASE_LEVEL: val |= BIT12 + BIT11; break;
4282         case HDLC_ENCODING_DIFF_BIPHASE_LEVEL: val |= BIT12 + BIT11 + BIT10; break;
4283         }
4284
4285         switch (info->params.crc_type & HDLC_CRC_MASK)
4286         {
4287         case HDLC_CRC_16_CCITT: val |= BIT9; break;
4288         case HDLC_CRC_32_CCITT: val |= BIT9 + BIT8; break;
4289         }
4290
4291         if (info->params.flags & HDLC_FLAG_AUTO_DCD)
4292                 val |= BIT0;
4293
4294         wr_reg16(info, RCR, val);
4295
4296         /* CCR (clock control)
4297          *
4298          * 07..05  tx clock source
4299          * 04..02  rx clock source
4300          * 01      auxclk enable
4301          * 00      BRG enable
4302          */
4303         val = 0;
4304
4305         if (info->params.flags & HDLC_FLAG_TXC_BRG)
4306         {
4307                 // when RxC source is DPLL, BRG generates 16X DPLL
4308                 // reference clock, so take TxC from BRG/16 to get
4309                 // transmit clock at actual data rate
4310                 if (info->params.flags & HDLC_FLAG_RXC_DPLL)
4311                         val |= BIT6 + BIT5;     /* 011, txclk = BRG/16 */
4312                 else
4313                         val |= BIT6;    /* 010, txclk = BRG */
4314         }
4315         else if (info->params.flags & HDLC_FLAG_TXC_DPLL)
4316                 val |= BIT7;    /* 100, txclk = DPLL Input */
4317         else if (info->params.flags & HDLC_FLAG_TXC_RXCPIN)
4318                 val |= BIT5;    /* 001, txclk = RXC Input */
4319
4320         if (info->params.flags & HDLC_FLAG_RXC_BRG)
4321                 val |= BIT3;    /* 010, rxclk = BRG */
4322         else if (info->params.flags & HDLC_FLAG_RXC_DPLL)
4323                 val |= BIT4;    /* 100, rxclk = DPLL */
4324         else if (info->params.flags & HDLC_FLAG_RXC_TXCPIN)
4325                 val |= BIT2;    /* 001, rxclk = TXC Input */
4326
4327         if (info->params.clock_speed)
4328                 val |= BIT1 + BIT0;
4329
4330         wr_reg8(info, CCR, (unsigned char)val);
4331
4332         if (info->params.flags & (HDLC_FLAG_TXC_DPLL + HDLC_FLAG_RXC_DPLL))
4333         {
4334                 // program DPLL mode
4335                 switch(info->params.encoding)
4336                 {
4337                 case HDLC_ENCODING_BIPHASE_MARK:
4338                 case HDLC_ENCODING_BIPHASE_SPACE:
4339                         val = BIT7; break;
4340                 case HDLC_ENCODING_BIPHASE_LEVEL:
4341                 case HDLC_ENCODING_DIFF_BIPHASE_LEVEL:
4342                         val = BIT7 + BIT6; break;
4343                 default: val = BIT6;    // NRZ encodings
4344                 }
4345                 wr_reg16(info, RCR, (unsigned short)(rd_reg16(info, RCR) | val));
4346
4347                 // DPLL requires a 16X reference clock from BRG
4348                 set_rate(info, info->params.clock_speed * 16);
4349         }
4350         else
4351                 set_rate(info, info->params.clock_speed);
4352
4353         tx_set_idle(info);
4354
4355         msc_set_vcr(info);
4356
4357         /* SCR (serial control)
4358          *
4359          * 15  1=tx req on FIFO half empty
4360          * 14  1=rx req on FIFO half full
4361          * 13  tx data  IRQ enable
4362          * 12  tx idle  IRQ enable
4363          * 11  underrun IRQ enable
4364          * 10  rx data  IRQ enable
4365          * 09  rx idle  IRQ enable
4366          * 08  overrun  IRQ enable
4367          * 07  DSR      IRQ enable
4368          * 06  CTS      IRQ enable
4369          * 05  DCD      IRQ enable
4370          * 04  RI       IRQ enable
4371          * 03  reserved, must be zero
4372          * 02  1=txd->rxd internal loopback enable
4373          * 01  reserved, must be zero
4374          * 00  1=master IRQ enable
4375          */
4376         wr_reg16(info, SCR, BIT15 + BIT14 + BIT0);
4377
4378         if (info->params.loopback)
4379                 enable_loopback(info);
4380 }
4381
4382 /*
4383  *  set transmit idle mode
4384  */
4385 static void tx_set_idle(struct slgt_info *info)
4386 {
4387         unsigned char val;
4388         unsigned short tcr;
4389
4390         /* if preamble enabled (tcr[6] == 1) then tx idle size = 8 bits
4391          * else tcr[5:4] = tx idle size: 00 = 8 bits, 01 = 16 bits
4392          */
4393         tcr = rd_reg16(info, TCR);
4394         if (info->idle_mode & HDLC_TXIDLE_CUSTOM_16) {
4395                 /* disable preamble, set idle size to 16 bits */
4396                 tcr = (tcr & ~(BIT6 + BIT5)) | BIT4;
4397                 /* MSB of 16 bit idle specified in tx preamble register (TPR) */
4398                 wr_reg8(info, TPR, (unsigned char)((info->idle_mode >> 8) & 0xff));
4399         } else if (!(tcr & BIT6)) {
4400                 /* preamble is disabled, set idle size to 8 bits */
4401                 tcr &= ~(BIT5 + BIT4);
4402         }
4403         wr_reg16(info, TCR, tcr);
4404
4405         if (info->idle_mode & (HDLC_TXIDLE_CUSTOM_8 | HDLC_TXIDLE_CUSTOM_16)) {
4406                 /* LSB of custom tx idle specified in tx idle register */
4407                 val = (unsigned char)(info->idle_mode & 0xff);
4408         } else {
4409                 /* standard 8 bit idle patterns */
4410                 switch(info->idle_mode)
4411                 {
4412                 case HDLC_TXIDLE_FLAGS:          val = 0x7e; break;
4413                 case HDLC_TXIDLE_ALT_ZEROS_ONES:
4414                 case HDLC_TXIDLE_ALT_MARK_SPACE: val = 0xaa; break;
4415                 case HDLC_TXIDLE_ZEROS:
4416                 case HDLC_TXIDLE_SPACE:          val = 0x00; break;
4417                 default:                         val = 0xff;
4418                 }
4419         }
4420
4421         wr_reg8(info, TIR, val);
4422 }
4423
4424 /*
4425  * get state of V24 status (input) signals
4426  */
4427 static void get_gtsignals(struct slgt_info *info)
4428 {
4429         unsigned short status = rd_reg16(info, SSR);
4430
4431         /* clear all serial signals except RTS and DTR */
4432         info->signals &= SerialSignal_RTS | SerialSignal_DTR;
4433
4434         if (status & BIT3)
4435                 info->signals |= SerialSignal_DSR;
4436         if (status & BIT2)
4437                 info->signals |= SerialSignal_CTS;
4438         if (status & BIT1)
4439                 info->signals |= SerialSignal_DCD;
4440         if (status & BIT0)
4441                 info->signals |= SerialSignal_RI;
4442 }
4443
4444 /*
4445  * set V.24 Control Register based on current configuration
4446  */
4447 static void msc_set_vcr(struct slgt_info *info)
4448 {
4449         unsigned char val = 0;
4450
4451         /* VCR (V.24 control)
4452          *
4453          * 07..04  serial IF select
4454          * 03      DTR
4455          * 02      RTS
4456          * 01      LL
4457          * 00      RL
4458          */
4459
4460         switch(info->if_mode & MGSL_INTERFACE_MASK)
4461         {
4462         case MGSL_INTERFACE_RS232:
4463                 val |= BIT5; /* 0010 */
4464                 break;
4465         case MGSL_INTERFACE_V35:
4466                 val |= BIT7 + BIT6 + BIT5; /* 1110 */
4467                 break;
4468         case MGSL_INTERFACE_RS422:
4469                 val |= BIT6; /* 0100 */
4470                 break;
4471         }
4472
4473         if (info->if_mode & MGSL_INTERFACE_MSB_FIRST)
4474                 val |= BIT4;
4475         if (info->signals & SerialSignal_DTR)
4476                 val |= BIT3;
4477         if (info->signals & SerialSignal_RTS)
4478                 val |= BIT2;
4479         if (info->if_mode & MGSL_INTERFACE_LL)
4480                 val |= BIT1;
4481         if (info->if_mode & MGSL_INTERFACE_RL)
4482                 val |= BIT0;
4483         wr_reg8(info, VCR, val);
4484 }
4485
4486 /*
4487  * set state of V24 control (output) signals
4488  */
4489 static void set_gtsignals(struct slgt_info *info)
4490 {
4491         unsigned char val = rd_reg8(info, VCR);
4492         if (info->signals & SerialSignal_DTR)
4493                 val |= BIT3;
4494         else
4495                 val &= ~BIT3;
4496         if (info->signals & SerialSignal_RTS)
4497                 val |= BIT2;
4498         else
4499                 val &= ~BIT2;
4500         wr_reg8(info, VCR, val);
4501 }
4502
4503 /*
4504  * free range of receive DMA buffers (i to last)
4505  */
4506 static void free_rbufs(struct slgt_info *info, unsigned int i, unsigned int last)
4507 {
4508         int done = 0;
4509
4510         while(!done) {
4511                 /* reset current buffer for reuse */
4512                 info->rbufs[i].status = 0;
4513                 set_desc_count(info->rbufs[i], info->rbuf_fill_level);
4514                 if (i == last)
4515                         done = 1;
4516                 if (++i == info->rbuf_count)
4517                         i = 0;
4518         }
4519         info->rbuf_current = i;
4520 }
4521
4522 /*
4523  * mark all receive DMA buffers as free
4524  */
4525 static void reset_rbufs(struct slgt_info *info)
4526 {
4527         free_rbufs(info, 0, info->rbuf_count - 1);
4528         info->rbuf_fill_index = 0;
4529         info->rbuf_fill_count = 0;
4530 }
4531
4532 /*
4533  * pass receive HDLC frame to upper layer
4534  *
4535  * return true if frame available, otherwise false
4536  */
4537 static bool rx_get_frame(struct slgt_info *info)
4538 {
4539         unsigned int start, end;
4540         unsigned short status;
4541         unsigned int framesize = 0;
4542         unsigned long flags;
4543         struct tty_struct *tty = info->port.tty;
4544         unsigned char addr_field = 0xff;
4545         unsigned int crc_size = 0;
4546
4547         switch (info->params.crc_type & HDLC_CRC_MASK) {
4548         case HDLC_CRC_16_CCITT: crc_size = 2; break;
4549         case HDLC_CRC_32_CCITT: crc_size = 4; break;
4550         }
4551
4552 check_again:
4553
4554         framesize = 0;
4555         addr_field = 0xff;
4556         start = end = info->rbuf_current;
4557
4558         for (;;) {
4559                 if (!desc_complete(info->rbufs[end]))
4560                         goto cleanup;
4561
4562                 if (framesize == 0 && info->params.addr_filter != 0xff)
4563                         addr_field = info->rbufs[end].buf[0];
4564
4565                 framesize += desc_count(info->rbufs[end]);
4566
4567                 if (desc_eof(info->rbufs[end]))
4568                         break;
4569
4570                 if (++end == info->rbuf_count)
4571                         end = 0;
4572
4573                 if (end == info->rbuf_current) {
4574                         if (info->rx_enabled){
4575                                 spin_lock_irqsave(&info->lock,flags);
4576                                 rx_start(info);
4577                                 spin_unlock_irqrestore(&info->lock,flags);
4578                         }
4579                         goto cleanup;
4580                 }
4581         }
4582
4583         /* status
4584          *
4585          * 15      buffer complete
4586          * 14..06  reserved
4587          * 05..04  residue
4588          * 02      eof (end of frame)
4589          * 01      CRC error
4590          * 00      abort
4591          */
4592         status = desc_status(info->rbufs[end]);
4593
4594         /* ignore CRC bit if not using CRC (bit is undefined) */
4595         if ((info->params.crc_type & HDLC_CRC_MASK) == HDLC_CRC_NONE)
4596                 status &= ~BIT1;
4597
4598         if (framesize == 0 ||
4599                  (addr_field != 0xff && addr_field != info->params.addr_filter)) {
4600                 free_rbufs(info, start, end);
4601                 goto check_again;
4602         }
4603
4604         if (framesize < (2 + crc_size) || status & BIT0) {
4605                 info->icount.rxshort++;
4606                 framesize = 0;
4607         } else if (status & BIT1) {
4608                 info->icount.rxcrc++;
4609                 if (!(info->params.crc_type & HDLC_CRC_RETURN_EX))
4610                         framesize = 0;
4611         }
4612
4613 #if SYNCLINK_GENERIC_HDLC
4614         if (framesize == 0) {
4615                 info->netdev->stats.rx_errors++;
4616                 info->netdev->stats.rx_frame_errors++;
4617         }
4618 #endif
4619
4620         DBGBH(("%s rx frame status=%04X size=%d\n",
4621                 info->device_name, status, framesize));
4622         DBGDATA(info, info->rbufs[start].buf, min_t(int, framesize, info->rbuf_fill_level), "rx");
4623
4624         if (framesize) {
4625                 if (!(info->params.crc_type & HDLC_CRC_RETURN_EX)) {
4626                         framesize -= crc_size;
4627                         crc_size = 0;
4628                 }
4629
4630                 if (framesize > info->max_frame_size + crc_size)
4631                         info->icount.rxlong++;
4632                 else {
4633                         /* copy dma buffer(s) to contiguous temp buffer */
4634                         int copy_count = framesize;
4635                         int i = start;
4636                         unsigned char *p = info->tmp_rbuf;
4637                         info->tmp_rbuf_count = framesize;
4638
4639                         info->icount.rxok++;
4640
4641                         while(copy_count) {
4642                                 int partial_count = min_t(int, copy_count, info->rbuf_fill_level);
4643                                 memcpy(p, info->rbufs[i].buf, partial_count);
4644                                 p += partial_count;
4645                                 copy_count -= partial_count;
4646                                 if (++i == info->rbuf_count)
4647                                         i = 0;
4648                         }
4649
4650                         if (info->params.crc_type & HDLC_CRC_RETURN_EX) {
4651                                 *p = (status & BIT1) ? RX_CRC_ERROR : RX_OK;
4652                                 framesize++;
4653                         }
4654
4655 #if SYNCLINK_GENERIC_HDLC
4656                         if (info->netcount)
4657                                 hdlcdev_rx(info,info->tmp_rbuf, framesize);
4658                         else
4659 #endif
4660                                 ldisc_receive_buf(tty, info->tmp_rbuf, info->flag_buf, framesize);
4661                 }
4662         }
4663         free_rbufs(info, start, end);
4664         return true;
4665
4666 cleanup:
4667         return false;
4668 }
4669
4670 /*
4671  * pass receive buffer (RAW synchronous mode) to tty layer
4672  * return true if buffer available, otherwise false
4673  */
4674 static bool rx_get_buf(struct slgt_info *info)
4675 {
4676         unsigned int i = info->rbuf_current;
4677         unsigned int count;
4678
4679         if (!desc_complete(info->rbufs[i]))
4680                 return false;
4681         count = desc_count(info->rbufs[i]);
4682         switch(info->params.mode) {
4683         case MGSL_MODE_MONOSYNC:
4684         case MGSL_MODE_BISYNC:
4685         case MGSL_MODE_XSYNC:
4686                 /* ignore residue in byte synchronous modes */
4687                 if (desc_residue(info->rbufs[i]))
4688                         count--;
4689                 break;
4690         }
4691         DBGDATA(info, info->rbufs[i].buf, count, "rx");
4692         DBGINFO(("rx_get_buf size=%d\n", count));
4693         if (count)
4694                 ldisc_receive_buf(info->port.tty, info->rbufs[i].buf,
4695                                   info->flag_buf, count);
4696         free_rbufs(info, i, i);
4697         return true;
4698 }
4699
4700 static void reset_tbufs(struct slgt_info *info)
4701 {
4702         unsigned int i;
4703         info->tbuf_current = 0;
4704         for (i=0 ; i < info->tbuf_count ; i++) {
4705                 info->tbufs[i].status = 0;
4706                 info->tbufs[i].count  = 0;
4707         }
4708 }
4709
4710 /*
4711  * return number of free transmit DMA buffers
4712  */
4713 static unsigned int free_tbuf_count(struct slgt_info *info)
4714 {
4715         unsigned int count = 0;
4716         unsigned int i = info->tbuf_current;
4717
4718         do
4719         {
4720                 if (desc_count(info->tbufs[i]))
4721                         break; /* buffer in use */
4722                 ++count;
4723                 if (++i == info->tbuf_count)
4724                         i=0;
4725         } while (i != info->tbuf_current);
4726
4727         /* if tx DMA active, last zero count buffer is in use */
4728         if (count && (rd_reg32(info, TDCSR) & BIT0))
4729                 --count;
4730
4731         return count;
4732 }
4733
4734 /*
4735  * return number of bytes in unsent transmit DMA buffers
4736  * and the serial controller tx FIFO
4737  */
4738 static unsigned int tbuf_bytes(struct slgt_info *info)
4739 {
4740         unsigned int total_count = 0;
4741         unsigned int i = info->tbuf_current;
4742         unsigned int reg_value;
4743         unsigned int count;
4744         unsigned int active_buf_count = 0;
4745
4746         /*
4747          * Add descriptor counts for all tx DMA buffers.
4748          * If count is zero (cleared by DMA controller after read),
4749          * the buffer is complete or is actively being read from.
4750          *
4751          * Record buf_count of last buffer with zero count starting
4752          * from current ring position. buf_count is mirror
4753          * copy of count and is not cleared by serial controller.
4754          * If DMA controller is active, that buffer is actively
4755          * being read so add to total.
4756          */
4757         do {
4758                 count = desc_count(info->tbufs[i]);
4759                 if (count)
4760                         total_count += count;
4761                 else if (!total_count)
4762                         active_buf_count = info->tbufs[i].buf_count;
4763                 if (++i == info->tbuf_count)
4764                         i = 0;
4765         } while (i != info->tbuf_current);
4766
4767         /* read tx DMA status register */
4768         reg_value = rd_reg32(info, TDCSR);
4769
4770         /* if tx DMA active, last zero count buffer is in use */
4771         if (reg_value & BIT0)
4772                 total_count += active_buf_count;
4773
4774         /* add tx FIFO count = reg_value[15..8] */
4775         total_count += (reg_value >> 8) & 0xff;
4776
4777         /* if transmitter active add one byte for shift register */
4778         if (info->tx_active)
4779                 total_count++;
4780
4781         return total_count;
4782 }
4783
4784 /*
4785  * load data into transmit DMA buffer ring and start transmitter if needed
4786  * return true if data accepted, otherwise false (buffers full)
4787  */
4788 static bool tx_load(struct slgt_info *info, const char *buf, unsigned int size)
4789 {
4790         unsigned short count;
4791         unsigned int i;
4792         struct slgt_desc *d;
4793
4794         /* check required buffer space */
4795         if (DIV_ROUND_UP(size, DMABUFSIZE) > free_tbuf_count(info))
4796                 return false;
4797
4798         DBGDATA(info, buf, size, "tx");
4799
4800         /*
4801          * copy data to one or more DMA buffers in circular ring
4802          * tbuf_start   = first buffer for this data
4803          * tbuf_current = next free buffer
4804          *
4805          * Copy all data before making data visible to DMA controller by
4806          * setting descriptor count of the first buffer.
4807          * This prevents an active DMA controller from reading the first DMA
4808          * buffers of a frame and stopping before the final buffers are filled.
4809          */
4810
4811         info->tbuf_start = i = info->tbuf_current;
4812
4813         while (size) {
4814                 d = &info->tbufs[i];
4815
4816                 count = (unsigned short)((size > DMABUFSIZE) ? DMABUFSIZE : size);
4817                 memcpy(d->buf, buf, count);
4818
4819                 size -= count;
4820                 buf  += count;
4821
4822                 /*
4823                  * set EOF bit for last buffer of HDLC frame or
4824                  * for every buffer in raw mode
4825                  */
4826                 if ((!size && info->params.mode == MGSL_MODE_HDLC) ||
4827                     info->params.mode == MGSL_MODE_RAW)
4828                         set_desc_eof(*d, 1);
4829                 else
4830                         set_desc_eof(*d, 0);
4831
4832                 /* set descriptor count for all but first buffer */
4833                 if (i != info->tbuf_start)
4834                         set_desc_count(*d, count);
4835                 d->buf_count = count;
4836
4837                 if (++i == info->tbuf_count)
4838                         i = 0;
4839         }
4840
4841         info->tbuf_current = i;
4842
4843         /* set first buffer count to make new data visible to DMA controller */
4844         d = &info->tbufs[info->tbuf_start];
4845         set_desc_count(*d, d->buf_count);
4846
4847         /* start transmitter if needed and update transmit timeout */
4848         if (!info->tx_active)
4849                 tx_start(info);
4850         update_tx_timer(info);
4851
4852         return true;
4853 }
4854
4855 static int register_test(struct slgt_info *info)
4856 {
4857         static unsigned short patterns[] =
4858                 {0x0000, 0xffff, 0xaaaa, 0x5555, 0x6969, 0x9696};
4859         static unsigned int count = ARRAY_SIZE(patterns);
4860         unsigned int i;
4861         int rc = 0;
4862
4863         for (i=0 ; i < count ; i++) {
4864                 wr_reg16(info, TIR, patterns[i]);
4865                 wr_reg16(info, BDR, patterns[(i+1)%count]);
4866                 if ((rd_reg16(info, TIR) != patterns[i]) ||
4867                     (rd_reg16(info, BDR) != patterns[(i+1)%count])) {
4868                         rc = -ENODEV;
4869                         break;
4870                 }
4871         }
4872         info->gpio_present = (rd_reg32(info, JCR) & BIT5) ? 1 : 0;
4873         info->init_error = rc ? 0 : DiagStatus_AddressFailure;
4874         return rc;
4875 }
4876
4877 static int irq_test(struct slgt_info *info)
4878 {
4879         unsigned long timeout;
4880         unsigned long flags;
4881         struct tty_struct *oldtty = info->port.tty;
4882         u32 speed = info->params.data_rate;
4883
4884         info->params.data_rate = 921600;
4885         info->port.tty = NULL;
4886
4887         spin_lock_irqsave(&info->lock, flags);
4888         async_mode(info);
4889         slgt_irq_on(info, IRQ_TXIDLE);
4890
4891         /* enable transmitter */
4892         wr_reg16(info, TCR,
4893                 (unsigned short)(rd_reg16(info, TCR) | BIT1));
4894
4895         /* write one byte and wait for tx idle */
4896         wr_reg16(info, TDR, 0);
4897
4898         /* assume failure */
4899         info->init_error = DiagStatus_IrqFailure;
4900         info->irq_occurred = false;
4901
4902         spin_unlock_irqrestore(&info->lock, flags);
4903
4904         timeout=100;
4905         while(timeout-- && !info->irq_occurred)
4906                 msleep_interruptible(10);
4907
4908         spin_lock_irqsave(&info->lock,flags);
4909         reset_port(info);
4910         spin_unlock_irqrestore(&info->lock,flags);
4911
4912         info->params.data_rate = speed;
4913         info->port.tty = oldtty;
4914
4915         info->init_error = info->irq_occurred ? 0 : DiagStatus_IrqFailure;
4916         return info->irq_occurred ? 0 : -ENODEV;
4917 }
4918
4919 static int loopback_test_rx(struct slgt_info *info)
4920 {
4921         unsigned char *src, *dest;
4922         int count;
4923
4924         if (desc_complete(info->rbufs[0])) {
4925                 count = desc_count(info->rbufs[0]);
4926                 src   = info->rbufs[0].buf;
4927                 dest  = info->tmp_rbuf;
4928
4929                 for( ; count ; count-=2, src+=2) {
4930                         /* src=data byte (src+1)=status byte */
4931                         if (!(*(src+1) & (BIT9 + BIT8))) {
4932                                 *dest = *src;
4933                                 dest++;
4934                                 info->tmp_rbuf_count++;
4935                         }
4936                 }
4937                 DBGDATA(info, info->tmp_rbuf, info->tmp_rbuf_count, "rx");
4938                 return 1;
4939         }
4940         return 0;
4941 }
4942
4943 static int loopback_test(struct slgt_info *info)
4944 {
4945 #define TESTFRAMESIZE 20
4946
4947         unsigned long timeout;
4948         u16 count;
4949         unsigned char buf[TESTFRAMESIZE];
4950         int rc = -ENODEV;
4951         unsigned long flags;
4952
4953         struct tty_struct *oldtty = info->port.tty;
4954         MGSL_PARAMS params;
4955
4956         memcpy(&params, &info->params, sizeof(params));
4957
4958         info->params.mode = MGSL_MODE_ASYNC;
4959         info->params.data_rate = 921600;
4960         info->params.loopback = 1;
4961         info->port.tty = NULL;
4962
4963         /* build and send transmit frame */
4964         for (count = 0; count < TESTFRAMESIZE; ++count)
4965                 buf[count] = (unsigned char)count;
4966
4967         info->tmp_rbuf_count = 0;
4968         memset(info->tmp_rbuf, 0, TESTFRAMESIZE);
4969
4970         /* program hardware for HDLC and enabled receiver */
4971         spin_lock_irqsave(&info->lock,flags);
4972         async_mode(info);
4973         rx_start(info);
4974         tx_load(info, buf, count);
4975         spin_unlock_irqrestore(&info->lock, flags);
4976
4977         /* wait for receive complete */
4978         for (timeout = 100; timeout; --timeout) {
4979                 msleep_interruptible(10);
4980                 if (loopback_test_rx(info)) {
4981                         rc = 0;
4982                         break;
4983                 }
4984         }
4985
4986         /* verify received frame length and contents */
4987         if (!rc && (info->tmp_rbuf_count != count ||
4988                   memcmp(buf, info->tmp_rbuf, count))) {
4989                 rc = -ENODEV;
4990         }
4991
4992         spin_lock_irqsave(&info->lock,flags);
4993         reset_adapter(info);
4994         spin_unlock_irqrestore(&info->lock,flags);
4995
4996         memcpy(&info->params, &params, sizeof(info->params));
4997         info->port.tty = oldtty;
4998
4999         info->init_error = rc ? DiagStatus_DmaFailure : 0;
5000         return rc;
5001 }
5002
5003 static int adapter_test(struct slgt_info *info)
5004 {
5005         DBGINFO(("testing %s\n", info->device_name));
5006         if (register_test(info) < 0) {
5007                 printk("register test failure %s addr=%08X\n",
5008                         info->device_name, info->phys_reg_addr);
5009         } else if (irq_test(info) < 0) {
5010                 printk("IRQ test failure %s IRQ=%d\n",
5011                         info->device_name, info->irq_level);
5012         } else if (loopback_test(info) < 0) {
5013                 printk("loopback test failure %s\n", info->device_name);
5014         }
5015         return info->init_error;
5016 }
5017
5018 /*
5019  * transmit timeout handler
5020  */
5021 static void tx_timeout(struct timer_list *t)
5022 {
5023         struct slgt_info *info = from_timer(info, t, tx_timer);
5024         unsigned long flags;
5025
5026         DBGINFO(("%s tx_timeout\n", info->device_name));
5027         if(info->tx_active && info->params.mode == MGSL_MODE_HDLC) {
5028                 info->icount.txtimeout++;
5029         }
5030         spin_lock_irqsave(&info->lock,flags);
5031         tx_stop(info);
5032         spin_unlock_irqrestore(&info->lock,flags);
5033
5034 #if SYNCLINK_GENERIC_HDLC
5035         if (info->netcount)
5036                 hdlcdev_tx_done(info);
5037         else
5038 #endif
5039                 bh_transmit(info);
5040 }
5041
5042 /*
5043  * receive buffer polling timer
5044  */
5045 static void rx_timeout(struct timer_list *t)
5046 {
5047         struct slgt_info *info = from_timer(info, t, rx_timer);
5048         unsigned long flags;
5049
5050         DBGINFO(("%s rx_timeout\n", info->device_name));
5051         spin_lock_irqsave(&info->lock, flags);
5052         info->pending_bh |= BH_RECEIVE;
5053         spin_unlock_irqrestore(&info->lock, flags);
5054         bh_handler(&info->task);
5055 }
5056