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