Home | History | Annotate | Line # | Download | only in scsipi
scsipi_base.c revision 1.26.2.9
      1 /*	$NetBSD: scsipi_base.c,v 1.26.2.9 2001/01/15 09:22:12 bouyer Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 1999, 2000 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Charles M. Hannum; by Jason R. Thorpe of the Numerical Aerospace
      9  * Simulation Facility, NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *        This product includes software developed by the NetBSD
     22  *        Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 #include "opt_scsi.h"
     41 
     42 #include <sys/types.h>
     43 #include <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/kernel.h>
     46 #include <sys/buf.h>
     47 #include <sys/uio.h>
     48 #include <sys/malloc.h>
     49 #include <sys/pool.h>
     50 #include <sys/errno.h>
     51 #include <sys/device.h>
     52 #include <sys/proc.h>
     53 #include <sys/kthread.h>
     54 
     55 #include <dev/scsipi/scsipi_all.h>
     56 #include <dev/scsipi/scsipi_disk.h>
     57 #include <dev/scsipi/scsipiconf.h>
     58 #include <dev/scsipi/scsipi_base.h>
     59 
     60 #include <dev/scsipi/scsi_all.h>
     61 #include <dev/scsipi/scsi_message.h>
     62 
     63 int	scsipi_complete __P((struct scsipi_xfer *));
     64 void	scsipi_request_sense __P((struct scsipi_xfer *));
     65 int	scsipi_enqueue __P((struct scsipi_xfer *));
     66 void	scsipi_run_queue __P((struct scsipi_channel *chan));
     67 
     68 void	scsipi_completion_thread __P((void *));
     69 
     70 void	scsipi_get_tag __P((struct scsipi_xfer *));
     71 void	scsipi_put_tag __P((struct scsipi_xfer *));
     72 
     73 int	scsipi_get_resource __P((struct scsipi_channel *));
     74 void	scsipi_put_resource __P((struct scsipi_channel *));
     75 __inline int scsipi_grow_resources __P((struct scsipi_channel *));
     76 
     77 void	scsipi_async_event_max_openings __P((struct scsipi_channel *,
     78 	    struct scsipi_max_openings *));
     79 void	scsipi_async_event_xfer_mode __P((struct scsipi_channel *,
     80 	    struct scsipi_xfer_mode *));
     81 void	scsipi_async_event_channel_reset __P((struct scsipi_channel *));
     82 
     83 struct pool scsipi_xfer_pool;
     84 
     85 /*
     86  * scsipi_init:
     87  *
     88  *	Called when a scsibus or atapibus is attached to the system
     89  *	to initialize shared data structures.
     90  */
     91 void
     92 scsipi_init()
     93 {
     94 	static int scsipi_init_done;
     95 
     96 	if (scsipi_init_done)
     97 		return;
     98 	scsipi_init_done = 1;
     99 
    100 	/* Initialize the scsipi_xfer pool. */
    101 	pool_init(&scsipi_xfer_pool, sizeof(struct scsipi_xfer), 0,
    102 	    0, 0, "scxspl", 0, NULL, NULL, M_DEVBUF);
    103 }
    104 
    105 /*
    106  * scsipi_channel_init:
    107  *
    108  *	Initialize a scsipi_channel when it is attached.
    109  */
    110 void
    111 scsipi_channel_init(chan)
    112 	struct scsipi_channel *chan;
    113 {
    114 	size_t nbytes;
    115 	int i;
    116 
    117 	/* Initialize shared data. */
    118 	scsipi_init();
    119 
    120 	/* Initialize the queues. */
    121 	TAILQ_INIT(&chan->chan_queue);
    122 	TAILQ_INIT(&chan->chan_complete);
    123 
    124 	nbytes = chan->chan_ntargets * sizeof(struct scsipi_link **);
    125 	chan->chan_periphs = malloc(nbytes, M_DEVBUF, M_WAITOK);
    126 
    127 	nbytes = chan->chan_nluns * sizeof(struct scsipi_periph *);
    128 	for (i = 0; i < chan->chan_ntargets; i++) {
    129 		chan->chan_periphs[i] = malloc(nbytes, M_DEVBUF, M_WAITOK);
    130 		memset(chan->chan_periphs[i], 0, nbytes);
    131 	}
    132 
    133 	/*
    134 	 * Create the asynchronous completion thread.
    135 	 */
    136 	kthread_create(scsipi_create_completion_thread, chan);
    137 }
    138 
    139 /*
    140  * scsipi_channel_shutdown:
    141  *
    142  *	Shutdown a scsipi_channel.
    143  */
    144 void
    145 scsipi_channel_shutdown(chan)
    146 	struct scsipi_channel *chan;
    147 {
    148 
    149 	/*
    150 	 * Shut down the completion thread.
    151 	 */
    152 	chan->chan_flags |= SCSIPI_CHAN_SHUTDOWN;
    153 	wakeup(&chan->chan_complete);
    154 
    155 	/*
    156 	 * Now wait for the thread to exit.
    157 	 */
    158 	while (chan->chan_thread != NULL)
    159 		(void) tsleep(&chan->chan_thread, PRIBIO, "scshut", 0);
    160 }
    161 
    162 /*
    163  * scsipi_insert_periph:
    164  *
    165  *	Insert a periph into the channel.
    166  */
    167 void
    168 scsipi_insert_periph(chan, periph)
    169 	struct scsipi_channel *chan;
    170 	struct scsipi_periph *periph;
    171 {
    172 	int s;
    173 
    174 	s = splbio();
    175 	chan->chan_periphs[periph->periph_target][periph->periph_lun] = periph;
    176 	splx(s);
    177 }
    178 
    179 /*
    180  * scsipi_remove_periph:
    181  *
    182  *	Remove a periph from the channel.
    183  */
    184 void
    185 scsipi_remove_periph(chan, periph)
    186 	struct scsipi_channel *chan;
    187 	struct scsipi_periph *periph;
    188 {
    189 	int s;
    190 
    191 	s = splbio();
    192 	chan->chan_periphs[periph->periph_target][periph->periph_lun] = NULL;
    193 	splx(s);
    194 }
    195 
    196 /*
    197  * scsipi_lookup_periph:
    198  *
    199  *	Lookup a periph on the specified channel.
    200  */
    201 struct scsipi_periph *
    202 scsipi_lookup_periph(chan, target, lun)
    203 	struct scsipi_channel *chan;
    204 	int target, lun;
    205 {
    206 	struct scsipi_periph *periph;
    207 	int s;
    208 
    209 	if (target >= chan->chan_ntargets ||
    210 	    lun >= chan->chan_nluns)
    211 		return (NULL);
    212 
    213 	s = splbio();
    214 	periph = chan->chan_periphs[target][lun];
    215 	splx(s);
    216 
    217 	return (periph);
    218 }
    219 
    220 /*
    221  * scsipi_get_resource:
    222  *
    223  *	Allocate a single xfer `resource' from the channel.
    224  *
    225  *	NOTE: Must be called at splbio().
    226  */
    227 int
    228 scsipi_get_resource(chan)
    229 	struct scsipi_channel *chan;
    230 {
    231 	struct scsipi_adapter *adapt = chan->chan_adapter;
    232 
    233 	if (chan->chan_flags & SCSIPI_CHAN_OPENINGS) {
    234 		if (chan->chan_openings > 0) {
    235 			chan->chan_openings--;
    236 			return (1);
    237 		}
    238 		return (0);
    239 	}
    240 
    241 	if (adapt->adapt_openings > 0) {
    242 		adapt->adapt_openings--;
    243 		return (1);
    244 	}
    245 	return (0);
    246 }
    247 
    248 /*
    249  * scsipi_grow_resources:
    250  *
    251  *	Attempt to grow resources for a channel.  If this succeeds,
    252  *	we allocate one for our caller.
    253  *
    254  *	NOTE: Must be called at splbio().
    255  */
    256 __inline int
    257 scsipi_grow_resources(chan)
    258 	struct scsipi_channel *chan;
    259 {
    260 
    261 	if (chan->chan_flags & SCSIPI_CHAN_CANGROW) {
    262 		scsipi_adapter_request(chan, ADAPTER_REQ_GROW_RESOURCES, NULL);
    263 		return (scsipi_get_resource(chan));
    264 	}
    265 
    266 	return (0);
    267 }
    268 
    269 /*
    270  * scsipi_put_resource:
    271  *
    272  *	Free a single xfer `resource' to the channel.
    273  *
    274  *	NOTE: Must be called at splbio().
    275  */
    276 void
    277 scsipi_put_resource(chan)
    278 	struct scsipi_channel *chan;
    279 {
    280 	struct scsipi_adapter *adapt = chan->chan_adapter;
    281 
    282 	if (chan->chan_flags & SCSIPI_CHAN_OPENINGS)
    283 		chan->chan_openings++;
    284 	else
    285 		adapt->adapt_openings++;
    286 }
    287 
    288 /*
    289  * scsipi_get_tag:
    290  *
    291  *	Get a tag ID for the specified xfer.
    292  *
    293  *	NOTE: Must be called at splbio().
    294  */
    295 void
    296 scsipi_get_tag(xs)
    297 	struct scsipi_xfer *xs;
    298 {
    299 	struct scsipi_periph *periph = xs->xs_periph;
    300 	int word, bit, tag;
    301 
    302 	for (word = 0; word < PERIPH_NTAGWORDS; word++) {
    303 		bit = ffs(periph->periph_freetags[word]);
    304 		if (bit != 0)
    305 			break;
    306 	}
    307 #ifdef DIAGNOSTIC
    308 	if (word == PERIPH_NTAGWORDS) {
    309 		scsipi_printaddr(periph);
    310 		printf("no free tags\n");
    311 		panic("scsipi_get_tag");
    312 	}
    313 #endif
    314 
    315 	bit -= 1;
    316 	periph->periph_freetags[word] &= ~(1 << bit);
    317 	tag = (word << 5) | bit;
    318 
    319 	/* XXX Should eventually disallow this completely. */
    320 	if (tag >= periph->periph_openings) {
    321 		scsipi_printaddr(periph);
    322 		printf("WARNING: tag %d greater than available openings %d\n",
    323 		    tag, periph->periph_openings);
    324 	}
    325 
    326 	xs->xs_tag_id = tag;
    327 }
    328 
    329 /*
    330  * scsipi_put_tag:
    331  *
    332  *	Put the tag ID for the specified xfer back into the pool.
    333  *
    334  *	NOTE: Must be called at splbio().
    335  */
    336 void
    337 scsipi_put_tag(xs)
    338 	struct scsipi_xfer *xs;
    339 {
    340 	struct scsipi_periph *periph = xs->xs_periph;
    341 	int word, bit;
    342 
    343 	word = xs->xs_tag_id >> 5;
    344 	bit = xs->xs_tag_id & 0x1f;
    345 
    346 	periph->periph_freetags[word] |= (1 << bit);
    347 }
    348 
    349 /*
    350  * scsipi_get_xs:
    351  *
    352  *	Allocate an xfer descriptor and associate it with the
    353  *	specified peripherial.  If the peripherial has no more
    354  *	available command openings, we either block waiting for
    355  *	one to become available, or fail.
    356  */
    357 struct scsipi_xfer *
    358 scsipi_get_xs(periph, flags)
    359 	struct scsipi_periph *periph;
    360 	int flags;
    361 {
    362 	struct scsipi_xfer *xs;
    363 	int s;
    364 
    365 	SC_DEBUG(periph, SCSIPI_DB3, ("scsipi_get_xs\n"));
    366 
    367 	/*
    368 	 * If we're cold, make sure we poll.
    369 	 */
    370 	if (cold)
    371 		flags |= XS_CTL_NOSLEEP | XS_CTL_POLL;
    372 
    373 #ifdef DIAGNOSTIC
    374 	/*
    375 	 * URGENT commands can never be ASYNC.
    376 	 */
    377 	if ((flags & (XS_CTL_URGENT|XS_CTL_ASYNC)) ==
    378 	    (XS_CTL_URGENT|XS_CTL_ASYNC)) {
    379 		scsipi_printaddr(periph);
    380 		printf("URGENT and ASYNC\n");
    381 		panic("scsipi_get_xs");
    382 	}
    383 #endif
    384 
    385 	s = splbio();
    386 	/*
    387 	 * Wait for a command opening to become available.  Rules:
    388 	 *
    389 	 *	- All xfers must wait for an available opening.
    390 	 *	  Exception: URGENT xfers can proceed when
    391 	 *	  active == openings, because we use the opening
    392 	 *	  of the command we're recovering for.
    393 	 *	- if the periph has sense pending, only URGENT & REQSENSE
    394 	 *	  xfers may proceed.
    395 	 *
    396 	 *	- If the periph is recovering, only URGENT xfers may
    397 	 *	  proceed.
    398 	 *
    399 	 *	- If the periph is currently executing a recovery
    400 	 *	  command, URGENT commands must block, because only
    401 	 *	  one recovery command can execute at a time.
    402 	 */
    403 	for (;;) {
    404 		if (flags & XS_CTL_URGENT) {
    405 			if (periph->periph_active > periph->periph_openings)
    406 				goto wait_for_opening;
    407 			if (periph->periph_flags & PERIPH_SENSE) {
    408 				if ((flags & XS_CTL_REQSENSE) == 0)
    409 					goto wait_for_opening;
    410 			} else {
    411 				if ((periph->periph_flags &
    412 				    PERIPH_RECOVERY_ACTIVE) != 0)
    413 					goto wait_for_opening;
    414 				periph->periph_flags |= PERIPH_RECOVERY_ACTIVE;
    415 			}
    416 			break;
    417 		}
    418 		if (periph->periph_active >= periph->periph_openings ||
    419 		    (periph->periph_flags & PERIPH_RECOVERING) != 0)
    420 			goto wait_for_opening;
    421 		periph->periph_active++;
    422 		break;
    423 
    424  wait_for_opening:
    425 		if (flags & XS_CTL_NOSLEEP) {
    426 			splx(s);
    427 			return (NULL);
    428 		}
    429 		SC_DEBUG(periph, SCSIPI_DB3, ("sleeping\n"));
    430 		periph->periph_flags |= PERIPH_WAITING;
    431 		(void) tsleep(periph, PRIBIO, "getxs", 0);
    432 	}
    433 	SC_DEBUG(periph, SCSIPI_DB3, ("calling pool_get\n"));
    434 	xs = pool_get(&scsipi_xfer_pool,
    435 	    ((flags & XS_CTL_NOSLEEP) != 0 ? PR_NOWAIT : PR_WAITOK));
    436 	if (xs == NULL) {
    437 		if (flags & XS_CTL_URGENT) {
    438 			if ((flags & XS_CTL_REQSENSE) == 0)
    439 				periph->periph_flags &= ~PERIPH_RECOVERY_ACTIVE;
    440 		} else
    441 			periph->periph_active--;
    442 		scsipi_printaddr(periph);
    443 		printf("unable to allocate %sscsipi_xfer\n",
    444 		    (flags & XS_CTL_URGENT) ? "URGENT " : "");
    445 	}
    446 	splx(s);
    447 
    448 	SC_DEBUG(periph, SCSIPI_DB3, ("returning\n"));
    449 
    450 	if (xs != NULL) {
    451 		callout_init(&xs->xs_callout);
    452 		memset(xs, 0, sizeof(*xs));
    453 		xs->xs_periph = periph;
    454 		xs->xs_control = flags;
    455 		xs->xs_status = 0;
    456 		s = splbio();
    457 		TAILQ_INSERT_TAIL(&periph->periph_xferq, xs, device_q);
    458 		splx(s);
    459 	}
    460 	return (xs);
    461 }
    462 
    463 /*
    464  * scsipi_put_xs:
    465  *
    466  *	Release an xfer descriptor, decreasing the outstanding command
    467  *	count for the peripherial.  If there is a thread waiting for
    468  *	an opening, wake it up.  If not, kick any queued I/O the
    469  *	peripherial may have.
    470  *
    471  *	NOTE: Must be called at splbio().
    472  */
    473 void
    474 scsipi_put_xs(xs)
    475 	struct scsipi_xfer *xs;
    476 {
    477 	struct scsipi_periph *periph = xs->xs_periph;
    478 	int flags = xs->xs_control;
    479 
    480 	SC_DEBUG(periph, SCSIPI_DB3, ("scsipi_free_xs\n"));
    481 
    482 	TAILQ_REMOVE(&periph->periph_xferq, xs, device_q);
    483 	pool_put(&scsipi_xfer_pool, xs);
    484 
    485 #ifdef DIAGNOSTIC
    486 	if ((periph->periph_flags & PERIPH_RECOVERY_ACTIVE) != 0 &&
    487 	    periph->periph_active == 0) {
    488 		scsipi_printaddr(periph);
    489 		printf("recovery without a command to recovery for\n");
    490 		panic("scsipi_put_xs");
    491 	}
    492 #endif
    493 
    494 	if (flags & XS_CTL_URGENT) {
    495 		if ((flags & XS_CTL_REQSENSE) == 0)
    496 			periph->periph_flags &= ~PERIPH_RECOVERY_ACTIVE;
    497 	} else
    498 		periph->periph_active--;
    499 	if (periph->periph_active == 0 &&
    500 	    (periph->periph_flags & PERIPH_WAITDRAIN) != 0) {
    501 		periph->periph_flags &= ~PERIPH_WAITDRAIN;
    502 		wakeup(&periph->periph_active);
    503 	}
    504 
    505 	if (periph->periph_flags & PERIPH_WAITING) {
    506 		periph->periph_flags &= ~PERIPH_WAITING;
    507 		wakeup(periph);
    508 	} else {
    509 		if (periph->periph_switch->psw_start != NULL) {
    510 			SC_DEBUG(periph, SCSIPI_DB2,
    511 			    ("calling private start()\n"));
    512 			(*periph->periph_switch->psw_start)(periph);
    513 		}
    514 	}
    515 }
    516 
    517 /*
    518  * scsipi_channel_freeze:
    519  *
    520  *	Freeze a channel's xfer queue.
    521  */
    522 void
    523 scsipi_channel_freeze(chan, count)
    524 	struct scsipi_channel *chan;
    525 	int count;
    526 {
    527 	int s;
    528 
    529 	s = splbio();
    530 	chan->chan_qfreeze += count;
    531 	splx(s);
    532 }
    533 
    534 /*
    535  * scsipi_channel_thaw:
    536  *
    537  *	Thaw a channel's xfer queue.
    538  */
    539 void
    540 scsipi_channel_thaw(chan, count)
    541 	struct scsipi_channel *chan;
    542 	int count;
    543 {
    544 	int s;
    545 
    546 	s = splbio();
    547 	chan->chan_qfreeze -= count;
    548 	splx(s);
    549 }
    550 
    551 /*
    552  * scsipi_channel_timed_thaw:
    553  *
    554  *	Thaw a channel after some time has expired.
    555  */
    556 void
    557 scsipi_channel_timed_thaw(arg)
    558 	void *arg;
    559 {
    560 	struct scsipi_channel *chan = arg;
    561 
    562 	scsipi_channel_thaw(chan, 1);
    563 
    564 	/*
    565 	 * Kick the channel's queue here.  Note, we're running in
    566 	 * interrupt context (softclock), so the adapter driver
    567 	 * had better not sleep.
    568 	 */
    569 	scsipi_run_queue(chan);
    570 }
    571 
    572 /*
    573  * scsipi_periph_freeze:
    574  *
    575  *	Freeze a device's xfer queue.
    576  */
    577 void
    578 scsipi_periph_freeze(periph, count)
    579 	struct scsipi_periph *periph;
    580 	int count;
    581 {
    582 	int s;
    583 
    584 	s = splbio();
    585 	periph->periph_qfreeze += count;
    586 	splx(s);
    587 }
    588 
    589 /*
    590  * scsipi_periph_thaw:
    591  *
    592  *	Thaw a device's xfer queue.
    593  */
    594 void
    595 scsipi_periph_thaw(periph, count)
    596 	struct scsipi_periph *periph;
    597 	int count;
    598 {
    599 	int s;
    600 
    601 	s = splbio();
    602 	periph->periph_qfreeze -= count;
    603 	if (periph->periph_qfreeze == 0 &&
    604 	    (periph->periph_flags & PERIPH_WAITING) != 0)
    605 		wakeup(periph);
    606 	splx(s);
    607 }
    608 
    609 /*
    610  * scsipi_periph_timed_thaw:
    611  *
    612  *	Thaw a device after some time has expired.
    613  */
    614 void
    615 scsipi_periph_timed_thaw(arg)
    616 	void *arg;
    617 {
    618 	struct scsipi_periph *periph = arg;
    619 
    620 	callout_stop(&periph->periph_callout);
    621 	scsipi_periph_thaw(periph, 1);
    622 
    623 	/*
    624 	 * Kick the channel's queue here.  Note, we're running in
    625 	 * interrupt context (softclock), so the adapter driver
    626 	 * had better not sleep.
    627 	 */
    628 	scsipi_run_queue(periph->periph_channel);
    629 }
    630 
    631 /*
    632  * scsipi_wait_drain:
    633  *
    634  *	Wait for a periph's pending xfers to drain.
    635  */
    636 void
    637 scsipi_wait_drain(periph)
    638 	struct scsipi_periph *periph;
    639 {
    640 	int s;
    641 
    642 	s = splbio();
    643 	while (periph->periph_active != 0) {
    644 		periph->periph_flags |= PERIPH_WAITDRAIN;
    645 		(void) tsleep(&periph->periph_active, PRIBIO, "sxdrn", 0);
    646 	}
    647 	splx(s);
    648 }
    649 
    650 /*
    651  * scsipi_kill_pending:
    652  *
    653  *	Kill off all pending xfers for a periph.
    654  *
    655  *	NOTE: Must be called at splbio().
    656  */
    657 void
    658 scsipi_kill_pending(periph)
    659 	struct scsipi_periph *periph;
    660 {
    661 
    662 	(*periph->periph_channel->chan_bustype->bustype_kill_pending)(periph);
    663 #ifdef DIAGNOSTIC
    664 	if (TAILQ_FIRST(&periph->periph_xferq) != NULL)
    665 		panic("scsipi_kill_pending");
    666 #endif
    667 	scsipi_wait_drain(periph);
    668 }
    669 
    670 /*
    671  * scsipi_interpret_sense:
    672  *
    673  *	Look at the returned sense and act on the error, determining
    674  *	the unix error number to pass back.  (0 = report no error)
    675  *
    676  *	NOTE: If we return ERESTART, we are expected to haved
    677  *	thawed the device!
    678  *
    679  *	THIS IS THE DEFAULT ERROR HANDLER FOR SCSI DEVICES.
    680  */
    681 int
    682 scsipi_interpret_sense(xs)
    683 	struct scsipi_xfer *xs;
    684 {
    685 	struct scsipi_sense_data *sense;
    686 	struct scsipi_periph *periph = xs->xs_periph;
    687 	u_int8_t key;
    688 	u_int32_t info;
    689 	int error;
    690 #ifndef	SCSIVERBOSE
    691 	static char *error_mes[] = {
    692 		"soft error (corrected)",
    693 		"not ready", "medium error",
    694 		"non-media hardware failure", "illegal request",
    695 		"unit attention", "readonly device",
    696 		"no data found", "vendor unique",
    697 		"copy aborted", "command aborted",
    698 		"search returned equal", "volume overflow",
    699 		"verify miscompare", "unknown error key"
    700 	};
    701 #endif
    702 
    703 	sense = &xs->sense.scsi_sense;
    704 #ifdef SCSIPI_DEBUG
    705 	if (periph->periph_flags & SCSIPI_DB1) {
    706 		int count;
    707 		scsipi_printaddr(periph);
    708 		printf(" sense debug information:\n");
    709 		printf("\tcode 0x%x valid 0x%x\n",
    710 			sense->error_code & SSD_ERRCODE,
    711 			sense->error_code & SSD_ERRCODE_VALID ? 1 : 0);
    712 		printf("\tseg 0x%x key 0x%x ili 0x%x eom 0x%x fmark 0x%x\n",
    713 			sense->segment,
    714 			sense->flags & SSD_KEY,
    715 			sense->flags & SSD_ILI ? 1 : 0,
    716 			sense->flags & SSD_EOM ? 1 : 0,
    717 			sense->flags & SSD_FILEMARK ? 1 : 0);
    718 		printf("\ninfo: 0x%x 0x%x 0x%x 0x%x followed by %d "
    719 			"extra bytes\n",
    720 			sense->info[0],
    721 			sense->info[1],
    722 			sense->info[2],
    723 			sense->info[3],
    724 			sense->extra_len);
    725 		printf("\textra: ");
    726 		for (count = 0; count < ADD_BYTES_LIM(sense); count++)
    727 			printf("0x%x ", sense->cmd_spec_info[count]);
    728 		printf("\n");
    729 	}
    730 #endif
    731 
    732 	/*
    733 	 * If the periph has it's own error handler, call it first.
    734 	 * If it returns a legit error value, return that, otherwise
    735 	 * it wants us to continue with normal error processing.
    736 	 */
    737 	if (periph->periph_switch->psw_error != NULL) {
    738 		SC_DEBUG(periph, SCSIPI_DB2,
    739 		    ("calling private err_handler()\n"));
    740 		error = (*periph->periph_switch->psw_error)(xs);
    741 		if (error != EJUSTRETURN)
    742 			return (error);
    743 	}
    744 	/* otherwise use the default */
    745 	switch (sense->error_code & SSD_ERRCODE) {
    746 		/*
    747 		 * If it's code 70, use the extended stuff and
    748 		 * interpret the key
    749 		 */
    750 	case 0x71:		/* delayed error */
    751 		scsipi_printaddr(periph);
    752 		key = sense->flags & SSD_KEY;
    753 		printf(" DEFERRED ERROR, key = 0x%x\n", key);
    754 		/* FALLTHROUGH */
    755 	case 0x70:
    756 		if ((sense->error_code & SSD_ERRCODE_VALID) != 0)
    757 			info = _4btol(sense->info);
    758 		else
    759 			info = 0;
    760 		key = sense->flags & SSD_KEY;
    761 
    762 		switch (key) {
    763 		case SKEY_NO_SENSE:
    764 		case SKEY_RECOVERED_ERROR:
    765 			if (xs->resid == xs->datalen && xs->datalen) {
    766 				/*
    767 				 * Why is this here?
    768 				 */
    769 				xs->resid = 0;	/* not short read */
    770 			}
    771 		case SKEY_EQUAL:
    772 			error = 0;
    773 			break;
    774 		case SKEY_NOT_READY:
    775 			if ((periph->periph_flags & PERIPH_REMOVABLE) != 0)
    776 				periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    777 			if ((xs->xs_control & XS_CTL_IGNORE_NOT_READY) != 0)
    778 				return (0);
    779 			if (sense->add_sense_code == 0x3A &&
    780 			    sense->add_sense_code_qual == 0x00)
    781 				error = ENODEV; /* Medium not present */
    782 			else
    783 				error = EIO;
    784 			if ((xs->xs_control & XS_CTL_SILENT) != 0)
    785 				return (error);
    786 			break;
    787 		case SKEY_ILLEGAL_REQUEST:
    788 			if ((xs->xs_control &
    789 			     XS_CTL_IGNORE_ILLEGAL_REQUEST) != 0)
    790 				return (0);
    791 			/*
    792 			 * Handle the case where a device reports
    793 			 * Logical Unit Not Supported during discovery.
    794 			 */
    795 			if ((xs->xs_control & XS_CTL_DISCOVERY) != 0 &&
    796 			    sense->add_sense_code == 0x25 &&
    797 			    sense->add_sense_code_qual == 0x00)
    798 				return (EINVAL);
    799 			if ((xs->xs_control & XS_CTL_SILENT) != 0)
    800 				return (EIO);
    801 			error = EINVAL;
    802 			break;
    803 		case SKEY_UNIT_ATTENTION:
    804 			if (sense->add_sense_code == 0x29 &&
    805 			    sense->add_sense_code_qual == 0x00) {
    806 				/* device or bus reset */
    807 				return (ERESTART);
    808 			}
    809 			if ((periph->periph_flags & PERIPH_REMOVABLE) != 0)
    810 				periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    811 			if ((xs->xs_control &
    812 			     XS_CTL_IGNORE_MEDIA_CHANGE) != 0 ||
    813 				/* XXX Should reupload any transient state. */
    814 				(periph->periph_flags &
    815 				 PERIPH_REMOVABLE) == 0) {
    816 				return (ERESTART);
    817 			}
    818 			if ((xs->xs_control & XS_CTL_SILENT) != 0)
    819 				return (EIO);
    820 			error = EIO;
    821 			break;
    822 		case SKEY_WRITE_PROTECT:
    823 			error = EROFS;
    824 			break;
    825 		case SKEY_BLANK_CHECK:
    826 			error = 0;
    827 			break;
    828 		case SKEY_ABORTED_COMMAND:
    829 			error = ERESTART;
    830 			break;
    831 		case SKEY_VOLUME_OVERFLOW:
    832 			error = ENOSPC;
    833 			break;
    834 		default:
    835 			error = EIO;
    836 			break;
    837 		}
    838 
    839 #ifdef SCSIVERBOSE
    840 		if (key && (xs->xs_control & XS_CTL_SILENT) == 0)
    841 			scsipi_print_sense(xs, 0);
    842 #else
    843 		if (key) {
    844 			scsipi_printaddr(periph);
    845 			printf("%s", error_mes[key - 1]);
    846 			if ((sense->error_code & SSD_ERRCODE_VALID) != 0) {
    847 				switch (key) {
    848 				case SKEY_NOT_READY:
    849 				case SKEY_ILLEGAL_REQUEST:
    850 				case SKEY_UNIT_ATTENTION:
    851 				case SKEY_WRITE_PROTECT:
    852 					break;
    853 				case SKEY_BLANK_CHECK:
    854 					printf(", requested size: %d (decimal)",
    855 					    info);
    856 					break;
    857 				case SKEY_ABORTED_COMMAND:
    858 					if (xs->xs_retries)
    859 						printf(", retrying");
    860 					printf(", cmd 0x%x, info 0x%x",
    861 					    xs->cmd->opcode, info);
    862 					break;
    863 				default:
    864 					printf(", info = %d (decimal)", info);
    865 				}
    866 			}
    867 			if (sense->extra_len != 0) {
    868 				int n;
    869 				printf(", data =");
    870 				for (n = 0; n < sense->extra_len; n++)
    871 					printf(" %02x",
    872 					    sense->cmd_spec_info[n]);
    873 			}
    874 			printf("\n");
    875 		}
    876 #endif
    877 		return (error);
    878 
    879 	/*
    880 	 * Not code 70, just report it
    881 	 */
    882 	default:
    883 #if    defined(SCSIDEBUG) || defined(DEBUG)
    884 	{
    885 		static char *uc = "undecodable sense error";
    886 		int i;
    887 		u_int8_t *cptr = (u_int8_t *) sense;
    888 		scsipi_printaddr(periph);
    889 		if (xs->cmd == &xs->cmdstore) {
    890 			printf("%s for opcode 0x%x, data=",
    891 			    uc, xs->cmdstore.opcode);
    892 		} else {
    893 			printf("%s, data=", uc);
    894 		}
    895 		for (i = 0; i < sizeof (sense); i++)
    896 			printf(" 0x%02x", *(cptr++) & 0xff);
    897 		printf("\n");
    898 	}
    899 #else
    900 
    901 		scsipi_printaddr(periph);
    902 		printf("Sense Error Code 0x%x",
    903 			sense->error_code & SSD_ERRCODE);
    904 		if ((sense->error_code & SSD_ERRCODE_VALID) != 0) {
    905 			struct scsipi_sense_data_unextended *usense =
    906 			    (struct scsipi_sense_data_unextended *)sense;
    907 			printf(" at block no. %d (decimal)",
    908 			    _3btol(usense->block));
    909 		}
    910 		printf("\n");
    911 #endif
    912 		return (EIO);
    913 	}
    914 }
    915 
    916 /*
    917  * scsipi_size:
    918  *
    919  *	Find out from the device what its capacity is.
    920  */
    921 u_long
    922 scsipi_size(periph, flags)
    923 	struct scsipi_periph *periph;
    924 	int flags;
    925 {
    926 	struct scsipi_read_cap_data rdcap;
    927 	struct scsipi_read_capacity scsipi_cmd;
    928 
    929 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
    930 	scsipi_cmd.opcode = READ_CAPACITY;
    931 
    932 	/*
    933 	 * If the command works, interpret the result as a 4 byte
    934 	 * number of blocks
    935 	 */
    936 	if (scsipi_command(periph, (struct scsipi_generic *)&scsipi_cmd,
    937 	    sizeof(scsipi_cmd), (u_char *)&rdcap, sizeof(rdcap),
    938 	    SCSIPIRETRIES, 20000, NULL,
    939 	    flags | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK) != 0) {
    940 		scsipi_printaddr(periph);
    941 		printf("could not get size\n");
    942 		return (0);
    943 	}
    944 
    945 	return (_4btol(rdcap.addr) + 1);
    946 }
    947 
    948 /*
    949  * scsipi_test_unit_ready:
    950  *
    951  *	Issue a `test unit ready' request.
    952  */
    953 int
    954 scsipi_test_unit_ready(periph, flags)
    955 	struct scsipi_periph *periph;
    956 	int flags;
    957 {
    958 	struct scsipi_test_unit_ready scsipi_cmd;
    959 
    960 	/* some ATAPI drives don't support TEST_UNIT_READY. Sigh */
    961 	if (periph->periph_quirks & PQUIRK_NOTUR)
    962 		return (0);
    963 
    964 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
    965 	scsipi_cmd.opcode = TEST_UNIT_READY;
    966 
    967 	return (scsipi_command(periph,
    968 	    (struct scsipi_generic *)&scsipi_cmd, sizeof(scsipi_cmd),
    969 	    0, 0, SCSIPIRETRIES, 10000, NULL, flags));
    970 }
    971 
    972 /*
    973  * scsipi_inquire:
    974  *
    975  *	Ask the device about itself.
    976  */
    977 int
    978 scsipi_inquire(periph, inqbuf, flags)
    979 	struct scsipi_periph *periph;
    980 	struct scsipi_inquiry_data *inqbuf;
    981 	int flags;
    982 {
    983 	struct scsipi_inquiry scsipi_cmd;
    984 
    985 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
    986 	scsipi_cmd.opcode = INQUIRY;
    987 	scsipi_cmd.length = sizeof(struct scsipi_inquiry_data);
    988 
    989 	return (scsipi_command(periph,
    990 	    (struct scsipi_generic *) &scsipi_cmd, sizeof(scsipi_cmd),
    991 	    (u_char *) inqbuf, sizeof(struct scsipi_inquiry_data),
    992 	    SCSIPIRETRIES, 10000, NULL, XS_CTL_DATA_IN | flags));
    993 }
    994 
    995 /*
    996  * scsipi_prevent:
    997  *
    998  *	Prevent or allow the user to remove the media
    999  */
   1000 int
   1001 scsipi_prevent(periph, type, flags)
   1002 	struct scsipi_periph *periph;
   1003 	int type, flags;
   1004 {
   1005 	struct scsipi_prevent scsipi_cmd;
   1006 
   1007 	if (periph->periph_quirks & PQUIRK_NODOORLOCK)
   1008 		return (0);
   1009 
   1010 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
   1011 	scsipi_cmd.opcode = PREVENT_ALLOW;
   1012 	scsipi_cmd.how = type;
   1013 
   1014 	return (scsipi_command(periph,
   1015 	    (struct scsipi_generic *) &scsipi_cmd, sizeof(scsipi_cmd),
   1016 	    0, 0, SCSIPIRETRIES, 5000, NULL, flags));
   1017 }
   1018 
   1019 /*
   1020  * scsipi_start:
   1021  *
   1022  *	Send a START UNIT.
   1023  */
   1024 int
   1025 scsipi_start(periph, type, flags)
   1026 	struct scsipi_periph *periph;
   1027 	int type, flags;
   1028 {
   1029 	struct scsipi_start_stop scsipi_cmd;
   1030 
   1031 	if (periph->periph_quirks & PQUIRK_NOSTARTUNIT)
   1032 		return 0;
   1033 
   1034 	bzero(&scsipi_cmd, sizeof(scsipi_cmd));
   1035 	scsipi_cmd.opcode = START_STOP;
   1036 	scsipi_cmd.byte2 = 0x00;
   1037 	scsipi_cmd.how = type;
   1038 
   1039 	return (scsipi_command(periph,
   1040 	    (struct scsipi_generic *) &scsipi_cmd, sizeof(scsipi_cmd),
   1041 	    0, 0, SCSIPIRETRIES, (type & SSS_START) ? 60000 : 10000,
   1042 	    NULL, flags));
   1043 }
   1044 
   1045 /*
   1046  * scsipi_done:
   1047  *
   1048  *	This routine is called by an adapter's interrupt handler when
   1049  *	an xfer is completed.
   1050  */
   1051 void
   1052 scsipi_done(xs)
   1053 	struct scsipi_xfer *xs;
   1054 {
   1055 	struct scsipi_periph *periph = xs->xs_periph;
   1056 	struct scsipi_channel *chan = periph->periph_channel;
   1057 	int s, freezecnt;
   1058 
   1059 	SC_DEBUG(periph, SCSIPI_DB2, ("scsipi_done\n"));
   1060 #ifdef SCSIPI_DEBUG
   1061 	if (periph->periph_dbflags & SCSIPI_DB1)
   1062 		show_scsipi_cmd(xs);
   1063 #endif
   1064 
   1065 	s = splbio();
   1066 	/*
   1067 	 * The resource this command was using is now free.
   1068 	 */
   1069 	scsipi_put_resource(chan);
   1070 
   1071 	/*
   1072 	 * If the command was tagged, free the tag.
   1073 	 */
   1074 	if (XS_CTL_TAGTYPE(xs) != 0)
   1075 		scsipi_put_tag(xs);
   1076 
   1077 	/* Mark the command as `done'. */
   1078 	xs->xs_status |= XS_STS_DONE;
   1079 
   1080 #ifdef DIAGNOSTIC
   1081 	if ((xs->xs_control & (XS_CTL_ASYNC|XS_CTL_POLL)) ==
   1082 	    (XS_CTL_ASYNC|XS_CTL_POLL))
   1083 		panic("scsipi_done: ASYNC and POLL");
   1084 #endif
   1085 
   1086 	/*
   1087 	 * If the xfer had an error of any sort, freeze the
   1088 	 * periph's queue.  Freeze it again if we were requested
   1089 	 * to do so in the xfer.
   1090 	 */
   1091 	freezecnt = 0;
   1092 	if (xs->error != XS_NOERROR)
   1093 		freezecnt++;
   1094 	if (xs->xs_control & XS_CTL_FREEZE_PERIPH)
   1095 		freezecnt++;
   1096 	if (freezecnt != 0)
   1097 		scsipi_periph_freeze(periph, freezecnt);
   1098 
   1099 	/*
   1100 	 * record the xfer with a pending sense, in case a SCSI reset is
   1101 	 * received before the thread is waked up.
   1102 	 */
   1103 	if (xs->error == XS_BUSY && xs->status == SCSI_CHECK) {
   1104 		periph->periph_flags |= PERIPH_SENSE;
   1105 		periph->periph_xscheck = xs;
   1106 	}
   1107 
   1108 	/*
   1109 	 * If this was an xfer that was not to complete asynchrnously,
   1110 	 * let the requesting thread perform error checking/handling
   1111 	 * in its context.
   1112 	 */
   1113 	if ((xs->xs_control & XS_CTL_ASYNC) == 0) {
   1114 		splx(s);
   1115 		/*
   1116 		 * If it's a polling job, just return, to unwind the
   1117 		 * call graph.  We don't need to restart the queue,
   1118 		 * because pollings jobs are treated specially, and
   1119 		 * are really only used during crash dumps anyway
   1120 		 * (XXX or during boot-time autconfiguration of
   1121 		 * ATAPI devices).
   1122 		 */
   1123 		if (xs->xs_control & XS_CTL_POLL)
   1124 			return;
   1125 		wakeup(xs);
   1126 		goto out;
   1127 	}
   1128 
   1129 	/*
   1130 	 * Catch the extremely common case of I/O completing
   1131 	 * without error; no use in taking a context switch
   1132 	 * if we can handle it in interrupt context.
   1133 	 */
   1134 	if (xs->error == XS_NOERROR) {
   1135 		splx(s);
   1136 		(void) scsipi_complete(xs);
   1137 		goto out;
   1138 	}
   1139 
   1140 	/*
   1141 	 * There is an error on this xfer.  Put it on the channel's
   1142 	 * completion queue, and wake up the completion thread.
   1143 	 */
   1144 	TAILQ_INSERT_TAIL(&chan->chan_complete, xs, channel_q);
   1145 	splx(s);
   1146 	wakeup(&chan->chan_complete);
   1147 
   1148  out:
   1149 	/*
   1150 	 * If there are more xfers on the channel's queue, attempt to
   1151 	 * run them.
   1152 	 */
   1153 	scsipi_run_queue(chan);
   1154 }
   1155 
   1156 /*
   1157  * scsipi_complete:
   1158  *
   1159  *	Completion of a scsipi_xfer.  This is the guts of scsipi_done().
   1160  *
   1161  *	NOTE: This routine MUST be called with valid thread context
   1162  *	except for the case where the following two conditions are
   1163  *	true:
   1164  *
   1165  *		xs->error == XS_NOERROR
   1166  *		XS_CTL_ASYNC is set in xs->xs_control
   1167  *
   1168  *	The semantics of this routine can be tricky, so here is an
   1169  *	explanation:
   1170  *
   1171  *		0		Xfer completed successfully.
   1172  *
   1173  *		ERESTART	Xfer had an error, but was restarted.
   1174  *
   1175  *		anything else	Xfer had an error, return value is Unix
   1176  *				errno.
   1177  *
   1178  *	If the return value is anything but ERESTART:
   1179  *
   1180  *		- If XS_CTL_ASYNC is set, `xs' has been freed back to
   1181  *		  the pool.
   1182  *		- If there is a buf associated with the xfer,
   1183  *		  it has been biodone()'d.
   1184  */
   1185 int
   1186 scsipi_complete(xs)
   1187 	struct scsipi_xfer *xs;
   1188 {
   1189 	struct scsipi_periph *periph = xs->xs_periph;
   1190 	struct scsipi_channel *chan = periph->periph_channel;
   1191 	struct buf *bp;
   1192 	int error, s;
   1193 
   1194 #ifdef DIAGNOSTIC
   1195 	if ((xs->xs_control & XS_CTL_ASYNC) != 0 && xs->bp == NULL)
   1196 		panic("scsipi_complete: XS_CTL_ASYNC but no buf");
   1197 #endif
   1198 	/*
   1199 	 * If command terminated with a CHECK CONDITION, we need to issue a
   1200 	 * REQUEST_SENSE command. Once the REQUEST_SENSE has been processed
   1201 	 * we'll have the real status.
   1202 	 * Must be processed at splbio() to avoid missing a SCSI bus reset
   1203 	 * for this command.
   1204 	 */
   1205 	s = splbio();
   1206 	if (xs->error == XS_BUSY && xs->status == SCSI_CHECK) {
   1207 		/* request sense for a request sense ? */
   1208 		if (xs->xs_control & XS_CTL_REQSENSE) {
   1209 			scsipi_printaddr(periph);
   1210 			printf("request sense for request sense\n");
   1211 			return EIO;
   1212 		}
   1213 		scsipi_request_sense(xs);
   1214 	}
   1215 	splx(s);
   1216 	/*
   1217 	 * If it's a user level request, bypass all usual completion
   1218 	 * processing, let the user work it out..
   1219 	 */
   1220 	if ((xs->xs_control & XS_CTL_USERCMD) != 0) {
   1221 		SC_DEBUG(periph, SCSIPI_DB3, ("calling user done()\n"));
   1222 		scsipi_user_done(xs);
   1223 		SC_DEBUG(periph, SCSIPI_DB3, ("returned from user done()\n "));
   1224 		return 0;
   1225 	}
   1226 
   1227 
   1228 	switch (xs->error) {
   1229 	case XS_NOERROR:
   1230 		error = 0;
   1231 		break;
   1232 
   1233 	case XS_SENSE:
   1234 	case XS_SHORTSENSE:
   1235 		error = (*chan->chan_bustype->bustype_interpret_sense)(xs);
   1236 		break;
   1237 
   1238 	case XS_RESOURCE_SHORTAGE:
   1239 		/*
   1240 		 * XXX Should freeze channel's queue.
   1241 		 */
   1242 		scsipi_printaddr(periph);
   1243 		printf("adapter resource shortage\n");
   1244 		/* FALLTHROUGH */
   1245 
   1246 	case XS_BUSY:
   1247 		if (xs->error == XS_BUSY && xs->status == SCSI_QUEUE_FULL) {
   1248 			struct scsipi_max_openings mo;
   1249 
   1250 			/*
   1251 			 * We set the openings to active - 1, assuming that
   1252 			 * the command that got us here is the first one that
   1253 			 * can't fit into the device's queue.  If that's not
   1254 			 * the case, I guess we'll find out soon enough.
   1255 			 */
   1256 			mo.mo_target = periph->periph_target;
   1257 			mo.mo_lun = periph->periph_lun;
   1258 			mo.mo_openings = periph->periph_active - 1;
   1259 #ifdef DIAGNOSTIC
   1260 			if (mo.mo_openings < 0) {
   1261 				scsipi_printaddr(periph);
   1262 				printf("QUEUE FULL resulted in < 0 openings\n");
   1263 				panic("scsipi_done");
   1264 			}
   1265 #endif
   1266 			if (mo.mo_openings == 0) {
   1267 				scsipi_printaddr(periph);
   1268 				printf("QUEUE FULL resulted in 0 openings\n");
   1269 				mo.mo_openings = 1;
   1270 			}
   1271 			scsipi_async_event(chan, ASYNC_EVENT_MAX_OPENINGS, &mo);
   1272 			error = ERESTART;
   1273 		} else if (xs->xs_retries != 0) {
   1274 			xs->xs_retries--;
   1275 			/*
   1276 			 * Wait one second, and try again.
   1277 			 */
   1278 			if (xs->xs_control & XS_CTL_POLL)
   1279 				delay(1000000);
   1280 			else {
   1281 				scsipi_periph_freeze(periph, 1);
   1282 				callout_reset(&periph->periph_callout,
   1283 				    hz, scsipi_periph_timed_thaw, periph);
   1284 			}
   1285 			error = ERESTART;
   1286 		} else
   1287 			error = EBUSY;
   1288 		break;
   1289 
   1290 	case XS_TIMEOUT:
   1291 		if (xs->xs_retries != 0) {
   1292 			xs->xs_retries--;
   1293 			error = ERESTART;
   1294 		} else
   1295 			error = EIO;
   1296 		break;
   1297 
   1298 	case XS_SELTIMEOUT:
   1299 		/* XXX Disable device? */
   1300 		error = EIO;
   1301 		break;
   1302 
   1303 	case XS_RESET:
   1304 		if (xs->xs_control & XS_CTL_REQSENSE) {
   1305 			/*
   1306 			 * request sense interrupted by reset: signal it
   1307 			 * with EINTR return code.
   1308 			 */
   1309 			error = EINTR;
   1310 		} else {
   1311 			if (xs->xs_retries != 0) {
   1312 				xs->xs_retries--;
   1313 				error = ERESTART;
   1314 			} else
   1315 				error = EIO;
   1316 		}
   1317 		break;
   1318 
   1319 	default:
   1320 		scsipi_printaddr(periph);
   1321 		printf("invalid return code from adapter: %d\n", xs->error);
   1322 		error = EIO;
   1323 		break;
   1324 	}
   1325 
   1326 	s = splbio();
   1327 	if (error == ERESTART) {
   1328 		/*
   1329 		 * If we get here, the periph has been thawed and frozen
   1330 		 * again if we had to issue recovery commands.  Alternatively,
   1331 		 * it may have been frozen again and in a timed thaw.  In
   1332 		 * any case, we thaw the periph once we re-enqueue the
   1333 		 * command.  Once the periph is fully thawed, it will begin
   1334 		 * operation again.
   1335 		 */
   1336 		xs->error = XS_NOERROR;
   1337 		xs->status = SCSI_OK;
   1338 		xs->xs_status &= ~XS_STS_DONE;
   1339 		xs->xs_requeuecnt++;
   1340 		error = scsipi_enqueue(xs);
   1341 		if (error == 0) {
   1342 			scsipi_periph_thaw(periph, 1);
   1343 			splx(s);
   1344 			return (ERESTART);
   1345 		}
   1346 	}
   1347 
   1348 	/*
   1349 	 * scsipi_done() freezes the queue if not XS_NOERROR.
   1350 	 * Thaw it here.
   1351 	 */
   1352 	if (xs->error != XS_NOERROR)
   1353 		scsipi_periph_thaw(periph, 1);
   1354 
   1355 	if ((bp = xs->bp) != NULL) {
   1356 		if (error) {
   1357 			bp->b_error = error;
   1358 			bp->b_flags |= B_ERROR;
   1359 			bp->b_resid = bp->b_bcount;
   1360 		} else {
   1361 			bp->b_error = 0;
   1362 			bp->b_resid = xs->resid;
   1363 		}
   1364 		biodone(bp);
   1365 	}
   1366 
   1367 	if (xs->xs_control & XS_CTL_ASYNC)
   1368 		scsipi_put_xs(xs);
   1369 	splx(s);
   1370 
   1371 	return (error);
   1372 }
   1373 
   1374 /*
   1375  * Issue a request sense for the given scsipi_xfer. Called when the xfer
   1376  * returns with a CHECK_CONDITION status. Must be called in valid thread
   1377  * context and at splbio().
   1378  */
   1379 
   1380 void
   1381 scsipi_request_sense(xs)
   1382 	struct scsipi_xfer *xs;
   1383 {
   1384 	struct scsipi_periph *periph = xs->xs_periph;
   1385 	int flags, error;
   1386 	struct scsipi_sense cmd;
   1387 
   1388 	periph->periph_flags |= PERIPH_SENSE;
   1389 
   1390 	/* if command was polling, request sense will too */
   1391 	flags = xs->xs_control & XS_CTL_POLL;
   1392 	/* Polling commands can't sleep */
   1393 	if (flags)
   1394 		flags |= XS_CTL_NOSLEEP;
   1395 
   1396 	flags |= XS_CTL_REQSENSE | XS_CTL_URGENT | XS_CTL_DATA_IN |
   1397 	    XS_CTL_THAW_PERIPH | XS_CTL_FREEZE_PERIPH;
   1398 
   1399 	bzero(&cmd, sizeof(cmd));
   1400 	cmd.opcode = REQUEST_SENSE;
   1401 	cmd.length = sizeof(struct scsipi_sense_data);
   1402 
   1403 	error = scsipi_command(periph,
   1404 	    (struct scsipi_generic *) &cmd, sizeof(cmd),
   1405 	    (u_char*)&xs->sense.scsi_sense, sizeof(struct scsipi_sense_data),
   1406 	    0, 1000, NULL, flags);
   1407 	periph->periph_flags &= ~PERIPH_SENSE;
   1408 	periph->periph_xscheck = NULL;
   1409 	switch(error) {
   1410 	case 0:
   1411 		/* we have a valid sense */
   1412 		xs->error = XS_SENSE;
   1413 		return;
   1414 	case EINTR:
   1415 		/* REQUEST_SENSE interrupted by bus reset. */
   1416 		xs->error = XS_RESET;
   1417 		return;
   1418 	default:
   1419 		 /* Notify that request sense failed. */
   1420 		xs->error = XS_DRIVER_STUFFUP;
   1421 		scsipi_printaddr(periph);
   1422 		printf("request sense failed with error %d\n", error);
   1423 		return;
   1424 	}
   1425 }
   1426 
   1427 /*
   1428  * scsipi_enqueue:
   1429  *
   1430  *	Enqueue an xfer on a channel.
   1431  */
   1432 int
   1433 scsipi_enqueue(xs)
   1434 	struct scsipi_xfer *xs;
   1435 {
   1436 	struct scsipi_channel *chan = xs->xs_periph->periph_channel;
   1437 	struct scsipi_xfer *qxs;
   1438 	int s;
   1439 
   1440 	s = splbio();
   1441 
   1442 	/*
   1443 	 * If the xfer is to be polled, and there are already jobs on
   1444 	 * the queue, we can't proceed.
   1445 	 */
   1446 	if ((xs->xs_control & XS_CTL_POLL) != 0 &&
   1447 	    TAILQ_FIRST(&chan->chan_queue) != NULL) {
   1448 		splx(s);
   1449 		xs->error = XS_DRIVER_STUFFUP;
   1450 		return (EAGAIN);
   1451 	}
   1452 
   1453 	/*
   1454 	 * If we have an URGENT xfer, it's an error recovery command
   1455 	 * and it should just go on the head of the channel's queue.
   1456 	 */
   1457 	if (xs->xs_control & XS_CTL_URGENT) {
   1458 		TAILQ_INSERT_HEAD(&chan->chan_queue, xs, channel_q);
   1459 		goto out;
   1460 	}
   1461 
   1462 	/*
   1463 	 * If this xfer has already been on the queue before, we
   1464 	 * need to reinsert it in the correct order.  That order is:
   1465 	 *
   1466 	 *	Immediately before the first xfer for this periph
   1467 	 *	with a requeuecnt less than xs->xs_requeuecnt.
   1468 	 *
   1469 	 * Failing that, at the end of the queue.  (We'll end up
   1470 	 * there naturally.)
   1471 	 */
   1472 	if (xs->xs_requeuecnt != 0) {
   1473 		for (qxs = TAILQ_FIRST(&chan->chan_queue); qxs != NULL;
   1474 		     qxs = TAILQ_NEXT(qxs, channel_q)) {
   1475 			if (qxs->xs_periph == xs->xs_periph &&
   1476 			    qxs->xs_requeuecnt < xs->xs_requeuecnt)
   1477 				break;
   1478 		}
   1479 		if (qxs != NULL) {
   1480 			TAILQ_INSERT_AFTER(&chan->chan_queue, qxs, xs,
   1481 			    channel_q);
   1482 			goto out;
   1483 		}
   1484 	}
   1485 	TAILQ_INSERT_TAIL(&chan->chan_queue, xs, channel_q);
   1486  out:
   1487 	if (xs->xs_control & XS_CTL_THAW_PERIPH)
   1488 		scsipi_periph_thaw(xs->xs_periph, 1);
   1489 	splx(s);
   1490 	return (0);
   1491 }
   1492 
   1493 /*
   1494  * scsipi_run_queue:
   1495  *
   1496  *	Start as many xfers as possible running on the channel.
   1497  */
   1498 void
   1499 scsipi_run_queue(chan)
   1500 	struct scsipi_channel *chan;
   1501 {
   1502 	struct scsipi_xfer *xs;
   1503 	struct scsipi_periph *periph;
   1504 	int s;
   1505 
   1506 	for (;;) {
   1507 		s = splbio();
   1508 
   1509 		/*
   1510 		 * If the channel is frozen, we can't do any work right
   1511 		 * now.
   1512 		 */
   1513 		if (chan->chan_qfreeze != 0) {
   1514 			splx(s);
   1515 			return;
   1516 		}
   1517 
   1518 		/*
   1519 		 * Look for work to do, and make sure we can do it.
   1520 		 */
   1521 		for (xs = TAILQ_FIRST(&chan->chan_queue); xs != NULL;
   1522 		     xs = TAILQ_NEXT(xs, channel_q)) {
   1523 			periph = xs->xs_periph;
   1524 
   1525 			if ((periph->periph_active > periph->periph_openings) ||			    periph->periph_qfreeze != 0)
   1526 				continue;
   1527 
   1528 			if ((periph->periph_flags &
   1529 			    (PERIPH_RECOVERING | PERIPH_SENSE)) != 0 &&
   1530 			    (xs->xs_control & XS_CTL_URGENT) == 0)
   1531 				continue;
   1532 
   1533 			/*
   1534 			 * We can issue this xfer!
   1535 			 */
   1536 			goto got_one;
   1537 		}
   1538 
   1539 		/*
   1540 		 * Can't find any work to do right now.
   1541 		 */
   1542 		splx(s);
   1543 		return;
   1544 
   1545  got_one:
   1546 		/*
   1547 		 * Have an xfer to run.  Allocate a resource from
   1548 		 * the adapter to run it.  If we can't allocate that
   1549 		 * resource, we don't dequeue the xfer.
   1550 		 */
   1551 		if (scsipi_get_resource(chan) == 0) {
   1552 			/*
   1553 			 * Adapter is out of resources.  If the adapter
   1554 			 * supports it, attempt to grow them.
   1555 			 */
   1556 			if (scsipi_grow_resources(chan) == 0) {
   1557 				/*
   1558 				 * Wasn't able to grow resources,
   1559 				 * nothing more we can do.
   1560 				 */
   1561 				if (xs->xs_control & XS_CTL_POLL) {
   1562 					scsipi_printaddr(xs->xs_periph);
   1563 					printf("polling command but no "
   1564 					    "adapter resources");
   1565 					/* We'll panic shortly... */
   1566 				}
   1567 				splx(s);
   1568 				return;
   1569 			}
   1570 			/*
   1571 			 * scsipi_grow_resources() allocated the resource
   1572 			 * for us.
   1573 			 */
   1574 		}
   1575 
   1576 		/*
   1577 		 * We have a resource to run this xfer, do it!
   1578 		 */
   1579 		TAILQ_REMOVE(&chan->chan_queue, xs, channel_q);
   1580 
   1581 		/*
   1582 		 * If the command is to be tagged, allocate a tag ID
   1583 		 * for it.
   1584 		 */
   1585 		if (XS_CTL_TAGTYPE(xs) != 0)
   1586 			scsipi_get_tag(xs);
   1587 		splx(s);
   1588 
   1589 		scsipi_adapter_request(chan, ADAPTER_REQ_RUN_XFER, xs);
   1590 	}
   1591 #ifdef DIAGNOSTIC
   1592 	panic("scsipi_run_queue: impossible");
   1593 #endif
   1594 }
   1595 
   1596 /*
   1597  * scsipi_execute_xs:
   1598  *
   1599  *	Begin execution of an xfer, waiting for it to complete, if necessary.
   1600  */
   1601 int
   1602 scsipi_execute_xs(xs)
   1603 	struct scsipi_xfer *xs;
   1604 {
   1605 	struct scsipi_periph *periph = xs->xs_periph;
   1606 	struct scsipi_channel *chan = periph->periph_channel;
   1607 	int async, poll, retries, error, s;
   1608 
   1609 	xs->xs_status &= ~XS_STS_DONE;
   1610 	xs->error = XS_NOERROR;
   1611 	xs->resid = xs->datalen;
   1612 	xs->status = SCSI_OK;
   1613 
   1614 #ifdef SCSIPI_DEBUG
   1615 	if (xs->xs_periph->periph_dbflags & SCSIPI_DB3) {
   1616 		printf("scsipi_execute_xs: ");
   1617 		show_scsipi_xs(xs);
   1618 		printf("\n");
   1619 	}
   1620 #endif
   1621 
   1622 	/*
   1623 	 * Deal with command tagging:
   1624 	 *
   1625 	 *	- If the device's current operating mode doesn't
   1626 	 *	  include tagged queueing, clear the tag mask.
   1627 	 *
   1628 	 *	- If the device's current operating mode *does*
   1629 	 *	  include tagged queueing, set the tag_type in
   1630 	 *	  the xfer to the appropriate byte for the tag
   1631 	 *	  message.
   1632 	 */
   1633 	if ((PERIPH_XFER_MODE(periph) & PERIPH_CAP_TQING) == 0 ||
   1634 		(xs->xs_control & XS_CTL_REQSENSE)) {
   1635 		xs->xs_control &= ~XS_CTL_TAGMASK;
   1636 		xs->xs_tag_type = 0;
   1637 	} else {
   1638 		/*
   1639 		 * If the request doesn't specify a tag, give Head
   1640 		 * tags to URGENT operations and Ordered tags to
   1641 		 * everything else.
   1642 		 */
   1643 		if (XS_CTL_TAGTYPE(xs) == 0) {
   1644 			if (xs->xs_control & XS_CTL_URGENT)
   1645 				xs->xs_control |= XS_CTL_HEAD_TAG;
   1646 			else
   1647 				xs->xs_control |= XS_CTL_ORDERED_TAG;
   1648 		}
   1649 
   1650 		switch (XS_CTL_TAGTYPE(xs)) {
   1651 		case XS_CTL_ORDERED_TAG:
   1652 			xs->xs_tag_type = MSG_ORDERED_Q_TAG;
   1653 			break;
   1654 
   1655 		case XS_CTL_SIMPLE_TAG:
   1656 			xs->xs_tag_type = MSG_SIMPLE_Q_TAG;
   1657 			break;
   1658 
   1659 		case XS_CTL_HEAD_TAG:
   1660 			xs->xs_tag_type = MSG_HEAD_OF_Q_TAG;
   1661 			break;
   1662 
   1663 		default:
   1664 			scsipi_printaddr(periph);
   1665 			printf("invalid tag mask 0x%08x\n",
   1666 			    XS_CTL_TAGTYPE(xs));
   1667 			panic("scsipi_execute_xs");
   1668 		}
   1669 	}
   1670 
   1671 	/*
   1672 	 * If we don't yet have a completion thread, or we are to poll for
   1673 	 * completion, clear the ASYNC flag.
   1674 	 */
   1675 	if (chan->chan_thread == NULL || (xs->xs_control & XS_CTL_POLL) != 0)
   1676 		xs->xs_control &= ~XS_CTL_ASYNC;
   1677 
   1678 	async = (xs->xs_control & XS_CTL_ASYNC);
   1679 	poll = (xs->xs_control & XS_CTL_POLL);
   1680 	retries = xs->xs_retries;		/* for polling commands */
   1681 
   1682 #ifdef DIAGNOSTIC
   1683 	if (async != 0 && xs->bp == NULL)
   1684 		panic("scsipi_execute_xs: XS_CTL_ASYNC but no buf");
   1685 #endif
   1686 
   1687 	/*
   1688 	 * Enqueue the transfer.  If we're not polling for completion, this
   1689 	 * should ALWAYS return `no error'.
   1690 	 */
   1691  try_again:
   1692 	error = scsipi_enqueue(xs);
   1693 	if (error) {
   1694 		if (poll == 0) {
   1695 			scsipi_printaddr(periph);
   1696 			printf("not polling, but enqueue failed with %d\n",
   1697 			    error);
   1698 			panic("scsipi_execute_xs");
   1699 		}
   1700 
   1701 		scsipi_printaddr(periph);
   1702 		printf("failed to enqueue polling command");
   1703 		if (retries != 0) {
   1704 			printf(", retrying...\n");
   1705 			delay(1000000);
   1706 			retries--;
   1707 			goto try_again;
   1708 		}
   1709 		printf("\n");
   1710 		goto free_xs;
   1711 	}
   1712 
   1713  restarted:
   1714 	scsipi_run_queue(chan);
   1715 
   1716 	/*
   1717 	 * The xfer is enqueued, and possibly running.  If it's to be
   1718 	 * completed asynchronously, just return now.
   1719 	 */
   1720 	if (async)
   1721 		return (EJUSTRETURN);
   1722 
   1723 	/*
   1724 	 * Not an asynchronous command; wait for it to complete.
   1725 	 */
   1726 	while ((xs->xs_status & XS_STS_DONE) == 0) {
   1727 		if (poll) {
   1728 			scsipi_printaddr(periph);
   1729 			printf("polling command not done\n");
   1730 			panic("scsipi_execute_xs");
   1731 		}
   1732 		(void) tsleep(xs, PRIBIO, "xscmd", 0);
   1733 	}
   1734 
   1735 	/*
   1736 	 * Command is complete.  scsipi_done() has awakened us to perform
   1737 	 * the error handling.
   1738 	 */
   1739 	error = scsipi_complete(xs);
   1740 	if (error == ERESTART)
   1741 		goto restarted;
   1742 
   1743 	/*
   1744 	 * Command completed successfully or fatal error occurred.  Fall
   1745 	 * into....
   1746 	 */
   1747  free_xs:
   1748 	s = splbio();
   1749 	scsipi_put_xs(xs);
   1750 	splx(s);
   1751 
   1752 	/*
   1753 	 * Kick the queue, keep it running in case it stopped for some
   1754 	 * reason.
   1755 	 */
   1756 	scsipi_run_queue(chan);
   1757 
   1758 	return (error);
   1759 }
   1760 
   1761 /*
   1762  * scsipi_completion_thread:
   1763  *
   1764  *	This is the completion thread.  We wait for errors on
   1765  *	asynchronous xfers, and perform the error handling
   1766  *	function, restarting the command, if necessary.
   1767  */
   1768 void
   1769 scsipi_completion_thread(arg)
   1770 	void *arg;
   1771 {
   1772 	struct scsipi_channel *chan = arg;
   1773 	struct scsipi_xfer *xs;
   1774 	int s;
   1775 
   1776 	for (;;) {
   1777 		s = splbio();
   1778 		xs = TAILQ_FIRST(&chan->chan_complete);
   1779 		if (xs == NULL &&
   1780 		    (chan->chan_flags & SCSIPI_CHAN_SHUTDOWN) == 0) {
   1781 			splx(s);
   1782 			(void) tsleep(&chan->chan_complete, PRIBIO,
   1783 			    "sccomp", 0);
   1784 			continue;
   1785 		}
   1786 		if (chan->chan_flags & SCSIPI_CHAN_SHUTDOWN) {
   1787 			splx(s);
   1788 			break;
   1789 		}
   1790 		TAILQ_REMOVE(&chan->chan_complete, xs, channel_q);
   1791 		splx(s);
   1792 
   1793 		/*
   1794 		 * Have an xfer with an error; process it.
   1795 		 */
   1796 		(void) scsipi_complete(xs);
   1797 
   1798 		/*
   1799 		 * Kick the queue; keep it running if it was stopped
   1800 		 * for some reason.
   1801 		 */
   1802 		scsipi_run_queue(chan);
   1803 	}
   1804 
   1805 	chan->chan_thread = NULL;
   1806 
   1807 	/* In case parent is waiting for us to exit. */
   1808 	wakeup(&chan->chan_thread);
   1809 
   1810 	kthread_exit(0);
   1811 }
   1812 
   1813 /*
   1814  * scsipi_create_completion_thread:
   1815  *
   1816  *	Callback to actually create the completion thread.
   1817  */
   1818 void
   1819 scsipi_create_completion_thread(arg)
   1820 	void *arg;
   1821 {
   1822 	struct scsipi_channel *chan = arg;
   1823 	struct scsipi_adapter *adapt = chan->chan_adapter;
   1824 
   1825 	if (kthread_create1(scsipi_completion_thread, chan,
   1826 	    &chan->chan_thread, "%s:%d", adapt->adapt_dev->dv_xname,
   1827 	    chan->chan_channel)) {
   1828 		printf("%s: unable to create completion thread for "
   1829 		    "channel %d\n", adapt->adapt_dev->dv_xname,
   1830 		    chan->chan_channel);
   1831 		panic("scsipi_create_completion_thread");
   1832 	}
   1833 }
   1834 
   1835 /*
   1836  * scsipi_async_event:
   1837  *
   1838  *	Handle an asynchronous event from an adapter.
   1839  */
   1840 void
   1841 scsipi_async_event(chan, event, arg)
   1842 	struct scsipi_channel *chan;
   1843 	scsipi_async_event_t event;
   1844 	void *arg;
   1845 {
   1846 	int s;
   1847 
   1848 	s = splbio();
   1849 	switch (event) {
   1850 	case ASYNC_EVENT_MAX_OPENINGS:
   1851 		scsipi_async_event_max_openings(chan,
   1852 		    (struct scsipi_max_openings *)arg);
   1853 		break;
   1854 
   1855 	case ASYNC_EVENT_XFER_MODE:
   1856 		scsipi_async_event_xfer_mode(chan,
   1857 		    (struct scsipi_xfer_mode *)arg);
   1858 		break;
   1859 	case ASYNC_EVENT_RESET:
   1860 		scsipi_async_event_channel_reset(chan);
   1861 		break;
   1862 	}
   1863 	splx(s);
   1864 }
   1865 
   1866 /*
   1867  * scsipi_print_xfer_mode:
   1868  *
   1869  *	Print a periph's capabilities.
   1870  */
   1871 void
   1872 scsipi_print_xfer_mode(periph)
   1873 	struct scsipi_periph *periph;
   1874 {
   1875 	int period, freq, speed, mbs;
   1876 
   1877 	if ((periph->periph_flags & PERIPH_MODE_VALID) == 0)
   1878 		return;
   1879 
   1880 	printf("%s: ", periph->periph_dev->dv_xname);
   1881 	if (periph->periph_mode & PERIPH_CAP_SYNC) {
   1882 		period = scsipi_sync_factor_to_period(periph->periph_period);
   1883 		printf("Sync (%d.%dns offset %d)",
   1884 		    period / 10, period % 10, periph->periph_offset);
   1885 	} else
   1886 		printf("Async");
   1887 
   1888 	if (periph->periph_mode & PERIPH_CAP_WIDE32)
   1889 		printf(", 32-bit");
   1890 	else if (periph->periph_mode & PERIPH_CAP_WIDE16)
   1891 		printf(", 16-bit");
   1892 	else
   1893 		printf(", 8-bit");
   1894 
   1895 	if (periph->periph_mode & PERIPH_CAP_SYNC) {
   1896 		freq = scsipi_sync_factor_to_freq(periph->periph_period);
   1897 		speed = freq;
   1898 		if (periph->periph_mode & PERIPH_CAP_WIDE32)
   1899 			speed *= 4;
   1900 		else if (periph->periph_mode & PERIPH_CAP_WIDE16)
   1901 			speed *= 2;
   1902 		mbs = speed / 1000;
   1903 		if (mbs > 0)
   1904 			printf(" (%d.%03dMB/s)", mbs, speed % 1000);
   1905 		else
   1906 			printf(" (%dKB/s)", speed % 1000);
   1907 	}
   1908 
   1909 	printf(" transfers");
   1910 
   1911 	if (periph->periph_mode & PERIPH_CAP_TQING)
   1912 		printf(", tagged queueing");
   1913 
   1914 	printf("\n");
   1915 }
   1916 
   1917 /*
   1918  * scsipi_async_event_max_openings:
   1919  *
   1920  *	Update the maximum number of outstanding commands a
   1921  *	device may have.
   1922  */
   1923 void
   1924 scsipi_async_event_max_openings(chan, mo)
   1925 	struct scsipi_channel *chan;
   1926 	struct scsipi_max_openings *mo;
   1927 {
   1928 	struct scsipi_periph *periph;
   1929 	int minlun, maxlun;
   1930 
   1931 	if (mo->mo_lun == -1) {
   1932 		/*
   1933 		 * Wildcarded; apply it to all LUNs.
   1934 		 */
   1935 		minlun = 0;
   1936 		maxlun = chan->chan_nluns - 1;
   1937 	} else
   1938 		minlun = maxlun = mo->mo_lun;
   1939 
   1940 	for (; minlun <= maxlun; minlun++) {
   1941 		periph = scsipi_lookup_periph(chan, mo->mo_target, minlun);
   1942 		if (periph == NULL)
   1943 			continue;
   1944 
   1945 		if (mo->mo_openings < periph->periph_openings)
   1946 			periph->periph_openings = mo->mo_openings;
   1947 		else if (mo->mo_openings > periph->periph_openings &&
   1948 		    (periph->periph_flags & PERIPH_GROW_OPENINGS) != 0)
   1949 			periph->periph_openings = mo->mo_openings;
   1950 	}
   1951 }
   1952 
   1953 /*
   1954  * scsipi_async_event_xfer_mode:
   1955  *
   1956  *	Update the xfer mode for all periphs sharing the
   1957  *	specified I_T Nexus.
   1958  */
   1959 void
   1960 scsipi_async_event_xfer_mode(chan, xm)
   1961 	struct scsipi_channel *chan;
   1962 	struct scsipi_xfer_mode *xm;
   1963 {
   1964 	struct scsipi_periph *periph;
   1965 	int lun, announce, mode, period, offset;
   1966 
   1967 	for (lun = 0; lun < chan->chan_nluns; lun++) {
   1968 		periph = scsipi_lookup_periph(chan, xm->xm_target, lun);
   1969 		if (periph == NULL)
   1970 			continue;
   1971 		announce = 0;
   1972 
   1973 		/*
   1974 		 * Clamp the xfer mode down to this periph's capabilities.
   1975 		 */
   1976 		mode = xm->xm_mode & periph->periph_cap;
   1977 		if (mode & PERIPH_CAP_SYNC) {
   1978 			period = xm->xm_period;
   1979 			offset = xm->xm_offset;
   1980 		} else {
   1981 			period = 0;
   1982 			offset = 0;
   1983 		}
   1984 
   1985 		/*
   1986 		 * If we do not have a valid xfer mode yet, or the parameters
   1987 		 * are different, announce them.
   1988 		 */
   1989 		if ((periph->periph_flags & PERIPH_MODE_VALID) == 0 ||
   1990 		    periph->periph_mode != mode ||
   1991 		    periph->periph_period != period ||
   1992 		    periph->periph_offset != offset)
   1993 			announce = 1;
   1994 
   1995 		periph->periph_mode = mode;
   1996 		periph->periph_period = period;
   1997 		periph->periph_offset = offset;
   1998 		periph->periph_flags |= PERIPH_MODE_VALID;
   1999 
   2000 		if (announce)
   2001 			scsipi_print_xfer_mode(periph);
   2002 	}
   2003 }
   2004 
   2005 /*
   2006  * scsipi_set_xfer_mode:
   2007  *
   2008  *	Set the xfer mode for the specified I_T Nexus.
   2009  */
   2010 void
   2011 scsipi_set_xfer_mode(chan, target, immed)
   2012 	struct scsipi_channel *chan;
   2013 	int target, immed;
   2014 {
   2015 	struct scsipi_xfer_mode xm;
   2016 	struct scsipi_periph *itperiph;
   2017 	int lun, s;
   2018 
   2019 	/*
   2020 	 * Go to the minimal xfer mode.
   2021 	 */
   2022 	xm.xm_target = target;
   2023 	xm.xm_mode = 0;
   2024 	xm.xm_period = 0;			/* ignored */
   2025 	xm.xm_offset = 0;			/* ignored */
   2026 
   2027 	/*
   2028 	 * Find the first LUN we know about on this I_T Nexus.
   2029 	 */
   2030 	for (lun = 0; lun < chan->chan_nluns; lun++) {
   2031 		itperiph = scsipi_lookup_periph(chan, target, lun);
   2032 		if (itperiph != NULL)
   2033 			break;
   2034 	}
   2035 	if (itperiph != NULL)
   2036 		xm.xm_mode = itperiph->periph_cap;
   2037 
   2038 	/*
   2039 	 * Now issue the request to the adapter.
   2040 	 */
   2041 	s = splbio();
   2042 	scsipi_adapter_request(chan, ADAPTER_REQ_SET_XFER_MODE, &xm);
   2043 	splx(s);
   2044 
   2045 	/*
   2046 	 * If we want this to happen immediately, issue a dummy command,
   2047 	 * since most adapters can't really negotiate unless they're
   2048 	 * executing a job.
   2049 	 */
   2050 	if (immed != 0 && itperiph != NULL) {
   2051 		(void) scsipi_test_unit_ready(itperiph,
   2052 		    XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
   2053 		    XS_CTL_IGNORE_NOT_READY |
   2054 		    XS_CTL_IGNORE_MEDIA_CHANGE);
   2055 	}
   2056 }
   2057 
   2058 /*
   2059  * scsipi_channel_reset:
   2060  *
   2061  *	handle scsi bus reset
   2062  */
   2063 void
   2064 scsipi_async_event_channel_reset(chan)
   2065 	struct scsipi_channel *chan;
   2066 {
   2067 	struct scsipi_xfer *xs, *xs_next;
   2068 	struct scsipi_periph *periph;
   2069 	int target, lun;
   2070 
   2071 	/*
   2072 	 * Channel has been reset. Also mark as reset pending REQUEST_SENSE
   2073 	 * commands; as the sense is not available any more.
   2074 	 */
   2075 
   2076 	for (xs = TAILQ_FIRST(&chan->chan_queue); xs != NULL; xs = xs_next) {
   2077 		xs_next = TAILQ_NEXT(xs, channel_q);
   2078 		if (xs->xs_control & XS_CTL_REQSENSE) {
   2079 			xs->error = XS_RESET;
   2080 			scsipi_done(xs);
   2081 		}
   2082 	}
   2083 	/* Catch xs with pending sense which may not have a REQSENSE xs yet */
   2084 	for (target = 0; target < chan->chan_ntargets; target++) {
   2085 		if (target == chan->chan_id)
   2086 			continue;
   2087 		for (lun = 0; lun <  chan->chan_nluns; lun++) {
   2088 			periph = chan->chan_periphs[target][lun];
   2089 			if (periph) {
   2090 				xs = periph->periph_xscheck;
   2091 				if (xs)
   2092 					xs->error = XS_RESET;
   2093 			}
   2094 		}
   2095 	}
   2096 }
   2097 
   2098 
   2099 /*
   2100  * scsipi_adapter_addref:
   2101  *
   2102  *	Add a reference to the adapter pointed to by the provided
   2103  *	link, enabling the adapter if necessary.
   2104  */
   2105 int
   2106 scsipi_adapter_addref(adapt)
   2107 	struct scsipi_adapter *adapt;
   2108 {
   2109 	int s, error = 0;
   2110 
   2111 	s = splbio();
   2112 	if (adapt->adapt_refcnt++ == 0 && adapt->adapt_enable != NULL) {
   2113 		error = (*adapt->adapt_enable)(adapt->adapt_dev, 1);
   2114 		if (error)
   2115 			adapt->adapt_refcnt--;
   2116 	}
   2117 	splx(s);
   2118 	return (error);
   2119 }
   2120 
   2121 /*
   2122  * scsipi_adapter_delref:
   2123  *
   2124  *	Delete a reference to the adapter pointed to by the provided
   2125  *	link, disabling the adapter if possible.
   2126  */
   2127 void
   2128 scsipi_adapter_delref(adapt)
   2129 	struct scsipi_adapter *adapt;
   2130 {
   2131 	int s;
   2132 
   2133 	s = splbio();
   2134 	if (adapt->adapt_refcnt-- == 1 && adapt->adapt_enable != NULL)
   2135 		(void) (*adapt->adapt_enable)(adapt->adapt_dev, 0);
   2136 	splx(s);
   2137 }
   2138 
   2139 struct scsipi_syncparam {
   2140 	int	ss_factor;
   2141 	int	ss_period;	/* ns * 10 */
   2142 } scsipi_syncparams[] = {
   2143 	{ 0x0a,		250 },
   2144 	{ 0x0b,		303 },
   2145 	{ 0x0c,		500 },
   2146 };
   2147 const int scsipi_nsyncparams =
   2148     sizeof(scsipi_syncparams) / sizeof(scsipi_syncparams[0]);
   2149 
   2150 int
   2151 scsipi_sync_period_to_factor(period)
   2152 	int period;		/* ns * 10 */
   2153 {
   2154 	int i;
   2155 
   2156 	for (i = 0; i < scsipi_nsyncparams; i++) {
   2157 		if (period <= scsipi_syncparams[i].ss_period)
   2158 			return (scsipi_syncparams[i].ss_factor);
   2159 	}
   2160 
   2161 	return ((period / 10) / 4);
   2162 }
   2163 
   2164 int
   2165 scsipi_sync_factor_to_period(factor)
   2166 	int factor;
   2167 {
   2168 	int i;
   2169 
   2170 	for (i = 0; i < scsipi_nsyncparams; i++) {
   2171 		if (factor == scsipi_syncparams[i].ss_factor)
   2172 			return (scsipi_syncparams[i].ss_period);
   2173 	}
   2174 
   2175 	return ((factor * 4) * 10);
   2176 }
   2177 
   2178 int
   2179 scsipi_sync_factor_to_freq(factor)
   2180 	int factor;
   2181 {
   2182 	int i;
   2183 
   2184 	for (i = 0; i < scsipi_nsyncparams; i++) {
   2185 		if (factor == scsipi_syncparams[i].ss_factor)
   2186 			return (10000000 / scsipi_syncparams[i].ss_period);
   2187 	}
   2188 
   2189 	return (10000000 / ((factor * 4) * 10));
   2190 }
   2191 
   2192 #ifdef SCSIPI_DEBUG
   2193 /*
   2194  * Given a scsipi_xfer, dump the request, in all it's glory
   2195  */
   2196 void
   2197 show_scsipi_xs(xs)
   2198 	struct scsipi_xfer *xs;
   2199 {
   2200 
   2201 	printf("xs(%p): ", xs);
   2202 	printf("xs_control(0x%08x)", xs->xs_control);
   2203 	printf("xs_status(0x%08x)", xs->xs_status);
   2204 	printf("periph(%p)", xs->xs_periph);
   2205 	printf("retr(0x%x)", xs->xs_retries);
   2206 	printf("timo(0x%x)", xs->timeout);
   2207 	printf("cmd(%p)", xs->cmd);
   2208 	printf("len(0x%x)", xs->cmdlen);
   2209 	printf("data(%p)", xs->data);
   2210 	printf("len(0x%x)", xs->datalen);
   2211 	printf("res(0x%x)", xs->resid);
   2212 	printf("err(0x%x)", xs->error);
   2213 	printf("bp(%p)", xs->bp);
   2214 	show_scsipi_cmd(xs);
   2215 }
   2216 
   2217 void
   2218 show_scsipi_cmd(xs)
   2219 	struct scsipi_xfer *xs;
   2220 {
   2221 	u_char *b = (u_char *) xs->cmd;
   2222 	int i = 0;
   2223 
   2224 	scsipi_printaddr(xs->xs_periph);
   2225 	printf(" command: ");
   2226 
   2227 	if ((xs->xs_control & XS_CTL_RESET) == 0) {
   2228 		while (i < xs->cmdlen) {
   2229 			if (i)
   2230 				printf(",");
   2231 			printf("0x%x", b[i++]);
   2232 		}
   2233 		printf("-[%d bytes]\n", xs->datalen);
   2234 		if (xs->datalen)
   2235 			show_mem(xs->data, min(64, xs->datalen));
   2236 	} else
   2237 		printf("-RESET-\n");
   2238 }
   2239 
   2240 void
   2241 show_mem(address, num)
   2242 	u_char *address;
   2243 	int num;
   2244 {
   2245 	int x;
   2246 
   2247 	printf("------------------------------");
   2248 	for (x = 0; x < num; x++) {
   2249 		if ((x % 16) == 0)
   2250 			printf("\n%03d: ", x);
   2251 		printf("%02x ", *address++);
   2252 	}
   2253 	printf("\n------------------------------\n");
   2254 }
   2255 #endif /* SCSIPI_DEBUG */
   2256