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