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