Char: moxa, remove port->port
[pandora-kernel.git] / drivers / char / moxa.c
1 /*****************************************************************************/
2 /*
3  *           moxa.c  -- MOXA Intellio family multiport serial driver.
4  *
5  *      Copyright (C) 1999-2000  Moxa Technologies (support@moxa.com.tw).
6  *
7  *      This code is loosely based on the Linux serial driver, written by
8  *      Linus Torvalds, Theodore T'so and others.
9  *
10  *      This program is free software; you can redistribute it and/or modify
11  *      it under the terms of the GNU General Public License as published by
12  *      the Free Software Foundation; either version 2 of the License, or
13  *      (at your option) any later version.
14  */
15
16 /*
17  *    MOXA Intellio Series Driver
18  *      for             : LINUX
19  *      date            : 1999/1/7
20  *      version         : 5.1
21  */
22
23 #include <linux/module.h>
24 #include <linux/types.h>
25 #include <linux/mm.h>
26 #include <linux/ioport.h>
27 #include <linux/errno.h>
28 #include <linux/firmware.h>
29 #include <linux/signal.h>
30 #include <linux/sched.h>
31 #include <linux/timer.h>
32 #include <linux/interrupt.h>
33 #include <linux/tty.h>
34 #include <linux/tty_flip.h>
35 #include <linux/major.h>
36 #include <linux/string.h>
37 #include <linux/fcntl.h>
38 #include <linux/ptrace.h>
39 #include <linux/serial.h>
40 #include <linux/tty_driver.h>
41 #include <linux/delay.h>
42 #include <linux/pci.h>
43 #include <linux/init.h>
44 #include <linux/bitops.h>
45 #include <linux/completion.h>
46
47 #include <asm/system.h>
48 #include <asm/io.h>
49 #include <asm/uaccess.h>
50
51 #include "moxa.h"
52
53 #define MOXA_VERSION            "5.1k"
54
55 #define MOXA_FW_HDRLEN          32
56
57 #define MOXAMAJOR               172
58 #define MOXACUMAJOR             173
59
60 #define MAX_BOARDS              4       /* Don't change this value */
61 #define MAX_PORTS_PER_BOARD     32      /* Don't change this value */
62 #define MAX_PORTS               (MAX_BOARDS * MAX_PORTS_PER_BOARD)
63
64 /*
65  *    Define the Moxa PCI vendor and device IDs.
66  */
67 #define MOXA_BUS_TYPE_ISA       0
68 #define MOXA_BUS_TYPE_PCI       1
69
70 enum {
71         MOXA_BOARD_C218_PCI = 1,
72         MOXA_BOARD_C218_ISA,
73         MOXA_BOARD_C320_PCI,
74         MOXA_BOARD_C320_ISA,
75         MOXA_BOARD_CP204J,
76 };
77
78 static char *moxa_brdname[] =
79 {
80         "C218 Turbo PCI series",
81         "C218 Turbo ISA series",
82         "C320 Turbo PCI series",
83         "C320 Turbo ISA series",
84         "CP-204J series",
85 };
86
87 #ifdef CONFIG_PCI
88 static struct pci_device_id moxa_pcibrds[] = {
89         { PCI_DEVICE(PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_MOXA_C218),
90                 .driver_data = MOXA_BOARD_C218_PCI },
91         { PCI_DEVICE(PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_MOXA_C320),
92                 .driver_data = MOXA_BOARD_C320_PCI },
93         { PCI_DEVICE(PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_MOXA_CP204J),
94                 .driver_data = MOXA_BOARD_CP204J },
95         { 0 }
96 };
97 MODULE_DEVICE_TABLE(pci, moxa_pcibrds);
98 #endif /* CONFIG_PCI */
99
100 struct moxa_port;
101
102 static struct moxa_board_conf {
103         int boardType;
104         int numPorts;
105         int busType;
106
107         int loadstat;
108
109         struct moxa_port *ports;
110
111         void __iomem *basemem;
112         void __iomem *intNdx;
113         void __iomem *intPend;
114         void __iomem *intTable;
115 } moxa_boards[MAX_BOARDS];
116
117 struct mxser_mstatus {
118         tcflag_t cflag;
119         int cts;
120         int dsr;
121         int ri;
122         int dcd;
123 };
124
125 struct moxaq_str {
126         int inq;
127         int outq;
128 };
129
130 struct moxa_port {
131         struct moxa_board_conf *board;
132         int type;
133         int close_delay;
134         unsigned short closing_wait;
135         int count;
136         int blocked_open;
137         long event; /* long req'd for set_bit --RR */
138         int asyncflags;
139         unsigned long statusflags;
140         struct tty_struct *tty;
141         int cflag;
142         wait_queue_head_t open_wait;
143         struct completion close_wait;
144
145         struct timer_list emptyTimer;
146
147         char chkPort;
148         char lineCtrl;
149         void __iomem *tableAddr;
150         long curBaud;
151         char DCDState;
152         char lowChkFlag;
153
154         ushort breakCnt;
155 };
156
157 /* statusflags */
158 #define TXSTOPPED       0x1
159 #define LOWWAIT         0x2
160 #define EMPTYWAIT       0x4
161 #define THROTTLE        0x8
162
163 #define SERIAL_DO_RESTART
164
165 #define WAKEUP_CHARS            256
166
167 static int ttymajor = MOXAMAJOR;
168 static int moxaCard;
169 /* Variables for insmod */
170 #ifdef MODULE
171 static unsigned long baseaddr[MAX_BOARDS];
172 static unsigned int type[MAX_BOARDS];
173 static unsigned int numports[MAX_BOARDS];
174 #endif
175
176 MODULE_AUTHOR("William Chen");
177 MODULE_DESCRIPTION("MOXA Intellio Family Multiport Board Device Driver");
178 MODULE_LICENSE("GPL");
179 #ifdef MODULE
180 module_param_array(type, uint, NULL, 0);
181 MODULE_PARM_DESC(type, "card type: C218=2, C320=4");
182 module_param_array(baseaddr, ulong, NULL, 0);
183 MODULE_PARM_DESC(baseaddr, "base address");
184 module_param_array(numports, uint, NULL, 0);
185 MODULE_PARM_DESC(numports, "numports (ignored for C218)");
186 #endif
187 module_param(ttymajor, int, 0);
188
189 /*
190  * static functions:
191  */
192 static int moxa_open(struct tty_struct *, struct file *);
193 static void moxa_close(struct tty_struct *, struct file *);
194 static int moxa_write(struct tty_struct *, const unsigned char *, int);
195 static int moxa_write_room(struct tty_struct *);
196 static void moxa_flush_buffer(struct tty_struct *);
197 static int moxa_chars_in_buffer(struct tty_struct *);
198 static void moxa_flush_chars(struct tty_struct *);
199 static void moxa_put_char(struct tty_struct *, unsigned char);
200 static int moxa_ioctl(struct tty_struct *, struct file *, unsigned int, unsigned long);
201 static void moxa_throttle(struct tty_struct *);
202 static void moxa_unthrottle(struct tty_struct *);
203 static void moxa_set_termios(struct tty_struct *, struct ktermios *);
204 static void moxa_stop(struct tty_struct *);
205 static void moxa_start(struct tty_struct *);
206 static void moxa_hangup(struct tty_struct *);
207 static int moxa_tiocmget(struct tty_struct *tty, struct file *file);
208 static int moxa_tiocmset(struct tty_struct *tty, struct file *file,
209                          unsigned int set, unsigned int clear);
210 static void moxa_poll(unsigned long);
211 static void moxa_set_tty_param(struct tty_struct *, struct ktermios *);
212 static int moxa_block_till_ready(struct tty_struct *, struct file *,
213                             struct moxa_port *);
214 static void moxa_setup_empty_event(struct tty_struct *);
215 static void moxa_check_xmit_empty(unsigned long);
216 static void moxa_shut_down(struct moxa_port *);
217 static void moxa_receive_data(struct moxa_port *);
218 /*
219  * moxa board interface functions:
220  */
221 static int MoxaDriverIoctl(struct tty_struct *, unsigned int, unsigned long);
222 static int MoxaDriverPoll(void);
223 static int MoxaPortsOfCard(int);
224 static int MoxaPortIsValid(int);
225 static void MoxaPortEnable(struct moxa_port *);
226 static void MoxaPortDisable(struct moxa_port *);
227 static int MoxaPortSetTermio(struct moxa_port *, struct ktermios *, speed_t);
228 static int MoxaPortGetLineOut(struct moxa_port *, int *, int *);
229 static void MoxaPortLineCtrl(struct moxa_port *, int, int);
230 static void MoxaPortFlowCtrl(struct moxa_port *, int, int, int, int, int);
231 static int MoxaPortLineStatus(struct moxa_port *);
232 static int MoxaPortDCDChange(struct moxa_port *);
233 static int MoxaPortDCDON(struct moxa_port *);
234 static void MoxaPortFlushData(struct moxa_port *, int);
235 static int MoxaPortWriteData(struct moxa_port *, unsigned char *, int);
236 static int MoxaPortReadData(struct moxa_port *, struct tty_struct *tty);
237 static int MoxaPortTxQueue(struct moxa_port *);
238 static int MoxaPortRxQueue(struct moxa_port *);
239 static int MoxaPortTxFree(struct moxa_port *);
240 static void MoxaPortTxDisable(struct moxa_port *);
241 static void MoxaPortTxEnable(struct moxa_port *);
242 static int MoxaPortResetBrkCnt(struct moxa_port *);
243 static void MoxaPortSendBreak(struct moxa_port *, int);
244 static int moxa_get_serial_info(struct moxa_port *, struct serial_struct __user *);
245 static int moxa_set_serial_info(struct moxa_port *, struct serial_struct __user *);
246 static void MoxaSetFifo(struct moxa_port *port, int enable);
247
248 static const struct tty_operations moxa_ops = {
249         .open = moxa_open,
250         .close = moxa_close,
251         .write = moxa_write,
252         .write_room = moxa_write_room,
253         .flush_buffer = moxa_flush_buffer,
254         .chars_in_buffer = moxa_chars_in_buffer,
255         .flush_chars = moxa_flush_chars,
256         .put_char = moxa_put_char,
257         .ioctl = moxa_ioctl,
258         .throttle = moxa_throttle,
259         .unthrottle = moxa_unthrottle,
260         .set_termios = moxa_set_termios,
261         .stop = moxa_stop,
262         .start = moxa_start,
263         .hangup = moxa_hangup,
264         .tiocmget = moxa_tiocmget,
265         .tiocmset = moxa_tiocmset,
266 };
267
268 static struct tty_driver *moxaDriver;
269 static struct moxa_port moxa_ports[MAX_PORTS];
270 static DEFINE_TIMER(moxaTimer, moxa_poll, 0, 0);
271 static DEFINE_SPINLOCK(moxa_lock);
272
273 static int moxa_check_fw_model(struct moxa_board_conf *brd, u8 model)
274 {
275         switch (brd->boardType) {
276         case MOXA_BOARD_C218_ISA:
277         case MOXA_BOARD_C218_PCI:
278                 if (model != 1)
279                         goto err;
280                 break;
281         case MOXA_BOARD_CP204J:
282                 if (model != 3)
283                         goto err;
284                 break;
285         default:
286                 if (model != 2)
287                         goto err;
288                 break;
289         }
290         return 0;
291 err:
292         return -EINVAL;
293 }
294
295 static int moxa_check_fw(const void *ptr)
296 {
297         const __le16 *lptr = ptr;
298
299         if (*lptr != cpu_to_le16(0x7980))
300                 return -EINVAL;
301
302         return 0;
303 }
304
305 static int moxa_load_bios(struct moxa_board_conf *brd, const u8 *buf,
306                 size_t len)
307 {
308         void __iomem *baseAddr = brd->basemem;
309         u16 tmp;
310
311         writeb(HW_reset, baseAddr + Control_reg);       /* reset */
312         msleep(10);
313         memset_io(baseAddr, 0, 4096);
314         memcpy_toio(baseAddr, buf, len);        /* download BIOS */
315         writeb(0, baseAddr + Control_reg);      /* restart */
316
317         msleep(2000);
318
319         switch (brd->boardType) {
320         case MOXA_BOARD_C218_ISA:
321         case MOXA_BOARD_C218_PCI:
322                 tmp = readw(baseAddr + C218_key);
323                 if (tmp != C218_KeyCode)
324                         goto err;
325                 break;
326         case MOXA_BOARD_CP204J:
327                 tmp = readw(baseAddr + C218_key);
328                 if (tmp != CP204J_KeyCode)
329                         goto err;
330                 break;
331         default:
332                 tmp = readw(baseAddr + C320_key);
333                 if (tmp != C320_KeyCode)
334                         goto err;
335                 tmp = readw(baseAddr + C320_status);
336                 if (tmp != STS_init) {
337                         printk(KERN_ERR "moxa: bios upload failed -- CPU/Basic "
338                                         "module not found\n");
339                         return -EIO;
340                 }
341                 break;
342         }
343
344         return 0;
345 err:
346         printk(KERN_ERR "moxa: bios upload failed -- board not found\n");
347         return -EIO;
348 }
349
350 static int moxa_load_320b(struct moxa_board_conf *brd, const u8 *ptr,
351                 size_t len)
352 {
353         void __iomem *baseAddr = brd->basemem;
354
355         if (len < 7168) {
356                 printk(KERN_ERR "moxa: invalid 320 bios -- too short\n");
357                 return -EINVAL;
358         }
359
360         writew(len - 7168 - 2, baseAddr + C320bapi_len);
361         writeb(1, baseAddr + Control_reg);      /* Select Page 1 */
362         memcpy_toio(baseAddr + DynPage_addr, ptr, 7168);
363         writeb(2, baseAddr + Control_reg);      /* Select Page 2 */
364         memcpy_toio(baseAddr + DynPage_addr, ptr + 7168, len - 7168);
365
366         return 0;
367 }
368
369 static int moxa_real_load_code(struct moxa_board_conf *brd, const void *ptr,
370                 size_t len)
371 {
372         void __iomem *baseAddr = brd->basemem;
373         const u16 *uptr = ptr;
374         size_t wlen, len2, j;
375         unsigned long key, loadbuf, loadlen, checksum, checksum_ok;
376         unsigned int i, retry, c320;
377         u16 usum, keycode;
378
379         c320 = brd->boardType == MOXA_BOARD_C320_PCI ||
380                         brd->boardType == MOXA_BOARD_C320_ISA;
381         keycode = (brd->boardType == MOXA_BOARD_CP204J) ? CP204J_KeyCode :
382                                 C218_KeyCode;
383
384         switch (brd->boardType) {
385         case MOXA_BOARD_CP204J:
386         case MOXA_BOARD_C218_ISA:
387         case MOXA_BOARD_C218_PCI:
388                 key = C218_key;
389                 loadbuf = C218_LoadBuf;
390                 loadlen = C218DLoad_len;
391                 checksum = C218check_sum;
392                 checksum_ok = C218chksum_ok;
393                 break;
394         default:
395                 key = C320_key;
396                 keycode = C320_KeyCode;
397                 loadbuf = C320_LoadBuf;
398                 loadlen = C320DLoad_len;
399                 checksum = C320check_sum;
400                 checksum_ok = C320chksum_ok;
401                 break;
402         }
403
404         usum = 0;
405         wlen = len >> 1;
406         for (i = 0; i < wlen; i++)
407                 usum += le16_to_cpu(uptr[i]);
408         retry = 0;
409         do {
410                 wlen = len >> 1;
411                 j = 0;
412                 while (wlen) {
413                         len2 = (wlen > 2048) ? 2048 : wlen;
414                         wlen -= len2;
415                         memcpy_toio(baseAddr + loadbuf, ptr + j, len2 << 1);
416                         j += len2 << 1;
417
418                         writew(len2, baseAddr + loadlen);
419                         writew(0, baseAddr + key);
420                         for (i = 0; i < 100; i++) {
421                                 if (readw(baseAddr + key) == keycode)
422                                         break;
423                                 msleep(10);
424                         }
425                         if (readw(baseAddr + key) != keycode)
426                                 return -EIO;
427                 }
428                 writew(0, baseAddr + loadlen);
429                 writew(usum, baseAddr + checksum);
430                 writew(0, baseAddr + key);
431                 for (i = 0; i < 100; i++) {
432                         if (readw(baseAddr + key) == keycode)
433                                 break;
434                         msleep(10);
435                 }
436                 retry++;
437         } while ((readb(baseAddr + checksum_ok) != 1) && (retry < 3));
438         if (readb(baseAddr + checksum_ok) != 1)
439                 return -EIO;
440
441         writew(0, baseAddr + key);
442         for (i = 0; i < 600; i++) {
443                 if (readw(baseAddr + Magic_no) == Magic_code)
444                         break;
445                 msleep(10);
446         }
447         if (readw(baseAddr + Magic_no) != Magic_code)
448                 return -EIO;
449
450         if (c320) {
451                 if (brd->busType == MOXA_BUS_TYPE_PCI) {        /* ASIC board */
452                         writew(0x3800, baseAddr + TMS320_PORT1);
453                         writew(0x3900, baseAddr + TMS320_PORT2);
454                         writew(28499, baseAddr + TMS320_CLOCK);
455                 } else {
456                         writew(0x3200, baseAddr + TMS320_PORT1);
457                         writew(0x3400, baseAddr + TMS320_PORT2);
458                         writew(19999, baseAddr + TMS320_CLOCK);
459                 }
460         }
461         writew(1, baseAddr + Disable_IRQ);
462         writew(0, baseAddr + Magic_no);
463         for (i = 0; i < 500; i++) {
464                 if (readw(baseAddr + Magic_no) == Magic_code)
465                         break;
466                 msleep(10);
467         }
468         if (readw(baseAddr + Magic_no) != Magic_code)
469                 return -EIO;
470
471         if (c320) {
472                 j = readw(baseAddr + Module_cnt);
473                 if (j <= 0)
474                         return -EIO;
475                 brd->numPorts = j * 8;
476                 writew(j, baseAddr + Module_no);
477                 writew(0, baseAddr + Magic_no);
478                 for (i = 0; i < 600; i++) {
479                         if (readw(baseAddr + Magic_no) == Magic_code)
480                                 break;
481                         msleep(10);
482                 }
483                 if (readw(baseAddr + Magic_no) != Magic_code)
484                         return -EIO;
485         }
486         moxaCard = 1;
487         brd->intNdx = baseAddr + IRQindex;
488         brd->intPend = baseAddr + IRQpending;
489         brd->intTable = baseAddr + IRQtable;
490
491         return 0;
492 }
493
494 static int moxa_load_code(struct moxa_board_conf *brd, const void *ptr,
495                 size_t len)
496 {
497         void __iomem *ofsAddr, *baseAddr = brd->basemem;
498         struct moxa_port *port;
499         int retval, i;
500
501         if (len % 2) {
502                 printk(KERN_ERR "moxa: bios length is not even\n");
503                 return -EINVAL;
504         }
505
506         retval = moxa_real_load_code(brd, ptr, len); /* may change numPorts */
507         if (retval)
508                 return retval;
509
510         switch (brd->boardType) {
511         case MOXA_BOARD_C218_ISA:
512         case MOXA_BOARD_C218_PCI:
513         case MOXA_BOARD_CP204J:
514                 port = brd->ports;
515                 for (i = 0; i < brd->numPorts; i++, port++) {
516                         port->board = brd;
517                         port->chkPort = 1;
518                         port->curBaud = 9600L;
519                         port->DCDState = 0;
520                         port->tableAddr = baseAddr + Extern_table +
521                                         Extern_size * i;
522                         ofsAddr = port->tableAddr;
523                         writew(C218rx_mask, ofsAddr + RX_mask);
524                         writew(C218tx_mask, ofsAddr + TX_mask);
525                         writew(C218rx_spage + i * C218buf_pageno, ofsAddr + Page_rxb);
526                         writew(readw(ofsAddr + Page_rxb) + C218rx_pageno, ofsAddr + EndPage_rxb);
527
528                         writew(C218tx_spage + i * C218buf_pageno, ofsAddr + Page_txb);
529                         writew(readw(ofsAddr + Page_txb) + C218tx_pageno, ofsAddr + EndPage_txb);
530
531                 }
532                 break;
533         default:
534                 port = brd->ports;
535                 for (i = 0; i < brd->numPorts; i++, port++) {
536                         port->board = brd;
537                         port->chkPort = 1;
538                         port->curBaud = 9600L;
539                         port->DCDState = 0;
540                         port->tableAddr = baseAddr + Extern_table +
541                                         Extern_size * i;
542                         ofsAddr = port->tableAddr;
543                         switch (brd->numPorts) {
544                         case 8:
545                                 writew(C320p8rx_mask, ofsAddr + RX_mask);
546                                 writew(C320p8tx_mask, ofsAddr + TX_mask);
547                                 writew(C320p8rx_spage + i * C320p8buf_pgno, ofsAddr + Page_rxb);
548                                 writew(readw(ofsAddr + Page_rxb) + C320p8rx_pgno, ofsAddr + EndPage_rxb);
549                                 writew(C320p8tx_spage + i * C320p8buf_pgno, ofsAddr + Page_txb);
550                                 writew(readw(ofsAddr + Page_txb) + C320p8tx_pgno, ofsAddr + EndPage_txb);
551
552                                 break;
553                         case 16:
554                                 writew(C320p16rx_mask, ofsAddr + RX_mask);
555                                 writew(C320p16tx_mask, ofsAddr + TX_mask);
556                                 writew(C320p16rx_spage + i * C320p16buf_pgno, ofsAddr + Page_rxb);
557                                 writew(readw(ofsAddr + Page_rxb) + C320p16rx_pgno, ofsAddr + EndPage_rxb);
558                                 writew(C320p16tx_spage + i * C320p16buf_pgno, ofsAddr + Page_txb);
559                                 writew(readw(ofsAddr + Page_txb) + C320p16tx_pgno, ofsAddr + EndPage_txb);
560                                 break;
561
562                         case 24:
563                                 writew(C320p24rx_mask, ofsAddr + RX_mask);
564                                 writew(C320p24tx_mask, ofsAddr + TX_mask);
565                                 writew(C320p24rx_spage + i * C320p24buf_pgno, ofsAddr + Page_rxb);
566                                 writew(readw(ofsAddr + Page_rxb) + C320p24rx_pgno, ofsAddr + EndPage_rxb);
567                                 writew(C320p24tx_spage + i * C320p24buf_pgno, ofsAddr + Page_txb);
568                                 writew(readw(ofsAddr + Page_txb), ofsAddr + EndPage_txb);
569                                 break;
570                         case 32:
571                                 writew(C320p32rx_mask, ofsAddr + RX_mask);
572                                 writew(C320p32tx_mask, ofsAddr + TX_mask);
573                                 writew(C320p32tx_ofs, ofsAddr + Ofs_txb);
574                                 writew(C320p32rx_spage + i * C320p32buf_pgno, ofsAddr + Page_rxb);
575                                 writew(readb(ofsAddr + Page_rxb), ofsAddr + EndPage_rxb);
576                                 writew(C320p32tx_spage + i * C320p32buf_pgno, ofsAddr + Page_txb);
577                                 writew(readw(ofsAddr + Page_txb), ofsAddr + EndPage_txb);
578                                 break;
579                         }
580                 }
581                 break;
582         }
583         brd->loadstat = 1;
584         return 0;
585 }
586
587 static int moxa_load_fw(struct moxa_board_conf *brd, const struct firmware *fw)
588 {
589         void *ptr = fw->data;
590         char rsn[64];
591         u16 lens[5];
592         size_t len;
593         unsigned int a, lenp, lencnt;
594         int ret = -EINVAL;
595         struct {
596                 __le32 magic;   /* 0x34303430 */
597                 u8 reserved1[2];
598                 u8 type;        /* UNIX = 3 */
599                 u8 model;       /* C218T=1, C320T=2, CP204=3 */
600                 u8 reserved2[8];
601                 __le16 len[5];
602         } *hdr = ptr;
603
604         BUILD_BUG_ON(ARRAY_SIZE(hdr->len) != ARRAY_SIZE(lens));
605
606         if (fw->size < MOXA_FW_HDRLEN) {
607                 strcpy(rsn, "too short (even header won't fit)");
608                 goto err;
609         }
610         if (hdr->magic != cpu_to_le32(0x30343034)) {
611                 sprintf(rsn, "bad magic: %.8x", le32_to_cpu(hdr->magic));
612                 goto err;
613         }
614         if (hdr->type != 3) {
615                 sprintf(rsn, "not for linux, type is %u", hdr->type);
616                 goto err;
617         }
618         if (moxa_check_fw_model(brd, hdr->model)) {
619                 sprintf(rsn, "not for this card, model is %u", hdr->model);
620                 goto err;
621         }
622
623         len = MOXA_FW_HDRLEN;
624         lencnt = hdr->model == 2 ? 5 : 3;
625         for (a = 0; a < ARRAY_SIZE(lens); a++) {
626                 lens[a] = le16_to_cpu(hdr->len[a]);
627                 if (lens[a] && len + lens[a] <= fw->size &&
628                                 moxa_check_fw(&fw->data[len]))
629                         printk(KERN_WARNING "moxa firmware: unexpected input "
630                                 "at offset %u, but going on\n", (u32)len);
631                 if (!lens[a] && a < lencnt) {
632                         sprintf(rsn, "too few entries in fw file");
633                         goto err;
634                 }
635                 len += lens[a];
636         }
637
638         if (len != fw->size) {
639                 sprintf(rsn, "bad length: %u (should be %u)", (u32)fw->size,
640                                 (u32)len);
641                 goto err;
642         }
643
644         ptr += MOXA_FW_HDRLEN;
645         lenp = 0; /* bios */
646
647         strcpy(rsn, "read above");
648
649         ret = moxa_load_bios(brd, ptr, lens[lenp]);
650         if (ret)
651                 goto err;
652
653         /* we skip the tty section (lens[1]), since we don't need it */
654         ptr += lens[lenp] + lens[lenp + 1];
655         lenp += 2; /* comm */
656
657         if (hdr->model == 2) {
658                 ret = moxa_load_320b(brd, ptr, lens[lenp]);
659                 if (ret)
660                         goto err;
661                 /* skip another tty */
662                 ptr += lens[lenp] + lens[lenp + 1];
663                 lenp += 2;
664         }
665
666         ret = moxa_load_code(brd, ptr, lens[lenp]);
667         if (ret)
668                 goto err;
669
670         return 0;
671 err:
672         printk(KERN_ERR "firmware failed to load, reason: %s\n", rsn);
673         return ret;
674 }
675
676 static int moxa_init_board(struct moxa_board_conf *brd, struct device *dev)
677 {
678         const struct firmware *fw;
679         const char *file;
680         int ret;
681
682         switch (brd->boardType) {
683         case MOXA_BOARD_C218_ISA:
684         case MOXA_BOARD_C218_PCI:
685                 file = "c218tunx.cod";
686                 break;
687         case MOXA_BOARD_CP204J:
688                 file = "cp204unx.cod";
689                 break;
690         default:
691                 file = "c320tunx.cod";
692                 break;
693         }
694
695         ret = request_firmware(&fw, file, dev);
696         if (ret) {
697                 printk(KERN_ERR "request_firmware failed\n");
698                 goto end;
699         }
700
701         ret = moxa_load_fw(brd, fw);
702
703         release_firmware(fw);
704 end:
705         return ret;
706 }
707
708 #ifdef CONFIG_PCI
709 static int __devinit moxa_pci_probe(struct pci_dev *pdev,
710                 const struct pci_device_id *ent)
711 {
712         struct moxa_board_conf *board;
713         unsigned int i;
714         int board_type = ent->driver_data;
715         int retval;
716
717         retval = pci_enable_device(pdev);
718         if (retval) {
719                 dev_err(&pdev->dev, "can't enable pci device\n");
720                 goto err;
721         }
722
723         for (i = 0; i < MAX_BOARDS; i++)
724                 if (moxa_boards[i].basemem == NULL)
725                         break;
726
727         retval = -ENODEV;
728         if (i >= MAX_BOARDS) {
729                 dev_warn(&pdev->dev, "more than %u MOXA Intellio family boards "
730                                 "found. Board is ignored.\n", MAX_BOARDS);
731                 goto err;
732         }
733
734         board = &moxa_boards[i];
735         board->ports = &moxa_ports[i * MAX_PORTS_PER_BOARD];
736
737         retval = pci_request_region(pdev, 2, "moxa-base");
738         if (retval) {
739                 dev_err(&pdev->dev, "can't request pci region 2\n");
740                 goto err;
741         }
742
743         board->basemem = ioremap(pci_resource_start(pdev, 2), 0x4000);
744         if (board->basemem == NULL) {
745                 dev_err(&pdev->dev, "can't remap io space 2\n");
746                 goto err_reg;
747         }
748
749         board->boardType = board_type;
750         switch (board_type) {
751         case MOXA_BOARD_C218_ISA:
752         case MOXA_BOARD_C218_PCI:
753                 board->numPorts = 8;
754                 break;
755
756         case MOXA_BOARD_CP204J:
757                 board->numPorts = 4;
758                 break;
759         default:
760                 board->numPorts = 0;
761                 break;
762         }
763         board->busType = MOXA_BUS_TYPE_PCI;
764
765         retval = moxa_init_board(board, &pdev->dev);
766         if (retval)
767                 goto err_base;
768
769         pci_set_drvdata(pdev, board);
770
771         return (0);
772 err_base:
773         iounmap(board->basemem);
774         board->basemem = NULL;
775 err_reg:
776         pci_release_region(pdev, 2);
777 err:
778         return retval;
779 }
780
781 static void __devexit moxa_pci_remove(struct pci_dev *pdev)
782 {
783         struct moxa_board_conf *brd = pci_get_drvdata(pdev);
784
785         iounmap(brd->basemem);
786         brd->basemem = NULL;
787         pci_release_region(pdev, 2);
788 }
789
790 static struct pci_driver moxa_pci_driver = {
791         .name = "moxa",
792         .id_table = moxa_pcibrds,
793         .probe = moxa_pci_probe,
794         .remove = __devexit_p(moxa_pci_remove)
795 };
796 #endif /* CONFIG_PCI */
797
798 static int __init moxa_init(void)
799 {
800         struct moxa_port *ch;
801         unsigned int i, isabrds = 0;
802         int retval = 0;
803
804         printk(KERN_INFO "MOXA Intellio family driver version %s\n",
805                         MOXA_VERSION);
806         moxaDriver = alloc_tty_driver(MAX_PORTS + 1);
807         if (!moxaDriver)
808                 return -ENOMEM;
809
810         moxaDriver->owner = THIS_MODULE;
811         moxaDriver->name = "ttyMX";
812         moxaDriver->major = ttymajor;
813         moxaDriver->minor_start = 0;
814         moxaDriver->type = TTY_DRIVER_TYPE_SERIAL;
815         moxaDriver->subtype = SERIAL_TYPE_NORMAL;
816         moxaDriver->init_termios = tty_std_termios;
817         moxaDriver->init_termios.c_cflag = B9600 | CS8 | CREAD | CLOCAL | HUPCL;
818         moxaDriver->init_termios.c_ispeed = 9600;
819         moxaDriver->init_termios.c_ospeed = 9600;
820         moxaDriver->flags = TTY_DRIVER_REAL_RAW;
821         tty_set_operations(moxaDriver, &moxa_ops);
822
823         for (i = 0, ch = moxa_ports; i < MAX_PORTS; i++, ch++) {
824                 ch->type = PORT_16550A;
825                 ch->close_delay = 5 * HZ / 10;
826                 ch->closing_wait = 30 * HZ;
827                 ch->cflag = B9600 | CS8 | CREAD | CLOCAL | HUPCL;
828                 init_waitqueue_head(&ch->open_wait);
829                 init_completion(&ch->close_wait);
830
831                 setup_timer(&ch->emptyTimer, moxa_check_xmit_empty,
832                                 (unsigned long)ch);
833         }
834
835         pr_debug("Moxa tty devices major number = %d\n", ttymajor);
836
837         if (tty_register_driver(moxaDriver)) {
838                 printk(KERN_ERR "Couldn't install MOXA Smartio family driver !\n");
839                 put_tty_driver(moxaDriver);
840                 return -1;
841         }
842
843         mod_timer(&moxaTimer, jiffies + HZ / 50);
844
845         /* Find the boards defined from module args. */
846 #ifdef MODULE
847         {
848         struct moxa_board_conf *brd = moxa_boards;
849         for (i = 0; i < MAX_BOARDS; i++) {
850                 if (!baseaddr[i])
851                         break;
852                 if (type[i] == MOXA_BOARD_C218_ISA ||
853                                 type[i] == MOXA_BOARD_C320_ISA) {
854                         pr_debug("Moxa board %2d: %s board(baseAddr=%lx)\n",
855                                         isabrds + 1, moxa_brdname[type[i] - 1],
856                                         baseaddr[i]);
857                         brd->boardType = type[i];
858                         brd->ports = &moxa_ports[isabrds * MAX_PORTS_PER_BOARD];
859                         brd->numPorts = type[i] == MOXA_BOARD_C218_ISA ? 8 :
860                                         numports[i];
861                         brd->busType = MOXA_BUS_TYPE_ISA;
862                         brd->basemem = ioremap(baseaddr[i], 0x4000);
863                         if (!brd->basemem) {
864                                 printk(KERN_ERR "moxa: can't remap %lx\n",
865                                                 baseaddr[i]);
866                                 continue;
867                         }
868                         if (moxa_init_board(brd, NULL)) {
869                                 iounmap(brd->basemem);
870                                 brd->basemem = NULL;
871                                 continue;
872                         }
873
874                         brd++;
875                         isabrds++;
876                 }
877         }
878         }
879 #endif
880
881 #ifdef CONFIG_PCI
882         retval = pci_register_driver(&moxa_pci_driver);
883         if (retval) {
884                 printk(KERN_ERR "Can't register moxa pci driver!\n");
885                 if (isabrds)
886                         retval = 0;
887         }
888 #endif
889
890         return retval;
891 }
892
893 static void __exit moxa_exit(void)
894 {
895         int i;
896
897         del_timer_sync(&moxaTimer);
898
899         for (i = 0; i < MAX_PORTS; i++)
900                 del_timer_sync(&moxa_ports[i].emptyTimer);
901
902         if (tty_unregister_driver(moxaDriver))
903                 printk(KERN_ERR "Couldn't unregister MOXA Intellio family "
904                                 "serial driver\n");
905         put_tty_driver(moxaDriver);
906
907 #ifdef CONFIG_PCI
908         pci_unregister_driver(&moxa_pci_driver);
909 #endif
910
911         for (i = 0; i < MAX_BOARDS; i++)
912                 if (moxa_boards[i].basemem)
913                         iounmap(moxa_boards[i].basemem);
914 }
915
916 module_init(moxa_init);
917 module_exit(moxa_exit);
918
919 static int moxa_open(struct tty_struct *tty, struct file *filp)
920 {
921         struct moxa_port *ch;
922         int port;
923         int retval;
924
925         port = tty->index;
926         if (port == MAX_PORTS) {
927                 return (0);
928         }
929         if (!MoxaPortIsValid(port)) {
930                 tty->driver_data = NULL;
931                 return (-ENODEV);
932         }
933
934         ch = &moxa_ports[port];
935         ch->count++;
936         tty->driver_data = ch;
937         ch->tty = tty;
938         if (!(ch->asyncflags & ASYNC_INITIALIZED)) {
939                 ch->statusflags = 0;
940                 moxa_set_tty_param(tty, tty->termios);
941                 MoxaPortLineCtrl(ch, 1, 1);
942                 MoxaPortEnable(ch);
943                 ch->asyncflags |= ASYNC_INITIALIZED;
944         }
945         retval = moxa_block_till_ready(tty, filp, ch);
946
947         moxa_unthrottle(tty);
948
949         if (ch->type == PORT_16550A) {
950                 MoxaSetFifo(ch, 1);
951         } else {
952                 MoxaSetFifo(ch, 0);
953         }
954
955         return (retval);
956 }
957
958 static void moxa_close(struct tty_struct *tty, struct file *filp)
959 {
960         struct moxa_port *ch;
961         int port;
962
963         port = tty->index;
964         if (port == MAX_PORTS) {
965                 return;
966         }
967         if (!MoxaPortIsValid(port)) {
968                 pr_debug("Invalid portno in moxa_close\n");
969                 tty->driver_data = NULL;
970                 return;
971         }
972         if (tty->driver_data == NULL) {
973                 return;
974         }
975         if (tty_hung_up_p(filp)) {
976                 return;
977         }
978         ch = (struct moxa_port *) tty->driver_data;
979
980         if ((tty->count == 1) && (ch->count != 1)) {
981                 printk(KERN_WARNING "moxa_close: bad serial port count; "
982                         "tty->count is 1, ch->count is %d\n", ch->count);
983                 ch->count = 1;
984         }
985         if (--ch->count < 0) {
986                 printk(KERN_WARNING "moxa_close: bad serial port count, "
987                         "device=%s\n", tty->name);
988                 ch->count = 0;
989         }
990         if (ch->count) {
991                 return;
992         }
993         ch->asyncflags |= ASYNC_CLOSING;
994
995         ch->cflag = tty->termios->c_cflag;
996         if (ch->asyncflags & ASYNC_INITIALIZED) {
997                 moxa_setup_empty_event(tty);
998                 tty_wait_until_sent(tty, 30 * HZ);      /* 30 seconds timeout */
999                 del_timer_sync(&ch->emptyTimer);
1000         }
1001         moxa_shut_down(ch);
1002         MoxaPortFlushData(ch, 2);
1003
1004         if (tty->driver->flush_buffer)
1005                 tty->driver->flush_buffer(tty);
1006         tty_ldisc_flush(tty);
1007                         
1008         tty->closing = 0;
1009         ch->event = 0;
1010         ch->tty = NULL;
1011         if (ch->blocked_open) {
1012                 if (ch->close_delay) {
1013                         msleep_interruptible(jiffies_to_msecs(ch->close_delay));
1014                 }
1015                 wake_up_interruptible(&ch->open_wait);
1016         }
1017         ch->asyncflags &= ~(ASYNC_NORMAL_ACTIVE | ASYNC_CLOSING);
1018         complete_all(&ch->close_wait);
1019 }
1020
1021 static int moxa_write(struct tty_struct *tty,
1022                       const unsigned char *buf, int count)
1023 {
1024         struct moxa_port *ch = tty->driver_data;
1025         unsigned long flags;
1026         int len;
1027
1028         if (ch == NULL)
1029                 return 0;
1030
1031         spin_lock_irqsave(&moxa_lock, flags);
1032         len = MoxaPortWriteData(ch, (unsigned char *) buf, count);
1033         spin_unlock_irqrestore(&moxa_lock, flags);
1034
1035         /*********************************************
1036         if ( !(ch->statusflags & LOWWAIT) &&
1037              ((len != count) || (MoxaPortTxFree(port) <= 100)) )
1038         ************************************************/
1039         ch->statusflags |= LOWWAIT;
1040         return (len);
1041 }
1042
1043 static int moxa_write_room(struct tty_struct *tty)
1044 {
1045         struct moxa_port *ch;
1046
1047         if (tty->stopped)
1048                 return (0);
1049         ch = tty->driver_data;
1050         if (ch == NULL)
1051                 return (0);
1052         return MoxaPortTxFree(ch);
1053 }
1054
1055 static void moxa_flush_buffer(struct tty_struct *tty)
1056 {
1057         struct moxa_port *ch = tty->driver_data;
1058
1059         if (ch == NULL)
1060                 return;
1061         MoxaPortFlushData(ch, 1);
1062         tty_wakeup(tty);
1063 }
1064
1065 static int moxa_chars_in_buffer(struct tty_struct *tty)
1066 {
1067         struct moxa_port *ch = tty->driver_data;
1068         int chars;
1069
1070         /*
1071          * Sigh...I have to check if driver_data is NULL here, because
1072          * if an open() fails, the TTY subsystem eventually calls
1073          * tty_wait_until_sent(), which calls the driver's chars_in_buffer()
1074          * routine.  And since the open() failed, we return 0 here.  TDJ
1075          */
1076         if (ch == NULL)
1077                 return (0);
1078         chars = MoxaPortTxQueue(ch);
1079         if (chars) {
1080                 /*
1081                  * Make it possible to wakeup anything waiting for output
1082                  * in tty_ioctl.c, etc.
1083                  */
1084                 if (!(ch->statusflags & EMPTYWAIT))
1085                         moxa_setup_empty_event(tty);
1086         }
1087         return (chars);
1088 }
1089
1090 static void moxa_flush_chars(struct tty_struct *tty)
1091 {
1092         /*
1093          * Don't think I need this, because this is called to empty the TX
1094          * buffer for the 16450, 16550, etc.
1095          */
1096 }
1097
1098 static void moxa_put_char(struct tty_struct *tty, unsigned char c)
1099 {
1100         struct moxa_port *ch = tty->driver_data;
1101         unsigned long flags;
1102
1103         if (ch == NULL)
1104                 return;
1105         spin_lock_irqsave(&moxa_lock, flags);
1106         MoxaPortWriteData(ch, &c, 1);
1107         spin_unlock_irqrestore(&moxa_lock, flags);
1108         /************************************************
1109         if ( !(ch->statusflags & LOWWAIT) && (MoxaPortTxFree(port) <= 100) )
1110         *************************************************/
1111         ch->statusflags |= LOWWAIT;
1112 }
1113
1114 static int moxa_tiocmget(struct tty_struct *tty, struct file *file)
1115 {
1116         struct moxa_port *ch = tty->driver_data;
1117         int flag = 0, dtr, rts;
1118
1119         if ((tty->index != MAX_PORTS) && (!ch))
1120                 return (-EINVAL);
1121
1122         MoxaPortGetLineOut(ch, &dtr, &rts);
1123         if (dtr)
1124                 flag |= TIOCM_DTR;
1125         if (rts)
1126                 flag |= TIOCM_RTS;
1127         dtr = MoxaPortLineStatus(ch);
1128         if (dtr & 1)
1129                 flag |= TIOCM_CTS;
1130         if (dtr & 2)
1131                 flag |= TIOCM_DSR;
1132         if (dtr & 4)
1133                 flag |= TIOCM_CD;
1134         return flag;
1135 }
1136
1137 static int moxa_tiocmset(struct tty_struct *tty, struct file *file,
1138                          unsigned int set, unsigned int clear)
1139 {
1140         struct moxa_port *ch = tty->driver_data;
1141         int port;
1142         int dtr, rts;
1143
1144         port = tty->index;
1145         if ((port != MAX_PORTS) && (!ch))
1146                 return (-EINVAL);
1147
1148         MoxaPortGetLineOut(ch, &dtr, &rts);
1149         if (set & TIOCM_RTS)
1150                 rts = 1;
1151         if (set & TIOCM_DTR)
1152                 dtr = 1;
1153         if (clear & TIOCM_RTS)
1154                 rts = 0;
1155         if (clear & TIOCM_DTR)
1156                 dtr = 0;
1157         MoxaPortLineCtrl(ch, dtr, rts);
1158         return 0;
1159 }
1160
1161 static int moxa_ioctl(struct tty_struct *tty, struct file *file,
1162                       unsigned int cmd, unsigned long arg)
1163 {
1164         struct moxa_port *ch = tty->driver_data;
1165         register int port;
1166         void __user *argp = (void __user *)arg;
1167         int retval;
1168
1169         port = tty->index;
1170         if ((port != MAX_PORTS) && (!ch))
1171                 return (-EINVAL);
1172
1173         switch (cmd) {
1174         case TCSBRK:            /* SVID version: non-zero arg --> no break */
1175                 retval = tty_check_change(tty);
1176                 if (retval)
1177                         return (retval);
1178                 moxa_setup_empty_event(tty);
1179                 tty_wait_until_sent(tty, 0);
1180                 if (!arg)
1181                         MoxaPortSendBreak(ch, 0);
1182                 return (0);
1183         case TCSBRKP:           /* support for POSIX tcsendbreak() */
1184                 retval = tty_check_change(tty);
1185                 if (retval)
1186                         return (retval);
1187                 moxa_setup_empty_event(tty);
1188                 tty_wait_until_sent(tty, 0);
1189                 MoxaPortSendBreak(ch, arg);
1190                 return (0);
1191         case TIOCGSOFTCAR:
1192                 return put_user(C_CLOCAL(tty) ? 1 : 0, (int __user *)argp);
1193         case TIOCSSOFTCAR:
1194                 if (get_user(retval, (int __user *)argp))
1195                         return -EFAULT;
1196                 arg = retval;
1197                 tty->termios->c_cflag = ((tty->termios->c_cflag & ~CLOCAL) |
1198                                          (arg ? CLOCAL : 0));
1199                 if (C_CLOCAL(tty))
1200                         ch->asyncflags &= ~ASYNC_CHECK_CD;
1201                 else
1202                         ch->asyncflags |= ASYNC_CHECK_CD;
1203                 return (0);
1204         case TIOCGSERIAL:
1205                 return moxa_get_serial_info(ch, argp);
1206
1207         case TIOCSSERIAL:
1208                 return moxa_set_serial_info(ch, argp);
1209         default:
1210                 retval = MoxaDriverIoctl(tty, cmd, arg);
1211         }
1212         return (retval);
1213 }
1214
1215 static void moxa_throttle(struct tty_struct *tty)
1216 {
1217         struct moxa_port *ch = (struct moxa_port *) tty->driver_data;
1218
1219         ch->statusflags |= THROTTLE;
1220 }
1221
1222 static void moxa_unthrottle(struct tty_struct *tty)
1223 {
1224         struct moxa_port *ch = (struct moxa_port *) tty->driver_data;
1225
1226         ch->statusflags &= ~THROTTLE;
1227 }
1228
1229 static void moxa_set_termios(struct tty_struct *tty,
1230                              struct ktermios *old_termios)
1231 {
1232         struct moxa_port *ch = (struct moxa_port *) tty->driver_data;
1233
1234         if (ch == NULL)
1235                 return;
1236         moxa_set_tty_param(tty, old_termios);
1237         if (!(old_termios->c_cflag & CLOCAL) &&
1238             (tty->termios->c_cflag & CLOCAL))
1239                 wake_up_interruptible(&ch->open_wait);
1240 }
1241
1242 static void moxa_stop(struct tty_struct *tty)
1243 {
1244         struct moxa_port *ch = (struct moxa_port *) tty->driver_data;
1245
1246         if (ch == NULL)
1247                 return;
1248         MoxaPortTxDisable(ch);
1249         ch->statusflags |= TXSTOPPED;
1250 }
1251
1252
1253 static void moxa_start(struct tty_struct *tty)
1254 {
1255         struct moxa_port *ch = (struct moxa_port *) tty->driver_data;
1256
1257         if (ch == NULL)
1258                 return;
1259
1260         if (!(ch->statusflags & TXSTOPPED))
1261                 return;
1262
1263         MoxaPortTxEnable(ch);
1264         ch->statusflags &= ~TXSTOPPED;
1265 }
1266
1267 static void moxa_hangup(struct tty_struct *tty)
1268 {
1269         struct moxa_port *ch = (struct moxa_port *) tty->driver_data;
1270
1271         moxa_flush_buffer(tty);
1272         moxa_shut_down(ch);
1273         ch->event = 0;
1274         ch->count = 0;
1275         ch->asyncflags &= ~ASYNC_NORMAL_ACTIVE;
1276         ch->tty = NULL;
1277         wake_up_interruptible(&ch->open_wait);
1278 }
1279
1280 static void moxa_poll(unsigned long ignored)
1281 {
1282         register int card;
1283         struct moxa_port *ch;
1284         struct tty_struct *tp;
1285         int i, ports;
1286
1287         del_timer(&moxaTimer);
1288
1289         if (MoxaDriverPoll() < 0) {
1290                 mod_timer(&moxaTimer, jiffies + HZ / 50);
1291                 return;
1292         }
1293         for (card = 0; card < MAX_BOARDS; card++) {
1294                 if ((ports = MoxaPortsOfCard(card)) <= 0)
1295                         continue;
1296                 ch = &moxa_ports[card * MAX_PORTS_PER_BOARD];
1297                 for (i = 0; i < ports; i++, ch++) {
1298                         if ((ch->asyncflags & ASYNC_INITIALIZED) == 0)
1299                                 continue;
1300                         if (!(ch->statusflags & THROTTLE) &&
1301                             (MoxaPortRxQueue(ch) > 0))
1302                                 moxa_receive_data(ch);
1303                         if ((tp = ch->tty) == 0)
1304                                 continue;
1305                         if (ch->statusflags & LOWWAIT) {
1306                                 if (MoxaPortTxQueue(ch) <= WAKEUP_CHARS) {
1307                                         if (!tp->stopped) {
1308                                                 ch->statusflags &= ~LOWWAIT;
1309                                                 tty_wakeup(tp);
1310                                         }
1311                                 }
1312                         }
1313                         if (!I_IGNBRK(tp) && (MoxaPortResetBrkCnt(ch) > 0)) {
1314                                 tty_insert_flip_char(tp, 0, TTY_BREAK);
1315                                 tty_schedule_flip(tp);
1316                         }
1317                         if (MoxaPortDCDChange(ch)) {
1318                                 if (ch->asyncflags & ASYNC_CHECK_CD) {
1319                                         if (MoxaPortDCDON(ch))
1320                                                 wake_up_interruptible(&ch->open_wait);
1321                                         else {
1322                                                 tty_hangup(tp);
1323                                                 wake_up_interruptible(&ch->open_wait);
1324                                                 ch->asyncflags &= ~ASYNC_NORMAL_ACTIVE;
1325                                         }
1326                                 }
1327                         }
1328                 }
1329         }
1330
1331         mod_timer(&moxaTimer, jiffies + HZ / 50);
1332 }
1333
1334 /******************************************************************************/
1335
1336 static void moxa_set_tty_param(struct tty_struct *tty, struct ktermios *old_termios)
1337 {
1338         register struct ktermios *ts;
1339         struct moxa_port *ch;
1340         int rts, cts, txflow, rxflow, xany, baud;
1341
1342         ch = (struct moxa_port *) tty->driver_data;
1343         ts = tty->termios;
1344         if (ts->c_cflag & CLOCAL)
1345                 ch->asyncflags &= ~ASYNC_CHECK_CD;
1346         else
1347                 ch->asyncflags |= ASYNC_CHECK_CD;
1348         rts = cts = txflow = rxflow = xany = 0;
1349         if (ts->c_cflag & CRTSCTS)
1350                 rts = cts = 1;
1351         if (ts->c_iflag & IXON)
1352                 txflow = 1;
1353         if (ts->c_iflag & IXOFF)
1354                 rxflow = 1;
1355         if (ts->c_iflag & IXANY)
1356                 xany = 1;
1357
1358         /* Clear the features we don't support */
1359         ts->c_cflag &= ~CMSPAR;
1360         MoxaPortFlowCtrl(ch, rts, cts, txflow, rxflow, xany);
1361         baud = MoxaPortSetTermio(ch, ts, tty_get_baud_rate(tty));
1362         if (baud == -1)
1363                 baud = tty_termios_baud_rate(old_termios);
1364         /* Not put the baud rate into the termios data */
1365         tty_encode_baud_rate(tty, baud, baud);
1366 }
1367
1368 static int moxa_block_till_ready(struct tty_struct *tty, struct file *filp,
1369                             struct moxa_port *ch)
1370 {
1371         DECLARE_WAITQUEUE(wait,current);
1372         unsigned long flags;
1373         int retval;
1374         int do_clocal = C_CLOCAL(tty);
1375
1376         /*
1377          * If the device is in the middle of being closed, then block
1378          * until it's done, and then try again.
1379          */
1380         if (tty_hung_up_p(filp) || (ch->asyncflags & ASYNC_CLOSING)) {
1381                 if (ch->asyncflags & ASYNC_CLOSING)
1382                         wait_for_completion_interruptible(&ch->close_wait);
1383 #ifdef SERIAL_DO_RESTART
1384                 if (ch->asyncflags & ASYNC_HUP_NOTIFY)
1385                         return (-EAGAIN);
1386                 else
1387                         return (-ERESTARTSYS);
1388 #else
1389                 return (-EAGAIN);
1390 #endif
1391         }
1392         /*
1393          * If non-blocking mode is set, then make the check up front
1394          * and then exit.
1395          */
1396         if (filp->f_flags & O_NONBLOCK) {
1397                 ch->asyncflags |= ASYNC_NORMAL_ACTIVE;
1398                 return (0);
1399         }
1400         /*
1401          * Block waiting for the carrier detect and the line to become free
1402          */
1403         retval = 0;
1404         add_wait_queue(&ch->open_wait, &wait);
1405         pr_debug("block_til_ready before block: ttys%d, count = %d\n",
1406                 tty->index, ch->count);
1407         spin_lock_irqsave(&moxa_lock, flags);
1408         if (!tty_hung_up_p(filp))
1409                 ch->count--;
1410         ch->blocked_open++;
1411         spin_unlock_irqrestore(&moxa_lock, flags);
1412
1413         while (1) {
1414                 set_current_state(TASK_INTERRUPTIBLE);
1415                 if (tty_hung_up_p(filp) ||
1416                     !(ch->asyncflags & ASYNC_INITIALIZED)) {
1417 #ifdef SERIAL_DO_RESTART
1418                         if (ch->asyncflags & ASYNC_HUP_NOTIFY)
1419                                 retval = -EAGAIN;
1420                         else
1421                                 retval = -ERESTARTSYS;
1422 #else
1423                         retval = -EAGAIN;
1424 #endif
1425                         break;
1426                 }
1427                 if (!(ch->asyncflags & ASYNC_CLOSING) && (do_clocal ||
1428                                                 MoxaPortDCDON(ch)))
1429                         break;
1430
1431                 if (signal_pending(current)) {
1432                         retval = -ERESTARTSYS;
1433                         break;
1434                 }
1435                 schedule();
1436         }
1437         set_current_state(TASK_RUNNING);
1438         remove_wait_queue(&ch->open_wait, &wait);
1439
1440         spin_lock_irqsave(&moxa_lock, flags);
1441         if (!tty_hung_up_p(filp))
1442                 ch->count++;
1443         ch->blocked_open--;
1444         spin_unlock_irqrestore(&moxa_lock, flags);
1445         pr_debug("block_til_ready after blocking: ttys%d, count = %d\n",
1446                 tty->index, ch->count);
1447         if (retval)
1448                 return (retval);
1449         /* FIXME: review to see if we need to use set_bit on these */
1450         ch->asyncflags |= ASYNC_NORMAL_ACTIVE;
1451         return 0;
1452 }
1453
1454 static void moxa_setup_empty_event(struct tty_struct *tty)
1455 {
1456         struct moxa_port *ch = tty->driver_data;
1457         unsigned long flags;
1458
1459         spin_lock_irqsave(&moxa_lock, flags);
1460         ch->statusflags |= EMPTYWAIT;
1461         mod_timer(&ch->emptyTimer, jiffies + HZ);
1462         spin_unlock_irqrestore(&moxa_lock, flags);
1463 }
1464
1465 static void moxa_check_xmit_empty(unsigned long data)
1466 {
1467         struct moxa_port *ch;
1468
1469         ch = (struct moxa_port *) data;
1470         if (ch->tty && (ch->statusflags & EMPTYWAIT)) {
1471                 if (MoxaPortTxQueue(ch) == 0) {
1472                         ch->statusflags &= ~EMPTYWAIT;
1473                         tty_wakeup(ch->tty);
1474                         return;
1475                 }
1476                 mod_timer(&ch->emptyTimer, round_jiffies(jiffies + HZ));
1477         } else
1478                 ch->statusflags &= ~EMPTYWAIT;
1479 }
1480
1481 static void moxa_shut_down(struct moxa_port *ch)
1482 {
1483         struct tty_struct *tp;
1484
1485         if (!(ch->asyncflags & ASYNC_INITIALIZED))
1486                 return;
1487
1488         tp = ch->tty;
1489
1490         MoxaPortDisable(ch);
1491
1492         /*
1493          * If we're a modem control device and HUPCL is on, drop RTS & DTR.
1494          */
1495         if (tp->termios->c_cflag & HUPCL)
1496                 MoxaPortLineCtrl(ch, 0, 0);
1497
1498         ch->asyncflags &= ~ASYNC_INITIALIZED;
1499 }
1500
1501 static void moxa_receive_data(struct moxa_port *ch)
1502 {
1503         struct tty_struct *tp;
1504         struct ktermios *ts;
1505         unsigned long flags;
1506
1507         ts = NULL;
1508         tp = ch->tty;
1509         if (tp)
1510                 ts = tp->termios;
1511         /**************************************************
1512         if ( !tp || !ts || !(ts->c_cflag & CREAD) ) {
1513         *****************************************************/
1514         if (!tp || !ts) {
1515                 MoxaPortFlushData(ch, 0);
1516                 return;
1517         }
1518         spin_lock_irqsave(&moxa_lock, flags);
1519         MoxaPortReadData(ch, tp);
1520         spin_unlock_irqrestore(&moxa_lock, flags);
1521         tty_schedule_flip(tp);
1522 }
1523
1524 /*
1525  *    Query
1526  */
1527
1528 struct mon_str {
1529         int tick;
1530         int rxcnt[MAX_PORTS];
1531         int txcnt[MAX_PORTS];
1532 };
1533
1534 #define         DCD_changed     0x01
1535 #define         DCD_oldstate    0x80
1536
1537 static int moxaLowWaterChk;
1538 static struct mon_str moxaLog;
1539 static int moxaFuncTout = HZ / 2;
1540
1541 static void moxafunc(void __iomem *, int, ushort);
1542 static void moxa_wait_finish(void __iomem *);
1543 static void moxa_low_water_check(void __iomem *);
1544
1545 /*****************************************************************************
1546  *      Driver level functions:                                              *
1547  *      2. MoxaDriverIoctl(unsigned int cmd, unsigned long arg, int port);   *
1548  *      3. MoxaDriverPoll(void);                                             *
1549  *****************************************************************************/
1550 #define MOXA            0x400
1551 #define MOXA_GET_IQUEUE         (MOXA + 1)      /* get input buffered count */
1552 #define MOXA_GET_OQUEUE         (MOXA + 2)      /* get output buffered count */
1553 #define MOXA_GETDATACOUNT       (MOXA + 23)
1554 #define MOXA_GET_IOQUEUE        (MOXA + 27)
1555 #define MOXA_FLUSH_QUEUE        (MOXA + 28)
1556 #define MOXA_GET_CONF           (MOXA + 35)     /* configuration */
1557 #define MOXA_GET_MAJOR          (MOXA + 63)
1558 #define MOXA_GET_CUMAJOR        (MOXA + 64)
1559 #define MOXA_GETMSTATUS         (MOXA + 65)
1560
1561 static void MoxaPortFlushData(struct moxa_port *port, int mode)
1562 {
1563         void __iomem *ofsAddr;
1564         if ((mode < 0) || (mode > 2))
1565                 return;
1566         ofsAddr = port->tableAddr;
1567         moxafunc(ofsAddr, FC_FlushQueue, mode);
1568         if (mode != 1) {
1569                 port->lowChkFlag = 0;
1570                 moxa_low_water_check(ofsAddr);
1571         }
1572 }
1573
1574 static int MoxaDriverIoctl(struct tty_struct *tty, unsigned int cmd,
1575                 unsigned long arg)
1576 {
1577         struct moxa_port *port = tty->driver_data;
1578         int i;
1579         int status;
1580         void __user *argp = (void __user *)arg;
1581
1582         if (tty->index == MAX_PORTS) {
1583                 if ((cmd != MOXA_GET_CONF) && (cmd != MOXA_GETDATACOUNT) &&
1584                     (cmd != MOXA_GET_IOQUEUE) && (cmd != MOXA_GET_MAJOR) &&
1585                     (cmd != MOXA_GET_CUMAJOR) && (cmd != MOXA_GETMSTATUS))
1586                         return (-EINVAL);
1587         }
1588         switch (cmd) {
1589         case MOXA_GETDATACOUNT:
1590                 moxaLog.tick = jiffies;
1591                 if(copy_to_user(argp, &moxaLog, sizeof(struct mon_str)))
1592                         return -EFAULT;
1593                 return (0);
1594         case MOXA_FLUSH_QUEUE:
1595                 MoxaPortFlushData(port, arg);
1596                 return (0);
1597         case MOXA_GET_IOQUEUE: {
1598                 struct moxaq_str __user *argm = argp;
1599                 struct moxaq_str tmp;
1600
1601                 for (i = 0; i < MAX_PORTS; i++, argm++) {
1602                         memset(&tmp, 0, sizeof(tmp));
1603                         if (moxa_ports[i].chkPort) {
1604                                 tmp.inq = MoxaPortRxQueue(&moxa_ports[i]);
1605                                 tmp.outq = MoxaPortTxQueue(&moxa_ports[i]);
1606                         }
1607                         if (copy_to_user(argm, &tmp, sizeof(tmp)))
1608                                 return -EFAULT;
1609                 }
1610                 return (0);
1611         } case MOXA_GET_OQUEUE:
1612                 i = MoxaPortTxQueue(port);
1613                 return put_user(i, (unsigned long __user *)argp);
1614         case MOXA_GET_IQUEUE:
1615                 i = MoxaPortRxQueue(port);
1616                 return put_user(i, (unsigned long __user *)argp);
1617         case MOXA_GET_MAJOR:
1618                 if(copy_to_user(argp, &ttymajor, sizeof(int)))
1619                         return -EFAULT;
1620                 return 0;
1621         case MOXA_GET_CUMAJOR:
1622                 i = 0;
1623                 if(copy_to_user(argp, &i, sizeof(int)))
1624                         return -EFAULT;
1625                 return 0;
1626         case MOXA_GETMSTATUS: {
1627                 struct mxser_mstatus __user *argm = argp;
1628                 struct mxser_mstatus tmp;
1629                 struct moxa_port *p;
1630
1631                 for (i = 0; i < MAX_PORTS; i++, argm++) {
1632                         p = &moxa_ports[i];
1633                         memset(&tmp, 0, sizeof(tmp));
1634                         if (!p->chkPort) {
1635                                 goto copy;
1636                         } else {
1637                                 status = MoxaPortLineStatus(p);
1638                                 if (status & 1)
1639                                         tmp.cts = 1;
1640                                 if (status & 2)
1641                                         tmp.dsr = 1;
1642                                 if (status & 4)
1643                                         tmp.dcd = 1;
1644                         }
1645
1646                         if (!p->tty || !p->tty->termios)
1647                                 tmp.cflag = p->cflag;
1648                         else
1649                                 tmp.cflag = p->tty->termios->c_cflag;
1650 copy:
1651                         if (copy_to_user(argm, &tmp, sizeof(tmp)))
1652                                 return -EFAULT;
1653                 }
1654                 return 0;
1655         }
1656         }
1657
1658         return -ENOIOCTLCMD;
1659 }
1660
1661 int MoxaDriverPoll(void)
1662 {
1663         struct moxa_board_conf *brd;
1664         register ushort temp;
1665         register int card;
1666         void __iomem *ofsAddr;
1667         void __iomem *ip;
1668         int port, p, ports;
1669
1670         if (moxaCard == 0)
1671                 return (-1);
1672         for (card = 0; card < MAX_BOARDS; card++) {
1673                 brd = &moxa_boards[card];
1674                 if (brd->loadstat == 0)
1675                         continue;
1676                 if ((ports = brd->numPorts) == 0)
1677                         continue;
1678                 if (readb(brd->intPend) == 0xff) {
1679                         ip = brd->intTable + readb(brd->intNdx);
1680                         p = card * MAX_PORTS_PER_BOARD;
1681                         ports <<= 1;
1682                         for (port = 0; port < ports; port += 2, p++) {
1683                                 if ((temp = readw(ip + port)) != 0) {
1684                                         writew(0, ip + port);
1685                                         ofsAddr = moxa_ports[p].tableAddr;
1686                                         if (temp & IntrTx)
1687                                                 writew(readw(ofsAddr + HostStat) & ~WakeupTx, ofsAddr + HostStat);
1688                                         if (temp & IntrBreak) {
1689                                                 moxa_ports[p].breakCnt++;
1690                                         }
1691                                         if (temp & IntrLine) {
1692                                                 if (readb(ofsAddr + FlagStat) & DCD_state) {
1693                                                         if ((moxa_ports[p].DCDState & DCD_oldstate) == 0)
1694                                                                 moxa_ports[p].DCDState = (DCD_oldstate |
1695                                                                                    DCD_changed);
1696                                                 } else {
1697                                                         if (moxa_ports[p].DCDState & DCD_oldstate)
1698                                                                 moxa_ports[p].DCDState = DCD_changed;
1699                                                 }
1700                                         }
1701                                 }
1702                         }
1703                         writeb(0, brd->intPend);
1704                 }
1705                 if (moxaLowWaterChk) {
1706                         p = card * MAX_PORTS_PER_BOARD;
1707                         for (port = 0; port < ports; port++, p++) {
1708                                 if (moxa_ports[p].lowChkFlag) {
1709                                         moxa_ports[p].lowChkFlag = 0;
1710                                         ofsAddr = moxa_ports[p].tableAddr;
1711                                         moxa_low_water_check(ofsAddr);
1712                                 }
1713                         }
1714                 }
1715         }
1716         moxaLowWaterChk = 0;
1717         return (0);
1718 }
1719
1720 /*****************************************************************************
1721  *      Card level function:                                                 *
1722  *      1. MoxaPortsOfCard(int cardno);                                      *
1723  *****************************************************************************/
1724 int MoxaPortsOfCard(int cardno)
1725 {
1726
1727         if (moxa_boards[cardno].boardType == 0)
1728                 return (0);
1729         return (moxa_boards[cardno].numPorts);
1730 }
1731
1732 /*****************************************************************************
1733  *      Port level functions:                                                *
1734  *      1.  MoxaPortIsValid(int port);                                       *
1735  *      2.  MoxaPortEnable(int port);                                        *
1736  *      3.  MoxaPortDisable(int port);                                       *
1737  *      4.  MoxaPortGetMaxBaud(int port);                                    *
1738  *      6.  MoxaPortSetBaud(int port, long baud);                            *
1739  *      8.  MoxaPortSetTermio(int port, unsigned char *termio);              *
1740  *      9.  MoxaPortGetLineOut(int port, int *dtrState, int *rtsState);      *
1741  *      10. MoxaPortLineCtrl(int port, int dtrState, int rtsState);          *
1742  *      11. MoxaPortFlowCtrl(int port, int rts, int cts, int rx, int tx,int xany);    *
1743  *      12. MoxaPortLineStatus(int port);                                    *
1744  *      13. MoxaPortDCDChange(int port);                                     *
1745  *      14. MoxaPortDCDON(int port);                                         *
1746  *      15. MoxaPortFlushData(int port, int mode);                           *
1747  *      16. MoxaPortWriteData(int port, unsigned char * buffer, int length); *
1748  *      17. MoxaPortReadData(int port, struct tty_struct *tty);              *
1749  *      20. MoxaPortTxQueue(int port);                                       *
1750  *      21. MoxaPortTxFree(int port);                                        *
1751  *      22. MoxaPortRxQueue(int port);                                       *
1752  *      24. MoxaPortTxDisable(int port);                                     *
1753  *      25. MoxaPortTxEnable(int port);                                      *
1754  *      27. MoxaPortResetBrkCnt(int port);                                   *
1755  *      30. MoxaPortSendBreak(int port, int ticks);                          *
1756  *****************************************************************************/
1757 /*
1758  *    Moxa Port Number Description:
1759  *
1760  *      MOXA serial driver supports up to 4 MOXA-C218/C320 boards. And,
1761  *      the port number using in MOXA driver functions will be 0 to 31 for
1762  *      first MOXA board, 32 to 63 for second, 64 to 95 for third and 96
1763  *      to 127 for fourth. For example, if you setup three MOXA boards,
1764  *      first board is C218, second board is C320-16 and third board is
1765  *      C320-32. The port number of first board (C218 - 8 ports) is from
1766  *      0 to 7. The port number of second board (C320 - 16 ports) is form
1767  *      32 to 47. The port number of third board (C320 - 32 ports) is from
1768  *      64 to 95. And those port numbers form 8 to 31, 48 to 63 and 96 to
1769  *      127 will be invalid.
1770  *
1771  *
1772  *      Moxa Functions Description:
1773  *
1774  *      Function 1:     Driver initialization routine, this routine must be
1775  *                      called when initialized driver.
1776  *      Syntax:
1777  *      void MoxaDriverInit();
1778  *
1779  *
1780  *      Function 2:     Moxa driver private IOCTL command processing.
1781  *      Syntax:
1782  *      int  MoxaDriverIoctl(unsigned int cmd, unsigned long arg, int port);
1783  *
1784  *           unsigned int cmd   : IOCTL command
1785  *           unsigned long arg  : IOCTL argument
1786  *           int port           : port number (0 - 127)
1787  *
1788  *           return:    0  (OK)
1789  *                      -EINVAL
1790  *                      -ENOIOCTLCMD
1791  *
1792  *
1793  *      Function 3:     Moxa driver polling process routine.
1794  *      Syntax:
1795  *      int  MoxaDriverPoll(void);
1796  *
1797  *           return:    0       ; polling O.K.
1798  *                      -1      : no any Moxa card.             
1799  *
1800  *
1801  *      Function 4:     Get the ports of this card.
1802  *      Syntax:
1803  *      int  MoxaPortsOfCard(int cardno);
1804  *
1805  *           int cardno         : card number (0 - 3)
1806  *
1807  *           return:    0       : this card is invalid
1808  *                      8/16/24/32
1809  *
1810  *
1811  *      Function 5:     Check this port is valid or invalid
1812  *      Syntax:
1813  *      int  MoxaPortIsValid(int port);
1814  *           int port           : port number (0 - 127, ref port description)
1815  *
1816  *           return:    0       : this port is invalid
1817  *                      1       : this port is valid
1818  *
1819  *
1820  *      Function 6:     Enable this port to start Tx/Rx data.
1821  *      Syntax:
1822  *      void MoxaPortEnable(int port);
1823  *           int port           : port number (0 - 127)
1824  *
1825  *
1826  *      Function 7:     Disable this port
1827  *      Syntax:
1828  *      void MoxaPortDisable(int port);
1829  *           int port           : port number (0 - 127)
1830  *
1831  *
1832  *      Function 8:     Get the maximun available baud rate of this port.
1833  *      Syntax:
1834  *      long MoxaPortGetMaxBaud(int port);
1835  *           int port           : port number (0 - 127)
1836  *
1837  *           return:    0       : this port is invalid
1838  *                      38400/57600/115200 bps
1839  *
1840  *
1841  *      Function 10:    Setting baud rate of this port.
1842  *      Syntax:
1843  *      long MoxaPortSetBaud(int port, long baud);
1844  *           int port           : port number (0 - 127)
1845  *           long baud          : baud rate (50 - 115200)
1846  *
1847  *           return:    0       : this port is invalid or baud < 50
1848  *                      50 - 115200 : the real baud rate set to the port, if
1849  *                                    the argument baud is large than maximun
1850  *                                    available baud rate, the real setting
1851  *                                    baud rate will be the maximun baud rate.
1852  *
1853  *
1854  *      Function 12:    Configure the port.
1855  *      Syntax:
1856  *      int  MoxaPortSetTermio(int port, struct ktermios *termio, speed_t baud);
1857  *           int port           : port number (0 - 127)
1858  *           struct ktermios * termio : termio structure pointer
1859  *           speed_t baud       : baud rate
1860  *
1861  *           return:    -1      : this port is invalid or termio == NULL
1862  *                      0       : setting O.K.
1863  *
1864  *
1865  *      Function 13:    Get the DTR/RTS state of this port.
1866  *      Syntax:
1867  *      int  MoxaPortGetLineOut(int port, int *dtrState, int *rtsState);
1868  *           int port           : port number (0 - 127)
1869  *           int * dtrState     : pointer to INT to receive the current DTR
1870  *                                state. (if NULL, this function will not
1871  *                                write to this address)
1872  *           int * rtsState     : pointer to INT to receive the current RTS
1873  *                                state. (if NULL, this function will not
1874  *                                write to this address)
1875  *
1876  *           return:    -1      : this port is invalid
1877  *                      0       : O.K.
1878  *
1879  *
1880  *      Function 14:    Setting the DTR/RTS output state of this port.
1881  *      Syntax:
1882  *      void MoxaPortLineCtrl(int port, int dtrState, int rtsState);
1883  *           int port           : port number (0 - 127)
1884  *           int dtrState       : DTR output state (0: off, 1: on)
1885  *           int rtsState       : RTS output state (0: off, 1: on)
1886  *
1887  *
1888  *      Function 15:    Setting the flow control of this port.
1889  *      Syntax:
1890  *      void MoxaPortFlowCtrl(int port, int rtsFlow, int ctsFlow, int rxFlow,
1891  *                            int txFlow,int xany);
1892  *           int port           : port number (0 - 127)
1893  *           int rtsFlow        : H/W RTS flow control (0: no, 1: yes)
1894  *           int ctsFlow        : H/W CTS flow control (0: no, 1: yes)
1895  *           int rxFlow         : S/W Rx XON/XOFF flow control (0: no, 1: yes)
1896  *           int txFlow         : S/W Tx XON/XOFF flow control (0: no, 1: yes)
1897  *           int xany           : S/W XANY flow control (0: no, 1: yes)
1898  *
1899  *
1900  *      Function 16:    Get ths line status of this port
1901  *      Syntax:
1902  *      int  MoxaPortLineStatus(int port);
1903  *           int port           : port number (0 - 127)
1904  *
1905  *           return:    Bit 0 - CTS state (0: off, 1: on)
1906  *                      Bit 1 - DSR state (0: off, 1: on)
1907  *                      Bit 2 - DCD state (0: off, 1: on)
1908  *
1909  *
1910  *      Function 17:    Check the DCD state has changed since the last read
1911  *                      of this function.
1912  *      Syntax:
1913  *      int  MoxaPortDCDChange(int port);
1914  *           int port           : port number (0 - 127)
1915  *
1916  *           return:    0       : no changed
1917  *                      1       : DCD has changed
1918  *
1919  *
1920  *      Function 18:    Check ths current DCD state is ON or not.
1921  *      Syntax:
1922  *      int  MoxaPortDCDON(int port);
1923  *           int port           : port number (0 - 127)
1924  *
1925  *           return:    0       : DCD off
1926  *                      1       : DCD on
1927  *
1928  *
1929  *      Function 19:    Flush the Rx/Tx buffer data of this port.
1930  *      Syntax:
1931  *      void MoxaPortFlushData(int port, int mode);
1932  *           int port           : port number (0 - 127)
1933  *           int mode    
1934  *                      0       : flush the Rx buffer 
1935  *                      1       : flush the Tx buffer 
1936  *                      2       : flush the Rx and Tx buffer 
1937  *
1938  *
1939  *      Function 20:    Write data.
1940  *      Syntax:
1941  *      int  MoxaPortWriteData(int port, unsigned char * buffer, int length);
1942  *           int port           : port number (0 - 127)
1943  *           unsigned char * buffer     : pointer to write data buffer.
1944  *           int length         : write data length
1945  *
1946  *           return:    0 - length      : real write data length
1947  *
1948  *
1949  *      Function 21:    Read data.
1950  *      Syntax:
1951  *      int  MoxaPortReadData(int port, struct tty_struct *tty);
1952  *           int port           : port number (0 - 127)
1953  *           struct tty_struct *tty : tty for data
1954  *
1955  *           return:    0 - length      : real read data length
1956  *
1957  *
1958  *      Function 24:    Get the Tx buffer current queued data bytes
1959  *      Syntax:
1960  *      int  MoxaPortTxQueue(int port);
1961  *           int port           : port number (0 - 127)
1962  *
1963  *           return:    ..      : Tx buffer current queued data bytes
1964  *
1965  *
1966  *      Function 25:    Get the Tx buffer current free space
1967  *      Syntax:
1968  *      int  MoxaPortTxFree(int port);
1969  *           int port           : port number (0 - 127)
1970  *
1971  *           return:    ..      : Tx buffer current free space
1972  *
1973  *
1974  *      Function 26:    Get the Rx buffer current queued data bytes
1975  *      Syntax:
1976  *      int  MoxaPortRxQueue(int port);
1977  *           int port           : port number (0 - 127)
1978  *
1979  *           return:    ..      : Rx buffer current queued data bytes
1980  *
1981  *
1982  *      Function 28:    Disable port data transmission.
1983  *      Syntax:
1984  *      void MoxaPortTxDisable(int port);
1985  *           int port           : port number (0 - 127)
1986  *
1987  *
1988  *      Function 29:    Enable port data transmission.
1989  *      Syntax:
1990  *      void MoxaPortTxEnable(int port);
1991  *           int port           : port number (0 - 127)
1992  *
1993  *
1994  *      Function 31:    Get the received BREAK signal count and reset it.
1995  *      Syntax:
1996  *      int  MoxaPortResetBrkCnt(int port);
1997  *           int port           : port number (0 - 127)
1998  *
1999  *           return:    0 - ..  : BREAK signal count
2000  *
2001  *
2002  *      Function 34:    Send out a BREAK signal.
2003  *      Syntax:
2004  *      void MoxaPortSendBreak(int port, int ms100);
2005  *           int port           : port number (0 - 127)
2006  *           int ms100          : break signal time interval.
2007  *                                unit: 100 mini-second. if ms100 == 0, it will
2008  *                                send out a about 250 ms BREAK signal.
2009  *
2010  */
2011 static int MoxaPortIsValid(int port)
2012 {
2013         if (moxaCard == 0)
2014                 return (0);
2015         if (moxa_ports[port].chkPort == 0)
2016                 return (0);
2017         return (1);
2018 }
2019
2020 static void MoxaPortEnable(struct moxa_port *port)
2021 {
2022         void __iomem *ofsAddr;
2023         short lowwater = 512;
2024
2025         ofsAddr = port->tableAddr;
2026         writew(lowwater, ofsAddr + Low_water);
2027         port->breakCnt = 0;
2028         if (port->board->boardType == MOXA_BOARD_C320_ISA ||
2029             port->board->boardType == MOXA_BOARD_C320_PCI) {
2030                 moxafunc(ofsAddr, FC_SetBreakIrq, 0);
2031         } else {
2032                 writew(readw(ofsAddr + HostStat) | WakeupBreak, ofsAddr + HostStat);
2033         }
2034
2035         moxafunc(ofsAddr, FC_SetLineIrq, Magic_code);
2036         moxafunc(ofsAddr, FC_FlushQueue, 2);
2037
2038         moxafunc(ofsAddr, FC_EnableCH, Magic_code);
2039         MoxaPortLineStatus(port);
2040 }
2041
2042 static void MoxaPortDisable(struct moxa_port *port)
2043 {
2044         void __iomem *ofsAddr = port->tableAddr;
2045
2046         moxafunc(ofsAddr, FC_SetFlowCtl, 0);    /* disable flow control */
2047         moxafunc(ofsAddr, FC_ClrLineIrq, Magic_code);
2048         writew(0, ofsAddr + HostStat);
2049         moxafunc(ofsAddr, FC_DisableCH, Magic_code);
2050 }
2051
2052 static long MoxaPortGetMaxBaud(struct moxa_port *port)
2053 {
2054         if (port->board->boardType == MOXA_BOARD_C320_ISA ||
2055                         port->board->boardType == MOXA_BOARD_C320_PCI)
2056                 return (460800L);
2057         else
2058                 return (921600L);
2059 }
2060
2061
2062 static long MoxaPortSetBaud(struct moxa_port *port, long baud)
2063 {
2064         void __iomem *ofsAddr;
2065         long max, clock;
2066         unsigned int val;
2067
2068         if ((baud < 50L) || ((max = MoxaPortGetMaxBaud(port)) == 0))
2069                 return (0);
2070         ofsAddr = port->tableAddr;
2071         if (baud > max)
2072                 baud = max;
2073         if (max == 38400L)
2074                 clock = 614400L;        /* for 9.8304 Mhz : max. 38400 bps */
2075         else if (max == 57600L)
2076                 clock = 691200L;        /* for 11.0592 Mhz : max. 57600 bps */
2077         else
2078                 clock = 921600L;        /* for 14.7456 Mhz : max. 115200 bps */
2079         val = clock / baud;
2080         moxafunc(ofsAddr, FC_SetBaud, val);
2081         baud = clock / val;
2082         port->curBaud = baud;
2083         return (baud);
2084 }
2085
2086 static int MoxaPortSetTermio(struct moxa_port *port, struct ktermios *termio,
2087                 speed_t baud)
2088 {
2089         void __iomem *ofsAddr;
2090         tcflag_t cflag;
2091         tcflag_t mode = 0;
2092
2093         if (port->chkPort == 0 || termio == 0)
2094                 return (-1);
2095         ofsAddr = port->tableAddr;
2096         cflag = termio->c_cflag;        /* termio->c_cflag */
2097
2098         mode = termio->c_cflag & CSIZE;
2099         if (mode == CS5)
2100                 mode = MX_CS5;
2101         else if (mode == CS6)
2102                 mode = MX_CS6;
2103         else if (mode == CS7)
2104                 mode = MX_CS7;
2105         else if (mode == CS8)
2106                 mode = MX_CS8;
2107
2108         if (termio->c_cflag & CSTOPB) {
2109                 if (mode == MX_CS5)
2110                         mode |= MX_STOP15;
2111                 else
2112                         mode |= MX_STOP2;
2113         } else
2114                 mode |= MX_STOP1;
2115
2116         if (termio->c_cflag & PARENB) {
2117                 if (termio->c_cflag & PARODD)
2118                         mode |= MX_PARODD;
2119                 else
2120                         mode |= MX_PAREVEN;
2121         } else
2122                 mode |= MX_PARNONE;
2123
2124         moxafunc(ofsAddr, FC_SetDataMode, (ushort) mode);
2125
2126         if (port->board->boardType == MOXA_BOARD_C320_ISA ||
2127                         port->board->boardType == MOXA_BOARD_C320_PCI) {
2128                 if (baud >= 921600L)
2129                         return (-1);
2130         }
2131         baud = MoxaPortSetBaud(port, baud);
2132
2133         if (termio->c_iflag & (IXON | IXOFF | IXANY)) {
2134                 writeb(termio->c_cc[VSTART], ofsAddr + FuncArg);
2135                 writeb(termio->c_cc[VSTOP], ofsAddr + FuncArg1);
2136                 writeb(FC_SetXonXoff, ofsAddr + FuncCode);
2137                 moxa_wait_finish(ofsAddr);
2138
2139         }
2140         return (baud);
2141 }
2142
2143 static int MoxaPortGetLineOut(struct moxa_port *port, int *dtrState,
2144                 int *rtsState)
2145 {
2146
2147         if (!MoxaPortIsValid(port->tty->index))
2148                 return (-1);
2149         if (dtrState)
2150                 *dtrState = !!(port->lineCtrl & DTR_ON);
2151         if (rtsState)
2152                 *rtsState = !!(port->lineCtrl & RTS_ON);
2153
2154         return (0);
2155 }
2156
2157 static void MoxaPortLineCtrl(struct moxa_port *port, int dtr, int rts)
2158 {
2159         int mode = 0;
2160
2161         if (dtr)
2162                 mode |= DTR_ON;
2163         if (rts)
2164                 mode |= RTS_ON;
2165         port->lineCtrl = mode;
2166         moxafunc(port->tableAddr, FC_LineControl, mode);
2167 }
2168
2169 static void MoxaPortFlowCtrl(struct moxa_port *port, int rts, int cts,
2170                 int txflow, int rxflow, int txany)
2171 {
2172         int mode = 0;
2173
2174         if (rts)
2175                 mode |= RTS_FlowCtl;
2176         if (cts)
2177                 mode |= CTS_FlowCtl;
2178         if (txflow)
2179                 mode |= Tx_FlowCtl;
2180         if (rxflow)
2181                 mode |= Rx_FlowCtl;
2182         if (txany)
2183                 mode |= IXM_IXANY;
2184         moxafunc(port->tableAddr, FC_SetFlowCtl, mode);
2185 }
2186
2187 static int MoxaPortLineStatus(struct moxa_port *port)
2188 {
2189         void __iomem *ofsAddr;
2190         int val;
2191
2192         ofsAddr = port->tableAddr;
2193         if (port->board->boardType == MOXA_BOARD_C320_ISA ||
2194                         port->board->boardType == MOXA_BOARD_C320_PCI) {
2195                 moxafunc(ofsAddr, FC_LineStatus, 0);
2196                 val = readw(ofsAddr + FuncArg);
2197         } else {
2198                 val = readw(ofsAddr + FlagStat) >> 4;
2199         }
2200         val &= 0x0B;
2201         if (val & 8) {
2202                 val |= 4;
2203                 if ((port->DCDState & DCD_oldstate) == 0)
2204                         port->DCDState = (DCD_oldstate | DCD_changed);
2205         } else {
2206                 if (port->DCDState & DCD_oldstate)
2207                         port->DCDState = DCD_changed;
2208         }
2209         val &= 7;
2210         return (val);
2211 }
2212
2213 static int MoxaPortDCDChange(struct moxa_port *port)
2214 {
2215         int n;
2216
2217         if (port->chkPort == 0)
2218                 return (0);
2219         n = port->DCDState;
2220         port->DCDState &= ~DCD_changed;
2221         n &= DCD_changed;
2222         return (n);
2223 }
2224
2225 static int MoxaPortDCDON(struct moxa_port *port)
2226 {
2227         int n;
2228
2229         if (port->chkPort == 0)
2230                 return (0);
2231         if (port->DCDState & DCD_oldstate)
2232                 n = 1;
2233         else
2234                 n = 0;
2235         return (n);
2236 }
2237
2238 static int MoxaPortWriteData(struct moxa_port *port, unsigned char *buffer,
2239                 int len)
2240 {
2241         int c, total, i;
2242         ushort tail;
2243         int cnt;
2244         ushort head, tx_mask, spage, epage;
2245         ushort pageno, pageofs, bufhead;
2246         void __iomem *baseAddr, *ofsAddr, *ofs;
2247
2248         ofsAddr = port->tableAddr;
2249         baseAddr = port->board->basemem;
2250         tx_mask = readw(ofsAddr + TX_mask);
2251         spage = readw(ofsAddr + Page_txb);
2252         epage = readw(ofsAddr + EndPage_txb);
2253         tail = readw(ofsAddr + TXwptr);
2254         head = readw(ofsAddr + TXrptr);
2255         c = (head > tail) ? (head - tail - 1)
2256             : (head - tail + tx_mask);
2257         if (c > len)
2258                 c = len;
2259         moxaLog.txcnt[port->tty->index] += c;
2260         total = c;
2261         if (spage == epage) {
2262                 bufhead = readw(ofsAddr + Ofs_txb);
2263                 writew(spage, baseAddr + Control_reg);
2264                 while (c > 0) {
2265                         if (head > tail)
2266                                 len = head - tail - 1;
2267                         else
2268                                 len = tx_mask + 1 - tail;
2269                         len = (c > len) ? len : c;
2270                         ofs = baseAddr + DynPage_addr + bufhead + tail;
2271                         for (i = 0; i < len; i++)
2272                                 writeb(*buffer++, ofs + i);
2273                         tail = (tail + len) & tx_mask;
2274                         c -= len;
2275                 }
2276                 writew(tail, ofsAddr + TXwptr);
2277         } else {
2278                 len = c;
2279                 pageno = spage + (tail >> 13);
2280                 pageofs = tail & Page_mask;
2281                 do {
2282                         cnt = Page_size - pageofs;
2283                         if (cnt > c)
2284                                 cnt = c;
2285                         c -= cnt;
2286                         writeb(pageno, baseAddr + Control_reg);
2287                         ofs = baseAddr + DynPage_addr + pageofs;
2288                         for (i = 0; i < cnt; i++)
2289                                 writeb(*buffer++, ofs + i);
2290                         if (c == 0) {
2291                                 writew((tail + len) & tx_mask, ofsAddr + TXwptr);
2292                                 break;
2293                         }
2294                         if (++pageno == epage)
2295                                 pageno = spage;
2296                         pageofs = 0;
2297                 } while (1);
2298         }
2299         writeb(1, ofsAddr + CD180TXirq);        /* start to send */
2300         return (total);
2301 }
2302
2303 static int MoxaPortReadData(struct moxa_port *port, struct tty_struct *tty)
2304 {
2305         register ushort head, pageofs;
2306         int i, count, cnt, len, total, remain;
2307         ushort tail, rx_mask, spage, epage;
2308         ushort pageno, bufhead;
2309         void __iomem *baseAddr, *ofsAddr, *ofs;
2310
2311         ofsAddr = port->tableAddr;
2312         baseAddr = port->board->basemem;
2313         head = readw(ofsAddr + RXrptr);
2314         tail = readw(ofsAddr + RXwptr);
2315         rx_mask = readw(ofsAddr + RX_mask);
2316         spage = readw(ofsAddr + Page_rxb);
2317         epage = readw(ofsAddr + EndPage_rxb);
2318         count = (tail >= head) ? (tail - head)
2319             : (tail - head + rx_mask + 1);
2320         if (count == 0)
2321                 return 0;
2322
2323         total = count;
2324         remain = count - total;
2325         moxaLog.rxcnt[port->tty->index] += total;
2326         count = total;
2327         if (spage == epage) {
2328                 bufhead = readw(ofsAddr + Ofs_rxb);
2329                 writew(spage, baseAddr + Control_reg);
2330                 while (count > 0) {
2331                         if (tail >= head)
2332                                 len = tail - head;
2333                         else
2334                                 len = rx_mask + 1 - head;
2335                         len = (count > len) ? len : count;
2336                         ofs = baseAddr + DynPage_addr + bufhead + head;
2337                         for (i = 0; i < len; i++)
2338                                 tty_insert_flip_char(tty, readb(ofs + i), TTY_NORMAL);
2339                         head = (head + len) & rx_mask;
2340                         count -= len;
2341                 }
2342                 writew(head, ofsAddr + RXrptr);
2343         } else {
2344                 len = count;
2345                 pageno = spage + (head >> 13);
2346                 pageofs = head & Page_mask;
2347                 do {
2348                         cnt = Page_size - pageofs;
2349                         if (cnt > count)
2350                                 cnt = count;
2351                         count -= cnt;
2352                         writew(pageno, baseAddr + Control_reg);
2353                         ofs = baseAddr + DynPage_addr + pageofs;
2354                         for (i = 0; i < cnt; i++)
2355                                 tty_insert_flip_char(tty, readb(ofs + i), TTY_NORMAL);
2356                         if (count == 0) {
2357                                 writew((head + len) & rx_mask, ofsAddr + RXrptr);
2358                                 break;
2359                         }
2360                         if (++pageno == epage)
2361                                 pageno = spage;
2362                         pageofs = 0;
2363                 } while (1);
2364         }
2365         if ((readb(ofsAddr + FlagStat) & Xoff_state) && (remain < LowWater)) {
2366                 moxaLowWaterChk = 1;
2367                 port->lowChkFlag = 1;
2368         }
2369         return (total);
2370 }
2371
2372
2373 static int MoxaPortTxQueue(struct moxa_port *port)
2374 {
2375         void __iomem *ofsAddr = port->tableAddr;
2376         ushort rptr, wptr, mask;
2377         int len;
2378
2379         rptr = readw(ofsAddr + TXrptr);
2380         wptr = readw(ofsAddr + TXwptr);
2381         mask = readw(ofsAddr + TX_mask);
2382         len = (wptr - rptr) & mask;
2383         return (len);
2384 }
2385
2386 static int MoxaPortTxFree(struct moxa_port *port)
2387 {
2388         void __iomem *ofsAddr = port->tableAddr;
2389         ushort rptr, wptr, mask;
2390         int len;
2391
2392         rptr = readw(ofsAddr + TXrptr);
2393         wptr = readw(ofsAddr + TXwptr);
2394         mask = readw(ofsAddr + TX_mask);
2395         len = mask - ((wptr - rptr) & mask);
2396         return (len);
2397 }
2398
2399 static int MoxaPortRxQueue(struct moxa_port *port)
2400 {
2401         void __iomem *ofsAddr = port->tableAddr;
2402         ushort rptr, wptr, mask;
2403         int len;
2404
2405         rptr = readw(ofsAddr + RXrptr);
2406         wptr = readw(ofsAddr + RXwptr);
2407         mask = readw(ofsAddr + RX_mask);
2408         len = (wptr - rptr) & mask;
2409         return (len);
2410 }
2411
2412
2413 static void MoxaPortTxDisable(struct moxa_port *port)
2414 {
2415         moxafunc(port->tableAddr, FC_SetXoffState, Magic_code);
2416 }
2417
2418 static void MoxaPortTxEnable(struct moxa_port *port)
2419 {
2420         moxafunc(port->tableAddr, FC_SetXonState, Magic_code);
2421 }
2422
2423
2424 static int MoxaPortResetBrkCnt(struct moxa_port *port)
2425 {
2426         ushort cnt;
2427         cnt = port->breakCnt;
2428         port->breakCnt = 0;
2429         return (cnt);
2430 }
2431
2432
2433 static void MoxaPortSendBreak(struct moxa_port *port, int ms100)
2434 {
2435         void __iomem *ofsAddr = port->tableAddr;
2436
2437         if (ms100) {
2438                 moxafunc(ofsAddr, FC_SendBreak, Magic_code);
2439                 msleep(ms100 * 10);
2440         } else {
2441                 moxafunc(ofsAddr, FC_SendBreak, Magic_code);
2442                 msleep(250);
2443         }
2444         moxafunc(ofsAddr, FC_StopBreak, Magic_code);
2445 }
2446
2447 static int moxa_get_serial_info(struct moxa_port *info,
2448                                 struct serial_struct __user *retinfo)
2449 {
2450         struct serial_struct tmp;
2451
2452         memset(&tmp, 0, sizeof(tmp));
2453         tmp.type = info->type;
2454         tmp.line = info->tty->index;
2455         tmp.port = 0;
2456         tmp.irq = 0;
2457         tmp.flags = info->asyncflags;
2458         tmp.baud_base = 921600;
2459         tmp.close_delay = info->close_delay;
2460         tmp.closing_wait = info->closing_wait;
2461         tmp.custom_divisor = 0;
2462         tmp.hub6 = 0;
2463         if(copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
2464                 return -EFAULT;
2465         return (0);
2466 }
2467
2468
2469 static int moxa_set_serial_info(struct moxa_port *info,
2470                                 struct serial_struct __user *new_info)
2471 {
2472         struct serial_struct new_serial;
2473
2474         if(copy_from_user(&new_serial, new_info, sizeof(new_serial)))
2475                 return -EFAULT;
2476
2477         if ((new_serial.irq != 0) ||
2478             (new_serial.port != 0) ||
2479 //           (new_serial.type != info->type) ||
2480             (new_serial.custom_divisor != 0) ||
2481             (new_serial.baud_base != 921600))
2482                 return (-EPERM);
2483
2484         if (!capable(CAP_SYS_ADMIN)) {
2485                 if (((new_serial.flags & ~ASYNC_USR_MASK) !=
2486                      (info->asyncflags & ~ASYNC_USR_MASK)))
2487                         return (-EPERM);
2488         } else {
2489                 info->close_delay = new_serial.close_delay * HZ / 100;
2490                 info->closing_wait = new_serial.closing_wait * HZ / 100;
2491         }
2492
2493         new_serial.flags = (new_serial.flags & ~ASYNC_FLAGS);
2494         new_serial.flags |= (info->asyncflags & ASYNC_FLAGS);
2495
2496         if (new_serial.type == PORT_16550A) {
2497                 MoxaSetFifo(info, 1);
2498         } else {
2499                 MoxaSetFifo(info, 0);
2500         }
2501
2502         info->type = new_serial.type;
2503         return (0);
2504 }
2505
2506
2507
2508 /*****************************************************************************
2509  *      Static local functions:                                              *
2510  *****************************************************************************/
2511 static void moxafunc(void __iomem *ofsAddr, int cmd, ushort arg)
2512 {
2513
2514         writew(arg, ofsAddr + FuncArg);
2515         writew(cmd, ofsAddr + FuncCode);
2516         moxa_wait_finish(ofsAddr);
2517 }
2518
2519 static void moxa_wait_finish(void __iomem *ofsAddr)
2520 {
2521         unsigned long i, j;
2522
2523         i = jiffies;
2524         while (readw(ofsAddr + FuncCode) != 0) {
2525                 j = jiffies;
2526                 if ((j - i) > moxaFuncTout) {
2527                         return;
2528                 }
2529         }
2530 }
2531
2532 static void moxa_low_water_check(void __iomem *ofsAddr)
2533 {
2534         int len;
2535         ushort rptr, wptr, mask;
2536
2537         if (readb(ofsAddr + FlagStat) & Xoff_state) {
2538                 rptr = readw(ofsAddr + RXrptr);
2539                 wptr = readw(ofsAddr + RXwptr);
2540                 mask = readw(ofsAddr + RX_mask);
2541                 len = (wptr - rptr) & mask;
2542                 if (len <= Low_water)
2543                         moxafunc(ofsAddr, FC_SendXon, 0);
2544         }
2545 }
2546
2547 static void MoxaSetFifo(struct moxa_port *port, int enable)
2548 {
2549         void __iomem *ofsAddr = port->tableAddr;
2550
2551         if (!enable) {
2552                 moxafunc(ofsAddr, FC_SetRxFIFOTrig, 0);
2553                 moxafunc(ofsAddr, FC_SetTxFIFOCnt, 1);
2554         } else {
2555                 moxafunc(ofsAddr, FC_SetRxFIFOTrig, 3);
2556                 moxafunc(ofsAddr, FC_SetTxFIFOCnt, 16);
2557         }
2558 }