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