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