tty/serial: lay the foundations for the next set of reworks
[pandora-kernel.git] / drivers / char / rocket.c
1 /*
2  * RocketPort device driver for Linux
3  *
4  * Written by Theodore Ts'o, 1995, 1996, 1997, 1998, 1999, 2000.
5  * 
6  * Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2003 by Comtrol, Inc.
7  * 
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as
10  * published by the Free Software Foundation; either version 2 of the
11  * License, or (at your option) any later version.
12  * 
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 /*
24  * Kernel Synchronization:
25  *
26  * This driver has 2 kernel control paths - exception handlers (calls into the driver
27  * from user mode) and the timer bottom half (tasklet).  This is a polled driver, interrupts
28  * are not used.
29  *
30  * Critical data: 
31  * -  rp_table[], accessed through passed "info" pointers, is a global (static) array of 
32  *    serial port state information and the xmit_buf circular buffer.  Protected by 
33  *    a per port spinlock.
34  * -  xmit_flags[], an array of ints indexed by line (port) number, indicating that there
35  *    is data to be transmitted.  Protected by atomic bit operations.
36  * -  rp_num_ports, int indicating number of open ports, protected by atomic operations.
37  * 
38  * rp_write() and rp_write_char() functions use a per port semaphore to protect against
39  * simultaneous access to the same port by more than one process.
40  */
41
42 /****** Defines ******/
43 #define ROCKET_PARANOIA_CHECK
44 #define ROCKET_DISABLE_SIMUSAGE
45
46 #undef ROCKET_SOFT_FLOW
47 #undef ROCKET_DEBUG_OPEN
48 #undef ROCKET_DEBUG_INTR
49 #undef ROCKET_DEBUG_WRITE
50 #undef ROCKET_DEBUG_FLOW
51 #undef ROCKET_DEBUG_THROTTLE
52 #undef ROCKET_DEBUG_WAIT_UNTIL_SENT
53 #undef ROCKET_DEBUG_RECEIVE
54 #undef ROCKET_DEBUG_HANGUP
55 #undef REV_PCI_ORDER
56 #undef ROCKET_DEBUG_IO
57
58 #define POLL_PERIOD HZ/100      /*  Polling period .01 seconds (10ms) */
59
60 /****** Kernel includes ******/
61
62 #include <linux/module.h>
63 #include <linux/errno.h>
64 #include <linux/major.h>
65 #include <linux/kernel.h>
66 #include <linux/signal.h>
67 #include <linux/slab.h>
68 #include <linux/mm.h>
69 #include <linux/sched.h>
70 #include <linux/timer.h>
71 #include <linux/interrupt.h>
72 #include <linux/tty.h>
73 #include <linux/tty_driver.h>
74 #include <linux/tty_flip.h>
75 #include <linux/string.h>
76 #include <linux/fcntl.h>
77 #include <linux/ptrace.h>
78 #include <linux/mutex.h>
79 #include <linux/ioport.h>
80 #include <linux/delay.h>
81 #include <linux/completion.h>
82 #include <linux/wait.h>
83 #include <linux/pci.h>
84 #include <asm/uaccess.h>
85 #include <asm/atomic.h>
86 #include <asm/unaligned.h>
87 #include <linux/bitops.h>
88 #include <linux/spinlock.h>
89 #include <linux/init.h>
90
91 /****** RocketPort includes ******/
92
93 #include "rocket_int.h"
94 #include "rocket.h"
95
96 #define ROCKET_VERSION "2.09"
97 #define ROCKET_DATE "12-June-2003"
98
99 /****** RocketPort Local Variables ******/
100
101 static void rp_do_poll(unsigned long dummy);
102
103 static struct tty_driver *rocket_driver;
104
105 static struct rocket_version driver_version = { 
106         ROCKET_VERSION, ROCKET_DATE
107 };
108
109 static struct r_port *rp_table[MAX_RP_PORTS];          /*  The main repository of serial port state information. */
110 static unsigned int xmit_flags[NUM_BOARDS];            /*  Bit significant, indicates port had data to transmit. */
111                                                        /*  eg.  Bit 0 indicates port 0 has xmit data, ...        */
112 static atomic_t rp_num_ports_open;                     /*  Number of serial ports open                           */
113 static DEFINE_TIMER(rocket_timer, rp_do_poll, 0, 0);
114
115 static unsigned long board1;                           /* ISA addresses, retrieved from rocketport.conf          */
116 static unsigned long board2;
117 static unsigned long board3;
118 static unsigned long board4;
119 static unsigned long controller;
120 static int support_low_speed;
121 static unsigned long modem1;
122 static unsigned long modem2;
123 static unsigned long modem3;
124 static unsigned long modem4;
125 static unsigned long pc104_1[8];
126 static unsigned long pc104_2[8];
127 static unsigned long pc104_3[8];
128 static unsigned long pc104_4[8];
129 static unsigned long *pc104[4] = { pc104_1, pc104_2, pc104_3, pc104_4 };
130
131 static int rp_baud_base[NUM_BOARDS];                   /*  Board config info (Someday make a per-board structure)  */
132 static unsigned long rcktpt_io_addr[NUM_BOARDS];
133 static int rcktpt_type[NUM_BOARDS];
134 static int is_PCI[NUM_BOARDS];
135 static rocketModel_t rocketModel[NUM_BOARDS];
136 static int max_board;
137
138 /*
139  * The following arrays define the interrupt bits corresponding to each AIOP.
140  * These bits are different between the ISA and regular PCI boards and the
141  * Universal PCI boards.
142  */
143
144 static Word_t aiop_intr_bits[AIOP_CTL_SIZE] = {
145         AIOP_INTR_BIT_0,
146         AIOP_INTR_BIT_1,
147         AIOP_INTR_BIT_2,
148         AIOP_INTR_BIT_3
149 };
150
151 static Word_t upci_aiop_intr_bits[AIOP_CTL_SIZE] = {
152         UPCI_AIOP_INTR_BIT_0,
153         UPCI_AIOP_INTR_BIT_1,
154         UPCI_AIOP_INTR_BIT_2,
155         UPCI_AIOP_INTR_BIT_3
156 };
157
158 static Byte_t RData[RDATASIZE] = {
159         0x00, 0x09, 0xf6, 0x82,
160         0x02, 0x09, 0x86, 0xfb,
161         0x04, 0x09, 0x00, 0x0a,
162         0x06, 0x09, 0x01, 0x0a,
163         0x08, 0x09, 0x8a, 0x13,
164         0x0a, 0x09, 0xc5, 0x11,
165         0x0c, 0x09, 0x86, 0x85,
166         0x0e, 0x09, 0x20, 0x0a,
167         0x10, 0x09, 0x21, 0x0a,
168         0x12, 0x09, 0x41, 0xff,
169         0x14, 0x09, 0x82, 0x00,
170         0x16, 0x09, 0x82, 0x7b,
171         0x18, 0x09, 0x8a, 0x7d,
172         0x1a, 0x09, 0x88, 0x81,
173         0x1c, 0x09, 0x86, 0x7a,
174         0x1e, 0x09, 0x84, 0x81,
175         0x20, 0x09, 0x82, 0x7c,
176         0x22, 0x09, 0x0a, 0x0a
177 };
178
179 static Byte_t RRegData[RREGDATASIZE] = {
180         0x00, 0x09, 0xf6, 0x82, /* 00: Stop Rx processor */
181         0x08, 0x09, 0x8a, 0x13, /* 04: Tx software flow control */
182         0x0a, 0x09, 0xc5, 0x11, /* 08: XON char */
183         0x0c, 0x09, 0x86, 0x85, /* 0c: XANY */
184         0x12, 0x09, 0x41, 0xff, /* 10: Rx mask char */
185         0x14, 0x09, 0x82, 0x00, /* 14: Compare/Ignore #0 */
186         0x16, 0x09, 0x82, 0x7b, /* 18: Compare #1 */
187         0x18, 0x09, 0x8a, 0x7d, /* 1c: Compare #2 */
188         0x1a, 0x09, 0x88, 0x81, /* 20: Interrupt #1 */
189         0x1c, 0x09, 0x86, 0x7a, /* 24: Ignore/Replace #1 */
190         0x1e, 0x09, 0x84, 0x81, /* 28: Interrupt #2 */
191         0x20, 0x09, 0x82, 0x7c, /* 2c: Ignore/Replace #2 */
192         0x22, 0x09, 0x0a, 0x0a  /* 30: Rx FIFO Enable */
193 };
194
195 static CONTROLLER_T sController[CTL_SIZE] = {
196         {-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0},
197          {0, 0, 0, 0}, {-1, -1, -1, -1}, {0, 0, 0, 0}},
198         {-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0},
199          {0, 0, 0, 0}, {-1, -1, -1, -1}, {0, 0, 0, 0}},
200         {-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0},
201          {0, 0, 0, 0}, {-1, -1, -1, -1}, {0, 0, 0, 0}},
202         {-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0},
203          {0, 0, 0, 0}, {-1, -1, -1, -1}, {0, 0, 0, 0}}
204 };
205
206 static Byte_t sBitMapClrTbl[8] = {
207         0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f
208 };
209
210 static Byte_t sBitMapSetTbl[8] = {
211         0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80
212 };
213
214 static int sClockPrescale = 0x14;
215
216 /*
217  *  Line number is the ttySIx number (x), the Minor number.  We 
218  *  assign them sequentially, starting at zero.  The following 
219  *  array keeps track of the line number assigned to a given board/aiop/channel.
220  */
221 static unsigned char lineNumbers[MAX_RP_PORTS];
222 static unsigned long nextLineNumber;
223
224 /*****  RocketPort Static Prototypes   *********/
225 static int __init init_ISA(int i);
226 static void rp_wait_until_sent(struct tty_struct *tty, int timeout);
227 static void rp_flush_buffer(struct tty_struct *tty);
228 static void rmSpeakerReset(CONTROLLER_T * CtlP, unsigned long model);
229 static unsigned char GetLineNumber(int ctrl, int aiop, int ch);
230 static unsigned char SetLineNumber(int ctrl, int aiop, int ch);
231 static void rp_start(struct tty_struct *tty);
232 static int sInitChan(CONTROLLER_T * CtlP, CHANNEL_T * ChP, int AiopNum,
233                      int ChanNum);
234 static void sSetInterfaceMode(CHANNEL_T * ChP, Byte_t mode);
235 static void sFlushRxFIFO(CHANNEL_T * ChP);
236 static void sFlushTxFIFO(CHANNEL_T * ChP);
237 static void sEnInterrupts(CHANNEL_T * ChP, Word_t Flags);
238 static void sDisInterrupts(CHANNEL_T * ChP, Word_t Flags);
239 static void sModemReset(CONTROLLER_T * CtlP, int chan, int on);
240 static void sPCIModemReset(CONTROLLER_T * CtlP, int chan, int on);
241 static int sWriteTxPrioByte(CHANNEL_T * ChP, Byte_t Data);
242 static int sPCIInitController(CONTROLLER_T * CtlP, int CtlNum,
243                               ByteIO_t * AiopIOList, int AiopIOListSize,
244                               WordIO_t ConfigIO, int IRQNum, Byte_t Frequency,
245                               int PeriodicOnly, int altChanRingIndicator,
246                               int UPCIRingInd);
247 static int sInitController(CONTROLLER_T * CtlP, int CtlNum, ByteIO_t MudbacIO,
248                            ByteIO_t * AiopIOList, int AiopIOListSize,
249                            int IRQNum, Byte_t Frequency, int PeriodicOnly);
250 static int sReadAiopID(ByteIO_t io);
251 static int sReadAiopNumChan(WordIO_t io);
252
253 MODULE_AUTHOR("Theodore Ts'o");
254 MODULE_DESCRIPTION("Comtrol RocketPort driver");
255 module_param(board1, ulong, 0);
256 MODULE_PARM_DESC(board1, "I/O port for (ISA) board #1");
257 module_param(board2, ulong, 0);
258 MODULE_PARM_DESC(board2, "I/O port for (ISA) board #2");
259 module_param(board3, ulong, 0);
260 MODULE_PARM_DESC(board3, "I/O port for (ISA) board #3");
261 module_param(board4, ulong, 0);
262 MODULE_PARM_DESC(board4, "I/O port for (ISA) board #4");
263 module_param(controller, ulong, 0);
264 MODULE_PARM_DESC(controller, "I/O port for (ISA) rocketport controller");
265 module_param(support_low_speed, bool, 0);
266 MODULE_PARM_DESC(support_low_speed, "1 means support 50 baud, 0 means support 460400 baud");
267 module_param(modem1, ulong, 0);
268 MODULE_PARM_DESC(modem1, "1 means (ISA) board #1 is a RocketModem");
269 module_param(modem2, ulong, 0);
270 MODULE_PARM_DESC(modem2, "1 means (ISA) board #2 is a RocketModem");
271 module_param(modem3, ulong, 0);
272 MODULE_PARM_DESC(modem3, "1 means (ISA) board #3 is a RocketModem");
273 module_param(modem4, ulong, 0);
274 MODULE_PARM_DESC(modem4, "1 means (ISA) board #4 is a RocketModem");
275 module_param_array(pc104_1, ulong, NULL, 0);
276 MODULE_PARM_DESC(pc104_1, "set interface types for ISA(PC104) board #1 (e.g. pc104_1=232,232,485,485,...");
277 module_param_array(pc104_2, ulong, NULL, 0);
278 MODULE_PARM_DESC(pc104_2, "set interface types for ISA(PC104) board #2 (e.g. pc104_2=232,232,485,485,...");
279 module_param_array(pc104_3, ulong, NULL, 0);
280 MODULE_PARM_DESC(pc104_3, "set interface types for ISA(PC104) board #3 (e.g. pc104_3=232,232,485,485,...");
281 module_param_array(pc104_4, ulong, NULL, 0);
282 MODULE_PARM_DESC(pc104_4, "set interface types for ISA(PC104) board #4 (e.g. pc104_4=232,232,485,485,...");
283
284 static int rp_init(void);
285 static void rp_cleanup_module(void);
286
287 module_init(rp_init);
288 module_exit(rp_cleanup_module);
289
290
291 MODULE_LICENSE("Dual BSD/GPL");
292
293 /*************************************************************************/
294 /*                     Module code starts here                           */
295
296 static inline int rocket_paranoia_check(struct r_port *info,
297                                         const char *routine)
298 {
299 #ifdef ROCKET_PARANOIA_CHECK
300         if (!info)
301                 return 1;
302         if (info->magic != RPORT_MAGIC) {
303                 printk(KERN_WARNING "Warning: bad magic number for rocketport "
304                                 "struct in %s\n", routine);
305                 return 1;
306         }
307 #endif
308         return 0;
309 }
310
311
312 /*  Serial port receive data function.  Called (from timer poll) when an AIOPIC signals 
313  *  that receive data is present on a serial port.  Pulls data from FIFO, moves it into the 
314  *  tty layer.  
315  */
316 static void rp_do_receive(struct r_port *info,
317                           struct tty_struct *tty,
318                           CHANNEL_t * cp, unsigned int ChanStatus)
319 {
320         unsigned int CharNStat;
321         int ToRecv, wRecv, space;
322         unsigned char *cbuf;
323
324         ToRecv = sGetRxCnt(cp);
325 #ifdef ROCKET_DEBUG_INTR
326         printk(KERN_INFO "rp_do_receive(%d)...\n", ToRecv);
327 #endif
328         if (ToRecv == 0)
329                 return;
330
331         /*
332          * if status indicates there are errored characters in the
333          * FIFO, then enter status mode (a word in FIFO holds
334          * character and status).
335          */
336         if (ChanStatus & (RXFOVERFL | RXBREAK | RXFRAME | RXPARITY)) {
337                 if (!(ChanStatus & STATMODE)) {
338 #ifdef ROCKET_DEBUG_RECEIVE
339                         printk(KERN_INFO "Entering STATMODE...\n");
340 #endif
341                         ChanStatus |= STATMODE;
342                         sEnRxStatusMode(cp);
343                 }
344         }
345
346         /* 
347          * if we previously entered status mode, then read down the
348          * FIFO one word at a time, pulling apart the character and
349          * the status.  Update error counters depending on status
350          */
351         if (ChanStatus & STATMODE) {
352 #ifdef ROCKET_DEBUG_RECEIVE
353                 printk(KERN_INFO "Ignore %x, read %x...\n",
354                         info->ignore_status_mask, info->read_status_mask);
355 #endif
356                 while (ToRecv) {
357                         char flag;
358
359                         CharNStat = sInW(sGetTxRxDataIO(cp));
360 #ifdef ROCKET_DEBUG_RECEIVE
361                         printk(KERN_INFO "%x...\n", CharNStat);
362 #endif
363                         if (CharNStat & STMBREAKH)
364                                 CharNStat &= ~(STMFRAMEH | STMPARITYH);
365                         if (CharNStat & info->ignore_status_mask) {
366                                 ToRecv--;
367                                 continue;
368                         }
369                         CharNStat &= info->read_status_mask;
370                         if (CharNStat & STMBREAKH)
371                                 flag = TTY_BREAK;
372                         else if (CharNStat & STMPARITYH)
373                                 flag = TTY_PARITY;
374                         else if (CharNStat & STMFRAMEH)
375                                 flag = TTY_FRAME;
376                         else if (CharNStat & STMRCVROVRH)
377                                 flag = TTY_OVERRUN;
378                         else
379                                 flag = TTY_NORMAL;
380                         tty_insert_flip_char(tty, CharNStat & 0xff, flag);
381                         ToRecv--;
382                 }
383
384                 /*
385                  * after we've emptied the FIFO in status mode, turn
386                  * status mode back off
387                  */
388                 if (sGetRxCnt(cp) == 0) {
389 #ifdef ROCKET_DEBUG_RECEIVE
390                         printk(KERN_INFO "Status mode off.\n");
391 #endif
392                         sDisRxStatusMode(cp);
393                 }
394         } else {
395                 /*
396                  * we aren't in status mode, so read down the FIFO two
397                  * characters at time by doing repeated word IO
398                  * transfer.
399                  */
400                 space = tty_prepare_flip_string(tty, &cbuf, ToRecv);
401                 if (space < ToRecv) {
402 #ifdef ROCKET_DEBUG_RECEIVE
403                         printk(KERN_INFO "rp_do_receive:insufficient space ToRecv=%d space=%d\n", ToRecv, space);
404 #endif
405                         if (space <= 0)
406                                 return;
407                         ToRecv = space;
408                 }
409                 wRecv = ToRecv >> 1;
410                 if (wRecv)
411                         sInStrW(sGetTxRxDataIO(cp), (unsigned short *) cbuf, wRecv);
412                 if (ToRecv & 1)
413                         cbuf[ToRecv - 1] = sInB(sGetTxRxDataIO(cp));
414         }
415         /*  Push the data up to the tty layer */
416         tty_flip_buffer_push(tty);
417 }
418
419 /*
420  *  Serial port transmit data function.  Called from the timer polling loop as a 
421  *  result of a bit set in xmit_flags[], indicating data (from the tty layer) is ready
422  *  to be sent out the serial port.  Data is buffered in rp_table[line].xmit_buf, it is 
423  *  moved to the port's xmit FIFO.  *info is critical data, protected by spinlocks.
424  */
425 static void rp_do_transmit(struct r_port *info)
426 {
427         int c;
428         CHANNEL_t *cp = &info->channel;
429         struct tty_struct *tty;
430         unsigned long flags;
431
432 #ifdef ROCKET_DEBUG_INTR
433         printk(KERN_DEBUG "%s\n", __func__);
434 #endif
435         if (!info)
436                 return;
437         if (!info->tty) {
438                 printk(KERN_WARNING "rp: WARNING %s called with "
439                                 "info->tty==NULL\n", __func__);
440                 clear_bit((info->aiop * 8) + info->chan, (void *) &xmit_flags[info->board]);
441                 return;
442         }
443
444         spin_lock_irqsave(&info->slock, flags);
445         tty = info->tty;
446         info->xmit_fifo_room = TXFIFO_SIZE - sGetTxCnt(cp);
447
448         /*  Loop sending data to FIFO until done or FIFO full */
449         while (1) {
450                 if (tty->stopped || tty->hw_stopped)
451                         break;
452                 c = min(info->xmit_fifo_room, info->xmit_cnt);
453                 c = min(c, XMIT_BUF_SIZE - info->xmit_tail);
454                 if (c <= 0 || info->xmit_fifo_room <= 0)
455                         break;
456                 sOutStrW(sGetTxRxDataIO(cp), (unsigned short *) (info->xmit_buf + info->xmit_tail), c / 2);
457                 if (c & 1)
458                         sOutB(sGetTxRxDataIO(cp), info->xmit_buf[info->xmit_tail + c - 1]);
459                 info->xmit_tail += c;
460                 info->xmit_tail &= XMIT_BUF_SIZE - 1;
461                 info->xmit_cnt -= c;
462                 info->xmit_fifo_room -= c;
463 #ifdef ROCKET_DEBUG_INTR
464                 printk(KERN_INFO "tx %d chars...\n", c);
465 #endif
466         }
467
468         if (info->xmit_cnt == 0)
469                 clear_bit((info->aiop * 8) + info->chan, (void *) &xmit_flags[info->board]);
470
471         if (info->xmit_cnt < WAKEUP_CHARS) {
472                 tty_wakeup(tty);
473 #ifdef ROCKETPORT_HAVE_POLL_WAIT
474                 wake_up_interruptible(&tty->poll_wait);
475 #endif
476         }
477
478         spin_unlock_irqrestore(&info->slock, flags);
479
480 #ifdef ROCKET_DEBUG_INTR
481         printk(KERN_DEBUG "(%d,%d,%d,%d)...\n", info->xmit_cnt, info->xmit_head,
482                info->xmit_tail, info->xmit_fifo_room);
483 #endif
484 }
485
486 /*
487  *  Called when a serial port signals it has read data in it's RX FIFO.
488  *  It checks what interrupts are pending and services them, including
489  *  receiving serial data.  
490  */
491 static void rp_handle_port(struct r_port *info)
492 {
493         CHANNEL_t *cp;
494         struct tty_struct *tty;
495         unsigned int IntMask, ChanStatus;
496
497         if (!info)
498                 return;
499
500         if ((info->flags & ROCKET_INITIALIZED) == 0) {
501                 printk(KERN_WARNING "rp: WARNING: rp_handle_port called with "
502                                 "info->flags & NOT_INIT\n");
503                 return;
504         }
505         if (!info->tty) {
506                 printk(KERN_WARNING "rp: WARNING: rp_handle_port called with "
507                                 "info->tty==NULL\n");
508                 return;
509         }
510         cp = &info->channel;
511         tty = info->tty;
512
513         IntMask = sGetChanIntID(cp) & info->intmask;
514 #ifdef ROCKET_DEBUG_INTR
515         printk(KERN_INFO "rp_interrupt %02x...\n", IntMask);
516 #endif
517         ChanStatus = sGetChanStatus(cp);
518         if (IntMask & RXF_TRIG) {       /* Rx FIFO trigger level */
519                 rp_do_receive(info, tty, cp, ChanStatus);
520         }
521         if (IntMask & DELTA_CD) {       /* CD change  */
522 #if (defined(ROCKET_DEBUG_OPEN) || defined(ROCKET_DEBUG_INTR) || defined(ROCKET_DEBUG_HANGUP))
523                 printk(KERN_INFO "ttyR%d CD now %s...\n", info->line,
524                        (ChanStatus & CD_ACT) ? "on" : "off");
525 #endif
526                 if (!(ChanStatus & CD_ACT) && info->cd_status) {
527 #ifdef ROCKET_DEBUG_HANGUP
528                         printk(KERN_INFO "CD drop, calling hangup.\n");
529 #endif
530                         tty_hangup(tty);
531                 }
532                 info->cd_status = (ChanStatus & CD_ACT) ? 1 : 0;
533                 wake_up_interruptible(&info->open_wait);
534         }
535 #ifdef ROCKET_DEBUG_INTR
536         if (IntMask & DELTA_CTS) {      /* CTS change */
537                 printk(KERN_INFO "CTS change...\n");
538         }
539         if (IntMask & DELTA_DSR) {      /* DSR change */
540                 printk(KERN_INFO "DSR change...\n");
541         }
542 #endif
543 }
544
545 /*
546  *  The top level polling routine.  Repeats every 1/100 HZ (10ms).
547  */
548 static void rp_do_poll(unsigned long dummy)
549 {
550         CONTROLLER_t *ctlp;
551         int ctrl, aiop, ch, line;
552         unsigned int xmitmask, i;
553         unsigned int CtlMask;
554         unsigned char AiopMask;
555         Word_t bit;
556
557         /*  Walk through all the boards (ctrl's) */
558         for (ctrl = 0; ctrl < max_board; ctrl++) {
559                 if (rcktpt_io_addr[ctrl] <= 0)
560                         continue;
561
562                 /*  Get a ptr to the board's control struct */
563                 ctlp = sCtlNumToCtlPtr(ctrl);
564
565                 /*  Get the interrupt status from the board */
566 #ifdef CONFIG_PCI
567                 if (ctlp->BusType == isPCI)
568                         CtlMask = sPCIGetControllerIntStatus(ctlp);
569                 else
570 #endif
571                         CtlMask = sGetControllerIntStatus(ctlp);
572
573                 /*  Check if any AIOP read bits are set */
574                 for (aiop = 0; CtlMask; aiop++) {
575                         bit = ctlp->AiopIntrBits[aiop];
576                         if (CtlMask & bit) {
577                                 CtlMask &= ~bit;
578                                 AiopMask = sGetAiopIntStatus(ctlp, aiop);
579
580                                 /*  Check if any port read bits are set */
581                                 for (ch = 0; AiopMask;  AiopMask >>= 1, ch++) {
582                                         if (AiopMask & 1) {
583
584                                                 /*  Get the line number (/dev/ttyRx number). */
585                                                 /*  Read the data from the port. */
586                                                 line = GetLineNumber(ctrl, aiop, ch);
587                                                 rp_handle_port(rp_table[line]);
588                                         }
589                                 }
590                         }
591                 }
592
593                 xmitmask = xmit_flags[ctrl];
594
595                 /*
596                  *  xmit_flags contains bit-significant flags, indicating there is data
597                  *  to xmit on the port. Bit 0 is port 0 on this board, bit 1 is port 
598                  *  1, ... (32 total possible).  The variable i has the aiop and ch 
599                  *  numbers encoded in it (port 0-7 are aiop0, 8-15 are aiop1, etc).
600                  */
601                 if (xmitmask) {
602                         for (i = 0; i < rocketModel[ctrl].numPorts; i++) {
603                                 if (xmitmask & (1 << i)) {
604                                         aiop = (i & 0x18) >> 3;
605                                         ch = i & 0x07;
606                                         line = GetLineNumber(ctrl, aiop, ch);
607                                         rp_do_transmit(rp_table[line]);
608                                 }
609                         }
610                 }
611         }
612
613         /*
614          * Reset the timer so we get called at the next clock tick (10ms).
615          */
616         if (atomic_read(&rp_num_ports_open))
617                 mod_timer(&rocket_timer, jiffies + POLL_PERIOD);
618 }
619
620 /*
621  *  Initializes the r_port structure for a port, as well as enabling the port on 
622  *  the board.  
623  *  Inputs:  board, aiop, chan numbers
624  */
625 static void init_r_port(int board, int aiop, int chan, struct pci_dev *pci_dev)
626 {
627         unsigned rocketMode;
628         struct r_port *info;
629         int line;
630         CONTROLLER_T *ctlp;
631
632         /*  Get the next available line number */
633         line = SetLineNumber(board, aiop, chan);
634
635         ctlp = sCtlNumToCtlPtr(board);
636
637         /*  Get a r_port struct for the port, fill it in and save it globally, indexed by line number */
638         info = kzalloc(sizeof (struct r_port), GFP_KERNEL);
639         if (!info) {
640                 printk(KERN_ERR "Couldn't allocate info struct for line #%d\n",
641                                 line);
642                 return;
643         }
644
645         info->magic = RPORT_MAGIC;
646         info->line = line;
647         info->ctlp = ctlp;
648         info->board = board;
649         info->aiop = aiop;
650         info->chan = chan;
651         info->closing_wait = 3000;
652         info->close_delay = 50;
653         init_waitqueue_head(&info->open_wait);
654         init_completion(&info->close_wait);
655         info->flags &= ~ROCKET_MODE_MASK;
656         switch (pc104[board][line]) {
657         case 422:
658                 info->flags |= ROCKET_MODE_RS422;
659                 break;
660         case 485:
661                 info->flags |= ROCKET_MODE_RS485;
662                 break;
663         case 232:
664         default:
665                 info->flags |= ROCKET_MODE_RS232;
666                 break;
667         }
668
669         info->intmask = RXF_TRIG | TXFIFO_MT | SRC_INT | DELTA_CD | DELTA_CTS | DELTA_DSR;
670         if (sInitChan(ctlp, &info->channel, aiop, chan) == 0) {
671                 printk(KERN_ERR "RocketPort sInitChan(%d, %d, %d) failed!\n",
672                                 board, aiop, chan);
673                 kfree(info);
674                 return;
675         }
676
677         rocketMode = info->flags & ROCKET_MODE_MASK;
678
679         if ((info->flags & ROCKET_RTS_TOGGLE) || (rocketMode == ROCKET_MODE_RS485))
680                 sEnRTSToggle(&info->channel);
681         else
682                 sDisRTSToggle(&info->channel);
683
684         if (ctlp->boardType == ROCKET_TYPE_PC104) {
685                 switch (rocketMode) {
686                 case ROCKET_MODE_RS485:
687                         sSetInterfaceMode(&info->channel, InterfaceModeRS485);
688                         break;
689                 case ROCKET_MODE_RS422:
690                         sSetInterfaceMode(&info->channel, InterfaceModeRS422);
691                         break;
692                 case ROCKET_MODE_RS232:
693                 default:
694                         if (info->flags & ROCKET_RTS_TOGGLE)
695                                 sSetInterfaceMode(&info->channel, InterfaceModeRS232T);
696                         else
697                                 sSetInterfaceMode(&info->channel, InterfaceModeRS232);
698                         break;
699                 }
700         }
701         spin_lock_init(&info->slock);
702         mutex_init(&info->write_mtx);
703         rp_table[line] = info;
704         tty_register_device(rocket_driver, line, pci_dev ? &pci_dev->dev :
705                         NULL);
706 }
707
708 /*
709  *  Configures a rocketport port according to its termio settings.  Called from 
710  *  user mode into the driver (exception handler).  *info CD manipulation is spinlock protected.
711  */
712 static void configure_r_port(struct r_port *info,
713                              struct ktermios *old_termios)
714 {
715         unsigned cflag;
716         unsigned long flags;
717         unsigned rocketMode;
718         int bits, baud, divisor;
719         CHANNEL_t *cp;
720         struct ktermios *t = info->tty->termios;
721
722         cp = &info->channel;
723         cflag = t->c_cflag;
724
725         /* Byte size and parity */
726         if ((cflag & CSIZE) == CS8) {
727                 sSetData8(cp);
728                 bits = 10;
729         } else {
730                 sSetData7(cp);
731                 bits = 9;
732         }
733         if (cflag & CSTOPB) {
734                 sSetStop2(cp);
735                 bits++;
736         } else {
737                 sSetStop1(cp);
738         }
739
740         if (cflag & PARENB) {
741                 sEnParity(cp);
742                 bits++;
743                 if (cflag & PARODD) {
744                         sSetOddParity(cp);
745                 } else {
746                         sSetEvenParity(cp);
747                 }
748         } else {
749                 sDisParity(cp);
750         }
751
752         /* baud rate */
753         baud = tty_get_baud_rate(info->tty);
754         if (!baud)
755                 baud = 9600;
756         divisor = ((rp_baud_base[info->board] + (baud >> 1)) / baud) - 1;
757         if ((divisor >= 8192 || divisor < 0) && old_termios) {
758                 baud = tty_termios_baud_rate(old_termios);
759                 if (!baud)
760                         baud = 9600;
761                 divisor = (rp_baud_base[info->board] / baud) - 1;
762         }
763         if (divisor >= 8192 || divisor < 0) {
764                 baud = 9600;
765                 divisor = (rp_baud_base[info->board] / baud) - 1;
766         }
767         info->cps = baud / bits;
768         sSetBaud(cp, divisor);
769
770         /* FIXME: Should really back compute a baud rate from the divisor */
771         tty_encode_baud_rate(info->tty, baud, baud);
772
773         if (cflag & CRTSCTS) {
774                 info->intmask |= DELTA_CTS;
775                 sEnCTSFlowCtl(cp);
776         } else {
777                 info->intmask &= ~DELTA_CTS;
778                 sDisCTSFlowCtl(cp);
779         }
780         if (cflag & CLOCAL) {
781                 info->intmask &= ~DELTA_CD;
782         } else {
783                 spin_lock_irqsave(&info->slock, flags);
784                 if (sGetChanStatus(cp) & CD_ACT)
785                         info->cd_status = 1;
786                 else
787                         info->cd_status = 0;
788                 info->intmask |= DELTA_CD;
789                 spin_unlock_irqrestore(&info->slock, flags);
790         }
791
792         /*
793          * Handle software flow control in the board
794          */
795 #ifdef ROCKET_SOFT_FLOW
796         if (I_IXON(info->tty)) {
797                 sEnTxSoftFlowCtl(cp);
798                 if (I_IXANY(info->tty)) {
799                         sEnIXANY(cp);
800                 } else {
801                         sDisIXANY(cp);
802                 }
803                 sSetTxXONChar(cp, START_CHAR(info->tty));
804                 sSetTxXOFFChar(cp, STOP_CHAR(info->tty));
805         } else {
806                 sDisTxSoftFlowCtl(cp);
807                 sDisIXANY(cp);
808                 sClrTxXOFF(cp);
809         }
810 #endif
811
812         /*
813          * Set up ignore/read mask words
814          */
815         info->read_status_mask = STMRCVROVRH | 0xFF;
816         if (I_INPCK(info->tty))
817                 info->read_status_mask |= STMFRAMEH | STMPARITYH;
818         if (I_BRKINT(info->tty) || I_PARMRK(info->tty))
819                 info->read_status_mask |= STMBREAKH;
820
821         /*
822          * Characters to ignore
823          */
824         info->ignore_status_mask = 0;
825         if (I_IGNPAR(info->tty))
826                 info->ignore_status_mask |= STMFRAMEH | STMPARITYH;
827         if (I_IGNBRK(info->tty)) {
828                 info->ignore_status_mask |= STMBREAKH;
829                 /*
830                  * If we're ignoring parity and break indicators,
831                  * ignore overruns too.  (For real raw support).
832                  */
833                 if (I_IGNPAR(info->tty))
834                         info->ignore_status_mask |= STMRCVROVRH;
835         }
836
837         rocketMode = info->flags & ROCKET_MODE_MASK;
838
839         if ((info->flags & ROCKET_RTS_TOGGLE)
840             || (rocketMode == ROCKET_MODE_RS485))
841                 sEnRTSToggle(cp);
842         else
843                 sDisRTSToggle(cp);
844
845         sSetRTS(&info->channel);
846
847         if (cp->CtlP->boardType == ROCKET_TYPE_PC104) {
848                 switch (rocketMode) {
849                 case ROCKET_MODE_RS485:
850                         sSetInterfaceMode(cp, InterfaceModeRS485);
851                         break;
852                 case ROCKET_MODE_RS422:
853                         sSetInterfaceMode(cp, InterfaceModeRS422);
854                         break;
855                 case ROCKET_MODE_RS232:
856                 default:
857                         if (info->flags & ROCKET_RTS_TOGGLE)
858                                 sSetInterfaceMode(cp, InterfaceModeRS232T);
859                         else
860                                 sSetInterfaceMode(cp, InterfaceModeRS232);
861                         break;
862                 }
863         }
864 }
865
866 /*  info->count is considered critical, protected by spinlocks.  */
867 static int block_til_ready(struct tty_struct *tty, struct file *filp,
868                            struct r_port *info)
869 {
870         DECLARE_WAITQUEUE(wait, current);
871         int retval;
872         int do_clocal = 0, extra_count = 0;
873         unsigned long flags;
874
875         /*
876          * If the device is in the middle of being closed, then block
877          * until it's done, and then try again.
878          */
879         if (tty_hung_up_p(filp))
880                 return ((info->flags & ROCKET_HUP_NOTIFY) ? -EAGAIN : -ERESTARTSYS);
881         if (info->flags & ROCKET_CLOSING) {
882                 if (wait_for_completion_interruptible(&info->close_wait))
883                         return -ERESTARTSYS;
884                 return ((info->flags & ROCKET_HUP_NOTIFY) ? -EAGAIN : -ERESTARTSYS);
885         }
886
887         /*
888          * If non-blocking mode is set, or the port is not enabled,
889          * then make the check up front and then exit.
890          */
891         if ((filp->f_flags & O_NONBLOCK) || (tty->flags & (1 << TTY_IO_ERROR))) {
892                 info->flags |= ROCKET_NORMAL_ACTIVE;
893                 return 0;
894         }
895         if (tty->termios->c_cflag & CLOCAL)
896                 do_clocal = 1;
897
898         /*
899          * Block waiting for the carrier detect and the line to become free.  While we are in
900          * this loop, info->count is dropped by one, so that rp_close() knows when to free things.  
901          * We restore it upon exit, either normal or abnormal.
902          */
903         retval = 0;
904         add_wait_queue(&info->open_wait, &wait);
905 #ifdef ROCKET_DEBUG_OPEN
906         printk(KERN_INFO "block_til_ready before block: ttyR%d, count = %d\n", info->line, info->count);
907 #endif
908         spin_lock_irqsave(&info->slock, flags);
909
910 #ifdef ROCKET_DISABLE_SIMUSAGE
911         info->flags |= ROCKET_NORMAL_ACTIVE;
912 #else
913         if (!tty_hung_up_p(filp)) {
914                 extra_count = 1;
915                 info->count--;
916         }
917 #endif
918         info->blocked_open++;
919
920         spin_unlock_irqrestore(&info->slock, flags);
921
922         while (1) {
923                 if (tty->termios->c_cflag & CBAUD) {
924                         sSetDTR(&info->channel);
925                         sSetRTS(&info->channel);
926                 }
927                 set_current_state(TASK_INTERRUPTIBLE);
928                 if (tty_hung_up_p(filp) || !(info->flags & ROCKET_INITIALIZED)) {
929                         if (info->flags & ROCKET_HUP_NOTIFY)
930                                 retval = -EAGAIN;
931                         else
932                                 retval = -ERESTARTSYS;
933                         break;
934                 }
935                 if (!(info->flags & ROCKET_CLOSING) && (do_clocal || (sGetChanStatusLo(&info->channel) & CD_ACT)))
936                         break;
937                 if (signal_pending(current)) {
938                         retval = -ERESTARTSYS;
939                         break;
940                 }
941 #ifdef ROCKET_DEBUG_OPEN
942                 printk(KERN_INFO "block_til_ready blocking: ttyR%d, count = %d, flags=0x%0x\n",
943                      info->line, info->count, info->flags);
944 #endif
945                 schedule();     /*  Don't hold spinlock here, will hang PC */
946         }
947         __set_current_state(TASK_RUNNING);
948         remove_wait_queue(&info->open_wait, &wait);
949
950         spin_lock_irqsave(&info->slock, flags);
951
952         if (extra_count)
953                 info->count++;
954         info->blocked_open--;
955
956         spin_unlock_irqrestore(&info->slock, flags);
957
958 #ifdef ROCKET_DEBUG_OPEN
959         printk(KERN_INFO "block_til_ready after blocking: ttyR%d, count = %d\n",
960                info->line, info->count);
961 #endif
962         if (retval)
963                 return retval;
964         info->flags |= ROCKET_NORMAL_ACTIVE;
965         return 0;
966 }
967
968 /*
969  *  Exception handler that opens a serial port.  Creates xmit_buf storage, fills in 
970  *  port's r_port struct.  Initializes the port hardware.  
971  */
972 static int rp_open(struct tty_struct *tty, struct file *filp)
973 {
974         struct r_port *info;
975         int line = 0, retval;
976         CHANNEL_t *cp;
977         unsigned long page;
978
979         line = tty->index;
980         if ((line < 0) || (line >= MAX_RP_PORTS) || ((info = rp_table[line]) == NULL))
981                 return -ENXIO;
982
983         page = __get_free_page(GFP_KERNEL);
984         if (!page)
985                 return -ENOMEM;
986
987         if (info->flags & ROCKET_CLOSING) {
988                 retval = wait_for_completion_interruptible(&info->close_wait);
989                 free_page(page);
990                 if (retval)
991                         return retval;
992                 return ((info->flags & ROCKET_HUP_NOTIFY) ? -EAGAIN : -ERESTARTSYS);
993         }
994
995         /*
996          * We must not sleep from here until the port is marked fully in use.
997          */
998         if (info->xmit_buf)
999                 free_page(page);
1000         else
1001                 info->xmit_buf = (unsigned char *) page;
1002
1003         tty->driver_data = info;
1004         info->tty = tty;
1005
1006         if (info->count++ == 0) {
1007                 atomic_inc(&rp_num_ports_open);
1008
1009 #ifdef ROCKET_DEBUG_OPEN
1010                 printk(KERN_INFO "rocket mod++ = %d...\n",
1011                                 atomic_read(&rp_num_ports_open));
1012 #endif
1013         }
1014 #ifdef ROCKET_DEBUG_OPEN
1015         printk(KERN_INFO "rp_open ttyR%d, count=%d\n", info->line, info->count);
1016 #endif
1017
1018         /*
1019          * Info->count is now 1; so it's safe to sleep now.
1020          */
1021         if ((info->flags & ROCKET_INITIALIZED) == 0) {
1022                 cp = &info->channel;
1023                 sSetRxTrigger(cp, TRIG_1);
1024                 if (sGetChanStatus(cp) & CD_ACT)
1025                         info->cd_status = 1;
1026                 else
1027                         info->cd_status = 0;
1028                 sDisRxStatusMode(cp);
1029                 sFlushRxFIFO(cp);
1030                 sFlushTxFIFO(cp);
1031
1032                 sEnInterrupts(cp, (TXINT_EN | MCINT_EN | RXINT_EN | SRCINT_EN | CHANINT_EN));
1033                 sSetRxTrigger(cp, TRIG_1);
1034
1035                 sGetChanStatus(cp);
1036                 sDisRxStatusMode(cp);
1037                 sClrTxXOFF(cp);
1038
1039                 sDisCTSFlowCtl(cp);
1040                 sDisTxSoftFlowCtl(cp);
1041
1042                 sEnRxFIFO(cp);
1043                 sEnTransmit(cp);
1044
1045                 info->flags |= ROCKET_INITIALIZED;
1046
1047                 /*
1048                  * Set up the tty->alt_speed kludge
1049                  */
1050                 if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_HI)
1051                         info->tty->alt_speed = 57600;
1052                 if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_VHI)
1053                         info->tty->alt_speed = 115200;
1054                 if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_SHI)
1055                         info->tty->alt_speed = 230400;
1056                 if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_WARP)
1057                         info->tty->alt_speed = 460800;
1058
1059                 configure_r_port(info, NULL);
1060                 if (tty->termios->c_cflag & CBAUD) {
1061                         sSetDTR(cp);
1062                         sSetRTS(cp);
1063                 }
1064         }
1065         /*  Starts (or resets) the maint polling loop */
1066         mod_timer(&rocket_timer, jiffies + POLL_PERIOD);
1067
1068         retval = block_til_ready(tty, filp, info);
1069         if (retval) {
1070 #ifdef ROCKET_DEBUG_OPEN
1071                 printk(KERN_INFO "rp_open returning after block_til_ready with %d\n", retval);
1072 #endif
1073                 return retval;
1074         }
1075         return 0;
1076 }
1077
1078 /*
1079  *  Exception handler that closes a serial port. info->count is considered critical. 
1080  */
1081 static void rp_close(struct tty_struct *tty, struct file *filp)
1082 {
1083         struct r_port *info = (struct r_port *) tty->driver_data;
1084         unsigned long flags;
1085         int timeout;
1086         CHANNEL_t *cp;
1087         
1088         if (rocket_paranoia_check(info, "rp_close"))
1089                 return;
1090
1091 #ifdef ROCKET_DEBUG_OPEN
1092         printk(KERN_INFO "rp_close ttyR%d, count = %d\n", info->line, info->count);
1093 #endif
1094
1095         if (tty_hung_up_p(filp))
1096                 return;
1097         spin_lock_irqsave(&info->slock, flags);
1098
1099         if ((tty->count == 1) && (info->count != 1)) {
1100                 /*
1101                  * Uh, oh.  tty->count is 1, which means that the tty
1102                  * structure will be freed.  Info->count should always
1103                  * be one in these conditions.  If it's greater than
1104                  * one, we've got real problems, since it means the
1105                  * serial port won't be shutdown.
1106                  */
1107                 printk(KERN_WARNING "rp_close: bad serial port count; "
1108                         "tty->count is 1, info->count is %d\n", info->count);
1109                 info->count = 1;
1110         }
1111         if (--info->count < 0) {
1112                 printk(KERN_WARNING "rp_close: bad serial port count for "
1113                                 "ttyR%d: %d\n", info->line, info->count);
1114                 info->count = 0;
1115         }
1116         if (info->count) {
1117                 spin_unlock_irqrestore(&info->slock, flags);
1118                 return;
1119         }
1120         info->flags |= ROCKET_CLOSING;
1121         spin_unlock_irqrestore(&info->slock, flags);
1122
1123         cp = &info->channel;
1124
1125         /*
1126          * Notify the line discpline to only process XON/XOFF characters
1127          */
1128         tty->closing = 1;
1129
1130         /*
1131          * If transmission was throttled by the application request,
1132          * just flush the xmit buffer.
1133          */
1134         if (tty->flow_stopped)
1135                 rp_flush_buffer(tty);
1136
1137         /*
1138          * Wait for the transmit buffer to clear
1139          */
1140         if (info->closing_wait != ROCKET_CLOSING_WAIT_NONE)
1141                 tty_wait_until_sent(tty, info->closing_wait);
1142         /*
1143          * Before we drop DTR, make sure the UART transmitter
1144          * has completely drained; this is especially
1145          * important if there is a transmit FIFO!
1146          */
1147         timeout = (sGetTxCnt(cp) + 1) * HZ / info->cps;
1148         if (timeout == 0)
1149                 timeout = 1;
1150         rp_wait_until_sent(tty, timeout);
1151         clear_bit((info->aiop * 8) + info->chan, (void *) &xmit_flags[info->board]);
1152
1153         sDisTransmit(cp);
1154         sDisInterrupts(cp, (TXINT_EN | MCINT_EN | RXINT_EN | SRCINT_EN | CHANINT_EN));
1155         sDisCTSFlowCtl(cp);
1156         sDisTxSoftFlowCtl(cp);
1157         sClrTxXOFF(cp);
1158         sFlushRxFIFO(cp);
1159         sFlushTxFIFO(cp);
1160         sClrRTS(cp);
1161         if (C_HUPCL(tty))
1162                 sClrDTR(cp);
1163
1164         rp_flush_buffer(tty);
1165                 
1166         tty_ldisc_flush(tty);
1167
1168         clear_bit((info->aiop * 8) + info->chan, (void *) &xmit_flags[info->board]);
1169
1170         if (info->blocked_open) {
1171                 if (info->close_delay) {
1172                         msleep_interruptible(jiffies_to_msecs(info->close_delay));
1173                 }
1174                 wake_up_interruptible(&info->open_wait);
1175         } else {
1176                 if (info->xmit_buf) {
1177                         free_page((unsigned long) info->xmit_buf);
1178                         info->xmit_buf = NULL;
1179                 }
1180         }
1181         info->flags &= ~(ROCKET_INITIALIZED | ROCKET_CLOSING | ROCKET_NORMAL_ACTIVE);
1182         tty->closing = 0;
1183         complete_all(&info->close_wait);
1184         atomic_dec(&rp_num_ports_open);
1185
1186 #ifdef ROCKET_DEBUG_OPEN
1187         printk(KERN_INFO "rocket mod-- = %d...\n",
1188                         atomic_read(&rp_num_ports_open));
1189         printk(KERN_INFO "rp_close ttyR%d complete shutdown\n", info->line);
1190 #endif
1191
1192 }
1193
1194 static void rp_set_termios(struct tty_struct *tty,
1195                            struct ktermios *old_termios)
1196 {
1197         struct r_port *info = (struct r_port *) tty->driver_data;
1198         CHANNEL_t *cp;
1199         unsigned cflag;
1200
1201         if (rocket_paranoia_check(info, "rp_set_termios"))
1202                 return;
1203
1204         cflag = tty->termios->c_cflag;
1205
1206         /*
1207          * This driver doesn't support CS5 or CS6
1208          */
1209         if (((cflag & CSIZE) == CS5) || ((cflag & CSIZE) == CS6))
1210                 tty->termios->c_cflag =
1211                     ((cflag & ~CSIZE) | (old_termios->c_cflag & CSIZE));
1212         /* Or CMSPAR */
1213         tty->termios->c_cflag &= ~CMSPAR;
1214
1215         configure_r_port(info, old_termios);
1216
1217         cp = &info->channel;
1218
1219         /* Handle transition to B0 status */
1220         if ((old_termios->c_cflag & CBAUD) && !(tty->termios->c_cflag & CBAUD)) {
1221                 sClrDTR(cp);
1222                 sClrRTS(cp);
1223         }
1224
1225         /* Handle transition away from B0 status */
1226         if (!(old_termios->c_cflag & CBAUD) && (tty->termios->c_cflag & CBAUD)) {
1227                 if (!tty->hw_stopped || !(tty->termios->c_cflag & CRTSCTS))
1228                         sSetRTS(cp);
1229                 sSetDTR(cp);
1230         }
1231
1232         if ((old_termios->c_cflag & CRTSCTS) && !(tty->termios->c_cflag & CRTSCTS)) {
1233                 tty->hw_stopped = 0;
1234                 rp_start(tty);
1235         }
1236 }
1237
1238 static void rp_break(struct tty_struct *tty, int break_state)
1239 {
1240         struct r_port *info = (struct r_port *) tty->driver_data;
1241         unsigned long flags;
1242
1243         if (rocket_paranoia_check(info, "rp_break"))
1244                 return;
1245
1246         spin_lock_irqsave(&info->slock, flags);
1247         if (break_state == -1)
1248                 sSendBreak(&info->channel);
1249         else
1250                 sClrBreak(&info->channel);
1251         spin_unlock_irqrestore(&info->slock, flags);
1252 }
1253
1254 /*
1255  * sGetChanRI used to be a macro in rocket_int.h. When the functionality for
1256  * the UPCI boards was added, it was decided to make this a function because
1257  * the macro was getting too complicated. All cases except the first one
1258  * (UPCIRingInd) are taken directly from the original macro.
1259  */
1260 static int sGetChanRI(CHANNEL_T * ChP)
1261 {
1262         CONTROLLER_t *CtlP = ChP->CtlP;
1263         int ChanNum = ChP->ChanNum;
1264         int RingInd = 0;
1265
1266         if (CtlP->UPCIRingInd)
1267                 RingInd = !(sInB(CtlP->UPCIRingInd) & sBitMapSetTbl[ChanNum]);
1268         else if (CtlP->AltChanRingIndicator)
1269                 RingInd = sInB((ByteIO_t) (ChP->ChanStat + 8)) & DSR_ACT;
1270         else if (CtlP->boardType == ROCKET_TYPE_PC104)
1271                 RingInd = !(sInB(CtlP->AiopIO[3]) & sBitMapSetTbl[ChanNum]);
1272
1273         return RingInd;
1274 }
1275
1276 /********************************************************************************************/
1277 /*  Here are the routines used by rp_ioctl.  These are all called from exception handlers.  */
1278
1279 /*
1280  *  Returns the state of the serial modem control lines.  These next 2 functions 
1281  *  are the way kernel versions > 2.5 handle modem control lines rather than IOCTLs.
1282  */
1283 static int rp_tiocmget(struct tty_struct *tty, struct file *file)
1284 {
1285         struct r_port *info = (struct r_port *)tty->driver_data;
1286         unsigned int control, result, ChanStatus;
1287
1288         ChanStatus = sGetChanStatusLo(&info->channel);
1289         control = info->channel.TxControl[3];
1290         result = ((control & SET_RTS) ? TIOCM_RTS : 0) | 
1291                 ((control & SET_DTR) ?  TIOCM_DTR : 0) |
1292                 ((ChanStatus & CD_ACT) ? TIOCM_CAR : 0) |
1293                 (sGetChanRI(&info->channel) ? TIOCM_RNG : 0) |
1294                 ((ChanStatus & DSR_ACT) ? TIOCM_DSR : 0) |
1295                 ((ChanStatus & CTS_ACT) ? TIOCM_CTS : 0);
1296
1297         return result;
1298 }
1299
1300 /* 
1301  *  Sets the modem control lines
1302  */
1303 static int rp_tiocmset(struct tty_struct *tty, struct file *file,
1304                     unsigned int set, unsigned int clear)
1305 {
1306         struct r_port *info = (struct r_port *)tty->driver_data;
1307
1308         if (set & TIOCM_RTS)
1309                 info->channel.TxControl[3] |= SET_RTS;
1310         if (set & TIOCM_DTR)
1311                 info->channel.TxControl[3] |= SET_DTR;
1312         if (clear & TIOCM_RTS)
1313                 info->channel.TxControl[3] &= ~SET_RTS;
1314         if (clear & TIOCM_DTR)
1315                 info->channel.TxControl[3] &= ~SET_DTR;
1316
1317         out32(info->channel.IndexAddr, info->channel.TxControl);
1318         return 0;
1319 }
1320
1321 static int get_config(struct r_port *info, struct rocket_config __user *retinfo)
1322 {
1323         struct rocket_config tmp;
1324
1325         if (!retinfo)
1326                 return -EFAULT;
1327         memset(&tmp, 0, sizeof (tmp));
1328         tmp.line = info->line;
1329         tmp.flags = info->flags;
1330         tmp.close_delay = info->close_delay;
1331         tmp.closing_wait = info->closing_wait;
1332         tmp.port = rcktpt_io_addr[(info->line >> 5) & 3];
1333
1334         if (copy_to_user(retinfo, &tmp, sizeof (*retinfo)))
1335                 return -EFAULT;
1336         return 0;
1337 }
1338
1339 static int set_config(struct r_port *info, struct rocket_config __user *new_info)
1340 {
1341         struct rocket_config new_serial;
1342
1343         if (copy_from_user(&new_serial, new_info, sizeof (new_serial)))
1344                 return -EFAULT;
1345
1346         if (!capable(CAP_SYS_ADMIN))
1347         {
1348                 if ((new_serial.flags & ~ROCKET_USR_MASK) != (info->flags & ~ROCKET_USR_MASK))
1349                         return -EPERM;
1350                 info->flags = ((info->flags & ~ROCKET_USR_MASK) | (new_serial.flags & ROCKET_USR_MASK));
1351                 configure_r_port(info, NULL);
1352                 return 0;
1353         }
1354
1355         info->flags = ((info->flags & ~ROCKET_FLAGS) | (new_serial.flags & ROCKET_FLAGS));
1356         info->close_delay = new_serial.close_delay;
1357         info->closing_wait = new_serial.closing_wait;
1358
1359         if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_HI)
1360                 info->tty->alt_speed = 57600;
1361         if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_VHI)
1362                 info->tty->alt_speed = 115200;
1363         if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_SHI)
1364                 info->tty->alt_speed = 230400;
1365         if ((info->flags & ROCKET_SPD_MASK) == ROCKET_SPD_WARP)
1366                 info->tty->alt_speed = 460800;
1367
1368         configure_r_port(info, NULL);
1369         return 0;
1370 }
1371
1372 /*
1373  *  This function fills in a rocket_ports struct with information
1374  *  about what boards/ports are in the system.  This info is passed
1375  *  to user space.  See setrocket.c where the info is used to create
1376  *  the /dev/ttyRx ports.
1377  */
1378 static int get_ports(struct r_port *info, struct rocket_ports __user *retports)
1379 {
1380         struct rocket_ports tmp;
1381         int board;
1382
1383         if (!retports)
1384                 return -EFAULT;
1385         memset(&tmp, 0, sizeof (tmp));
1386         tmp.tty_major = rocket_driver->major;
1387
1388         for (board = 0; board < 4; board++) {
1389                 tmp.rocketModel[board].model = rocketModel[board].model;
1390                 strcpy(tmp.rocketModel[board].modelString, rocketModel[board].modelString);
1391                 tmp.rocketModel[board].numPorts = rocketModel[board].numPorts;
1392                 tmp.rocketModel[board].loadrm2 = rocketModel[board].loadrm2;
1393                 tmp.rocketModel[board].startingPortNumber = rocketModel[board].startingPortNumber;
1394         }
1395         if (copy_to_user(retports, &tmp, sizeof (*retports)))
1396                 return -EFAULT;
1397         return 0;
1398 }
1399
1400 static int reset_rm2(struct r_port *info, void __user *arg)
1401 {
1402         int reset;
1403
1404         if (!capable(CAP_SYS_ADMIN))
1405                 return -EPERM;
1406
1407         if (copy_from_user(&reset, arg, sizeof (int)))
1408                 return -EFAULT;
1409         if (reset)
1410                 reset = 1;
1411
1412         if (rcktpt_type[info->board] != ROCKET_TYPE_MODEMII &&
1413             rcktpt_type[info->board] != ROCKET_TYPE_MODEMIII)
1414                 return -EINVAL;
1415
1416         if (info->ctlp->BusType == isISA)
1417                 sModemReset(info->ctlp, info->chan, reset);
1418         else
1419                 sPCIModemReset(info->ctlp, info->chan, reset);
1420
1421         return 0;
1422 }
1423
1424 static int get_version(struct r_port *info, struct rocket_version __user *retvers)
1425 {
1426         if (copy_to_user(retvers, &driver_version, sizeof (*retvers)))
1427                 return -EFAULT;
1428         return 0;
1429 }
1430
1431 /*  IOCTL call handler into the driver */
1432 static int rp_ioctl(struct tty_struct *tty, struct file *file,
1433                     unsigned int cmd, unsigned long arg)
1434 {
1435         struct r_port *info = (struct r_port *) tty->driver_data;
1436         void __user *argp = (void __user *)arg;
1437         int ret = 0;
1438
1439         if (cmd != RCKP_GET_PORTS && rocket_paranoia_check(info, "rp_ioctl"))
1440                 return -ENXIO;
1441
1442         lock_kernel();
1443
1444         switch (cmd) {
1445         case RCKP_GET_STRUCT:
1446                 if (copy_to_user(argp, info, sizeof (struct r_port)))
1447                         ret = -EFAULT;
1448                 break;
1449         case RCKP_GET_CONFIG:
1450                 ret = get_config(info, argp);
1451                 break;
1452         case RCKP_SET_CONFIG:
1453                 ret = set_config(info, argp);
1454                 break;
1455         case RCKP_GET_PORTS:
1456                 ret = get_ports(info, argp);
1457                 break;
1458         case RCKP_RESET_RM2:
1459                 ret = reset_rm2(info, argp);
1460                 break;
1461         case RCKP_GET_VERSION:
1462                 ret = get_version(info, argp);
1463                 break;
1464         default:
1465                 ret = -ENOIOCTLCMD;
1466         }
1467         unlock_kernel();
1468         return ret;
1469 }
1470
1471 static void rp_send_xchar(struct tty_struct *tty, char ch)
1472 {
1473         struct r_port *info = (struct r_port *) tty->driver_data;
1474         CHANNEL_t *cp;
1475
1476         if (rocket_paranoia_check(info, "rp_send_xchar"))
1477                 return;
1478
1479         cp = &info->channel;
1480         if (sGetTxCnt(cp))
1481                 sWriteTxPrioByte(cp, ch);
1482         else
1483                 sWriteTxByte(sGetTxRxDataIO(cp), ch);
1484 }
1485
1486 static void rp_throttle(struct tty_struct *tty)
1487 {
1488         struct r_port *info = (struct r_port *) tty->driver_data;
1489         CHANNEL_t *cp;
1490
1491 #ifdef ROCKET_DEBUG_THROTTLE
1492         printk(KERN_INFO "throttle %s: %d....\n", tty->name,
1493                tty->ldisc.chars_in_buffer(tty));
1494 #endif
1495
1496         if (rocket_paranoia_check(info, "rp_throttle"))
1497                 return;
1498
1499         cp = &info->channel;
1500         if (I_IXOFF(tty))
1501                 rp_send_xchar(tty, STOP_CHAR(tty));
1502
1503         sClrRTS(&info->channel);
1504 }
1505
1506 static void rp_unthrottle(struct tty_struct *tty)
1507 {
1508         struct r_port *info = (struct r_port *) tty->driver_data;
1509         CHANNEL_t *cp;
1510 #ifdef ROCKET_DEBUG_THROTTLE
1511         printk(KERN_INFO "unthrottle %s: %d....\n", tty->name,
1512                tty->ldisc.chars_in_buffer(tty));
1513 #endif
1514
1515         if (rocket_paranoia_check(info, "rp_throttle"))
1516                 return;
1517
1518         cp = &info->channel;
1519         if (I_IXOFF(tty))
1520                 rp_send_xchar(tty, START_CHAR(tty));
1521
1522         sSetRTS(&info->channel);
1523 }
1524
1525 /*
1526  * ------------------------------------------------------------
1527  * rp_stop() and rp_start()
1528  *
1529  * This routines are called before setting or resetting tty->stopped.
1530  * They enable or disable transmitter interrupts, as necessary.
1531  * ------------------------------------------------------------
1532  */
1533 static void rp_stop(struct tty_struct *tty)
1534 {
1535         struct r_port *info = (struct r_port *) tty->driver_data;
1536
1537 #ifdef ROCKET_DEBUG_FLOW
1538         printk(KERN_INFO "stop %s: %d %d....\n", tty->name,
1539                info->xmit_cnt, info->xmit_fifo_room);
1540 #endif
1541
1542         if (rocket_paranoia_check(info, "rp_stop"))
1543                 return;
1544
1545         if (sGetTxCnt(&info->channel))
1546                 sDisTransmit(&info->channel);
1547 }
1548
1549 static void rp_start(struct tty_struct *tty)
1550 {
1551         struct r_port *info = (struct r_port *) tty->driver_data;
1552
1553 #ifdef ROCKET_DEBUG_FLOW
1554         printk(KERN_INFO "start %s: %d %d....\n", tty->name,
1555                info->xmit_cnt, info->xmit_fifo_room);
1556 #endif
1557
1558         if (rocket_paranoia_check(info, "rp_stop"))
1559                 return;
1560
1561         sEnTransmit(&info->channel);
1562         set_bit((info->aiop * 8) + info->chan,
1563                 (void *) &xmit_flags[info->board]);
1564 }
1565
1566 /*
1567  * rp_wait_until_sent() --- wait until the transmitter is empty
1568  */
1569 static void rp_wait_until_sent(struct tty_struct *tty, int timeout)
1570 {
1571         struct r_port *info = (struct r_port *) tty->driver_data;
1572         CHANNEL_t *cp;
1573         unsigned long orig_jiffies;
1574         int check_time, exit_time;
1575         int txcnt;
1576
1577         if (rocket_paranoia_check(info, "rp_wait_until_sent"))
1578                 return;
1579
1580         cp = &info->channel;
1581
1582         orig_jiffies = jiffies;
1583 #ifdef ROCKET_DEBUG_WAIT_UNTIL_SENT
1584         printk(KERN_INFO "In RP_wait_until_sent(%d) (jiff=%lu)...\n", timeout,
1585                jiffies);
1586         printk(KERN_INFO "cps=%d...\n", info->cps);
1587 #endif
1588         lock_kernel();
1589         while (1) {
1590                 txcnt = sGetTxCnt(cp);
1591                 if (!txcnt) {
1592                         if (sGetChanStatusLo(cp) & TXSHRMT)
1593                                 break;
1594                         check_time = (HZ / info->cps) / 5;
1595                 } else {
1596                         check_time = HZ * txcnt / info->cps;
1597                 }
1598                 if (timeout) {
1599                         exit_time = orig_jiffies + timeout - jiffies;
1600                         if (exit_time <= 0)
1601                                 break;
1602                         if (exit_time < check_time)
1603                                 check_time = exit_time;
1604                 }
1605                 if (check_time == 0)
1606                         check_time = 1;
1607 #ifdef ROCKET_DEBUG_WAIT_UNTIL_SENT
1608                 printk(KERN_INFO "txcnt = %d (jiff=%lu,check=%d)...\n", txcnt,
1609                                 jiffies, check_time);
1610 #endif
1611                 msleep_interruptible(jiffies_to_msecs(check_time));
1612                 if (signal_pending(current))
1613                         break;
1614         }
1615         __set_current_state(TASK_RUNNING);
1616         unlock_kernel();
1617 #ifdef ROCKET_DEBUG_WAIT_UNTIL_SENT
1618         printk(KERN_INFO "txcnt = %d (jiff=%lu)...done\n", txcnt, jiffies);
1619 #endif
1620 }
1621
1622 /*
1623  * rp_hangup() --- called by tty_hangup() when a hangup is signaled.
1624  */
1625 static void rp_hangup(struct tty_struct *tty)
1626 {
1627         CHANNEL_t *cp;
1628         struct r_port *info = (struct r_port *) tty->driver_data;
1629
1630         if (rocket_paranoia_check(info, "rp_hangup"))
1631                 return;
1632
1633 #if (defined(ROCKET_DEBUG_OPEN) || defined(ROCKET_DEBUG_HANGUP))
1634         printk(KERN_INFO "rp_hangup of ttyR%d...\n", info->line);
1635 #endif
1636         rp_flush_buffer(tty);
1637         if (info->flags & ROCKET_CLOSING)
1638                 return;
1639         if (info->count) 
1640                 atomic_dec(&rp_num_ports_open);
1641         clear_bit((info->aiop * 8) + info->chan, (void *) &xmit_flags[info->board]);
1642
1643         info->count = 0;
1644         info->flags &= ~ROCKET_NORMAL_ACTIVE;
1645         info->tty = NULL;
1646
1647         cp = &info->channel;
1648         sDisRxFIFO(cp);
1649         sDisTransmit(cp);
1650         sDisInterrupts(cp, (TXINT_EN | MCINT_EN | RXINT_EN | SRCINT_EN | CHANINT_EN));
1651         sDisCTSFlowCtl(cp);
1652         sDisTxSoftFlowCtl(cp);
1653         sClrTxXOFF(cp);
1654         info->flags &= ~ROCKET_INITIALIZED;
1655
1656         wake_up_interruptible(&info->open_wait);
1657 }
1658
1659 /*
1660  *  Exception handler - write char routine.  The RocketPort driver uses a
1661  *  double-buffering strategy, with the twist that if the in-memory CPU
1662  *  buffer is empty, and there's space in the transmit FIFO, the
1663  *  writing routines will write directly to transmit FIFO.
1664  *  Write buffer and counters protected by spinlocks
1665  */
1666 static void rp_put_char(struct tty_struct *tty, unsigned char ch)
1667 {
1668         struct r_port *info = (struct r_port *) tty->driver_data;
1669         CHANNEL_t *cp;
1670         unsigned long flags;
1671
1672         if (rocket_paranoia_check(info, "rp_put_char"))
1673                 return;
1674
1675         /*
1676          * Grab the port write mutex, locking out other processes that try to
1677          * write to this port
1678          */
1679         mutex_lock(&info->write_mtx);
1680
1681 #ifdef ROCKET_DEBUG_WRITE
1682         printk(KERN_INFO "rp_put_char %c...\n", ch);
1683 #endif
1684
1685         spin_lock_irqsave(&info->slock, flags);
1686         cp = &info->channel;
1687
1688         if (!tty->stopped && !tty->hw_stopped && info->xmit_fifo_room == 0)
1689                 info->xmit_fifo_room = TXFIFO_SIZE - sGetTxCnt(cp);
1690
1691         if (tty->stopped || tty->hw_stopped || info->xmit_fifo_room == 0 || info->xmit_cnt != 0) {
1692                 info->xmit_buf[info->xmit_head++] = ch;
1693                 info->xmit_head &= XMIT_BUF_SIZE - 1;
1694                 info->xmit_cnt++;
1695                 set_bit((info->aiop * 8) + info->chan, (void *) &xmit_flags[info->board]);
1696         } else {
1697                 sOutB(sGetTxRxDataIO(cp), ch);
1698                 info->xmit_fifo_room--;
1699         }
1700         spin_unlock_irqrestore(&info->slock, flags);
1701         mutex_unlock(&info->write_mtx);
1702 }
1703
1704 /*
1705  *  Exception handler - write routine, called when user app writes to the device.
1706  *  A per port write mutex is used to protect from another process writing to
1707  *  this port at the same time.  This other process could be running on the other CPU
1708  *  or get control of the CPU if the copy_from_user() blocks due to a page fault (swapped out). 
1709  *  Spinlocks protect the info xmit members.
1710  */
1711 static int rp_write(struct tty_struct *tty,
1712                     const unsigned char *buf, int count)
1713 {
1714         struct r_port *info = (struct r_port *) tty->driver_data;
1715         CHANNEL_t *cp;
1716         const unsigned char *b;
1717         int c, retval = 0;
1718         unsigned long flags;
1719
1720         if (count <= 0 || rocket_paranoia_check(info, "rp_write"))
1721                 return 0;
1722
1723         if (mutex_lock_interruptible(&info->write_mtx))
1724                 return -ERESTARTSYS;
1725
1726 #ifdef ROCKET_DEBUG_WRITE
1727         printk(KERN_INFO "rp_write %d chars...\n", count);
1728 #endif
1729         cp = &info->channel;
1730
1731         if (!tty->stopped && !tty->hw_stopped && info->xmit_fifo_room < count)
1732                 info->xmit_fifo_room = TXFIFO_SIZE - sGetTxCnt(cp);
1733
1734         /*
1735          *  If the write queue for the port is empty, and there is FIFO space, stuff bytes 
1736          *  into FIFO.  Use the write queue for temp storage.
1737          */
1738         if (!tty->stopped && !tty->hw_stopped && info->xmit_cnt == 0 && info->xmit_fifo_room > 0) {
1739                 c = min(count, info->xmit_fifo_room);
1740                 b = buf;
1741
1742                 /*  Push data into FIFO, 2 bytes at a time */
1743                 sOutStrW(sGetTxRxDataIO(cp), (unsigned short *) b, c / 2);
1744
1745                 /*  If there is a byte remaining, write it */
1746                 if (c & 1)
1747                         sOutB(sGetTxRxDataIO(cp), b[c - 1]);
1748
1749                 retval += c;
1750                 buf += c;
1751                 count -= c;
1752
1753                 spin_lock_irqsave(&info->slock, flags);
1754                 info->xmit_fifo_room -= c;
1755                 spin_unlock_irqrestore(&info->slock, flags);
1756         }
1757
1758         /* If count is zero, we wrote it all and are done */
1759         if (!count)
1760                 goto end;
1761
1762         /*  Write remaining data into the port's xmit_buf */
1763         while (1) {
1764                 if (!info->tty)         /* Seemingly obligatory check... */
1765                         goto end;
1766                 c = min(count, XMIT_BUF_SIZE - info->xmit_cnt - 1);
1767                 c = min(c, XMIT_BUF_SIZE - info->xmit_head);
1768                 if (c <= 0)
1769                         break;
1770
1771                 b = buf;
1772                 memcpy(info->xmit_buf + info->xmit_head, b, c);
1773
1774                 spin_lock_irqsave(&info->slock, flags);
1775                 info->xmit_head =
1776                     (info->xmit_head + c) & (XMIT_BUF_SIZE - 1);
1777                 info->xmit_cnt += c;
1778                 spin_unlock_irqrestore(&info->slock, flags);
1779
1780                 buf += c;
1781                 count -= c;
1782                 retval += c;
1783         }
1784
1785         if ((retval > 0) && !tty->stopped && !tty->hw_stopped)
1786                 set_bit((info->aiop * 8) + info->chan, (void *) &xmit_flags[info->board]);
1787         
1788 end:
1789         if (info->xmit_cnt < WAKEUP_CHARS) {
1790                 tty_wakeup(tty);
1791 #ifdef ROCKETPORT_HAVE_POLL_WAIT
1792                 wake_up_interruptible(&tty->poll_wait);
1793 #endif
1794         }
1795         mutex_unlock(&info->write_mtx);
1796         return retval;
1797 }
1798
1799 /*
1800  * Return the number of characters that can be sent.  We estimate
1801  * only using the in-memory transmit buffer only, and ignore the
1802  * potential space in the transmit FIFO.
1803  */
1804 static int rp_write_room(struct tty_struct *tty)
1805 {
1806         struct r_port *info = (struct r_port *) tty->driver_data;
1807         int ret;
1808
1809         if (rocket_paranoia_check(info, "rp_write_room"))
1810                 return 0;
1811
1812         ret = XMIT_BUF_SIZE - info->xmit_cnt - 1;
1813         if (ret < 0)
1814                 ret = 0;
1815 #ifdef ROCKET_DEBUG_WRITE
1816         printk(KERN_INFO "rp_write_room returns %d...\n", ret);
1817 #endif
1818         return ret;
1819 }
1820
1821 /*
1822  * Return the number of characters in the buffer.  Again, this only
1823  * counts those characters in the in-memory transmit buffer.
1824  */
1825 static int rp_chars_in_buffer(struct tty_struct *tty)
1826 {
1827         struct r_port *info = (struct r_port *) tty->driver_data;
1828         CHANNEL_t *cp;
1829
1830         if (rocket_paranoia_check(info, "rp_chars_in_buffer"))
1831                 return 0;
1832
1833         cp = &info->channel;
1834
1835 #ifdef ROCKET_DEBUG_WRITE
1836         printk(KERN_INFO "rp_chars_in_buffer returns %d...\n", info->xmit_cnt);
1837 #endif
1838         return info->xmit_cnt;
1839 }
1840
1841 /*
1842  *  Flushes the TX fifo for a port, deletes data in the xmit_buf stored in the
1843  *  r_port struct for the port.  Note that spinlock are used to protect info members,
1844  *  do not call this function if the spinlock is already held.
1845  */
1846 static void rp_flush_buffer(struct tty_struct *tty)
1847 {
1848         struct r_port *info = (struct r_port *) tty->driver_data;
1849         CHANNEL_t *cp;
1850         unsigned long flags;
1851
1852         if (rocket_paranoia_check(info, "rp_flush_buffer"))
1853                 return;
1854
1855         spin_lock_irqsave(&info->slock, flags);
1856         info->xmit_cnt = info->xmit_head = info->xmit_tail = 0;
1857         spin_unlock_irqrestore(&info->slock, flags);
1858
1859 #ifdef ROCKETPORT_HAVE_POLL_WAIT
1860         wake_up_interruptible(&tty->poll_wait);
1861 #endif
1862         tty_wakeup(tty);
1863
1864         cp = &info->channel;
1865         sFlushTxFIFO(cp);
1866 }
1867
1868 #ifdef CONFIG_PCI
1869
1870 static struct pci_device_id __devinitdata rocket_pci_ids[] = {
1871         { PCI_DEVICE(PCI_VENDOR_ID_RP, PCI_ANY_ID) },
1872         { }
1873 };
1874 MODULE_DEVICE_TABLE(pci, rocket_pci_ids);
1875
1876 /*
1877  *  Called when a PCI card is found.  Retrieves and stores model information,
1878  *  init's aiopic and serial port hardware.
1879  *  Inputs:  i is the board number (0-n)
1880  */
1881 static __init int register_PCI(int i, struct pci_dev *dev)
1882 {
1883         int num_aiops, aiop, max_num_aiops, num_chan, chan;
1884         unsigned int aiopio[MAX_AIOPS_PER_BOARD];
1885         char *str, *board_type;
1886         CONTROLLER_t *ctlp;
1887
1888         int fast_clock = 0;
1889         int altChanRingIndicator = 0;
1890         int ports_per_aiop = 8;
1891         WordIO_t ConfigIO = 0;
1892         ByteIO_t UPCIRingInd = 0;
1893
1894         if (!dev || pci_enable_device(dev))
1895                 return 0;
1896
1897         rcktpt_io_addr[i] = pci_resource_start(dev, 0);
1898
1899         rcktpt_type[i] = ROCKET_TYPE_NORMAL;
1900         rocketModel[i].loadrm2 = 0;
1901         rocketModel[i].startingPortNumber = nextLineNumber;
1902
1903         /*  Depending on the model, set up some config variables */
1904         switch (dev->device) {
1905         case PCI_DEVICE_ID_RP4QUAD:
1906                 str = "Quadcable";
1907                 max_num_aiops = 1;
1908                 ports_per_aiop = 4;
1909                 rocketModel[i].model = MODEL_RP4QUAD;
1910                 strcpy(rocketModel[i].modelString, "RocketPort 4 port w/quad cable");
1911                 rocketModel[i].numPorts = 4;
1912                 break;
1913         case PCI_DEVICE_ID_RP8OCTA:
1914                 str = "Octacable";
1915                 max_num_aiops = 1;
1916                 rocketModel[i].model = MODEL_RP8OCTA;
1917                 strcpy(rocketModel[i].modelString, "RocketPort 8 port w/octa cable");
1918                 rocketModel[i].numPorts = 8;
1919                 break;
1920         case PCI_DEVICE_ID_URP8OCTA:
1921                 str = "Octacable";
1922                 max_num_aiops = 1;
1923                 rocketModel[i].model = MODEL_UPCI_RP8OCTA;
1924                 strcpy(rocketModel[i].modelString, "RocketPort UPCI 8 port w/octa cable");
1925                 rocketModel[i].numPorts = 8;
1926                 break;
1927         case PCI_DEVICE_ID_RP8INTF:
1928                 str = "8";
1929                 max_num_aiops = 1;
1930                 rocketModel[i].model = MODEL_RP8INTF;
1931                 strcpy(rocketModel[i].modelString, "RocketPort 8 port w/external I/F");
1932                 rocketModel[i].numPorts = 8;
1933                 break;
1934         case PCI_DEVICE_ID_URP8INTF:
1935                 str = "8";
1936                 max_num_aiops = 1;
1937                 rocketModel[i].model = MODEL_UPCI_RP8INTF;
1938                 strcpy(rocketModel[i].modelString, "RocketPort UPCI 8 port w/external I/F");
1939                 rocketModel[i].numPorts = 8;
1940                 break;
1941         case PCI_DEVICE_ID_RP8J:
1942                 str = "8J";
1943                 max_num_aiops = 1;
1944                 rocketModel[i].model = MODEL_RP8J;
1945                 strcpy(rocketModel[i].modelString, "RocketPort 8 port w/RJ11 connectors");
1946                 rocketModel[i].numPorts = 8;
1947                 break;
1948         case PCI_DEVICE_ID_RP4J:
1949                 str = "4J";
1950                 max_num_aiops = 1;
1951                 ports_per_aiop = 4;
1952                 rocketModel[i].model = MODEL_RP4J;
1953                 strcpy(rocketModel[i].modelString, "RocketPort 4 port w/RJ45 connectors");
1954                 rocketModel[i].numPorts = 4;
1955                 break;
1956         case PCI_DEVICE_ID_RP8SNI:
1957                 str = "8 (DB78 Custom)";
1958                 max_num_aiops = 1;
1959                 rocketModel[i].model = MODEL_RP8SNI;
1960                 strcpy(rocketModel[i].modelString, "RocketPort 8 port w/ custom DB78");
1961                 rocketModel[i].numPorts = 8;
1962                 break;
1963         case PCI_DEVICE_ID_RP16SNI:
1964                 str = "16 (DB78 Custom)";
1965                 max_num_aiops = 2;
1966                 rocketModel[i].model = MODEL_RP16SNI;
1967                 strcpy(rocketModel[i].modelString, "RocketPort 16 port w/ custom DB78");
1968                 rocketModel[i].numPorts = 16;
1969                 break;
1970         case PCI_DEVICE_ID_RP16INTF:
1971                 str = "16";
1972                 max_num_aiops = 2;
1973                 rocketModel[i].model = MODEL_RP16INTF;
1974                 strcpy(rocketModel[i].modelString, "RocketPort 16 port w/external I/F");
1975                 rocketModel[i].numPorts = 16;
1976                 break;
1977         case PCI_DEVICE_ID_URP16INTF:
1978                 str = "16";
1979                 max_num_aiops = 2;
1980                 rocketModel[i].model = MODEL_UPCI_RP16INTF;
1981                 strcpy(rocketModel[i].modelString, "RocketPort UPCI 16 port w/external I/F");
1982                 rocketModel[i].numPorts = 16;
1983                 break;
1984         case PCI_DEVICE_ID_CRP16INTF:
1985                 str = "16";
1986                 max_num_aiops = 2;
1987                 rocketModel[i].model = MODEL_CPCI_RP16INTF;
1988                 strcpy(rocketModel[i].modelString, "RocketPort Compact PCI 16 port w/external I/F");
1989                 rocketModel[i].numPorts = 16;
1990                 break;
1991         case PCI_DEVICE_ID_RP32INTF:
1992                 str = "32";
1993                 max_num_aiops = 4;
1994                 rocketModel[i].model = MODEL_RP32INTF;
1995                 strcpy(rocketModel[i].modelString, "RocketPort 32 port w/external I/F");
1996                 rocketModel[i].numPorts = 32;
1997                 break;
1998         case PCI_DEVICE_ID_URP32INTF:
1999                 str = "32";
2000                 max_num_aiops = 4;
2001                 rocketModel[i].model = MODEL_UPCI_RP32INTF;
2002                 strcpy(rocketModel[i].modelString, "RocketPort UPCI 32 port w/external I/F");
2003                 rocketModel[i].numPorts = 32;
2004                 break;
2005         case PCI_DEVICE_ID_RPP4:
2006                 str = "Plus Quadcable";
2007                 max_num_aiops = 1;
2008                 ports_per_aiop = 4;
2009                 altChanRingIndicator++;
2010                 fast_clock++;
2011                 rocketModel[i].model = MODEL_RPP4;
2012                 strcpy(rocketModel[i].modelString, "RocketPort Plus 4 port");
2013                 rocketModel[i].numPorts = 4;
2014                 break;
2015         case PCI_DEVICE_ID_RPP8:
2016                 str = "Plus Octacable";
2017                 max_num_aiops = 2;
2018                 ports_per_aiop = 4;
2019                 altChanRingIndicator++;
2020                 fast_clock++;
2021                 rocketModel[i].model = MODEL_RPP8;
2022                 strcpy(rocketModel[i].modelString, "RocketPort Plus 8 port");
2023                 rocketModel[i].numPorts = 8;
2024                 break;
2025         case PCI_DEVICE_ID_RP2_232:
2026                 str = "Plus 2 (RS-232)";
2027                 max_num_aiops = 1;
2028                 ports_per_aiop = 2;
2029                 altChanRingIndicator++;
2030                 fast_clock++;
2031                 rocketModel[i].model = MODEL_RP2_232;
2032                 strcpy(rocketModel[i].modelString, "RocketPort Plus 2 port RS232");
2033                 rocketModel[i].numPorts = 2;
2034                 break;
2035         case PCI_DEVICE_ID_RP2_422:
2036                 str = "Plus 2 (RS-422)";
2037                 max_num_aiops = 1;
2038                 ports_per_aiop = 2;
2039                 altChanRingIndicator++;
2040                 fast_clock++;
2041                 rocketModel[i].model = MODEL_RP2_422;
2042                 strcpy(rocketModel[i].modelString, "RocketPort Plus 2 port RS422");
2043                 rocketModel[i].numPorts = 2;
2044                 break;
2045         case PCI_DEVICE_ID_RP6M:
2046
2047                 max_num_aiops = 1;
2048                 ports_per_aiop = 6;
2049                 str = "6-port";
2050
2051                 /*  If revision is 1, the rocketmodem flash must be loaded.
2052                  *  If it is 2 it is a "socketed" version. */
2053                 if (dev->revision == 1) {
2054                         rcktpt_type[i] = ROCKET_TYPE_MODEMII;
2055                         rocketModel[i].loadrm2 = 1;
2056                 } else {
2057                         rcktpt_type[i] = ROCKET_TYPE_MODEM;
2058                 }
2059
2060                 rocketModel[i].model = MODEL_RP6M;
2061                 strcpy(rocketModel[i].modelString, "RocketModem 6 port");
2062                 rocketModel[i].numPorts = 6;
2063                 break;
2064         case PCI_DEVICE_ID_RP4M:
2065                 max_num_aiops = 1;
2066                 ports_per_aiop = 4;
2067                 str = "4-port";
2068                 if (dev->revision == 1) {
2069                         rcktpt_type[i] = ROCKET_TYPE_MODEMII;
2070                         rocketModel[i].loadrm2 = 1;
2071                 } else {
2072                         rcktpt_type[i] = ROCKET_TYPE_MODEM;
2073                 }
2074
2075                 rocketModel[i].model = MODEL_RP4M;
2076                 strcpy(rocketModel[i].modelString, "RocketModem 4 port");
2077                 rocketModel[i].numPorts = 4;
2078                 break;
2079         default:
2080                 str = "(unknown/unsupported)";
2081                 max_num_aiops = 0;
2082                 break;
2083         }
2084
2085         /*
2086          * Check for UPCI boards.
2087          */
2088
2089         switch (dev->device) {
2090         case PCI_DEVICE_ID_URP32INTF:
2091         case PCI_DEVICE_ID_URP8INTF:
2092         case PCI_DEVICE_ID_URP16INTF:
2093         case PCI_DEVICE_ID_CRP16INTF:
2094         case PCI_DEVICE_ID_URP8OCTA:
2095                 rcktpt_io_addr[i] = pci_resource_start(dev, 2);
2096                 ConfigIO = pci_resource_start(dev, 1);
2097                 if (dev->device == PCI_DEVICE_ID_URP8OCTA) {
2098                         UPCIRingInd = rcktpt_io_addr[i] + _PCI_9030_RING_IND;
2099
2100                         /*
2101                          * Check for octa or quad cable.
2102                          */
2103                         if (!
2104                             (sInW(ConfigIO + _PCI_9030_GPIO_CTRL) &
2105                              PCI_GPIO_CTRL_8PORT)) {
2106                                 str = "Quadcable";
2107                                 ports_per_aiop = 4;
2108                                 rocketModel[i].numPorts = 4;
2109                         }
2110                 }
2111                 break;
2112         case PCI_DEVICE_ID_UPCI_RM3_8PORT:
2113                 str = "8 ports";
2114                 max_num_aiops = 1;
2115                 rocketModel[i].model = MODEL_UPCI_RM3_8PORT;
2116                 strcpy(rocketModel[i].modelString, "RocketModem III 8 port");
2117                 rocketModel[i].numPorts = 8;
2118                 rcktpt_io_addr[i] = pci_resource_start(dev, 2);
2119                 UPCIRingInd = rcktpt_io_addr[i] + _PCI_9030_RING_IND;
2120                 ConfigIO = pci_resource_start(dev, 1);
2121                 rcktpt_type[i] = ROCKET_TYPE_MODEMIII;
2122                 break;
2123         case PCI_DEVICE_ID_UPCI_RM3_4PORT:
2124                 str = "4 ports";
2125                 max_num_aiops = 1;
2126                 rocketModel[i].model = MODEL_UPCI_RM3_4PORT;
2127                 strcpy(rocketModel[i].modelString, "RocketModem III 4 port");
2128                 rocketModel[i].numPorts = 4;
2129                 rcktpt_io_addr[i] = pci_resource_start(dev, 2);
2130                 UPCIRingInd = rcktpt_io_addr[i] + _PCI_9030_RING_IND;
2131                 ConfigIO = pci_resource_start(dev, 1);
2132                 rcktpt_type[i] = ROCKET_TYPE_MODEMIII;
2133                 break;
2134         default:
2135                 break;
2136         }
2137
2138         switch (rcktpt_type[i]) {
2139         case ROCKET_TYPE_MODEM:
2140                 board_type = "RocketModem";
2141                 break;
2142         case ROCKET_TYPE_MODEMII:
2143                 board_type = "RocketModem II";
2144                 break;
2145         case ROCKET_TYPE_MODEMIII:
2146                 board_type = "RocketModem III";
2147                 break;
2148         default:
2149                 board_type = "RocketPort";
2150                 break;
2151         }
2152
2153         if (fast_clock) {
2154                 sClockPrescale = 0x12;  /* mod 2 (divide by 3) */
2155                 rp_baud_base[i] = 921600;
2156         } else {
2157                 /*
2158                  * If support_low_speed is set, use the slow clock
2159                  * prescale, which supports 50 bps
2160                  */
2161                 if (support_low_speed) {
2162                         /* mod 9 (divide by 10) prescale */
2163                         sClockPrescale = 0x19;
2164                         rp_baud_base[i] = 230400;
2165                 } else {
2166                         /* mod 4 (devide by 5) prescale */
2167                         sClockPrescale = 0x14;
2168                         rp_baud_base[i] = 460800;
2169                 }
2170         }
2171
2172         for (aiop = 0; aiop < max_num_aiops; aiop++)
2173                 aiopio[aiop] = rcktpt_io_addr[i] + (aiop * 0x40);
2174         ctlp = sCtlNumToCtlPtr(i);
2175         num_aiops = sPCIInitController(ctlp, i, aiopio, max_num_aiops, ConfigIO, 0, FREQ_DIS, 0, altChanRingIndicator, UPCIRingInd);
2176         for (aiop = 0; aiop < max_num_aiops; aiop++)
2177                 ctlp->AiopNumChan[aiop] = ports_per_aiop;
2178
2179         dev_info(&dev->dev, "comtrol PCI controller #%d found at "
2180                 "address %04lx, %d AIOP(s) (%s), creating ttyR%d - %ld\n",
2181                 i, rcktpt_io_addr[i], num_aiops, rocketModel[i].modelString,
2182                 rocketModel[i].startingPortNumber,
2183                 rocketModel[i].startingPortNumber + rocketModel[i].numPorts-1);
2184
2185         if (num_aiops <= 0) {
2186                 rcktpt_io_addr[i] = 0;
2187                 return (0);
2188         }
2189         is_PCI[i] = 1;
2190
2191         /*  Reset the AIOPIC, init the serial ports */
2192         for (aiop = 0; aiop < num_aiops; aiop++) {
2193                 sResetAiopByNum(ctlp, aiop);
2194                 num_chan = ports_per_aiop;
2195                 for (chan = 0; chan < num_chan; chan++)
2196                         init_r_port(i, aiop, chan, dev);
2197         }
2198
2199         /*  Rocket modems must be reset */
2200         if ((rcktpt_type[i] == ROCKET_TYPE_MODEM) ||
2201             (rcktpt_type[i] == ROCKET_TYPE_MODEMII) ||
2202             (rcktpt_type[i] == ROCKET_TYPE_MODEMIII)) {
2203                 num_chan = ports_per_aiop;
2204                 for (chan = 0; chan < num_chan; chan++)
2205                         sPCIModemReset(ctlp, chan, 1);
2206                 msleep(500);
2207                 for (chan = 0; chan < num_chan; chan++)
2208                         sPCIModemReset(ctlp, chan, 0);
2209                 msleep(500);
2210                 rmSpeakerReset(ctlp, rocketModel[i].model);
2211         }
2212         return (1);
2213 }
2214
2215 /*
2216  *  Probes for PCI cards, inits them if found
2217  *  Input:   board_found = number of ISA boards already found, or the
2218  *           starting board number
2219  *  Returns: Number of PCI boards found
2220  */
2221 static int __init init_PCI(int boards_found)
2222 {
2223         struct pci_dev *dev = NULL;
2224         int count = 0;
2225
2226         /*  Work through the PCI device list, pulling out ours */
2227         while ((dev = pci_get_device(PCI_VENDOR_ID_RP, PCI_ANY_ID, dev))) {
2228                 if (register_PCI(count + boards_found, dev))
2229                         count++;
2230         }
2231         return (count);
2232 }
2233
2234 #endif                          /* CONFIG_PCI */
2235
2236 /*
2237  *  Probes for ISA cards
2238  *  Input:   i = the board number to look for
2239  *  Returns: 1 if board found, 0 else
2240  */
2241 static int __init init_ISA(int i)
2242 {
2243         int num_aiops, num_chan = 0, total_num_chan = 0;
2244         int aiop, chan;
2245         unsigned int aiopio[MAX_AIOPS_PER_BOARD];
2246         CONTROLLER_t *ctlp;
2247         char *type_string;
2248
2249         /*  If io_addr is zero, no board configured */
2250         if (rcktpt_io_addr[i] == 0)
2251                 return (0);
2252
2253         /*  Reserve the IO region */
2254         if (!request_region(rcktpt_io_addr[i], 64, "Comtrol RocketPort")) {
2255                 printk(KERN_ERR "Unable to reserve IO region for configured "
2256                                 "ISA RocketPort at address 0x%lx, board not "
2257                                 "installed...\n", rcktpt_io_addr[i]);
2258                 rcktpt_io_addr[i] = 0;
2259                 return (0);
2260         }
2261
2262         ctlp = sCtlNumToCtlPtr(i);
2263
2264         ctlp->boardType = rcktpt_type[i];
2265
2266         switch (rcktpt_type[i]) {
2267         case ROCKET_TYPE_PC104:
2268                 type_string = "(PC104)";
2269                 break;
2270         case ROCKET_TYPE_MODEM:
2271                 type_string = "(RocketModem)";
2272                 break;
2273         case ROCKET_TYPE_MODEMII:
2274                 type_string = "(RocketModem II)";
2275                 break;
2276         default:
2277                 type_string = "";
2278                 break;
2279         }
2280
2281         /*
2282          * If support_low_speed is set, use the slow clock prescale,
2283          * which supports 50 bps
2284          */
2285         if (support_low_speed) {
2286                 sClockPrescale = 0x19;  /* mod 9 (divide by 10) prescale */
2287                 rp_baud_base[i] = 230400;
2288         } else {
2289                 sClockPrescale = 0x14;  /* mod 4 (devide by 5) prescale */
2290                 rp_baud_base[i] = 460800;
2291         }
2292
2293         for (aiop = 0; aiop < MAX_AIOPS_PER_BOARD; aiop++)
2294                 aiopio[aiop] = rcktpt_io_addr[i] + (aiop * 0x400);
2295
2296         num_aiops = sInitController(ctlp, i, controller + (i * 0x400), aiopio,  MAX_AIOPS_PER_BOARD, 0, FREQ_DIS, 0);
2297
2298         if (ctlp->boardType == ROCKET_TYPE_PC104) {
2299                 sEnAiop(ctlp, 2);       /* only one AIOPIC, but these */
2300                 sEnAiop(ctlp, 3);       /* CSels used for other stuff */
2301         }
2302
2303         /*  If something went wrong initing the AIOP's release the ISA IO memory */
2304         if (num_aiops <= 0) {
2305                 release_region(rcktpt_io_addr[i], 64);
2306                 rcktpt_io_addr[i] = 0;
2307                 return (0);
2308         }
2309   
2310         rocketModel[i].startingPortNumber = nextLineNumber;
2311
2312         for (aiop = 0; aiop < num_aiops; aiop++) {
2313                 sResetAiopByNum(ctlp, aiop);
2314                 sEnAiop(ctlp, aiop);
2315                 num_chan = sGetAiopNumChan(ctlp, aiop);
2316                 total_num_chan += num_chan;
2317                 for (chan = 0; chan < num_chan; chan++)
2318                         init_r_port(i, aiop, chan, NULL);
2319         }
2320         is_PCI[i] = 0;
2321         if ((rcktpt_type[i] == ROCKET_TYPE_MODEM) || (rcktpt_type[i] == ROCKET_TYPE_MODEMII)) {
2322                 num_chan = sGetAiopNumChan(ctlp, 0);
2323                 total_num_chan = num_chan;
2324                 for (chan = 0; chan < num_chan; chan++)
2325                         sModemReset(ctlp, chan, 1);
2326                 msleep(500);
2327                 for (chan = 0; chan < num_chan; chan++)
2328                         sModemReset(ctlp, chan, 0);
2329                 msleep(500);
2330                 strcpy(rocketModel[i].modelString, "RocketModem ISA");
2331         } else {
2332                 strcpy(rocketModel[i].modelString, "RocketPort ISA");
2333         }
2334         rocketModel[i].numPorts = total_num_chan;
2335         rocketModel[i].model = MODEL_ISA;
2336
2337         printk(KERN_INFO "RocketPort ISA card #%d found at 0x%lx - %d AIOPs %s\n", 
2338                i, rcktpt_io_addr[i], num_aiops, type_string);
2339
2340         printk(KERN_INFO "Installing %s, creating /dev/ttyR%d - %ld\n",
2341                rocketModel[i].modelString,
2342                rocketModel[i].startingPortNumber,
2343                rocketModel[i].startingPortNumber +
2344                rocketModel[i].numPorts - 1);
2345
2346         return (1);
2347 }
2348
2349 static const struct tty_operations rocket_ops = {
2350         .open = rp_open,
2351         .close = rp_close,
2352         .write = rp_write,
2353         .put_char = rp_put_char,
2354         .write_room = rp_write_room,
2355         .chars_in_buffer = rp_chars_in_buffer,
2356         .flush_buffer = rp_flush_buffer,
2357         .ioctl = rp_ioctl,
2358         .throttle = rp_throttle,
2359         .unthrottle = rp_unthrottle,
2360         .set_termios = rp_set_termios,
2361         .stop = rp_stop,
2362         .start = rp_start,
2363         .hangup = rp_hangup,
2364         .break_ctl = rp_break,
2365         .send_xchar = rp_send_xchar,
2366         .wait_until_sent = rp_wait_until_sent,
2367         .tiocmget = rp_tiocmget,
2368         .tiocmset = rp_tiocmset,
2369 };
2370
2371 /*
2372  * The module "startup" routine; it's run when the module is loaded.
2373  */
2374 static int __init rp_init(void)
2375 {
2376         int ret = -ENOMEM, pci_boards_found, isa_boards_found, i;
2377
2378         printk(KERN_INFO "RocketPort device driver module, version %s, %s\n",
2379                ROCKET_VERSION, ROCKET_DATE);
2380
2381         rocket_driver = alloc_tty_driver(MAX_RP_PORTS);
2382         if (!rocket_driver)
2383                 goto err;
2384
2385         /*
2386          *  If board 1 is non-zero, there is at least one ISA configured.  If controller is 
2387          *  zero, use the default controller IO address of board1 + 0x40.
2388          */
2389         if (board1) {
2390                 if (controller == 0)
2391                         controller = board1 + 0x40;
2392         } else {
2393                 controller = 0;  /*  Used as a flag, meaning no ISA boards */
2394         }
2395
2396         /*  If an ISA card is configured, reserve the 4 byte IO space for the Mudbac controller */
2397         if (controller && (!request_region(controller, 4, "Comtrol RocketPort"))) {
2398                 printk(KERN_ERR "Unable to reserve IO region for first "
2399                         "configured ISA RocketPort controller 0x%lx.  "
2400                         "Driver exiting\n", controller);
2401                 ret = -EBUSY;
2402                 goto err_tty;
2403         }
2404
2405         /*  Store ISA variable retrieved from command line or .conf file. */
2406         rcktpt_io_addr[0] = board1;
2407         rcktpt_io_addr[1] = board2;
2408         rcktpt_io_addr[2] = board3;
2409         rcktpt_io_addr[3] = board4;
2410
2411         rcktpt_type[0] = modem1 ? ROCKET_TYPE_MODEM : ROCKET_TYPE_NORMAL;
2412         rcktpt_type[0] = pc104_1[0] ? ROCKET_TYPE_PC104 : rcktpt_type[0];
2413         rcktpt_type[1] = modem2 ? ROCKET_TYPE_MODEM : ROCKET_TYPE_NORMAL;
2414         rcktpt_type[1] = pc104_2[0] ? ROCKET_TYPE_PC104 : rcktpt_type[1];
2415         rcktpt_type[2] = modem3 ? ROCKET_TYPE_MODEM : ROCKET_TYPE_NORMAL;
2416         rcktpt_type[2] = pc104_3[0] ? ROCKET_TYPE_PC104 : rcktpt_type[2];
2417         rcktpt_type[3] = modem4 ? ROCKET_TYPE_MODEM : ROCKET_TYPE_NORMAL;
2418         rcktpt_type[3] = pc104_4[0] ? ROCKET_TYPE_PC104 : rcktpt_type[3];
2419
2420         /*
2421          * Set up the tty driver structure and then register this
2422          * driver with the tty layer.
2423          */
2424
2425         rocket_driver->owner = THIS_MODULE;
2426         rocket_driver->flags = TTY_DRIVER_DYNAMIC_DEV;
2427         rocket_driver->name = "ttyR";
2428         rocket_driver->driver_name = "Comtrol RocketPort";
2429         rocket_driver->major = TTY_ROCKET_MAJOR;
2430         rocket_driver->minor_start = 0;
2431         rocket_driver->type = TTY_DRIVER_TYPE_SERIAL;
2432         rocket_driver->subtype = SERIAL_TYPE_NORMAL;
2433         rocket_driver->init_termios = tty_std_termios;
2434         rocket_driver->init_termios.c_cflag =
2435             B9600 | CS8 | CREAD | HUPCL | CLOCAL;
2436         rocket_driver->init_termios.c_ispeed = 9600;
2437         rocket_driver->init_termios.c_ospeed = 9600;
2438 #ifdef ROCKET_SOFT_FLOW
2439         rocket_driver->flags |= TTY_DRIVER_REAL_RAW;
2440 #endif
2441         tty_set_operations(rocket_driver, &rocket_ops);
2442
2443         ret = tty_register_driver(rocket_driver);
2444         if (ret < 0) {
2445                 printk(KERN_ERR "Couldn't install tty RocketPort driver\n");
2446                 goto err_tty;
2447         }
2448
2449 #ifdef ROCKET_DEBUG_OPEN
2450         printk(KERN_INFO "RocketPort driver is major %d\n", rocket_driver.major);
2451 #endif
2452
2453         /*
2454          *  OK, let's probe each of the controllers looking for boards.  Any boards found
2455          *  will be initialized here.
2456          */
2457         isa_boards_found = 0;
2458         pci_boards_found = 0;
2459
2460         for (i = 0; i < NUM_BOARDS; i++) {
2461                 if (init_ISA(i))
2462                         isa_boards_found++;
2463         }
2464
2465 #ifdef CONFIG_PCI
2466         if (isa_boards_found < NUM_BOARDS)
2467                 pci_boards_found = init_PCI(isa_boards_found);
2468 #endif
2469
2470         max_board = pci_boards_found + isa_boards_found;
2471
2472         if (max_board == 0) {
2473                 printk(KERN_ERR "No rocketport ports found; unloading driver\n");
2474                 ret = -ENXIO;
2475                 goto err_ttyu;
2476         }
2477
2478         return 0;
2479 err_ttyu:
2480         tty_unregister_driver(rocket_driver);
2481 err_tty:
2482         put_tty_driver(rocket_driver);
2483 err:
2484         return ret;
2485 }
2486
2487
2488 static void rp_cleanup_module(void)
2489 {
2490         int retval;
2491         int i;
2492
2493         del_timer_sync(&rocket_timer);
2494
2495         retval = tty_unregister_driver(rocket_driver);
2496         if (retval)
2497                 printk(KERN_ERR "Error %d while trying to unregister "
2498                        "rocketport driver\n", -retval);
2499
2500         for (i = 0; i < MAX_RP_PORTS; i++)
2501                 if (rp_table[i]) {
2502                         tty_unregister_device(rocket_driver, i);
2503                         kfree(rp_table[i]);
2504                 }
2505
2506         put_tty_driver(rocket_driver);
2507
2508         for (i = 0; i < NUM_BOARDS; i++) {
2509                 if (rcktpt_io_addr[i] <= 0 || is_PCI[i])
2510                         continue;
2511                 release_region(rcktpt_io_addr[i], 64);
2512         }
2513         if (controller)
2514                 release_region(controller, 4);
2515 }
2516
2517 /***************************************************************************
2518 Function: sInitController
2519 Purpose:  Initialization of controller global registers and controller
2520           structure.
2521 Call:     sInitController(CtlP,CtlNum,MudbacIO,AiopIOList,AiopIOListSize,
2522                           IRQNum,Frequency,PeriodicOnly)
2523           CONTROLLER_T *CtlP; Ptr to controller structure
2524           int CtlNum; Controller number
2525           ByteIO_t MudbacIO; Mudbac base I/O address.
2526           ByteIO_t *AiopIOList; List of I/O addresses for each AIOP.
2527              This list must be in the order the AIOPs will be found on the
2528              controller.  Once an AIOP in the list is not found, it is
2529              assumed that there are no more AIOPs on the controller.
2530           int AiopIOListSize; Number of addresses in AiopIOList
2531           int IRQNum; Interrupt Request number.  Can be any of the following:
2532                          0: Disable global interrupts
2533                          3: IRQ 3
2534                          4: IRQ 4
2535                          5: IRQ 5
2536                          9: IRQ 9
2537                          10: IRQ 10
2538                          11: IRQ 11
2539                          12: IRQ 12
2540                          15: IRQ 15
2541           Byte_t Frequency: A flag identifying the frequency
2542                    of the periodic interrupt, can be any one of the following:
2543                       FREQ_DIS - periodic interrupt disabled
2544                       FREQ_137HZ - 137 Hertz
2545                       FREQ_69HZ - 69 Hertz
2546                       FREQ_34HZ - 34 Hertz
2547                       FREQ_17HZ - 17 Hertz
2548                       FREQ_9HZ - 9 Hertz
2549                       FREQ_4HZ - 4 Hertz
2550                    If IRQNum is set to 0 the Frequency parameter is
2551                    overidden, it is forced to a value of FREQ_DIS.
2552           int PeriodicOnly: 1 if all interrupts except the periodic
2553                                interrupt are to be blocked.
2554                             0 is both the periodic interrupt and
2555                                other channel interrupts are allowed.
2556                             If IRQNum is set to 0 the PeriodicOnly parameter is
2557                                overidden, it is forced to a value of 0.
2558 Return:   int: Number of AIOPs on the controller, or CTLID_NULL if controller
2559                initialization failed.
2560
2561 Comments:
2562           If periodic interrupts are to be disabled but AIOP interrupts
2563           are allowed, set Frequency to FREQ_DIS and PeriodicOnly to 0.
2564
2565           If interrupts are to be completely disabled set IRQNum to 0.
2566
2567           Setting Frequency to FREQ_DIS and PeriodicOnly to 1 is an
2568           invalid combination.
2569
2570           This function performs initialization of global interrupt modes,
2571           but it does not actually enable global interrupts.  To enable
2572           and disable global interrupts use functions sEnGlobalInt() and
2573           sDisGlobalInt().  Enabling of global interrupts is normally not
2574           done until all other initializations are complete.
2575
2576           Even if interrupts are globally enabled, they must also be
2577           individually enabled for each channel that is to generate
2578           interrupts.
2579
2580 Warnings: No range checking on any of the parameters is done.
2581
2582           No context switches are allowed while executing this function.
2583
2584           After this function all AIOPs on the controller are disabled,
2585           they can be enabled with sEnAiop().
2586 */
2587 static int sInitController(CONTROLLER_T * CtlP, int CtlNum, ByteIO_t MudbacIO,
2588                            ByteIO_t * AiopIOList, int AiopIOListSize,
2589                            int IRQNum, Byte_t Frequency, int PeriodicOnly)
2590 {
2591         int i;
2592         ByteIO_t io;
2593         int done;
2594
2595         CtlP->AiopIntrBits = aiop_intr_bits;
2596         CtlP->AltChanRingIndicator = 0;
2597         CtlP->CtlNum = CtlNum;
2598         CtlP->CtlID = CTLID_0001;       /* controller release 1 */
2599         CtlP->BusType = isISA;
2600         CtlP->MBaseIO = MudbacIO;
2601         CtlP->MReg1IO = MudbacIO + 1;
2602         CtlP->MReg2IO = MudbacIO + 2;
2603         CtlP->MReg3IO = MudbacIO + 3;
2604 #if 1
2605         CtlP->MReg2 = 0;        /* interrupt disable */
2606         CtlP->MReg3 = 0;        /* no periodic interrupts */
2607 #else
2608         if (sIRQMap[IRQNum] == 0) {     /* interrupts globally disabled */
2609                 CtlP->MReg2 = 0;        /* interrupt disable */
2610                 CtlP->MReg3 = 0;        /* no periodic interrupts */
2611         } else {
2612                 CtlP->MReg2 = sIRQMap[IRQNum];  /* set IRQ number */
2613                 CtlP->MReg3 = Frequency;        /* set frequency */
2614                 if (PeriodicOnly) {     /* periodic interrupt only */
2615                         CtlP->MReg3 |= PERIODIC_ONLY;
2616                 }
2617         }
2618 #endif
2619         sOutB(CtlP->MReg2IO, CtlP->MReg2);
2620         sOutB(CtlP->MReg3IO, CtlP->MReg3);
2621         sControllerEOI(CtlP);   /* clear EOI if warm init */
2622         /* Init AIOPs */
2623         CtlP->NumAiop = 0;
2624         for (i = done = 0; i < AiopIOListSize; i++) {
2625                 io = AiopIOList[i];
2626                 CtlP->AiopIO[i] = (WordIO_t) io;
2627                 CtlP->AiopIntChanIO[i] = io + _INT_CHAN;
2628                 sOutB(CtlP->MReg2IO, CtlP->MReg2 | (i & 0x03)); /* AIOP index */
2629                 sOutB(MudbacIO, (Byte_t) (io >> 6));    /* set up AIOP I/O in MUDBAC */
2630                 if (done)
2631                         continue;
2632                 sEnAiop(CtlP, i);       /* enable the AIOP */
2633                 CtlP->AiopID[i] = sReadAiopID(io);      /* read AIOP ID */
2634                 if (CtlP->AiopID[i] == AIOPID_NULL)     /* if AIOP does not exist */
2635                         done = 1;       /* done looking for AIOPs */
2636                 else {
2637                         CtlP->AiopNumChan[i] = sReadAiopNumChan((WordIO_t) io); /* num channels in AIOP */
2638                         sOutW((WordIO_t) io + _INDX_ADDR, _CLK_PRE);    /* clock prescaler */
2639                         sOutB(io + _INDX_DATA, sClockPrescale);
2640                         CtlP->NumAiop++;        /* bump count of AIOPs */
2641                 }
2642                 sDisAiop(CtlP, i);      /* disable AIOP */
2643         }
2644
2645         if (CtlP->NumAiop == 0)
2646                 return (-1);
2647         else
2648                 return (CtlP->NumAiop);
2649 }
2650
2651 /***************************************************************************
2652 Function: sPCIInitController
2653 Purpose:  Initialization of controller global registers and controller
2654           structure.
2655 Call:     sPCIInitController(CtlP,CtlNum,AiopIOList,AiopIOListSize,
2656                           IRQNum,Frequency,PeriodicOnly)
2657           CONTROLLER_T *CtlP; Ptr to controller structure
2658           int CtlNum; Controller number
2659           ByteIO_t *AiopIOList; List of I/O addresses for each AIOP.
2660              This list must be in the order the AIOPs will be found on the
2661              controller.  Once an AIOP in the list is not found, it is
2662              assumed that there are no more AIOPs on the controller.
2663           int AiopIOListSize; Number of addresses in AiopIOList
2664           int IRQNum; Interrupt Request number.  Can be any of the following:
2665                          0: Disable global interrupts
2666                          3: IRQ 3
2667                          4: IRQ 4
2668                          5: IRQ 5
2669                          9: IRQ 9
2670                          10: IRQ 10
2671                          11: IRQ 11
2672                          12: IRQ 12
2673                          15: IRQ 15
2674           Byte_t Frequency: A flag identifying the frequency
2675                    of the periodic interrupt, can be any one of the following:
2676                       FREQ_DIS - periodic interrupt disabled
2677                       FREQ_137HZ - 137 Hertz
2678                       FREQ_69HZ - 69 Hertz
2679                       FREQ_34HZ - 34 Hertz
2680                       FREQ_17HZ - 17 Hertz
2681                       FREQ_9HZ - 9 Hertz
2682                       FREQ_4HZ - 4 Hertz
2683                    If IRQNum is set to 0 the Frequency parameter is
2684                    overidden, it is forced to a value of FREQ_DIS.
2685           int PeriodicOnly: 1 if all interrupts except the periodic
2686                                interrupt are to be blocked.
2687                             0 is both the periodic interrupt and
2688                                other channel interrupts are allowed.
2689                             If IRQNum is set to 0 the PeriodicOnly parameter is
2690                                overidden, it is forced to a value of 0.
2691 Return:   int: Number of AIOPs on the controller, or CTLID_NULL if controller
2692                initialization failed.
2693
2694 Comments:
2695           If periodic interrupts are to be disabled but AIOP interrupts
2696           are allowed, set Frequency to FREQ_DIS and PeriodicOnly to 0.
2697
2698           If interrupts are to be completely disabled set IRQNum to 0.
2699
2700           Setting Frequency to FREQ_DIS and PeriodicOnly to 1 is an
2701           invalid combination.
2702
2703           This function performs initialization of global interrupt modes,
2704           but it does not actually enable global interrupts.  To enable
2705           and disable global interrupts use functions sEnGlobalInt() and
2706           sDisGlobalInt().  Enabling of global interrupts is normally not
2707           done until all other initializations are complete.
2708
2709           Even if interrupts are globally enabled, they must also be
2710           individually enabled for each channel that is to generate
2711           interrupts.
2712
2713 Warnings: No range checking on any of the parameters is done.
2714
2715           No context switches are allowed while executing this function.
2716
2717           After this function all AIOPs on the controller are disabled,
2718           they can be enabled with sEnAiop().
2719 */
2720 static int sPCIInitController(CONTROLLER_T * CtlP, int CtlNum,
2721                               ByteIO_t * AiopIOList, int AiopIOListSize,
2722                               WordIO_t ConfigIO, int IRQNum, Byte_t Frequency,
2723                               int PeriodicOnly, int altChanRingIndicator,
2724                               int UPCIRingInd)
2725 {
2726         int i;
2727         ByteIO_t io;
2728
2729         CtlP->AltChanRingIndicator = altChanRingIndicator;
2730         CtlP->UPCIRingInd = UPCIRingInd;
2731         CtlP->CtlNum = CtlNum;
2732         CtlP->CtlID = CTLID_0001;       /* controller release 1 */
2733         CtlP->BusType = isPCI;  /* controller release 1 */
2734
2735         if (ConfigIO) {
2736                 CtlP->isUPCI = 1;
2737                 CtlP->PCIIO = ConfigIO + _PCI_9030_INT_CTRL;
2738                 CtlP->PCIIO2 = ConfigIO + _PCI_9030_GPIO_CTRL;
2739                 CtlP->AiopIntrBits = upci_aiop_intr_bits;
2740         } else {
2741                 CtlP->isUPCI = 0;
2742                 CtlP->PCIIO =
2743                     (WordIO_t) ((ByteIO_t) AiopIOList[0] + _PCI_INT_FUNC);
2744                 CtlP->AiopIntrBits = aiop_intr_bits;
2745         }
2746
2747         sPCIControllerEOI(CtlP);        /* clear EOI if warm init */
2748         /* Init AIOPs */
2749         CtlP->NumAiop = 0;
2750         for (i = 0; i < AiopIOListSize; i++) {
2751                 io = AiopIOList[i];
2752                 CtlP->AiopIO[i] = (WordIO_t) io;
2753                 CtlP->AiopIntChanIO[i] = io + _INT_CHAN;
2754
2755                 CtlP->AiopID[i] = sReadAiopID(io);      /* read AIOP ID */
2756                 if (CtlP->AiopID[i] == AIOPID_NULL)     /* if AIOP does not exist */
2757                         break;  /* done looking for AIOPs */
2758
2759                 CtlP->AiopNumChan[i] = sReadAiopNumChan((WordIO_t) io); /* num channels in AIOP */
2760                 sOutW((WordIO_t) io + _INDX_ADDR, _CLK_PRE);    /* clock prescaler */
2761                 sOutB(io + _INDX_DATA, sClockPrescale);
2762                 CtlP->NumAiop++;        /* bump count of AIOPs */
2763         }
2764
2765         if (CtlP->NumAiop == 0)
2766                 return (-1);
2767         else
2768                 return (CtlP->NumAiop);
2769 }
2770
2771 /***************************************************************************
2772 Function: sReadAiopID
2773 Purpose:  Read the AIOP idenfication number directly from an AIOP.
2774 Call:     sReadAiopID(io)
2775           ByteIO_t io: AIOP base I/O address
2776 Return:   int: Flag AIOPID_XXXX if a valid AIOP is found, where X
2777                  is replace by an identifying number.
2778           Flag AIOPID_NULL if no valid AIOP is found
2779 Warnings: No context switches are allowed while executing this function.
2780
2781 */
2782 static int sReadAiopID(ByteIO_t io)
2783 {
2784         Byte_t AiopID;          /* ID byte from AIOP */
2785
2786         sOutB(io + _CMD_REG, RESET_ALL);        /* reset AIOP */
2787         sOutB(io + _CMD_REG, 0x0);
2788         AiopID = sInW(io + _CHN_STAT0) & 0x07;
2789         if (AiopID == 0x06)
2790                 return (1);
2791         else                    /* AIOP does not exist */
2792                 return (-1);
2793 }
2794
2795 /***************************************************************************
2796 Function: sReadAiopNumChan
2797 Purpose:  Read the number of channels available in an AIOP directly from
2798           an AIOP.
2799 Call:     sReadAiopNumChan(io)
2800           WordIO_t io: AIOP base I/O address
2801 Return:   int: The number of channels available
2802 Comments: The number of channels is determined by write/reads from identical
2803           offsets within the SRAM address spaces for channels 0 and 4.
2804           If the channel 4 space is mirrored to channel 0 it is a 4 channel
2805           AIOP, otherwise it is an 8 channel.
2806 Warnings: No context switches are allowed while executing this function.
2807 */
2808 static int sReadAiopNumChan(WordIO_t io)
2809 {
2810         Word_t x;
2811         static Byte_t R[4] = { 0x00, 0x00, 0x34, 0x12 };
2812
2813         /* write to chan 0 SRAM */
2814         out32((DWordIO_t) io + _INDX_ADDR, R);
2815         sOutW(io + _INDX_ADDR, 0);      /* read from SRAM, chan 0 */
2816         x = sInW(io + _INDX_DATA);
2817         sOutW(io + _INDX_ADDR, 0x4000); /* read from SRAM, chan 4 */
2818         if (x != sInW(io + _INDX_DATA)) /* if different must be 8 chan */
2819                 return (8);
2820         else
2821                 return (4);
2822 }
2823
2824 /***************************************************************************
2825 Function: sInitChan
2826 Purpose:  Initialization of a channel and channel structure
2827 Call:     sInitChan(CtlP,ChP,AiopNum,ChanNum)
2828           CONTROLLER_T *CtlP; Ptr to controller structure
2829           CHANNEL_T *ChP; Ptr to channel structure
2830           int AiopNum; AIOP number within controller
2831           int ChanNum; Channel number within AIOP
2832 Return:   int: 1 if initialization succeeded, 0 if it fails because channel
2833                number exceeds number of channels available in AIOP.
2834 Comments: This function must be called before a channel can be used.
2835 Warnings: No range checking on any of the parameters is done.
2836
2837           No context switches are allowed while executing this function.
2838 */
2839 static int sInitChan(CONTROLLER_T * CtlP, CHANNEL_T * ChP, int AiopNum,
2840                      int ChanNum)
2841 {
2842         int i;
2843         WordIO_t AiopIO;
2844         WordIO_t ChIOOff;
2845         Byte_t *ChR;
2846         Word_t ChOff;
2847         static Byte_t R[4];
2848         int brd9600;
2849
2850         if (ChanNum >= CtlP->AiopNumChan[AiopNum])
2851                 return 0;       /* exceeds num chans in AIOP */
2852
2853         /* Channel, AIOP, and controller identifiers */
2854         ChP->CtlP = CtlP;
2855         ChP->ChanID = CtlP->AiopID[AiopNum];
2856         ChP->AiopNum = AiopNum;
2857         ChP->ChanNum = ChanNum;
2858
2859         /* Global direct addresses */
2860         AiopIO = CtlP->AiopIO[AiopNum];
2861         ChP->Cmd = (ByteIO_t) AiopIO + _CMD_REG;
2862         ChP->IntChan = (ByteIO_t) AiopIO + _INT_CHAN;
2863         ChP->IntMask = (ByteIO_t) AiopIO + _INT_MASK;
2864         ChP->IndexAddr = (DWordIO_t) AiopIO + _INDX_ADDR;
2865         ChP->IndexData = AiopIO + _INDX_DATA;
2866
2867         /* Channel direct addresses */
2868         ChIOOff = AiopIO + ChP->ChanNum * 2;
2869         ChP->TxRxData = ChIOOff + _TD0;
2870         ChP->ChanStat = ChIOOff + _CHN_STAT0;
2871         ChP->TxRxCount = ChIOOff + _FIFO_CNT0;
2872         ChP->IntID = (ByteIO_t) AiopIO + ChP->ChanNum + _INT_ID0;
2873
2874         /* Initialize the channel from the RData array */
2875         for (i = 0; i < RDATASIZE; i += 4) {
2876                 R[0] = RData[i];
2877                 R[1] = RData[i + 1] + 0x10 * ChanNum;
2878                 R[2] = RData[i + 2];
2879                 R[3] = RData[i + 3];
2880                 out32(ChP->IndexAddr, R);
2881         }
2882
2883         ChR = ChP->R;
2884         for (i = 0; i < RREGDATASIZE; i += 4) {
2885                 ChR[i] = RRegData[i];
2886                 ChR[i + 1] = RRegData[i + 1] + 0x10 * ChanNum;
2887                 ChR[i + 2] = RRegData[i + 2];
2888                 ChR[i + 3] = RRegData[i + 3];
2889         }
2890
2891         /* Indexed registers */
2892         ChOff = (Word_t) ChanNum *0x1000;
2893
2894         if (sClockPrescale == 0x14)
2895                 brd9600 = 47;
2896         else
2897                 brd9600 = 23;
2898
2899         ChP->BaudDiv[0] = (Byte_t) (ChOff + _BAUD);
2900         ChP->BaudDiv[1] = (Byte_t) ((ChOff + _BAUD) >> 8);
2901         ChP->BaudDiv[2] = (Byte_t) brd9600;
2902         ChP->BaudDiv[3] = (Byte_t) (brd9600 >> 8);
2903         out32(ChP->IndexAddr, ChP->BaudDiv);
2904
2905         ChP->TxControl[0] = (Byte_t) (ChOff + _TX_CTRL);
2906         ChP->TxControl[1] = (Byte_t) ((ChOff + _TX_CTRL) >> 8);
2907         ChP->TxControl[2] = 0;
2908         ChP->TxControl[3] = 0;
2909         out32(ChP->IndexAddr, ChP->TxControl);
2910
2911         ChP->RxControl[0] = (Byte_t) (ChOff + _RX_CTRL);
2912         ChP->RxControl[1] = (Byte_t) ((ChOff + _RX_CTRL) >> 8);
2913         ChP->RxControl[2] = 0;
2914         ChP->RxControl[3] = 0;
2915         out32(ChP->IndexAddr, ChP->RxControl);
2916
2917         ChP->TxEnables[0] = (Byte_t) (ChOff + _TX_ENBLS);
2918         ChP->TxEnables[1] = (Byte_t) ((ChOff + _TX_ENBLS) >> 8);
2919         ChP->TxEnables[2] = 0;
2920         ChP->TxEnables[3] = 0;
2921         out32(ChP->IndexAddr, ChP->TxEnables);
2922
2923         ChP->TxCompare[0] = (Byte_t) (ChOff + _TXCMP1);
2924         ChP->TxCompare[1] = (Byte_t) ((ChOff + _TXCMP1) >> 8);
2925         ChP->TxCompare[2] = 0;
2926         ChP->TxCompare[3] = 0;
2927         out32(ChP->IndexAddr, ChP->TxCompare);
2928
2929         ChP->TxReplace1[0] = (Byte_t) (ChOff + _TXREP1B1);
2930         ChP->TxReplace1[1] = (Byte_t) ((ChOff + _TXREP1B1) >> 8);
2931         ChP->TxReplace1[2] = 0;
2932         ChP->TxReplace1[3] = 0;
2933         out32(ChP->IndexAddr, ChP->TxReplace1);
2934
2935         ChP->TxReplace2[0] = (Byte_t) (ChOff + _TXREP2);
2936         ChP->TxReplace2[1] = (Byte_t) ((ChOff + _TXREP2) >> 8);
2937         ChP->TxReplace2[2] = 0;
2938         ChP->TxReplace2[3] = 0;
2939         out32(ChP->IndexAddr, ChP->TxReplace2);
2940
2941         ChP->TxFIFOPtrs = ChOff + _TXF_OUTP;
2942         ChP->TxFIFO = ChOff + _TX_FIFO;
2943
2944         sOutB(ChP->Cmd, (Byte_t) ChanNum | RESTXFCNT);  /* apply reset Tx FIFO count */
2945         sOutB(ChP->Cmd, (Byte_t) ChanNum);      /* remove reset Tx FIFO count */
2946         sOutW((WordIO_t) ChP->IndexAddr, ChP->TxFIFOPtrs);      /* clear Tx in/out ptrs */
2947         sOutW(ChP->IndexData, 0);
2948         ChP->RxFIFOPtrs = ChOff + _RXF_OUTP;
2949         ChP->RxFIFO = ChOff + _RX_FIFO;
2950
2951         sOutB(ChP->Cmd, (Byte_t) ChanNum | RESRXFCNT);  /* apply reset Rx FIFO count */
2952         sOutB(ChP->Cmd, (Byte_t) ChanNum);      /* remove reset Rx FIFO count */
2953         sOutW((WordIO_t) ChP->IndexAddr, ChP->RxFIFOPtrs);      /* clear Rx out ptr */
2954         sOutW(ChP->IndexData, 0);
2955         sOutW((WordIO_t) ChP->IndexAddr, ChP->RxFIFOPtrs + 2);  /* clear Rx in ptr */
2956         sOutW(ChP->IndexData, 0);
2957         ChP->TxPrioCnt = ChOff + _TXP_CNT;
2958         sOutW((WordIO_t) ChP->IndexAddr, ChP->TxPrioCnt);
2959         sOutB(ChP->IndexData, 0);
2960         ChP->TxPrioPtr = ChOff + _TXP_PNTR;
2961         sOutW((WordIO_t) ChP->IndexAddr, ChP->TxPrioPtr);
2962         sOutB(ChP->IndexData, 0);
2963         ChP->TxPrioBuf = ChOff + _TXP_BUF;
2964         sEnRxProcessor(ChP);    /* start the Rx processor */
2965
2966         return 1;
2967 }
2968
2969 /***************************************************************************
2970 Function: sStopRxProcessor
2971 Purpose:  Stop the receive processor from processing a channel.
2972 Call:     sStopRxProcessor(ChP)
2973           CHANNEL_T *ChP; Ptr to channel structure
2974
2975 Comments: The receive processor can be started again with sStartRxProcessor().
2976           This function causes the receive processor to skip over the
2977           stopped channel.  It does not stop it from processing other channels.
2978
2979 Warnings: No context switches are allowed while executing this function.
2980
2981           Do not leave the receive processor stopped for more than one
2982           character time.
2983
2984           After calling this function a delay of 4 uS is required to ensure
2985           that the receive processor is no longer processing this channel.
2986 */
2987 static void sStopRxProcessor(CHANNEL_T * ChP)
2988 {
2989         Byte_t R[4];
2990
2991         R[0] = ChP->R[0];
2992         R[1] = ChP->R[1];
2993         R[2] = 0x0a;
2994         R[3] = ChP->R[3];
2995         out32(ChP->IndexAddr, R);
2996 }
2997
2998 /***************************************************************************
2999 Function: sFlushRxFIFO
3000 Purpose:  Flush the Rx FIFO
3001 Call:     sFlushRxFIFO(ChP)
3002           CHANNEL_T *ChP; Ptr to channel structure
3003 Return:   void
3004 Comments: To prevent data from being enqueued or dequeued in the Tx FIFO
3005           while it is being flushed the receive processor is stopped
3006           and the transmitter is disabled.  After these operations a
3007           4 uS delay is done before clearing the pointers to allow
3008           the receive processor to stop.  These items are handled inside
3009           this function.
3010 Warnings: No context switches are allowed while executing this function.
3011 */
3012 static void sFlushRxFIFO(CHANNEL_T * ChP)
3013 {
3014         int i;
3015         Byte_t Ch;              /* channel number within AIOP */
3016         int RxFIFOEnabled;      /* 1 if Rx FIFO enabled */
3017
3018         if (sGetRxCnt(ChP) == 0)        /* Rx FIFO empty */
3019                 return;         /* don't need to flush */
3020
3021         RxFIFOEnabled = 0;
3022         if (ChP->R[0x32] == 0x08) {     /* Rx FIFO is enabled */
3023                 RxFIFOEnabled = 1;
3024                 sDisRxFIFO(ChP);        /* disable it */
3025                 for (i = 0; i < 2000 / 200; i++)        /* delay 2 uS to allow proc to disable FIFO */
3026                         sInB(ChP->IntChan);     /* depends on bus i/o timing */
3027         }
3028         sGetChanStatus(ChP);    /* clear any pending Rx errors in chan stat */
3029         Ch = (Byte_t) sGetChanNum(ChP);
3030         sOutB(ChP->Cmd, Ch | RESRXFCNT);        /* apply reset Rx FIFO count */
3031         sOutB(ChP->Cmd, Ch);    /* remove reset Rx FIFO count */
3032         sOutW((WordIO_t) ChP->IndexAddr, ChP->RxFIFOPtrs);      /* clear Rx out ptr */
3033         sOutW(ChP->IndexData, 0);
3034         sOutW((WordIO_t) ChP->IndexAddr, ChP->RxFIFOPtrs + 2);  /* clear Rx in ptr */
3035         sOutW(ChP->IndexData, 0);
3036         if (RxFIFOEnabled)
3037                 sEnRxFIFO(ChP); /* enable Rx FIFO */
3038 }
3039
3040 /***************************************************************************
3041 Function: sFlushTxFIFO
3042 Purpose:  Flush the Tx FIFO
3043 Call:     sFlushTxFIFO(ChP)
3044           CHANNEL_T *ChP; Ptr to channel structure
3045 Return:   void
3046 Comments: To prevent data from being enqueued or dequeued in the Tx FIFO
3047           while it is being flushed the receive processor is stopped
3048           and the transmitter is disabled.  After these operations a
3049           4 uS delay is done before clearing the pointers to allow
3050           the receive processor to stop.  These items are handled inside
3051           this function.
3052 Warnings: No context switches are allowed while executing this function.
3053 */
3054 static void sFlushTxFIFO(CHANNEL_T * ChP)
3055 {
3056         int i;
3057         Byte_t Ch;              /* channel number within AIOP */
3058         int TxEnabled;          /* 1 if transmitter enabled */
3059
3060         if (sGetTxCnt(ChP) == 0)        /* Tx FIFO empty */
3061                 return;         /* don't need to flush */
3062
3063         TxEnabled = 0;
3064         if (ChP->TxControl[3] & TX_ENABLE) {
3065                 TxEnabled = 1;
3066                 sDisTransmit(ChP);      /* disable transmitter */
3067         }
3068         sStopRxProcessor(ChP);  /* stop Rx processor */
3069         for (i = 0; i < 4000 / 200; i++)        /* delay 4 uS to allow proc to stop */
3070                 sInB(ChP->IntChan);     /* depends on bus i/o timing */
3071         Ch = (Byte_t) sGetChanNum(ChP);
3072         sOutB(ChP->Cmd, Ch | RESTXFCNT);        /* apply reset Tx FIFO count */
3073         sOutB(ChP->Cmd, Ch);    /* remove reset Tx FIFO count */
3074         sOutW((WordIO_t) ChP->IndexAddr, ChP->TxFIFOPtrs);      /* clear Tx in/out ptrs */
3075         sOutW(ChP->IndexData, 0);
3076         if (TxEnabled)
3077                 sEnTransmit(ChP);       /* enable transmitter */
3078         sStartRxProcessor(ChP); /* restart Rx processor */
3079 }
3080
3081 /***************************************************************************
3082 Function: sWriteTxPrioByte
3083 Purpose:  Write a byte of priority transmit data to a channel
3084 Call:     sWriteTxPrioByte(ChP,Data)
3085           CHANNEL_T *ChP; Ptr to channel structure
3086           Byte_t Data; The transmit data byte
3087
3088 Return:   int: 1 if the bytes is successfully written, otherwise 0.
3089
3090 Comments: The priority byte is transmitted before any data in the Tx FIFO.
3091
3092 Warnings: No context switches are allowed while executing this function.
3093 */
3094 static int sWriteTxPrioByte(CHANNEL_T * ChP, Byte_t Data)
3095 {
3096         Byte_t DWBuf[4];        /* buffer for double word writes */
3097         Word_t *WordPtr;        /* must be far because Win SS != DS */
3098         register DWordIO_t IndexAddr;
3099
3100         if (sGetTxCnt(ChP) > 1) {       /* write it to Tx priority buffer */
3101                 IndexAddr = ChP->IndexAddr;
3102                 sOutW((WordIO_t) IndexAddr, ChP->TxPrioCnt);    /* get priority buffer status */
3103                 if (sInB((ByteIO_t) ChP->IndexData) & PRI_PEND) /* priority buffer busy */
3104                         return (0);     /* nothing sent */
3105
3106                 WordPtr = (Word_t *) (&DWBuf[0]);
3107                 *WordPtr = ChP->TxPrioBuf;      /* data byte address */
3108
3109                 DWBuf[2] = Data;        /* data byte value */
3110                 out32(IndexAddr, DWBuf);        /* write it out */
3111
3112                 *WordPtr = ChP->TxPrioCnt;      /* Tx priority count address */
3113
3114                 DWBuf[2] = PRI_PEND + 1;        /* indicate 1 byte pending */
3115                 DWBuf[3] = 0;   /* priority buffer pointer */
3116                 out32(IndexAddr, DWBuf);        /* write it out */
3117         } else {                /* write it to Tx FIFO */
3118
3119                 sWriteTxByte(sGetTxRxDataIO(ChP), Data);
3120         }
3121         return (1);             /* 1 byte sent */
3122 }
3123
3124 /***************************************************************************
3125 Function: sEnInterrupts
3126 Purpose:  Enable one or more interrupts for a channel
3127 Call:     sEnInterrupts(ChP,Flags)
3128           CHANNEL_T *ChP; Ptr to channel structure
3129           Word_t Flags: Interrupt enable flags, can be any combination
3130              of the following flags:
3131                 TXINT_EN:   Interrupt on Tx FIFO empty
3132                 RXINT_EN:   Interrupt on Rx FIFO at trigger level (see
3133                             sSetRxTrigger())
3134                 SRCINT_EN:  Interrupt on SRC (Special Rx Condition)
3135                 MCINT_EN:   Interrupt on modem input change
3136                 CHANINT_EN: Allow channel interrupt signal to the AIOP's
3137                             Interrupt Channel Register.
3138 Return:   void
3139 Comments: If an interrupt enable flag is set in Flags, that interrupt will be
3140           enabled.  If an interrupt enable flag is not set in Flags, that
3141           interrupt will not be changed.  Interrupts can be disabled with
3142           function sDisInterrupts().
3143
3144           This function sets the appropriate bit for the channel in the AIOP's
3145           Interrupt Mask Register if the CHANINT_EN flag is set.  This allows
3146           this channel's bit to be set in the AIOP's Interrupt Channel Register.
3147
3148           Interrupts must also be globally enabled before channel interrupts
3149           will be passed on to the host.  This is done with function
3150           sEnGlobalInt().
3151
3152           In some cases it may be desirable to disable interrupts globally but
3153           enable channel interrupts.  This would allow the global interrupt
3154           status register to be used to determine which AIOPs need service.
3155 */
3156 static void sEnInterrupts(CHANNEL_T * ChP, Word_t Flags)
3157 {
3158         Byte_t Mask;            /* Interrupt Mask Register */
3159
3160         ChP->RxControl[2] |=
3161             ((Byte_t) Flags & (RXINT_EN | SRCINT_EN | MCINT_EN));
3162
3163         out32(ChP->IndexAddr, ChP->RxControl);
3164
3165         ChP->TxControl[2] |= ((Byte_t) Flags & TXINT_EN);
3166
3167         out32(ChP->IndexAddr, ChP->TxControl);
3168
3169         if (Flags & CHANINT_EN) {
3170                 Mask = sInB(ChP->IntMask) | sBitMapSetTbl[ChP->ChanNum];
3171                 sOutB(ChP->IntMask, Mask);
3172         }
3173 }
3174
3175 /***************************************************************************
3176 Function: sDisInterrupts
3177 Purpose:  Disable one or more interrupts for a channel
3178 Call:     sDisInterrupts(ChP,Flags)
3179           CHANNEL_T *ChP; Ptr to channel structure
3180           Word_t Flags: Interrupt flags, can be any combination
3181              of the following flags:
3182                 TXINT_EN:   Interrupt on Tx FIFO empty
3183                 RXINT_EN:   Interrupt on Rx FIFO at trigger level (see
3184                             sSetRxTrigger())
3185                 SRCINT_EN:  Interrupt on SRC (Special Rx Condition)
3186                 MCINT_EN:   Interrupt on modem input change
3187                 CHANINT_EN: Disable channel interrupt signal to the
3188                             AIOP's Interrupt Channel Register.
3189 Return:   void
3190 Comments: If an interrupt flag is set in Flags, that interrupt will be
3191           disabled.  If an interrupt flag is not set in Flags, that
3192           interrupt will not be changed.  Interrupts can be enabled with
3193           function sEnInterrupts().
3194
3195           This function clears the appropriate bit for the channel in the AIOP's
3196           Interrupt Mask Register if the CHANINT_EN flag is set.  This blocks
3197           this channel's bit from being set in the AIOP's Interrupt Channel
3198           Register.
3199 */
3200 static void sDisInterrupts(CHANNEL_T * ChP, Word_t Flags)
3201 {
3202         Byte_t Mask;            /* Interrupt Mask Register */
3203
3204         ChP->RxControl[2] &=
3205             ~((Byte_t) Flags & (RXINT_EN | SRCINT_EN | MCINT_EN));
3206         out32(ChP->IndexAddr, ChP->RxControl);
3207         ChP->TxControl[2] &= ~((Byte_t) Flags & TXINT_EN);
3208         out32(ChP->IndexAddr, ChP->TxControl);
3209
3210         if (Flags & CHANINT_EN) {
3211                 Mask = sInB(ChP->IntMask) & sBitMapClrTbl[ChP->ChanNum];
3212                 sOutB(ChP->IntMask, Mask);
3213         }
3214 }
3215
3216 static void sSetInterfaceMode(CHANNEL_T * ChP, Byte_t mode)
3217 {
3218         sOutB(ChP->CtlP->AiopIO[2], (mode & 0x18) | ChP->ChanNum);
3219 }
3220
3221 /*
3222  *  Not an official SSCI function, but how to reset RocketModems.
3223  *  ISA bus version
3224  */
3225 static void sModemReset(CONTROLLER_T * CtlP, int chan, int on)
3226 {
3227         ByteIO_t addr;
3228         Byte_t val;
3229
3230         addr = CtlP->AiopIO[0] + 0x400;
3231         val = sInB(CtlP->MReg3IO);
3232         /* if AIOP[1] is not enabled, enable it */
3233         if ((val & 2) == 0) {
3234                 val = sInB(CtlP->MReg2IO);
3235                 sOutB(CtlP->MReg2IO, (val & 0xfc) | (1 & 0x03));
3236                 sOutB(CtlP->MBaseIO, (unsigned char) (addr >> 6));
3237         }
3238
3239         sEnAiop(CtlP, 1);
3240         if (!on)
3241                 addr += 8;
3242         sOutB(addr + chan, 0);  /* apply or remove reset */
3243         sDisAiop(CtlP, 1);
3244 }
3245
3246 /*
3247  *  Not an official SSCI function, but how to reset RocketModems.
3248  *  PCI bus version
3249  */
3250 static void sPCIModemReset(CONTROLLER_T * CtlP, int chan, int on)
3251 {
3252         ByteIO_t addr;
3253
3254         addr = CtlP->AiopIO[0] + 0x40;  /* 2nd AIOP */
3255         if (!on)
3256                 addr += 8;
3257         sOutB(addr + chan, 0);  /* apply or remove reset */
3258 }
3259
3260 /*  Resets the speaker controller on RocketModem II and III devices */
3261 static void rmSpeakerReset(CONTROLLER_T * CtlP, unsigned long model)
3262 {
3263         ByteIO_t addr;
3264
3265         /* RocketModem II speaker control is at the 8th port location of offset 0x40 */
3266         if ((model == MODEL_RP4M) || (model == MODEL_RP6M)) {
3267                 addr = CtlP->AiopIO[0] + 0x4F;
3268                 sOutB(addr, 0);
3269         }
3270
3271         /* RocketModem III speaker control is at the 1st port location of offset 0x80 */
3272         if ((model == MODEL_UPCI_RM3_8PORT)
3273             || (model == MODEL_UPCI_RM3_4PORT)) {
3274                 addr = CtlP->AiopIO[0] + 0x88;
3275                 sOutB(addr, 0);
3276         }
3277 }
3278
3279 /*  Returns the line number given the controller (board), aiop and channel number */
3280 static unsigned char GetLineNumber(int ctrl, int aiop, int ch)
3281 {
3282         return lineNumbers[(ctrl << 5) | (aiop << 3) | ch];
3283 }
3284
3285 /*
3286  *  Stores the line number associated with a given controller (board), aiop
3287  *  and channel number.  
3288  *  Returns:  The line number assigned 
3289  */
3290 static unsigned char SetLineNumber(int ctrl, int aiop, int ch)
3291 {
3292         lineNumbers[(ctrl << 5) | (aiop << 3) | ch] = nextLineNumber++;
3293         return (nextLineNumber - 1);
3294 }