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