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