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