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