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