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