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