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