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