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