vserver 1.9.3
[linux-2.6.git] / drivers / scsi / sym53c8xx_2 / sym_hipd.c
1 /*
2  * Device driver for the SYMBIOS/LSILOGIC 53C8XX and 53C1010 family 
3  * of PCI-SCSI IO processors.
4  *
5  * Copyright (C) 1999-2001  Gerard Roudier <groudier@free.fr>
6  *
7  * This driver is derived from the Linux sym53c8xx driver.
8  * Copyright (C) 1998-2000  Gerard Roudier
9  *
10  * The sym53c8xx driver is derived from the ncr53c8xx driver that had been 
11  * a port of the FreeBSD ncr driver to Linux-1.2.13.
12  *
13  * The original ncr driver has been written for 386bsd and FreeBSD by
14  *         Wolfgang Stanglmeier        <wolf@cologne.de>
15  *         Stefan Esser                <se@mi.Uni-Koeln.de>
16  * Copyright (C) 1994  Wolfgang Stanglmeier
17  *
18  * Other major contributions:
19  *
20  * NVRAM detection and reading.
21  * Copyright (C) 1997 Richard Waltham <dormouse@farsrobt.demon.co.uk>
22  *
23  *-----------------------------------------------------------------------------
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. The name of the author may not be used to endorse or promote products
31  *    derived from this software without specific prior written permission.
32  *
33  * Where this Software is combined with software released under the terms of 
34  * the GNU Public License ("GPL") and the terms of the GPL would require the 
35  * combined work to also be released under the terms of the GPL, the terms
36  * and conditions of this License will apply in addition to those of the
37  * GPL with the exception of any terms or conditions of this License that
38  * conflict with, or are expressly prohibited by, the GPL.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
44  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  */
52 #include "sym_glue.h"
53 #include "sym_nvram.h"
54
55 #if 0
56 #define SYM_DEBUG_GENERIC_SUPPORT
57 #endif
58
59 /*
60  *  Needed function prototypes.
61  */
62 static void sym_int_ma (hcb_p np);
63 static void sym_int_sir (hcb_p np);
64 static ccb_p sym_alloc_ccb(hcb_p np);
65 static ccb_p sym_ccb_from_dsa(hcb_p np, u32 dsa);
66 static void sym_alloc_lcb_tags (hcb_p np, u_char tn, u_char ln);
67 static void sym_complete_error (hcb_p np, ccb_p cp);
68 static void sym_complete_ok (hcb_p np, ccb_p cp);
69 static int sym_compute_residual(hcb_p np, ccb_p cp);
70
71 /*
72  *  Returns the name of this driver.
73  */
74 char *sym_driver_name(void)
75 {
76         return SYM_DRIVER_NAME;
77 }
78 /*
79  *  Print a buffer in hexadecimal format.
80  */
81 static void sym_printb_hex (u_char *p, int n)
82 {
83         while (n-- > 0)
84                 printf (" %x", *p++);
85 }
86
87 /*
88  *  Same with a label at beginning and .\n at end.
89  */
90 static void sym_printl_hex (char *label, u_char *p, int n)
91 {
92         printf ("%s", label);
93         sym_printb_hex (p, n);
94         printf (".\n");
95 }
96
97 /*
98  *  Print something which allows to retrieve the controler type, 
99  *  unit, target, lun concerned by a kernel message.
100  */
101 static void sym_print_target (hcb_p np, int target)
102 {
103         printf ("%s:%d:", sym_name(np), target);
104 }
105
106 static void sym_print_lun(hcb_p np, int target, int lun)
107 {
108         printf ("%s:%d:%d:", sym_name(np), target, lun);
109 }
110
111 /*
112  *  Print out the content of a SCSI message.
113  */
114 static int sym_show_msg (u_char * msg)
115 {
116         u_char i;
117         printf ("%x",*msg);
118         if (*msg==M_EXTENDED) {
119                 for (i=1;i<8;i++) {
120                         if (i-1>msg[1]) break;
121                         printf ("-%x",msg[i]);
122                 };
123                 return (i+1);
124         } else if ((*msg & 0xf0) == 0x20) {
125                 printf ("-%x",msg[1]);
126                 return (2);
127         };
128         return (1);
129 }
130
131 static void sym_print_msg (ccb_p cp, char *label, u_char *msg)
132 {
133         PRINT_ADDR(cp);
134         if (label)
135                 printf ("%s: ", label);
136
137         (void) sym_show_msg (msg);
138         printf (".\n");
139 }
140
141 static void sym_print_nego_msg (hcb_p np, int target, char *label, u_char *msg)
142 {
143         PRINT_TARGET(np, target);
144         if (label)
145                 printf ("%s: ", label);
146
147         (void) sym_show_msg (msg);
148         printf (".\n");
149 }
150
151 /*
152  *  Print something that tells about extended errors.
153  */
154 void sym_print_xerr(ccb_p cp, int x_status)
155 {
156         if (x_status & XE_PARITY_ERR) {
157                 PRINT_ADDR(cp);
158                 printf ("unrecovered SCSI parity error.\n");
159         }
160         if (x_status & XE_EXTRA_DATA) {
161                 PRINT_ADDR(cp);
162                 printf ("extraneous data discarded.\n");
163         }
164         if (x_status & XE_BAD_PHASE) {
165                 PRINT_ADDR(cp);
166                 printf ("illegal scsi phase (4/5).\n");
167         }
168         if (x_status & XE_SODL_UNRUN) {
169                 PRINT_ADDR(cp);
170                 printf ("ODD transfer in DATA OUT phase.\n");
171         }
172         if (x_status & XE_SWIDE_OVRUN) {
173                 PRINT_ADDR(cp);
174                 printf ("ODD transfer in DATA IN phase.\n");
175         }
176 }
177
178 /*
179  *  Return a string for SCSI BUS mode.
180  */
181 static char *sym_scsi_bus_mode(int mode)
182 {
183         switch(mode) {
184         case SMODE_HVD: return "HVD";
185         case SMODE_SE:  return "SE";
186         case SMODE_LVD: return "LVD";
187         }
188         return "??";
189 }
190
191 /*
192  *  Soft reset the chip.
193  *
194  *  Raising SRST when the chip is running may cause 
195  *  problems on dual function chips (see below).
196  *  On the other hand, LVD devices need some delay 
197  *  to settle and report actual BUS mode in STEST4.
198  */
199 static void sym_chip_reset (hcb_p np)
200 {
201         OUTB (nc_istat, SRST);
202         UDELAY (10);
203         OUTB (nc_istat, 0);
204         UDELAY(2000);   /* For BUS MODE to settle */
205 }
206
207 /*
208  *  Really soft reset the chip.:)
209  *
210  *  Some 896 and 876 chip revisions may hang-up if we set 
211  *  the SRST (soft reset) bit at the wrong time when SCRIPTS 
212  *  are running.
213  *  So, we need to abort the current operation prior to 
214  *  soft resetting the chip.
215  */
216 static void sym_soft_reset (hcb_p np)
217 {
218         u_char istat = 0;
219         int i;
220
221         if (!(np->features & FE_ISTAT1) || !(INB (nc_istat1) & SCRUN))
222                 goto do_chip_reset;
223
224         OUTB (nc_istat, CABRT);
225         for (i = 100000 ; i ; --i) {
226                 istat = INB (nc_istat);
227                 if (istat & SIP) {
228                         INW (nc_sist);
229                 }
230                 else if (istat & DIP) {
231                         if (INB (nc_dstat) & ABRT)
232                                 break;
233                 }
234                 UDELAY(5);
235         }
236         OUTB (nc_istat, 0);
237         if (!i)
238                 printf("%s: unable to abort current chip operation, "
239                        "ISTAT=0x%02x.\n", sym_name(np), istat);
240 do_chip_reset:
241         sym_chip_reset (np);
242 }
243
244 /*
245  *  Start reset process.
246  *
247  *  The interrupt handler will reinitialize the chip.
248  */
249 static void sym_start_reset(hcb_p np)
250 {
251         (void) sym_reset_scsi_bus(np, 1);
252 }
253  
254 int sym_reset_scsi_bus(hcb_p np, int enab_int)
255 {
256         u32 term;
257         int retv = 0;
258
259         sym_soft_reset(np);     /* Soft reset the chip */
260         if (enab_int)
261                 OUTW (nc_sien, RST);
262         /*
263          *  Enable Tolerant, reset IRQD if present and 
264          *  properly set IRQ mode, prior to resetting the bus.
265          */
266         OUTB (nc_stest3, TE);
267         OUTB (nc_dcntl, (np->rv_dcntl & IRQM));
268         OUTB (nc_scntl1, CRST);
269         UDELAY (200);
270
271         if (!SYM_SETUP_SCSI_BUS_CHECK)
272                 goto out;
273         /*
274          *  Check for no terminators or SCSI bus shorts to ground.
275          *  Read SCSI data bus, data parity bits and control signals.
276          *  We are expecting RESET to be TRUE and other signals to be 
277          *  FALSE.
278          */
279         term =  INB(nc_sstat0);
280         term =  ((term & 2) << 7) + ((term & 1) << 17); /* rst sdp0 */
281         term |= ((INB(nc_sstat2) & 0x01) << 26) |       /* sdp1     */
282                 ((INW(nc_sbdl) & 0xff)   << 9)  |       /* d7-0     */
283                 ((INW(nc_sbdl) & 0xff00) << 10) |       /* d15-8    */
284                 INB(nc_sbcl);   /* req ack bsy sel atn msg cd io    */
285
286         if (!np->maxwide)
287                 term &= 0x3ffff;
288
289         if (term != (2<<7)) {
290                 printf("%s: suspicious SCSI data while resetting the BUS.\n",
291                         sym_name(np));
292                 printf("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
293                         "0x%lx, expecting 0x%lx\n",
294                         sym_name(np),
295                         (np->features & FE_WIDE) ? "dp1,d15-8," : "",
296                         (u_long)term, (u_long)(2<<7));
297                 if (SYM_SETUP_SCSI_BUS_CHECK == 1)
298                         retv = 1;
299         }
300 out:
301         OUTB (nc_scntl1, 0);
302         /* MDELAY(100); */
303         return retv;
304 }
305
306 /*
307  *  Select SCSI clock frequency
308  */
309 static void sym_selectclock(hcb_p np, u_char scntl3)
310 {
311         /*
312          *  If multiplier not present or not selected, leave here.
313          */
314         if (np->multiplier <= 1) {
315                 OUTB(nc_scntl3, scntl3);
316                 return;
317         }
318
319         if (sym_verbose >= 2)
320                 printf ("%s: enabling clock multiplier\n", sym_name(np));
321
322         OUTB(nc_stest1, DBLEN);    /* Enable clock multiplier             */
323         /*
324          *  Wait for the LCKFRQ bit to be set if supported by the chip.
325          *  Otherwise wait 50 micro-seconds (at least).
326          */
327         if (np->features & FE_LCKFRQ) {
328                 int i = 20;
329                 while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
330                         UDELAY (20);
331                 if (!i)
332                         printf("%s: the chip cannot lock the frequency\n",
333                                 sym_name(np));
334         } else
335                 UDELAY ((50+10));
336         OUTB(nc_stest3, HSC);           /* Halt the scsi clock          */
337         OUTB(nc_scntl3, scntl3);
338         OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier      */
339         OUTB(nc_stest3, 0x00);          /* Restart scsi clock           */
340 }
341
342
343 /*
344  *  Determine the chip's clock frequency.
345  *
346  *  This is essential for the negotiation of the synchronous 
347  *  transfer rate.
348  *
349  *  Note: we have to return the correct value.
350  *  THERE IS NO SAFE DEFAULT VALUE.
351  *
352  *  Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
353  *  53C860 and 53C875 rev. 1 support fast20 transfers but 
354  *  do not have a clock doubler and so are provided with a 
355  *  80 MHz clock. All other fast20 boards incorporate a doubler 
356  *  and so should be delivered with a 40 MHz clock.
357  *  The recent fast40 chips (895/896/895A/1010) use a 40 Mhz base 
358  *  clock and provide a clock quadrupler (160 Mhz).
359  */
360
361 /*
362  *  calculate SCSI clock frequency (in KHz)
363  */
364 static unsigned getfreq (hcb_p np, int gen)
365 {
366         unsigned int ms = 0;
367         unsigned int f;
368
369         /*
370          * Measure GEN timer delay in order 
371          * to calculate SCSI clock frequency
372          *
373          * This code will never execute too
374          * many loop iterations (if DELAY is 
375          * reasonably correct). It could get
376          * too low a delay (too high a freq.)
377          * if the CPU is slow executing the 
378          * loop for some reason (an NMI, for
379          * example). For this reason we will
380          * if multiple measurements are to be 
381          * performed trust the higher delay 
382          * (lower frequency returned).
383          */
384         OUTW (nc_sien , 0);     /* mask all scsi interrupts */
385         (void) INW (nc_sist);   /* clear pending scsi interrupt */
386         OUTB (nc_dien , 0);     /* mask all dma interrupts */
387         (void) INW (nc_sist);   /* another one, just to be sure :) */
388         /*
389          * The C1010-33 core does not report GEN in SIST,
390          * if this interrupt is masked in SIEN.
391          * I don't know yet if the C1010-66 behaves the same way.
392          */
393         if (np->features & FE_C10) {
394                 OUTW (nc_sien, GEN);
395                 OUTB (nc_istat1, SIRQD);
396         }
397         OUTB (nc_scntl3, 4);    /* set pre-scaler to divide by 3 */
398         OUTB (nc_stime1, 0);    /* disable general purpose timer */
399         OUTB (nc_stime1, gen);  /* set to nominal delay of 1<<gen * 125us */
400         while (!(INW(nc_sist) & GEN) && ms++ < 100000)
401                 UDELAY (1000/4);/* count in 1/4 of ms */
402         OUTB (nc_stime1, 0);    /* disable general purpose timer */
403         /*
404          * Undo C1010-33 specific settings.
405          */
406         if (np->features & FE_C10) {
407                 OUTW (nc_sien, 0);
408                 OUTB (nc_istat1, 0);
409         }
410         /*
411          * set prescaler to divide by whatever 0 means
412          * 0 ought to choose divide by 2, but appears
413          * to set divide by 3.5 mode in my 53c810 ...
414          */
415         OUTB (nc_scntl3, 0);
416
417         /*
418          * adjust for prescaler, and convert into KHz 
419          */
420         f = ms ? ((1 << gen) * (4340*4)) / ms : 0;
421
422         /*
423          * The C1010-33 result is biased by a factor 
424          * of 2/3 compared to earlier chips.
425          */
426         if (np->features & FE_C10)
427                 f = (f * 2) / 3;
428
429         if (sym_verbose >= 2)
430                 printf ("%s: Delay (GEN=%d): %u msec, %u KHz\n",
431                         sym_name(np), gen, ms/4, f);
432
433         return f;
434 }
435
436 static unsigned sym_getfreq (hcb_p np)
437 {
438         u_int f1, f2;
439         int gen = 8;
440
441         (void) getfreq (np, gen);       /* throw away first result */
442         f1 = getfreq (np, gen);
443         f2 = getfreq (np, gen);
444         if (f1 > f2) f1 = f2;           /* trust lower result   */
445         return f1;
446 }
447
448 /*
449  *  Get/probe chip SCSI clock frequency
450  */
451 static void sym_getclock (hcb_p np, int mult)
452 {
453         unsigned char scntl3 = np->sv_scntl3;
454         unsigned char stest1 = np->sv_stest1;
455         unsigned f1;
456
457         np->multiplier = 1;
458         f1 = 40000;
459         /*
460          *  True with 875/895/896/895A with clock multiplier selected
461          */
462         if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
463                 if (sym_verbose >= 2)
464                         printf ("%s: clock multiplier found\n", sym_name(np));
465                 np->multiplier = mult;
466         }
467
468         /*
469          *  If multiplier not found or scntl3 not 7,5,3,
470          *  reset chip and get frequency from general purpose timer.
471          *  Otherwise trust scntl3 BIOS setting.
472          */
473         if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
474                 OUTB (nc_stest1, 0);            /* make sure doubler is OFF */
475                 f1 = sym_getfreq (np);
476
477                 if (sym_verbose)
478                         printf ("%s: chip clock is %uKHz\n", sym_name(np), f1);
479
480                 if      (f1 <   45000)          f1 =  40000;
481                 else if (f1 <   55000)          f1 =  50000;
482                 else                            f1 =  80000;
483
484                 if (f1 < 80000 && mult > 1) {
485                         if (sym_verbose >= 2)
486                                 printf ("%s: clock multiplier assumed\n",
487                                         sym_name(np));
488                         np->multiplier  = mult;
489                 }
490         } else {
491                 if      ((scntl3 & 7) == 3)     f1 =  40000;
492                 else if ((scntl3 & 7) == 5)     f1 =  80000;
493                 else                            f1 = 160000;
494
495                 f1 /= np->multiplier;
496         }
497
498         /*
499          *  Compute controller synchronous parameters.
500          */
501         f1              *= np->multiplier;
502         np->clock_khz   = f1;
503 }
504
505 /*
506  *  Get/probe PCI clock frequency
507  */
508 static int sym_getpciclock (hcb_p np)
509 {
510         int f = 0;
511
512         /*
513          *  For now, we only need to know about the actual 
514          *  PCI BUS clock frequency for C1010-66 chips.
515          */
516 #if 1
517         if (np->features & FE_66MHZ) {
518 #else
519         if (1) {
520 #endif
521                 OUTB (nc_stest1, SCLK); /* Use the PCI clock as SCSI clock */
522                 f = (int) sym_getfreq (np);
523                 OUTB (nc_stest1, 0);
524         }
525         np->pciclk_khz = f;
526
527         return f;
528 }
529
530 /*
531  *  SYMBIOS chip clock divisor table.
532  *
533  *  Divisors are multiplied by 10,000,000 in order to make 
534  *  calculations more simple.
535  */
536 #define _5M 5000000
537 static u32 div_10M[] = {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
538
539 /*
540  *  Get clock factor and sync divisor for a given 
541  *  synchronous factor period.
542  */
543 static int 
544 sym_getsync(hcb_p np, u_char dt, u_char sfac, u_char *divp, u_char *fakp)
545 {
546         u32     clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
547         int     div = np->clock_divn;   /* Number of divisors supported */
548         u32     fak;                    /* Sync factor in sxfer         */
549         u32     per;                    /* Period in tenths of ns       */
550         u32     kpc;                    /* (per * clk)                  */
551         int     ret;
552
553         /*
554          *  Compute the synchronous period in tenths of nano-seconds
555          */
556         if (dt && sfac <= 9)    per = 125;
557         else if (sfac <= 10)    per = 250;
558         else if (sfac == 11)    per = 303;
559         else if (sfac == 12)    per = 500;
560         else                    per = 40 * sfac;
561         ret = per;
562
563         kpc = per * clk;
564         if (dt)
565                 kpc <<= 1;
566
567         /*
568          *  For earliest C10 revision 0, we cannot use extra 
569          *  clocks for the setting of the SCSI clocking.
570          *  Note that this limits the lowest sync data transfer 
571          *  to 5 Mega-transfers per second and may result in
572          *  using higher clock divisors.
573          */
574 #if 1
575         if ((np->features & (FE_C10|FE_U3EN)) == FE_C10) {
576                 /*
577                  *  Look for the lowest clock divisor that allows an 
578                  *  output speed not faster than the period.
579                  */
580                 while (div > 0) {
581                         --div;
582                         if (kpc > (div_10M[div] << 2)) {
583                                 ++div;
584                                 break;
585                         }
586                 }
587                 fak = 0;                        /* No extra clocks */
588                 if (div == np->clock_divn) {    /* Are we too fast ? */
589                         ret = -1;
590                 }
591                 *divp = div;
592                 *fakp = fak;
593                 return ret;
594         }
595 #endif
596
597         /*
598          *  Look for the greatest clock divisor that allows an 
599          *  input speed faster than the period.
600          */
601         while (div-- > 0)
602                 if (kpc >= (div_10M[div] << 2)) break;
603
604         /*
605          *  Calculate the lowest clock factor that allows an output 
606          *  speed not faster than the period, and the max output speed.
607          *  If fak >= 1 we will set both XCLKH_ST and XCLKH_DT.
608          *  If fak >= 2 we will also set XCLKS_ST and XCLKS_DT.
609          */
610         if (dt) {
611                 fak = (kpc - 1) / (div_10M[div] << 1) + 1 - 2;
612                 /* ret = ((2+fak)*div_10M[div])/np->clock_khz; */
613         } else {
614                 fak = (kpc - 1) / div_10M[div] + 1 - 4;
615                 /* ret = ((4+fak)*div_10M[div])/np->clock_khz; */
616         }
617
618         /*
619          *  Check against our hardware limits, or bugs :).
620          */
621         if (fak > 2) {
622                 fak = 2;
623                 ret = -1;
624         }
625
626         /*
627          *  Compute and return sync parameters.
628          */
629         *divp = div;
630         *fakp = fak;
631
632         return ret;
633 }
634
635 /*
636  *  SYMBIOS chips allow burst lengths of 2, 4, 8, 16, 32, 64,
637  *  128 transfers. All chips support at least 16 transfers 
638  *  bursts. The 825A, 875 and 895 chips support bursts of up 
639  *  to 128 transfers and the 895A and 896 support bursts of up
640  *  to 64 transfers. All other chips support up to 16 
641  *  transfers bursts.
642  *
643  *  For PCI 32 bit data transfers each transfer is a DWORD.
644  *  It is a QUADWORD (8 bytes) for PCI 64 bit data transfers.
645  *
646  *  We use log base 2 (burst length) as internal code, with 
647  *  value 0 meaning "burst disabled".
648  */
649
650 /*
651  *  Burst length from burst code.
652  */
653 #define burst_length(bc) (!(bc))? 0 : 1 << (bc)
654
655 /*
656  *  Burst code from io register bits.
657  */
658 #define burst_code(dmode, ctest4, ctest5) \
659         (ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
660
661 /*
662  *  Set initial io register bits from burst code.
663  */
664 static __inline void sym_init_burst(hcb_p np, u_char bc)
665 {
666         np->rv_ctest4   &= ~0x80;
667         np->rv_dmode    &= ~(0x3 << 6);
668         np->rv_ctest5   &= ~0x4;
669
670         if (!bc) {
671                 np->rv_ctest4   |= 0x80;
672         }
673         else {
674                 --bc;
675                 np->rv_dmode    |= ((bc & 0x3) << 6);
676                 np->rv_ctest5   |= (bc & 0x4);
677         }
678 }
679
680
681 /*
682  * Print out the list of targets that have some flag disabled by user.
683  */
684 static void sym_print_targets_flag(hcb_p np, int mask, char *msg)
685 {
686         int cnt;
687         int i;
688
689         for (cnt = 0, i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
690                 if (i == np->myaddr)
691                         continue;
692                 if (np->target[i].usrflags & mask) {
693                         if (!cnt++)
694                                 printf("%s: %s disabled for targets",
695                                         sym_name(np), msg);
696                         printf(" %d", i);
697                 }
698         }
699         if (cnt)
700                 printf(".\n");
701 }
702
703 /*
704  *  Save initial settings of some IO registers.
705  *  Assumed to have been set by BIOS.
706  *  We cannot reset the chip prior to reading the 
707  *  IO registers, since informations will be lost.
708  *  Since the SCRIPTS processor may be running, this 
709  *  is not safe on paper, but it seems to work quite 
710  *  well. :)
711  */
712 static void sym_save_initial_setting (hcb_p np)
713 {
714         np->sv_scntl0   = INB(nc_scntl0) & 0x0a;
715         np->sv_scntl3   = INB(nc_scntl3) & 0x07;
716         np->sv_dmode    = INB(nc_dmode)  & 0xce;
717         np->sv_dcntl    = INB(nc_dcntl)  & 0xa8;
718         np->sv_ctest3   = INB(nc_ctest3) & 0x01;
719         np->sv_ctest4   = INB(nc_ctest4) & 0x80;
720         np->sv_gpcntl   = INB(nc_gpcntl);
721         np->sv_stest1   = INB(nc_stest1);
722         np->sv_stest2   = INB(nc_stest2) & 0x20;
723         np->sv_stest4   = INB(nc_stest4);
724         if (np->features & FE_C10) {    /* Always large DMA fifo + ultra3 */
725                 np->sv_scntl4   = INB(nc_scntl4);
726                 np->sv_ctest5   = INB(nc_ctest5) & 0x04;
727         }
728         else
729                 np->sv_ctest5   = INB(nc_ctest5) & 0x24;
730 }
731
732 #ifdef CONFIG_PARISC
733 static u32 parisc_setup_hcb(hcb_p np, u32 period)
734 {
735         unsigned long pdc_period;
736         char scsi_mode;
737         struct hardware_path hwpath;
738
739         /* Host firmware (PDC) keeps a table for crippling SCSI capabilities.
740          * Many newer machines export one channel of 53c896 chip
741          * as SE, 50-pin HD.  Also used for Multi-initiator SCSI clusters
742          * to set the SCSI Initiator ID.
743          */
744         get_pci_node_path(np->s.device, &hwpath);
745         if (!pdc_get_initiator(&hwpath, &np->myaddr, &pdc_period,
746                                 &np->maxwide, &scsi_mode))
747                 return period;
748
749         if (scsi_mode >= 0) {
750                 /* C3000 PDC reports period/mode */
751                 SYM_SETUP_SCSI_DIFF = 0;
752                 switch(scsi_mode) {
753                 case 0: np->scsi_mode = SMODE_SE; break;
754                 case 1: np->scsi_mode = SMODE_HVD; break;
755                 case 2: np->scsi_mode = SMODE_LVD; break;
756                 default:        break;
757                 }
758         }
759
760         return (u32) pdc_period;
761 }
762 #else
763 static inline int parisc_setup_hcb(hcb_p np, u32 period) { return period; }
764 #endif
765 /*
766  *  Prepare io register values used by sym_start_up() 
767  *  according to selected and supported features.
768  */
769 static int sym_prepare_setting(hcb_p np, struct sym_nvram *nvram)
770 {
771         u_char  burst_max;
772         u32     period;
773         int i;
774
775         /*
776          *  Wide ?
777          */
778         np->maxwide     = (np->features & FE_WIDE)? 1 : 0;
779
780         /*
781          *  Guess the frequency of the chip's clock.
782          */
783         if      (np->features & (FE_ULTRA3 | FE_ULTRA2))
784                 np->clock_khz = 160000;
785         else if (np->features & FE_ULTRA)
786                 np->clock_khz = 80000;
787         else
788                 np->clock_khz = 40000;
789
790         /*
791          *  Get the clock multiplier factor.
792          */
793         if      (np->features & FE_QUAD)
794                 np->multiplier  = 4;
795         else if (np->features & FE_DBLR)
796                 np->multiplier  = 2;
797         else
798                 np->multiplier  = 1;
799
800         /*
801          *  Measure SCSI clock frequency for chips 
802          *  it may vary from assumed one.
803          */
804         if (np->features & FE_VARCLK)
805                 sym_getclock(np, np->multiplier);
806
807         /*
808          * Divisor to be used for async (timer pre-scaler).
809          */
810         i = np->clock_divn - 1;
811         while (--i >= 0) {
812                 if (10ul * SYM_CONF_MIN_ASYNC * np->clock_khz > div_10M[i]) {
813                         ++i;
814                         break;
815                 }
816         }
817         np->rv_scntl3 = i+1;
818
819         /*
820          * The C1010 uses hardwired divisors for async.
821          * So, we just throw away, the async. divisor.:-)
822          */
823         if (np->features & FE_C10)
824                 np->rv_scntl3 = 0;
825
826         /*
827          * Minimum synchronous period factor supported by the chip.
828          * Btw, 'period' is in tenths of nanoseconds.
829          */
830         period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
831
832         period = parisc_setup_hcb(np, period);
833
834         if      (period <= 250)         np->minsync = 10;
835         else if (period <= 303)         np->minsync = 11;
836         else if (period <= 500)         np->minsync = 12;
837         else                            np->minsync = (period + 40 - 1) / 40;
838
839         /*
840          * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
841          */
842         if      (np->minsync < 25 &&
843                  !(np->features & (FE_ULTRA|FE_ULTRA2|FE_ULTRA3)))
844                 np->minsync = 25;
845         else if (np->minsync < 12 &&
846                  !(np->features & (FE_ULTRA2|FE_ULTRA3)))
847                 np->minsync = 12;
848
849         /*
850          * Maximum synchronous period factor supported by the chip.
851          */
852         period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
853         np->maxsync = period > 2540 ? 254 : period / 10;
854
855         /*
856          * If chip is a C1010, guess the sync limits in DT mode.
857          */
858         if ((np->features & (FE_C10|FE_ULTRA3)) == (FE_C10|FE_ULTRA3)) {
859                 if (np->clock_khz == 160000) {
860                         np->minsync_dt = 9;
861                         np->maxsync_dt = 50;
862                         np->maxoffs_dt = nvram->type ? 62 : 31;
863                 }
864         }
865         
866         /*
867          *  64 bit addressing  (895A/896/1010) ?
868          */
869         if (np->features & FE_DAC) {
870 #if   SYM_CONF_DMA_ADDRESSING_MODE == 0
871                 np->rv_ccntl1   |= (DDAC);
872 #elif SYM_CONF_DMA_ADDRESSING_MODE == 1
873                 if (!np->use_dac)
874                         np->rv_ccntl1   |= (DDAC);
875                 else
876                         np->rv_ccntl1   |= (XTIMOD | EXTIBMV);
877 #elif SYM_CONF_DMA_ADDRESSING_MODE == 2
878                 if (!np->use_dac)
879                         np->rv_ccntl1   |= (DDAC);
880                 else
881                         np->rv_ccntl1   |= (0 | EXTIBMV);
882 #endif
883         }
884
885         /*
886          *  Phase mismatch handled by SCRIPTS (895A/896/1010) ?
887          */
888         if (np->features & FE_NOPM)
889                 np->rv_ccntl0   |= (ENPMJ);
890
891         /*
892          *  C1010-33 Errata: Part Number:609-039638 (rev. 1) is fixed.
893          *  In dual channel mode, contention occurs if internal cycles
894          *  are used. Disable internal cycles.
895          */
896         if (np->device_id == PCI_ID_LSI53C1010_33 &&
897             np->revision_id < 0x1)
898                 np->rv_ccntl0   |=  DILS;
899
900         /*
901          *  Select burst length (dwords)
902          */
903         burst_max       = SYM_SETUP_BURST_ORDER;
904         if (burst_max == 255)
905                 burst_max = burst_code(np->sv_dmode, np->sv_ctest4,
906                                        np->sv_ctest5);
907         if (burst_max > 7)
908                 burst_max = 7;
909         if (burst_max > np->maxburst)
910                 burst_max = np->maxburst;
911
912         /*
913          *  DEL 352 - 53C810 Rev x11 - Part Number 609-0392140 - ITEM 2.
914          *  This chip and the 860 Rev 1 may wrongly use PCI cache line 
915          *  based transactions on LOAD/STORE instructions. So we have 
916          *  to prevent these chips from using such PCI transactions in 
917          *  this driver. The generic ncr driver that does not use 
918          *  LOAD/STORE instructions does not need this work-around.
919          */
920         if ((np->device_id == PCI_ID_SYM53C810 &&
921              np->revision_id >= 0x10 && np->revision_id <= 0x11) ||
922             (np->device_id == PCI_ID_SYM53C860 &&
923              np->revision_id <= 0x1))
924                 np->features &= ~(FE_WRIE|FE_ERL|FE_ERMP);
925
926         /*
927          *  Select all supported special features.
928          *  If we are using on-board RAM for scripts, prefetch (PFEN) 
929          *  does not help, but burst op fetch (BOF) does.
930          *  Disabling PFEN makes sure BOF will be used.
931          */
932         if (np->features & FE_ERL)
933                 np->rv_dmode    |= ERL;         /* Enable Read Line */
934         if (np->features & FE_BOF)
935                 np->rv_dmode    |= BOF;         /* Burst Opcode Fetch */
936         if (np->features & FE_ERMP)
937                 np->rv_dmode    |= ERMP;        /* Enable Read Multiple */
938 #if 1
939         if ((np->features & FE_PFEN) && !np->ram_ba)
940 #else
941         if (np->features & FE_PFEN)
942 #endif
943                 np->rv_dcntl    |= PFEN;        /* Prefetch Enable */
944         if (np->features & FE_CLSE)
945                 np->rv_dcntl    |= CLSE;        /* Cache Line Size Enable */
946         if (np->features & FE_WRIE)
947                 np->rv_ctest3   |= WRIE;        /* Write and Invalidate */
948         if (np->features & FE_DFS)
949                 np->rv_ctest5   |= DFS;         /* Dma Fifo Size */
950
951         /*
952          *  Select some other
953          */
954         if (SYM_SETUP_PCI_PARITY)
955                 np->rv_ctest4   |= MPEE; /* Master parity checking */
956         if (SYM_SETUP_SCSI_PARITY)
957                 np->rv_scntl0   |= 0x0a; /*  full arb., ena parity, par->ATN  */
958
959         /*
960          *  Get parity checking, host ID and verbose mode from NVRAM
961          */
962         np->myaddr = 255;
963         sym_nvram_setup_host (np, nvram);
964
965         /*
966          *  Get SCSI addr of host adapter (set by bios?).
967          */
968         if (np->myaddr == 255) {
969                 np->myaddr = INB(nc_scid) & 0x07;
970                 if (!np->myaddr)
971                         np->myaddr = SYM_SETUP_HOST_ID;
972         }
973
974         /*
975          *  Prepare initial io register bits for burst length
976          */
977         sym_init_burst(np, burst_max);
978
979         /*
980          *  Set SCSI BUS mode.
981          *  - LVD capable chips (895/895A/896/1010) report the 
982          *    current BUS mode through the STEST4 IO register.
983          *  - For previous generation chips (825/825A/875), 
984          *    user has to tell us how to check against HVD, 
985          *    since a 100% safe algorithm is not possible.
986          */
987         np->scsi_mode = SMODE_SE;
988         if (np->features & (FE_ULTRA2|FE_ULTRA3))
989                 np->scsi_mode = (np->sv_stest4 & SMODE);
990         else if (np->features & FE_DIFF) {
991                 if (SYM_SETUP_SCSI_DIFF == 1) {
992                         if (np->sv_scntl3) {
993                                 if (np->sv_stest2 & 0x20)
994                                         np->scsi_mode = SMODE_HVD;
995                         }
996                         else if (nvram->type == SYM_SYMBIOS_NVRAM) {
997                                 if (!(INB(nc_gpreg) & 0x08))
998                                         np->scsi_mode = SMODE_HVD;
999                         }
1000                 }
1001                 else if (SYM_SETUP_SCSI_DIFF == 2)
1002                         np->scsi_mode = SMODE_HVD;
1003         }
1004         if (np->scsi_mode == SMODE_HVD)
1005                 np->rv_stest2 |= 0x20;
1006
1007         /*
1008          *  Set LED support from SCRIPTS.
1009          *  Ignore this feature for boards known to use a 
1010          *  specific GPIO wiring and for the 895A, 896 
1011          *  and 1010 that drive the LED directly.
1012          */
1013         if ((SYM_SETUP_SCSI_LED || 
1014              (nvram->type == SYM_SYMBIOS_NVRAM ||
1015               (nvram->type == SYM_TEKRAM_NVRAM &&
1016                np->device_id == PCI_ID_SYM53C895))) &&
1017             !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
1018                 np->features |= FE_LED0;
1019
1020         /*
1021          *  Set irq mode.
1022          */
1023         switch(SYM_SETUP_IRQ_MODE & 3) {
1024         case 2:
1025                 np->rv_dcntl    |= IRQM;
1026                 break;
1027         case 1:
1028                 np->rv_dcntl    |= (np->sv_dcntl & IRQM);
1029                 break;
1030         default:
1031                 break;
1032         }
1033
1034         /*
1035          *  Configure targets according to driver setup.
1036          *  If NVRAM present get targets setup from NVRAM.
1037          */
1038         for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
1039                 tcb_p tp = &np->target[i];
1040
1041                 tp->usrflags |= (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
1042                 tp->usrtags = SYM_SETUP_MAX_TAG;
1043
1044                 sym_nvram_setup_target (np, i, nvram);
1045
1046                 if (!tp->usrtags)
1047                         tp->usrflags &= ~SYM_TAGS_ENABLED;
1048         }
1049
1050         /*
1051          *  Let user know about the settings.
1052          */
1053         i = nvram->type;
1054         printf("%s: %s NVRAM, ID %d, Fast-%d, %s, %s\n", sym_name(np),
1055                 i  == SYM_SYMBIOS_NVRAM ? "Symbios" :
1056                 (i == SYM_TEKRAM_NVRAM  ? "Tekram" : "No"),
1057                 np->myaddr,
1058                 (np->features & FE_ULTRA3) ? 80 : 
1059                 (np->features & FE_ULTRA2) ? 40 : 
1060                 (np->features & FE_ULTRA)  ? 20 : 10,
1061                 sym_scsi_bus_mode(np->scsi_mode),
1062                 (np->rv_scntl0 & 0xa)   ? "parity checking" : "NO parity");
1063         /*
1064          *  Tell him more on demand.
1065          */
1066         if (sym_verbose) {
1067                 printf("%s: %s IRQ line driver%s\n",
1068                         sym_name(np),
1069                         np->rv_dcntl & IRQM ? "totem pole" : "open drain",
1070                         np->ram_ba ? ", using on-chip SRAM" : "");
1071                 printf("%s: using %s firmware.\n", sym_name(np), np->fw_name);
1072                 if (np->features & FE_NOPM)
1073                         printf("%s: handling phase mismatch from SCRIPTS.\n", 
1074                                sym_name(np));
1075         }
1076         /*
1077          *  And still more.
1078          */
1079         if (sym_verbose >= 2) {
1080                 printf ("%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
1081                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
1082                         sym_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
1083                         np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
1084
1085                 printf ("%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
1086                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
1087                         sym_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
1088                         np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
1089         }
1090         /*
1091          *  Let user be aware of targets that have some disable flags set.
1092          */
1093         sym_print_targets_flag(np, SYM_SCAN_BOOT_DISABLED, "SCAN AT BOOT");
1094         if (sym_verbose)
1095                 sym_print_targets_flag(np, SYM_SCAN_LUNS_DISABLED,
1096                                        "SCAN FOR LUNS");
1097
1098         return 0;
1099 }
1100
1101 /*
1102  *  Test the pci bus snoop logic :-(
1103  *
1104  *  Has to be called with interrupts disabled.
1105  */
1106 #ifndef SYM_CONF_IOMAPPED
1107 static int sym_regtest (hcb_p np)
1108 {
1109         register volatile u32 data;
1110         /*
1111          *  chip registers may NOT be cached.
1112          *  write 0xffffffff to a read only register area,
1113          *  and try to read it back.
1114          */
1115         data = 0xffffffff;
1116         OUTL_OFF(offsetof(struct sym_reg, nc_dstat), data);
1117         data = INL_OFF(offsetof(struct sym_reg, nc_dstat));
1118 #if 1
1119         if (data == 0xffffffff) {
1120 #else
1121         if ((data & 0xe2f0fffd) != 0x02000080) {
1122 #endif
1123                 printf ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
1124                         (unsigned) data);
1125                 return (0x10);
1126         };
1127         return (0);
1128 }
1129 #endif
1130
1131 static int sym_snooptest (hcb_p np)
1132 {
1133         u32     sym_rd, sym_wr, sym_bk, host_rd, host_wr, pc, dstat;
1134         int     i, err=0;
1135 #ifndef SYM_CONF_IOMAPPED
1136         err |= sym_regtest (np);
1137         if (err) return (err);
1138 #endif
1139 restart_test:
1140         /*
1141          *  Enable Master Parity Checking as we intend 
1142          *  to enable it for normal operations.
1143          */
1144         OUTB (nc_ctest4, (np->rv_ctest4 & MPEE));
1145         /*
1146          *  init
1147          */
1148         pc  = SCRIPTZ_BA (np, snooptest);
1149         host_wr = 1;
1150         sym_wr  = 2;
1151         /*
1152          *  Set memory and register.
1153          */
1154         np->scratch = cpu_to_scr(host_wr);
1155         OUTL (nc_temp, sym_wr);
1156         /*
1157          *  Start script (exchange values)
1158          */
1159         OUTL (nc_dsa, np->hcb_ba);
1160         OUTL_DSP (pc);
1161         /*
1162          *  Wait 'til done (with timeout)
1163          */
1164         for (i=0; i<SYM_SNOOP_TIMEOUT; i++)
1165                 if (INB(nc_istat) & (INTF|SIP|DIP))
1166                         break;
1167         if (i>=SYM_SNOOP_TIMEOUT) {
1168                 printf ("CACHE TEST FAILED: timeout.\n");
1169                 return (0x20);
1170         };
1171         /*
1172          *  Check for fatal DMA errors.
1173          */
1174         dstat = INB (nc_dstat);
1175 #if 1   /* Band aiding for broken hardwares that fail PCI parity */
1176         if ((dstat & MDPE) && (np->rv_ctest4 & MPEE)) {
1177                 printf ("%s: PCI DATA PARITY ERROR DETECTED - "
1178                         "DISABLING MASTER DATA PARITY CHECKING.\n",
1179                         sym_name(np));
1180                 np->rv_ctest4 &= ~MPEE;
1181                 goto restart_test;
1182         }
1183 #endif
1184         if (dstat & (MDPE|BF|IID)) {
1185                 printf ("CACHE TEST FAILED: DMA error (dstat=0x%02x).", dstat);
1186                 return (0x80);
1187         }
1188         /*
1189          *  Save termination position.
1190          */
1191         pc = INL (nc_dsp);
1192         /*
1193          *  Read memory and register.
1194          */
1195         host_rd = scr_to_cpu(np->scratch);
1196         sym_rd  = INL (nc_scratcha);
1197         sym_bk  = INL (nc_temp);
1198         /*
1199          *  Check termination position.
1200          */
1201         if (pc != SCRIPTZ_BA (np, snoopend)+8) {
1202                 printf ("CACHE TEST FAILED: script execution failed.\n");
1203                 printf ("start=%08lx, pc=%08lx, end=%08lx\n", 
1204                         (u_long) SCRIPTZ_BA (np, snooptest), (u_long) pc,
1205                         (u_long) SCRIPTZ_BA (np, snoopend) +8);
1206                 return (0x40);
1207         };
1208         /*
1209          *  Show results.
1210          */
1211         if (host_wr != sym_rd) {
1212                 printf ("CACHE TEST FAILED: host wrote %d, chip read %d.\n",
1213                         (int) host_wr, (int) sym_rd);
1214                 err |= 1;
1215         };
1216         if (host_rd != sym_wr) {
1217                 printf ("CACHE TEST FAILED: chip wrote %d, host read %d.\n",
1218                         (int) sym_wr, (int) host_rd);
1219                 err |= 2;
1220         };
1221         if (sym_bk != sym_wr) {
1222                 printf ("CACHE TEST FAILED: chip wrote %d, read back %d.\n",
1223                         (int) sym_wr, (int) sym_bk);
1224                 err |= 4;
1225         };
1226
1227         return (err);
1228 }
1229
1230 /*
1231  *  log message for real hard errors
1232  *
1233  *  sym0 targ 0?: ERROR (ds:si) (so-si-sd) (sx/s3/s4) @ name (dsp:dbc).
1234  *            reg: r0 r1 r2 r3 r4 r5 r6 ..... rf.
1235  *
1236  *  exception register:
1237  *      ds:     dstat
1238  *      si:     sist
1239  *
1240  *  SCSI bus lines:
1241  *      so:     control lines as driven by chip.
1242  *      si:     control lines as seen by chip.
1243  *      sd:     scsi data lines as seen by chip.
1244  *
1245  *  wide/fastmode:
1246  *      sx:     sxfer  (see the manual)
1247  *      s3:     scntl3 (see the manual)
1248  *      s4:     scntl4 (see the manual)
1249  *
1250  *  current script command:
1251  *      dsp:    script address (relative to start of script).
1252  *      dbc:    first word of script command.
1253  *
1254  *  First 24 register of the chip:
1255  *      r0..rf
1256  */
1257 static void sym_log_hard_error(hcb_p np, u_short sist, u_char dstat)
1258 {
1259         u32     dsp;
1260         int     script_ofs;
1261         int     script_size;
1262         char    *script_name;
1263         u_char  *script_base;
1264         int     i;
1265
1266         dsp     = INL (nc_dsp);
1267
1268         if      (dsp > np->scripta_ba &&
1269                  dsp <= np->scripta_ba + np->scripta_sz) {
1270                 script_ofs      = dsp - np->scripta_ba;
1271                 script_size     = np->scripta_sz;
1272                 script_base     = (u_char *) np->scripta0;
1273                 script_name     = "scripta";
1274         }
1275         else if (np->scriptb_ba < dsp && 
1276                  dsp <= np->scriptb_ba + np->scriptb_sz) {
1277                 script_ofs      = dsp - np->scriptb_ba;
1278                 script_size     = np->scriptb_sz;
1279                 script_base     = (u_char *) np->scriptb0;
1280                 script_name     = "scriptb";
1281         } else {
1282                 script_ofs      = dsp;
1283                 script_size     = 0;
1284                 script_base     = NULL;
1285                 script_name     = "mem";
1286         }
1287
1288         printf ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x/%x) @ (%s %x:%08x).\n",
1289                 sym_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
1290                 (unsigned)INB (nc_socl),   (unsigned)INB (nc_sbcl),
1291                 (unsigned)INB (nc_sbdl),   (unsigned)INB (nc_sxfer),
1292                 (unsigned)INB (nc_scntl3),
1293                 (np->features & FE_C10) ?  (unsigned)INB (nc_scntl4) : 0,
1294                 script_name, script_ofs,   (unsigned)INL (nc_dbc));
1295
1296         if (((script_ofs & 3) == 0) &&
1297             (unsigned)script_ofs < script_size) {
1298                 printf ("%s: script cmd = %08x\n", sym_name(np),
1299                         scr_to_cpu((int) *(u32 *)(script_base + script_ofs)));
1300         }
1301
1302         printf ("%s: regdump:", sym_name(np));
1303         for (i=0; i<24;i++)
1304             printf (" %02x", (unsigned)INB_OFF(i));
1305         printf (".\n");
1306
1307         /*
1308          *  PCI BUS error.
1309          */
1310         if (dstat & (MDPE|BF))
1311                 sym_log_bus_error(np);
1312 }
1313
1314 static struct sym_pci_chip sym_pci_dev_table[] = {
1315  {PCI_ID_SYM53C810, 0x0f, "810", 4, 8, 4, 64,
1316  FE_ERL}
1317  ,
1318 #ifdef SYM_DEBUG_GENERIC_SUPPORT
1319  {PCI_ID_SYM53C810, 0xff, "810a", 4,  8, 4, 1,
1320  FE_BOF}
1321  ,
1322 #else
1323  {PCI_ID_SYM53C810, 0xff, "810a", 4,  8, 4, 1,
1324  FE_CACHE_SET|FE_LDSTR|FE_PFEN|FE_BOF}
1325  ,
1326 #endif
1327  {PCI_ID_SYM53C815, 0xff, "815", 4,  8, 4, 64,
1328  FE_BOF|FE_ERL}
1329  ,
1330  {PCI_ID_SYM53C825, 0x0f, "825", 6,  8, 4, 64,
1331  FE_WIDE|FE_BOF|FE_ERL|FE_DIFF}
1332  ,
1333  {PCI_ID_SYM53C825, 0xff, "825a", 6,  8, 4, 2,
1334  FE_WIDE|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM|FE_DIFF}
1335  ,
1336  {PCI_ID_SYM53C860, 0xff, "860", 4,  8, 5, 1,
1337  FE_ULTRA|FE_CACHE_SET|FE_BOF|FE_LDSTR|FE_PFEN}
1338  ,
1339  {PCI_ID_SYM53C875, 0x01, "875", 6, 16, 5, 2,
1340  FE_WIDE|FE_ULTRA|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1341  FE_RAM|FE_DIFF|FE_VARCLK}
1342  ,
1343  {PCI_ID_SYM53C875, 0xff, "875", 6, 16, 5, 2,
1344  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1345  FE_RAM|FE_DIFF|FE_VARCLK}
1346  ,
1347  {PCI_ID_SYM53C875_2, 0xff, "875", 6, 16, 5, 2,
1348  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1349  FE_RAM|FE_DIFF|FE_VARCLK}
1350  ,
1351  {PCI_ID_SYM53C885, 0xff, "885", 6, 16, 5, 2,
1352  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1353  FE_RAM|FE_DIFF|FE_VARCLK}
1354  ,
1355 #ifdef SYM_DEBUG_GENERIC_SUPPORT
1356  {PCI_ID_SYM53C895, 0xff, "895", 6, 31, 7, 2,
1357  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|
1358  FE_RAM|FE_LCKFRQ}
1359  ,
1360 #else
1361  {PCI_ID_SYM53C895, 0xff, "895", 6, 31, 7, 2,
1362  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1363  FE_RAM|FE_LCKFRQ}
1364  ,
1365 #endif
1366  {PCI_ID_SYM53C896, 0xff, "896", 6, 31, 7, 4,
1367  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1368  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
1369  ,
1370  {PCI_ID_SYM53C895A, 0xff, "895a", 6, 31, 7, 4,
1371  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1372  FE_RAM|FE_RAM8K|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
1373  ,
1374  {PCI_ID_SYM53C875A, 0xff, "875a", 6, 31, 7, 4,
1375  FE_WIDE|FE_ULTRA|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1376  FE_RAM|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
1377  ,
1378  {PCI_ID_LSI53C1010_33, 0x00, "1010-33", 6, 31, 7, 8,
1379  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
1380  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_CRC|
1381  FE_C10}
1382  ,
1383  {PCI_ID_LSI53C1010_33, 0xff, "1010-33", 6, 31, 7, 8,
1384  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
1385  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_CRC|
1386  FE_C10|FE_U3EN}
1387  ,
1388  {PCI_ID_LSI53C1010_66, 0xff, "1010-66", 6, 31, 7, 8,
1389  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
1390  FE_RAM|FE_RAM8K|FE_64BIT|FE_DAC|FE_IO256|FE_NOPM|FE_LEDC|FE_66MHZ|FE_CRC|
1391  FE_C10|FE_U3EN}
1392  ,
1393  {PCI_ID_LSI53C1510D, 0xff, "1510d", 6, 31, 7, 4,
1394  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
1395  FE_RAM|FE_IO256|FE_LEDC}
1396 };
1397
1398 #define sym_pci_num_devs \
1399         (sizeof(sym_pci_dev_table) / sizeof(sym_pci_dev_table[0]))
1400
1401 /*
1402  *  Look up the chip table.
1403  *
1404  *  Return a pointer to the chip entry if found, 
1405  *  zero otherwise.
1406  */
1407 struct sym_pci_chip *
1408 sym_lookup_pci_chip_table (u_short device_id, u_char revision)
1409 {
1410         struct  sym_pci_chip *chip;
1411         int     i;
1412
1413         for (i = 0; i < sym_pci_num_devs; i++) {
1414                 chip = &sym_pci_dev_table[i];
1415                 if (device_id != chip->device_id)
1416                         continue;
1417                 if (revision > chip->revision_id)
1418                         continue;
1419                 return chip;
1420         }
1421
1422         return NULL;
1423 }
1424
1425 #if SYM_CONF_DMA_ADDRESSING_MODE == 2
1426 /*
1427  *  Lookup the 64 bit DMA segments map.
1428  *  This is only used if the direct mapping 
1429  *  has been unsuccessful.
1430  */
1431 int sym_lookup_dmap(hcb_p np, u32 h, int s)
1432 {
1433         int i;
1434
1435         if (!np->use_dac)
1436                 goto weird;
1437
1438         /* Look up existing mappings */
1439         for (i = SYM_DMAP_SIZE-1; i > 0; i--) {
1440                 if (h == np->dmap_bah[i])
1441                         return i;
1442         }
1443         /* If direct mapping is free, get it */
1444         if (!np->dmap_bah[s])
1445                 goto new;
1446         /* Collision -> lookup free mappings */
1447         for (s = SYM_DMAP_SIZE-1; s > 0; s--) {
1448                 if (!np->dmap_bah[s])
1449                         goto new;
1450         }
1451 weird:
1452         panic("sym: ran out of 64 bit DMA segment registers");
1453         return -1;
1454 new:
1455         np->dmap_bah[s] = h;
1456         np->dmap_dirty = 1;
1457         return s;
1458 }
1459
1460 /*
1461  *  Update IO registers scratch C..R so they will be 
1462  *  in sync. with queued CCB expectations.
1463  */
1464 static void sym_update_dmap_regs(hcb_p np)
1465 {
1466         int o, i;
1467
1468         if (!np->dmap_dirty)
1469                 return;
1470         o = offsetof(struct sym_reg, nc_scrx[0]);
1471         for (i = 0; i < SYM_DMAP_SIZE; i++) {
1472                 OUTL_OFF(o, np->dmap_bah[i]);
1473                 o += 4;
1474         }
1475         np->dmap_dirty = 0;
1476 }
1477 #endif
1478
1479 static void sym_check_goals(struct scsi_device *sdev)
1480 {
1481         struct sym_hcb *np = ((struct host_data *)sdev->host->hostdata)->ncb;
1482         struct sym_trans *st = &np->target[sdev->id].tinfo.goal;
1483
1484         /* here we enforce all the fiddly SPI rules */
1485
1486         if (!scsi_device_wide(sdev))
1487                 st->width = 0;
1488
1489         if (!scsi_device_sync(sdev)) {
1490                 st->options = 0;
1491                 st->period = 0;
1492                 st->offset = 0;
1493                 return;
1494         }
1495                 
1496         if (scsi_device_dt(sdev)) {
1497                 if (scsi_device_dt_only(sdev))
1498                         st->options |= PPR_OPT_DT;
1499
1500                 if (st->offset == 0)
1501                         st->options &= ~PPR_OPT_DT;
1502         } else {
1503                 st->options &= ~PPR_OPT_DT;
1504         }
1505
1506         if (!(np->features & FE_ULTRA3))
1507                 st->options &= ~PPR_OPT_DT;
1508
1509         if (st->options & PPR_OPT_DT) {
1510                 /* all DT transfers must be wide */
1511                 st->width = 1;
1512                 if (st->offset > np->maxoffs_dt)
1513                         st->offset = np->maxoffs_dt;
1514                 if (st->period < np->minsync_dt)
1515                         st->period = np->minsync_dt;
1516                 if (st->period > np->maxsync_dt)
1517                         st->period = np->maxsync_dt;
1518         } else {
1519                 if (st->offset > np->maxoffs)
1520                         st->offset = np->maxoffs;
1521                 if (st->period < np->minsync)
1522                         st->period = np->minsync;
1523                 if (st->period > np->maxsync)
1524                         st->period = np->maxsync;
1525         }
1526 }               
1527
1528 /*
1529  *  Prepare the next negotiation message if needed.
1530  *
1531  *  Fill in the part of message buffer that contains the 
1532  *  negotiation and the nego_status field of the CCB.
1533  *  Returns the size of the message in bytes.
1534  */
1535 static int sym_prepare_nego(hcb_p np, ccb_p cp, int nego, u_char *msgptr)
1536 {
1537         tcb_p tp = &np->target[cp->target];
1538         int msglen = 0;
1539         struct scsi_device *sdev = tp->sdev;
1540
1541         if (likely(sdev))
1542                 sym_check_goals(sdev);
1543
1544         /*
1545          *  Early C1010 chips need a work-around for DT 
1546          *  data transfer to work.
1547          */
1548         if (!(np->features & FE_U3EN))
1549                 tp->tinfo.goal.options = 0;
1550         /*
1551          *  negotiate using PPR ?
1552          */
1553         if (scsi_device_dt(sdev)) {
1554                 nego = NS_PPR;
1555         } else {
1556                 /*
1557                  *  negotiate wide transfers ?
1558                  */
1559                 if (tp->tinfo.curr.width != tp->tinfo.goal.width)
1560                         nego = NS_WIDE;
1561                 /*
1562                  *  negotiate synchronous transfers?
1563                  */
1564                 else if (tp->tinfo.curr.period != tp->tinfo.goal.period ||
1565                          tp->tinfo.curr.offset != tp->tinfo.goal.offset)
1566                         nego = NS_SYNC;
1567         }
1568
1569         switch (nego) {
1570         case NS_SYNC:
1571                 msgptr[msglen++] = M_EXTENDED;
1572                 msgptr[msglen++] = 3;
1573                 msgptr[msglen++] = M_X_SYNC_REQ;
1574                 msgptr[msglen++] = tp->tinfo.goal.period;
1575                 msgptr[msglen++] = tp->tinfo.goal.offset;
1576                 break;
1577         case NS_WIDE:
1578                 msgptr[msglen++] = M_EXTENDED;
1579                 msgptr[msglen++] = 2;
1580                 msgptr[msglen++] = M_X_WIDE_REQ;
1581                 msgptr[msglen++] = tp->tinfo.goal.width;
1582                 break;
1583         case NS_PPR:
1584                 msgptr[msglen++] = M_EXTENDED;
1585                 msgptr[msglen++] = 6;
1586                 msgptr[msglen++] = M_X_PPR_REQ;
1587                 msgptr[msglen++] = tp->tinfo.goal.period;
1588                 msgptr[msglen++] = 0;
1589                 msgptr[msglen++] = tp->tinfo.goal.offset;
1590                 msgptr[msglen++] = tp->tinfo.goal.width;
1591                 msgptr[msglen++] = tp->tinfo.goal.options & PPR_OPT_DT;
1592                 break;
1593         };
1594
1595         cp->nego_status = nego;
1596
1597         if (nego) {
1598                 tp->nego_cp = cp; /* Keep track a nego will be performed */
1599                 if (DEBUG_FLAGS & DEBUG_NEGO) {
1600                         sym_print_nego_msg(np, cp->target, 
1601                                           nego == NS_SYNC ? "sync msgout" :
1602                                           nego == NS_WIDE ? "wide msgout" :
1603                                           "ppr msgout", msgptr);
1604                 };
1605         };
1606
1607         return msglen;
1608 }
1609
1610 /*
1611  *  Insert a job into the start queue.
1612  */
1613 void sym_put_start_queue(hcb_p np, ccb_p cp)
1614 {
1615         u_short qidx;
1616
1617 #ifdef SYM_CONF_IARB_SUPPORT
1618         /*
1619          *  If the previously queued CCB is not yet done, 
1620          *  set the IARB hint. The SCRIPTS will go with IARB 
1621          *  for this job when starting the previous one.
1622          *  We leave devices a chance to win arbitration by 
1623          *  not using more than 'iarb_max' consecutive 
1624          *  immediate arbitrations.
1625          */
1626         if (np->last_cp && np->iarb_count < np->iarb_max) {
1627                 np->last_cp->host_flags |= HF_HINT_IARB;
1628                 ++np->iarb_count;
1629         }
1630         else
1631                 np->iarb_count = 0;
1632         np->last_cp = cp;
1633 #endif
1634
1635 #if   SYM_CONF_DMA_ADDRESSING_MODE == 2
1636         /*
1637          *  Make SCRIPTS aware of the 64 bit DMA 
1638          *  segment registers not being up-to-date.
1639          */
1640         if (np->dmap_dirty)
1641                 cp->host_xflags |= HX_DMAP_DIRTY;
1642 #endif
1643
1644         /*
1645          *  Optionnaly, set the IO timeout condition.
1646          */
1647 #ifdef  SYM_OPT_HANDLE_IO_TIMEOUT
1648         sym_timeout_ccb(np, cp, sym_cam_timeout(cp->cam_ccb));
1649 #endif
1650
1651         /*
1652          *  Insert first the idle task and then our job.
1653          *  The MBs should ensure proper ordering.
1654          */
1655         qidx = np->squeueput + 2;
1656         if (qidx >= MAX_QUEUE*2) qidx = 0;
1657
1658         np->squeue [qidx]          = cpu_to_scr(np->idletask_ba);
1659         MEMORY_WRITE_BARRIER();
1660         np->squeue [np->squeueput] = cpu_to_scr(cp->ccb_ba);
1661
1662         np->squeueput = qidx;
1663
1664         if (DEBUG_FLAGS & DEBUG_QUEUE)
1665                 printf ("%s: queuepos=%d.\n", sym_name (np), np->squeueput);
1666
1667         /*
1668          *  Script processor may be waiting for reselect.
1669          *  Wake it up.
1670          */
1671         MEMORY_WRITE_BARRIER();
1672         OUTB (nc_istat, SIGP|np->istat_sem);
1673 }
1674
1675 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
1676 /*
1677  *  Start next ready-to-start CCBs.
1678  */
1679 void sym_start_next_ccbs(hcb_p np, lcb_p lp, int maxn)
1680 {
1681         SYM_QUEHEAD *qp;
1682         ccb_p cp;
1683
1684         /* 
1685          *  Paranoia, as usual. :-)
1686          */
1687         assert(!lp->started_tags || !lp->started_no_tag);
1688
1689         /*
1690          *  Try to start as many commands as asked by caller.
1691          *  Prevent from having both tagged and untagged 
1692          *  commands queued to the device at the same time.
1693          */
1694         while (maxn--) {
1695                 qp = sym_remque_head(&lp->waiting_ccbq);
1696                 if (!qp)
1697                         break;
1698                 cp = sym_que_entry(qp, struct sym_ccb, link2_ccbq);
1699                 if (cp->tag != NO_TAG) {
1700                         if (lp->started_no_tag ||
1701                             lp->started_tags >= lp->started_max) {
1702                                 sym_insque_head(qp, &lp->waiting_ccbq);
1703                                 break;
1704                         }
1705                         lp->itlq_tbl[cp->tag] = cpu_to_scr(cp->ccb_ba);
1706                         lp->head.resel_sa =
1707                                 cpu_to_scr(SCRIPTA_BA (np, resel_tag));
1708                         ++lp->started_tags;
1709                 } else {
1710                         if (lp->started_no_tag || lp->started_tags) {
1711                                 sym_insque_head(qp, &lp->waiting_ccbq);
1712                                 break;
1713                         }
1714                         lp->head.itl_task_sa = cpu_to_scr(cp->ccb_ba);
1715                         lp->head.resel_sa =
1716                               cpu_to_scr(SCRIPTA_BA (np, resel_no_tag));
1717                         ++lp->started_no_tag;
1718                 }
1719                 cp->started = 1;
1720                 sym_insque_tail(qp, &lp->started_ccbq);
1721                 sym_put_start_queue(np, cp);
1722         }
1723 }
1724 #endif /* SYM_OPT_HANDLE_DEVICE_QUEUEING */
1725
1726 /*
1727  *  The chip may have completed jobs. Look at the DONE QUEUE.
1728  *
1729  *  On paper, memory read barriers may be needed here to 
1730  *  prevent out of order LOADs by the CPU from having 
1731  *  prefetched stale data prior to DMA having occurred.
1732  */
1733 static int sym_wakeup_done (hcb_p np)
1734 {
1735         ccb_p cp;
1736         int i, n;
1737         u32 dsa;
1738
1739         n = 0;
1740         i = np->dqueueget;
1741
1742         /* MEMORY_READ_BARRIER(); */
1743         while (1) {
1744                 dsa = scr_to_cpu(np->dqueue[i]);
1745                 if (!dsa)
1746                         break;
1747                 np->dqueue[i] = 0;
1748                 if ((i = i+2) >= MAX_QUEUE*2)
1749                         i = 0;
1750
1751                 cp = sym_ccb_from_dsa(np, dsa);
1752                 if (cp) {
1753                         MEMORY_READ_BARRIER();
1754                         sym_complete_ok (np, cp);
1755                         ++n;
1756                 }
1757                 else
1758                         printf ("%s: bad DSA (%x) in done queue.\n",
1759                                 sym_name(np), (u_int) dsa);
1760         }
1761         np->dqueueget = i;
1762
1763         return n;
1764 }
1765
1766 /*
1767  *  Complete all active CCBs with error.
1768  *  Used on CHIP/SCSI RESET.
1769  */
1770 static void sym_flush_busy_queue (hcb_p np, int cam_status)
1771 {
1772         /*
1773          *  Move all active CCBs to the COMP queue 
1774          *  and flush this queue.
1775          */
1776         sym_que_splice(&np->busy_ccbq, &np->comp_ccbq);
1777         sym_que_init(&np->busy_ccbq);
1778         sym_flush_comp_queue(np, cam_status);
1779 }
1780
1781 /*
1782  *  Start chip.
1783  *
1784  *  'reason' means:
1785  *     0: initialisation.
1786  *     1: SCSI BUS RESET delivered or received.
1787  *     2: SCSI BUS MODE changed.
1788  */
1789 void sym_start_up (hcb_p np, int reason)
1790 {
1791         int     i;
1792         u32     phys;
1793
1794         /*
1795          *  Reset chip if asked, otherwise just clear fifos.
1796          */
1797         if (reason == 1)
1798                 sym_soft_reset(np);
1799         else {
1800                 OUTB (nc_stest3, TE|CSF);
1801                 OUTONB (nc_ctest3, CLF);
1802         }
1803  
1804         /*
1805          *  Clear Start Queue
1806          */
1807         phys = np->squeue_ba;
1808         for (i = 0; i < MAX_QUEUE*2; i += 2) {
1809                 np->squeue[i]   = cpu_to_scr(np->idletask_ba);
1810                 np->squeue[i+1] = cpu_to_scr(phys + (i+2)*4);
1811         }
1812         np->squeue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
1813
1814         /*
1815          *  Start at first entry.
1816          */
1817         np->squeueput = 0;
1818
1819         /*
1820          *  Clear Done Queue
1821          */
1822         phys = np->dqueue_ba;
1823         for (i = 0; i < MAX_QUEUE*2; i += 2) {
1824                 np->dqueue[i]   = 0;
1825                 np->dqueue[i+1] = cpu_to_scr(phys + (i+2)*4);
1826         }
1827         np->dqueue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
1828
1829         /*
1830          *  Start at first entry.
1831          */
1832         np->dqueueget = 0;
1833
1834         /*
1835          *  Install patches in scripts.
1836          *  This also let point to first position the start 
1837          *  and done queue pointers used from SCRIPTS.
1838          */
1839         np->fw_patch(np);
1840
1841         /*
1842          *  Wakeup all pending jobs.
1843          */
1844         sym_flush_busy_queue(np, CAM_SCSI_BUS_RESET);
1845
1846         /*
1847          *  Init chip.
1848          */
1849         OUTB (nc_istat,  0x00   );      /*  Remove Reset, abort */
1850         UDELAY (2000);  /* The 895 needs time for the bus mode to settle */
1851
1852         OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
1853                                         /*  full arb., ena parity, par->ATN  */
1854         OUTB (nc_scntl1, 0x00);         /*  odd parity, and remove CRST!! */
1855
1856         sym_selectclock(np, np->rv_scntl3);     /* Select SCSI clock */
1857
1858         OUTB (nc_scid  , RRE|np->myaddr);       /* Adapter SCSI address */
1859         OUTW (nc_respid, 1ul<<np->myaddr);      /* Id to respond to */
1860         OUTB (nc_istat , SIGP   );              /*  Signal Process */
1861         OUTB (nc_dmode , np->rv_dmode);         /* Burst length, dma mode */
1862         OUTB (nc_ctest5, np->rv_ctest5);        /* Large fifo + large burst */
1863
1864         OUTB (nc_dcntl , NOCOM|np->rv_dcntl);   /* Protect SFBR */
1865         OUTB (nc_ctest3, np->rv_ctest3);        /* Write and invalidate */
1866         OUTB (nc_ctest4, np->rv_ctest4);        /* Master parity checking */
1867
1868         /* Extended Sreq/Sack filtering not supported on the C10 */
1869         if (np->features & FE_C10)
1870                 OUTB (nc_stest2, np->rv_stest2);
1871         else
1872                 OUTB (nc_stest2, EXT|np->rv_stest2);
1873
1874         OUTB (nc_stest3, TE);                   /* TolerANT enable */
1875         OUTB (nc_stime0, 0x0c);                 /* HTH disabled  STO 0.25 sec */
1876
1877         /*
1878          *  For now, disable AIP generation on C1010-66.
1879          */
1880         if (np->device_id == PCI_ID_LSI53C1010_66)
1881                 OUTB (nc_aipcntl1, DISAIP);
1882
1883         /*
1884          *  C10101 rev. 0 errata.
1885          *  Errant SGE's when in narrow. Write bits 4 & 5 of
1886          *  STEST1 register to disable SGE. We probably should do 
1887          *  that from SCRIPTS for each selection/reselection, but 
1888          *  I just don't want. :)
1889          */
1890         if (np->device_id == PCI_ID_LSI53C1010_33 &&
1891             np->revision_id < 1)
1892                 OUTB (nc_stest1, INB(nc_stest1) | 0x30);
1893
1894         /*
1895          *  DEL 441 - 53C876 Rev 5 - Part Number 609-0392787/2788 - ITEM 2.
1896          *  Disable overlapped arbitration for some dual function devices, 
1897          *  regardless revision id (kind of post-chip-design feature. ;-))
1898          */
1899         if (np->device_id == PCI_ID_SYM53C875)
1900                 OUTB (nc_ctest0, (1<<5));
1901         else if (np->device_id == PCI_ID_SYM53C896)
1902                 np->rv_ccntl0 |= DPR;
1903
1904         /*
1905          *  Write CCNTL0/CCNTL1 for chips capable of 64 bit addressing 
1906          *  and/or hardware phase mismatch, since only such chips 
1907          *  seem to support those IO registers.
1908          */
1909         if (np->features & (FE_DAC|FE_NOPM)) {
1910                 OUTB (nc_ccntl0, np->rv_ccntl0);
1911                 OUTB (nc_ccntl1, np->rv_ccntl1);
1912         }
1913
1914 #if     SYM_CONF_DMA_ADDRESSING_MODE == 2
1915         /*
1916          *  Set up scratch C and DRS IO registers to map the 32 bit 
1917          *  DMA address range our data structures are located in.
1918          */
1919         if (np->use_dac) {
1920                 np->dmap_bah[0] = 0;    /* ??? */
1921                 OUTL (nc_scrx[0], np->dmap_bah[0]);
1922                 OUTL (nc_drs, np->dmap_bah[0]);
1923         }
1924 #endif
1925
1926         /*
1927          *  If phase mismatch handled by scripts (895A/896/1010),
1928          *  set PM jump addresses.
1929          */
1930         if (np->features & FE_NOPM) {
1931                 OUTL (nc_pmjad1, SCRIPTB_BA (np, pm_handle));
1932                 OUTL (nc_pmjad2, SCRIPTB_BA (np, pm_handle));
1933         }
1934
1935         /*
1936          *    Enable GPIO0 pin for writing if LED support from SCRIPTS.
1937          *    Also set GPIO5 and clear GPIO6 if hardware LED control.
1938          */
1939         if (np->features & FE_LED0)
1940                 OUTB(nc_gpcntl, INB(nc_gpcntl) & ~0x01);
1941         else if (np->features & FE_LEDC)
1942                 OUTB(nc_gpcntl, (INB(nc_gpcntl) & ~0x41) | 0x20);
1943
1944         /*
1945          *      enable ints
1946          */
1947         OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
1948         OUTB (nc_dien , MDPE|BF|SSI|SIR|IID);
1949
1950         /*
1951          *  For 895/6 enable SBMC interrupt and save current SCSI bus mode.
1952          *  Try to eat the spurious SBMC interrupt that may occur when 
1953          *  we reset the chip but not the SCSI BUS (at initialization).
1954          */
1955         if (np->features & (FE_ULTRA2|FE_ULTRA3)) {
1956                 OUTONW (nc_sien, SBMC);
1957                 if (reason == 0) {
1958                         MDELAY(100);
1959                         INW (nc_sist);
1960                 }
1961                 np->scsi_mode = INB (nc_stest4) & SMODE;
1962         }
1963
1964         /*
1965          *  Fill in target structure.
1966          *  Reinitialize usrsync.
1967          *  Reinitialize usrwide.
1968          *  Prepare sync negotiation according to actual SCSI bus mode.
1969          */
1970         for (i=0;i<SYM_CONF_MAX_TARGET;i++) {
1971                 tcb_p tp = &np->target[i];
1972
1973                 tp->to_reset  = 0;
1974                 tp->head.sval = 0;
1975                 tp->head.wval = np->rv_scntl3;
1976                 tp->head.uval = 0;
1977
1978                 tp->tinfo.curr.period = 0;
1979                 tp->tinfo.curr.offset = 0;
1980                 tp->tinfo.curr.width  = BUS_8_BIT;
1981                 tp->tinfo.curr.options = 0;
1982         }
1983
1984         /*
1985          *  Download SCSI SCRIPTS to on-chip RAM if present,
1986          *  and start script processor.
1987          *  We do the download preferently from the CPU.
1988          *  For platforms that may not support PCI memory mapping,
1989          *  we use simple SCRIPTS that performs MEMORY MOVEs.
1990          */
1991         if (np->ram_ba) {
1992                 if (sym_verbose >= 2)
1993                         printf ("%s: Downloading SCSI SCRIPTS.\n",
1994                                 sym_name(np));
1995                 if (np->ram_ws == 8192) {
1996                         OUTRAM_OFF(4096, np->scriptb0, np->scriptb_sz);
1997                         phys =  scr_to_cpu(np->scr_ram_seg);
1998                         OUTL (nc_mmws, phys);
1999                         OUTL (nc_mmrs, phys);
2000                         OUTL (nc_sfs,  phys);
2001                         phys = SCRIPTB_BA (np, start64);
2002                 }
2003                 else
2004                         phys = SCRIPTA_BA (np, init);
2005                 OUTRAM_OFF(0, np->scripta0, np->scripta_sz);
2006         }
2007         else
2008                 phys = SCRIPTA_BA (np, init);
2009
2010         np->istat_sem = 0;
2011
2012         OUTL (nc_dsa, np->hcb_ba);
2013         OUTL_DSP (phys);
2014
2015         /*
2016          *  Notify the XPT about the RESET condition.
2017          */
2018         if (reason != 0)
2019                 sym_xpt_async_bus_reset(np);
2020 }
2021
2022 /*
2023  *  Switch trans mode for current job and it's target.
2024  */
2025 static void sym_settrans(hcb_p np, int target, u_char dt, u_char ofs,
2026                          u_char per, u_char wide, u_char div, u_char fak)
2027 {
2028         SYM_QUEHEAD *qp;
2029         u_char sval, wval, uval;
2030         tcb_p tp = &np->target[target];
2031
2032         assert(target == (INB (nc_sdid) & 0x0f));
2033
2034         sval = tp->head.sval;
2035         wval = tp->head.wval;
2036         uval = tp->head.uval;
2037
2038 #if 0
2039         printf("XXXX sval=%x wval=%x uval=%x (%x)\n", 
2040                 sval, wval, uval, np->rv_scntl3);
2041 #endif
2042         /*
2043          *  Set the offset.
2044          */
2045         if (!(np->features & FE_C10))
2046                 sval = (sval & ~0x1f) | ofs;
2047         else
2048                 sval = (sval & ~0x3f) | ofs;
2049
2050         /*
2051          *  Set the sync divisor and extra clock factor.
2052          */
2053         if (ofs != 0) {
2054                 wval = (wval & ~0x70) | ((div+1) << 4);
2055                 if (!(np->features & FE_C10))
2056                         sval = (sval & ~0xe0) | (fak << 5);
2057                 else {
2058                         uval = uval & ~(XCLKH_ST|XCLKH_DT|XCLKS_ST|XCLKS_DT);
2059                         if (fak >= 1) uval |= (XCLKH_ST|XCLKH_DT);
2060                         if (fak >= 2) uval |= (XCLKS_ST|XCLKS_DT);
2061                 }
2062         }
2063
2064         /*
2065          *  Set the bus width.
2066          */
2067         wval = wval & ~EWS;
2068         if (wide != 0)
2069                 wval |= EWS;
2070
2071         /*
2072          *  Set misc. ultra enable bits.
2073          */
2074         if (np->features & FE_C10) {
2075                 uval = uval & ~(U3EN|AIPCKEN);
2076                 if (dt) {
2077                         assert(np->features & FE_U3EN);
2078                         uval |= U3EN;
2079                 }
2080         }
2081         else {
2082                 wval = wval & ~ULTRA;
2083                 if (per <= 12)  wval |= ULTRA;
2084         }
2085
2086         /*
2087          *   Stop there if sync parameters are unchanged.
2088          */
2089         if (tp->head.sval == sval && 
2090             tp->head.wval == wval &&
2091             tp->head.uval == uval)
2092                 return;
2093         tp->head.sval = sval;
2094         tp->head.wval = wval;
2095         tp->head.uval = uval;
2096
2097         /*
2098          *  Disable extended Sreq/Sack filtering if per < 50.
2099          *  Not supported on the C1010.
2100          */
2101         if (per < 50 && !(np->features & FE_C10))
2102                 OUTOFFB (nc_stest2, EXT);
2103
2104         /*
2105          *  set actual value and sync_status
2106          */
2107         OUTB (nc_sxfer,  tp->head.sval);
2108         OUTB (nc_scntl3, tp->head.wval);
2109
2110         if (np->features & FE_C10) {
2111                 OUTB (nc_scntl4, tp->head.uval);
2112         }
2113
2114         /*
2115          *  patch ALL busy ccbs of this target.
2116          */
2117         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
2118                 ccb_p cp;
2119                 cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
2120                 if (cp->target != target)
2121                         continue;
2122                 cp->phys.select.sel_scntl3 = tp->head.wval;
2123                 cp->phys.select.sel_sxfer  = tp->head.sval;
2124                 if (np->features & FE_C10) {
2125                         cp->phys.select.sel_scntl4 = tp->head.uval;
2126                 }
2127         }
2128 }
2129
2130 /*
2131  *  We received a WDTR.
2132  *  Let everything be aware of the changes.
2133  */
2134 static void sym_setwide(hcb_p np, int target, u_char wide)
2135 {
2136         tcb_p tp = &np->target[target];
2137
2138         sym_settrans(np, target, 0, 0, 0, wide, 0, 0);
2139
2140         tp->tinfo.goal.width = tp->tinfo.curr.width = wide;
2141         tp->tinfo.curr.offset = 0;
2142         tp->tinfo.curr.period = 0;
2143         tp->tinfo.curr.options = 0;
2144
2145         sym_xpt_async_nego_wide(np, target);
2146 }
2147
2148 /*
2149  *  We received a SDTR.
2150  *  Let everything be aware of the changes.
2151  */
2152 static void
2153 sym_setsync(hcb_p np, int target,
2154             u_char ofs, u_char per, u_char div, u_char fak)
2155 {
2156         tcb_p tp = &np->target[target];
2157         u_char wide = (tp->head.wval & EWS) ? BUS_16_BIT : BUS_8_BIT;
2158
2159         sym_settrans(np, target, 0, ofs, per, wide, div, fak);
2160
2161         tp->tinfo.curr.period  = per;
2162         tp->tinfo.curr.offset  = ofs;
2163         tp->tinfo.curr.options = 0;
2164
2165         if (!(tp->tinfo.goal.options & PPR_OPT_MASK)) {
2166                 tp->tinfo.goal.period   = per;
2167                 tp->tinfo.goal.offset   = ofs;
2168                 tp->tinfo.goal.options  = 0;
2169         }
2170
2171         sym_xpt_async_nego_sync(np, target);
2172 }
2173
2174 /*
2175  *  We received a PPR.
2176  *  Let everything be aware of the changes.
2177  */
2178 static void 
2179 sym_setpprot(hcb_p np, int target, u_char dt, u_char ofs,
2180              u_char per, u_char wide, u_char div, u_char fak)
2181 {
2182         tcb_p tp = &np->target[target];
2183
2184         sym_settrans(np, target, dt, ofs, per, wide, div, fak);
2185
2186         tp->tinfo.goal.width    = tp->tinfo.curr.width  = wide;
2187         tp->tinfo.goal.period   = tp->tinfo.curr.period = per;
2188         tp->tinfo.goal.offset   = tp->tinfo.curr.offset = ofs;
2189         tp->tinfo.goal.options  = tp->tinfo.curr.options = dt;
2190
2191         sym_xpt_async_nego_ppr(np, target);
2192 }
2193
2194 /*
2195  *  generic recovery from scsi interrupt
2196  *
2197  *  The doc says that when the chip gets an SCSI interrupt,
2198  *  it tries to stop in an orderly fashion, by completing 
2199  *  an instruction fetch that had started or by flushing 
2200  *  the DMA fifo for a write to memory that was executing.
2201  *  Such a fashion is not enough to know if the instruction 
2202  *  that was just before the current DSP value has been 
2203  *  executed or not.
2204  *
2205  *  There are some small SCRIPTS sections that deal with 
2206  *  the start queue and the done queue that may break any 
2207  *  assomption from the C code if we are interrupted 
2208  *  inside, so we reset if this happens. Btw, since these 
2209  *  SCRIPTS sections are executed while the SCRIPTS hasn't 
2210  *  started SCSI operations, it is very unlikely to happen.
2211  *
2212  *  All the driver data structures are supposed to be 
2213  *  allocated from the same 4 GB memory window, so there 
2214  *  is a 1 to 1 relationship between DSA and driver data 
2215  *  structures. Since we are careful :) to invalidate the 
2216  *  DSA when we complete a command or when the SCRIPTS 
2217  *  pushes a DSA into a queue, we can trust it when it 
2218  *  points to a CCB.
2219  */
2220 static void sym_recover_scsi_int (hcb_p np, u_char hsts)
2221 {
2222         u32     dsp     = INL (nc_dsp);
2223         u32     dsa     = INL (nc_dsa);
2224         ccb_p cp        = sym_ccb_from_dsa(np, dsa);
2225
2226         /*
2227          *  If we haven't been interrupted inside the SCRIPTS 
2228          *  critical pathes, we can safely restart the SCRIPTS 
2229          *  and trust the DSA value if it matches a CCB.
2230          */
2231         if ((!(dsp > SCRIPTA_BA (np, getjob_begin) &&
2232                dsp < SCRIPTA_BA (np, getjob_end) + 1)) &&
2233             (!(dsp > SCRIPTA_BA (np, ungetjob) &&
2234                dsp < SCRIPTA_BA (np, reselect) + 1)) &&
2235             (!(dsp > SCRIPTB_BA (np, sel_for_abort) &&
2236                dsp < SCRIPTB_BA (np, sel_for_abort_1) + 1)) &&
2237             (!(dsp > SCRIPTA_BA (np, done) &&
2238                dsp < SCRIPTA_BA (np, done_end) + 1))) {
2239                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* clear dma fifo  */
2240                 OUTB (nc_stest3, TE|CSF);               /* clear scsi fifo */
2241                 /*
2242                  *  If we have a CCB, let the SCRIPTS call us back for 
2243                  *  the handling of the error with SCRATCHA filled with 
2244                  *  STARTPOS. This way, we will be able to freeze the 
2245                  *  device queue and requeue awaiting IOs.
2246                  */
2247                 if (cp) {
2248                         cp->host_status = hsts;
2249                         OUTL_DSP (SCRIPTA_BA (np, complete_error));
2250                 }
2251                 /*
2252                  *  Otherwise just restart the SCRIPTS.
2253                  */
2254                 else {
2255                         OUTL (nc_dsa, 0xffffff);
2256                         OUTL_DSP (SCRIPTA_BA (np, start));
2257                 }
2258         }
2259         else
2260                 goto reset_all;
2261
2262         return;
2263
2264 reset_all:
2265         sym_start_reset(np);
2266 }
2267
2268 /*
2269  *  chip exception handler for selection timeout
2270  */
2271 static void sym_int_sto (hcb_p np)
2272 {
2273         u32 dsp = INL (nc_dsp);
2274
2275         if (DEBUG_FLAGS & DEBUG_TINY) printf ("T");
2276
2277         if (dsp == SCRIPTA_BA (np, wf_sel_done) + 8)
2278                 sym_recover_scsi_int(np, HS_SEL_TIMEOUT);
2279         else
2280                 sym_start_reset(np);
2281 }
2282
2283 /*
2284  *  chip exception handler for unexpected disconnect
2285  */
2286 static void sym_int_udc (hcb_p np)
2287 {
2288         printf ("%s: unexpected disconnect\n", sym_name(np));
2289         sym_recover_scsi_int(np, HS_UNEXPECTED);
2290 }
2291
2292 /*
2293  *  chip exception handler for SCSI bus mode change
2294  *
2295  *  spi2-r12 11.2.3 says a transceiver mode change must 
2296  *  generate a reset event and a device that detects a reset 
2297  *  event shall initiate a hard reset. It says also that a
2298  *  device that detects a mode change shall set data transfer 
2299  *  mode to eight bit asynchronous, etc...
2300  *  So, just reinitializing all except chip should be enough.
2301  */
2302 static void sym_int_sbmc (hcb_p np)
2303 {
2304         u_char scsi_mode = INB (nc_stest4) & SMODE;
2305
2306         /*
2307          *  Notify user.
2308          */
2309         printf("%s: SCSI BUS mode change from %s to %s.\n", sym_name(np),
2310                 sym_scsi_bus_mode(np->scsi_mode), sym_scsi_bus_mode(scsi_mode));
2311
2312         /*
2313          *  Should suspend command processing for a few seconds and 
2314          *  reinitialize all except the chip.
2315          */
2316         sym_start_up (np, 2);
2317 }
2318
2319 /*
2320  *  chip exception handler for SCSI parity error.
2321  *
2322  *  When the chip detects a SCSI parity error and is 
2323  *  currently executing a (CH)MOV instruction, it does 
2324  *  not interrupt immediately, but tries to finish the 
2325  *  transfer of the current scatter entry before 
2326  *  interrupting. The following situations may occur:
2327  *
2328  *  - The complete scatter entry has been transferred 
2329  *    without the device having changed phase.
2330  *    The chip will then interrupt with the DSP pointing 
2331  *    to the instruction that follows the MOV.
2332  *
2333  *  - A phase mismatch occurs before the MOV finished 
2334  *    and phase errors are to be handled by the C code.
2335  *    The chip will then interrupt with both PAR and MA 
2336  *    conditions set.
2337  *
2338  *  - A phase mismatch occurs before the MOV finished and 
2339  *    phase errors are to be handled by SCRIPTS.
2340  *    The chip will load the DSP with the phase mismatch 
2341  *    JUMP address and interrupt the host processor.
2342  */
2343 static void sym_int_par (hcb_p np, u_short sist)
2344 {
2345         u_char  hsts    = INB (HS_PRT);
2346         u32     dsp     = INL (nc_dsp);
2347         u32     dbc     = INL (nc_dbc);
2348         u32     dsa     = INL (nc_dsa);
2349         u_char  sbcl    = INB (nc_sbcl);
2350         u_char  cmd     = dbc >> 24;
2351         int phase       = cmd & 7;
2352         ccb_p   cp      = sym_ccb_from_dsa(np, dsa);
2353
2354         printf("%s: SCSI parity error detected: SCR1=%d DBC=%x SBCL=%x\n",
2355                 sym_name(np), hsts, dbc, sbcl);
2356
2357         /*
2358          *  Check that the chip is connected to the SCSI BUS.
2359          */
2360         if (!(INB (nc_scntl1) & ISCON)) {
2361                 sym_recover_scsi_int(np, HS_UNEXPECTED);
2362                 return;
2363         }
2364
2365         /*
2366          *  If the nexus is not clearly identified, reset the bus.
2367          *  We will try to do better later.
2368          */
2369         if (!cp)
2370                 goto reset_all;
2371
2372         /*
2373          *  Check instruction was a MOV, direction was INPUT and 
2374          *  ATN is asserted.
2375          */
2376         if ((cmd & 0xc0) || !(phase & 1) || !(sbcl & 0x8))
2377                 goto reset_all;
2378
2379         /*
2380          *  Keep track of the parity error.
2381          */
2382         OUTONB (HF_PRT, HF_EXT_ERR);
2383         cp->xerr_status |= XE_PARITY_ERR;
2384
2385         /*
2386          *  Prepare the message to send to the device.
2387          */
2388         np->msgout[0] = (phase == 7) ? M_PARITY : M_ID_ERROR;
2389
2390         /*
2391          *  If the old phase was DATA IN phase, we have to deal with
2392          *  the 3 situations described above.
2393          *  For other input phases (MSG IN and STATUS), the device 
2394          *  must resend the whole thing that failed parity checking 
2395          *  or signal error. So, jumping to dispatcher should be OK.
2396          */
2397         if (phase == 1 || phase == 5) {
2398                 /* Phase mismatch handled by SCRIPTS */
2399                 if (dsp == SCRIPTB_BA (np, pm_handle))
2400                         OUTL_DSP (dsp);
2401                 /* Phase mismatch handled by the C code */
2402                 else if (sist & MA)
2403                         sym_int_ma (np);
2404                 /* No phase mismatch occurred */
2405                 else {
2406                         sym_set_script_dp (np, cp, dsp);
2407                         OUTL_DSP (SCRIPTA_BA (np, dispatch));
2408                 }
2409         }
2410         else if (phase == 7)    /* We definitely cannot handle parity errors */
2411 #if 1                           /* in message-in phase due to the relection  */
2412                 goto reset_all; /* path and various message anticipations.   */
2413 #else
2414                 OUTL_DSP (SCRIPTA_BA (np, clrack));
2415 #endif
2416         else
2417                 OUTL_DSP (SCRIPTA_BA (np, dispatch));
2418         return;
2419
2420 reset_all:
2421         sym_start_reset(np);
2422         return;
2423 }
2424
2425 /*
2426  *  chip exception handler for phase errors.
2427  *
2428  *  We have to construct a new transfer descriptor,
2429  *  to transfer the rest of the current block.
2430  */
2431 static void sym_int_ma (hcb_p np)
2432 {
2433         u32     dbc;
2434         u32     rest;
2435         u32     dsp;
2436         u32     dsa;
2437         u32     nxtdsp;
2438         u32     *vdsp;
2439         u32     oadr, olen;
2440         u32     *tblp;
2441         u32     newcmd;
2442         u_int   delta;
2443         u_char  cmd;
2444         u_char  hflags, hflags0;
2445         struct  sym_pmc *pm;
2446         ccb_p   cp;
2447
2448         dsp     = INL (nc_dsp);
2449         dbc     = INL (nc_dbc);
2450         dsa     = INL (nc_dsa);
2451
2452         cmd     = dbc >> 24;
2453         rest    = dbc & 0xffffff;
2454         delta   = 0;
2455
2456         /*
2457          *  locate matching cp if any.
2458          */
2459         cp = sym_ccb_from_dsa(np, dsa);
2460
2461         /*
2462          *  Donnot take into account dma fifo and various buffers in 
2463          *  INPUT phase since the chip flushes everything before 
2464          *  raising the MA interrupt for interrupted INPUT phases.
2465          *  For DATA IN phase, we will check for the SWIDE later.
2466          */
2467         if ((cmd & 7) != 1 && (cmd & 7) != 5) {
2468                 u_char ss0, ss2;
2469
2470                 if (np->features & FE_DFBC)
2471                         delta = INW (nc_dfbc);
2472                 else {
2473                         u32 dfifo;
2474
2475                         /*
2476                          * Read DFIFO, CTEST[4-6] using 1 PCI bus ownership.
2477                          */
2478                         dfifo = INL(nc_dfifo);
2479
2480                         /*
2481                          *  Calculate remaining bytes in DMA fifo.
2482                          *  (CTEST5 = dfifo >> 16)
2483                          */
2484                         if (dfifo & (DFS << 16))
2485                                 delta = ((((dfifo >> 8) & 0x300) |
2486                                           (dfifo & 0xff)) - rest) & 0x3ff;
2487                         else
2488                                 delta = ((dfifo & 0xff) - rest) & 0x7f;
2489                 }
2490
2491                 /*
2492                  *  The data in the dma fifo has not been transfered to
2493                  *  the target -> add the amount to the rest
2494                  *  and clear the data.
2495                  *  Check the sstat2 register in case of wide transfer.
2496                  */
2497                 rest += delta;
2498                 ss0  = INB (nc_sstat0);
2499                 if (ss0 & OLF) rest++;
2500                 if (!(np->features & FE_C10))
2501                         if (ss0 & ORF) rest++;
2502                 if (cp && (cp->phys.select.sel_scntl3 & EWS)) {
2503                         ss2 = INB (nc_sstat2);
2504                         if (ss2 & OLF1) rest++;
2505                         if (!(np->features & FE_C10))
2506                                 if (ss2 & ORF1) rest++;
2507                 };
2508
2509                 /*
2510                  *  Clear fifos.
2511                  */
2512                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* dma fifo  */
2513                 OUTB (nc_stest3, TE|CSF);               /* scsi fifo */
2514         }
2515
2516         /*
2517          *  log the information
2518          */
2519         if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
2520                 printf ("P%x%x RL=%d D=%d ", cmd&7, INB(nc_sbcl)&7,
2521                         (unsigned) rest, (unsigned) delta);
2522
2523         /*
2524          *  try to find the interrupted script command,
2525          *  and the address at which to continue.
2526          */
2527         vdsp    = NULL;
2528         nxtdsp  = 0;
2529         if      (dsp >  np->scripta_ba &&
2530                  dsp <= np->scripta_ba + np->scripta_sz) {
2531                 vdsp = (u32 *)((char*)np->scripta0 + (dsp-np->scripta_ba-8));
2532                 nxtdsp = dsp;
2533         }
2534         else if (dsp >  np->scriptb_ba &&
2535                  dsp <= np->scriptb_ba + np->scriptb_sz) {
2536                 vdsp = (u32 *)((char*)np->scriptb0 + (dsp-np->scriptb_ba-8));
2537                 nxtdsp = dsp;
2538         }
2539
2540         /*
2541          *  log the information
2542          */
2543         if (DEBUG_FLAGS & DEBUG_PHASE) {
2544                 printf ("\nCP=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
2545                         cp, (unsigned)dsp, (unsigned)nxtdsp, vdsp, cmd);
2546         };
2547
2548         if (!vdsp) {
2549                 printf ("%s: interrupted SCRIPT address not found.\n", 
2550                         sym_name (np));
2551                 goto reset_all;
2552         }
2553
2554         if (!cp) {
2555                 printf ("%s: SCSI phase error fixup: CCB already dequeued.\n", 
2556                         sym_name (np));
2557                 goto reset_all;
2558         }
2559
2560         /*
2561          *  get old startaddress and old length.
2562          */
2563         oadr = scr_to_cpu(vdsp[1]);
2564
2565         if (cmd & 0x10) {       /* Table indirect */
2566                 tblp = (u32 *) ((char*) &cp->phys + oadr);
2567                 olen = scr_to_cpu(tblp[0]);
2568                 oadr = scr_to_cpu(tblp[1]);
2569         } else {
2570                 tblp = (u32 *) 0;
2571                 olen = scr_to_cpu(vdsp[0]) & 0xffffff;
2572         };
2573
2574         if (DEBUG_FLAGS & DEBUG_PHASE) {
2575                 printf ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
2576                         (unsigned) (scr_to_cpu(vdsp[0]) >> 24),
2577                         tblp,
2578                         (unsigned) olen,
2579                         (unsigned) oadr);
2580         };
2581
2582         /*
2583          *  check cmd against assumed interrupted script command.
2584          *  If dt data phase, the MOVE instruction hasn't bit 4 of 
2585          *  the phase.
2586          */
2587         if (((cmd & 2) ? cmd : (cmd & ~4)) != (scr_to_cpu(vdsp[0]) >> 24)) {
2588                 PRINT_ADDR(cp);
2589                 printf ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
2590                         (unsigned)cmd, (unsigned)scr_to_cpu(vdsp[0]) >> 24);
2591
2592                 goto reset_all;
2593         };
2594
2595         /*
2596          *  if old phase not dataphase, leave here.
2597          */
2598         if (cmd & 2) {
2599                 PRINT_ADDR(cp);
2600                 printf ("phase change %x-%x %d@%08x resid=%d.\n",
2601                         cmd&7, INB(nc_sbcl)&7, (unsigned)olen,
2602                         (unsigned)oadr, (unsigned)rest);
2603                 goto unexpected_phase;
2604         };
2605
2606         /*
2607          *  Choose the correct PM save area.
2608          *
2609          *  Look at the PM_SAVE SCRIPT if you want to understand 
2610          *  this stuff. The equivalent code is implemented in 
2611          *  SCRIPTS for the 895A, 896 and 1010 that are able to 
2612          *  handle PM from the SCRIPTS processor.
2613          */
2614         hflags0 = INB (HF_PRT);
2615         hflags = hflags0;
2616
2617         if (hflags & (HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED)) {
2618                 if (hflags & HF_IN_PM0)
2619                         nxtdsp = scr_to_cpu(cp->phys.pm0.ret);
2620                 else if (hflags & HF_IN_PM1)
2621                         nxtdsp = scr_to_cpu(cp->phys.pm1.ret);
2622
2623                 if (hflags & HF_DP_SAVED)
2624                         hflags ^= HF_ACT_PM;
2625         }
2626
2627         if (!(hflags & HF_ACT_PM)) {
2628                 pm = &cp->phys.pm0;
2629                 newcmd = SCRIPTA_BA (np, pm0_data);
2630         }
2631         else {
2632                 pm = &cp->phys.pm1;
2633                 newcmd = SCRIPTA_BA (np, pm1_data);
2634         }
2635
2636         hflags &= ~(HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED);
2637         if (hflags != hflags0)
2638                 OUTB (HF_PRT, hflags);
2639
2640         /*
2641          *  fillin the phase mismatch context
2642          */
2643         pm->sg.addr = cpu_to_scr(oadr + olen - rest);
2644         pm->sg.size = cpu_to_scr(rest);
2645         pm->ret     = cpu_to_scr(nxtdsp);
2646
2647         /*
2648          *  If we have a SWIDE,
2649          *  - prepare the address to write the SWIDE from SCRIPTS,
2650          *  - compute the SCRIPTS address to restart from,
2651          *  - move current data pointer context by one byte.
2652          */
2653         nxtdsp = SCRIPTA_BA (np, dispatch);
2654         if ((cmd & 7) == 1 && cp && (cp->phys.select.sel_scntl3 & EWS) &&
2655             (INB (nc_scntl2) & WSR)) {
2656                 u32 tmp;
2657
2658                 /*
2659                  *  Set up the table indirect for the MOVE
2660                  *  of the residual byte and adjust the data 
2661                  *  pointer context.
2662                  */
2663                 tmp = scr_to_cpu(pm->sg.addr);
2664                 cp->phys.wresid.addr = cpu_to_scr(tmp);
2665                 pm->sg.addr = cpu_to_scr(tmp + 1);
2666                 tmp = scr_to_cpu(pm->sg.size);
2667                 cp->phys.wresid.size = cpu_to_scr((tmp&0xff000000) | 1);
2668                 pm->sg.size = cpu_to_scr(tmp - 1);
2669
2670                 /*
2671                  *  If only the residual byte is to be moved, 
2672                  *  no PM context is needed.
2673                  */
2674                 if ((tmp&0xffffff) == 1)
2675                         newcmd = pm->ret;
2676
2677                 /*
2678                  *  Prepare the address of SCRIPTS that will 
2679                  *  move the residual byte to memory.
2680                  */
2681                 nxtdsp = SCRIPTB_BA (np, wsr_ma_helper);
2682         }
2683
2684         if (DEBUG_FLAGS & DEBUG_PHASE) {
2685                 PRINT_ADDR(cp);
2686                 printf ("PM %x %x %x / %x %x %x.\n",
2687                         hflags0, hflags, newcmd,
2688                         (unsigned)scr_to_cpu(pm->sg.addr),
2689                         (unsigned)scr_to_cpu(pm->sg.size),
2690                         (unsigned)scr_to_cpu(pm->ret));
2691         }
2692
2693         /*
2694          *  Restart the SCRIPTS processor.
2695          */
2696         sym_set_script_dp (np, cp, newcmd);
2697         OUTL_DSP (nxtdsp);
2698         return;
2699
2700         /*
2701          *  Unexpected phase changes that occurs when the current phase 
2702          *  is not a DATA IN or DATA OUT phase are due to error conditions.
2703          *  Such event may only happen when the SCRIPTS is using a 
2704          *  multibyte SCSI MOVE.
2705          *
2706          *  Phase change                Some possible cause
2707          *
2708          *  COMMAND  --> MSG IN SCSI parity error detected by target.
2709          *  COMMAND  --> STATUS Bad command or refused by target.
2710          *  MSG OUT  --> MSG IN     Message rejected by target.
2711          *  MSG OUT  --> COMMAND    Bogus target that discards extended
2712          *                      negotiation messages.
2713          *
2714          *  The code below does not care of the new phase and so 
2715          *  trusts the target. Why to annoy it ?
2716          *  If the interrupted phase is COMMAND phase, we restart at
2717          *  dispatcher.
2718          *  If a target does not get all the messages after selection, 
2719          *  the code assumes blindly that the target discards extended 
2720          *  messages and clears the negotiation status.
2721          *  If the target does not want all our response to negotiation,
2722          *  we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids 
2723          *  bloat for such a should_not_happen situation).
2724          *  In all other situation, we reset the BUS.
2725          *  Are these assumptions reasonnable ? (Wait and see ...)
2726          */
2727 unexpected_phase:
2728         dsp -= 8;
2729         nxtdsp = 0;
2730
2731         switch (cmd & 7) {
2732         case 2: /* COMMAND phase */
2733                 nxtdsp = SCRIPTA_BA (np, dispatch);
2734                 break;
2735 #if 0
2736         case 3: /* STATUS  phase */
2737                 nxtdsp = SCRIPTA_BA (np, dispatch);
2738                 break;
2739 #endif
2740         case 6: /* MSG OUT phase */
2741                 /*
2742                  *  If the device may want to use untagged when we want 
2743                  *  tagged, we prepare an IDENTIFY without disc. granted, 
2744                  *  since we will not be able to handle reselect.
2745                  *  Otherwise, we just don't care.
2746                  */
2747                 if      (dsp == SCRIPTA_BA (np, send_ident)) {
2748                         if (cp->tag != NO_TAG && olen - rest <= 3) {
2749                                 cp->host_status = HS_BUSY;
2750                                 np->msgout[0] = M_IDENTIFY | cp->lun;
2751                                 nxtdsp = SCRIPTB_BA (np, ident_break_atn);
2752                         }
2753                         else
2754                                 nxtdsp = SCRIPTB_BA (np, ident_break);
2755                 }
2756                 else if (dsp == SCRIPTB_BA (np, send_wdtr) ||
2757                          dsp == SCRIPTB_BA (np, send_sdtr) ||
2758                          dsp == SCRIPTB_BA (np, send_ppr)) {
2759                         nxtdsp = SCRIPTB_BA (np, nego_bad_phase);
2760                 }
2761                 break;
2762 #if 0
2763         case 7: /* MSG IN  phase */
2764                 nxtdsp = SCRIPTA_BA (np, clrack);
2765                 break;
2766 #endif
2767         }
2768
2769         if (nxtdsp) {
2770                 OUTL_DSP (nxtdsp);
2771                 return;
2772         }
2773
2774 reset_all:
2775         sym_start_reset(np);
2776 }
2777
2778 /*
2779  *  chip interrupt handler
2780  *
2781  *  In normal situations, interrupt conditions occur one at 
2782  *  a time. But when something bad happens on the SCSI BUS, 
2783  *  the chip may raise several interrupt flags before 
2784  *  stopping and interrupting the CPU. The additionnal 
2785  *  interrupt flags are stacked in some extra registers 
2786  *  after the SIP and/or DIP flag has been raised in the 
2787  *  ISTAT. After the CPU has read the interrupt condition 
2788  *  flag from SIST or DSTAT, the chip unstacks the other 
2789  *  interrupt flags and sets the corresponding bits in 
2790  *  SIST or DSTAT. Since the chip starts stacking once the 
2791  *  SIP or DIP flag is set, there is a small window of time 
2792  *  where the stacking does not occur.
2793  *
2794  *  Typically, multiple interrupt conditions may happen in 
2795  *  the following situations:
2796  *
2797  *  - SCSI parity error + Phase mismatch  (PAR|MA)
2798  *    When an parity error is detected in input phase 
2799  *    and the device switches to msg-in phase inside a 
2800  *    block MOV.
2801  *  - SCSI parity error + Unexpected disconnect (PAR|UDC)
2802  *    When a stupid device does not want to handle the 
2803  *    recovery of an SCSI parity error.
2804  *  - Some combinations of STO, PAR, UDC, ...
2805  *    When using non compliant SCSI stuff, when user is 
2806  *    doing non compliant hot tampering on the BUS, when 
2807  *    something really bad happens to a device, etc ...
2808  *
2809  *  The heuristic suggested by SYMBIOS to handle 
2810  *  multiple interrupts is to try unstacking all 
2811  *  interrupts conditions and to handle them on some 
2812  *  priority based on error severity.
2813  *  This will work when the unstacking has been 
2814  *  successful, but we cannot be 100 % sure of that, 
2815  *  since the CPU may have been faster to unstack than 
2816  *  the chip is able to stack. Hmmm ... But it seems that 
2817  *  such a situation is very unlikely to happen.
2818  *
2819  *  If this happen, for example STO caught by the CPU 
2820  *  then UDC happenning before the CPU have restarted 
2821  *  the SCRIPTS, the driver may wrongly complete the 
2822  *  same command on UDC, since the SCRIPTS didn't restart 
2823  *  and the DSA still points to the same command.
2824  *  We avoid this situation by setting the DSA to an 
2825  *  invalid value when the CCB is completed and before 
2826  *  restarting the SCRIPTS.
2827  *
2828  *  Another issue is that we need some section of our 
2829  *  recovery procedures to be somehow uninterruptible but 
2830  *  the SCRIPTS processor does not provides such a 
2831  *  feature. For this reason, we handle recovery preferently 
2832  *  from the C code and check against some SCRIPTS critical 
2833  *  sections from the C code.
2834  *
2835  *  Hopefully, the interrupt handling of the driver is now 
2836  *  able to resist to weird BUS error conditions, but donnot 
2837  *  ask me for any guarantee that it will never fail. :-)
2838  *  Use at your own decision and risk.
2839  */
2840
2841 void sym_interrupt (hcb_p np)
2842 {
2843         u_char  istat, istatc;
2844         u_char  dstat;
2845         u_short sist;
2846
2847         /*
2848          *  interrupt on the fly ?
2849          *  (SCRIPTS may still be running)
2850          *
2851          *  A `dummy read' is needed to ensure that the 
2852          *  clear of the INTF flag reaches the device 
2853          *  and that posted writes are flushed to memory
2854          *  before the scanning of the DONE queue.
2855          *  Note that SCRIPTS also (dummy) read to memory 
2856          *  prior to deliver the INTF interrupt condition.
2857          */
2858         istat = INB (nc_istat);
2859         if (istat & INTF) {
2860                 OUTB (nc_istat, (istat & SIGP) | INTF | np->istat_sem);
2861                 istat = INB (nc_istat);         /* DUMMY READ */
2862                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("F ");
2863                 (void)sym_wakeup_done (np);
2864         };
2865
2866         if (!(istat & (SIP|DIP)))
2867                 return;
2868
2869 #if 0   /* We should never get this one */
2870         if (istat & CABRT)
2871                 OUTB (nc_istat, CABRT);
2872 #endif
2873
2874         /*
2875          *  PAR and MA interrupts may occur at the same time,
2876          *  and we need to know of both in order to handle 
2877          *  this situation properly. We try to unstack SCSI 
2878          *  interrupts for that reason. BTW, I dislike a LOT 
2879          *  such a loop inside the interrupt routine.
2880          *  Even if DMA interrupt stacking is very unlikely to 
2881          *  happen, we also try unstacking these ones, since 
2882          *  this has no performance impact.
2883          */
2884         sist    = 0;
2885         dstat   = 0;
2886         istatc  = istat;
2887         do {
2888                 if (istatc & SIP)
2889                         sist  |= INW (nc_sist);
2890                 if (istatc & DIP)
2891                         dstat |= INB (nc_dstat);
2892                 istatc = INB (nc_istat);
2893                 istat |= istatc;
2894         } while (istatc & (SIP|DIP));
2895
2896         if (DEBUG_FLAGS & DEBUG_TINY)
2897                 printf ("<%d|%x:%x|%x:%x>",
2898                         (int)INB(nc_scr0),
2899                         dstat,sist,
2900                         (unsigned)INL(nc_dsp),
2901                         (unsigned)INL(nc_dbc));
2902         /*
2903          *  On paper, a memory read barrier may be needed here to 
2904          *  prevent out of order LOADs by the CPU from having 
2905          *  prefetched stale data prior to DMA having occurred.
2906          *  And since we are paranoid ... :)
2907          */
2908         MEMORY_READ_BARRIER();
2909
2910         /*
2911          *  First, interrupts we want to service cleanly.
2912          *
2913          *  Phase mismatch (MA) is the most frequent interrupt 
2914          *  for chip earlier than the 896 and so we have to service 
2915          *  it as quickly as possible.
2916          *  A SCSI parity error (PAR) may be combined with a phase 
2917          *  mismatch condition (MA).
2918          *  Programmed interrupts (SIR) are used to call the C code 
2919          *  from SCRIPTS.
2920          *  The single step interrupt (SSI) is not used in this 
2921          *  driver.
2922          */
2923         if (!(sist  & (STO|GEN|HTH|SGE|UDC|SBMC|RST)) &&
2924             !(dstat & (MDPE|BF|ABRT|IID))) {
2925                 if      (sist & PAR)    sym_int_par (np, sist);
2926                 else if (sist & MA)     sym_int_ma (np);
2927                 else if (dstat & SIR)   sym_int_sir (np);
2928                 else if (dstat & SSI)   OUTONB_STD ();
2929                 else                    goto unknown_int;
2930                 return;
2931         };
2932
2933         /*
2934          *  Now, interrupts that donnot happen in normal 
2935          *  situations and that we may need to recover from.
2936          *
2937          *  On SCSI RESET (RST), we reset everything.
2938          *  On SCSI BUS MODE CHANGE (SBMC), we complete all 
2939          *  active CCBs with RESET status, prepare all devices 
2940          *  for negotiating again and restart the SCRIPTS.
2941          *  On STO and UDC, we complete the CCB with the corres- 
2942          *  ponding status and restart the SCRIPTS.
2943          */
2944         if (sist & RST) {
2945                 printf("%s: SCSI BUS reset detected.\n", sym_name(np));
2946                 sym_start_up (np, 1);
2947                 return;
2948         };
2949
2950         OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* clear dma fifo  */
2951         OUTB (nc_stest3, TE|CSF);               /* clear scsi fifo */
2952
2953         if (!(sist  & (GEN|HTH|SGE)) &&
2954             !(dstat & (MDPE|BF|ABRT|IID))) {
2955                 if      (sist & SBMC)   sym_int_sbmc (np);
2956                 else if (sist & STO)    sym_int_sto (np);
2957                 else if (sist & UDC)    sym_int_udc (np);
2958                 else                    goto unknown_int;
2959                 return;
2960         };
2961
2962         /*
2963          *  Now, interrupts we are not able to recover cleanly.
2964          *
2965          *  Log message for hard errors.
2966          *  Reset everything.
2967          */
2968
2969         sym_log_hard_error(np, sist, dstat);
2970
2971         if ((sist & (GEN|HTH|SGE)) ||
2972                 (dstat & (MDPE|BF|ABRT|IID))) {
2973                 sym_start_reset(np);
2974                 return;
2975         };
2976
2977 unknown_int:
2978         /*
2979          *  We just miss the cause of the interrupt. :(
2980          *  Print a message. The timeout will do the real work.
2981          */
2982         printf( "%s: unknown interrupt(s) ignored, "
2983                 "ISTAT=0x%x DSTAT=0x%x SIST=0x%x\n",
2984                 sym_name(np), istat, dstat, sist);
2985 }
2986
2987 /*
2988  *  Dequeue from the START queue all CCBs that match 
2989  *  a given target/lun/task condition (-1 means all),
2990  *  and move them from the BUSY queue to the COMP queue 
2991  *  with CAM_REQUEUE_REQ status condition.
2992  *  This function is used during error handling/recovery.
2993  *  It is called with SCRIPTS not running.
2994  */
2995 static int 
2996 sym_dequeue_from_squeue(hcb_p np, int i, int target, int lun, int task)
2997 {
2998         int j;
2999         ccb_p cp;
3000
3001         /*
3002          *  Make sure the starting index is within range.
3003          */
3004         assert((i >= 0) && (i < 2*MAX_QUEUE));
3005
3006         /*
3007          *  Walk until end of START queue and dequeue every job 
3008          *  that matches the target/lun/task condition.
3009          */
3010         j = i;
3011         while (i != np->squeueput) {
3012                 cp = sym_ccb_from_dsa(np, scr_to_cpu(np->squeue[i]));
3013                 assert(cp);
3014 #ifdef SYM_CONF_IARB_SUPPORT
3015                 /* Forget hints for IARB, they may be no longer relevant */
3016                 cp->host_flags &= ~HF_HINT_IARB;
3017 #endif
3018                 if ((target == -1 || cp->target == target) &&
3019                     (lun    == -1 || cp->lun    == lun)    &&
3020                     (task   == -1 || cp->tag    == task)) {
3021                         sym_set_cam_status(cp->cam_ccb, CAM_REQUEUE_REQ);
3022                         sym_remque(&cp->link_ccbq);
3023                         sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
3024                 }
3025                 else {
3026                         if (i != j)
3027                                 np->squeue[j] = np->squeue[i];
3028                         if ((j += 2) >= MAX_QUEUE*2) j = 0;
3029                 }
3030                 if ((i += 2) >= MAX_QUEUE*2) i = 0;
3031         }
3032         if (i != j)             /* Copy back the idle task if needed */
3033                 np->squeue[j] = np->squeue[i];
3034         np->squeueput = j;      /* Update our current start queue pointer */
3035
3036         return (i - j) / 2;
3037 }
3038
3039 /*
3040  *  Complete all CCBs queued to the COMP queue.
3041  *
3042  *  These CCBs are assumed:
3043  *  - Not to be referenced either by devices or 
3044  *    SCRIPTS-related queues and datas.
3045  *  - To have to be completed with an error condition 
3046  *    or requeued.
3047  *
3048  *  The device queue freeze count is incremented 
3049  *  for each CCB that does not prevent this.
3050  *  This function is called when all CCBs involved 
3051  *  in error handling/recovery have been reaped.
3052  */
3053 void sym_flush_comp_queue(hcb_p np, int cam_status)
3054 {
3055         SYM_QUEHEAD *qp;
3056         ccb_p cp;
3057
3058         while ((qp = sym_remque_head(&np->comp_ccbq)) != 0) {
3059                 cam_ccb_p ccb;
3060                 cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
3061                 sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
3062                 /* Leave quiet CCBs waiting for resources */
3063                 if (cp->host_status == HS_WAIT)
3064                         continue;
3065                 ccb = cp->cam_ccb;
3066                 if (cam_status)
3067                         sym_set_cam_status(ccb, cam_status);
3068 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
3069                 if (sym_get_cam_status(ccb) == CAM_REQUEUE_REQ) {
3070                         tcb_p tp = &np->target[cp->target];
3071                         lcb_p lp = sym_lp(np, tp, cp->lun);
3072                         if (lp) {
3073                                 sym_remque(&cp->link2_ccbq);
3074                                 sym_insque_tail(&cp->link2_ccbq,
3075                                                 &lp->waiting_ccbq);
3076                                 if (cp->started) {
3077                                         if (cp->tag != NO_TAG)
3078                                                 --lp->started_tags;
3079                                         else
3080                                                 --lp->started_no_tag;
3081                                 }
3082                         }
3083                         cp->started = 0;
3084                         continue;
3085                 }
3086 #endif
3087                 sym_free_ccb(np, cp);
3088                 sym_freeze_cam_ccb(ccb);
3089                 sym_xpt_done(np, ccb);
3090         }
3091 }
3092
3093 /*
3094  *  chip handler for bad SCSI status condition
3095  *
3096  *  In case of bad SCSI status, we unqueue all the tasks 
3097  *  currently queued to the controller but not yet started 
3098  *  and then restart the SCRIPTS processor immediately.
3099  *
3100  *  QUEUE FULL and BUSY conditions are handled the same way.
3101  *  Basically all the not yet started tasks are requeued in 
3102  *  device queue and the queue is frozen until a completion.
3103  *
3104  *  For CHECK CONDITION and COMMAND TERMINATED status, we use 
3105  *  the CCB of the failed command to prepare a REQUEST SENSE 
3106  *  SCSI command and queue it to the controller queue.
3107  *
3108  *  SCRATCHA is assumed to have been loaded with STARTPOS 
3109  *  before the SCRIPTS called the C code.
3110  */
3111 static void sym_sir_bad_scsi_status(hcb_p np, int num, ccb_p cp)
3112 {
3113         tcb_p tp        = &np->target[cp->target];
3114         u32             startp;
3115         u_char          s_status = cp->ssss_status;
3116         u_char          h_flags  = cp->host_flags;
3117         int             msglen;
3118         int             nego;
3119         int             i;
3120
3121         /*
3122          *  Compute the index of the next job to start from SCRIPTS.
3123          */
3124         i = (INL (nc_scratcha) - np->squeue_ba) / 4;
3125
3126         /*
3127          *  The last CCB queued used for IARB hint may be 
3128          *  no longer relevant. Forget it.
3129          */
3130 #ifdef SYM_CONF_IARB_SUPPORT
3131         if (np->last_cp)
3132                 np->last_cp = 0;
3133 #endif
3134
3135         /*
3136          *  Now deal with the SCSI status.
3137          */
3138         switch(s_status) {
3139         case S_BUSY:
3140         case S_QUEUE_FULL:
3141                 if (sym_verbose >= 2) {
3142                         PRINT_ADDR(cp);
3143                         printf ("%s\n",
3144                                 s_status == S_BUSY ? "BUSY" : "QUEUE FULL\n");
3145                 }
3146         default:        /* S_INT, S_INT_COND_MET, S_CONFLICT */
3147                 sym_complete_error (np, cp);
3148                 break;
3149         case S_TERMINATED:
3150         case S_CHECK_COND:
3151                 /*
3152                  *  If we get an SCSI error when requesting sense, give up.
3153                  */
3154                 if (h_flags & HF_SENSE) {
3155                         sym_complete_error (np, cp);
3156                         break;
3157                 }
3158
3159                 /*
3160                  *  Dequeue all queued CCBs for that device not yet started,
3161                  *  and restart the SCRIPTS processor immediately.
3162                  */
3163                 (void) sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
3164                 OUTL_DSP (SCRIPTA_BA (np, start));
3165
3166                 /*
3167                  *  Save some info of the actual IO.
3168                  *  Compute the data residual.
3169                  */
3170                 cp->sv_scsi_status = cp->ssss_status;
3171                 cp->sv_xerr_status = cp->xerr_status;
3172                 cp->sv_resid = sym_compute_residual(np, cp);
3173
3174                 /*
3175                  *  Prepare all needed data structures for 
3176                  *  requesting sense data.
3177                  */
3178
3179                 /*
3180                  *  identify message
3181                  */
3182                 cp->scsi_smsg2[0] = M_IDENTIFY | cp->lun;
3183                 msglen = 1;
3184
3185                 /*
3186                  *  If we are currently using anything different from 
3187                  *  async. 8 bit data transfers with that target,
3188                  *  start a negotiation, since the device may want 
3189                  *  to report us a UNIT ATTENTION condition due to 
3190                  *  a cause we currently ignore, and we donnot want 
3191                  *  to be stuck with WIDE and/or SYNC data transfer.
3192                  *
3193                  *  cp->nego_status is filled by sym_prepare_nego().
3194                  */
3195                 cp->nego_status = 0;
3196                 nego = 0;
3197                 if      (tp->tinfo.curr.options & PPR_OPT_MASK)
3198                         nego = NS_PPR;
3199                 else if (tp->tinfo.curr.width != BUS_8_BIT)
3200                         nego = NS_WIDE;
3201                 else if (tp->tinfo.curr.offset != 0)
3202                         nego = NS_SYNC;
3203                 if (nego)
3204                         msglen +=
3205                         sym_prepare_nego (np,cp, nego, &cp->scsi_smsg2[msglen]);
3206                 /*
3207                  *  Message table indirect structure.
3208                  */
3209                 cp->phys.smsg.addr      = cpu_to_scr(CCB_BA (cp, scsi_smsg2));
3210                 cp->phys.smsg.size      = cpu_to_scr(msglen);
3211
3212                 /*
3213                  *  sense command
3214                  */
3215                 cp->phys.cmd.addr       = cpu_to_scr(CCB_BA (cp, sensecmd));
3216                 cp->phys.cmd.size       = cpu_to_scr(6);
3217
3218                 /*
3219                  *  patch requested size into sense command
3220                  */
3221                 cp->sensecmd[0]         = REQUEST_SENSE;
3222                 cp->sensecmd[1]         = 0;
3223                 if (tp->tinfo.curr.scsi_version <= 2 && cp->lun <= 7)
3224                         cp->sensecmd[1] = cp->lun << 5;
3225                 cp->sensecmd[4]         = SYM_SNS_BBUF_LEN;
3226                 cp->data_len            = SYM_SNS_BBUF_LEN;
3227
3228                 /*
3229                  *  sense data
3230                  */
3231                 bzero(cp->sns_bbuf, SYM_SNS_BBUF_LEN);
3232                 cp->phys.sense.addr     = cpu_to_scr(vtobus(cp->sns_bbuf));
3233                 cp->phys.sense.size     = cpu_to_scr(SYM_SNS_BBUF_LEN);
3234
3235                 /*
3236                  *  requeue the command.
3237                  */
3238                 startp = SCRIPTB_BA (np, sdata_in);
3239
3240                 cp->phys.head.savep     = cpu_to_scr(startp);
3241                 cp->phys.head.lastp     = cpu_to_scr(startp);
3242                 cp->startp              = cpu_to_scr(startp);
3243                 cp->goalp               = cpu_to_scr(startp + 16);
3244
3245                 cp->host_xflags = 0;
3246                 cp->host_status = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
3247                 cp->ssss_status = S_ILLEGAL;
3248                 cp->host_flags  = (HF_SENSE|HF_DATA_IN);
3249                 cp->xerr_status = 0;
3250                 cp->extra_bytes = 0;
3251
3252                 cp->phys.head.go.start = cpu_to_scr(SCRIPTA_BA (np, select));
3253
3254                 /*
3255                  *  Requeue the command.
3256                  */
3257                 sym_put_start_queue(np, cp);
3258
3259                 /*
3260                  *  Give back to upper layer everything we have dequeued.
3261                  */
3262                 sym_flush_comp_queue(np, 0);
3263                 break;
3264         }
3265 }
3266
3267 /*
3268  *  After a device has accepted some management message 
3269  *  as BUS DEVICE RESET, ABORT TASK, etc ..., or when 
3270  *  a device signals a UNIT ATTENTION condition, some 
3271  *  tasks are thrown away by the device. We are required 
3272  *  to reflect that on our tasks list since the device 
3273  *  will never complete these tasks.
3274  *
3275  *  This function move from the BUSY queue to the COMP 
3276  *  queue all disconnected CCBs for a given target that 
3277  *  match the following criteria:
3278  *  - lun=-1  means any logical UNIT otherwise a given one.
3279  *  - task=-1 means any task, otherwise a given one.
3280  */
3281 int sym_clear_tasks(hcb_p np, int cam_status, int target, int lun, int task)
3282 {
3283         SYM_QUEHEAD qtmp, *qp;
3284         int i = 0;
3285         ccb_p cp;
3286
3287         /*
3288          *  Move the entire BUSY queue to our temporary queue.
3289          */
3290         sym_que_init(&qtmp);
3291         sym_que_splice(&np->busy_ccbq, &qtmp);
3292         sym_que_init(&np->busy_ccbq);
3293
3294         /*
3295          *  Put all CCBs that matches our criteria into 
3296          *  the COMP queue and put back other ones into 
3297          *  the BUSY queue.
3298          */
3299         while ((qp = sym_remque_head(&qtmp)) != 0) {
3300                 cam_ccb_p ccb;
3301                 cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
3302                 ccb = cp->cam_ccb;
3303                 if (cp->host_status != HS_DISCONNECT ||
3304                     cp->target != target             ||
3305                     (lun  != -1 && cp->lun != lun)   ||
3306                     (task != -1 && 
3307                         (cp->tag != NO_TAG && cp->scsi_smsg[2] != task))) {
3308                         sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
3309                         continue;
3310                 }
3311                 sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
3312
3313                 /* Preserve the software timeout condition */
3314                 if (sym_get_cam_status(ccb) != CAM_CMD_TIMEOUT)
3315                         sym_set_cam_status(ccb, cam_status);
3316                 ++i;
3317 #if 0
3318 printf("XXXX TASK @%p CLEARED\n", cp);
3319 #endif
3320         }
3321         return i;
3322 }
3323
3324 /*
3325  *  chip handler for TASKS recovery
3326  *
3327  *  We cannot safely abort a command, while the SCRIPTS 
3328  *  processor is running, since we just would be in race 
3329  *  with it.
3330  *
3331  *  As long as we have tasks to abort, we keep the SEM 
3332  *  bit set in the ISTAT. When this bit is set, the 
3333  *  SCRIPTS processor interrupts (SIR_SCRIPT_STOPPED) 
3334  *  each time it enters the scheduler.
3335  *
3336  *  If we have to reset a target, clear tasks of a unit,
3337  *  or to perform the abort of a disconnected job, we 
3338  *  restart the SCRIPTS for selecting the target. Once 
3339  *  selected, the SCRIPTS interrupts (SIR_TARGET_SELECTED).
3340  *  If it loses arbitration, the SCRIPTS will interrupt again 
3341  *  the next time it will enter its scheduler, and so on ...
3342  *
3343  *  On SIR_TARGET_SELECTED, we scan for the more 
3344  *  appropriate thing to do:
3345  *
3346  *  - If nothing, we just sent a M_ABORT message to the 
3347  *    target to get rid of the useless SCSI bus ownership.
3348  *    According to the specs, no tasks shall be affected.
3349  *  - If the target is to be reset, we send it a M_RESET 
3350  *    message.
3351  *  - If a logical UNIT is to be cleared , we send the 
3352  *    IDENTIFY(lun) + M_ABORT.
3353  *  - If an untagged task is to be aborted, we send the 
3354  *    IDENTIFY(lun) + M_ABORT.
3355  *  - If a tagged task is to be aborted, we send the 
3356  *    IDENTIFY(lun) + task attributes + M_ABORT_TAG.
3357  *
3358  *  Once our 'kiss of death' :) message has been accepted 
3359  *  by the target, the SCRIPTS interrupts again 
3360  *  (SIR_ABORT_SENT). On this interrupt, we complete 
3361  *  all the CCBs that should have been aborted by the 
3362  *  target according to our message.
3363  */
3364 static void sym_sir_task_recovery(hcb_p np, int num)
3365 {
3366         SYM_QUEHEAD *qp;
3367         ccb_p cp;
3368         tcb_p tp;
3369         int target=-1, lun=-1, task;
3370         int i, k;
3371
3372         switch(num) {
3373         /*
3374          *  The SCRIPTS processor stopped before starting
3375          *  the next command in order to allow us to perform 
3376          *  some task recovery.
3377          */
3378         case SIR_SCRIPT_STOPPED:
3379                 /*
3380                  *  Do we have any target to reset or unit to clear ?
3381                  */
3382                 for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
3383                         tp = &np->target[i];
3384                         if (tp->to_reset || 
3385                             (tp->lun0p && tp->lun0p->to_clear)) {
3386                                 target = i;
3387                                 break;
3388                         }
3389                         if (!tp->lunmp)
3390                                 continue;
3391                         for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
3392                                 if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
3393                                         target  = i;
3394                                         break;
3395                                 }
3396                         }
3397                         if (target != -1)
3398                                 break;
3399                 }
3400
3401                 /*
3402                  *  If not, walk the busy queue for any 
3403                  *  disconnected CCB to be aborted.
3404                  */
3405                 if (target == -1) {
3406                         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
3407                                 cp = sym_que_entry(qp,struct sym_ccb,link_ccbq);
3408                                 if (cp->host_status != HS_DISCONNECT)
3409                                         continue;
3410                                 if (cp->to_abort) {
3411                                         target = cp->target;
3412                                         break;
3413                                 }
3414                         }
3415                 }
3416
3417                 /*
3418                  *  If some target is to be selected, 
3419                  *  prepare and start the selection.
3420                  */
3421                 if (target != -1) {
3422                         tp = &np->target[target];
3423                         np->abrt_sel.sel_id     = target;
3424                         np->abrt_sel.sel_scntl3 = tp->head.wval;
3425                         np->abrt_sel.sel_sxfer  = tp->head.sval;
3426                         OUTL(nc_dsa, np->hcb_ba);
3427                         OUTL_DSP (SCRIPTB_BA (np, sel_for_abort));
3428                         return;
3429                 }
3430
3431                 /*
3432                  *  Now look for a CCB to abort that haven't started yet.
3433                  *  Btw, the SCRIPTS processor is still stopped, so 
3434                  *  we are not in race.
3435                  */
3436                 i = 0;
3437                 cp = NULL;
3438                 FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
3439                         cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
3440                         if (cp->host_status != HS_BUSY &&
3441                             cp->host_status != HS_NEGOTIATE)
3442                                 continue;
3443                         if (!cp->to_abort)
3444                                 continue;
3445 #ifdef SYM_CONF_IARB_SUPPORT
3446                         /*
3447                          *    If we are using IMMEDIATE ARBITRATION, we donnot 
3448                          *    want to cancel the last queued CCB, since the 
3449                          *    SCRIPTS may have anticipated the selection.
3450                          */
3451                         if (cp == np->last_cp) {
3452                                 cp->to_abort = 0;
3453                                 continue;
3454                         }
3455 #endif
3456                         i = 1;  /* Means we have found some */
3457                         break;
3458                 }
3459                 if (!i) {
3460                         /*
3461                          *  We are done, so we donnot need 
3462                          *  to synchronize with the SCRIPTS anylonger.
3463                          *  Remove the SEM flag from the ISTAT.
3464                          */
3465                         np->istat_sem = 0;
3466                         OUTB (nc_istat, SIGP);
3467                         break;
3468                 }
3469                 /*
3470                  *  Compute index of next position in the start 
3471                  *  queue the SCRIPTS intends to start and dequeue 
3472                  *  all CCBs for that device that haven't been started.
3473                  */
3474                 i = (INL (nc_scratcha) - np->squeue_ba) / 4;
3475                 i = sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
3476
3477                 /*
3478                  *  Make sure at least our IO to abort has been dequeued.
3479                  */
3480 #ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
3481                 assert(i && sym_get_cam_status(cp->cam_ccb) == CAM_REQUEUE_REQ);
3482 #else
3483                 sym_remque(&cp->link_ccbq);
3484                 sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
3485 #endif
3486                 /*
3487                  *  Keep track in cam status of the reason of the abort.
3488                  */
3489                 if (cp->to_abort == 2)
3490                         sym_set_cam_status(cp->cam_ccb, CAM_CMD_TIMEOUT);
3491                 else
3492                         sym_set_cam_status(cp->cam_ccb, CAM_REQ_ABORTED);
3493
3494                 /*
3495                  *  Complete with error everything that we have dequeued.
3496                  */
3497                 sym_flush_comp_queue(np, 0);
3498                 break;
3499         /*
3500          *  The SCRIPTS processor has selected a target 
3501          *  we may have some manual recovery to perform for.
3502          */
3503         case SIR_TARGET_SELECTED:
3504                 target = (INB (nc_sdid) & 0xf);
3505                 tp = &np->target[target];
3506
3507                 np->abrt_tbl.addr = cpu_to_scr(vtobus(np->abrt_msg));
3508
3509                 /*
3510                  *  If the target is to be reset, prepare a 
3511                  *  M_RESET message and clear the to_reset flag 
3512                  *  since we donnot expect this operation to fail.
3513                  */
3514                 if (tp->to_reset) {
3515                         np->abrt_msg[0] = M_RESET;
3516                         np->abrt_tbl.size = 1;
3517                         tp->to_reset = 0;
3518                         break;
3519                 }
3520
3521                 /*
3522                  *  Otherwise, look for some logical unit to be cleared.
3523                  */
3524                 if (tp->lun0p && tp->lun0p->to_clear)
3525                         lun = 0;
3526                 else if (tp->lunmp) {
3527                         for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
3528                                 if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
3529                                         lun = k;
3530                                         break;
3531                                 }
3532                         }
3533                 }
3534
3535                 /*
3536                  *  If a logical unit is to be cleared, prepare 
3537                  *  an IDENTIFY(lun) + ABORT MESSAGE.
3538                  */
3539                 if (lun != -1) {
3540                         lcb_p lp = sym_lp(np, tp, lun);
3541                         lp->to_clear = 0; /* We donnot expect to fail here */
3542                         np->abrt_msg[0] = M_IDENTIFY | lun;
3543                         np->abrt_msg[1] = M_ABORT;
3544                         np->abrt_tbl.size = 2;
3545                         break;
3546                 }
3547
3548                 /*
3549                  *  Otherwise, look for some disconnected job to 
3550                  *  abort for this target.
3551                  */
3552                 i = 0;
3553                 cp = NULL;
3554                 FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
3555                         cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
3556                         if (cp->host_status != HS_DISCONNECT)
3557                                 continue;
3558                         if (cp->target != target)
3559                                 continue;
3560                         if (!cp->to_abort)
3561                                 continue;
3562                         i = 1;  /* Means we have some */
3563                         break;
3564                 }
3565
3566                 /*
3567                  *  If we have none, probably since the device has 
3568                  *  completed the command before we won abitration,
3569                  *  send a M_ABORT message without IDENTIFY.
3570                  *  According to the specs, the device must just 
3571                  *  disconnect the BUS and not abort any task.
3572                  */
3573                 if (!i) {
3574                         np->abrt_msg[0] = M_ABORT;
3575                         np->abrt_tbl.size = 1;
3576                         break;
3577                 }
3578
3579                 /*
3580                  *  We have some task to abort.
3581                  *  Set the IDENTIFY(lun)
3582                  */
3583                 np->abrt_msg[0] = M_IDENTIFY | cp->lun;
3584
3585                 /*
3586                  *  If we want to abort an untagged command, we 
3587                  *  will send a IDENTIFY + M_ABORT.
3588                  *  Otherwise (tagged command), we will send 
3589                  *  a IDENTITFY + task attributes + ABORT TAG.
3590                  */
3591                 if (cp->tag == NO_TAG) {
3592                         np->abrt_msg[1] = M_ABORT;
3593                         np->abrt_tbl.size = 2;
3594                 }
3595                 else {
3596                         np->abrt_msg[1] = cp->scsi_smsg[1];
3597                         np->abrt_msg[2] = cp->scsi_smsg[2];
3598                         np->abrt_msg[3] = M_ABORT_TAG;
3599                         np->abrt_tbl.size = 4;
3600                 }
3601                 /*
3602                  *  Keep track of software timeout condition, since the 
3603                  *  peripheral driver may not count retries on abort 
3604                  *  conditions not due to timeout.
3605                  */
3606                 if (cp->to_abort == 2)
3607                         sym_set_cam_status(cp->cam_ccb, CAM_CMD_TIMEOUT);
3608                 cp->to_abort = 0; /* We donnot expect to fail here */
3609                 break;
3610
3611         /*
3612          *  The target has accepted our message and switched 
3613          *  to BUS FREE phase as we expected.
3614          */
3615         case SIR_ABORT_SENT:
3616                 target = (INB (nc_sdid) & 0xf);
3617                 tp = &np->target[target];
3618                 
3619                 /*
3620                 **  If we didn't abort anything, leave here.
3621                 */
3622                 if (np->abrt_msg[0] == M_ABORT)
3623                         break;
3624
3625                 /*
3626                  *  If we sent a M_RESET, then a hardware reset has 
3627                  *  been performed by the target.
3628                  *  - Reset everything to async 8 bit
3629                  *  - Tell ourself to negotiate next time :-)
3630                  *  - Prepare to clear all disconnected CCBs for 
3631                  *    this target from our task list (lun=task=-1)
3632                  */
3633                 lun = -1;
3634                 task = -1;
3635                 if (np->abrt_msg[0] == M_RESET) {
3636                         tp->head.sval = 0;
3637                         tp->head.wval = np->rv_scntl3;
3638                         tp->head.uval = 0;
3639                         tp->tinfo.curr.period = 0;
3640                         tp->tinfo.curr.offset = 0;
3641                         tp->tinfo.curr.width  = BUS_8_BIT;
3642                         tp->tinfo.curr.options = 0;
3643                 }
3644
3645                 /*
3646                  *  Otherwise, check for the LUN and TASK(s) 
3647                  *  concerned by the cancelation.
3648                  *  If it is not ABORT_TAG then it is CLEAR_QUEUE 
3649                  *  or an ABORT message :-)
3650                  */
3651                 else {
3652                         lun = np->abrt_msg[0] & 0x3f;
3653                         if (np->abrt_msg[1] == M_ABORT_TAG)
3654                                 task = np->abrt_msg[2];
3655                 }
3656
3657                 /*
3658                  *  Complete all the CCBs the device should have 
3659                  *  aborted due to our 'kiss of death' message.
3660                  */
3661                 i = (INL (nc_scratcha) - np->squeue_ba) / 4;
3662                 (void) sym_dequeue_from_squeue(np, i, target, lun, -1);
3663                 (void) sym_clear_tasks(np, CAM_REQ_ABORTED, target, lun, task);
3664                 sym_flush_comp_queue(np, 0);
3665
3666                 /*
3667                  *  If we sent a BDR, make upper layer aware of that.
3668                  */
3669                 if (np->abrt_msg[0] == M_RESET)
3670                         sym_xpt_async_sent_bdr(np, target);
3671                 break;
3672         }
3673
3674         /*
3675          *  Print to the log the message we intend to send.
3676          */
3677         if (num == SIR_TARGET_SELECTED) {
3678                 PRINT_TARGET(np, target);
3679                 sym_printl_hex("control msgout:", np->abrt_msg,
3680                               np->abrt_tbl.size);
3681                 np->abrt_tbl.size = cpu_to_scr(np->abrt_tbl.size);
3682         }
3683
3684         /*
3685          *  Let the SCRIPTS processor continue.
3686          */
3687         OUTONB_STD ();
3688 }
3689
3690 /*
3691  *  Gerard's alchemy:) that deals with with the data 
3692  *  pointer for both MDP and the residual calculation.
3693  *
3694  *  I didn't want to bloat the code by more than 200 
3695  *  lignes for the handling of both MDP and the residual.
3696  *  This has been achieved by using a data pointer 
3697  *  representation consisting in an index in the data 
3698  *  array (dp_sg) and a negative offset (dp_ofs) that 
3699  *  have the following meaning:
3700  *
3701  *  - dp_sg = SYM_CONF_MAX_SG
3702  *    we are at the end of the data script.
3703  *  - dp_sg < SYM_CONF_MAX_SG
3704  *    dp_sg points to the next entry of the scatter array 
3705  *    we want to transfer.
3706  *  - dp_ofs < 0
3707  *    dp_ofs represents the residual of bytes of the 
3708  *    previous entry scatter entry we will send first.
3709  *  - dp_ofs = 0
3710  *    no residual to send first.
3711  *
3712  *  The function sym_evaluate_dp() accepts an arbitray 
3713  *  offset (basically from the MDP message) and returns 
3714  *  the corresponding values of dp_sg and dp_ofs.
3715  */
3716
3717 static int sym_evaluate_dp(hcb_p np, ccb_p cp, u32 scr, int *ofs)
3718 {
3719         u32     dp_scr;
3720         int     dp_ofs, dp_sg, dp_sgmin;
3721         int     tmp;
3722         struct sym_pmc *pm;
3723
3724         /*
3725          *  Compute the resulted data pointer in term of a script 
3726          *  address within some DATA script and a signed byte offset.
3727          */
3728         dp_scr = scr;
3729         dp_ofs = *ofs;
3730         if      (dp_scr == SCRIPTA_BA (np, pm0_data))
3731                 pm = &cp->phys.pm0;
3732         else if (dp_scr == SCRIPTA_BA (np, pm1_data))
3733                 pm = &cp->phys.pm1;
3734         else
3735                 pm = NULL;
3736
3737         if (pm) {
3738                 dp_scr  = scr_to_cpu(pm->ret);
3739                 dp_ofs -= scr_to_cpu(pm->sg.size);
3740         }
3741
3742         /*
3743          *  If we are auto-sensing, then we are done.
3744          */
3745         if (cp->host_flags & HF_SENSE) {
3746                 *ofs = dp_ofs;
3747                 return 0;
3748         }
3749
3750         /*
3751          *  Deduce the index of the sg entry.
3752          *  Keep track of the index of the first valid entry.
3753          *  If result is dp_sg = SYM_CONF_MAX_SG, then we are at the 
3754          *  end of the data.
3755          */
3756         tmp = scr_to_cpu(sym_goalp(cp));
3757         dp_sg = SYM_CONF_MAX_SG;
3758         if (dp_scr != tmp)
3759                 dp_sg -= (tmp - 8 - (int)dp_scr) / (2*4);
3760         dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
3761
3762         /*
3763          *  Move to the sg entry the data pointer belongs to.
3764          *
3765          *  If we are inside the data area, we expect result to be:
3766          *
3767          *  Either,
3768          *      dp_ofs = 0 and dp_sg is the index of the sg entry
3769          *      the data pointer belongs to (or the end of the data)
3770          *  Or,
3771          *      dp_ofs < 0 and dp_sg is the index of the sg entry 
3772          *      the data pointer belongs to + 1.
3773          */
3774         if (dp_ofs < 0) {
3775                 int n;
3776                 while (dp_sg > dp_sgmin) {
3777                         --dp_sg;
3778                         tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
3779                         n = dp_ofs + (tmp & 0xffffff);
3780                         if (n > 0) {
3781                                 ++dp_sg;
3782                                 break;
3783                         }
3784                         dp_ofs = n;
3785                 }
3786         }
3787         else if (dp_ofs > 0) {
3788                 while (dp_sg < SYM_CONF_MAX_SG) {
3789                         tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
3790                         dp_ofs -= (tmp & 0xffffff);
3791                         ++dp_sg;
3792                         if (dp_ofs <= 0)
3793                                 break;
3794                 }
3795         }
3796
3797         /*
3798          *  Make sure the data pointer is inside the data area.
3799          *  If not, return some error.
3800          */
3801         if      (dp_sg < dp_sgmin || (dp_sg == dp_sgmin && dp_ofs < 0))
3802                 goto out_err;
3803         else if (dp_sg > SYM_CONF_MAX_SG ||
3804                  (dp_sg == SYM_CONF_MAX_SG && dp_ofs > 0))
3805                 goto out_err;
3806
3807         /*
3808          *  Save the extreme pointer if needed.
3809          */
3810         if (dp_sg > cp->ext_sg ||
3811             (dp_sg == cp->ext_sg && dp_ofs > cp->ext_ofs)) {
3812                 cp->ext_sg  = dp_sg;
3813                 cp->ext_ofs = dp_ofs;
3814         }
3815
3816         /*
3817          *  Return data.
3818          */
3819         *ofs = dp_ofs;
3820         return dp_sg;
3821
3822 out_err:
3823         return -1;
3824 }
3825
3826 /*
3827  *  chip handler for MODIFY DATA POINTER MESSAGE
3828  *
3829  *  We also call this function on IGNORE WIDE RESIDUE 
3830  *  messages that do not match a SWIDE full condition.
3831  *  Btw, we assume in that situation that such a message 
3832  *  is equivalent to a MODIFY DATA POINTER (offset=-1).
3833  */
3834
3835 static void sym_modify_dp(hcb_p np, tcb_p tp, ccb_p cp, int ofs)
3836 {
3837         int dp_ofs      = ofs;
3838         u32     dp_scr  = sym_get_script_dp (np, cp);
3839         u32     dp_ret;
3840         u32     tmp;
3841         u_char  hflags;
3842         int     dp_sg;
3843         struct  sym_pmc *pm;
3844
3845         /*
3846          *  Not supported for auto-sense.
3847          */
3848         if (cp->host_flags & HF_SENSE)
3849                 goto out_reject;
3850
3851         /*
3852          *  Apply our alchemy:) (see comments in sym_evaluate_dp()), 
3853          *  to the resulted data pointer.
3854          */
3855         dp_sg = sym_evaluate_dp(np, cp, dp_scr, &dp_ofs);
3856         if (dp_sg < 0)
3857                 goto out_reject;
3858
3859         /*
3860          *  And our alchemy:) allows to easily calculate the data 
3861          *  script address we want to return for the next data phase.
3862          */
3863         dp_ret = cpu_to_scr(sym_goalp(cp));
3864         dp_ret = dp_ret - 8 - (SYM_CONF_MAX_SG - dp_sg) * (2*4);
3865
3866         /*
3867          *  If offset / scatter entry is zero we donnot need 
3868          *  a context for the new current data pointer.
3869          */
3870         if (dp_ofs == 0) {
3871                 dp_scr = dp_ret;
3872                 goto out_ok;
3873         }
3874
3875         /*
3876          *  Get a context for the new current data pointer.
3877          */
3878         hflags = INB (HF_PRT);
3879
3880         if (hflags & HF_DP_SAVED)
3881                 hflags ^= HF_ACT_PM;
3882
3883         if (!(hflags & HF_ACT_PM)) {
3884                 pm  = &cp->phys.pm0;
3885                 dp_scr = SCRIPTA_BA (np, pm0_data);
3886         }
3887         else {
3888                 pm = &cp->phys.pm1;
3889                 dp_scr = SCRIPTA_BA (np, pm1_data);
3890         }
3891
3892         hflags &= ~(HF_DP_SAVED);
3893
3894         OUTB (HF_PRT, hflags);
3895
3896         /*
3897          *  Set up the new current data pointer.
3898          *  ofs < 0 there, and for the next data phase, we 
3899          *  want to transfer part of the data of the sg entry 
3900          *  corresponding to index dp_sg-1 prior to returning 
3901          *  to the main data script.
3902          */
3903         pm->ret = cpu_to_scr(dp_ret);
3904         tmp  = scr_to_cpu(cp->phys.data[dp_sg-1].addr);
3905         tmp += scr_to_cpu(cp->phys.data[dp_sg-1].size) + dp_ofs;
3906         pm->sg.addr = cpu_to_scr(tmp);
3907         pm->sg.size = cpu_to_scr(-dp_ofs);
3908
3909 out_ok:
3910         sym_set_script_dp (np, cp, dp_scr);
3911         OUTL_DSP (SCRIPTA_BA (np, clrack));
3912         return;
3913
3914 out_reject:
3915         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
3916 }
3917
3918
3919 /*
3920  *  chip calculation of the data residual.
3921  *
3922  *  As I used to say, the requirement of data residual 
3923  *  in SCSI is broken, useless and cannot be achieved 
3924  *  without huge complexity.
3925  *  But most OSes and even the official CAM require it.
3926  *  When stupidity happens to be so widely spread inside 
3927  *  a community, it gets hard to convince.
3928  *
3929  *  Anyway, I don't care, since I am not going to use 
3930  *  any software that considers this data residual as 
3931  *  a relevant information. :)
3932  */
3933
3934 int sym_compute_residual(hcb_p np, ccb_p cp)
3935 {
3936         int dp_sg, dp_sgmin, resid = 0;
3937         int dp_ofs = 0;
3938
3939         /*
3940          *  Check for some data lost or just thrown away.
3941          *  We are not required to be quite accurate in this 
3942          *  situation. Btw, if we are odd for output and the 
3943          *  device claims some more data, it may well happen 
3944          *  than our residual be zero. :-)
3945          */
3946         if (cp->xerr_status & (XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN)) {
3947                 if (cp->xerr_status & XE_EXTRA_DATA)
3948                         resid -= cp->extra_bytes;
3949                 if (cp->xerr_status & XE_SODL_UNRUN)
3950                         ++resid;
3951                 if (cp->xerr_status & XE_SWIDE_OVRUN)
3952                         --resid;
3953         }
3954
3955         /*
3956          *  If all data has been transferred,
3957          *  there is no residual.
3958          */
3959         if (cp->phys.head.lastp == sym_goalp(cp))
3960                 return resid;
3961
3962         /*
3963          *  If no data transfer occurs, or if the data
3964          *  pointer is weird, return full residual.
3965          */
3966         if (cp->startp == cp->phys.head.lastp ||
3967             sym_evaluate_dp(np, cp, scr_to_cpu(cp->phys.head.lastp),
3968                             &dp_ofs) < 0) {
3969                 return cp->data_len;
3970         }
3971
3972         /*
3973          *  If we were auto-sensing, then we are done.
3974          */
3975         if (cp->host_flags & HF_SENSE) {
3976                 return -dp_ofs;
3977         }
3978
3979         /*
3980          *  We are now full comfortable in the computation 
3981          *  of the data residual (2's complement).
3982          */
3983         dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
3984         resid = -cp->ext_ofs;
3985         for (dp_sg = cp->ext_sg; dp_sg < SYM_CONF_MAX_SG; ++dp_sg) {
3986                 u_int tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
3987                 resid += (tmp & 0xffffff);
3988         }
3989
3990         /*
3991          *  Hopefully, the result is not too wrong.
3992          */
3993         return resid;
3994 }
3995
3996 /*
3997  *  Negotiation for WIDE and SYNCHRONOUS DATA TRANSFER.
3998  *
3999  *  When we try to negotiate, we append the negotiation message
4000  *  to the identify and (maybe) simple tag message.
4001  *  The host status field is set to HS_NEGOTIATE to mark this
4002  *  situation.
4003  *
4004  *  If the target doesn't answer this message immediately
4005  *  (as required by the standard), the SIR_NEGO_FAILED interrupt
4006  *  will be raised eventually.
4007  *  The handler removes the HS_NEGOTIATE status, and sets the
4008  *  negotiated value to the default (async / nowide).
4009  *
4010  *  If we receive a matching answer immediately, we check it
4011  *  for validity, and set the values.
4012  *
4013  *  If we receive a Reject message immediately, we assume the
4014  *  negotiation has failed, and fall back to standard values.
4015  *
4016  *  If we receive a negotiation message while not in HS_NEGOTIATE
4017  *  state, it's a target initiated negotiation. We prepare a
4018  *  (hopefully) valid answer, set our parameters, and send back 
4019  *  this answer to the target.
4020  *
4021  *  If the target doesn't fetch the answer (no message out phase),
4022  *  we assume the negotiation has failed, and fall back to default
4023  *  settings (SIR_NEGO_PROTO interrupt).
4024  *
4025  *  When we set the values, we adjust them in all ccbs belonging 
4026  *  to this target, in the controller's register, and in the "phys"
4027  *  field of the controller's struct sym_hcb.
4028  */
4029
4030 /*
4031  *  chip handler for SYNCHRONOUS DATA TRANSFER REQUEST (SDTR) message.
4032  */
4033 static int  
4034 sym_sync_nego_check(hcb_p np, int req, int target)
4035 {
4036         u_char  chg, ofs, per, fak, div;
4037
4038         if (DEBUG_FLAGS & DEBUG_NEGO) {
4039                 sym_print_nego_msg(np, target, "sync msgin", np->msgin);
4040         };
4041
4042         /*
4043          *  Get requested values.
4044          */
4045         chg = 0;
4046         per = np->msgin[3];
4047         ofs = np->msgin[4];
4048
4049         /*
4050          *  Check values against our limits.
4051          */
4052         if (ofs) {
4053                 if (ofs > np->maxoffs)
4054                         {chg = 1; ofs = np->maxoffs;}
4055         }
4056
4057         if (ofs) {
4058                 if (per < np->minsync)
4059                         {chg = 1; per = np->minsync;}
4060         }
4061
4062         /*
4063          *  Get new chip synchronous parameters value.
4064          */
4065         div = fak = 0;
4066         if (ofs && sym_getsync(np, 0, per, &div, &fak) < 0)
4067                 goto reject_it;
4068
4069         if (DEBUG_FLAGS & DEBUG_NEGO) {
4070                 PRINT_TARGET(np, target);
4071                 printf ("sdtr: ofs=%d per=%d div=%d fak=%d chg=%d.\n",
4072                         ofs, per, div, fak, chg);
4073         }
4074
4075         /*
4076          *  If it was an answer we want to change, 
4077          *  then it isn't acceptable. Reject it.
4078          */
4079         if (!req && chg)
4080                 goto reject_it;
4081
4082         /*
4083          *  Apply new values.
4084          */
4085         sym_setsync (np, target, ofs, per, div, fak);
4086
4087         /*
4088          *  It was an answer. We are done.
4089          */
4090         if (!req)
4091                 return 0;
4092
4093         /*
4094          *  It was a request. Prepare an answer message.
4095          */
4096         np->msgout[0] = M_EXTENDED;
4097         np->msgout[1] = 3;
4098         np->msgout[2] = M_X_SYNC_REQ;
4099         np->msgout[3] = per;
4100         np->msgout[4] = ofs;
4101
4102         if (DEBUG_FLAGS & DEBUG_NEGO) {
4103                 sym_print_nego_msg(np, target, "sync msgout", np->msgout);
4104         }
4105
4106         np->msgin [0] = M_NOOP;
4107
4108         return 0;
4109
4110 reject_it:
4111         sym_setsync (np, target, 0, 0, 0, 0);
4112         return -1;
4113 }
4114
4115 static void sym_sync_nego(hcb_p np, tcb_p tp, ccb_p cp)
4116 {
4117         int req = 1;
4118         int result;
4119
4120         /*
4121          *  Request or answer ?
4122          */
4123         if (INB (HS_PRT) == HS_NEGOTIATE) {
4124                 OUTB (HS_PRT, HS_BUSY);
4125                 if (cp->nego_status && cp->nego_status != NS_SYNC)
4126                         goto reject_it;
4127                 req = 0;
4128         }
4129
4130         /*
4131          *  Check and apply new values.
4132          */
4133         result = sym_sync_nego_check(np, req, cp->target);
4134         if (result)     /* Not acceptable, reject it */
4135                 goto reject_it;
4136         if (req) {      /* Was a request, send response. */
4137                 cp->nego_status = NS_SYNC;
4138                 OUTL_DSP (SCRIPTB_BA (np, sdtr_resp));
4139         }
4140         else            /* Was a response, we are done. */
4141                 OUTL_DSP (SCRIPTA_BA (np, clrack));
4142         return;
4143
4144 reject_it:
4145         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
4146 }
4147
4148 /*
4149  *  chip handler for PARALLEL PROTOCOL REQUEST (PPR) message.
4150  */
4151 static int 
4152 sym_ppr_nego_check(hcb_p np, int req, int target)
4153 {
4154         tcb_p tp = &np->target[target];
4155         u_char  chg, ofs, per, fak, dt, div, wide;
4156
4157         if (DEBUG_FLAGS & DEBUG_NEGO) {
4158                 sym_print_nego_msg(np, target, "ppr msgin", np->msgin);
4159         };
4160
4161         /*
4162          *  Get requested values.
4163          */
4164         chg  = 0;
4165         per  = np->msgin[3];
4166         ofs  = np->msgin[5];
4167         wide = np->msgin[6];
4168         dt   = np->msgin[7] & PPR_OPT_DT;
4169
4170         /*
4171          *  Check values against our limits.
4172          */
4173         if (wide > np->maxwide) {
4174                 chg = 1;
4175                 wide = np->maxwide;
4176         }
4177         if (!wide || !(np->features & FE_ULTRA3))
4178                 dt &= ~PPR_OPT_DT;
4179
4180         if (!(np->features & FE_U3EN))  /* Broken U3EN bit not supported */
4181                 dt &= ~PPR_OPT_DT;
4182
4183         if (dt != (np->msgin[7] & PPR_OPT_MASK)) chg = 1;
4184
4185         if (ofs) {
4186                 if (dt) {
4187                         if (ofs > np->maxoffs_dt)
4188                                 {chg = 1; ofs = np->maxoffs_dt;}
4189                 }
4190                 else if (ofs > np->maxoffs)
4191                         {chg = 1; ofs = np->maxoffs;}
4192         }
4193
4194         if (ofs) {
4195                 if (dt) {
4196                         if (per < np->minsync_dt)
4197                                 {chg = 1; per = np->minsync_dt;}
4198                 }
4199                 else if (per < np->minsync)
4200                         {chg = 1; per = np->minsync;}
4201         }
4202
4203         /*
4204          *  Get new chip synchronous parameters value.
4205          */
4206         div = fak = 0;
4207         if (ofs && sym_getsync(np, dt, per, &div, &fak) < 0)
4208                 goto reject_it;
4209
4210         /*
4211          *  If it was an answer we want to change, 
4212          *  then it isn't acceptable. Reject it.
4213          */
4214         if (!req && chg)
4215                 goto reject_it;
4216
4217         /*
4218          *  Apply new values.
4219          */
4220         sym_setpprot (np, target, dt, ofs, per, wide, div, fak);
4221
4222         /*
4223          *  It was an answer. We are done.
4224          */
4225         if (!req)
4226                 return 0;
4227
4228         /*
4229          *  It was a request. Prepare an answer message.
4230          */
4231         np->msgout[0] = M_EXTENDED;
4232         np->msgout[1] = 6;
4233         np->msgout[2] = M_X_PPR_REQ;
4234         np->msgout[3] = per;
4235         np->msgout[4] = 0;
4236         np->msgout[5] = ofs;
4237         np->msgout[6] = wide;
4238         np->msgout[7] = dt;
4239
4240         if (DEBUG_FLAGS & DEBUG_NEGO) {
4241                 sym_print_nego_msg(np, target, "ppr msgout", np->msgout);
4242         }
4243
4244         np->msgin [0] = M_NOOP;
4245
4246         return 0;
4247
4248 reject_it:
4249         sym_setpprot (np, target, 0, 0, 0, 0, 0, 0);
4250         /*
4251          *  If it is a device response that should result in  
4252          *  ST, we may want to try a legacy negotiation later.
4253          */
4254         if (!req && !dt) {
4255                 tp->tinfo.goal.options = 0;
4256                 tp->tinfo.goal.width   = wide;
4257                 tp->tinfo.goal.period  = per;
4258                 tp->tinfo.goal.offset  = ofs;
4259         }
4260         return -1;
4261 }
4262
4263 static void sym_ppr_nego(hcb_p np, tcb_p tp, ccb_p cp)
4264 {
4265         int req = 1;
4266         int result;
4267
4268         /*
4269          *  Request or answer ?
4270          */
4271         if (INB (HS_PRT) == HS_NEGOTIATE) {
4272                 OUTB (HS_PRT, HS_BUSY);
4273                 if (cp->nego_status && cp->nego_status != NS_PPR)
4274                         goto reject_it;
4275                 req = 0;
4276         }
4277
4278         /*
4279          *  Check and apply new values.
4280          */
4281         result = sym_ppr_nego_check(np, req, cp->target);
4282         if (result)     /* Not acceptable, reject it */
4283                 goto reject_it;
4284         if (req) {      /* Was a request, send response. */
4285                 cp->nego_status = NS_PPR;
4286                 OUTL_DSP (SCRIPTB_BA (np, ppr_resp));
4287         }
4288         else            /* Was a response, we are done. */
4289                 OUTL_DSP (SCRIPTA_BA (np, clrack));
4290         return;
4291
4292 reject_it:
4293         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
4294 }
4295
4296 /*
4297  *  chip handler for WIDE DATA TRANSFER REQUEST (WDTR) message.
4298  */
4299 static int  
4300 sym_wide_nego_check(hcb_p np, int req, int target)
4301 {
4302         u_char  chg, wide;
4303
4304         if (DEBUG_FLAGS & DEBUG_NEGO) {
4305                 sym_print_nego_msg(np, target, "wide msgin", np->msgin);
4306         };
4307
4308         /*
4309          *  Get requested values.
4310          */
4311         chg  = 0;
4312         wide = np->msgin[3];
4313
4314         /*
4315          *  Check values against our limits.
4316          */
4317         if (wide > np->maxwide) {
4318                 chg = 1;
4319                 wide = np->maxwide;
4320         }
4321
4322         if (DEBUG_FLAGS & DEBUG_NEGO) {
4323                 PRINT_TARGET(np, target);
4324                 printf ("wdtr: wide=%d chg=%d.\n", wide, chg);
4325         }
4326
4327         /*
4328          *  If it was an answer we want to change, 
4329          *  then it isn't acceptable. Reject it.
4330          */
4331         if (!req && chg)
4332                 goto reject_it;
4333
4334         /*
4335          *  Apply new values.
4336          */
4337         sym_setwide (np, target, wide);
4338
4339         /*
4340          *  It was an answer. We are done.
4341          */
4342         if (!req)
4343                 return 0;
4344
4345         /*
4346          *  It was a request. Prepare an answer message.
4347          */
4348         np->msgout[0] = M_EXTENDED;
4349         np->msgout[1] = 2;
4350         np->msgout[2] = M_X_WIDE_REQ;
4351         np->msgout[3] = wide;
4352
4353         np->msgin [0] = M_NOOP;
4354
4355         if (DEBUG_FLAGS & DEBUG_NEGO) {
4356                 sym_print_nego_msg(np, target, "wide msgout", np->msgout);
4357         }
4358
4359         return 0;
4360
4361 reject_it:
4362         return -1;
4363 }
4364
4365 static void sym_wide_nego(hcb_p np, tcb_p tp, ccb_p cp)
4366 {
4367         int req = 1;
4368         int result;
4369
4370         /*
4371          *  Request or answer ?
4372          */
4373         if (INB (HS_PRT) == HS_NEGOTIATE) {
4374                 OUTB (HS_PRT, HS_BUSY);
4375                 if (cp->nego_status && cp->nego_status != NS_WIDE)
4376                         goto reject_it;
4377                 req = 0;
4378         }
4379
4380         /*
4381          *  Check and apply new values.
4382          */
4383         result = sym_wide_nego_check(np, req, cp->target);
4384         if (result)     /* Not acceptable, reject it */
4385                 goto reject_it;
4386         if (req) {      /* Was a request, send response. */
4387                 cp->nego_status = NS_WIDE;
4388                 OUTL_DSP (SCRIPTB_BA (np, wdtr_resp));
4389         }
4390         else {          /* Was a response. */
4391                 /*
4392                  * Negotiate for SYNC immediately after WIDE response.
4393                  * This allows to negotiate for both WIDE and SYNC on 
4394                  * a single SCSI command (Suggested by Justin Gibbs).
4395                  */
4396                 if (tp->tinfo.goal.offset) {
4397                         np->msgout[0] = M_EXTENDED;
4398                         np->msgout[1] = 3;
4399                         np->msgout[2] = M_X_SYNC_REQ;
4400                         np->msgout[3] = tp->tinfo.goal.period;
4401                         np->msgout[4] = tp->tinfo.goal.offset;
4402
4403                         if (DEBUG_FLAGS & DEBUG_NEGO) {
4404                                 sym_print_nego_msg(np, cp->target,
4405                                                    "sync msgout", np->msgout);
4406                         }
4407
4408                         cp->nego_status = NS_SYNC;
4409                         OUTB (HS_PRT, HS_NEGOTIATE);
4410                         OUTL_DSP (SCRIPTB_BA (np, sdtr_resp));
4411                         return;
4412                 }
4413                 else
4414                         OUTL_DSP (SCRIPTA_BA (np, clrack));
4415         };
4416
4417         return;
4418
4419 reject_it:
4420         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
4421 }
4422
4423 /*
4424  *  Reset DT, SYNC or WIDE to default settings.
4425  *
4426  *  Called when a negotiation does not succeed either 
4427  *  on rejection or on protocol error.
4428  *
4429  *  A target that understands a PPR message should never 
4430  *  reject it, and messing with it is very unlikely.
4431  *  So, if a PPR makes problems, we may just want to 
4432  *  try a legacy negotiation later.
4433  */
4434 static void sym_nego_default(hcb_p np, tcb_p tp, ccb_p cp)
4435 {
4436         switch (cp->nego_status) {
4437         case NS_PPR:
4438 #if 0
4439                 sym_setpprot (np, cp->target, 0, 0, 0, 0, 0, 0);
4440 #else
4441                 tp->tinfo.goal.options = 0;
4442                 if (tp->tinfo.goal.period < np->minsync)
4443                         tp->tinfo.goal.period = np->minsync;
4444                 if (tp->tinfo.goal.offset > np->maxoffs)
4445                         tp->tinfo.goal.offset = np->maxoffs;
4446 #endif
4447                 break;
4448         case NS_SYNC:
4449                 sym_setsync (np, cp->target, 0, 0, 0, 0);
4450                 break;
4451         case NS_WIDE:
4452                 sym_setwide (np, cp->target, 0);
4453                 break;
4454         };
4455         np->msgin [0] = M_NOOP;
4456         np->msgout[0] = M_NOOP;
4457         cp->nego_status = 0;
4458 }
4459
4460 /*
4461  *  chip handler for MESSAGE REJECT received in response to 
4462  *  PPR, WIDE or SYNCHRONOUS negotiation.
4463  */
4464 static void sym_nego_rejected(hcb_p np, tcb_p tp, ccb_p cp)
4465 {
4466         sym_nego_default(np, tp, cp);
4467         OUTB (HS_PRT, HS_BUSY);
4468 }
4469
4470 /*
4471  *  chip exception handler for programmed interrupts.
4472  */
4473 static void sym_int_sir (hcb_p np)
4474 {
4475         u_char  num     = INB (nc_dsps);
4476         u32     dsa     = INL (nc_dsa);
4477         ccb_p   cp      = sym_ccb_from_dsa(np, dsa);
4478         u_char  target  = INB (nc_sdid) & 0x0f;
4479         tcb_p   tp      = &np->target[target];
4480         int     tmp;
4481
4482         if (DEBUG_FLAGS & DEBUG_TINY) printf ("I#%d", num);
4483
4484         switch (num) {
4485 #if   SYM_CONF_DMA_ADDRESSING_MODE == 2
4486         /*
4487          *  SCRIPTS tell us that we may have to update 
4488          *  64 bit DMA segment registers.
4489          */
4490         case SIR_DMAP_DIRTY:
4491                 sym_update_dmap_regs(np);
4492                 goto out;
4493 #endif
4494         /*
4495          *  Command has been completed with error condition 
4496          *  or has been auto-sensed.
4497          */
4498         case SIR_COMPLETE_ERROR:
4499                 sym_complete_error(np, cp);
4500                 return;
4501         /*
4502          *  The C code is currently trying to recover from something.
4503          *  Typically, user want to abort some command.
4504          */
4505         case SIR_SCRIPT_STOPPED:
4506         case SIR_TARGET_SELECTED:
4507         case SIR_ABORT_SENT:
4508                 sym_sir_task_recovery(np, num);
4509                 return;
4510         /*
4511          *  The device didn't go to MSG OUT phase after having 
4512          *  been selected with ATN. We donnot want to handle 
4513          *  that.
4514          */
4515         case SIR_SEL_ATN_NO_MSG_OUT:
4516                 printf ("%s:%d: No MSG OUT phase after selection with ATN.\n",
4517                         sym_name (np), target);
4518                 goto out_stuck;
4519         /*
4520          *  The device didn't switch to MSG IN phase after 
4521          *  having reseleted the initiator.
4522          */
4523         case SIR_RESEL_NO_MSG_IN:
4524                 printf ("%s:%d: No MSG IN phase after reselection.\n",
4525                         sym_name (np), target);
4526                 goto out_stuck;
4527         /*
4528          *  After reselection, the device sent a message that wasn't 
4529          *  an IDENTIFY.
4530          */
4531         case SIR_RESEL_NO_IDENTIFY:
4532                 printf ("%s:%d: No IDENTIFY after reselection.\n",
4533                         sym_name (np), target);
4534                 goto out_stuck;
4535         /*
4536          *  The device reselected a LUN we donnot know about.
4537          */
4538         case SIR_RESEL_BAD_LUN:
4539                 np->msgout[0] = M_RESET;
4540                 goto out;
4541         /*
4542          *  The device reselected for an untagged nexus and we 
4543          *  haven't any.
4544          */
4545         case SIR_RESEL_BAD_I_T_L:
4546                 np->msgout[0] = M_ABORT;
4547                 goto out;
4548         /*
4549          *  The device reselected for a tagged nexus that we donnot 
4550          *  have.
4551          */
4552         case SIR_RESEL_BAD_I_T_L_Q:
4553                 np->msgout[0] = M_ABORT_TAG;
4554                 goto out;
4555         /*
4556          *  The SCRIPTS let us know that the device has grabbed 
4557          *  our message and will abort the job.
4558          */
4559         case SIR_RESEL_ABORTED:
4560                 np->lastmsg = np->msgout[0];
4561                 np->msgout[0] = M_NOOP;
4562                 printf ("%s:%d: message %x sent on bad reselection.\n",
4563                         sym_name (np), target, np->lastmsg);
4564                 goto out;
4565         /*
4566          *  The SCRIPTS let us know that a message has been 
4567          *  successfully sent to the device.
4568          */
4569         case SIR_MSG_OUT_DONE:
4570                 np->lastmsg = np->msgout[0];
4571                 np->msgout[0] = M_NOOP;
4572                 /* Should we really care of that */
4573                 if (np->lastmsg == M_PARITY || np->lastmsg == M_ID_ERROR) {
4574                         if (cp) {
4575                                 cp->xerr_status &= ~XE_PARITY_ERR;
4576                                 if (!cp->xerr_status)
4577                                         OUTOFFB (HF_PRT, HF_EXT_ERR);
4578                         }
4579                 }
4580                 goto out;
4581         /*
4582          *  The device didn't send a GOOD SCSI status.
4583          *  We may have some work to do prior to allow 
4584          *  the SCRIPTS processor to continue.
4585          */
4586         case SIR_BAD_SCSI_STATUS:
4587                 if (!cp)
4588                         goto out;
4589                 sym_sir_bad_scsi_status(np, num, cp);
4590                 return;
4591         /*
4592          *  We are asked by the SCRIPTS to prepare a 
4593          *  REJECT message.
4594          */
4595         case SIR_REJECT_TO_SEND:
4596                 sym_print_msg(cp, "M_REJECT to send for ", np->msgin);
4597                 np->msgout[0] = M_REJECT;
4598                 goto out;
4599         /*
4600          *  We have been ODD at the end of a DATA IN 
4601          *  transfer and the device didn't send a 
4602          *  IGNORE WIDE RESIDUE message.
4603          *  It is a data overrun condition.
4604          */
4605         case SIR_SWIDE_OVERRUN:
4606                 if (cp) {
4607                         OUTONB (HF_PRT, HF_EXT_ERR);
4608                         cp->xerr_status |= XE_SWIDE_OVRUN;
4609                 }
4610                 goto out;
4611         /*
4612          *  We have been ODD at the end of a DATA OUT 
4613          *  transfer.
4614          *  It is a data underrun condition.
4615          */
4616         case SIR_SODL_UNDERRUN:
4617                 if (cp) {
4618                         OUTONB (HF_PRT, HF_EXT_ERR);
4619                         cp->xerr_status |= XE_SODL_UNRUN;
4620                 }
4621                 goto out;
4622         /*
4623          *  The device wants us to tranfer more data than 
4624          *  expected or in the wrong direction.
4625          *  The number of extra bytes is in scratcha.
4626          *  It is a data overrun condition.
4627          */
4628         case SIR_DATA_OVERRUN:
4629                 if (cp) {
4630                         OUTONB (HF_PRT, HF_EXT_ERR);
4631                         cp->xerr_status |= XE_EXTRA_DATA;
4632                         cp->extra_bytes += INL (nc_scratcha);
4633                 }
4634                 goto out;
4635         /*
4636          *  The device switched to an illegal phase (4/5).
4637          */
4638         case SIR_BAD_PHASE:
4639                 if (cp) {
4640                         OUTONB (HF_PRT, HF_EXT_ERR);
4641                         cp->xerr_status |= XE_BAD_PHASE;
4642                 }
4643                 goto out;
4644         /*
4645          *  We received a message.
4646          */
4647         case SIR_MSG_RECEIVED:
4648                 if (!cp)
4649                         goto out_stuck;
4650                 switch (np->msgin [0]) {
4651                 /*
4652                  *  We received an extended message.
4653                  *  We handle MODIFY DATA POINTER, SDTR, WDTR 
4654                  *  and reject all other extended messages.
4655                  */
4656                 case M_EXTENDED:
4657                         switch (np->msgin [2]) {
4658                         case M_X_MODIFY_DP:
4659                                 if (DEBUG_FLAGS & DEBUG_POINTER)
4660                                         sym_print_msg(cp,"modify DP",np->msgin);
4661                                 tmp = (np->msgin[3]<<24) + (np->msgin[4]<<16) + 
4662                                       (np->msgin[5]<<8)  + (np->msgin[6]);
4663                                 sym_modify_dp(np, tp, cp, tmp);
4664                                 return;
4665                         case M_X_SYNC_REQ:
4666                                 sym_sync_nego(np, tp, cp);
4667                                 return;
4668                         case M_X_PPR_REQ:
4669                                 sym_ppr_nego(np, tp, cp);
4670                                 return;
4671                         case M_X_WIDE_REQ:
4672                                 sym_wide_nego(np, tp, cp);
4673                                 return;
4674                         default:
4675                                 goto out_reject;
4676                         }
4677                         break;
4678                 /*
4679                  *  We received a 1/2 byte message not handled from SCRIPTS.
4680                  *  We are only expecting MESSAGE REJECT and IGNORE WIDE 
4681                  *  RESIDUE messages that haven't been anticipated by 
4682                  *  SCRIPTS on SWIDE full condition. Unanticipated IGNORE 
4683                  *  WIDE RESIDUE messages are aliased as MODIFY DP (-1).
4684                  */
4685                 case M_IGN_RESIDUE:
4686                         if (DEBUG_FLAGS & DEBUG_POINTER)
4687                                 sym_print_msg(cp,"ign wide residue", np->msgin);
4688                         if (cp->host_flags & HF_SENSE)
4689                                 OUTL_DSP (SCRIPTA_BA (np, clrack));
4690                         else
4691                                 sym_modify_dp(np, tp, cp, -1);
4692                         return;
4693                 case M_REJECT:
4694                         if (INB (HS_PRT) == HS_NEGOTIATE)
4695                                 sym_nego_rejected(np, tp, cp);
4696                         else {
4697                                 PRINT_ADDR(cp);
4698                                 printf ("M_REJECT received (%x:%x).\n",
4699                                         scr_to_cpu(np->lastmsg), np->msgout[0]);
4700                         }
4701                         goto out_clrack;
4702                         break;
4703                 default:
4704                         goto out_reject;
4705                 }
4706                 break;
4707         /*
4708          *  We received an unknown message.
4709          *  Ignore all MSG IN phases and reject it.
4710          */
4711         case SIR_MSG_WEIRD:
4712                 sym_print_msg(cp, "WEIRD message received", np->msgin);
4713                 OUTL_DSP (SCRIPTB_BA (np, msg_weird));
4714                 return;
4715         /*
4716          *  Negotiation failed.
4717          *  Target does not send us the reply.
4718          *  Remove the HS_NEGOTIATE status.
4719          */
4720         case SIR_NEGO_FAILED:
4721                 OUTB (HS_PRT, HS_BUSY);
4722         /*
4723          *  Negotiation failed.
4724          *  Target does not want answer message.
4725          */
4726         case SIR_NEGO_PROTO:
4727                 sym_nego_default(np, tp, cp);
4728                 goto out;
4729         };
4730
4731 out:
4732         OUTONB_STD ();
4733         return;
4734 out_reject:
4735         OUTL_DSP (SCRIPTB_BA (np, msg_bad));
4736         return;
4737 out_clrack:
4738         OUTL_DSP (SCRIPTA_BA (np, clrack));
4739         return;
4740 out_stuck:
4741         return;
4742 }
4743
4744 /*
4745  *  Acquire a control block
4746  */
4747 ccb_p sym_get_ccb (hcb_p np, u_char tn, u_char ln, u_char tag_order)
4748 {
4749         tcb_p tp = &np->target[tn];
4750         lcb_p lp = sym_lp(np, tp, ln);
4751         u_short tag = NO_TAG;
4752         SYM_QUEHEAD *qp;
4753         ccb_p cp = (ccb_p) 0;
4754
4755         /*
4756          *  Look for a free CCB
4757          */
4758         if (sym_que_empty(&np->free_ccbq))
4759                 (void) sym_alloc_ccb(np);
4760         qp = sym_remque_head(&np->free_ccbq);
4761         if (!qp)
4762                 goto out;
4763         cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
4764
4765 #ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
4766         /*
4767          *  If the LCB is not yet available and the LUN
4768          *  has been probed ok, try to allocate the LCB.
4769          */
4770         if (!lp && sym_is_bit(tp->lun_map, ln)) {
4771                 lp = sym_alloc_lcb(np, tn, ln);
4772                 if (!lp)
4773                         goto out_free;
4774         }
4775 #endif
4776
4777         /*
4778          *  If the LCB is not available here, then the 
4779          *  logical unit is not yet discovered. For those 
4780          *  ones only accept 1 SCSI IO per logical unit, 
4781          *  since we cannot allow disconnections.
4782          */
4783         if (!lp) {
4784                 if (!sym_is_bit(tp->busy0_map, ln))
4785                         sym_set_bit(tp->busy0_map, ln);
4786                 else
4787                         goto out_free;
4788         } else {
4789                 /*
4790                  *  If we have been asked for a tagged command.
4791                  */
4792                 if (tag_order) {
4793                         /*
4794                          *  Debugging purpose.
4795                          */
4796 #ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
4797                         assert(lp->busy_itl == 0);
4798 #endif
4799                         /*
4800                          *  Allocate resources for tags if not yet.
4801                          */
4802                         if (!lp->cb_tags) {
4803                                 sym_alloc_lcb_tags(np, tn, ln);
4804                                 if (!lp->cb_tags)
4805                                         goto out_free;
4806                         }
4807                         /*
4808                          *  Get a tag for this SCSI IO and set up
4809                          *  the CCB bus address for reselection, 
4810                          *  and count it for this LUN.
4811                          *  Toggle reselect path to tagged.
4812                          */
4813                         if (lp->busy_itlq < SYM_CONF_MAX_TASK) {
4814                                 tag = lp->cb_tags[lp->ia_tag];
4815                                 if (++lp->ia_tag == SYM_CONF_MAX_TASK)
4816                                         lp->ia_tag = 0;
4817                                 ++lp->busy_itlq;
4818 #ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
4819                                 lp->itlq_tbl[tag] = cpu_to_scr(cp->ccb_ba);
4820                                 lp->head.resel_sa =
4821                                         cpu_to_scr(SCRIPTA_BA (np, resel_tag));
4822 #endif
4823 #ifdef SYM_OPT_LIMIT_COMMAND_REORDERING
4824                                 cp->tags_si = lp->tags_si;
4825                                 ++lp->tags_sum[cp->tags_si];
4826                                 ++lp->tags_since;
4827 #endif
4828                         }
4829                         else
4830                                 goto out_free;
4831                 }
4832                 /*
4833                  *  This command will not be tagged.
4834                  *  If we already have either a tagged or untagged 
4835                  *  one, refuse to overlap this untagged one.
4836                  */
4837                 else {
4838                         /*
4839                          *  Debugging purpose.
4840                          */
4841 #ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
4842                         assert(lp->busy_itl == 0 && lp->busy_itlq == 0);
4843 #endif
4844                         /*
4845                          *  Count this nexus for this LUN.
4846                          *  Set up the CCB bus address for reselection.
4847                          *  Toggle reselect path to untagged.
4848                          */
4849                         ++lp->busy_itl;
4850 #ifndef SYM_OPT_HANDLE_DEVICE_QUEUEING
4851                         if (lp->busy_itl == 1) {
4852                                 lp->head.itl_task_sa = cpu_to_scr(cp->ccb_ba);
4853                                 lp->head.resel_sa =
4854                                       cpu_to_scr(SCRIPTA_BA (np, resel_no_tag));
4855                         }
4856                         else
4857                                 goto out_free;
4858 #endif
4859                 }
4860         }
4861         /*
4862          *  Put the CCB into the busy queue.
4863          */
4864         sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
4865 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
4866         if (lp) {
4867                 sym_remque(&cp->link2_ccbq);
4868                 sym_insque_tail(&cp->link2_ccbq, &lp->waiting_ccbq);
4869         }
4870
4871 #endif
4872         /*
4873          *  Remember all informations needed to free this CCB.
4874          */
4875         cp->to_abort = 0;
4876         cp->tag    = tag;
4877         cp->order  = tag_order;
4878         cp->target = tn;
4879         cp->lun    = ln;
4880
4881         if (DEBUG_FLAGS & DEBUG_TAGS) {
4882                 PRINT_LUN(np, tn, ln);
4883                 printf ("ccb @%p using tag %d.\n", cp, tag);
4884         }
4885
4886 out:
4887         return cp;
4888 out_free:
4889         sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
4890         return (ccb_p) 0;
4891 }
4892
4893 /*
4894  *  Release one control block
4895  */
4896 void sym_free_ccb (hcb_p np, ccb_p cp)
4897 {
4898         tcb_p tp = &np->target[cp->target];
4899         lcb_p lp = sym_lp(np, tp, cp->lun);
4900
4901         if (DEBUG_FLAGS & DEBUG_TAGS) {
4902                 PRINT_LUN(np, cp->target, cp->lun);
4903                 printf ("ccb @%p freeing tag %d.\n", cp, cp->tag);
4904         }
4905
4906         /*
4907          *  If LCB available,
4908          */
4909         if (lp) {
4910                 /*
4911                  *  If tagged, release the tag, set the relect path 
4912                  */
4913                 if (cp->tag != NO_TAG) {
4914 #ifdef SYM_OPT_LIMIT_COMMAND_REORDERING
4915                         --lp->tags_sum[cp->tags_si];
4916 #endif
4917                         /*
4918                          *  Free the tag value.
4919                          */
4920                         lp->cb_tags[lp->if_tag] = cp->tag;
4921                         if (++lp->if_tag == SYM_CONF_MAX_TASK)
4922                                 lp->if_tag = 0;
4923                         /*
4924                          *  Make the reselect path invalid, 
4925                          *  and uncount this CCB.
4926                          */
4927                         lp->itlq_tbl[cp->tag] = cpu_to_scr(np->bad_itlq_ba);
4928                         --lp->busy_itlq;
4929                 } else {        /* Untagged */
4930                         /*
4931                          *  Make the reselect path invalid, 
4932                          *  and uncount this CCB.
4933                          */
4934                         lp->head.itl_task_sa = cpu_to_scr(np->bad_itl_ba);
4935                         --lp->busy_itl;
4936                 }
4937                 /*
4938                  *  If no JOB active, make the LUN reselect path invalid.
4939                  */
4940                 if (lp->busy_itlq == 0 && lp->busy_itl == 0)
4941                         lp->head.resel_sa =
4942                                 cpu_to_scr(SCRIPTB_BA (np, resel_bad_lun));
4943         }
4944         /*
4945          *  Otherwise, we only accept 1 IO per LUN.
4946          *  Clear the bit that keeps track of this IO.
4947          */
4948         else
4949                 sym_clr_bit(tp->busy0_map, cp->lun);
4950
4951         /*
4952          *  We donnot queue more than 1 ccb per target 
4953          *  with negotiation at any time. If this ccb was 
4954          *  used for negotiation, clear this info in the tcb.
4955          */
4956         if (cp == tp->nego_cp)
4957                 tp->nego_cp = NULL;
4958
4959 #ifdef SYM_CONF_IARB_SUPPORT
4960         /*
4961          *  If we just complete the last queued CCB,
4962          *  clear this info that is no longer relevant.
4963          */
4964         if (cp == np->last_cp)
4965                 np->last_cp = 0;
4966 #endif
4967
4968         /*
4969          *  Unmap user data from DMA map if needed.
4970          */
4971         sym_data_dmamap_unload(np, cp);
4972
4973         /*
4974          *  Make this CCB available.
4975          */
4976         cp->cam_ccb = NULL;
4977         cp->host_status = HS_IDLE;
4978         sym_remque(&cp->link_ccbq);
4979         sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
4980
4981 #ifdef  SYM_OPT_HANDLE_IO_TIMEOUT
4982         /*
4983          *  Cancel any pending timeout condition.
4984          */
4985         sym_untimeout_ccb(np, cp);
4986 #endif
4987
4988 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
4989         if (lp) {
4990                 sym_remque(&cp->link2_ccbq);
4991                 sym_insque_tail(&cp->link2_ccbq, &np->dummy_ccbq);
4992                 if (cp->started) {
4993                         if (cp->tag != NO_TAG)
4994                                 --lp->started_tags;
4995                         else
4996                                 --lp->started_no_tag;
4997                 }
4998         }
4999         cp->started = 0;
5000 #endif
5001 }
5002
5003 /*
5004  *  Allocate a CCB from memory and initialize its fixed part.
5005  */
5006 static ccb_p sym_alloc_ccb(hcb_p np)
5007 {
5008         ccb_p cp = NULL;
5009         int hcode;
5010
5011         /*
5012          *  Prevent from allocating more CCBs than we can 
5013          *  queue to the controller.
5014          */
5015         if (np->actccbs >= SYM_CONF_MAX_START)
5016                 return NULL;
5017
5018         /*
5019          *  Allocate memory for this CCB.
5020          */
5021         cp = sym_calloc_dma(sizeof(struct sym_ccb), "CCB");
5022         if (!cp)
5023                 goto out_free;
5024
5025         /*
5026          *  Allocate a bounce buffer for sense data.
5027          */
5028         cp->sns_bbuf = sym_calloc_dma(SYM_SNS_BBUF_LEN, "SNS_BBUF");
5029         if (!cp->sns_bbuf)
5030                 goto out_free;
5031
5032         /*
5033          *  Allocate a map for the DMA of user data.
5034          */
5035         if (sym_data_dmamap_create(np, cp))
5036                 goto out_free;
5037
5038         /*
5039          *  Count it.
5040          */
5041         np->actccbs++;
5042
5043         /*
5044          *  Compute the bus address of this ccb.
5045          */
5046         cp->ccb_ba = vtobus(cp);
5047
5048         /*
5049          *  Insert this ccb into the hashed list.
5050          */
5051         hcode = CCB_HASH_CODE(cp->ccb_ba);
5052         cp->link_ccbh = np->ccbh[hcode];
5053         np->ccbh[hcode] = cp;
5054
5055         /*
5056          *  Initialyze the start and restart actions.
5057          */
5058         cp->phys.head.go.start   = cpu_to_scr(SCRIPTA_BA (np, idle));
5059         cp->phys.head.go.restart = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
5060
5061         /*
5062          *  Initilialyze some other fields.
5063          */
5064         cp->phys.smsg_ext.addr = cpu_to_scr(HCB_BA(np, msgin[2]));
5065
5066         /*
5067          *  Chain into free ccb queue.
5068          */
5069         sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
5070
5071         /*
5072          *  Chain into optionnal lists.
5073          */
5074 #ifdef  SYM_OPT_HANDLE_IO_TIMEOUT
5075         sym_insque_head(&cp->tmo_linkq, &np->tmo0_ccbq);
5076 #endif
5077 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5078         sym_insque_head(&cp->link2_ccbq, &np->dummy_ccbq);
5079 #endif
5080         return cp;
5081 out_free:
5082         if (cp) {
5083                 if (cp->sns_bbuf)
5084                         sym_mfree_dma(cp->sns_bbuf,SYM_SNS_BBUF_LEN,"SNS_BBUF");
5085                 sym_mfree_dma(cp, sizeof(*cp), "CCB");
5086         }
5087         return NULL;
5088 }
5089
5090 /*
5091  *  Look up a CCB from a DSA value.
5092  */
5093 static ccb_p sym_ccb_from_dsa(hcb_p np, u32 dsa)
5094 {
5095         int hcode;
5096         ccb_p cp;
5097
5098         hcode = CCB_HASH_CODE(dsa);
5099         cp = np->ccbh[hcode];
5100         while (cp) {
5101                 if (cp->ccb_ba == dsa)
5102                         break;
5103                 cp = cp->link_ccbh;
5104         }
5105
5106         return cp;
5107 }
5108
5109 /*
5110  *  Target control block initialisation.
5111  *  Nothing important to do at the moment.
5112  */
5113 static void sym_init_tcb (hcb_p np, u_char tn)
5114 {
5115 #if 0   /*  Hmmm... this checking looks paranoid. */
5116         /*
5117          *  Check some alignments required by the chip.
5118          */     
5119         assert (((offsetof(struct sym_reg, nc_sxfer) ^
5120                 offsetof(struct sym_tcb, head.sval)) &3) == 0);
5121         assert (((offsetof(struct sym_reg, nc_scntl3) ^
5122                 offsetof(struct sym_tcb, head.wval)) &3) == 0);
5123 #endif
5124 }
5125
5126 /*
5127  *  Lun control block allocation and initialization.
5128  */
5129 lcb_p sym_alloc_lcb (hcb_p np, u_char tn, u_char ln)
5130 {
5131         tcb_p tp = &np->target[tn];
5132         lcb_p lp = sym_lp(np, tp, ln);
5133
5134         /*
5135          *  Already done, just return.
5136          */
5137         if (lp)
5138                 return lp;
5139
5140         /*
5141          *  Donnot allow LUN control block 
5142          *  allocation for not probed LUNs.
5143          */
5144         if (!sym_is_bit(tp->lun_map, ln))
5145                 return NULL;
5146
5147         /*
5148          *  Initialize the target control block if not yet.
5149          */
5150         sym_init_tcb (np, tn);
5151
5152         /*
5153          *  Allocate the LCB bus address array.
5154          *  Compute the bus address of this table.
5155          */
5156         if (ln && !tp->luntbl) {
5157                 int i;
5158
5159                 tp->luntbl = sym_calloc_dma(256, "LUNTBL");
5160                 if (!tp->luntbl)
5161                         goto fail;
5162                 for (i = 0 ; i < 64 ; i++)
5163                         tp->luntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
5164                 tp->head.luntbl_sa = cpu_to_scr(vtobus(tp->luntbl));
5165         }
5166
5167         /*
5168          *  Allocate the table of pointers for LUN(s) > 0, if needed.
5169          */
5170         if (ln && !tp->lunmp) {
5171                 tp->lunmp = sym_calloc(SYM_CONF_MAX_LUN * sizeof(lcb_p),
5172                                    "LUNMP");
5173                 if (!tp->lunmp)
5174                         goto fail;
5175         }
5176
5177         /*
5178          *  Allocate the lcb.
5179          *  Make it available to the chip.
5180          */
5181         lp = sym_calloc_dma(sizeof(struct sym_lcb), "LCB");
5182         if (!lp)
5183                 goto fail;
5184         if (ln) {
5185                 tp->lunmp[ln] = lp;
5186                 tp->luntbl[ln] = cpu_to_scr(vtobus(lp));
5187         }
5188         else {
5189                 tp->lun0p = lp;
5190                 tp->head.lun0_sa = cpu_to_scr(vtobus(lp));
5191         }
5192
5193         /*
5194          *  Let the itl task point to error handling.
5195          */
5196         lp->head.itl_task_sa = cpu_to_scr(np->bad_itl_ba);
5197
5198         /*
5199          *  Set the reselect pattern to our default. :)
5200          */
5201         lp->head.resel_sa = cpu_to_scr(SCRIPTB_BA (np, resel_bad_lun));
5202
5203         /*
5204          *  Set user capabilities.
5205          */
5206         lp->user_flags = tp->usrflags & (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
5207
5208 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5209         /*
5210          *  Initialize device queueing.
5211          */
5212         sym_que_init(&lp->waiting_ccbq);
5213         sym_que_init(&lp->started_ccbq);
5214         lp->started_max   = SYM_CONF_MAX_TASK;
5215         lp->started_limit = SYM_CONF_MAX_TASK;
5216 #endif
5217         /*
5218          *  If we are busy, count the IO.
5219          */
5220         if (sym_is_bit(tp->busy0_map, ln)) {
5221                 lp->busy_itl = 1;
5222                 sym_clr_bit(tp->busy0_map, ln);
5223         }
5224 fail:
5225         return lp;
5226 }
5227
5228 /*
5229  *  Allocate LCB resources for tagged command queuing.
5230  */
5231 static void sym_alloc_lcb_tags (hcb_p np, u_char tn, u_char ln)
5232 {
5233         tcb_p tp = &np->target[tn];
5234         lcb_p lp = sym_lp(np, tp, ln);
5235         int i;
5236
5237         /*
5238          *  If LCB not available, try to allocate it.
5239          */
5240         if (!lp && !(lp = sym_alloc_lcb(np, tn, ln)))
5241                 goto fail;
5242
5243         /*
5244          *  Allocate the task table and and the tag allocation 
5245          *  circular buffer. We want both or none.
5246          */
5247         lp->itlq_tbl = sym_calloc_dma(SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
5248         if (!lp->itlq_tbl)
5249                 goto fail;
5250         lp->cb_tags = sym_calloc(SYM_CONF_MAX_TASK, "CB_TAGS");
5251         if (!lp->cb_tags) {
5252                 sym_mfree_dma(lp->itlq_tbl, SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
5253                 lp->itlq_tbl = NULL;
5254                 goto fail;
5255         }
5256
5257         /*
5258          *  Initialize the task table with invalid entries.
5259          */
5260         for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
5261                 lp->itlq_tbl[i] = cpu_to_scr(np->notask_ba);
5262
5263         /*
5264          *  Fill up the tag buffer with tag numbers.
5265          */
5266         for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
5267                 lp->cb_tags[i] = i;
5268
5269         /*
5270          *  Make the task table available to SCRIPTS, 
5271          *  And accept tagged commands now.
5272          */
5273         lp->head.itlq_tbl_sa = cpu_to_scr(vtobus(lp->itlq_tbl));
5274
5275         return;
5276 fail:
5277         return;
5278 }
5279
5280 /*
5281  *  Queue a SCSI IO to the controller.
5282  */
5283 int sym_queue_scsiio(hcb_p np, cam_scsiio_p csio, ccb_p cp)
5284 {
5285         tcb_p   tp;
5286         lcb_p   lp;
5287         u_char  idmsg, *msgptr;
5288         u_int   msglen;
5289
5290         /*
5291          *  Keep track of the IO in our CCB.
5292          */
5293         cp->cam_ccb = (cam_ccb_p) csio;
5294
5295         /*
5296          *  Retreive the target descriptor.
5297          */
5298         tp = &np->target[cp->target];
5299
5300         /*
5301          *  Retreive the lun descriptor.
5302          */
5303         lp = sym_lp(np, tp, cp->lun);
5304
5305         /*
5306          *  Build the IDENTIFY message.
5307          */
5308         idmsg = M_IDENTIFY | cp->lun;
5309         if (cp->tag != NO_TAG || (lp && (lp->curr_flags & SYM_DISC_ENABLED)))
5310                 idmsg |= 0x40;
5311
5312         msgptr = cp->scsi_smsg;
5313         msglen = 0;
5314         msgptr[msglen++] = idmsg;
5315
5316         /*
5317          *  Build the tag message if present.
5318          */
5319         if (cp->tag != NO_TAG) {
5320                 u_char order = cp->order;
5321
5322                 switch(order) {
5323                 case M_ORDERED_TAG:
5324                         break;
5325                 case M_HEAD_TAG:
5326                         break;
5327                 default:
5328                         order = M_SIMPLE_TAG;
5329                 }
5330 #ifdef SYM_OPT_LIMIT_COMMAND_REORDERING
5331                 /*
5332                  *  Avoid too much reordering of SCSI commands.
5333                  *  The algorithm tries to prevent completion of any 
5334                  *  tagged command from being delayed against more 
5335                  *  than 3 times the max number of queued commands.
5336                  */
5337                 if (lp && lp->tags_since > 3*SYM_CONF_MAX_TAG) {
5338                         lp->tags_si = !(lp->tags_si);
5339                         if (lp->tags_sum[lp->tags_si]) {
5340                                 order = M_ORDERED_TAG;
5341                                 if ((DEBUG_FLAGS & DEBUG_TAGS)||sym_verbose>1) {
5342                                         PRINT_ADDR(cp);
5343                                         printf("ordered tag forced.\n");
5344                                 }
5345                         }
5346                         lp->tags_since = 0;
5347                 }
5348 #endif
5349                 msgptr[msglen++] = order;
5350
5351                 /*
5352                  *  For less than 128 tags, actual tags are numbered 
5353                  *  1,3,5,..2*MAXTAGS+1,since we may have to deal 
5354                  *  with devices that have problems with #TAG 0 or too 
5355                  *  great #TAG numbers. For more tags (up to 256), 
5356                  *  we use directly our tag number.
5357                  */
5358 #if SYM_CONF_MAX_TASK > (512/4)
5359                 msgptr[msglen++] = cp->tag;
5360 #else
5361                 msgptr[msglen++] = (cp->tag << 1) + 1;
5362 #endif
5363         }
5364
5365         /*
5366          *  Build a negotiation message if needed.
5367          *  (nego_status is filled by sym_prepare_nego())
5368          */
5369         cp->nego_status = 0;
5370         if (tp->tinfo.curr.width   != tp->tinfo.goal.width  ||
5371             tp->tinfo.curr.period  != tp->tinfo.goal.period ||
5372             tp->tinfo.curr.offset  != tp->tinfo.goal.offset ||
5373             tp->tinfo.curr.options != tp->tinfo.goal.options) {
5374                 if (!tp->nego_cp && lp)
5375                         msglen += sym_prepare_nego(np, cp, 0, msgptr + msglen);
5376         }
5377
5378         /*
5379          *  Startqueue
5380          */
5381         cp->phys.head.go.start   = cpu_to_scr(SCRIPTA_BA (np, select));
5382         cp->phys.head.go.restart = cpu_to_scr(SCRIPTA_BA (np, resel_dsa));
5383
5384         /*
5385          *  select
5386          */
5387         cp->phys.select.sel_id          = cp->target;
5388         cp->phys.select.sel_scntl3      = tp->head.wval;
5389         cp->phys.select.sel_sxfer       = tp->head.sval;
5390         cp->phys.select.sel_scntl4      = tp->head.uval;
5391
5392         /*
5393          *  message
5394          */
5395         cp->phys.smsg.addr      = cpu_to_scr(CCB_BA (cp, scsi_smsg));
5396         cp->phys.smsg.size      = cpu_to_scr(msglen);
5397
5398         /*
5399          *  status
5400          */
5401         cp->host_xflags         = 0;
5402         cp->host_status         = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
5403         cp->ssss_status         = S_ILLEGAL;
5404         cp->xerr_status         = 0;
5405         cp->host_flags          = 0;
5406         cp->extra_bytes         = 0;
5407
5408         /*
5409          *  extreme data pointer.
5410          *  shall be positive, so -1 is lower than lowest.:)
5411          */
5412         cp->ext_sg  = -1;
5413         cp->ext_ofs = 0;
5414
5415         /*
5416          *  Build the CDB and DATA descriptor block 
5417          *  and start the IO.
5418          */
5419         return sym_setup_data_and_start(np, csio, cp);
5420 }
5421
5422 /*
5423  *  Reset a SCSI target (all LUNs of this target).
5424  */
5425 int sym_reset_scsi_target(hcb_p np, int target)
5426 {
5427         tcb_p tp;
5428
5429         if (target == np->myaddr || (u_int)target >= SYM_CONF_MAX_TARGET)
5430                 return -1;
5431
5432         tp = &np->target[target];
5433         tp->to_reset = 1;
5434
5435         np->istat_sem = SEM;
5436         OUTB (nc_istat, SIGP|SEM);
5437
5438         return 0;
5439 }
5440
5441 /*
5442  *  Abort a SCSI IO.
5443  */
5444 int sym_abort_ccb(hcb_p np, ccb_p cp, int timed_out)
5445 {
5446         /*
5447          *  Check that the IO is active.
5448          */
5449         if (!cp || !cp->host_status || cp->host_status == HS_WAIT)
5450                 return -1;
5451
5452         /*
5453          *  If a previous abort didn't succeed in time,
5454          *  perform a BUS reset.
5455          */
5456         if (cp->to_abort) {
5457                 sym_reset_scsi_bus(np, 1);
5458                 return 0;
5459         }
5460
5461         /*
5462          *  Mark the CCB for abort and allow time for.
5463          */
5464         cp->to_abort = timed_out ? 2 : 1;
5465
5466         /*
5467          *  Tell the SCRIPTS processor to stop and synchronize with us.
5468          */
5469         np->istat_sem = SEM;
5470         OUTB (nc_istat, SIGP|SEM);
5471         return 0;
5472 }
5473
5474 int sym_abort_scsiio(hcb_p np, cam_ccb_p ccb, int timed_out)
5475 {
5476         ccb_p cp;
5477         SYM_QUEHEAD *qp;
5478
5479         /*
5480          *  Look up our CCB control block.
5481          */
5482         cp = NULL;
5483         FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
5484                 ccb_p cp2 = sym_que_entry(qp, struct sym_ccb, link_ccbq);
5485                 if (cp2->cam_ccb == ccb) {
5486                         cp = cp2;
5487                         break;
5488                 }
5489         }
5490
5491         return sym_abort_ccb(np, cp, timed_out);
5492 }
5493
5494 /*
5495  *  Complete execution of a SCSI command with extented 
5496  *  error, SCSI status error, or having been auto-sensed.
5497  *
5498  *  The SCRIPTS processor is not running there, so we 
5499  *  can safely access IO registers and remove JOBs from  
5500  *  the START queue.
5501  *  SCRATCHA is assumed to have been loaded with STARTPOS 
5502  *  before the SCRIPTS called the C code.
5503  */
5504 void sym_complete_error (hcb_p np, ccb_p cp)
5505 {
5506         tcb_p tp;
5507         lcb_p lp;
5508         int resid;
5509         int i;
5510
5511         /*
5512          *  Paranoid check. :)
5513          */
5514         if (!cp || !cp->cam_ccb)
5515                 return;
5516
5517         if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_RESULT)) {
5518                 printf ("CCB=%lx STAT=%x/%x/%x DEV=%d/%d\n", (unsigned long)cp,
5519                         cp->host_status, cp->ssss_status, cp->host_flags,
5520                         cp->target, cp->lun);
5521                 MDELAY(100);
5522         }
5523
5524         /*
5525          *  Get target and lun pointers.
5526          */
5527         tp = &np->target[cp->target];
5528         lp = sym_lp(np, tp, cp->lun);
5529
5530         /*
5531          *  Check for extended errors.
5532          */
5533         if (cp->xerr_status) {
5534                 if (sym_verbose)
5535                         sym_print_xerr(cp, cp->xerr_status);
5536                 if (cp->host_status == HS_COMPLETE)
5537                         cp->host_status = HS_COMP_ERR;
5538         }
5539
5540         /*
5541          *  Calculate the residual.
5542          */
5543         resid = sym_compute_residual(np, cp);
5544
5545         if (!SYM_SETUP_RESIDUAL_SUPPORT) {/* If user does not want residuals */
5546                 resid  = 0;              /* throw them away. :)             */
5547                 cp->sv_resid = 0;
5548         }
5549 #ifdef DEBUG_2_0_X
5550 if (resid)
5551         printf("XXXX RESID= %d - 0x%x\n", resid, resid);
5552 #endif
5553
5554         /*
5555          *  Dequeue all queued CCBs for that device 
5556          *  not yet started by SCRIPTS.
5557          */
5558         i = (INL (nc_scratcha) - np->squeue_ba) / 4;
5559         i = sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
5560
5561         /*
5562          *  Restart the SCRIPTS processor.
5563          */
5564         OUTL_DSP (SCRIPTA_BA (np, start));
5565
5566 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5567         if (cp->host_status == HS_COMPLETE &&
5568             cp->ssss_status == S_QUEUE_FULL) {
5569                 if (!lp || lp->started_tags - i < 2)
5570                         goto weirdness;
5571                 /*
5572                  *  Decrease queue depth as needed.
5573                  */
5574                 lp->started_max = lp->started_tags - i - 1;
5575                 lp->num_sgood = 0;
5576
5577                 if (sym_verbose >= 2) {
5578                         PRINT_LUN(np, cp->target, cp->lun);
5579                         printf(" queue depth is now %d\n", lp->started_max);
5580                 }
5581
5582                 /*
5583                  *  Repair the CCB.
5584                  */
5585                 cp->host_status = HS_BUSY;
5586                 cp->ssss_status = S_ILLEGAL;
5587
5588                 /*
5589                  *  Let's requeue it to device.
5590                  */
5591                 sym_set_cam_status(cp->cam_ccb, CAM_REQUEUE_REQ);
5592                 goto finish;
5593         }
5594 weirdness:
5595 #endif
5596         /*
5597          *  Synchronize DMA map if needed.
5598          */
5599         sym_data_dmamap_postsync(np, cp);
5600
5601         /*
5602          *  Build result in CAM ccb.
5603          */
5604         sym_set_cam_result_error(np, cp, resid);
5605
5606 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5607 finish:
5608 #endif
5609         /*
5610          *  Add this one to the COMP queue.
5611          */
5612         sym_remque(&cp->link_ccbq);
5613         sym_insque_head(&cp->link_ccbq, &np->comp_ccbq);
5614
5615         /*
5616          *  Complete all those commands with either error 
5617          *  or requeue condition.
5618          */
5619         sym_flush_comp_queue(np, 0);
5620
5621 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5622         /*
5623          *  Donnot start more than 1 command after an error.
5624          */
5625         if (lp)
5626                 sym_start_next_ccbs(np, lp, 1);
5627 #endif
5628 }
5629
5630 /*
5631  *  Complete execution of a successful SCSI command.
5632  *
5633  *  Only successful commands go to the DONE queue, 
5634  *  since we need to have the SCRIPTS processor 
5635  *  stopped on any error condition.
5636  *  The SCRIPTS processor is running while we are 
5637  *  completing successful commands.
5638  */
5639 void sym_complete_ok (hcb_p np, ccb_p cp)
5640 {
5641         tcb_p tp;
5642         lcb_p lp;
5643         cam_ccb_p ccb;
5644         int resid;
5645
5646         /*
5647          *  Paranoid check. :)
5648          */
5649         if (!cp || !cp->cam_ccb)
5650                 return;
5651         assert (cp->host_status == HS_COMPLETE);
5652
5653         /*
5654          *  Get user command.
5655          */
5656         ccb = cp->cam_ccb;
5657
5658         /*
5659          *  Get target and lun pointers.
5660          */
5661         tp = &np->target[cp->target];
5662         lp = sym_lp(np, tp, cp->lun);
5663
5664         /*
5665          *  Assume device discovered on first success.
5666          */
5667         if (!lp)
5668                 sym_set_bit(tp->lun_map, cp->lun);
5669
5670         /*
5671          *  If all data have been transferred, given than no
5672          *  extended error did occur, there is no residual.
5673          */
5674         resid = 0;
5675         if (cp->phys.head.lastp != sym_goalp(cp))
5676                 resid = sym_compute_residual(np, cp);
5677
5678         /*
5679          *  Wrong transfer residuals may be worse than just always 
5680          *  returning zero. User can disable this feature from 
5681          *  sym_conf.h. Residual support is enabled by default.
5682          */
5683         if (!SYM_SETUP_RESIDUAL_SUPPORT)
5684                 resid  = 0;
5685 #ifdef DEBUG_2_0_X
5686 if (resid)
5687         printf("XXXX RESID= %d - 0x%x\n", resid, resid);
5688 #endif
5689
5690         /*
5691          *  Synchronize DMA map if needed.
5692          */
5693         sym_data_dmamap_postsync(np, cp);
5694
5695         /*
5696          *  Build result in CAM ccb.
5697          */
5698         sym_set_cam_result_ok(np, cp, resid);
5699
5700 #ifdef  SYM_OPT_SNIFF_INQUIRY
5701         /*
5702          *  On standard INQUIRY response (EVPD and CmDt 
5703          *  not set), sniff out device capabilities.
5704          */
5705         if (cp->cdb_buf[0] == INQUIRY && !(cp->cdb_buf[1] & 0x3))
5706                 sym_sniff_inquiry(np, cp->cam_ccb, resid);
5707 #endif
5708
5709 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5710         /*
5711          *  If max number of started ccbs had been reduced,
5712          *  increase it if 200 good status received.
5713          */
5714         if (lp && lp->started_max < lp->started_limit) {
5715                 ++lp->num_sgood;
5716                 if (lp->num_sgood >= 200) {
5717                         lp->num_sgood = 0;
5718                         ++lp->started_max;
5719                         if (sym_verbose >= 2) {
5720                                 PRINT_LUN(np, cp->target, cp->lun);
5721                                 printf(" queue depth is now %d\n",
5722                                        lp->started_max);
5723                         }
5724                 }
5725         }
5726 #endif
5727
5728         /*
5729          *  Free our CCB.
5730          */
5731         sym_free_ccb (np, cp);
5732
5733 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5734         /*
5735          *  Requeue a couple of awaiting scsi commands.
5736          */
5737         if (lp && !sym_que_empty(&lp->waiting_ccbq))
5738                 sym_start_next_ccbs(np, lp, 2);
5739 #endif
5740         /*
5741          *  Complete the command.
5742          */
5743         sym_xpt_done(np, ccb);
5744 }
5745
5746 /*
5747  *  Soft-attach the controller.
5748  */
5749 #ifdef SYM_OPT_NVRAM_PRE_READ
5750 int sym_hcb_attach(hcb_p np, struct sym_fw *fw, struct sym_nvram *nvram)
5751 #else
5752 int sym_hcb_attach(hcb_p np, struct sym_fw *fw)
5753 #endif
5754 {
5755 #ifndef SYM_OPT_NVRAM_PRE_READ
5756         struct sym_nvram nvram_buf, *nvram = &nvram_buf;
5757 #endif
5758         int i;
5759
5760         /*
5761          *  Get some info about the firmware.
5762          */
5763         np->scripta_sz   = fw->a_size;
5764         np->scriptb_sz   = fw->b_size;
5765         np->scriptz_sz   = fw->z_size;
5766         np->fw_setup     = fw->setup;
5767         np->fw_patch     = fw->patch;
5768         np->fw_name      = fw->name;
5769
5770         /*
5771          *  Save setting of some IO registers, so we will 
5772          *  be able to probe specific implementations.
5773          */
5774         sym_save_initial_setting (np);
5775
5776         /*
5777          *  Reset the chip now, since it has been reported 
5778          *  that SCSI clock calibration may not work properly 
5779          *  if the chip is currently active.
5780          */
5781         sym_chip_reset (np);
5782
5783         /*
5784          *  Try to read the user set-up.
5785          */
5786 #ifndef SYM_OPT_NVRAM_PRE_READ
5787         (void) sym_read_nvram(np, nvram);
5788 #endif
5789
5790         /*
5791          *  Prepare controller and devices settings, according 
5792          *  to chip features, user set-up and driver set-up.
5793          */
5794         (void) sym_prepare_setting(np, nvram);
5795
5796         /*
5797          *  Check the PCI clock frequency.
5798          *  Must be performed after prepare_setting since it destroys 
5799          *  STEST1 that is used to probe for the clock doubler.
5800          */
5801         i = sym_getpciclock(np);
5802         if (i > 37000 && !(np->features & FE_66MHZ))
5803                 printf("%s: PCI BUS clock seems too high: %u KHz.\n",
5804                         sym_name(np), i);
5805
5806         /*
5807          *  Allocate the start queue.
5808          */
5809         np->squeue = (u32 *) sym_calloc_dma(sizeof(u32)*(MAX_QUEUE*2),"SQUEUE");
5810         if (!np->squeue)
5811                 goto attach_failed;
5812         np->squeue_ba = vtobus(np->squeue);
5813
5814         /*
5815          *  Allocate the done queue.
5816          */
5817         np->dqueue = (u32 *) sym_calloc_dma(sizeof(u32)*(MAX_QUEUE*2),"DQUEUE");
5818         if (!np->dqueue)
5819                 goto attach_failed;
5820         np->dqueue_ba = vtobus(np->dqueue);
5821
5822         /*
5823          *  Allocate the target bus address array.
5824          */
5825         np->targtbl = (u32 *) sym_calloc_dma(256, "TARGTBL");
5826         if (!np->targtbl)
5827                 goto attach_failed;
5828         np->targtbl_ba = vtobus(np->targtbl);
5829
5830         /*
5831          *  Allocate SCRIPTS areas.
5832          */
5833         np->scripta0 = sym_calloc_dma(np->scripta_sz, "SCRIPTA0");
5834         np->scriptb0 = sym_calloc_dma(np->scriptb_sz, "SCRIPTB0");
5835         np->scriptz0 = sym_calloc_dma(np->scriptz_sz, "SCRIPTZ0");
5836         if (!np->scripta0 || !np->scriptb0 || !np->scriptz0)
5837                 goto attach_failed;
5838
5839         /*
5840          *  Allocate the array of lists of CCBs hashed by DSA.
5841          */
5842         np->ccbh = sym_calloc(sizeof(ccb_p *)*CCB_HASH_SIZE, "CCBH");
5843         if (!np->ccbh)
5844                 goto attach_failed;
5845
5846         /*
5847          *  Initialyze the CCB free and busy queues.
5848          */
5849         sym_que_init(&np->free_ccbq);
5850         sym_que_init(&np->busy_ccbq);
5851         sym_que_init(&np->comp_ccbq);
5852
5853         /*
5854          *  Initializations for optional handling 
5855          *  of IO timeouts and device queueing.
5856          */
5857 #ifdef  SYM_OPT_HANDLE_IO_TIMEOUT
5858         sym_que_init(&np->tmo0_ccbq);
5859         np->tmo_ccbq =
5860                 sym_calloc(2*SYM_CONF_TIMEOUT_ORDER_MAX*sizeof(SYM_QUEHEAD),
5861                            "TMO_CCBQ");
5862         for (i = 0 ; i < 2*SYM_CONF_TIMEOUT_ORDER_MAX ; i++)
5863                 sym_que_init(&np->tmo_ccbq[i]);
5864 #endif
5865 #ifdef SYM_OPT_HANDLE_DEVICE_QUEUEING
5866         sym_que_init(&np->dummy_ccbq);
5867 #endif
5868         /*
5869          *  Allocate some CCB. We need at least ONE.
5870          */
5871         if (!sym_alloc_ccb(np))
5872                 goto attach_failed;
5873
5874         /*
5875          *  Calculate BUS addresses where we are going 
5876          *  to load the SCRIPTS.
5877          */
5878         np->scripta_ba  = vtobus(np->scripta0);
5879         np->scriptb_ba  = vtobus(np->scriptb0);
5880         np->scriptz_ba  = vtobus(np->scriptz0);
5881
5882         if (np->ram_ba) {
5883                 np->scripta_ba  = np->ram_ba;
5884                 if (np->features & FE_RAM8K) {
5885                         np->ram_ws = 8192;
5886                         np->scriptb_ba = np->scripta_ba + 4096;
5887 #if 0   /* May get useful for 64 BIT PCI addressing */
5888                         np->scr_ram_seg = cpu_to_scr(np->scripta_ba >> 32);
5889 #endif
5890                 }
5891                 else
5892                         np->ram_ws = 4096;
5893         }
5894
5895         /*
5896          *  Copy scripts to controller instance.
5897          */
5898         memcpy(np->scripta0, fw->a_base, np->scripta_sz);
5899         memcpy(np->scriptb0, fw->b_base, np->scriptb_sz);
5900         memcpy(np->scriptz0, fw->z_base, np->scriptz_sz);
5901
5902         /*
5903          *  Setup variable parts in scripts and compute
5904          *  scripts bus addresses used from the C code.
5905          */
5906         np->fw_setup(np, fw);
5907
5908         /*
5909          *  Bind SCRIPTS with physical addresses usable by the 
5910          *  SCRIPTS processor (as seen from the BUS = BUS addresses).
5911          */
5912         sym_fw_bind_script(np, (u32 *) np->scripta0, np->scripta_sz);
5913         sym_fw_bind_script(np, (u32 *) np->scriptb0, np->scriptb_sz);
5914         sym_fw_bind_script(np, (u32 *) np->scriptz0, np->scriptz_sz);
5915
5916 #ifdef SYM_CONF_IARB_SUPPORT
5917         /*
5918          *    If user wants IARB to be set when we win arbitration 
5919          *    and have other jobs, compute the max number of consecutive 
5920          *    settings of IARB hints before we leave devices a chance to 
5921          *    arbitrate for reselection.
5922          */
5923 #ifdef  SYM_SETUP_IARB_MAX
5924         np->iarb_max = SYM_SETUP_IARB_MAX;
5925 #else
5926         np->iarb_max = 4;
5927 #endif
5928 #endif
5929
5930         /*
5931          *  Prepare the idle and invalid task actions.
5932          */
5933         np->idletask.start      = cpu_to_scr(SCRIPTA_BA (np, idle));
5934         np->idletask.restart    = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
5935         np->idletask_ba         = vtobus(&np->idletask);
5936
5937         np->notask.start        = cpu_to_scr(SCRIPTA_BA (np, idle));
5938         np->notask.restart      = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
5939         np->notask_ba           = vtobus(&np->notask);
5940
5941         np->bad_itl.start       = cpu_to_scr(SCRIPTA_BA (np, idle));
5942         np->bad_itl.restart     = cpu_to_scr(SCRIPTB_BA (np, bad_i_t_l));
5943         np->bad_itl_ba          = vtobus(&np->bad_itl);
5944
5945         np->bad_itlq.start      = cpu_to_scr(SCRIPTA_BA (np, idle));
5946         np->bad_itlq.restart    = cpu_to_scr(SCRIPTB_BA (np,bad_i_t_l_q));
5947         np->bad_itlq_ba         = vtobus(&np->bad_itlq);
5948
5949         /*
5950          *  Allocate and prepare the lun JUMP table that is used 
5951          *  for a target prior the probing of devices (bad lun table).
5952          *  A private table will be allocated for the target on the 
5953          *  first INQUIRY response received.
5954          */
5955         np->badluntbl = sym_calloc_dma(256, "BADLUNTBL");
5956         if (!np->badluntbl)
5957                 goto attach_failed;
5958
5959         np->badlun_sa = cpu_to_scr(SCRIPTB_BA (np, resel_bad_lun));
5960         for (i = 0 ; i < 64 ; i++)      /* 64 luns/target, no less */
5961                 np->badluntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
5962
5963         /*
5964          *  Prepare the bus address array that contains the bus 
5965          *  address of each target control block.
5966          *  For now, assume all logical units are wrong. :)
5967          */
5968         for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
5969                 np->targtbl[i] = cpu_to_scr(vtobus(&np->target[i]));
5970                 np->target[i].head.luntbl_sa =
5971                                 cpu_to_scr(vtobus(np->badluntbl));
5972                 np->target[i].head.lun0_sa =
5973                                 cpu_to_scr(vtobus(&np->badlun_sa));
5974         }
5975
5976         /*
5977          *  Now check the cache handling of the pci chipset.
5978          */
5979         if (sym_snooptest (np)) {
5980                 printf("%s: CACHE INCORRECTLY CONFIGURED.\n", sym_name(np));
5981                 goto attach_failed;
5982         };
5983
5984         /*
5985          *  Sigh! we are done.
5986          */
5987         return 0;
5988
5989 attach_failed:
5990         return -ENXIO;
5991 }
5992
5993 /*
5994  *  Free everything that has been allocated for this device.
5995  */
5996 void sym_hcb_free(hcb_p np)
5997 {
5998         SYM_QUEHEAD *qp;
5999         ccb_p cp;
6000         tcb_p tp;
6001         lcb_p lp;
6002         int target, lun;
6003
6004         if (np->scriptz0)
6005                 sym_mfree_dma(np->scriptz0, np->scriptz_sz, "SCRIPTZ0");
6006         if (np->scriptb0)
6007                 sym_mfree_dma(np->scriptb0, np->scriptb_sz, "SCRIPTB0");
6008         if (np->scripta0)
6009                 sym_mfree_dma(np->scripta0, np->scripta_sz, "SCRIPTA0");
6010 #ifdef  SYM_OPT_HANDLE_IO_TIMEOUT
6011         if (np->tmo_ccbq)
6012                 sym_mfree(np->tmo_ccbq,
6013                           2*SYM_CONF_TIMEOUT_ORDER_MAX*sizeof(SYM_QUEHEAD),
6014                           "TMO_CCBQ");
6015 #endif
6016         if (np->squeue)
6017                 sym_mfree_dma(np->squeue, sizeof(u32)*(MAX_QUEUE*2), "SQUEUE");
6018         if (np->dqueue)
6019                 sym_mfree_dma(np->dqueue, sizeof(u32)*(MAX_QUEUE*2), "DQUEUE");
6020
6021         if (np->actccbs) {
6022                 while ((qp = sym_remque_head(&np->free_ccbq)) != 0) {
6023                         cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
6024                         sym_data_dmamap_destroy(np, cp);
6025                         sym_mfree_dma(cp->sns_bbuf, SYM_SNS_BBUF_LEN,
6026                                       "SNS_BBUF");
6027                         sym_mfree_dma(cp, sizeof(*cp), "CCB");
6028                 }
6029         }
6030         if (np->ccbh)
6031                 sym_mfree(np->ccbh, sizeof(ccb_p *)*CCB_HASH_SIZE, "CCBH");
6032
6033         if (np->badluntbl)
6034                 sym_mfree_dma(np->badluntbl, 256,"BADLUNTBL");
6035
6036         for (target = 0; target < SYM_CONF_MAX_TARGET ; target++) {
6037                 tp = &np->target[target];
6038                 for (lun = 0 ; lun < SYM_CONF_MAX_LUN ; lun++) {
6039                         lp = sym_lp(np, tp, lun);
6040                         if (!lp)
6041                                 continue;
6042                         if (lp->itlq_tbl)
6043                                 sym_mfree_dma(lp->itlq_tbl, SYM_CONF_MAX_TASK*4,
6044                                        "ITLQ_TBL");
6045                         if (lp->cb_tags)
6046                                 sym_mfree(lp->cb_tags, SYM_CONF_MAX_TASK,
6047                                        "CB_TAGS");
6048                         sym_mfree_dma(lp, sizeof(*lp), "LCB");
6049                 }
6050 #if SYM_CONF_MAX_LUN > 1
6051                 if (tp->lunmp)
6052                         sym_mfree(tp->lunmp, SYM_CONF_MAX_LUN*sizeof(lcb_p),
6053                                "LUNMP");
6054 #endif 
6055         }
6056         if (np->targtbl)
6057                 sym_mfree_dma(np->targtbl, 256, "TARGTBL");
6058 }