Home | History | Annotate | Line # | Download | only in scsipi
scsipi_base.c revision 1.139
      1 /*	$NetBSD: scsipi_base.c,v 1.139 2006/10/12 01:31:57 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 1999, 2000, 2002, 2003, 2004 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 <sys/cdefs.h>
     41 __KERNEL_RCSID(0, "$NetBSD: scsipi_base.c,v 1.139 2006/10/12 01:31:57 christos Exp $");
     42 
     43 #include "opt_scsi.h"
     44 
     45 #include <sys/param.h>
     46 #include <sys/systm.h>
     47 #include <sys/kernel.h>
     48 #include <sys/buf.h>
     49 #include <sys/uio.h>
     50 #include <sys/malloc.h>
     51 #include <sys/pool.h>
     52 #include <sys/errno.h>
     53 #include <sys/device.h>
     54 #include <sys/proc.h>
     55 #include <sys/kthread.h>
     56 #include <sys/hash.h>
     57 
     58 #include <uvm/uvm_extern.h>
     59 
     60 #include <dev/scsipi/scsi_spc.h>
     61 #include <dev/scsipi/scsipi_all.h>
     62 #include <dev/scsipi/scsipi_disk.h>
     63 #include <dev/scsipi/scsipiconf.h>
     64 #include <dev/scsipi/scsipi_base.h>
     65 
     66 #include <dev/scsipi/scsi_all.h>
     67 #include <dev/scsipi/scsi_message.h>
     68 
     69 static int	scsipi_complete(struct scsipi_xfer *);
     70 static void	scsipi_request_sense(struct scsipi_xfer *);
     71 static int	scsipi_enqueue(struct scsipi_xfer *);
     72 static void	scsipi_run_queue(struct scsipi_channel *chan);
     73 
     74 static void	scsipi_completion_thread(void *);
     75 
     76 static void	scsipi_get_tag(struct scsipi_xfer *);
     77 static void	scsipi_put_tag(struct scsipi_xfer *);
     78 
     79 static int	scsipi_get_resource(struct scsipi_channel *);
     80 static void	scsipi_put_resource(struct scsipi_channel *);
     81 
     82 static void	scsipi_async_event_max_openings(struct scsipi_channel *,
     83 		    struct scsipi_max_openings *);
     84 static void	scsipi_async_event_xfer_mode(struct scsipi_channel *,
     85 		    struct scsipi_xfer_mode *);
     86 static void	scsipi_async_event_channel_reset(struct scsipi_channel *);
     87 
     88 static struct pool scsipi_xfer_pool;
     89 
     90 /*
     91  * scsipi_init:
     92  *
     93  *	Called when a scsibus or atapibus is attached to the system
     94  *	to initialize shared data structures.
     95  */
     96 void
     97 scsipi_init(void)
     98 {
     99 	static int scsipi_init_done;
    100 
    101 	if (scsipi_init_done)
    102 		return;
    103 	scsipi_init_done = 1;
    104 
    105 	/* Initialize the scsipi_xfer pool. */
    106 	pool_init(&scsipi_xfer_pool, sizeof(struct scsipi_xfer), 0,
    107 	    0, 0, "scxspl", NULL);
    108 	if (pool_prime(&scsipi_xfer_pool,
    109 	    PAGE_SIZE / sizeof(struct scsipi_xfer)) == ENOMEM) {
    110 		printf("WARNING: not enough memory for scsipi_xfer_pool\n");
    111 	}
    112 }
    113 
    114 /*
    115  * scsipi_channel_init:
    116  *
    117  *	Initialize a scsipi_channel when it is attached.
    118  */
    119 int
    120 scsipi_channel_init(struct scsipi_channel *chan)
    121 {
    122 	int i;
    123 
    124 	/* Initialize shared data. */
    125 	scsipi_init();
    126 
    127 	/* Initialize the queues. */
    128 	TAILQ_INIT(&chan->chan_queue);
    129 	TAILQ_INIT(&chan->chan_complete);
    130 
    131 	for (i = 0; i < SCSIPI_CHAN_PERIPH_BUCKETS; i++)
    132 		LIST_INIT(&chan->chan_periphtab[i]);
    133 
    134 	/*
    135 	 * Create the asynchronous completion thread.
    136 	 */
    137 	kthread_create(scsipi_create_completion_thread, chan);
    138 	return (0);
    139 }
    140 
    141 /*
    142  * scsipi_channel_shutdown:
    143  *
    144  *	Shutdown a scsipi_channel.
    145  */
    146 void
    147 scsipi_channel_shutdown(struct scsipi_channel *chan)
    148 {
    149 
    150 	/*
    151 	 * Shut down the completion thread.
    152 	 */
    153 	chan->chan_tflags |= SCSIPI_CHANT_SHUTDOWN;
    154 	wakeup(&chan->chan_complete);
    155 
    156 	/*
    157 	 * Now wait for the thread to exit.
    158 	 */
    159 	while (chan->chan_thread != NULL)
    160 		(void) tsleep(&chan->chan_thread, PRIBIO, "scshut", 0);
    161 }
    162 
    163 static uint32_t
    164 scsipi_chan_periph_hash(uint64_t t, uint64_t l)
    165 {
    166 	uint32_t hash;
    167 
    168 	hash = hash32_buf(&t, sizeof(t), HASH32_BUF_INIT);
    169 	hash = hash32_buf(&l, sizeof(l), hash);
    170 
    171 	return (hash & SCSIPI_CHAN_PERIPH_HASHMASK);
    172 }
    173 
    174 /*
    175  * scsipi_insert_periph:
    176  *
    177  *	Insert a periph into the channel.
    178  */
    179 void
    180 scsipi_insert_periph(struct scsipi_channel *chan, struct scsipi_periph *periph)
    181 {
    182 	uint32_t hash;
    183 	int s;
    184 
    185 	hash = scsipi_chan_periph_hash(periph->periph_target,
    186 	    periph->periph_lun);
    187 
    188 	s = splbio();
    189 	LIST_INSERT_HEAD(&chan->chan_periphtab[hash], periph, periph_hash);
    190 	splx(s);
    191 }
    192 
    193 /*
    194  * scsipi_remove_periph:
    195  *
    196  *	Remove a periph from the channel.
    197  */
    198 void
    199 scsipi_remove_periph(struct scsipi_channel *chan __unused,
    200     struct scsipi_periph *periph)
    201 {
    202 	int s;
    203 
    204 	s = splbio();
    205 	LIST_REMOVE(periph, periph_hash);
    206 	splx(s);
    207 }
    208 
    209 /*
    210  * scsipi_lookup_periph:
    211  *
    212  *	Lookup a periph on the specified channel.
    213  */
    214 struct scsipi_periph *
    215 scsipi_lookup_periph(struct scsipi_channel *chan, int target, int lun)
    216 {
    217 	struct scsipi_periph *periph;
    218 	uint32_t hash;
    219 	int s;
    220 
    221 	if (target >= chan->chan_ntargets ||
    222 	    lun >= chan->chan_nluns)
    223 		return (NULL);
    224 
    225 	hash = scsipi_chan_periph_hash(target, lun);
    226 
    227 	s = splbio();
    228 	LIST_FOREACH(periph, &chan->chan_periphtab[hash], periph_hash) {
    229 		if (periph->periph_target == target &&
    230 		    periph->periph_lun == lun)
    231 			break;
    232 	}
    233 	splx(s);
    234 
    235 	return (periph);
    236 }
    237 
    238 /*
    239  * scsipi_get_resource:
    240  *
    241  *	Allocate a single xfer `resource' from the channel.
    242  *
    243  *	NOTE: Must be called at splbio().
    244  */
    245 static int
    246 scsipi_get_resource(struct scsipi_channel *chan)
    247 {
    248 	struct scsipi_adapter *adapt = chan->chan_adapter;
    249 
    250 	if (chan->chan_flags & SCSIPI_CHAN_OPENINGS) {
    251 		if (chan->chan_openings > 0) {
    252 			chan->chan_openings--;
    253 			return (1);
    254 		}
    255 		return (0);
    256 	}
    257 
    258 	if (adapt->adapt_openings > 0) {
    259 		adapt->adapt_openings--;
    260 		return (1);
    261 	}
    262 	return (0);
    263 }
    264 
    265 /*
    266  * scsipi_grow_resources:
    267  *
    268  *	Attempt to grow resources for a channel.  If this succeeds,
    269  *	we allocate one for our caller.
    270  *
    271  *	NOTE: Must be called at splbio().
    272  */
    273 static inline int
    274 scsipi_grow_resources(struct scsipi_channel *chan)
    275 {
    276 
    277 	if (chan->chan_flags & SCSIPI_CHAN_CANGROW) {
    278 		if ((chan->chan_flags & SCSIPI_CHAN_TACTIVE) == 0) {
    279 			scsipi_adapter_request(chan,
    280 			    ADAPTER_REQ_GROW_RESOURCES, NULL);
    281 			return (scsipi_get_resource(chan));
    282 		}
    283 		/*
    284 		 * ask the channel thread to do it. It'll have to thaw the
    285 		 * queue
    286 		 */
    287 		scsipi_channel_freeze(chan, 1);
    288 		chan->chan_tflags |= SCSIPI_CHANT_GROWRES;
    289 		wakeup(&chan->chan_complete);
    290 		return (0);
    291 	}
    292 
    293 	return (0);
    294 }
    295 
    296 /*
    297  * scsipi_put_resource:
    298  *
    299  *	Free a single xfer `resource' to the channel.
    300  *
    301  *	NOTE: Must be called at splbio().
    302  */
    303 static void
    304 scsipi_put_resource(struct scsipi_channel *chan)
    305 {
    306 	struct scsipi_adapter *adapt = chan->chan_adapter;
    307 
    308 	if (chan->chan_flags & SCSIPI_CHAN_OPENINGS)
    309 		chan->chan_openings++;
    310 	else
    311 		adapt->adapt_openings++;
    312 }
    313 
    314 /*
    315  * scsipi_get_tag:
    316  *
    317  *	Get a tag ID for the specified xfer.
    318  *
    319  *	NOTE: Must be called at splbio().
    320  */
    321 static void
    322 scsipi_get_tag(struct scsipi_xfer *xs)
    323 {
    324 	struct scsipi_periph *periph = xs->xs_periph;
    325 	int bit, tag;
    326 	u_int word;
    327 
    328 	bit = 0;	/* XXX gcc */
    329 	for (word = 0; word < PERIPH_NTAGWORDS; word++) {
    330 		bit = ffs(periph->periph_freetags[word]);
    331 		if (bit != 0)
    332 			break;
    333 	}
    334 #ifdef DIAGNOSTIC
    335 	if (word == PERIPH_NTAGWORDS) {
    336 		scsipi_printaddr(periph);
    337 		printf("no free tags\n");
    338 		panic("scsipi_get_tag");
    339 	}
    340 #endif
    341 
    342 	bit -= 1;
    343 	periph->periph_freetags[word] &= ~(1 << bit);
    344 	tag = (word << 5) | bit;
    345 
    346 	/* XXX Should eventually disallow this completely. */
    347 	if (tag >= periph->periph_openings) {
    348 		scsipi_printaddr(periph);
    349 		printf("WARNING: tag %d greater than available openings %d\n",
    350 		    tag, periph->periph_openings);
    351 	}
    352 
    353 	xs->xs_tag_id = tag;
    354 }
    355 
    356 /*
    357  * scsipi_put_tag:
    358  *
    359  *	Put the tag ID for the specified xfer back into the pool.
    360  *
    361  *	NOTE: Must be called at splbio().
    362  */
    363 static void
    364 scsipi_put_tag(struct scsipi_xfer *xs)
    365 {
    366 	struct scsipi_periph *periph = xs->xs_periph;
    367 	int word, bit;
    368 
    369 	word = xs->xs_tag_id >> 5;
    370 	bit = xs->xs_tag_id & 0x1f;
    371 
    372 	periph->periph_freetags[word] |= (1 << bit);
    373 }
    374 
    375 /*
    376  * scsipi_get_xs:
    377  *
    378  *	Allocate an xfer descriptor and associate it with the
    379  *	specified peripherial.  If the peripherial has no more
    380  *	available command openings, we either block waiting for
    381  *	one to become available, or fail.
    382  */
    383 struct scsipi_xfer *
    384 scsipi_get_xs(struct scsipi_periph *periph, int flags)
    385 {
    386 	struct scsipi_xfer *xs;
    387 	int s;
    388 
    389 	SC_DEBUG(periph, SCSIPI_DB3, ("scsipi_get_xs\n"));
    390 
    391 	KASSERT(!cold);
    392 
    393 #ifdef DIAGNOSTIC
    394 	/*
    395 	 * URGENT commands can never be ASYNC.
    396 	 */
    397 	if ((flags & (XS_CTL_URGENT|XS_CTL_ASYNC)) ==
    398 	    (XS_CTL_URGENT|XS_CTL_ASYNC)) {
    399 		scsipi_printaddr(periph);
    400 		printf("URGENT and ASYNC\n");
    401 		panic("scsipi_get_xs");
    402 	}
    403 #endif
    404 
    405 	s = splbio();
    406 	/*
    407 	 * Wait for a command opening to become available.  Rules:
    408 	 *
    409 	 *	- All xfers must wait for an available opening.
    410 	 *	  Exception: URGENT xfers can proceed when
    411 	 *	  active == openings, because we use the opening
    412 	 *	  of the command we're recovering for.
    413 	 *	- if the periph has sense pending, only URGENT & REQSENSE
    414 	 *	  xfers may proceed.
    415 	 *
    416 	 *	- If the periph is recovering, only URGENT xfers may
    417 	 *	  proceed.
    418 	 *
    419 	 *	- If the periph is currently executing a recovery
    420 	 *	  command, URGENT commands must block, because only
    421 	 *	  one recovery command can execute at a time.
    422 	 */
    423 	for (;;) {
    424 		if (flags & XS_CTL_URGENT) {
    425 			if (periph->periph_active > periph->periph_openings)
    426 				goto wait_for_opening;
    427 			if (periph->periph_flags & PERIPH_SENSE) {
    428 				if ((flags & XS_CTL_REQSENSE) == 0)
    429 					goto wait_for_opening;
    430 			} else {
    431 				if ((periph->periph_flags &
    432 				    PERIPH_RECOVERY_ACTIVE) != 0)
    433 					goto wait_for_opening;
    434 				periph->periph_flags |= PERIPH_RECOVERY_ACTIVE;
    435 			}
    436 			break;
    437 		}
    438 		if (periph->periph_active >= periph->periph_openings ||
    439 		    (periph->periph_flags & PERIPH_RECOVERING) != 0)
    440 			goto wait_for_opening;
    441 		periph->periph_active++;
    442 		break;
    443 
    444  wait_for_opening:
    445 		if (flags & XS_CTL_NOSLEEP) {
    446 			splx(s);
    447 			return (NULL);
    448 		}
    449 		SC_DEBUG(periph, SCSIPI_DB3, ("sleeping\n"));
    450 		periph->periph_flags |= PERIPH_WAITING;
    451 		(void) tsleep(periph, PRIBIO, "getxs", 0);
    452 	}
    453 	SC_DEBUG(periph, SCSIPI_DB3, ("calling pool_get\n"));
    454 	xs = pool_get(&scsipi_xfer_pool,
    455 	    ((flags & XS_CTL_NOSLEEP) != 0 ? PR_NOWAIT : PR_WAITOK));
    456 	if (xs == NULL) {
    457 		if (flags & XS_CTL_URGENT) {
    458 			if ((flags & XS_CTL_REQSENSE) == 0)
    459 				periph->periph_flags &= ~PERIPH_RECOVERY_ACTIVE;
    460 		} else
    461 			periph->periph_active--;
    462 		scsipi_printaddr(periph);
    463 		printf("unable to allocate %sscsipi_xfer\n",
    464 		    (flags & XS_CTL_URGENT) ? "URGENT " : "");
    465 	}
    466 	splx(s);
    467 
    468 	SC_DEBUG(periph, SCSIPI_DB3, ("returning\n"));
    469 
    470 	if (xs != NULL) {
    471 		memset(xs, 0, sizeof(*xs));
    472 		callout_init(&xs->xs_callout);
    473 		xs->xs_periph = periph;
    474 		xs->xs_control = flags;
    475 		xs->xs_status = 0;
    476 		s = splbio();
    477 		TAILQ_INSERT_TAIL(&periph->periph_xferq, xs, device_q);
    478 		splx(s);
    479 	}
    480 	return (xs);
    481 }
    482 
    483 /*
    484  * scsipi_put_xs:
    485  *
    486  *	Release an xfer descriptor, decreasing the outstanding command
    487  *	count for the peripherial.  If there is a thread waiting for
    488  *	an opening, wake it up.  If not, kick any queued I/O the
    489  *	peripherial may have.
    490  *
    491  *	NOTE: Must be called at splbio().
    492  */
    493 void
    494 scsipi_put_xs(struct scsipi_xfer *xs)
    495 {
    496 	struct scsipi_periph *periph = xs->xs_periph;
    497 	int flags = xs->xs_control;
    498 
    499 	SC_DEBUG(periph, SCSIPI_DB3, ("scsipi_free_xs\n"));
    500 
    501 	TAILQ_REMOVE(&periph->periph_xferq, xs, device_q);
    502 	pool_put(&scsipi_xfer_pool, xs);
    503 
    504 #ifdef DIAGNOSTIC
    505 	if ((periph->periph_flags & PERIPH_RECOVERY_ACTIVE) != 0 &&
    506 	    periph->periph_active == 0) {
    507 		scsipi_printaddr(periph);
    508 		printf("recovery without a command to recovery for\n");
    509 		panic("scsipi_put_xs");
    510 	}
    511 #endif
    512 
    513 	if (flags & XS_CTL_URGENT) {
    514 		if ((flags & XS_CTL_REQSENSE) == 0)
    515 			periph->periph_flags &= ~PERIPH_RECOVERY_ACTIVE;
    516 	} else
    517 		periph->periph_active--;
    518 	if (periph->periph_active == 0 &&
    519 	    (periph->periph_flags & PERIPH_WAITDRAIN) != 0) {
    520 		periph->periph_flags &= ~PERIPH_WAITDRAIN;
    521 		wakeup(&periph->periph_active);
    522 	}
    523 
    524 	if (periph->periph_flags & PERIPH_WAITING) {
    525 		periph->periph_flags &= ~PERIPH_WAITING;
    526 		wakeup(periph);
    527 	} else {
    528 		if (periph->periph_switch->psw_start != NULL &&
    529 		    device_is_active(periph->periph_dev)) {
    530 			SC_DEBUG(periph, SCSIPI_DB2,
    531 			    ("calling private start()\n"));
    532 			(*periph->periph_switch->psw_start)(periph);
    533 		}
    534 	}
    535 }
    536 
    537 /*
    538  * scsipi_channel_freeze:
    539  *
    540  *	Freeze a channel's xfer queue.
    541  */
    542 void
    543 scsipi_channel_freeze(struct scsipi_channel *chan, int count)
    544 {
    545 	int s;
    546 
    547 	s = splbio();
    548 	chan->chan_qfreeze += count;
    549 	splx(s);
    550 }
    551 
    552 /*
    553  * scsipi_channel_thaw:
    554  *
    555  *	Thaw a channel's xfer queue.
    556  */
    557 void
    558 scsipi_channel_thaw(struct scsipi_channel *chan, int count)
    559 {
    560 	int s;
    561 
    562 	s = splbio();
    563 	chan->chan_qfreeze -= count;
    564 	/*
    565 	 * Don't let the freeze count go negative.
    566 	 *
    567 	 * Presumably the adapter driver could keep track of this,
    568 	 * but it might just be easier to do this here so as to allow
    569 	 * multiple callers, including those outside the adapter driver.
    570 	 */
    571 	if (chan->chan_qfreeze < 0) {
    572 		chan->chan_qfreeze = 0;
    573 	}
    574 	splx(s);
    575 	/*
    576 	 * Kick the channel's queue here.  Note, we may be running in
    577 	 * interrupt context (softclock or HBA's interrupt), so the adapter
    578 	 * driver had better not sleep.
    579 	 */
    580 	if (chan->chan_qfreeze == 0)
    581 		scsipi_run_queue(chan);
    582 }
    583 
    584 /*
    585  * scsipi_channel_timed_thaw:
    586  *
    587  *	Thaw a channel after some time has expired. This will also
    588  * 	run the channel's queue if the freeze count has reached 0.
    589  */
    590 void
    591 scsipi_channel_timed_thaw(void *arg)
    592 {
    593 	struct scsipi_channel *chan = arg;
    594 
    595 	scsipi_channel_thaw(chan, 1);
    596 }
    597 
    598 /*
    599  * scsipi_periph_freeze:
    600  *
    601  *	Freeze a device's xfer queue.
    602  */
    603 void
    604 scsipi_periph_freeze(struct scsipi_periph *periph, int count)
    605 {
    606 	int s;
    607 
    608 	s = splbio();
    609 	periph->periph_qfreeze += count;
    610 	splx(s);
    611 }
    612 
    613 /*
    614  * scsipi_periph_thaw:
    615  *
    616  *	Thaw a device's xfer queue.
    617  */
    618 void
    619 scsipi_periph_thaw(struct scsipi_periph *periph, int count)
    620 {
    621 	int s;
    622 
    623 	s = splbio();
    624 	periph->periph_qfreeze -= count;
    625 #ifdef DIAGNOSTIC
    626 	if (periph->periph_qfreeze < 0) {
    627 		static const char pc[] = "periph freeze count < 0";
    628 		scsipi_printaddr(periph);
    629 		printf("%s\n", pc);
    630 		panic(pc);
    631 	}
    632 #endif
    633 	if (periph->periph_qfreeze == 0 &&
    634 	    (periph->periph_flags & PERIPH_WAITING) != 0)
    635 		wakeup(periph);
    636 	splx(s);
    637 }
    638 
    639 /*
    640  * scsipi_periph_timed_thaw:
    641  *
    642  *	Thaw a device after some time has expired.
    643  */
    644 void
    645 scsipi_periph_timed_thaw(void *arg)
    646 {
    647 	int s;
    648 	struct scsipi_periph *periph = arg;
    649 
    650 	callout_stop(&periph->periph_callout);
    651 
    652 	s = splbio();
    653 	scsipi_periph_thaw(periph, 1);
    654 	if ((periph->periph_channel->chan_flags & SCSIPI_CHAN_TACTIVE) == 0) {
    655 		/*
    656 		 * Kick the channel's queue here.  Note, we're running in
    657 		 * interrupt context (softclock), so the adapter driver
    658 		 * had better not sleep.
    659 		 */
    660 		scsipi_run_queue(periph->periph_channel);
    661 	} else {
    662 		/*
    663 		 * Tell the completion thread to kick the channel's queue here.
    664 		 */
    665 		periph->periph_channel->chan_tflags |= SCSIPI_CHANT_KICK;
    666 		wakeup(&periph->periph_channel->chan_complete);
    667 	}
    668 	splx(s);
    669 }
    670 
    671 /*
    672  * scsipi_wait_drain:
    673  *
    674  *	Wait for a periph's pending xfers to drain.
    675  */
    676 void
    677 scsipi_wait_drain(struct scsipi_periph *periph)
    678 {
    679 	int s;
    680 
    681 	s = splbio();
    682 	while (periph->periph_active != 0) {
    683 		periph->periph_flags |= PERIPH_WAITDRAIN;
    684 		(void) tsleep(&periph->periph_active, PRIBIO, "sxdrn", 0);
    685 	}
    686 	splx(s);
    687 }
    688 
    689 /*
    690  * scsipi_kill_pending:
    691  *
    692  *	Kill off all pending xfers for a periph.
    693  *
    694  *	NOTE: Must be called at splbio().
    695  */
    696 void
    697 scsipi_kill_pending(struct scsipi_periph *periph)
    698 {
    699 
    700 	(*periph->periph_channel->chan_bustype->bustype_kill_pending)(periph);
    701 	scsipi_wait_drain(periph);
    702 }
    703 
    704 /*
    705  * scsipi_print_cdb:
    706  * prints a command descriptor block (for debug purpose, error messages,
    707  * SCSIPI_VERBOSE, ...)
    708  */
    709 void
    710 scsipi_print_cdb(struct scsipi_generic *cmd)
    711 {
    712 	int i, j;
    713 
    714  	printf("0x%02x", cmd->opcode);
    715 
    716  	switch (CDB_GROUPID(cmd->opcode)) {
    717  	case CDB_GROUPID_0:
    718  		j = CDB_GROUP0;
    719  		break;
    720  	case CDB_GROUPID_1:
    721  		j = CDB_GROUP1;
    722  		break;
    723  	case CDB_GROUPID_2:
    724  		j = CDB_GROUP2;
    725  		break;
    726  	case CDB_GROUPID_3:
    727  		j = CDB_GROUP3;
    728  		break;
    729  	case CDB_GROUPID_4:
    730  		j = CDB_GROUP4;
    731  		break;
    732  	case CDB_GROUPID_5:
    733  		j = CDB_GROUP5;
    734  		break;
    735  	case CDB_GROUPID_6:
    736  		j = CDB_GROUP6;
    737  		break;
    738  	case CDB_GROUPID_7:
    739  		j = CDB_GROUP7;
    740  		break;
    741  	default:
    742  		j = 0;
    743  	}
    744  	if (j == 0)
    745  		j = sizeof (cmd->bytes);
    746  	for (i = 0; i < j-1; i++) /* already done the opcode */
    747  		printf(" %02x", cmd->bytes[i]);
    748 }
    749 
    750 /*
    751  * scsipi_interpret_sense:
    752  *
    753  *	Look at the returned sense and act on the error, determining
    754  *	the unix error number to pass back.  (0 = report no error)
    755  *
    756  *	NOTE: If we return ERESTART, we are expected to haved
    757  *	thawed the device!
    758  *
    759  *	THIS IS THE DEFAULT ERROR HANDLER FOR SCSI DEVICES.
    760  */
    761 int
    762 scsipi_interpret_sense(struct scsipi_xfer *xs)
    763 {
    764 	struct scsi_sense_data *sense;
    765 	struct scsipi_periph *periph = xs->xs_periph;
    766 	u_int8_t key;
    767 	int error;
    768 #ifndef	SCSIVERBOSE
    769 	u_int32_t info;
    770 	static const char *error_mes[] = {
    771 		"soft error (corrected)",
    772 		"not ready", "medium error",
    773 		"non-media hardware failure", "illegal request",
    774 		"unit attention", "readonly device",
    775 		"no data found", "vendor unique",
    776 		"copy aborted", "command aborted",
    777 		"search returned equal", "volume overflow",
    778 		"verify miscompare", "unknown error key"
    779 	};
    780 #endif
    781 
    782 	sense = &xs->sense.scsi_sense;
    783 #ifdef SCSIPI_DEBUG
    784 	if (periph->periph_flags & SCSIPI_DB1) {
    785 		int count;
    786 		scsipi_printaddr(periph);
    787 		printf(" sense debug information:\n");
    788 		printf("\tcode 0x%x valid %d\n",
    789 			SSD_RCODE(sense->response_code),
    790 			sense->response_code & SSD_RCODE_VALID ? 1 : 0);
    791 		printf("\tseg 0x%x key 0x%x ili 0x%x eom 0x%x fmark 0x%x\n",
    792 			sense->segment,
    793 			SSD_SENSE_KEY(sense->flags),
    794 			sense->flags & SSD_ILI ? 1 : 0,
    795 			sense->flags & SSD_EOM ? 1 : 0,
    796 			sense->flags & SSD_FILEMARK ? 1 : 0);
    797 		printf("\ninfo: 0x%x 0x%x 0x%x 0x%x followed by %d "
    798 			"extra bytes\n",
    799 			sense->info[0],
    800 			sense->info[1],
    801 			sense->info[2],
    802 			sense->info[3],
    803 			sense->extra_len);
    804 		printf("\textra: ");
    805 		for (count = 0; count < SSD_ADD_BYTES_LIM(sense); count++)
    806 			printf("0x%x ", sense->csi[count]);
    807 		printf("\n");
    808 	}
    809 #endif
    810 
    811 	/*
    812 	 * If the periph has it's own error handler, call it first.
    813 	 * If it returns a legit error value, return that, otherwise
    814 	 * it wants us to continue with normal error processing.
    815 	 */
    816 	if (periph->periph_switch->psw_error != NULL) {
    817 		SC_DEBUG(periph, SCSIPI_DB2,
    818 		    ("calling private err_handler()\n"));
    819 		error = (*periph->periph_switch->psw_error)(xs);
    820 		if (error != EJUSTRETURN)
    821 			return (error);
    822 	}
    823 	/* otherwise use the default */
    824 	switch (SSD_RCODE(sense->response_code)) {
    825 
    826 		/*
    827 		 * Old SCSI-1 and SASI devices respond with
    828 		 * codes other than 70.
    829 		 */
    830 	case 0x00:		/* no error (command completed OK) */
    831 		return (0);
    832 	case 0x04:		/* drive not ready after it was selected */
    833 		if ((periph->periph_flags & PERIPH_REMOVABLE) != 0)
    834 			periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    835 		if ((xs->xs_control & XS_CTL_IGNORE_NOT_READY) != 0)
    836 			return (0);
    837 		/* XXX - display some sort of error here? */
    838 		return (EIO);
    839 	case 0x20:		/* invalid command */
    840 		if ((xs->xs_control &
    841 		     XS_CTL_IGNORE_ILLEGAL_REQUEST) != 0)
    842 			return (0);
    843 		return (EINVAL);
    844 	case 0x25:		/* invalid LUN (Adaptec ACB-4000) */
    845 		return (EACCES);
    846 
    847 		/*
    848 		 * If it's code 70, use the extended stuff and
    849 		 * interpret the key
    850 		 */
    851 	case 0x71:		/* delayed error */
    852 		scsipi_printaddr(periph);
    853 		key = SSD_SENSE_KEY(sense->flags);
    854 		printf(" DEFERRED ERROR, key = 0x%x\n", key);
    855 		/* FALLTHROUGH */
    856 	case 0x70:
    857 #ifndef	SCSIVERBOSE
    858 		if ((sense->response_code & SSD_RCODE_VALID) != 0)
    859 			info = _4btol(sense->info);
    860 		else
    861 			info = 0;
    862 #endif
    863 		key = SSD_SENSE_KEY(sense->flags);
    864 
    865 		switch (key) {
    866 		case SKEY_NO_SENSE:
    867 		case SKEY_RECOVERED_ERROR:
    868 			if (xs->resid == xs->datalen && xs->datalen) {
    869 				/*
    870 				 * Why is this here?
    871 				 */
    872 				xs->resid = 0;	/* not short read */
    873 			}
    874 		case SKEY_EQUAL:
    875 			error = 0;
    876 			break;
    877 		case SKEY_NOT_READY:
    878 			if ((periph->periph_flags & PERIPH_REMOVABLE) != 0)
    879 				periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    880 			if ((xs->xs_control & XS_CTL_IGNORE_NOT_READY) != 0)
    881 				return (0);
    882 			if (sense->asc == 0x3A) {
    883 				error = ENODEV; /* Medium not present */
    884 				if (xs->xs_control & XS_CTL_SILENT_NODEV)
    885 					return (error);
    886 			} else
    887 				error = EIO;
    888 			if ((xs->xs_control & XS_CTL_SILENT) != 0)
    889 				return (error);
    890 			break;
    891 		case SKEY_ILLEGAL_REQUEST:
    892 			if ((xs->xs_control &
    893 			     XS_CTL_IGNORE_ILLEGAL_REQUEST) != 0)
    894 				return (0);
    895 			/*
    896 			 * Handle the case where a device reports
    897 			 * Logical Unit Not Supported during discovery.
    898 			 */
    899 			if ((xs->xs_control & XS_CTL_DISCOVERY) != 0 &&
    900 			    sense->asc == 0x25 &&
    901 			    sense->ascq == 0x00)
    902 				return (EINVAL);
    903 			if ((xs->xs_control & XS_CTL_SILENT) != 0)
    904 				return (EIO);
    905 			error = EINVAL;
    906 			break;
    907 		case SKEY_UNIT_ATTENTION:
    908 			if (sense->asc == 0x29 &&
    909 			    sense->ascq == 0x00) {
    910 				/* device or bus reset */
    911 				return (ERESTART);
    912 			}
    913 			if ((periph->periph_flags & PERIPH_REMOVABLE) != 0)
    914 				periph->periph_flags &= ~PERIPH_MEDIA_LOADED;
    915 			if ((xs->xs_control &
    916 			     XS_CTL_IGNORE_MEDIA_CHANGE) != 0 ||
    917 				/* XXX Should reupload any transient state. */
    918 				(periph->periph_flags &
    919 				 PERIPH_REMOVABLE) == 0) {
    920 				return (ERESTART);
    921 			}
    922 			if ((xs->xs_control & XS_CTL_SILENT) != 0)
    923 				return (EIO);
    924 			error = EIO;
    925 			break;
    926 		case SKEY_DATA_PROTECT:
    927 			error = EROFS;
    928 			break;
    929 		case SKEY_BLANK_CHECK:
    930 			error = 0;
    931 			break;
    932 		case SKEY_ABORTED_COMMAND:
    933 			if (xs->xs_retries != 0) {
    934 				xs->xs_retries--;
    935 				error = ERESTART;
    936 			} else
    937 				error = EIO;
    938 			break;
    939 		case SKEY_VOLUME_OVERFLOW:
    940 			error = ENOSPC;
    941 			break;
    942 		default:
    943 			error = EIO;
    944 			break;
    945 		}
    946 
    947 #ifdef SCSIVERBOSE
    948 		if (key && (xs->xs_control & XS_CTL_SILENT) == 0)
    949 			scsipi_print_sense(xs, 0);
    950 #else
    951 		if (key) {
    952 			scsipi_printaddr(periph);
    953 			printf("%s", error_mes[key - 1]);
    954 			if ((sense->response_code & SSD_RCODE_VALID) != 0) {
    955 				switch (key) {
    956 				case SKEY_NOT_READY:
    957 				case SKEY_ILLEGAL_REQUEST:
    958 				case SKEY_UNIT_ATTENTION:
    959 				case SKEY_DATA_PROTECT:
    960 					break;
    961 				case SKEY_BLANK_CHECK:
    962 					printf(", requested size: %d (decimal)",
    963 					    info);
    964 					break;
    965 				case SKEY_ABORTED_COMMAND:
    966 					if (xs->xs_retries)
    967 						printf(", retrying");
    968 					printf(", cmd 0x%x, info 0x%x",
    969 					    xs->cmd->opcode, info);
    970 					break;
    971 				default:
    972 					printf(", info = %d (decimal)", info);
    973 				}
    974 			}
    975 			if (sense->extra_len != 0) {
    976 				int n;
    977 				printf(", data =");
    978 				for (n = 0; n < sense->extra_len; n++)
    979 					printf(" %02x",
    980 					    sense->csi[n]);
    981 			}
    982 			printf("\n");
    983 		}
    984 #endif
    985 		return (error);
    986 
    987 	/*
    988 	 * Some other code, just report it
    989 	 */
    990 	default:
    991 #if    defined(SCSIDEBUG) || defined(DEBUG)
    992 	{
    993 		static const char *uc = "undecodable sense error";
    994 		int i;
    995 		u_int8_t *cptr = (u_int8_t *) sense;
    996 		scsipi_printaddr(periph);
    997 		if (xs->cmd == &xs->cmdstore) {
    998 			printf("%s for opcode 0x%x, data=",
    999 			    uc, xs->cmdstore.opcode);
   1000 		} else {
   1001 			printf("%s, data=", uc);
   1002 		}
   1003 		for (i = 0; i < sizeof (sense); i++)
   1004 			printf(" 0x%02x", *(cptr++) & 0xff);
   1005 		printf("\n");
   1006 	}
   1007 #else
   1008 		scsipi_printaddr(periph);
   1009 		printf("Sense Error Code 0x%x",
   1010 			SSD_RCODE(sense->response_code));
   1011 		if ((sense->response_code & SSD_RCODE_VALID) != 0) {
   1012 			struct scsi_sense_data_unextended *usense =
   1013 			    (struct scsi_sense_data_unextended *)sense;
   1014 			printf(" at block no. %d (decimal)",
   1015 			    _3btol(usense->block));
   1016 		}
   1017 		printf("\n");
   1018 #endif
   1019 		return (EIO);
   1020 	}
   1021 }
   1022 
   1023 /*
   1024  * scsipi_size:
   1025  *
   1026  *	Find out from the device what its capacity is.
   1027  */
   1028 u_int64_t
   1029 scsipi_size(struct scsipi_periph *periph, int *secsize, int flags)
   1030 {
   1031 	union {
   1032 		struct scsipi_read_capacity_10 cmd;
   1033 		struct scsipi_read_capacity_16 cmd16;
   1034 	} cmd;
   1035 	union {
   1036 		struct scsipi_read_capacity_10_data data;
   1037 		struct scsipi_read_capacity_16_data data16;
   1038 	} data;
   1039 
   1040 	memset(&cmd, 0, sizeof(cmd));
   1041 	cmd.cmd.opcode = READ_CAPACITY_10;
   1042 
   1043 	/*
   1044 	 * If the command works, interpret the result as a 4 byte
   1045 	 * number of blocks
   1046 	 */
   1047 	if (scsipi_command(periph, (void *)&cmd.cmd, sizeof(cmd.cmd),
   1048 	    (void *)&data.data, sizeof(data.data), SCSIPIRETRIES, 20000, NULL,
   1049 	    flags | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT) != 0)
   1050 		return (0);
   1051 
   1052 	if (_4btol(data.data.addr) != 0xffffffff) {
   1053 		if (secsize)
   1054 			*secsize = _4btol(data.data.length);
   1055 		return (_4btol(data.data.addr) + 1);
   1056 	}
   1057 
   1058 	/*
   1059 	 * Device is larger than can be reflected by READ CAPACITY (10).
   1060 	 * Try READ CAPACITY (16).
   1061 	 */
   1062 
   1063 	memset(&cmd, 0, sizeof(cmd));
   1064 	cmd.cmd16.opcode = READ_CAPACITY_16;
   1065 	cmd.cmd16.byte2 = SRC16_SERVICE_ACTION;
   1066 	_lto4b(sizeof(data.data16), cmd.cmd16.len);
   1067 
   1068 	if (scsipi_command(periph, (void *)&cmd.cmd16, sizeof(cmd.cmd16),
   1069 	    (void *)&data.data16, sizeof(data.data16), SCSIPIRETRIES, 20000,
   1070 	    NULL,
   1071 	    flags | XS_CTL_DATA_IN | XS_CTL_DATA_ONSTACK | XS_CTL_SILENT) != 0)
   1072 		return (0);
   1073 
   1074 	if (secsize)
   1075 		*secsize = _4btol(data.data16.length);
   1076 	return (_8btol(data.data16.addr) + 1);
   1077 }
   1078 
   1079 /*
   1080  * scsipi_test_unit_ready:
   1081  *
   1082  *	Issue a `test unit ready' request.
   1083  */
   1084 int
   1085 scsipi_test_unit_ready(struct scsipi_periph *periph, int flags)
   1086 {
   1087 	struct scsi_test_unit_ready cmd;
   1088 	int retries;
   1089 
   1090 	/* some ATAPI drives don't support TEST UNIT READY. Sigh */
   1091 	if (periph->periph_quirks & PQUIRK_NOTUR)
   1092 		return (0);
   1093 
   1094 	if (flags & XS_CTL_DISCOVERY)
   1095 		retries = 0;
   1096 	else
   1097 		retries = SCSIPIRETRIES;
   1098 
   1099 	memset(&cmd, 0, sizeof(cmd));
   1100 	cmd.opcode = SCSI_TEST_UNIT_READY;
   1101 
   1102 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
   1103 	    retries, 10000, NULL, flags));
   1104 }
   1105 
   1106 /*
   1107  * scsipi_inquire:
   1108  *
   1109  *	Ask the device about itself.
   1110  */
   1111 int
   1112 scsipi_inquire(struct scsipi_periph *periph, struct scsipi_inquiry_data *inqbuf,
   1113     int flags)
   1114 {
   1115 	struct scsipi_inquiry cmd;
   1116 	int error;
   1117 	int retries;
   1118 
   1119 	if (flags & XS_CTL_DISCOVERY)
   1120 		retries = 0;
   1121 	else
   1122 		retries = SCSIPIRETRIES;
   1123 
   1124 	/*
   1125 	 * If we request more data than the device can provide, it SHOULD just
   1126 	 * return a short reponse.  However, some devices error with an
   1127 	 * ILLEGAL REQUEST sense code, and yet others have even more special
   1128 	 * failture modes (such as the GL641USB flash adapter, which goes loony
   1129 	 * and sends corrupted CRCs).  To work around this, and to bring our
   1130 	 * behavior more in line with other OSes, we do a shorter inquiry,
   1131 	 * covering all the SCSI-2 information, first, and then request more
   1132 	 * data iff the "additional length" field indicates there is more.
   1133 	 * - mycroft, 2003/10/16
   1134 	 */
   1135 	memset(&cmd, 0, sizeof(cmd));
   1136 	cmd.opcode = INQUIRY;
   1137 	cmd.length = SCSIPI_INQUIRY_LENGTH_SCSI2;
   1138 	error = scsipi_command(periph, (void *)&cmd, sizeof(cmd),
   1139 	    (void *)inqbuf, SCSIPI_INQUIRY_LENGTH_SCSI2, retries,
   1140 	    10000, NULL, flags | XS_CTL_DATA_IN);
   1141 	if (!error &&
   1142 	    inqbuf->additional_length > SCSIPI_INQUIRY_LENGTH_SCSI2 - 4) {
   1143 #if 0
   1144 printf("inquire: addlen=%d, retrying\n", inqbuf->additional_length);
   1145 #endif
   1146 		cmd.length = SCSIPI_INQUIRY_LENGTH_SCSI3;
   1147 		error = scsipi_command(periph, (void *)&cmd, sizeof(cmd),
   1148 		    (void *)inqbuf, SCSIPI_INQUIRY_LENGTH_SCSI3, retries,
   1149 		    10000, NULL, flags | XS_CTL_DATA_IN);
   1150 #if 0
   1151 printf("inquire: error=%d\n", error);
   1152 #endif
   1153 	}
   1154 
   1155 #ifdef SCSI_OLD_NOINQUIRY
   1156 	/*
   1157 	 * Kludge for the Adaptec ACB-4000 SCSI->MFM translator.
   1158 	 * This board doesn't support the INQUIRY command at all.
   1159 	 */
   1160 	if (error == EINVAL || error == EACCES) {
   1161 		/*
   1162 		 * Conjure up an INQUIRY response.
   1163 		 */
   1164 		inqbuf->device = (error == EINVAL ?
   1165 			 SID_QUAL_LU_PRESENT :
   1166 			 SID_QUAL_LU_NOTPRESENT) | T_DIRECT;
   1167 		inqbuf->dev_qual2 = 0;
   1168 		inqbuf->version = 0;
   1169 		inqbuf->response_format = SID_FORMAT_SCSI1;
   1170 		inqbuf->additional_length = SCSIPI_INQUIRY_LENGTH_SCSI2 - 4;
   1171 		inqbuf->flags1 = inqbuf->flags2 = inqbuf->flags3 = 0;
   1172 		memcpy(inqbuf->vendor, "ADAPTEC ACB-4000            ", 28);
   1173 		error = 0;
   1174 	}
   1175 
   1176 	/*
   1177 	 * Kludge for the Emulex MT-02 SCSI->QIC translator.
   1178 	 * This board gives an empty response to an INQUIRY command.
   1179 	 */
   1180 	else if (error == 0 &&
   1181 	    inqbuf->device == (SID_QUAL_LU_PRESENT | T_DIRECT) &&
   1182 	    inqbuf->dev_qual2 == 0 &&
   1183 	    inqbuf->version == 0 &&
   1184 	    inqbuf->response_format == SID_FORMAT_SCSI1) {
   1185 		/*
   1186 		 * Fill out the INQUIRY response.
   1187 		 */
   1188 		inqbuf->device = (SID_QUAL_LU_PRESENT | T_SEQUENTIAL);
   1189 		inqbuf->dev_qual2 = SID_REMOVABLE;
   1190 		inqbuf->additional_length = SCSIPI_INQUIRY_LENGTH_SCSI2 - 4;
   1191 		inqbuf->flags1 = inqbuf->flags2 = inqbuf->flags3 = 0;
   1192 		memcpy(inqbuf->vendor, "EMULEX  MT-02 QIC           ", 28);
   1193 	}
   1194 #endif /* SCSI_OLD_NOINQUIRY */
   1195 
   1196 	return error;
   1197 }
   1198 
   1199 /*
   1200  * scsipi_prevent:
   1201  *
   1202  *	Prevent or allow the user to remove the media
   1203  */
   1204 int
   1205 scsipi_prevent(struct scsipi_periph *periph, int type, int flags)
   1206 {
   1207 	struct scsi_prevent_allow_medium_removal cmd;
   1208 
   1209 	memset(&cmd, 0, sizeof(cmd));
   1210 	cmd.opcode = SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL;
   1211 	cmd.how = type;
   1212 
   1213 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
   1214 	    SCSIPIRETRIES, 5000, NULL, flags));
   1215 }
   1216 
   1217 /*
   1218  * scsipi_start:
   1219  *
   1220  *	Send a START UNIT.
   1221  */
   1222 int
   1223 scsipi_start(struct scsipi_periph *periph, int type, int flags)
   1224 {
   1225 	struct scsipi_start_stop cmd;
   1226 
   1227 	memset(&cmd, 0, sizeof(cmd));
   1228 	cmd.opcode = START_STOP;
   1229 	cmd.byte2 = 0x00;
   1230 	cmd.how = type;
   1231 
   1232 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
   1233 	    SCSIPIRETRIES, (type & SSS_START) ? 60000 : 10000, NULL, flags));
   1234 }
   1235 
   1236 /*
   1237  * scsipi_mode_sense, scsipi_mode_sense_big:
   1238  *	get a sense page from a device
   1239  */
   1240 
   1241 int
   1242 scsipi_mode_sense(struct scsipi_periph *periph, int byte2, int page,
   1243     struct scsi_mode_parameter_header_6 *data, int len, int flags, int retries,
   1244     int timeout)
   1245 {
   1246 	struct scsi_mode_sense_6 cmd;
   1247 
   1248 	memset(&cmd, 0, sizeof(cmd));
   1249 	cmd.opcode = SCSI_MODE_SENSE_6;
   1250 	cmd.byte2 = byte2;
   1251 	cmd.page = page;
   1252 	cmd.length = len & 0xff;
   1253 
   1254 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd),
   1255 	    (void *)data, len, retries, timeout, NULL, flags | XS_CTL_DATA_IN));
   1256 }
   1257 
   1258 int
   1259 scsipi_mode_sense_big(struct scsipi_periph *periph, int byte2, int page,
   1260     struct scsi_mode_parameter_header_10 *data, int len, int flags, int retries,
   1261     int timeout)
   1262 {
   1263 	struct scsi_mode_sense_10 cmd;
   1264 
   1265 	memset(&cmd, 0, sizeof(cmd));
   1266 	cmd.opcode = SCSI_MODE_SENSE_10;
   1267 	cmd.byte2 = byte2;
   1268 	cmd.page = page;
   1269 	_lto2b(len, cmd.length);
   1270 
   1271 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd),
   1272 	    (void *)data, len, retries, timeout, NULL, flags | XS_CTL_DATA_IN));
   1273 }
   1274 
   1275 int
   1276 scsipi_mode_select(struct scsipi_periph *periph, int byte2,
   1277     struct scsi_mode_parameter_header_6 *data, int len, int flags, int retries,
   1278     int timeout)
   1279 {
   1280 	struct scsi_mode_select_6 cmd;
   1281 
   1282 	memset(&cmd, 0, sizeof(cmd));
   1283 	cmd.opcode = SCSI_MODE_SELECT_6;
   1284 	cmd.byte2 = byte2;
   1285 	cmd.length = len & 0xff;
   1286 
   1287 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd),
   1288 	    (void *)data, len, retries, timeout, NULL, flags | XS_CTL_DATA_OUT));
   1289 }
   1290 
   1291 int
   1292 scsipi_mode_select_big(struct scsipi_periph *periph, int byte2,
   1293     struct scsi_mode_parameter_header_10 *data, int len, int flags, int retries,
   1294     int timeout)
   1295 {
   1296 	struct scsi_mode_select_10 cmd;
   1297 
   1298 	memset(&cmd, 0, sizeof(cmd));
   1299 	cmd.opcode = SCSI_MODE_SELECT_10;
   1300 	cmd.byte2 = byte2;
   1301 	_lto2b(len, cmd.length);
   1302 
   1303 	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd),
   1304 	    (void *)data, len, retries, timeout, NULL, flags | XS_CTL_DATA_OUT));
   1305 }
   1306 
   1307 /*
   1308  * scsipi_done:
   1309  *
   1310  *	This routine is called by an adapter's interrupt handler when
   1311  *	an xfer is completed.
   1312  */
   1313 void
   1314 scsipi_done(struct scsipi_xfer *xs)
   1315 {
   1316 	struct scsipi_periph *periph = xs->xs_periph;
   1317 	struct scsipi_channel *chan = periph->periph_channel;
   1318 	int s, freezecnt;
   1319 
   1320 	SC_DEBUG(periph, SCSIPI_DB2, ("scsipi_done\n"));
   1321 #ifdef SCSIPI_DEBUG
   1322 	if (periph->periph_dbflags & SCSIPI_DB1)
   1323 		show_scsipi_cmd(xs);
   1324 #endif
   1325 
   1326 	s = splbio();
   1327 	/*
   1328 	 * The resource this command was using is now free.
   1329 	 */
   1330 	if (xs->xs_status & XS_STS_DONE) {
   1331 		/* XXX in certain circumstances, such as a device
   1332 		 * being detached, a xs that has already been
   1333 		 * scsipi_done()'d by the main thread will be done'd
   1334 		 * again by scsibusdetach(). Putting the xs on the
   1335 		 * chan_complete queue causes list corruption and
   1336 		 * everyone dies. This prevents that, but perhaps
   1337 		 * there should be better coordination somewhere such
   1338 		 * that this won't ever happen (and can be turned into
   1339 		 * a KASSERT().
   1340 		 */
   1341 		splx(s);
   1342 		goto out;
   1343 	}
   1344 	scsipi_put_resource(chan);
   1345 	xs->xs_periph->periph_sent--;
   1346 
   1347 	/*
   1348 	 * If the command was tagged, free the tag.
   1349 	 */
   1350 	if (XS_CTL_TAGTYPE(xs) != 0)
   1351 		scsipi_put_tag(xs);
   1352 	else
   1353 		periph->periph_flags &= ~PERIPH_UNTAG;
   1354 
   1355 	/* Mark the command as `done'. */
   1356 	xs->xs_status |= XS_STS_DONE;
   1357 
   1358 #ifdef DIAGNOSTIC
   1359 	if ((xs->xs_control & (XS_CTL_ASYNC|XS_CTL_POLL)) ==
   1360 	    (XS_CTL_ASYNC|XS_CTL_POLL))
   1361 		panic("scsipi_done: ASYNC and POLL");
   1362 #endif
   1363 
   1364 	/*
   1365 	 * If the xfer had an error of any sort, freeze the
   1366 	 * periph's queue.  Freeze it again if we were requested
   1367 	 * to do so in the xfer.
   1368 	 */
   1369 	freezecnt = 0;
   1370 	if (xs->error != XS_NOERROR)
   1371 		freezecnt++;
   1372 	if (xs->xs_control & XS_CTL_FREEZE_PERIPH)
   1373 		freezecnt++;
   1374 	if (freezecnt != 0)
   1375 		scsipi_periph_freeze(periph, freezecnt);
   1376 
   1377 	/*
   1378 	 * record the xfer with a pending sense, in case a SCSI reset is
   1379 	 * received before the thread is waked up.
   1380 	 */
   1381 	if (xs->error == XS_BUSY && xs->status == SCSI_CHECK) {
   1382 		periph->periph_flags |= PERIPH_SENSE;
   1383 		periph->periph_xscheck = xs;
   1384 	}
   1385 
   1386 	/*
   1387 	 * If this was an xfer that was not to complete asynchronously,
   1388 	 * let the requesting thread perform error checking/handling
   1389 	 * in its context.
   1390 	 */
   1391 	if ((xs->xs_control & XS_CTL_ASYNC) == 0) {
   1392 		splx(s);
   1393 		/*
   1394 		 * If it's a polling job, just return, to unwind the
   1395 		 * call graph.  We don't need to restart the queue,
   1396 		 * because pollings jobs are treated specially, and
   1397 		 * are really only used during crash dumps anyway
   1398 		 * (XXX or during boot-time autconfiguration of
   1399 		 * ATAPI devices).
   1400 		 */
   1401 		if (xs->xs_control & XS_CTL_POLL)
   1402 			return;
   1403 		wakeup(xs);
   1404 		goto out;
   1405 	}
   1406 
   1407 	/*
   1408 	 * Catch the extremely common case of I/O completing
   1409 	 * without error; no use in taking a context switch
   1410 	 * if we can handle it in interrupt context.
   1411 	 */
   1412 	if (xs->error == XS_NOERROR) {
   1413 		splx(s);
   1414 		(void) scsipi_complete(xs);
   1415 		goto out;
   1416 	}
   1417 
   1418 	/*
   1419 	 * There is an error on this xfer.  Put it on the channel's
   1420 	 * completion queue, and wake up the completion thread.
   1421 	 */
   1422 	TAILQ_INSERT_TAIL(&chan->chan_complete, xs, channel_q);
   1423 	splx(s);
   1424 	wakeup(&chan->chan_complete);
   1425 
   1426  out:
   1427 	/*
   1428 	 * If there are more xfers on the channel's queue, attempt to
   1429 	 * run them.
   1430 	 */
   1431 	scsipi_run_queue(chan);
   1432 }
   1433 
   1434 /*
   1435  * scsipi_complete:
   1436  *
   1437  *	Completion of a scsipi_xfer.  This is the guts of scsipi_done().
   1438  *
   1439  *	NOTE: This routine MUST be called with valid thread context
   1440  *	except for the case where the following two conditions are
   1441  *	true:
   1442  *
   1443  *		xs->error == XS_NOERROR
   1444  *		XS_CTL_ASYNC is set in xs->xs_control
   1445  *
   1446  *	The semantics of this routine can be tricky, so here is an
   1447  *	explanation:
   1448  *
   1449  *		0		Xfer completed successfully.
   1450  *
   1451  *		ERESTART	Xfer had an error, but was restarted.
   1452  *
   1453  *		anything else	Xfer had an error, return value is Unix
   1454  *				errno.
   1455  *
   1456  *	If the return value is anything but ERESTART:
   1457  *
   1458  *		- If XS_CTL_ASYNC is set, `xs' has been freed back to
   1459  *		  the pool.
   1460  *		- If there is a buf associated with the xfer,
   1461  *		  it has been biodone()'d.
   1462  */
   1463 static int
   1464 scsipi_complete(struct scsipi_xfer *xs)
   1465 {
   1466 	struct scsipi_periph *periph = xs->xs_periph;
   1467 	struct scsipi_channel *chan = periph->periph_channel;
   1468 	int error, s;
   1469 
   1470 #ifdef DIAGNOSTIC
   1471 	if ((xs->xs_control & XS_CTL_ASYNC) != 0 && xs->bp == NULL)
   1472 		panic("scsipi_complete: XS_CTL_ASYNC but no buf");
   1473 #endif
   1474 	/*
   1475 	 * If command terminated with a CHECK CONDITION, we need to issue a
   1476 	 * REQUEST_SENSE command. Once the REQUEST_SENSE has been processed
   1477 	 * we'll have the real status.
   1478 	 * Must be processed at splbio() to avoid missing a SCSI bus reset
   1479 	 * for this command.
   1480 	 */
   1481 	s = splbio();
   1482 	if (xs->error == XS_BUSY && xs->status == SCSI_CHECK) {
   1483 		/* request sense for a request sense ? */
   1484 		if (xs->xs_control & XS_CTL_REQSENSE) {
   1485 			scsipi_printaddr(periph);
   1486 			printf("request sense for a request sense ?\n");
   1487 			/* XXX maybe we should reset the device ? */
   1488 			/* we've been frozen because xs->error != XS_NOERROR */
   1489 			scsipi_periph_thaw(periph, 1);
   1490 			splx(s);
   1491 			if (xs->resid < xs->datalen) {
   1492 				printf("we read %d bytes of sense anyway:\n",
   1493 				    xs->datalen - xs->resid);
   1494 #ifdef SCSIVERBOSE
   1495 				scsipi_print_sense_data((void *)xs->data, 0);
   1496 #endif
   1497 			}
   1498 			return EINVAL;
   1499 		}
   1500 		scsipi_request_sense(xs);
   1501 	}
   1502 	splx(s);
   1503 
   1504 	/*
   1505 	 * If it's a user level request, bypass all usual completion
   1506 	 * processing, let the user work it out..
   1507 	 */
   1508 	if ((xs->xs_control & XS_CTL_USERCMD) != 0) {
   1509 		SC_DEBUG(periph, SCSIPI_DB3, ("calling user done()\n"));
   1510 		if (xs->error != XS_NOERROR)
   1511 			scsipi_periph_thaw(periph, 1);
   1512 		scsipi_user_done(xs);
   1513 		SC_DEBUG(periph, SCSIPI_DB3, ("returned from user done()\n "));
   1514 		return 0;
   1515 	}
   1516 
   1517 	switch (xs->error) {
   1518 	case XS_NOERROR:
   1519 		error = 0;
   1520 		break;
   1521 
   1522 	case XS_SENSE:
   1523 	case XS_SHORTSENSE:
   1524 		error = (*chan->chan_bustype->bustype_interpret_sense)(xs);
   1525 		break;
   1526 
   1527 	case XS_RESOURCE_SHORTAGE:
   1528 		/*
   1529 		 * XXX Should freeze channel's queue.
   1530 		 */
   1531 		scsipi_printaddr(periph);
   1532 		printf("adapter resource shortage\n");
   1533 		/* FALLTHROUGH */
   1534 
   1535 	case XS_BUSY:
   1536 		if (xs->error == XS_BUSY && xs->status == SCSI_QUEUE_FULL) {
   1537 			struct scsipi_max_openings mo;
   1538 
   1539 			/*
   1540 			 * We set the openings to active - 1, assuming that
   1541 			 * the command that got us here is the first one that
   1542 			 * can't fit into the device's queue.  If that's not
   1543 			 * the case, I guess we'll find out soon enough.
   1544 			 */
   1545 			mo.mo_target = periph->periph_target;
   1546 			mo.mo_lun = periph->periph_lun;
   1547 			if (periph->periph_active < periph->periph_openings)
   1548 				mo.mo_openings = periph->periph_active - 1;
   1549 			else
   1550 				mo.mo_openings = periph->periph_openings - 1;
   1551 #ifdef DIAGNOSTIC
   1552 			if (mo.mo_openings < 0) {
   1553 				scsipi_printaddr(periph);
   1554 				printf("QUEUE FULL resulted in < 0 openings\n");
   1555 				panic("scsipi_done");
   1556 			}
   1557 #endif
   1558 			if (mo.mo_openings == 0) {
   1559 				scsipi_printaddr(periph);
   1560 				printf("QUEUE FULL resulted in 0 openings\n");
   1561 				mo.mo_openings = 1;
   1562 			}
   1563 			scsipi_async_event(chan, ASYNC_EVENT_MAX_OPENINGS, &mo);
   1564 			error = ERESTART;
   1565 		} else if (xs->xs_retries != 0) {
   1566 			xs->xs_retries--;
   1567 			/*
   1568 			 * Wait one second, and try again.
   1569 			 */
   1570 			if ((xs->xs_control & XS_CTL_POLL) ||
   1571 			    (chan->chan_flags & SCSIPI_CHAN_TACTIVE) == 0) {
   1572 				delay(1000000);
   1573 			} else if (!callout_pending(&periph->periph_callout)) {
   1574 				scsipi_periph_freeze(periph, 1);
   1575 				callout_reset(&periph->periph_callout,
   1576 				    hz, scsipi_periph_timed_thaw, periph);
   1577 			}
   1578 			error = ERESTART;
   1579 		} else
   1580 			error = EBUSY;
   1581 		break;
   1582 
   1583 	case XS_REQUEUE:
   1584 		error = ERESTART;
   1585 		break;
   1586 
   1587 	case XS_SELTIMEOUT:
   1588 	case XS_TIMEOUT:
   1589 		/*
   1590 		 * If the device hasn't gone away, honor retry counts.
   1591 		 *
   1592 		 * Note that if we're in the middle of probing it,
   1593 		 * it won't be found because it isn't here yet so
   1594 		 * we won't honor the retry count in that case.
   1595 		 */
   1596 		if (scsipi_lookup_periph(chan, periph->periph_target,
   1597 		    periph->periph_lun) && xs->xs_retries != 0) {
   1598 			xs->xs_retries--;
   1599 			error = ERESTART;
   1600 		} else
   1601 			error = EIO;
   1602 		break;
   1603 
   1604 	case XS_RESET:
   1605 		if (xs->xs_control & XS_CTL_REQSENSE) {
   1606 			/*
   1607 			 * request sense interrupted by reset: signal it
   1608 			 * with EINTR return code.
   1609 			 */
   1610 			error = EINTR;
   1611 		} else {
   1612 			if (xs->xs_retries != 0) {
   1613 				xs->xs_retries--;
   1614 				error = ERESTART;
   1615 			} else
   1616 				error = EIO;
   1617 		}
   1618 		break;
   1619 
   1620 	case XS_DRIVER_STUFFUP:
   1621 		scsipi_printaddr(periph);
   1622 		printf("generic HBA error\n");
   1623 		error = EIO;
   1624 		break;
   1625 	default:
   1626 		scsipi_printaddr(periph);
   1627 		printf("invalid return code from adapter: %d\n", xs->error);
   1628 		error = EIO;
   1629 		break;
   1630 	}
   1631 
   1632 	s = splbio();
   1633 	if (error == ERESTART) {
   1634 		/*
   1635 		 * If we get here, the periph has been thawed and frozen
   1636 		 * again if we had to issue recovery commands.  Alternatively,
   1637 		 * it may have been frozen again and in a timed thaw.  In
   1638 		 * any case, we thaw the periph once we re-enqueue the
   1639 		 * command.  Once the periph is fully thawed, it will begin
   1640 		 * operation again.
   1641 		 */
   1642 		xs->error = XS_NOERROR;
   1643 		xs->status = SCSI_OK;
   1644 		xs->xs_status &= ~XS_STS_DONE;
   1645 		xs->xs_requeuecnt++;
   1646 		error = scsipi_enqueue(xs);
   1647 		if (error == 0) {
   1648 			scsipi_periph_thaw(periph, 1);
   1649 			splx(s);
   1650 			return (ERESTART);
   1651 		}
   1652 	}
   1653 
   1654 	/*
   1655 	 * scsipi_done() freezes the queue if not XS_NOERROR.
   1656 	 * Thaw it here.
   1657 	 */
   1658 	if (xs->error != XS_NOERROR)
   1659 		scsipi_periph_thaw(periph, 1);
   1660 
   1661 	if (periph->periph_switch->psw_done)
   1662 		periph->periph_switch->psw_done(xs, error);
   1663 
   1664 	if (xs->xs_control & XS_CTL_ASYNC)
   1665 		scsipi_put_xs(xs);
   1666 	splx(s);
   1667 
   1668 	return (error);
   1669 }
   1670 
   1671 /*
   1672  * Issue a request sense for the given scsipi_xfer. Called when the xfer
   1673  * returns with a CHECK_CONDITION status. Must be called in valid thread
   1674  * context and at splbio().
   1675  */
   1676 
   1677 static void
   1678 scsipi_request_sense(struct scsipi_xfer *xs)
   1679 {
   1680 	struct scsipi_periph *periph = xs->xs_periph;
   1681 	int flags, error;
   1682 	struct scsi_request_sense cmd;
   1683 
   1684 	periph->periph_flags |= PERIPH_SENSE;
   1685 
   1686 	/* if command was polling, request sense will too */
   1687 	flags = xs->xs_control & XS_CTL_POLL;
   1688 	/* Polling commands can't sleep */
   1689 	if (flags)
   1690 		flags |= XS_CTL_NOSLEEP;
   1691 
   1692 	flags |= XS_CTL_REQSENSE | XS_CTL_URGENT | XS_CTL_DATA_IN |
   1693 	    XS_CTL_THAW_PERIPH | XS_CTL_FREEZE_PERIPH;
   1694 
   1695 	memset(&cmd, 0, sizeof(cmd));
   1696 	cmd.opcode = SCSI_REQUEST_SENSE;
   1697 	cmd.length = sizeof(struct scsi_sense_data);
   1698 
   1699 	error = scsipi_command(periph, (void *)&cmd, sizeof(cmd),
   1700 	    (void *)&xs->sense.scsi_sense, sizeof(struct scsi_sense_data),
   1701 	    0, 1000, NULL, flags);
   1702 	periph->periph_flags &= ~PERIPH_SENSE;
   1703 	periph->periph_xscheck = NULL;
   1704 	switch (error) {
   1705 	case 0:
   1706 		/* we have a valid sense */
   1707 		xs->error = XS_SENSE;
   1708 		return;
   1709 	case EINTR:
   1710 		/* REQUEST_SENSE interrupted by bus reset. */
   1711 		xs->error = XS_RESET;
   1712 		return;
   1713 	case EIO:
   1714 		 /* request sense coudn't be performed */
   1715 		/*
   1716 		 * XXX this isn't quite right but we don't have anything
   1717 		 * better for now
   1718 		 */
   1719 		xs->error = XS_DRIVER_STUFFUP;
   1720 		return;
   1721 	default:
   1722 		 /* Notify that request sense failed. */
   1723 		xs->error = XS_DRIVER_STUFFUP;
   1724 		scsipi_printaddr(periph);
   1725 		printf("request sense failed with error %d\n", error);
   1726 		return;
   1727 	}
   1728 }
   1729 
   1730 /*
   1731  * scsipi_enqueue:
   1732  *
   1733  *	Enqueue an xfer on a channel.
   1734  */
   1735 static int
   1736 scsipi_enqueue(struct scsipi_xfer *xs)
   1737 {
   1738 	struct scsipi_channel *chan = xs->xs_periph->periph_channel;
   1739 	struct scsipi_xfer *qxs;
   1740 	int s;
   1741 
   1742 	s = splbio();
   1743 
   1744 	/*
   1745 	 * If the xfer is to be polled, and there are already jobs on
   1746 	 * the queue, we can't proceed.
   1747 	 */
   1748 	if ((xs->xs_control & XS_CTL_POLL) != 0 &&
   1749 	    TAILQ_FIRST(&chan->chan_queue) != NULL) {
   1750 		splx(s);
   1751 		xs->error = XS_DRIVER_STUFFUP;
   1752 		return (EAGAIN);
   1753 	}
   1754 
   1755 	/*
   1756 	 * If we have an URGENT xfer, it's an error recovery command
   1757 	 * and it should just go on the head of the channel's queue.
   1758 	 */
   1759 	if (xs->xs_control & XS_CTL_URGENT) {
   1760 		TAILQ_INSERT_HEAD(&chan->chan_queue, xs, channel_q);
   1761 		goto out;
   1762 	}
   1763 
   1764 	/*
   1765 	 * If this xfer has already been on the queue before, we
   1766 	 * need to reinsert it in the correct order.  That order is:
   1767 	 *
   1768 	 *	Immediately before the first xfer for this periph
   1769 	 *	with a requeuecnt less than xs->xs_requeuecnt.
   1770 	 *
   1771 	 * Failing that, at the end of the queue.  (We'll end up
   1772 	 * there naturally.)
   1773 	 */
   1774 	if (xs->xs_requeuecnt != 0) {
   1775 		for (qxs = TAILQ_FIRST(&chan->chan_queue); qxs != NULL;
   1776 		     qxs = TAILQ_NEXT(qxs, channel_q)) {
   1777 			if (qxs->xs_periph == xs->xs_periph &&
   1778 			    qxs->xs_requeuecnt < xs->xs_requeuecnt)
   1779 				break;
   1780 		}
   1781 		if (qxs != NULL) {
   1782 			TAILQ_INSERT_AFTER(&chan->chan_queue, qxs, xs,
   1783 			    channel_q);
   1784 			goto out;
   1785 		}
   1786 	}
   1787 	TAILQ_INSERT_TAIL(&chan->chan_queue, xs, channel_q);
   1788  out:
   1789 	if (xs->xs_control & XS_CTL_THAW_PERIPH)
   1790 		scsipi_periph_thaw(xs->xs_periph, 1);
   1791 	splx(s);
   1792 	return (0);
   1793 }
   1794 
   1795 /*
   1796  * scsipi_run_queue:
   1797  *
   1798  *	Start as many xfers as possible running on the channel.
   1799  */
   1800 static void
   1801 scsipi_run_queue(struct scsipi_channel *chan)
   1802 {
   1803 	struct scsipi_xfer *xs;
   1804 	struct scsipi_periph *periph;
   1805 	int s;
   1806 
   1807 	for (;;) {
   1808 		s = splbio();
   1809 
   1810 		/*
   1811 		 * If the channel is frozen, we can't do any work right
   1812 		 * now.
   1813 		 */
   1814 		if (chan->chan_qfreeze != 0) {
   1815 			splx(s);
   1816 			return;
   1817 		}
   1818 
   1819 		/*
   1820 		 * Look for work to do, and make sure we can do it.
   1821 		 */
   1822 		for (xs = TAILQ_FIRST(&chan->chan_queue); xs != NULL;
   1823 		     xs = TAILQ_NEXT(xs, channel_q)) {
   1824 			periph = xs->xs_periph;
   1825 
   1826 			if ((periph->periph_sent >= periph->periph_openings) ||
   1827 			    periph->periph_qfreeze != 0 ||
   1828 			    (periph->periph_flags & PERIPH_UNTAG) != 0)
   1829 				continue;
   1830 
   1831 			if ((periph->periph_flags &
   1832 			    (PERIPH_RECOVERING | PERIPH_SENSE)) != 0 &&
   1833 			    (xs->xs_control & XS_CTL_URGENT) == 0)
   1834 				continue;
   1835 
   1836 			/*
   1837 			 * We can issue this xfer!
   1838 			 */
   1839 			goto got_one;
   1840 		}
   1841 
   1842 		/*
   1843 		 * Can't find any work to do right now.
   1844 		 */
   1845 		splx(s);
   1846 		return;
   1847 
   1848  got_one:
   1849 		/*
   1850 		 * Have an xfer to run.  Allocate a resource from
   1851 		 * the adapter to run it.  If we can't allocate that
   1852 		 * resource, we don't dequeue the xfer.
   1853 		 */
   1854 		if (scsipi_get_resource(chan) == 0) {
   1855 			/*
   1856 			 * Adapter is out of resources.  If the adapter
   1857 			 * supports it, attempt to grow them.
   1858 			 */
   1859 			if (scsipi_grow_resources(chan) == 0) {
   1860 				/*
   1861 				 * Wasn't able to grow resources,
   1862 				 * nothing more we can do.
   1863 				 */
   1864 				if (xs->xs_control & XS_CTL_POLL) {
   1865 					scsipi_printaddr(xs->xs_periph);
   1866 					printf("polling command but no "
   1867 					    "adapter resources");
   1868 					/* We'll panic shortly... */
   1869 				}
   1870 				splx(s);
   1871 
   1872 				/*
   1873 				 * XXX: We should be able to note that
   1874 				 * XXX: that resources are needed here!
   1875 				 */
   1876 				return;
   1877 			}
   1878 			/*
   1879 			 * scsipi_grow_resources() allocated the resource
   1880 			 * for us.
   1881 			 */
   1882 		}
   1883 
   1884 		/*
   1885 		 * We have a resource to run this xfer, do it!
   1886 		 */
   1887 		TAILQ_REMOVE(&chan->chan_queue, xs, channel_q);
   1888 
   1889 		/*
   1890 		 * If the command is to be tagged, allocate a tag ID
   1891 		 * for it.
   1892 		 */
   1893 		if (XS_CTL_TAGTYPE(xs) != 0)
   1894 			scsipi_get_tag(xs);
   1895 		else
   1896 			periph->periph_flags |= PERIPH_UNTAG;
   1897 		periph->periph_sent++;
   1898 		splx(s);
   1899 
   1900 		scsipi_adapter_request(chan, ADAPTER_REQ_RUN_XFER, xs);
   1901 	}
   1902 #ifdef DIAGNOSTIC
   1903 	panic("scsipi_run_queue: impossible");
   1904 #endif
   1905 }
   1906 
   1907 /*
   1908  * scsipi_execute_xs:
   1909  *
   1910  *	Begin execution of an xfer, waiting for it to complete, if necessary.
   1911  */
   1912 int
   1913 scsipi_execute_xs(struct scsipi_xfer *xs)
   1914 {
   1915 	struct scsipi_periph *periph = xs->xs_periph;
   1916 	struct scsipi_channel *chan = periph->periph_channel;
   1917 	int oasync, async, poll, error, s;
   1918 
   1919 	KASSERT(!cold);
   1920 
   1921 	(chan->chan_bustype->bustype_cmd)(xs);
   1922 
   1923 	if (xs->xs_control & XS_CTL_DATA_ONSTACK) {
   1924 #if 1
   1925 		if (xs->xs_control & XS_CTL_ASYNC)
   1926 			panic("scsipi_execute_xs: on stack and async");
   1927 #endif
   1928 		/*
   1929 		 * If the I/O buffer is allocated on stack, the
   1930 		 * process must NOT be swapped out, as the device will
   1931 		 * be accessing the stack.
   1932 		 */
   1933 		PHOLD(curlwp);
   1934 	}
   1935 
   1936 	xs->xs_status &= ~XS_STS_DONE;
   1937 	xs->error = XS_NOERROR;
   1938 	xs->resid = xs->datalen;
   1939 	xs->status = SCSI_OK;
   1940 
   1941 #ifdef SCSIPI_DEBUG
   1942 	if (xs->xs_periph->periph_dbflags & SCSIPI_DB3) {
   1943 		printf("scsipi_execute_xs: ");
   1944 		show_scsipi_xs(xs);
   1945 		printf("\n");
   1946 	}
   1947 #endif
   1948 
   1949 	/*
   1950 	 * Deal with command tagging:
   1951 	 *
   1952 	 *	- If the device's current operating mode doesn't
   1953 	 *	  include tagged queueing, clear the tag mask.
   1954 	 *
   1955 	 *	- If the device's current operating mode *does*
   1956 	 *	  include tagged queueing, set the tag_type in
   1957 	 *	  the xfer to the appropriate byte for the tag
   1958 	 *	  message.
   1959 	 */
   1960 	if ((PERIPH_XFER_MODE(periph) & PERIPH_CAP_TQING) == 0 ||
   1961 		(xs->xs_control & XS_CTL_REQSENSE)) {
   1962 		xs->xs_control &= ~XS_CTL_TAGMASK;
   1963 		xs->xs_tag_type = 0;
   1964 	} else {
   1965 		/*
   1966 		 * If the request doesn't specify a tag, give Head
   1967 		 * tags to URGENT operations and Ordered tags to
   1968 		 * everything else.
   1969 		 */
   1970 		if (XS_CTL_TAGTYPE(xs) == 0) {
   1971 			if (xs->xs_control & XS_CTL_URGENT)
   1972 				xs->xs_control |= XS_CTL_HEAD_TAG;
   1973 			else
   1974 				xs->xs_control |= XS_CTL_ORDERED_TAG;
   1975 		}
   1976 
   1977 		switch (XS_CTL_TAGTYPE(xs)) {
   1978 		case XS_CTL_ORDERED_TAG:
   1979 			xs->xs_tag_type = MSG_ORDERED_Q_TAG;
   1980 			break;
   1981 
   1982 		case XS_CTL_SIMPLE_TAG:
   1983 			xs->xs_tag_type = MSG_SIMPLE_Q_TAG;
   1984 			break;
   1985 
   1986 		case XS_CTL_HEAD_TAG:
   1987 			xs->xs_tag_type = MSG_HEAD_OF_Q_TAG;
   1988 			break;
   1989 
   1990 		default:
   1991 			scsipi_printaddr(periph);
   1992 			printf("invalid tag mask 0x%08x\n",
   1993 			    XS_CTL_TAGTYPE(xs));
   1994 			panic("scsipi_execute_xs");
   1995 		}
   1996 	}
   1997 
   1998 	/* If the adaptor wants us to poll, poll. */
   1999 	if (chan->chan_adapter->adapt_flags & SCSIPI_ADAPT_POLL_ONLY)
   2000 		xs->xs_control |= XS_CTL_POLL;
   2001 
   2002 	/*
   2003 	 * If we don't yet have a completion thread, or we are to poll for
   2004 	 * completion, clear the ASYNC flag.
   2005 	 */
   2006 	oasync =  (xs->xs_control & XS_CTL_ASYNC);
   2007 	if (chan->chan_thread == NULL || (xs->xs_control & XS_CTL_POLL) != 0)
   2008 		xs->xs_control &= ~XS_CTL_ASYNC;
   2009 
   2010 	async = (xs->xs_control & XS_CTL_ASYNC);
   2011 	poll = (xs->xs_control & XS_CTL_POLL);
   2012 
   2013 #ifdef DIAGNOSTIC
   2014 	if (oasync != 0 && xs->bp == NULL)
   2015 		panic("scsipi_execute_xs: XS_CTL_ASYNC but no buf");
   2016 #endif
   2017 
   2018 	/*
   2019 	 * Enqueue the transfer.  If we're not polling for completion, this
   2020 	 * should ALWAYS return `no error'.
   2021 	 */
   2022 	error = scsipi_enqueue(xs);
   2023 	if (error) {
   2024 		if (poll == 0) {
   2025 			scsipi_printaddr(periph);
   2026 			printf("not polling, but enqueue failed with %d\n",
   2027 			    error);
   2028 			panic("scsipi_execute_xs");
   2029 		}
   2030 
   2031 		scsipi_printaddr(periph);
   2032 		printf("should have flushed queue?\n");
   2033 		goto free_xs;
   2034 	}
   2035 
   2036  restarted:
   2037 	scsipi_run_queue(chan);
   2038 
   2039 	/*
   2040 	 * The xfer is enqueued, and possibly running.  If it's to be
   2041 	 * completed asynchronously, just return now.
   2042 	 */
   2043 	if (async)
   2044 		return (0);
   2045 
   2046 	/*
   2047 	 * Not an asynchronous command; wait for it to complete.
   2048 	 */
   2049 	s = splbio();
   2050 	while ((xs->xs_status & XS_STS_DONE) == 0) {
   2051 		if (poll) {
   2052 			scsipi_printaddr(periph);
   2053 			printf("polling command not done\n");
   2054 			panic("scsipi_execute_xs");
   2055 		}
   2056 		(void) tsleep(xs, PRIBIO, "xscmd", 0);
   2057 	}
   2058 	splx(s);
   2059 
   2060 	/*
   2061 	 * Command is complete.  scsipi_done() has awakened us to perform
   2062 	 * the error handling.
   2063 	 */
   2064 	error = scsipi_complete(xs);
   2065 	if (error == ERESTART)
   2066 		goto restarted;
   2067 
   2068 	/*
   2069 	 * If it was meant to run async and we cleared aync ourselve,
   2070 	 * don't return an error here. It has already been handled
   2071 	 */
   2072 	if (oasync)
   2073 		error = 0;
   2074 	/*
   2075 	 * Command completed successfully or fatal error occurred.  Fall
   2076 	 * into....
   2077 	 */
   2078  free_xs:
   2079 	if (xs->xs_control & XS_CTL_DATA_ONSTACK)
   2080 		PRELE(curlwp);
   2081 
   2082 	s = splbio();
   2083 	scsipi_put_xs(xs);
   2084 	splx(s);
   2085 
   2086 	/*
   2087 	 * Kick the queue, keep it running in case it stopped for some
   2088 	 * reason.
   2089 	 */
   2090 	scsipi_run_queue(chan);
   2091 
   2092 	return (error);
   2093 }
   2094 
   2095 /*
   2096  * scsipi_completion_thread:
   2097  *
   2098  *	This is the completion thread.  We wait for errors on
   2099  *	asynchronous xfers, and perform the error handling
   2100  *	function, restarting the command, if necessary.
   2101  */
   2102 static void
   2103 scsipi_completion_thread(void *arg)
   2104 {
   2105 	struct scsipi_channel *chan = arg;
   2106 	struct scsipi_xfer *xs;
   2107 	int s;
   2108 
   2109 	if (chan->chan_init_cb)
   2110 		(*chan->chan_init_cb)(chan, chan->chan_init_cb_arg);
   2111 
   2112 	s = splbio();
   2113 	chan->chan_flags |= SCSIPI_CHAN_TACTIVE;
   2114 	splx(s);
   2115 	for (;;) {
   2116 		s = splbio();
   2117 		xs = TAILQ_FIRST(&chan->chan_complete);
   2118 		if (xs == NULL && chan->chan_tflags  == 0) {
   2119 			/* nothing to do; wait */
   2120 			(void) tsleep(&chan->chan_complete, PRIBIO,
   2121 			    "sccomp", 0);
   2122 			splx(s);
   2123 			continue;
   2124 		}
   2125 		if (chan->chan_tflags & SCSIPI_CHANT_CALLBACK) {
   2126 			/* call chan_callback from thread context */
   2127 			chan->chan_tflags &= ~SCSIPI_CHANT_CALLBACK;
   2128 			chan->chan_callback(chan, chan->chan_callback_arg);
   2129 			splx(s);
   2130 			continue;
   2131 		}
   2132 		if (chan->chan_tflags & SCSIPI_CHANT_GROWRES) {
   2133 			/* attempt to get more openings for this channel */
   2134 			chan->chan_tflags &= ~SCSIPI_CHANT_GROWRES;
   2135 			scsipi_adapter_request(chan,
   2136 			    ADAPTER_REQ_GROW_RESOURCES, NULL);
   2137 			scsipi_channel_thaw(chan, 1);
   2138 			splx(s);
   2139 			if (chan->chan_tflags & SCSIPI_CHANT_GROWRES) {
   2140 				preempt(1);
   2141 			}
   2142 			continue;
   2143 		}
   2144 		if (chan->chan_tflags & SCSIPI_CHANT_KICK) {
   2145 			/* explicitly run the queues for this channel */
   2146 			chan->chan_tflags &= ~SCSIPI_CHANT_KICK;
   2147 			scsipi_run_queue(chan);
   2148 			splx(s);
   2149 			continue;
   2150 		}
   2151 		if (chan->chan_tflags & SCSIPI_CHANT_SHUTDOWN) {
   2152 			splx(s);
   2153 			break;
   2154 		}
   2155 		if (xs) {
   2156 			TAILQ_REMOVE(&chan->chan_complete, xs, channel_q);
   2157 			splx(s);
   2158 
   2159 			/*
   2160 			 * Have an xfer with an error; process it.
   2161 			 */
   2162 			(void) scsipi_complete(xs);
   2163 
   2164 			/*
   2165 			 * Kick the queue; keep it running if it was stopped
   2166 			 * for some reason.
   2167 			 */
   2168 			scsipi_run_queue(chan);
   2169 		} else {
   2170 			splx(s);
   2171 		}
   2172 	}
   2173 
   2174 	chan->chan_thread = NULL;
   2175 
   2176 	/* In case parent is waiting for us to exit. */
   2177 	wakeup(&chan->chan_thread);
   2178 
   2179 	kthread_exit(0);
   2180 }
   2181 
   2182 /*
   2183  * scsipi_create_completion_thread:
   2184  *
   2185  *	Callback to actually create the completion thread.
   2186  */
   2187 void
   2188 scsipi_create_completion_thread(void *arg)
   2189 {
   2190 	struct scsipi_channel *chan = arg;
   2191 	struct scsipi_adapter *adapt = chan->chan_adapter;
   2192 
   2193 	if (kthread_create1(scsipi_completion_thread, chan,
   2194 	    &chan->chan_thread, "%s", chan->chan_name)) {
   2195 		printf("%s: unable to create completion thread for "
   2196 		    "channel %d\n", adapt->adapt_dev->dv_xname,
   2197 		    chan->chan_channel);
   2198 		panic("scsipi_create_completion_thread");
   2199 	}
   2200 }
   2201 
   2202 /*
   2203  * scsipi_thread_call_callback:
   2204  *
   2205  * 	request to call a callback from the completion thread
   2206  */
   2207 int
   2208 scsipi_thread_call_callback(struct scsipi_channel *chan,
   2209     void (*callback)(struct scsipi_channel *, void *), void *arg)
   2210 {
   2211 	int s;
   2212 
   2213 	s = splbio();
   2214 	if ((chan->chan_flags & SCSIPI_CHAN_TACTIVE) == 0) {
   2215 		/* kernel thread doesn't exist yet */
   2216 		splx(s);
   2217 		return ESRCH;
   2218 	}
   2219 	if (chan->chan_tflags & SCSIPI_CHANT_CALLBACK) {
   2220 		splx(s);
   2221 		return EBUSY;
   2222 	}
   2223 	scsipi_channel_freeze(chan, 1);
   2224 	chan->chan_callback = callback;
   2225 	chan->chan_callback_arg = arg;
   2226 	chan->chan_tflags |= SCSIPI_CHANT_CALLBACK;
   2227 	wakeup(&chan->chan_complete);
   2228 	splx(s);
   2229 	return(0);
   2230 }
   2231 
   2232 /*
   2233  * scsipi_async_event:
   2234  *
   2235  *	Handle an asynchronous event from an adapter.
   2236  */
   2237 void
   2238 scsipi_async_event(struct scsipi_channel *chan, scsipi_async_event_t event,
   2239     void *arg)
   2240 {
   2241 	int s;
   2242 
   2243 	s = splbio();
   2244 	switch (event) {
   2245 	case ASYNC_EVENT_MAX_OPENINGS:
   2246 		scsipi_async_event_max_openings(chan,
   2247 		    (struct scsipi_max_openings *)arg);
   2248 		break;
   2249 
   2250 	case ASYNC_EVENT_XFER_MODE:
   2251 		scsipi_async_event_xfer_mode(chan,
   2252 		    (struct scsipi_xfer_mode *)arg);
   2253 		break;
   2254 	case ASYNC_EVENT_RESET:
   2255 		scsipi_async_event_channel_reset(chan);
   2256 		break;
   2257 	}
   2258 	splx(s);
   2259 }
   2260 
   2261 /*
   2262  * scsipi_print_xfer_mode:
   2263  *
   2264  *	Print a periph's capabilities.
   2265  */
   2266 void
   2267 scsipi_print_xfer_mode(struct scsipi_periph *periph)
   2268 {
   2269 	int period, freq, speed, mbs;
   2270 
   2271 	if ((periph->periph_flags & PERIPH_MODE_VALID) == 0)
   2272 		return;
   2273 
   2274 	aprint_normal("%s: ", periph->periph_dev->dv_xname);
   2275 	if (periph->periph_mode & (PERIPH_CAP_SYNC | PERIPH_CAP_DT)) {
   2276 		period = scsipi_sync_factor_to_period(periph->periph_period);
   2277 		aprint_normal("sync (%d.%02dns offset %d)",
   2278 		    period / 100, period % 100, periph->periph_offset);
   2279 	} else
   2280 		aprint_normal("async");
   2281 
   2282 	if (periph->periph_mode & PERIPH_CAP_WIDE32)
   2283 		aprint_normal(", 32-bit");
   2284 	else if (periph->periph_mode & (PERIPH_CAP_WIDE16 | PERIPH_CAP_DT))
   2285 		aprint_normal(", 16-bit");
   2286 	else
   2287 		aprint_normal(", 8-bit");
   2288 
   2289 	if (periph->periph_mode & (PERIPH_CAP_SYNC | PERIPH_CAP_DT)) {
   2290 		freq = scsipi_sync_factor_to_freq(periph->periph_period);
   2291 		speed = freq;
   2292 		if (periph->periph_mode & PERIPH_CAP_WIDE32)
   2293 			speed *= 4;
   2294 		else if (periph->periph_mode &
   2295 		    (PERIPH_CAP_WIDE16 | PERIPH_CAP_DT))
   2296 			speed *= 2;
   2297 		mbs = speed / 1000;
   2298 		if (mbs > 0)
   2299 			aprint_normal(" (%d.%03dMB/s)", mbs, speed % 1000);
   2300 		else
   2301 			aprint_normal(" (%dKB/s)", speed % 1000);
   2302 	}
   2303 
   2304 	aprint_normal(" transfers");
   2305 
   2306 	if (periph->periph_mode & PERIPH_CAP_TQING)
   2307 		aprint_normal(", tagged queueing");
   2308 
   2309 	aprint_normal("\n");
   2310 }
   2311 
   2312 /*
   2313  * scsipi_async_event_max_openings:
   2314  *
   2315  *	Update the maximum number of outstanding commands a
   2316  *	device may have.
   2317  */
   2318 static void
   2319 scsipi_async_event_max_openings(struct scsipi_channel *chan,
   2320     struct scsipi_max_openings *mo)
   2321 {
   2322 	struct scsipi_periph *periph;
   2323 	int minlun, maxlun;
   2324 
   2325 	if (mo->mo_lun == -1) {
   2326 		/*
   2327 		 * Wildcarded; apply it to all LUNs.
   2328 		 */
   2329 		minlun = 0;
   2330 		maxlun = chan->chan_nluns - 1;
   2331 	} else
   2332 		minlun = maxlun = mo->mo_lun;
   2333 
   2334 	/* XXX This could really suck with a large LUN space. */
   2335 	for (; minlun <= maxlun; minlun++) {
   2336 		periph = scsipi_lookup_periph(chan, mo->mo_target, minlun);
   2337 		if (periph == NULL)
   2338 			continue;
   2339 
   2340 		if (mo->mo_openings < periph->periph_openings)
   2341 			periph->periph_openings = mo->mo_openings;
   2342 		else if (mo->mo_openings > periph->periph_openings &&
   2343 		    (periph->periph_flags & PERIPH_GROW_OPENINGS) != 0)
   2344 			periph->periph_openings = mo->mo_openings;
   2345 	}
   2346 }
   2347 
   2348 /*
   2349  * scsipi_async_event_xfer_mode:
   2350  *
   2351  *	Update the xfer mode for all periphs sharing the
   2352  *	specified I_T Nexus.
   2353  */
   2354 static void
   2355 scsipi_async_event_xfer_mode(struct scsipi_channel *chan,
   2356     struct scsipi_xfer_mode *xm)
   2357 {
   2358 	struct scsipi_periph *periph;
   2359 	int lun, announce, mode, period, offset;
   2360 
   2361 	for (lun = 0; lun < chan->chan_nluns; lun++) {
   2362 		periph = scsipi_lookup_periph(chan, xm->xm_target, lun);
   2363 		if (periph == NULL)
   2364 			continue;
   2365 		announce = 0;
   2366 
   2367 		/*
   2368 		 * Clamp the xfer mode down to this periph's capabilities.
   2369 		 */
   2370 		mode = xm->xm_mode & periph->periph_cap;
   2371 		if (mode & PERIPH_CAP_SYNC) {
   2372 			period = xm->xm_period;
   2373 			offset = xm->xm_offset;
   2374 		} else {
   2375 			period = 0;
   2376 			offset = 0;
   2377 		}
   2378 
   2379 		/*
   2380 		 * If we do not have a valid xfer mode yet, or the parameters
   2381 		 * are different, announce them.
   2382 		 */
   2383 		if ((periph->periph_flags & PERIPH_MODE_VALID) == 0 ||
   2384 		    periph->periph_mode != mode ||
   2385 		    periph->periph_period != period ||
   2386 		    periph->periph_offset != offset)
   2387 			announce = 1;
   2388 
   2389 		periph->periph_mode = mode;
   2390 		periph->periph_period = period;
   2391 		periph->periph_offset = offset;
   2392 		periph->periph_flags |= PERIPH_MODE_VALID;
   2393 
   2394 		if (announce)
   2395 			scsipi_print_xfer_mode(periph);
   2396 	}
   2397 }
   2398 
   2399 /*
   2400  * scsipi_set_xfer_mode:
   2401  *
   2402  *	Set the xfer mode for the specified I_T Nexus.
   2403  */
   2404 void
   2405 scsipi_set_xfer_mode(struct scsipi_channel *chan, int target, int immed)
   2406 {
   2407 	struct scsipi_xfer_mode xm;
   2408 	struct scsipi_periph *itperiph;
   2409 	int lun, s;
   2410 
   2411 	/*
   2412 	 * Go to the minimal xfer mode.
   2413 	 */
   2414 	xm.xm_target = target;
   2415 	xm.xm_mode = 0;
   2416 	xm.xm_period = 0;			/* ignored */
   2417 	xm.xm_offset = 0;			/* ignored */
   2418 
   2419 	/*
   2420 	 * Find the first LUN we know about on this I_T Nexus.
   2421 	 */
   2422 	for (itperiph = NULL, lun = 0; lun < chan->chan_nluns; lun++) {
   2423 		itperiph = scsipi_lookup_periph(chan, target, lun);
   2424 		if (itperiph != NULL)
   2425 			break;
   2426 	}
   2427 	if (itperiph != NULL) {
   2428 		xm.xm_mode = itperiph->periph_cap;
   2429 		/*
   2430 		 * Now issue the request to the adapter.
   2431 		 */
   2432 		s = splbio();
   2433 		scsipi_adapter_request(chan, ADAPTER_REQ_SET_XFER_MODE, &xm);
   2434 		splx(s);
   2435 		/*
   2436 		 * If we want this to happen immediately, issue a dummy
   2437 		 * command, since most adapters can't really negotiate unless
   2438 		 * they're executing a job.
   2439 		 */
   2440 		if (immed != 0) {
   2441 			(void) scsipi_test_unit_ready(itperiph,
   2442 			    XS_CTL_DISCOVERY | XS_CTL_IGNORE_ILLEGAL_REQUEST |
   2443 			    XS_CTL_IGNORE_NOT_READY |
   2444 			    XS_CTL_IGNORE_MEDIA_CHANGE);
   2445 		}
   2446 	}
   2447 }
   2448 
   2449 /*
   2450  * scsipi_channel_reset:
   2451  *
   2452  *	handle scsi bus reset
   2453  * called at splbio
   2454  */
   2455 static void
   2456 scsipi_async_event_channel_reset(struct scsipi_channel *chan)
   2457 {
   2458 	struct scsipi_xfer *xs, *xs_next;
   2459 	struct scsipi_periph *periph;
   2460 	int target, lun;
   2461 
   2462 	/*
   2463 	 * Channel has been reset. Also mark as reset pending REQUEST_SENSE
   2464 	 * commands; as the sense is not available any more.
   2465 	 * can't call scsipi_done() from here, as the command has not been
   2466 	 * sent to the adapter yet (this would corrupt accounting).
   2467 	 */
   2468 
   2469 	for (xs = TAILQ_FIRST(&chan->chan_queue); xs != NULL; xs = xs_next) {
   2470 		xs_next = TAILQ_NEXT(xs, channel_q);
   2471 		if (xs->xs_control & XS_CTL_REQSENSE) {
   2472 			TAILQ_REMOVE(&chan->chan_queue, xs, channel_q);
   2473 			xs->error = XS_RESET;
   2474 			if ((xs->xs_control & XS_CTL_ASYNC) != 0)
   2475 				TAILQ_INSERT_TAIL(&chan->chan_complete, xs,
   2476 				    channel_q);
   2477 		}
   2478 	}
   2479 	wakeup(&chan->chan_complete);
   2480 	/* Catch xs with pending sense which may not have a REQSENSE xs yet */
   2481 	for (target = 0; target < chan->chan_ntargets; target++) {
   2482 		if (target == chan->chan_id)
   2483 			continue;
   2484 		for (lun = 0; lun <  chan->chan_nluns; lun++) {
   2485 			periph = scsipi_lookup_periph(chan, target, lun);
   2486 			if (periph) {
   2487 				xs = periph->periph_xscheck;
   2488 				if (xs)
   2489 					xs->error = XS_RESET;
   2490 			}
   2491 		}
   2492 	}
   2493 }
   2494 
   2495 /*
   2496  * scsipi_target_detach:
   2497  *
   2498  *	detach all periph associated with a I_T
   2499  * 	must be called from valid thread context
   2500  */
   2501 int
   2502 scsipi_target_detach(struct scsipi_channel *chan, int target, int lun,
   2503     int flags)
   2504 {
   2505 	struct scsipi_periph *periph;
   2506 	int ctarget, mintarget, maxtarget;
   2507 	int clun, minlun, maxlun;
   2508 	int error;
   2509 
   2510 	if (target == -1) {
   2511 		mintarget = 0;
   2512 		maxtarget = chan->chan_ntargets;
   2513 	} else {
   2514 		if (target == chan->chan_id)
   2515 			return EINVAL;
   2516 		if (target < 0 || target >= chan->chan_ntargets)
   2517 			return EINVAL;
   2518 		mintarget = target;
   2519 		maxtarget = target + 1;
   2520 	}
   2521 
   2522 	if (lun == -1) {
   2523 		minlun = 0;
   2524 		maxlun = chan->chan_nluns;
   2525 	} else {
   2526 		if (lun < 0 || lun >= chan->chan_nluns)
   2527 			return EINVAL;
   2528 		minlun = lun;
   2529 		maxlun = lun + 1;
   2530 	}
   2531 
   2532 	for (ctarget = mintarget; ctarget < maxtarget; ctarget++) {
   2533 		if (ctarget == chan->chan_id)
   2534 			continue;
   2535 
   2536 		for (clun = minlun; clun < maxlun; clun++) {
   2537 			periph = scsipi_lookup_periph(chan, ctarget, clun);
   2538 			if (periph == NULL)
   2539 				continue;
   2540 			error = config_detach(periph->periph_dev, flags);
   2541 			if (error)
   2542 				return (error);
   2543 		}
   2544 	}
   2545 	return(0);
   2546 }
   2547 
   2548 /*
   2549  * scsipi_adapter_addref:
   2550  *
   2551  *	Add a reference to the adapter pointed to by the provided
   2552  *	link, enabling the adapter if necessary.
   2553  */
   2554 int
   2555 scsipi_adapter_addref(struct scsipi_adapter *adapt)
   2556 {
   2557 	int s, error = 0;
   2558 
   2559 	s = splbio();
   2560 	if (adapt->adapt_refcnt++ == 0 && adapt->adapt_enable != NULL) {
   2561 		error = (*adapt->adapt_enable)(adapt->adapt_dev, 1);
   2562 		if (error)
   2563 			adapt->adapt_refcnt--;
   2564 	}
   2565 	splx(s);
   2566 	return (error);
   2567 }
   2568 
   2569 /*
   2570  * scsipi_adapter_delref:
   2571  *
   2572  *	Delete a reference to the adapter pointed to by the provided
   2573  *	link, disabling the adapter if possible.
   2574  */
   2575 void
   2576 scsipi_adapter_delref(struct scsipi_adapter *adapt)
   2577 {
   2578 	int s;
   2579 
   2580 	s = splbio();
   2581 	if (adapt->adapt_refcnt-- == 1 && adapt->adapt_enable != NULL)
   2582 		(void) (*adapt->adapt_enable)(adapt->adapt_dev, 0);
   2583 	splx(s);
   2584 }
   2585 
   2586 static struct scsipi_syncparam {
   2587 	int	ss_factor;
   2588 	int	ss_period;	/* ns * 100 */
   2589 } scsipi_syncparams[] = {
   2590 	{ 0x08,		 625 },	/* FAST-160 (Ultra320) */
   2591 	{ 0x09,		1250 },	/* FAST-80 (Ultra160) */
   2592 	{ 0x0a,		2500 },	/* FAST-40 40MHz (Ultra2) */
   2593 	{ 0x0b,		3030 },	/* FAST-40 33MHz (Ultra2) */
   2594 	{ 0x0c,		5000 },	/* FAST-20 (Ultra) */
   2595 };
   2596 static const int scsipi_nsyncparams =
   2597     sizeof(scsipi_syncparams) / sizeof(scsipi_syncparams[0]);
   2598 
   2599 int
   2600 scsipi_sync_period_to_factor(int period /* ns * 100 */)
   2601 {
   2602 	int i;
   2603 
   2604 	for (i = 0; i < scsipi_nsyncparams; i++) {
   2605 		if (period <= scsipi_syncparams[i].ss_period)
   2606 			return (scsipi_syncparams[i].ss_factor);
   2607 	}
   2608 
   2609 	return ((period / 100) / 4);
   2610 }
   2611 
   2612 int
   2613 scsipi_sync_factor_to_period(int factor)
   2614 {
   2615 	int i;
   2616 
   2617 	for (i = 0; i < scsipi_nsyncparams; i++) {
   2618 		if (factor == scsipi_syncparams[i].ss_factor)
   2619 			return (scsipi_syncparams[i].ss_period);
   2620 	}
   2621 
   2622 	return ((factor * 4) * 100);
   2623 }
   2624 
   2625 int
   2626 scsipi_sync_factor_to_freq(int factor)
   2627 {
   2628 	int i;
   2629 
   2630 	for (i = 0; i < scsipi_nsyncparams; i++) {
   2631 		if (factor == scsipi_syncparams[i].ss_factor)
   2632 			return (100000000 / scsipi_syncparams[i].ss_period);
   2633 	}
   2634 
   2635 	return (10000000 / ((factor * 4) * 10));
   2636 }
   2637 
   2638 #ifdef SCSIPI_DEBUG
   2639 /*
   2640  * Given a scsipi_xfer, dump the request, in all it's glory
   2641  */
   2642 void
   2643 show_scsipi_xs(struct scsipi_xfer *xs)
   2644 {
   2645 
   2646 	printf("xs(%p): ", xs);
   2647 	printf("xs_control(0x%08x)", xs->xs_control);
   2648 	printf("xs_status(0x%08x)", xs->xs_status);
   2649 	printf("periph(%p)", xs->xs_periph);
   2650 	printf("retr(0x%x)", xs->xs_retries);
   2651 	printf("timo(0x%x)", xs->timeout);
   2652 	printf("cmd(%p)", xs->cmd);
   2653 	printf("len(0x%x)", xs->cmdlen);
   2654 	printf("data(%p)", xs->data);
   2655 	printf("len(0x%x)", xs->datalen);
   2656 	printf("res(0x%x)", xs->resid);
   2657 	printf("err(0x%x)", xs->error);
   2658 	printf("bp(%p)", xs->bp);
   2659 	show_scsipi_cmd(xs);
   2660 }
   2661 
   2662 void
   2663 show_scsipi_cmd(struct scsipi_xfer *xs)
   2664 {
   2665 	u_char *b = (u_char *) xs->cmd;
   2666 	int i = 0;
   2667 
   2668 	scsipi_printaddr(xs->xs_periph);
   2669 	printf(" command: ");
   2670 
   2671 	if ((xs->xs_control & XS_CTL_RESET) == 0) {
   2672 		while (i < xs->cmdlen) {
   2673 			if (i)
   2674 				printf(",");
   2675 			printf("0x%x", b[i++]);
   2676 		}
   2677 		printf("-[%d bytes]\n", xs->datalen);
   2678 		if (xs->datalen)
   2679 			show_mem(xs->data, min(64, xs->datalen));
   2680 	} else
   2681 		printf("-RESET-\n");
   2682 }
   2683 
   2684 void
   2685 show_mem(u_char *address, int num)
   2686 {
   2687 	int x;
   2688 
   2689 	printf("------------------------------");
   2690 	for (x = 0; x < num; x++) {
   2691 		if ((x % 16) == 0)
   2692 			printf("\n%03d: ", x);
   2693 		printf("%02x ", *address++);
   2694 	}
   2695 	printf("\n------------------------------\n");
   2696 }
   2697 #endif /* SCSIPI_DEBUG */
   2698