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