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