Merge master.kernel.org:/pub/scm/linux/kernel/git/roland/infiniband
[linux-2.6] / drivers / char / ip2 / i2lib.c
1 /*******************************************************************************
2 *
3 *   (c) 1999 by Computone Corporation
4 *
5 ********************************************************************************
6 *
7 *
8 *   PACKAGE:     Linux tty Device Driver for IntelliPort family of multiport
9 *                serial I/O controllers.
10 *
11 *   DESCRIPTION: High-level interface code for the device driver. Uses the
12 *                Extremely Low Level Interface Support (i2ellis.c). Provides an
13 *                interface to the standard loadware, to support drivers or
14 *                application code. (This is included source code, not a separate
15 *                compilation module.)
16 *
17 *******************************************************************************/
18 //------------------------------------------------------------------------------
19 // Note on Strategy:
20 // Once the board has been initialized, it will interrupt us when:
21 // 1) It has something in the fifo for us to read (incoming data, flow control
22 // packets, or whatever).
23 // 2) It has stripped whatever we have sent last time in the FIFO (and
24 // consequently is ready for more).
25 //
26 // Note also that the buffer sizes declared in i2lib.h are VERY SMALL. This
27 // worsens performance considerably, but is done so that a great many channels
28 // might use only a little memory.
29 //------------------------------------------------------------------------------
30
31 //------------------------------------------------------------------------------
32 // Revision History:
33 //
34 // 0.00 -  4/16/91 --- First Draft
35 // 0.01 -  4/29/91 --- 1st beta release
36 // 0.02 -  6/14/91 --- Changes to allow small model compilation
37 // 0.03 -  6/17/91 MAG Break reporting protected from interrupts routines with
38 //                     in-line asm added for moving data to/from ring buffers,
39 //                     replacing a variety of methods used previously.
40 // 0.04 -  6/21/91 MAG Initial flow-control packets not queued until
41 //                     i2_enable_interrupts time. Former versions would enqueue
42 //                     them at i2_init_channel time, before we knew how many
43 //                     channels were supposed to exist!
44 // 0.05 - 10/12/91 MAG Major changes: works through the ellis.c routines now;
45 //                     supports new 16-bit protocol and expandable boards.
46 //      - 10/24/91 MAG Most changes in place and stable.
47 // 0.06 -  2/20/92 MAG Format of CMD_HOTACK corrected: the command takes no
48 //                     argument.
49 // 0.07 -- 3/11/92 MAG Support added to store special packet types at interrupt
50 //                     level (mostly responses to specific commands.)
51 // 0.08 -- 3/30/92 MAG Support added for STAT_MODEM packet
52 // 0.09 -- 6/24/93 MAG i2Link... needed to update number of boards BEFORE
53 //                     turning on the interrupt.
54 // 0.10 -- 6/25/93 MAG To avoid gruesome death from a bad board, we sanity check
55 //                     some incoming.
56 //
57 // 1.1  - 12/25/96 AKM Linux version.
58 //      - 10/09/98 DMC Revised Linux version.
59 //------------------------------------------------------------------------------
60
61 //************
62 //* Includes *
63 //************
64
65 #include <linux/sched.h>
66 #include "i2lib.h"
67
68
69 //***********************
70 //* Function Prototypes *
71 //***********************
72 static void i2QueueNeeds(i2eBordStrPtr, i2ChanStrPtr, int);
73 static i2ChanStrPtr i2DeQueueNeeds(i2eBordStrPtr, int );
74 static void i2StripFifo(i2eBordStrPtr);
75 static void i2StuffFifoBypass(i2eBordStrPtr);
76 static void i2StuffFifoFlow(i2eBordStrPtr);
77 static void i2StuffFifoInline(i2eBordStrPtr);
78 static int i2RetryFlushOutput(i2ChanStrPtr);
79
80 // Not a documented part of the library routines (careful...) but the Diagnostic
81 // i2diag.c finds them useful to help the throughput in certain limited
82 // single-threaded operations.
83 static void iiSendPendingMail(i2eBordStrPtr);
84 static void serviceOutgoingFifo(i2eBordStrPtr);
85
86 // Functions defined in ip2.c as part of interrupt handling
87 static void do_input(void *);
88 static void do_status(void *);
89
90 //***************
91 //* Debug  Data *
92 //***************
93 #ifdef DEBUG_FIFO
94
95 unsigned char DBGBuf[0x4000];
96 unsigned short I = 0;
97
98 static void
99 WriteDBGBuf(char *s, unsigned char *src, unsigned short n ) 
100 {
101         char *p = src;
102
103         // XXX: We need a spin lock here if we ever use this again
104
105         while (*s) {    // copy label
106                 DBGBuf[I] = *s++;
107                 I = I++ & 0x3fff;
108         }
109         while (n--) {   // copy data
110                 DBGBuf[I] = *p++;
111                 I = I++ & 0x3fff;
112         }
113 }
114
115 static void
116 fatality(i2eBordStrPtr pB )
117 {
118         int i;
119
120         for (i=0;i<sizeof(DBGBuf);i++) {
121                 if ((i%16) == 0)
122                         printk("\n%4x:",i);
123                 printk("%02x ",DBGBuf[i]);
124         }
125         printk("\n");
126         for (i=0;i<sizeof(DBGBuf);i++) {
127                 if ((i%16) == 0)
128                         printk("\n%4x:",i);
129                 if (DBGBuf[i] >= ' ' && DBGBuf[i] <= '~') {
130                         printk(" %c ",DBGBuf[i]);
131                 } else {
132                         printk(" . ");
133                 }
134         }
135         printk("\n");
136         printk("Last index %x\n",I);
137 }
138 #endif /* DEBUG_FIFO */
139
140 //********
141 //* Code *
142 //********
143
144 static inline int
145 i2Validate ( i2ChanStrPtr pCh )
146 {
147         //ip2trace(pCh->port_index, ITRC_VERIFY,ITRC_ENTER,2,pCh->validity,
148         //      (CHANNEL_MAGIC | CHANNEL_SUPPORT));
149         return ((pCh->validity & (CHANNEL_MAGIC_BITS | CHANNEL_SUPPORT)) 
150                           == (CHANNEL_MAGIC | CHANNEL_SUPPORT));
151 }
152
153 //******************************************************************************
154 // Function:   iiSendPendingMail(pB)
155 // Parameters: Pointer to a board structure
156 // Returns:    Nothing
157 //
158 // Description:
159 // If any outgoing mail bits are set and there is outgoing mailbox is empty,
160 // send the mail and clear the bits.
161 //******************************************************************************
162 static inline void
163 iiSendPendingMail(i2eBordStrPtr pB)
164 {
165         if (pB->i2eOutMailWaiting && (!pB->i2eWaitingForEmptyFifo) )
166         {
167                 if (iiTrySendMail(pB, pB->i2eOutMailWaiting))
168                 {
169                         /* If we were already waiting for fifo to empty,
170                          * or just sent MB_OUT_STUFFED, then we are
171                          * still waiting for it to empty, until we should
172                          * receive an MB_IN_STRIPPED from the board.
173                          */
174                         pB->i2eWaitingForEmptyFifo |=
175                                 (pB->i2eOutMailWaiting & MB_OUT_STUFFED);
176                         pB->i2eOutMailWaiting = 0;
177                         pB->SendPendingRetry = 0;
178                 } else {
179 /*              The only time we hit this area is when "iiTrySendMail" has
180                 failed.  That only occurs when the outbound mailbox is
181                 still busy with the last message.  We take a short breather
182                 to let the board catch up with itself and then try again.
183                 16 Retries is the limit - then we got a borked board.
184                         /\/\|=mhw=|\/\/                         */
185
186                         if( ++pB->SendPendingRetry < 16 ) {
187
188                                 init_timer( &(pB->SendPendingTimer) );
189                                 pB->SendPendingTimer.expires  = jiffies + 1;
190                                 pB->SendPendingTimer.function = (void*)(unsigned long)iiSendPendingMail;
191                                 pB->SendPendingTimer.data     = (unsigned long)pB;
192                                 add_timer( &(pB->SendPendingTimer) );
193                         } else {
194                                 printk( KERN_ERR "IP2: iiSendPendingMail unable to queue outbound mail\n" );
195                         }
196                 }
197         }
198 }
199
200 //******************************************************************************
201 // Function:   i2InitChannels(pB, nChannels, pCh)
202 // Parameters: Pointer to Ellis Board structure
203 //             Number of channels to initialize
204 //             Pointer to first element in an array of channel structures
205 // Returns:    Success or failure
206 //
207 // Description:
208 //
209 // This function patches pointers, back-pointers, and initializes all the
210 // elements in the channel structure array.
211 //
212 // This should be run after the board structure is initialized, through having
213 // loaded the standard loadware (otherwise it complains).
214 //
215 // In any case, it must be done before any serious work begins initializing the
216 // irq's or sending commands...
217 //
218 //******************************************************************************
219 static int
220 i2InitChannels ( i2eBordStrPtr pB, int nChannels, i2ChanStrPtr pCh)
221 {
222         int index, stuffIndex;
223         i2ChanStrPtr *ppCh;
224         
225         if (pB->i2eValid != I2E_MAGIC) {
226                 COMPLETE(pB, I2EE_BADMAGIC);
227         }
228         if (pB->i2eState != II_STATE_STDLOADED) {
229                 COMPLETE(pB, I2EE_BADSTATE);
230         }
231
232         LOCK_INIT(&pB->read_fifo_spinlock);
233         LOCK_INIT(&pB->write_fifo_spinlock);
234         LOCK_INIT(&pB->Dbuf_spinlock);
235         LOCK_INIT(&pB->Bbuf_spinlock);
236         LOCK_INIT(&pB->Fbuf_spinlock);
237         
238         // NO LOCK needed yet - this is init
239
240         pB->i2eChannelPtr = pCh;
241         pB->i2eChannelCnt = nChannels;
242
243         pB->i2Fbuf_strip = pB->i2Fbuf_stuff = 0;
244         pB->i2Dbuf_strip = pB->i2Dbuf_stuff = 0;
245         pB->i2Bbuf_strip = pB->i2Bbuf_stuff = 0;
246
247         pB->SendPendingRetry = 0;
248
249         memset ( pCh, 0, sizeof (i2ChanStr) * nChannels );
250
251         for (index = stuffIndex = 0, ppCh = (i2ChanStrPtr *)(pB->i2Fbuf);
252                   nChannels && index < ABS_MOST_PORTS;
253                   index++)
254         {
255                 if ( !(pB->i2eChannelMap[index >> 4] & (1 << (index & 0xf)) ) ) {
256                         continue;
257                 }
258                 LOCK_INIT(&pCh->Ibuf_spinlock);
259                 LOCK_INIT(&pCh->Obuf_spinlock);
260                 LOCK_INIT(&pCh->Cbuf_spinlock);
261                 LOCK_INIT(&pCh->Pbuf_spinlock);
262                 // NO LOCK needed yet - this is init
263                 // Set up validity flag according to support level
264                 if (pB->i2eGoodMap[index >> 4] & (1 << (index & 0xf)) ) {
265                         pCh->validity = CHANNEL_MAGIC | CHANNEL_SUPPORT;
266                 } else {
267                         pCh->validity = CHANNEL_MAGIC;
268                 }
269                 pCh->pMyBord = pB;      /* Back-pointer */
270
271                 // Prepare an outgoing flow-control packet to send as soon as the chance
272                 // occurs.
273                 if ( pCh->validity & CHANNEL_SUPPORT ) {
274                         pCh->infl.hd.i2sChannel = index;
275                         pCh->infl.hd.i2sCount = 5;
276                         pCh->infl.hd.i2sType = PTYPE_BYPASS;
277                         pCh->infl.fcmd = 37;
278                         pCh->infl.asof = 0;
279                         pCh->infl.room = IBUF_SIZE - 1;
280
281                         pCh->whenSendFlow = (IBUF_SIZE/5)*4; // when 80% full
282
283                 // The following is similar to calling i2QueueNeeds, except that this
284                 // is done in longhand, since we are setting up initial conditions on
285                 // many channels at once.
286                         pCh->channelNeeds = NEED_FLOW;  // Since starting from scratch
287                         pCh->sinceLastFlow = 0;         // No bytes received since last flow
288                                                                                         // control packet was queued
289                         stuffIndex++;
290                         *ppCh++ = pCh;      // List this channel as needing
291                                                                 // initial flow control packet sent
292                 }
293
294                 // Don't allow anything to be sent until the status packets come in from
295                 // the board.
296
297                 pCh->outfl.asof = 0;
298                 pCh->outfl.room = 0;
299
300                 // Initialize all the ring buffers
301
302                 pCh->Ibuf_stuff = pCh->Ibuf_strip = 0;
303                 pCh->Obuf_stuff = pCh->Obuf_strip = 0;
304                 pCh->Cbuf_stuff = pCh->Cbuf_strip = 0;
305
306                 memset( &pCh->icount, 0, sizeof (struct async_icount) );
307                 pCh->hotKeyIn       = HOT_CLEAR;
308                 pCh->channelOptions = 0;
309                 pCh->bookMarks      = 0;
310                 init_waitqueue_head(&pCh->pBookmarkWait);
311
312                 init_waitqueue_head(&pCh->open_wait);
313                 init_waitqueue_head(&pCh->close_wait);
314                 init_waitqueue_head(&pCh->delta_msr_wait);
315
316                 // Set base and divisor so default custom rate is 9600
317                 pCh->BaudBase    = 921600;      // MAX for ST654, changed after we get
318                 pCh->BaudDivisor = 96;          // the boxids (UART types) later
319
320                 pCh->dataSetIn   = 0;
321                 pCh->dataSetOut  = 0;
322
323                 pCh->wopen       = 0;
324                 pCh->throttled   = 0;
325
326                 pCh->speed       = CBR_9600;
327
328                 pCh->flags    = 0;
329
330                 pCh->ClosingDelay     = 5*HZ/10;
331                 pCh->ClosingWaitTime  = 30*HZ;
332
333                 // Initialize task queue objects
334                 INIT_WORK(&pCh->tqueue_input, do_input, pCh);
335                 INIT_WORK(&pCh->tqueue_status, do_status, pCh);
336
337 #ifdef IP2DEBUG_TRACE
338                 pCh->trace = ip2trace;
339 #endif
340
341                 ++pCh;
342         --nChannels;
343         }
344         // No need to check for wrap here; this is initialization.
345         pB->i2Fbuf_stuff = stuffIndex;
346         COMPLETE(pB, I2EE_GOOD);
347
348 }
349
350 //******************************************************************************
351 // Function:   i2DeQueueNeeds(pB, type)
352 // Parameters: Pointer to a board structure
353 //             type bit map: may include NEED_INLINE, NEED_BYPASS, or NEED_FLOW
354 // Returns:   
355 //             Pointer to a channel structure
356 //
357 // Description: Returns pointer struct of next channel that needs service of
358 //  the type specified. Otherwise returns a NULL reference.
359 //
360 //******************************************************************************
361 static i2ChanStrPtr 
362 i2DeQueueNeeds(i2eBordStrPtr pB, int type)
363 {
364         unsigned short queueIndex;
365         unsigned long flags;
366
367         i2ChanStrPtr pCh = NULL;
368
369         switch(type) {
370
371         case  NEED_INLINE:
372
373                 WRITE_LOCK_IRQSAVE(&pB->Dbuf_spinlock,flags);
374                 if ( pB->i2Dbuf_stuff != pB->i2Dbuf_strip)
375                 {
376                         queueIndex = pB->i2Dbuf_strip;
377                         pCh = pB->i2Dbuf[queueIndex];
378                         queueIndex++;
379                         if (queueIndex >= CH_QUEUE_SIZE) {
380                                 queueIndex = 0;
381                         }
382                         pB->i2Dbuf_strip = queueIndex;
383                         pCh->channelNeeds &= ~NEED_INLINE;
384                 }
385                 WRITE_UNLOCK_IRQRESTORE(&pB->Dbuf_spinlock,flags); 
386                 break;
387
388         case NEED_BYPASS:
389
390                 WRITE_LOCK_IRQSAVE(&pB->Bbuf_spinlock,flags);
391                 if (pB->i2Bbuf_stuff != pB->i2Bbuf_strip)
392                 {
393                         queueIndex = pB->i2Bbuf_strip;
394                         pCh = pB->i2Bbuf[queueIndex];
395                         queueIndex++;
396                         if (queueIndex >= CH_QUEUE_SIZE) {
397                                 queueIndex = 0;
398                         }
399                         pB->i2Bbuf_strip = queueIndex;
400                         pCh->channelNeeds &= ~NEED_BYPASS;
401                 }
402                 WRITE_UNLOCK_IRQRESTORE(&pB->Bbuf_spinlock,flags); 
403                 break;
404         
405         case NEED_FLOW:
406
407                 WRITE_LOCK_IRQSAVE(&pB->Fbuf_spinlock,flags);
408                 if (pB->i2Fbuf_stuff != pB->i2Fbuf_strip)
409                 {
410                         queueIndex = pB->i2Fbuf_strip;
411                         pCh = pB->i2Fbuf[queueIndex];
412                         queueIndex++;
413                         if (queueIndex >= CH_QUEUE_SIZE) {
414                                 queueIndex = 0;
415                         }
416                         pB->i2Fbuf_strip = queueIndex;
417                         pCh->channelNeeds &= ~NEED_FLOW;
418                 }
419                 WRITE_UNLOCK_IRQRESTORE(&pB->Fbuf_spinlock,flags); 
420                 break;
421         default:
422                 printk(KERN_ERR "i2DeQueueNeeds called with bad type:%x\n",type);
423                 break;
424         }
425         return pCh;
426 }
427
428 //******************************************************************************
429 // Function:   i2QueueNeeds(pB, pCh, type)
430 // Parameters: Pointer to a board structure
431 //             Pointer to a channel structure
432 //             type bit map: may include NEED_INLINE, NEED_BYPASS, or NEED_FLOW
433 // Returns:    Nothing
434 //
435 // Description:
436 // For each type of need selected, if the given channel is not already in the
437 // queue, adds it, and sets the flag indicating it is in the queue.
438 //******************************************************************************
439 static void
440 i2QueueNeeds(i2eBordStrPtr pB, i2ChanStrPtr pCh, int type)
441 {
442         unsigned short queueIndex;
443         unsigned long flags;
444
445         // We turn off all the interrupts during this brief process, since the
446         // interrupt-level code might want to put things on the queue as well.
447
448         switch (type) {
449
450         case NEED_INLINE:
451
452                 WRITE_LOCK_IRQSAVE(&pB->Dbuf_spinlock,flags);
453                 if ( !(pCh->channelNeeds & NEED_INLINE) )
454                 {
455                         pCh->channelNeeds |= NEED_INLINE;
456                         queueIndex = pB->i2Dbuf_stuff;
457                         pB->i2Dbuf[queueIndex++] = pCh;
458                         if (queueIndex >= CH_QUEUE_SIZE)
459                                 queueIndex = 0;
460                         pB->i2Dbuf_stuff = queueIndex;
461                 }
462                 WRITE_UNLOCK_IRQRESTORE(&pB->Dbuf_spinlock,flags); 
463                 break;
464
465         case NEED_BYPASS:
466
467                 WRITE_LOCK_IRQSAVE(&pB->Bbuf_spinlock,flags);
468                 if ((type & NEED_BYPASS) && !(pCh->channelNeeds & NEED_BYPASS))
469                 {
470                         pCh->channelNeeds |= NEED_BYPASS;
471                         queueIndex = pB->i2Bbuf_stuff;
472                         pB->i2Bbuf[queueIndex++] = pCh;
473                         if (queueIndex >= CH_QUEUE_SIZE)
474                                 queueIndex = 0;
475                         pB->i2Bbuf_stuff = queueIndex;
476                 } 
477                 WRITE_UNLOCK_IRQRESTORE(&pB->Bbuf_spinlock,flags); 
478                 break;
479
480         case NEED_FLOW:
481
482                 WRITE_LOCK_IRQSAVE(&pB->Fbuf_spinlock,flags);
483                 if ((type & NEED_FLOW) && !(pCh->channelNeeds & NEED_FLOW))
484                 {
485                         pCh->channelNeeds |= NEED_FLOW;
486                         queueIndex = pB->i2Fbuf_stuff;
487                         pB->i2Fbuf[queueIndex++] = pCh;
488                         if (queueIndex >= CH_QUEUE_SIZE)
489                                 queueIndex = 0;
490                         pB->i2Fbuf_stuff = queueIndex;
491                 }
492                 WRITE_UNLOCK_IRQRESTORE(&pB->Fbuf_spinlock,flags); 
493                 break;
494
495         case NEED_CREDIT:
496                 pCh->channelNeeds |= NEED_CREDIT;
497                 break;
498         default:
499                 printk(KERN_ERR "i2QueueNeeds called with bad type:%x\n",type);
500                 break;
501         }
502         return;
503 }
504
505 //******************************************************************************
506 // Function:   i2QueueCommands(type, pCh, timeout, nCommands, pCs,...)
507 // Parameters: type - PTYPE_BYPASS or PTYPE_INLINE
508 //             pointer to the channel structure
509 //             maximum period to wait
510 //             number of commands (n)
511 //             n commands
512 // Returns:    Number of commands sent, or -1 for error
513 //
514 // get board lock before calling
515 //
516 // Description:
517 // Queues up some commands to be sent to a channel. To send possibly several
518 // bypass or inline commands to the given channel. The timeout parameter
519 // indicates how many HUNDREDTHS OF SECONDS to wait until there is room:
520 // 0 = return immediately if no room, -ive  = wait forever, +ive = number of
521 // 1/100 seconds to wait. Return values:
522 // -1 Some kind of nasty error: bad channel structure or invalid arguments.
523 //  0 No room to send all the commands
524 // (+)   Number of commands sent
525 //******************************************************************************
526 static int
527 i2QueueCommands(int type, i2ChanStrPtr pCh, int timeout, int nCommands,
528                                          cmdSyntaxPtr pCs0,...)
529 {
530         int totalsize = 0;
531         int blocksize;
532         int lastended;
533         cmdSyntaxPtr *ppCs;
534         cmdSyntaxPtr pCs;
535         int count;
536         int flag;
537         i2eBordStrPtr pB;
538
539         unsigned short maxBlock;
540         unsigned short maxBuff;
541         short bufroom;
542         unsigned short stuffIndex;
543         unsigned char *pBuf;
544         unsigned char *pInsert;
545         unsigned char *pDest, *pSource;
546         unsigned short channel;
547         int cnt;
548         unsigned long flags = 0;
549         rwlock_t *lock_var_p = NULL;
550
551         // Make sure the channel exists, otherwise do nothing
552         if ( !i2Validate ( pCh ) ) {
553                 return -1;
554         }
555
556         ip2trace (CHANN, ITRC_QUEUE, ITRC_ENTER, 0 );
557
558         pB = pCh->pMyBord;
559
560         // Board must also exist, and THE INTERRUPT COMMAND ALREADY SENT
561         if (pB->i2eValid != I2E_MAGIC || pB->i2eUsingIrq == IRQ_UNDEFINED) {
562                 return -2;
563         }
564         // If the board has gone fatal, return bad, and also hit the trap routine if
565         // it exists.
566         if (pB->i2eFatal) {
567                 if ( pB->i2eFatalTrap ) {
568                         (*(pB)->i2eFatalTrap)(pB);
569                 }
570                 return -3;
571         }
572         // Set up some variables, Which buffers are we using?  How big are they?
573         switch(type)
574         {
575         case PTYPE_INLINE:
576                 flag = INL;
577                 maxBlock = MAX_OBUF_BLOCK;
578                 maxBuff = OBUF_SIZE;
579                 pBuf = pCh->Obuf;
580                 break;
581         case PTYPE_BYPASS:
582                 flag = BYP;
583                 maxBlock = MAX_CBUF_BLOCK;
584                 maxBuff = CBUF_SIZE;
585                 pBuf = pCh->Cbuf;
586                 break;
587         default:
588                 return -4;
589         }
590         // Determine the total size required for all the commands
591         totalsize = blocksize = sizeof(i2CmdHeader);
592         lastended = 0;
593         ppCs = &pCs0;
594         for ( count = nCommands; count; count--, ppCs++)
595         {
596                 pCs = *ppCs;
597                 cnt = pCs->length;
598                 // Will a new block be needed for this one? 
599                 // Two possible reasons: too
600                 // big or previous command has to be at the end of a packet.
601                 if ((blocksize + cnt > maxBlock) || lastended) {
602                         blocksize = sizeof(i2CmdHeader);
603                         totalsize += sizeof(i2CmdHeader);
604                 }
605                 totalsize += cnt;
606                 blocksize += cnt;
607
608                 // If this command had to end a block, then we will make sure to
609                 // account for it should there be any more blocks.
610                 lastended = pCs->flags & END;
611         }
612         for (;;) {
613                 // Make sure any pending flush commands go out before we add more data.
614                 if ( !( pCh->flush_flags && i2RetryFlushOutput( pCh ) ) ) {
615                         // How much room (this time through) ?
616                         switch(type) {
617                         case PTYPE_INLINE:
618                                 lock_var_p = &pCh->Obuf_spinlock;
619                                 WRITE_LOCK_IRQSAVE(lock_var_p,flags);
620                                 stuffIndex = pCh->Obuf_stuff;
621                                 bufroom = pCh->Obuf_strip - stuffIndex;
622                                 break;
623                         case PTYPE_BYPASS:
624                                 lock_var_p = &pCh->Cbuf_spinlock;
625                                 WRITE_LOCK_IRQSAVE(lock_var_p,flags);
626                                 stuffIndex = pCh->Cbuf_stuff;
627                                 bufroom = pCh->Cbuf_strip - stuffIndex;
628                                 break;
629                         default:
630                                 return -5;
631                         }
632                         if (--bufroom < 0) {
633                                 bufroom += maxBuff;
634                         }
635
636                         ip2trace (CHANN, ITRC_QUEUE, 2, 1, bufroom );
637
638                         // Check for overflow
639                         if (totalsize <= bufroom) {
640                                 // Normal Expected path - We still hold LOCK
641                                 break; /* from for()- Enough room: goto proceed */
642                         }
643                 }
644
645                 ip2trace (CHANN, ITRC_QUEUE, 3, 1, totalsize );
646
647                 // Prepare to wait for buffers to empty
648                 WRITE_UNLOCK_IRQRESTORE(lock_var_p,flags); 
649                 serviceOutgoingFifo(pB);        // Dump what we got
650
651                 if (timeout == 0) {
652                         return 0;   // Tired of waiting
653                 }
654                 if (timeout > 0)
655                         timeout--;   // So negative values == forever
656                 
657                 if (!in_interrupt()) {
658                         schedule_timeout_interruptible(1);      // short nap
659                 } else {
660                         // we cannot sched/sleep in interrrupt silly
661                         return 0;   
662                 }
663                 if (signal_pending(current)) {
664                         return 0;   // Wake up! Time to die!!!
665                 }
666
667                 ip2trace (CHANN, ITRC_QUEUE, 4, 0 );
668
669         }       // end of for(;;)
670
671         // At this point we have room and the lock - stick them in.
672         channel = pCh->infl.hd.i2sChannel;
673         pInsert = &pBuf[stuffIndex];     // Pointer to start of packet
674         pDest = CMD_OF(pInsert);         // Pointer to start of command
675
676         // When we start counting, the block is the size of the header
677         for (blocksize = sizeof(i2CmdHeader), count = nCommands,
678                         lastended = 0, ppCs = &pCs0;
679                 count;
680                 count--, ppCs++)
681         {
682                 pCs = *ppCs;         // Points to command protocol structure
683
684                 // If this is a bookmark request command, post the fact that a bookmark
685                 // request is pending. NOTE THIS TRICK ONLY WORKS BECAUSE CMD_BMARK_REQ
686                 // has no parameters!  The more general solution would be to reference
687                 // pCs->cmd[0].
688                 if (pCs == CMD_BMARK_REQ) {
689                         pCh->bookMarks++;
690
691                         ip2trace (CHANN, ITRC_DRAIN, 30, 1, pCh->bookMarks );
692
693                 }
694                 cnt = pCs->length;
695
696                 // If this command would put us over the maximum block size or 
697                 // if the last command had to be at the end of a block, we end
698                 // the existing block here and start a new one.
699                 if ((blocksize + cnt > maxBlock) || lastended) {
700
701                         ip2trace (CHANN, ITRC_QUEUE, 5, 0 );
702
703                         PTYPE_OF(pInsert) = type;
704                         CHANNEL_OF(pInsert) = channel;
705                         // count here does not include the header
706                         CMD_COUNT_OF(pInsert) = blocksize - sizeof(i2CmdHeader);
707                         stuffIndex += blocksize;
708                         if(stuffIndex >= maxBuff) {
709                                 stuffIndex = 0;
710                                 pInsert = pBuf;
711                         }
712                         pInsert = &pBuf[stuffIndex];  // Pointer to start of next pkt
713                         pDest = CMD_OF(pInsert);
714                         blocksize = sizeof(i2CmdHeader);
715                 }
716                 // Now we know there is room for this one in the current block
717
718                 blocksize += cnt;       // Total bytes in this command
719                 pSource = pCs->cmd;     // Copy the command into the buffer
720                 while (cnt--) {
721                         *pDest++ = *pSource++;
722                 }
723                 // If this command had to end a block, then we will make sure to account
724                 // for it should there be any more blocks.
725                 lastended = pCs->flags & END;
726         }       // end for
727         // Clean up the final block by writing header, etc
728
729         PTYPE_OF(pInsert) = type;
730         CHANNEL_OF(pInsert) = channel;
731         // count here does not include the header
732         CMD_COUNT_OF(pInsert) = blocksize - sizeof(i2CmdHeader);
733         stuffIndex += blocksize;
734         if(stuffIndex >= maxBuff) {
735                 stuffIndex = 0;
736                 pInsert = pBuf;
737         }
738         // Updates the index, and post the need for service. When adding these to
739         // the queue of channels, we turn off the interrupt while doing so,
740         // because at interrupt level we might want to push a channel back to the
741         // end of the queue.
742         switch(type)
743         {
744         case PTYPE_INLINE:
745                 pCh->Obuf_stuff = stuffIndex;  // Store buffer pointer
746                 WRITE_UNLOCK_IRQRESTORE(&pCh->Obuf_spinlock,flags); 
747
748                 pB->debugInlineQueued++;
749                 // Add the channel pointer to list of channels needing service (first
750                 // come...), if it's not already there.
751                 i2QueueNeeds(pB, pCh, NEED_INLINE);
752                 break;
753
754         case PTYPE_BYPASS:
755                 pCh->Cbuf_stuff = stuffIndex;  // Store buffer pointer
756                 WRITE_UNLOCK_IRQRESTORE(&pCh->Cbuf_spinlock,flags); 
757
758                 pB->debugBypassQueued++;
759                 // Add the channel pointer to list of channels needing service (first
760                 // come...), if it's not already there.
761                 i2QueueNeeds(pB, pCh, NEED_BYPASS);
762                 break;
763         }
764
765         ip2trace (CHANN, ITRC_QUEUE, ITRC_RETURN, 1, nCommands );
766
767         return nCommands; // Good status: number of commands sent
768 }
769
770 //******************************************************************************
771 // Function:   i2GetStatus(pCh,resetBits)
772 // Parameters: Pointer to a channel structure
773 //             Bit map of status bits to clear
774 // Returns:    Bit map of current status bits
775 //
776 // Description:
777 // Returns the state of data set signals, and whether a break has been received,
778 // (see i2lib.h for bit-mapped result). resetBits is a bit-map of any status
779 // bits to be cleared: I2_BRK, I2_PAR, I2_FRA, I2_OVR,... These are cleared
780 // AFTER the condition is passed. If pCh does not point to a valid channel,
781 // returns -1 (which would be impossible otherwise.
782 //******************************************************************************
783 static int
784 i2GetStatus(i2ChanStrPtr pCh, int resetBits)
785 {
786         unsigned short status;
787         i2eBordStrPtr pB;
788
789         ip2trace (CHANN, ITRC_STATUS, ITRC_ENTER, 2, pCh->dataSetIn, resetBits );
790
791         // Make sure the channel exists, otherwise do nothing */
792         if ( !i2Validate ( pCh ) )
793                 return -1;
794
795         pB = pCh->pMyBord;
796
797         status = pCh->dataSetIn;
798
799         // Clear any specified error bits: but note that only actual error bits can
800         // be cleared, regardless of the value passed.
801         if (resetBits)
802         {
803                 pCh->dataSetIn &= ~(resetBits & (I2_BRK | I2_PAR | I2_FRA | I2_OVR));
804                 pCh->dataSetIn &= ~(I2_DDCD | I2_DCTS | I2_DDSR | I2_DRI);
805         }
806
807         ip2trace (CHANN, ITRC_STATUS, ITRC_RETURN, 1, pCh->dataSetIn );
808
809         return status;
810 }
811
812 //******************************************************************************
813 // Function:   i2Input(pChpDest,count)
814 // Parameters: Pointer to a channel structure
815 //             Pointer to data buffer
816 //             Number of bytes to read
817 // Returns:    Number of bytes read, or -1 for error
818 //
819 // Description:
820 // Strips data from the input buffer and writes it to pDest. If there is a
821 // collosal blunder, (invalid structure pointers or the like), returns -1.
822 // Otherwise, returns the number of bytes read.
823 //******************************************************************************
824 static int
825 i2Input(i2ChanStrPtr pCh)
826 {
827         int amountToMove;
828         unsigned short stripIndex;
829         int count;
830         unsigned long flags = 0;
831
832         ip2trace (CHANN, ITRC_INPUT, ITRC_ENTER, 0);
833
834         // Ensure channel structure seems real
835         if ( !i2Validate( pCh ) ) {
836                 count = -1;
837                 goto i2Input_exit;
838         }
839         WRITE_LOCK_IRQSAVE(&pCh->Ibuf_spinlock,flags);
840
841         // initialize some accelerators and private copies
842         stripIndex = pCh->Ibuf_strip;
843
844         count = pCh->Ibuf_stuff - stripIndex;
845
846         // If buffer is empty or requested data count was 0, (trivial case) return
847         // without any further thought.
848         if ( count == 0 ) {
849                 WRITE_UNLOCK_IRQRESTORE(&pCh->Ibuf_spinlock,flags);
850                 goto i2Input_exit;
851         }
852         // Adjust for buffer wrap
853         if ( count < 0 ) {
854                 count += IBUF_SIZE;
855         }
856         // Don't give more than can be taken by the line discipline
857         amountToMove = pCh->pTTY->ldisc.receive_room( pCh->pTTY );
858         if (count > amountToMove) {
859                 count = amountToMove;
860         }
861         // How much could we copy without a wrap?
862         amountToMove = IBUF_SIZE - stripIndex;
863
864         if (amountToMove > count) {
865                 amountToMove = count;
866         }
867         // Move the first block
868         pCh->pTTY->ldisc.receive_buf( pCh->pTTY, 
869                  &(pCh->Ibuf[stripIndex]), NULL, amountToMove );
870         // If we needed to wrap, do the second data move
871         if (count > amountToMove) {
872                 pCh->pTTY->ldisc.receive_buf( pCh->pTTY, 
873                  pCh->Ibuf, NULL, count - amountToMove );
874         }
875         // Bump and wrap the stripIndex all at once by the amount of data read. This
876         // method is good regardless of whether the data was in one or two pieces.
877         stripIndex += count;
878         if (stripIndex >= IBUF_SIZE) {
879                 stripIndex -= IBUF_SIZE;
880         }
881         pCh->Ibuf_strip = stripIndex;
882
883         // Update our flow control information and possibly queue ourselves to send
884         // it, depending on how much data has been stripped since the last time a
885         // packet was sent.
886         pCh->infl.asof += count;
887
888         if ((pCh->sinceLastFlow += count) >= pCh->whenSendFlow) {
889                 pCh->sinceLastFlow -= pCh->whenSendFlow;
890                 WRITE_UNLOCK_IRQRESTORE(&pCh->Ibuf_spinlock,flags);
891                 i2QueueNeeds(pCh->pMyBord, pCh, NEED_FLOW);
892         } else {
893                 WRITE_UNLOCK_IRQRESTORE(&pCh->Ibuf_spinlock,flags);
894         }
895
896 i2Input_exit:
897
898         ip2trace (CHANN, ITRC_INPUT, ITRC_RETURN, 1, count);
899
900         return count;
901 }
902
903 //******************************************************************************
904 // Function:   i2InputFlush(pCh)
905 // Parameters: Pointer to a channel structure
906 // Returns:    Number of bytes stripped, or -1 for error
907 //
908 // Description:
909 // Strips any data from the input buffer. If there is a collosal blunder,
910 // (invalid structure pointers or the like), returns -1. Otherwise, returns the
911 // number of bytes stripped.
912 //******************************************************************************
913 static int
914 i2InputFlush(i2ChanStrPtr pCh)
915 {
916         int count;
917         unsigned long flags;
918
919         // Ensure channel structure seems real
920         if ( !i2Validate ( pCh ) )
921                 return -1;
922
923         ip2trace (CHANN, ITRC_INPUT, 10, 0);
924
925         WRITE_LOCK_IRQSAVE(&pCh->Ibuf_spinlock,flags);
926         count = pCh->Ibuf_stuff - pCh->Ibuf_strip;
927
928         // Adjust for buffer wrap
929         if (count < 0) {
930                 count += IBUF_SIZE;
931         }
932
933         // Expedient way to zero out the buffer
934         pCh->Ibuf_strip = pCh->Ibuf_stuff;
935
936
937         // Update our flow control information and possibly queue ourselves to send
938         // it, depending on how much data has been stripped since the last time a
939         // packet was sent.
940
941         pCh->infl.asof += count;
942
943         if ( (pCh->sinceLastFlow += count) >= pCh->whenSendFlow )
944         {
945                 pCh->sinceLastFlow -= pCh->whenSendFlow;
946                 WRITE_UNLOCK_IRQRESTORE(&pCh->Ibuf_spinlock,flags);
947                 i2QueueNeeds(pCh->pMyBord, pCh, NEED_FLOW);
948         } else {
949                 WRITE_UNLOCK_IRQRESTORE(&pCh->Ibuf_spinlock,flags);
950         }
951
952         ip2trace (CHANN, ITRC_INPUT, 19, 1, count);
953
954         return count;
955 }
956
957 //******************************************************************************
958 // Function:   i2InputAvailable(pCh)
959 // Parameters: Pointer to a channel structure
960 // Returns:    Number of bytes available, or -1 for error
961 //
962 // Description:
963 // If there is a collosal blunder, (invalid structure pointers or the like),
964 // returns -1. Otherwise, returns the number of bytes stripped. Otherwise,
965 // returns the number of bytes available in the buffer.
966 //******************************************************************************
967 #if 0
968 static int
969 i2InputAvailable(i2ChanStrPtr pCh)
970 {
971         int count;
972
973         // Ensure channel structure seems real
974         if ( !i2Validate ( pCh ) ) return -1;
975
976
977         // initialize some accelerators and private copies
978         READ_LOCK_IRQSAVE(&pCh->Ibuf_spinlock,flags);
979         count = pCh->Ibuf_stuff - pCh->Ibuf_strip;
980         READ_UNLOCK_IRQRESTORE(&pCh->Ibuf_spinlock,flags);
981
982         // Adjust for buffer wrap
983         if (count < 0)
984         {
985                 count += IBUF_SIZE;
986         }
987
988         return count;
989 }
990 #endif 
991
992 //******************************************************************************
993 // Function:   i2Output(pCh, pSource, count)
994 // Parameters: Pointer to channel structure
995 //             Pointer to source data
996 //             Number of bytes to send
997 // Returns:    Number of bytes sent, or -1 for error
998 //
999 // Description:
1000 // Queues the data at pSource to be sent as data packets to the board. If there
1001 // is a collosal blunder, (invalid structure pointers or the like), returns -1.
1002 // Otherwise, returns the number of bytes written. What if there is not enough
1003 // room for all the data? If pCh->channelOptions & CO_NBLOCK_WRITE is set, then
1004 // we transfer as many characters as we can now, then return. If this bit is
1005 // clear (default), routine will spin along until all the data is buffered.
1006 // Should this occur, the 1-ms delay routine is called while waiting to avoid
1007 // applications that one cannot break out of.
1008 //******************************************************************************
1009 static int
1010 i2Output(i2ChanStrPtr pCh, const char *pSource, int count, int user )
1011 {
1012         i2eBordStrPtr pB;
1013         unsigned char *pInsert;
1014         int amountToMove;
1015         int countOriginal = count;
1016         unsigned short channel;
1017         unsigned short stuffIndex;
1018         unsigned long flags;
1019         int rc = 0;
1020
1021         int bailout = 10;
1022
1023         ip2trace (CHANN, ITRC_OUTPUT, ITRC_ENTER, 2, count, user );
1024
1025         // Ensure channel structure seems real
1026         if ( !i2Validate ( pCh ) ) 
1027                 return -1;
1028
1029         // initialize some accelerators and private copies
1030         pB = pCh->pMyBord;
1031         channel = pCh->infl.hd.i2sChannel;
1032
1033         // If the board has gone fatal, return bad, and also hit the trap routine if
1034         // it exists.
1035         if (pB->i2eFatal) {
1036                 if (pB->i2eFatalTrap) {
1037                         (*(pB)->i2eFatalTrap)(pB);
1038                 }
1039                 return -1;
1040         }
1041         // Proceed as though we would do everything
1042         while ( count > 0 ) {
1043
1044                 // How much room in output buffer is there?
1045                 READ_LOCK_IRQSAVE(&pCh->Obuf_spinlock,flags);
1046                 amountToMove = pCh->Obuf_strip - pCh->Obuf_stuff - 1;
1047                 READ_UNLOCK_IRQRESTORE(&pCh->Obuf_spinlock,flags);
1048                 if (amountToMove < 0) {
1049                         amountToMove += OBUF_SIZE;
1050                 }
1051                 // Subtract off the headers size and see how much room there is for real
1052                 // data. If this is negative, we will discover later.
1053                 amountToMove -= sizeof (i2DataHeader);
1054
1055                 // Don't move more (now) than can go in a single packet
1056                 if ( amountToMove > (int)(MAX_OBUF_BLOCK - sizeof(i2DataHeader)) ) {
1057                         amountToMove = MAX_OBUF_BLOCK - sizeof(i2DataHeader);
1058                 }
1059                 // Don't move more than the count we were given
1060                 if (amountToMove > count) {
1061                         amountToMove = count;
1062                 }
1063                 // Now we know how much we must move: NB because the ring buffers have
1064                 // an overflow area at the end, we needn't worry about wrapping in the
1065                 // middle of a packet.
1066
1067 // Small WINDOW here with no LOCK but I can't call Flush with LOCK
1068 // We would be flushing (or ending flush) anyway
1069
1070                 ip2trace (CHANN, ITRC_OUTPUT, 10, 1, amountToMove );
1071
1072                 if ( !(pCh->flush_flags && i2RetryFlushOutput(pCh) ) 
1073                                 && amountToMove > 0 )
1074                 {
1075                         WRITE_LOCK_IRQSAVE(&pCh->Obuf_spinlock,flags);
1076                         stuffIndex = pCh->Obuf_stuff;
1077       
1078                         // Had room to move some data: don't know whether the block size,
1079                         // buffer space, or what was the limiting factor...
1080                         pInsert = &(pCh->Obuf[stuffIndex]);
1081
1082                         // Set up the header
1083                         CHANNEL_OF(pInsert)     = channel;
1084                         PTYPE_OF(pInsert)       = PTYPE_DATA;
1085                         TAG_OF(pInsert)         = 0;
1086                         ID_OF(pInsert)          = ID_ORDINARY_DATA;
1087                         DATA_COUNT_OF(pInsert)  = amountToMove;
1088
1089                         // Move the data
1090                         if ( user ) {
1091                                 rc = copy_from_user((char*)(DATA_OF(pInsert)), pSource,
1092                                                 amountToMove );
1093                         } else {
1094                                 memcpy( (char*)(DATA_OF(pInsert)), pSource, amountToMove );
1095                         }
1096                         // Adjust pointers and indices
1097                         pSource                                 += amountToMove;
1098                         pCh->Obuf_char_count    += amountToMove;
1099                         stuffIndex                              += amountToMove + sizeof(i2DataHeader);
1100                         count                                   -= amountToMove;
1101
1102                         if (stuffIndex >= OBUF_SIZE) {
1103                                 stuffIndex = 0;
1104                         }
1105                         pCh->Obuf_stuff = stuffIndex;
1106
1107                         WRITE_UNLOCK_IRQRESTORE(&pCh->Obuf_spinlock,flags);
1108
1109                         ip2trace (CHANN, ITRC_OUTPUT, 13, 1, stuffIndex );
1110
1111                 } else {
1112
1113                         // Cannot move data
1114                         // becuz we need to stuff a flush 
1115                         // or amount to move is <= 0
1116
1117                         ip2trace(CHANN, ITRC_OUTPUT, 14, 3,
1118                                 amountToMove,  pB->i2eFifoRemains,
1119                                 pB->i2eWaitingForEmptyFifo );
1120
1121                         // Put this channel back on queue
1122                         // this ultimatly gets more data or wakes write output
1123                         i2QueueNeeds(pB, pCh, NEED_INLINE);
1124
1125                         if ( pB->i2eWaitingForEmptyFifo ) {
1126
1127                                 ip2trace (CHANN, ITRC_OUTPUT, 16, 0 );
1128
1129                                 // or schedule
1130                                 if (!in_interrupt()) {
1131
1132                                         ip2trace (CHANN, ITRC_OUTPUT, 61, 0 );
1133
1134                                         schedule_timeout_interruptible(2);
1135                                         if (signal_pending(current)) {
1136                                                 break;
1137                                         }
1138                                         continue;
1139                                 } else {
1140
1141                                         ip2trace (CHANN, ITRC_OUTPUT, 62, 0 );
1142
1143                                         // let interrupt in = WAS restore_flags()
1144                                         // We hold no lock nor is irq off anymore???
1145                                         
1146                                         break;
1147                                 }
1148                                 break;   // from while(count)
1149                         }
1150                         else if ( pB->i2eFifoRemains < 32 && !pB->i2eTxMailEmpty ( pB ) )
1151                         {
1152                                 ip2trace (CHANN, ITRC_OUTPUT, 19, 2,
1153                                         pB->i2eFifoRemains,
1154                                         pB->i2eTxMailEmpty );
1155
1156                                 break;   // from while(count)
1157                         } else if ( pCh->channelNeeds & NEED_CREDIT ) {
1158
1159                                 ip2trace (CHANN, ITRC_OUTPUT, 22, 0 );
1160
1161                                 break;   // from while(count)
1162                         } else if ( --bailout) {
1163
1164                                 // Try to throw more things (maybe not us) in the fifo if we're
1165                                 // not already waiting for it.
1166         
1167                                 ip2trace (CHANN, ITRC_OUTPUT, 20, 0 );
1168
1169                                 serviceOutgoingFifo(pB);
1170                                 //break;  CONTINUE;
1171                         } else {
1172                                 ip2trace (CHANN, ITRC_OUTPUT, 21, 3,
1173                                         pB->i2eFifoRemains,
1174                                         pB->i2eOutMailWaiting,
1175                                         pB->i2eWaitingForEmptyFifo );
1176
1177                                 break;   // from while(count)
1178                         }
1179                 }
1180         } // End of while(count)
1181
1182         i2QueueNeeds(pB, pCh, NEED_INLINE);
1183
1184         // We drop through either when the count expires, or when there is some
1185         // count left, but there was a non-blocking write.
1186         if (countOriginal > count) {
1187
1188                 ip2trace (CHANN, ITRC_OUTPUT, 17, 2, countOriginal, count );
1189
1190                 serviceOutgoingFifo( pB );
1191         }
1192
1193         ip2trace (CHANN, ITRC_OUTPUT, ITRC_RETURN, 2, countOriginal, count );
1194
1195         return countOriginal - count;
1196 }
1197
1198 //******************************************************************************
1199 // Function:   i2FlushOutput(pCh)
1200 // Parameters: Pointer to a channel structure
1201 // Returns:    Nothing
1202 //
1203 // Description:
1204 // Sends bypass command to start flushing (waiting possibly forever until there
1205 // is room), then sends inline command to stop flushing output, (again waiting
1206 // possibly forever).
1207 //******************************************************************************
1208 static inline void
1209 i2FlushOutput(i2ChanStrPtr pCh)
1210 {
1211
1212         ip2trace (CHANN, ITRC_FLUSH, 1, 1, pCh->flush_flags );
1213
1214         if (pCh->flush_flags)
1215                 return;
1216
1217         if ( 1 != i2QueueCommands(PTYPE_BYPASS, pCh, 0, 1, CMD_STARTFL) ) {
1218                 pCh->flush_flags = STARTFL_FLAG;                // Failed - flag for later
1219
1220                 ip2trace (CHANN, ITRC_FLUSH, 2, 0 );
1221
1222         } else if ( 1 != i2QueueCommands(PTYPE_INLINE, pCh, 0, 1, CMD_STOPFL) ) {
1223                 pCh->flush_flags = STOPFL_FLAG;         // Failed - flag for later
1224
1225                 ip2trace (CHANN, ITRC_FLUSH, 3, 0 );
1226         }
1227 }
1228
1229 static int 
1230 i2RetryFlushOutput(i2ChanStrPtr pCh)
1231 {
1232         int old_flags = pCh->flush_flags;
1233
1234         ip2trace (CHANN, ITRC_FLUSH, 14, 1, old_flags );
1235
1236         pCh->flush_flags = 0;   // Clear flag so we can avoid recursion
1237                                                                         // and queue the commands
1238
1239         if ( old_flags & STARTFL_FLAG ) {
1240                 if ( 1 == i2QueueCommands(PTYPE_BYPASS, pCh, 0, 1, CMD_STARTFL) ) {
1241                         old_flags = STOPFL_FLAG;        //Success - send stop flush
1242                 } else {
1243                         old_flags = STARTFL_FLAG;       //Failure - Flag for retry later
1244                 }
1245
1246                 ip2trace (CHANN, ITRC_FLUSH, 15, 1, old_flags );
1247
1248         }
1249         if ( old_flags & STOPFL_FLAG ) {
1250                 if (1 == i2QueueCommands(PTYPE_INLINE, pCh, 0, 1, CMD_STOPFL)) {
1251                         old_flags = 0;  // Success - clear flags
1252                 }
1253
1254                 ip2trace (CHANN, ITRC_FLUSH, 16, 1, old_flags );
1255         }
1256         pCh->flush_flags = old_flags;
1257
1258         ip2trace (CHANN, ITRC_FLUSH, 17, 1, old_flags );
1259
1260         return old_flags;
1261 }
1262
1263 //******************************************************************************
1264 // Function:   i2DrainOutput(pCh,timeout)
1265 // Parameters: Pointer to a channel structure
1266 //             Maximum period to wait
1267 // Returns:    ?
1268 //
1269 // Description:
1270 // Uses the bookmark request command to ask the board to send a bookmark back as
1271 // soon as all the data is completely sent.
1272 //******************************************************************************
1273 static void
1274 i2DrainWakeup(i2ChanStrPtr pCh)
1275 {
1276         ip2trace (CHANN, ITRC_DRAIN, 10, 1, pCh->BookmarkTimer.expires );
1277
1278         pCh->BookmarkTimer.expires = 0;
1279         wake_up_interruptible( &pCh->pBookmarkWait );
1280 }
1281
1282 static void
1283 i2DrainOutput(i2ChanStrPtr pCh, int timeout)
1284 {
1285         wait_queue_t wait;
1286         i2eBordStrPtr pB;
1287
1288         ip2trace (CHANN, ITRC_DRAIN, ITRC_ENTER, 1, pCh->BookmarkTimer.expires);
1289
1290         pB = pCh->pMyBord;
1291         // If the board has gone fatal, return bad, 
1292         // and also hit the trap routine if it exists.
1293         if (pB->i2eFatal) {
1294                 if (pB->i2eFatalTrap) {
1295                         (*(pB)->i2eFatalTrap)(pB);
1296                 }
1297                 return;
1298         }
1299         if ((timeout > 0) && (pCh->BookmarkTimer.expires == 0 )) {
1300                 // One per customer (channel)
1301                 init_timer( &(pCh->BookmarkTimer) );
1302                 pCh->BookmarkTimer.expires  = jiffies + timeout;
1303                 pCh->BookmarkTimer.function = (void*)(unsigned long)i2DrainWakeup;
1304                 pCh->BookmarkTimer.data     = (unsigned long)pCh;
1305
1306                 ip2trace (CHANN, ITRC_DRAIN, 1, 1, pCh->BookmarkTimer.expires );
1307
1308                 add_timer( &(pCh->BookmarkTimer) );
1309         }
1310         
1311         i2QueueCommands( PTYPE_INLINE, pCh, -1, 1, CMD_BMARK_REQ );
1312
1313         init_waitqueue_entry(&wait, current);
1314         add_wait_queue(&(pCh->pBookmarkWait), &wait);
1315         set_current_state( TASK_INTERRUPTIBLE );
1316
1317         serviceOutgoingFifo( pB );
1318         
1319         schedule();     // Now we take our interruptible sleep on
1320
1321         // Clean up the queue
1322         set_current_state( TASK_RUNNING );
1323         remove_wait_queue(&(pCh->pBookmarkWait), &wait);
1324
1325         // if expires == 0 then timer poped, then do not need to del_timer
1326         if ((timeout > 0) && pCh->BookmarkTimer.expires && 
1327                              time_before(jiffies, pCh->BookmarkTimer.expires)) {
1328                 del_timer( &(pCh->BookmarkTimer) );
1329                 pCh->BookmarkTimer.expires = 0;
1330
1331                 ip2trace (CHANN, ITRC_DRAIN, 3, 1, pCh->BookmarkTimer.expires );
1332
1333         }
1334         ip2trace (CHANN, ITRC_DRAIN, ITRC_RETURN, 1, pCh->BookmarkTimer.expires );
1335         return;
1336 }
1337
1338 //******************************************************************************
1339 // Function:   i2OutputFree(pCh)
1340 // Parameters: Pointer to a channel structure
1341 // Returns:    Space in output buffer
1342 //
1343 // Description:
1344 // Returns -1 if very gross error. Otherwise returns the amount of bytes still
1345 // free in the output buffer.
1346 //******************************************************************************
1347 static int
1348 i2OutputFree(i2ChanStrPtr pCh)
1349 {
1350         int amountToMove;
1351         unsigned long flags;
1352
1353         // Ensure channel structure seems real
1354         if ( !i2Validate ( pCh ) ) {
1355                 return -1;
1356         }
1357         READ_LOCK_IRQSAVE(&pCh->Obuf_spinlock,flags);
1358         amountToMove = pCh->Obuf_strip - pCh->Obuf_stuff - 1;
1359         READ_UNLOCK_IRQRESTORE(&pCh->Obuf_spinlock,flags);
1360
1361         if (amountToMove < 0) {
1362                 amountToMove += OBUF_SIZE;
1363         }
1364         // If this is negative, we will discover later
1365         amountToMove -= sizeof(i2DataHeader);
1366
1367         return (amountToMove < 0) ? 0 : amountToMove;
1368 }
1369 static void
1370
1371 ip2_owake( PTTY tp)
1372 {
1373         i2ChanStrPtr  pCh;
1374
1375         if (tp == NULL) return;
1376
1377         pCh = tp->driver_data;
1378
1379         ip2trace (CHANN, ITRC_SICMD, 10, 2, tp->flags,
1380                         (1 << TTY_DO_WRITE_WAKEUP) );
1381
1382         wake_up_interruptible ( &tp->write_wait );
1383         if ( ( tp->flags & (1 << TTY_DO_WRITE_WAKEUP) ) 
1384           && tp->ldisc.write_wakeup )
1385         {
1386                 (tp->ldisc.write_wakeup) ( tp );
1387
1388                 ip2trace (CHANN, ITRC_SICMD, 11, 0 );
1389
1390         }
1391 }
1392
1393 static inline void
1394 set_baud_params(i2eBordStrPtr pB) 
1395 {
1396         int i,j;
1397         i2ChanStrPtr  *pCh;
1398
1399         pCh = (i2ChanStrPtr *) pB->i2eChannelPtr;
1400
1401         for (i = 0; i < ABS_MAX_BOXES; i++) {
1402                 if (pB->channelBtypes.bid_value[i]) {
1403                         if (BID_HAS_654(pB->channelBtypes.bid_value[i])) {
1404                                 for (j = 0; j < ABS_BIGGEST_BOX; j++) {
1405                                         if (pCh[i*16+j] == NULL)
1406                                                 break;
1407                                         (pCh[i*16+j])->BaudBase    = 921600;    // MAX for ST654
1408                                         (pCh[i*16+j])->BaudDivisor = 96;
1409                                 }
1410                         } else {        // has cirrus cd1400
1411                                 for (j = 0; j < ABS_BIGGEST_BOX; j++) {
1412                                         if (pCh[i*16+j] == NULL)
1413                                                 break;
1414                                         (pCh[i*16+j])->BaudBase    = 115200;    // MAX for CD1400
1415                                         (pCh[i*16+j])->BaudDivisor = 12;
1416                                 }
1417                         }
1418                 }
1419         }
1420 }
1421
1422 //******************************************************************************
1423 // Function:   i2StripFifo(pB)
1424 // Parameters: Pointer to a board structure
1425 // Returns:    ?
1426 //
1427 // Description:
1428 // Strips all the available data from the incoming FIFO, identifies the type of
1429 // packet, and either buffers the data or does what needs to be done.
1430 //
1431 // Note there is no overflow checking here: if the board sends more data than it
1432 // ought to, we will not detect it here, but blindly overflow...
1433 //******************************************************************************
1434
1435 // A buffer for reading in blocks for unknown channels
1436 static unsigned char junkBuffer[IBUF_SIZE];
1437
1438 // A buffer to read in a status packet. Because of the size of the count field
1439 // for these things, the maximum packet size must be less than MAX_CMD_PACK_SIZE
1440 static unsigned char cmdBuffer[MAX_CMD_PACK_SIZE + 4];
1441
1442 // This table changes the bit order from MSR order given by STAT_MODEM packet to
1443 // status bits used in our library.
1444 static char xlatDss[16] = {
1445 0      | 0     | 0      | 0      ,
1446 0      | 0     | 0      | I2_CTS ,
1447 0      | 0     | I2_DSR | 0      ,
1448 0      | 0     | I2_DSR | I2_CTS ,
1449 0      | I2_RI | 0      | 0      ,
1450 0      | I2_RI | 0      | I2_CTS ,
1451 0      | I2_RI | I2_DSR | 0      ,
1452 0      | I2_RI | I2_DSR | I2_CTS ,
1453 I2_DCD | 0     | 0      | 0      ,
1454 I2_DCD | 0     | 0      | I2_CTS ,
1455 I2_DCD | 0     | I2_DSR | 0      ,
1456 I2_DCD | 0     | I2_DSR | I2_CTS ,
1457 I2_DCD | I2_RI | 0      | 0      ,
1458 I2_DCD | I2_RI | 0      | I2_CTS ,
1459 I2_DCD | I2_RI | I2_DSR | 0      ,
1460 I2_DCD | I2_RI | I2_DSR | I2_CTS };
1461
1462 static inline void
1463 i2StripFifo(i2eBordStrPtr pB)
1464 {
1465         i2ChanStrPtr pCh;
1466         int channel;
1467         int count;
1468         unsigned short stuffIndex;
1469         int amountToRead;
1470         unsigned char *pc, *pcLimit;
1471         unsigned char uc;
1472         unsigned char dss_change;
1473         unsigned long bflags,cflags;
1474
1475 //      ip2trace (ITRC_NO_PORT, ITRC_SFIFO, ITRC_ENTER, 0 );
1476
1477         while (HAS_INPUT(pB)) {
1478 //              ip2trace (ITRC_NO_PORT, ITRC_SFIFO, 2, 0 );
1479
1480                 // Process packet from fifo a one atomic unit
1481                 WRITE_LOCK_IRQSAVE(&pB->read_fifo_spinlock,bflags);
1482    
1483                 // The first word (or two bytes) will have channel number and type of
1484                 // packet, possibly other information
1485                 pB->i2eLeadoffWord[0] = iiReadWord(pB);
1486
1487                 switch(PTYPE_OF(pB->i2eLeadoffWord))
1488                 {
1489                 case PTYPE_DATA:
1490                         pB->got_input = 1;
1491
1492 //                      ip2trace (ITRC_NO_PORT, ITRC_SFIFO, 3, 0 );
1493
1494                         channel = CHANNEL_OF(pB->i2eLeadoffWord); /* Store channel */
1495                         count = iiReadWord(pB);          /* Count is in the next word */
1496
1497 // NEW: Check the count for sanity! Should the hardware fail, our death
1498 // is more pleasant. While an oversize channel is acceptable (just more
1499 // than the driver supports), an over-length count clearly means we are
1500 // sick!
1501                         if ( ((unsigned int)count) > IBUF_SIZE ) {
1502                                 pB->i2eFatal = 2;
1503                                 WRITE_UNLOCK_IRQRESTORE(&pB->read_fifo_spinlock,bflags);
1504                                 return;     /* Bail out ASAP */
1505                         }
1506                         // Channel is illegally big ?
1507                         if ((channel >= pB->i2eChannelCnt) ||
1508                                 (NULL==(pCh = ((i2ChanStrPtr*)pB->i2eChannelPtr)[channel])))
1509                         {
1510                                 iiReadBuf(pB, junkBuffer, count);
1511                                 WRITE_UNLOCK_IRQRESTORE(&pB->read_fifo_spinlock,bflags);
1512                                 break;         /* From switch: ready for next packet */
1513                         }
1514
1515                         // Channel should be valid, then
1516
1517                         // If this is a hot-key, merely post its receipt for now. These are
1518                         // always supposed to be 1-byte packets, so we won't even check the
1519                         // count. Also we will post an acknowledgement to the board so that
1520                         // more data can be forthcoming. Note that we are not trying to use
1521                         // these sequences in this driver, merely to robustly ignore them.
1522                         if(ID_OF(pB->i2eLeadoffWord) == ID_HOT_KEY)
1523                         {
1524                                 pCh->hotKeyIn = iiReadWord(pB) & 0xff;
1525                                 WRITE_UNLOCK_IRQRESTORE(&pB->read_fifo_spinlock,bflags);
1526                                 i2QueueCommands(PTYPE_BYPASS, pCh, 0, 1, CMD_HOTACK);
1527                                 break;   /* From the switch: ready for next packet */
1528                         }
1529
1530                         // Normal data! We crudely assume there is room for the data in our
1531                         // buffer because the board wouldn't have exceeded his credit limit.
1532                         WRITE_LOCK_IRQSAVE(&pCh->Ibuf_spinlock,cflags);
1533                                                                                                         // We have 2 locks now
1534                         stuffIndex = pCh->Ibuf_stuff;
1535                         amountToRead = IBUF_SIZE - stuffIndex;
1536                         if (amountToRead > count)
1537                                 amountToRead = count;
1538
1539                         // stuffIndex would have been already adjusted so there would 
1540                         // always be room for at least one, and count is always at least
1541                         // one.
1542
1543                         iiReadBuf(pB, &(pCh->Ibuf[stuffIndex]), amountToRead);
1544                         pCh->icount.rx += amountToRead;
1545
1546                         // Update the stuffIndex by the amount of data moved. Note we could
1547                         // never ask for more data than would just fit. However, we might
1548                         // have read in one more byte than we wanted because the read
1549                         // rounds up to even bytes. If this byte is on the end of the
1550                         // packet, and is padding, we ignore it. If the byte is part of
1551                         // the actual data, we need to move it.
1552
1553                         stuffIndex += amountToRead;
1554
1555                         if (stuffIndex >= IBUF_SIZE) {
1556                                 if ((amountToRead & 1) && (count > amountToRead)) {
1557                                         pCh->Ibuf[0] = pCh->Ibuf[IBUF_SIZE];
1558                                         amountToRead++;
1559                                         stuffIndex = 1;
1560                                 } else {
1561                                         stuffIndex = 0;
1562                                 }
1563                         }
1564
1565                         // If there is anything left over, read it as well
1566                         if (count > amountToRead) {
1567                                 amountToRead = count - amountToRead;
1568                                 iiReadBuf(pB, &(pCh->Ibuf[stuffIndex]), amountToRead);
1569                                 pCh->icount.rx += amountToRead;
1570                                 stuffIndex += amountToRead;
1571                         }
1572
1573                         // Update stuff index
1574                         pCh->Ibuf_stuff = stuffIndex;
1575                         WRITE_UNLOCK_IRQRESTORE(&pCh->Ibuf_spinlock,cflags);
1576                         WRITE_UNLOCK_IRQRESTORE(&pB->read_fifo_spinlock,bflags);
1577
1578 #ifdef USE_IQ
1579                         schedule_work(&pCh->tqueue_input);
1580 #else
1581                         do_input(pCh);
1582 #endif
1583
1584                         // Note we do not need to maintain any flow-control credits at this
1585                         // time:  if we were to increment .asof and decrement .room, there
1586                         // would be no net effect. Instead, when we strip data, we will
1587                         // increment .asof and leave .room unchanged.
1588
1589                         break;   // From switch: ready for next packet
1590
1591                 case PTYPE_STATUS:
1592                         ip2trace (ITRC_NO_PORT, ITRC_SFIFO, 4, 0 );
1593       
1594                         count = CMD_COUNT_OF(pB->i2eLeadoffWord);
1595
1596                         iiReadBuf(pB, cmdBuffer, count);
1597                         // We can release early with buffer grab
1598                         WRITE_UNLOCK_IRQRESTORE(&pB->read_fifo_spinlock,bflags);
1599
1600                         pc = cmdBuffer;
1601                         pcLimit = &(cmdBuffer[count]);
1602
1603                         while (pc < pcLimit) {
1604                                 channel = *pc++;
1605
1606                                 ip2trace (channel, ITRC_SFIFO, 7, 2, channel, *pc );
1607
1608                                 /* check for valid channel */
1609                                 if (channel < pB->i2eChannelCnt
1610                                          && 
1611                                          (pCh = (((i2ChanStrPtr*)pB->i2eChannelPtr)[channel])) != NULL
1612                                         )
1613                                 {
1614                                         dss_change = 0;
1615
1616                                         switch (uc = *pc++)
1617                                         {
1618                                         /* Breaks and modem signals are easy: just update status */
1619                                         case STAT_CTS_UP:
1620                                                 if ( !(pCh->dataSetIn & I2_CTS) )
1621                                                 {
1622                                                         pCh->dataSetIn |= I2_DCTS;
1623                                                         pCh->icount.cts++;
1624                                                         dss_change = 1;
1625                                                 }
1626                                                 pCh->dataSetIn |= I2_CTS;
1627                                                 break;
1628
1629                                         case STAT_CTS_DN:
1630                                                 if ( pCh->dataSetIn & I2_CTS )
1631                                                 {
1632                                                         pCh->dataSetIn |= I2_DCTS;
1633                                                         pCh->icount.cts++;
1634                                                         dss_change = 1;
1635                                                 }
1636                                                 pCh->dataSetIn &= ~I2_CTS;
1637                                                 break;
1638
1639                                         case STAT_DCD_UP:
1640                                                 ip2trace (channel, ITRC_MODEM, 1, 1, pCh->dataSetIn );
1641
1642                                                 if ( !(pCh->dataSetIn & I2_DCD) )
1643                                                 {
1644                                                         ip2trace (CHANN, ITRC_MODEM, 2, 0 );
1645                                                         pCh->dataSetIn |= I2_DDCD;
1646                                                         pCh->icount.dcd++;
1647                                                         dss_change = 1;
1648                                                 }
1649                                                 pCh->dataSetIn |= I2_DCD;
1650
1651                                                 ip2trace (channel, ITRC_MODEM, 3, 1, pCh->dataSetIn );
1652                                                 break;
1653
1654                                         case STAT_DCD_DN:
1655                                                 ip2trace (channel, ITRC_MODEM, 4, 1, pCh->dataSetIn );
1656                                                 if ( pCh->dataSetIn & I2_DCD )
1657                                                 {
1658                                                         ip2trace (channel, ITRC_MODEM, 5, 0 );
1659                                                         pCh->dataSetIn |= I2_DDCD;
1660                                                         pCh->icount.dcd++;
1661                                                         dss_change = 1;
1662                                                 }
1663                                                 pCh->dataSetIn &= ~I2_DCD;
1664
1665                                                 ip2trace (channel, ITRC_MODEM, 6, 1, pCh->dataSetIn );
1666                                                 break;
1667
1668                                         case STAT_DSR_UP:
1669                                                 if ( !(pCh->dataSetIn & I2_DSR) )
1670                                                 {
1671                                                         pCh->dataSetIn |= I2_DDSR;
1672                                                         pCh->icount.dsr++;
1673                                                         dss_change = 1;
1674                                                 }
1675                                                 pCh->dataSetIn |= I2_DSR;
1676                                                 break;
1677
1678                                         case STAT_DSR_DN:
1679                                                 if ( pCh->dataSetIn & I2_DSR )
1680                                                 {
1681                                                         pCh->dataSetIn |= I2_DDSR;
1682                                                         pCh->icount.dsr++;
1683                                                         dss_change = 1;
1684                                                 }
1685                                                 pCh->dataSetIn &= ~I2_DSR;
1686                                                 break;
1687
1688                                         case STAT_RI_UP:
1689                                                 if ( !(pCh->dataSetIn & I2_RI) )
1690                                                 {
1691                                                         pCh->dataSetIn |= I2_DRI;
1692                                                         pCh->icount.rng++;
1693                                                         dss_change = 1;
1694                                                 }
1695                                                 pCh->dataSetIn |= I2_RI ;
1696                                                 break;
1697
1698                                         case STAT_RI_DN:
1699                                                 // to be compat with serial.c
1700                                                 //if ( pCh->dataSetIn & I2_RI )
1701                                                 //{
1702                                                 //      pCh->dataSetIn |= I2_DRI;
1703                                                 //      pCh->icount.rng++; 
1704                                                 //      dss_change = 1;
1705                                                 //}
1706                                                 pCh->dataSetIn &= ~I2_RI ;
1707                                                 break;
1708
1709                                         case STAT_BRK_DET:
1710                                                 pCh->dataSetIn |= I2_BRK;
1711                                                 pCh->icount.brk++;
1712                                                 dss_change = 1;
1713                                                 break;
1714
1715                                         // Bookmarks? one less request we're waiting for
1716                                         case STAT_BMARK:
1717                                                 pCh->bookMarks--;
1718                                                 if (pCh->bookMarks <= 0 ) {
1719                                                         pCh->bookMarks = 0;
1720                                                         wake_up_interruptible( &pCh->pBookmarkWait );
1721
1722                                                 ip2trace (channel, ITRC_DRAIN, 20, 1, pCh->BookmarkTimer.expires );
1723                                                 }
1724                                                 break;
1725
1726                                         // Flow control packets? Update the new credits, and if
1727                                         // someone was waiting for output, queue him up again.
1728                                         case STAT_FLOW:
1729                                                 pCh->outfl.room =
1730                                                         ((flowStatPtr)pc)->room -
1731                                                         (pCh->outfl.asof - ((flowStatPtr)pc)->asof);
1732
1733                                                 ip2trace (channel, ITRC_STFLW, 1, 1, pCh->outfl.room );
1734
1735                                                 if (pCh->channelNeeds & NEED_CREDIT)
1736                                                 {
1737                                                         ip2trace (channel, ITRC_STFLW, 2, 1, pCh->channelNeeds);
1738
1739                                                         pCh->channelNeeds &= ~NEED_CREDIT;
1740                                                         i2QueueNeeds(pB, pCh, NEED_INLINE);
1741                                                         if ( pCh->pTTY )
1742                                                                 ip2_owake(pCh->pTTY);
1743                                                 }
1744
1745                                                 ip2trace (channel, ITRC_STFLW, 3, 1, pCh->channelNeeds);
1746
1747                                                 pc += sizeof(flowStat);
1748                                                 break;
1749
1750                                         /* Special packets: */
1751                                         /* Just copy the information into the channel structure */
1752
1753                                         case STAT_STATUS:
1754
1755                                                 pCh->channelStatus = *((debugStatPtr)pc);
1756                                                 pc += sizeof(debugStat);
1757                                                 break;
1758
1759                                         case STAT_TXCNT:
1760
1761                                                 pCh->channelTcount = *((cntStatPtr)pc);
1762                                                 pc += sizeof(cntStat);
1763                                                 break;
1764
1765                                         case STAT_RXCNT:
1766
1767                                                 pCh->channelRcount = *((cntStatPtr)pc);
1768                                                 pc += sizeof(cntStat);
1769                                                 break;
1770
1771                                         case STAT_BOXIDS:
1772                                                 pB->channelBtypes = *((bidStatPtr)pc);
1773                                                 pc += sizeof(bidStat);
1774                                                 set_baud_params(pB);
1775                                                 break;
1776
1777                                         case STAT_HWFAIL:
1778                                                 i2QueueCommands (PTYPE_INLINE, pCh, 0, 1, CMD_HW_TEST);
1779                                                 pCh->channelFail = *((failStatPtr)pc);
1780                                                 pc += sizeof(failStat);
1781                                                 break;
1782
1783                                         /* No explicit match? then
1784                                          * Might be an error packet...
1785                                          */
1786                                         default:
1787                                                 switch (uc & STAT_MOD_ERROR)
1788                                                 {
1789                                                 case STAT_ERROR:
1790                                                         if (uc & STAT_E_PARITY) {
1791                                                                 pCh->dataSetIn |= I2_PAR;
1792                                                                 pCh->icount.parity++;
1793                                                         }
1794                                                         if (uc & STAT_E_FRAMING){
1795                                                                 pCh->dataSetIn |= I2_FRA;
1796                                                                 pCh->icount.frame++;
1797                                                         }
1798                                                         if (uc & STAT_E_OVERRUN){
1799                                                                 pCh->dataSetIn |= I2_OVR;
1800                                                                 pCh->icount.overrun++;
1801                                                         }
1802                                                         break;
1803
1804                                                 case STAT_MODEM:
1805                                                         // the answer to DSS_NOW request (not change)
1806                                                         pCh->dataSetIn = (pCh->dataSetIn
1807                                                                 & ~(I2_RI | I2_CTS | I2_DCD | I2_DSR) )
1808                                                                 | xlatDss[uc & 0xf];
1809                                                         wake_up_interruptible ( &pCh->dss_now_wait );
1810                                                 default:
1811                                                         break;
1812                                                 }
1813                                         }  /* End of switch on status type */
1814                                         if (dss_change) {
1815 #ifdef USE_IQ
1816                                                 schedule_work(&pCh->tqueue_status);
1817 #else
1818                                                 do_status(pCh);
1819 #endif
1820                                         }
1821                                 }
1822                                 else  /* Or else, channel is invalid */
1823                                 {
1824                                         // Even though the channel is invalid, we must test the
1825                                         // status to see how much additional data it has (to be
1826                                         // skipped)
1827                                         switch (*pc++)
1828                                         {
1829                                         case STAT_FLOW:
1830                                                 pc += 4;    /* Skip the data */
1831                                                 break;
1832
1833                                         default:
1834                                                 break;
1835                                         }
1836                                 }
1837                         }  // End of while (there is still some status packet left)
1838                         break;
1839
1840                 default: // Neither packet? should be impossible
1841                         ip2trace (ITRC_NO_PORT, ITRC_SFIFO, 5, 1,
1842                                 PTYPE_OF(pB->i2eLeadoffWord) );
1843
1844                         break;
1845                 }  // End of switch on type of packets
1846         }       //while(board HAS_INPUT)
1847
1848         ip2trace (ITRC_NO_PORT, ITRC_SFIFO, ITRC_RETURN, 0 );
1849
1850         // Send acknowledgement to the board even if there was no data!
1851         pB->i2eOutMailWaiting |= MB_IN_STRIPPED;
1852         return;
1853 }
1854
1855 //******************************************************************************
1856 // Function:   i2Write2Fifo(pB,address,count)
1857 // Parameters: Pointer to a board structure, source address, byte count
1858 // Returns:    bytes written
1859 //
1860 // Description:
1861 //  Writes count bytes to board io address(implied) from source
1862 //  Adjusts count, leaves reserve for next time around bypass cmds
1863 //******************************************************************************
1864 static int
1865 i2Write2Fifo(i2eBordStrPtr pB, unsigned char *source, int count,int reserve)
1866 {
1867         int rc = 0;
1868         unsigned long flags;
1869         WRITE_LOCK_IRQSAVE(&pB->write_fifo_spinlock,flags);
1870         if (!pB->i2eWaitingForEmptyFifo) {
1871                 if (pB->i2eFifoRemains > (count+reserve)) {
1872                         pB->i2eFifoRemains -= count;
1873                         iiWriteBuf(pB, source, count);
1874                         pB->i2eOutMailWaiting |= MB_OUT_STUFFED;
1875                         rc =  count;
1876                 }
1877         }
1878         WRITE_UNLOCK_IRQRESTORE(&pB->write_fifo_spinlock,flags);
1879         return rc;
1880 }
1881 //******************************************************************************
1882 // Function:   i2StuffFifoBypass(pB)
1883 // Parameters: Pointer to a board structure
1884 // Returns:    Nothing
1885 //
1886 // Description:
1887 // Stuffs as many bypass commands into the fifo as possible. This is simpler
1888 // than stuffing data or inline commands to fifo, since we do not have
1889 // flow-control to deal with.
1890 //******************************************************************************
1891 static inline void
1892 i2StuffFifoBypass(i2eBordStrPtr pB)
1893 {
1894         i2ChanStrPtr pCh;
1895         unsigned char *pRemove;
1896         unsigned short stripIndex;
1897         unsigned short packetSize;
1898         unsigned short paddedSize;
1899         unsigned short notClogged = 1;
1900         unsigned long flags;
1901
1902         int bailout = 1000;
1903
1904         // Continue processing so long as there are entries, or there is room in the
1905         // fifo. Each entry represents a channel with something to do.
1906         while ( --bailout && notClogged && 
1907                         (NULL != (pCh = i2DeQueueNeeds(pB,NEED_BYPASS))))
1908         {
1909                 WRITE_LOCK_IRQSAVE(&pCh->Cbuf_spinlock,flags);
1910                 stripIndex = pCh->Cbuf_strip;
1911
1912                 // as long as there are packets for this channel...
1913
1914                 while (stripIndex != pCh->Cbuf_stuff) {
1915                         pRemove = &(pCh->Cbuf[stripIndex]);
1916                         packetSize = CMD_COUNT_OF(pRemove) + sizeof(i2CmdHeader);
1917                         paddedSize = ROUNDUP(packetSize);
1918
1919                         if (paddedSize > 0) {
1920                                 if ( 0 == i2Write2Fifo(pB, pRemove, paddedSize,0)) {
1921                                         notClogged = 0; /* fifo full */
1922                                         i2QueueNeeds(pB, pCh, NEED_BYPASS);     // Put back on queue
1923                                         break;   // Break from the channel
1924                                 } 
1925                         }
1926 #ifdef DEBUG_FIFO
1927 WriteDBGBuf("BYPS", pRemove, paddedSize);
1928 #endif  /* DEBUG_FIFO */
1929                         pB->debugBypassCount++;
1930
1931                         pRemove += packetSize;
1932                         stripIndex += packetSize;
1933                         if (stripIndex >= CBUF_SIZE) {
1934                                 stripIndex = 0;
1935                                 pRemove = pCh->Cbuf;
1936                         }
1937                 }
1938                 // Done with this channel. Move to next, removing this one from 
1939                 // the queue of channels if we cleaned it out (i.e., didn't get clogged.
1940                 pCh->Cbuf_strip = stripIndex;
1941                 WRITE_UNLOCK_IRQRESTORE(&pCh->Cbuf_spinlock,flags);
1942         }  // Either clogged or finished all the work
1943
1944 #ifdef IP2DEBUG_TRACE
1945         if ( !bailout ) {
1946                 ip2trace (ITRC_NO_PORT, ITRC_ERROR, 1, 0 );
1947         }
1948 #endif
1949 }
1950
1951 //******************************************************************************
1952 // Function:   i2StuffFifoFlow(pB)
1953 // Parameters: Pointer to a board structure
1954 // Returns:    Nothing
1955 //
1956 // Description:
1957 // Stuffs as many flow control packets into the fifo as possible. This is easier
1958 // even than doing normal bypass commands, because there is always at most one
1959 // packet, already assembled, for each channel.
1960 //******************************************************************************
1961 static inline void
1962 i2StuffFifoFlow(i2eBordStrPtr pB)
1963 {
1964         i2ChanStrPtr pCh;
1965         unsigned short paddedSize               = ROUNDUP(sizeof(flowIn));
1966
1967         ip2trace (ITRC_NO_PORT, ITRC_SFLOW, ITRC_ENTER, 2,
1968                 pB->i2eFifoRemains, paddedSize );
1969
1970         // Continue processing so long as there are entries, or there is room in the
1971         // fifo. Each entry represents a channel with something to do.
1972         while ( (NULL != (pCh = i2DeQueueNeeds(pB,NEED_FLOW)))) {
1973                 pB->debugFlowCount++;
1974
1975                 // NO Chan LOCK needed ???
1976                 if ( 0 == i2Write2Fifo(pB,(unsigned char *)&(pCh->infl),paddedSize,0)) {
1977                         break;
1978                 }
1979 #ifdef DEBUG_FIFO
1980                 WriteDBGBuf("FLOW",(unsigned char *) &(pCh->infl), paddedSize);
1981 #endif /* DEBUG_FIFO */
1982
1983         }  // Either clogged or finished all the work
1984
1985         ip2trace (ITRC_NO_PORT, ITRC_SFLOW, ITRC_RETURN, 0 );
1986 }
1987
1988 //******************************************************************************
1989 // Function:   i2StuffFifoInline(pB)
1990 // Parameters: Pointer to a board structure
1991 // Returns:    Nothing
1992 //
1993 // Description:
1994 // Stuffs as much data and inline commands into the fifo as possible. This is
1995 // the most complex fifo-stuffing operation, since there if now the channel
1996 // flow-control issue to deal with.
1997 //******************************************************************************
1998 static inline void
1999 i2StuffFifoInline(i2eBordStrPtr pB)
2000 {
2001         i2ChanStrPtr pCh;
2002         unsigned char *pRemove;
2003         unsigned short stripIndex;
2004         unsigned short packetSize;
2005         unsigned short paddedSize;
2006         unsigned short notClogged = 1;
2007         unsigned short flowsize;
2008         unsigned long flags;
2009
2010         int bailout  = 1000;
2011         int bailout2;
2012
2013         ip2trace (ITRC_NO_PORT, ITRC_SICMD, ITRC_ENTER, 3, pB->i2eFifoRemains, 
2014                         pB->i2Dbuf_strip, pB->i2Dbuf_stuff );
2015
2016         // Continue processing so long as there are entries, or there is room in the
2017         // fifo. Each entry represents a channel with something to do.
2018         while ( --bailout && notClogged && 
2019                         (NULL != (pCh = i2DeQueueNeeds(pB,NEED_INLINE))) )
2020         {
2021                 WRITE_LOCK_IRQSAVE(&pCh->Obuf_spinlock,flags);
2022                 stripIndex = pCh->Obuf_strip;
2023
2024                 ip2trace (CHANN, ITRC_SICMD, 3, 2, stripIndex, pCh->Obuf_stuff );
2025
2026                 // as long as there are packets for this channel...
2027                 bailout2 = 1000;
2028                 while ( --bailout2 && stripIndex != pCh->Obuf_stuff) {
2029                         pRemove = &(pCh->Obuf[stripIndex]);
2030
2031                         // Must determine whether this be a data or command packet to
2032                         // calculate correctly the header size and the amount of
2033                         // flow-control credit this type of packet will use.
2034                         if (PTYPE_OF(pRemove) == PTYPE_DATA) {
2035                                 flowsize = DATA_COUNT_OF(pRemove);
2036                                 packetSize = flowsize + sizeof(i2DataHeader);
2037                         } else {
2038                                 flowsize = CMD_COUNT_OF(pRemove);
2039                                 packetSize = flowsize + sizeof(i2CmdHeader);
2040                         }
2041                         flowsize = CREDIT_USAGE(flowsize);
2042                         paddedSize = ROUNDUP(packetSize);
2043
2044                         ip2trace (CHANN, ITRC_SICMD, 4, 2, pB->i2eFifoRemains, paddedSize );
2045
2046                         // If we don't have enough credits from the board to send the data,
2047                         // flag the channel that we are waiting for flow control credit, and
2048                         // break out. This will clean up this channel and remove us from the
2049                         // queue of hot things to do.
2050
2051                                 ip2trace (CHANN, ITRC_SICMD, 5, 2, pCh->outfl.room, flowsize );
2052
2053                         if (pCh->outfl.room <= flowsize)        {
2054                                 // Do Not have the credits to send this packet.
2055                                 i2QueueNeeds(pB, pCh, NEED_CREDIT);
2056                                 notClogged = 0;
2057                                 break;   // So to do next channel
2058                         }
2059                         if ( (paddedSize > 0) 
2060                                 && ( 0 == i2Write2Fifo(pB, pRemove, paddedSize, 128))) {
2061                                 // Do Not have room in fifo to send this packet.
2062                                 notClogged = 0;
2063                                 i2QueueNeeds(pB, pCh, NEED_INLINE);     
2064                                 break;   // Break from the channel
2065                         }
2066 #ifdef DEBUG_FIFO
2067 WriteDBGBuf("DATA", pRemove, paddedSize);
2068 #endif /* DEBUG_FIFO */
2069                         pB->debugInlineCount++;
2070
2071                         pCh->icount.tx += flowsize;
2072                         // Update current credits
2073                         pCh->outfl.room -= flowsize;
2074                         pCh->outfl.asof += flowsize;
2075                         if (PTYPE_OF(pRemove) == PTYPE_DATA) {
2076                                 pCh->Obuf_char_count -= DATA_COUNT_OF(pRemove);
2077                         }
2078                         pRemove += packetSize;
2079                         stripIndex += packetSize;
2080
2081                         ip2trace (CHANN, ITRC_SICMD, 6, 2, stripIndex, pCh->Obuf_strip);
2082
2083                         if (stripIndex >= OBUF_SIZE) {
2084                                 stripIndex = 0;
2085                                 pRemove = pCh->Obuf;
2086
2087                                 ip2trace (CHANN, ITRC_SICMD, 7, 1, stripIndex );
2088
2089                         }
2090                 }       /* while */
2091                 if ( !bailout2 ) {
2092                         ip2trace (CHANN, ITRC_ERROR, 3, 0 );
2093                 }
2094                 // Done with this channel. Move to next, removing this one from the
2095                 // queue of channels if we cleaned it out (i.e., didn't get clogged.
2096                 pCh->Obuf_strip = stripIndex;
2097                 WRITE_UNLOCK_IRQRESTORE(&pCh->Obuf_spinlock,flags);
2098                 if ( notClogged )
2099                 {
2100
2101                         ip2trace (CHANN, ITRC_SICMD, 8, 0 );
2102
2103                         if ( pCh->pTTY ) {
2104                                 ip2_owake(pCh->pTTY);
2105                         }
2106                 }
2107         }  // Either clogged or finished all the work
2108
2109         if ( !bailout ) {
2110                 ip2trace (ITRC_NO_PORT, ITRC_ERROR, 4, 0 );
2111         }
2112
2113         ip2trace (ITRC_NO_PORT, ITRC_SICMD, ITRC_RETURN, 1,pB->i2Dbuf_strip);
2114 }
2115
2116 //******************************************************************************
2117 // Function:   serviceOutgoingFifo(pB)
2118 // Parameters: Pointer to a board structure
2119 // Returns:    Nothing
2120 //
2121 // Description:
2122 // Helper routine to put data in the outgoing fifo, if we aren't already waiting
2123 // for something to be there. If the fifo has only room for a very little data,
2124 // go head and hit the board with a mailbox hit immediately. Otherwise, it will
2125 // have to happen later in the interrupt processing. Since this routine may be
2126 // called both at interrupt and foreground time, we must turn off interrupts
2127 // during the entire process.
2128 //******************************************************************************
2129 static void
2130 serviceOutgoingFifo(i2eBordStrPtr pB)
2131 {
2132         // If we aren't currently waiting for the board to empty our fifo, service
2133         // everything that is pending, in priority order (especially, Bypass before
2134         // Inline).
2135         if ( ! pB->i2eWaitingForEmptyFifo )
2136         {
2137                 i2StuffFifoFlow(pB);
2138                 i2StuffFifoBypass(pB);
2139                 i2StuffFifoInline(pB);
2140
2141                 iiSendPendingMail(pB);
2142         } 
2143 }
2144
2145 //******************************************************************************
2146 // Function:   i2ServiceBoard(pB)
2147 // Parameters: Pointer to a board structure
2148 // Returns:    Nothing
2149 //
2150 // Description:
2151 // Normally this is called from interrupt level, but there is deliberately
2152 // nothing in here specific to being called from interrupt level. All the
2153 // hardware-specific, interrupt-specific things happen at the outer levels.
2154 //
2155 // For example, a timer interrupt could drive this routine for some sort of
2156 // polled operation. The only requirement is that the programmer deal with any
2157 // atomiticity/concurrency issues that result.
2158 //
2159 // This routine responds to the board's having sent mailbox information to the
2160 // host (which would normally cause an interrupt). This routine reads the
2161 // incoming mailbox. If there is no data in it, this board did not create the
2162 // interrupt and/or has nothing to be done to it. (Except, if we have been
2163 // waiting to write mailbox data to it, we may do so.
2164 //
2165 // Based on the value in the mailbox, we may take various actions.
2166 //
2167 // No checking here of pB validity: after all, it shouldn't have been called by
2168 // the handler unless pB were on the list.
2169 //******************************************************************************
2170 static inline int
2171 i2ServiceBoard ( i2eBordStrPtr pB )
2172 {
2173         unsigned inmail;
2174         unsigned long flags;
2175
2176
2177         /* This should be atomic because of the way we are called... */
2178         if (NO_MAIL_HERE == ( inmail = pB->i2eStartMail ) ) {
2179                 inmail = iiGetMail(pB);
2180         }
2181         pB->i2eStartMail = NO_MAIL_HERE;
2182
2183         ip2trace (ITRC_NO_PORT, ITRC_INTR, 2, 1, inmail );
2184
2185         if (inmail != NO_MAIL_HERE) {
2186                 // If the board has gone fatal, nothing to do but hit a bit that will
2187                 // alert foreground tasks to protest!
2188                 if ( inmail & MB_FATAL_ERROR ) {
2189                         pB->i2eFatal = 1;
2190                         goto exit_i2ServiceBoard;
2191                 }
2192
2193                 /* Assuming no fatal condition, we proceed to do work */
2194                 if ( inmail & MB_IN_STUFFED ) {
2195                         pB->i2eFifoInInts++;
2196                         i2StripFifo(pB);     /* There might be incoming packets */
2197                 }
2198
2199                 if (inmail & MB_OUT_STRIPPED) {
2200                         pB->i2eFifoOutInts++;
2201                         WRITE_LOCK_IRQSAVE(&pB->write_fifo_spinlock,flags);
2202                         pB->i2eFifoRemains = pB->i2eFifoSize;
2203                         pB->i2eWaitingForEmptyFifo = 0;
2204                         WRITE_UNLOCK_IRQRESTORE(&pB->write_fifo_spinlock,flags);
2205
2206                         ip2trace (ITRC_NO_PORT, ITRC_INTR, 30, 1, pB->i2eFifoRemains );
2207
2208                 }
2209                 serviceOutgoingFifo(pB);
2210         }
2211
2212         ip2trace (ITRC_NO_PORT, ITRC_INTR, 8, 0 );
2213
2214 exit_i2ServiceBoard:
2215
2216         return 0;
2217 }