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