xref: /openbsd-src/sys/scsi/scsi_base.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: scsi_base.c,v 1.225 2016/09/15 02:00:18 dlg Exp $	*/
2 /*	$NetBSD: scsi_base.c,v 1.43 1997/04/02 02:29:36 mycroft Exp $	*/
3 
4 /*
5  * Copyright (c) 1994, 1995, 1997 Charles M. Hannum.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by Charles M. Hannum.
18  * 4. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Originally written by Julian Elischer (julian@dialix.oz.au)
35  * Detailed SCSI error printing Copyright 1997 by Matthew Jacob.
36  */
37 
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/uio.h>
43 #include <sys/errno.h>
44 #include <sys/device.h>
45 #include <sys/pool.h>
46 #include <sys/task.h>
47 
48 #include <scsi/scsi_all.h>
49 #include <scsi/scsi_disk.h>
50 #include <scsi/scsiconf.h>
51 
52 static __inline void asc2ascii(u_int8_t, u_int8_t ascq, char *result,
53     size_t len);
54 int	scsi_xs_error(struct scsi_xfer *);
55 char   *scsi_decode_sense(struct scsi_sense_data *, int);
56 
57 void	scsi_xs_sync_done(struct scsi_xfer *);
58 
59 /* Values for flag parameter to scsi_decode_sense. */
60 #define	DECODE_SENSE_KEY	1
61 #define	DECODE_ASC_ASCQ		2
62 #define DECODE_SKSV		3
63 
64 struct pool		scsi_xfer_pool;
65 struct pool		scsi_plug_pool;
66 
67 struct scsi_plug {
68 	struct task		task;
69 	struct scsibus_softc	*sb;
70 	int			target;
71 	int			lun;
72 	int			how;
73 };
74 
75 void	scsi_plug_probe(void *);
76 void	scsi_plug_detach(void *);
77 
78 struct scsi_xfer *	scsi_xs_io(struct scsi_link *, void *, int);
79 
80 int			scsi_ioh_pending(struct scsi_iopool *);
81 struct scsi_iohandler *	scsi_ioh_deq(struct scsi_iopool *);
82 
83 void			scsi_xsh_runqueue(struct scsi_link *);
84 void			scsi_xsh_ioh(void *, void *);
85 
86 int			scsi_link_open(struct scsi_link *);
87 void			scsi_link_close(struct scsi_link *);
88 
89 void *			scsi_iopool_get(struct scsi_iopool *);
90 void			scsi_iopool_put(struct scsi_iopool *, void *);
91 
92 /* ioh/xsh queue state */
93 #define RUNQ_IDLE	0
94 #define RUNQ_LINKQ	1
95 #define RUNQ_POOLQ	2
96 
97 /* synchronous api for allocating an io. */
98 struct scsi_io_mover {
99 	struct mutex mtx;
100 	void *io;
101 	u_int done;
102 };
103 #define SCSI_IO_MOVER_INITIALIZER { MUTEX_INITIALIZER(IPL_BIO), NULL, 0 }
104 
105 void scsi_move(struct scsi_io_mover *);
106 void scsi_move_done(void *, void *);
107 
108 void scsi_io_get_done(void *, void *);
109 void scsi_xs_get_done(void *, void *);
110 
111 /*
112  * Called when a scsibus is attached to initialize global data.
113  */
114 void
115 scsi_init(void)
116 {
117 	static int scsi_init_done;
118 
119 	if (scsi_init_done)
120 		return;
121 	scsi_init_done = 1;
122 
123 #if defined(SCSI_DELAY) && SCSI_DELAY > 0
124 	/* Historical. Older buses may need a moment to stabilize. */
125 	delay(1000000 * SCSI_DELAY);
126 #endif
127 
128 	/* Initialize the scsi_xfer pool. */
129 	pool_init(&scsi_xfer_pool, sizeof(struct scsi_xfer), 0, IPL_BIO, 0,
130 	    "scxspl", NULL);
131 	pool_init(&scsi_plug_pool, sizeof(struct scsi_plug), 0, IPL_BIO, 0,
132 	    "scsiplug", NULL);
133 }
134 
135 int
136 scsi_req_probe(struct scsibus_softc *sb, int target, int lun)
137 {
138 	struct scsi_plug *p;
139 
140 	p = pool_get(&scsi_plug_pool, PR_NOWAIT);
141 	if (p == NULL)
142 		return (ENOMEM);
143 
144 	task_set(&p->task, scsi_plug_probe, p);
145 	p->sb = sb;
146 	p->target = target;
147 	p->lun = lun;
148 
149 	task_add(systq, &p->task);
150 
151 	return (0);
152 }
153 
154 int
155 scsi_req_detach(struct scsibus_softc *sb, int target, int lun, int how)
156 {
157 	struct scsi_plug *p;
158 
159 	p = pool_get(&scsi_plug_pool, PR_NOWAIT);
160 	if (p == NULL)
161 		return (ENOMEM);
162 
163 	task_set(&p->task, scsi_plug_detach, p);
164 	p->sb = sb;
165 	p->target = target;
166 	p->lun = lun;
167 	p->how = how;
168 
169 	task_add(systq, &p->task);
170 
171 	return (0);
172 }
173 
174 void
175 scsi_plug_probe(void *xp)
176 {
177 	struct scsi_plug *p = xp;
178 	struct scsibus_softc *sb = p->sb;
179 	int target = p->target, lun = p->lun;
180 
181 	pool_put(&scsi_plug_pool, p);
182 
183 	scsi_probe(sb, target, lun);
184 }
185 
186 void
187 scsi_plug_detach(void *xp)
188 {
189 	struct scsi_plug *p = xp;
190 	struct scsibus_softc *sb = p->sb;
191 	int target = p->target, lun = p->lun;
192 	int how = p->how;
193 
194 	pool_put(&scsi_plug_pool, p);
195 
196 	scsi_detach(sb, target, lun, how);
197 }
198 
199 int
200 scsi_pending_start(struct mutex *mtx, u_int *running)
201 {
202 	int rv = 1;
203 
204 	mtx_enter(mtx);
205 	(*running)++;
206 	if ((*running) > 1)
207 		rv = 0;
208 	mtx_leave(mtx);
209 
210 	return (rv);
211 }
212 
213 int
214 scsi_pending_finish(struct mutex *mtx, u_int *running)
215 {
216 	int rv = 1;
217 
218 	mtx_enter(mtx);
219 	(*running)--;
220 	if ((*running) > 0) {
221 		(*running) = 1;
222 		rv = 0;
223 	}
224 	mtx_leave(mtx);
225 
226 	return (rv);
227 }
228 
229 void
230 scsi_iopool_init(struct scsi_iopool *iopl, void *iocookie,
231     void *(*io_get)(void *), void (*io_put)(void *, void *))
232 {
233 	iopl->iocookie = iocookie;
234 	iopl->io_get = io_get;
235 	iopl->io_put = io_put;
236 
237 	TAILQ_INIT(&iopl->queue);
238 	iopl->running = 0;
239 	mtx_init(&iopl->mtx, IPL_BIO);
240 }
241 
242 void *
243 scsi_iopool_get(struct scsi_iopool *iopl)
244 {
245 	void *io;
246 
247 	KERNEL_LOCK();
248 	io = iopl->io_get(iopl->iocookie);
249 	KERNEL_UNLOCK();
250 
251 	return (io);
252 }
253 
254 void
255 scsi_iopool_put(struct scsi_iopool *iopl, void *io)
256 {
257 	KERNEL_LOCK();
258 	iopl->io_put(iopl->iocookie, io);
259 	KERNEL_UNLOCK();
260 }
261 
262 void
263 scsi_iopool_destroy(struct scsi_iopool *iopl)
264 {
265 	struct scsi_runq sleepers = TAILQ_HEAD_INITIALIZER(sleepers);
266 	struct scsi_iohandler *ioh = NULL;
267 
268 	mtx_enter(&iopl->mtx);
269 	while ((ioh = TAILQ_FIRST(&iopl->queue)) != NULL) {
270 		TAILQ_REMOVE(&iopl->queue, ioh, q_entry);
271 		ioh->q_state = RUNQ_IDLE;
272 
273 		if (ioh->handler == scsi_io_get_done)
274 			TAILQ_INSERT_TAIL(&sleepers, ioh, q_entry);
275 #ifdef DIAGNOSTIC
276 		else
277 			panic("scsi_iopool_destroy: scsi_iohandler on pool");
278 #endif
279 	}
280 	mtx_leave(&iopl->mtx);
281 
282 	while ((ioh = TAILQ_FIRST(&sleepers)) != NULL) {
283 		TAILQ_REMOVE(&sleepers, ioh, q_entry);
284 		ioh->handler(ioh->cookie, NULL);
285 	}
286 }
287 
288 void *
289 scsi_default_get(void *iocookie)
290 {
291 	return (SCSI_IOPOOL_POISON);
292 }
293 
294 void
295 scsi_default_put(void *iocookie, void *io)
296 {
297 #ifdef DIAGNOSTIC
298 	if (io != SCSI_IOPOOL_POISON)
299 		panic("unexpected opening returned");
300 #endif
301 }
302 
303 /*
304  * public interface to the ioh api.
305  */
306 
307 void
308 scsi_ioh_set(struct scsi_iohandler *ioh, struct scsi_iopool *iopl,
309     void (*handler)(void *, void *), void *cookie)
310 {
311 	ioh->q_state = RUNQ_IDLE;
312 	ioh->pool = iopl;
313 	ioh->handler = handler;
314 	ioh->cookie = cookie;
315 }
316 
317 int
318 scsi_ioh_add(struct scsi_iohandler *ioh)
319 {
320 	struct scsi_iopool *iopl = ioh->pool;
321 	int rv = 0;
322 
323 	mtx_enter(&iopl->mtx);
324 	switch (ioh->q_state) {
325 	case RUNQ_IDLE:
326 		TAILQ_INSERT_TAIL(&iopl->queue, ioh, q_entry);
327 		ioh->q_state = RUNQ_POOLQ;
328 		rv = 1;
329 		break;
330 #ifdef DIAGNOSTIC
331 	case RUNQ_POOLQ:
332 		break;
333 	default:
334 		panic("scsi_ioh_add: unexpected state %u", ioh->q_state);
335 #endif
336 	}
337 	mtx_leave(&iopl->mtx);
338 
339 	/* lets get some io up in the air */
340 	scsi_iopool_run(iopl);
341 
342 	return (rv);
343 }
344 
345 int
346 scsi_ioh_del(struct scsi_iohandler *ioh)
347 {
348 	struct scsi_iopool *iopl = ioh->pool;
349 	int rv = 0;
350 
351 	mtx_enter(&iopl->mtx);
352 	switch (ioh->q_state) {
353 	case RUNQ_POOLQ:
354 		TAILQ_REMOVE(&iopl->queue, ioh, q_entry);
355 		ioh->q_state = RUNQ_IDLE;
356 		rv = 1;
357 		break;
358 #ifdef DIAGNOSTIC
359 	case RUNQ_IDLE:
360 		break;
361 	default:
362 		panic("scsi_ioh_del: unexpected state %u", ioh->q_state);
363 #endif
364 	}
365 	mtx_leave(&iopl->mtx);
366 
367 	return (rv);
368 }
369 
370 /*
371  * internal iopool runqueue handling.
372  */
373 
374 struct scsi_iohandler *
375 scsi_ioh_deq(struct scsi_iopool *iopl)
376 {
377 	struct scsi_iohandler *ioh = NULL;
378 
379 	mtx_enter(&iopl->mtx);
380 	ioh = TAILQ_FIRST(&iopl->queue);
381 	if (ioh != NULL) {
382 		TAILQ_REMOVE(&iopl->queue, ioh, q_entry);
383 		ioh->q_state = RUNQ_IDLE;
384 	}
385 	mtx_leave(&iopl->mtx);
386 
387 	return (ioh);
388 }
389 
390 int
391 scsi_ioh_pending(struct scsi_iopool *iopl)
392 {
393 	int rv;
394 
395 	mtx_enter(&iopl->mtx);
396 	rv = !TAILQ_EMPTY(&iopl->queue);
397 	mtx_leave(&iopl->mtx);
398 
399 	return (rv);
400 }
401 
402 void
403 scsi_iopool_run(struct scsi_iopool *iopl)
404 {
405 	struct scsi_iohandler *ioh;
406 	void *io;
407 
408 	if (!scsi_pending_start(&iopl->mtx, &iopl->running))
409 		return;
410 	do {
411 		while (scsi_ioh_pending(iopl)) {
412 			io = scsi_iopool_get(iopl);
413 			if (io == NULL)
414 				break;
415 
416 			ioh = scsi_ioh_deq(iopl);
417 			if (ioh == NULL) {
418 				scsi_iopool_put(iopl, io);
419 				break;
420 			}
421 
422 			ioh->handler(ioh->cookie, io);
423 		}
424 	} while (!scsi_pending_finish(&iopl->mtx, &iopl->running));
425 }
426 
427 /*
428  * move an io from a runq to a proc thats waiting for an io.
429  */
430 
431 void
432 scsi_move(struct scsi_io_mover *m)
433 {
434 	mtx_enter(&m->mtx);
435 	while (!m->done)
436 		msleep(m, &m->mtx, PRIBIO, "scsiiomv", 0);
437 	mtx_leave(&m->mtx);
438 }
439 
440 void
441 scsi_move_done(void *cookie, void *io)
442 {
443 	struct scsi_io_mover *m = cookie;
444 
445 	mtx_enter(&m->mtx);
446 	m->io = io;
447 	m->done = 1;
448 	wakeup_one(m);
449 	mtx_leave(&m->mtx);
450 }
451 
452 /*
453  * synchronous api for allocating an io.
454  */
455 
456 void *
457 scsi_io_get(struct scsi_iopool *iopl, int flags)
458 {
459 	struct scsi_io_mover m = SCSI_IO_MOVER_INITIALIZER;
460 	struct scsi_iohandler ioh;
461 	void *io;
462 
463 	/* try and sneak an io off the backend immediately */
464 	io = scsi_iopool_get(iopl);
465 	if (io != NULL)
466 		return (io);
467 	else if (ISSET(flags, SCSI_NOSLEEP))
468 		return (NULL);
469 
470 	/* otherwise sleep until we get one */
471 	scsi_ioh_set(&ioh, iopl, scsi_io_get_done, &m);
472 	scsi_ioh_add(&ioh);
473 	scsi_move(&m);
474 
475 	return (m.io);
476 }
477 
478 void
479 scsi_io_get_done(void *cookie, void *io)
480 {
481 	scsi_move_done(cookie, io);
482 }
483 
484 void
485 scsi_io_put(struct scsi_iopool *iopl, void *io)
486 {
487 	scsi_iopool_put(iopl, io);
488 	scsi_iopool_run(iopl);
489 }
490 
491 /*
492  * public interface to the xsh api.
493  */
494 
495 void
496 scsi_xsh_set(struct scsi_xshandler *xsh, struct scsi_link *link,
497     void (*handler)(struct scsi_xfer *))
498 {
499 	scsi_ioh_set(&xsh->ioh, link->pool, scsi_xsh_ioh, xsh);
500 
501 	xsh->link = link;
502 	xsh->handler = handler;
503 }
504 
505 int
506 scsi_xsh_add(struct scsi_xshandler *xsh)
507 {
508 	struct scsi_link *link = xsh->link;
509 	int rv = 0;
510 
511 	if (ISSET(link->state, SDEV_S_DYING))
512 		return (0);
513 
514 	mtx_enter(&link->pool->mtx);
515 	if (xsh->ioh.q_state == RUNQ_IDLE) {
516 		TAILQ_INSERT_TAIL(&link->queue, &xsh->ioh, q_entry);
517 		xsh->ioh.q_state = RUNQ_LINKQ;
518 		rv = 1;
519 	}
520 	mtx_leave(&link->pool->mtx);
521 
522 	/* lets get some io up in the air */
523 	scsi_xsh_runqueue(link);
524 
525 	return (rv);
526 }
527 
528 int
529 scsi_xsh_del(struct scsi_xshandler *xsh)
530 {
531 	struct scsi_link *link = xsh->link;
532 	int rv = 1;
533 
534 	mtx_enter(&link->pool->mtx);
535 	switch (xsh->ioh.q_state) {
536 	case RUNQ_IDLE:
537 		rv = 0;
538 		break;
539 	case RUNQ_LINKQ:
540 		TAILQ_REMOVE(&link->queue, &xsh->ioh, q_entry);
541 		break;
542 	case RUNQ_POOLQ:
543 		TAILQ_REMOVE(&link->pool->queue, &xsh->ioh, q_entry);
544 		link->pending--;
545 		if (ISSET(link->state, SDEV_S_DYING) && link->pending == 0)
546 			wakeup_one(&link->pending);
547 		break;
548 	default:
549 		panic("unexpected xsh state %u", xsh->ioh.q_state);
550 	}
551 	xsh->ioh.q_state = RUNQ_IDLE;
552 	mtx_leave(&link->pool->mtx);
553 
554 	return (rv);
555 }
556 
557 /*
558  * internal xs runqueue handling.
559  */
560 
561 void
562 scsi_xsh_runqueue(struct scsi_link *link)
563 {
564 	struct scsi_iohandler *ioh;
565 	int runq;
566 
567 	if (!scsi_pending_start(&link->pool->mtx, &link->running))
568 		return;
569 	do {
570 		runq = 0;
571 
572 		mtx_enter(&link->pool->mtx);
573 		while (!ISSET(link->state, SDEV_S_DYING) &&
574 		    link->pending < link->openings &&
575 		    ((ioh = TAILQ_FIRST(&link->queue)) != NULL)) {
576 			link->pending++;
577 
578 			TAILQ_REMOVE(&link->queue, ioh, q_entry);
579 			TAILQ_INSERT_TAIL(&link->pool->queue, ioh, q_entry);
580 			ioh->q_state = RUNQ_POOLQ;
581 
582 			runq = 1;
583 		}
584 		mtx_leave(&link->pool->mtx);
585 
586 		if (runq)
587 			scsi_iopool_run(link->pool);
588 	} while (!scsi_pending_finish(&link->pool->mtx, &link->running));
589 }
590 
591 void
592 scsi_xsh_ioh(void *cookie, void *io)
593 {
594 	struct scsi_xshandler *xsh = cookie;
595 	struct scsi_xfer *xs;
596 
597 	xs = scsi_xs_io(xsh->link, io, SCSI_NOSLEEP);
598 	if (xs == NULL) {
599 		/*
600 		 * in this situation we should queue things waiting for an
601 		 * xs and then give them xses when they were supposed be to
602 		 * returned to the pool.
603 		 */
604 
605 		printf("scsi_xfer pool exhausted!\n");
606 		scsi_xsh_add(xsh);
607 		return;
608 	}
609 
610 	xsh->handler(xs);
611 }
612 
613 /*
614  * Get a scsi transfer structure for the caller.
615  * Go to the iopool backend for an "opening" and then attach an xs to it.
616  */
617 
618 struct scsi_xfer *
619 scsi_xs_get(struct scsi_link *link, int flags)
620 {
621 	struct scsi_xshandler xsh;
622 	struct scsi_io_mover m = SCSI_IO_MOVER_INITIALIZER;
623 
624 	struct scsi_iopool *iopl = link->pool;
625 	void *io;
626 
627 	if (ISSET(link->state, SDEV_S_DYING))
628 		return (NULL);
629 
630 	/* really custom xs handler to avoid scsi_xsh_ioh */
631 	scsi_ioh_set(&xsh.ioh, iopl, scsi_xs_get_done, &m);
632 	xsh.link = link;
633 
634 	if (!scsi_link_open(link)) {
635 		if (ISSET(flags, SCSI_NOSLEEP))
636 			return (NULL);
637 
638 		scsi_xsh_add(&xsh);
639 		scsi_move(&m);
640 		if (m.io == NULL)
641 			return (NULL);
642 
643 		io = m.io;
644 	} else if ((io = scsi_iopool_get(iopl)) == NULL) {
645 		if (ISSET(flags, SCSI_NOSLEEP)) {
646 			scsi_link_close(link);
647 			return (NULL);
648 		}
649 
650 		scsi_ioh_add(&xsh.ioh);
651 		scsi_move(&m);
652 		if (m.io == NULL)
653 			return (NULL);
654 
655 		io = m.io;
656 	}
657 
658 	return (scsi_xs_io(link, io, flags));
659 }
660 
661 void
662 scsi_xs_get_done(void *cookie, void *io)
663 {
664 	scsi_move_done(cookie, io);
665 }
666 
667 void
668 scsi_link_shutdown(struct scsi_link *link)
669 {
670 	struct scsi_runq sleepers = TAILQ_HEAD_INITIALIZER(sleepers);
671 	struct scsi_iopool *iopl = link->pool;
672 	struct scsi_iohandler *ioh;
673 	struct scsi_xshandler *xsh;
674 
675 	mtx_enter(&iopl->mtx);
676 	while ((ioh = TAILQ_FIRST(&link->queue)) != NULL) {
677 		TAILQ_REMOVE(&link->queue, ioh, q_entry);
678 		ioh->q_state = RUNQ_IDLE;
679 
680 		if (ioh->handler == scsi_xs_get_done)
681 			TAILQ_INSERT_TAIL(&sleepers, ioh, q_entry);
682 #ifdef DIAGNOSTIC
683 		else
684 			panic("scsi_link_shutdown: scsi_xshandler on link");
685 #endif
686 	}
687 
688 	ioh = TAILQ_FIRST(&iopl->queue);
689 	while (ioh != NULL) {
690 		xsh = (struct scsi_xshandler *)ioh;
691 		ioh = TAILQ_NEXT(ioh, q_entry);
692 
693 #ifdef DIAGNOSTIC
694 		if (xsh->ioh.handler == scsi_xsh_ioh &&
695 		    xsh->link == link)
696 			panic("scsi_link_shutdown: scsi_xshandler on pool");
697 #endif
698 
699 		if (xsh->ioh.handler == scsi_xs_get_done &&
700 		    xsh->link == link) {
701 			TAILQ_REMOVE(&iopl->queue, &xsh->ioh, q_entry);
702 			xsh->ioh.q_state = RUNQ_IDLE;
703 			link->pending--;
704 
705 			TAILQ_INSERT_TAIL(&sleepers, &xsh->ioh, q_entry);
706 		}
707 	}
708 
709 	while (link->pending > 0)
710 		msleep(&link->pending, &iopl->mtx, PRIBIO, "pendxs", 0);
711 	mtx_leave(&iopl->mtx);
712 
713 	while ((ioh = TAILQ_FIRST(&sleepers)) != NULL) {
714 		TAILQ_REMOVE(&sleepers, ioh, q_entry);
715 		ioh->handler(ioh->cookie, NULL);
716 	}
717 }
718 
719 int
720 scsi_link_open(struct scsi_link *link)
721 {
722 	int open = 0;
723 
724 	mtx_enter(&link->pool->mtx);
725 	if (link->pending < link->openings) {
726 		link->pending++;
727 		open = 1;
728 	}
729 	mtx_leave(&link->pool->mtx);
730 
731 	return (open);
732 }
733 
734 void
735 scsi_link_close(struct scsi_link *link)
736 {
737 	mtx_enter(&link->pool->mtx);
738 	link->pending--;
739 	if (ISSET(link->state, SDEV_S_DYING) && link->pending == 0)
740 		wakeup_one(&link->pending);
741 	mtx_leave(&link->pool->mtx);
742 
743 	scsi_xsh_runqueue(link);
744 }
745 
746 struct scsi_xfer *
747 scsi_xs_io(struct scsi_link *link, void *io, int flags)
748 {
749 	struct scsi_xfer *xs;
750 
751 	xs = pool_get(&scsi_xfer_pool, PR_ZERO |
752 	    (ISSET(flags, SCSI_NOSLEEP) ? PR_NOWAIT : PR_WAITOK));
753 	if (xs == NULL) {
754 		scsi_io_put(link->pool, io);
755 		scsi_link_close(link);
756 	} else {
757 		xs->flags = flags;
758 		xs->sc_link = link;
759 		xs->retries = SCSI_RETRIES;
760 		xs->timeout = 10000;
761 		xs->cmd = &xs->cmdstore;
762 		xs->io = io;
763 	}
764 
765 	return (xs);
766 }
767 
768 void
769 scsi_xs_put(struct scsi_xfer *xs)
770 {
771 	struct scsi_link *link = xs->sc_link;
772 	void *io = xs->io;
773 
774 	pool_put(&scsi_xfer_pool, xs);
775 
776 	scsi_io_put(link->pool, io);
777 	scsi_link_close(link);
778 }
779 
780 /*
781  * Get scsi driver to send a "are you ready?" command
782  */
783 int
784 scsi_test_unit_ready(struct scsi_link *link, int retries, int flags)
785 {
786 	struct scsi_test_unit_ready *cmd;
787 	struct scsi_xfer *xs;
788 	int error;
789 
790 	xs = scsi_xs_get(link, flags);
791 	if (xs == NULL)
792 		return (ENOMEM);
793 	xs->cmdlen = sizeof(*cmd);
794 	xs->retries = retries;
795 	xs->timeout = 10000;
796 
797 	cmd = (struct scsi_test_unit_ready *)xs->cmd;
798 	cmd->opcode = TEST_UNIT_READY;
799 
800 	error = scsi_xs_sync(xs);
801 	scsi_xs_put(xs);
802 
803 	return (error);
804 }
805 
806 void
807 scsi_init_inquiry(struct scsi_xfer *xs, u_int8_t flags, u_int8_t pagecode,
808     void *data, size_t len)
809 {
810 	struct scsi_inquiry *cmd;
811 
812 	cmd = (struct scsi_inquiry *)xs->cmd;
813 	cmd->opcode = INQUIRY;
814 	cmd->flags = flags;
815 	cmd->pagecode = pagecode;
816 	_lto2b(len, cmd->length);
817 
818 	xs->cmdlen = sizeof(*cmd);
819 
820 	xs->flags |= SCSI_DATA_IN;
821 	xs->data = data;
822 	xs->datalen = len;
823 }
824 
825 /*
826  * Do a scsi operation asking a device what it is.
827  * Use the scsi_cmd routine in the switch table.
828  */
829 int
830 scsi_inquire(struct scsi_link *link, struct scsi_inquiry_data *inqbuf,
831     int flags)
832 {
833 	struct scsi_xfer *xs;
834 	int error;
835 
836 	xs = scsi_xs_get(link, flags);
837 	if (xs == NULL)
838 		return (EBUSY);
839 
840 	/*
841 	 * Ask for only the basic 36 bytes of SCSI2 inquiry information. This
842 	 * avoids problems with devices that choke trying to supply more.
843 	 */
844 	scsi_init_inquiry(xs, 0, 0, inqbuf, SID_INQUIRY_HDR + SID_SCSI2_ALEN);
845 
846 	bzero(inqbuf, sizeof(*inqbuf));
847 	memset(&inqbuf->vendor, ' ', sizeof inqbuf->vendor);
848 	memset(&inqbuf->product, ' ', sizeof inqbuf->product);
849 	memset(&inqbuf->revision, ' ', sizeof inqbuf->revision);
850 	memset(&inqbuf->extra, ' ', sizeof inqbuf->extra);
851 
852 	error = scsi_xs_sync(xs);
853 
854 	scsi_xs_put(xs);
855 
856 	return (error);
857 }
858 
859 /*
860  * Query a VPD inquiry page
861  */
862 int
863 scsi_inquire_vpd(struct scsi_link *link, void *buf, u_int buflen,
864     u_int8_t page, int flags)
865 {
866 	struct scsi_xfer *xs;
867 	int error;
868 
869 	if (link->flags & SDEV_UMASS)
870 		return (EJUSTRETURN);
871 
872 	xs = scsi_xs_get(link, flags | SCSI_DATA_IN | SCSI_SILENT);
873 	if (xs == NULL)
874 		return (ENOMEM);
875 
876 	xs->retries = 2;
877 	xs->timeout = 10000;
878 
879 	scsi_init_inquiry(xs, SI_EVPD, page, buf, buflen);
880 
881 	error = scsi_xs_sync(xs);
882 
883 	scsi_xs_put(xs);
884 
885 	return (error);
886 }
887 
888 /*
889  * Prevent or allow the user to remove the media
890  */
891 int
892 scsi_prevent(struct scsi_link *link, int type, int flags)
893 {
894 	struct scsi_prevent *cmd;
895 	struct scsi_xfer *xs;
896 	int error;
897 
898 	if (link->quirks & ADEV_NODOORLOCK)
899 		return (0);
900 
901 	xs = scsi_xs_get(link, flags);
902 	if (xs == NULL)
903 		return (ENOMEM);
904 	xs->cmdlen = sizeof(*cmd);
905 	xs->retries = 2;
906 	xs->timeout = 5000;
907 
908 	cmd = (struct scsi_prevent *)xs->cmd;
909 	cmd->opcode = PREVENT_ALLOW;
910 	cmd->how = type;
911 
912 	error = scsi_xs_sync(xs);
913 	scsi_xs_put(xs);
914 
915 	return (error);
916 }
917 
918 /*
919  * Get scsi driver to send a "start up" command
920  */
921 int
922 scsi_start(struct scsi_link *link, int type, int flags)
923 {
924 	struct scsi_start_stop *cmd;
925 	struct scsi_xfer *xs;
926 	int error;
927 
928 	xs = scsi_xs_get(link, flags);
929 	if (xs == NULL)
930 		return (ENOMEM);
931 	xs->cmdlen = sizeof(*cmd);
932 	xs->retries = 2;
933 	xs->timeout = (type == SSS_START) ? 30000 : 10000;
934 
935 	cmd = (struct scsi_start_stop *)xs->cmd;
936 	cmd->opcode = START_STOP;
937 	cmd->how = type;
938 
939 	error = scsi_xs_sync(xs);
940 	scsi_xs_put(xs);
941 
942 	return (error);
943 }
944 
945 int
946 scsi_mode_sense(struct scsi_link *link, int byte2, int page,
947     struct scsi_mode_header *data, size_t len, int flags, int timeout)
948 {
949 	struct scsi_mode_sense *cmd;
950 	struct scsi_xfer *xs;
951 	int error;
952 
953 	xs = scsi_xs_get(link, flags | SCSI_DATA_IN);
954 	if (xs == NULL)
955 		return (ENOMEM);
956 	xs->cmdlen = sizeof(*cmd);
957 	xs->data = (void *)data;
958 	xs->datalen = len;
959 	xs->timeout = timeout;
960 
961 	/*
962 	 * Make sure the sense buffer is clean before we do the mode sense, so
963 	 * that checks for bogus values of 0 will work in case the mode sense
964 	 * fails.
965 	 */
966 	bzero(data, len);
967 
968 	cmd = (struct scsi_mode_sense *)xs->cmd;
969 	cmd->opcode = MODE_SENSE;
970 	cmd->byte2 = byte2;
971 	cmd->page = page;
972 
973 	if (len > 0xff)
974 		len = 0xff;
975 	cmd->length = len;
976 
977 	error = scsi_xs_sync(xs);
978 	scsi_xs_put(xs);
979 
980 	SC_DEBUG(link, SDEV_DB2, ("scsi_mode_sense: page %#x, error = %d\n",
981 	    page, error));
982 
983 	return (error);
984 }
985 
986 int
987 scsi_mode_sense_big(struct scsi_link *link, int byte2, int page,
988     struct scsi_mode_header_big *data, size_t len, int flags, int timeout)
989 {
990 	struct scsi_mode_sense_big *cmd;
991 	struct scsi_xfer *xs;
992 	int error;
993 
994 	xs = scsi_xs_get(link, flags | SCSI_DATA_IN);
995 	if (xs == NULL)
996 		return (ENOMEM);
997 	xs->cmdlen = sizeof(*cmd);
998 	xs->data = (void *)data;
999 	xs->datalen = len;
1000 	xs->timeout = timeout;
1001 
1002 	/*
1003 	 * Make sure the sense buffer is clean before we do the mode sense, so
1004 	 * that checks for bogus values of 0 will work in case the mode sense
1005 	 * fails.
1006 	 */
1007 	bzero(data, len);
1008 
1009 	cmd = (struct scsi_mode_sense_big *)xs->cmd;
1010 	cmd->opcode = MODE_SENSE_BIG;
1011 	cmd->byte2 = byte2;
1012 	cmd->page = page;
1013 
1014 	if (len > 0xffff)
1015 		len = 0xffff;
1016 	_lto2b(len, cmd->length);
1017 
1018 	error = scsi_xs_sync(xs);
1019 	scsi_xs_put(xs);
1020 
1021 	SC_DEBUG(link, SDEV_DB2,
1022 	    ("scsi_mode_sense_big: page %#x, error = %d\n", page, error));
1023 
1024 	return (error);
1025 }
1026 
1027 void *
1028 scsi_mode_sense_page(struct scsi_mode_header *hdr, const int page_len)
1029 {
1030 	int					total_length, header_length;
1031 
1032 	total_length = hdr->data_length + sizeof(hdr->data_length);
1033 	header_length = sizeof(*hdr) + hdr->blk_desc_len;
1034 
1035 	if ((total_length - header_length) < page_len)
1036 		return (NULL);
1037 
1038 	return ((u_char *)hdr + header_length);
1039 }
1040 
1041 void *
1042 scsi_mode_sense_big_page(struct scsi_mode_header_big *hdr, const int page_len)
1043 {
1044 	int					total_length, header_length;
1045 
1046 	total_length = _2btol(hdr->data_length) + sizeof(hdr->data_length);
1047 	header_length = sizeof(*hdr) + _2btol(hdr->blk_desc_len);
1048 
1049 	if ((total_length - header_length) < page_len)
1050 		return (NULL);
1051 
1052 	return ((u_char *)hdr + header_length);
1053 }
1054 
1055 int
1056 scsi_do_mode_sense(struct scsi_link *link, int page,
1057     union scsi_mode_sense_buf *buf, void **page_data, u_int32_t *density,
1058     u_int64_t *block_count, u_int32_t *block_size, int page_len, int flags,
1059     int *big)
1060 {
1061 	struct scsi_direct_blk_desc		*direct;
1062 	struct scsi_blk_desc			*general;
1063 	int					error, blk_desc_len, offset;
1064 
1065 	*page_data = NULL;
1066 
1067 	if (density != NULL)
1068 		*density = 0;
1069 	if (block_count != NULL)
1070 		*block_count = 0;
1071 	if (block_size != NULL)
1072 		*block_size = 0;
1073 	if (big != NULL)
1074 		*big = 0;
1075 
1076 	if ((link->flags & SDEV_ATAPI) == 0 ||
1077 	    (link->inqdata.device & SID_TYPE) == T_SEQUENTIAL) {
1078 		/*
1079 		 * Try 6 byte mode sense request first. Some devices don't
1080 		 * distinguish between 6 and 10 byte MODE SENSE commands,
1081 		 * returning 6 byte data for 10 byte requests. ATAPI tape
1082 		 * drives use MODE SENSE (6) even though ATAPI uses 10 byte
1083 		 * everything else. Don't bother with SMS_DBD. Check returned
1084 		 * data length to ensure that at least a header (3 additional
1085 		 * bytes) is returned.
1086 		 */
1087 		error = scsi_mode_sense(link, 0, page, &buf->hdr,
1088 		    sizeof(*buf), flags, 20000);
1089 		if (error == 0) {
1090 			*page_data = scsi_mode_sense_page(&buf->hdr, page_len);
1091 			if (*page_data == NULL) {
1092 				/*
1093 				 * XXX
1094 				 * Page data may be invalid (e.g. all zeros)
1095 				 * but we accept the device's word that this is
1096 				 * the best it can do. Some devices will freak
1097 				 * out if their word is not accepted and
1098 				 * MODE_SENSE_BIG is attempted.
1099 				 */
1100 				return (0);
1101 			}
1102 			offset = sizeof(struct scsi_mode_header);
1103 			blk_desc_len = buf->hdr.blk_desc_len;
1104 			goto blk_desc;
1105 		}
1106 	}
1107 
1108 	/*
1109 	 * Try 10 byte mode sense request. Don't bother with SMS_DBD or
1110 	 * SMS_LLBAA. Bail out if the returned information is less than
1111 	 * a big header in size (6 additional bytes).
1112 	 */
1113 	if ((link->flags & (SDEV_ATAPI | SDEV_UMASS)) == 0 &&
1114 	    SCSISPC(link->inqdata.version) < 2) {
1115 		/*
1116 		 * The 10 byte MODE_SENSE request appeared with SCSI-2,
1117 		 * so don't bother trying it on SCSI-1 devices, they are
1118 		 * not supposed to understand it.
1119 		 */
1120 		return (0);
1121 	}
1122 	error = scsi_mode_sense_big(link, 0, page, &buf->hdr_big,
1123 	    sizeof(*buf), flags, 20000);
1124 	if (error != 0)
1125 		return (error);
1126 	if (_2btol(buf->hdr_big.data_length) < 6)
1127 		return (EIO);
1128 
1129 	if (big != NULL)
1130 		*big = 1;
1131 	offset = sizeof(struct scsi_mode_header_big);
1132 	*page_data = scsi_mode_sense_big_page(&buf->hdr_big, page_len);
1133 	blk_desc_len = _2btol(buf->hdr_big.blk_desc_len);
1134 
1135 blk_desc:
1136 	/* Both scsi_blk_desc and scsi_direct_blk_desc are 8 bytes. */
1137 	if (blk_desc_len == 0 || (blk_desc_len % 8 != 0))
1138 		return (0);
1139 
1140 	switch (link->inqdata.device & SID_TYPE) {
1141 	case T_SEQUENTIAL:
1142 		/*
1143 		 * XXX What other device types return general block descriptors?
1144 		 */
1145 		general = (struct scsi_blk_desc *)&buf->buf[offset];
1146 		if (density != NULL)
1147 			*density = general->density;
1148 		if (block_size != NULL)
1149 			*block_size = _3btol(general->blklen);
1150 		if (block_count != NULL)
1151 			*block_count = (u_int64_t)_3btol(general->nblocks);
1152 		break;
1153 
1154 	default:
1155 		direct = (struct scsi_direct_blk_desc *)&buf->buf[offset];
1156 		if (density != NULL)
1157 			*density = direct->density;
1158 		if (block_size != NULL)
1159 			*block_size = _3btol(direct->blklen);
1160 		if (block_count != NULL)
1161 			*block_count = (u_int64_t)_4btol(direct->nblocks);
1162 		break;
1163 	}
1164 
1165 	return (0);
1166 }
1167 
1168 int
1169 scsi_mode_select(struct scsi_link *link, int byte2,
1170     struct scsi_mode_header *data, int flags, int timeout)
1171 {
1172 	struct scsi_mode_select *cmd;
1173 	struct scsi_xfer *xs;
1174 	u_int32_t len;
1175 	int error;
1176 
1177 	len = data->data_length + 1; /* 1 == sizeof(data_length) */
1178 
1179 	xs = scsi_xs_get(link, flags | SCSI_DATA_OUT);
1180 	if (xs == NULL)
1181 		return (ENOMEM);
1182 	xs->cmdlen = sizeof(*cmd);
1183 	xs->data = (void *)data;
1184 	xs->datalen = len;
1185 	xs->timeout = timeout;
1186 
1187 	cmd = (struct scsi_mode_select *)xs->cmd;
1188 	cmd->opcode = MODE_SELECT;
1189 	cmd->byte2 = byte2;
1190 	cmd->length = len;
1191 
1192 	/* Length is reserved when doing mode select so zero it. */
1193 	data->data_length = 0;
1194 
1195 	error = scsi_xs_sync(xs);
1196 	scsi_xs_put(xs);
1197 
1198 	SC_DEBUG(link, SDEV_DB2, ("scsi_mode_select: error = %d\n", error));
1199 
1200 	return (error);
1201 }
1202 
1203 int
1204 scsi_mode_select_big(struct scsi_link *link, int byte2,
1205     struct scsi_mode_header_big *data, int flags, int timeout)
1206 {
1207 	struct scsi_mode_select_big *cmd;
1208 	struct scsi_xfer *xs;
1209 	u_int32_t len;
1210 	int error;
1211 
1212 	len = _2btol(data->data_length) + 2; /* 2 == sizeof data_length */
1213 
1214 	xs = scsi_xs_get(link, flags | SCSI_DATA_OUT);
1215 	if (xs == NULL)
1216 		return (ENOMEM);
1217 	xs->cmdlen = sizeof(*cmd);
1218 	xs->data = (void *)data;
1219 	xs->datalen = len;
1220 	xs->timeout = timeout;
1221 
1222 	cmd = (struct scsi_mode_select_big *)xs->cmd;
1223 	cmd->opcode = MODE_SELECT_BIG;
1224 	cmd->byte2 = byte2;
1225 	_lto2b(len, cmd->length);
1226 
1227 	/* Length is reserved when doing mode select so zero it. */
1228 	_lto2b(0, data->data_length);
1229 
1230 	error = scsi_xs_sync(xs);
1231 	scsi_xs_put(xs);
1232 
1233 	SC_DEBUG(link, SDEV_DB2, ("scsi_mode_select_big: error = %d\n",
1234 	    error));
1235 
1236 	return (error);
1237 }
1238 
1239 int
1240 scsi_report_luns(struct scsi_link *link, int selectreport,
1241     struct scsi_report_luns_data *data, u_int32_t datalen, int flags,
1242     int timeout)
1243 {
1244 	struct scsi_report_luns *cmd;
1245 	struct scsi_xfer *xs;
1246 	int error;
1247 
1248 	xs = scsi_xs_get(link, flags | SCSI_DATA_IN);
1249 	if (xs == NULL)
1250 		return (ENOMEM);
1251 	xs->cmdlen = sizeof(*cmd);
1252 	xs->data = (void *)data;
1253 	xs->datalen = datalen;
1254 	xs->timeout = timeout;
1255 
1256 	bzero(data, datalen);
1257 
1258 	cmd = (struct scsi_report_luns *)xs->cmd;
1259 	cmd->opcode = REPORT_LUNS;
1260 	cmd->selectreport = selectreport;
1261 	_lto4b(datalen, cmd->length);
1262 
1263 	error = scsi_xs_sync(xs);
1264 	scsi_xs_put(xs);
1265 
1266 	SC_DEBUG(link, SDEV_DB2, ("scsi_report_luns: error = %d\n", error));
1267 
1268 	return (error);
1269 }
1270 
1271 void
1272 scsi_xs_exec(struct scsi_xfer *xs)
1273 {
1274 	xs->error = XS_NOERROR;
1275 	xs->resid = xs->datalen;
1276 	xs->status = 0;
1277 	CLR(xs->flags, ITSDONE);
1278 
1279 #ifdef SCSIDEBUG
1280 	if (xs->sc_link->flags & SDEV_DB1) {
1281 		scsi_xs_show(xs);
1282 		if (xs->datalen && (xs->flags & SCSI_DATA_OUT))
1283 			scsi_show_mem(xs->data, min(64, xs->datalen));
1284 	}
1285 #endif
1286 
1287 	/* The adapter's scsi_cmd() is responsible for calling scsi_done(). */
1288 	KERNEL_LOCK();
1289 	xs->sc_link->adapter->scsi_cmd(xs);
1290 	KERNEL_UNLOCK();
1291 }
1292 
1293 /*
1294  * This routine is called by the adapter when its xs handling is done.
1295  */
1296 void
1297 scsi_done(struct scsi_xfer *xs)
1298 {
1299 #ifdef SCSIDEBUG
1300 	if (xs->sc_link->flags & SDEV_DB1) {
1301 		if (xs->datalen && (xs->flags & SCSI_DATA_IN))
1302 			scsi_show_mem(xs->data, min(64, xs->datalen));
1303 	}
1304 #endif /* SCSIDEBUG */
1305 
1306 	SET(xs->flags, ITSDONE);
1307 	KERNEL_LOCK();
1308 	xs->done(xs);
1309 	KERNEL_UNLOCK();
1310 }
1311 
1312 int
1313 scsi_xs_sync(struct scsi_xfer *xs)
1314 {
1315 	struct mutex cookie = MUTEX_INITIALIZER(IPL_BIO);
1316 	int error;
1317 
1318 #ifdef DIAGNOSTIC
1319 	if (xs->cookie != NULL)
1320 		panic("xs->cookie != NULL in scsi_xs_sync");
1321 	if (xs->done != NULL)
1322 		panic("xs->done != NULL in scsi_xs_sync");
1323 #endif
1324 
1325 	/*
1326 	 * If we cant sleep while waiting for completion, get the adapter to
1327 	 * complete it for us.
1328 	 */
1329 	if (ISSET(xs->flags, SCSI_NOSLEEP))
1330 		SET(xs->flags, SCSI_POLL);
1331 
1332 	xs->done = scsi_xs_sync_done;
1333 
1334 	do {
1335 		xs->cookie = &cookie;
1336 
1337 		scsi_xs_exec(xs);
1338 
1339 		mtx_enter(&cookie);
1340 		while (xs->cookie != NULL)
1341 			msleep(xs, &cookie, PRIBIO, "syncxs", 0);
1342 		mtx_leave(&cookie);
1343 
1344 		error = scsi_xs_error(xs);
1345 	} while (error == ERESTART);
1346 
1347 	return (error);
1348 }
1349 
1350 void
1351 scsi_xs_sync_done(struct scsi_xfer *xs)
1352 {
1353 	struct mutex *cookie = xs->cookie;
1354 
1355 	if (cookie == NULL)
1356 		panic("scsi_done called twice on xs(%p)", xs);
1357 
1358 	mtx_enter(cookie);
1359 	xs->cookie = NULL;
1360 	if (!ISSET(xs->flags, SCSI_NOSLEEP))
1361 		wakeup_one(xs);
1362 	mtx_leave(cookie);
1363 }
1364 
1365 int
1366 scsi_xs_error(struct scsi_xfer *xs)
1367 {
1368 	int error = EIO;
1369 
1370 	SC_DEBUG(xs->sc_link, SDEV_DB3, ("scsi_xs_error,err = 0x%x\n",
1371 	    xs->error));
1372 
1373 	if (ISSET(xs->sc_link->state, SDEV_S_DYING))
1374 		return (ENXIO);
1375 
1376 	switch (xs->error) {
1377 	case XS_NOERROR:	/* nearly always hit this one */
1378 		error = 0;
1379 		break;
1380 
1381 	case XS_SENSE:
1382 	case XS_SHORTSENSE:
1383 #ifdef SCSIDEBUG
1384 		scsi_sense_print_debug(xs);
1385 #endif
1386 		error = xs->sc_link->interpret_sense(xs);
1387 		SC_DEBUG(xs->sc_link, SDEV_DB3,
1388 		    ("scsi_interpret_sense returned %#x\n", error));
1389 		break;
1390 
1391 	case XS_NO_CCB:
1392 	case XS_BUSY:
1393 		error = scsi_delay(xs, 1);
1394 		break;
1395 
1396 	case XS_TIMEOUT:
1397 	case XS_RESET:
1398 		error = ERESTART;
1399 		break;
1400 
1401 	case XS_DRIVER_STUFFUP:
1402 	case XS_SELTIMEOUT:
1403 		break;
1404 
1405 	default:
1406 		sc_print_addr(xs->sc_link);
1407 		printf("unknown error category (0x%x) from scsi driver\n",
1408 		    xs->error);
1409 		break;
1410 	}
1411 
1412 	if (error == ERESTART && xs->retries-- < 1)
1413 		return (EIO);
1414 	else
1415 		return (error);
1416 }
1417 
1418 int
1419 scsi_delay(struct scsi_xfer *xs, int seconds)
1420 {
1421 	switch (xs->flags & (SCSI_POLL | SCSI_NOSLEEP)) {
1422 	case SCSI_POLL:
1423 		delay(1000000 * seconds);
1424 		return (ERESTART);
1425 	case SCSI_NOSLEEP:
1426 		/* Retry the command immediately since we can't delay. */
1427 		return (ERESTART);
1428 	case (SCSI_POLL | SCSI_NOSLEEP):
1429 		/* Invalid combination! */
1430 		return (EIO);
1431 	}
1432 
1433 	while (seconds-- > 0) {
1434 		if (tsleep(&lbolt, PRIBIO|PCATCH, "scbusy", 0)) {
1435 			/* Signal == abort xs. */
1436 			return (EIO);
1437 		}
1438 	}
1439 
1440 	return (ERESTART);
1441 }
1442 
1443 #ifdef SCSIDEBUG
1444 /*
1445  * Print out sense data details.
1446  */
1447 void
1448 scsi_sense_print_debug(struct scsi_xfer *xs)
1449 {
1450 	struct scsi_sense_data *sense = &xs->sense;
1451 	struct scsi_link *link = xs->sc_link;
1452 
1453 	SC_DEBUG(link, SDEV_DB1,
1454 	    ("code:%#x valid:%d key:%#x ili:%d eom:%d fmark:%d extra:%d\n",
1455 	    sense->error_code & SSD_ERRCODE,
1456 	    sense->error_code & SSD_ERRCODE_VALID ? 1 : 0,
1457 	    sense->flags & SSD_KEY,
1458 	    sense->flags & SSD_ILI ? 1 : 0,
1459 	    sense->flags & SSD_EOM ? 1 : 0,
1460 	    sense->flags & SSD_FILEMARK ? 1 : 0,
1461 	    sense->extra_len));
1462 
1463 	if (xs->sc_link->flags & SDEV_DB1)
1464 		scsi_show_mem((u_char *)&xs->sense, sizeof(xs->sense));
1465 
1466 	scsi_print_sense(xs);
1467 }
1468 #endif
1469 
1470 /*
1471  * Look at the returned sense and act on the error, determining
1472  * the unix error number to pass back.  (0 = report no error)
1473  *
1474  * THIS IS THE DEFAULT ERROR HANDLER
1475  */
1476 int
1477 scsi_interpret_sense(struct scsi_xfer *xs)
1478 {
1479 	struct scsi_sense_data			*sense = &xs->sense;
1480 	struct scsi_link			*link = xs->sc_link;
1481 	u_int8_t				serr, skey;
1482 	int					error;
1483 
1484 	/* Default sense interpretation. */
1485 	serr = sense->error_code & SSD_ERRCODE;
1486 	if (serr != SSD_ERRCODE_CURRENT && serr != SSD_ERRCODE_DEFERRED)
1487 		skey = 0xff;	/* Invalid value, since key is 4 bit value. */
1488 	else
1489 		skey = sense->flags & SSD_KEY;
1490 
1491 	/*
1492 	 * Interpret the key/asc/ascq information where appropriate.
1493 	 */
1494 	error = 0;
1495 	switch (skey) {
1496 	case SKEY_NO_SENSE:
1497 	case SKEY_RECOVERED_ERROR:
1498 		if (xs->resid == xs->datalen)
1499 			xs->resid = 0;	/* not short read */
1500 		break;
1501 	case SKEY_BLANK_CHECK:
1502 	case SKEY_EQUAL:
1503 		break;
1504 	case SKEY_NOT_READY:
1505 		if ((xs->flags & SCSI_IGNORE_NOT_READY) != 0)
1506 			return (0);
1507 		error = EIO;
1508 		if (xs->retries) {
1509 			switch (ASC_ASCQ(sense)) {
1510 			case SENSE_NOT_READY_BECOMING_READY:
1511 			case SENSE_NOT_READY_FORMAT:
1512 			case SENSE_NOT_READY_REBUILD:
1513 			case SENSE_NOT_READY_RECALC:
1514 			case SENSE_NOT_READY_INPROGRESS:
1515 			case SENSE_NOT_READY_LONGWRITE:
1516 			case SENSE_NOT_READY_SELFTEST:
1517 			case SENSE_NOT_READY_INIT_REQUIRED:
1518 				SC_DEBUG(link, SDEV_DB1,
1519 				    ("not ready (ASC_ASCQ == %#x)\n",
1520 				    ASC_ASCQ(sense)));
1521 				return (scsi_delay(xs, 1));
1522 			case SENSE_NOMEDIUM:
1523 			case SENSE_NOMEDIUM_TCLOSED:
1524 			case SENSE_NOMEDIUM_TOPEN:
1525 			case SENSE_NOMEDIUM_LOADABLE:
1526 			case SENSE_NOMEDIUM_AUXMEM:
1527 				link->flags &= ~SDEV_MEDIA_LOADED;
1528 				error = ENOMEDIUM;
1529 				break;
1530 			default:
1531 				break;
1532 			}
1533 		}
1534 		break;
1535 	case SKEY_MEDIUM_ERROR:
1536 		switch (ASC_ASCQ(sense)) {
1537 		case SENSE_NOMEDIUM:
1538 		case SENSE_NOMEDIUM_TCLOSED:
1539 		case SENSE_NOMEDIUM_TOPEN:
1540 		case SENSE_NOMEDIUM_LOADABLE:
1541 		case SENSE_NOMEDIUM_AUXMEM:
1542 			link->flags &= ~SDEV_MEDIA_LOADED;
1543 			error = ENOMEDIUM;
1544 			break;
1545 		case SENSE_BAD_MEDIUM:
1546 		case SENSE_NR_MEDIUM_UNKNOWN_FORMAT:
1547 		case SENSE_NR_MEDIUM_INCOMPATIBLE_FORMAT:
1548 		case SENSE_NW_MEDIUM_UNKNOWN_FORMAT:
1549 		case SENSE_NW_MEDIUM_INCOMPATIBLE_FORMAT:
1550 		case SENSE_NF_MEDIUM_INCOMPATIBLE_FORMAT:
1551 		case SENSE_NW_MEDIUM_AC_MISMATCH:
1552 			error = EMEDIUMTYPE;
1553 			break;
1554 		default:
1555 			error = EIO;
1556 			break;
1557 		}
1558 		break;
1559 	case SKEY_ILLEGAL_REQUEST:
1560 		if ((xs->flags & SCSI_IGNORE_ILLEGAL_REQUEST) != 0)
1561 			return (0);
1562 		if (ASC_ASCQ(sense) == SENSE_MEDIUM_REMOVAL_PREVENTED)
1563 			return(EBUSY);
1564 		error = EINVAL;
1565 		break;
1566 	case SKEY_UNIT_ATTENTION:
1567 		switch (ASC_ASCQ(sense)) {
1568 		case SENSE_POWER_RESET_OR_BUS:
1569 		case SENSE_POWER_ON:
1570 		case SENSE_BUS_RESET:
1571 		case SENSE_BUS_DEVICE_RESET:
1572 		case SENSE_DEVICE_INTERNAL_RESET:
1573 		case SENSE_TSC_CHANGE_SE:
1574 		case SENSE_TSC_CHANGE_LVD:
1575 		case SENSE_IT_NEXUS_LOSS:
1576 			return (scsi_delay(xs, 1));
1577 		default:
1578 			break;
1579 		}
1580 		if ((link->flags & SDEV_REMOVABLE) != 0)
1581 			link->flags &= ~SDEV_MEDIA_LOADED;
1582 		if ((xs->flags & SCSI_IGNORE_MEDIA_CHANGE) != 0 ||
1583 		    /* XXX Should reupload any transient state. */
1584 		    (link->flags & SDEV_REMOVABLE) == 0) {
1585 			return (scsi_delay(xs, 1));
1586 		}
1587 		error = EIO;
1588 		break;
1589 	case SKEY_WRITE_PROTECT:
1590 		error = EROFS;
1591 		break;
1592 	case SKEY_ABORTED_COMMAND:
1593 		error = ERESTART;
1594 		break;
1595 	case SKEY_VOLUME_OVERFLOW:
1596 		error = ENOSPC;
1597 		break;
1598 	case SKEY_HARDWARE_ERROR:
1599 		if (ASC_ASCQ(sense) == SENSE_CARTRIDGE_FAULT)
1600 			return(EMEDIUMTYPE);
1601 		error = EIO;
1602 		break;
1603 	default:
1604 		error = EIO;
1605 		break;
1606 	}
1607 
1608 #ifndef SCSIDEBUG
1609 	/* SCSIDEBUG would mean it has already been printed. */
1610 	if (skey && (xs->flags & SCSI_SILENT) == 0)
1611 		scsi_print_sense(xs);
1612 #endif /* SCSIDEBUG */
1613 
1614 	return (error);
1615 }
1616 
1617 /*
1618  * Utility routines often used in SCSI stuff
1619  */
1620 
1621 
1622 /*
1623  * Print out the scsi_link structure's address info.
1624  */
1625 void
1626 sc_print_addr(struct scsi_link *link)
1627 {
1628 	struct device *adapter_device = link->bus->sc_dev.dv_parent;
1629 
1630 	printf("%s(%s:%d:%d): ",
1631 	    link->device_softc ?
1632 	    ((struct device *)link->device_softc)->dv_xname : "probe",
1633 	    adapter_device->dv_xname,
1634 	    link->target, link->lun);
1635 }
1636 
1637 static const char *sense_keys[16] = {
1638 	"No Additional Sense",
1639 	"Soft Error",
1640 	"Not Ready",
1641 	"Media Error",
1642 	"Hardware Error",
1643 	"Illegal Request",
1644 	"Unit Attention",
1645 	"Write Protected",
1646 	"Blank Check",
1647 	"Vendor Unique",
1648 	"Copy Aborted",
1649 	"Aborted Command",
1650 	"Equal Error",
1651 	"Volume Overflow",
1652 	"Miscompare Error",
1653 	"Reserved"
1654 };
1655 
1656 #ifdef SCSITERSE
1657 static __inline void
1658 asc2ascii(u_int8_t asc, u_int8_t ascq, char *result, size_t len)
1659 {
1660 	snprintf(result, len, "ASC 0x%02x ASCQ 0x%02x", asc, ascq);
1661 }
1662 #else
1663 static const struct {
1664 	u_int8_t asc, ascq;
1665 	char *description;
1666 } adesc[] = {
1667 	/* www.t10.org/lists/asc-num.txt as of 11/15/10. */
1668 	{ 0x00, 0x00, "No Additional Sense Information" },
1669 	{ 0x00, 0x01, "Filemark Detected" },
1670 	{ 0x00, 0x02, "End-Of-Partition/Medium Detected" },
1671 	{ 0x00, 0x03, "Setmark Detected" },
1672 	{ 0x00, 0x04, "Beginning-Of-Partition/Medium Detected" },
1673 	{ 0x00, 0x05, "End-Of-Data Detected" },
1674 	{ 0x00, 0x06, "I/O Process Terminated" },
1675 	{ 0x00, 0x11, "Audio Play Operation In Progress" },
1676 	{ 0x00, 0x12, "Audio Play Operation Paused" },
1677 	{ 0x00, 0x13, "Audio Play Operation Successfully Completed" },
1678 	{ 0x00, 0x14, "Audio Play Operation Stopped Due to Error" },
1679 	{ 0x00, 0x15, "No Current Audio Status To Return" },
1680 	{ 0x00, 0x16, "Operation In Progress" },
1681 	{ 0x00, 0x17, "Cleaning Requested" },
1682 	{ 0x00, 0x18, "Erase Operation In Progress" },
1683 	{ 0x00, 0x19, "Locate Operation In Progress" },
1684 	{ 0x00, 0x1A, "Rewind Operation In Progress" },
1685 	{ 0x00, 0x1B, "Set Capacity Operation In Progress" },
1686 	{ 0x00, 0x1C, "Verify Operation In Progress" },
1687 	{ 0x01, 0x00, "No Index/Sector Signal" },
1688 	{ 0x02, 0x00, "No Seek Complete" },
1689 	{ 0x03, 0x00, "Peripheral Device Write Fault" },
1690 	{ 0x03, 0x01, "No Write Current" },
1691 	{ 0x03, 0x02, "Excessive Write Errors" },
1692 	{ 0x04, 0x00, "Logical Unit Not Ready, Cause Not Reportable" },
1693 	{ 0x04, 0x01, "Logical Unit Is in Process Of Becoming Ready" },
1694 	{ 0x04, 0x02, "Logical Unit Not Ready, Initialization Command Required" },
1695 	{ 0x04, 0x03, "Logical Unit Not Ready, Manual Intervention Required" },
1696 	{ 0x04, 0x04, "Logical Unit Not Ready, Format In Progress" },
1697 	{ 0x04, 0x05, "Logical Unit Not Ready, Rebuild In Progress" },
1698 	{ 0x04, 0x06, "Logical Unit Not Ready, Recalculation In Progress" },
1699 	{ 0x04, 0x07, "Logical Unit Not Ready, Operation In Progress" },
1700 	{ 0x04, 0x08, "Logical Unit Not Ready, Long Write In Progress" },
1701 	{ 0x04, 0x09, "Logical Unit Not Ready, Self-Test In Progress" },
1702 	{ 0x04, 0x0A, "Logical Unit Not Accessible, Asymmetric Access State Transition" },
1703 	{ 0x04, 0x0B, "Logical Unit Not Accessible, Target Port In Standby State" },
1704 	{ 0x04, 0x0C, "Logical Unit Not Accessible, Target Port In Unavailable State" },
1705 	{ 0x04, 0x0D, "Logical Unit Not Ready, Structure Check Required" },
1706 	{ 0x04, 0x10, "Logical Unit Not Ready, Auxiliary Memory Not Accessible" },
1707 	{ 0x04, 0x11, "Logical Unit Not Ready, Notify (Enable Spinup) Required" },
1708 	{ 0x04, 0x12, "Logical Unit Not Ready, Offline" },
1709 	{ 0x04, 0x13, "Logical Unit Not Ready, SA Creation In Progress" },
1710 	{ 0x04, 0x14, "Logical Unit Not Ready, Space Allocation In Progress" },
1711 	{ 0x04, 0x15, "Logical Unit Not Ready, Robotics Disabled" },
1712 	{ 0x04, 0x16, "Logical Unit Not Ready, Configuration Required" },
1713 	{ 0x04, 0x17, "Logical Unit Not Ready, Calibration Required" },
1714 	{ 0x04, 0x18, "Logical Unit Not Ready, A Door Is Open" },
1715 	{ 0x04, 0x19, "Logical Unit Not Ready, Operating In Sequential Mode" },
1716 	{ 0x04, 0x1A, "Logical Unit Not Ready, Start Stop Unit Command In Progress" },
1717 	{ 0x05, 0x00, "Logical Unit Does Not Respond To Selection" },
1718 	{ 0x06, 0x00, "No Reference Position Found" },
1719 	{ 0x07, 0x00, "Multiple Peripheral Devices Selected" },
1720 	{ 0x08, 0x00, "Logical Unit Communication Failure" },
1721 	{ 0x08, 0x01, "Logical Unit Communication Timeout" },
1722 	{ 0x08, 0x02, "Logical Unit Communication Parity Error" },
1723 	{ 0x08, 0x03, "Logical Unit Communication CRC Error (ULTRA-DMA/32)" },
1724 	{ 0x08, 0x04, "Unreachable Copy Target" },
1725 	{ 0x09, 0x00, "Track Following Error" },
1726 	{ 0x09, 0x01, "Tracking Servo Failure" },
1727 	{ 0x09, 0x02, "Focus Servo Failure" },
1728 	{ 0x09, 0x03, "Spindle Servo Failure" },
1729 	{ 0x09, 0x04, "Head Select Fault" },
1730 	{ 0x0A, 0x00, "Error Log Overflow" },
1731 	{ 0x0B, 0x00, "Warning" },
1732 	{ 0x0B, 0x01, "Warning - Specified Temperature Exceeded" },
1733 	{ 0x0B, 0x02, "Warning - Enclosure Degraded" },
1734 	{ 0x0B, 0x03, "Warning - Background Self-Test Failed" },
1735 	{ 0x0B, 0x04, "Warning - Background Pre-Scan Detected Medium Error" },
1736 	{ 0x0B, 0x05, "Warning - Background Medium Scan Detected Medium Error" },
1737 	{ 0x0B, 0x06, "Warning - Non-Volatile Cache Now Volatile" },
1738 	{ 0x0B, 0x07, "Warning - Degraded Power To Non-Volatile Cache" },
1739 	{ 0x0B, 0x08, "Warning - Power Loss Expected" },
1740 	{ 0x0C, 0x00, "Write Error" },
1741 	{ 0x0C, 0x01, "Write Error Recovered with Auto Reallocation" },
1742 	{ 0x0C, 0x02, "Write Error - Auto Reallocate Failed" },
1743 	{ 0x0C, 0x03, "Write Error - Recommend Reassignment" },
1744 	{ 0x0C, 0x04, "Compression Check Miscompare Error" },
1745 	{ 0x0C, 0x05, "Data Expansion Occurred During Compression" },
1746 	{ 0x0C, 0x06, "Block Not Compressible" },
1747 	{ 0x0C, 0x07, "Write Error - Recovery Needed" },
1748 	{ 0x0C, 0x08, "Write Error - Recovery Failed" },
1749 	{ 0x0C, 0x09, "Write Error - Loss Of Streaming" },
1750 	{ 0x0C, 0x0A, "Write Error - Padding Blocks Added" },
1751 	{ 0x0C, 0x0B, "Auxiliary Memory Write Error" },
1752 	{ 0x0C, 0x0C, "Write Error - Unexpected Unsolicited Data" },
1753 	{ 0x0C, 0x0D, "Write Error - Not Enough Unsolicited Data" },
1754 	{ 0x0C, 0x0F, "Defects In Error Window" },
1755 	{ 0x0D, 0x00, "Error Detected By Third Party Temporary Initiator" },
1756 	{ 0x0D, 0x01, "Third Party Device Failure" },
1757 	{ 0x0D, 0x02, "Copy Target Device Not Reachable" },
1758 	{ 0x0D, 0x03, "Incorrect Copy Target Device Type" },
1759 	{ 0x0D, 0x04, "Copy Target Device Data Underrun" },
1760 	{ 0x0D, 0x05, "Copy Target Device Data Overrun" },
1761 	{ 0x0E, 0x00, "Invalid Information Unit" },
1762 	{ 0x0E, 0x01, "Information Unit Too Short" },
1763 	{ 0x0E, 0x02, "Information Unit Too Long" },
1764 	{ 0x10, 0x00, "ID CRC Or ECC Error" },
1765 	{ 0x10, 0x01, "Logical Block Guard Check Failed" },
1766 	{ 0x10, 0x02, "Logical Block Application Tag Check Failed" },
1767 	{ 0x10, 0x03, "Logical Block Reference Tag Check Failed" },
1768 	{ 0x10, 0x04, "Logical Block Protection Error On Recover Buffered Data" },
1769 	{ 0x10, 0x05, "Logical Block Protection Method Error" },
1770 	{ 0x11, 0x00, "Unrecovered Read Error" },
1771 	{ 0x11, 0x01, "Read Retries Exhausted" },
1772 	{ 0x11, 0x02, "Error Too Long To Correct" },
1773 	{ 0x11, 0x03, "Multiple Read Errors" },
1774 	{ 0x11, 0x04, "Unrecovered Read Error - Auto Reallocate Failed" },
1775 	{ 0x11, 0x05, "L-EC Uncorrectable Error" },
1776 	{ 0x11, 0x06, "CIRC Unrecovered Error" },
1777 	{ 0x11, 0x07, "Data Resynchronization Error" },
1778 	{ 0x11, 0x08, "Incomplete Block Read" },
1779 	{ 0x11, 0x09, "No Gap Found" },
1780 	{ 0x11, 0x0A, "Miscorrected Error" },
1781 	{ 0x11, 0x0B, "Uncorrected Read Error - Recommend Reassignment" },
1782 	{ 0x11, 0x0C, "Uncorrected Read Error - Recommend Rewrite The Data" },
1783 	{ 0x11, 0x0D, "De-Compression CRC Error" },
1784 	{ 0x11, 0x0E, "Cannot Decompress Using Declared Algorithm" },
1785 	{ 0x11, 0x0F, "Error Reading UPC/EAN Number" },
1786 	{ 0x11, 0x10, "Error Reading ISRC Number" },
1787 	{ 0x11, 0x11, "Read Error - Loss Of Streaming" },
1788 	{ 0x11, 0x12, "Auxiliary Memory Read Error" },
1789 	{ 0x11, 0x13, "Read Error - Failed Retransmission Request" },
1790 	{ 0x11, 0x14, "Read Error - LBA Marked Bad By Application Client" },
1791 	{ 0x12, 0x00, "Address Mark Not Found for ID Field" },
1792 	{ 0x13, 0x00, "Address Mark Not Found for Data Field" },
1793 	{ 0x14, 0x00, "Recorded Entity Not Found" },
1794 	{ 0x14, 0x01, "Record Not Found" },
1795 	{ 0x14, 0x02, "Filemark or Setmark Not Found" },
1796 	{ 0x14, 0x03, "End-Of-Data Not Found" },
1797 	{ 0x14, 0x04, "Block Sequence Error" },
1798 	{ 0x14, 0x05, "Record Not Found - Recommend Reassignment" },
1799 	{ 0x14, 0x06, "Record Not Found - Data Auto-Reallocated" },
1800 	{ 0x14, 0x07, "Locate Operation Failure" },
1801 	{ 0x15, 0x00, "Random Positioning Error" },
1802 	{ 0x15, 0x01, "Mechanical Positioning Error" },
1803 	{ 0x15, 0x02, "Positioning Error Detected By Read of Medium" },
1804 	{ 0x16, 0x00, "Data Synchronization Mark Error" },
1805 	{ 0x16, 0x01, "Data Sync Error - Data Rewritten" },
1806 	{ 0x16, 0x02, "Data Sync Error - Recommend Rewrite" },
1807 	{ 0x16, 0x03, "Data Sync Error - Data Auto-Reallocated" },
1808 	{ 0x16, 0x04, "Data Sync Error - Recommend Reassignment" },
1809 	{ 0x17, 0x00, "Recovered Data With No Error Correction Applied" },
1810 	{ 0x17, 0x01, "Recovered Data With Retries" },
1811 	{ 0x17, 0x02, "Recovered Data With Positive Head Offset" },
1812 	{ 0x17, 0x03, "Recovered Data With Negative Head Offset" },
1813 	{ 0x17, 0x04, "Recovered Data With Retries and/or CIRC Applied" },
1814 	{ 0x17, 0x05, "Recovered Data Using Previous Sector ID" },
1815 	{ 0x17, 0x06, "Recovered Data Without ECC - Data Auto-Reallocated" },
1816 	{ 0x17, 0x07, "Recovered Data Without ECC - Recommend Reassignment" },
1817 	{ 0x17, 0x08, "Recovered Data Without ECC - Recommend Rewrite" },
1818 	{ 0x17, 0x09, "Recovered Data Without ECC - Data Rewritten" },
1819 	{ 0x18, 0x00, "Recovered Data With Error Correction Applied" },
1820 	{ 0x18, 0x01, "Recovered Data With Error Correction & Retries Applied" },
1821 	{ 0x18, 0x02, "Recovered Data - Data Auto-Reallocated" },
1822 	{ 0x18, 0x03, "Recovered Data With CIRC" },
1823 	{ 0x18, 0x04, "Recovered Data With L-EC" },
1824 	{ 0x18, 0x05, "Recovered Data - Recommend Reassignment" },
1825 	{ 0x18, 0x06, "Recovered Data - Recommend Rewrite" },
1826 	{ 0x18, 0x07, "Recovered Data With ECC - Data Rewritten" },
1827 	{ 0x18, 0x08, "Recovered Data With Linking" },
1828 	{ 0x19, 0x00, "Defect List Error" },
1829 	{ 0x19, 0x01, "Defect List Not Available" },
1830 	{ 0x19, 0x02, "Defect List Error in Primary List" },
1831 	{ 0x19, 0x03, "Defect List Error in Grown List" },
1832 	{ 0x1A, 0x00, "Parameter List Length Error" },
1833 	{ 0x1B, 0x00, "Synchronous Data Transfer Error" },
1834 	{ 0x1C, 0x00, "Defect List Not Found" },
1835 	{ 0x1C, 0x01, "Primary Defect List Not Found" },
1836 	{ 0x1C, 0x02, "Grown Defect List Not Found" },
1837 	{ 0x1D, 0x00, "Miscompare During Verify Operation" },
1838 	{ 0x1D, 0x01, "Miscompare Verify Of Unmapped Lba" },
1839 	{ 0x1E, 0x00, "Recovered ID with ECC" },
1840 	{ 0x1F, 0x00, "Partial Defect List Transfer" },
1841 	{ 0x20, 0x00, "Invalid Command Operation Code" },
1842 	{ 0x20, 0x01, "Access Denied - Initiator Pending-Enrolled" },
1843 	{ 0x20, 0x02, "Access Denied - No Access rights" },
1844 	{ 0x20, 0x03, "Access Denied - Invalid Mgmt ID Key" },
1845 	{ 0x20, 0x04, "Illegal Command While In Write Capable State" },
1846 	{ 0x20, 0x05, "Obsolete" },
1847 	{ 0x20, 0x06, "Illegal Command While In Explicit Address Mode" },
1848 	{ 0x20, 0x07, "Illegal Command While In Implicit Address Mode" },
1849 	{ 0x20, 0x08, "Access Denied - Enrollment Conflict" },
1850 	{ 0x20, 0x09, "Access Denied - Invalid LU Identifier" },
1851 	{ 0x20, 0x0A, "Access Denied - Invalid Proxy Token" },
1852 	{ 0x20, 0x0B, "Access Denied - ACL LUN Conflict" },
1853 	{ 0x20, 0x0C, "Illegal Command When Not In Append-Only Mode" },
1854 	{ 0x21, 0x00, "Logical Block Address Out of Range" },
1855 	{ 0x21, 0x01, "Invalid Element Address" },
1856 	{ 0x21, 0x02, "Invalid Address For Write" },
1857 	{ 0x21, 0x03, "Invalid Write Crossing Layer Jump" },
1858 	{ 0x22, 0x00, "Illegal Function (Should 20 00, 24 00, or 26 00)" },
1859 	{ 0x24, 0x00, "Illegal Field in CDB" },
1860 	{ 0x24, 0x01, "CDB Decryption Error" },
1861 	{ 0x24, 0x02, "Obsolete" },
1862 	{ 0x24, 0x03, "Obsolete" },
1863 	{ 0x24, 0x04, "Security Audit Value Frozen" },
1864 	{ 0x24, 0x05, "Security Working Key Frozen" },
1865 	{ 0x24, 0x06, "Nonce Not Unique" },
1866 	{ 0x24, 0x07, "Nonce Timestamp Out Of Range" },
1867 	{ 0x24, 0x08, "Invalid XCDB" },
1868 	{ 0x25, 0x00, "Logical Unit Not Supported" },
1869 	{ 0x26, 0x00, "Invalid Field In Parameter List" },
1870 	{ 0x26, 0x01, "Parameter Not Supported" },
1871 	{ 0x26, 0x02, "Parameter Value Invalid" },
1872 	{ 0x26, 0x03, "Threshold Parameters Not Supported" },
1873 	{ 0x26, 0x04, "Invalid Release Of Persistent Reservation" },
1874 	{ 0x26, 0x05, "Data Decryption Error" },
1875 	{ 0x26, 0x06, "Too Many Target Descriptors" },
1876 	{ 0x26, 0x07, "Unsupported Target Descriptor Type Code" },
1877 	{ 0x26, 0x08, "Too Many Segment Descriptors" },
1878 	{ 0x26, 0x09, "Unsupported Segment Descriptor Type Code" },
1879 	{ 0x26, 0x0A, "Unexpected Inexact Segment" },
1880 	{ 0x26, 0x0B, "Inline Data Length Exceeded" },
1881 	{ 0x26, 0x0C, "Invalid Operation For Copy Source Or Destination" },
1882 	{ 0x26, 0x0D, "Copy Segment Granularity Violation" },
1883 	{ 0x26, 0x0E, "Invalid Parameter While Port Is Enabled" },
1884 	{ 0x26, 0x0F, "Invalid Data-Out Buffer Integrity Check Value" },
1885 	{ 0x26, 0x10, "Data Decryption Key Fail Limit Reached" },
1886 	{ 0x26, 0x11, "Incomplete Key-Associated Data Set" },
1887 	{ 0x26, 0x12, "Vendor Specific Key Reference Not Found" },
1888 	{ 0x27, 0x00, "Write Protected" },
1889 	{ 0x27, 0x01, "Hardware Write Protected" },
1890 	{ 0x27, 0x02, "Logical Unit Software Write Protected" },
1891 	{ 0x27, 0x03, "Associated Write Protect" },
1892 	{ 0x27, 0x04, "Persistent Write Protect" },
1893 	{ 0x27, 0x05, "Permanent Write Protect" },
1894 	{ 0x27, 0x06, "Conditional Write Protect" },
1895 	{ 0x27, 0x07, "Space Allocation Failed Write Protect" },
1896 	{ 0x28, 0x00, "Not Ready To Ready Transition (Medium May Have Changed)" },
1897 	{ 0x28, 0x01, "Import Or Export Element Accessed" },
1898 	{ 0x28, 0x02, "Format-Layer May Have Changed" },
1899 	{ 0x28, 0x03, "Import/Export Element Accessed, Medium Changed" },
1900 	{ 0x29, 0x00, "Power On, Reset, or Bus Device Reset Occurred" },
1901 	{ 0x29, 0x01, "Power On Occurred" },
1902 	{ 0x29, 0x02, "SCSI Bus Reset Occurred" },
1903 	{ 0x29, 0x03, "Bus Device Reset Function Occurred" },
1904 	{ 0x29, 0x04, "Device Internal Reset" },
1905 	{ 0x29, 0x05, "Transceiver Mode Changed to Single Ended" },
1906 	{ 0x29, 0x06, "Transceiver Mode Changed to LVD" },
1907 	{ 0x29, 0x07, "I_T Nexus Loss Occurred" },
1908 	{ 0x2A, 0x00, "Parameters Changed" },
1909 	{ 0x2A, 0x01, "Mode Parameters Changed" },
1910 	{ 0x2A, 0x02, "Log Parameters Changed" },
1911 	{ 0x2A, 0x03, "Reservations Preempted" },
1912 	{ 0x2A, 0x04, "Reservations Released" },
1913 	{ 0x2A, 0x05, "Registrations Preempted" },
1914 	{ 0x2A, 0x06, "Asymmetric Access State Changed" },
1915 	{ 0x2A, 0x07, "Implicit Asymmetric Access State Transition Failed" },
1916 	{ 0x2A, 0x08, "Priority Changed" },
1917 	{ 0x2A, 0x09, "Capacity Data Has Changed" },
1918 	{ 0x2A, 0x0A, "Error History I_T Nexus Cleared" },
1919 	{ 0x2A, 0x0B, "Error History Snapshot Released" },
1920 	{ 0x2A, 0x0C, "Error Recovery Attributes Have Changed" },
1921 	{ 0x2A, 0x0D, "Data Encryption Capabilities Changed" },
1922 	{ 0x2A, 0x10, "Timestamp Changed" },
1923 	{ 0x2A, 0x11, "Data Encryption Parameters Changed By Another I_T Nexus" },
1924 	{ 0x2A, 0x12, "Data Encryption Parameters Changed By Vendor Specific Event" },
1925 	{ 0x2A, 0x13, "Data Encryption Key Instance Counter Has Changed" },
1926 	{ 0x2A, 0x14, "SA Creation Capabilities Data Has Changed" },
1927 	{ 0x2B, 0x00, "Copy Cannot Execute Since Host Cannot Disconnect" },
1928 	{ 0x2C, 0x00, "Command Sequence Error" },
1929 	{ 0x2C, 0x01, "Too Many Windows Specified" },
1930 	{ 0x2C, 0x02, "Invalid Combination of Windows Specified" },
1931 	{ 0x2C, 0x03, "Current Program Area Is Not Empty" },
1932 	{ 0x2C, 0x04, "Current Program Area Is Empty" },
1933 	{ 0x2C, 0x05, "Illegal Power Condition Request" },
1934 	{ 0x2C, 0x06, "Persistent Prevent Conflict" },
1935 	{ 0x2C, 0x07, "Previous Busy Status" },
1936 	{ 0x2C, 0x08, "Previous Task Set Full Status" },
1937 	{ 0x2C, 0x09, "Previous Reservation Conflict Status" },
1938 	{ 0x2C, 0x0A, "Partition Or Collection Contains User Objects" },
1939 	{ 0x2C, 0x0B, "Not Reserved" },
1940 	{ 0x2C, 0x0C, "ORWrite Generation Does Not Match" },
1941 	{ 0x2D, 0x00, "Overwrite Error On Update In Place" },
1942 	{ 0x2E, 0x00, "Insufficient Time For Operation" },
1943 	{ 0x2F, 0x00, "Commands Cleared By Another Initiator" },
1944 	{ 0x2F, 0x01, "Commands Cleared By Power Loss Notification" },
1945 	{ 0x2F, 0x02, "Commands Cleared By Device Server" },
1946 	{ 0x30, 0x00, "Incompatible Medium Installed" },
1947 	{ 0x30, 0x01, "Cannot Read Medium - Unknown Format" },
1948 	{ 0x30, 0x02, "Cannot Read Medium - Incompatible Format" },
1949 	{ 0x30, 0x03, "Cleaning Cartridge Installed" },
1950 	{ 0x30, 0x04, "Cannot Write Medium - Unknown Format" },
1951 	{ 0x30, 0x05, "Cannot Write Medium - Incompatible Format" },
1952 	{ 0x30, 0x06, "Cannot Format Medium - Incompatible Medium" },
1953 	{ 0x30, 0x07, "Cleaning Failure" },
1954 	{ 0x30, 0x08, "Cannot Write - Application Code Mismatch" },
1955 	{ 0x30, 0x09, "Current Session Not Fixated For Append" },
1956 	{ 0x30, 0x0A, "Cleaning Request Rejected" },
1957 	{ 0x30, 0x10, "Medium Not Formatted" },
1958 	{ 0x30, 0x11, "Incompatible Volume Type" },
1959 	{ 0x30, 0x12, "Incompatible Volume Qualifier" },
1960 	{ 0x30, 0x13, "Cleaning Volume Expired" },
1961 	{ 0x31, 0x00, "Medium Format Corrupted" },
1962 	{ 0x31, 0x01, "Format Command Failed" },
1963 	{ 0x31, 0x02, "Zoned Formatting Failed Due To Spare Linking" },
1964 	{ 0x32, 0x00, "No Defect Spare Location Available" },
1965 	{ 0x32, 0x01, "Defect List Update Failure" },
1966 	{ 0x33, 0x00, "Tape Length Error" },
1967 	{ 0x34, 0x00, "Enclosure Failure" },
1968 	{ 0x35, 0x00, "Enclosure Services Failure" },
1969 	{ 0x35, 0x01, "Unsupported Enclosure Function" },
1970 	{ 0x35, 0x02, "Enclosure Services Unavailable" },
1971 	{ 0x35, 0x03, "Enclosure Services Transfer Failure" },
1972 	{ 0x35, 0x04, "Enclosure Services Transfer Refused" },
1973 	{ 0x36, 0x00, "Ribbon, Ink, or Toner Failure" },
1974 	{ 0x37, 0x00, "Rounded Parameter" },
1975 	{ 0x38, 0x00, "Event Status Notification" },
1976 	{ 0x38, 0x02, "ESN - Power Management Class Event" },
1977 	{ 0x38, 0x04, "ESN - Media Class Event" },
1978 	{ 0x38, 0x06, "ESN - Device Busy Class Event" },
1979 	{ 0x39, 0x00, "Saving Parameters Not Supported" },
1980 	{ 0x3A, 0x00, "Medium Not Present" },
1981 	{ 0x3A, 0x01, "Medium Not Present - Tray Closed" },
1982 	{ 0x3A, 0x02, "Medium Not Present - Tray Open" },
1983 	{ 0x3A, 0x03, "Medium Not Present - Loadable" },
1984 	{ 0x3A, 0x04, "Medium Not Present - Medium Auxiliary Memory Accessible" },
1985 	{ 0x3B, 0x00, "Sequential Positioning Error" },
1986 	{ 0x3B, 0x01, "Tape Position Error At Beginning-of-Medium" },
1987 	{ 0x3B, 0x02, "Tape Position Error At End-of-Medium" },
1988 	{ 0x3B, 0x03, "Tape or Electronic Vertical Forms Unit Not Ready" },
1989 	{ 0x3B, 0x04, "Slew Failure" },
1990 	{ 0x3B, 0x05, "Paper Jam" },
1991 	{ 0x3B, 0x06, "Failed To Sense Top-Of-Form" },
1992 	{ 0x3B, 0x07, "Failed To Sense Bottom-Of-Form" },
1993 	{ 0x3B, 0x08, "Reposition Error" },
1994 	{ 0x3B, 0x09, "Read Past End Of Medium" },
1995 	{ 0x3B, 0x0A, "Read Past Beginning Of Medium" },
1996 	{ 0x3B, 0x0B, "Position Past End Of Medium" },
1997 	{ 0x3B, 0x0C, "Position Past Beginning Of Medium" },
1998 	{ 0x3B, 0x0D, "Medium Destination Element Full" },
1999 	{ 0x3B, 0x0E, "Medium Source Element Empty" },
2000 	{ 0x3B, 0x0F, "End Of Medium Reached" },
2001 	{ 0x3B, 0x11, "Medium Magazine Not Accessible" },
2002 	{ 0x3B, 0x12, "Medium Magazine Removed" },
2003 	{ 0x3B, 0x13, "Medium Magazine Inserted" },
2004 	{ 0x3B, 0x14, "Medium Magazine Locked" },
2005 	{ 0x3B, 0x15, "Medium Magazine Unlocked" },
2006 	{ 0x3B, 0x16, "Mechanical Positioning Or Changer Error" },
2007 	{ 0x3B, 0x17, "Read Past End Of User Object" },
2008 	{ 0x3B, 0x18, "Element Disabled" },
2009 	{ 0x3B, 0x19, "Element Enabled" },
2010 	{ 0x3B, 0x1A, "Data Transfer Device Removed" },
2011 	{ 0x3B, 0x1B, "Data Transfer Device Inserted" },
2012 	{ 0x3D, 0x00, "Invalid Bits In IDENTIFY Message" },
2013 	{ 0x3E, 0x00, "Logical Unit Has Not Self-Configured Yet" },
2014 	{ 0x3E, 0x01, "Logical Unit Failure" },
2015 	{ 0x3E, 0x02, "Timeout On Logical Unit" },
2016 	{ 0x3E, 0x03, "Logical Unit Failed Self-Test" },
2017 	{ 0x3E, 0x04, "Logical Unit Unable To Update Self-Test Log" },
2018 	{ 0x3F, 0x00, "Target Operating Conditions Have Changed" },
2019 	{ 0x3F, 0x01, "Microcode Has Changed" },
2020 	{ 0x3F, 0x02, "Changed Operating Definition" },
2021 	{ 0x3F, 0x03, "INQUIRY Data Has Changed" },
2022 	{ 0x3F, 0x04, "component Device Attached" },
2023 	{ 0x3F, 0x05, "Device Identifier Changed" },
2024 	{ 0x3F, 0x06, "Redundancy Group Created Or Modified" },
2025 	{ 0x3F, 0x07, "Redundancy Group Deleted" },
2026 	{ 0x3F, 0x08, "Spare Created Or Modified" },
2027 	{ 0x3F, 0x09, "Spare Deleted" },
2028 	{ 0x3F, 0x0A, "Volume Set Created Or Modified" },
2029 	{ 0x3F, 0x0B, "Volume Set Deleted" },
2030 	{ 0x3F, 0x0C, "Volume Set Deassigned" },
2031 	{ 0x3F, 0x0D, "Volume Set Reassigned" },
2032 	{ 0x3F, 0x0E, "Reported LUNs Data Has Changed" },
2033 	{ 0x3F, 0x0F, "Echo Buffer Overwritten" },
2034 	{ 0x3F, 0x10, "Medium Loadable" },
2035 	{ 0x3F, 0x11, "Medium Auxiliary Memory Accessible" },
2036 	{ 0x3F, 0x12, "iSCSI IP Address Added" },
2037 	{ 0x3F, 0x13, "iSCSI IP Address Removed" },
2038 	{ 0x3F, 0x14, "iSCSI IP Address Changed" },
2039 	{ 0x40, 0x00, "RAM FAILURE (Should Use 40 NN)" },
2040 	/*
2041 	 * ASC 0x40 also has an ASCQ range from 0x80 to 0xFF.
2042 	 * 0x40 0xNN DIAGNOSTIC FAILURE ON COMPONENT NN
2043 	 */
2044 	{ 0x41, 0x00, "Data Path FAILURE (Should Use 40 NN)" },
2045 	{ 0x42, 0x00, "Power-On or Self-Test FAILURE (Should Use 40 NN)" },
2046 	{ 0x43, 0x00, "Message Error" },
2047 	{ 0x44, 0x00, "Internal Target Failure" },
2048 	{ 0x44, 0x71, "ATA Device Failed Set Features" },
2049 	{ 0x45, 0x00, "Select Or Reselect Failure" },
2050 	{ 0x46, 0x00, "Unsuccessful Soft Reset" },
2051 	{ 0x47, 0x00, "SCSI Parity Error" },
2052 	{ 0x47, 0x01, "Data Phase CRC Error Detected" },
2053 	{ 0x47, 0x02, "SCSI Parity Error Detected During ST Data Phase" },
2054 	{ 0x47, 0x03, "Information Unit iuCRC Error Detected" },
2055 	{ 0x47, 0x04, "Asynchronous Information Protection Error Detected" },
2056 	{ 0x47, 0x05, "Protocol Service CRC Error" },
2057 	{ 0x47, 0x06, "PHY Test Function In Progress" },
2058 	{ 0x47, 0x7F, "Some Commands Cleared By iSCSI Protocol Event" },
2059 	{ 0x48, 0x00, "Initiator Detected Error Message Received" },
2060 	{ 0x49, 0x00, "Invalid Message Error" },
2061 	{ 0x4A, 0x00, "Command Phase Error" },
2062 	{ 0x4B, 0x00, "Data Phase Error" },
2063 	{ 0x4B, 0x01, "Invalid Target Port Transfer Tag Received" },
2064 	{ 0x4B, 0x02, "Too Much Write Data" },
2065 	{ 0x4B, 0x03, "ACK/NAK Timeout" },
2066 	{ 0x4B, 0x04, "NAK Received" },
2067 	{ 0x4B, 0x05, "Data Offset Error" },
2068 	{ 0x4B, 0x06, "Initiator Response Timeout" },
2069 	{ 0x4B, 0x07, "Connection Lost" },
2070 	{ 0x4C, 0x00, "Logical Unit Failed Self-Configuration" },
2071 	/*
2072 	 * ASC 0x4D has an ASCQ range from 0x00 to 0xFF.
2073 	 * 0x4D 0xNN TAGGED OVERLAPPED COMMANDS (NN = TASK TAG)
2074 	 */
2075 	{ 0x4E, 0x00, "Overlapped Commands Attempted" },
2076 	{ 0x50, 0x00, "Write Append Error" },
2077 	{ 0x50, 0x01, "Write Append Position Error" },
2078 	{ 0x50, 0x02, "Position Error Related To Timing" },
2079 	{ 0x51, 0x00, "Erase Failure" },
2080 	{ 0x51, 0x01, "Erase Failure - Incomplete Erase Operation Detected" },
2081 	{ 0x52, 0x00, "Cartridge Fault" },
2082 	{ 0x53, 0x00, "Media Load or Eject Failed" },
2083 	{ 0x53, 0x01, "Unload Tape Failure" },
2084 	{ 0x53, 0x02, "Medium Removal Prevented" },
2085 	{ 0x53, 0x03, "Medium Removal Prevented By Data Transfer Element" },
2086 	{ 0x53, 0x04, "Medium Thread Or Unthread Failure" },
2087 	{ 0x53, 0x05, "Volume Identifier Invalid" },
2088 	{ 0x53, 0x06, "Volume Identifier Missing" },
2089 	{ 0x53, 0x07, "Duplicate Volume Identifier" },
2090 	{ 0x53, 0x08, "Element Status Unknown" },
2091 	{ 0x54, 0x00, "SCSI To Host System Interface Failure" },
2092 	{ 0x55, 0x00, "System Resource Failure" },
2093 	{ 0x55, 0x01, "System Buffer Full" },
2094 	{ 0x55, 0x02, "Insufficient Reservation Resources" },
2095 	{ 0x55, 0x03, "Insufficient Resources" },
2096 	{ 0x55, 0x04, "Insufficient Registration Resources" },
2097 	{ 0x55, 0x05, "Insufficient Access Control Resources" },
2098 	{ 0x55, 0x06, "Auxiliary Memory Out Of Space" },
2099 	{ 0x55, 0x07, "Quota Error" },
2100 	{ 0x55, 0x08, "Maximum Number Of Supplemental Decryption Keys Exceeded" },
2101 	{ 0x55, 0x09, "Medium Auxiliary Memory Not Accessible" },
2102 	{ 0x55, 0x0A, "Data Currently Unavailable" },
2103 	{ 0x55, 0x0B, "Insufficient Power For Operation" },
2104 	{ 0x57, 0x00, "Unable To Recover Table-Of-Contents" },
2105 	{ 0x58, 0x00, "Generation Does Not Exist" },
2106 	{ 0x59, 0x00, "Updated Block Read" },
2107 	{ 0x5A, 0x00, "Operator Request or State Change Input" },
2108 	{ 0x5A, 0x01, "Operator Medium Removal Requested" },
2109 	{ 0x5A, 0x02, "Operator Selected Write Protect" },
2110 	{ 0x5A, 0x03, "Operator Selected Write Permit" },
2111 	{ 0x5B, 0x00, "Log Exception" },
2112 	{ 0x5B, 0x01, "Threshold Condition Met" },
2113 	{ 0x5B, 0x02, "Log Counter At Maximum" },
2114 	{ 0x5B, 0x03, "Log List Codes Exhausted" },
2115 	{ 0x5C, 0x00, "RPL Status Change" },
2116 	{ 0x5C, 0x01, "Spindles Synchronized" },
2117 	{ 0x5C, 0x02, "Spindles Not Synchronized" },
2118 	{ 0x5D, 0x00, "Failure Prediction Threshold Exceeded" },
2119 	{ 0x5D, 0x01, "Media Failure Prediction Threshold Exceeded" },
2120 	{ 0x5D, 0x02, "Logical Unit Failure Prediction Threshold Exceeded" },
2121 	{ 0x5D, 0x03, "Spare Area Exhaustion Prediction Threshold Exceeded" },
2122 	{ 0x5D, 0x10, "Hardware Impending Failure General Hard Drive Failure" },
2123 	{ 0x5D, 0x11, "Hardware Impending Failure Drive Error Rate Too High" },
2124 	{ 0x5D, 0x12, "Hardware Impending Failure Data Error Rate Too High" },
2125 	{ 0x5D, 0x13, "Hardware Impending Failure Seek Error Rate Too High" },
2126 	{ 0x5D, 0x14, "Hardware Impending Failure Too Many Block Reassigns" },
2127 	{ 0x5D, 0x15, "Hardware Impending Failure Access Times Too High" },
2128 	{ 0x5D, 0x16, "Hardware Impending Failure Start Unit Times Too High" },
2129 	{ 0x5D, 0x17, "Hardware Impending Failure Channel Parametrics" },
2130 	{ 0x5D, 0x18, "Hardware Impending Failure Controller Detected" },
2131 	{ 0x5D, 0x19, "Hardware Impending Failure Throughput Performance" },
2132 	{ 0x5D, 0x1A, "Hardware Impending Failure Seek Time Performance" },
2133 	{ 0x5D, 0x1B, "Hardware Impending Failure Spin-Up Retry Count" },
2134 	{ 0x5D, 0x1C, "Hardware Impending Failure Drive Calibration Retry Count" },
2135 	{ 0x5D, 0x20, "Controller Impending Failure General Hard Drive Failure" },
2136 	{ 0x5D, 0x21, "Controller Impending Failure Drive Error Rate Too High" },
2137 	{ 0x5D, 0x22, "Controller Impending Failure Data Error Rate Too High" },
2138 	{ 0x5D, 0x23, "Controller Impending Failure Seek Error Rate Too High" },
2139 	{ 0x5D, 0x24, "Controller Impending Failure Too Many Block Reassigns" },
2140 	{ 0x5D, 0x25, "Controller Impending Failure Access Times Too High" },
2141 	{ 0x5D, 0x26, "Controller Impending Failure Start Unit Times Too High" },
2142 	{ 0x5D, 0x27, "Controller Impending Failure Channel Parametrics" },
2143 	{ 0x5D, 0x28, "Controller Impending Failure Controller Detected" },
2144 	{ 0x5D, 0x29, "Controller Impending Failure Throughput Performance" },
2145 	{ 0x5D, 0x2A, "Controller Impending Failure Seek Time Performance" },
2146 	{ 0x5D, 0x2B, "Controller Impending Failure Spin-Up Retry Count" },
2147 	{ 0x5D, 0x2C, "Controller Impending Failure Drive Calibration Retry Count" },
2148 	{ 0x5D, 0x30, "Data Channel Impending Failure General Hard Drive Failure" },
2149 	{ 0x5D, 0x31, "Data Channel Impending Failure Drive Error Rate Too High" },
2150 	{ 0x5D, 0x32, "Data Channel Impending Failure Data Error Rate Too High" },
2151 	{ 0x5D, 0x33, "Data Channel Impending Failure Seek Error Rate Too High" },
2152 	{ 0x5D, 0x34, "Data Channel Impending Failure Too Many Block Reassigns" },
2153 	{ 0x5D, 0x35, "Data Channel Impending Failure Access Times Too High" },
2154 	{ 0x5D, 0x36, "Data Channel Impending Failure Start Unit Times Too High" },
2155 	{ 0x5D, 0x37, "Data Channel Impending Failure Channel Parametrics" },
2156 	{ 0x5D, 0x38, "Data Channel Impending Failure Controller Detected" },
2157 	{ 0x5D, 0x39, "Data Channel Impending Failure Throughput Performance" },
2158 	{ 0x5D, 0x3A, "Data Channel Impending Failure Seek Time Performance" },
2159 	{ 0x5D, 0x3B, "Data Channel Impending Failure Spin-Up Retry Count" },
2160 	{ 0x5D, 0x3C, "Data Channel Impending Failure Drive Calibration Retry Count" },
2161 	{ 0x5D, 0x40, "Servo Impending Failure General Hard Drive Failure" },
2162 	{ 0x5D, 0x41, "Servo Impending Failure Drive Error Rate Too High" },
2163 	{ 0x5D, 0x42, "Servo Impending Failure Data Error Rate Too High" },
2164 	{ 0x5D, 0x43, "Servo Impending Failure Seek Error Rate Too High" },
2165 	{ 0x5D, 0x44, "Servo Impending Failure Too Many Block Reassigns" },
2166 	{ 0x5D, 0x45, "Servo Impending Failure Access Times Too High" },
2167 	{ 0x5D, 0x46, "Servo Impending Failure Start Unit Times Too High" },
2168 	{ 0x5D, 0x47, "Servo Impending Failure Channel Parametrics" },
2169 	{ 0x5D, 0x48, "Servo Impending Failure Controller Detected" },
2170 	{ 0x5D, 0x49, "Servo Impending Failure Throughput Performance" },
2171 	{ 0x5D, 0x4A, "Servo Impending Failure Seek Time Performance" },
2172 	{ 0x5D, 0x4B, "Servo Impending Failure Spin-Up Retry Count" },
2173 	{ 0x5D, 0x4C, "Servo Impending Failure Drive Calibration Retry Count" },
2174 	{ 0x5D, 0x50, "Spindle Impending Failure General Hard Drive Failure" },
2175 	{ 0x5D, 0x51, "Spindle Impending Failure Drive Error Rate Too High" },
2176 	{ 0x5D, 0x52, "Spindle Impending Failure Data Error Rate Too High" },
2177 	{ 0x5D, 0x53, "Spindle Impending Failure Seek Error Rate Too High" },
2178 	{ 0x5D, 0x54, "Spindle Impending Failure Too Many Block Reassigns" },
2179 	{ 0x5D, 0x55, "Spindle Impending Failure Access Times Too High" },
2180 	{ 0x5D, 0x56, "Spindle Impending Failure Start Unit Times Too High" },
2181 	{ 0x5D, 0x57, "Spindle Impending Failure Channel Parametrics" },
2182 	{ 0x5D, 0x58, "Spindle Impending Failure Controller Detected" },
2183 	{ 0x5D, 0x59, "Spindle Impending Failure Throughput Performance" },
2184 	{ 0x5D, 0x5A, "Spindle Impending Failure Seek Time Performance" },
2185 	{ 0x5D, 0x5B, "Spindle Impending Failure Spin-Up Retry Count" },
2186 	{ 0x5D, 0x5C, "Spindle Impending Failure Drive Calibration Retry Count" },
2187 	{ 0x5D, 0x60, "Firmware Impending Failure General Hard Drive Failure" },
2188 	{ 0x5D, 0x61, "Firmware Impending Failure Drive Error Rate Too High" },
2189 	{ 0x5D, 0x62, "Firmware Impending Failure Data Error Rate Too High" },
2190 	{ 0x5D, 0x63, "Firmware Impending Failure Seek Error Rate Too High" },
2191 	{ 0x5D, 0x64, "Firmware Impending Failure Too Many Block Reassigns" },
2192 	{ 0x5D, 0x65, "Firmware Impending Failure Access Times Too High" },
2193 	{ 0x5D, 0x66, "Firmware Impending Failure Start Unit Times Too High" },
2194 	{ 0x5D, 0x67, "Firmware Impending Failure Channel Parametrics" },
2195 	{ 0x5D, 0x68, "Firmware Impending Failure Controller Detected" },
2196 	{ 0x5D, 0x69, "Firmware Impending Failure Throughput Performance" },
2197 	{ 0x5D, 0x6A, "Firmware Impending Failure Seek Time Performance" },
2198 	{ 0x5D, 0x6B, "Firmware Impending Failure Spin-Up Retry Count" },
2199 	{ 0x5D, 0x6C, "Firmware Impending Failure Drive Calibration Retry Count" },
2200 	{ 0x5D, 0xFF, "Failure Prediction Threshold Exceeded (false)" },
2201 	{ 0x5E, 0x00, "Low Power Condition On" },
2202 	{ 0x5E, 0x01, "Idle Condition Activated By Timer" },
2203 	{ 0x5E, 0x02, "Standby Condition Activated By Timer" },
2204 	{ 0x5E, 0x03, "Idle Condition Activated By Command" },
2205 	{ 0x5E, 0x04, "Standby Condition Activated By Command" },
2206 	{ 0x5E, 0x05, "IDLE_B Condition Activated By Timer" },
2207 	{ 0x5E, 0x06, "IDLE_B Condition Activated By Command" },
2208 	{ 0x5E, 0x07, "IDLE_C Condition Activated By Timer" },
2209 	{ 0x5E, 0x08, "IDLE_C Condition Activated By Command" },
2210 	{ 0x5E, 0x09, "STANDBY_Y Condition Activated By Timer" },
2211 	{ 0x5E, 0x0A, "STANDBY_Y Condition Activated By Command" },
2212 	{ 0x5E, 0x41, "Power State Change To Active" },
2213 	{ 0x5E, 0x42, "Power State Change To Idle" },
2214 	{ 0x5E, 0x43, "Power State Change To Standby" },
2215 	{ 0x5E, 0x45, "Power State Change To Sleep" },
2216 	{ 0x5E, 0x47, "Power State Change To Device Control" },
2217 	{ 0x60, 0x00, "Lamp Failure" },
2218 	{ 0x61, 0x00, "Video Acquisition Error" },
2219 	{ 0x61, 0x01, "Unable To Acquire Video" },
2220 	{ 0x61, 0x02, "Out Of Focus" },
2221 	{ 0x62, 0x00, "Scan Head Positioning Error" },
2222 	{ 0x63, 0x00, "End Of User Area Encountered On This Track" },
2223 	{ 0x63, 0x01, "Packet Does Not Fit In Available Space" },
2224 	{ 0x64, 0x00, "Illegal Mode For This Track" },
2225 	{ 0x64, 0x01, "Invalid Packet Size" },
2226 	{ 0x65, 0x00, "Voltage Fault" },
2227 	{ 0x66, 0x00, "Automatic Document Feeder Cover Up" },
2228 	{ 0x66, 0x01, "Automatic Document Feeder Lift Up" },
2229 	{ 0x66, 0x02, "Document Jam In Automatic Document Feeder" },
2230 	{ 0x66, 0x03, "Document Miss Feed Automatic In Document Feeder" },
2231 	{ 0x67, 0x00, "Configuration Failure" },
2232 	{ 0x67, 0x01, "Configuration Of Incapable Logical Units Failed" },
2233 	{ 0x67, 0x02, "Add Logical Unit Failed" },
2234 	{ 0x67, 0x03, "Modification Of Logical Unit Failed" },
2235 	{ 0x67, 0x04, "Exchange Of Logical Unit Failed" },
2236 	{ 0x67, 0x05, "Remove Of Logical Unit Failed" },
2237 	{ 0x67, 0x06, "Attachment Of Logical Unit Failed" },
2238 	{ 0x67, 0x07, "Creation Of Logical Unit Failed" },
2239 	{ 0x67, 0x08, "Assign Failure Occurred" },
2240 	{ 0x67, 0x09, "Multiply Assigned Logical Unit" },
2241 	{ 0x67, 0x0A, "Set Target Port Groups Command Failed" },
2242 	{ 0x67, 0x0B, "ATA Device Feature Not Enabled" },
2243 	{ 0x68, 0x00, "Logical Unit Not Configured" },
2244 	{ 0x69, 0x00, "Data Loss On Logical Unit" },
2245 	{ 0x69, 0x01, "Multiple Logical Unit Failures" },
2246 	{ 0x69, 0x02, "Parity/Data Mismatch" },
2247 	{ 0x6A, 0x00, "Informational, Refer To Log" },
2248 	{ 0x6B, 0x00, "State Change Has Occurred" },
2249 	{ 0x6B, 0x01, "Redundancy Level Got Better" },
2250 	{ 0x6B, 0x02, "Redundancy Level Got Worse" },
2251 	{ 0x6C, 0x00, "Rebuild Failure Occurred" },
2252 	{ 0x6D, 0x00, "Recalculate Failure Occurred" },
2253 	{ 0x6E, 0x00, "Command To Logical Unit Failed" },
2254 	{ 0x6F, 0x00, "Copy Protection Key Exchange Failure - Authentication Failure" },
2255 	{ 0x6F, 0x01, "Copy Protection Key Exchange Failure - Key Not Present" },
2256 	{ 0x6F, 0x02, "Copy Protection Key Exchange Failure - Key Not Established" },
2257 	{ 0x6F, 0x03, "Read Of Scrambled Sector Without Authentication" },
2258 	{ 0x6F, 0x04, "Media Region Code Is Mismatched To Logical Unit Region" },
2259 	{ 0x6F, 0x05, "Drive Region Must Be Permanent/Region Reset Count Error" },
2260 	/*
2261 	 * ASC 0x70 has an ASCQ range from 0x00 to 0xFF.
2262 	 * 0x70 0xNN DECOMPRESSION EXCEPTION SHORT ALGORITHM ID Of NN
2263 	 */
2264 	{ 0x71, 0x00, "Decompression Exception Long Algorithm ID" },
2265 	{ 0x72, 0x00, "Session Fixation Error" },
2266 	{ 0x72, 0x01, "Session Fixation Error Writing Lead-In" },
2267 	{ 0x72, 0x02, "Session Fixation Error Writing Lead-Out" },
2268 	{ 0x72, 0x03, "Session Fixation Error - Incomplete Track In Session" },
2269 	{ 0x72, 0x04, "Empty Or Partially Written Reserved Track" },
2270 	{ 0x72, 0x05, "No More Track Reservations Allowed" },
2271 	{ 0x72, 0x06, "RMZ Extension Is Not Allowed" },
2272 	{ 0x72, 0x07, "No More Test Zone Extensions Are Allowed" },
2273 	{ 0x73, 0x00, "CD Control Error" },
2274 	{ 0x73, 0x01, "Power Calibration Area Almost Full" },
2275 	{ 0x73, 0x02, "Power Calibration Area Is Full" },
2276 	{ 0x73, 0x03, "Power Calibration Area Error" },
2277 	{ 0x73, 0x04, "Program Memory Area Update Failure" },
2278 	{ 0x73, 0x05, "Program Memory Area Is Full" },
2279 	{ 0x73, 0x06, "RMA/PMA Is Almost Full" },
2280 	{ 0x73, 0x10, "Current Power Calibration Area Almost Full" },
2281 	{ 0x73, 0x11, "Current Power Calibration Area Is Full" },
2282 	{ 0x73, 0x17, "RDZ Is Full" },
2283 	{ 0x74, 0x00, "Security Error" },
2284 	{ 0x74, 0x01, "Unable To Decrypt Data" },
2285 	{ 0x74, 0x02, "Unencrypted Data Encountered While Decrypting" },
2286 	{ 0x74, 0x03, "Incorrect Data Encryption Key" },
2287 	{ 0x74, 0x04, "Cryptographic Integrity Validation Failed" },
2288 	{ 0x74, 0x05, "Error Decrypting Data" },
2289 	{ 0x74, 0x06, "Unknown Signature Verification Key" },
2290 	{ 0x74, 0x07, "Encryption Parameters Not Useable" },
2291 	{ 0x74, 0x08, "Digital Signature Validation Failure" },
2292 	{ 0x74, 0x09, "Encryption Mode Mismatch On Read" },
2293 	{ 0x74, 0x0A, "Encrypted Block Not Raw Read Enabled" },
2294 	{ 0x74, 0x0B, "Incorrect Encryption Parameters" },
2295 	{ 0x74, 0x0C, "Unable To Decrypt Parameter List" },
2296 	{ 0x74, 0x0D, "Encryption Algorithm Disabled" },
2297 	{ 0x74, 0x10, "SA Creation Parameter Value Invalid" },
2298 	{ 0x74, 0x11, "SA Creation Parameter Value Rejected" },
2299 	{ 0x74, 0x12, "Invalid SA Usage" },
2300 	{ 0x74, 0x21, "Data Encryption Configuration Prevented" },
2301 	{ 0x74, 0x30, "SA Creation Parameter Not Supported" },
2302 	{ 0x74, 0x40, "Authentication Failed" },
2303 	{ 0x74, 0x61, "External Data Encryption Key Manager Access Error" },
2304 	{ 0x74, 0x62, "External Data Encryption Key Manager Error" },
2305 	{ 0x74, 0x63, "External Data Encryption Key Not Found" },
2306 	{ 0x74, 0x64, "External Data Encryption Request Not Authorized" },
2307 	{ 0x74, 0x6E, "External Data Encryption Control Timeout" },
2308 	{ 0x74, 0x6F, "External Data Encryption Control Error" },
2309 	{ 0x74, 0x71, "Logical Unit Access Not Authorized" },
2310 	{ 0x74, 0x79, "Security Conflict In Translated Device" },
2311 	{ 0x00, 0x00, NULL }
2312 };
2313 
2314 static __inline void
2315 asc2ascii(u_int8_t asc, u_int8_t ascq, char *result, size_t len)
2316 {
2317 	int					i;
2318 
2319 	/* Check for a dynamically built description. */
2320 	switch (asc) {
2321 	case 0x40:
2322 		if (ascq >= 0x80) {
2323 			snprintf(result, len,
2324 		            "Diagnostic Failure on Component 0x%02x", ascq);
2325 			return;
2326 		}
2327 		break;
2328 	case 0x4d:
2329 		snprintf(result, len,
2330 		    "Tagged Overlapped Commands (0x%02x = TASK TAG)", ascq);
2331 		return;
2332 	case 0x70:
2333 		snprintf(result, len,
2334 		    "Decompression Exception Short Algorithm ID OF 0x%02x",
2335 		    ascq);
2336 		return;
2337 	default:
2338 		break;
2339 	}
2340 
2341 	/* Check for a fixed description. */
2342 	for (i = 0; adesc[i].description != NULL; i++) {
2343 		if (adesc[i].asc == asc && adesc[i].ascq == ascq) {
2344 			strlcpy(result, adesc[i].description, len);
2345 			return;
2346 		}
2347 	}
2348 
2349 	/* Just print out the ASC and ASCQ values as a description. */
2350 	snprintf(result, len, "ASC 0x%02x ASCQ 0x%02x", asc, ascq);
2351 }
2352 #endif /* SCSITERSE */
2353 
2354 void
2355 scsi_print_sense(struct scsi_xfer *xs)
2356 {
2357 	struct scsi_sense_data			*sense = &xs->sense;
2358 	u_int8_t				serr = sense->error_code &
2359 						    SSD_ERRCODE;
2360 	int32_t					info;
2361 	char					*sbs;
2362 
2363 	sc_print_addr(xs->sc_link);
2364 
2365 	/* XXX For error 0x71, current opcode is not the relevant one. */
2366 	printf("%sCheck Condition (error %#x) on opcode 0x%x\n",
2367 	    (serr == SSD_ERRCODE_DEFERRED) ? "DEFERRED " : "", serr,
2368 	    xs->cmd->opcode);
2369 
2370 	if (serr != SSD_ERRCODE_CURRENT && serr != SSD_ERRCODE_DEFERRED) {
2371 		if ((sense->error_code & SSD_ERRCODE_VALID) != 0) {
2372 			struct scsi_sense_data_unextended *usense =
2373 			    (struct scsi_sense_data_unextended *)sense;
2374 			printf("   AT BLOCK #: %d (decimal)",
2375 			    _3btol(usense->block));
2376 		}
2377 		return;
2378 	}
2379 
2380 	printf("    SENSE KEY: %s\n", scsi_decode_sense(sense,
2381 	    DECODE_SENSE_KEY));
2382 
2383 	if (sense->flags & (SSD_FILEMARK | SSD_EOM | SSD_ILI)) {
2384 		char pad = ' ';
2385 
2386 		printf("             ");
2387 		if (sense->flags & SSD_FILEMARK) {
2388 			printf("%c Filemark Detected", pad);
2389 			pad = ',';
2390 		}
2391 		if (sense->flags & SSD_EOM) {
2392 			printf("%c EOM Detected", pad);
2393 			pad = ',';
2394 		}
2395 		if (sense->flags & SSD_ILI)
2396 			printf("%c Incorrect Length Indicator Set", pad);
2397 		printf("\n");
2398 	}
2399 
2400 	/*
2401 	 * It is inconvenient to use device type to figure out how to
2402 	 * format the info fields. So print them as 32 bit integers.
2403 	 */
2404 	info = _4btol(&sense->info[0]);
2405 	if (info)
2406 		printf("         INFO: 0x%x (VALID flag %s)\n", info,
2407 		    sense->error_code & SSD_ERRCODE_VALID ? "on" : "off");
2408 
2409 	if (sense->extra_len < 4)
2410 		return;
2411 
2412 	info = _4btol(&sense->cmd_spec_info[0]);
2413 	if (info)
2414 		printf(" COMMAND INFO: 0x%x\n", info);
2415 	sbs = scsi_decode_sense(sense, DECODE_ASC_ASCQ);
2416 	if (strlen(sbs) > 0)
2417 		printf("     ASC/ASCQ: %s\n", sbs);
2418 	if (sense->fru != 0)
2419 		printf("     FRU CODE: 0x%x\n", sense->fru);
2420 	sbs = scsi_decode_sense(sense, DECODE_SKSV);
2421 	if (strlen(sbs) > 0)
2422 		printf("         SKSV: %s\n", sbs);
2423 }
2424 
2425 char *
2426 scsi_decode_sense(struct scsi_sense_data *sense, int flag)
2427 {
2428 	static char				rqsbuf[132];
2429 	u_int16_t				count;
2430 	u_int8_t				skey, spec_1;
2431 	int					len;
2432 
2433 	bzero(rqsbuf, sizeof(rqsbuf));
2434 
2435 	skey = sense->flags & SSD_KEY;
2436 	spec_1 = sense->sense_key_spec_1;
2437 	count = _2btol(&sense->sense_key_spec_2);
2438 
2439 	switch (flag) {
2440 	case DECODE_SENSE_KEY:
2441 		strlcpy(rqsbuf, sense_keys[skey], sizeof(rqsbuf));
2442 		break;
2443 	case DECODE_ASC_ASCQ:
2444 		asc2ascii(sense->add_sense_code, sense->add_sense_code_qual,
2445 		    rqsbuf, sizeof(rqsbuf));
2446 		break;
2447 	case DECODE_SKSV:
2448 		if (sense->extra_len < 9 || ((spec_1 & SSD_SCS_VALID) == 0))
2449 			break;
2450 		switch (skey) {
2451 		case SKEY_ILLEGAL_REQUEST:
2452 			len = snprintf(rqsbuf, sizeof rqsbuf,
2453 			    "Error in %s, Offset %d",
2454 			    (spec_1 & SSD_SCS_CDB_ERROR) ? "CDB" : "Parameters",
2455 			    count);
2456 			if ((len != -1 && len < sizeof rqsbuf) &&
2457 			    (spec_1 & SSD_SCS_VALID_BIT_INDEX))
2458 				snprintf(rqsbuf+len, sizeof rqsbuf - len,
2459 				    ", bit %d", spec_1 & SSD_SCS_BIT_INDEX);
2460 			break;
2461 		case SKEY_RECOVERED_ERROR:
2462 		case SKEY_MEDIUM_ERROR:
2463 		case SKEY_HARDWARE_ERROR:
2464 			snprintf(rqsbuf, sizeof rqsbuf,
2465 			    "Actual Retry Count: %d", count);
2466 			break;
2467 		case SKEY_NOT_READY:
2468 			snprintf(rqsbuf, sizeof rqsbuf,
2469 			    "Progress Indicator: %d", count);
2470 			break;
2471 		default:
2472 			break;
2473 		}
2474 		break;
2475 	default:
2476 		break;
2477 	}
2478 
2479 	return (rqsbuf);
2480 }
2481 
2482 #ifdef SCSIDEBUG
2483 /*
2484  * Given a scsi_xfer, dump the request, in all its glory
2485  */
2486 void
2487 scsi_xs_show(struct scsi_xfer *xs)
2488 {
2489 	u_char *b = (u_char *)xs->cmd;
2490 	int i = 0;
2491 
2492 	sc_print_addr(xs->sc_link);
2493 	printf("xs  (%p): ", xs);
2494 
2495 	printf("flg(0x%x)", xs->flags);
2496 	printf("link(%p)", xs->sc_link);
2497 	printf("retr(0x%x)", xs->retries);
2498 	printf("timo(0x%x)", xs->timeout);
2499 	printf("data(%p)", xs->data);
2500 	printf("res(0x%zx)", xs->resid);
2501 	printf("err(0x%x)", xs->error);
2502 	printf("bp(%p)\n", xs->bp);
2503 
2504 	sc_print_addr(xs->sc_link);
2505 	printf("cmd (%p): ", xs->cmd);
2506 
2507 	if ((xs->flags & SCSI_RESET) == 0) {
2508 		while (i < xs->cmdlen) {
2509 			if (i)
2510 				printf(",");
2511 			printf("%x", b[i++]);
2512 		}
2513 		printf("-[%d bytes]\n", xs->datalen);
2514 	} else
2515 		printf("-RESET-\n");
2516 }
2517 
2518 void
2519 scsi_show_mem(u_char *address, int num)
2520 {
2521 	int x;
2522 
2523 	printf("------------------------------");
2524 	for (x = 0; x < num; x++) {
2525 		if ((x % 16) == 0)
2526 			printf("\n%03d: ", x);
2527 		printf("%02x ", *address++);
2528 	}
2529 	printf("\n------------------------------\n");
2530 }
2531 #endif /* SCSIDEBUG */
2532 
2533 void
2534 scsi_cmd_rw_decode(struct scsi_generic *cmd, u_int64_t *blkno,
2535     u_int32_t *nblks)
2536 {
2537 	switch (cmd->opcode) {
2538 	case READ_COMMAND:
2539 	case WRITE_COMMAND: {
2540 		struct scsi_rw *rw = (struct scsi_rw *)cmd;
2541 		*blkno = _3btol(rw->addr) & (SRW_TOPADDR << 16 | 0xffff);
2542 		*nblks = rw->length ? rw->length : 0x100;
2543 		break;
2544 	}
2545 	case READ_BIG:
2546 	case WRITE_BIG: {
2547 		struct scsi_rw_big *rwb = (struct scsi_rw_big *)cmd;
2548 		*blkno = _4btol(rwb->addr);
2549 		*nblks = _2btol(rwb->length);
2550 		break;
2551 	}
2552 	case READ_12:
2553 	case WRITE_12: {
2554 		struct scsi_rw_12 *rw12 = (struct scsi_rw_12 *)cmd;
2555 		*blkno = _4btol(rw12->addr);
2556 		*nblks = _4btol(rw12->length);
2557 		break;
2558 	}
2559 	case READ_16:
2560 	case WRITE_16: {
2561 		struct scsi_rw_16 *rw16 = (struct scsi_rw_16 *)cmd;
2562 		*blkno = _8btol(rw16->addr);
2563 		*nblks = _4btol(rw16->length);
2564 		break;
2565 	}
2566 	default:
2567 		panic("scsi_cmd_rw_decode: bad opcode 0x%02x", cmd->opcode);
2568 	}
2569 }
2570