Home | History | Annotate | Line # | Download | only in dev
ncr5380.c revision 1.8
      1 /*	$NetBSD: ncr5380.c,v 1.8 1995/09/12 19:58:53 leo Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1995 Leo Weppelman.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *      This product includes software developed by Leo Weppelman.
     18  * 4. The name of the author may not be used to endorse or promote products
     19  *    derived from this software without specific prior written permission
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 
     34 #ifdef DBG_NOSTATIC
     35 #	define	static
     36 #endif
     37 #ifdef DBG_SEL
     38 #	define	DBG_SELPRINT(a,b)	printf(a,b)
     39 #else
     40 #	define DBG_SELPRINT(a,b)
     41 #endif
     42 #ifdef DBG_PIO
     43 #	define DBG_PIOPRINT(a,b,c) 	printf(a,b,c)
     44 #else
     45 #	define DBG_PIOPRINT(a,b,c)
     46 #endif
     47 #ifdef DBG_INF
     48 #	define DBG_INFPRINT(a,b,c)	a(b,c)
     49 #else
     50 #	define DBG_INFPRINT(a,b,c)
     51 #endif
     52 #ifdef DBG_PID
     53 	static	char	*last_hit = NULL, *olast_hit = NULL;
     54 #	define	PID(a)	olast_hit = last_hit; last_hit = a;
     55 #else
     56 #	define	PID(a)
     57 #endif
     58 
     59 /*
     60  * Bit mask of targets you want debugging to be shown
     61  */
     62 u_char	dbg_target_mask = 0x7f;
     63 
     64 /*
     65  * Set bit for target when parity checking must be disabled.
     66  * My (LWP) Maxtor 7245S  seems to generate parity errors on about 50%
     67  * of all transfers while the data is correct!?
     68  */
     69 u_char	ncr5380_no_parchk = 0xff;
     70 
     71 /*
     72  * This is the default sense-command we send.
     73  */
     74 static	u_char	sense_cmd[] = {
     75 		REQUEST_SENSE, 0, 0, 0, sizeof(struct scsi_sense_data), 0
     76 };
     77 
     78 /*
     79  * True if the main co-routine is running
     80  */
     81 static volatile int	main_running = 0;
     82 
     83 /*
     84  * Mask of targets selected
     85  */
     86 static u_char	busy;
     87 
     88 static void	ncr5380_minphys(struct buf *bp);
     89 static int	ncr5380_scsi_cmd(struct scsi_xfer *xs);
     90 static int	ncr5380_show_scsi_cmd(struct scsi_xfer *xs);
     91 
     92 struct scsi_adapter ncr5380_switch = {
     93 	ncr5380_scsi_cmd,		/* scsi_cmd()			*/
     94 	ncr5380_minphys,		/* scsi_minphys()		*/
     95 	0,				/* open_target_lu()		*/
     96 	0				/* close_target_lu()		*/
     97 };
     98 
     99 struct scsi_device ncr5380_dev = {
    100 	NULL,		/* use default error handler		*/
    101 	NULL,		/* do not have a start functio		*/
    102 	NULL,		/* have no async handler		*/
    103 	NULL		/* Use default done routine		*/
    104 };
    105 
    106 
    107 static SC_REQ	req_queue[NREQ];
    108 static SC_REQ	*free_head = NULL;	/* Free request structures	*/
    109 
    110 
    111 /*
    112  * Inline functions:
    113  */
    114 
    115 /*
    116  * Determine the size of a SCSI command.
    117  */
    118 extern __inline__ int command_size(opcode)
    119 u_char	opcode;
    120 {
    121 	switch ((opcode >> 4) & 0xf) {
    122 		case 0:
    123 		case 1:
    124 			return (6);
    125 		case 2:
    126 		case 3:
    127 			return (10);
    128 	}
    129 	return (12);
    130 }
    131 
    132 
    133 /*
    134  * Wait for request-line to become active. When it doesn't return 0.
    135  * Otherwise return != 0.
    136  * The timeouts in the 'wait_req_*' functions are arbitrary and rather
    137  * large. In 99% of the invocations nearly no timeout is needed but in
    138  * some cases (especially when using my tapedrive, a Tandberg 3600) the
    139  * device is busy internally and the first SCSI-phase will be delayed.
    140  */
    141 extern __inline__ int wait_req_true(void)
    142 {
    143 	int	timeout = 25000;
    144 
    145 	while (!(GET_5380_REG(NCR5380_IDSTAT) & SC_S_REQ) && --timeout)
    146 		delay(1);
    147 	return (GET_5380_REG(NCR5380_IDSTAT) & SC_S_REQ);
    148 }
    149 
    150 /*
    151  * Wait for request-line to become inactive. When it doesn't return 0.
    152  * Otherwise return != 0.
    153  */
    154 extern __inline__ int wait_req_false(void)
    155 {
    156 	int	timeout = 25000;
    157 
    158 	while ((GET_5380_REG(NCR5380_IDSTAT) & SC_S_REQ) && --timeout)
    159 		delay(1);
    160 	return (!(GET_5380_REG(NCR5380_IDSTAT) & SC_S_REQ));
    161 }
    162 
    163 extern __inline__ void ack_message()
    164 {
    165 	SET_5380_REG(NCR5380_ICOM, 0);
    166 }
    167 
    168 extern __inline__ void nack_message(SC_REQ *reqp)
    169 {
    170 	SET_5380_REG(NCR5380_ICOM, SC_A_ATN);
    171 	reqp->msgout = MSG_ABORT;
    172 }
    173 
    174 extern __inline__ void finish_req(SC_REQ *reqp)
    175 {
    176 	int			sps;
    177 	struct scsi_xfer	*xs = reqp->xs;
    178 
    179 #ifdef REAL_DMA
    180 	/*
    181 	 * If we bounced, free the bounce buffer
    182 	 */
    183 	if (reqp->dr_flag & DRIVER_BOUNCING)
    184 		free_bounceb(reqp->bounceb);
    185 #endif /* REAL_DMA */
    186 #ifdef DBG_REQ
    187 	if (dbg_target_mask & (1 << reqp->targ_id))
    188 		show_request(reqp, "DONE");
    189 #endif
    190 #ifdef DBG_ERR_RET
    191 	if (reqp->xs->error != 0)
    192 		show_request(reqp, "ERR_RET");
    193 #endif
    194 
    195 	/*
    196 	 * Return request to free-q
    197 	 */
    198 	sps = splbio();
    199 	reqp->next = free_head;
    200 	free_head  = reqp;
    201 	splx(sps);
    202 
    203 	xs->flags |= ITSDONE;
    204 	scsi_done(xs);
    205 }
    206 
    207 /*
    208  * Auto config stuff....
    209  */
    210 int	ncr_cprint __P((void *auxp, char *));
    211 void	ncr_attach __P((struct device *, struct device *, void *));
    212 int	ncr_match __P((struct device *, struct cfdata *, void *));
    213 
    214 /*
    215  * Tricks to make driver-name configurable
    216  */
    217 #define CFNAME(n)	__CONCAT(n,cd)
    218 #define CFSTRING(n)	__STRING(n)
    219 
    220 struct cfdriver CFNAME(DRNAME) = {
    221 	NULL, CFSTRING(DRNAME), (cfmatch_t)ncr_match, ncr_attach,
    222 	DV_DULL, sizeof(struct ncr_softc), NULL, 0 };
    223 
    224 int
    225 ncr_match(pdp, cdp, auxp)
    226 struct device	*pdp;
    227 struct cfdata	*cdp;
    228 void		*auxp;
    229 {
    230 	return (machine_match(pdp, cdp, auxp, &CFNAME(DRNAME)));
    231 }
    232 
    233 void
    234 ncr_attach(pdp, dp, auxp)
    235 struct device	*pdp, *dp;
    236 void		*auxp;
    237 {
    238 	struct ncr_softc	*sc;
    239 	int			i;
    240 
    241 	sc = (struct ncr_softc *)dp;
    242 
    243 	sc->sc_link.adapter_softc   = sc;
    244 	sc->sc_link.adapter_target  = 7;
    245 	sc->sc_link.adapter         = &ncr5380_switch;
    246 	sc->sc_link.device          = &ncr5380_dev;
    247 	sc->sc_link.openings        = NREQ - 1;
    248 
    249 	/*
    250 	 * Initialize machine-type specific things...
    251 	 */
    252 	scsi_mach_init(sc);
    253 	printf("\n");
    254 
    255 	/*
    256 	 * Initialize request queue freelist.
    257 	 */
    258 	for (i = 0; i < NREQ; i++) {
    259 		req_queue[i].next = free_head;
    260 		free_head = &req_queue[i];
    261 	}
    262 
    263 	/*
    264 	 * Initialize the host adapter
    265 	 */
    266 	scsi_idisable();
    267 	ENABLE_NCR5380(sc);
    268 	SET_5380_REG(NCR5380_ICOM, 0);
    269 	SET_5380_REG(NCR5380_MODE, IMODE_BASE);
    270 	SET_5380_REG(NCR5380_TCOM, 0);
    271 	SET_5380_REG(NCR5380_IDSTAT, 0);
    272 	scsi_ienable();
    273 
    274 	/*
    275 	 * attach all scsi units on us
    276 	 */
    277 	config_found(dp, &sc->sc_link, ncr_cprint);
    278 }
    279 
    280 /*
    281  * print diag if name is NULL else just extra
    282  */
    283 int
    284 ncr_cprint(auxp, name)
    285 void	*auxp;
    286 char	*name;
    287 {
    288 	if (name == NULL)
    289 		return (UNCONF);
    290 	return (QUIET);
    291 }
    292 /*
    293  * End of auto config stuff....
    294  */
    295 
    296 /*
    297  * Carry out a request from the high level driver.
    298  */
    299 static int
    300 ncr5380_scsi_cmd(struct scsi_xfer *xs)
    301 {
    302 	int	sps;
    303 	SC_REQ	*reqp;
    304 	int	flags = xs->flags;
    305 
    306 	/*
    307 	 * We do not queue RESET commands
    308 	 */
    309 	if (flags & SCSI_RESET) {
    310 		scsi_reset(xs->sc_link->adapter_softc);
    311 		return (COMPLETE);
    312 	}
    313 
    314 	/*
    315 	 * Get a request block
    316 	 */
    317 	sps = splbio();
    318 	if ((reqp = free_head) == 0) {
    319 		splx(sps);
    320 		return (TRY_AGAIN_LATER);
    321 	}
    322 	free_head  = reqp->next;
    323 	reqp->next = NULL;
    324 	splx(sps);
    325 
    326 	/*
    327 	 * Initialize our private fields
    328 	 */
    329 	reqp->dr_flag   = (flags & SCSI_POLL) ? DRIVER_NOINT : 0;
    330 	reqp->phase     = NR_PHASE;
    331 	reqp->msgout    = MSG_NOOP;
    332 	reqp->status    = SCSGOOD;
    333 	reqp->link      = NULL;
    334 	reqp->xs        = xs;
    335 	reqp->targ_id   = xs->sc_link->target;
    336 	reqp->targ_lun  = xs->sc_link->lun;
    337 	reqp->xdata_ptr = (u_char*)xs->data;
    338 	reqp->xdata_len = xs->datalen;
    339 	memcpy(&reqp->xcmd, xs->cmd, sizeof(struct scsi_generic));
    340 	reqp->xcmd.bytes[0] |= reqp->targ_lun << 5;
    341 
    342 	/*
    343 	 * Sanity check on flags...
    344 	 */
    345 	if (flags & ITSDONE) {
    346 		ncr_tprint(reqp, "scsi_cmd: command already done.....\n");
    347 		xs->flags &= ~ITSDONE;
    348 	}
    349 	if (!(flags & INUSE)) {
    350 		ncr_tprint(reqp, "scsi_cmd: command not in use.....\n");
    351 		xs->flags |= ~INUSE;
    352 	}
    353 
    354 #ifdef REAL_DMA
    355 	/*
    356 	 * Check if DMA can be used on this request
    357 	 */
    358 	if (scsi_dmaok(reqp))
    359 		reqp->dr_flag |= DRIVER_DMAOK;
    360 #endif /* REAL_DMA */
    361 
    362 	/*
    363 	 * Insert the command into the issue queue. Note that 'REQUEST SENSE'
    364 	 * commands are inserted at the head of the queue since any command
    365 	 * will clear the existing contingent allegience condition and the sense
    366 	 * data is only valid while the condition exists.
    367 	 * When possible, link the command to a previous command to the same
    368 	 * target. This is not very sensible when AUTO_SENSE is not defined!
    369 	 * Interrupts are disabled while we are fiddling with the issue-queue.
    370 	 */
    371 	sps = splbio();
    372 	if ((issue_q == NULL) || (reqp->xcmd.opcode == REQUEST_SENSE)) {
    373 		reqp->next = issue_q;
    374 		issue_q    = reqp;
    375 	}
    376 	else {
    377 		SC_REQ	*tmp, *link;
    378 
    379 		tmp  = issue_q;
    380 		link = NULL;
    381 		do {
    382 		    if (!link && (tmp->targ_id == reqp->targ_id) && !tmp->link)
    383 				link = tmp;
    384 		} while (tmp->next && (tmp = tmp->next));
    385 		tmp->next = reqp;
    386 #ifdef AUTO_SENSE
    387 		if (link) {
    388 			link->link = reqp;
    389 			link->xcmd.bytes[link->xs->cmdlen-1] |= 1;
    390 		}
    391 #endif
    392 	}
    393 	splx(sps);
    394 
    395 #ifdef DBG_REQ
    396 	if (dbg_target_mask & (1 << reqp->targ_id))
    397 		show_request(reqp, (reqp->xcmd.opcode == REQUEST_SENSE) ?
    398 								"HEAD":"TAIL");
    399 #endif
    400 
    401 	run_main(xs->sc_link->adapter_softc);
    402 
    403 	if (xs->flags & SCSI_POLL)
    404 		return (COMPLETE);	/* We're booting */
    405 	return (SUCCESSFULLY_QUEUED);
    406 }
    407 
    408 #define MIN_PHYS	65536	/*BARF!!!!*/
    409 static void
    410 ncr5380_minphys(struct buf *bp)
    411 {
    412     if (bp->b_bcount > MIN_PHYS)
    413 	bp->b_bcount = MIN_PHYS;
    414     minphys(bp);
    415 }
    416 #undef MIN_PHYS
    417 
    418 static int
    419 ncr5380_show_scsi_cmd(struct scsi_xfer *xs)
    420 {
    421 	u_char	*b = (u_char *) xs->cmd;
    422 	int	i  = 0;
    423 
    424 	if (!(xs->flags & SCSI_RESET)) {
    425 		printf("(%d:%d:%d,0x%x)-", xs->sc_link->scsibus,
    426 		    xs->sc_link->target, xs->sc_link->lun, xs->sc_link->flags);
    427 		while (i < xs->cmdlen) {
    428 			if (i)
    429 				printf(",");
    430 			printf("%x",b[i++]);
    431 		}
    432 		printf("-\n");
    433 	}
    434 	else {
    435 		printf("(%d:%d:%d)-RESET-\n",
    436 		    xs->sc_link->scsibus,xs->sc_link->target, xs->sc_link->lun);
    437 	}
    438 }
    439 
    440 /*
    441  * The body of the driver.
    442  */
    443 static void
    444 scsi_main(sc)
    445 struct ncr_softc *sc;
    446 {
    447 	SC_REQ	*req, *prev;
    448 	int	itype;
    449 	int	sps;
    450 
    451 	/*
    452 	 * While running in the driver SCSI-interrupts are disabled.
    453 	 */
    454 	scsi_idisable();
    455 	ENABLE_NCR5380(sc);
    456 
    457 	PID("scsi_main1");
    458 	for (;;) {
    459 	    sps = splbio();
    460 	    if (!connected) {
    461 		/*
    462 		 * Check if it is fair keep any exclusive access to DMA
    463 		 * claimed. If not, stop queueing new jobs so the discon_q
    464 		 * will be eventually drained and DMA can be given up.
    465 		 */
    466 		if (!fair_to_keep_dma())
    467 			goto main_exit;
    468 
    469 		/*
    470 		 * Search through the issue-queue for a command
    471 		 * destined for a target that isn't busy.
    472 		 */
    473 		prev = NULL;
    474 		for (req=issue_q; req != NULL; prev = req, req = req->next) {
    475 			if (!(busy & (1 << req->targ_id))) {
    476 				/*
    477 				 * Found one, remove it from the issue queue
    478 				 */
    479 				if (prev == NULL)
    480 					issue_q = req->next;
    481 				else prev->next = req->next;
    482 				req->next = NULL;
    483 				break;
    484 			}
    485 		}
    486 
    487 		/*
    488 		 * When a request has just ended, we get here before an other
    489 		 * device detects that the bus is free and that it can
    490 		 * reconnect. The problem is that when this happens, we always
    491 		 * baffle the device because our (initiator) id is higher. This
    492 		 * can cause a sort of starvation on slow devices. So we check
    493 		 * for a pending reselection here.
    494 		 * Note that 'connected' will be non-null if the reselection
    495 		 * succeeds.
    496 		 */
    497 		if ((GET_5380_REG(NCR5380_IDSTAT) & (SC_S_SEL|SC_S_IO))
    498 						== (SC_S_SEL|SC_S_IO)){
    499 			if (req != NULL) {
    500 				req->next = issue_q;
    501 				issue_q = req;
    502 			}
    503 			splx(sps);
    504 
    505 			reselect(sc);
    506 			scsi_clr_ipend();
    507 			goto connected;
    508 		}
    509 
    510 		/*
    511 		 * The host is not connected and there is no request
    512 		 * pending, exit.
    513 		 */
    514 		if (req == NULL) {
    515 			PID("scsi_main2");
    516 			goto main_exit;
    517 		}
    518 
    519 		/*
    520 		 * Re-enable interrupts before handling the request.
    521 		 */
    522 		splx(sps);
    523 
    524 #ifdef DBG_REQ
    525 		if (dbg_target_mask & (1 << req->targ_id))
    526 			show_request(req, "TARGET");
    527 #endif
    528 		/*
    529 		 * We found a request. Try to connect to the target. If the
    530 		 * initiator fails arbitration, the command is put back in the
    531 		 * issue queue.
    532 		 */
    533 		if (scsi_select(req, 0)) {
    534 			sps = splbio();
    535 			req->next = issue_q;
    536 			issue_q = req;
    537 			splx(sps);
    538 #ifdef DBG_REQ
    539 			if (dbg_target_mask & (1 << req->targ_id))
    540 				ncr_tprint(req, "Select failed\n");
    541 #endif
    542 		}
    543 	    }
    544 	    else splx(sps);
    545 connected:
    546 	    if (connected) {
    547 		/*
    548 		 * If the host is currently connected but a 'real-dma' transfer
    549 		 * is in progress, the 'end-of-dma' interrupt restarts main.
    550 		 * So quit.
    551 		 */
    552 		sps = splbio();
    553 		if (connected && (connected->dr_flag & DRIVER_IN_DMA)) {
    554 			PID("scsi_main3");
    555 			goto main_exit;
    556 		}
    557 		splx(sps);
    558 
    559 		/*
    560 		 * Let the target guide us through the bus-phases
    561 		 */
    562 		while (information_transfer() == -1)
    563 			;
    564 	    }
    565 	}
    566 	/* NEVER TO REACH HERE */
    567 	panic("ncr5380-SCSI: not designed to come here");
    568 
    569 main_exit:
    570 	/*
    571 	 * We enter here with interrupts disabled. We are about to exit main
    572 	 * so interrupts should be re-enabled. Because interrupts are edge
    573 	 * triggered, we could already have missed the interrupt. Therefore
    574 	 * we check the IRQ-line here and re-enter when we really missed a
    575 	 * valid interrupt.
    576 	 */
    577 	PID("scsi_main4");
    578 	scsi_ienable();
    579 	SET_5380_REG(NCR5380_IDSTAT, SC_HOST_ID);
    580 	if (GET_5380_REG(NCR5380_DMSTAT) & SC_IRQ_SET) {
    581 		if ((itype = check_intr(sc)) != INTR_SPURIOUS) {
    582 			scsi_idisable();
    583 			splx(sps);
    584 
    585 			if (itype == INTR_RESEL)
    586 				reselect(sc);
    587 #ifdef REAL_DMA
    588 			else dma_ready();
    589 #else
    590 			else panic("Got DMA interrupt without DMA");
    591 #endif
    592 			scsi_clr_ipend();
    593 			goto connected;
    594 		}
    595 	}
    596 	reconsider_dma();
    597 
    598 	main_running = 0;
    599 	splx(sps);
    600 	PID("scsi_main5");
    601 }
    602 
    603 #ifdef REAL_DMA
    604 /*
    605  * The SCSI-DMA interrupt.
    606  * This interrupt can only be triggered when running in non-polled DMA
    607  * mode. When DMA is not active, it will be silently ignored, it is usually
    608  * to late because the EOP interrupt of the controller happens just a tiny
    609  * bit earlier. It might become usefull when scatter/gather is implemented,
    610  * because in that case only part of the DATAIN/DATAOUT transfer is taken
    611  * out of a single buffer.
    612  */
    613 static void
    614 ncr_dma_intr(sc)
    615 struct ncr_softc *sc;
    616 {
    617 	SC_REQ	*reqp;
    618 	int	dma_done;
    619 
    620 	PID("ncr_dma_intr");
    621 	if ((reqp = connected) && (reqp->dr_flag & DRIVER_IN_DMA)) {
    622 		scsi_idisable();
    623 		if (!(dma_done = dma_ready())) {
    624 			transfer_dma(reqp, reqp->phase, 0);
    625 			return;
    626 		}
    627 		run_main(sc);
    628 	}
    629 }
    630 #endif /* REAL_DMA */
    631 
    632 /*
    633  * The SCSI-controller interrupt. This interrupt occurs on reselections and
    634  * at the end of non-polled DMA-interrupts. It is assumed to be called from
    635  * the machine-dependent hardware interrupt.
    636  */
    637 static void
    638 ncr_ctrl_intr(sc)
    639 struct ncr_softc *sc;
    640 {
    641 	int	itype;
    642 	int	dma_done;
    643 
    644 	while (GET_5380_REG(NCR5380_DMSTAT) & SC_IRQ_SET) {
    645 		scsi_idisable();
    646 		if ((itype = check_intr(sc)) != INTR_SPURIOUS) {
    647 			if (itype == INTR_RESEL)
    648 				reselect(sc);
    649 			else {
    650 #ifdef REAL_DMA
    651 			    if (!(dma_done = dma_ready())) {
    652 				transfer_dma(connected, connected->phase, 0);
    653 				return;
    654 			    }
    655 #else
    656 			    panic("Got DMA interrupt without DMA\n");
    657 #endif
    658 			}
    659 			scsi_clr_ipend();
    660 		}
    661 		run_main(sc);
    662 		return;
    663 	}
    664 	PID("ncr_ctrl_intr1");
    665 }
    666 
    667 /*
    668  * Initiate a connection path between the host and the target. The function
    669  * first goes into arbitration for the SCSI-bus. When this succeeds, the target
    670  * is selected and an 'IDENTIFY' message is send.
    671  * Returns -1 when the arbitration failed. Otherwise 0 is returned. When
    672  * the target does not respond (to either selection or 'MESSAGE OUT') the
    673  * 'done' function is executed.
    674  * The result code given by the driver can be influenced by setting 'code'
    675  * to a non-zero value. This is the case when 'select' is called by abort.
    676  */
    677 static int
    678 scsi_select(reqp, code)
    679 SC_REQ	*reqp;
    680 {
    681 	u_long			timeout;
    682 	u_char			tmp[1];
    683 	u_char			phase;
    684 	u_long			cnt;
    685 	int			sps;
    686 	struct ncr_softc	*sc;
    687 
    688 	sc = reqp->xs->sc_link->adapter_softc;
    689 	DBG_SELPRINT ("Starting arbitration\n", 0);
    690 	PID("scsi_select1");
    691 
    692 	sps = splbio();
    693 
    694 	/*
    695 	 * Prevent a race condition here. If a reslection interrupt occurred
    696 	 * between the decision to pick a new request and the call to select,
    697 	 * we abort the selection.
    698 	 * Interrupts are lowered when the 5380 is setup to arbitrate for the
    699 	 * bus.
    700 	 */
    701 	if (connected || (GET_5380_REG(NCR5380_IDSTAT) & SC_S_BSY)) {
    702 		splx(sps);
    703 		PID("scsi_select2");
    704 		return (-1);
    705 	}
    706 
    707 	/*
    708 	 * Set phase bits to 0, otherwise the 5380 won't drive the bus during
    709 	 * selection.
    710 	 */
    711 	SET_5380_REG(NCR5380_TCOM, 0);
    712 	SET_5380_REG(NCR5380_ICOM, 0);
    713 
    714 	/*
    715 	 * Arbitrate for the bus.
    716 	 */
    717 	SET_5380_REG(NCR5380_DATA, SC_HOST_ID);
    718 	SET_5380_REG(NCR5380_MODE, SC_ARBIT);
    719 
    720 	splx(sps);
    721 
    722 	cnt = 10000;
    723 	while (!(GET_5380_REG(NCR5380_ICOM) & SC_AIP) && --cnt)
    724 		delay(1);
    725 
    726 	if (!(GET_5380_REG(NCR5380_ICOM) & SC_AIP)) {
    727 		SET_5380_REG(NCR5380_MODE, IMODE_BASE);
    728 		delay(1);
    729 		PID("scsi_select3");
    730 
    731 		if (GET_5380_REG(NCR5380_IDSTAT) & SC_S_BSY) {
    732 			/*
    733 			 * Damn, we have a connected target that we don't know
    734 			 * of. Some targets seem to respond to a selection
    735 			 * AFTER the selection-timeout. Try to get the target
    736 			 * into the Message-out phase so we can send an ABORT
    737 			 * message. We try to avoid resetting the SCSI-bus!
    738 			 */
    739 			if (!reach_msg_out(sc, sizeof(struct scsi_generic))) {
    740 				u_long	len   = 1;
    741 				u_char	phase = PH_MSGOUT;
    742 				u_char	msg   = MSG_ABORT;
    743 
    744 				transfer_pio(&phase, &msg, &len, 0);
    745 			}
    746 			else if (GET_5380_REG(NCR5380_IDSTAT) & SC_S_BSY)
    747 					scsi_reset(sc);
    748 		}
    749 		PID("scsi_select4");
    750 		return (-1);
    751 	}
    752 
    753 	/* The arbitration delay is 2.2 usecs */
    754 	delay(3);
    755 
    756 	/*
    757 	 * Check the result of the arbitration. If we failed, return -1.
    758 	 */
    759 	if (GET_5380_REG(NCR5380_ICOM) & SC_LA) {
    760 		/*
    761 		 * The spec requires that we should read the data register to
    762 		 * check for higher id's and check the SC_LA again.
    763 		 */
    764 		tmp[0] = GET_5380_REG(NCR5380_DATA);
    765 		if (GET_5380_REG(NCR5380_ICOM) & SC_LA) {
    766 			SET_5380_REG(NCR5380_MODE, IMODE_BASE);
    767 			SET_5380_REG(NCR5380_ICOM, 0);
    768 			DBG_SELPRINT ("Arbitration lost,deassert SC_ARBIT\n",0);
    769 			PID("scsi_select5");
    770 			return (-1);
    771 		}
    772 	}
    773 	SET_5380_REG(NCR5380_ICOM, SC_A_SEL | SC_A_BSY);
    774 	if (GET_5380_REG(NCR5380_ICOM) & SC_LA) {
    775 		SET_5380_REG(NCR5380_MODE, IMODE_BASE);
    776 		SET_5380_REG(NCR5380_ICOM, 0);
    777 		DBG_SELPRINT ("Arbitration lost, deassert SC_A_SEL\n", 0);
    778 		PID("scsi_select6");
    779 		return (-1);
    780 	}
    781 	/* Bus settle delay + Bus clear delay = 1.2 usecs */
    782 	delay(2);
    783 	DBG_SELPRINT ("Arbitration complete\n", 0);
    784 
    785 	/*
    786 	 * Now that we won the arbitration, start the selection.
    787 	 */
    788 	SET_5380_REG(NCR5380_DATA, SC_HOST_ID | (1 << reqp->targ_id));
    789 
    790 	/*
    791 	 * Raise ATN while SEL is true before BSY goes false from arbitration,
    792 	 * since this is the only way to guarantee that we'll get a MESSAGE OUT
    793 	 * phase immediately after the selection.
    794 	 */
    795 	SET_5380_REG(NCR5380_ICOM, SC_A_BSY | SC_A_SEL | SC_A_ATN | SC_ADTB);
    796 	SET_5380_REG(NCR5380_MODE, IMODE_BASE);
    797 
    798 	/*
    799 	 * Turn off reselection interrupts
    800 	 */
    801 	SET_5380_REG(NCR5380_IDSTAT, 0);
    802 
    803 	/*
    804 	 * Reset BSY. The delay following it, surpresses a glitch in the
    805 	 * 5380 which causes us to see our own BSY signal instead of that of
    806 	 * the target.
    807 	 */
    808 	SET_5380_REG(NCR5380_ICOM, SC_A_SEL | SC_A_ATN | SC_ADTB);
    809 	delay(1);
    810 
    811 	/*
    812 	 * Wait for the target to react, the specs call for a timeout of
    813 	 * 250 ms.
    814 	 */
    815 	cnt = 25000 /* 250 */;
    816 	while (!(GET_5380_REG(NCR5380_IDSTAT) & SC_S_BSY) && --cnt)
    817 		delay(10);
    818 
    819 	if (!(GET_5380_REG(NCR5380_IDSTAT) & SC_S_BSY)) {
    820 		/*
    821 		 * There is no reaction from the target, start the selection
    822 		 * timeout procedure. We release the databus but keep SEL
    823 		 * asserted. After that we wait a 'selection abort time' (200
    824 		 * usecs) and 2 deskew delays (90 ns) and check BSY again.
    825 		 * When BSY is asserted, we assume the selection succeeded,
    826 		 * otherwise we release the bus.
    827 		 */
    828 		SET_5380_REG(NCR5380_ICOM, SC_A_SEL | SC_A_ATN);
    829 		delay(201);
    830 		if (!(GET_5380_REG(NCR5380_IDSTAT) & SC_S_BSY)) {
    831 			SET_5380_REG(NCR5380_ICOM, 0);
    832 			reqp->xs->error      = code ? code : XS_SELTIMEOUT;
    833 			DBG_SELPRINT ("Target %d not responding to sel\n",
    834 								reqp->targ_id);
    835 			finish_req(reqp);
    836 			PID("scsi_select7");
    837 			return (0);
    838 		}
    839 	}
    840 	SET_5380_REG(NCR5380_ICOM, SC_A_ATN);
    841 
    842 	DBG_SELPRINT ("Target %d responding to select.\n", reqp->targ_id);
    843 
    844 	/*
    845 	 * The SCSI-interrupts are disabled while a request is being handled.
    846 	 */
    847 	scsi_idisable();
    848 
    849 	/*
    850 	 * Since we followed the SCSI-spec and raised ATN while SEL was true
    851 	 * but before BSY was false during the selection, a 'MESSAGE OUT'
    852 	 * phase should follow. Here we send an 'IDENTIFY' message.
    853 	 * Allow disconnect only when interrups are allowed.
    854 	 */
    855 	tmp[0] = MSG_IDENTIFY(reqp->targ_lun,
    856 				(reqp->dr_flag & DRIVER_NOINT) ? 0 : 1);
    857 	cnt    = 1;
    858 	phase  = PH_MSGOUT;
    859 	if (transfer_pio(&phase, tmp, &cnt, 0) || cnt) {
    860 		DBG_SELPRINT ("Target %d: failed to send identify\n",
    861 							reqp->targ_id);
    862 		/*
    863 		 * Try to disconnect from the target. We cannot leave it just
    864 		 * hanging here.
    865 		 */
    866 		if (!reach_msg_out(sc, sizeof(struct scsi_generic))) {
    867 			u_long	len   = 1;
    868 			u_char	phase = PH_MSGOUT;
    869 			u_char	msg   = MSG_ABORT;
    870 
    871 			transfer_pio(&phase, &msg, &len, 0);
    872 		}
    873 		else scsi_reset(sc);
    874 
    875 		SET_5380_REG(NCR5380_ICOM, 0);
    876 		reqp->xs->error = code ? code : XS_DRIVER_STUFFUP;
    877 		finish_req(reqp);
    878 		PID("scsi_select8");
    879 		return (0);
    880 	}
    881 	reqp->phase = PH_MSGOUT;
    882 
    883 #ifdef notyet /* LWP: Do we need timeouts in the driver? */
    884 	/*
    885 	 * Command is connected, start timer ticking.
    886 	 */
    887 	ccb_p->xtimeout = ccb_p->timeout + Lbolt;
    888 #endif
    889 
    890 	connected  = reqp;
    891 	busy      |= 1 << reqp->targ_id;
    892 	PID("scsi_select9");
    893 	return (0);
    894 }
    895 
    896 /*
    897  * Return codes:
    898  *	-1: quit main, trigger on interrupt
    899  *   0: keep on running main.
    900  */
    901 static int
    902 information_transfer()
    903 {
    904 	SC_REQ	*reqp = connected;
    905 	u_char	tmp, phase;
    906 	u_long	len;
    907 
    908 	PID("info_transf1");
    909 	/*
    910 	 * Clear pending interrupts from 5380-chip.
    911 	 */
    912 	scsi_clr_ipend();
    913 
    914 	/*
    915 	 * We only have a valid SCSI-phase when REQ is asserted. Something
    916 	 * is deadly wrong when BSY has dropped.
    917 	 */
    918 	tmp = GET_5380_REG(NCR5380_IDSTAT);
    919 
    920 	if (!(tmp & SC_S_BSY)) {
    921 		busy           &= ~(1 << reqp->targ_id);
    922 		connected       = NULL;
    923 		reqp->xs->error = XS_BUSY;
    924 		finish_req(reqp);
    925 		PID("info_transf2");
    926 		return (0);
    927 	}
    928 
    929 	if (tmp & SC_S_REQ) {
    930 		phase = (tmp >> 2) & 7;
    931 		if (phase != reqp->phase) {
    932 			reqp->phase = phase;
    933 			DBG_INFPRINT(show_phase, reqp, phase);
    934 		}
    935 	}
    936 	else return (-1);
    937 
    938 	switch (phase) {
    939 	    case PH_DATAOUT:
    940 
    941 #ifdef DBG_NOWRITE
    942 		ncr_tprint(reqp, "NOWRITE set -- write attempt aborted.");
    943 		reqp->msgout = MSG_ABORT;
    944 		SET_5380_REG(NCR5380_ICOM, SC_A_ATN);
    945 		return (-1);
    946 #endif /* DBG_NOWRITE */
    947 		/*
    948 		 * If this is the first write using DMA, fill
    949 		 * the bounce buffer.
    950 		 */
    951 		if (reqp->xdata_ptr == reqp->xs->data) { /* XXX */
    952 		    if (reqp->dr_flag & DRIVER_BOUNCING)
    953 			bcopy(reqp->xdata_ptr, reqp->bounceb, reqp->xdata_len);
    954 		}
    955 
    956 	   case PH_DATAIN:
    957 #ifdef REAL_DMA
    958 		if (reqp->dr_flag & DRIVER_DMAOK) {
    959 			int poll = REAL_DMA_POLL|(reqp->dr_flag & DRIVER_NOINT);
    960 			transfer_dma(reqp, phase, poll);
    961 			if (!poll)
    962 				return (0);
    963 		}
    964 		else
    965 #endif
    966 		{
    967 			PID("info_transf3");
    968 			len = reqp->xdata_len;
    969 #ifdef USE_PDMA
    970 			if (transfer_pdma(&phase, reqp->xdata_ptr, &len) == 0)
    971 				return (0);
    972 #else
    973 			transfer_pio(&phase, reqp->xdata_ptr, &len, 0);
    974 #endif
    975 			reqp->xdata_ptr += reqp->xdata_len - len;
    976 			reqp->xdata_len  = len;
    977 		}
    978 		return (-1);
    979 	   case PH_MSGIN:
    980 		/*
    981 		 * We only expect single byte messages here.
    982 		 */
    983 		len = 1;
    984 		transfer_pio(&phase, &tmp, &len, 1);
    985 		reqp->message = tmp;
    986 		return (handle_message(reqp, tmp));
    987 	   case PH_MSGOUT:
    988 		len = 1;
    989 		transfer_pio(&phase, &reqp->msgout, &len, 0);
    990 		if (reqp->msgout == MSG_ABORT) {
    991 			busy     &= ~(1 << reqp->targ_id);
    992 			connected = NULL;
    993 			reqp->xs->error = XS_DRIVER_STUFFUP;
    994 			finish_req(reqp);
    995 			PID("info_transf4");
    996 			return (0);
    997 		}
    998 		reqp->msgout = MSG_NOOP;
    999 		return (-1);
   1000 	   case PH_CMD :
   1001 		len = command_size(reqp->xcmd.opcode);
   1002 		transfer_pio(&phase, (u_char *)&reqp->xcmd, &len, 0);
   1003 		PID("info_transf5");
   1004 		return (-1);
   1005 	   case PH_STATUS:
   1006 		len = 1;
   1007 		transfer_pio(&phase, &tmp, &len, 0);
   1008 		reqp->status = tmp;
   1009 		PID("info_transf6");
   1010 		return (-1);
   1011 	   default :
   1012 		ncr_tprint(reqp, "Unknown phase\n");
   1013 	}
   1014 	PID("info_transf7");
   1015 	return (-1);
   1016 }
   1017 
   1018 /*
   1019  * Handle the message 'msg' send to us by the target.
   1020  * Return values:
   1021  *	 0 : The current command has completed.
   1022  *	-1 : Get on to the next phase.
   1023  */
   1024 static int
   1025 handle_message(reqp, msg)
   1026 SC_REQ	*reqp;
   1027 u_int	msg;
   1028 {
   1029 	int	sps;
   1030 
   1031 	PID("hmessage1");
   1032 	switch (msg) {
   1033 		/*
   1034 		 * Linking lets us reduce the time required to get
   1035 		 * the next command to the device, skipping the arbitration
   1036 		 * and selection time. In the current implementation,
   1037 		 * we merely have to start the next command pointed
   1038 		 * to by 'next_link'.
   1039 		 */
   1040 		case MSG_LINK_CMD_COMPLETE:
   1041 		case MSG_LINK_CMD_COMPLETEF:
   1042 			if (reqp->link == NULL) {
   1043 				ncr_tprint(reqp, "No link for linked command");
   1044 				nack_message(reqp);
   1045 				PID("hmessage2");
   1046 				return (-1);
   1047 			}
   1048 			ack_message();
   1049 			reqp->xs->error = 0;
   1050 
   1051 #ifdef AUTO_SENSE
   1052 			if (check_autosense(reqp, 0) == -1)
   1053 				return (-1);
   1054 #endif /* AUTO_SENSE */
   1055 
   1056 #ifdef DBG_REQ
   1057 			if (dbg_target_mask & (1 << reqp->targ_id))
   1058 				show_request(reqp->link, "LINK");
   1059 #endif
   1060 			connected = reqp->link;
   1061 			finish_req(reqp);
   1062 			PID("hmessage3");
   1063 			return (-1);
   1064 		case MSG_ABORT:
   1065 		case MSG_CMDCOMPLETE:
   1066 			ack_message();
   1067 			connected = NULL;
   1068 			busy     &= ~(1 << reqp->targ_id);
   1069 			if (!(reqp->dr_flag & DRIVER_AUTOSEN)) {
   1070 				reqp->xs->resid = reqp->xdata_len;
   1071 				reqp->xs->error = 0;
   1072 			}
   1073 
   1074 #ifdef AUTO_SENSE
   1075 			if (check_autosense(reqp, 0) == -1) {
   1076 				PID("hmessage4");
   1077 				return (0);
   1078 			}
   1079 #endif /* AUTO_SENSE */
   1080 
   1081 			finish_req(reqp);
   1082 			PID("hmessage5");
   1083 			return (0);
   1084 		case MSG_MESSAGE_REJECT:
   1085 			ack_message();
   1086 			PID("hmessage6");
   1087 			return (-1);
   1088 		case MSG_DISCONNECT:
   1089 			ack_message();
   1090 #ifdef DBG_REQ
   1091 			if (dbg_target_mask & (1 << reqp->targ_id))
   1092 				show_request(reqp, "DISCON");
   1093 #endif
   1094 			sps = splbio();
   1095 			connected  = NULL;
   1096 			reqp->next = discon_q;
   1097 			discon_q   = reqp;
   1098 			splx(sps);
   1099 			PID("hmessage7");
   1100 			return (0);
   1101 		case MSG_SAVEDATAPOINTER:
   1102 		case MSG_RESTOREPOINTERS:
   1103 			/*
   1104 			 * We save pointers implicitely at disconnect.
   1105 			 * So we can ignore these messages.
   1106 			 */
   1107 			ack_message();
   1108 			PID("hmessage8");
   1109 			return (-1);
   1110 		case MSG_EXTENDED:
   1111 			nack_message(reqp);
   1112 			PID("hmessage9");
   1113 			return (-1);
   1114 		default:
   1115 			ncr_tprint(reqp, "Unkown message %x\n", msg);
   1116 			return (-1);
   1117 	}
   1118 	PID("hmessage10");
   1119 	return (-1);
   1120 }
   1121 
   1122 /*
   1123  * Handle reselection. If a valid reconnection occurs, connected
   1124  * points at the reconnected command. The command is removed from the
   1125  * disconnected queue.
   1126  */
   1127 static void
   1128 reselect(sc)
   1129 struct ncr_softc *sc;
   1130 {
   1131 	u_char	phase;
   1132 	u_long	len;
   1133 	u_char	msg;
   1134 	u_char	target_mask;
   1135 	int	abort = 0;
   1136 	SC_REQ	*tmp, *prev;
   1137 
   1138 	PID("reselect1");
   1139 	target_mask = GET_5380_REG(NCR5380_DATA) & ~SC_HOST_ID;
   1140 
   1141 	/*
   1142 	 * At this point, we have detected that our SCSI-id is on the bus,
   1143 	 * SEL is true and BSY was false for at least one bus settle
   1144 	 * delay (400 ns.).
   1145 	 * We must assert BSY ourselves, until the target drops the SEL signal.
   1146 	 * The SCSI-spec specifies no maximum time for this, so we have to
   1147 	 * choose something long enough to suit all targets.
   1148 	 */
   1149 	SET_5380_REG(NCR5380_ICOM, SC_A_BSY);
   1150 	len = 100;
   1151 	while ((GET_5380_REG(NCR5380_IDSTAT) & SC_S_SEL) && (len > 0)) {
   1152 		delay(1);
   1153 		len--;
   1154 	}
   1155 	if (GET_5380_REG(NCR5380_IDSTAT) & SC_S_SEL) {
   1156 		/* Damn SEL isn't dropping */
   1157 		scsi_reset(sc);
   1158 		return;
   1159 	}
   1160 
   1161 	SET_5380_REG(NCR5380_ICOM, 0);
   1162 
   1163 	/*
   1164 	 * Get the expected identify message.
   1165 	 */
   1166 	phase = PH_MSGIN;
   1167 	len   = 1;
   1168 	transfer_pio(&phase, &msg, &len, 0);
   1169 	if (len || !MSG_ISIDENTIFY(msg)) {
   1170 		ncr_aprint(sc, "Expecting IDENTIFY, got 0x%x\n", msg);
   1171 		abort = 1;
   1172 	}
   1173 	else {
   1174 	    /*
   1175 	     * Find the command reconnecting
   1176 	     */
   1177 	    for (tmp = discon_q, prev = NULL; tmp; prev = tmp, tmp = tmp->next){
   1178 		if (target_mask == (1 << tmp->targ_id)) {
   1179 			if (prev)
   1180 				prev->next = tmp->next;
   1181 			else discon_q = tmp->next;
   1182 			tmp->next = NULL;
   1183 			break;
   1184 		}
   1185 	    }
   1186 	    if (tmp == NULL) {
   1187 		ncr_aprint(sc, "No disconnected job for targetmask %x\n",
   1188 								target_mask);
   1189 		abort = 1;
   1190 	    }
   1191 	}
   1192 	if (abort) {
   1193 		msg   = MSG_ABORT;
   1194 		len   = 1;
   1195 		phase = PH_MSGOUT;
   1196 
   1197 		SET_5380_REG(NCR5380_ICOM, SC_A_ATN);
   1198 		transfer_pio(&phase, &msg, &len, 0);
   1199 	}
   1200 	else {
   1201 		connected = tmp;
   1202 #ifdef DBG_REQ
   1203 		if (dbg_target_mask & (1 << tmp->targ_id))
   1204 			show_request(tmp, "RECON");
   1205 #endif
   1206 	}
   1207 	PID("reselect2");
   1208 }
   1209 
   1210 /*
   1211  * Transfer data in a given phase using programmed I/O.
   1212  * Returns -1 when a different phase is entered without transferring the
   1213  * maximum number of bytes, 0 if all bytes transferred or exit is in the same
   1214  * phase.
   1215  */
   1216 static int
   1217 transfer_pio(phase, data, len, dont_drop_ack)
   1218 u_char	*phase;
   1219 u_char	*data;
   1220 u_long	*len;
   1221 int	dont_drop_ack;
   1222 {
   1223 	u_int	cnt = *len;
   1224 	u_char	ph  = *phase;
   1225 	u_char	tmp, new_icom;
   1226 
   1227 	DBG_PIOPRINT ("SCSI: transfer_pio start: phase: %d, len: %d\n", ph,cnt);
   1228 	PID("tpio1");
   1229 	SET_5380_REG(NCR5380_TCOM, ph);
   1230 	do {
   1231 	    if (!wait_req_true()) {
   1232 		DBG_PIOPRINT ("SCSI: transfer_pio: missing REQ\n", 0, 0);
   1233 		break;
   1234 	    }
   1235 	    if (((GET_5380_REG(NCR5380_IDSTAT) >> 2) & 7) != ph) {
   1236 		DBG_PIOPRINT ("SCSI: transfer_pio: phase mismatch\n", 0, 0);
   1237 		break;
   1238 	    }
   1239 	    if (PH_IN(ph)) {
   1240 		*data++ = GET_5380_REG(NCR5380_DATA);
   1241 		SET_5380_REG(NCR5380_ICOM, SC_A_ACK);
   1242 		if ((cnt == 1) && dont_drop_ack)
   1243 			new_icom = SC_A_ACK;
   1244 		else new_icom = 0;
   1245 	    }
   1246 	    else {
   1247 		SET_5380_REG(NCR5380_DATA, *data++);
   1248 
   1249 		/*
   1250 		 * The SCSI-standard suggests that in the 'MESSAGE OUT' phase,
   1251 		 * the initiator should drop ATN on the last byte of the
   1252 		 * message phase after REQ has been asserted for the handshake
   1253 		 * but before the initiator raises ACK.
   1254 		 */
   1255 		if (!( (ph == PH_MSGOUT) && (cnt > 1) )) {
   1256 			SET_5380_REG(NCR5380_ICOM, SC_ADTB);
   1257 			SET_5380_REG(NCR5380_ICOM, SC_ADTB | SC_A_ACK);
   1258 			new_icom = 0;
   1259 		}
   1260 		else {
   1261 			SET_5380_REG(NCR5380_ICOM, SC_ADTB | SC_A_ATN);
   1262 			SET_5380_REG(NCR5380_ICOM, SC_ADTB|SC_A_ATN|SC_A_ACK);
   1263 			new_icom = SC_A_ATN;
   1264 		}
   1265 	    }
   1266 	    if (!wait_req_false()) {
   1267 		DBG_PIOPRINT ("SCSI: transfer_pio - REQ not dropping\n", 0, 0);
   1268 		break;
   1269 	    }
   1270 	    SET_5380_REG(NCR5380_ICOM, new_icom);
   1271 
   1272 	} while (--cnt);
   1273 
   1274 	if ((tmp = GET_5380_REG(NCR5380_IDSTAT)) & SC_S_REQ)
   1275 		*phase = (tmp >> 2) & 7;
   1276 	else *phase = NR_PHASE;
   1277 	*len = cnt;
   1278 	DBG_PIOPRINT ("SCSI: transfer_pio done: phase: %d, len: %d\n",
   1279 								*phase, cnt);
   1280 	PID("tpio2");
   1281 	if (!cnt || (*phase == ph))
   1282 		return (0);
   1283 	return (-1);
   1284 }
   1285 
   1286 #ifdef REAL_DMA
   1287 /*
   1288  * Start a DMA-transfer on the device using the current pointers.
   1289  * If 'poll' is true, the function busy-waits until DMA has completed.
   1290  */
   1291 static void
   1292 transfer_dma(reqp, phase, poll)
   1293 SC_REQ	*reqp;
   1294 u_int	phase;
   1295 int	poll;
   1296 {
   1297 	int	dma_done;
   1298 	u_char	mbase = 0;
   1299 	int	sps;
   1300 
   1301 again:
   1302 	PID("tdma1");
   1303 
   1304 	/*
   1305 	 * We should be in phase, otherwise we are not allowed to
   1306 	 * drive the bus.
   1307 	 */
   1308 	SET_5380_REG(NCR5380_TCOM, phase);
   1309 
   1310 	/*
   1311 	 * Defer interrupts until DMA is fully running.
   1312 	 */
   1313 	sps = splbio();
   1314 
   1315 	/*
   1316 	 * Clear pending interrupts and parity errors.
   1317 	 */
   1318 	scsi_clr_ipend();
   1319 
   1320 	if (!poll) {
   1321 		/*
   1322 		 * Enable SCSI interrupts and set IN_DMA flag, set 'mbase'
   1323 		 * to the interrupts we want enabled.
   1324 		 */
   1325 		scsi_ienable();
   1326 		reqp->dr_flag |= DRIVER_IN_DMA;
   1327 		mbase = SC_E_EOPI | SC_MON_BSY;
   1328 	}
   1329 	else scsi_idisable();
   1330 	mbase |=  IMODE_BASE | SC_M_DMA;
   1331 	scsi_dma_setup(reqp, phase, mbase);
   1332 
   1333 	splx(sps);
   1334 
   1335 	if (poll) {
   1336 		/*
   1337 		 * On polled-dma transfers, we wait here until the
   1338 		 * 'end-of-dma' condition occurs.
   1339 		 */
   1340 		poll_edma(reqp);
   1341 		if (!(dma_done = dma_ready()))
   1342 			goto again;
   1343 	}
   1344 	PID("tdma2");
   1345 }
   1346 
   1347 /*
   1348  * Check results of a DMA data-transfer.
   1349  */
   1350 static int
   1351 dma_ready()
   1352 {
   1353 	SC_REQ	*reqp = connected;
   1354 	int	dmstat, is_edma;
   1355 	long	bytes_left, bytes_done;
   1356 
   1357 	is_edma = get_dma_result(reqp, &bytes_left);
   1358 	dmstat  = GET_5380_REG(NCR5380_DMSTAT);
   1359 
   1360 	/*
   1361 	 * Check if the call is sensible and not caused by any spurious
   1362 	 * interrupt.
   1363 	 */
   1364 	if (!is_edma && !(dmstat & (SC_END_DMA|SC_BSY_ERR))
   1365 		     && (dmstat & SC_PHS_MTCH) ) {
   1366 		ncr_tprint(reqp, "dma_ready: spurious call"
   1367 				 "(dm:%x,last_hit: %s)\n",
   1368 #ifdef DBG_PID
   1369 							dmstat, last_hit);
   1370 #else
   1371 							dmstat, "unknown");
   1372 #endif
   1373 		return (0);
   1374 	}
   1375 
   1376 	/*
   1377 	 * Clear all (pending) interrupts.
   1378 	 */
   1379 	scsi_clr_ipend();
   1380 
   1381 	/*
   1382 	 * Update various transfer-pointers/lengths
   1383 	 */
   1384 	bytes_done = reqp->dm_cur->dm_count - bytes_left;
   1385 
   1386 	if ((reqp->dr_flag & DRIVER_BOUNCING) && (PH_IN(reqp->phase))) {
   1387 		/*
   1388 		 * Copy the bytes read until now from the bounce buffer
   1389 		 * to the 'real' destination. Flush the data-cache
   1390 		 * before copying.
   1391 		 */
   1392 		PCIA();
   1393 		bcopy(reqp->bouncerp, reqp->xdata_ptr, bytes_done);
   1394 		reqp->bouncerp += bytes_done;
   1395 	}
   1396 
   1397 	reqp->xdata_ptr  = &reqp->xdata_ptr[bytes_done];	/* XXX */
   1398 	reqp->xdata_len -= bytes_done;				/* XXX */
   1399 	if ((reqp->dm_cur->dm_count -= bytes_done) == 0)
   1400 		reqp->dm_cur++;
   1401 	else reqp->dm_cur->dm_addr += bytes_done;
   1402 
   1403 	if (PH_IN(reqp->phase) && (dmstat & SC_PAR_ERR)) {
   1404 		if (!(ncr5380_no_parchk & (1 << reqp->targ_id)))
   1405 			/* XXX: Should be parity error ???? */
   1406 			reqp->xs->error = XS_DRIVER_STUFFUP;
   1407 	}
   1408 
   1409 	/*
   1410 	 * DMA mode should always be reset even when we will continue with the
   1411 	 * next chain.
   1412 	 */
   1413 	SET_5380_REG(NCR5380_MODE, GET_5380_REG(NCR5380_MODE) & ~SC_M_DMA);
   1414 
   1415 
   1416 	if ((dmstat & SC_BSY_ERR) || !(dmstat & SC_PHS_MTCH)
   1417 		 || (reqp->dm_cur > reqp->dm_last) || (reqp->xs->error)) {
   1418 
   1419 		/*
   1420 		 * Tell interrupt functions DMA mode has ended.
   1421 		 */
   1422 		reqp->dr_flag &= ~DRIVER_IN_DMA;
   1423 
   1424 		/*
   1425 		 * Clear mode and icom
   1426 		 */
   1427 		SET_5380_REG(NCR5380_MODE, IMODE_BASE);
   1428 		SET_5380_REG(NCR5380_ICOM, 0);
   1429 
   1430 		if (dmstat & SC_BSY_ERR) {
   1431 			if (!reqp->xs->error)
   1432 				reqp->xs->error = XS_BUSY;
   1433 			finish_req(reqp);
   1434 			PID("dma_ready1");
   1435 			return (1);
   1436 		}
   1437 
   1438 		if (reqp->xs->error != 0) {
   1439 ncr_tprint(reqp, "dma-ready: code = %d\n", reqp->xs->error); /* LWP */
   1440 			reqp->msgout = MSG_ABORT;
   1441 			SET_5380_REG(NCR5380_ICOM, SC_A_ATN);
   1442 		}
   1443 		PID("dma_ready2");
   1444 		return (1);
   1445 	}
   1446 	return (0);
   1447 }
   1448 #endif /* REAL_DMA */
   1449 
   1450 static int
   1451 check_autosense(reqp, linked)
   1452 SC_REQ	*reqp;
   1453 int	linked;
   1454 {
   1455 	int	sps;
   1456 
   1457 	/*
   1458 	 * If we not executing an auto-sense and the status code
   1459 	 * is request-sense, we automatically issue a request
   1460 	 * sense command.
   1461 	 */
   1462 	PID("cautos1");
   1463 	if (!(reqp->dr_flag & DRIVER_AUTOSEN)) {
   1464 		if (reqp->status == SCSCHKC) {
   1465 			memcpy(&reqp->xcmd, sense_cmd, sizeof(sense_cmd));
   1466 			reqp->xdata_ptr = (u_char *)&reqp->xs->sense;
   1467 			reqp->xdata_len = sizeof(reqp->xs->sense);
   1468 			reqp->dr_flag  |= DRIVER_AUTOSEN;
   1469 			reqp->dr_flag  &= ~DRIVER_DMAOK;
   1470 			if (!linked) {
   1471 				sps = splbio();
   1472 				reqp->next = issue_q;
   1473 				issue_q    = reqp;
   1474 				splx(sps);
   1475 			}
   1476 			else reqp->xcmd.bytes[4] |= 1;
   1477 
   1478 #ifdef DBG_REQ
   1479 			bzero(reqp->xdata_ptr, reqp->xdata_len);
   1480 			if (dbg_target_mask & (1 << reqp->targ_id))
   1481 				show_request(reqp, "AUTO-SENSE");
   1482 #endif
   1483 			PID("cautos2");
   1484 			return (-1);
   1485 		}
   1486 	}
   1487 	else {
   1488 		/*
   1489 		 * An auto-sense has finished
   1490 		 */
   1491 		if ((reqp->status & SCSMASK) != SCSGOOD)
   1492 			reqp->xs->error = XS_DRIVER_STUFFUP; /* SC_E_AUTOSEN; */
   1493 		else reqp->xs->error = XS_SENSE;
   1494 		reqp->status = SCSCHKC;
   1495 	}
   1496 	PID("cautos3");
   1497 	return (0);
   1498 }
   1499 
   1500 static int
   1501 reach_msg_out(sc, len)
   1502 struct ncr_softc *sc;
   1503 u_long		 len;
   1504 {
   1505 	u_char	phase;
   1506 	u_char	data;
   1507 
   1508 	ncr_aprint(sc, "Trying to reach Message-out phase\n");
   1509 	if ((phase = GET_5380_REG(NCR5380_IDSTAT)) & SC_S_REQ)
   1510 		phase = (phase >> 2) & 7;
   1511 	else return (-1);
   1512 	ncr_aprint(sc, "Trying to reach Message-out phase, now: %d\n", phase);
   1513 	if (phase == PH_MSGOUT)
   1514 		return (0);
   1515 
   1516 	SET_5380_REG(NCR5380_TCOM, phase);
   1517 
   1518 	do {
   1519 		if (!wait_req_true())
   1520 			break;
   1521 		if (((GET_5380_REG(NCR5380_IDSTAT) >> 2) & 7) != phase)
   1522 			break;
   1523 		if (PH_IN(phase)) {
   1524 			data = GET_5380_REG(NCR5380_DATA);
   1525 			SET_5380_REG(NCR5380_ICOM, SC_A_ACK | SC_A_ATN);
   1526 		}
   1527 		else {
   1528 			SET_5380_REG(NCR5380_DATA, 0);
   1529 			SET_5380_REG(NCR5380_ICOM, SC_ADTB|SC_A_ACK|SC_A_ATN);
   1530 		}
   1531 		if (!wait_req_false())
   1532 			break;
   1533 		SET_5380_REG(NCR5380_ICOM, SC_A_ATN);
   1534 	} while (--len);
   1535 
   1536 	if ((phase = GET_5380_REG(NCR5380_IDSTAT)) & SC_S_REQ) {
   1537 		phase = (phase >> 2) & 7;
   1538 		if (phase == PH_MSGOUT) {
   1539 			ncr_aprint(sc, "Message-out phase reached.\n");
   1540 			return (0);
   1541 		}
   1542 	}
   1543 	return (-1);
   1544 }
   1545 
   1546 static void
   1547 scsi_reset(sc)
   1548 struct ncr_softc *sc;
   1549 {
   1550 	SC_REQ	*tmp, *next;
   1551 	int	sps;
   1552 
   1553 	ncr_aprint(sc, "Resetting SCSI-bus\n");
   1554 
   1555 	PID("scsi_reset1");
   1556 	sps = splbio();
   1557 	SET_5380_REG(NCR5380_ICOM, SC_A_RST);
   1558 	delay(1);
   1559 	SET_5380_REG(NCR5380_ICOM, 0);
   1560 
   1561 	/*
   1562 	 * None of the jobs in the discon_q will ever be reconnected,
   1563 	 * notify this to the higher level code.
   1564 	 */
   1565 	for (tmp = discon_q; tmp ;) {
   1566 		next = tmp->next;
   1567 		tmp->next = NULL;
   1568 		tmp->xs->error = XS_TIMEOUT;
   1569 		busy &= ~(1 << tmp->targ_id);
   1570 		finish_req(tmp);
   1571 		tmp = next;
   1572 	}
   1573 	discon_q = NULL;
   1574 
   1575 	/*
   1576 	 * The current job will never finish either.
   1577 	 * The problem is that we can't finish the job because an instance
   1578 	 * of main is running on it. Our best guess is that the job is currently
   1579 	 * doing REAL-DMA. In that case 'dma_ready()' should correctly finish
   1580 	 * the job because it detects BSY-loss.
   1581 	 */
   1582 	if (tmp = connected) {
   1583 		if (tmp->dr_flag & DRIVER_IN_DMA) {
   1584 			tmp->xs->error = XS_DRIVER_STUFFUP;
   1585 #ifdef REAL_DMA
   1586 			dma_ready();
   1587 #endif
   1588 		}
   1589 	}
   1590 	splx(sps);
   1591 	PID("scsi_reset2");
   1592 }
   1593 
   1594 /*
   1595  * Check validity of the IRQ set by the 5380. If the interrupt is valid,
   1596  * the appropriate action is carried out (reselection or DMA ready) and
   1597  * INTR_RESEL or INTR_DMA is returned. Otherwise a console notice is written
   1598  * and INTR_SPURIOUS is returned.
   1599  */
   1600 static int
   1601 check_intr(sc)
   1602 struct ncr_softc *sc;
   1603 {
   1604 	SC_REQ	*reqp;
   1605 
   1606 	if ((GET_5380_REG(NCR5380_IDSTAT) & (SC_S_SEL|SC_S_IO))
   1607 							==(SC_S_SEL|SC_S_IO))
   1608 		return (INTR_RESEL);
   1609 	else {
   1610 		if ((reqp = connected) && (reqp->dr_flag & DRIVER_IN_DMA)){
   1611 			reqp->dr_flag &= ~DRIVER_IN_DMA;
   1612 			return (INTR_DMA);
   1613 		}
   1614 	}
   1615 	scsi_clr_ipend();
   1616 	printf("-->");
   1617 	scsi_show();
   1618 	ncr_aprint(sc, "Spurious interrupt.\n");
   1619 	return (INTR_SPURIOUS);
   1620 }
   1621 
   1622 #ifdef REAL_DMA
   1623 /*
   1624  * Check if DMA can be used for this request. This function also builds
   1625  * the dma-chain.
   1626  */
   1627 static int
   1628 scsi_dmaok(reqp)
   1629 SC_REQ	*reqp;
   1630 {
   1631 	u_long			phy_buf;
   1632 	u_long			phy_len;
   1633 	void			*req_addr;
   1634 	u_long			req_len;
   1635 	struct dma_chain	*dm;
   1636 
   1637 	/*
   1638 	 * Initialize locals and requests' DMA-chain.
   1639 	 */
   1640 	req_len        = reqp->xdata_len;
   1641 	req_addr       = (void*)reqp->xdata_ptr;
   1642 	dm             = reqp->dm_cur = reqp->dm_last = reqp->dm_chain;
   1643 	dm->dm_count   = dm->dm_addr = 0;
   1644 	reqp->dr_flag &= ~DRIVER_BOUNCING;
   1645 
   1646 	/*
   1647 	 * Do not accept zero length DMA.
   1648 	 */
   1649 	if (req_len == 0)
   1650 		return (0);
   1651 
   1652 	/*
   1653 	 * LWP: I think that this restriction is not strictly nessecary.
   1654 	 */
   1655 	if ((req_len & 0x1) || ((u_int)req_addr & 0x3))
   1656 		return (0);
   1657 
   1658 	/*
   1659 	 * Build the DMA-chain.
   1660 	 */
   1661 	dm->dm_addr = phy_buf = kvtop(req_addr);
   1662 	while (req_len) {
   1663 		if (req_len < (phy_len = NBPG - ((u_long)req_addr & PGOFSET)))
   1664 			phy_len = req_len;
   1665 
   1666 		req_addr     += phy_len;
   1667 		req_len      -= phy_len;
   1668 		dm->dm_count += phy_len;
   1669 
   1670 		if (req_len) {
   1671 			u_long	tmp = kvtop(req_addr);
   1672 
   1673 			if ((phy_buf + phy_len) != tmp) {
   1674 			    if (wrong_dma_range(reqp, dm)) {
   1675 				if (reqp->dr_flag & DRIVER_BOUNCING)
   1676 					goto bounceit;
   1677 				return (0);
   1678 			    }
   1679 
   1680 			    if (++dm >= &reqp->dm_chain[MAXDMAIO]) {
   1681 				ncr_tprint(reqp,"dmaok: DMA chain too long!\n");
   1682 				return (0);
   1683 			    }
   1684 			    dm->dm_count = 0;
   1685 			    dm->dm_addr  = tmp;
   1686 			}
   1687 			phy_buf = tmp;
   1688 		}
   1689 	}
   1690         if (wrong_dma_range(reqp, dm)) {
   1691 		if (reqp->dr_flag & DRIVER_BOUNCING)
   1692 			goto bounceit;
   1693 		return (0);
   1694 	}
   1695 	reqp->dm_last = dm;
   1696 	return (1);
   1697 
   1698 bounceit:
   1699 	if ((reqp->bounceb = alloc_bounceb(reqp->xdata_len)) == NULL) {
   1700 		/*
   1701 		 * If we can't get a bounce buffer, forget DMA
   1702 		 */
   1703 		reqp->dr_flag &= ~DRIVER_BOUNCING;
   1704 		return(0);
   1705 	}
   1706 	/*
   1707 	 * Initialize a single DMA-range containing the bounced request
   1708 	 */
   1709 	dm = reqp->dm_cur = reqp->dm_last = reqp->dm_chain;
   1710 	dm->dm_addr    = kvtop(reqp->bounceb);
   1711 	dm->dm_count   = reqp->xdata_len;
   1712 	reqp->bouncerp = reqp->bounceb;
   1713 
   1714 	return (1);
   1715 }
   1716 #endif /* REAL_DMA */
   1717 
   1718 static void
   1719 run_main(sc)
   1720 struct ncr_softc *sc;
   1721 {
   1722 	int	sps = splbio();
   1723 
   1724 	if (!main_running) {
   1725 		/*
   1726 		 * If shared resources are required, claim them
   1727 		 * before entering 'scsi_main'. If we can't get them
   1728 		 * now, assume 'run_main' will be called when the resource
   1729 		 * becomes available.
   1730 		 */
   1731 		if (!claimed_dma()) {
   1732 			splx(sps);
   1733 			return;
   1734 		}
   1735 		main_running = 1;
   1736 		splx(sps);
   1737 		scsi_main(sc);
   1738 	}
   1739 	else splx(sps);
   1740 }
   1741 
   1742 /*
   1743  * Prefix message with full target info.
   1744  */
   1745 static void
   1746 ncr_tprint(SC_REQ *reqp, char *fmt, ...)
   1747 {
   1748 	va_list	ap;
   1749 
   1750 	va_start(ap, fmt);
   1751 	sc_print_addr(reqp->xs->sc_link);
   1752 	printf("%r", fmt, ap);
   1753 	va_end(ap);
   1754 }
   1755 
   1756 /*
   1757  * Prefix message with adapter info.
   1758  */
   1759 static void
   1760 ncr_aprint(struct ncr_softc *sc, char *fmt, ...)
   1761 {
   1762 	va_list	ap;
   1763 
   1764 	va_start(ap, fmt);
   1765 	printf("%s : %r", sc->sc_dev.dv_xname, fmt, ap);
   1766 	va_end(ap);
   1767 }
   1768 /****************************************************************************
   1769  *		Start Debugging Functions				    *
   1770  ****************************************************************************/
   1771 static void
   1772 show_data_sense(xs)
   1773 struct scsi_xfer	*xs;
   1774 {
   1775 	u_char	*p1, *p2;
   1776 	int	i;
   1777 	int	sz;
   1778 
   1779 	p1 = (u_char *) xs->cmd;
   1780 	p2 = (u_char *)&xs->sense;
   1781 	if(*p2 == 0)
   1782 		return;	/* No(n)sense */
   1783 	printf("cmd[%d,%d]: ", xs->cmdlen, sz = command_size(*p1));
   1784 	for (i = 0; i < sz; i++)
   1785 		printf("%x ", p1[i]);
   1786 	printf("\nsense: ");
   1787 	for (i = 0; i < sizeof(xs->sense); i++)
   1788 		printf("%x ", p2[i]);
   1789 	printf("\n");
   1790 }
   1791 
   1792 static void
   1793 show_request(reqp, qtxt)
   1794 SC_REQ	*reqp;
   1795 char	*qtxt;
   1796 {
   1797 	printf("REQ-%s: %d %x[%d] cmd[0]=%x S=%x M=%x R=%x resid=%d %s\n",
   1798 			qtxt, reqp->targ_id, reqp->xdata_ptr, reqp->xdata_len,
   1799 			reqp->xcmd.opcode, reqp->status, reqp->message,
   1800 			reqp->xs->error, reqp->xs->resid, reqp->link ? "L":"");
   1801 	if (reqp->status == SCSCHKC)
   1802 		show_data_sense(reqp->xs);
   1803 }
   1804 
   1805 static char *sig_names[] = {
   1806 	"PAR", "SEL", "I/O", "C/D", "MSG", "REQ", "BSY", "RST",
   1807 	"ACK", "ATN", "LBSY", "PMATCH", "IRQ", "EPAR", "DREQ", "EDMA"
   1808 };
   1809 
   1810 static void
   1811 show_signals(dmstat, idstat)
   1812 u_char	dmstat, idstat;
   1813 {
   1814 	u_short	tmp, mask;
   1815 	int	i, j, need_pipe;
   1816 
   1817 	tmp = idstat | ((dmstat & 3) << 8);
   1818 	printf("Bus signals (%02x/%02x): ", idstat, dmstat & 3);
   1819 	for (mask = 1, j = need_pipe = 0; mask <= tmp; mask <<= 1, j++) {
   1820 		if (tmp & mask)
   1821 			printf("%s%s", need_pipe++ ? "|" : "", sig_names[j]);
   1822 	}
   1823 	printf("\nDma status (%02x): ", dmstat);
   1824 	for (mask = 4, j = 10, need_pipe = 0; mask <= dmstat; mask <<= 1, j++) {
   1825 		if (dmstat & mask)
   1826 			printf("%s%s", need_pipe++ ? "|" : "", sig_names[j]);
   1827 	}
   1828 	printf("\n");
   1829 }
   1830 
   1831 scsi_show()
   1832 {
   1833 	SC_REQ	*tmp;
   1834 	int	sps = splhigh();
   1835 	u_char	idstat, dmstat;
   1836 
   1837 #ifndef DBG_PID
   1838 	#define	last_hit	""
   1839 	#define	olast_hit	""
   1840 #endif
   1841 
   1842 	for (tmp = issue_q; tmp; tmp = tmp->next)
   1843 		show_request(tmp, "ISSUED");
   1844 	for (tmp = discon_q; tmp; tmp = tmp->next)
   1845 		show_request(tmp, "DISCONNECTED");
   1846 	if (connected)
   1847 		show_request(connected, "CONNECTED");
   1848 	idstat = GET_5380_REG(NCR5380_IDSTAT);
   1849 	dmstat = GET_5380_REG(NCR5380_DMSTAT);
   1850 	show_signals(dmstat, idstat);
   1851 	if (connected)
   1852 		printf("phase = %d, ", connected->phase);
   1853 	printf("busy:%x, last_hit:%s, olast_hit:%s spl:%04x\n", busy,
   1854 						last_hit, olast_hit, sps);
   1855 
   1856 	splx(sps);
   1857 }
   1858