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