xref: /titanic_44/usr/src/uts/common/io/scsi/targets/st.c (revision 0bc46f0d82f5e2ab983b9daff3aa7c9abb447ff2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29  */
30 
31 #if defined(lint) && !defined(DEBUG)
32 #define	DEBUG	1
33 #endif
34 
35 #include <sys/modctl.h>
36 #include <sys/scsi/scsi.h>
37 #include <sys/mtio.h>
38 #include <sys/scsi/targets/stdef.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/ddidmareq.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/byteorder.h>
45 
46 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
47 /*
48  * stats maintained only for reads/writes as commands
49  * like rewind etc skew the wait/busy times
50  */
51 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
52 #define	ST_DO_KSTATS(bp, kstat_function) \
53 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54 		kstat_function(IOSP); \
55 	}
56 
57 #define	ST_DO_ERRSTATS(un, x)  \
58 	if (un->un_errstats) { \
59 		struct st_errstats *stp; \
60 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61 		stp->x.value.ul++; \
62 	}
63 
64 #define	FILL_SCSI1_LUN(devp, pkt) 					\
65 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66 		int _lun;						\
67 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69 		if (_lun > 0) {						\
70 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71 			    _lun;					\
72 		}							\
73 	}
74 
75 /*
76  * get an available contig mem header, cp.
77  * when big_enough is true, we will return NULL, if no big enough
78  * contig mem is found.
79  * when big_enough is false, we will try to find cp containing big
80  * enough contig mem. if not found, we will ruturn the last cp available.
81  *
82  * used by st_get_contig_mem()
83  */
84 #define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85 	struct contig_mem *tmp_cp = NULL;				\
86 	for ((cp) = (un)->un_contig_mem;				\
87 	    (cp) != NULL;						\
88 	    tmp_cp = (cp), (cp) = (cp)->cm_next) { 			\
89 		if (((cp)->cm_len >= (len)) || 				\
90 		    (!(big_enough) && ((cp)->cm_next == NULL))) { 	\
91 			if (tmp_cp == NULL) { 				\
92 				(un)->un_contig_mem = (cp)->cm_next; 	\
93 			} else { 					\
94 				tmp_cp->cm_next = (cp)->cm_next; 	\
95 			} 						\
96 			(cp)->cm_next = NULL; 				\
97 			(un)->un_contig_mem_available_num--; 		\
98 			break; 						\
99 		} 							\
100 	} 								\
101 }
102 
103 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104 #define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105 #define	ISALNUM(byte) \
106 	(((byte) >= 'a' && (byte) <= 'z') || \
107 	((byte) >= 'A' && (byte) <= 'Z') || \
108 	((byte) >= '0' && (byte) <= '9'))
109 
110 #define	ONE_K	1024
111 
112 #define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113 		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114 			return (EINVAL); \
115 	} else { \
116 		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117 			return (EINVAL); \
118 	} \
119 
120 /*
121  * Global External Data Definitions
122  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static const char mp_misconf[] = {
133 	"St Tape is misconfigured, MPxIO enabled and "
134 	"tape-command-recovery-disable set in st.conf\n"
135 };
136 
137 #ifdef	__x86
138 /*
139  * We need to use below DMA attr to alloc physically contiguous
140  * memory to do I/O in big block size
141  */
142 static ddi_dma_attr_t st_contig_mem_dma_attr = {
143 	DMA_ATTR_V0,    /* version number */
144 	0x0,		/* lowest usable address */
145 	0xFFFFFFFFull,  /* high DMA address range */
146 	0xFFFFFFFFull,  /* DMA counter register */
147 	1,		/* DMA address alignment */
148 	1,		/* DMA burstsizes */
149 	1,		/* min effective DMA size */
150 	0xFFFFFFFFull,  /* max DMA xfer size */
151 	0xFFFFFFFFull,  /* segment boundary */
152 	1,		/* s/g list length */
153 	1,		/* granularity of device */
154 	0		/* DMA transfer flags */
155 };
156 
157 static ddi_device_acc_attr_t st_acc_attr = {
158 	DDI_DEVICE_ATTR_V0,
159 	DDI_NEVERSWAP_ACC,
160 	DDI_STRICTORDER_ACC
161 };
162 
163 /* set limitation for the number of contig_mem */
164 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165 #endif
166 
167 /*
168  * Tunable parameters
169  *
170  * DISCLAIMER
171  * ----------
172  * These parameters are intended for use only in system testing; if you use
173  * them in production systems, you do so at your own risk. Altering any
174  * variable not listed below may cause unpredictable system behavior.
175  *
176  * st_check_media_time
177  *
178  *   Three second state check
179  *
180  * st_allow_large_xfer
181  *
182  *   Gated with ST_NO_RECSIZE_LIMIT
183  *
184  *   0 - Transfers larger than 64KB will not be allowed
185  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186  *   1 - Transfers larger than 64KB will be allowed
187  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188  *
189  * st_report_soft_errors_on_close
190  *
191  *  Gated with ST_SOFT_ERROR_REPORTING
192  *
193  *  0 - Errors will not be reported on close regardless
194  *      of the setting of ST_SOFT_ERROR_REPORTING
195  *
196  *  1 - Errors will be reported on close if
197  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static int st_report_soft_errors_on_close = 1;
217 
218 /*
219  * End of tunable parameters list
220  */
221 
222 
223 
224 /*
225  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226  *
227  * Asynchronous I/O's main offering is that it is a non-blocking way to do
228  * reads and writes.  The driver will queue up all the requests it gets and
229  * have them ready to transport to the HBA.  Unfortunately, we cannot always
230  * just ship the I/O requests to the HBA, as there errors and exceptions
231  * that may happen when we don't want the HBA to continue.  Therein comes
232  * the flush-on-errors capability.  If the HBA supports it, then st will
233  * send in st_max_throttle I/O requests at the same time.
234  *
235  * Persistent errors : This was also reasonably simple.  In the interrupt
236  * routines, if there was an error or exception (FM, LEOT, media error,
237  * transport error), the persistent error bits are set and shuts everything
238  * down, but setting the throttle to zero.  If we hit and exception in the
239  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241  * the appropriate error, and this will preserve order. Of course, depending
242  * on the exception we have to show a zero read or write before we show
243  * errors back to the application.
244  */
245 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static const struct vid_drivetype {
260 	char	*vid;
261 	char	type;
262 } st_vid_dt[] = {
263 	{"LTO-CVE ",	MT_LTO},
264 	{"QUANTUM ",    MT_ISDLT},
265 	{"SONY    ",    MT_ISAIT},
266 	{"STK     ",	MT_ISSTK9840}
267 };
268 
269 static const struct driver_minor_data {
270 	char	*name;
271 	int	minor;
272 } st_minor_data[] = {
273 	/*
274 	 * The top 4 entries are for the default densities,
275 	 * don't alter their position.
276 	 */
277 	{"",	0},
278 	{"n",	MT_NOREWIND},
279 	{"b",	MT_BSD},
280 	{"bn",	MT_NOREWIND | MT_BSD},
281 	{"l",	MT_DENSITY1},
282 	{"m",	MT_DENSITY2},
283 	{"h",	MT_DENSITY3},
284 	{"c",	MT_DENSITY4},
285 	{"u",	MT_DENSITY4},
286 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290 	{"un",	MT_DENSITY4 | MT_NOREWIND},
291 	{"lb",	MT_DENSITY1 | MT_BSD},
292 	{"mb",	MT_DENSITY2 | MT_BSD},
293 	{"hb",	MT_DENSITY3 | MT_BSD},
294 	{"cb",	MT_DENSITY4 | MT_BSD},
295 	{"ub",	MT_DENSITY4 | MT_BSD},
296 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301 };
302 
303 /* strings used in many debug and warning messages */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static const char *load_strs[] = {
319 	"unload",		/* LD_UNLOAD		0 */
320 	"load",			/* LD_LOAD		1 */
321 	"retension",		/* LD_RETEN		2 */
322 	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323 	"eod",			/* LD_EOT		4 */
324 	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325 	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326 	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327 	"hold",			/* LD_HOLD		8 */
328 	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329 };
330 
331 static const char *errstatenames[] = {
332 	"COMMAND_DONE",
333 	"COMMAND_DONE_ERROR",
334 	"COMMAND_DONE_ERROR_RECOVERED",
335 	"QUE_COMMAND",
336 	"QUE_BUSY_COMMAND",
337 	"QUE_SENSE",
338 	"JUST_RETURN",
339 	"COMMAND_DONE_EACCES",
340 	"QUE_LAST_COMMAND",
341 	"COMMAND_TIMEOUT",
342 	"PATH_FAILED",
343 	"DEVICE_RESET",
344 	"DEVICE_TAMPER",
345 	"ATTEMPT_RETRY"
346 };
347 
348 const char *bogusID = "Unknown Media ID";
349 
350 /* default density offsets in the table above */
351 #define	DEF_BLANK	0
352 #define	DEF_NOREWIND	1
353 #define	DEF_BSD		2
354 #define	DEF_BSD_NR	3
355 
356 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
357 
358 static struct tape_failure_code {
359 	uchar_t key;
360 	uchar_t add_code;
361 	uchar_t qual_code;
362 } st_tape_failure_code[] = {
363 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367 	{ KEY_NOT_READY, 0x53, 0x00},
368 	{ 0xff}
369 };
370 
371 /*  clean bit position and mask */
372 
373 static struct cln_bit_position {
374 	ushort_t cln_bit_byte;
375 	uchar_t cln_bit_mask;
376 } st_cln_bit_position[] = {
377 	{ 21, 0x08},
378 	{ 70, 0xc0},
379 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380 };
381 
382 /*
383  * architecture dependent allocation restrictions. For x86, we'll set
384  * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385  * st_sgl_size during _init().
386  */
387 #if defined(__sparc)
388 static ddi_dma_attr_t st_alloc_attr = {
389 	DMA_ATTR_V0,	/* version number */
390 	0x0,		/* lowest usable address */
391 	0xFFFFFFFFull,	/* high DMA address range */
392 	0xFFFFFFFFull,	/* DMA counter register */
393 	1,		/* DMA address alignment */
394 	1,		/* DMA burstsizes */
395 	1,		/* min effective DMA size */
396 	0xFFFFFFFFull,	/* max DMA xfer size */
397 	0xFFFFFFFFull,	/* segment boundary */
398 	1,		/* s/g list length */
399 	512,		/* granularity of device */
400 	0		/* DMA transfer flags */
401 };
402 #elif defined(__x86)
403 static ddi_dma_attr_t st_alloc_attr = {
404 	DMA_ATTR_V0,	/* version number */
405 	0x0,		/* lowest usable address */
406 	0x0,		/* high DMA address range [set in _init()] */
407 	0xFFFFull,	/* DMA counter register */
408 	512,		/* DMA address alignment */
409 	1,		/* DMA burstsizes */
410 	1,		/* min effective DMA size */
411 	0xFFFFFFFFull,	/* max DMA xfer size */
412 	0xFFFFFFFFull,  /* segment boundary */
413 	0,		/* s/g list length */
414 	512,		/* granularity of device [set in _init()] */
415 	0		/* DMA transfer flags */
416 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static struct cb_ops st_cb_ops = {
440 	st_open,		/* open */
441 	st_close,		/* close */
442 	st_queued_strategy,	/* strategy Not Block device but async checks */
443 	nodev,			/* print */
444 	nodev,			/* dump */
445 	st_read,		/* read */
446 	st_write,		/* write */
447 	st_ioctl,		/* ioctl */
448 	nodev,			/* devmap */
449 	nodev,			/* mmap */
450 	nodev,			/* segmap */
451 	nochpoll,		/* poll */
452 	ddi_prop_op,		/* cb_prop_op */
453 	0,			/* streamtab  */
454 	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455 	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456 	CB_REV,			/* cb_rev */
457 	st_aread, 		/* async I/O read entry point */
458 	st_awrite		/* async I/O write entry point */
459 
460 };
461 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static struct dev_ops st_ops = {
469 	DEVO_REV,		/* devo_rev, */
470 	0,			/* refcnt  */
471 	st_info,		/* info */
472 	nulldev,		/* identify */
473 	st_probe,		/* probe */
474 	st_attach,		/* attach */
475 	st_detach,		/* detach */
476 	nodev,			/* reset */
477 	&st_cb_ops,		/* driver operations */
478 	(struct bus_ops *)0,	/* bus operations */
479 	nulldev,		/* power */
480 	ddi_quiesce_not_needed,	/* devo_quiesce */
481 };
482 
483 /*
484  * Local Function Declarations
485  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 #ifdef	__x86
650 /*
651  * routines for I/O in big block size
652  */
653 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
654 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
655     int alloc_flags);
656 static int st_bigblk_xfer_done(struct buf *bp);
657 static struct buf *st_get_bigblk_bp(struct buf *bp);
658 #endif
659 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
660     const char *comment, tapepos_t *pos);
661 
662 /*
663  * error statistics create/update functions
664  */
665 static int st_create_errstats(struct scsi_tape *, int);
666 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
667     tapepos_t *pos);
668 
669 #ifdef STDEBUG
670 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
671 #endif /* STDEBUG */
672 static char *st_dev_name(dev_t dev);
673 
674 #if !defined(lint)
675 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
676     scsi_pkt buf uio scsi_cdb uscsi_cmd))
677 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
678 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
679 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
680 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
681 #endif
682 
683 /*
684  * autoconfiguration routines.
685  */
686 char _depends_on[] = "misc/scsi";
687 
688 static struct modldrv modldrv = {
689 	&mod_driverops,		/* Type of module. This one is a driver */
690 	"SCSI tape Driver", 	/* Name of the module. */
691 	&st_ops			/* driver ops */
692 };
693 
694 static struct modlinkage modlinkage = {
695 	MODREV_1, &modldrv, NULL
696 };
697 
698 /*
699  * Notes on Post Reset Behavior in the tape driver:
700  *
701  * When the tape drive is opened, the driver  attempts  to make sure that
702  * the tape head is positioned exactly where it was left when it was last
703  * closed  provided  the  medium  is not  changed.  If the tape  drive is
704  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
705  * of position due to reset) will happen when the first tape operation or
706  * I/O occurs.  The repositioning (if required) may not be possible under
707  * certain situations such as when the device firmware not able to report
708  * the medium  change in the REQUEST  SENSE data  because of a reset or a
709  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
710  * extraordinary  situations, where the driver fails to position the head
711  * at its  original  position,  it will fail the open the first  time, to
712  * save the applications from overwriting the data.  All further attempts
713  * to open the tape device will result in the driver  attempting  to load
714  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
715  * indicate  that further  attempts to open the tape device may result in
716  * the tape being  loaded at BOT will be printed on the  console.  If the
717  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
718  * original tape head  position,  will result in the failure of the first
719  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
720  * internal tape position  which will  necessitate  the  applications  to
721  * validate the position by using either a tape  positioning  ioctl (such
722  * as MTREW) or closing and reopening the tape device.
723  *
724  */
725 
726 int
727 _init(void)
728 {
729 	int e;
730 
731 	if (((e = ddi_soft_state_init(&st_state,
732 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
733 		return (e);
734 	}
735 
736 	if ((e = mod_install(&modlinkage)) != 0) {
737 		ddi_soft_state_fini(&st_state);
738 	} else {
739 #ifdef STDEBUG
740 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
741 #endif
742 
743 #if defined(__x86)
744 		/* set the max physical address for iob allocs on x86 */
745 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
746 
747 		/*
748 		 * set the sgllen for iob allocs on x86. If this is set less
749 		 * than the number of pages the buffer will take
750 		 * (taking into account alignment), it would force the
751 		 * allocator to try and allocate contiguous pages.
752 		 */
753 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
754 #endif
755 	}
756 
757 	return (e);
758 }
759 
760 int
761 _fini(void)
762 {
763 	int e;
764 
765 	if ((e = mod_remove(&modlinkage)) != 0) {
766 		return (e);
767 	}
768 
769 #ifdef STDEBUG
770 	mutex_destroy(&st_debug_mutex);
771 #endif
772 
773 	ddi_soft_state_fini(&st_state);
774 
775 	return (e);
776 }
777 
778 int
779 _info(struct modinfo *modinfop)
780 {
781 	return (mod_info(&modlinkage, modinfop));
782 }
783 
784 
785 static int
786 st_probe(dev_info_t *devi)
787 {
788 	int instance;
789 	struct scsi_device *devp;
790 	int rval;
791 
792 #if !defined(__sparc)
793 	char    *tape_prop;
794 	int	tape_prop_len;
795 #endif
796 
797 	ST_ENTR(devi, st_probe);
798 
799 	/* If self identifying device */
800 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
801 		return (DDI_PROBE_DONTCARE);
802 	}
803 
804 #if !defined(__sparc)
805 	/*
806 	 * Since some x86 HBAs have devnodes that look like SCSI as
807 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
808 	 * we check for the presence of the "tape" property.
809 	 */
810 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
811 	    DDI_PROP_CANSLEEP, "tape",
812 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
813 		return (DDI_PROBE_FAILURE);
814 	}
815 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
816 		kmem_free(tape_prop, tape_prop_len);
817 		return (DDI_PROBE_FAILURE);
818 	}
819 	kmem_free(tape_prop, tape_prop_len);
820 #endif
821 
822 	devp = ddi_get_driver_private(devi);
823 	instance = ddi_get_instance(devi);
824 
825 	if (ddi_get_soft_state(st_state, instance) != NULL) {
826 		return (DDI_PROBE_PARTIAL);
827 	}
828 
829 
830 	/*
831 	 * Turn around and call probe routine to see whether
832 	 * we actually have a tape at this SCSI nexus.
833 	 */
834 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
835 
836 		/*
837 		 * In checking the whole inq_dtype byte we are looking at both
838 		 * the Peripheral Qualifier and the Peripheral Device Type.
839 		 * For this driver we are only interested in sequential devices
840 		 * that are connected or capable if connecting to this logical
841 		 * unit.
842 		 */
843 		if (devp->sd_inq->inq_dtype ==
844 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
845 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
846 			    "probe exists\n");
847 			rval = DDI_PROBE_SUCCESS;
848 		} else {
849 			rval = DDI_PROBE_FAILURE;
850 		}
851 	} else {
852 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
853 		    "probe failure: nothing there\n");
854 		rval = DDI_PROBE_FAILURE;
855 	}
856 	scsi_unprobe(devp);
857 	return (rval);
858 }
859 
860 static int
861 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
862 {
863 	int 	instance;
864 	int	wide;
865 	int 	dev_instance;
866 	int	ret_status;
867 	struct	scsi_device *devp;
868 	int	node_ix;
869 	struct	scsi_tape *un;
870 
871 	ST_ENTR(devi, st_attach);
872 
873 	devp = ddi_get_driver_private(devi);
874 	instance = ddi_get_instance(devi);
875 
876 	switch (cmd) {
877 		case DDI_ATTACH:
878 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
879 			    "tape-command-recovery-disable", 0) != 0) {
880 				st_recov_sz = sizeof (pkt_info);
881 			}
882 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
883 				return (DDI_FAILURE);
884 			}
885 			break;
886 		case DDI_RESUME:
887 			/*
888 			 * Suspend/Resume
889 			 *
890 			 * When the driver suspended, there might be
891 			 * outstanding cmds and therefore we need to
892 			 * reset the suspended flag and resume the scsi
893 			 * watch thread and restart commands and timeouts
894 			 */
895 
896 			if (!(un = ddi_get_soft_state(st_state, instance))) {
897 				return (DDI_FAILURE);
898 			}
899 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
900 			    un->un_dev);
901 
902 			mutex_enter(ST_MUTEX);
903 
904 			un->un_throttle = un->un_max_throttle;
905 			un->un_tids_at_suspend = 0;
906 			un->un_pwr_mgmt = ST_PWR_NORMAL;
907 
908 			if (un->un_swr_token) {
909 				scsi_watch_resume(un->un_swr_token);
910 			}
911 
912 			/*
913 			 * Restart timeouts
914 			 */
915 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
916 				mutex_exit(ST_MUTEX);
917 				un->un_delay_tid = timeout(
918 				    st_delayed_cv_broadcast, un,
919 				    drv_usectohz((clock_t)
920 				    MEDIA_ACCESS_DELAY));
921 				mutex_enter(ST_MUTEX);
922 			}
923 
924 			if (un->un_tids_at_suspend & ST_HIB_TID) {
925 				mutex_exit(ST_MUTEX);
926 				un->un_hib_tid = timeout(st_intr_restart, un,
927 				    ST_STATUS_BUSY_TIMEOUT);
928 				mutex_enter(ST_MUTEX);
929 			}
930 
931 			ret_status = st_clear_unit_attentions(dev_instance, 5);
932 
933 			/*
934 			 * now check if we need to restore the tape position
935 			 */
936 			if ((un->un_suspend_pos.pmode != invalid) &&
937 			    ((un->un_suspend_pos.fileno > 0) ||
938 			    (un->un_suspend_pos.blkno > 0)) ||
939 			    (un->un_suspend_pos.lgclblkno > 0)) {
940 				if (ret_status != 0) {
941 					/*
942 					 * tape didn't get good TUR
943 					 * just print out error messages
944 					 */
945 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
946 					    "st_attach-RESUME: tape failure "
947 					    " tape position will be lost");
948 				} else {
949 					/* this prints errors */
950 					(void) st_validate_tapemarks(un,
951 					    st_uscsi_cmd, &un->un_suspend_pos);
952 				}
953 				/*
954 				 * there are no retries, if there is an error
955 				 * we don't know if the tape has changed
956 				 */
957 				un->un_suspend_pos.pmode = invalid;
958 			}
959 
960 			/* now we are ready to start up any queued I/Os */
961 			if (un->un_ncmds || un->un_quef) {
962 				st_start(un);
963 			}
964 
965 			cv_broadcast(&un->un_suspend_cv);
966 			mutex_exit(ST_MUTEX);
967 			return (DDI_SUCCESS);
968 
969 		default:
970 			return (DDI_FAILURE);
971 	}
972 
973 	un = ddi_get_soft_state(st_state, instance);
974 
975 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
976 	    "st_attach: instance=%x\n", instance);
977 
978 	/*
979 	 * Add a zero-length attribute to tell the world we support
980 	 * kernel ioctls (for layered drivers)
981 	 */
982 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
983 	    DDI_KERNEL_IOCTL, NULL, 0);
984 
985 	ddi_report_dev((dev_info_t *)devi);
986 
987 	/*
988 	 * If it's a SCSI-2 tape drive which supports wide,
989 	 * tell the host adapter to use wide.
990 	 */
991 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
992 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
993 
994 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
995 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
996 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
997 	}
998 
999 	/*
1000 	 * enable autorequest sense; keep the rq packet around in case
1001 	 * the autorequest sense fails because of a busy condition
1002 	 * do a getcap first in case the capability is not variable
1003 	 */
1004 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1005 		un->un_arq_enabled = 1;
1006 	} else {
1007 		un->un_arq_enabled =
1008 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1009 	}
1010 
1011 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1012 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1013 
1014 	un->un_untagged_qing =
1015 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1016 
1017 	/*
1018 	 * XXX - This is just for 2.6.  to tell users that write buffering
1019 	 *	has gone away.
1020 	 */
1021 	if (un->un_arq_enabled && un->un_untagged_qing) {
1022 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1023 		    "tape-driver-buffering", 0) != 0) {
1024 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1025 			    "Write Data Buffering has been depricated. Your "
1026 			    "applications should continue to work normally.\n"
1027 			    " But, they should  ported to use Asynchronous "
1028 			    " I/O\n"
1029 			    " For more information, read about "
1030 			    " tape-driver-buffering "
1031 			    "property in the st(7d) man page\n");
1032 		}
1033 	}
1034 
1035 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1036 	un->un_flush_on_errors = 0;
1037 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1038 
1039 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1040 	    "throttle=%x, max_throttle = %x\n",
1041 	    un->un_throttle, un->un_max_throttle);
1042 
1043 	/* initialize persistent errors to nil */
1044 	un->un_persistence = 0;
1045 	un->un_persist_errors = 0;
1046 
1047 	/*
1048 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1049 	 */
1050 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1051 	if (un->un_maxdma == -1) {
1052 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1053 		    "Received a value that looked like -1. Using 64k maxdma");
1054 		un->un_maxdma = (64 * ONE_K);
1055 	}
1056 
1057 #ifdef	__x86
1058 	/*
1059 	 * for x86, the device may be able to DMA more than the system will
1060 	 * allow under some circumstances. We need account for both the HBA's
1061 	 * and system's contraints.
1062 	 *
1063 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1064 	 * device constraints, the max copy buffer size, and the worse case
1065 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1066 	 * doesn't take the worse case framentation into account.
1067 	 *
1068 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1069 	 * if none of the pages are contiguous. Keeping track of both of these
1070 	 * values allows us to support larger tape block sizes on some devices.
1071 	 */
1072 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1073 	    1);
1074 
1075 	/*
1076 	 * If the dma-max-arch capability is not implemented, or the value
1077 	 * comes back higher than what was reported in dma-max, use dma-max.
1078 	 */
1079 	if ((un->un_maxdma_arch == -1) ||
1080 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1081 		un->un_maxdma_arch = un->un_maxdma;
1082 	}
1083 #endif
1084 
1085 	/*
1086 	 * Get the max allowable cdb size
1087 	 */
1088 	un->un_max_cdb_sz =
1089 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1090 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1091 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1092 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1093 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1094 	}
1095 
1096 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1097 		un->un_multipath = 0;
1098 	} else {
1099 		un->un_multipath = 1;
1100 	}
1101 
1102 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1103 
1104 	un->un_mediastate = MTIO_NONE;
1105 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1106 
1107 	/*
1108 	 * initialize kstats
1109 	 */
1110 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1111 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1112 	if (un->un_stats) {
1113 		un->un_stats->ks_lock = ST_MUTEX;
1114 		kstat_install(un->un_stats);
1115 	}
1116 	(void) st_create_errstats(un, instance);
1117 
1118 	/*
1119 	 * find the drive type for this target
1120 	 */
1121 	mutex_enter(ST_MUTEX);
1122 	un->un_dev = MTMINOR(instance);
1123 	st_known_tape_type(un);
1124 	un->un_dev = 0;
1125 	mutex_exit(ST_MUTEX);
1126 
1127 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1128 		int minor;
1129 		char *name;
1130 
1131 		name  = st_minor_data[node_ix].name;
1132 		minor = st_minor_data[node_ix].minor;
1133 
1134 		/*
1135 		 * For default devices set the density to the
1136 		 * preferred default density for this device.
1137 		 */
1138 		if (node_ix <= DEF_BSD_NR) {
1139 			minor |= un->un_dp->default_density;
1140 		}
1141 		minor |= MTMINOR(instance);
1142 
1143 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1144 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1145 			continue;
1146 		}
1147 
1148 		ddi_remove_minor_node(devi, NULL);
1149 
1150 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1151 		    st_reset_notification, (caddr_t)un);
1152 		cv_destroy(&un->un_clscv);
1153 		cv_destroy(&un->un_sbuf_cv);
1154 		cv_destroy(&un->un_queue_cv);
1155 		cv_destroy(&un->un_state_cv);
1156 #ifdef	__x86
1157 		cv_destroy(&un->un_contig_mem_cv);
1158 #endif
1159 		cv_destroy(&un->un_suspend_cv);
1160 		cv_destroy(&un->un_tape_busy_cv);
1161 		cv_destroy(&un->un_recov_buf_cv);
1162 		if (un->un_recov_taskq) {
1163 			ddi_taskq_destroy(un->un_recov_taskq);
1164 		}
1165 		if (un->un_sbufp) {
1166 			freerbuf(un->un_sbufp);
1167 		}
1168 		if (un->un_recov_buf) {
1169 			freerbuf(un->un_recov_buf);
1170 		}
1171 		if (un->un_uscsi_rqs_buf) {
1172 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1173 		}
1174 		if (un->un_mspl) {
1175 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1176 		}
1177 		if (un->un_dp_size) {
1178 			kmem_free(un->un_dp, un->un_dp_size);
1179 		}
1180 		if (un->un_state) {
1181 			kstat_delete(un->un_stats);
1182 		}
1183 		if (un->un_errstats) {
1184 			kstat_delete(un->un_errstats);
1185 		}
1186 
1187 		scsi_destroy_pkt(un->un_rqs);
1188 		scsi_free_consistent_buf(un->un_rqs_bp);
1189 		ddi_soft_state_free(st_state, instance);
1190 		devp->sd_private = NULL;
1191 		devp->sd_sense = NULL;
1192 
1193 		ddi_prop_remove_all(devi);
1194 		return (DDI_FAILURE);
1195 	}
1196 
1197 	return (DDI_SUCCESS);
1198 }
1199 
1200 /*
1201  * st_detach:
1202  *
1203  * we allow a detach if and only if:
1204  *	- no tape is currently inserted
1205  *	- tape position is at BOT or unknown
1206  *		(if it is not at BOT then a no rewind
1207  *		device was opened and we have to preserve state)
1208  *	- it must be in a closed state : no timeouts or scsi_watch requests
1209  *		will exist if it is closed, so we don't need to check for
1210  *		them here.
1211  */
1212 /*ARGSUSED*/
1213 static int
1214 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1215 {
1216 	int instance;
1217 	int result;
1218 	struct scsi_device *devp;
1219 	struct scsi_tape *un;
1220 	clock_t wait_cmds_complete;
1221 
1222 	ST_ENTR(devi, st_detach);
1223 
1224 	instance = ddi_get_instance(devi);
1225 
1226 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1227 		return (DDI_FAILURE);
1228 	}
1229 
1230 	mutex_enter(ST_MUTEX);
1231 
1232 	/*
1233 	 * Clear error entry stack
1234 	 */
1235 	st_empty_error_stack(un);
1236 
1237 	mutex_exit(ST_MUTEX);
1238 
1239 	switch (cmd) {
1240 
1241 	case DDI_DETACH:
1242 		/*
1243 		 * Undo what we did in st_attach & st_doattach,
1244 		 * freeing resources and removing things we installed.
1245 		 * The system framework guarantees we are not active
1246 		 * with this devinfo node in any other entry points at
1247 		 * this time.
1248 		 */
1249 
1250 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1251 		    "st_detach: instance=%x, un=%p\n", instance,
1252 		    (void *)un);
1253 
1254 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1255 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1256 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1257 		    (un->un_state != ST_STATE_CLOSED)) {
1258 			/*
1259 			 * we cannot unload some targets because the
1260 			 * inquiry returns junk unless immediately
1261 			 * after a reset
1262 			 */
1263 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1264 			    "cannot unload instance %x\n", instance);
1265 			un->un_unit_attention_flags |= 4;
1266 			return (DDI_FAILURE);
1267 		}
1268 
1269 		/*
1270 		 * if the tape has been removed then we may unload;
1271 		 * do a test unit ready and if it returns NOT READY
1272 		 * then we assume that it is safe to unload.
1273 		 * as a side effect, pmode may be set to invalid if the
1274 		 * the test unit ready fails;
1275 		 * also un_state may be set to non-closed, so reset it
1276 		 */
1277 		if ((un->un_dev) &&		/* Been opened since attach */
1278 		    ((un->un_pos.pmode == legacy) &&
1279 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1280 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1281 		    ((un->un_pos.pmode == logical) &&
1282 		    (un->un_pos.lgclblkno > 0))) {
1283 			mutex_enter(ST_MUTEX);
1284 			/*
1285 			 * Send Test Unit Ready in the hopes that if
1286 			 * the drive is not in the state we think it is.
1287 			 * And the state will be changed so it can be detached.
1288 			 * If the command fails to reach the device and
1289 			 * the drive was not rewound or unloaded we want
1290 			 * to fail the detach till a user command fails
1291 			 * where after the detach will succead.
1292 			 */
1293 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1294 			/*
1295 			 * After TUR un_state may be set to non-closed,
1296 			 * so reset it back.
1297 			 */
1298 			un->un_state = ST_STATE_CLOSED;
1299 			mutex_exit(ST_MUTEX);
1300 		}
1301 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1302 		    "un_status=%x, fileno=%x, blkno=%x\n",
1303 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1304 
1305 		/*
1306 		 * check again:
1307 		 * if we are not at BOT then it is not safe to unload
1308 		 */
1309 		if ((un->un_dev) &&		/* Been opened since attach */
1310 		    (result != EACCES) &&	/* drive is use by somebody */
1311 		    ((((un->un_pos.pmode == legacy) &&
1312 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1313 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1314 		    ((un->un_pos.pmode == logical) &&
1315 		    (un->un_pos.lgclblkno > 0))) &&
1316 		    ((un->un_state != ST_STATE_CLOSED) &&
1317 		    (un->un_laststate != ST_STATE_CLOSING)))) {
1318 
1319 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1320 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1321 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1322 			    un->un_pos.fileno, un->un_pos.blkno,
1323 			    un->un_pos.lgclblkno);
1324 			un->un_unit_attention_flags |= 4;
1325 			return (DDI_FAILURE);
1326 		}
1327 
1328 		/*
1329 		 * Just To make sure that we have released the
1330 		 * tape unit .
1331 		 */
1332 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1333 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1334 			mutex_enter(ST_MUTEX);
1335 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1336 			mutex_exit(ST_MUTEX);
1337 		}
1338 
1339 		/*
1340 		 * now remove other data structures allocated in st_doattach()
1341 		 */
1342 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1343 		    "destroying/freeing\n");
1344 
1345 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1346 		    st_reset_notification, (caddr_t)un);
1347 		cv_destroy(&un->un_clscv);
1348 		cv_destroy(&un->un_sbuf_cv);
1349 		cv_destroy(&un->un_queue_cv);
1350 		cv_destroy(&un->un_suspend_cv);
1351 		cv_destroy(&un->un_tape_busy_cv);
1352 		cv_destroy(&un->un_recov_buf_cv);
1353 
1354 		if (un->un_recov_taskq) {
1355 			ddi_taskq_destroy(un->un_recov_taskq);
1356 		}
1357 
1358 		if (un->un_hib_tid) {
1359 			(void) untimeout(un->un_hib_tid);
1360 			un->un_hib_tid = 0;
1361 		}
1362 
1363 		if (un->un_delay_tid) {
1364 			(void) untimeout(un->un_delay_tid);
1365 			un->un_delay_tid = 0;
1366 		}
1367 		cv_destroy(&un->un_state_cv);
1368 
1369 #ifdef	__x86
1370 		cv_destroy(&un->un_contig_mem_cv);
1371 
1372 		if (un->un_contig_mem_hdl != NULL) {
1373 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1374 		}
1375 #endif
1376 		if (un->un_sbufp) {
1377 			freerbuf(un->un_sbufp);
1378 		}
1379 		if (un->un_recov_buf) {
1380 			freerbuf(un->un_recov_buf);
1381 		}
1382 		if (un->un_uscsi_rqs_buf) {
1383 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1384 		}
1385 		if (un->un_mspl) {
1386 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1387 		}
1388 		if (un->un_rqs) {
1389 			scsi_destroy_pkt(un->un_rqs);
1390 			scsi_free_consistent_buf(un->un_rqs_bp);
1391 		}
1392 		if (un->un_mkr_pkt) {
1393 			scsi_destroy_pkt(un->un_mkr_pkt);
1394 		}
1395 		if (un->un_arq_enabled) {
1396 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1397 		}
1398 		if (un->un_dp_size) {
1399 			kmem_free(un->un_dp, un->un_dp_size);
1400 		}
1401 		if (un->un_stats) {
1402 			kstat_delete(un->un_stats);
1403 			un->un_stats = (kstat_t *)0;
1404 		}
1405 		if (un->un_errstats) {
1406 			kstat_delete(un->un_errstats);
1407 			un->un_errstats = (kstat_t *)0;
1408 		}
1409 		if (un->un_media_id_len) {
1410 			kmem_free(un->un_media_id, un->un_media_id_len);
1411 		}
1412 		devp = ST_SCSI_DEVP;
1413 		ddi_soft_state_free(st_state, instance);
1414 		devp->sd_private = NULL;
1415 		devp->sd_sense = NULL;
1416 		scsi_unprobe(devp);
1417 		ddi_prop_remove_all(devi);
1418 		ddi_remove_minor_node(devi, NULL);
1419 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1420 		return (DDI_SUCCESS);
1421 
1422 	case DDI_SUSPEND:
1423 
1424 		/*
1425 		 * Suspend/Resume
1426 		 *
1427 		 * To process DDI_SUSPEND, we must do the following:
1428 		 *
1429 		 *  - check ddi_removing_power to see if power will be turned
1430 		 *    off. if so, return DDI_FAILURE
1431 		 *  - check if we are already suspended,
1432 		 *    if so, return DDI_FAILURE
1433 		 *  - check if device state is CLOSED,
1434 		 *    if not, return DDI_FAILURE.
1435 		 *  - wait until outstanding operations complete
1436 		 *  - save tape state
1437 		 *  - block new operations
1438 		 *  - cancel pending timeouts
1439 		 *
1440 		 */
1441 
1442 		if (ddi_removing_power(devi)) {
1443 			return (DDI_FAILURE);
1444 		}
1445 		mutex_enter(ST_MUTEX);
1446 
1447 		/*
1448 		 * Shouldn't already be suspended, if so return failure
1449 		 */
1450 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1451 			mutex_exit(ST_MUTEX);
1452 			return (DDI_FAILURE);
1453 		}
1454 		if (un->un_state != ST_STATE_CLOSED) {
1455 			mutex_exit(ST_MUTEX);
1456 			return (DDI_FAILURE);
1457 		}
1458 
1459 		/*
1460 		 * Wait for all outstanding I/O's to complete
1461 		 *
1462 		 * we wait on both ncmds and the wait queue for times
1463 		 * when we are flushing after persistent errors are
1464 		 * flagged, which is when ncmds can be 0, and the
1465 		 * queue can still have I/O's.  This way we preserve
1466 		 * order of biodone's.
1467 		 */
1468 		wait_cmds_complete = ddi_get_lbolt();
1469 		wait_cmds_complete +=
1470 		    st_wait_cmds_complete * drv_usectohz(1000000);
1471 		while (un->un_ncmds || un->un_quef ||
1472 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1473 
1474 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1475 			    wait_cmds_complete) == -1) {
1476 				/*
1477 				 * Time expired then cancel the command
1478 				 */
1479 				if (st_reset(un, RESET_LUN) == 0) {
1480 					if (un->un_last_throttle) {
1481 						un->un_throttle =
1482 						    un->un_last_throttle;
1483 					}
1484 					mutex_exit(ST_MUTEX);
1485 					return (DDI_FAILURE);
1486 				} else {
1487 					break;
1488 				}
1489 			}
1490 		}
1491 
1492 		/*
1493 		 * DDI_SUSPEND says that the system "may" power down, we
1494 		 * remember the file and block number before rewinding.
1495 		 * we also need to save state before issuing
1496 		 * any WRITE_FILE_MARK command.
1497 		 */
1498 		(void) st_update_block_pos(un, st_cmd, 0);
1499 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1500 
1501 
1502 		/*
1503 		 * Issue a zero write file fmk command to tell the drive to
1504 		 * flush any buffered tape marks
1505 		 */
1506 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1507 
1508 		/*
1509 		 * Because not all tape drives correctly implement buffer
1510 		 * flushing with the zero write file fmk command, issue a
1511 		 * synchronous rewind command to force data flushing.
1512 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1513 		 * anyway.
1514 		 */
1515 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1516 
1517 		/* stop any new operations */
1518 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1519 		un->un_throttle = 0;
1520 
1521 		/*
1522 		 * cancel any outstanding timeouts
1523 		 */
1524 		if (un->un_delay_tid) {
1525 			timeout_id_t temp_id = un->un_delay_tid;
1526 			un->un_delay_tid = 0;
1527 			un->un_tids_at_suspend |= ST_DELAY_TID;
1528 			mutex_exit(ST_MUTEX);
1529 			(void) untimeout(temp_id);
1530 			mutex_enter(ST_MUTEX);
1531 		}
1532 
1533 		if (un->un_hib_tid) {
1534 			timeout_id_t temp_id = un->un_hib_tid;
1535 			un->un_hib_tid = 0;
1536 			un->un_tids_at_suspend |= ST_HIB_TID;
1537 			mutex_exit(ST_MUTEX);
1538 			(void) untimeout(temp_id);
1539 			mutex_enter(ST_MUTEX);
1540 		}
1541 
1542 		/*
1543 		 * Suspend the scsi_watch_thread
1544 		 */
1545 		if (un->un_swr_token) {
1546 			opaque_t temp_token = un->un_swr_token;
1547 			mutex_exit(ST_MUTEX);
1548 			scsi_watch_suspend(temp_token);
1549 		} else {
1550 			mutex_exit(ST_MUTEX);
1551 		}
1552 
1553 		return (DDI_SUCCESS);
1554 
1555 	default:
1556 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1557 		return (DDI_FAILURE);
1558 	}
1559 }
1560 
1561 
1562 /* ARGSUSED */
1563 static int
1564 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1565 {
1566 	dev_t dev;
1567 	struct scsi_tape *un;
1568 	int instance, error;
1569 
1570 	ST_ENTR(dip, st_info);
1571 
1572 	switch (infocmd) {
1573 	case DDI_INFO_DEVT2DEVINFO:
1574 		dev = (dev_t)arg;
1575 		instance = MTUNIT(dev);
1576 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1577 			return (DDI_FAILURE);
1578 		*result = (void *) ST_DEVINFO;
1579 		error = DDI_SUCCESS;
1580 		break;
1581 	case DDI_INFO_DEVT2INSTANCE:
1582 		dev = (dev_t)arg;
1583 		instance = MTUNIT(dev);
1584 		*result = (void *)(uintptr_t)instance;
1585 		error = DDI_SUCCESS;
1586 		break;
1587 	default:
1588 		error = DDI_FAILURE;
1589 	}
1590 	return (error);
1591 }
1592 
1593 static int
1594 st_doattach(struct scsi_device *devp, int (*canwait)())
1595 {
1596 	struct scsi_tape *un = NULL;
1597 	recov_info *ri;
1598 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1599 	int instance;
1600 	size_t rlen;
1601 
1602 	ST_FUNC(devp->sd_dev, st_doattach);
1603 	/*
1604 	 * Call the routine scsi_probe to do some of the dirty work.
1605 	 * If the INQUIRY command succeeds, the field sd_inq in the
1606 	 * device structure will be filled in.
1607 	 */
1608 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1609 	    "st_doattach(): probing\n");
1610 
1611 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1612 
1613 		/*
1614 		 * In checking the whole inq_dtype byte we are looking at both
1615 		 * the Peripheral Qualifier and the Peripheral Device Type.
1616 		 * For this driver we are only interested in sequential devices
1617 		 * that are connected or capable if connecting to this logical
1618 		 * unit.
1619 		 */
1620 		if (devp->sd_inq->inq_dtype ==
1621 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1622 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1623 			    "probe exists\n");
1624 		} else {
1625 			/* Something there but not a tape device */
1626 			scsi_unprobe(devp);
1627 			return (DDI_FAILURE);
1628 		}
1629 	} else {
1630 		/* Nothing there */
1631 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1632 		    "probe failure: nothing there\n");
1633 		scsi_unprobe(devp);
1634 		return (DDI_FAILURE);
1635 	}
1636 
1637 
1638 	/*
1639 	 * The actual unit is present.
1640 	 * Now is the time to fill in the rest of our info..
1641 	 */
1642 	instance = ddi_get_instance(devp->sd_dev);
1643 
1644 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1645 		goto error;
1646 	}
1647 	un = ddi_get_soft_state(st_state, instance);
1648 
1649 	ASSERT(un != NULL);
1650 
1651 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1652 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1653 	if (un->un_rqs_bp == NULL) {
1654 		goto error;
1655 	}
1656 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1657 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1658 	if (!un->un_rqs) {
1659 		goto error;
1660 	}
1661 	ASSERT(un->un_rqs->pkt_resid == 0);
1662 	devp->sd_sense =
1663 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1664 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1665 
1666 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1667 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1668 	FILL_SCSI1_LUN(devp, un->un_rqs);
1669 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1670 	un->un_rqs->pkt_time = st_io_time;
1671 	un->un_rqs->pkt_comp = st_intr;
1672 	ri = (recov_info *)un->un_rqs->pkt_private;
1673 	if (st_recov_sz == sizeof (recov_info)) {
1674 		ri->privatelen = sizeof (recov_info);
1675 	} else {
1676 		ri->privatelen = sizeof (pkt_info);
1677 	}
1678 
1679 	un->un_sbufp = getrbuf(km_flags);
1680 	un->un_recov_buf = getrbuf(km_flags);
1681 
1682 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1683 
1684 	/*
1685 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1686 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1687 	 * is obsolete and we want more flexibility in controlling the DMA
1688 	 * address constraints.
1689 	 */
1690 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1691 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1692 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1693 
1694 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1695 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1696 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1697 
1698 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1699 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1700 		    "probe partial failure: no space\n");
1701 		goto error;
1702 	}
1703 
1704 	bzero(un->un_mspl, sizeof (struct seq_mode));
1705 
1706 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1707 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1708 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1709 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1710 #ifdef	__x86
1711 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1712 #endif
1713 
1714 	/* Initialize power managemnet condition variable */
1715 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1716 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1717 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1718 
1719 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1720 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1721 
1722 	ASSERT(un->un_recov_taskq != NULL);
1723 
1724 	un->un_pos.pmode = invalid;
1725 	un->un_sd	= devp;
1726 	un->un_swr_token = (opaque_t)NULL;
1727 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1728 	un->un_wormable = st_is_drive_worm;
1729 	un->un_media_id_method = st_get_media_identification;
1730 	/*
1731 	 * setting long a initial as it contains logical file info.
1732 	 * support for long format is mandatory but many drive don't do it.
1733 	 */
1734 	un->un_read_pos_type = LONG_POS;
1735 
1736 	un->un_suspend_pos.pmode = invalid;
1737 
1738 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1739 
1740 #ifdef	__x86
1741 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1742 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1743 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1744 		    "allocation of contiguous memory dma handle failed!");
1745 		un->un_contig_mem_hdl = NULL;
1746 		goto error;
1747 	}
1748 #endif
1749 
1750 	/*
1751 	 * Since this driver manages devices with "remote" hardware,
1752 	 * i.e. the devices themselves have no "reg" properties,
1753 	 * the SUSPEND/RESUME commands in detach/attach will not be
1754 	 * called by the power management framework unless we request
1755 	 * it by creating a "pm-hardware-state" property and setting it
1756 	 * to value "needs-suspend-resume".
1757 	 */
1758 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1759 	    "pm-hardware-state", "needs-suspend-resume") !=
1760 	    DDI_PROP_SUCCESS) {
1761 
1762 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1763 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1764 		goto error;
1765 	}
1766 
1767 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1768 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1769 
1770 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1771 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1772 		    "failed\n");
1773 		goto error;
1774 	}
1775 
1776 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1777 	    st_reset_notification, (caddr_t)un);
1778 
1779 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1780 	return (DDI_SUCCESS);
1781 
1782 error:
1783 	devp->sd_sense = NULL;
1784 
1785 	ddi_remove_minor_node(devp->sd_dev, NULL);
1786 	if (un) {
1787 		if (un->un_mspl) {
1788 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1789 		}
1790 		if (un->un_read_pos_data) {
1791 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1792 		}
1793 		if (un->un_sbufp) {
1794 			freerbuf(un->un_sbufp);
1795 		}
1796 		if (un->un_recov_buf) {
1797 			freerbuf(un->un_recov_buf);
1798 		}
1799 		if (un->un_uscsi_rqs_buf) {
1800 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1801 		}
1802 #ifdef	__x86
1803 		if (un->un_contig_mem_hdl != NULL) {
1804 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1805 		}
1806 #endif
1807 		if (un->un_rqs) {
1808 			scsi_destroy_pkt(un->un_rqs);
1809 		}
1810 
1811 		if (un->un_rqs_bp) {
1812 			scsi_free_consistent_buf(un->un_rqs_bp);
1813 		}
1814 
1815 		ddi_soft_state_free(st_state, instance);
1816 		devp->sd_private = NULL;
1817 	}
1818 
1819 	if (devp->sd_inq) {
1820 		scsi_unprobe(devp);
1821 	}
1822 	return (DDI_FAILURE);
1823 }
1824 
1825 typedef int
1826 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1827 
1828 static cfg_functp config_functs[] = {
1829 	st_get_conf_from_st_dot_conf,
1830 	st_get_conf_from_st_conf_dot_c,
1831 	st_get_conf_from_tape_drive,
1832 	st_get_default_conf
1833 };
1834 
1835 
1836 /*
1837  * determine tape type, using tape-config-list or built-in table or
1838  * use a generic tape config entry
1839  */
1840 static void
1841 st_known_tape_type(struct scsi_tape *un)
1842 {
1843 	struct st_drivetype *dp;
1844 	cfg_functp *config_funct;
1845 	uchar_t reserved;
1846 
1847 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1848 
1849 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1850 	    : ST_RELEASE;
1851 
1852 	/*
1853 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1854 	 *	 no vid & pid inquiry data.  So, we provide one.
1855 	 */
1856 	if (ST_INQUIRY->inq_len == 0 ||
1857 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1858 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1859 	}
1860 
1861 	if (un->un_dp_size == 0) {
1862 		un->un_dp_size = sizeof (struct st_drivetype);
1863 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1864 		un->un_dp = dp;
1865 	} else {
1866 		dp = un->un_dp;
1867 	}
1868 
1869 	un->un_dp->non_motion_timeout = st_io_time;
1870 	/*
1871 	 * Loop through the configuration methods till one works.
1872 	 */
1873 	for (config_funct = &config_functs[0]; ; config_funct++) {
1874 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1875 			break;
1876 		}
1877 	}
1878 
1879 	/*
1880 	 * If we didn't just make up this configuration and
1881 	 * all the density codes are the same..
1882 	 * Set Auto Density over ride.
1883 	 */
1884 	if (*config_funct != st_get_default_conf) {
1885 		/*
1886 		 * If this device is one that is configured and all
1887 		 * densities are the same, This saves doing gets and set
1888 		 * that yield nothing.
1889 		 */
1890 		if ((dp->densities[0]) == (dp->densities[1]) &&
1891 		    (dp->densities[0]) == (dp->densities[2]) &&
1892 		    (dp->densities[0]) == (dp->densities[3])) {
1893 
1894 			dp->options |= ST_AUTODEN_OVERRIDE;
1895 		}
1896 	}
1897 
1898 
1899 	/*
1900 	 * Store tape drive characteristics.
1901 	 */
1902 	un->un_status = 0;
1903 	un->un_attached = 1;
1904 	un->un_init_options = dp->options;
1905 
1906 	/* setup operation time-outs based on options */
1907 	st_calculate_timeouts(un);
1908 
1909 	/* make sure if we are supposed to be variable, make it variable */
1910 	if (dp->options & ST_VARIABLE) {
1911 		dp->bsize = 0;
1912 	}
1913 
1914 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1915 	    : ST_RELEASE)) {
1916 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1917 	}
1918 
1919 	un->un_unit_attention_flags |= 1;
1920 
1921 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1922 
1923 }
1924 
1925 
1926 typedef struct {
1927 	int mask;
1928 	int bottom;
1929 	int top;
1930 	char *name;
1931 } conf_limit;
1932 
1933 static const conf_limit conf_limits[] = {
1934 
1935 	-1,		1,		2,		"conf version",
1936 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1937 	-1,		0,		0xffffff,	"block size",
1938 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1939 	-1,		0,		4,		"number of densities",
1940 	-1,		0,		UINT8_MAX,	"density code",
1941 	-1,		0,		3,		"default density",
1942 	-1,		0,		UINT16_MAX,	"non motion timeout",
1943 	-1,		0,		UINT16_MAX,	"I/O timeout",
1944 	-1,		0,		UINT16_MAX,	"space timeout",
1945 	-1,		0,		UINT16_MAX,	"load timeout",
1946 	-1,		0,		UINT16_MAX,	"unload timeout",
1947 	-1,		0,		UINT16_MAX,	"erase timeout",
1948 	0,		0,		0,		NULL
1949 };
1950 
1951 static int
1952 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1953     const char *conf_name)
1954 {
1955 	int dens;
1956 	int ndens;
1957 	int value;
1958 	int type;
1959 	int count;
1960 	const conf_limit *limit = &conf_limits[0];
1961 
1962 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1963 
1964 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1965 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1966 
1967 	count = list_len;
1968 	type = *list;
1969 	for (;  count && limit->name; count--, list++, limit++) {
1970 
1971 		value = *list;
1972 		if (value & ~limit->mask) {
1973 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1974 			    "%s %s value invalid bits set: 0x%X\n",
1975 			    conf_name, limit->name, value & ~limit->mask);
1976 			*list &= limit->mask;
1977 		} else if (value < limit->bottom) {
1978 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1979 			    "%s %s value too low: value = %d limit %d\n",
1980 			    conf_name, limit->name, value, limit->bottom);
1981 		} else if (value > limit->top) {
1982 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1983 			    "%s %s value too high: value = %d limit %d\n",
1984 			    conf_name, limit->name, value, limit->top);
1985 		} else {
1986 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1987 			    "%s %s value = 0x%X\n",
1988 			    conf_name, limit->name, value);
1989 		}
1990 
1991 		/* If not the number of densities continue */
1992 		if (limit != &conf_limits[4]) {
1993 			continue;
1994 		}
1995 
1996 		/* If number of densities is not in range can't use config */
1997 		if (value < limit->bottom || value > limit->top) {
1998 			return (-1);
1999 		}
2000 
2001 		ndens = min(value, NDENSITIES);
2002 		if ((type == 1) && (list_len - ndens) != 6) {
2003 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2004 			    "%s conf version 1 with %d densities has %d items"
2005 			    " should have %d",
2006 			    conf_name, ndens, list_len, 6 + ndens);
2007 		} else if ((type == 2) && (list_len - ndens) != 13) {
2008 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2009 			    "%s conf version 2 with %d densities has %d items"
2010 			    " should have %d",
2011 			    conf_name, ndens, list_len, 13 + ndens);
2012 		}
2013 
2014 		limit++;
2015 		for (dens = 0; dens < ndens && count; dens++) {
2016 			count--;
2017 			list++;
2018 			value = *list;
2019 			if (value < limit->bottom) {
2020 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2021 				    "%s density[%d] value too low: value ="
2022 				    " 0x%X limit 0x%X\n",
2023 				    conf_name, dens, value, limit->bottom);
2024 			} else if (value > limit->top) {
2025 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2026 				    "%s density[%d] value too high: value ="
2027 				    " 0x%X limit 0x%X\n",
2028 				    conf_name, dens, value, limit->top);
2029 			} else {
2030 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2031 				    "%s density[%d] value = 0x%X\n",
2032 				    conf_name, dens, value);
2033 			}
2034 		}
2035 	}
2036 
2037 	return (0);
2038 }
2039 
2040 static int
2041 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2042     struct st_drivetype *dp)
2043 {
2044 	caddr_t config_list = NULL;
2045 	caddr_t data_list = NULL;
2046 	int	*data_ptr;
2047 	caddr_t vidptr, prettyptr, datanameptr;
2048 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2049 	int config_list_len, data_list_len, len, i;
2050 	int version;
2051 	int found = 0;
2052 
2053 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2054 
2055 	/*
2056 	 * Determine type of tape controller. Type is determined by
2057 	 * checking the vendor ids of the earlier inquiry command and
2058 	 * comparing those with vids in tape-config-list defined in st.conf
2059 	 */
2060 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2061 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2062 	    != DDI_PROP_SUCCESS) {
2063 		return (found);
2064 	}
2065 
2066 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2067 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2068 
2069 	/*
2070 	 * Compare vids in each triplet - if it matches, get value for
2071 	 * data_name and contruct a st_drivetype struct
2072 	 * tripletlen is not set yet!
2073 	 */
2074 	for (len = config_list_len, vidptr = config_list;
2075 	    len > 0;
2076 	    vidptr += tripletlen, len -= tripletlen) {
2077 
2078 		vidlen = strlen(vidptr);
2079 		prettyptr = vidptr + vidlen + 1;
2080 		prettylen = strlen(prettyptr);
2081 		datanameptr = prettyptr + prettylen + 1;
2082 		datanamelen = strlen(datanameptr);
2083 		tripletlen = vidlen + prettylen + datanamelen + 3;
2084 
2085 		if (vidlen == 0) {
2086 			continue;
2087 		}
2088 
2089 		/*
2090 		 * If inquiry vid dosen't match this triplets vid,
2091 		 * try the next.
2092 		 */
2093 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2094 			continue;
2095 		}
2096 
2097 		/*
2098 		 * if prettylen is zero then use the vid string
2099 		 */
2100 		if (prettylen == 0) {
2101 			prettyptr = vidptr;
2102 			prettylen = vidlen;
2103 		}
2104 
2105 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2106 		    "vid = %s, pretty=%s, dataname = %s\n",
2107 		    vidptr, prettyptr, datanameptr);
2108 
2109 		/*
2110 		 * get the data list
2111 		 */
2112 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2113 		    datanameptr, (caddr_t)&data_list,
2114 		    &data_list_len) != DDI_PROP_SUCCESS) {
2115 			/*
2116 			 * Error in getting property value
2117 			 * print warning!
2118 			 */
2119 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2120 			    "data property (%s) has no value\n",
2121 			    datanameptr);
2122 			continue;
2123 		}
2124 
2125 		/*
2126 		 * now initialize the st_drivetype struct
2127 		 */
2128 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2129 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2130 		(void) strncpy(dp->vid, vidptr, dp->length);
2131 		data_ptr = (int *)data_list;
2132 		/*
2133 		 * check if data is enough for version, type,
2134 		 * bsize, options, # of densities, density1,
2135 		 * density2, ..., default_density
2136 		 */
2137 		if ((data_list_len < 5 * sizeof (int)) ||
2138 		    (data_list_len < 6 * sizeof (int) +
2139 		    *(data_ptr + 4) * sizeof (int))) {
2140 			/*
2141 			 * print warning and skip to next triplet.
2142 			 */
2143 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2144 			    "data property (%s) incomplete\n",
2145 			    datanameptr);
2146 			kmem_free(data_list, data_list_len);
2147 			continue;
2148 		}
2149 
2150 		if (st_validate_conf_data(un, data_ptr,
2151 		    data_list_len / sizeof (int), datanameptr)) {
2152 			kmem_free(data_list, data_list_len);
2153 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2154 			    "data property (%s) rejected\n",
2155 			    datanameptr);
2156 			continue;
2157 		}
2158 
2159 		/*
2160 		 * check version
2161 		 */
2162 		version = *data_ptr++;
2163 		if (version != 1 && version != 2) {
2164 			/* print warning but accept it */
2165 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2166 			    "Version # for data property (%s) "
2167 			    "not set to 1 or 2\n", datanameptr);
2168 		}
2169 
2170 		dp->type    = *data_ptr++;
2171 		dp->bsize   = *data_ptr++;
2172 		dp->options = *data_ptr++;
2173 		dp->options |= ST_DYNAMIC;
2174 		len = *data_ptr++;
2175 		for (i = 0; i < NDENSITIES; i++) {
2176 			if (i < len) {
2177 				dp->densities[i] = *data_ptr++;
2178 			}
2179 		}
2180 		dp->default_density = *data_ptr << 3;
2181 		if (version == 2 &&
2182 		    data_list_len >= (13 + len) * sizeof (int)) {
2183 			data_ptr++;
2184 			dp->non_motion_timeout	= *data_ptr++;
2185 			dp->io_timeout		= *data_ptr++;
2186 			dp->rewind_timeout	= *data_ptr++;
2187 			dp->space_timeout	= *data_ptr++;
2188 			dp->load_timeout	= *data_ptr++;
2189 			dp->unload_timeout	= *data_ptr++;
2190 			dp->erase_timeout	= *data_ptr++;
2191 		}
2192 		kmem_free(data_list, data_list_len);
2193 		found = 1;
2194 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2195 		    "found in st.conf: vid = %s, pretty=%s\n",
2196 		    dp->vid, dp->name);
2197 		break;
2198 	}
2199 
2200 	/*
2201 	 * free up the memory allocated by ddi_getlongprop
2202 	 */
2203 	if (config_list) {
2204 		kmem_free(config_list, config_list_len);
2205 	}
2206 	return (found);
2207 }
2208 
2209 static int
2210 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2211     struct st_drivetype *dp)
2212 {
2213 	int i;
2214 
2215 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2216 	/*
2217 	 * Determine type of tape controller.  Type is determined by
2218 	 * checking the result of the earlier inquiry command and
2219 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2220 	 */
2221 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2222 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2223 
2224 	for (i = 0; i < st_ndrivetypes; i++) {
2225 		if (st_drivetypes[i].length == 0) {
2226 			continue;
2227 		}
2228 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2229 		    st_drivetypes[i].length)) {
2230 			continue;
2231 		}
2232 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2233 		return (1);
2234 	}
2235 	return (0);
2236 }
2237 
2238 static int
2239 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2240     struct st_drivetype *dp)
2241 {
2242 	int bsize;
2243 	ulong_t maxbsize;
2244 	caddr_t buf;
2245 	struct st_drivetype *tem_dp;
2246 	struct read_blklim *blklim;
2247 	int rval;
2248 	int i;
2249 
2250 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2251 
2252 	/*
2253 	 * Determine the type of tape controller. Type is determined by
2254 	 * sending SCSI commands to tape drive and deriving the type from
2255 	 * the returned data.
2256 	 */
2257 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2258 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2259 
2260 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2261 
2262 	/*
2263 	 * Make up a name
2264 	 */
2265 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2266 	tem_dp->name[VIDPIDLEN] = '\0';
2267 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2268 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2269 	/*
2270 	 * 'clean' vendor and product strings of non-printing chars
2271 	 */
2272 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2273 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2274 			tem_dp->name[i] = '.';
2275 		}
2276 	}
2277 
2278 	/*
2279 	 * MODE SENSE to determine block size.
2280 	 */
2281 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2282 	rval = st_modesense(un);
2283 	if (rval) {
2284 		if (rval == EACCES) {
2285 			un->un_dp->type = ST_TYPE_INVALID;
2286 			rval = 1;
2287 		} else {
2288 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2289 			rval = 0;
2290 		}
2291 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2292 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2293 		goto exit;
2294 	}
2295 
2296 	/* Can mode sense page 0x10 or 0xf */
2297 	tem_dp->options |= ST_MODE_SEL_COMP;
2298 	bsize = (un->un_mspl->high_bl << 16)	|
2299 	    (un->un_mspl->mid_bl << 8)		|
2300 	    (un->un_mspl->low_bl);
2301 
2302 	if (bsize == 0) {
2303 		tem_dp->options |= ST_VARIABLE;
2304 		tem_dp->bsize = 0;
2305 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2306 		rval = st_change_block_size(un, 0);
2307 		if (rval) {
2308 			if (rval == EACCES) {
2309 				un->un_dp->type = ST_TYPE_INVALID;
2310 				rval = 1;
2311 			} else {
2312 				rval = 0;
2313 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2314 				    "st_get_conf_from_tape_drive(): "
2315 				    "Fixed record size is too large and"
2316 				    "cannot switch to variable record size");
2317 			}
2318 			goto exit;
2319 		}
2320 		tem_dp->options |= ST_VARIABLE;
2321 	} else {
2322 		rval = st_change_block_size(un, 0);
2323 		if (rval == 0) {
2324 			tem_dp->options |= ST_VARIABLE;
2325 			tem_dp->bsize = 0;
2326 		} else if (rval != EACCES) {
2327 			tem_dp->bsize = bsize;
2328 		} else {
2329 			un->un_dp->type = ST_TYPE_INVALID;
2330 			rval = 1;
2331 			goto exit;
2332 		}
2333 	}
2334 
2335 	/*
2336 	 * If READ BLOCk LIMITS works and upper block size limit is
2337 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2338 	 */
2339 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2340 	rval = st_read_block_limits(un, blklim);
2341 	if (rval) {
2342 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2343 		    "st_get_conf_from_tape_drive(): "
2344 		    "fail to read block limits.\n");
2345 		rval = 0;
2346 		kmem_free(blklim, sizeof (struct read_blklim));
2347 		goto exit;
2348 	}
2349 	maxbsize = (blklim->max_hi << 16) +
2350 	    (blklim->max_mid << 8) + blklim->max_lo;
2351 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2352 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2353 	}
2354 	kmem_free(blklim, sizeof (struct read_blklim));
2355 
2356 	/*
2357 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2358 	 */
2359 	buf = kmem_zalloc(6, KM_SLEEP);
2360 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2361 	if (rval) {
2362 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2363 		    "st_get_conf_from_tape_drive(): "
2364 		    "fail to read vitial inquiry.\n");
2365 		rval = 0;
2366 		kmem_free(buf, 6);
2367 		goto exit;
2368 	}
2369 	if (buf[4] & 1) {
2370 		tem_dp->options |= ST_WORMABLE;
2371 	}
2372 	kmem_free(buf, 6);
2373 
2374 	/* Assume BSD BSR KNOWS_EOD */
2375 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2376 	tem_dp->max_rretries = -1;
2377 	tem_dp->max_wretries = -1;
2378 
2379 	/*
2380 	 * Decide the densities supported by tape drive by sending
2381 	 * REPORT DENSITY SUPPORT command.
2382 	 */
2383 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2384 		goto exit;
2385 	}
2386 
2387 	/*
2388 	 * Decide the timeout values for several commands by sending
2389 	 * REPORT SUPPORTED OPERATION CODES command.
2390 	 */
2391 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2392 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2393 		goto exit;
2394 	}
2395 
2396 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2397 	rval = 1;
2398 
2399 exit:
2400 	un->un_status = KEY_NO_SENSE;
2401 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2402 	return (rval);
2403 }
2404 
2405 static int
2406 st_get_densities_from_tape_drive(struct scsi_tape *un,
2407     struct st_drivetype *dp)
2408 {
2409 	int i, p;
2410 	size_t buflen;
2411 	ushort_t des_len;
2412 	uchar_t *den_header;
2413 	uchar_t num_den;
2414 	uchar_t den[NDENSITIES];
2415 	uchar_t deflt[NDENSITIES];
2416 	struct report_density_desc *den_desc;
2417 
2418 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2419 
2420 	/*
2421 	 * Since we have no idea how many densitiy support entries
2422 	 * will be returned, we send the command firstly assuming
2423 	 * there is only one. Then we can decide the number of
2424 	 * entries by available density support length. If multiple
2425 	 * entries exist, we will resend the command with enough
2426 	 * buffer size.
2427 	 */
2428 	buflen = sizeof (struct report_density_header) +
2429 	    sizeof (struct report_density_desc);
2430 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2431 	if (st_report_density_support(un, den_header, buflen) != 0) {
2432 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2433 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2434 		kmem_free(den_header, buflen);
2435 		return (0);
2436 	}
2437 	des_len =
2438 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2439 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2440 
2441 	if (num_den > 1) {
2442 		kmem_free(den_header, buflen);
2443 		buflen = sizeof (struct report_density_header) +
2444 		    sizeof (struct report_density_desc) * num_den;
2445 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2446 		if (st_report_density_support(un, den_header, buflen) != 0) {
2447 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2448 			    "st_get_conf_from_tape_drive(): "
2449 			    "fail to report density.\n");
2450 			kmem_free(den_header, buflen);
2451 			return (0);
2452 		}
2453 	}
2454 
2455 	den_desc = (struct report_density_desc *)(den_header
2456 	    + sizeof (struct report_density_header));
2457 
2458 	/*
2459 	 * Decide the drive type by assigning organization
2460 	 */
2461 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2462 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2463 		    8) == 0) {
2464 			dp->type = st_vid_dt[i].type;
2465 			break;
2466 		}
2467 	}
2468 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2469 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2470 		    "st_get_conf_from_tape_drive(): "
2471 		    "can't find match of assigned ort.\n");
2472 		kmem_free(den_header, buflen);
2473 		return (0);
2474 	}
2475 
2476 	/*
2477 	 * The tape drive may support many tape formats, but the st driver
2478 	 * supports only the four highest densities. Since density code
2479 	 * values are returned by ascending sequence, we start from the
2480 	 * last entry of density support data block descriptor.
2481 	 */
2482 	p = 0;
2483 	den_desc += num_den - 1;
2484 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2485 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2486 			if (p != 0) {
2487 				if (den_desc->pri_den >= den[p - 1]) {
2488 					continue;
2489 				}
2490 			}
2491 			den[p] = den_desc->pri_den;
2492 			deflt[p] = den_desc->deflt;
2493 			p ++;
2494 		}
2495 	}
2496 
2497 	switch (p) {
2498 	case 0:
2499 		bzero(dp->densities, NDENSITIES);
2500 		dp->options |= ST_AUTODEN_OVERRIDE;
2501 		dp->default_density = MT_DENSITY4;
2502 		break;
2503 
2504 	case 1:
2505 		(void) memset(dp->densities, den[0], NDENSITIES);
2506 		dp->options |= ST_AUTODEN_OVERRIDE;
2507 		dp->default_density = MT_DENSITY4;
2508 		break;
2509 
2510 	case 2:
2511 		dp->densities[0] = den[1];
2512 		dp->densities[1] = den[1];
2513 		dp->densities[2] = den[0];
2514 		dp->densities[3] = den[0];
2515 		if (deflt[0]) {
2516 			dp->default_density = MT_DENSITY4;
2517 		} else {
2518 			dp->default_density = MT_DENSITY2;
2519 		}
2520 		break;
2521 
2522 	case 3:
2523 		dp->densities[0] = den[2];
2524 		dp->densities[1] = den[1];
2525 		dp->densities[2] = den[0];
2526 		dp->densities[3] = den[0];
2527 		if (deflt[0]) {
2528 			dp->default_density = MT_DENSITY4;
2529 		} else if (deflt[1]) {
2530 			dp->default_density = MT_DENSITY2;
2531 		} else {
2532 			dp->default_density = MT_DENSITY1;
2533 		}
2534 		break;
2535 
2536 	default:
2537 		for (i = p; i > p - NDENSITIES; i --) {
2538 			dp->densities[i - 1] = den[p - i];
2539 		}
2540 		if (deflt[0]) {
2541 			dp->default_density = MT_DENSITY4;
2542 		} else if (deflt[1]) {
2543 			dp->default_density = MT_DENSITY3;
2544 		} else if (deflt[2]) {
2545 			dp->default_density = MT_DENSITY2;
2546 		} else {
2547 			dp->default_density = MT_DENSITY1;
2548 		}
2549 		break;
2550 	}
2551 
2552 	bzero(dp->mediatype, NDENSITIES);
2553 
2554 	kmem_free(den_header, buflen);
2555 	return (1);
2556 }
2557 
2558 static int
2559 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2560     struct st_drivetype *dp)
2561 {
2562 	ushort_t timeout;
2563 	int rval;
2564 
2565 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2566 
2567 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2568 	if (rval) {
2569 		if (rval == EACCES) {
2570 			un->un_dp->type = ST_TYPE_INVALID;
2571 			dp->type = ST_TYPE_INVALID;
2572 			return (1);
2573 		}
2574 		return (0);
2575 	}
2576 	dp->erase_timeout = timeout;
2577 
2578 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2579 	if (rval) {
2580 		if (rval == EACCES) {
2581 			un->un_dp->type = ST_TYPE_INVALID;
2582 			dp->type = ST_TYPE_INVALID;
2583 			return (1);
2584 		}
2585 		return (0);
2586 	}
2587 	dp->io_timeout = timeout;
2588 
2589 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2590 	if (rval) {
2591 		if (rval == EACCES) {
2592 			un->un_dp->type = ST_TYPE_INVALID;
2593 			dp->type = ST_TYPE_INVALID;
2594 			return (1);
2595 		}
2596 		return (0);
2597 	}
2598 	dp->io_timeout = max(dp->io_timeout, timeout);
2599 
2600 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2601 	if (rval) {
2602 		if (rval == EACCES) {
2603 			un->un_dp->type = ST_TYPE_INVALID;
2604 			dp->type = ST_TYPE_INVALID;
2605 			return (1);
2606 		}
2607 		return (0);
2608 	}
2609 	dp->space_timeout = timeout;
2610 
2611 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2612 	if (rval) {
2613 		if (rval == EACCES) {
2614 			un->un_dp->type = ST_TYPE_INVALID;
2615 			dp->type = ST_TYPE_INVALID;
2616 			return (1);
2617 		}
2618 		return (0);
2619 	}
2620 	dp->load_timeout = timeout;
2621 	dp->unload_timeout = timeout;
2622 
2623 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2624 	if (rval) {
2625 		if (rval == EACCES) {
2626 			un->un_dp->type = ST_TYPE_INVALID;
2627 			dp->type = ST_TYPE_INVALID;
2628 			return (1);
2629 		}
2630 		return (0);
2631 	}
2632 	dp->rewind_timeout = timeout;
2633 
2634 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2635 	if (rval) {
2636 		if (rval == EACCES) {
2637 			un->un_dp->type = ST_TYPE_INVALID;
2638 			dp->type = ST_TYPE_INVALID;
2639 			return (1);
2640 		}
2641 		return (0);
2642 	}
2643 	dp->non_motion_timeout = timeout;
2644 
2645 	return (1);
2646 }
2647 
2648 static int
2649 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2650     ushort_t *timeout_value, ushort_t service_action)
2651 {
2652 	uchar_t *timeouts;
2653 	uchar_t *oper;
2654 	uchar_t support;
2655 	uchar_t cdbsize;
2656 	uchar_t ctdp;
2657 	size_t buflen;
2658 	int rval;
2659 
2660 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2661 
2662 	buflen = sizeof (struct one_com_des) +
2663 	    sizeof (struct com_timeout_des);
2664 	oper = kmem_zalloc(buflen, KM_SLEEP);
2665 	rval = st_report_supported_operation(un, oper, option_code,
2666 	    service_action);
2667 
2668 	if (rval) {
2669 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2670 		    "st_get_timeouts_value(): "
2671 		    "fail to timeouts value for command %d.\n", option_code);
2672 		kmem_free(oper, buflen);
2673 		return (rval);
2674 	}
2675 
2676 	support = ((struct one_com_des *)oper)->support;
2677 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2678 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2679 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2680 		    "st_get_timeouts_value(): "
2681 		    "command %d is not supported.\n", option_code);
2682 		kmem_free(oper, buflen);
2683 		return (ENOTSUP);
2684 	}
2685 
2686 	ctdp = ((struct one_com_des *)oper)->ctdp;
2687 	if (!ctdp) {
2688 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2689 		    "st_get_timeouts_value(): "
2690 		    "command timeout is not included.\n");
2691 		kmem_free(oper, buflen);
2692 		return (ENOTSUP);
2693 	}
2694 
2695 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2696 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2697 
2698 	/*
2699 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2700 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2701 	 * to 0xFFFF.
2702 	 */
2703 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2704 		*timeout_value = USHRT_MAX;
2705 	} else {
2706 		*timeout_value = ((*(timeouts + 10)) << 8) |
2707 		    (*(timeouts + 11));
2708 	}
2709 
2710 	kmem_free(oper, buflen);
2711 	return (0);
2712 }
2713 
2714 static int
2715 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2716 {
2717 	int i;
2718 
2719 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2720 
2721 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2722 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2723 
2724 	/*
2725 	 * Make up a name
2726 	 */
2727 	bcopy("Vendor '", dp->name, 8);
2728 	bcopy(vidpid, &dp->name[8], VIDLEN);
2729 	bcopy("' Product '", &dp->name[16], 11);
2730 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2731 	dp->name[ST_NAMESIZE - 2] = '\'';
2732 	dp->name[ST_NAMESIZE - 1] = '\0';
2733 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2734 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2735 	/*
2736 	 * 'clean' vendor and product strings of non-printing chars
2737 	 */
2738 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2739 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2740 			dp->name[i] = '.';
2741 		}
2742 	}
2743 	dp->type = ST_TYPE_INVALID;
2744 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2745 
2746 	return (1); /* Can Not Fail */
2747 }
2748 
2749 /*
2750  * Regular Unix Entry points
2751  */
2752 
2753 
2754 
2755 /* ARGSUSED */
2756 static int
2757 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2758 {
2759 	dev_t dev = *dev_p;
2760 	int rval = 0;
2761 
2762 	GET_SOFT_STATE(dev);
2763 
2764 	ST_ENTR(ST_DEVINFO, st_open);
2765 
2766 	/*
2767 	 * validate that we are addressing a sensible unit
2768 	 */
2769 	mutex_enter(ST_MUTEX);
2770 
2771 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2772 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2773 	    st_dev_name(dev), *dev_p, flag, otyp);
2774 
2775 	/*
2776 	 * All device accesss go thru st_strategy() where we check
2777 	 * suspend status
2778 	 */
2779 
2780 	if (!un->un_attached) {
2781 		st_known_tape_type(un);
2782 		if (!un->un_attached) {
2783 			rval = ENXIO;
2784 			goto exit;
2785 		}
2786 
2787 	}
2788 
2789 	/*
2790 	 * Check for the case of the tape in the middle of closing.
2791 	 * This isn't simply a check of the current state, because
2792 	 * we could be in state of sensing with the previous state
2793 	 * that of closing.
2794 	 *
2795 	 * And don't allow multiple opens.
2796 	 */
2797 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2798 		un->un_laststate = un->un_state;
2799 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2800 		while (IS_CLOSING(un) ||
2801 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2802 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2803 				rval = EINTR;
2804 				un->un_state = un->un_laststate;
2805 				goto exit;
2806 			}
2807 		}
2808 	} else if (un->un_state != ST_STATE_CLOSED) {
2809 		rval = EBUSY;
2810 		goto busy;
2811 	}
2812 
2813 	/*
2814 	 * record current dev
2815 	 */
2816 	un->un_dev = dev;
2817 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2818 	un->un_errno = 0;	/* no errors yet */
2819 	un->un_restore_pos = 0;
2820 	un->un_rqs_state = 0;
2821 
2822 	/*
2823 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2824 	 * anything, leave internal states alone, if fileno >= 0
2825 	 */
2826 	if (flag & (FNDELAY | FNONBLOCK)) {
2827 		switch (un->un_pos.pmode) {
2828 
2829 		case invalid:
2830 			un->un_state = ST_STATE_OFFLINE;
2831 			break;
2832 
2833 		case legacy:
2834 			/*
2835 			 * If position is anything other than rewound.
2836 			 */
2837 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2838 				/*
2839 				 * set un_read_only/write-protect status.
2840 				 *
2841 				 * If the tape is not bot we can assume
2842 				 * that mspl->wp_status is set properly.
2843 				 * else
2844 				 * we need to do a mode sense/Tur once
2845 				 * again to get the actual tape status.(since
2846 				 * user might have replaced the tape)
2847 				 * Hence make the st state OFFLINE so that
2848 				 * we re-intialize the tape once again.
2849 				 */
2850 				un->un_read_only =
2851 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2852 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2853 			} else {
2854 				un->un_state = ST_STATE_OFFLINE;
2855 			}
2856 			break;
2857 		case logical:
2858 			if (un->un_pos.lgclblkno == 0) {
2859 				un->un_state = ST_STATE_OFFLINE;
2860 			} else {
2861 				un->un_read_only =
2862 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2863 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2864 			}
2865 			break;
2866 		}
2867 		rval = 0;
2868 	} else {
2869 		/*
2870 		 * Not opening O_NDELAY.
2871 		 */
2872 		un->un_state = ST_STATE_OPENING;
2873 
2874 		/*
2875 		 * Clear error entry stack
2876 		 */
2877 		st_empty_error_stack(un);
2878 
2879 		rval = st_tape_init(un);
2880 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2881 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2882 			rval = 0; /* so open doesn't fail */
2883 		} else if (rval) {
2884 			/*
2885 			 * Release the tape unit, if reserved and not
2886 			 * preserve reserve.
2887 			 */
2888 			if ((un->un_rsvd_status &
2889 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2890 				(void) st_reserve_release(un, ST_RELEASE,
2891 				    st_uscsi_cmd);
2892 			}
2893 		} else {
2894 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2895 		}
2896 	}
2897 
2898 exit:
2899 	/*
2900 	 * we don't want any uninvited guests scrogging our data when we're
2901 	 * busy with something, so for successful opens or failed opens
2902 	 * (except for EBUSY), reset these counters and state appropriately.
2903 	 */
2904 	if (rval != EBUSY) {
2905 		if (rval) {
2906 			un->un_state = ST_STATE_CLOSED;
2907 		}
2908 		un->un_err_resid = 0;
2909 		un->un_retry_ct = 0;
2910 	}
2911 busy:
2912 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2913 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2914 	mutex_exit(ST_MUTEX);
2915 	return (rval);
2916 
2917 }
2918 
2919 static int
2920 st_tape_init(struct scsi_tape *un)
2921 {
2922 	int err;
2923 	int rval = 0;
2924 
2925 	ST_FUNC(ST_DEVINFO, st_tape_init);
2926 
2927 	ASSERT(mutex_owned(ST_MUTEX));
2928 
2929 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2930 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2931 
2932 	/*
2933 	 * Clean up after any errors left by 'last' close.
2934 	 * This also handles the case of the initial open.
2935 	 */
2936 	if (un->un_state != ST_STATE_INITIALIZING) {
2937 		un->un_laststate = un->un_state;
2938 		un->un_state = ST_STATE_OPENING;
2939 	}
2940 
2941 	un->un_kbytes_xferred = 0;
2942 
2943 	/*
2944 	 * do a throw away TUR to clear check condition
2945 	 */
2946 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2947 
2948 	/*
2949 	 * If test unit ready fails because the drive is reserved
2950 	 * by another host fail the open for no access.
2951 	 */
2952 	if (err) {
2953 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2954 			un->un_state = ST_STATE_CLOSED;
2955 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2956 			    "st_tape_init: RESERVATION CONFLICT\n");
2957 			rval = EACCES;
2958 			goto exit;
2959 		} else if ((un->un_rsvd_status &
2960 		    ST_APPLICATION_RESERVATIONS) != 0) {
2961 			if ((ST_RQSENSE != NULL) &&
2962 			    (ST_RQSENSE->es_add_code == 0x2a &&
2963 			    ST_RQSENSE->es_qual_code == 0x03)) {
2964 				un->un_state = ST_STATE_CLOSED;
2965 				rval = EACCES;
2966 				goto exit;
2967 			}
2968 		}
2969 	}
2970 
2971 	/*
2972 	 * Tape self identification could fail if the tape drive is used by
2973 	 * another host during attach time. We try to get the tape type
2974 	 * again. This is also applied to any posponed configuration methods.
2975 	 */
2976 	if (un->un_dp->type == ST_TYPE_INVALID) {
2977 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2978 		st_known_tape_type(un);
2979 	}
2980 
2981 	/*
2982 	 * If the tape type is still invalid, try to determine the generic
2983 	 * configuration.
2984 	 */
2985 	if (un->un_dp->type == ST_TYPE_INVALID) {
2986 		rval = st_determine_generic(un);
2987 		if (rval) {
2988 			if (rval != EACCES) {
2989 				rval = EIO;
2990 			}
2991 			un->un_state = ST_STATE_CLOSED;
2992 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2993 			    "st_tape_init: %s invalid type\n",
2994 			    rval == EACCES ? "EACCES" : "EIO");
2995 			goto exit;
2996 		}
2997 		/*
2998 		 * If this is a Unknown Type drive,
2999 		 * Use the READ BLOCK LIMITS to determine if
3000 		 * allow large xfer is approprate if not globally
3001 		 * disabled with st_allow_large_xfer.
3002 		 */
3003 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3004 	} else {
3005 
3006 		/*
3007 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3008 		 * the max block size supported by the drive,
3009 		 * find it by issueing a READ_BLKLIM command.
3010 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3011 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3012 		 */
3013 		un->un_allow_large_xfer = st_allow_large_xfer &&
3014 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3015 	}
3016 	/*
3017 	 * if maxbsize is unknown, set the maximum block size.
3018 	 */
3019 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3020 
3021 		/*
3022 		 * Get the Block limits of the tape drive.
3023 		 * if un->un_allow_large_xfer = 0 , then make sure
3024 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3025 		 */
3026 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3027 
3028 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3029 		if (err) {
3030 			/* Retry */
3031 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3032 		}
3033 		if (!err) {
3034 
3035 			/*
3036 			 * if cmd successful, use limit returned
3037 			 */
3038 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3039 			    (un->un_rbl->max_mid << 8) +
3040 			    un->un_rbl->max_lo;
3041 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3042 			    un->un_rbl->min_lo;
3043 			un->un_data_mod = 1 << un->un_rbl->granularity;
3044 			if ((un->un_maxbsize == 0) ||
3045 			    (un->un_allow_large_xfer == 0 &&
3046 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3047 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3048 
3049 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3050 				/*
3051 				 * Drive is not one that is configured, But the
3052 				 * READ BLOCK LIMITS tells us it can do large
3053 				 * xfers.
3054 				 */
3055 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3056 					un->un_dp->options |=
3057 					    ST_NO_RECSIZE_LIMIT;
3058 				}
3059 				/*
3060 				 * If max and mimimum block limits are the
3061 				 * same this is a fixed block size device.
3062 				 */
3063 				if (un->un_maxbsize == un->un_minbsize) {
3064 					un->un_dp->options &= ~ST_VARIABLE;
3065 				}
3066 			}
3067 
3068 			if (un->un_minbsize == 0) {
3069 				un->un_minbsize = 1;
3070 			}
3071 
3072 		} else { /* error on read block limits */
3073 
3074 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3075 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3076 			    " errno = %d un_rsvd_status = 0x%X\n",
3077 			    err, un->un_rsvd_status);
3078 
3079 			/*
3080 			 * since read block limits cmd failed,
3081 			 * do not allow large xfers.
3082 			 * use old values in st_minphys
3083 			 */
3084 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3085 				rval = EACCES;
3086 			} else {
3087 				un->un_allow_large_xfer = 0;
3088 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3089 				    "!Disabling large transfers\n");
3090 
3091 				/*
3092 				 * we guess maxbsize and minbsize
3093 				 */
3094 				if (un->un_bsize) {
3095 					un->un_maxbsize = un->un_minbsize =
3096 					    un->un_bsize;
3097 				} else {
3098 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3099 					un->un_minbsize = 1;
3100 				}
3101 				/*
3102 				 * Data Mod must be set,
3103 				 * Even if read block limits fails.
3104 				 * Prevents Divide By Zero in st_rw().
3105 				 */
3106 				un->un_data_mod = 1;
3107 			}
3108 		}
3109 		if (un->un_rbl) {
3110 			kmem_free(un->un_rbl, RBLSIZE);
3111 			un->un_rbl = NULL;
3112 		}
3113 
3114 		if (rval) {
3115 			goto exit;
3116 		}
3117 	}
3118 
3119 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3120 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3121 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3122 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3123 
3124 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3125 
3126 	if (err != 0) {
3127 		if (err == EINTR) {
3128 			un->un_laststate = un->un_state;
3129 			un->un_state = ST_STATE_CLOSED;
3130 			rval = EINTR;
3131 			goto exit;
3132 		}
3133 		/*
3134 		 * Make sure the tape is ready
3135 		 */
3136 		un->un_pos.pmode = invalid;
3137 		if (un->un_status != KEY_UNIT_ATTENTION) {
3138 			/*
3139 			 * allow open no media.  Subsequent MTIOCSTATE
3140 			 * with media present will complete the open
3141 			 * logic.
3142 			 */
3143 			un->un_laststate = un->un_state;
3144 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3145 				un->un_mediastate = MTIO_EJECTED;
3146 				un->un_state = ST_STATE_OFFLINE;
3147 				rval = 0;
3148 				goto exit;
3149 			} else {
3150 				un->un_state = ST_STATE_CLOSED;
3151 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3152 				    "st_tape_init EIO no media, not opened "
3153 				    "O_NONBLOCK|O_EXCL\n");
3154 				rval = EIO;
3155 				goto exit;
3156 			}
3157 		}
3158 	}
3159 
3160 	/*
3161 	 * On each open, initialize block size from drivetype struct,
3162 	 * as it could have been changed by MTSRSZ ioctl.
3163 	 * Now, ST_VARIABLE simply means drive is capable of variable
3164 	 * mode. All drives are assumed to support fixed records.
3165 	 * Hence, un_bsize tells what mode the drive is in.
3166 	 *	un_bsize	= 0	- variable record length
3167 	 *			= x	- fixed record length is x
3168 	 */
3169 	un->un_bsize = un->un_dp->bsize;
3170 
3171 	/*
3172 	 * If saved position is valid go there
3173 	 */
3174 	if (un->un_restore_pos) {
3175 		un->un_restore_pos = 0;
3176 		un->un_pos.fileno = un->un_save_fileno;
3177 		un->un_pos.blkno = un->un_save_blkno;
3178 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3179 		if (rval != 0) {
3180 			if (rval != EACCES) {
3181 				rval = EIO;
3182 			}
3183 			un->un_laststate = un->un_state;
3184 			un->un_state = ST_STATE_CLOSED;
3185 			goto exit;
3186 		}
3187 	}
3188 
3189 	if (un->un_pos.pmode == invalid) {
3190 		rval = st_loadtape(un);
3191 		if (rval) {
3192 			if (rval != EACCES) {
3193 				rval = EIO;
3194 			}
3195 			un->un_laststate = un->un_state;
3196 			un->un_state = ST_STATE_CLOSED;
3197 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3198 			    "st_tape_init: %s can't open tape\n",
3199 			    rval == EACCES ? "EACCES" : "EIO");
3200 			goto exit;
3201 		}
3202 	}
3203 
3204 	/*
3205 	 * do a mode sense to pick up state of current write-protect,
3206 	 * Could cause reserve and fail due to conflict.
3207 	 */
3208 	if (un->un_unit_attention_flags) {
3209 		rval = st_modesense(un);
3210 		if (rval == EACCES) {
3211 			goto exit;
3212 		}
3213 	}
3214 
3215 	/*
3216 	 * If we are opening the tape for writing, check
3217 	 * to make sure that the tape can be written.
3218 	 */
3219 	if (un->un_oflags & FWRITE) {
3220 		err = 0;
3221 		if (un->un_mspl->wp) {
3222 			un->un_status = KEY_WRITE_PROTECT;
3223 			un->un_laststate = un->un_state;
3224 			un->un_state = ST_STATE_CLOSED;
3225 			rval = EACCES;
3226 			/*
3227 			 * STK sets the wp bit if volsafe tape is loaded.
3228 			 */
3229 			if ((un->un_dp->type == MT_ISSTK9840) &&
3230 			    (un->un_dp->options & ST_WORMABLE)) {
3231 				un->un_read_only = RDONLY;
3232 			} else {
3233 				goto exit;
3234 			}
3235 		} else {
3236 			un->un_read_only = RDWR;
3237 		}
3238 	} else {
3239 		un->un_read_only = RDONLY;
3240 	}
3241 
3242 	if (un->un_dp->options & ST_WORMABLE &&
3243 	    un->un_unit_attention_flags) {
3244 		un->un_read_only |= un->un_wormable(un);
3245 
3246 		if (((un->un_read_only == WORM) ||
3247 		    (un->un_read_only == RDWORM)) &&
3248 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3249 			un->un_status = KEY_DATA_PROTECT;
3250 			rval = EACCES;
3251 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3252 			    "read_only = %d eof = %d oflag = %d\n",
3253 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3254 		}
3255 	}
3256 
3257 	/*
3258 	 * If we're opening the tape write-only, we need to
3259 	 * write 2 filemarks on the HP 1/2 inch drive, to
3260 	 * create a null file.
3261 	 */
3262 	if ((un->un_read_only == RDWR) ||
3263 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3264 		if (un->un_dp->options & ST_REEL) {
3265 			un->un_fmneeded = 2;
3266 		} else {
3267 			un->un_fmneeded = 1;
3268 		}
3269 	} else {
3270 		un->un_fmneeded = 0;
3271 	}
3272 
3273 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3274 	    "fmneeded = %x\n", un->un_fmneeded);
3275 
3276 	/*
3277 	 * Make sure the density can be selected correctly.
3278 	 * If WORM can only write at the append point which in most cases
3279 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3280 	 * to set and try densities if a BOP.
3281 	 */
3282 	if (st_determine_density(un,
3283 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3284 		un->un_status = KEY_ILLEGAL_REQUEST;
3285 		un->un_laststate = un->un_state;
3286 		un->un_state = ST_STATE_CLOSED;
3287 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3288 		    "st_tape_init: EIO can't determine density\n");
3289 		rval = EIO;
3290 		goto exit;
3291 	}
3292 
3293 	/*
3294 	 * Destroy the knowledge that we have 'determined'
3295 	 * density so that a later read at BOT comes along
3296 	 * does the right density determination.
3297 	 */
3298 
3299 	un->un_density_known = 0;
3300 
3301 
3302 	/*
3303 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3304 	 * Mark the state such that any I/O or tape space operations
3305 	 * will get/set the right density, etc..
3306 	 */
3307 	un->un_laststate = un->un_state;
3308 	un->un_lastop = ST_OP_NIL;
3309 	un->un_mediastate = MTIO_INSERTED;
3310 	cv_broadcast(&un->un_state_cv);
3311 
3312 	/*
3313 	 *  Set test append flag if writing.
3314 	 *  First write must check that tape is positioned correctly.
3315 	 */
3316 	un->un_test_append = (un->un_oflags & FWRITE);
3317 
3318 	/*
3319 	 * if there are pending unit attention flags.
3320 	 * Check that the media has not changed.
3321 	 */
3322 	if (un->un_unit_attention_flags) {
3323 		rval = st_get_media_identification(un, st_uscsi_cmd);
3324 		if (rval != 0 && rval != EACCES) {
3325 			rval = EIO;
3326 		}
3327 		un->un_unit_attention_flags = 0;
3328 	}
3329 
3330 exit:
3331 	un->un_err_resid = 0;
3332 	un->un_last_resid = 0;
3333 	un->un_last_count = 0;
3334 
3335 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3336 	    "st_tape_init: return val = %x\n", rval);
3337 	return (rval);
3338 
3339 }
3340 
3341 
3342 
3343 /* ARGSUSED */
3344 static int
3345 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3346 {
3347 	int err = 0;
3348 	int count, last_state;
3349 	minor_t minor = getminor(dev);
3350 #ifdef	__x86
3351 	struct contig_mem *cp, *cp_temp;
3352 #endif
3353 
3354 	GET_SOFT_STATE(dev);
3355 
3356 	ST_ENTR(ST_DEVINFO, st_close);
3357 
3358 	/*
3359 	 * wait till all cmds in the pipeline have been completed
3360 	 */
3361 	mutex_enter(ST_MUTEX);
3362 
3363 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3364 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3365 
3366 	st_wait_for_io(un);
3367 
3368 	/* turn off persistent errors on close, as we want close to succeed */
3369 	st_turn_pe_off(un);
3370 
3371 	/*
3372 	 * set state to indicate that we are in process of closing
3373 	 */
3374 	last_state = un->un_laststate = un->un_state;
3375 	un->un_state = ST_STATE_CLOSING;
3376 
3377 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3378 
3379 	/*
3380 	 * BSD behavior:
3381 	 * a close always causes a silent span to the next file if we've hit
3382 	 * an EOF (but not yet read across it).
3383 	 */
3384 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3385 		if (un->un_pos.pmode != invalid) {
3386 			un->un_pos.fileno++;
3387 			un->un_pos.blkno = 0;
3388 		}
3389 		un->un_pos.eof = ST_NO_EOF;
3390 	}
3391 
3392 	/*
3393 	 * SVR4 behavior for skipping to next file:
3394 	 *
3395 	 * If we have not seen a filemark, space to the next file
3396 	 *
3397 	 * If we have already seen the filemark we are physically in the next
3398 	 * file and we only increment the filenumber
3399 	 */
3400 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3401 	    (flag & FREAD) &&		/* reading or at least asked to */
3402 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3403 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3404 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3405 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3406 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3407 		switch (un->un_pos.eof) {
3408 		case ST_NO_EOF:
3409 			/*
3410 			 * if we were reading and did not read the complete file
3411 			 * skip to the next file, leaving the tape correctly
3412 			 * positioned to read the first record of the next file
3413 			 * Check first for REEL if we are at EOT by trying to
3414 			 * read a block
3415 			 */
3416 			if ((un->un_dp->options & ST_REEL) &&
3417 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3418 			    (un->un_pos.blkno == 0)) {
3419 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3420 					ST_DEBUG2(ST_DEVINFO, st_label,
3421 					    SCSI_DEBUG,
3422 					    "st_close : EIO can't space\n");
3423 					err = EIO;
3424 					goto error_out;
3425 				}
3426 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3427 					un->un_pos.eof = ST_EOT_PENDING;
3428 					un->un_pos.fileno += 1;
3429 					un->un_pos.blkno   = 0;
3430 					break;
3431 				}
3432 			}
3433 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3434 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3435 				    "st_close: EIO can't space #2\n");
3436 				err = EIO;
3437 				goto error_out;
3438 			} else {
3439 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3440 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3441 				    un->un_pos.fileno, un->un_pos.blkno,
3442 				    un->un_pos.eof);
3443 				un->un_pos.eof = ST_NO_EOF;
3444 			}
3445 			break;
3446 
3447 		case ST_EOF_PENDING:
3448 		case ST_EOF:
3449 			un->un_pos.fileno += 1;
3450 			un->un_pos.lgclblkno += 1;
3451 			un->un_pos.blkno   = 0;
3452 			un->un_pos.eof = ST_NO_EOF;
3453 			break;
3454 
3455 		case ST_EOT:
3456 		case ST_EOT_PENDING:
3457 		case ST_EOM:
3458 			/* nothing to do */
3459 			break;
3460 		default:
3461 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3462 			    "Undefined state 0x%x", un->un_pos.eof);
3463 
3464 		}
3465 	}
3466 
3467 
3468 	/*
3469 	 * For performance reasons (HP 88780), the driver should
3470 	 * postpone writing the second tape mark until just before a file
3471 	 * positioning ioctl is issued (e.g., rewind).	This means that
3472 	 * the user must not manually rewind the tape because the tape will
3473 	 * be missing the second tape mark which marks EOM.
3474 	 * However, this small performance improvement is not worth the risk.
3475 	 */
3476 
3477 	/*
3478 	 * We need to back up over the filemark we inadvertently popped
3479 	 * over doing a read in between the two filemarks that constitute
3480 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3481 	 * set while reading.
3482 	 *
3483 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3484 	 * the writing of filemark(s) will clear the ST_EOM state, which
3485 	 * we don't want, so we save this state and restore it later.
3486 	 */
3487 
3488 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3489 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3490 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3491 
3492 	if (un->un_pos.eof == ST_EOT_PENDING) {
3493 		if (minor & MT_NOREWIND) {
3494 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3495 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3496 				    "st_close: EIO can't space #3\n");
3497 				err = EIO;
3498 				goto error_out;
3499 			} else {
3500 				un->un_pos.blkno = 0;
3501 				un->un_pos.eof = ST_EOT;
3502 			}
3503 		} else {
3504 			un->un_pos.eof = ST_NO_EOF;
3505 		}
3506 
3507 	/*
3508 	 * Do we need to write a file mark?
3509 	 *
3510 	 * only write filemarks if there are fmks to be written and
3511 	 *   - open for write (possibly read/write)
3512 	 *   - the last operation was a write
3513 	 * or:
3514 	 *   -	opened for wronly
3515 	 *   -	no data was written
3516 	 */
3517 	} else if ((un->un_pos.pmode != invalid) &&
3518 	    (un->un_fmneeded > 0) &&
3519 	    (((flag & FWRITE) &&
3520 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3521 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3522 
3523 		/* save ST_EOM state */
3524 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3525 
3526 		/*
3527 		 * Note that we will write a filemark if we had opened
3528 		 * the tape write only and no data was written, thus
3529 		 * creating a null file.
3530 		 *
3531 		 * If the user already wrote one, we only have to write 1 more.
3532 		 * If they wrote two, we don't have to write any.
3533 		 */
3534 
3535 		count = un->un_fmneeded;
3536 		if (count > 0) {
3537 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3538 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3539 				    "st_close : EIO can't wfm\n");
3540 				err = EIO;
3541 				goto error_out;
3542 			}
3543 			if ((un->un_dp->options & ST_REEL) &&
3544 			    (minor & MT_NOREWIND)) {
3545 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3546 					ST_DEBUG2(ST_DEVINFO, st_label,
3547 					    SCSI_DEBUG,
3548 					    "st_close : EIO space fmk(-1)\n");
3549 					err = EIO;
3550 					goto error_out;
3551 				}
3552 				un->un_pos.eof = ST_NO_EOF;
3553 				/* fix up block number */
3554 				un->un_pos.blkno = 0;
3555 			}
3556 		}
3557 
3558 		/*
3559 		 * If we aren't going to be rewinding, and we were at
3560 		 * physical eot, restore the state that indicates we
3561 		 * are at physical eot. Once you have reached physical
3562 		 * eot, and you close the tape, the only thing you can
3563 		 * do on the next open is to rewind. Access to trailer
3564 		 * records is only allowed without closing the device.
3565 		 */
3566 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3567 			un->un_pos.eof = ST_EOM;
3568 		}
3569 	}
3570 
3571 	/*
3572 	 * report soft errors if enabled and available, if we never accessed
3573 	 * the drive, don't get errors. This will prevent some DAT error
3574 	 * messages upon LOG SENSE.
3575 	 */
3576 	if (st_report_soft_errors_on_close &&
3577 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3578 	    (last_state != ST_STATE_OFFLINE)) {
3579 		if (st_report_soft_errors(dev, flag)) {
3580 			err = EIO;
3581 			goto error_out;
3582 		}
3583 	}
3584 
3585 
3586 	/*
3587 	 * Do we need to rewind? Can we rewind?
3588 	 */
3589 	if ((minor & MT_NOREWIND) == 0 &&
3590 	    un->un_pos.pmode != invalid && err == 0) {
3591 		/*
3592 		 * We'd like to rewind with the
3593 		 * 'immediate' bit set, but this
3594 		 * causes problems on some drives
3595 		 * where subsequent opens get a
3596 		 * 'NOT READY' error condition
3597 		 * back while the tape is rewinding,
3598 		 * which is impossible to distinguish
3599 		 * from the condition of 'no tape loaded'.
3600 		 *
3601 		 * Also, for some targets, if you disconnect
3602 		 * with the 'immediate' bit set, you don't
3603 		 * actually return right away, i.e., the
3604 		 * target ignores your request for immediate
3605 		 * return.
3606 		 *
3607 		 * Instead, we'll fire off an async rewind
3608 		 * command. We'll mark the device as closed,
3609 		 * and any subsequent open will stall on
3610 		 * the first TEST_UNIT_READY until the rewind
3611 		 * completes.
3612 		 */
3613 
3614 		/*
3615 		 * Used to be if reserve was not supported we'd send an
3616 		 * asynchronious rewind. Comments above may be slightly invalid
3617 		 * as the immediate bit was never set. Doing an immedate rewind
3618 		 * makes sense, I think fixes to not ready status might handle
3619 		 * the problems described above.
3620 		 */
3621 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3622 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3623 				err = EIO;
3624 			}
3625 		} else {
3626 			/* flush data for older drives per scsi spec. */
3627 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3628 				err = EIO;
3629 			} else {
3630 				/* release the drive before rewind immediate */
3631 				if ((un->un_rsvd_status &
3632 				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3633 				    ST_RESERVE) {
3634 					if (st_reserve_release(un, ST_RELEASE,
3635 					    st_uscsi_cmd)) {
3636 						err = EIO;
3637 					}
3638 				}
3639 
3640 				/* send rewind with immediate bit set */
3641 				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3642 					err = EIO;
3643 				}
3644 			}
3645 		}
3646 		/*
3647 		 * Setting positions invalid in case the rewind doesn't
3648 		 * happen. Drives don't like to rewind if resets happen
3649 		 * they will tend to move back to where the rewind was
3650 		 * issued if a reset or something happens so that if a
3651 		 * write happens the data doesn't get clobbered.
3652 		 *
3653 		 * Not a big deal if the position is invalid when the
3654 		 * open occures it will do a read position.
3655 		 */
3656 		un->un_pos.pmode = invalid;
3657 		un->un_running.pmode = invalid;
3658 
3659 		if (err == EIO) {
3660 			goto error_out;
3661 		}
3662 	}
3663 
3664 	/*
3665 	 * eject tape if necessary
3666 	 */
3667 	if (un->un_eject_tape_on_failure) {
3668 		un->un_eject_tape_on_failure = 0;
3669 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3670 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3671 			    "st_close : can't unload tape\n");
3672 			err = EIO;
3673 			goto error_out;
3674 		} else {
3675 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3676 			    "st_close : tape unloaded \n");
3677 			un->un_pos.eof = ST_NO_EOF;
3678 			un->un_mediastate = MTIO_EJECTED;
3679 		}
3680 	}
3681 	/*
3682 	 * Release the tape unit, if default reserve/release
3683 	 * behaviour.
3684 	 */
3685 	if ((un->un_rsvd_status &
3686 	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3687 	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3688 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3689 	}
3690 error_out:
3691 	/*
3692 	 * clear up state
3693 	 */
3694 	un->un_laststate = un->un_state;
3695 	un->un_state = ST_STATE_CLOSED;
3696 	un->un_lastop = ST_OP_NIL;
3697 	un->un_throttle = 1;	/* assume one request at time, for now */
3698 	un->un_retry_ct = 0;
3699 	un->un_errno = 0;
3700 	un->un_swr_token = (opaque_t)NULL;
3701 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3702 
3703 	/* Restore the options to the init time settings */
3704 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3705 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3706 	} else {
3707 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3708 	}
3709 
3710 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3711 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3712 	} else {
3713 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3714 	}
3715 
3716 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3717 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3718 	} else {
3719 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3720 	}
3721 
3722 	ASSERT(mutex_owned(ST_MUTEX));
3723 
3724 	/*
3725 	 * Signal anyone awaiting a close operation to complete.
3726 	 */
3727 	cv_signal(&un->un_clscv);
3728 
3729 	/*
3730 	 * any kind of error on closing causes all state to be tossed
3731 	 */
3732 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3733 		/*
3734 		 * note that st_intr has already set
3735 		 * un_pos.pmode to invalid.
3736 		 */
3737 		un->un_density_known = 0;
3738 	}
3739 
3740 #ifdef	__x86
3741 	/*
3742 	 * free any contiguous mem alloc'ed for big block I/O
3743 	 */
3744 	cp = un->un_contig_mem;
3745 	while (cp) {
3746 		if (cp->cm_addr) {
3747 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3748 		}
3749 		cp_temp = cp;
3750 		cp = cp->cm_next;
3751 		kmem_free(cp_temp,
3752 		    sizeof (struct contig_mem) + biosize());
3753 	}
3754 	un->un_contig_mem_total_num = 0;
3755 	un->un_contig_mem_available_num = 0;
3756 	un->un_contig_mem = NULL;
3757 	un->un_max_contig_mem_len = 0;
3758 #endif
3759 
3760 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3761 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3762 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3763 
3764 	mutex_exit(ST_MUTEX);
3765 	return (err);
3766 }
3767 
3768 /*
3769  * These routines perform raw i/o operations.
3770  */
3771 
3772 /* ARGSUSED2 */
3773 static int
3774 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3775 {
3776 #ifdef STDEBUG
3777 	GET_SOFT_STATE(dev);
3778 	ST_ENTR(ST_DEVINFO, st_aread);
3779 #endif
3780 	return (st_arw(dev, aio, B_READ));
3781 }
3782 
3783 
3784 /* ARGSUSED2 */
3785 static int
3786 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3787 {
3788 #ifdef STDEBUG
3789 	GET_SOFT_STATE(dev);
3790 	ST_ENTR(ST_DEVINFO, st_awrite);
3791 #endif
3792 	return (st_arw(dev, aio, B_WRITE));
3793 }
3794 
3795 
3796 
3797 /* ARGSUSED */
3798 static int
3799 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3800 {
3801 #ifdef STDEBUG
3802 	GET_SOFT_STATE(dev);
3803 	ST_ENTR(ST_DEVINFO, st_read);
3804 #endif
3805 	return (st_rw(dev, uiop, B_READ));
3806 }
3807 
3808 /* ARGSUSED */
3809 static int
3810 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3811 {
3812 #ifdef STDEBUG
3813 	GET_SOFT_STATE(dev);
3814 	ST_ENTR(ST_DEVINFO, st_write);
3815 #endif
3816 	return (st_rw(dev, uiop, B_WRITE));
3817 }
3818 
3819 /*
3820  * Due to historical reasons, old limits are: For variable-length devices:
3821  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3822  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3823  * (let it through unmodified. For fixed-length record devices:
3824  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3825  *
3826  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3827  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3828  * command to the drive).
3829  *
3830  */
3831 static void
3832 st_minphys(struct buf *bp)
3833 {
3834 	struct scsi_tape *un;
3835 
3836 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3837 
3838 	ST_FUNC(ST_DEVINFO, st_minphys);
3839 
3840 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3841 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3842 	    bp->b_bcount);
3843 
3844 	if (un->un_allow_large_xfer) {
3845 
3846 		/*
3847 		 * check un_maxbsize for variable length devices only
3848 		 */
3849 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3850 			bp->b_bcount = un->un_maxbsize;
3851 		}
3852 		/*
3853 		 * can't go more that HBA maxdma limit in either fixed-length
3854 		 * or variable-length tape drives.
3855 		 */
3856 		if (bp->b_bcount > un->un_maxdma) {
3857 			bp->b_bcount = un->un_maxdma;
3858 		}
3859 	} else {
3860 
3861 		/*
3862 		 *  use old fixed limits
3863 		 */
3864 		if (un->un_bsize == 0) {
3865 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3866 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3867 			}
3868 		} else {
3869 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3870 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3871 			}
3872 		}
3873 	}
3874 
3875 	/*
3876 	 * For regular raw I/O and Fixed Block length devices, make sure
3877 	 * the adjusted block count is a whole multiple of the device
3878 	 * block size.
3879 	 */
3880 	if (bp != un->un_sbufp && un->un_bsize) {
3881 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3882 	}
3883 }
3884 
3885 static int
3886 st_rw(dev_t dev, struct uio *uio, int flag)
3887 {
3888 	int rval = 0;
3889 	long len;
3890 
3891 	GET_SOFT_STATE(dev);
3892 
3893 	ST_FUNC(ST_DEVINFO, st_rw);
3894 
3895 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3896 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3897 	    (flag == B_READ ? rd_str: wr_str));
3898 
3899 	/* get local copy of transfer length */
3900 	len = uio->uio_iov->iov_len;
3901 
3902 	mutex_enter(ST_MUTEX);
3903 
3904 	/*
3905 	 * Clear error entry stack
3906 	 */
3907 	st_empty_error_stack(un);
3908 
3909 	/*
3910 	 * If in fixed block size mode and requested read or write
3911 	 * is not an even multiple of that block size.
3912 	 */
3913 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3914 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3915 		    "%s: not modulo %d block size\n",
3916 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3917 		rval = EINVAL;
3918 	}
3919 
3920 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3921 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3922 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3923 		    "%s: not modulo %d device granularity\n",
3924 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3925 		rval = EINVAL;
3926 	}
3927 
3928 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3929 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3930 		rval = EFAULT;
3931 	}
3932 
3933 	if (rval != 0) {
3934 		un->un_errno = rval;
3935 		mutex_exit(ST_MUTEX);
3936 		return (rval);
3937 	}
3938 
3939 	/*
3940 	 * Reset this so it can be set if Berkeley and read over a filemark.
3941 	 */
3942 	un->un_silent_skip = 0;
3943 	mutex_exit(ST_MUTEX);
3944 
3945 	len = uio->uio_resid;
3946 
3947 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3948 	    dev, flag, st_minphys, uio);
3949 	/*
3950 	 * if we have hit logical EOT during this xfer and there is not a
3951 	 * full residue, then set eof back  to ST_EOM to make sure that
3952 	 * the user will see at least one zero write
3953 	 * after this short write
3954 	 */
3955 	mutex_enter(ST_MUTEX);
3956 	if (un->un_pos.eof > ST_NO_EOF) {
3957 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3958 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3959 	}
3960 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3961 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3962 			un->un_pos.eof = ST_EOM;
3963 		} else if (uio->uio_resid == len) {
3964 			un->un_pos.eof = ST_NO_EOF;
3965 		}
3966 	}
3967 
3968 	if (un->un_silent_skip && uio->uio_resid != len) {
3969 		un->un_pos.eof = ST_EOF;
3970 		un->un_pos.blkno = un->un_save_blkno;
3971 		un->un_pos.fileno--;
3972 	}
3973 
3974 	un->un_errno = rval;
3975 
3976 	mutex_exit(ST_MUTEX);
3977 
3978 	return (rval);
3979 }
3980 
3981 static int
3982 st_arw(dev_t dev, struct aio_req *aio, int flag)
3983 {
3984 	struct uio *uio = aio->aio_uio;
3985 	int rval = 0;
3986 	long len;
3987 
3988 	GET_SOFT_STATE(dev);
3989 
3990 	ST_FUNC(ST_DEVINFO, st_arw);
3991 
3992 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3993 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3994 	    (flag == B_READ ? rd_str: wr_str));
3995 
3996 	/* get local copy of transfer length */
3997 	len = uio->uio_iov->iov_len;
3998 
3999 	mutex_enter(ST_MUTEX);
4000 
4001 	/*
4002 	 * If in fixed block size mode and requested read or write
4003 	 * is not an even multiple of that block size.
4004 	 */
4005 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4006 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4007 		    "%s: not modulo %d block size\n",
4008 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4009 		rval = EINVAL;
4010 	}
4011 
4012 	/* If device has set granularity in the READ_BLKLIM we honor it. */
4013 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4014 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4015 		    "%s: not modulo %d device granularity\n",
4016 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4017 		rval = EINVAL;
4018 	}
4019 
4020 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4021 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4022 		rval = EFAULT;
4023 	}
4024 
4025 	if (rval != 0) {
4026 		un->un_errno = rval;
4027 		mutex_exit(ST_MUTEX);
4028 		return (rval);
4029 	}
4030 
4031 	mutex_exit(ST_MUTEX);
4032 
4033 	len = uio->uio_resid;
4034 
4035 	rval =
4036 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4037 
4038 	/*
4039 	 * if we have hit logical EOT during this xfer and there is not a
4040 	 * full residue, then set eof back  to ST_EOM to make sure that
4041 	 * the user will see at least one zero write
4042 	 * after this short write
4043 	 *
4044 	 * we keep this here just in case the application is not using
4045 	 * persistent errors
4046 	 */
4047 	mutex_enter(ST_MUTEX);
4048 	if (un->un_pos.eof > ST_NO_EOF) {
4049 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4050 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4051 	}
4052 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4053 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4054 			un->un_pos.eof = ST_EOM;
4055 		} else if (uio->uio_resid == len &&
4056 		    !(un->un_persistence && un->un_persist_errors)) {
4057 			un->un_pos.eof = ST_NO_EOF;
4058 		}
4059 	}
4060 	un->un_errno = rval;
4061 	mutex_exit(ST_MUTEX);
4062 
4063 	return (rval);
4064 }
4065 
4066 
4067 
4068 static int
4069 st_queued_strategy(buf_t *bp)
4070 {
4071 	struct scsi_tape *un;
4072 	char reading = bp->b_flags & B_READ;
4073 	int wasopening = 0;
4074 
4075 	/*
4076 	 * validate arguments
4077 	 */
4078 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4079 	if (un == NULL) {
4080 		bp->b_resid = bp->b_bcount;
4081 		bioerror(bp, ENXIO);
4082 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4083 		    "st_queued_strategy: ENXIO error exit\n");
4084 		biodone(bp);
4085 		return (0);
4086 	}
4087 
4088 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4089 
4090 	mutex_enter(ST_MUTEX);
4091 
4092 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4093 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4094 	}
4095 
4096 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4097 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4098 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4099 
4100 	/*
4101 	 * If persistent errors have been flagged, just nix this one. We wait
4102 	 * for any outstanding I/O's below, so we will be in order.
4103 	 */
4104 	if (un->un_persistence && un->un_persist_errors) {
4105 		goto exit;
4106 	}
4107 
4108 	/*
4109 	 * If last command was non queued, wait till it finishes.
4110 	 */
4111 	while (un->un_sbuf_busy) {
4112 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4113 		/* woke up because of an error */
4114 		if (un->un_persistence && un->un_persist_errors) {
4115 			goto exit;
4116 		}
4117 	}
4118 
4119 	/*
4120 	 * s_buf and recovery commands shouldn't come here.
4121 	 */
4122 	ASSERT(bp != un->un_recov_buf);
4123 	ASSERT(bp != un->un_sbufp);
4124 
4125 	/*
4126 	 * If we haven't done/checked reservation on the tape unit
4127 	 * do it now.
4128 	 */
4129 	if ((un->un_rsvd_status &
4130 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4131 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4132 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4133 				st_bioerror(bp, un->un_errno);
4134 				goto exit;
4135 			}
4136 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4137 			/*
4138 			 * Enter here to restore position for possible
4139 			 * resets when the device was closed and opened
4140 			 * in O_NDELAY mode subsequently
4141 			 */
4142 			un->un_state = ST_STATE_INITIALIZING;
4143 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4144 			    0, SYNC_CMD);
4145 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4146 		}
4147 		un->un_rsvd_status |= ST_INIT_RESERVE;
4148 	}
4149 
4150 	/*
4151 	 * If we are offline, we have to initialize everything first.
4152 	 * This is to handle either when opened with O_NDELAY, or
4153 	 * we just got a new tape in the drive, after an offline.
4154 	 * We don't observe O_NDELAY past the open,
4155 	 * as it will not make sense for tapes.
4156 	 */
4157 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4158 		/*
4159 		 * reset state to avoid recursion
4160 		 */
4161 		un->un_laststate = un->un_state;
4162 		un->un_state = ST_STATE_INITIALIZING;
4163 		if (st_tape_init(un)) {
4164 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4165 			    "stioctl : OFFLINE init failure ");
4166 			un->un_state = ST_STATE_OFFLINE;
4167 			un->un_pos.pmode = invalid;
4168 			goto b_done_err;
4169 		}
4170 		/* un_restore_pos make invalid */
4171 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4172 		un->un_restore_pos = 0;
4173 	}
4174 	/*
4175 	 * Check for legal operations
4176 	 */
4177 	if (un->un_pos.pmode == invalid) {
4178 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4179 		    "strategy with un->un_pos.pmode invalid\n");
4180 		goto b_done_err;
4181 	}
4182 
4183 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4184 	    "st_queued_strategy(): regular io\n");
4185 
4186 	/*
4187 	 * Process this first. If we were reading, and we're pending
4188 	 * logical eot, that means we've bumped one file mark too far.
4189 	 */
4190 
4191 	/*
4192 	 * Recursion warning: st_cmd will route back through here.
4193 	 * Not anymore st_cmd will go through st_strategy()!
4194 	 */
4195 	if (un->un_pos.eof == ST_EOT_PENDING) {
4196 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4197 			un->un_pos.pmode = invalid;
4198 			un->un_density_known = 0;
4199 			goto b_done_err;
4200 		}
4201 		un->un_pos.blkno = 0; /* fix up block number.. */
4202 		un->un_pos.eof = ST_EOT;
4203 	}
4204 
4205 	/*
4206 	 * If we are in the process of opening, we may have to
4207 	 * determine/set the correct density. We also may have
4208 	 * to do a test_append (if QIC) to see whether we are
4209 	 * in a position to append to the end of the tape.
4210 	 *
4211 	 * If we're already at logical eot, we transition
4212 	 * to ST_NO_EOF. If we're at physical eot, we punt
4213 	 * to the switch statement below to handle.
4214 	 */
4215 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4216 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4217 
4218 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4219 			if (st_determine_density(un, (int)reading)) {
4220 				goto b_done_err;
4221 			}
4222 		}
4223 
4224 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4225 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4226 		    un->un_pos.fileno, (int)reading,
4227 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4228 		    un->un_pos.eof);
4229 
4230 		if (!reading && un->un_pos.eof != ST_EOM) {
4231 			if (un->un_pos.eof == ST_EOT) {
4232 				un->un_pos.eof = ST_NO_EOF;
4233 			} else if (un->un_pos.pmode != invalid &&
4234 			    (un->un_dp->options & ST_QIC)) {
4235 				/*
4236 				 * st_test_append() will do it all
4237 				 */
4238 				st_test_append(bp);
4239 				mutex_exit(ST_MUTEX);
4240 				return (0);
4241 			}
4242 		}
4243 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4244 			wasopening = 1;
4245 		}
4246 		un->un_laststate = un->un_state;
4247 		un->un_state = ST_STATE_OPEN;
4248 	}
4249 
4250 
4251 	/*
4252 	 * Process rest of END OF FILE and END OF TAPE conditions
4253 	 */
4254 
4255 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4256 	    "eof=%x, wasopening=%x\n",
4257 	    un->un_pos.eof, wasopening);
4258 
4259 	switch (un->un_pos.eof) {
4260 	case ST_EOM:
4261 		/*
4262 		 * This allows writes to proceed past physical
4263 		 * eot. We'll *really* be in trouble if the
4264 		 * user continues blindly writing data too
4265 		 * much past this point (unwind the tape).
4266 		 * Physical eot really means 'early warning
4267 		 * eot' in this context.
4268 		 *
4269 		 * Every other write from now on will succeed
4270 		 * (if sufficient  tape left).
4271 		 * This write will return with resid == count
4272 		 * but the next one should be successful
4273 		 *
4274 		 * Note that we only transition to logical EOT
4275 		 * if the last state wasn't the OPENING state.
4276 		 * We explicitly prohibit running up to physical
4277 		 * eot, closing the device, and then re-opening
4278 		 * to proceed. Trailer records may only be gotten
4279 		 * at by keeping the tape open after hitting eot.
4280 		 *
4281 		 * Also note that ST_EOM cannot be set by reading-
4282 		 * this can only be set during writing. Reading
4283 		 * up to the end of the tape gets a blank check
4284 		 * or a double-filemark indication (ST_EOT_PENDING),
4285 		 * and we prohibit reading after that point.
4286 		 *
4287 		 */
4288 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4289 		if (wasopening == 0) {
4290 			/*
4291 			 * this allows st_rw() to reset it back to
4292 			 * will see a zero write
4293 			 */
4294 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4295 		}
4296 		un->un_status = SUN_KEY_EOT;
4297 		goto b_done;
4298 
4299 	case ST_WRITE_AFTER_EOM:
4300 	case ST_EOT:
4301 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4302 		un->un_status = SUN_KEY_EOT;
4303 		if (SVR4_BEHAVIOR && reading) {
4304 			goto b_done_err;
4305 		}
4306 
4307 		if (reading) {
4308 			goto b_done;
4309 		}
4310 		un->un_pos.eof = ST_NO_EOF;
4311 		break;
4312 
4313 	case ST_EOF_PENDING:
4314 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4315 		    "EOF PENDING\n");
4316 		un->un_status = SUN_KEY_EOF;
4317 		if (SVR4_BEHAVIOR) {
4318 			un->un_pos.eof = ST_EOF;
4319 			goto b_done;
4320 		}
4321 		/* FALLTHROUGH */
4322 	case ST_EOF:
4323 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4324 		un->un_status = SUN_KEY_EOF;
4325 		if (SVR4_BEHAVIOR) {
4326 			goto b_done_err;
4327 		}
4328 
4329 		if (BSD_BEHAVIOR) {
4330 			un->un_pos.eof = ST_NO_EOF;
4331 			un->un_pos.fileno += 1;
4332 			un->un_pos.blkno   = 0;
4333 		}
4334 
4335 		if (reading) {
4336 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4337 			    "now file %d (read)\n",
4338 			    un->un_pos.fileno);
4339 			goto b_done;
4340 		}
4341 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4342 		    "now file %d (write)\n", un->un_pos.fileno);
4343 		break;
4344 	default:
4345 		un->un_status = 0;
4346 		break;
4347 	}
4348 
4349 	bp->b_flags &= ~(B_DONE);
4350 	st_bioerror(bp, 0);
4351 	bp->av_forw = NULL;
4352 	bp->b_resid = 0;
4353 	SET_BP_PKT(bp, 0);
4354 
4355 
4356 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4357 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4358 	    " pkt=0x%p\n",
4359 	    (void *)bp->b_forw, bp->b_bcount,
4360 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4361 
4362 #ifdef	__x86
4363 	/*
4364 	 * We will replace bp with a new bp that can do big blk xfer
4365 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4366 	 *
4367 	 * Also, we need to make sure that we're handling real I/O
4368 	 * by checking group 0/1 SCSI I/O commands, if needed
4369 	 */
4370 	if (bp->b_bcount > un->un_maxdma_arch &&
4371 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4372 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4373 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4374 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4375 		mutex_exit(ST_MUTEX);
4376 		bp = st_get_bigblk_bp(bp);
4377 		mutex_enter(ST_MUTEX);
4378 	}
4379 #endif
4380 
4381 	/* put on wait queue */
4382 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4383 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4384 	    (void *)un->un_quef, (void *)bp);
4385 
4386 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4387 
4388 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4389 
4390 	st_start(un);
4391 
4392 	mutex_exit(ST_MUTEX);
4393 	return (0);
4394 
4395 b_done_err:
4396 	st_bioerror(bp, EIO);
4397 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4398 	    "st_queued_strategy : EIO b_done_err\n");
4399 
4400 b_done:
4401 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4402 	    "st_queued_strategy: b_done\n");
4403 
4404 exit:
4405 	/*
4406 	 * make sure no commands are outstanding or waiting before closing,
4407 	 * so we can guarantee order
4408 	 */
4409 	st_wait_for_io(un);
4410 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4411 
4412 	/* override errno here, if persistent errors were flagged */
4413 	if (un->un_persistence && un->un_persist_errors)
4414 		bioerror(bp, un->un_errno);
4415 
4416 	mutex_exit(ST_MUTEX);
4417 
4418 	biodone(bp);
4419 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4420 	return (0);
4421 }
4422 
4423 
4424 static int
4425 st_strategy(struct buf *bp)
4426 {
4427 	struct scsi_tape *un;
4428 
4429 	/*
4430 	 * validate arguments
4431 	 */
4432 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4433 	if (un == NULL) {
4434 		bp->b_resid = bp->b_bcount;
4435 		bioerror(bp, ENXIO);
4436 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4437 		    "st_strategy: ENXIO error exit\n");
4438 
4439 		biodone(bp);
4440 		return (0);
4441 
4442 	}
4443 
4444 	ST_ENTR(ST_DEVINFO, st_strategy);
4445 
4446 	mutex_enter(ST_MUTEX);
4447 
4448 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4449 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4450 	}
4451 
4452 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4453 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4454 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4455 
4456 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4457 
4458 	bp->b_flags &= ~(B_DONE);
4459 	st_bioerror(bp, 0);
4460 	bp->av_forw = NULL;
4461 	bp->b_resid = 0;
4462 	SET_BP_PKT(bp, 0);
4463 
4464 
4465 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4466 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4467 	    " pkt=0x%p\n",
4468 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4469 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4470 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4471 
4472 	st_start(un);
4473 
4474 	mutex_exit(ST_MUTEX);
4475 	return (0);
4476 }
4477 
4478 /*
4479  * this routine spaces forward over filemarks
4480  */
4481 static int
4482 st_space_fmks(struct scsi_tape *un, int64_t count)
4483 {
4484 	int rval = 0;
4485 
4486 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4487 
4488 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4489 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4490 	    un->un_dev, count);
4491 
4492 	ASSERT(mutex_owned(ST_MUTEX));
4493 
4494 	/*
4495 	 * the risk with doing only one space operation is that we
4496 	 * may accidentily jump in old data
4497 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4498 	 * because the 8200 does not append a marker; in order not to
4499 	 * sacrifice the fast file skip, we do a slow skip if the low
4500 	 * density device has been opened
4501 	 */
4502 
4503 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4504 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4505 	    MT_DENSITY(un->un_dev) == 0))) {
4506 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4507 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4508 			    "space_fmks : EIO can't do space cmd #1\n");
4509 			rval = EIO;
4510 		}
4511 	} else {
4512 		while (count > 0) {
4513 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4514 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4515 				    "space_fmks : EIO can't do space cmd #2\n");
4516 				rval = EIO;
4517 				break;
4518 			}
4519 			count -= 1;
4520 			/*
4521 			 * read a block to see if we have reached
4522 			 * end of medium (double filemark for reel or
4523 			 * medium error for others)
4524 			 */
4525 			if (count > 0) {
4526 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4527 					ST_DEBUG2(ST_DEVINFO, st_label,
4528 					    SCSI_DEBUG,
4529 					    "space_fmks : EIO can't do "
4530 					    "space cmd #3\n");
4531 					rval = EIO;
4532 					break;
4533 				}
4534 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4535 				    (un->un_dp->options & ST_REEL)) {
4536 					un->un_status = SUN_KEY_EOT;
4537 					ST_DEBUG2(ST_DEVINFO, st_label,
4538 					    SCSI_DEBUG,
4539 					    "space_fmks : EIO ST_REEL\n");
4540 					rval = EIO;
4541 					break;
4542 				} else if (IN_EOF(un->un_pos)) {
4543 					un->un_pos.eof = ST_NO_EOF;
4544 					un->un_pos.fileno++;
4545 					un->un_pos.blkno = 0;
4546 					count--;
4547 				} else if (un->un_pos.eof > ST_EOF) {
4548 					ST_DEBUG2(ST_DEVINFO, st_label,
4549 					    SCSI_DEBUG,
4550 					    "space_fmks, EIO > ST_EOF\n");
4551 					rval = EIO;
4552 					break;
4553 				}
4554 
4555 			}
4556 		}
4557 		un->un_err_resid = count;
4558 		COPY_POS(&un->un_pos, &un->un_err_pos);
4559 	}
4560 	ASSERT(mutex_owned(ST_MUTEX));
4561 	return (rval);
4562 }
4563 
4564 /*
4565  * this routine spaces to EOD
4566  *
4567  * it keeps track of the current filenumber and returns the filenumber after
4568  * the last successful space operation, we keep the number high because as
4569  * tapes are getting larger, the possibility of more and more files exist,
4570  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4571  * soon
4572  */
4573 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4574 
4575 static int
4576 st_find_eod(struct scsi_tape *un)
4577 {
4578 	tapepos_t savepos;
4579 	int64_t sp_type;
4580 	int result;
4581 
4582 	if (un == NULL) {
4583 		return (-1);
4584 	}
4585 
4586 	ST_FUNC(ST_DEVINFO, st_find_eod);
4587 
4588 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4589 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4590 	    un->un_pos.fileno);
4591 
4592 	ASSERT(mutex_owned(ST_MUTEX));
4593 
4594 	COPY_POS(&savepos, &un->un_pos);
4595 
4596 	/*
4597 	 * see if the drive is smart enough to do the skips in
4598 	 * one operation; 1/2" use two filemarks
4599 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4600 	 * because the 8200 does not append a marker; in order not to
4601 	 * sacrifice the fast file skip, we do a slow skip if the low
4602 	 * density device has been opened
4603 	 */
4604 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4605 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4606 		    (MT_DENSITY(un->un_dev) == 0)) {
4607 			sp_type = Fmk(1);
4608 		} else if (un->un_pos.pmode == logical) {
4609 			sp_type = SPACE(SP_EOD, 0);
4610 		} else {
4611 			sp_type = Fmk(MAX_SKIP);
4612 		}
4613 	} else {
4614 		sp_type = Fmk(1);
4615 	}
4616 
4617 	for (;;) {
4618 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4619 
4620 		if (result == 0) {
4621 			COPY_POS(&savepos, &un->un_pos);
4622 		}
4623 
4624 		if (sp_type == SPACE(SP_EOD, 0)) {
4625 			if (result != 0) {
4626 				sp_type = Fmk(MAX_SKIP);
4627 				continue;
4628 			}
4629 
4630 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4631 			    "st_find_eod: 0x%"PRIx64"\n",
4632 			    savepos.lgclblkno);
4633 			/*
4634 			 * What we return will become the current file position.
4635 			 * After completing the space command with the position
4636 			 * mode that is not invalid a read position command will
4637 			 * be automaticly issued. If the drive support the long
4638 			 * read position format a valid file position can be
4639 			 * returned.
4640 			 */
4641 			return (un->un_pos.fileno);
4642 		}
4643 
4644 		if (result != 0) {
4645 			break;
4646 		}
4647 
4648 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4649 		    "count=%"PRIx64", eof=%x, status=%x\n",
4650 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4651 
4652 		/*
4653 		 * If we're not EOM smart,  space a record
4654 		 * to see whether we're now in the slot between
4655 		 * the two sequential filemarks that logical
4656 		 * EOM consists of (REEL) or hit nowhere land
4657 		 * (8mm).
4658 		 */
4659 		if (sp_type == Fmk(1)) {
4660 			/*
4661 			 * no fast skipping, check a record
4662 			 */
4663 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4664 				break;
4665 			}
4666 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4667 			    (un->un_dp->options & ST_REEL)) {
4668 				un->un_status = KEY_BLANK_CHECK;
4669 				un->un_pos.fileno++;
4670 				un->un_pos.blkno = 0;
4671 				break;
4672 			}
4673 			if (IN_EOF(un->un_pos)) {
4674 				un->un_pos.eof = ST_NO_EOF;
4675 				un->un_pos.fileno++;
4676 				un->un_pos.blkno = 0;
4677 			}
4678 			if (un->un_pos.eof > ST_EOF) {
4679 				break;
4680 			}
4681 		} else {
4682 			if (un->un_pos.eof > ST_EOF) {
4683 				break;
4684 			}
4685 		}
4686 	}
4687 
4688 	if (un->un_dp->options & ST_KNOWS_EOD) {
4689 		COPY_POS(&savepos, &un->un_pos);
4690 	}
4691 
4692 	ASSERT(mutex_owned(ST_MUTEX));
4693 
4694 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4695 	    "st_find_eod: %x\n", savepos.fileno);
4696 	return (savepos.fileno);
4697 }
4698 
4699 
4700 /*
4701  * this routine is frequently used in ioctls below;
4702  * it determines whether we know the density and if not will
4703  * determine it
4704  * if we have written the tape before, one or more filemarks are written
4705  *
4706  * depending on the stepflag, the head is repositioned to where it was before
4707  * the filemarks were written in order not to confuse step counts
4708  */
4709 #define	STEPBACK    0
4710 #define	NO_STEPBACK 1
4711 
4712 static int
4713 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4714 {
4715 
4716 	GET_SOFT_STATE(dev);
4717 
4718 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4719 
4720 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4721 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4722 	    "\n", dev, wfm, mode, stepflag);
4723 
4724 	ASSERT(mutex_owned(ST_MUTEX));
4725 
4726 	/*
4727 	 * If we don't yet know the density of the tape we have inserted,
4728 	 * we have to either unconditionally set it (if we're 'writing'),
4729 	 * or we have to determine it. As side effects, check for any
4730 	 * write-protect errors, and for the need to put out any file-marks
4731 	 * before positioning a tape.
4732 	 *
4733 	 * If we are going to be spacing forward, and we haven't determined
4734 	 * the tape density yet, we have to do so now...
4735 	 */
4736 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4737 		if (st_determine_density(un, mode)) {
4738 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4739 			    "check_density_or_wfm : EIO can't determine "
4740 			    "density\n");
4741 			un->un_errno = EIO;
4742 			return (EIO);
4743 		}
4744 		/*
4745 		 * Presumably we are at BOT. If we attempt to write, it will
4746 		 * either work okay, or bomb. We don't do a st_test_append
4747 		 * unless we're past BOT.
4748 		 */
4749 		un->un_laststate = un->un_state;
4750 		un->un_state = ST_STATE_OPEN;
4751 
4752 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4753 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4754 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4755 
4756 		tapepos_t spos;
4757 
4758 		COPY_POS(&spos, &un->un_pos);
4759 
4760 		/*
4761 		 * We need to write one or two filemarks.
4762 		 * In the case of the HP, we need to
4763 		 * position the head between the two
4764 		 * marks.
4765 		 */
4766 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4767 			wfm = un->un_fmneeded;
4768 			un->un_fmneeded = 0;
4769 		}
4770 
4771 		if (st_write_fm(dev, wfm)) {
4772 			un->un_pos.pmode = invalid;
4773 			un->un_density_known = 0;
4774 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4775 			    "check_density_or_wfm : EIO can't write fm\n");
4776 			un->un_errno = EIO;
4777 			return (EIO);
4778 		}
4779 
4780 		if (stepflag == STEPBACK) {
4781 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4782 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4783 				    "check_density_or_wfm : EIO can't space "
4784 				    "(-wfm)\n");
4785 				un->un_errno = EIO;
4786 				return (EIO);
4787 			}
4788 			COPY_POS(&un->un_pos, &spos);
4789 		}
4790 	}
4791 
4792 	/*
4793 	 * Whatever we do at this point clears the state of the eof flag.
4794 	 */
4795 
4796 	un->un_pos.eof = ST_NO_EOF;
4797 
4798 	/*
4799 	 * If writing, let's check that we're positioned correctly
4800 	 * at the end of tape before issuing the next write.
4801 	 */
4802 	if (un->un_read_only == RDWR) {
4803 		un->un_test_append = 1;
4804 	}
4805 
4806 	ASSERT(mutex_owned(ST_MUTEX));
4807 	return (0);
4808 }
4809 
4810 
4811 /*
4812  * Wait for all outstaning I/O's to complete
4813  *
4814  * we wait on both ncmds and the wait queue for times when we are flushing
4815  * after persistent errors are flagged, which is when ncmds can be 0, and the
4816  * queue can still have I/O's.  This way we preserve order of biodone's.
4817  */
4818 static void
4819 st_wait_for_io(struct scsi_tape *un)
4820 {
4821 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4822 	ASSERT(mutex_owned(ST_MUTEX));
4823 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4824 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4825 	}
4826 }
4827 
4828 /*
4829  * This routine implements the ioctl calls.  It is called
4830  * from the device switch at normal priority.
4831  */
4832 /*ARGSUSED*/
4833 static int
4834 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4835     int *rval_p)
4836 {
4837 	int tmp, rval = 0;
4838 
4839 	GET_SOFT_STATE(dev);
4840 
4841 	ST_ENTR(ST_DEVINFO, st_ioctl);
4842 
4843 	mutex_enter(ST_MUTEX);
4844 
4845 	ASSERT(un->un_recov_buf_busy == 0);
4846 
4847 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4848 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4849 	    "pe_flag = %d\n",
4850 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4851 	    un->un_persistence && un->un_persist_errors);
4852 
4853 	/*
4854 	 * We don't want to block on these, so let them through
4855 	 * and we don't care about setting driver states here.
4856 	 */
4857 	if ((cmd == MTIOCGETDRIVETYPE) ||
4858 	    (cmd == MTIOCGUARANTEEDORDER) ||
4859 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4860 		goto check_commands;
4861 	}
4862 
4863 	/*
4864 	 * We clear error entry stack except command
4865 	 * MTIOCGETERROR and MTIOCGET
4866 	 */
4867 	if ((cmd != MTIOCGETERROR) &&
4868 	    (cmd != MTIOCGET)) {
4869 		st_empty_error_stack(un);
4870 	}
4871 
4872 	/*
4873 	 * wait for all outstanding commands to complete, or be dequeued.
4874 	 * And because ioctl's are synchronous commands, any return value
4875 	 * after this,  will be in order
4876 	 */
4877 	st_wait_for_io(un);
4878 
4879 	/*
4880 	 * allow only a through clear errors and persistent status, and
4881 	 * status
4882 	 */
4883 	if (un->un_persistence && un->un_persist_errors) {
4884 		if ((cmd == MTIOCLRERR) ||
4885 		    (cmd == MTIOCPERSISTENT) ||
4886 		    (cmd == MTIOCGET)) {
4887 			goto check_commands;
4888 		} else {
4889 			rval = un->un_errno;
4890 			goto exit;
4891 		}
4892 	}
4893 
4894 	ASSERT(un->un_throttle != 0);
4895 	un->un_throttle = 1;	/* > 1 will never happen here */
4896 	un->un_errno = 0;	/* start clean from here */
4897 
4898 	/*
4899 	 * first and foremost, handle any ST_EOT_PENDING cases.
4900 	 * That is, if a logical eot is pending notice, notice it.
4901 	 */
4902 	if (un->un_pos.eof == ST_EOT_PENDING) {
4903 		int resid = un->un_err_resid;
4904 		uchar_t status = un->un_status;
4905 		uchar_t lastop = un->un_lastop;
4906 
4907 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4908 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4909 			    "stioctl : EIO can't space fmk(-1)\n");
4910 			rval = EIO;
4911 			goto exit;
4912 		}
4913 		un->un_lastop = lastop; /* restore last operation */
4914 		if (status == SUN_KEY_EOF) {
4915 			un->un_status = SUN_KEY_EOT;
4916 		} else {
4917 			un->un_status = status;
4918 		}
4919 		un->un_err_resid  = resid;
4920 		/* fix up block number */
4921 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4922 		/* now we're at logical eot */
4923 		un->un_pos.eof = ST_EOT;
4924 	}
4925 
4926 	/*
4927 	 * now, handle the rest of the situations
4928 	 */
4929 check_commands:
4930 	switch (cmd) {
4931 	case MTIOCGET:
4932 	{
4933 #ifdef _MULTI_DATAMODEL
4934 		/*
4935 		 * For use when a 32 bit app makes a call into a
4936 		 * 64 bit ioctl
4937 		 */
4938 		struct mtget32		mtg_local32;
4939 		struct mtget32 		*mtget_32 = &mtg_local32;
4940 #endif /* _MULTI_DATAMODEL */
4941 
4942 			/* Get tape status */
4943 		struct mtget mtg_local;
4944 		struct mtget *mtget = &mtg_local;
4945 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4946 		    "st_ioctl: MTIOCGET\n");
4947 
4948 		bzero((caddr_t)mtget, sizeof (struct mtget));
4949 		mtget->mt_erreg = un->un_status;
4950 		mtget->mt_resid = un->un_err_resid;
4951 		mtget->mt_dsreg = un->un_retry_ct;
4952 		if (un->un_err_pos.pmode == legacy) {
4953 			mtget->mt_fileno = un->un_err_pos.fileno;
4954 		} else {
4955 			mtget->mt_fileno = -1;
4956 		}
4957 		/*
4958 		 * If the value is positive fine.
4959 		 * If its negative we need to return a value based on the
4960 		 * old way if counting backwards from INF (1,000,000,000).
4961 		 */
4962 		if (un->un_err_pos.blkno >= 0) {
4963 			mtget->mt_blkno = un->un_err_pos.blkno;
4964 		} else {
4965 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4966 		}
4967 		mtget->mt_type = un->un_dp->type;
4968 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4969 		if (un->un_read_pos_type != NO_POS) {
4970 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4971 		}
4972 		if (un->un_dp->options & ST_REEL) {
4973 			mtget->mt_flags |= MTF_REEL;
4974 			mtget->mt_bf = 20;
4975 		} else {		/* 1/4" cartridges */
4976 			switch (mtget->mt_type) {
4977 			/* Emulex cartridge tape */
4978 			case MT_ISMT02:
4979 				mtget->mt_bf = 40;
4980 				break;
4981 			default:
4982 				mtget->mt_bf = 126;
4983 				break;
4984 			}
4985 		}
4986 
4987 		/*
4988 		 * If large transfers are allowed and drive options
4989 		 * has no record size limit set. Calculate blocking
4990 		 * factor from the lesser of maxbsize and maxdma.
4991 		 */
4992 		if ((un->un_allow_large_xfer) &&
4993 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4994 			mtget->mt_bf = min(un->un_maxbsize,
4995 			    un->un_maxdma) / SECSIZE;
4996 		}
4997 
4998 		if (un->un_read_only == WORM ||
4999 		    un->un_read_only == RDWORM) {
5000 			mtget->mt_flags |= MTF_WORM_MEDIA;
5001 		}
5002 
5003 		/*
5004 		 * In persistent error mode sending a non-queued can hang
5005 		 * because this ioctl gets to be run without turning off
5006 		 * persistense. Fake the answer based on previous info.
5007 		 */
5008 		if (un->un_persistence) {
5009 			rval = 0;
5010 		} else {
5011 			rval = st_check_clean_bit(un);
5012 		}
5013 		if (rval == 0) {
5014 			/*
5015 			 * If zero is returned or in persistent mode,
5016 			 * use the old data.
5017 			 */
5018 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5019 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5020 			    != TAPE_ALERT_NOT_SUPPORTED) {
5021 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5022 			}
5023 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5024 			    TAPE_ALERT_STILL_DIRTY)) {
5025 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5026 			}
5027 		} else {
5028 			mtget->mt_flags |= (ushort_t)rval;
5029 			rval = 0;
5030 		}
5031 
5032 		un->un_status = 0;		/* Reset status */
5033 		un->un_err_resid = 0;
5034 		tmp = sizeof (struct mtget);
5035 
5036 #ifdef _MULTI_DATAMODEL
5037 
5038 		switch (ddi_model_convert_from(flag & FMODELS)) {
5039 		case DDI_MODEL_ILP32:
5040 			/*
5041 			 * Convert 64 bit back to 32 bit before doing
5042 			 * copyout. This is what the ILP32 app expects.
5043 			 */
5044 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5045 			mtget_32->mt_resid = 	mtget->mt_resid;
5046 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5047 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5048 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5049 			mtget_32->mt_type =  	mtget->mt_type;
5050 			mtget_32->mt_flags = 	mtget->mt_flags;
5051 			mtget_32->mt_bf = 	mtget->mt_bf;
5052 
5053 			if (ddi_copyout(mtget_32, (void *)arg,
5054 			    sizeof (struct mtget32), flag)) {
5055 				rval = EFAULT;
5056 			}
5057 			break;
5058 
5059 		case DDI_MODEL_NONE:
5060 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5061 				rval = EFAULT;
5062 			}
5063 			break;
5064 		}
5065 #else /* ! _MULTI_DATAMODE */
5066 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5067 			rval = EFAULT;
5068 		}
5069 #endif /* _MULTI_DATAMODE */
5070 
5071 		break;
5072 	}
5073 	case MTIOCGETERROR:
5074 			/*
5075 			 * get error entry from error stack
5076 			 */
5077 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5078 			    "st_ioctl: MTIOCGETERROR\n");
5079 
5080 			rval = st_get_error_entry(un, arg, flag);
5081 
5082 			break;
5083 
5084 	case MTIOCSTATE:
5085 		{
5086 			/*
5087 			 * return when media presence matches state
5088 			 */
5089 			enum mtio_state state;
5090 
5091 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5092 			    "st_ioctl: MTIOCSTATE\n");
5093 
5094 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5095 				rval = EFAULT;
5096 
5097 			mutex_exit(ST_MUTEX);
5098 
5099 			rval = st_check_media(dev, state);
5100 
5101 			mutex_enter(ST_MUTEX);
5102 
5103 			if (rval != 0) {
5104 				break;
5105 			}
5106 
5107 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5108 			    sizeof (int), flag))
5109 				rval = EFAULT;
5110 			break;
5111 
5112 		}
5113 
5114 	case MTIOCGETDRIVETYPE:
5115 		{
5116 #ifdef _MULTI_DATAMODEL
5117 		/*
5118 		 * For use when a 32 bit app makes a call into a
5119 		 * 64 bit ioctl
5120 		 */
5121 		struct mtdrivetype_request32	mtdtrq32;
5122 #endif /* _MULTI_DATAMODEL */
5123 
5124 			/*
5125 			 * return mtdrivetype
5126 			 */
5127 			struct mtdrivetype_request mtdtrq;
5128 			struct mtdrivetype mtdrtyp;
5129 			struct mtdrivetype *mtdt = &mtdrtyp;
5130 			struct st_drivetype *stdt = un->un_dp;
5131 
5132 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5133 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5134 
5135 #ifdef _MULTI_DATAMODEL
5136 		switch (ddi_model_convert_from(flag & FMODELS)) {
5137 		case DDI_MODEL_ILP32:
5138 		{
5139 			if (ddi_copyin((void *)arg, &mtdtrq32,
5140 			    sizeof (struct mtdrivetype_request32), flag)) {
5141 				rval = EFAULT;
5142 				break;
5143 			}
5144 			mtdtrq.size = mtdtrq32.size;
5145 			mtdtrq.mtdtp =
5146 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5147 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5148 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5149 			break;
5150 		}
5151 		case DDI_MODEL_NONE:
5152 			if (ddi_copyin((void *)arg, &mtdtrq,
5153 			    sizeof (struct mtdrivetype_request), flag)) {
5154 				rval = EFAULT;
5155 				break;
5156 			}
5157 			break;
5158 		}
5159 
5160 #else /* ! _MULTI_DATAMODEL */
5161 		if (ddi_copyin((void *)arg, &mtdtrq,
5162 		    sizeof (struct mtdrivetype_request), flag)) {
5163 			rval = EFAULT;
5164 			break;
5165 		}
5166 #endif /* _MULTI_DATAMODEL */
5167 
5168 			/*
5169 			 * if requested size is < 0 then return
5170 			 * error.
5171 			 */
5172 			if (mtdtrq.size < 0) {
5173 				rval = EINVAL;
5174 				break;
5175 			}
5176 			bzero(mtdt, sizeof (struct mtdrivetype));
5177 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5178 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5179 			mtdt->type = stdt->type;
5180 			mtdt->bsize = stdt->bsize;
5181 			mtdt->options = stdt->options;
5182 			mtdt->max_rretries = stdt->max_rretries;
5183 			mtdt->max_wretries = stdt->max_wretries;
5184 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5185 				mtdt->densities[tmp] = stdt->densities[tmp];
5186 			}
5187 			mtdt->default_density = stdt->default_density;
5188 			/*
5189 			 * Speed hasn't been used since the hayday of reel tape.
5190 			 * For all drives not setting the option ST_KNOWS_MEDIA
5191 			 * the speed member renamed to mediatype are zeros.
5192 			 * Those drives that have ST_KNOWS_MEDIA set use the
5193 			 * new mediatype member which is used to figure the
5194 			 * type of media loaded.
5195 			 *
5196 			 * So as to not break applications speed in the
5197 			 * mtdrivetype structure is not renamed.
5198 			 */
5199 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5200 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5201 			}
5202 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5203 			mtdt->io_timeout = stdt->io_timeout;
5204 			mtdt->rewind_timeout = stdt->rewind_timeout;
5205 			mtdt->space_timeout = stdt->space_timeout;
5206 			mtdt->load_timeout = stdt->load_timeout;
5207 			mtdt->unload_timeout = stdt->unload_timeout;
5208 			mtdt->erase_timeout = stdt->erase_timeout;
5209 
5210 			/*
5211 			 * Limit the maximum length of the result to
5212 			 * sizeof (struct mtdrivetype).
5213 			 */
5214 			tmp = sizeof (struct mtdrivetype);
5215 			if (mtdtrq.size < tmp)
5216 				tmp = mtdtrq.size;
5217 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5218 				rval = EFAULT;
5219 			}
5220 			break;
5221 		}
5222 	case MTIOCPERSISTENT:
5223 
5224 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5225 			rval = EFAULT;
5226 			break;
5227 		}
5228 
5229 		if (tmp) {
5230 			st_turn_pe_on(un);
5231 		} else {
5232 			st_turn_pe_off(un);
5233 		}
5234 
5235 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5236 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5237 		    un->un_persistence);
5238 
5239 		break;
5240 
5241 	case MTIOCPERSISTENTSTATUS:
5242 		tmp = (int)un->un_persistence;
5243 
5244 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5245 			rval = EFAULT;
5246 		}
5247 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5248 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5249 		    un->un_persistence);
5250 
5251 		break;
5252 
5253 	case MTIOCLRERR:
5254 		{
5255 			/* clear persistent errors */
5256 
5257 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5258 			    "st_ioctl: MTIOCLRERR\n");
5259 
5260 			st_clear_pe(un);
5261 
5262 			break;
5263 		}
5264 
5265 	case MTIOCGUARANTEEDORDER:
5266 		{
5267 			/*
5268 			 * this is just a holder to make a valid ioctl and
5269 			 * it won't be in any earlier release
5270 			 */
5271 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5272 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5273 
5274 			break;
5275 		}
5276 
5277 	case MTIOCRESERVE:
5278 		{
5279 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5280 			    "st_ioctl: MTIOCRESERVE\n");
5281 
5282 			/*
5283 			 * Check if Reserve/Release is supported.
5284 			 */
5285 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5286 				rval = ENOTTY;
5287 				break;
5288 			}
5289 
5290 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5291 
5292 			if (rval == 0) {
5293 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5294 			}
5295 			break;
5296 		}
5297 
5298 	case MTIOCRELEASE:
5299 		{
5300 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5301 			    "st_ioctl: MTIOCRELEASE\n");
5302 
5303 			/*
5304 			 * Check if Reserve/Release is supported.
5305 			 */
5306 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5307 				rval = ENOTTY;
5308 				break;
5309 			}
5310 
5311 			/*
5312 			 * Used to just clear ST_PRESERVE_RESERVE which
5313 			 * made the reservation release at next close.
5314 			 * As the user may have opened and then done a
5315 			 * persistant reservation we now need to drop
5316 			 * the reservation without closing if the user
5317 			 * attempts to do this.
5318 			 */
5319 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5320 
5321 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5322 
5323 			break;
5324 		}
5325 
5326 	case MTIOCFORCERESERVE:
5327 	{
5328 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5329 		    "st_ioctl: MTIOCFORCERESERVE\n");
5330 
5331 		/*
5332 		 * Check if Reserve/Release is supported.
5333 		 */
5334 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5335 			rval = ENOTTY;
5336 			break;
5337 		}
5338 		/*
5339 		 * allow only super user to run this.
5340 		 */
5341 		if (drv_priv(cred_p) != 0) {
5342 			rval = EPERM;
5343 			break;
5344 		}
5345 		/*
5346 		 * Throw away reserve,
5347 		 * not using test-unit-ready
5348 		 * since reserve can succeed without tape being
5349 		 * present in the drive.
5350 		 */
5351 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5352 
5353 		rval = st_take_ownership(un, st_uscsi_cmd);
5354 
5355 		break;
5356 	}
5357 
5358 	case USCSICMD:
5359 	{
5360 		cred_t	*cr;
5361 
5362 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5363 		    "st_ioctl: USCSICMD\n");
5364 
5365 		cr = ddi_get_cred();
5366 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5367 			rval = EPERM;
5368 		} else {
5369 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5370 		}
5371 		break;
5372 	}
5373 	case MTIOCTOP:
5374 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5375 		    "st_ioctl: MTIOCTOP\n");
5376 		rval = st_mtioctop(un, arg, flag);
5377 		break;
5378 
5379 	case MTIOCLTOP:
5380 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5381 		    "st_ioctl: MTIOLCTOP\n");
5382 		rval = st_mtiocltop(un, arg, flag);
5383 		break;
5384 
5385 	case MTIOCREADIGNOREILI:
5386 		{
5387 			int set_ili;
5388 
5389 			if (ddi_copyin((void *)arg, &set_ili,
5390 			    sizeof (set_ili), flag)) {
5391 				rval = EFAULT;
5392 				break;
5393 			}
5394 
5395 			if (un->un_bsize) {
5396 				rval = ENOTTY;
5397 				break;
5398 			}
5399 
5400 			switch (set_ili) {
5401 			case 0:
5402 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5403 				break;
5404 
5405 			case 1:
5406 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5407 				break;
5408 
5409 			default:
5410 				rval = EINVAL;
5411 				break;
5412 			}
5413 			break;
5414 		}
5415 
5416 	case MTIOCREADIGNOREEOFS:
5417 		{
5418 			int ignore_eof;
5419 
5420 			if (ddi_copyin((void *)arg, &ignore_eof,
5421 			    sizeof (ignore_eof), flag)) {
5422 				rval = EFAULT;
5423 				break;
5424 			}
5425 
5426 			if (!(un->un_dp->options & ST_REEL)) {
5427 				rval = ENOTTY;
5428 				break;
5429 			}
5430 
5431 			switch (ignore_eof) {
5432 			case 0:
5433 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5434 				break;
5435 
5436 			case 1:
5437 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5438 				break;
5439 
5440 			default:
5441 				rval = EINVAL;
5442 				break;
5443 			}
5444 			break;
5445 		}
5446 
5447 	case MTIOCSHORTFMK:
5448 	{
5449 		int short_fmk;
5450 
5451 		if (ddi_copyin((void *)arg, &short_fmk,
5452 		    sizeof (short_fmk), flag)) {
5453 			rval = EFAULT;
5454 			break;
5455 		}
5456 
5457 		switch (un->un_dp->type) {
5458 		case ST_TYPE_EXB8500:
5459 		case ST_TYPE_EXABYTE:
5460 			if (!short_fmk) {
5461 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5462 			} else if (short_fmk == 1) {
5463 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5464 			} else {
5465 				rval = EINVAL;
5466 			}
5467 			break;
5468 
5469 		default:
5470 			rval = ENOTTY;
5471 			break;
5472 		}
5473 		break;
5474 	}
5475 
5476 	case MTIOCGETPOS:
5477 		rval = st_update_block_pos(un, st_cmd, 0);
5478 		if (rval == 0) {
5479 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5480 			    sizeof (tapepos_t), flag)) {
5481 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5482 				    "MTIOCGETPOS copy out failed\n");
5483 				rval = EFAULT;
5484 			}
5485 		}
5486 		break;
5487 
5488 	case MTIOCRESTPOS:
5489 	{
5490 		tapepos_t dest;
5491 
5492 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5493 		    flag) != 0) {
5494 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5495 			    "MTIOCRESTPOS copy in failed\n");
5496 			rval = EFAULT;
5497 			break;
5498 		}
5499 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5500 		if (rval != 0) {
5501 			rval = EIO;
5502 		}
5503 		break;
5504 	}
5505 	default:
5506 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5507 		    "st_ioctl: unknown ioctl\n");
5508 		rval = ENOTTY;
5509 	}
5510 
5511 exit:
5512 	if (!(un->un_persistence && un->un_persist_errors)) {
5513 		un->un_errno = rval;
5514 	}
5515 
5516 	mutex_exit(ST_MUTEX);
5517 
5518 	return (rval);
5519 }
5520 
5521 
5522 /*
5523  * do some MTIOCTOP tape operations
5524  */
5525 static int
5526 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5527 {
5528 #ifdef _MULTI_DATAMODEL
5529 	/*
5530 	 * For use when a 32 bit app makes a call into a
5531 	 * 64 bit ioctl
5532 	 */
5533 	struct mtop32	mtop_32_for_64;
5534 #endif /* _MULTI_DATAMODEL */
5535 	struct mtop passed;
5536 	struct mtlop local;
5537 	int rval = 0;
5538 
5539 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5540 
5541 	ASSERT(mutex_owned(ST_MUTEX));
5542 
5543 #ifdef _MULTI_DATAMODEL
5544 	switch (ddi_model_convert_from(flag & FMODELS)) {
5545 	case DDI_MODEL_ILP32:
5546 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5547 		    sizeof (struct mtop32), flag)) {
5548 			return (EFAULT);
5549 		}
5550 		local.mt_op = mtop_32_for_64.mt_op;
5551 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5552 		break;
5553 
5554 	case DDI_MODEL_NONE:
5555 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5556 			return (EFAULT);
5557 		}
5558 		local.mt_op = passed.mt_op;
5559 		/* prevent sign extention */
5560 		local.mt_count = (UINT32_MAX & passed.mt_count);
5561 		break;
5562 	}
5563 
5564 #else /* ! _MULTI_DATAMODEL */
5565 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5566 		return (EFAULT);
5567 	}
5568 	local.mt_op = passed.mt_op;
5569 	/* prevent sign extention */
5570 	local.mt_count = (UINT32_MAX & passed.mt_count);
5571 #endif /* _MULTI_DATAMODEL */
5572 
5573 	rval = st_do_mtioctop(un, &local);
5574 
5575 #ifdef _MULTI_DATAMODEL
5576 	switch (ddi_model_convert_from(flag & FMODELS)) {
5577 	case DDI_MODEL_ILP32:
5578 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5579 			rval = ERANGE;
5580 			break;
5581 		}
5582 		/*
5583 		 * Convert 64 bit back to 32 bit before doing
5584 		 * copyout. This is what the ILP32 app expects.
5585 		 */
5586 		mtop_32_for_64.mt_op = local.mt_op;
5587 		mtop_32_for_64.mt_count = local.mt_count;
5588 
5589 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5590 		    sizeof (struct mtop32), flag)) {
5591 			rval = EFAULT;
5592 		}
5593 		break;
5594 
5595 	case DDI_MODEL_NONE:
5596 		passed.mt_count = local.mt_count;
5597 		passed.mt_op = local.mt_op;
5598 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5599 			rval = EFAULT;
5600 		}
5601 		break;
5602 	}
5603 #else /* ! _MULTI_DATAMODE */
5604 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5605 		rval = ERANGE;
5606 	} else {
5607 		passed.mt_op = local.mt_op;
5608 		passed.mt_count = local.mt_count;
5609 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5610 			rval = EFAULT;
5611 		}
5612 	}
5613 #endif /* _MULTI_DATAMODE */
5614 
5615 
5616 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5617 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5618 	    un->un_pos.blkno, un->un_pos.eof);
5619 
5620 	if (un->un_pos.pmode == invalid) {
5621 		un->un_density_known = 0;
5622 	}
5623 
5624 	ASSERT(mutex_owned(ST_MUTEX));
5625 	return (rval);
5626 }
5627 
5628 static int
5629 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5630 {
5631 	struct mtlop local;
5632 	int rval;
5633 
5634 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5635 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5636 		return (EFAULT);
5637 	}
5638 
5639 	rval = st_do_mtioctop(un, &local);
5640 
5641 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5642 		rval = EFAULT;
5643 	}
5644 	return (rval);
5645 }
5646 
5647 
5648 static int
5649 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5650 {
5651 	dev_t dev = un->un_dev;
5652 	int savefile;
5653 	int rval = 0;
5654 
5655 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5656 
5657 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5658 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5659 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5660 	    "fileno=%x, blkno=%x, eof=%x\n",
5661 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5662 
5663 	un->un_status = 0;
5664 
5665 	/*
5666 	 * if we are going to mess with a tape, we have to make sure we have
5667 	 * one and are not offline (i.e. no tape is initialized).  We let
5668 	 * commands pass here that don't actually touch the tape, except for
5669 	 * loading and initialization (rewinding).
5670 	 */
5671 	if (un->un_state == ST_STATE_OFFLINE) {
5672 		switch (mtop->mt_op) {
5673 		case MTLOAD:
5674 		case MTNOP:
5675 			/*
5676 			 * We don't want strategy calling st_tape_init here,
5677 			 * so, change state
5678 			 */
5679 			un->un_state = ST_STATE_INITIALIZING;
5680 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5681 			    "st_do_mtioctop : OFFLINE state = %d\n",
5682 			    un->un_state);
5683 			break;
5684 		default:
5685 			/*
5686 			 * reinitialize by normal means
5687 			 */
5688 			rval = st_tape_init(un);
5689 			if (rval) {
5690 				un->un_state = ST_STATE_INITIALIZING;
5691 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5692 				    "st_do_mtioctop : OFFLINE init failure ");
5693 				un->un_state = ST_STATE_OFFLINE;
5694 				un->un_pos.pmode = invalid;
5695 				if (rval != EACCES) {
5696 					rval = EIO;
5697 				}
5698 				return (rval);
5699 			}
5700 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5701 			break;
5702 		}
5703 	}
5704 
5705 	/*
5706 	 * If the file position is invalid, allow only those
5707 	 * commands that properly position the tape and fail
5708 	 * the rest with EIO
5709 	 */
5710 	if (un->un_pos.pmode == invalid) {
5711 		switch (mtop->mt_op) {
5712 		case MTWEOF:
5713 		case MTRETEN:
5714 		case MTERASE:
5715 		case MTEOM:
5716 		case MTFSF:
5717 		case MTFSR:
5718 		case MTBSF:
5719 		case MTNBSF:
5720 		case MTBSR:
5721 		case MTSRSZ:
5722 		case MTGRSZ:
5723 		case MTSEEK:
5724 		case MTBSSF:
5725 		case MTFSSF:
5726 			return (EIO);
5727 			/* NOTREACHED */
5728 		case MTREW:
5729 		case MTLOAD:
5730 		case MTOFFL:
5731 		case MTNOP:
5732 		case MTTELL:
5733 		case MTLOCK:
5734 		case MTUNLOCK:
5735 			break;
5736 
5737 		default:
5738 			return (ENOTTY);
5739 			/* NOTREACHED */
5740 		}
5741 	}
5742 
5743 	switch (mtop->mt_op) {
5744 	case MTERASE:
5745 		/*
5746 		 * MTERASE rewinds the tape, erase it completely, and returns
5747 		 * to the beginning of the tape
5748 		 */
5749 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5750 			un->un_status = KEY_WRITE_PROTECT;
5751 			un->un_err_resid = mtop->mt_count;
5752 			COPY_POS(&un->un_err_pos, &un->un_pos);
5753 			return (EACCES);
5754 		}
5755 		if (un->un_dp->options & ST_REEL) {
5756 			un->un_fmneeded = 2;
5757 		} else {
5758 			un->un_fmneeded = 1;
5759 		}
5760 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5761 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5762 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5763 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5764 			un->un_pos.pmode = invalid;
5765 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5766 			    "st_do_mtioctop : EIO space or erase or "
5767 			    "check den)\n");
5768 			rval = EIO;
5769 		} else {
5770 			/* QIC and helical scan rewind after erase */
5771 			if (un->un_dp->options & ST_REEL) {
5772 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5773 			}
5774 		}
5775 		break;
5776 
5777 	case MTWEOF:
5778 		/*
5779 		 * write an end-of-file record
5780 		 */
5781 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5782 			un->un_status = KEY_WRITE_PROTECT;
5783 			un->un_err_resid = mtop->mt_count;
5784 			COPY_POS(&un->un_err_pos, &un->un_pos);
5785 			return (EACCES);
5786 		}
5787 
5788 		/*
5789 		 * zero count means just flush buffers
5790 		 * negative count is not permitted
5791 		 */
5792 		if (mtop->mt_count < 0) {
5793 			return (EINVAL);
5794 		}
5795 
5796 		/* Not on worm */
5797 		if (un->un_read_only == RDWR) {
5798 			un->un_test_append = 1;
5799 		}
5800 
5801 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5802 			if (st_determine_density(un, B_WRITE)) {
5803 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5804 				    "st_do_mtioctop : EIO : MTWEOF can't "
5805 				    "determine density");
5806 				return (EIO);
5807 			}
5808 		}
5809 
5810 		rval = st_write_fm(dev, (int)mtop->mt_count);
5811 		if ((rval != 0) && (rval != EACCES)) {
5812 			/*
5813 			 * Failure due to something other than illegal
5814 			 * request results in loss of state (st_intr).
5815 			 */
5816 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5817 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5818 			    "file mark");
5819 			rval = EIO;
5820 		}
5821 		break;
5822 
5823 	case MTRETEN:
5824 		/*
5825 		 * retension the tape
5826 		 */
5827 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5828 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5829 			un->un_pos.pmode = invalid;
5830 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5831 			    "st_do_mtioctop : EIO : MTRETEN ");
5832 			rval = EIO;
5833 		}
5834 		break;
5835 
5836 	case MTREW:
5837 		/*
5838 		 * rewind  the tape
5839 		 */
5840 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5841 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5842 			    "st_do_mtioctop : EIO:MTREW check "
5843 			    "density/wfm failed");
5844 			return (EIO);
5845 		}
5846 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5847 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5848 			    "st_do_mtioctop : EIO : MTREW ");
5849 			rval = EIO;
5850 		}
5851 		break;
5852 
5853 	case MTOFFL:
5854 		/*
5855 		 * rewinds, and, if appropriate, takes the device offline by
5856 		 * unloading the tape
5857 		 */
5858 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5859 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5860 			    "st_do_mtioctop :EIO:MTOFFL check "
5861 			    "density/wfm failed");
5862 			return (EIO);
5863 		}
5864 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5865 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5866 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5867 			    "st_do_mtioctop : EIO : MTOFFL");
5868 			return (EIO);
5869 		}
5870 		un->un_pos.eof = ST_NO_EOF;
5871 		un->un_laststate = un->un_state;
5872 		un->un_state = ST_STATE_OFFLINE;
5873 		un->un_mediastate = MTIO_EJECTED;
5874 		break;
5875 
5876 	case MTLOAD:
5877 		/*
5878 		 * This is to load a tape into the drive
5879 		 * Note that if the tape is not loaded, the device will have
5880 		 * to be opened via O_NDELAY or O_NONBLOCK.
5881 		 */
5882 		/*
5883 		 * Let's try and clean things up, if we are not
5884 		 * initializing, and then send in the load command, no
5885 		 * matter what.
5886 		 *
5887 		 * load after a media change by the user.
5888 		 */
5889 
5890 		if (un->un_state > ST_STATE_INITIALIZING) {
5891 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5892 		}
5893 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5894 		/* Load command to a drive that doesn't support load */
5895 		if ((rval == EIO) &&
5896 		    ((un->un_status == KEY_NOT_READY) &&
5897 			/* Medium not present */
5898 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5899 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5900 		    (un->un_dp->type == MT_ISSTK9840) &&
5901 			/* CSL not present */
5902 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5903 			rval = ENOTTY;
5904 			break;
5905 		} else if (rval != EACCES && rval != 0) {
5906 			rval = EIO;
5907 		}
5908 		if (rval) {
5909 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5910 			    "st_do_mtioctop : %s : MTLOAD\n",
5911 			    rval == EACCES ? "EACCES" : "EIO");
5912 			/*
5913 			 * If load tape fails, who knows what happened...
5914 			 */
5915 			un->un_pos.pmode = invalid;
5916 			break;
5917 		}
5918 
5919 		/*
5920 		 * reset all counters appropriately using rewind, as if LOAD
5921 		 * succeeds, we are at BOT
5922 		 */
5923 		un->un_state = ST_STATE_INITIALIZING;
5924 
5925 		rval = st_tape_init(un);
5926 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5927 			rval = 0;
5928 			break;
5929 		}
5930 
5931 		if (rval != 0) {
5932 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5933 			    "st_do_mtioctop : EIO : MTLOAD calls "
5934 			    "st_tape_init\n");
5935 			rval = EIO;
5936 			un->un_state = ST_STATE_OFFLINE;
5937 		}
5938 
5939 		break;
5940 
5941 	case MTNOP:
5942 		un->un_status = 0;		/* Reset status */
5943 		un->un_err_resid = 0;
5944 		mtop->mt_count = MTUNIT(dev);
5945 		break;
5946 
5947 	case MTEOM:
5948 		/*
5949 		 * positions the tape at a location just after the last file
5950 		 * written on the tape. For cartridge and 8 mm, this after
5951 		 * the last file mark; for reel, this is inbetween the two
5952 		 * last 2 file marks
5953 		 */
5954 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5955 		    (un->un_lastop == ST_OP_WRITE) ||
5956 		    (un->un_lastop == ST_OP_WEOF)) {
5957 			/*
5958 			 * If the command wants to move to logical end
5959 			 * of media, and we're already there, we're done.
5960 			 * If we were at logical eot, we reset the state
5961 			 * to be *not* at logical eot.
5962 			 *
5963 			 * If we're at physical or logical eot, we prohibit
5964 			 * forward space operations (unconditionally).
5965 			 *
5966 			 * Also if the last operation was a write of any
5967 			 * kind the tape is at EOD.
5968 			 */
5969 			return (0);
5970 		}
5971 		/*
5972 		 * physical tape position may not be what we've been
5973 		 * telling the user; adjust the request accordingly
5974 		 */
5975 		if (IN_EOF(un->un_pos)) {
5976 			un->un_pos.fileno++;
5977 			un->un_pos.blkno = 0;
5978 		}
5979 
5980 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5981 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5982 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5983 			    " failed");
5984 			return (EIO);
5985 		}
5986 
5987 		/*
5988 		 * st_find_eod() returns the last fileno we knew about;
5989 		 */
5990 		savefile = st_find_eod(un);
5991 
5992 		if ((un->un_status != KEY_BLANK_CHECK) &&
5993 		    (un->un_status != SUN_KEY_EOT)) {
5994 			un->un_pos.pmode = invalid;
5995 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5996 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5997 			rval = EIO;
5998 		} else {
5999 			/*
6000 			 * For 1/2" reel tapes assume logical EOT marked
6001 			 * by two file marks or we don't care that we may
6002 			 * be extending the last file on the tape.
6003 			 */
6004 			if (un->un_dp->options & ST_REEL) {
6005 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6006 					un->un_pos.pmode = invalid;
6007 					ST_DEBUG2(ST_DEVINFO, st_label,
6008 					    SCSI_DEBUG,
6009 					    "st_do_mtioctop : EIO : MTEOM space"
6010 					    " cmd failed");
6011 					rval = EIO;
6012 					break;
6013 				}
6014 				/*
6015 				 * Fix up the block number.
6016 				 */
6017 				un->un_pos.blkno = 0;
6018 				un->un_err_pos.blkno = 0;
6019 			}
6020 			un->un_err_resid = 0;
6021 			un->un_pos.fileno = savefile;
6022 			un->un_pos.eof = ST_EOT;
6023 		}
6024 		un->un_status = 0;
6025 		break;
6026 
6027 	case MTFSF:
6028 		MAX_SPACE_CNT(mtop->mt_count);
6029 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6030 		break;
6031 
6032 	case MTFSR:
6033 		MAX_SPACE_CNT(mtop->mt_count);
6034 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6035 		break;
6036 
6037 	case MTBSF:
6038 		MAX_SPACE_CNT(mtop->mt_count);
6039 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6040 		break;
6041 
6042 	case MTNBSF:
6043 		MAX_SPACE_CNT(mtop->mt_count);
6044 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6045 		break;
6046 
6047 	case MTBSR:
6048 		MAX_SPACE_CNT(mtop->mt_count);
6049 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6050 		break;
6051 
6052 	case MTBSSF:
6053 		MAX_SPACE_CNT(mtop->mt_count);
6054 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6055 		break;
6056 
6057 	case MTFSSF:
6058 		MAX_SPACE_CNT(mtop->mt_count);
6059 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6060 		break;
6061 
6062 	case MTSRSZ:
6063 
6064 		/*
6065 		 * Set record-size to that sent by user
6066 		 * Check to see if there is reason that the requested
6067 		 * block size should not be set.
6068 		 */
6069 
6070 		/* If requesting variable block size is it ok? */
6071 		if ((mtop->mt_count == 0) &&
6072 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6073 			return (ENOTTY);
6074 		}
6075 
6076 		/*
6077 		 * If requested block size is not variable "0",
6078 		 * is it less then minimum.
6079 		 */
6080 		if ((mtop->mt_count != 0) &&
6081 		    (mtop->mt_count < un->un_minbsize)) {
6082 			return (EINVAL);
6083 		}
6084 
6085 		/* Is the requested block size more then maximum */
6086 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6087 		    (un->un_maxbsize != 0)) {
6088 			return (EINVAL);
6089 		}
6090 
6091 		/* Is requested block size a modulus the device likes */
6092 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6093 			return (EINVAL);
6094 		}
6095 
6096 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6097 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6098 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6099 			return (EIO);
6100 		}
6101 
6102 		return (0);
6103 
6104 	case MTGRSZ:
6105 		/*
6106 		 * Get record-size to the user
6107 		 */
6108 		mtop->mt_count = un->un_bsize;
6109 		rval = 0;
6110 		break;
6111 
6112 	case MTTELL:
6113 		rval = st_update_block_pos(un, st_cmd, 0);
6114 		mtop->mt_count = un->un_pos.lgclblkno;
6115 		break;
6116 
6117 	case MTSEEK:
6118 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6119 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6120 		/*
6121 		 * This bit of magic make mt print the actual position if
6122 		 * the resulting position was not what was asked for.
6123 		 */
6124 		if (rval == ESPIPE) {
6125 			rval = EIO;
6126 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6127 				mtop->mt_op = MTTELL;
6128 				mtop->mt_count = un->un_pos.lgclblkno;
6129 			}
6130 		}
6131 		break;
6132 
6133 	case MTLOCK:
6134 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6135 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6136 			    "st_do_mtioctop : EIO : MTLOCK");
6137 			rval = EIO;
6138 		}
6139 		break;
6140 
6141 	case MTUNLOCK:
6142 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6143 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6144 			    "st_do_mtioctop : EIO : MTUNLOCK");
6145 			rval = EIO;
6146 		}
6147 		break;
6148 
6149 	default:
6150 		rval = ENOTTY;
6151 	}
6152 
6153 	return (rval);
6154 }
6155 
6156 
6157 /*
6158  * Run a command for uscsi ioctl.
6159  */
6160 static int
6161 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6162 {
6163 	struct uscsi_cmd	*uscmd;
6164 	struct buf	*bp;
6165 	enum uio_seg	uioseg;
6166 	int	offline_state = 0;
6167 	int	err = 0;
6168 	dev_t dev = un->un_dev;
6169 
6170 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6171 
6172 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6173 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6174 
6175 	ASSERT(mutex_owned(ST_MUTEX));
6176 
6177 	/*
6178 	 * We really don't know what commands are coming in here and
6179 	 * we don't want to limit the commands coming in.
6180 	 *
6181 	 * If st_tape_init() gets called from st_strategy(), then we
6182 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6183 	 * which it never will, as we set it below.  To prevent
6184 	 * st_tape_init() from getting called, we have to set state to other
6185 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6186 	 * achieves this purpose already.
6187 	 *
6188 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6189 	 * so other entry points to the driver might have the chance to call
6190 	 * st_tape_init().
6191 	 */
6192 	if (un->un_state == ST_STATE_OFFLINE) {
6193 		un->un_laststate = ST_STATE_OFFLINE;
6194 		un->un_state = ST_STATE_INITIALIZING;
6195 		offline_state = 1;
6196 	}
6197 
6198 	mutex_exit(ST_MUTEX);
6199 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6200 	mutex_enter(ST_MUTEX);
6201 	if (err != 0) {
6202 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6203 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6204 		goto exit;
6205 	}
6206 
6207 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6208 
6209 	/* check to see if this command requires the drive to be reserved */
6210 	if (uscmd->uscsi_cdb != NULL) {
6211 		err = st_check_cdb_for_need_to_reserve(un,
6212 		    (uchar_t *)uscmd->uscsi_cdb);
6213 		if (err) {
6214 			goto exit_free;
6215 		}
6216 		/*
6217 		 * If this is a space command we need to save the starting
6218 		 * point so we can retry from there if the command fails.
6219 		 */
6220 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6221 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6222 			(void) st_update_block_pos(un, st_cmd, 0);
6223 		}
6224 	}
6225 
6226 	/*
6227 	 * Forground should not be doing anything while recovery is active.
6228 	 */
6229 	ASSERT(un->un_recov_buf_busy == 0);
6230 
6231 	/*
6232 	 * Get buffer resources...
6233 	 */
6234 	while (un->un_sbuf_busy)
6235 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6236 	un->un_sbuf_busy = 1;
6237 
6238 #ifdef STDEBUG
6239 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6240 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6241 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6242 		    "uscsi cdb", uscmd->uscsi_cdb);
6243 		if (uscmd->uscsi_buflen) {
6244 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6245 			    "uscsi %s of %ld bytes %s %s space\n",
6246 			    (rw == B_READ) ? rd_str : wr_str,
6247 			    uscmd->uscsi_buflen,
6248 			    (rw == B_READ) ? "to" : "from",
6249 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6250 		}
6251 	}
6252 #endif /* STDEBUG */
6253 
6254 	/*
6255 	 * Although st_uscsi_cmd() never makes use of these
6256 	 * now, we are just being safe and consistent.
6257 	 */
6258 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6259 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6260 
6261 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6262 	bp = un->un_sbufp;
6263 	bzero(bp, sizeof (buf_t));
6264 	if (uscmd->uscsi_cdb != NULL) {
6265 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6266 	}
6267 	bp->b_back = (struct buf *)uscmd;
6268 
6269 	mutex_exit(ST_MUTEX);
6270 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6271 	mutex_enter(ST_MUTEX);
6272 
6273 	/*
6274 	 * If scsi reset successful, don't write any filemarks.
6275 	 */
6276 	if ((err == 0) && (uscmd->uscsi_flags &
6277 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6278 		un->un_fmneeded = 0;
6279 	}
6280 
6281 exit_free:
6282 	/*
6283 	 * Free resources
6284 	 */
6285 	un->un_sbuf_busy = 0;
6286 	un->un_srqbufp = NULL;
6287 
6288 	/*
6289 	 * If was a space command need to update logical block position.
6290 	 * If the command failed such that positioning is invalid, Don't
6291 	 * update the position as the user must do this to validate the
6292 	 * position for data protection.
6293 	 */
6294 	if ((uscmd->uscsi_cdb != NULL) &&
6295 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6296 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6297 	    (un->un_pos.pmode != invalid)) {
6298 		un->un_running.pmode = invalid;
6299 		(void) st_update_block_pos(un, st_cmd, 1);
6300 		/*
6301 		 * Set running position to invalid so it updates on the
6302 		 * next command.
6303 		 */
6304 		un->un_running.pmode = invalid;
6305 	}
6306 	cv_signal(&un->un_sbuf_cv);
6307 	mutex_exit(ST_MUTEX);
6308 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6309 	mutex_enter(ST_MUTEX);
6310 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6311 	    "st_uscsi_cmd returns 0x%x\n", err);
6312 
6313 exit:
6314 	/* don't lose offline state */
6315 	if (offline_state) {
6316 		un->un_state = ST_STATE_OFFLINE;
6317 	}
6318 
6319 	ASSERT(mutex_owned(ST_MUTEX));
6320 	return (err);
6321 }
6322 
6323 static int
6324 st_write_fm(dev_t dev, int wfm)
6325 {
6326 	int i;
6327 	int rval;
6328 
6329 	GET_SOFT_STATE(dev);
6330 
6331 	ST_FUNC(ST_DEVINFO, st_write_fm);
6332 
6333 	ASSERT(mutex_owned(ST_MUTEX));
6334 
6335 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6336 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6337 
6338 	/*
6339 	 * write one filemark at the time after EOT
6340 	 */
6341 	if (un->un_pos.eof >= ST_EOT) {
6342 		for (i = 0; i < wfm; i++) {
6343 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6344 			if (rval == EACCES) {
6345 				return (rval);
6346 			}
6347 			if (rval != 0) {
6348 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6349 				    "st_write_fm : EIO : write EOT file mark");
6350 				return (EIO);
6351 			}
6352 		}
6353 	} else {
6354 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6355 		if (rval == EACCES) {
6356 			return (rval);
6357 		}
6358 		if (rval) {
6359 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6360 			    "st_write_fm : EIO : write file mark");
6361 			return (EIO);
6362 		}
6363 	}
6364 
6365 	ASSERT(mutex_owned(ST_MUTEX));
6366 	return (0);
6367 }
6368 
6369 #ifdef STDEBUG
6370 static void
6371 st_start_dump(struct scsi_tape *un, struct buf *bp)
6372 {
6373 	struct scsi_pkt *pkt = BP_PKT(bp);
6374 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6375 
6376 	ST_FUNC(ST_DEVINFO, st_start_dump);
6377 
6378 	if ((st_debug & 0x7) < 6)
6379 		return;
6380 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6381 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6382 	    (void *)bp->b_forw, bp->b_bcount,
6383 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6384 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6385 	    "st_start: cdb",  (caddr_t)cdbp);
6386 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6387 	    "st_start: fileno=%d, blk=%d\n",
6388 	    un->un_pos.fileno, un->un_pos.blkno);
6389 }
6390 #endif
6391 
6392 
6393 /*
6394  * Command start && done functions
6395  */
6396 
6397 /*
6398  * st_start()
6399  *
6400  * Called from:
6401  *  st_strategy() to start a command.
6402  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6403  *  st_attach() when resuming from power down state.
6404  *  st_start_restart() to retry transport when device was previously busy.
6405  *  st_done_and_mutex_exit() to start the next command when previous is done.
6406  *
6407  * On entry:
6408  *  scsi_pkt may or may not be allocated.
6409  *
6410  */
6411 static void
6412 st_start(struct scsi_tape *un)
6413 {
6414 	struct buf *bp;
6415 	int status;
6416 	int queued;
6417 
6418 	ST_FUNC(ST_DEVINFO, st_start);
6419 	ASSERT(mutex_owned(ST_MUTEX));
6420 
6421 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6422 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6423 
6424 	if (un->un_recov_buf_busy) {
6425 		/* recovery commands can happen anytime */
6426 		bp = un->un_recov_buf;
6427 		queued = 0;
6428 	} else if (un->un_sbuf_busy) {
6429 		/* sbuf commands should only happen with an empty queue. */
6430 		ASSERT(un->un_quef == NULL);
6431 		ASSERT(un->un_runqf == NULL);
6432 		bp = un->un_sbufp;
6433 		queued = 0;
6434 	} else if (un->un_quef != NULL) {
6435 		if (un->un_persistence && un->un_persist_errors) {
6436 			return;
6437 		}
6438 		bp = un->un_quef;
6439 		queued = 1;
6440 	} else {
6441 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6442 		    "st_start() returning no buf found\n");
6443 		return;
6444 	}
6445 
6446 	ASSERT((bp->b_flags & B_DONE) == 0);
6447 
6448 	/*
6449 	 * Don't send more than un_throttle commands to the HBA
6450 	 */
6451 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6452 		/*
6453 		 * if doing recovery we know there is outstanding commands.
6454 		 */
6455 		if (bp != un->un_recov_buf) {
6456 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6457 			    "st_start returning throttle = %d or ncmds = %d\n",
6458 			    un->un_throttle, un->un_ncmds);
6459 			if (un->un_ncmds == 0) {
6460 				typedef void (*func)();
6461 				func fnc = (func)st_runout;
6462 
6463 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6464 				    "Sending delayed start to st_runout()\n");
6465 				mutex_exit(ST_MUTEX);
6466 				(void) timeout(fnc, un, drv_usectohz(1000000));
6467 				mutex_enter(ST_MUTEX);
6468 			}
6469 			return;
6470 		}
6471 	}
6472 
6473 	/*
6474 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6475 	 * build the command.
6476 	 */
6477 	if (BP_PKT(bp) == NULL) {
6478 		ASSERT((bp->b_flags & B_DONE) == 0);
6479 		st_make_cmd(un, bp, st_runout);
6480 		ASSERT((bp->b_flags & B_DONE) == 0);
6481 		status = geterror(bp);
6482 
6483 		/*
6484 		 * Some HBA's don't call bioerror() to set an error.
6485 		 * And geterror() returns zero if B_ERROR is not set.
6486 		 * So if we get zero we must check b_error.
6487 		 */
6488 		if (status == 0 && bp->b_error != 0) {
6489 			status = bp->b_error;
6490 			bioerror(bp, status);
6491 		}
6492 
6493 		/*
6494 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6495 		 * In tape ENOMEM has special meaning so we'll change it.
6496 		 */
6497 		if (status == ENOMEM) {
6498 			status = 0;
6499 			bioerror(bp, status);
6500 		}
6501 
6502 		/*
6503 		 * Did it fail and is it retryable?
6504 		 * If so return and wait for the callback through st_runout.
6505 		 * Also looks like scsi_init_pkt() will setup a callback even
6506 		 * if it isn't retryable.
6507 		 */
6508 		if (BP_PKT(bp) == NULL) {
6509 			if (status == 0) {
6510 				/*
6511 				 * If first attempt save state.
6512 				 */
6513 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6514 					un->un_laststate = un->un_state;
6515 					un->un_state = ST_STATE_RESOURCE_WAIT;
6516 				}
6517 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6518 				    "temp no resources for pkt\n");
6519 			} else if (status == EINVAL) {
6520 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6521 				    "scsi_init_pkt rejected pkt as too big\n");
6522 				if (un->un_persistence) {
6523 					st_set_pe_flag(un);
6524 				}
6525 			} else {
6526 				/*
6527 				 * Unlikely that it would be retryable then not.
6528 				 */
6529 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6530 					un->un_state = un->un_laststate;
6531 				}
6532 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6533 				    "perm no resources for pkt errno = 0x%x\n",
6534 				    status);
6535 			}
6536 			return;
6537 		}
6538 		/*
6539 		 * Worked this time set the state back.
6540 		 */
6541 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6542 			un->un_state = un->un_laststate;
6543 		}
6544 	}
6545 
6546 	if (queued) {
6547 		/*
6548 		 * move from waitq to runq
6549 		 */
6550 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6551 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6552 	}
6553 
6554 
6555 #ifdef STDEBUG
6556 	st_start_dump(un, bp);
6557 #endif
6558 
6559 	/* could not get here if throttle was zero */
6560 	un->un_last_throttle = un->un_throttle;
6561 	un->un_throttle = 0;	/* so nothing else will come in here */
6562 	un->un_ncmds++;
6563 
6564 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6565 
6566 	status = st_transport(un, BP_PKT(bp));
6567 
6568 	if (un->un_last_throttle) {
6569 		un->un_throttle = un->un_last_throttle;
6570 	}
6571 
6572 	if (status != TRAN_ACCEPT) {
6573 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6574 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6575 		    "Unhappy transport packet status 0x%x\n", status);
6576 
6577 		if (status == TRAN_BUSY) {
6578 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6579 
6580 			/*
6581 			 * If command recovery is enabled and this isn't
6582 			 * a recovery command try command recovery.
6583 			 */
6584 			if (pkti->privatelen == sizeof (recov_info) &&
6585 			    bp != un->un_recov_buf) {
6586 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6587 				    "Command Recovery called on busy send\n");
6588 				if (st_command_recovery(un, BP_PKT(bp),
6589 				    ATTEMPT_RETRY) == JUST_RETURN) {
6590 					return;
6591 				}
6592 			} else {
6593 				mutex_exit(ST_MUTEX);
6594 				if (st_handle_start_busy(un, bp,
6595 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6596 					mutex_enter(ST_MUTEX);
6597 					return;
6598 				}
6599 				/*
6600 				 * if too many retries, fail the transport
6601 				 */
6602 				mutex_enter(ST_MUTEX);
6603 			}
6604 		}
6605 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6606 		    "transport rejected %d\n", status);
6607 		bp->b_resid = bp->b_bcount;
6608 
6609 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6610 		ST_DO_ERRSTATS(un, st_transerrs);
6611 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6612 			st_bioerror(bp, EBUSY);
6613 		} else {
6614 			st_bioerror(bp, EIO);
6615 			st_set_pe_flag(un);
6616 		}
6617 		st_done_and_mutex_exit(un, bp);
6618 		mutex_enter(ST_MUTEX);
6619 	}
6620 
6621 	ASSERT(mutex_owned(ST_MUTEX));
6622 }
6623 
6624 /*
6625  * if the transport is busy, then put this bp back on the waitq
6626  */
6627 static int
6628 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6629     clock_t timeout_interval, int queued)
6630 {
6631 
6632 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6633 
6634 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6635 
6636 	mutex_enter(ST_MUTEX);
6637 
6638 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6639 	    "st_handle_start_busy()\n");
6640 
6641 	/*
6642 	 * Check to see if we hit the retry timeout and one last check for
6643 	 * making sure this is the last on the runq, if it is not, we have
6644 	 * to fail
6645 	 */
6646 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6647 	    ((queued) && (un->un_runql != bp))) {
6648 		mutex_exit(ST_MUTEX);
6649 		return (-1);
6650 	}
6651 
6652 	if (queued) {
6653 		/* put the bp back on the waitq */
6654 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6655 	}
6656 
6657 	/*
6658 	 * Decrement un_ncmds so that this
6659 	 * gets thru' st_start() again.
6660 	 */
6661 	un->un_ncmds--;
6662 
6663 	if (queued) {
6664 		/*
6665 		 * since this is an error case, we won't have to do this list
6666 		 * walking much. We've already made sure this bp was the
6667 		 * last on the runq
6668 		 */
6669 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6670 
6671 		/*
6672 		 * send a marker pkt, if appropriate
6673 		 */
6674 		st_hba_unflush(un);
6675 
6676 	}
6677 	/*
6678 	 * all queues are aligned, we are just waiting to
6679 	 * transport, don't alloc any more buf p's, when
6680 	 * st_start is reentered.
6681 	 */
6682 	(void) timeout(st_start_restart, un, timeout_interval);
6683 
6684 	mutex_exit(ST_MUTEX);
6685 	return (0);
6686 }
6687 
6688 
6689 /*
6690  * st_runout a callback that is called what a resource allocatation failed
6691  */
6692 static int
6693 st_runout(caddr_t arg)
6694 {
6695 	struct scsi_tape *un = (struct scsi_tape *)arg;
6696 	struct buf *bp;
6697 	int queued;
6698 
6699 	ASSERT(un != NULL);
6700 
6701 	ST_FUNC(ST_DEVINFO, st_runout);
6702 
6703 	mutex_enter(ST_MUTEX);
6704 
6705 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6706 
6707 	if (un->un_recov_buf_busy != 0) {
6708 		bp = un->un_recov_buf;
6709 		queued = 0;
6710 	} else if (un->un_sbuf_busy != 0) {
6711 		/* sbuf commands should only happen with an empty queue. */
6712 		ASSERT(un->un_quef == NULL);
6713 		ASSERT(un->un_runqf == NULL);
6714 		bp = un->un_sbufp;
6715 		queued = 0;
6716 	} else if (un->un_quef != NULL) {
6717 		bp = un->un_quef;
6718 		if (un->un_persistence && un->un_persist_errors) {
6719 			mutex_exit(ST_MUTEX);
6720 			bp->b_resid = bp->b_bcount;
6721 			biodone(bp);
6722 			return (1);
6723 		}
6724 		queued = 1;
6725 	} else {
6726 		ASSERT(1 == 0);
6727 		mutex_exit(ST_MUTEX);
6728 		return (1);
6729 	}
6730 
6731 	/*
6732 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6733 	 */
6734 	if ((bp != NULL) && (geterror(bp) != 0)) {
6735 
6736 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6737 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6738 		    bp->b_flags, geterror(bp));
6739 		ASSERT((bp->b_flags & B_DONE) == 0);
6740 
6741 		if (queued) {
6742 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6743 			    bp);
6744 		}
6745 		mutex_exit(ST_MUTEX);
6746 
6747 		ASSERT((bp->b_flags & B_DONE) == 0);
6748 
6749 		/*
6750 		 * Set resid, Error already set, then unblock calling thread.
6751 		 */
6752 		bp->b_resid = bp->b_bcount;
6753 		biodone(bp);
6754 	} else {
6755 		/*
6756 		 * Try Again
6757 		 */
6758 		st_start(un);
6759 		mutex_exit(ST_MUTEX);
6760 	}
6761 
6762 	/*
6763 	 * Comments courtesy of sd.c
6764 	 * The scsi_init_pkt routine allows for the callback function to
6765 	 * return a 0 indicating the callback should be rescheduled or a 1
6766 	 * indicating not to reschedule. This routine always returns 1
6767 	 * because the driver always provides a callback function to
6768 	 * scsi_init_pkt. This results in a callback always being scheduled
6769 	 * (via the scsi_init_pkt callback implementation) if a resource
6770 	 * failure occurs.
6771 	 */
6772 
6773 	return (1);
6774 }
6775 
6776 /*
6777  * st_done_and_mutex_exit()
6778  *	- remove bp from runq
6779  *	- start up the next request
6780  *	- if this was an asynch bp, clean up
6781  *	- exit with released mutex
6782  */
6783 static void
6784 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6785 {
6786 	int pe_flagged = 0;
6787 	struct scsi_pkt *pkt = BP_PKT(bp);
6788 	pkt_info *pktinfo = pkt->pkt_private;
6789 
6790 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6791 #if !defined(lint)
6792 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6793 #endif
6794 
6795 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6796 
6797 	ASSERT(mutex_owned(ST_MUTEX));
6798 
6799 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6800 
6801 	un->un_ncmds--;
6802 	cv_signal(&un->un_queue_cv);
6803 
6804 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6805 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6806 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6807 	    bp->b_resid, bp->b_flags);
6808 
6809 
6810 	/*
6811 	 * update kstats with transfer count info
6812 	 */
6813 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6814 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6815 		if (bp->b_flags & B_READ) {
6816 			IOSP->reads++;
6817 			IOSP->nread += n_done;
6818 		} else {
6819 			IOSP->writes++;
6820 			IOSP->nwritten += n_done;
6821 		}
6822 	}
6823 
6824 	/*
6825 	 * Start the next one before releasing resources on this one, if
6826 	 * there is something on the queue and persistent errors has not been
6827 	 * flagged
6828 	 */
6829 
6830 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6831 		un->un_last_resid = bp->b_resid;
6832 		un->un_last_count = bp->b_bcount;
6833 	}
6834 
6835 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6836 		cv_broadcast(&un->un_tape_busy_cv);
6837 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6838 	    (bp != un->un_recov_buf)) {
6839 		st_start(un);
6840 	}
6841 
6842 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6843 
6844 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6845 		/*
6846 		 * Since we marked this ourselves as ASYNC,
6847 		 * there isn't anybody around waiting for
6848 		 * completion any more.
6849 		 */
6850 		uchar_t *cmd = pkt->pkt_cdbp;
6851 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6852 			bp->b_un.b_addr = (caddr_t)0;
6853 		}
6854 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6855 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6856 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6857 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6858 		if (pkt) {
6859 			scsi_destroy_pkt(pkt);
6860 		}
6861 		un->un_sbuf_busy = 0;
6862 		cv_signal(&un->un_sbuf_cv);
6863 		mutex_exit(ST_MUTEX);
6864 		return;
6865 	}
6866 
6867 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6868 		/*
6869 		 * Copy status from scsi_pkt to uscsi_cmd
6870 		 * since st_uscsi_cmd needs it
6871 		 */
6872 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6873 	}
6874 
6875 
6876 #ifdef STDEBUG
6877 	if (((st_debug & 0x7) >= 4) &&
6878 	    (((un->un_pos.blkno % 100) == 0) ||
6879 	    (un->un_persistence && un->un_persist_errors))) {
6880 
6881 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6882 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6883 		    "un_errno = %d, un_pe = %d\n",
6884 		    un->un_ncmds, un->un_throttle, un->un_errno,
6885 		    un->un_persist_errors);
6886 	}
6887 
6888 #endif
6889 
6890 	mutex_exit(ST_MUTEX);
6891 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6892 	    "st_done_and_mutex_exit: freeing pkt\n");
6893 
6894 	if (pkt) {
6895 		scsi_destroy_pkt(pkt);
6896 	}
6897 
6898 	biodone(bp);
6899 
6900 	/*
6901 	 * now that we biodoned that command, if persistent errors have been
6902 	 * flagged, flush the waitq
6903 	 */
6904 	if (pe_flagged)
6905 		st_flush(un);
6906 }
6907 
6908 
6909 /*
6910  * Tape error, flush tape driver queue.
6911  */
6912 static void
6913 st_flush(struct scsi_tape *un)
6914 {
6915 	struct buf *bp;
6916 
6917 	ST_FUNC(ST_DEVINFO, st_flush);
6918 
6919 	mutex_enter(ST_MUTEX);
6920 
6921 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6922 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6923 	    un->un_ncmds, (void *)un->un_quef);
6924 
6925 	/*
6926 	 * if we still have commands outstanding, wait for them to come in
6927 	 * before flushing the queue, and make sure there is a queue
6928 	 */
6929 	if (un->un_ncmds || !un->un_quef)
6930 		goto exit;
6931 
6932 	/*
6933 	 * we have no more commands outstanding, so let's deal with special
6934 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6935 	 * is 0, then we know there was no error and we return a 0 read or
6936 	 * write before showing errors
6937 	 */
6938 
6939 	/* Flush the wait queue. */
6940 	while ((bp = un->un_quef) != NULL) {
6941 		un->un_quef = bp->b_actf;
6942 
6943 		bp->b_resid = bp->b_bcount;
6944 
6945 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6946 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6947 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6948 
6949 		st_set_pe_errno(un);
6950 
6951 		bioerror(bp, un->un_errno);
6952 
6953 		mutex_exit(ST_MUTEX);
6954 		/* it should have one, but check anyway */
6955 		if (BP_PKT(bp)) {
6956 			scsi_destroy_pkt(BP_PKT(bp));
6957 		}
6958 		biodone(bp);
6959 		mutex_enter(ST_MUTEX);
6960 	}
6961 
6962 	/*
6963 	 * It's not a bad practice to reset the
6964 	 * waitq tail pointer to NULL.
6965 	 */
6966 	un->un_quel = NULL;
6967 
6968 exit:
6969 	/* we mucked with the queue, so let others know about it */
6970 	cv_signal(&un->un_queue_cv);
6971 	mutex_exit(ST_MUTEX);
6972 }
6973 
6974 
6975 /*
6976  * Utility functions
6977  */
6978 static int
6979 st_determine_generic(struct scsi_tape *un)
6980 {
6981 	int bsize;
6982 	static char *cart = "0.25 inch cartridge";
6983 	char *sizestr;
6984 
6985 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6986 
6987 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6988 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6989 
6990 	ASSERT(mutex_owned(ST_MUTEX));
6991 
6992 	if (st_modesense(un)) {
6993 		return (-1);
6994 	}
6995 
6996 	bsize = (un->un_mspl->high_bl << 16)	|
6997 	    (un->un_mspl->mid_bl << 8)	|
6998 	    (un->un_mspl->low_bl);
6999 
7000 	if (bsize == 0) {
7001 		un->un_dp->options |= ST_VARIABLE;
7002 		un->un_dp->bsize = 0;
7003 		un->un_bsize = 0;
7004 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
7005 		/*
7006 		 * record size of this device too big.
7007 		 * try and convert it to variable record length.
7008 		 *
7009 		 */
7010 		un->un_dp->options |= ST_VARIABLE;
7011 		if (st_change_block_size(un, 0) != 0) {
7012 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7013 			    "Fixed Record Size %d is too large\n", bsize);
7014 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7015 			    "Cannot switch to variable record size\n");
7016 			un->un_dp->options &= ~ST_VARIABLE;
7017 			return (-1);
7018 		}
7019 	} else if (st_change_block_size(un, 0) == 0) {
7020 		/*
7021 		 * If the drive was set to a non zero block size,
7022 		 * See if it can be set to a zero block size.
7023 		 * If it works, ST_VARIABLE so user can set it as they want.
7024 		 */
7025 		un->un_dp->options |= ST_VARIABLE;
7026 		un->un_dp->bsize = 0;
7027 		un->un_bsize = 0;
7028 	} else {
7029 		un->un_dp->bsize = bsize;
7030 		un->un_bsize = bsize;
7031 	}
7032 
7033 
7034 	switch (un->un_mspl->density) {
7035 	default:
7036 	case 0x0:
7037 		/*
7038 		 * default density, cannot determine any other
7039 		 * information.
7040 		 */
7041 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7042 		un->un_dp->type = ST_TYPE_DEFAULT;
7043 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7044 		break;
7045 	case 0x1:
7046 	case 0x2:
7047 	case 0x3:
7048 	case 0x6:
7049 		/*
7050 		 * 1/2" reel
7051 		 */
7052 		sizestr = "0.50 inch reel";
7053 		un->un_dp->type = ST_TYPE_REEL;
7054 		un->un_dp->options |= ST_REEL;
7055 		un->un_dp->densities[0] = 0x1;
7056 		un->un_dp->densities[1] = 0x2;
7057 		un->un_dp->densities[2] = 0x6;
7058 		un->un_dp->densities[3] = 0x3;
7059 		break;
7060 	case 0x4:
7061 	case 0x5:
7062 	case 0x7:
7063 	case 0x0b:
7064 
7065 		/*
7066 		 * Quarter inch.
7067 		 */
7068 		sizestr = cart;
7069 		un->un_dp->type = ST_TYPE_DEFAULT;
7070 		un->un_dp->options |= ST_QIC;
7071 
7072 		un->un_dp->densities[1] = 0x4;
7073 		un->un_dp->densities[2] = 0x5;
7074 		un->un_dp->densities[3] = 0x7;
7075 		un->un_dp->densities[0] = 0x0b;
7076 		break;
7077 
7078 	case 0x0f:
7079 	case 0x10:
7080 	case 0x11:
7081 	case 0x12:
7082 		/*
7083 		 * QIC-120, QIC-150, QIC-320, QIC-600
7084 		 */
7085 		sizestr = cart;
7086 		un->un_dp->type = ST_TYPE_DEFAULT;
7087 		un->un_dp->options |= ST_QIC;
7088 		un->un_dp->densities[0] = 0x0f;
7089 		un->un_dp->densities[1] = 0x10;
7090 		un->un_dp->densities[2] = 0x11;
7091 		un->un_dp->densities[3] = 0x12;
7092 		break;
7093 
7094 	case 0x09:
7095 	case 0x0a:
7096 	case 0x0c:
7097 	case 0x0d:
7098 		/*
7099 		 * 1/2" cartridge tapes. Include HI-TC.
7100 		 */
7101 		sizestr = cart;
7102 		sizestr[2] = '5';
7103 		sizestr[3] = '0';
7104 		un->un_dp->type = ST_TYPE_HIC;
7105 		un->un_dp->densities[0] = 0x09;
7106 		un->un_dp->densities[1] = 0x0a;
7107 		un->un_dp->densities[2] = 0x0c;
7108 		un->un_dp->densities[3] = 0x0d;
7109 		break;
7110 
7111 	case 0x13:
7112 			/* DDS-2/DDS-3 scsi spec densities */
7113 	case 0x24:
7114 	case 0x25:
7115 	case 0x26:
7116 		sizestr = "DAT Data Storage (DDS)";
7117 		un->un_dp->type = ST_TYPE_DAT;
7118 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7119 		break;
7120 
7121 	case 0x14:
7122 		/*
7123 		 * Helical Scan (Exabyte) devices
7124 		 */
7125 		sizestr = "8mm helical scan cartridge";
7126 		un->un_dp->type = ST_TYPE_EXABYTE;
7127 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7128 		break;
7129 	}
7130 
7131 	/*
7132 	 * Assume LONG ERASE, BSF and BSR
7133 	 */
7134 
7135 	un->un_dp->options |=
7136 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7137 
7138 	/*
7139 	 * Only if mode sense data says no buffered write, set NOBUF
7140 	 */
7141 	if (un->un_mspl->bufm == 0)
7142 		un->un_dp->options |= ST_NOBUF;
7143 
7144 	/*
7145 	 * set up large read and write retry counts
7146 	 */
7147 
7148 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7149 
7150 	/*
7151 	 * If this is a 0.50 inch reel tape, and
7152 	 * it is *not* variable mode, try and
7153 	 * set it to variable record length
7154 	 * mode.
7155 	 */
7156 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7157 	    (un->un_dp->options & ST_VARIABLE)) {
7158 		if (st_change_block_size(un, 0) == 0) {
7159 			un->un_dp->bsize = 0;
7160 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7161 			    un->un_mspl->low_bl = 0;
7162 		}
7163 	}
7164 
7165 	/*
7166 	 * Write to console about type of device found
7167 	 */
7168 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7169 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7170 	    sizestr);
7171 	if (un->un_dp->options & ST_VARIABLE) {
7172 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7173 		    "!Variable record length I/O\n");
7174 	} else {
7175 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7176 		    "!Fixed record length (%d byte blocks) I/O\n",
7177 		    un->un_dp->bsize);
7178 	}
7179 	ASSERT(mutex_owned(ST_MUTEX));
7180 	return (0);
7181 }
7182 
7183 static int
7184 st_determine_density(struct scsi_tape *un, int rw)
7185 {
7186 	int rval = 0;
7187 
7188 	ST_FUNC(ST_DEVINFO, st_determine_density);
7189 
7190 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7191 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7192 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7193 
7194 	ASSERT(mutex_owned(ST_MUTEX));
7195 
7196 	/*
7197 	 * If we're past BOT, density is determined already.
7198 	 */
7199 	if (un->un_pos.pmode == logical) {
7200 		if (un->un_pos.lgclblkno != 0) {
7201 			goto exit;
7202 		}
7203 	} else if (un->un_pos.pmode == legacy) {
7204 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7205 			/*
7206 			 * XXX: put in a bitch message about attempting to
7207 			 * XXX: change density past BOT.
7208 			 */
7209 			goto exit;
7210 		}
7211 	} else {
7212 		goto exit;
7213 	}
7214 	if ((un->un_pos.pmode == logical) &&
7215 	    (un->un_pos.lgclblkno != 0)) {
7216 		goto exit;
7217 	}
7218 
7219 
7220 	/*
7221 	 * If we're going to be writing, we set the density
7222 	 */
7223 	if (rw == 0 || rw == B_WRITE) {
7224 		/* un_curdens is used as an index into densities table */
7225 		un->un_curdens = MT_DENSITY(un->un_dev);
7226 		if (st_set_density(un)) {
7227 			rval = -1;
7228 		}
7229 		goto exit;
7230 	}
7231 
7232 	/*
7233 	 * If density is known already,
7234 	 * we don't have to get it again.(?)
7235 	 */
7236 	if (!un->un_density_known) {
7237 		if (st_get_density(un)) {
7238 			rval = -1;
7239 		}
7240 	}
7241 
7242 exit:
7243 	ASSERT(mutex_owned(ST_MUTEX));
7244 	return (rval);
7245 }
7246 
7247 
7248 /*
7249  * Try to determine density. We do this by attempting to read the
7250  * first record off the tape, cycling through the available density
7251  * codes as we go.
7252  */
7253 
7254 static int
7255 st_get_density(struct scsi_tape *un)
7256 {
7257 	int succes = 0, rval = -1, i;
7258 	uint_t size;
7259 	uchar_t dens, olddens;
7260 
7261 	ST_FUNC(ST_DEVINFO, st_get_density);
7262 
7263 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7264 	    "st_get_density(un = 0x%p)\n", (void*)un);
7265 
7266 	ASSERT(mutex_owned(ST_MUTEX));
7267 
7268 	/*
7269 	 * If Auto Density override is enabled The drive has
7270 	 * only one density and there is no point in attempting
7271 	 * find the correct one.
7272 	 *
7273 	 * Since most modern drives auto detect the density
7274 	 * and format of the recorded media before they come
7275 	 * ready. What this function does is a legacy behavior
7276 	 * and modern drives not only don't need it, The backup
7277 	 * utilities that do positioning via uscsi find the un-
7278 	 * expected rewinds problematic.
7279 	 *
7280 	 * The drives that need this are old reel to reel devices.
7281 	 * I took a swag and said they must be scsi-1 or older.
7282 	 * I don't beleave there will any of the newer devices
7283 	 * that need this. There will be some scsi-1 devices that
7284 	 * don't need this but I don't think they will be using the
7285 	 * BIG aftermarket backup and restore utilitys.
7286 	 */
7287 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7288 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7289 		un->un_density_known = 1;
7290 		rval = 0;
7291 		goto exit;
7292 	}
7293 
7294 	/*
7295 	 * This will only work on variable record length tapes
7296 	 * if and only if all variable record length tapes autodensity
7297 	 * select.
7298 	 */
7299 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7300 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7301 
7302 	/*
7303 	 * Start at the specified density
7304 	 */
7305 
7306 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7307 
7308 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7309 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7310 		/*
7311 		 * If we've done this density before,
7312 		 * don't bother to do it again.
7313 		 */
7314 		dens = un->un_dp->densities[un->un_curdens];
7315 		if (i > 0 && dens == olddens)
7316 			continue;
7317 		olddens = dens;
7318 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7319 		    "trying density 0x%x\n", dens);
7320 		if (st_set_density(un)) {
7321 			continue;
7322 		}
7323 
7324 		/*
7325 		 * XXX - the creates lots of headaches and slowdowns - must
7326 		 * fix.
7327 		 */
7328 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7329 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7330 			break;
7331 		}
7332 		if (succes) {
7333 			st_init(un);
7334 			rval = 0;
7335 			un->un_density_known = 1;
7336 			break;
7337 		}
7338 	}
7339 	kmem_free(un->un_tmpbuf, size);
7340 	un->un_tmpbuf = 0;
7341 
7342 exit:
7343 	ASSERT(mutex_owned(ST_MUTEX));
7344 	return (rval);
7345 }
7346 
7347 static int
7348 st_set_density(struct scsi_tape *un)
7349 {
7350 	int rval = 0;
7351 
7352 	ST_FUNC(ST_DEVINFO, st_set_density);
7353 
7354 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7355 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7356 	    un->un_dp->densities[un->un_curdens]);
7357 
7358 	ASSERT(mutex_owned(ST_MUTEX));
7359 
7360 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7361 
7362 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7363 		/*
7364 		 * If auto density override is not set, Use mode select
7365 		 * to set density and compression.
7366 		 */
7367 		if (st_modeselect(un)) {
7368 			rval = -1;
7369 		}
7370 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7371 		/*
7372 		 * If auto density and mode select compression are set,
7373 		 * This is a drive with one density code but compression
7374 		 * can be enabled or disabled.
7375 		 * Set compression but no need to set density.
7376 		 */
7377 		rval = st_set_compression(un);
7378 		if ((rval != 0) && (rval != EALREADY)) {
7379 			rval = -1;
7380 		} else {
7381 			rval = 0;
7382 		}
7383 	}
7384 
7385 	/* If sucessful set density and/or compression, mark density known */
7386 	if (rval == 0) {
7387 		un->un_density_known = 1;
7388 	}
7389 
7390 	ASSERT(mutex_owned(ST_MUTEX));
7391 	return (rval);
7392 }
7393 
7394 static int
7395 st_loadtape(struct scsi_tape *un)
7396 {
7397 	int rval;
7398 
7399 	ST_FUNC(ST_DEVINFO, st_loadtape);
7400 
7401 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7402 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7403 
7404 	ASSERT(mutex_owned(ST_MUTEX));
7405 
7406 	rval = st_update_block_pos(un, st_cmd, 0);
7407 	if (rval == EACCES) {
7408 		return (rval);
7409 	}
7410 
7411 	/*
7412 	 * 'LOAD' the tape to BOT by rewinding
7413 	 */
7414 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7415 	if (rval == 0) {
7416 		st_init(un);
7417 		un->un_density_known = 0;
7418 	}
7419 
7420 	ASSERT(mutex_owned(ST_MUTEX));
7421 	return (rval);
7422 }
7423 
7424 
7425 /*
7426  * Note: QIC devices aren't so smart.  If you try to append
7427  * after EOM, the write can fail because the device doesn't know
7428  * it's at EOM.	 In that case, issue a read.  The read should fail
7429  * because there's no data, but the device knows it's at EOM,
7430  * so a subsequent write should succeed.  To further confuse matters,
7431  * the target returns the same error if the tape is positioned
7432  * such that a write would overwrite existing data.  That's why
7433  * we have to do the append test.  A read in the middle of
7434  * recorded data would succeed, thus indicating we're attempting
7435  * something illegal.
7436  */
7437 
7438 
7439 static void
7440 st_test_append(struct buf *bp)
7441 {
7442 	dev_t dev = bp->b_edev;
7443 	struct scsi_tape *un;
7444 	uchar_t status;
7445 	unsigned bcount;
7446 
7447 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7448 
7449 	ST_FUNC(ST_DEVINFO, st_test_append);
7450 
7451 	ASSERT(mutex_owned(ST_MUTEX));
7452 
7453 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7454 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7455 
7456 	un->un_laststate = un->un_state;
7457 	un->un_state = ST_STATE_APPEND_TESTING;
7458 	un->un_test_append = 0;
7459 
7460 	/*
7461 	 * first, map in the buffer, because we're doing a double write --
7462 	 * first into the kernel, then onto the tape.
7463 	 */
7464 	bp_mapin(bp);
7465 
7466 	/*
7467 	 * get a copy of the data....
7468 	 */
7469 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7470 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7471 
7472 	/*
7473 	 * attempt the write..
7474 	 */
7475 
7476 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7477 success:
7478 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7479 		    "append write succeeded\n");
7480 		bp->b_resid = un->un_sbufp->b_resid;
7481 		mutex_exit(ST_MUTEX);
7482 		bcount = (unsigned)bp->b_bcount;
7483 		biodone(bp);
7484 		mutex_enter(ST_MUTEX);
7485 		un->un_laststate = un->un_state;
7486 		un->un_state = ST_STATE_OPEN;
7487 		kmem_free(un->un_tmpbuf, bcount);
7488 		un->un_tmpbuf = NULL;
7489 		return;
7490 	}
7491 
7492 	/*
7493 	 * The append failed. Do a short read. If that fails,  we are at EOM
7494 	 * so we can retry the write command. If that succeeds, than we're
7495 	 * all screwed up (the controller reported a real error).
7496 	 *
7497 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7498 	 * XXX: block size?
7499 	 *
7500 	 */
7501 	status = un->un_status;
7502 	un->un_status = 0;
7503 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7504 	if (un->un_status == KEY_BLANK_CHECK) {
7505 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7506 		    "append at EOM\n");
7507 		/*
7508 		 * Okay- the read failed. We should actually have confused
7509 		 * the controller enough to allow writing. In any case, the
7510 		 * i/o is on its own from here on out.
7511 		 */
7512 		un->un_laststate = un->un_state;
7513 		un->un_state = ST_STATE_OPEN;
7514 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7515 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7516 		    SYNC_CMD) == 0) {
7517 			goto success;
7518 		}
7519 	}
7520 
7521 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7522 	    "append write failed- not at EOM\n");
7523 	bp->b_resid = bp->b_bcount;
7524 	st_bioerror(bp, EIO);
7525 
7526 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7527 	    "st_test_append : EIO : append write failed - not at EOM");
7528 
7529 	/*
7530 	 * backspace one record to get back to where we were
7531 	 */
7532 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7533 		un->un_pos.pmode = invalid;
7534 	}
7535 
7536 	un->un_err_resid = bp->b_resid;
7537 	un->un_status = status;
7538 
7539 	/*
7540 	 * Note: biodone will do a bp_mapout()
7541 	 */
7542 	mutex_exit(ST_MUTEX);
7543 	bcount = (unsigned)bp->b_bcount;
7544 	biodone(bp);
7545 	mutex_enter(ST_MUTEX);
7546 	un->un_laststate = un->un_state;
7547 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7548 	kmem_free(un->un_tmpbuf, bcount);
7549 	un->un_tmpbuf = NULL;
7550 }
7551 
7552 /*
7553  * Special command handler
7554  */
7555 
7556 /*
7557  * common st_cmd code. The fourth parameter states
7558  * whether the caller wishes to await the results
7559  * Note the release of the mutex during most of the function
7560  */
7561 static int
7562 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7563 {
7564 	struct buf *bp;
7565 	int err;
7566 	uint_t last_err_resid;
7567 
7568 	ST_FUNC(ST_DEVINFO, st_cmd);
7569 
7570 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7571 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7572 	    un->un_dev, com, count, wait);
7573 
7574 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7575 	ASSERT(mutex_owned(ST_MUTEX));
7576 
7577 #ifdef STDEBUG
7578 	if ((st_debug & 0x7)) {
7579 		st_debug_cmds(un, com, count, wait);
7580 	}
7581 #endif
7582 
7583 	st_wait_for_io(un);
7584 
7585 	/* check to see if this command requires the drive to be reserved */
7586 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7587 
7588 	if (err) {
7589 		return (err);
7590 	}
7591 
7592 	/*
7593 	 * A space command is not recoverable if we don't know were we
7594 	 * were when it was issued.
7595 	 */
7596 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7597 		(void) st_update_block_pos(un, st_cmd, 0);
7598 	}
7599 
7600 	/*
7601 	 * Forground should not be doing anything while recovery is active.
7602 	 */
7603 	ASSERT(un->un_recov_buf_busy == 0);
7604 
7605 	while (un->un_sbuf_busy)
7606 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7607 	un->un_sbuf_busy = 1;
7608 
7609 	bp = un->un_sbufp;
7610 	bzero(bp, sizeof (buf_t));
7611 
7612 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7613 
7614 	err = st_setup_cmd(un, bp, com, count);
7615 
7616 	un->un_sbuf_busy = 0;
7617 
7618 	/*
7619 	 * If was a space command need to update logical block position.
7620 	 * Only do this if the command was sucessful or it will mask the fact
7621 	 * that the space command failed by promoting the pmode to logical.
7622 	 */
7623 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7624 	    (un->un_pos.pmode != invalid)) {
7625 		un->un_running.pmode = invalid;
7626 		last_err_resid = un->un_err_resid;
7627 		(void) st_update_block_pos(un, st_cmd, 1);
7628 		/*
7629 		 * Set running position to invalid so it updates on the
7630 		 * next command.
7631 		 */
7632 		un->un_running.pmode = invalid;
7633 		un->un_err_resid = last_err_resid;
7634 	}
7635 
7636 	cv_signal(&un->un_sbuf_cv);
7637 
7638 	return (err);
7639 }
7640 
7641 static int
7642 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7643 {
7644 	int err;
7645 	dev_t dev = un->un_dev;
7646 
7647 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7648 	/*
7649 	 * Set count to the actual size of the data tranfer.
7650 	 * For commands with no data transfer, set bp->b_bcount
7651 	 * to the value to be used when constructing the
7652 	 * cdb in st_make_cmd().
7653 	 */
7654 	switch (com) {
7655 	case SCMD_READ:
7656 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7657 		    "special read %"PRId64"\n", count);
7658 		bp->b_flags |= B_READ;
7659 		bp->b_un.b_addr = un->un_tmpbuf;
7660 		break;
7661 
7662 	case SCMD_WRITE:
7663 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7664 		    "special write %"PRId64"\n", count);
7665 		bp->b_un.b_addr = un->un_tmpbuf;
7666 		break;
7667 
7668 	case SCMD_WRITE_FILE_MARK:
7669 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7670 		    "write %"PRId64" file marks\n", count);
7671 		bp->b_bcount = count;
7672 		count = 0;
7673 		break;
7674 
7675 	case SCMD_REWIND:
7676 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7677 		bp->b_bcount = count;
7678 		count = 0;
7679 		break;
7680 
7681 	case SCMD_SPACE:
7682 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7683 		/*
7684 		 * If the user could have entered a number that will
7685 		 * not fit in the 12 bit count field of space(8),
7686 		 * use space(16).
7687 		 */
7688 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7689 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7690 			com = SCMD_SPACE_G4;
7691 		}
7692 		bp->b_bcount = count;
7693 		count = 0;
7694 		break;
7695 
7696 	case SCMD_RESERVE:
7697 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7698 		bp->b_bcount = 0;
7699 		count = 0;
7700 		break;
7701 
7702 	case SCMD_RELEASE:
7703 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7704 		bp->b_bcount = 0;
7705 		count = 0;
7706 		break;
7707 
7708 	case SCMD_LOAD:
7709 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7710 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7711 		bp->b_bcount = count;
7712 		count = 0;
7713 		break;
7714 
7715 	case SCMD_ERASE:
7716 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7717 		    "erase tape\n");
7718 		bp->b_bcount = count;
7719 		count = 0;
7720 		break;
7721 
7722 	case SCMD_MODE_SENSE:
7723 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7724 		    "mode sense\n");
7725 		bp->b_flags |= B_READ;
7726 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7727 		break;
7728 
7729 	case SCMD_MODE_SELECT:
7730 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7731 		    "mode select\n");
7732 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7733 		break;
7734 
7735 	case SCMD_READ_BLKLIM:
7736 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7737 		    "read block limits\n");
7738 		bp->b_bcount = count;
7739 		bp->b_flags |= B_READ;
7740 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7741 		break;
7742 
7743 	case SCMD_TEST_UNIT_READY:
7744 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7745 		    "test unit ready\n");
7746 		bp->b_bcount = 0;
7747 		count = 0;
7748 		break;
7749 
7750 	case SCMD_DOORLOCK:
7751 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7752 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7753 		bp->b_bcount = count = 0;
7754 		break;
7755 
7756 	case SCMD_READ_POSITION:
7757 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7758 		    "read position\n");
7759 		switch (un->un_read_pos_type) {
7760 		case LONG_POS:
7761 			count = sizeof (tape_position_long_t);
7762 			break;
7763 		case EXT_POS:
7764 			count = min(count, sizeof (tape_position_ext_t));
7765 			break;
7766 		case SHORT_POS:
7767 			count = sizeof (tape_position_t);
7768 			break;
7769 		default:
7770 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7771 			    "Unknown read position type 0x%x in "
7772 			    "st_make_cmd()\n", un->un_read_pos_type);
7773 		}
7774 		bp->b_bcount = count;
7775 		bp->b_flags |= B_READ;
7776 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7777 		break;
7778 
7779 	default:
7780 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7781 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7782 	}
7783 
7784 	mutex_exit(ST_MUTEX);
7785 
7786 	if (count > 0) {
7787 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7788 		/*
7789 		 * We're going to do actual I/O.
7790 		 * Set things up for physio.
7791 		 */
7792 		struct iovec aiov;
7793 		struct uio auio;
7794 		struct uio *uio = &auio;
7795 
7796 		bzero(&auio, sizeof (struct uio));
7797 		bzero(&aiov, sizeof (struct iovec));
7798 		aiov.iov_base = bp->b_un.b_addr;
7799 		aiov.iov_len = count;
7800 
7801 		uio->uio_iov = &aiov;
7802 		uio->uio_iovcnt = 1;
7803 		uio->uio_resid = aiov.iov_len;
7804 		uio->uio_segflg = UIO_SYSSPACE;
7805 
7806 		/*
7807 		 * Let physio do the rest...
7808 		 */
7809 		bp->b_forw = (struct buf *)(uintptr_t)com;
7810 		bp->b_back = NULL;
7811 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7812 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7813 		    "st_setup_cmd: physio returns %d\n", err);
7814 	} else {
7815 		/*
7816 		 * Mimic physio
7817 		 */
7818 		bp->b_forw = (struct buf *)(uintptr_t)com;
7819 		bp->b_back = NULL;
7820 		bp->b_edev = dev;
7821 		bp->b_dev = cmpdev(dev);
7822 		bp->b_blkno = 0;
7823 		bp->b_resid = 0;
7824 		(void) st_strategy(bp);
7825 		if (bp->b_flags & B_ASYNC) {
7826 			/*
7827 			 * This is an async command- the caller won't wait
7828 			 * and doesn't care about errors.
7829 			 */
7830 			mutex_enter(ST_MUTEX);
7831 			return (0);
7832 		}
7833 
7834 		/*
7835 		 * BugTraq #4260046
7836 		 * ----------------
7837 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7838 		 * unconditionally. The old comment said...
7839 		 *
7840 		 * "if strategy was flagged with  persistent errors, we would
7841 		 *  have an error here, and the bp would never be sent, so we
7842 		 *  don't want to wait on a bp that was never sent...or hang"
7843 		 *
7844 		 * The new rationale, courtesy of Chitrank...
7845 		 *
7846 		 * "we should unconditionally biowait() here because
7847 		 *  st_strategy() will do a biodone() in the persistent error
7848 		 *  case and the following biowait() will return immediately.
7849 		 *  If not, in the case of "errors after pkt alloc" in
7850 		 *  st_start(), we will not biowait here which will cause the
7851 		 *  next biowait() to return immediately which will cause
7852 		 *  us to send out the next command. In the case where both of
7853 		 *  these use the sbuf, when the first command completes we'll
7854 		 *  free the packet attached to sbuf and the same pkt will
7855 		 *  get freed again when we complete the second command.
7856 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7857 		 *  st_start() for the pkt alloc failure case because physio()
7858 		 *  does biowait() and will hang if we don't do biodone()"
7859 		 */
7860 
7861 		err = biowait(bp);
7862 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7863 		    "st_setup_cmd: biowait returns %d\n", err);
7864 	}
7865 
7866 	mutex_enter(ST_MUTEX);
7867 
7868 	return (err);
7869 }
7870 
7871 static int
7872 st_set_compression(struct scsi_tape *un)
7873 {
7874 	int rval;
7875 	int turn_compression_on;
7876 	minor_t minor;
7877 
7878 	ST_FUNC(ST_DEVINFO, st_set_compression);
7879 
7880 	/*
7881 	 * Drive either dosn't have compression or it is controlled with
7882 	 * special density codes. Return ENOTTY so caller
7883 	 * knows nothing was done.
7884 	 */
7885 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7886 		un->un_comp_page = 0;
7887 		return (ENOTTY);
7888 	}
7889 
7890 	/* set compression based on minor node opened */
7891 	minor = MT_DENSITY(un->un_dev);
7892 
7893 	/*
7894 	 * If this the compression density or
7895 	 * the drive has two densities and uses mode select for
7896 	 * control of compression turn on compression for MT_DENSITY2
7897 	 * as well.
7898 	 */
7899 	if ((minor == ST_COMPRESSION_DENSITY) ||
7900 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7901 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7902 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7903 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7904 
7905 		turn_compression_on = 1;
7906 	} else {
7907 		turn_compression_on = 0;
7908 	}
7909 
7910 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7911 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7912 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7913 
7914 	/*
7915 	 * Need to determine which page does the device use for compression.
7916 	 * First try the data compression page. If this fails try the device
7917 	 * configuration page
7918 	 */
7919 
7920 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7921 		rval = st_set_datacomp_page(un, turn_compression_on);
7922 		if (rval == EALREADY) {
7923 			return (rval);
7924 		}
7925 		if (rval != 0) {
7926 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7927 				/*
7928 				 * This device does not support data
7929 				 * compression page
7930 				 */
7931 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7932 			} else if (un->un_state >= ST_STATE_OPEN) {
7933 				un->un_pos.pmode = invalid;
7934 				rval = EIO;
7935 			} else {
7936 				rval = -1;
7937 			}
7938 		} else {
7939 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7940 		}
7941 	}
7942 
7943 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7944 		rval = st_set_devconfig_page(un, turn_compression_on);
7945 		if (rval == EALREADY) {
7946 			return (rval);
7947 		}
7948 		if (rval != 0) {
7949 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7950 				/*
7951 				 * This device does not support
7952 				 * compression at all advice the
7953 				 * user and unset ST_MODE_SEL_COMP
7954 				 */
7955 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7956 				un->un_comp_page = 0;
7957 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7958 				    "Device Does Not Support Compression\n");
7959 			} else if (un->un_state >= ST_STATE_OPEN) {
7960 				un->un_pos.pmode = invalid;
7961 				rval = EIO;
7962 			} else {
7963 				rval = -1;
7964 			}
7965 		}
7966 	}
7967 
7968 	return (rval);
7969 }
7970 
7971 /*
7972  * set or unset compression thru device configuration page.
7973  */
7974 static int
7975 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7976 {
7977 	unsigned char cflag;
7978 	int rval = 0;
7979 
7980 
7981 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7982 
7983 	ASSERT(mutex_owned(ST_MUTEX));
7984 
7985 	/*
7986 	 * if the mode sense page is not the correct one, load the correct one.
7987 	 */
7988 	if (un->un_mspl->page_code != ST_DEV_CONFIG_PAGE) {
7989 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_CONFIG_PAGE,
7990 		    un->un_mspl, sizeof (struct seq_mode));
7991 		if (rval)
7992 			return (rval);
7993 	}
7994 
7995 	/*
7996 	 * Figure what to set compression flag to.
7997 	 */
7998 	if (compression_on) {
7999 		/* They have selected a compression node */
8000 		if (un->un_dp->type == ST_TYPE_FUJI) {
8001 			cflag = 0x84;   /* use EDRC */
8002 		} else {
8003 			cflag = ST_DEV_CONFIG_DEF_COMP;
8004 		}
8005 	} else {
8006 		cflag = ST_DEV_CONFIG_NO_COMP;
8007 	}
8008 
8009 	/*
8010 	 * If compression is already set the way it was requested.
8011 	 * And if this not the first time we has tried.
8012 	 */
8013 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
8014 	    (un->un_comp_page == ST_DEV_CONFIG_PAGE)) {
8015 		return (EALREADY);
8016 	}
8017 
8018 	un->un_mspl->page.dev.comp_alg = cflag;
8019 	/*
8020 	 * need to send mode select even if correct compression is
8021 	 * already set since need to set density code
8022 	 */
8023 
8024 #ifdef STDEBUG
8025 	if ((st_debug & 0x7) >= 6) {
8026 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8027 		    "st_set_devconfig_page: sense data for mode select",
8028 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8029 	}
8030 #endif
8031 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8032 	    sizeof (struct seq_mode));
8033 
8034 	return (rval);
8035 }
8036 
8037 /*
8038  * set/reset compression bit thru data compression page
8039  */
8040 static int
8041 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8042 {
8043 	int compression_on_already;
8044 	int rval = 0;
8045 
8046 
8047 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8048 
8049 	ASSERT(mutex_owned(ST_MUTEX));
8050 
8051 	/*
8052 	 * if the mode sense page is not the correct one, load the correct one.
8053 	 */
8054 	if (un->un_mspl->page_code != ST_DEV_DATACOMP_PAGE) {
8055 		rval = st_gen_mode_sense(un, st_uscsi_cmd, ST_DEV_DATACOMP_PAGE,
8056 		    un->un_mspl, sizeof (struct seq_mode));
8057 		if (rval)
8058 			return (rval);
8059 	}
8060 
8061 	/*
8062 	 * If drive is not capable of compression (at this time)
8063 	 * return EALREADY so caller doesn't think that this page
8064 	 * is not supported. This check is for drives that can
8065 	 * disable compression from the front panel or configuration.
8066 	 * I doubt that a drive that supports this page is not really
8067 	 * capable of compression.
8068 	 */
8069 	if (un->un_mspl->page.comp.dcc == 0) {
8070 		return (EALREADY);
8071 	}
8072 
8073 	/* See if compression currently turned on */
8074 	if (un->un_mspl->page.comp.dce) {
8075 		compression_on_already = 1;
8076 	} else {
8077 		compression_on_already = 0;
8078 	}
8079 
8080 	/*
8081 	 * If compression is already set the way it was requested.
8082 	 * And if this not the first time we has tried.
8083 	 */
8084 	if ((compression_on == compression_on_already) &&
8085 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8086 		return (EALREADY);
8087 	}
8088 
8089 	/*
8090 	 * if we are already set to the appropriate compression
8091 	 * mode, don't set it again
8092 	 */
8093 	if (compression_on) {
8094 		/* compression selected */
8095 		un->un_mspl->page.comp.dce = 1;
8096 	} else {
8097 		un->un_mspl->page.comp.dce = 0;
8098 	}
8099 
8100 
8101 #ifdef STDEBUG
8102 	if ((st_debug & 0x7) >= 6) {
8103 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8104 		    "st_set_datacomp_page: sense data for mode select",
8105 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8106 	}
8107 #endif
8108 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8109 	    sizeof (struct seq_mode));
8110 
8111 	return (rval);
8112 }
8113 
8114 static int
8115 st_modesense(struct scsi_tape *un)
8116 {
8117 	int rval;
8118 	uchar_t page;
8119 
8120 	ST_FUNC(ST_DEVINFO, st_modesense);
8121 
8122 	page = un->un_comp_page;
8123 
8124 	switch (page) {
8125 	case ST_DEV_DATACOMP_PAGE:
8126 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8127 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8128 		    sizeof (struct seq_mode));
8129 		break;
8130 
8131 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8132 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8133 			page = ST_DEV_DATACOMP_PAGE;
8134 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8135 			    un->un_mspl, sizeof (struct seq_mode));
8136 			if (rval == 0 && un->un_mspl->page_code == page) {
8137 				un->un_comp_page = page;
8138 				break;
8139 			}
8140 			page = ST_DEV_CONFIG_PAGE;
8141 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8142 			    un->un_mspl, sizeof (struct seq_mode));
8143 			if (rval == 0 && un->un_mspl->page_code == page) {
8144 				un->un_comp_page = page;
8145 				break;
8146 			}
8147 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8148 			un->un_comp_page = 0;
8149 		} else {
8150 			un->un_comp_page = 0;
8151 		}
8152 
8153 	default:	/* FALLTHROUGH */
8154 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8155 	}
8156 	return (rval);
8157 }
8158 
8159 static int
8160 st_modeselect(struct scsi_tape *un)
8161 {
8162 	int rval = 0;
8163 	int ix;
8164 
8165 	ST_FUNC(ST_DEVINFO, st_modeselect);
8166 
8167 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8168 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8169 	    un->un_dev, un->un_mspl->density);
8170 
8171 	ASSERT(mutex_owned(ST_MUTEX));
8172 
8173 	/*
8174 	 * The parameter list should be the same for all of the
8175 	 * cases that follow so set them here
8176 	 *
8177 	 * Try mode select first if if fails set fields manually
8178 	 */
8179 	rval = st_modesense(un);
8180 	if (rval != 0) {
8181 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8182 		    "st_modeselect: First mode sense failed\n");
8183 		un->un_mspl->bd_len  = 8;
8184 		un->un_mspl->high_nb = 0;
8185 		un->un_mspl->mid_nb  = 0;
8186 		un->un_mspl->low_nb  = 0;
8187 	}
8188 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8189 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8190 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8191 
8192 
8193 	/*
8194 	 * If configured to use a specific density code for a media type.
8195 	 * curdens is previously set by the minor node opened.
8196 	 * If the media type doesn't match the minor node we change it so it
8197 	 * looks like the correct one was opened.
8198 	 */
8199 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8200 		uchar_t best;
8201 
8202 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8203 			if (un->un_mspl->media_type ==
8204 			    un->un_dp->mediatype[ix]) {
8205 				best = ix;
8206 				/*
8207 				 * It matches but it might not be the only one.
8208 				 * Use the highest matching media type but not
8209 				 * to exceed the density selected by the open.
8210 				 */
8211 				if (ix < un->un_curdens) {
8212 					continue;
8213 				}
8214 				un->un_curdens = ix;
8215 				break;
8216 			}
8217 		}
8218 		/* If a match was found best will not be 0xff any more */
8219 		if (best < NDENSITIES) {
8220 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8221 			    "found media 0x%X using density 0x%X\n",
8222 			    un->un_mspl->media_type,
8223 			    un->un_dp->densities[best]);
8224 			un->un_mspl->density = un->un_dp->densities[best];
8225 		} else {
8226 			/* Otherwise set density based on minor node opened */
8227 			un->un_mspl->density =
8228 			    un->un_dp->densities[un->un_curdens];
8229 		}
8230 	} else {
8231 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8232 	}
8233 
8234 	if (un->un_dp->options & ST_NOBUF) {
8235 		un->un_mspl->bufm = 0;
8236 	} else {
8237 		un->un_mspl->bufm = 1;
8238 	}
8239 
8240 	rval = st_set_compression(un);
8241 
8242 	/*
8243 	 * If st_set_compression returned invalid or already it
8244 	 * found no need to do the mode select.
8245 	 * So do it here.
8246 	 */
8247 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8248 
8249 		/* Zero non-writeable fields */
8250 		un->un_mspl->data_len = 0;
8251 		un->un_mspl->media_type = 0;
8252 		un->un_mspl->wp = 0;
8253 
8254 		/* need to set the density code */
8255 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8256 		if (rval != 0) {
8257 			if (un->un_state >= ST_STATE_OPEN) {
8258 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8259 				    "unable to set tape mode\n");
8260 				un->un_pos.pmode = invalid;
8261 				rval = EIO;
8262 			} else {
8263 				rval = -1;
8264 			}
8265 		}
8266 	}
8267 
8268 	/*
8269 	 * The spec recommends to send a mode sense after a mode select
8270 	 */
8271 	(void) st_modesense(un);
8272 
8273 	ASSERT(mutex_owned(ST_MUTEX));
8274 
8275 	return (rval);
8276 }
8277 
8278 /*
8279  * st_gen_mode_sense
8280  *
8281  * generic mode sense.. it allows for any page
8282  */
8283 static int
8284 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8285     struct seq_mode *page_data, int page_size)
8286 {
8287 
8288 	int r;
8289 	char	cdb[CDB_GROUP0];
8290 	struct uscsi_cmd *com;
8291 	struct scsi_arq_status status;
8292 
8293 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8294 
8295 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8296 
8297 	bzero(cdb, CDB_GROUP0);
8298 	cdb[0] = SCMD_MODE_SENSE;
8299 	cdb[2] = (char)page;
8300 	cdb[4] = (char)page_size;
8301 
8302 	com->uscsi_cdb = cdb;
8303 	com->uscsi_cdblen = CDB_GROUP0;
8304 	com->uscsi_bufaddr = (caddr_t)page_data;
8305 	com->uscsi_buflen = page_size;
8306 	com->uscsi_rqlen = sizeof (status);
8307 	com->uscsi_rqbuf = (caddr_t)&status;
8308 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8309 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8310 
8311 	r = ubf(un, com, FKIOCTL);
8312 	kmem_free(com, sizeof (*com));
8313 	return (r);
8314 }
8315 
8316 /*
8317  * st_gen_mode_select
8318  *
8319  * generic mode select.. it allows for any page
8320  */
8321 static int
8322 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8323     struct seq_mode *page_data, int page_size)
8324 {
8325 
8326 	int r;
8327 	char cdb[CDB_GROUP0];
8328 	struct uscsi_cmd *com;
8329 	struct scsi_arq_status status;
8330 
8331 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8332 
8333 	/* Zero non-writeable fields */
8334 	page_data->data_len = 0;
8335 	page_data->media_type = 0;
8336 	page_data->wp = 0;
8337 
8338 	/*
8339 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8340 	 */
8341 	if (page_size > MSIZE) {
8342 		page_data->ps = 0;
8343 	}
8344 
8345 
8346 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8347 
8348 	/*
8349 	 * then, do a mode select to set what ever info
8350 	 */
8351 	bzero(cdb, CDB_GROUP0);
8352 	cdb[0] = SCMD_MODE_SELECT;
8353 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8354 	cdb[4] = (char)page_size;
8355 
8356 	com->uscsi_cdb = cdb;
8357 	com->uscsi_cdblen = CDB_GROUP0;
8358 	com->uscsi_bufaddr = (caddr_t)page_data;
8359 	com->uscsi_buflen = page_size;
8360 	com->uscsi_rqlen = sizeof (status);
8361 	com->uscsi_rqbuf = (caddr_t)&status;
8362 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8363 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8364 
8365 	r = ubf(un, com, FKIOCTL);
8366 
8367 	kmem_free(com, sizeof (*com));
8368 	return (r);
8369 }
8370 
8371 static int
8372 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8373 {
8374 	int rval;
8375 	char cdb[CDB_GROUP0];
8376 	struct uscsi_cmd *com;
8377 	struct scsi_arq_status status;
8378 
8379 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8380 
8381 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8382 
8383 	bzero(cdb, CDB_GROUP0);
8384 	cdb[0] = SCMD_READ_BLKLIM;
8385 
8386 	com->uscsi_cdb = cdb;
8387 	com->uscsi_cdblen = CDB_GROUP0;
8388 	com->uscsi_bufaddr = (caddr_t)read_blk;
8389 	com->uscsi_buflen = sizeof (struct read_blklim);
8390 	com->uscsi_rqlen = sizeof (status);
8391 	com->uscsi_rqbuf = (caddr_t)&status;
8392 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8393 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8394 
8395 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8396 	if (com->uscsi_status || com->uscsi_resid) {
8397 		rval = -1;
8398 	}
8399 
8400 	kmem_free(com, sizeof (*com));
8401 	return (rval);
8402 }
8403 
8404 static int
8405 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8406     size_t buflen)
8407 {
8408 	int rval;
8409 	char cdb[CDB_GROUP1];
8410 	struct uscsi_cmd *com;
8411 	struct scsi_arq_status status;
8412 
8413 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8414 
8415 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8416 
8417 	bzero(cdb, CDB_GROUP1);
8418 	cdb[0] = SCMD_REPORT_DENSITIES;
8419 	cdb[7] = (buflen & 0xff00) >> 8;
8420 	cdb[8] = buflen & 0xff;
8421 
8422 	com->uscsi_cdb = cdb;
8423 	com->uscsi_cdblen = CDB_GROUP1;
8424 	com->uscsi_bufaddr = (caddr_t)density_data;
8425 	com->uscsi_buflen = buflen;
8426 	com->uscsi_rqlen = sizeof (status);
8427 	com->uscsi_rqbuf = (caddr_t)&status;
8428 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8429 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8430 
8431 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8432 	if (com->uscsi_status || com->uscsi_resid) {
8433 		rval = -1;
8434 	}
8435 
8436 	kmem_free(com, sizeof (*com));
8437 	return (rval);
8438 }
8439 
8440 static int
8441 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8442     uchar_t option_code, ushort_t service_action)
8443 {
8444 	int rval;
8445 	char cdb[CDB_GROUP5];
8446 	struct uscsi_cmd *com;
8447 	struct scsi_arq_status status;
8448 	uint32_t allo_length;
8449 
8450 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8451 
8452 	allo_length = sizeof (struct one_com_des) +
8453 	    sizeof (struct com_timeout_des);
8454 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8455 
8456 	bzero(cdb, CDB_GROUP5);
8457 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8458 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8459 	if (service_action) {
8460 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8461 		cdb[4] = (service_action & 0xff00) >> 8;
8462 		cdb[5] = service_action & 0xff;
8463 	} else {
8464 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8465 		    0x80); /* RCTD */
8466 	}
8467 	cdb[3] = option_code;
8468 	cdb[6] = (allo_length & 0xff000000) >> 24;
8469 	cdb[7] = (allo_length & 0xff0000) >> 16;
8470 	cdb[8] = (allo_length & 0xff00) >> 8;
8471 	cdb[9] = allo_length & 0xff;
8472 
8473 	com->uscsi_cdb = cdb;
8474 	com->uscsi_cdblen = CDB_GROUP5;
8475 	com->uscsi_bufaddr = (caddr_t)oper_data;
8476 	com->uscsi_buflen = allo_length;
8477 	com->uscsi_rqlen = sizeof (status);
8478 	com->uscsi_rqbuf = (caddr_t)&status;
8479 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8480 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8481 
8482 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8483 	if (com->uscsi_status) {
8484 		rval = -1;
8485 	}
8486 
8487 	kmem_free(com, sizeof (*com));
8488 	return (rval);
8489 }
8490 
8491 /*
8492  * Changes devices blocksize and bsize to requested blocksize nblksz.
8493  * Returns returned value from first failed call or zero on success.
8494  */
8495 static int
8496 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8497 {
8498 	struct seq_mode *current;
8499 	int rval;
8500 	uint32_t oldblksz;
8501 
8502 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8503 
8504 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8505 
8506 	/*
8507 	 * If we haven't got the compression page yet, do that first.
8508 	 */
8509 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8510 		(void) st_modesense(un);
8511 	}
8512 
8513 	/* Read current settings */
8514 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8515 	if (rval != 0) {
8516 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8517 		    "mode sense for change block size failed: rval = %d", rval);
8518 		goto finish;
8519 	}
8520 
8521 	/* Figure the current block size */
8522 	oldblksz =
8523 	    (current->high_bl << 16) |
8524 	    (current->mid_bl << 8) |
8525 	    (current->low_bl);
8526 
8527 	/* If current block size is the same as requested were done */
8528 	if (oldblksz == nblksz) {
8529 		un->un_bsize = nblksz;
8530 		rval = 0;
8531 		goto finish;
8532 	}
8533 
8534 	/* Change to requested block size */
8535 	current->high_bl = (uchar_t)(nblksz >> 16);
8536 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8537 	current->low_bl  = (uchar_t)(nblksz);
8538 
8539 	/* Attempt to change block size */
8540 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8541 	if (rval != 0) {
8542 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8543 		    "Set new block size failed: rval = %d", rval);
8544 		goto finish;
8545 	}
8546 
8547 	/* Read back and verify setting */
8548 	rval = st_modesense(un);
8549 	if (rval == 0) {
8550 		un->un_bsize =
8551 		    (un->un_mspl->high_bl << 16) |
8552 		    (un->un_mspl->mid_bl << 8) |
8553 		    (un->un_mspl->low_bl);
8554 
8555 		if (un->un_bsize != nblksz) {
8556 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8557 			    "Blocksize set does not equal requested blocksize"
8558 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8559 			rval = EIO;
8560 		}
8561 	}
8562 finish:
8563 	kmem_free(current, MSIZE);
8564 	return (rval);
8565 }
8566 
8567 
8568 static void
8569 st_init(struct scsi_tape *un)
8570 {
8571 	ST_FUNC(ST_DEVINFO, st_init);
8572 
8573 	ASSERT(mutex_owned(ST_MUTEX));
8574 
8575 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8576 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8577 	    un->un_dev);
8578 
8579 	un->un_pos.blkno = 0;
8580 	un->un_pos.fileno = 0;
8581 	un->un_lastop = ST_OP_NIL;
8582 	un->un_pos.eof = ST_NO_EOF;
8583 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8584 	if (st_error_level != SCSI_ERR_ALL) {
8585 		if (DEBUGGING) {
8586 			st_error_level = SCSI_ERR_ALL;
8587 		} else {
8588 			st_error_level = SCSI_ERR_RETRYABLE;
8589 		}
8590 	}
8591 }
8592 
8593 
8594 static void
8595 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8596 {
8597 	struct scsi_pkt *pkt;
8598 	struct uscsi_cmd *ucmd;
8599 	recov_info *ri;
8600 	int tval = 0;
8601 	int64_t count;
8602 	uint32_t additional = 0;
8603 	uint32_t address = 0;
8604 	union scsi_cdb *ucdb;
8605 	int flags = 0;
8606 	int cdb_len = CDB_GROUP0; /* default */
8607 	uchar_t com;
8608 	char fixbit;
8609 	char short_fm = 0;
8610 	optype prev_op = un->un_lastop;
8611 	int stat_size =
8612 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8613 
8614 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8615 
8616 	ASSERT(mutex_owned(ST_MUTEX));
8617 
8618 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8619 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8620 
8621 
8622 	/*
8623 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8624 	 * Length Indicator bits on read/write commands, for setting
8625 	 * the Long bit on erase commands, and for setting the Code
8626 	 * Field bits on space commands.
8627 	 */
8628 
8629 	/* regular raw I/O */
8630 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8631 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8632 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8633 		    (caddr_t)un);
8634 		if (pkt == NULL) {
8635 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8636 			    "Read Write scsi_init_pkt() failure\n");
8637 			goto exit;
8638 		}
8639 		ASSERT(pkt->pkt_resid == 0);
8640 #ifdef STDEBUG
8641 		bzero(pkt->pkt_private, st_recov_sz);
8642 		bzero(pkt->pkt_scbp, stat_size);
8643 #endif
8644 		ri = (recov_info *)pkt->pkt_private;
8645 		ri->privatelen = st_recov_sz;
8646 		if (un->un_bsize == 0) {
8647 			count = bp->b_bcount;
8648 			fixbit = 0;
8649 		} else {
8650 			count = bp->b_bcount / un->un_bsize;
8651 			fixbit = 1;
8652 		}
8653 		if (bp->b_flags & B_READ) {
8654 			com = SCMD_READ;
8655 			un->un_lastop = ST_OP_READ;
8656 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8657 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8658 				fixbit = 2;
8659 			}
8660 		} else {
8661 			com = SCMD_WRITE;
8662 			un->un_lastop = ST_OP_WRITE;
8663 		}
8664 		tval = un->un_dp->io_timeout;
8665 
8666 		/*
8667 		 * For really large xfers, increase timeout
8668 		 */
8669 		if (bp->b_bcount > (10 * ONE_MEG))
8670 			tval *= bp->b_bcount/(10 * ONE_MEG);
8671 
8672 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8673 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8674 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8675 
8676 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8677 		/*
8678 		 * uscsi - build command, allocate scsi resources
8679 		 */
8680 		st_make_uscsi_cmd(un, ucmd, bp, func);
8681 		goto exit;
8682 
8683 	} else {				/* special I/O */
8684 		struct buf *allocbp = NULL;
8685 		com = (uchar_t)(uintptr_t)bp->b_forw;
8686 		count = bp->b_bcount;
8687 
8688 		switch (com) {
8689 		case SCMD_READ:
8690 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8691 			    "special read %"PRId64"\n", count);
8692 			if (un->un_bsize == 0) {
8693 				fixbit = 2;	/* suppress SILI */
8694 			} else {
8695 				fixbit = 1;	/* Fixed Block Mode */
8696 				count /= un->un_bsize;
8697 			}
8698 			allocbp = bp;
8699 			un->un_lastop = ST_OP_READ;
8700 			tval = un->un_dp->io_timeout;
8701 			break;
8702 
8703 		case SCMD_WRITE:
8704 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8705 			    "special write %"PRId64"\n", count);
8706 			if (un->un_bsize != 0) {
8707 				fixbit = 1;	/* Fixed Block Mode */
8708 				count /= un->un_bsize;
8709 			} else {
8710 				fixbit = 0;
8711 			}
8712 			allocbp = bp;
8713 			un->un_lastop = ST_OP_WRITE;
8714 			tval = un->un_dp->io_timeout;
8715 			break;
8716 
8717 		case SCMD_WRITE_FILE_MARK:
8718 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8719 			    "write %"PRId64" file marks\n", count);
8720 			un->un_lastop = ST_OP_WEOF;
8721 			fixbit = 0;
8722 			tval = un->un_dp->io_timeout;
8723 			/*
8724 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8725 			 * device, set the Vendor Unique bit to
8726 			 * write Short File Mark.
8727 			 */
8728 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8729 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8730 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8731 				/*
8732 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8733 				 * is set to to write Short File Mark
8734 				 */
8735 				short_fm = 1;
8736 			}
8737 			break;
8738 
8739 		case SCMD_REWIND:
8740 			/*
8741 			 * In the case of rewind we're gona do the rewind with
8742 			 * the immediate bit set so status will be retured when
8743 			 * the command is accepted by the device. We clear the
8744 			 * B_ASYNC flag so we wait for that acceptance.
8745 			 */
8746 			fixbit = 0;
8747 			if (bp->b_flags & B_ASYNC) {
8748 				allocbp = bp;
8749 				if (count) {
8750 					fixbit = 1;
8751 					bp->b_flags &= ~B_ASYNC;
8752 				}
8753 			}
8754 			count = 0;
8755 			bp->b_bcount = 0;
8756 			un->un_lastop = ST_OP_CTL;
8757 			tval = un->un_dp->rewind_timeout;
8758 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8759 			    "rewind\n");
8760 			break;
8761 
8762 		case SCMD_SPACE_G4:
8763 			cdb_len = CDB_GROUP4;
8764 			fixbit = SPACE_TYPE(bp->b_bcount);
8765 			count = SPACE_CNT(bp->b_bcount);
8766 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8767 			    " %s space %s %"PRId64" from file %d blk %d\n",
8768 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8769 			    space_strs[fixbit & 7], count,
8770 			    un->un_pos.fileno, un->un_pos.blkno);
8771 			address = (count >> 48) & 0x1fff;
8772 			additional = (count >> 16) & 0xffffffff;
8773 			count &= 0xffff;
8774 			count <<= 16;
8775 			un->un_lastop = ST_OP_CTL;
8776 			tval = un->un_dp->space_timeout;
8777 			break;
8778 
8779 		case SCMD_SPACE:
8780 			fixbit = SPACE_TYPE(bp->b_bcount);
8781 			count = SPACE_CNT(bp->b_bcount);
8782 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8783 			    " %s space %s %"PRId64" from file %d blk %d\n",
8784 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8785 			    space_strs[fixbit & 7], count,
8786 			    un->un_pos.fileno, un->un_pos.blkno);
8787 			count &= 0xffffffff;
8788 			un->un_lastop = ST_OP_CTL;
8789 			tval = un->un_dp->space_timeout;
8790 			break;
8791 
8792 		case SCMD_LOAD:
8793 			ASSERT(count < 10);
8794 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8795 			    "%s tape\n", load_strs[count]);
8796 			fixbit = 0;
8797 
8798 			/* Loading or Unloading */
8799 			if (count & LD_LOAD) {
8800 				tval = un->un_dp->load_timeout;
8801 			} else {
8802 				tval = un->un_dp->unload_timeout;
8803 			}
8804 			/* Is Retension requested */
8805 			if (count & LD_RETEN) {
8806 				tval += un->un_dp->rewind_timeout;
8807 			}
8808 			un->un_lastop = ST_OP_CTL;
8809 			break;
8810 
8811 		case SCMD_ERASE:
8812 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8813 			    "erase tape\n");
8814 			ASSERT(count == 1); /* mt sets this */
8815 			if (count == 1) {
8816 				/*
8817 				 * do long erase
8818 				 */
8819 				fixbit = 1; /* Long */
8820 
8821 				/* Drive might not honor immidiate bit */
8822 				tval = un->un_dp->erase_timeout;
8823 			} else {
8824 				/* Short Erase */
8825 				tval = un->un_dp->erase_timeout;
8826 				fixbit = 0;
8827 			}
8828 			un->un_lastop = ST_OP_CTL;
8829 			count = 0;
8830 			break;
8831 
8832 		case SCMD_MODE_SENSE:
8833 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8834 			    "mode sense\n");
8835 			allocbp = bp;
8836 			fixbit = 0;
8837 			tval = un->un_dp->non_motion_timeout;
8838 			un->un_lastop = ST_OP_CTL;
8839 			break;
8840 
8841 		case SCMD_MODE_SELECT:
8842 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8843 			    "mode select\n");
8844 			allocbp = bp;
8845 			fixbit = 0;
8846 			tval = un->un_dp->non_motion_timeout;
8847 			un->un_lastop = ST_OP_CTL;
8848 			break;
8849 
8850 		case SCMD_RESERVE:
8851 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8852 			    "reserve\n");
8853 			fixbit = 0;
8854 			tval = un->un_dp->non_motion_timeout;
8855 			un->un_lastop = ST_OP_CTL;
8856 			break;
8857 
8858 		case SCMD_RELEASE:
8859 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8860 			    "release\n");
8861 			fixbit = 0;
8862 			tval = un->un_dp->non_motion_timeout;
8863 			un->un_lastop = ST_OP_CTL;
8864 			break;
8865 
8866 		case SCMD_READ_BLKLIM:
8867 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8868 			    "read block limits\n");
8869 			allocbp = bp;
8870 			fixbit = count = 0;
8871 			tval = un->un_dp->non_motion_timeout;
8872 			un->un_lastop = ST_OP_CTL;
8873 			break;
8874 
8875 		case SCMD_TEST_UNIT_READY:
8876 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8877 			    "test unit ready\n");
8878 			fixbit = 0;
8879 			tval = un->un_dp->non_motion_timeout;
8880 			un->un_lastop = ST_OP_CTL;
8881 			break;
8882 
8883 		case SCMD_DOORLOCK:
8884 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8885 			    "prevent/allow media removal\n");
8886 			fixbit = 0;
8887 			tval = un->un_dp->non_motion_timeout;
8888 			un->un_lastop = ST_OP_CTL;
8889 			break;
8890 
8891 		case SCMD_READ_POSITION:
8892 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8893 			    "read position\n");
8894 			fixbit = un->un_read_pos_type;
8895 			cdb_len = CDB_GROUP1;
8896 			tval = un->un_dp->non_motion_timeout;
8897 			allocbp = bp;
8898 			un->un_lastop = ST_OP_CTL;
8899 			switch (un->un_read_pos_type) {
8900 			case LONG_POS:
8901 				count = 0;
8902 				break;
8903 			case EXT_POS:
8904 				count = sizeof (tape_position_ext_t);
8905 				break;
8906 			case SHORT_POS:
8907 				count = 0;
8908 				break;
8909 			default:
8910 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8911 				    "Unknown read position type 0x%x in "
8912 				    " st_make_cmd()\n", un->un_read_pos_type);
8913 			}
8914 			break;
8915 
8916 		default:
8917 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8918 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8919 			    com);
8920 		}
8921 
8922 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8923 		    st_recov_sz, 0, func, (caddr_t)un);
8924 		if (pkt == NULL) {
8925 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8926 			    "generic command scsi_init_pkt() failure\n");
8927 			goto exit;
8928 		}
8929 
8930 		ASSERT(pkt->pkt_resid == 0);
8931 #ifdef STDEBUG
8932 		bzero(pkt->pkt_private, st_recov_sz);
8933 		bzero(pkt->pkt_scbp, stat_size);
8934 #endif
8935 		ri = (recov_info *)pkt->pkt_private;
8936 		ri->privatelen = st_recov_sz;
8937 		if (allocbp) {
8938 			ASSERT(geterror(allocbp) == 0);
8939 		}
8940 
8941 	}
8942 
8943 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8944 
8945 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8946 	FILL_SCSI1_LUN(un->un_sd, pkt);
8947 	/*
8948 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8949 	 */
8950 	ucdb->t_code = fixbit;
8951 	ucdb->g0_vu_1 = short_fm;
8952 	pkt->pkt_flags = flags;
8953 
8954 	ASSERT(tval);
8955 	pkt->pkt_time = tval;
8956 	if (bp == un->un_recov_buf) {
8957 		pkt->pkt_comp = st_recov_cb;
8958 	} else {
8959 		pkt->pkt_comp = st_intr;
8960 	}
8961 
8962 	st_add_recovery_info_to_pkt(un, bp, pkt);
8963 
8964 	/*
8965 	 * If we just write data to tape and did a command that doesn't
8966 	 * change position, we still need to write a filemark.
8967 	 */
8968 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
8969 		recov_info *rcvi = pkt->pkt_private;
8970 		cmd_attribute const *atrib;
8971 
8972 		if (rcvi->privatelen == sizeof (recov_info)) {
8973 			atrib = rcvi->cmd_attrib;
8974 		} else {
8975 			atrib = st_lookup_cmd_attribute(com);
8976 		}
8977 		if (atrib->chg_tape_direction == DIR_NONE) {
8978 			un->un_lastop = prev_op;
8979 		}
8980 	}
8981 
8982 exit:
8983 	ASSERT(mutex_owned(ST_MUTEX));
8984 }
8985 
8986 
8987 /*
8988  * Build a command based on a uscsi command;
8989  */
8990 static void
8991 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8992     struct buf *bp, int (*func)(caddr_t))
8993 {
8994 	struct scsi_pkt *pkt;
8995 	recov_info *ri;
8996 	caddr_t cdb;
8997 	int	cdblen;
8998 	int	stat_size = 1;
8999 	int	flags = 0;
9000 
9001 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
9002 
9003 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9004 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
9005 
9006 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
9007 		if (un->un_arq_enabled) {
9008 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
9009 				stat_size = (int)(ucmd->uscsi_rqlen) +
9010 				    sizeof (struct scsi_arq_status) -
9011 				    sizeof (struct scsi_extended_sense);
9012 				flags = PKT_XARQ;
9013 			} else {
9014 				stat_size = sizeof (struct scsi_arq_status);
9015 			}
9016 		}
9017 	}
9018 
9019 	ASSERT(mutex_owned(ST_MUTEX));
9020 
9021 	cdb = ucmd->uscsi_cdb;
9022 	cdblen = ucmd->uscsi_cdblen;
9023 
9024 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9025 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
9026 	    ucmd->uscsi_buflen, bp->b_bcount);
9027 	pkt = scsi_init_pkt(ROUTE, NULL,
9028 	    (bp->b_bcount > 0) ? bp : NULL,
9029 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
9030 	if (pkt == NULL) {
9031 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9032 		    "uscsi command scsi_init_pkt() failure\n");
9033 		goto exit;
9034 	}
9035 
9036 	ASSERT(pkt->pkt_resid == 0);
9037 #ifdef STDEBUG
9038 	bzero(pkt->pkt_private, st_recov_sz);
9039 	bzero(pkt->pkt_scbp, stat_size);
9040 #endif
9041 	ri = (recov_info *)pkt->pkt_private;
9042 	ri->privatelen = st_recov_sz;
9043 
9044 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9045 
9046 #ifdef STDEBUG
9047 	if ((st_debug & 0x7) >= 6) {
9048 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9049 		    "pkt_cdbp", (char *)cdb, cdblen);
9050 	}
9051 #endif
9052 
9053 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9054 		pkt->pkt_flags |= FLAG_SILENT;
9055 	}
9056 
9057 	(void) scsi_uscsi_pktinit(ucmd, pkt);
9058 
9059 	pkt->pkt_time = ucmd->uscsi_timeout;
9060 	if (bp == un->un_recov_buf) {
9061 		pkt->pkt_comp = st_recov_cb;
9062 	} else {
9063 		pkt->pkt_comp = st_intr;
9064 	}
9065 	st_add_recovery_info_to_pkt(un, bp, pkt);
9066 exit:
9067 	ASSERT(mutex_owned(ST_MUTEX));
9068 }
9069 
9070 
9071 /*
9072  * restart cmd currently at the head of the runq
9073  *
9074  * If scsi_transport() succeeds or the retries
9075  * count exhausted, restore the throttle that was
9076  * zeroed out in st_handle_intr_busy().
9077  *
9078  */
9079 static void
9080 st_intr_restart(void *arg)
9081 {
9082 	struct scsi_tape *un = arg;
9083 	struct buf *bp;
9084 	int queued;
9085 	int status = TRAN_ACCEPT;
9086 
9087 	mutex_enter(ST_MUTEX);
9088 
9089 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9090 
9091 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9092 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9093 
9094 	un->un_hib_tid = 0;
9095 
9096 	if (un->un_recov_buf_busy != 0) {
9097 		bp = un->un_recov_buf;
9098 		queued = 0;
9099 	} else if (un->un_sbuf_busy != 0) {
9100 		bp = un->un_sbufp;
9101 		queued = 0;
9102 	} else if (un->un_quef != NULL) {
9103 		bp = un->un_quef;
9104 		queued = 1;
9105 	} else {
9106 		mutex_exit(ST_MUTEX);
9107 		return;
9108 	}
9109 
9110 	/*
9111 	 * Here we know :
9112 	 *	throttle = 0, via st_handle_intr_busy
9113 	 */
9114 
9115 	if (queued) {
9116 		/*
9117 		 * move from waitq to runq, if there is anything on the waitq
9118 		 */
9119 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9120 
9121 		if (un->un_runqf) {
9122 			/*
9123 			 * not good, we don't want to requeue something after
9124 			 * another.
9125 			 */
9126 			goto done_error;
9127 		} else {
9128 			un->un_runqf = bp;
9129 			un->un_runql = bp;
9130 		}
9131 	}
9132 
9133 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9134 	    (char *)BP_PKT(bp)->pkt_cdbp);
9135 
9136 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9137 
9138 	status = st_transport(un, BP_PKT(bp));
9139 
9140 	if (status != TRAN_ACCEPT) {
9141 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9142 
9143 		if (status == TRAN_BUSY) {
9144 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9145 
9146 			if (pkti->privatelen == sizeof (recov_info) &&
9147 			    un->un_unit_attention_flags &&
9148 			    bp != un->un_recov_buf) {
9149 			un->un_unit_attention_flags = 0;
9150 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9151 				    "Command Recovery called on busy resend\n");
9152 				if (st_command_recovery(un, BP_PKT(bp),
9153 				    ATTEMPT_RETRY) == JUST_RETURN) {
9154 					mutex_exit(ST_MUTEX);
9155 					return;
9156 				}
9157 			}
9158 			mutex_exit(ST_MUTEX);
9159 			if (st_handle_intr_busy(un, bp,
9160 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9161 				return;	/* timeout is setup again */
9162 			mutex_enter(ST_MUTEX);
9163 		}
9164 
9165 done_error:
9166 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9167 		    "restart transport rejected\n");
9168 		bp->b_resid = bp->b_bcount;
9169 
9170 		if (un->un_last_throttle) {
9171 			un->un_throttle = un->un_last_throttle;
9172 		}
9173 		if (status != TRAN_ACCEPT) {
9174 			ST_DO_ERRSTATS(un, st_transerrs);
9175 		}
9176 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9177 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9178 		    "busy restart aborted\n");
9179 		st_set_pe_flag(un);
9180 		st_bioerror(bp, EIO);
9181 		st_done_and_mutex_exit(un, bp);
9182 	} else {
9183 		if (un->un_last_throttle) {
9184 			un->un_throttle = un->un_last_throttle;
9185 		}
9186 		mutex_exit(ST_MUTEX);
9187 	}
9188 }
9189 
9190 /*
9191  * st_check_media():
9192  * Periodically check the media state using scsi_watch service;
9193  * this service calls back after TUR and possibly request sense
9194  * the callback handler (st_media_watch_cb()) decodes the request sense
9195  * data (if any)
9196  */
9197 
9198 static int
9199 st_check_media(dev_t dev, enum mtio_state state)
9200 {
9201 	int rval = 0;
9202 	enum mtio_state	prev_state;
9203 	opaque_t token = NULL;
9204 
9205 	GET_SOFT_STATE(dev);
9206 
9207 	ST_FUNC(ST_DEVINFO, st_check_media);
9208 
9209 	mutex_enter(ST_MUTEX);
9210 
9211 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9212 	    "st_check_media:state=%x, mediastate=%x\n",
9213 	    state, un->un_mediastate);
9214 
9215 	prev_state = un->un_mediastate;
9216 
9217 	/*
9218 	 * is there anything to do?
9219 	 */
9220 retry:
9221 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9222 		/*
9223 		 * submit the request to the scsi_watch service;
9224 		 * scsi_media_watch_cb() does the real work
9225 		 */
9226 		mutex_exit(ST_MUTEX);
9227 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9228 		    st_check_media_time, SENSE_LENGTH,
9229 		    st_media_watch_cb, (caddr_t)dev);
9230 		if (token == NULL) {
9231 			rval = EAGAIN;
9232 			goto done;
9233 		}
9234 		mutex_enter(ST_MUTEX);
9235 
9236 		un->un_swr_token = token;
9237 		un->un_specified_mediastate = state;
9238 
9239 		/*
9240 		 * now wait for media change
9241 		 * we will not be signalled unless mediastate == state but it
9242 		 * still better to test for this condition, since there
9243 		 * is a 5 sec cv_broadcast delay when
9244 		 *  mediastate == MTIO_INSERTED
9245 		 */
9246 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9247 		    "st_check_media:waiting for media state change\n");
9248 		while (un->un_mediastate == state) {
9249 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9250 				mutex_exit(ST_MUTEX);
9251 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9252 				    "st_check_media:waiting for media state "
9253 				    "was interrupted\n");
9254 				rval = EINTR;
9255 				goto done;
9256 			}
9257 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9258 			    "st_check_media:received signal, state=%x\n",
9259 			    un->un_mediastate);
9260 		}
9261 	}
9262 
9263 	/*
9264 	 * if we transitioned to MTIO_INSERTED, media has really been
9265 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9266 	 * Reset and retry the state change.  If everything is ok, replay
9267 	 * the open() logic.
9268 	 */
9269 	if ((un->un_mediastate == MTIO_INSERTED) &&
9270 	    (un->un_state == ST_STATE_OFFLINE)) {
9271 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9272 		    "st_check_media: calling st_cmd to confirm inserted\n");
9273 
9274 		/*
9275 		 * set this early so that TUR will make it through strategy
9276 		 * without triggering a st_tape_init().  We needed it set
9277 		 * before calling st_tape_init() ourselves anyway.  If TUR
9278 		 * fails, set it back
9279 		 */
9280 		un->un_state = ST_STATE_INITIALIZING;
9281 
9282 		/*
9283 		 * If not reserved fail as getting reservation conflict
9284 		 * will make this hang forever.
9285 		 */
9286 		if ((un->un_rsvd_status &
9287 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9288 			mutex_exit(ST_MUTEX);
9289 			rval = EACCES;
9290 			goto done;
9291 		}
9292 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9293 		if (rval == EACCES) {
9294 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9295 			    "st_check_media: TUR got Reservation Conflict\n");
9296 			mutex_exit(ST_MUTEX);
9297 			goto done;
9298 		}
9299 		if (rval) {
9300 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9301 			    "st_check_media: TUR failed, going to retry\n");
9302 			un->un_mediastate = prev_state;
9303 			un->un_state = ST_STATE_OFFLINE;
9304 			goto retry;
9305 		}
9306 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9307 		    "st_check_media: media inserted\n");
9308 
9309 		/* this also rewinds the tape */
9310 		rval = st_tape_init(un);
9311 		if (rval != 0) {
9312 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9313 			    "st_check_media : OFFLINE init failure ");
9314 			un->un_state = ST_STATE_OFFLINE;
9315 			un->un_pos.pmode = invalid;
9316 		} else {
9317 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9318 		}
9319 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9320 	    (un->un_state != ST_STATE_OFFLINE)) {
9321 		/*
9322 		 * supported devices must be rewound before ejection
9323 		 * rewind resets fileno & blkno
9324 		 */
9325 		un->un_laststate = un->un_state;
9326 		un->un_state = ST_STATE_OFFLINE;
9327 	}
9328 	mutex_exit(ST_MUTEX);
9329 done:
9330 	if (token) {
9331 		(void) scsi_watch_request_terminate(token,
9332 		    SCSI_WATCH_TERMINATE_WAIT);
9333 		mutex_enter(ST_MUTEX);
9334 		un->un_swr_token = (opaque_t)NULL;
9335 		mutex_exit(ST_MUTEX);
9336 	}
9337 
9338 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9339 
9340 	return (rval);
9341 }
9342 
9343 /*
9344  * st_media_watch_cb() is called by scsi_watch_thread for
9345  * verifying the request sense data (if any)
9346  */
9347 static int
9348 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9349 {
9350 	struct scsi_status *statusp = resultp->statusp;
9351 	struct scsi_extended_sense *sensep = resultp->sensep;
9352 	uchar_t actual_sense_length = resultp->actual_sense_length;
9353 	struct scsi_tape *un;
9354 	enum mtio_state state = MTIO_NONE;
9355 	int instance;
9356 	dev_t dev = (dev_t)arg;
9357 
9358 	instance = MTUNIT(dev);
9359 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9360 		return (-1);
9361 	}
9362 
9363 	mutex_enter(ST_MUTEX);
9364 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9365 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9366 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9367 	    *((char *)statusp), (void *)sensep,
9368 	    actual_sense_length);
9369 
9370 
9371 	/*
9372 	 * if there was a check condition then sensep points to valid
9373 	 * sense data
9374 	 * if status was not a check condition but a reservation or busy
9375 	 * status then the new state is MTIO_NONE
9376 	 */
9377 	if (sensep) {
9378 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9379 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9380 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9381 
9382 		switch (un->un_dp->type) {
9383 		default:
9384 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9385 			    "st_media_watch_cb: unknown drive type %d, "
9386 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9387 		/* FALLTHROUGH */
9388 
9389 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9390 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9391 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9392 			if (un->un_dp->type == ST_TYPE_FUJI) {
9393 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9394 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9395 			} else {
9396 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9397 				    "st_media_watch_cb: ST_TYPE_HP\n");
9398 			}
9399 			switch (sensep->es_key) {
9400 			case KEY_UNIT_ATTENTION:
9401 				/* not ready to ready transition */
9402 				/* hp/es_qual_code == 80 on>off>on */
9403 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9404 				if (sensep->es_add_code == 0x28) {
9405 					state = MTIO_INSERTED;
9406 				}
9407 				break;
9408 			case KEY_NOT_READY:
9409 				/* in process, rewinding or loading */
9410 				if ((sensep->es_add_code == 0x04) &&
9411 				    (sensep->es_qual_code == 0x00)) {
9412 					state = MTIO_EJECTED;
9413 				}
9414 				break;
9415 			}
9416 			break;
9417 
9418 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9419 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9420 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9421 			switch (sensep->es_key) {
9422 			case KEY_UNIT_ATTENTION:
9423 				/* operator medium removal request */
9424 				if ((sensep->es_add_code == 0x5a) &&
9425 				    (sensep->es_qual_code == 0x01)) {
9426 					state = MTIO_EJECTED;
9427 				/* not ready to ready transition */
9428 				} else if ((sensep->es_add_code == 0x28) &&
9429 				    (sensep->es_qual_code == 0x00)) {
9430 					state = MTIO_INSERTED;
9431 				}
9432 				break;
9433 			case KEY_NOT_READY:
9434 				/* medium not present */
9435 				if (sensep->es_add_code == 0x3a) {
9436 					state = MTIO_EJECTED;
9437 				}
9438 				break;
9439 			}
9440 			break;
9441 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9442 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9443 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9444 			switch (sensep->es_key) {
9445 			case KEY_NOT_READY:
9446 				if ((sensep->es_add_code == 0x04) &&
9447 				    (sensep->es_qual_code == 0x00)) {
9448 					/* volume not mounted? */
9449 					state = MTIO_EJECTED;
9450 				} else if (sensep->es_add_code == 0x3a) {
9451 					state = MTIO_EJECTED;
9452 				}
9453 				break;
9454 			case KEY_UNIT_ATTENTION:
9455 				state = MTIO_EJECTED;
9456 				break;
9457 			}
9458 			break;
9459 
9460 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9461 			switch (sensep->es_key) {
9462 			case KEY_UNIT_ATTENTION:
9463 				if (sensep->es_add_code == 0x28) {
9464 					state = MTIO_INSERTED;
9465 				}
9466 				break;
9467 			case KEY_NOT_READY:
9468 				if (sensep->es_add_code == 0x04) {
9469 					/* in transition but could be either */
9470 					state = un->un_specified_mediastate;
9471 				} else if ((sensep->es_add_code == 0x3a) &&
9472 				    (sensep->es_qual_code == 0x00)) {
9473 					state = MTIO_EJECTED;
9474 				}
9475 				break;
9476 			}
9477 			break;
9478 		}
9479 	} else if (*((char *)statusp) == STATUS_GOOD) {
9480 		state = MTIO_INSERTED;
9481 	}
9482 
9483 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9484 	    "st_media_watch_cb:state=%x, specified=%x\n",
9485 	    state, un->un_specified_mediastate);
9486 
9487 	/*
9488 	 * now signal the waiting thread if this is *not* the specified state;
9489 	 * delay the signal if the state is MTIO_INSERTED
9490 	 * to allow the target to recover
9491 	 */
9492 	if (state != un->un_specified_mediastate) {
9493 		un->un_mediastate = state;
9494 		if (state == MTIO_INSERTED) {
9495 			/*
9496 			 * delay the signal to give the drive a chance
9497 			 * to do what it apparently needs to do
9498 			 */
9499 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9500 			    "st_media_watch_cb:delayed cv_broadcast\n");
9501 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9502 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9503 		} else {
9504 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9505 			    "st_media_watch_cb:immediate cv_broadcast\n");
9506 			cv_broadcast(&un->un_state_cv);
9507 		}
9508 	}
9509 	mutex_exit(ST_MUTEX);
9510 	return (0);
9511 }
9512 
9513 /*
9514  * delayed cv_broadcast to allow for target to recover
9515  * from media insertion
9516  */
9517 static void
9518 st_delayed_cv_broadcast(void *arg)
9519 {
9520 	struct scsi_tape *un = arg;
9521 
9522 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9523 
9524 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9525 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9526 
9527 	mutex_enter(ST_MUTEX);
9528 	cv_broadcast(&un->un_state_cv);
9529 	mutex_exit(ST_MUTEX);
9530 }
9531 
9532 /*
9533  * restart cmd currently at the start of the waitq
9534  */
9535 static void
9536 st_start_restart(void *arg)
9537 {
9538 	struct scsi_tape *un = arg;
9539 
9540 	ST_FUNC(ST_DEVINFO, st_start_restart);
9541 
9542 	ASSERT(un != NULL);
9543 
9544 	mutex_enter(ST_MUTEX);
9545 
9546 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9547 
9548 	st_start(un);
9549 
9550 	mutex_exit(ST_MUTEX);
9551 }
9552 
9553 
9554 /*
9555  * Command completion processing
9556  *
9557  */
9558 static void
9559 st_intr(struct scsi_pkt *pkt)
9560 {
9561 	recov_info *rcv = pkt->pkt_private;
9562 	struct buf *bp = rcv->cmd_bp;
9563 	struct scsi_tape *un;
9564 	errstate action = COMMAND_DONE;
9565 	clock_t	timout;
9566 	int	status;
9567 
9568 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9569 
9570 	ST_FUNC(ST_DEVINFO, st_intr);
9571 
9572 	ASSERT(un != NULL);
9573 
9574 	mutex_enter(ST_MUTEX);
9575 
9576 	ASSERT(bp != un->un_recov_buf);
9577 
9578 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9579 
9580 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9581 
9582 	if (pkt->pkt_reason != CMD_CMPLT) {
9583 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9584 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9585 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9586 
9587 		/* If device has gone away not much else to do */
9588 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9589 			action = COMMAND_DONE_ERROR;
9590 		} else if ((pkt == un->un_rqs) ||
9591 		    (un->un_state == ST_STATE_SENSING)) {
9592 			ASSERT(pkt == un->un_rqs);
9593 			ASSERT(un->un_state == ST_STATE_SENSING);
9594 			un->un_state = un->un_laststate;
9595 			rcv->cmd_bp = un->un_rqs_bp;
9596 			ST_DO_ERRSTATS(un, st_transerrs);
9597 			action = COMMAND_DONE_ERROR;
9598 		} else {
9599 			action = st_handle_incomplete(un, bp);
9600 		}
9601 	/*
9602 	 * At this point we know that the command was successfully
9603 	 * completed. Now what?
9604 	 */
9605 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9606 		/*
9607 		 * okay. We were running a REQUEST SENSE. Find
9608 		 * out what to do next.
9609 		 */
9610 		ASSERT(pkt == un->un_rqs);
9611 		ASSERT(un->un_state == ST_STATE_SENSING);
9612 		scsi_sync_pkt(pkt);
9613 		action = st_handle_sense(un, bp, &un->un_pos);
9614 		/*
9615 		 * Make rqs isn't going to be retied.
9616 		 */
9617 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9618 			/*
9619 			 * set pkt back to original packet in case we will have
9620 			 * to requeue it
9621 			 */
9622 			pkt = BP_PKT(bp);
9623 			rcv->cmd_bp = un->un_rqs_bp;
9624 			/*
9625 			 * some actions are based on un_state, hence
9626 			 * restore the state st was in before ST_STATE_SENSING.
9627 			 */
9628 			un->un_state = un->un_laststate;
9629 		}
9630 
9631 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9632 		/*
9633 		 * the transport layer successfully completed an autorqsense
9634 		 */
9635 		action = st_handle_autosense(un, bp, &un->un_pos);
9636 
9637 	} else  if ((SCBP(pkt)->sts_busy) ||
9638 	    (SCBP(pkt)->sts_chk) ||
9639 	    (SCBP(pkt)->sts_vu7)) {
9640 		/*
9641 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9642 		 * to see if the status bits we're okay. If a request sense
9643 		 * is to be run, that will happen.
9644 		 */
9645 		action = st_check_error(un, pkt);
9646 	}
9647 
9648 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9649 		switch (action) {
9650 			case QUE_COMMAND:
9651 				/*
9652 				 * return cmd to head to the queue
9653 				 * since we are suspending so that
9654 				 * it gets restarted during resume
9655 				 */
9656 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9657 				    un->un_runqf, bp);
9658 
9659 				action = JUST_RETURN;
9660 				break;
9661 
9662 			case QUE_SENSE:
9663 				action = COMMAND_DONE_ERROR;
9664 				break;
9665 
9666 			default:
9667 				break;
9668 		}
9669 	}
9670 
9671 	/*
9672 	 * check for undetected path failover.
9673 	 */
9674 	if (un->un_multipath) {
9675 
9676 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9677 		int pkt_valid;
9678 
9679 		if (ucmd) {
9680 			/*
9681 			 * Also copies path instance to the uscsi structure.
9682 			 */
9683 			pkt_valid = scsi_uscsi_pktfini(pkt, ucmd);
9684 
9685 			/*
9686 			 * scsi_uscsi_pktfini() zeros pkt_path_instance.
9687 			 */
9688 			pkt->pkt_path_instance = ucmd->uscsi_path_instance;
9689 		} else {
9690 			pkt_valid = scsi_pkt_allocated_correctly(pkt);
9691 		}
9692 
9693 		/*
9694 		 * If the scsi_pkt was not allocated correctly the
9695 		 * pkt_path_instance is not even there.
9696 		 */
9697 		if ((pkt_valid != 0) &&
9698 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9699 			if (un->un_state > ST_STATE_OPENING) {
9700 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9701 				    "Failover detected, action is %s\n",
9702 				    errstatenames[action]);
9703 				if (action == COMMAND_DONE) {
9704 					action = PATH_FAILED;
9705 				}
9706 			}
9707 			un->un_last_path_instance = pkt->pkt_path_instance;
9708 		}
9709 	}
9710 
9711 	/*
9712 	 * Restore old state if we were sensing.
9713 	 */
9714 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9715 		un->un_state = un->un_laststate;
9716 	}
9717 
9718 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9719 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9720 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9721 
9722 again:
9723 	switch (action) {
9724 	case COMMAND_DONE_EACCES:
9725 		/* this is to report a reservation conflict */
9726 		st_bioerror(bp, EACCES);
9727 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9728 		    "Reservation Conflict \n");
9729 		un->un_pos.pmode = invalid;
9730 
9731 		/*FALLTHROUGH*/
9732 	case COMMAND_DONE_ERROR:
9733 		if (un->un_pos.eof < ST_EOT_PENDING &&
9734 		    un->un_state >= ST_STATE_OPEN) {
9735 			/*
9736 			 * all errors set state of the tape to 'unknown'
9737 			 * unless we're at EOT or are doing append testing.
9738 			 * If sense key was illegal request, preserve state.
9739 			 */
9740 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9741 				un->un_pos.pmode = invalid;
9742 			}
9743 		}
9744 
9745 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9746 		/*
9747 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9748 		 * make sure an error ocurrs, so make sure at least EIO is
9749 		 * returned
9750 		 */
9751 		if (geterror(bp) == 0)
9752 			st_bioerror(bp, EIO);
9753 
9754 		st_set_pe_flag(un);
9755 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9756 		    (un->un_errno == EIO)) {
9757 			un->un_rqs_state &= ~(ST_RQS_VALID);
9758 		}
9759 		break;
9760 
9761 	case COMMAND_DONE_ERROR_RECOVERED:
9762 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9763 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9764 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9765 		if (geterror(bp) == 0) {
9766 			st_bioerror(bp, EIO);
9767 		}
9768 		st_set_pe_flag(un);
9769 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9770 		    (un->un_errno == EIO)) {
9771 			un->un_rqs_state &= ~(ST_RQS_VALID);
9772 		}
9773 		/*FALLTHROUGH*/
9774 	case COMMAND_DONE:
9775 		st_set_state(un, bp);
9776 		break;
9777 
9778 	case QUE_SENSE:
9779 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9780 			goto sense_error;
9781 
9782 		if (un->un_state != ST_STATE_SENSING) {
9783 			un->un_laststate = un->un_state;
9784 			un->un_state = ST_STATE_SENSING;
9785 		}
9786 
9787 		/*
9788 		 * zero the sense data.
9789 		 */
9790 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9791 
9792 		/*
9793 		 * If this is not a retry on QUE_SENSE point to the original
9794 		 * bp of the command that got us here.
9795 		 */
9796 		if (pkt != un->un_rqs) {
9797 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9798 		}
9799 
9800 		if (un->un_throttle) {
9801 			un->un_last_throttle = un->un_throttle;
9802 			un->un_throttle = 0;
9803 		}
9804 
9805 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9806 		    (char *)BP_PKT(bp)->pkt_cdbp);
9807 
9808 		/*
9809 		 * never retry this, some other command will have nuked the
9810 		 * sense, anyway
9811 		 */
9812 		status = st_transport(un, un->un_rqs);
9813 
9814 		if (un->un_last_throttle) {
9815 			un->un_throttle = un->un_last_throttle;
9816 		}
9817 
9818 		if (status == TRAN_ACCEPT) {
9819 			mutex_exit(ST_MUTEX);
9820 			return;
9821 		}
9822 		if (status != TRAN_BUSY)
9823 			ST_DO_ERRSTATS(un, st_transerrs);
9824 sense_error:
9825 		un->un_pos.pmode = invalid;
9826 		st_bioerror(bp, EIO);
9827 		st_set_pe_flag(un);
9828 		break;
9829 
9830 	case QUE_BUSY_COMMAND:
9831 		/* longish timeout */
9832 		timout = ST_STATUS_BUSY_TIMEOUT;
9833 		goto que_it_up;
9834 
9835 	case QUE_COMMAND:
9836 		/* short timeout */
9837 		timout = ST_TRAN_BUSY_TIMEOUT;
9838 que_it_up:
9839 		/*
9840 		 * let st_handle_intr_busy put this bp back on waitq and make
9841 		 * checks to see if it is ok to requeue the command.
9842 		 */
9843 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9844 
9845 		/*
9846 		 * Save the throttle before setting up the timeout
9847 		 */
9848 		if (un->un_throttle) {
9849 			un->un_last_throttle = un->un_throttle;
9850 		}
9851 		mutex_exit(ST_MUTEX);
9852 		if (st_handle_intr_busy(un, bp, timout) == 0)
9853 			return;		/* timeout is setup again */
9854 
9855 		mutex_enter(ST_MUTEX);
9856 		un->un_pos.pmode = invalid;
9857 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9858 		st_bioerror(bp, EIO);
9859 		st_set_pe_flag(un);
9860 		break;
9861 
9862 	case QUE_LAST_COMMAND:
9863 
9864 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9865 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9866 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9867 			goto last_command_error;
9868 		}
9869 		mutex_exit(ST_MUTEX);
9870 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9871 			return;
9872 		mutex_enter(ST_MUTEX);
9873 last_command_error:
9874 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9875 		un->un_pos.pmode = invalid;
9876 		st_bioerror(bp, EIO);
9877 		st_set_pe_flag(un);
9878 		break;
9879 
9880 	case COMMAND_TIMEOUT:
9881 	case DEVICE_RESET:
9882 	case DEVICE_TAMPER:
9883 	case ATTEMPT_RETRY:
9884 	case PATH_FAILED:
9885 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9886 		    "Command Recovery called on %s status\n",
9887 		    errstatenames[action]);
9888 		action = st_command_recovery(un, pkt, action);
9889 		goto again;
9890 
9891 	default:
9892 		ASSERT(0);
9893 		/* FALLTHRU */
9894 	case JUST_RETURN:
9895 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9896 		mutex_exit(ST_MUTEX);
9897 		return;
9898 	}
9899 
9900 	ST_DO_KSTATS(bp, kstat_runq_exit);
9901 	st_done_and_mutex_exit(un, bp);
9902 }
9903 
9904 static errstate
9905 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9906 {
9907 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9908 	recov_info *rinfo;
9909 	errstate rval = COMMAND_DONE_ERROR;
9910 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9911 	    un->un_rqs : BP_PKT(bp);
9912 	int result;
9913 
9914 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9915 
9916 	rinfo = (recov_info *)pkt->pkt_private;
9917 
9918 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9919 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9920 
9921 	ASSERT(mutex_owned(ST_MUTEX));
9922 
9923 	switch (pkt->pkt_reason) {
9924 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9925 		/*
9926 		 * this occurs when accessing a powered down drive, no
9927 		 * need to complain; just fail the open
9928 		 */
9929 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9930 
9931 		/*
9932 		 * if we have commands outstanding in HBA, and a command
9933 		 * comes back incomplete, we're hosed, so reset target
9934 		 * If we have the bus, but cmd_incomplete, we probably just
9935 		 * have a failed selection, so don't reset the target, just
9936 		 * requeue the command and try again
9937 		 */
9938 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9939 			goto reset_target;
9940 		}
9941 
9942 		/*
9943 		 * Retry selection a couple more times if we're
9944 		 * open.  If opening, we only try just once to
9945 		 * reduce probe time for nonexistant devices.
9946 		 */
9947 		if ((un->un_laststate > ST_STATE_OPENING) &&
9948 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9949 			/* XXX check retriable? */
9950 			rval = QUE_COMMAND;
9951 		}
9952 		ST_DO_ERRSTATS(un, st_transerrs);
9953 		break;
9954 
9955 	case CMD_ABORTED:
9956 		/*
9957 		 * most likely this is caused by flush-on-error support. If
9958 		 * it was not there, the we're in trouble.
9959 		 */
9960 		if (!un->un_flush_on_errors) {
9961 			un->un_status = SUN_KEY_FATAL;
9962 			goto reset_target;
9963 		}
9964 
9965 		st_set_pe_errno(un);
9966 		bioerror(bp, un->un_errno);
9967 		if (un->un_errno)
9968 			return (COMMAND_DONE_ERROR);
9969 		else
9970 			return (COMMAND_DONE);
9971 
9972 	case CMD_TIMEOUT:	/* Command timed out */
9973 		un->un_status = SUN_KEY_TIMEOUT;
9974 		return (COMMAND_TIMEOUT);
9975 
9976 	case CMD_TRAN_ERR:
9977 	case CMD_RESET:
9978 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9979 			if ((un->un_rsvd_status &
9980 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9981 			    ST_RESERVE) {
9982 				un->un_rsvd_status |= ST_LOST_RESERVE;
9983 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9984 				    "Lost Reservation\n");
9985 			}
9986 			rval = DEVICE_RESET;
9987 			return (rval);
9988 		}
9989 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9990 			rval = DEVICE_RESET;
9991 			return (rval);
9992 		}
9993 		/*FALLTHROUGH*/
9994 	default:
9995 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9996 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9997 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9998 reset_target:
9999 
10000 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10001 		    "transport completed with %s\n",
10002 		    scsi_rname(pkt->pkt_reason));
10003 		ST_DO_ERRSTATS(un, st_transerrs);
10004 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
10005 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
10006 		    STAT_ABORTED)) == 0)) {
10007 
10008 			/*
10009 			 * If we haven't reserved the drive don't reset it.
10010 			 */
10011 			if ((un->un_rsvd_status &
10012 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
10013 				return (rval);
10014 			}
10015 
10016 			/*
10017 			 * if we aren't lost yet we will be soon.
10018 			 */
10019 			un->un_pos.pmode = invalid;
10020 
10021 			result = st_reset(un, RESET_LUN);
10022 
10023 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
10024 				/* no hope left to recover */
10025 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10026 				    "recovery by resets failed\n");
10027 				return (rval);
10028 			}
10029 		}
10030 	}
10031 
10032 
10033 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
10034 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
10035 			rval = QUE_COMMAND;
10036 		} else if (bp == un->un_sbufp) {
10037 			if (rinfo->privatelen == sizeof (recov_info)) {
10038 				if (rinfo->cmd_attrib->retriable) {
10039 					/*
10040 					 * These commands can be rerun
10041 					 * with impunity
10042 					 */
10043 					rval = QUE_COMMAND;
10044 				}
10045 			} else {
10046 				cmd_attribute const *attrib;
10047 				attrib =
10048 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10049 				if (attrib->retriable) {
10050 					rval = QUE_COMMAND;
10051 				}
10052 			}
10053 		}
10054 	} else {
10055 		rval = COMMAND_DONE_ERROR;
10056 	}
10057 
10058 	if (un->un_state >= ST_STATE_OPEN) {
10059 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10060 		    fail, scsi_rname(pkt->pkt_reason),
10061 		    (rval == COMMAND_DONE_ERROR)?
10062 		    "giving up" : "retrying command");
10063 	}
10064 	return (rval);
10065 }
10066 
10067 /*
10068  * if the device is busy, then put this bp back on the waitq, on the
10069  * interrupt thread, where we want the head of the queue and not the
10070  * end
10071  *
10072  * The callers of this routine should take measures to save the
10073  * un_throttle in un_last_throttle which will be restored in
10074  * st_intr_restart(). The only exception should be st_intr_restart()
10075  * calling this routine for which the saving is already done.
10076  */
10077 static int
10078 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10079 	clock_t timeout_interval)
10080 {
10081 
10082 	int queued;
10083 	int rval = 0;
10084 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10085 
10086 	mutex_enter(ST_MUTEX);
10087 
10088 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10089 
10090 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10091 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10092 
10093 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10094 		queued = 1;
10095 	} else {
10096 		queued = 0;
10097 	}
10098 
10099 	/*
10100 	 * Check to see if we hit the retry timeout. We check to make sure
10101 	 * this is the first one on the runq and make sure we have not
10102 	 * queued up any more, so this one has to be the last on the list
10103 	 * also. If it is not, we have to fail.  If it is not the first, but
10104 	 * is the last we are in trouble anyway, as we are in the interrupt
10105 	 * context here.
10106 	 */
10107 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10108 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10109 		rval = -1;
10110 		goto exit;
10111 	}
10112 
10113 	/* put the bp back on the waitq */
10114 	if (queued) {
10115 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10116 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10117 	}
10118 
10119 	/*
10120 	 * We don't want any other commands being started in the mean time.
10121 	 * If start had just released mutex after putting something on the
10122 	 * runq, we won't even get here.
10123 	 */
10124 	un->un_throttle = 0;
10125 
10126 	/*
10127 	 * send a marker pkt, if appropriate
10128 	 */
10129 	st_hba_unflush(un);
10130 
10131 	/*
10132 	 * all queues are aligned, we are just waiting to
10133 	 * transport
10134 	 */
10135 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10136 
10137 exit:
10138 	mutex_exit(ST_MUTEX);
10139 	return (rval);
10140 }
10141 
10142 /*
10143  * To get one error entry from error stack
10144  */
10145 static int
10146 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10147 {
10148 #ifdef _MULTI_DATAMODEL
10149 	/*
10150 	 * For use when a 32 bit app makes a call into a
10151 	 * 64 bit ioctl
10152 	 */
10153 	struct mterror_entry32 err_entry32;
10154 #endif /* _MULTI_DATAMODEL */
10155 
10156 	int rval = 0;
10157 	struct mterror_entry err_entry;
10158 	struct mterror_entry_stack *err_link_entry_p;
10159 	size_t arq_status_len_in, arq_status_len_kr;
10160 
10161 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10162 
10163 	ASSERT(mutex_owned(ST_MUTEX));
10164 
10165 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10166 	    "st_get_error_entry()\n");
10167 
10168 	/*
10169 	 * if error record stack empty, return ENXIO
10170 	 */
10171 	if (un->un_error_entry_stk == NULL) {
10172 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10173 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10174 		rval = ENXIO;
10175 		goto ret;
10176 	}
10177 
10178 	/*
10179 	 * get the top entry from stack
10180 	 */
10181 	err_link_entry_p = un->un_error_entry_stk;
10182 	arq_status_len_kr =
10183 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10184 
10185 #ifdef _MULTI_DATAMODEL
10186 	switch (ddi_model_convert_from(flag & FMODELS)) {
10187 	case DDI_MODEL_ILP32:
10188 		if (ddi_copyin((void *)arg, &err_entry32,
10189 		    MTERROR_ENTRY_SIZE_32, flag)) {
10190 			rval = EFAULT;
10191 			goto ret;
10192 		}
10193 
10194 		arq_status_len_in =
10195 		    (size_t)err_entry32.mtee_arq_status_len;
10196 
10197 		err_entry32.mtee_cdb_len =
10198 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10199 
10200 		if (arq_status_len_in > arq_status_len_kr)
10201 			err_entry32.mtee_arq_status_len =
10202 			    (size32_t)arq_status_len_kr;
10203 
10204 		if (ddi_copyout(
10205 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10206 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10207 		    err_entry32.mtee_cdb_len, flag)) {
10208 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10209 			    "st_get_error_entry: Copy cdb buffer error!");
10210 			rval = EFAULT;
10211 		}
10212 
10213 		if (ddi_copyout(
10214 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10215 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10216 		    err_entry32.mtee_arq_status_len, flag)) {
10217 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10218 			    "st_get_error_entry: copy arq status error!");
10219 			rval = EFAULT;
10220 		}
10221 
10222 		if (ddi_copyout(&err_entry32, (void *)arg,
10223 		    MTERROR_ENTRY_SIZE_32, flag)) {
10224 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10225 			    "st_get_error_entry: copy arq status out error!");
10226 			rval = EFAULT;
10227 		}
10228 		break;
10229 
10230 	case DDI_MODEL_NONE:
10231 		if (ddi_copyin((void *)arg, &err_entry,
10232 		    MTERROR_ENTRY_SIZE_64, flag)) {
10233 			rval = EFAULT;
10234 			goto ret;
10235 		}
10236 		arq_status_len_in = err_entry.mtee_arq_status_len;
10237 
10238 		err_entry.mtee_cdb_len =
10239 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10240 
10241 		if (arq_status_len_in > arq_status_len_kr)
10242 			err_entry.mtee_arq_status_len =
10243 			    arq_status_len_kr;
10244 
10245 		if (ddi_copyout(
10246 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10247 		    err_entry.mtee_cdb_buf,
10248 		    err_entry.mtee_cdb_len, flag)) {
10249 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10250 			    "st_get_error_entry: Copy cdb buffer error!");
10251 			rval = EFAULT;
10252 		}
10253 
10254 		if (ddi_copyout(
10255 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10256 		    err_entry.mtee_arq_status,
10257 		    err_entry.mtee_arq_status_len, flag)) {
10258 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10259 			    "st_get_error_entry: copy arq status error!");
10260 			rval = EFAULT;
10261 		}
10262 
10263 		if (ddi_copyout(&err_entry, (void *)arg,
10264 		    MTERROR_ENTRY_SIZE_64, flag)) {
10265 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10266 			    "st_get_error_entry: copy arq status out error!");
10267 			rval = EFAULT;
10268 		}
10269 		break;
10270 	}
10271 #else /* _MULTI_DATAMODEL */
10272 	if (ddi_copyin((void *)arg, &err_entry,
10273 	    MTERROR_ENTRY_SIZE_64, flag)) {
10274 		rval = EFAULT;
10275 		goto ret;
10276 	}
10277 	arq_status_len_in = err_entry.mtee_arq_status_len;
10278 
10279 	err_entry.mtee_cdb_len =
10280 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10281 
10282 	if (arq_status_len_in > arq_status_len_kr)
10283 		err_entry.mtee_arq_status_len =
10284 		    arq_status_len_kr;
10285 
10286 	if (ddi_copyout(
10287 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10288 	    err_entry.mtee_cdb_buf,
10289 	    err_entry.mtee_cdb_len, flag)) {
10290 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10291 		    "st_get_error_entry: Copy cdb buffer error!");
10292 		rval = EFAULT;
10293 	}
10294 
10295 	if (ddi_copyout(
10296 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10297 	    err_entry.mtee_arq_status,
10298 	    err_entry.mtee_arq_status_len, flag)) {
10299 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10300 		    "st_get_error_entry: copy arq status buffer error!");
10301 		rval = EFAULT;
10302 	}
10303 
10304 	if (ddi_copyout(&err_entry, (void *)arg,
10305 	    MTERROR_ENTRY_SIZE_64, flag)) {
10306 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10307 		    "st_get_error_entry: copy arq status out error!");
10308 		rval = EFAULT;
10309 	}
10310 #endif /* _MULTI_DATAMODEL */
10311 
10312 	/*
10313 	 * update stack
10314 	 */
10315 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10316 
10317 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10318 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10319 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10320 
10321 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10322 	    SECMDS_STATUS_SIZE);
10323 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10324 
10325 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10326 	err_link_entry_p = NULL;
10327 ret:
10328 	return (rval);
10329 }
10330 
10331 /*
10332  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10333  * the scsi CDB command which causes the error and generates sense data and
10334  * the scsi status.
10335  *
10336  *      error-record stack
10337  *
10338  *
10339  *             TOP                                     BOTTOM
10340  *              ------------------------------------------
10341  *              |   0   |   1   |   2   |   ...  |   n   |
10342  *              ------------------------------------------
10343  *                  ^
10344  *                  |
10345  *       pointer to error entry
10346  *
10347  * when st driver generates one sense data record, it creates a error-entry
10348  * and pushes it onto the stack.
10349  *
10350  */
10351 
10352 static void
10353 st_update_error_stack(struct scsi_tape *un,
10354 			struct scsi_pkt *pkt,
10355 			struct scsi_arq_status *cmd)
10356 {
10357 	struct mterror_entry_stack *err_entry_tmp;
10358 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10359 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10360 
10361 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10362 
10363 	ASSERT(mutex_owned(ST_MUTEX));
10364 
10365 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10366 	    "st_update_error_stack()\n");
10367 
10368 	ASSERT(cmd);
10369 	ASSERT(cdbp);
10370 	if (cdblen == 0) {
10371 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10372 		    "st_update_error_stack: CDB length error!\n");
10373 		return;
10374 	}
10375 
10376 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10377 	ASSERT(err_entry_tmp != NULL);
10378 
10379 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10380 	    kmem_alloc(cdblen, KM_SLEEP);
10381 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10382 
10383 	err_entry_tmp->mtees_entry.mtee_arq_status =
10384 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10385 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10386 
10387 	/*
10388 	 * copy cdb command & length to current error entry
10389 	 */
10390 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10391 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10392 
10393 	/*
10394 	 * copy scsi status length to current error entry
10395 	 */
10396 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10397 	    SECMDS_STATUS_SIZE;
10398 
10399 	/*
10400 	 * copy sense data and scsi status to current error entry
10401 	 */
10402 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10403 	    SECMDS_STATUS_SIZE);
10404 
10405 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10406 	un->un_error_entry_stk = err_entry_tmp;
10407 
10408 }
10409 
10410 /*
10411  * Empty all the error entry in stack
10412  */
10413 static void
10414 st_empty_error_stack(struct scsi_tape *un)
10415 {
10416 	struct mterror_entry_stack *linkp;
10417 
10418 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10419 
10420 	ASSERT(mutex_owned(ST_MUTEX));
10421 
10422 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10423 	    "st_empty_entry_stack()\n");
10424 
10425 	while (un->un_error_entry_stk != NULL) {
10426 		linkp = un->un_error_entry_stk;
10427 		un->un_error_entry_stk =
10428 		    un->un_error_entry_stk->mtees_nextp;
10429 
10430 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10431 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10432 			    linkp->mtees_entry.mtee_cdb_len);
10433 
10434 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10435 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10436 			    linkp->mtees_entry.mtee_arq_status_len);
10437 
10438 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10439 		linkp = NULL;
10440 	}
10441 }
10442 
10443 static errstate
10444 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10445 {
10446 	struct scsi_pkt *pkt = BP_PKT(bp);
10447 	struct scsi_pkt *rqpkt = un->un_rqs;
10448 	struct scsi_arq_status arqstat;
10449 	recov_info *rcif = pkt->pkt_private;
10450 
10451 	errstate rval = COMMAND_DONE_ERROR;
10452 	int amt;
10453 
10454 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10455 
10456 	ASSERT(mutex_owned(ST_MUTEX));
10457 
10458 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10459 	    "st_handle_sense()\n");
10460 
10461 	if (SCBP(rqpkt)->sts_busy) {
10462 		if (rcif->privatelen == sizeof (recov_info)) {
10463 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10464 			    "Attempt recovery of busy unit on request sense\n");
10465 			rval = ATTEMPT_RETRY;
10466 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10467 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10468 			    "Retry busy unit on request sense\n");
10469 			rval = QUE_BUSY_COMMAND;
10470 		}
10471 		return (rval);
10472 	} else if (SCBP(rqpkt)->sts_chk) {
10473 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10474 		    "Check Condition on REQUEST SENSE\n");
10475 		return (rval);
10476 	}
10477 
10478 	/*
10479 	 * Make sure there is sense data to look at.
10480 	 */
10481 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10482 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10483 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10484 		return (rval);
10485 	}
10486 
10487 	/* was there enough data? */
10488 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10489 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10490 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10491 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10492 		    "REQUEST SENSE couldn't get sense data\n");
10493 		return (rval);
10494 	}
10495 
10496 	bcopy(SCBP(pkt), &arqstat.sts_status,
10497 	    sizeof (struct scsi_status));
10498 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10499 	    sizeof (struct scsi_status));
10500 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10501 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10502 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10503 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10504 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10505 
10506 	/*
10507 	 * copy one arqstat entry in the sense data buffer
10508 	 */
10509 	st_update_error_stack(un, pkt, &arqstat);
10510 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10511 }
10512 
10513 static errstate
10514 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10515 {
10516 	struct scsi_pkt *pkt = BP_PKT(bp);
10517 	struct scsi_arq_status *arqstat =
10518 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10519 	errstate rval = COMMAND_DONE_ERROR;
10520 	int amt;
10521 
10522 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10523 
10524 	ASSERT(mutex_owned(ST_MUTEX));
10525 
10526 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10527 	    "st_handle_autosense()\n");
10528 
10529 	if (arqstat->sts_rqpkt_status.sts_busy) {
10530 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10531 		    "busy unit on request sense\n");
10532 		/*
10533 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10534 		 * the disadvantage is that we do not have any delay for the
10535 		 * second retry of rqsense and we have to keep a packet around
10536 		 */
10537 		return (QUE_SENSE);
10538 
10539 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10540 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10541 		    "transport error on REQUEST SENSE\n");
10542 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10543 		    ((arqstat->sts_rqpkt_statistics &
10544 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10545 			if (st_reset(un, RESET_LUN) == 0) {
10546 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10547 				    "recovery by resets failed\n");
10548 			}
10549 		}
10550 		return (rval);
10551 
10552 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10553 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10554 		    "Check Condition on REQUEST SENSE\n");
10555 		return (rval);
10556 	}
10557 
10558 
10559 	/* was there enough data? */
10560 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10561 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10562 	} else {
10563 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10564 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10565 		} else {
10566 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10567 		}
10568 	}
10569 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10570 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10571 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10572 		    "REQUEST SENSE couldn't get sense data\n");
10573 		return (rval);
10574 	}
10575 
10576 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10577 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10578 	} else {
10579 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10580 	}
10581 
10582 	/*
10583 	 * copy one arqstat entry in the sense data buffer
10584 	 */
10585 	st_update_error_stack(un, pkt, arqstat);
10586 
10587 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10588 }
10589 
10590 static errstate
10591 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10592     struct scsi_arq_status *statusp, tapepos_t *pos)
10593 {
10594 	struct scsi_pkt *pkt = BP_PKT(bp);
10595 	recov_info *ri = pkt->pkt_private;
10596 	errstate rval = COMMAND_DONE_ERROR;
10597 	cmd_attribute const *attrib;
10598 	long resid;
10599 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10600 	int severity;
10601 	int get_error;
10602 
10603 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10604 
10605 	ASSERT(mutex_owned(ST_MUTEX));
10606 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10607 	    "st_decode_sense()\n");
10608 
10609 	/*
10610 	 * For uscsi commands, squirrel away a copy of the
10611 	 * results of the Request Sense.
10612 	 */
10613 	if (USCSI_CMD(bp)) {
10614 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10615 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10616 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10617 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10618 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10619 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10620 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10621 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10622 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10623 		}
10624 	}
10625 
10626 	if (ri->privatelen == sizeof (recov_info)) {
10627 		attrib = ri->cmd_attrib;
10628 	} else {
10629 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10630 	}
10631 
10632 	/*
10633 	 * If the drive is an MT-02, reposition the
10634 	 * secondary error code into the proper place.
10635 	 *
10636 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10637 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10638 	 * so it's in byte 12.
10639 	 */
10640 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10641 		sensep->es_code = sensep->es_add_info[0];
10642 	}
10643 
10644 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10645 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10646 
10647 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10648 	    sizeof (*statusp));
10649 
10650 	/* for normal I/O check extract the resid values. */
10651 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10652 		if (sensep->es_valid) {
10653 			resid =
10654 			    (sensep->es_info_1 << 24) |
10655 			    (sensep->es_info_2 << 16) |
10656 			    (sensep->es_info_3 << 8)  |
10657 			    (sensep->es_info_4);
10658 			/* If fixed block */
10659 			if (un->un_bsize) {
10660 				resid *= un->un_bsize;
10661 			}
10662 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10663 			resid = pkt->pkt_resid;
10664 		} else {
10665 			resid = bp->b_bcount;
10666 		}
10667 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10668 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10669 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10670 		    resid,
10671 		    (sensep->es_info_1 << 24) |
10672 		    (sensep->es_info_2 << 16) |
10673 		    (sensep->es_info_3 << 8)  |
10674 		    (sensep->es_info_4),
10675 		    pkt->pkt_resid);
10676 		/*
10677 		 * The problem is, what should we believe?
10678 		 */
10679 		if (resid && (pkt->pkt_resid == 0)) {
10680 			pkt->pkt_resid = resid;
10681 		}
10682 	} else {
10683 		/*
10684 		 * If the command is SCMD_SPACE, we need to get the
10685 		 * residual as returned in the sense data, to adjust
10686 		 * our idea of current tape position correctly
10687 		 */
10688 		if ((sensep->es_valid) &&
10689 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10690 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10691 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10692 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10693 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10694 			resid =
10695 			    (sensep->es_info_1 << 24) |
10696 			    (sensep->es_info_2 << 16) |
10697 			    (sensep->es_info_3 << 8)  |
10698 			    (sensep->es_info_4);
10699 			bp->b_resid = resid;
10700 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10701 			    "st_decode_sense(other):	resid=%ld\n", resid);
10702 		} else {
10703 			/*
10704 			 * If the special command is SCMD_READ,
10705 			 * the correct resid will be set later.
10706 			 */
10707 			if (attrib->get_cnt != NULL) {
10708 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10709 			} else {
10710 				resid = bp->b_bcount;
10711 			}
10712 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10713 			    "st_decode_sense(special read):  resid=%ld\n",
10714 			    resid);
10715 		}
10716 	}
10717 
10718 	if ((un->un_state >= ST_STATE_OPEN) &&
10719 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10720 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10721 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10722 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10723 		    "sense data", (char *)sensep, amt);
10724 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10725 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10726 		    bp->b_bcount, resid, pkt->pkt_resid);
10727 	}
10728 
10729 	switch (un->un_status = sensep->es_key) {
10730 	case KEY_NO_SENSE:
10731 		severity = SCSI_ERR_INFO;
10732 
10733 		/*
10734 		 * Erase, locate or rewind operation in progress, retry
10735 		 * ASC  ASCQ
10736 		 *  00   18    Erase operation in progress
10737 		 *  00   19    Locate operation in progress
10738 		 *  00   1A    Rewind operation in progress
10739 		 */
10740 		if (sensep->es_add_code == 0 &&
10741 		    ((sensep->es_qual_code == 0x18) ||
10742 		    (sensep->es_qual_code == 0x19) ||
10743 		    (sensep->es_qual_code == 0x1a))) {
10744 			rval = QUE_BUSY_COMMAND;
10745 			break;
10746 		}
10747 
10748 		goto common;
10749 
10750 	case KEY_RECOVERABLE_ERROR:
10751 		severity = SCSI_ERR_RECOVERED;
10752 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10753 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10754 			if (un->un_dp->options &
10755 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10756 				rval = QUE_LAST_COMMAND;
10757 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10758 				    severity, pos->lgclblkno,
10759 				    un->un_err_pos.lgclblkno, scsi_cmds,
10760 				    sensep);
10761 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10762 				    "Command will be retried\n");
10763 			} else {
10764 				severity = SCSI_ERR_FATAL;
10765 				rval = COMMAND_DONE_ERROR_RECOVERED;
10766 				ST_DO_ERRSTATS(un, st_softerrs);
10767 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10768 				    severity, pos->lgclblkno,
10769 				    un->un_err_pos.lgclblkno, scsi_cmds,
10770 				    sensep);
10771 			}
10772 			break;
10773 		}
10774 common:
10775 		/*
10776 		 * XXX only want reads to be stopped by filemarks.
10777 		 * Don't want them to be stopped by EOT.  EOT matters
10778 		 * only on write.
10779 		 */
10780 		if (sensep->es_filmk && !sensep->es_eom) {
10781 			rval = COMMAND_DONE;
10782 		} else if (sensep->es_eom) {
10783 			rval = COMMAND_DONE;
10784 		} else if (sensep->es_ili) {
10785 			/*
10786 			 * Fun with variable length record devices:
10787 			 * for specifying larger blocks sizes than the
10788 			 * actual physical record size.
10789 			 */
10790 			if (un->un_bsize == 0 && resid > 0) {
10791 				/*
10792 				 * XXX! Ugly.
10793 				 * The requested blocksize is > tape blocksize,
10794 				 * so this is ok, so we just return the
10795 				 * actual size xferred.
10796 				 */
10797 				pkt->pkt_resid = resid;
10798 				rval = COMMAND_DONE;
10799 			} else if (un->un_bsize == 0 && resid < 0) {
10800 				/*
10801 				 * The requested blocksize is < tape blocksize,
10802 				 * so this is not ok, so we err with ENOMEM
10803 				 */
10804 				rval = COMMAND_DONE_ERROR_RECOVERED;
10805 				st_bioerror(bp, ENOMEM);
10806 			} else {
10807 				ST_DO_ERRSTATS(un, st_softerrs);
10808 				severity = SCSI_ERR_FATAL;
10809 				rval = COMMAND_DONE_ERROR;
10810 				st_bioerror(bp, EINVAL);
10811 				un->un_running.pmode = invalid;
10812 			}
10813 		} else {
10814 			/*
10815 			 * we hope and pray for this just being
10816 			 * something we can ignore (ie. a
10817 			 * truly recoverable soft error)
10818 			 */
10819 			rval = COMMAND_DONE;
10820 		}
10821 		if (sensep->es_filmk) {
10822 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10823 			    "filemark\n");
10824 			un->un_status = SUN_KEY_EOF;
10825 			pos->eof = ST_EOF_PENDING;
10826 			st_set_pe_flag(un);
10827 		}
10828 
10829 		/*
10830 		 * ignore eom when reading, a fmk should terminate reading
10831 		 */
10832 		if ((sensep->es_eom) &&
10833 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10834 			if ((sensep->es_add_code == 0) &&
10835 			    (sensep->es_qual_code == 4)) {
10836 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10837 				    "bot\n");
10838 				un->un_status = SUN_KEY_BOT;
10839 				pos->eof = ST_NO_EOF;
10840 				pos->lgclblkno = 0;
10841 				pos->fileno = 0;
10842 				pos->blkno = 0;
10843 				if (pos->pmode != legacy)
10844 					pos->pmode = legacy;
10845 			} else {
10846 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10847 				    "eom\n");
10848 				un->un_status = SUN_KEY_EOT;
10849 				pos->eof = ST_EOM;
10850 			}
10851 			st_set_pe_flag(un);
10852 		}
10853 
10854 		break;
10855 
10856 	case KEY_ILLEGAL_REQUEST:
10857 
10858 		if (un->un_laststate >= ST_STATE_OPEN) {
10859 			ST_DO_ERRSTATS(un, st_softerrs);
10860 			severity = SCSI_ERR_FATAL;
10861 		} else {
10862 			severity = SCSI_ERR_INFO;
10863 		}
10864 		break;
10865 
10866 	case KEY_MEDIUM_ERROR:
10867 		ST_DO_ERRSTATS(un, st_harderrs);
10868 		severity = SCSI_ERR_FATAL;
10869 		un->un_pos.pmode = invalid;
10870 		un->un_running.pmode = invalid;
10871 check_keys:
10872 		/*
10873 		 * attempt to process the keys in the presence of
10874 		 * other errors
10875 		 */
10876 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10877 			/*
10878 			 * Fun with variable length record devices:
10879 			 * for specifying larger blocks sizes than the
10880 			 * actual physical record size.
10881 			 */
10882 			if (un->un_bsize == 0 && resid > 0) {
10883 				/*
10884 				 * XXX! Ugly
10885 				 */
10886 				pkt->pkt_resid = resid;
10887 			} else if (un->un_bsize == 0 && resid < 0) {
10888 				st_bioerror(bp, EINVAL);
10889 			} else {
10890 				severity = SCSI_ERR_FATAL;
10891 				rval = COMMAND_DONE_ERROR;
10892 				st_bioerror(bp, EINVAL);
10893 			}
10894 		}
10895 		if (sensep->es_filmk) {
10896 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10897 			    "filemark\n");
10898 			un->un_status = SUN_KEY_EOF;
10899 			pos->eof = ST_EOF_PENDING;
10900 			st_set_pe_flag(un);
10901 		}
10902 
10903 		/*
10904 		 * ignore eom when reading, a fmk should terminate reading
10905 		 */
10906 		if ((sensep->es_eom) &&
10907 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10908 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10909 			un->un_status = SUN_KEY_EOT;
10910 			pos->eof = ST_EOM;
10911 			st_set_pe_flag(un);
10912 		}
10913 
10914 		break;
10915 
10916 	case KEY_VOLUME_OVERFLOW:
10917 		ST_DO_ERRSTATS(un, st_softerrs);
10918 		pos->eof = ST_EOM;
10919 		severity = SCSI_ERR_FATAL;
10920 		rval = COMMAND_DONE_ERROR;
10921 		goto check_keys;
10922 
10923 	case KEY_HARDWARE_ERROR:
10924 		ST_DO_ERRSTATS(un, st_harderrs);
10925 		severity = SCSI_ERR_FATAL;
10926 		rval = COMMAND_DONE_ERROR;
10927 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10928 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10929 		break;
10930 
10931 	case KEY_BLANK_CHECK:
10932 		ST_DO_ERRSTATS(un, st_softerrs);
10933 		severity = SCSI_ERR_INFO;
10934 
10935 		/*
10936 		 * if not a special request and some data was xferred then it
10937 		 * it is not an error yet
10938 		 */
10939 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10940 			/*
10941 			 * no error for read with or without data xferred
10942 			 */
10943 			un->un_status = SUN_KEY_EOT;
10944 			pos->eof = ST_EOT;
10945 			rval = COMMAND_DONE_ERROR;
10946 			un->un_running.pmode = invalid;
10947 			st_set_pe_flag(un);
10948 			goto check_keys;
10949 		} else if (bp != un->un_sbufp &&
10950 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10951 			rval = COMMAND_DONE;
10952 		} else {
10953 			rval = COMMAND_DONE_ERROR_RECOVERED;
10954 		}
10955 
10956 		if (un->un_laststate >= ST_STATE_OPEN) {
10957 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10958 			    "blank check\n");
10959 			pos->eof = ST_EOM;
10960 		}
10961 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10962 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10963 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10964 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10965 			/*
10966 			 * we were doing a fast forward by skipping
10967 			 * multiple fmk at the time
10968 			 */
10969 			st_bioerror(bp, EIO);
10970 			severity = SCSI_ERR_RECOVERED;
10971 			rval	 = COMMAND_DONE;
10972 		}
10973 		st_set_pe_flag(un);
10974 		goto check_keys;
10975 
10976 	case KEY_WRITE_PROTECT:
10977 		if (st_wrongtapetype(un)) {
10978 			un->un_status = SUN_KEY_WRONGMEDIA;
10979 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10980 			    "wrong tape for writing- use DC6150 tape "
10981 			    "(or equivalent)\n");
10982 			severity = SCSI_ERR_UNKNOWN;
10983 		} else {
10984 			severity = SCSI_ERR_FATAL;
10985 		}
10986 		ST_DO_ERRSTATS(un, st_harderrs);
10987 		rval = COMMAND_DONE_ERROR;
10988 		st_bioerror(bp, EACCES);
10989 		break;
10990 
10991 	case KEY_UNIT_ATTENTION:
10992 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10993 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10994 
10995 		un->un_unit_attention_flags |= 1;
10996 		/*
10997 		 * If we have detected a Bus Reset and the tape
10998 		 * drive has been reserved.
10999 		 */
11000 		if (ST_RQSENSE->es_add_code == 0x29) {
11001 			rval = DEVICE_RESET;
11002 			if ((un->un_rsvd_status &
11003 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
11004 			    ST_RESERVE) {
11005 				un->un_rsvd_status |= ST_LOST_RESERVE;
11006 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
11007 				    "st_decode_sense: Lost Reservation\n");
11008 			}
11009 		}
11010 
11011 		/*
11012 		 * If this is a recovery command and retrable, retry.
11013 		 */
11014 		if (bp == un->un_recov_buf) {
11015 			severity = SCSI_ERR_INFO;
11016 			if (attrib->retriable &&
11017 			    ri->pkt_retry_cnt++ < st_retry_count) {
11018 				rval = QUE_COMMAND;
11019 			} else {
11020 				rval = COMMAND_DONE_ERROR;
11021 			}
11022 			break; /* Don't set position invalid */
11023 		}
11024 
11025 		/*
11026 		 * If ST_APPLICATION_RESERVATIONS is set,
11027 		 * If the asc/ascq indicates that the reservation
11028 		 * has been cleared just allow the write to continue
11029 		 * which would force a scsi 2 reserve.
11030 		 * If preempted that persistent reservation
11031 		 * the scsi 2 reserve would get a reservation conflict.
11032 		 */
11033 		if ((un->un_rsvd_status &
11034 		    ST_APPLICATION_RESERVATIONS) != 0) {
11035 			/*
11036 			 * RESERVATIONS PREEMPTED
11037 			 * With MPxIO this could be a fail over? XXX
11038 			 */
11039 			if (ST_RQSENSE->es_add_code == 0x2a &&
11040 			    ST_RQSENSE->es_qual_code == 0x03) {
11041 				severity = SCSI_ERR_INFO;
11042 				rval = COMMAND_DONE_ERROR;
11043 				pos->pmode = invalid;
11044 				break;
11045 			/*
11046 			 * RESERVATIONS RELEASED
11047 			 */
11048 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
11049 			    ST_RQSENSE->es_qual_code == 0x04) {
11050 				severity = SCSI_ERR_INFO;
11051 				rval = COMMAND_DONE;
11052 				break;
11053 			}
11054 		}
11055 
11056 		if (un->un_state <= ST_STATE_OPENING) {
11057 			/*
11058 			 * Look, the tape isn't open yet, now determine
11059 			 * if the cause is a BUS RESET, Save the file
11060 			 * and Block positions for the callers to
11061 			 * recover from the loss of position.
11062 			 */
11063 			severity = SCSI_ERR_INFO;
11064 			if ((pos->pmode != invalid) &&
11065 			    (rval == DEVICE_RESET) &&
11066 			    (un->un_restore_pos != 1)) {
11067 				un->un_save_fileno = pos->fileno;
11068 				un->un_save_blkno = pos->blkno;
11069 				un->un_restore_pos = 1;
11070 			}
11071 
11072 			if (attrib->retriable &&
11073 			    ri->pkt_retry_cnt++ < st_retry_count) {
11074 				rval = QUE_COMMAND;
11075 			} else if (rval == DEVICE_RESET) {
11076 				break;
11077 			} else {
11078 				rval = COMMAND_DONE_ERROR;
11079 			}
11080 		/*
11081 		 * Means it thinks the mode parameters have changed.
11082 		 * This is the result of a reset clearing settings or
11083 		 * another initiator changing what we set.
11084 		 */
11085 		}
11086 		if (ST_RQSENSE->es_add_code == 0x2a) {
11087 			if (ST_RQSENSE->es_qual_code == 0x1) {
11088 				/* Error recovery will modeselect and retry. */
11089 				rval = DEVICE_TAMPER;
11090 				severity = SCSI_ERR_INFO;
11091 				break; /* don't set position invalid */
11092 			}
11093 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11094 			    ST_RQSENSE->es_qual_code == 0x2 ||
11095 			    ST_RQSENSE->es_qual_code == 0x3 ||
11096 			    ST_RQSENSE->es_qual_code == 0x4 ||
11097 			    ST_RQSENSE->es_qual_code == 0x5 ||
11098 			    ST_RQSENSE->es_qual_code == 0x6 ||
11099 			    ST_RQSENSE->es_qual_code == 0x7) {
11100 				rval = DEVICE_TAMPER;
11101 				severity = SCSI_ERR_INFO;
11102 			}
11103 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11104 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11105 		    ST_RQSENSE->es_qual_code == 0x5)) {
11106 			/*
11107 			 * Not Ready to Ready change, Media may have changed.
11108 			 */
11109 			rval = DEVICE_TAMPER;
11110 			severity = SCSI_ERR_RETRYABLE;
11111 		} else {
11112 			if (rval != DEVICE_RESET) {
11113 				rval = COMMAND_DONE_ERROR;
11114 			} else {
11115 				/*
11116 				 * Returning DEVICE_RESET will call
11117 				 * error recovery.
11118 				 */
11119 				severity = SCSI_ERR_INFO;
11120 				break; /* don't set position invalid */
11121 			}
11122 			/*
11123 			 * Check if it is an Unexpected Unit Attention.
11124 			 * If state is >= ST_STATE_OPEN, we have
11125 			 * already done the initialization .
11126 			 * In this case it is Fatal Error
11127 			 * since no further reading/writing
11128 			 * can be done with fileno set to < 0.
11129 			 */
11130 			if (un->un_state >= ST_STATE_OPEN) {
11131 				ST_DO_ERRSTATS(un, st_harderrs);
11132 				severity = SCSI_ERR_FATAL;
11133 			} else {
11134 				severity = SCSI_ERR_INFO;
11135 			}
11136 		}
11137 
11138 		pos->pmode = invalid;
11139 
11140 		break;
11141 
11142 	case KEY_NOT_READY:
11143 		/*
11144 		 * If in process of getting ready retry.
11145 		 */
11146 		if (sensep->es_add_code == 0x04) {
11147 			switch (sensep->es_qual_code) {
11148 			case 0x07:
11149 				/*
11150 				 * We get here when the tape is rewinding.
11151 				 * QUE_BUSY_COMMAND retries every 10 seconds.
11152 				 */
11153 				if (ri->pkt_retry_cnt++ <
11154 				    (un->un_dp->rewind_timeout / 10)) {
11155 					rval = QUE_BUSY_COMMAND;
11156 					severity = SCSI_ERR_INFO;
11157 				} else {
11158 					/* give up */
11159 					rval = COMMAND_DONE_ERROR;
11160 					severity = SCSI_ERR_FATAL;
11161 				}
11162 				break;
11163 			case 0x01:
11164 				if (ri->pkt_retry_cnt++ < st_retry_count) {
11165 					rval = QUE_COMMAND;
11166 					severity = SCSI_ERR_INFO;
11167 					break;
11168 				}
11169 			default: /* FALLTHRU */
11170 				/* give up */
11171 				rval = COMMAND_DONE_ERROR;
11172 				severity = SCSI_ERR_FATAL;
11173 			}
11174 		} else {
11175 			/* give up */
11176 			rval = COMMAND_DONE_ERROR;
11177 			severity = SCSI_ERR_FATAL;
11178 		}
11179 
11180 		/*
11181 		 * If this was an error and after device opened
11182 		 * do error stats.
11183 		 */
11184 		if (rval == COMMAND_DONE_ERROR &&
11185 		    un->un_state > ST_STATE_OPENING) {
11186 			ST_DO_ERRSTATS(un, st_harderrs);
11187 		}
11188 
11189 		if (ST_RQSENSE->es_add_code == 0x3a) {
11190 			if (st_error_level >= SCSI_ERR_FATAL)
11191 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11192 				    "Tape not inserted in drive\n");
11193 			un->un_mediastate = MTIO_EJECTED;
11194 			cv_broadcast(&un->un_state_cv);
11195 		}
11196 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11197 		    (rval != QUE_COMMAND))
11198 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11199 		break;
11200 
11201 	case KEY_ABORTED_COMMAND:
11202 		/* XXX Do drives return this when they see a lost light? */
11203 		/* Testing would say yes */
11204 
11205 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11206 			rval = ATTEMPT_RETRY;
11207 			severity = SCSI_ERR_RETRYABLE;
11208 			goto check_keys;
11209 		}
11210 		/*
11211 		 * Probably a parity error...
11212 		 * if we retry here then this may cause data to be
11213 		 * written twice or data skipped during reading
11214 		 */
11215 		ST_DO_ERRSTATS(un, st_harderrs);
11216 		severity = SCSI_ERR_FATAL;
11217 		rval = COMMAND_DONE_ERROR;
11218 		goto check_keys;
11219 
11220 	default:
11221 		/*
11222 		 * Undecoded sense key.	 Try retries and hope
11223 		 * that will fix the problem.  Otherwise, we're
11224 		 * dead.
11225 		 */
11226 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11227 		    "Unhandled Sense Key '%s'\n",
11228 		    sense_keys[un->un_status]);
11229 		ST_DO_ERRSTATS(un, st_harderrs);
11230 		severity = SCSI_ERR_FATAL;
11231 		rval = COMMAND_DONE_ERROR;
11232 		goto check_keys;
11233 	}
11234 
11235 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11236 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11237 	    (un->un_laststate > ST_STATE_OPENING) &&
11238 	    (severity >= st_error_level))) {
11239 
11240 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11241 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11242 		    scsi_cmds, sensep);
11243 		if (sensep->es_filmk) {
11244 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11245 			    "File Mark Detected\n");
11246 		}
11247 		if (sensep->es_eom) {
11248 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11249 			    "End-of-Media Detected\n");
11250 		}
11251 		if (sensep->es_ili) {
11252 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11253 			    "Incorrect Length Indicator Set\n");
11254 		}
11255 	}
11256 	get_error = geterror(bp);
11257 	if (((rval == COMMAND_DONE_ERROR) ||
11258 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11259 	    ((get_error == EIO) || (get_error == 0))) {
11260 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11261 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11262 		if (un->un_rqs_state & ST_RQS_READ) {
11263 			un->un_rqs_state &= ~(ST_RQS_READ);
11264 		} else {
11265 			un->un_rqs_state |= ST_RQS_OVR;
11266 		}
11267 	}
11268 
11269 	return (rval);
11270 }
11271 
11272 
11273 static int
11274 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11275 {
11276 	int status = TRAN_ACCEPT;
11277 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11278 
11279 	mutex_enter(ST_MUTEX);
11280 
11281 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11282 
11283 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11284 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11285 
11286 	/*
11287 	 * Check to see if we hit the retry timeout. We check to make sure
11288 	 * this is the first one on the runq and make sure we have not
11289 	 * queued up any more, so this one has to be the last on the list
11290 	 * also. If it is not, we have to fail.  If it is not the first, but
11291 	 * is the last we are in trouble anyway, as we are in the interrupt
11292 	 * context here.
11293 	 */
11294 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11295 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11296 		goto exit;
11297 	}
11298 
11299 	if (un->un_throttle) {
11300 		un->un_last_throttle = un->un_throttle;
11301 		un->un_throttle = 0;
11302 	}
11303 
11304 	/*
11305 	 * Here we know : bp is the first and last one on the runq
11306 	 * it is not necessary to put it back on the head of the
11307 	 * waitq and then move from waitq to runq. Save this queuing
11308 	 * and call scsi_transport.
11309 	 */
11310 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11311 
11312 	status = st_transport(un, BP_PKT(bp));
11313 
11314 	if (status == TRAN_ACCEPT) {
11315 		if (un->un_last_throttle) {
11316 			un->un_throttle = un->un_last_throttle;
11317 		}
11318 		mutex_exit(ST_MUTEX);
11319 
11320 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11321 		    "restart transport \n");
11322 		return (0);
11323 	}
11324 
11325 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11326 	mutex_exit(ST_MUTEX);
11327 
11328 	if (status == TRAN_BUSY) {
11329 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11330 			return (0);
11331 		}
11332 	}
11333 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11334 	    "restart transport rejected\n");
11335 	mutex_enter(ST_MUTEX);
11336 	ST_DO_ERRSTATS(un, st_transerrs);
11337 	if (un->un_last_throttle) {
11338 		un->un_throttle = un->un_last_throttle;
11339 	}
11340 exit:
11341 	mutex_exit(ST_MUTEX);
11342 	return (-1);
11343 }
11344 
11345 static int
11346 st_wrongtapetype(struct scsi_tape *un)
11347 {
11348 
11349 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11350 
11351 	ASSERT(mutex_owned(ST_MUTEX));
11352 
11353 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11354 
11355 	/*
11356 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11357 	 */
11358 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11359 		switch (un->un_dp->type) {
11360 		case ST_TYPE_WANGTEK:
11361 		case ST_TYPE_ARCHIVE:
11362 			/*
11363 			 * If this really worked, we could go off of
11364 			 * the density codes set in the modesense
11365 			 * page. For this drive, 0x10 == QIC-120,
11366 			 * 0xf == QIC-150, and 0x5 should be for
11367 			 * both QIC-24 and, maybe, QIC-11. However,
11368 			 * the h/w doesn't do what the manual says
11369 			 * that it should, so we'll key off of
11370 			 * getting a WRITE PROTECT error AND wp *not*
11371 			 * set in the mode sense information.
11372 			 */
11373 			/*
11374 			 * XXX but we already know that status is
11375 			 * write protect, so don't check it again.
11376 			 */
11377 
11378 			if (un->un_status == KEY_WRITE_PROTECT &&
11379 			    un->un_mspl->wp == 0) {
11380 				return (1);
11381 			}
11382 			break;
11383 		default:
11384 			break;
11385 		}
11386 	}
11387 	return (0);
11388 }
11389 
11390 static errstate
11391 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11392 {
11393 	errstate action;
11394 	recov_info *rcvi = pkt->pkt_private;
11395 	buf_t *bp = rcvi->cmd_bp;
11396 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11397 
11398 	ST_FUNC(ST_DEVINFO, st_check_error);
11399 
11400 	ASSERT(mutex_owned(ST_MUTEX));
11401 
11402 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11403 
11404 	switch (SCBP_C(pkt)) {
11405 	case STATUS_RESERVATION_CONFLICT:
11406 		/*
11407 		 * Command recovery is enabled, not just opening,
11408 		 * we had the drive reserved and we thing its ours.
11409 		 * Call recovery to attempt to take it back.
11410 		 */
11411 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11412 		    (bp != un->un_recov_buf) &&
11413 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11414 		    ((un->un_rsvd_status & (ST_RESERVE |
11415 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11416 			action = ATTEMPT_RETRY;
11417 			un->un_rsvd_status |= ST_LOST_RESERVE;
11418 		} else {
11419 			action = COMMAND_DONE_EACCES;
11420 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11421 		}
11422 		break;
11423 
11424 	case STATUS_BUSY:
11425 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11426 		if (rcvi->privatelen == sizeof (recov_info) &&
11427 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11428 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11429 			/*
11430 			 * Status returned by scsi_vhci indicating path
11431 			 * has failed over.
11432 			 */
11433 			action = PATH_FAILED;
11434 			break;
11435 		}
11436 		/* FALLTHRU */
11437 	case STATUS_QFULL:
11438 		if (rcvi->privatelen == sizeof (recov_info)) {
11439 			/*
11440 			 * If recovery is inabled use it instead of
11441 			 * blind reties.
11442 			 */
11443 			action = ATTEMPT_RETRY;
11444 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11445 			action = QUE_BUSY_COMMAND;
11446 		} else if ((un->un_rsvd_status &
11447 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11448 			/*
11449 			 * If this is a command done before reserve is done
11450 			 * don't reset.
11451 			 */
11452 			action = COMMAND_DONE_ERROR;
11453 		} else {
11454 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11455 			    "unit busy too long\n");
11456 			(void) st_reset(un, RESET_ALL);
11457 			action = COMMAND_DONE_ERROR;
11458 		}
11459 		break;
11460 
11461 	case STATUS_CHECK:
11462 	case STATUS_TERMINATED:
11463 		/*
11464 		 * we should only get here if the auto rqsense failed
11465 		 * thru a uscsi cmd without autorequest sense
11466 		 * so we just try again
11467 		 */
11468 		if (un->un_arq_enabled &&
11469 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11470 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11471 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11472 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11473 		    STATE_GOT_STATUS)) {
11474 
11475 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11476 			    "Really got sense data\n");
11477 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11478 			    pkt->pkt_resid, stat, &un->un_pos);
11479 		} else {
11480 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11481 			    "Trying to queue sense command\n");
11482 			action = QUE_SENSE;
11483 		}
11484 		break;
11485 
11486 	case STATUS_TASK_ABORT:
11487 		/*
11488 		 * This is an aborted task. This can be a reset on the other
11489 		 * port of a multiport drive. Lets try and recover it.
11490 		 */
11491 		action = DEVICE_RESET;
11492 		break;
11493 
11494 	default:
11495 		action = COMMAND_DONE;
11496 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11497 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11498 	}
11499 	return (action);
11500 }
11501 
11502 static void
11503 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11504 {
11505 	int nblks;
11506 	int nfiles;
11507 	long count;
11508 	recov_info *ri = pkt->pkt_private;
11509 	cmd_attribute const *attrib;
11510 
11511 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11512 
11513 	ASSERT(mutex_owned(ST_MUTEX));
11514 
11515 	if (ri->privatelen == sizeof (recov_info)) {
11516 		attrib = ri->cmd_attrib;
11517 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11518 		ASSERT(attrib->chg_tape_pos);
11519 	} else {
11520 		ri = NULL;
11521 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11522 	}
11523 
11524 	count = bp->b_bcount - bp->b_resid;
11525 
11526 	/* Command reads or writes data */
11527 	if (attrib->transfers_data != TRAN_NONE) {
11528 		if (count == 0) {
11529 			/* failed writes should not make it here */
11530 			ASSERT(attrib->transfers_data == TRAN_READ);
11531 			nblks = 0;
11532 			nfiles = 1;
11533 		} else if (un->un_bsize == 0) {
11534 			/*
11535 			 * If variable block mode.
11536 			 * Fixed bit in CBD should be zero.
11537 			 */
11538 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11539 			nblks = 1;
11540 			un->un_kbytes_xferred += (count / ONE_K);
11541 			nfiles = 0;
11542 		} else {
11543 			/*
11544 			 * If fixed block mode.
11545 			 * Fixed bit in CBD should be one.
11546 			 */
11547 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11548 			nblks = (count / un->un_bsize);
11549 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11550 			nfiles = 0;
11551 		}
11552 		/*
11553 		 * So its possable to read some blocks and hit a filemark.
11554 		 * Example reading in fixed block mode where more then one
11555 		 * block at a time is requested. In this case because the
11556 		 * filemark is hit something less then the requesed number
11557 		 * of blocks is read.
11558 		 */
11559 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11560 			nfiles = 1;
11561 		}
11562 	} else {
11563 		nblks = 0;
11564 		nfiles = count;
11565 	}
11566 
11567 	/*
11568 	 * If some command failed after this one started and it seems
11569 	 * to have finshed without error count the position.
11570 	 */
11571 	if (un->un_persistence && un->un_persist_errors) {
11572 		ASSERT(un->un_pos.pmode != invalid);
11573 	}
11574 
11575 	if (attrib->chg_tape_direction == DIR_FORW) {
11576 		un->un_pos.blkno += nblks;
11577 		un->un_pos.lgclblkno += nblks;
11578 		un->un_pos.lgclblkno += nfiles;
11579 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11580 		un->un_pos.blkno -= nblks;
11581 		un->un_pos.lgclblkno -= nblks;
11582 		un->un_pos.lgclblkno -= nfiles;
11583 	} else {
11584 		ASSERT(0);
11585 	}
11586 
11587 	/* recovery disabled */
11588 	if (ri == NULL) {
11589 		un->un_running.pmode = invalid;
11590 		return;
11591 	}
11592 
11593 	/*
11594 	 * If we didn't just read a filemark.
11595 	 */
11596 	if (un->un_pos.eof != ST_EOF_PENDING) {
11597 		ASSERT(nblks != 0 && nfiles == 0);
11598 		/*
11599 		 * If Previously calulated expected position does not match
11600 		 * debug the expected position.
11601 		 */
11602 		if ((ri->pos.pmode != invalid) && nblks &&
11603 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11604 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11605 #ifdef STDEBUG
11606 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11607 			    "Expected", &ri->pos);
11608 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11609 			    "But Got", &un->un_pos);
11610 #endif
11611 			un->un_running.pmode = invalid;
11612 		}
11613 	} else {
11614 		ASSERT(nfiles != 0);
11615 		if (un->un_running.pmode != invalid) {
11616 			/*
11617 			 * blkno and lgclblkno already counted in
11618 			 * st_add_recovery_info_to_pkt(). Since a block was not
11619 			 * read and a filemark was.
11620 			 */
11621 			if (attrib->chg_tape_direction == DIR_FORW) {
11622 				un->un_running.fileno++;
11623 				un->un_running.blkno = 0;
11624 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11625 				un->un_running.fileno--;
11626 				un->un_running.blkno = LASTBLK;
11627 			}
11628 		}
11629 	}
11630 }
11631 
11632 static void
11633 st_set_state(struct scsi_tape *un, struct buf *bp)
11634 {
11635 	struct scsi_pkt *sp = BP_PKT(bp);
11636 	struct uscsi_cmd *ucmd;
11637 
11638 	ST_FUNC(ST_DEVINFO, st_set_state);
11639 
11640 	ASSERT(mutex_owned(ST_MUTEX));
11641 	ASSERT(bp != un->un_recov_buf);
11642 
11643 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11644 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11645 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11646 
11647 	if (bp != un->un_sbufp) {
11648 #ifdef STDEBUG
11649 		if (DEBUGGING && sp->pkt_resid) {
11650 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11651 			    "pkt_resid %ld bcount %ld\n",
11652 			    sp->pkt_resid, bp->b_bcount);
11653 		}
11654 #endif
11655 		bp->b_resid = sp->pkt_resid;
11656 		if (geterror(bp) != EIO) {
11657 			st_calc_bnum(un, bp, sp);
11658 		}
11659 		if (bp->b_flags & B_READ) {
11660 			un->un_lastop = ST_OP_READ;
11661 			un->un_fmneeded = 0;
11662 		} else {
11663 			un->un_lastop = ST_OP_WRITE;
11664 			if (un->un_dp->options & ST_REEL) {
11665 				un->un_fmneeded = 2;
11666 			} else {
11667 				un->un_fmneeded = 1;
11668 			}
11669 		}
11670 		/*
11671 		 * all is honky dory at this point, so let's
11672 		 * readjust the throttle, to increase speed, if we
11673 		 * have not throttled down.
11674 		 */
11675 		if (un->un_throttle) {
11676 			un->un_throttle = un->un_max_throttle;
11677 		}
11678 	} else {
11679 		optype new_lastop = ST_OP_NIL;
11680 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11681 
11682 		switch (cmd) {
11683 		case SCMD_WRITE:
11684 		case SCMD_WRITE_G4:
11685 			bp->b_resid = sp->pkt_resid;
11686 			new_lastop = ST_OP_WRITE;
11687 			if (geterror(bp) == EIO) {
11688 				break;
11689 			}
11690 			st_calc_bnum(un, bp, sp);
11691 			if (un->un_dp->options & ST_REEL) {
11692 				un->un_fmneeded = 2;
11693 			} else {
11694 				un->un_fmneeded = 1;
11695 			}
11696 			break;
11697 		case SCMD_READ:
11698 		case SCMD_READ_G4:
11699 			bp->b_resid = sp->pkt_resid;
11700 			new_lastop = ST_OP_READ;
11701 			if (geterror(bp) == EIO) {
11702 				break;
11703 			}
11704 			st_calc_bnum(un, bp, sp);
11705 			un->un_fmneeded = 0;
11706 			break;
11707 		case SCMD_WRITE_FILE_MARK_G4:
11708 		case SCMD_WRITE_FILE_MARK:
11709 		{
11710 			int fmdone;
11711 
11712 			if (un->un_pos.eof != ST_EOM) {
11713 				un->un_pos.eof = ST_NO_EOF;
11714 			}
11715 			fmdone = (bp->b_bcount - bp->b_resid);
11716 			if (fmdone > 0) {
11717 				un->un_lastop = new_lastop = ST_OP_WEOF;
11718 				un->un_pos.lgclblkno += fmdone;
11719 				un->un_pos.fileno += fmdone;
11720 				un->un_pos.blkno = 0;
11721 			} else {
11722 				new_lastop = ST_OP_CTL;
11723 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11724 				    "Flushed buffer\n");
11725 			}
11726 			if (fmdone > un->un_fmneeded) {
11727 				un->un_fmneeded = 0;
11728 			} else {
11729 				un->un_fmneeded -= fmdone;
11730 			}
11731 			break;
11732 		}
11733 		case SCMD_REWIND:
11734 			un->un_pos.eof = ST_NO_EOF;
11735 			un->un_pos.fileno = 0;
11736 			un->un_pos.blkno = 0;
11737 			un->un_pos.lgclblkno = 0;
11738 			if (un->un_pos.pmode != legacy)
11739 				un->un_pos.pmode = legacy;
11740 			new_lastop = ST_OP_CTL;
11741 			un->un_restore_pos = 0;
11742 			break;
11743 
11744 		case SCMD_SPACE:
11745 		case SCMD_SPACE_G4:
11746 		{
11747 			int64_t count;
11748 			int64_t resid;
11749 			int64_t done;
11750 			cmd_attribute const *attrib;
11751 			recov_info *ri = sp->pkt_private;
11752 
11753 			if (ri->privatelen == sizeof (recov_info)) {
11754 				attrib = ri->cmd_attrib;
11755 			} else {
11756 				attrib =
11757 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11758 			}
11759 
11760 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11761 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11762 
11763 			if (count >= 0) {
11764 				done = (count - resid);
11765 			} else {
11766 				done = ((-count) - resid);
11767 			}
11768 			if (done > 0) {
11769 				un->un_lastop = new_lastop = ST_OP_CTL;
11770 			} else {
11771 				new_lastop = ST_OP_CTL;
11772 			}
11773 
11774 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11775 			    "space cmd: cdb[1] = %s\n"
11776 			    "space data:       = 0x%lx\n"
11777 			    "space count:      = %"PRId64"\n"
11778 			    "space resid:      = %"PRId64"\n"
11779 			    "spaces done:      = %"PRId64"\n"
11780 			    "fileno before     = %d\n"
11781 			    "blkno before      = %d\n",
11782 			    space_strs[sp->pkt_cdbp[1] & 7],
11783 			    bp->b_bcount,
11784 			    count, resid, done,
11785 			    un->un_pos.fileno, un->un_pos.blkno);
11786 
11787 			switch (sp->pkt_cdbp[1]) {
11788 			case SPACE_TYPE(SP_FLM):
11789 				/* Space file forward */
11790 				if (count >= 0) {
11791 					if (un->un_pos.eof <= ST_EOF) {
11792 						un->un_pos.eof = ST_NO_EOF;
11793 					}
11794 					un->un_pos.fileno += done;
11795 					un->un_pos.blkno = 0;
11796 					break;
11797 				}
11798 				/* Space file backward */
11799 				if (done > un->un_pos.fileno) {
11800 					un->un_pos.fileno = 0;
11801 					un->un_pos.blkno = 0;
11802 				} else {
11803 					un->un_pos.fileno -= done;
11804 					un->un_pos.blkno = LASTBLK;
11805 					un->un_running.pmode = invalid;
11806 				}
11807 				break;
11808 			case SPACE_TYPE(SP_BLK):
11809 				/* Space block forward */
11810 				if (count >= 0) {
11811 					un->un_pos.blkno += done;
11812 					break;
11813 				}
11814 				/* Space block backward */
11815 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11816 				/*
11817 				 * we stepped back into
11818 				 * a previous file; we are not
11819 				 * making an effort to pretend that
11820 				 * we are still in the current file
11821 				 * ie. logical == physical position
11822 				 * and leave it to st_ioctl to correct
11823 				 */
11824 					if (done > un->un_pos.blkno) {
11825 						un->un_pos.blkno = 0;
11826 					} else {
11827 						un->un_pos.fileno--;
11828 						un->un_pos.blkno = LASTBLK;
11829 						un->un_running.pmode = invalid;
11830 					}
11831 				} else {
11832 					un->un_pos.blkno -= done;
11833 				}
11834 				break;
11835 			case SPACE_TYPE(SP_SQFLM):
11836 				un->un_pos.pmode = logical;
11837 				un->un_pos.blkno = 0;
11838 				un->un_lastop = new_lastop = ST_OP_CTL;
11839 				break;
11840 			case SPACE_TYPE(SP_EOD):
11841 				un->un_pos.pmode = logical;
11842 				un->un_pos.eof = ST_EOM;
11843 				un->un_status = KEY_BLANK_CHECK;
11844 				break;
11845 			default:
11846 				un->un_pos.pmode = invalid;
11847 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11848 				    "Unsupported space cmd: %s\n",
11849 				    space_strs[sp->pkt_cdbp[1] & 7]);
11850 
11851 				un->un_lastop = new_lastop = ST_OP_CTL;
11852 			}
11853 
11854 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11855 			    "after_space rs %"PRId64" fil %d blk %d\n",
11856 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11857 
11858 			break;
11859 		}
11860 		case SCMD_LOAD:
11861 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11862 				un->un_pos.fileno = 0;
11863 				if (un->un_pos.pmode != legacy)
11864 					un->un_pos.pmode = legacy;
11865 			} else {
11866 				un->un_state = ST_STATE_OFFLINE;
11867 				un->un_pos.pmode = invalid;
11868 
11869 			}
11870 			/*
11871 			 * If we are loading or unloading we expect the media id
11872 			 * to change. Lets make it unknown.
11873 			 */
11874 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11875 				kmem_free(un->un_media_id, un->un_media_id_len);
11876 				un->un_media_id = NULL;
11877 				un->un_media_id_len = 0;
11878 			}
11879 			un->un_density_known = 0;
11880 			un->un_pos.eof = ST_NO_EOF;
11881 			un->un_pos.blkno = 0;
11882 			un->un_lastop = new_lastop = ST_OP_CTL;
11883 			break;
11884 		case SCMD_ERASE:
11885 			un->un_pos.eof = ST_NO_EOF;
11886 			un->un_pos.blkno = 0;
11887 			un->un_pos.fileno = 0;
11888 			un->un_pos.lgclblkno = 0;
11889 			if (un->un_pos.pmode != legacy)
11890 				un->un_pos.pmode = legacy;
11891 			new_lastop = ST_OP_CTL;
11892 			break;
11893 		case SCMD_RESERVE:
11894 			un->un_rsvd_status |= ST_RESERVE;
11895 			un->un_rsvd_status &=
11896 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11897 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11898 			new_lastop = ST_OP_CTL;
11899 			break;
11900 		case SCMD_RELEASE:
11901 			un->un_rsvd_status |= ST_RELEASE;
11902 			un->un_rsvd_status &=
11903 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11904 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11905 			new_lastop = ST_OP_CTL;
11906 			break;
11907 		case SCMD_PERSISTENT_RESERVE_IN:
11908 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11909 			    "PGR_IN command\n");
11910 			new_lastop = ST_OP_CTL;
11911 			break;
11912 		case SCMD_PERSISTENT_RESERVE_OUT:
11913 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11914 			case ST_SA_SCSI3_RESERVE:
11915 			case ST_SA_SCSI3_PREEMPT:
11916 			case ST_SA_SCSI3_PREEMPTANDABORT:
11917 				un->un_rsvd_status |=
11918 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11919 				un->un_rsvd_status &= ~(ST_RELEASE |
11920 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11921 				    ST_INITIATED_RESET);
11922 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11923 				    "PGR Reserve and set: entering"
11924 				    " ST_APPLICATION_RESERVATIONS mode");
11925 				break;
11926 			case ST_SA_SCSI3_REGISTER:
11927 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11928 				    "PGR Reserve register key");
11929 				un->un_rsvd_status |= ST_INIT_RESERVE;
11930 				break;
11931 			case ST_SA_SCSI3_CLEAR:
11932 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11933 				/* FALLTHROUGH */
11934 			case ST_SA_SCSI3_RELEASE:
11935 				un->un_rsvd_status &=
11936 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11937 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11938 				    ST_INITIATED_RESET);
11939 				un->un_rsvd_status |= ST_RELEASE;
11940 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11941 				    "PGR Release and reset: exiting"
11942 				    " ST_APPLICATION_RESERVATIONS mode");
11943 				break;
11944 			}
11945 			new_lastop = ST_OP_CTL;
11946 			break;
11947 		case SCMD_TEST_UNIT_READY:
11948 		case SCMD_READ_BLKLIM:
11949 		case SCMD_REQUEST_SENSE:
11950 		case SCMD_INQUIRY:
11951 		case SCMD_RECOVER_BUF:
11952 		case SCMD_MODE_SELECT:
11953 		case SCMD_MODE_SENSE:
11954 		case SCMD_DOORLOCK:
11955 		case SCMD_READ_BUFFER:
11956 		case SCMD_REPORT_DENSITIES:
11957 		case SCMD_LOG_SELECT_G1:
11958 		case SCMD_LOG_SENSE_G1:
11959 		case SCMD_REPORT_LUNS:
11960 		case SCMD_READ_ATTRIBUTE:
11961 		case SCMD_WRITE_ATTRIBUTE:
11962 		case SCMD_SVC_ACTION_IN_G5:
11963 			new_lastop = ST_OP_CTL;
11964 			break;
11965 		case SCMD_READ_POSITION:
11966 			new_lastop = ST_OP_CTL;
11967 			/*
11968 			 * Only if the buf used was un_sbufp.
11969 			 * Among other things the prevents read positions used
11970 			 * as part of error recovery from messing up our
11971 			 * current position as they will use un_recov_buf.
11972 			 */
11973 			if (USCSI_CMD(bp)) {
11974 				(void) st_get_read_pos(un, bp);
11975 			}
11976 			break;
11977 		case SCMD_LOCATE:
11978 		case SCMD_LOCATE_G4:
11979 			/* Locate makes position mode no longer legacy */
11980 			un->un_lastop = new_lastop = ST_OP_CTL;
11981 			break;
11982 		case SCMD_MAINTENANCE_IN:
11983 			switch (sp->pkt_cdbp[1]) {
11984 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
11985 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
11986 				new_lastop = ST_OP_CTL;
11987 				break;
11988 			}
11989 			if (new_lastop != ST_OP_NIL) {
11990 				break;
11991 			}
11992 		default:
11993 			/*
11994 			 * Unknown command, If was USCSI and USCSI_SILENT
11995 			 * flag was not set, set position to unknown.
11996 			 */
11997 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11998 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11999 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
12000 				    "unknown cmd 0x%X caused loss of state\n",
12001 				    cmd);
12002 			} else {
12003 				/*
12004 				 * keep the old agreement to allow unknown
12005 				 * commands with the USCSI_SILENT set.
12006 				 * This prevents ASSERT below.
12007 				 */
12008 				new_lastop = ST_OP_CTL;
12009 				break;
12010 			}
12011 			/* FALLTHROUGH */
12012 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
12013 			un->un_pos.pmode = invalid;
12014 			un->un_lastop = new_lastop = ST_OP_CTL;
12015 			break;
12016 		}
12017 
12018 		/* new_lastop should have been changed */
12019 		ASSERT(new_lastop != ST_OP_NIL);
12020 
12021 		/* If un_lastop should copy new_lastop  */
12022 		if (((un->un_lastop == ST_OP_WRITE) ||
12023 		    (un->un_lastop == ST_OP_WEOF)) &&
12024 		    new_lastop != ST_OP_CTL) {
12025 			un->un_lastop = new_lastop;
12026 		}
12027 	}
12028 
12029 	/*
12030 	 * In the st driver we have a logical and physical file position.
12031 	 * Under BSD behavior, when you get a zero read, the logical position
12032 	 * is before the filemark but after the last record of the file.
12033 	 * The physical position is after the filemark. MTIOCGET should always
12034 	 * return the logical file position.
12035 	 *
12036 	 * The next read gives a silent skip to the next file.
12037 	 * Under SVR4, the logical file position remains before the filemark
12038 	 * until the file is closed or a space operation is performed.
12039 	 * Hence set err_resid and err_file before changing fileno if case
12040 	 * BSD Behaviour.
12041 	 */
12042 	un->un_err_resid = bp->b_resid;
12043 	COPY_POS(&un->un_err_pos, &un->un_pos);
12044 
12045 
12046 	/*
12047 	 * If we've seen a filemark via the last read operation
12048 	 * advance the file counter, but mark things such that
12049 	 * the next read operation gets a zero count. We have
12050 	 * to put this here to handle the case of sitting right
12051 	 * at the end of a tape file having seen the file mark,
12052 	 * but the tape is closed and then re-opened without
12053 	 * any further i/o. That is, the position information
12054 	 * must be updated before a close.
12055 	 */
12056 
12057 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
12058 		/*
12059 		 * If we're a 1/2" tape, and we get a filemark
12060 		 * right on block 0, *AND* we were not in the
12061 		 * first file on the tape, and we've hit logical EOM.
12062 		 * We'll mark the state so that later we do the
12063 		 * right thing (in st_close(), st_strategy() or
12064 		 * st_ioctl()).
12065 		 *
12066 		 */
12067 		if ((un->un_dp->options & ST_REEL) &&
12068 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
12069 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
12070 			un->un_pos.eof = ST_EOT_PENDING;
12071 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12072 			    "eot pending\n");
12073 			un->un_pos.fileno++;
12074 			un->un_pos.blkno = 0;
12075 		} else if (BSD_BEHAVIOR) {
12076 			/*
12077 			 * If the read of the filemark was a side effect
12078 			 * of reading some blocks (i.e., data was actually
12079 			 * read), then the EOF mark is pending and the
12080 			 * bump into the next file awaits the next read
12081 			 * operation (which will return a zero count), or
12082 			 * a close or a space operation, else the bump
12083 			 * into the next file occurs now.
12084 			 */
12085 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12086 			    "resid=%lx, bcount=%lx\n",
12087 			    bp->b_resid, bp->b_bcount);
12088 
12089 			if (bp->b_resid != bp->b_bcount) {
12090 				un->un_pos.eof = ST_EOF;
12091 			} else {
12092 				un->un_silent_skip = 1;
12093 				un->un_pos.eof = ST_NO_EOF;
12094 				un->un_pos.fileno++;
12095 				un->un_pos.lgclblkno++;
12096 				un->un_save_blkno = un->un_pos.blkno;
12097 				un->un_pos.blkno = 0;
12098 			}
12099 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12100 			    "eof of file %d, eof=%d\n",
12101 			    un->un_pos.fileno, un->un_pos.eof);
12102 		} else if (SVR4_BEHAVIOR) {
12103 			/*
12104 			 * If the read of the filemark was a side effect
12105 			 * of reading some blocks (i.e., data was actually
12106 			 * read), then the next read should return 0
12107 			 */
12108 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12109 			    "resid=%lx, bcount=%lx\n",
12110 			    bp->b_resid, bp->b_bcount);
12111 			if (bp->b_resid == bp->b_bcount) {
12112 				un->un_pos.eof = ST_EOF;
12113 			}
12114 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12115 			    "eof of file=%d, eof=%d\n",
12116 			    un->un_pos.fileno, un->un_pos.eof);
12117 		}
12118 	}
12119 }
12120 
12121 /*
12122  * set the correct un_errno, to take corner cases into consideration
12123  */
12124 static void
12125 st_set_pe_errno(struct scsi_tape *un)
12126 {
12127 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12128 
12129 	ASSERT(mutex_owned(ST_MUTEX));
12130 
12131 	/* if errno is already set, don't reset it */
12132 	if (un->un_errno)
12133 		return;
12134 
12135 	/* here un_errno == 0 */
12136 	/*
12137 	 * if the last transfer before flushing all the
12138 	 * waiting I/O's, was 0 (resid = count), then we
12139 	 * want to give the user an error on all the rest,
12140 	 * so here.  If there was a transfer, we set the
12141 	 * resid and counts to 0, and let it drop through,
12142 	 * giving a zero return.  the next I/O will then
12143 	 * give an error.
12144 	 */
12145 	if (un->un_last_resid == un->un_last_count) {
12146 		switch (un->un_pos.eof) {
12147 		case ST_EOM:
12148 			un->un_errno = ENOMEM;
12149 			break;
12150 		case ST_EOT:
12151 		case ST_EOF:
12152 			un->un_errno = EIO;
12153 			break;
12154 		}
12155 	} else {
12156 		/*
12157 		 * we know they did not have a zero, so make
12158 		 * sure they get one
12159 		 */
12160 		un->un_last_resid = un->un_last_count = 0;
12161 	}
12162 }
12163 
12164 
12165 /*
12166  * send in a marker pkt to terminate flushing of commands by BBA (via
12167  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12168  */
12169 static void
12170 st_hba_unflush(struct scsi_tape *un)
12171 {
12172 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12173 
12174 	ASSERT(mutex_owned(ST_MUTEX));
12175 
12176 	if (!un->un_flush_on_errors)
12177 		return;
12178 
12179 #ifdef FLUSH_ON_ERRORS
12180 
12181 	if (!un->un_mkr_pkt) {
12182 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12183 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12184 
12185 		/* we slept, so it must be there */
12186 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12187 	}
12188 
12189 	st_transport(un, un->un_mkr_pkt);
12190 #endif
12191 }
12192 
12193 static char *
12194 st_print_scsi_cmd(char cmd)
12195 {
12196 	char tmp[64];
12197 	char *cpnt;
12198 
12199 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12200 	/* tmp goes out of scope on return and caller sees garbage */
12201 	if (cpnt == tmp) {
12202 		cpnt = "Unknown Command";
12203 	}
12204 	return (cpnt);
12205 }
12206 
12207 static void
12208 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12209     char *title, char *cdb)
12210 {
12211 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12212 	char buf[256];
12213 	struct scsi_tape *un;
12214 	int instance = ddi_get_instance(dip);
12215 
12216 	un = ddi_get_soft_state(st_state, instance);
12217 
12218 	ST_FUNC(dip, st_print_cdb);
12219 
12220 	/* force one line output so repeated commands are printed once */
12221 	if ((st_debug & 0x180) == 0x100) {
12222 		scsi_log(dip, label, level, "node %s cmd %s\n",
12223 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12224 		return;
12225 	}
12226 
12227 	/* force one line output so repeated CDB's are printed once */
12228 	if ((st_debug & 0x180) == 0x80) {
12229 		st_clean_print(dip, label, level, NULL, cdb, len);
12230 	} else {
12231 		(void) sprintf(buf, "%s for cmd(%s)", title,
12232 		    st_print_scsi_cmd(*cdb));
12233 		st_clean_print(dip, label, level, buf, cdb, len);
12234 	}
12235 }
12236 
12237 static void
12238 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12239     char *title, char *data, int len)
12240 {
12241 	int	i;
12242 	int 	c;
12243 	char	*format;
12244 	char	buf[256];
12245 	uchar_t	byte;
12246 
12247 	ST_FUNC(dev, st_clean_print);
12248 
12249 
12250 	if (title) {
12251 		(void) sprintf(buf, "%s:\n", title);
12252 		scsi_log(dev, label, level, "%s", buf);
12253 		level = CE_CONT;
12254 	}
12255 
12256 	for (i = 0; i < len; ) {
12257 		buf[0] = 0;
12258 		for (c = 0; c < 8 && i < len; c++, i++) {
12259 			byte = (uchar_t)data[i];
12260 			if (byte < 0x10)
12261 				format = "0x0%x ";
12262 			else
12263 				format = "0x%x ";
12264 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12265 		}
12266 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12267 
12268 		scsi_log(dev, label, level, "%s\n", buf);
12269 		level = CE_CONT;
12270 	}
12271 }
12272 
12273 /*
12274  * Conditionally enabled debugging
12275  */
12276 #ifdef	STDEBUG
12277 static void
12278 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12279 {
12280 	char tmpbuf[64];
12281 
12282 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12283 
12284 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12285 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12286 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12287 	    count, count,
12288 	    wait == ASYNC_CMD ? "a" : "");
12289 }
12290 #endif	/* STDEBUG */
12291 
12292 /*
12293  * Returns pointer to name of minor node name of device 'dev'.
12294  */
12295 static char *
12296 st_dev_name(dev_t dev)
12297 {
12298 	struct scsi_tape *un;
12299 	const char density[] = { 'l', 'm', 'h', 'c' };
12300 	static char name[32];
12301 	minor_t minor;
12302 	int instance;
12303 	int nprt = 0;
12304 
12305 	minor = getminor(dev);
12306 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12307 	un = ddi_get_soft_state(st_state, instance);
12308 	if (un) {
12309 		ST_FUNC(ST_DEVINFO, st_dev_name);
12310 	}
12311 
12312 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12313 
12314 	if (minor & MT_BSD) {
12315 		name[++nprt] = 'b';
12316 	}
12317 
12318 	if (minor & MT_NOREWIND) {
12319 		name[++nprt] = 'n';
12320 	}
12321 
12322 	/* NULL terminator */
12323 	name[++nprt] = 0;
12324 
12325 	return (name);
12326 }
12327 
12328 /*
12329  * Soft error reporting, so far unique to each drive
12330  *
12331  * Currently supported: exabyte and DAT soft error reporting
12332  */
12333 static int
12334 st_report_exabyte_soft_errors(dev_t dev, int flag)
12335 {
12336 	uchar_t *sensep;
12337 	int amt;
12338 	int rval = 0;
12339 	char cdb[CDB_GROUP0], *c = cdb;
12340 	struct uscsi_cmd *com;
12341 
12342 	GET_SOFT_STATE(dev);
12343 
12344 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12345 
12346 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12347 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12348 	    dev, flag);
12349 
12350 	ASSERT(mutex_owned(ST_MUTEX));
12351 
12352 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12353 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12354 
12355 	*c++ = SCMD_REQUEST_SENSE;
12356 	*c++ = 0;
12357 	*c++ = 0;
12358 	*c++ = 0;
12359 	*c++ = TAPE_SENSE_LENGTH;
12360 	/*
12361 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12362 	 */
12363 	*c   = (char)0x80;
12364 
12365 	com->uscsi_cdb = cdb;
12366 	com->uscsi_cdblen = CDB_GROUP0;
12367 	com->uscsi_bufaddr = (caddr_t)sensep;
12368 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12369 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12370 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12371 
12372 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12373 	if (rval || com->uscsi_status) {
12374 		goto done;
12375 	}
12376 
12377 	/*
12378 	 * was there enough data?
12379 	 */
12380 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12381 
12382 	if ((amt >= 19) && un->un_kbytes_xferred) {
12383 		uint_t count, error_rate;
12384 		uint_t rate;
12385 
12386 		if (sensep[21] & CLN) {
12387 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12388 			    "Periodic head cleaning required");
12389 		}
12390 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12391 			goto done;
12392 		}
12393 		/*
12394 		 * check if soft error reporting needs to be done.
12395 		 */
12396 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12397 		count &= 0xffffff;
12398 		error_rate = (count * 100)/un->un_kbytes_xferred;
12399 
12400 #ifdef	STDEBUG
12401 		if (st_soft_error_report_debug) {
12402 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12403 			    "Exabyte Soft Error Report:\n");
12404 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12405 			    "read/write error counter: %d\n", count);
12406 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12407 			    "number of bytes transferred: %dK\n",
12408 			    un->un_kbytes_xferred);
12409 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12410 			    "error_rate: %d%%\n", error_rate);
12411 
12412 			if (amt >= 22) {
12413 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12414 				    "unit sense: 0x%b 0x%b 0x%b\n",
12415 				    sensep[19], SENSE_19_BITS,
12416 				    sensep[20], SENSE_20_BITS,
12417 				    sensep[21], SENSE_21_BITS);
12418 			}
12419 			if (amt >= 27) {
12420 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12421 				    "tracking retry counter: %d\n",
12422 				    sensep[26]);
12423 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12424 				    "read/write retry counter: %d\n",
12425 				    sensep[27]);
12426 			}
12427 		}
12428 #endif
12429 
12430 		if (flag & FWRITE) {
12431 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12432 		} else {
12433 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12434 		}
12435 		if (error_rate >= rate) {
12436 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12437 			    "Soft error rate (%d%%) during %s was too high",
12438 			    error_rate,
12439 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12440 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12441 			    "Please, replace tape cartridge\n");
12442 		}
12443 	}
12444 
12445 done:
12446 	kmem_free(com, sizeof (*com));
12447 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12448 
12449 	if (rval != 0) {
12450 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12451 		    "exabyte soft error reporting failed\n");
12452 	}
12453 	return (rval);
12454 }
12455 
12456 /*
12457  * this is very specific to Archive 4mm dat
12458  */
12459 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12460 
12461 static int
12462 st_report_dat_soft_errors(dev_t dev, int flag)
12463 {
12464 	uchar_t *sensep;
12465 	int amt, i;
12466 	int rval = 0;
12467 	char cdb[CDB_GROUP1], *c = cdb;
12468 	struct uscsi_cmd *com;
12469 	struct scsi_arq_status status;
12470 
12471 	GET_SOFT_STATE(dev);
12472 
12473 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12474 
12475 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12476 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12477 
12478 	ASSERT(mutex_owned(ST_MUTEX));
12479 
12480 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12481 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12482 
12483 	*c++ = SCMD_LOG_SENSE_G1;
12484 	*c++ = 0;
12485 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12486 	*c++ = 0;
12487 	*c++ = 0;
12488 	*c++ = 0;
12489 	*c++ = 2;
12490 	*c++ = 0;
12491 	*c++ = (char)LOG_SENSE_LENGTH;
12492 	*c   = 0;
12493 	com->uscsi_cdb    = cdb;
12494 	com->uscsi_cdblen  = CDB_GROUP1;
12495 	com->uscsi_bufaddr = (caddr_t)sensep;
12496 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12497 	com->uscsi_rqlen = sizeof (status);
12498 	com->uscsi_rqbuf = (caddr_t)&status;
12499 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12500 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12501 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12502 	if (rval) {
12503 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12504 		    "DAT soft error reporting failed\n");
12505 	}
12506 	if (rval || com->uscsi_status) {
12507 		goto done;
12508 	}
12509 
12510 	/*
12511 	 * was there enough data?
12512 	 */
12513 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12514 
12515 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12516 		int total, retries, param_code;
12517 
12518 		total = -1;
12519 		retries = -1;
12520 		amt = sensep[3] + 4;
12521 
12522 
12523 #ifdef STDEBUG
12524 		if (st_soft_error_report_debug) {
12525 			(void) printf("logsense:");
12526 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12527 				if (i % 16 == 0) {
12528 					(void) printf("\t\n");
12529 				}
12530 				(void) printf(" %x", sensep[i]);
12531 			}
12532 			(void) printf("\n");
12533 		}
12534 #endif
12535 
12536 		/*
12537 		 * parse the param_codes
12538 		 */
12539 		if (sensep[0] == 2 || sensep[0] == 3) {
12540 			for (i = 4; i < amt; i++) {
12541 				param_code = (sensep[i++] << 8);
12542 				param_code += sensep[i++];
12543 				i++; /* skip control byte */
12544 				if (param_code == 5) {
12545 					if (sensep[i++] == 4) {
12546 						total = (sensep[i++] << 24);
12547 						total += (sensep[i++] << 16);
12548 						total += (sensep[i++] << 8);
12549 						total += sensep[i];
12550 					}
12551 				} else if (param_code == 0x8007) {
12552 					if (sensep[i++] == 2) {
12553 						retries = sensep[i++] << 8;
12554 						retries += sensep[i];
12555 					}
12556 				} else {
12557 					i += sensep[i];
12558 				}
12559 			}
12560 		}
12561 
12562 		/*
12563 		 * if the log sense returned valid numbers then determine
12564 		 * the read and write error thresholds based on the amount of
12565 		 * data transferred
12566 		 */
12567 
12568 		if (total > 0 && retries > 0) {
12569 			short normal_retries = 0;
12570 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12571 			    "total xferred (%s) =%x, retries=%x\n",
12572 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12573 			    total, retries);
12574 
12575 			if (flag & FWRITE) {
12576 				if (total <=
12577 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12578 					normal_retries =
12579 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12580 				} else {
12581 					normal_retries =
12582 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12583 				}
12584 			} else {
12585 				if (total <=
12586 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12587 					normal_retries =
12588 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12589 				} else {
12590 					normal_retries =
12591 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12592 				}
12593 			}
12594 
12595 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12596 			"normal retries=%d\n", normal_retries);
12597 
12598 			if (retries >= normal_retries) {
12599 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12600 				    "Soft error rate (retries = %d) during "
12601 				    "%s was too high",  retries,
12602 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12603 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12604 				    "Periodic head cleaning required "
12605 				    "and/or replace tape cartridge\n");
12606 			}
12607 
12608 		} else if (total == -1 || retries == -1) {
12609 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12610 			    "log sense parameter code does not make sense\n");
12611 		}
12612 	}
12613 
12614 	/*
12615 	 * reset all values
12616 	 */
12617 	c = cdb;
12618 	*c++ = SCMD_LOG_SELECT_G1;
12619 	*c++ = 2;	/* this resets all values */
12620 	*c++ = (char)0xc0;
12621 	*c++ = 0;
12622 	*c++ = 0;
12623 	*c++ = 0;
12624 	*c++ = 0;
12625 	*c++ = 0;
12626 	*c++ = 0;
12627 	*c   = 0;
12628 	com->uscsi_bufaddr = NULL;
12629 	com->uscsi_buflen  = 0;
12630 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12631 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12632 	if (rval) {
12633 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12634 		    "DAT soft error reset failed\n");
12635 	}
12636 done:
12637 	kmem_free(com, sizeof (*com));
12638 	kmem_free(sensep, LOG_SENSE_LENGTH);
12639 	return (rval);
12640 }
12641 
12642 static int
12643 st_report_soft_errors(dev_t dev, int flag)
12644 {
12645 	GET_SOFT_STATE(dev);
12646 
12647 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12648 
12649 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12650 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12651 
12652 	ASSERT(mutex_owned(ST_MUTEX));
12653 
12654 	switch (un->un_dp->type) {
12655 	case ST_TYPE_EXB8500:
12656 	case ST_TYPE_EXABYTE:
12657 		return (st_report_exabyte_soft_errors(dev, flag));
12658 		/*NOTREACHED*/
12659 	case ST_TYPE_PYTHON:
12660 		return (st_report_dat_soft_errors(dev, flag));
12661 		/*NOTREACHED*/
12662 	default:
12663 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12664 		return (-1);
12665 	}
12666 }
12667 
12668 /*
12669  * persistent error routines
12670  */
12671 
12672 /*
12673  * enable persistent errors, and set the throttle appropriately, checking
12674  * for flush-on-errors capability
12675  */
12676 static void
12677 st_turn_pe_on(struct scsi_tape *un)
12678 {
12679 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12680 
12681 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12682 	ASSERT(mutex_owned(ST_MUTEX));
12683 
12684 	un->un_persistence = 1;
12685 
12686 	/*
12687 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12688 	 * enabled.  This will simplify the error handling for request senses
12689 	 */
12690 
12691 	if (un->un_arq_enabled && un->un_untagged_qing) {
12692 		uchar_t f_o_e;
12693 
12694 		mutex_exit(ST_MUTEX);
12695 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12696 		    1 : 0;
12697 		mutex_enter(ST_MUTEX);
12698 
12699 		un->un_flush_on_errors = f_o_e;
12700 	} else {
12701 		un->un_flush_on_errors = 0;
12702 	}
12703 
12704 	if (un->un_flush_on_errors)
12705 		un->un_max_throttle = (uchar_t)st_max_throttle;
12706 	else
12707 		un->un_max_throttle = 1;
12708 
12709 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12710 		un->un_max_throttle = 1;
12711 
12712 	/* this will send a marker pkt */
12713 	st_clear_pe(un);
12714 }
12715 
12716 /*
12717  * This turns persistent errors permanently off
12718  */
12719 static void
12720 st_turn_pe_off(struct scsi_tape *un)
12721 {
12722 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12723 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12724 	ASSERT(mutex_owned(ST_MUTEX));
12725 
12726 	/* turn it off for good */
12727 	un->un_persistence = 0;
12728 
12729 	/* this will send a marker pkt */
12730 	st_clear_pe(un);
12731 
12732 	/* turn off flush on error capability, if enabled */
12733 	if (un->un_flush_on_errors) {
12734 		mutex_exit(ST_MUTEX);
12735 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12736 		mutex_enter(ST_MUTEX);
12737 	}
12738 
12739 
12740 	un->un_flush_on_errors = 0;
12741 }
12742 
12743 /*
12744  * This clear persistent errors, allowing more commands through, and also
12745  * sending a marker packet.
12746  */
12747 static void
12748 st_clear_pe(struct scsi_tape *un)
12749 {
12750 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12751 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12752 	ASSERT(mutex_owned(ST_MUTEX));
12753 
12754 	un->un_persist_errors = 0;
12755 	un->un_throttle = un->un_last_throttle = 1;
12756 	un->un_errno = 0;
12757 	st_hba_unflush(un);
12758 }
12759 
12760 /*
12761  * This will flag persistent errors, shutting everything down, if the
12762  * application had enabled persistent errors via MTIOCPERSISTENT
12763  */
12764 static void
12765 st_set_pe_flag(struct scsi_tape *un)
12766 {
12767 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12768 	ASSERT(mutex_owned(ST_MUTEX));
12769 
12770 	if (un->un_persistence) {
12771 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12772 		un->un_persist_errors = 1;
12773 		un->un_throttle = un->un_last_throttle = 0;
12774 		cv_broadcast(&un->un_sbuf_cv);
12775 	}
12776 }
12777 
12778 static int
12779 st_do_reserve(struct scsi_tape *un)
12780 {
12781 	int rval;
12782 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12783 
12784 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12785 
12786 	/*
12787 	 * Issue a Throw-Away reserve command to clear the
12788 	 * check condition.
12789 	 * If the current behaviour of reserve/release is to
12790 	 * hold reservation across opens , and if a Bus reset
12791 	 * has been issued between opens then this command
12792 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12793 	 * In this case return an EACCES so that user knows that
12794 	 * reservation has been lost in between opens.
12795 	 * If this error is not returned and we continue with
12796 	 * successful open , then user may think position of the
12797 	 * tape is still the same but inreality we would rewind the
12798 	 * tape and continue from BOT.
12799 	 */
12800 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12801 	if (rval) {
12802 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12803 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12804 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12805 			un->un_errno = EACCES;
12806 			return (EACCES);
12807 		}
12808 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12809 	}
12810 	if (rval == 0) {
12811 		un->un_rsvd_status |= ST_INIT_RESERVE;
12812 	}
12813 	if (was_lost) {
12814 		un->un_running.pmode = invalid;
12815 	}
12816 
12817 	return (rval);
12818 }
12819 
12820 static int
12821 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12822 {
12823 	int rval;
12824 	cmd_attribute const *attrib;
12825 
12826 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12827 
12828 	/*
12829 	 * If already reserved no need to do it again.
12830 	 * Also if Reserve and Release are disabled Just return.
12831 	 */
12832 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12833 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12834 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12835 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12836 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12837 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12838 		return (0);
12839 	}
12840 
12841 	/* See if command is on the list */
12842 	attrib = st_lookup_cmd_attribute(cdb[0]);
12843 
12844 	if (attrib == NULL) {
12845 		rval = 1; /* Not found, when in doubt reserve */
12846 	} else if ((attrib->requires_reserve) != 0) {
12847 		rval = 1;
12848 	} else if ((attrib->reserve_byte) != 0) {
12849 		/*
12850 		 * cmd is on list.
12851 		 * if byte is zero always allowed.
12852 		 */
12853 		rval = 1;
12854 	} else if (((cdb[attrib->reserve_byte]) &
12855 	    (attrib->reserve_mask)) != 0) {
12856 		rval = 1;
12857 	} else {
12858 		rval = 0;
12859 	}
12860 
12861 	if (rval) {
12862 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12863 		    "Command %s requires reservation",
12864 		    st_print_scsi_cmd(cdb[0]));
12865 
12866 		rval = st_do_reserve(un);
12867 	}
12868 
12869 	return (rval);
12870 }
12871 
12872 static int
12873 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12874 {
12875 	int rval;
12876 	cmd_attribute const *attrib;
12877 
12878 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12879 
12880 	/*
12881 	 * Do not reserve when already reserved, when not supported or when
12882 	 * auto-rewinding on device closure.
12883 	 */
12884 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12885 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12886 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE) ||
12887 	    ((un->un_state == ST_STATE_CLOSING) && (cmd == SCMD_REWIND))) {
12888 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12889 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12890 		    st_print_scsi_cmd(cmd));
12891 		return (0);
12892 	}
12893 
12894 	/* search for this command on the list */
12895 	attrib = st_lookup_cmd_attribute(cmd);
12896 
12897 	if (attrib == NULL) {
12898 		rval = 1; /* Not found, when in doubt reserve */
12899 	} else if ((attrib->requires_reserve) != 0) {
12900 		rval = 1;
12901 	} else if ((attrib->reserve_byte) != 0) {
12902 		/*
12903 		 * cmd is on list.
12904 		 * if byte is zero always allowed.
12905 		 */
12906 		rval = 1;
12907 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12908 		rval = 1;
12909 	} else {
12910 		rval = 0;
12911 	}
12912 
12913 	if (rval) {
12914 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12915 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12916 
12917 		rval = st_do_reserve(un);
12918 	}
12919 
12920 	return (rval);
12921 }
12922 
12923 static int
12924 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12925 {
12926 	struct uscsi_cmd	uscsi_cmd;
12927 	int			rval;
12928 	char			cdb[CDB_GROUP0];
12929 	struct scsi_arq_status	stat;
12930 
12931 
12932 
12933 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12934 
12935 	ASSERT(mutex_owned(ST_MUTEX));
12936 
12937 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12938 	    "st_reserve_release: %s \n",
12939 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12940 
12941 	bzero(&cdb, CDB_GROUP0);
12942 	if (cmd == ST_RELEASE) {
12943 		cdb[0] = SCMD_RELEASE;
12944 	} else {
12945 		cdb[0] = SCMD_RESERVE;
12946 	}
12947 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12948 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12949 	uscsi_cmd.uscsi_cdb = cdb;
12950 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12951 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12952 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12953 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12954 
12955 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12956 
12957 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12958 	    "st_reserve_release: rval(1)=%d\n", rval);
12959 
12960 	if (rval) {
12961 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12962 			rval = EACCES;
12963 		}
12964 		/*
12965 		 * dynamically turn off reserve/release support
12966 		 * in case of drives which do not support
12967 		 * reserve/release command(ATAPI drives).
12968 		 */
12969 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12970 			if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
12971 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12972 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12973 				    "Tape unit does not support "
12974 				    "reserve/release \n");
12975 			}
12976 			rval = 0;
12977 		}
12978 	}
12979 	return (rval);
12980 }
12981 
12982 static int
12983 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
12984 {
12985 	int rval;
12986 
12987 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12988 
12989 	ASSERT(mutex_owned(ST_MUTEX));
12990 
12991 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12992 	    "st_take_ownership: Entering ...\n");
12993 
12994 
12995 	rval = st_reserve_release(un, ST_RESERVE, ubf);
12996 	/*
12997 	 * XXX -> Should reset be done only if we get EACCES.
12998 	 * .
12999 	 */
13000 	if (rval) {
13001 		if (st_reset(un, RESET_LUN) == 0) {
13002 			return (EIO);
13003 		}
13004 		un->un_rsvd_status &=
13005 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
13006 
13007 		mutex_exit(ST_MUTEX);
13008 		delay(drv_usectohz(ST_RESERVATION_DELAY));
13009 		mutex_enter(ST_MUTEX);
13010 		/*
13011 		 * remove the check condition.
13012 		 */
13013 		(void) st_reserve_release(un, ST_RESERVE, ubf);
13014 		rval = st_reserve_release(un, ST_RESERVE, ubf);
13015 		if (rval != 0) {
13016 			if ((st_reserve_release(un, ST_RESERVE, ubf))
13017 			    != 0) {
13018 				rval = (un->un_rsvd_status &
13019 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
13020 				return (rval);
13021 			}
13022 		}
13023 		/*
13024 		 * Set tape state to ST_STATE_OFFLINE , in case if
13025 		 * the user wants to continue and start using
13026 		 * the tape.
13027 		 */
13028 		un->un_state = ST_STATE_OFFLINE;
13029 		un->un_rsvd_status |= ST_INIT_RESERVE;
13030 	}
13031 	return (rval);
13032 }
13033 
13034 static int
13035 st_create_errstats(struct scsi_tape *un, int instance)
13036 {
13037 	char	kstatname[KSTAT_STRLEN];
13038 
13039 	ST_FUNC(ST_DEVINFO, st_create_errstats);
13040 
13041 	/*
13042 	 * Create device error kstats
13043 	 */
13044 
13045 	if (un->un_errstats == (kstat_t *)0) {
13046 		(void) sprintf(kstatname, "st%d,err", instance);
13047 		un->un_errstats = kstat_create("sterr", instance, kstatname,
13048 		    "device_error", KSTAT_TYPE_NAMED,
13049 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
13050 		    KSTAT_FLAG_PERSISTENT);
13051 
13052 		if (un->un_errstats) {
13053 			struct st_errstats	*stp;
13054 
13055 			stp = (struct st_errstats *)un->un_errstats->ks_data;
13056 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
13057 			    KSTAT_DATA_ULONG);
13058 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
13059 			    KSTAT_DATA_ULONG);
13060 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
13061 			    KSTAT_DATA_ULONG);
13062 			kstat_named_init(&stp->st_vid, "Vendor",
13063 			    KSTAT_DATA_CHAR);
13064 			kstat_named_init(&stp->st_pid, "Product",
13065 			    KSTAT_DATA_CHAR);
13066 			kstat_named_init(&stp->st_revision, "Revision",
13067 			    KSTAT_DATA_CHAR);
13068 			kstat_named_init(&stp->st_serial, "Serial No",
13069 			    KSTAT_DATA_CHAR);
13070 			un->un_errstats->ks_private = un;
13071 			un->un_errstats->ks_update = nulldev;
13072 			kstat_install(un->un_errstats);
13073 			/*
13074 			 * Fill in the static data
13075 			 */
13076 			(void) strncpy(&stp->st_vid.value.c[0],
13077 			    ST_INQUIRY->inq_vid, 8);
13078 			/*
13079 			 * XXX:  Emulex MT-02 (and emulators) predates
13080 			 *	 SCSI-1 and has no vid & pid inquiry data.
13081 			 */
13082 			if (ST_INQUIRY->inq_len != 0) {
13083 				(void) strncpy(&stp->st_pid.value.c[0],
13084 				    ST_INQUIRY->inq_pid, 16);
13085 				(void) strncpy(&stp->st_revision.value.c[0],
13086 				    ST_INQUIRY->inq_revision, 4);
13087 			}
13088 		}
13089 	}
13090 	return (0);
13091 }
13092 
13093 static int
13094 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13095 {
13096 	int rval;
13097 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13098 
13099 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13100 
13101 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13102 	ASSERT(mutex_owned(ST_MUTEX));
13103 
13104 	/* Can't restore an invalid position */
13105 	if (pos->pmode == invalid) {
13106 		return (4);
13107 	}
13108 
13109 	/*
13110 	 * Assumtions:
13111 	 *	If a position was read and is in logical position mode.
13112 	 *	If a drive supports read position it supports locate.
13113 	 *	If the read position type is not NO_POS. even though
13114 	 *	   a read position make not have been attemped yet.
13115 	 *
13116 	 *	The drive can locate to the position.
13117 	 */
13118 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13119 		/*
13120 		 * If position mode is logical or legacy mode try
13121 		 * to locate there as it is faster.
13122 		 * If it fails try the old way.
13123 		 */
13124 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13125 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13126 		    pos->lgclblkno);
13127 
13128 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13129 		    pos->lgclblkno, pos->partition) == 0) {
13130 			/* Assume we are there copy rest of position back */
13131 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13132 				COPY_POS(&un->un_pos, pos);
13133 			}
13134 			return (0);
13135 		}
13136 
13137 		/*
13138 		 * If logical block locate failed to restore a logical
13139 		 * position, can't recover.
13140 		 */
13141 		if (pos->pmode == logical) {
13142 			return (-1);
13143 		}
13144 	}
13145 
13146 
13147 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13148 	    "Restoring tape position at fileno=%x, blkno=%x....",
13149 	    pos->fileno, pos->blkno);
13150 
13151 	/*
13152 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13153 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13154 	 * been simple in tape land ?
13155 	 */
13156 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13157 	if (rval) {
13158 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13159 		    "Failed to restore the last file and block position: In"
13160 		    " this state, Tape will be loaded at BOT during next open");
13161 		un->un_pos.pmode = invalid;
13162 		return (rval);
13163 	}
13164 
13165 	/* If the position was as the result of back space file */
13166 	if (pos->blkno > (INF / 2)) {
13167 		/* Go one extra file forward */
13168 		pos->fileno++;
13169 		/* Figure how many blocks to back into the previous file */
13170 		pos->blkno = -(INF - pos->blkno);
13171 	}
13172 
13173 	/* Go to requested fileno */
13174 	if (pos->fileno) {
13175 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13176 		if (rval) {
13177 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13178 			    "Failed to restore the last file position: In this "
13179 			    " state, Tape will be loaded at BOT during next"
13180 			    " open %d", __LINE__);
13181 			un->un_pos.pmode = invalid;
13182 			pos->pmode = invalid;
13183 			return (rval);
13184 		}
13185 	}
13186 
13187 	/*
13188 	 * If backing into a file we already did an extra file forward.
13189 	 * Now we have to back over the filemark to get to the end of
13190 	 * the previous file. The blkno has been ajusted to a negative
13191 	 * value so we will get to the expected location.
13192 	 */
13193 	if (pos->blkno) {
13194 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13195 		if (rval) {
13196 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13197 			    "Failed to restore the last file position: In this "
13198 			    " state, Tape will be loaded at BOT during next"
13199 			    " open %d", __LINE__);
13200 			un->un_pos.pmode = invalid;
13201 			pos->pmode = invalid;
13202 			return (rval);
13203 		}
13204 	}
13205 
13206 	/*
13207 	 * The position mode, block and fileno should be correct,
13208 	 * This updates eof and logical position information.
13209 	 */
13210 	un->un_pos.eof = pos->eof;
13211 	un->un_pos.lgclblkno = pos->lgclblkno;
13212 
13213 	return (0);
13214 }
13215 
13216 /*
13217  * check sense key, ASC, ASCQ in order to determine if the tape needs
13218  * to be ejected
13219  */
13220 
13221 static int
13222 st_check_asc_ascq(struct scsi_tape *un)
13223 {
13224 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13225 	struct tape_failure_code   *code;
13226 
13227 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13228 
13229 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13230 		if ((code->key  == sensep->es_key) &&
13231 		    (code->add_code  == sensep->es_add_code) &&
13232 		    (code->qual_code == sensep->es_qual_code))
13233 			return (1);
13234 	}
13235 	return (0);
13236 }
13237 
13238 /*
13239  * st_logpage_supported() sends a Log Sense command with
13240  * page code = 0 = Supported Log Pages Page to the device,
13241  * to see whether the page 'page' is supported.
13242  * Return values are:
13243  * -1 if the Log Sense command fails
13244  * 0 if page is not supported
13245  * 1 if page is supported
13246  */
13247 
13248 static int
13249 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13250 {
13251 	uchar_t *sp, *sensep;
13252 	unsigned length;
13253 	struct uscsi_cmd *com;
13254 	struct scsi_arq_status status;
13255 	int rval;
13256 	char cdb[CDB_GROUP1] = {
13257 		SCMD_LOG_SENSE_G1,
13258 		0,
13259 		SUPPORTED_LOG_PAGES_PAGE,
13260 		0,
13261 		0,
13262 		0,
13263 		0,
13264 		0,
13265 		(char)LOG_SENSE_LENGTH,
13266 		0
13267 	};
13268 
13269 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13270 
13271 	ASSERT(mutex_owned(ST_MUTEX));
13272 
13273 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13274 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13275 
13276 	com->uscsi_cdb = cdb;
13277 	com->uscsi_cdblen = CDB_GROUP1;
13278 	com->uscsi_bufaddr = (caddr_t)sensep;
13279 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13280 	com->uscsi_rqlen = sizeof (status);
13281 	com->uscsi_rqbuf = (caddr_t)&status;
13282 	com->uscsi_flags =
13283 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13284 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13285 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13286 	if (rval || com->uscsi_status) {
13287 		/* uscsi-command failed */
13288 		rval = -1;
13289 	} else {
13290 
13291 		sp = sensep + 3;
13292 
13293 		for (length = *sp++; length > 0; length--, sp++) {
13294 
13295 			if (*sp == page) {
13296 				rval = 1;
13297 				break;
13298 			}
13299 		}
13300 	}
13301 	kmem_free(com, sizeof (struct uscsi_cmd));
13302 	kmem_free(sensep, LOG_SENSE_LENGTH);
13303 	return (rval);
13304 }
13305 
13306 
13307 /*
13308  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13309  *
13310  * If the device does support the TapeAlert log page, then the cleaning bit
13311  * information will be read from this page. Otherwise we will see if one of
13312  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13313  * the device, which means, that we can get the cleaning bit information via
13314  * a RequestSense command.
13315  * If both methods of getting cleaning bit information are not supported
13316  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13317  * returns with
13318  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13319  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13320  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13321  * command fails, or if the amount of Request Sense data is not enough, then
13322  *  st_check_clean_bit() returns with -1.
13323  */
13324 
13325 static int
13326 st_check_clean_bit(struct scsi_tape *un)
13327 {
13328 	int rval = 0;
13329 
13330 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13331 
13332 	ASSERT(mutex_owned(ST_MUTEX));
13333 
13334 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13335 		return (rval);
13336 	}
13337 
13338 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13339 
13340 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13341 		if (rval == -1) {
13342 			return (0);
13343 		}
13344 		if (rval == 1) {
13345 
13346 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13347 		}
13348 
13349 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13350 		if (rval == -1) {
13351 			return (0);
13352 		}
13353 		if (rval == 1) {
13354 
13355 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13356 		}
13357 
13358 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13359 
13360 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13361 		}
13362 	}
13363 
13364 	rval = 0;
13365 
13366 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13367 
13368 		rval = st_check_sequential_clean_bit(un);
13369 		if (rval == -1) {
13370 			return (0);
13371 		}
13372 	}
13373 
13374 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13375 
13376 		rval = st_check_alert_flags(un);
13377 		if (rval == -1) {
13378 			return (0);
13379 		}
13380 	}
13381 
13382 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13383 
13384 		rval = st_check_sense_clean_bit(un);
13385 		if (rval == -1) {
13386 			return (0);
13387 		}
13388 	}
13389 
13390 	/*
13391 	 * If found a supported means to check need to clean.
13392 	 */
13393 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13394 
13395 		/*
13396 		 * head needs to be cleaned.
13397 		 */
13398 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13399 
13400 			/*
13401 			 * Print log message only first time
13402 			 * found needing cleaned.
13403 			 */
13404 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13405 
13406 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13407 				    "Periodic head cleaning required");
13408 
13409 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13410 			}
13411 
13412 		} else {
13413 
13414 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13415 		}
13416 	}
13417 
13418 	return (rval);
13419 }
13420 
13421 
13422 static int
13423 st_check_sequential_clean_bit(struct scsi_tape *un)
13424 {
13425 	int rval;
13426 	int ix;
13427 	ushort_t parameter;
13428 	struct uscsi_cmd *cmd;
13429 	struct log_sequential_page *sp;
13430 	struct log_sequential_page_parameter *prm;
13431 	struct scsi_arq_status status;
13432 	char cdb[CDB_GROUP1] = {
13433 		SCMD_LOG_SENSE_G1,
13434 		0,
13435 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13436 		0,
13437 		0,
13438 		0,
13439 		0,
13440 		(char)(sizeof (struct log_sequential_page) >> 8),
13441 		(char)(sizeof (struct log_sequential_page)),
13442 		0
13443 	};
13444 
13445 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13446 
13447 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13448 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13449 
13450 	cmd->uscsi_flags   =
13451 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13452 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13453 	cmd->uscsi_cdb	   = cdb;
13454 	cmd->uscsi_cdblen  = CDB_GROUP1;
13455 	cmd->uscsi_bufaddr = (caddr_t)sp;
13456 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13457 	cmd->uscsi_rqlen   = sizeof (status);
13458 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13459 
13460 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13461 
13462 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13463 
13464 		rval = -1;
13465 
13466 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13467 
13468 		rval = -1;
13469 	}
13470 
13471 	prm = &sp->param[0];
13472 
13473 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13474 
13475 		if (prm->log_param.length == 0) {
13476 			break;
13477 		}
13478 
13479 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13480 		    (prm->log_param.pc_lo & 0xff));
13481 
13482 		if (parameter == SEQUENTIAL_NEED_CLN) {
13483 
13484 			rval = MTF_TAPE_CLN_SUPPORTED;
13485 			if (prm->param_value[prm->log_param.length - 1]) {
13486 
13487 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13488 				    "sequential log says head dirty\n");
13489 				rval |= MTF_TAPE_HEAD_DIRTY;
13490 			}
13491 		}
13492 		prm = (struct log_sequential_page_parameter *)
13493 		    &prm->param_value[prm->log_param.length];
13494 	}
13495 
13496 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13497 	kmem_free(sp,  sizeof (struct log_sequential_page));
13498 
13499 	return (rval);
13500 }
13501 
13502 
13503 static int
13504 st_check_alert_flags(struct scsi_tape *un)
13505 {
13506 	struct st_tape_alert *ta;
13507 	struct uscsi_cmd *com;
13508 	struct scsi_arq_status status;
13509 	unsigned ix, length;
13510 	int rval;
13511 	tape_alert_flags flag;
13512 	char cdb[CDB_GROUP1] = {
13513 		SCMD_LOG_SENSE_G1,
13514 		0,
13515 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13516 		0,
13517 		0,
13518 		0,
13519 		0,
13520 		(char)(sizeof (struct st_tape_alert) >> 8),
13521 		(char)(sizeof (struct st_tape_alert)),
13522 		0
13523 	};
13524 
13525 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13526 
13527 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13528 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13529 
13530 	com->uscsi_cdb = cdb;
13531 	com->uscsi_cdblen = CDB_GROUP1;
13532 	com->uscsi_bufaddr = (caddr_t)ta;
13533 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13534 	com->uscsi_rqlen = sizeof (status);
13535 	com->uscsi_rqbuf = (caddr_t)&status;
13536 	com->uscsi_flags =
13537 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13538 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13539 
13540 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13541 
13542 	if (rval || com->uscsi_status || com->uscsi_resid) {
13543 
13544 		rval = -1; /* uscsi-command failed */
13545 
13546 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13547 
13548 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13549 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13550 		rval = -1;
13551 	}
13552 
13553 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13554 
13555 
13556 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13557 
13558 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13559 		    "TapeAlert length %d\n", length);
13560 	}
13561 
13562 
13563 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13564 
13565 		/*
13566 		 * if rval is bad before the first pass don't bother
13567 		 */
13568 		if (ix == 0 && rval != 0) {
13569 
13570 			break;
13571 		}
13572 
13573 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13574 		    ta->param[ix].log_param.pc_lo);
13575 
13576 		if ((ta->param[ix].param_value & 1) == 0) {
13577 			continue;
13578 		}
13579 		/*
13580 		 * check to see if current parameter is of interest.
13581 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13582 		 */
13583 		if ((flag == TAF_CLEAN_NOW) ||
13584 		    (flag == TAF_CLEAN_PERIODIC) ||
13585 		    ((flag == CLEAN_FOR_ERRORS) &&
13586 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13587 
13588 			rval = MTF_TAPE_CLN_SUPPORTED;
13589 
13590 
13591 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13592 			    "alert_page drive needs clean %d\n", flag);
13593 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13594 			rval |= MTF_TAPE_HEAD_DIRTY;
13595 
13596 		} else if (flag == TAF_CLEANING_MEDIA) {
13597 
13598 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13599 			    "alert_page drive was cleaned\n");
13600 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13601 		}
13602 
13603 	}
13604 
13605 	/*
13606 	 * Report it as dirty till we see it cleaned
13607 	 */
13608 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13609 
13610 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13611 		    "alert_page still dirty\n");
13612 		rval |= MTF_TAPE_HEAD_DIRTY;
13613 	}
13614 
13615 	kmem_free(com, sizeof (struct uscsi_cmd));
13616 	kmem_free(ta,  sizeof (struct st_tape_alert));
13617 
13618 	return (rval);
13619 }
13620 
13621 
13622 static int
13623 st_check_sense_clean_bit(struct scsi_tape *un)
13624 {
13625 	uchar_t *sensep;
13626 	char cdb[CDB_GROUP0];
13627 	struct uscsi_cmd *com;
13628 	ushort_t byte_pos;
13629 	uchar_t bit_mask;
13630 	unsigned length;
13631 	int index;
13632 	int rval;
13633 
13634 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13635 
13636 	/*
13637 	 * Since this tape does not support Tape Alert,
13638 	 * we now try to get the cleanbit status via
13639 	 * Request Sense.
13640 	 */
13641 
13642 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13643 
13644 		index = 0;
13645 
13646 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13647 
13648 		index = 1;
13649 
13650 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13651 
13652 		index = 2;
13653 
13654 	} else {
13655 
13656 		return (-1);
13657 	}
13658 
13659 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13660 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13661 	length = byte_pos + 1;
13662 
13663 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13664 	sensep = kmem_zalloc(length, KM_SLEEP);
13665 
13666 	cdb[0] = SCMD_REQUEST_SENSE;
13667 	cdb[1] = 0;
13668 	cdb[2] = 0;
13669 	cdb[3] = 0;
13670 	cdb[4] = (char)length;
13671 	cdb[5] = 0;
13672 
13673 	com->uscsi_cdb = cdb;
13674 	com->uscsi_cdblen = CDB_GROUP0;
13675 	com->uscsi_bufaddr = (caddr_t)sensep;
13676 	com->uscsi_buflen = length;
13677 	com->uscsi_flags =
13678 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13679 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13680 
13681 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13682 
13683 	if (rval || com->uscsi_status || com->uscsi_resid) {
13684 
13685 		rval = -1;
13686 
13687 	} else {
13688 
13689 		rval = MTF_TAPE_CLN_SUPPORTED;
13690 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13691 
13692 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13693 			    "sense data says head dirty\n");
13694 			rval |= MTF_TAPE_HEAD_DIRTY;
13695 		}
13696 	}
13697 
13698 	kmem_free(com, sizeof (struct uscsi_cmd));
13699 	kmem_free(sensep, length);
13700 	return (rval);
13701 }
13702 
13703 /*
13704  * st_clear_unit_attention
13705  *
13706  *  	run test unit ready's to clear out outstanding
13707  * 	unit attentions.
13708  * 	returns zero for SUCCESS or the errno from st_cmd call
13709  */
13710 static int
13711 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13712 {
13713 	int	i    = 0;
13714 	int	rval;
13715 
13716 	GET_SOFT_STATE(dev_instance);
13717 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13718 
13719 	do {
13720 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13721 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13722 	return (rval);
13723 }
13724 
13725 static void
13726 st_calculate_timeouts(struct scsi_tape *un)
13727 {
13728 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13729 
13730 	if (un->un_dp->non_motion_timeout == 0) {
13731 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13732 			un->un_dp->non_motion_timeout =
13733 			    st_io_time * st_long_timeout_x;
13734 		} else {
13735 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13736 		}
13737 	}
13738 
13739 	if (un->un_dp->io_timeout == 0) {
13740 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13741 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13742 		} else {
13743 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13744 		}
13745 	}
13746 
13747 	if (un->un_dp->rewind_timeout == 0) {
13748 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13749 			un->un_dp->rewind_timeout =
13750 			    st_space_time * st_long_timeout_x;
13751 		} else {
13752 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13753 		}
13754 	}
13755 
13756 	if (un->un_dp->space_timeout == 0) {
13757 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13758 			un->un_dp->space_timeout =
13759 			    st_space_time * st_long_timeout_x;
13760 		} else {
13761 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13762 		}
13763 	}
13764 
13765 	if (un->un_dp->load_timeout == 0) {
13766 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13767 			un->un_dp->load_timeout =
13768 			    st_space_time * st_long_timeout_x;
13769 		} else {
13770 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13771 		}
13772 	}
13773 
13774 	if (un->un_dp->unload_timeout == 0) {
13775 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13776 			un->un_dp->unload_timeout =
13777 			    st_space_time * st_long_timeout_x;
13778 		} else {
13779 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13780 		}
13781 	}
13782 
13783 	if (un->un_dp->erase_timeout == 0) {
13784 		if (un->un_dp->options & ST_LONG_ERASE) {
13785 			un->un_dp->erase_timeout =
13786 			    st_space_time * st_long_space_time_x;
13787 		} else {
13788 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13789 		}
13790 	}
13791 }
13792 
13793 
13794 static writablity
13795 st_is_not_wormable(struct scsi_tape *un)
13796 {
13797 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13798 	return (RDWR);
13799 }
13800 
13801 static writablity
13802 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13803 {
13804 	writablity wrt;
13805 
13806 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13807 
13808 	/* Mode sense should be current */
13809 	if (un->un_mspl->media_type == 1) {
13810 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13811 		    "Drive has WORM media loaded\n");
13812 		wrt = WORM;
13813 	} else {
13814 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13815 		    "Drive has non WORM media loaded\n");
13816 		wrt = RDWR;
13817 	}
13818 	return (wrt);
13819 }
13820 
13821 #define	HP_DAT_INQUIRY 0x4A
13822 static writablity
13823 st_is_hp_dat_worm(struct scsi_tape *un)
13824 {
13825 	char *buf;
13826 	int result;
13827 	writablity wrt;
13828 
13829 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13830 
13831 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13832 
13833 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13834 
13835 	if (result != 0) {
13836 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13837 		    "Read Standard Inquiry for WORM support failed");
13838 		wrt = FAILED;
13839 	} else if ((buf[40] & 1) == 0) {
13840 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13841 		    "Drive is NOT WORMable\n");
13842 		/* This drive doesn't support it so don't check again */
13843 		un->un_dp->options &= ~ST_WORMABLE;
13844 		wrt = RDWR;
13845 		un->un_wormable = st_is_not_wormable;
13846 	} else {
13847 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13848 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13849 		un->un_wormable = st_is_hp_dat_tape_worm;
13850 		wrt = un->un_wormable(un);
13851 	}
13852 
13853 	kmem_free(buf, HP_DAT_INQUIRY);
13854 
13855 	/*
13856 	 * If drive doesn't support it no point in checking further.
13857 	 */
13858 	return (wrt);
13859 }
13860 
13861 static writablity
13862 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13863 {
13864 	writablity wrt;
13865 
13866 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13867 
13868 	/* Mode sense should be current */
13869 	switch (un->un_mspl->media_type) {
13870 	case 0x00:
13871 		switch (un->un_mspl->density) {
13872 		case 0x40:
13873 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13874 			    "Drive has standard Gen I media loaded\n");
13875 			break;
13876 		case 0x42:
13877 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13878 			    "Drive has standard Gen II media loaded\n");
13879 			break;
13880 		case 0x44:
13881 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13882 			    "Drive has standard Gen III media loaded\n");
13883 			break;
13884 		case 0x46:
13885 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13886 			    "Drive has standard Gen IV media loaded\n");
13887 			break;
13888 		default:
13889 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13890 			    "Drive has standard unknown 0x%X media loaded\n",
13891 			    un->un_mspl->density);
13892 		}
13893 		wrt = RDWR;
13894 		break;
13895 	case 0x01:
13896 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13897 		    "Drive has WORM medium loaded\n");
13898 		wrt = WORM;
13899 		break;
13900 	case 0x80:
13901 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13902 		    "Drive has CD-ROM emulation medium loaded\n");
13903 		wrt = WORM;
13904 		break;
13905 	default:
13906 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13907 		    "Drive has an unexpected medium type 0x%X loaded\n",
13908 		    un->un_mspl->media_type);
13909 		wrt = RDWR;
13910 	}
13911 
13912 	return (wrt);
13913 }
13914 
13915 #define	LTO_REQ_INQUIRY 44
13916 static writablity
13917 st_is_hp_lto_worm(struct scsi_tape *un)
13918 {
13919 	char *buf;
13920 	int result;
13921 	writablity wrt;
13922 
13923 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13924 
13925 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13926 
13927 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13928 
13929 	if (result != 0) {
13930 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13931 		    "Read Standard Inquiry for WORM support failed");
13932 		wrt = FAILED;
13933 	} else if ((buf[40] & 1) == 0) {
13934 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13935 		    "Drive is NOT WORMable\n");
13936 		/* This drive doesn't support it so don't check again */
13937 		un->un_dp->options &= ~ST_WORMABLE;
13938 		wrt = RDWR;
13939 		un->un_wormable = st_is_not_wormable;
13940 	} else {
13941 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13942 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13943 		un->un_wormable = st_is_hp_lto_tape_worm;
13944 		wrt = un->un_wormable(un);
13945 	}
13946 
13947 	kmem_free(buf, LTO_REQ_INQUIRY);
13948 
13949 	/*
13950 	 * If drive doesn't support it no point in checking further.
13951 	 */
13952 	return (wrt);
13953 }
13954 
13955 static writablity
13956 st_is_t10_worm_device(struct scsi_tape *un)
13957 {
13958 	writablity wrt;
13959 
13960 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13961 
13962 	if (un->un_mspl->media_type == 0x3c) {
13963 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13964 		    "Drive has WORM media loaded\n");
13965 		wrt = WORM;
13966 	} else {
13967 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13968 		    "Drive has non WORM media loaded\n");
13969 		wrt = RDWR;
13970 	}
13971 	return (wrt);
13972 }
13973 
13974 #define	SEQ_CAP_PAGE	(char)0xb0
13975 static writablity
13976 st_is_t10_worm(struct scsi_tape *un)
13977 {
13978 	char *buf;
13979 	int result;
13980 	writablity wrt;
13981 
13982 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13983 
13984 	buf = kmem_zalloc(6, KM_SLEEP);
13985 
13986 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13987 
13988 	if (result != 0) {
13989 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13990 		    "Read Vitial Inquiry for Sequental Capability"
13991 		    " WORM support failed %x", result);
13992 		wrt = FAILED;
13993 	} else if ((buf[4] & 1) == 0) {
13994 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13995 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13996 		    "Drive is NOT WORMable\n");
13997 		/* This drive doesn't support it so don't check again */
13998 		un->un_dp->options &= ~ST_WORMABLE;
13999 		wrt = RDWR;
14000 		un->un_wormable = st_is_not_wormable;
14001 	} else {
14002 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14003 		    "Drive supports WORM\n");
14004 		un->un_wormable = st_is_t10_worm_device;
14005 		wrt = un->un_wormable(un);
14006 	}
14007 
14008 	kmem_free(buf, 6);
14009 
14010 	return (wrt);
14011 }
14012 
14013 
14014 #define	STK_REQ_SENSE 26
14015 
14016 static writablity
14017 st_is_stk_worm(struct scsi_tape *un)
14018 {
14019 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
14020 	struct scsi_extended_sense *sense;
14021 	struct uscsi_cmd *cmd;
14022 	char *buf;
14023 	int result;
14024 	writablity wrt;
14025 
14026 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
14027 
14028 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14029 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
14030 	sense = (struct scsi_extended_sense *)buf;
14031 
14032 	cmd->uscsi_flags = USCSI_READ;
14033 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14034 	cmd->uscsi_cdb = &cdb[0];
14035 	cmd->uscsi_bufaddr = buf;
14036 	cmd->uscsi_buflen = STK_REQ_SENSE;
14037 	cmd->uscsi_cdblen = CDB_GROUP0;
14038 	cmd->uscsi_rqlen = 0;
14039 	cmd->uscsi_rqbuf = NULL;
14040 
14041 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14042 
14043 	if (result != 0 || cmd->uscsi_status != 0) {
14044 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14045 		    "Request Sense for WORM failed");
14046 		wrt = RDWR;
14047 	} else if (sense->es_add_len + 8 < 24) {
14048 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14049 		    "Drive didn't send enough sense data for WORM byte %d\n",
14050 		    sense->es_add_len + 8);
14051 		wrt = RDWR;
14052 		un->un_wormable = st_is_not_wormable;
14053 	} else if ((buf[24]) & 0x02) {
14054 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14055 		    "Drive has WORM tape loaded\n");
14056 		wrt = WORM;
14057 		un->un_wormable = st_is_stk_worm;
14058 	} else {
14059 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14060 		    "Drive has normal tape loaded\n");
14061 		wrt = RDWR;
14062 		un->un_wormable = st_is_stk_worm;
14063 	}
14064 
14065 	kmem_free(buf, STK_REQ_SENSE);
14066 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14067 	return (wrt);
14068 }
14069 
14070 #define	DLT_INQ_SZ 44
14071 
14072 static writablity
14073 st_is_dlt_tape_worm(struct scsi_tape *un)
14074 {
14075 	caddr_t buf;
14076 	int result;
14077 	writablity wrt;
14078 
14079 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
14080 
14081 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14082 
14083 	/* Read Attribute Media Type */
14084 
14085 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
14086 
14087 	/*
14088 	 * If this quantum drive is attached via an HBA that cannot
14089 	 * support thr read attributes command return error in the
14090 	 * hope that someday they will support the t10 method.
14091 	 */
14092 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14093 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14094 		    "Read Attribute Command for WORM Media detection is not "
14095 		    "supported on the HBA that this drive is attached to.");
14096 		wrt = RDWR;
14097 		un->un_wormable = st_is_not_wormable;
14098 		goto out;
14099 	}
14100 
14101 	if (result != 0) {
14102 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14103 		    "Read Attribute Command for WORM Media returned 0x%x",
14104 		    result);
14105 		wrt = RDWR;
14106 		un->un_dp->options &= ~ST_WORMABLE;
14107 		goto out;
14108 	}
14109 
14110 	if ((uchar_t)buf[9] == 0x80) {
14111 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14112 		    "Drive media is WORM\n");
14113 		wrt = WORM;
14114 	} else {
14115 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14116 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14117 		wrt = RDWR;
14118 	}
14119 
14120 out:
14121 	kmem_free(buf, DLT_INQ_SZ);
14122 	return (wrt);
14123 }
14124 
14125 static writablity
14126 st_is_dlt_worm(struct scsi_tape *un)
14127 {
14128 	caddr_t buf;
14129 	int result;
14130 	writablity wrt;
14131 
14132 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14133 
14134 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14135 
14136 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14137 
14138 	if (result != 0) {
14139 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14140 		    "Read Vendor Specific Inquiry for WORM support failed");
14141 		wrt = RDWR;
14142 		goto out;
14143 	}
14144 
14145 	if ((buf[2] & 1) == 0) {
14146 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14147 		    "Drive is not WORMable\n");
14148 		wrt = RDWR;
14149 		un->un_dp->options &= ~ST_WORMABLE;
14150 		un->un_wormable = st_is_not_wormable;
14151 		goto out;
14152 	} else {
14153 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14154 		    "Drive is WORMable\n");
14155 		un->un_wormable = st_is_dlt_tape_worm;
14156 		wrt = un->un_wormable(un);
14157 	}
14158 out:
14159 	kmem_free(buf, DLT_INQ_SZ);
14160 
14161 	return (wrt);
14162 }
14163 
14164 typedef struct {
14165 	struct modeheader_seq header;
14166 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14167 	uchar_t pagecode	:6,
14168 				:2;
14169 	uchar_t page_len;
14170 	uchar_t syslogalive	:2,
14171 		device		:1,
14172 		abs		:1,
14173 		ulpbot		:1,
14174 		prth		:1,
14175 		ponej		:1,
14176 		ait		:1;
14177 	uchar_t span;
14178 
14179 	uchar_t			:6,
14180 		worm		:1,
14181 		mic		:1;
14182 	uchar_t worm_cap	:1,
14183 				:7;
14184 	uint32_t		:32;
14185 #else /* SPARC */
14186 	uchar_t			:2,
14187 		pagecode	:6;
14188 	uchar_t page_len;
14189 	uchar_t ait		:1,
14190 		device		:1,
14191 		abs		:1,
14192 		ulpbot		:1,
14193 		prth		:1,
14194 		ponej		:1,
14195 		syslogalive	:2;
14196 	uchar_t span;
14197 	uchar_t mic		:1,
14198 		worm		:1,
14199 				:6;
14200 	uchar_t			:7,
14201 		worm_cap	:1;
14202 	uint32_t		:32;
14203 #endif
14204 }ait_dev_con;
14205 
14206 #define	AIT_DEV_PAGE 0x31
14207 static writablity
14208 st_is_sony_worm(struct scsi_tape *un)
14209 {
14210 	int result;
14211 	writablity wrt;
14212 	ait_dev_con *ait_conf;
14213 
14214 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14215 
14216 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14217 
14218 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14219 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14220 
14221 	if (result == 0) {
14222 
14223 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14224 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14225 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14226 			    ait_conf->pagecode, AIT_DEV_PAGE);
14227 			wrt = RDWR;
14228 			un->un_wormable = st_is_not_wormable;
14229 
14230 		} else if (ait_conf->worm_cap) {
14231 
14232 			un->un_wormable = st_is_sony_worm;
14233 
14234 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14235 			    "Drives is WORMable\n");
14236 			if (ait_conf->worm) {
14237 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14238 				    "Media is WORM\n");
14239 				wrt = WORM;
14240 			} else {
14241 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14242 				    "Media is not WORM\n");
14243 				wrt = RDWR;
14244 			}
14245 
14246 		} else {
14247 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14248 			    "Drives not is WORMable\n");
14249 			wrt = RDWR;
14250 			/* No further checking required */
14251 			un->un_dp->options &= ~ST_WORMABLE;
14252 		}
14253 
14254 	} else {
14255 
14256 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14257 		    "AIT device config mode sense page read command failed"
14258 		    " result = %d ", result);
14259 		wrt = FAILED;
14260 		un->un_wormable = st_is_not_wormable;
14261 	}
14262 
14263 	kmem_free(ait_conf, sizeof (ait_dev_con));
14264 	return (wrt);
14265 }
14266 
14267 static writablity
14268 st_is_drive_worm(struct scsi_tape *un)
14269 {
14270 	writablity wrt;
14271 
14272 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14273 
14274 	switch (un->un_dp->type) {
14275 	case MT_ISDLT:
14276 		wrt = st_is_dlt_worm(un);
14277 		break;
14278 
14279 	case MT_ISSTK9840:
14280 		wrt = st_is_stk_worm(un);
14281 		break;
14282 
14283 	case MT_IS8MM:
14284 	case MT_ISAIT:
14285 		wrt = st_is_sony_worm(un);
14286 		break;
14287 
14288 	case MT_LTO:
14289 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14290 			wrt = st_is_hp_lto_worm(un);
14291 		} else {
14292 			wrt = st_is_t10_worm(un);
14293 		}
14294 		break;
14295 
14296 	case MT_ISDAT:
14297 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14298 			wrt = st_is_hp_dat_worm(un);
14299 		} else {
14300 			wrt = st_is_t10_worm(un);
14301 		}
14302 		break;
14303 
14304 	default:
14305 		wrt = FAILED;
14306 		break;
14307 	}
14308 
14309 	/*
14310 	 * If any of the above failed try the t10 standard method.
14311 	 */
14312 	if (wrt == FAILED) {
14313 		wrt = st_is_t10_worm(un);
14314 	}
14315 
14316 	/*
14317 	 * Unknown method for detecting WORM media.
14318 	 */
14319 	if (wrt == FAILED) {
14320 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14321 		    "Unknown method for WORM media detection\n");
14322 		wrt = RDWR;
14323 		un->un_dp->options &= ~ST_WORMABLE;
14324 	}
14325 
14326 	return (wrt);
14327 }
14328 
14329 static int
14330 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14331     size_t size, ubufunc_t bufunc)
14332 {
14333 	char cdb[CDB_GROUP4];
14334 	int result;
14335 	struct uscsi_cmd *cmd;
14336 	struct scsi_arq_status status;
14337 
14338 	caddr_t buf = (caddr_t)pnt;
14339 
14340 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14341 
14342 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14343 		return (ENOTTY);
14344 	}
14345 
14346 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14347 
14348 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14349 	cdb[1] = 0;
14350 	cdb[2] = 0;
14351 	cdb[3] = 0;
14352 	cdb[4] = 0;
14353 	cdb[5] = 0;
14354 	cdb[6] = 0;
14355 	cdb[7] = 0;
14356 	cdb[8] = (char)(attribute >> 8);
14357 	cdb[9] = (char)(attribute);
14358 	cdb[10] = (char)(size >> 24);
14359 	cdb[11] = (char)(size >> 16);
14360 	cdb[12] = (char)(size >> 8);
14361 	cdb[13] = (char)(size);
14362 	cdb[14] = 0;
14363 	cdb[15] = 0;
14364 
14365 
14366 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14367 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14368 	cmd->uscsi_cdb = &cdb[0];
14369 	cmd->uscsi_bufaddr = (caddr_t)buf;
14370 	cmd->uscsi_buflen = size;
14371 	cmd->uscsi_cdblen = sizeof (cdb);
14372 	cmd->uscsi_rqlen = sizeof (status);
14373 	cmd->uscsi_rqbuf = (caddr_t)&status;
14374 
14375 	result = bufunc(un, cmd, FKIOCTL);
14376 
14377 	if (result != 0 || cmd->uscsi_status != 0) {
14378 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14379 		    "st_read_attribute failed: result %d status %d\n",
14380 		    result, cmd->uscsi_status);
14381 		/*
14382 		 * If this returns invalid operation code don't try again.
14383 		 */
14384 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14385 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14386 			result = ENOTTY;
14387 		} else if (result == 0) {
14388 			result = EIO;
14389 		}
14390 
14391 	} else {
14392 
14393 		/*
14394 		 * The attribute retured should match the attribute requested.
14395 		 */
14396 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14397 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14398 			    "st_read_attribute got wrong data back expected "
14399 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14400 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14401 			    "bad? data", buf, size);
14402 			result = EIO;
14403 		}
14404 	}
14405 
14406 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14407 
14408 	return (result);
14409 }
14410 
14411 static int
14412 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14413     uchar_t page)
14414 {
14415 	char cdb[CDB_GROUP0];
14416 	struct scsi_extended_sense *sense;
14417 	struct uscsi_cmd *cmd;
14418 	int result;
14419 
14420 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14421 
14422 	cdb[0] = SCMD_INQUIRY;
14423 	cdb[1] = page ? 1 : 0;
14424 	cdb[2] = page;
14425 	cdb[3] = 0;
14426 	cdb[4] = size;
14427 	cdb[5] = 0;
14428 
14429 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14430 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14431 
14432 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14433 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14434 	cmd->uscsi_cdb = &cdb[0];
14435 	cmd->uscsi_bufaddr = dest;
14436 	cmd->uscsi_buflen = size;
14437 	cmd->uscsi_cdblen = CDB_GROUP0;
14438 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14439 	cmd->uscsi_rqbuf = (caddr_t)sense;
14440 
14441 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14442 
14443 	if (result != 0 || cmd->uscsi_status != 0) {
14444 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14445 		    "st_get_special_inquiry() failed for page %x", page);
14446 		if (result == 0) {
14447 			result = EIO;
14448 		}
14449 	}
14450 
14451 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14452 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14453 
14454 	return (result);
14455 }
14456 
14457 
14458 static int
14459 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14460 {
14461 	int rval = ENOTTY;
14462 	uchar_t status = un->un_status;
14463 	posmode previous_pmode = un->un_running.pmode;
14464 
14465 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14466 
14467 	while (un->un_read_pos_type != NO_POS) {
14468 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14469 
14470 		/*
14471 		 * If read position command returned good status
14472 		 * Parse the data to see if the position can be interpreted.
14473 		 */
14474 		if ((rval == 0) &&
14475 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14476 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14477 		    post_space)) == 0)) {
14478 			/*
14479 			 * Update the running position as well if un_pos was
14480 			 * ok. But only if recovery is enabled.
14481 			 */
14482 			if (st_recov_sz != sizeof (recov_info)) {
14483 				break;
14484 			}
14485 			rval = st_interpret_read_pos(un, &un->un_running,
14486 			    un->un_read_pos_type, 32,
14487 			    (caddr_t)un->un_read_pos_data, post_space);
14488 			un->un_status = status;
14489 			break;
14490 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14491 			un->un_running.pmode = previous_pmode;
14492 			continue;
14493 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14494 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14495 			    "st_update_block_pos() read position cmd 0x%x"
14496 			    " returned 0x%x un_status = %d",
14497 			    un->un_read_pos_type, rval, un->un_status);
14498 			/* ENOTTY means it read garbage. try something else. */
14499 			if (rval == ENOTTY) {
14500 				rval = EIO; /* so ENOTTY is not final rval */
14501 			} else {
14502 				break;
14503 			}
14504 		} else {
14505 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14506 			    "st_update_block_pos() read position cmd %x"
14507 			    " returned %x", un->un_read_pos_type, rval);
14508 			un->un_running.pmode = previous_pmode;
14509 		}
14510 
14511 		switch (un->un_read_pos_type) {
14512 		case SHORT_POS:
14513 			un->un_read_pos_type = NO_POS;
14514 			break;
14515 
14516 		case LONG_POS:
14517 			un->un_read_pos_type = EXT_POS;
14518 			break;
14519 
14520 		case EXT_POS:
14521 			un->un_read_pos_type = SHORT_POS;
14522 			break;
14523 
14524 		default:
14525 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14526 			    "Unexpected read position type 0x%x",
14527 			    un->un_read_pos_type);
14528 		}
14529 		un->un_status = KEY_NO_SENSE;
14530 	}
14531 
14532 	return (rval);
14533 }
14534 
14535 static int
14536 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14537 {
14538 	int result;
14539 	size_t d_sz;
14540 	caddr_t pos_info;
14541 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14542 
14543 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14544 
14545 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14546 		return (0);
14547 	}
14548 
14549 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14550 
14551 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14552 		    "bp_mapin_common() failed");
14553 
14554 		return (EIO);
14555 	}
14556 
14557 	d_sz = bp->b_bcount - bp->b_resid;
14558 	if (d_sz == 0) {
14559 		bp_mapout(bp);
14560 		return (EIO);
14561 	}
14562 
14563 	/*
14564 	 * Copy the buf to a double-word aligned memory that can hold the
14565 	 * tape_position_t data structure.
14566 	 */
14567 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14568 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14569 		    "kmem_alloc() failed");
14570 		bp_mapout(bp);
14571 		return (EIO);
14572 	}
14573 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14574 
14575 #ifdef STDEBUG
14576 	if ((st_debug & 0x7) > 2) {
14577 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14578 		    "st_get_read_pos() position info",
14579 		    pos_info, bp->b_bcount);
14580 	}
14581 #endif
14582 
14583 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14584 	    d_sz, pos_info, 0);
14585 
14586 	COPY_POS(&un->un_running, &un->un_pos);
14587 
14588 	kmem_free(pos_info, d_sz);
14589 	bp_mapout(bp);
14590 
14591 	return (result);
14592 }
14593 
14594 #if defined(_BIG_ENDIAN)
14595 
14596 #define	FIX_ENDIAN16(x)
14597 #define	FIX_ENDIAN32(x)
14598 #define	FIX_ENDIAN64(x)
14599 
14600 #elif defined(_LITTLE_ENDIAN)
14601 
14602 static void
14603 st_swap16(uint16_t *val)
14604 {
14605 	uint16_t tmp;
14606 
14607 	tmp = (*val >>  8) & 0xff;
14608 	tmp |= (*val <<  8) & 0xff00;
14609 
14610 	*val = tmp;
14611 }
14612 
14613 static void
14614 st_swap32(uint32_t *val)
14615 {
14616 	uint32_t tmp;
14617 
14618 	tmp =  (*val >> 24) & 0xff;
14619 	tmp |= (*val >>  8) & 0xff00;
14620 	tmp |= (*val <<  8) & 0xff0000;
14621 	tmp |= (*val << 24) & 0xff000000;
14622 
14623 	*val = tmp;
14624 }
14625 
14626 static void
14627 st_swap64(uint64_t *val)
14628 {
14629 	uint32_t low;
14630 	uint32_t high;
14631 
14632 	low =  (uint32_t)(*val);
14633 	high = (uint32_t)(*val >> 32);
14634 
14635 	st_swap32(&low);
14636 	st_swap32(&high);
14637 
14638 	*val =  high;
14639 	*val |= ((uint64_t)low << 32);
14640 }
14641 
14642 #define	FIX_ENDIAN16(x) st_swap16(x)
14643 #define	FIX_ENDIAN32(x) st_swap32(x)
14644 #define	FIX_ENDIAN64(x) st_swap64(x)
14645 #endif
14646 
14647 /*
14648  * st_interpret_read_pos()
14649  *
14650  * Returns:
14651  *	0	If secsessful.
14652  *	EIO	If read postion responce data was unuseable or invalid.
14653  *	ERANGE	If the position of the drive is too large for the read_p_type.
14654  *	ENOTTY	If the responce data looks invalid for the read position type.
14655  */
14656 
14657 static int
14658 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14659     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14660 {
14661 	int rval = 0;
14662 	int flag = 0;
14663 	tapepos_t org;
14664 
14665 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14666 
14667 	/*
14668 	 * We expect the position value to change after a space command.
14669 	 * So if post_space is set we don't print out what has changed.
14670 	 */
14671 	if ((dest != &un->un_pos) && (post_space == 0) &&
14672 	    (st_recov_sz == sizeof (recov_info))) {
14673 		COPY_POS(&org, dest);
14674 		flag = 1;
14675 	}
14676 
14677 	/*
14678 	 * See what kind of read position was requested.
14679 	 */
14680 	switch (type) {
14681 
14682 	case SHORT_POS: /* Short data format */
14683 	{
14684 		tape_position_t *pos_info = (tape_position_t *)responce;
14685 		uint32_t value;
14686 
14687 		/* If reserved fields are non zero don't use the data */
14688 		if (pos_info->reserved0 || pos_info->reserved1 ||
14689 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14690 		    pos_info->reserved3) {
14691 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14692 			    "Invalid Read Short Position Data returned\n");
14693 			rval = EIO;
14694 			break;
14695 		}
14696 		/*
14697 		 * Position is to large to use this type of read position.
14698 		 */
14699 		if (pos_info->posi_err == 1) {
14700 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14701 			    "Drive reported position error\n");
14702 			rval = ERANGE;
14703 			break;
14704 		}
14705 		/*
14706 		 * If your at the begining of partition and end at the same
14707 		 * time it's very small partition or bad data.
14708 		 */
14709 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14710 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14711 			    "SHORT_POS returned begin and end of"
14712 			    " partition\n");
14713 			rval = EIO;
14714 			break;
14715 		}
14716 
14717 		if (pos_info->blk_posi_unkwn == 0) {
14718 
14719 			value = pos_info->host_block;
14720 			FIX_ENDIAN32(&value);
14721 
14722 			/*
14723 			 * If the tape is rewound the host blcok should be 0.
14724 			 */
14725 			if ((pos_info->begin_of_part == 1) &&
14726 			    (value != 0)) {
14727 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14728 				    "SHORT_POS returned begin of partition"
14729 				    " but host block was 0x%x\n", value);
14730 				rval = EIO;
14731 				break;
14732 			}
14733 
14734 			if (dest->lgclblkno != value) {
14735 				if (flag)
14736 					flag++;
14737 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14738 				    "SHORT_POS current logical 0x%"PRIx64" read"
14739 				    " 0x%x\n", dest->lgclblkno, value);
14740 			}
14741 
14742 			dest->lgclblkno = (uint64_t)value;
14743 
14744 			/*
14745 			 * If the begining of partition is true and the
14746 			 * block number is zero we will beleive that it is
14747 			 * rewound. Promote the pmode to legacy.
14748 			 */
14749 			if ((pos_info->begin_of_part == 1) &&
14750 			    (value == 0)) {
14751 				dest->blkno = 0;
14752 				dest->fileno = 0;
14753 				if (dest->pmode != legacy)
14754 					dest->pmode = legacy;
14755 			/*
14756 			 * otherwise if the pmode was invalid,
14757 			 * promote it to logical.
14758 			 */
14759 			} else if (dest->pmode == invalid) {
14760 				dest->pmode = logical;
14761 			}
14762 
14763 			if (dest->partition != pos_info->partition_number) {
14764 				if (flag)
14765 					flag++;
14766 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14767 				    "SHORT_POS current partition %d read %d\n",
14768 				    dest->partition,
14769 				    pos_info->partition_number);
14770 			}
14771 
14772 			dest->partition = pos_info->partition_number;
14773 
14774 		} else {
14775 			dest->pmode = invalid;
14776 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14777 			    "Tape drive reported block position as unknown\n");
14778 		}
14779 		break;
14780 	}
14781 
14782 	case LONG_POS: /* Long data format */
14783 	{
14784 		uint64_t value;
14785 		tape_position_long_t *long_pos_info =
14786 		    (tape_position_long_t *)responce;
14787 
14788 		/* If reserved fields are non zero don't use the data */
14789 		if ((long_pos_info->reserved0) ||
14790 		    (long_pos_info->reserved1) ||
14791 		    (long_pos_info->reserved2)) {
14792 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14793 			    "Invalid Read Long Position Data returned\n");
14794 			rval = ENOTTY;
14795 			break;
14796 		}
14797 
14798 		/* Is position Valid */
14799 		if (long_pos_info->blk_posi_unkwn == 0) {
14800 			uint32_t part;
14801 
14802 			value = long_pos_info->block_number;
14803 			FIX_ENDIAN64(&value);
14804 
14805 			/*
14806 			 * If it says we are at the begining of partition
14807 			 * the block value better be 0.
14808 			 */
14809 			if ((long_pos_info->begin_of_part == 1) &&
14810 			    (value != 0)) {
14811 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14812 				    "LONG_POS returned begin of partition but"
14813 				    " block number was 0x%"PRIx64"\n", value);
14814 				rval = ENOTTY;
14815 				break;
14816 			}
14817 			/*
14818 			 * Can't be at the start and the end of the partition
14819 			 * at the same time if the partition is larger the 0.
14820 			 */
14821 			if (long_pos_info->begin_of_part &&
14822 			    long_pos_info->end_of_part) {
14823 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14824 				    "LONG_POS returned begin and end of"
14825 				    " partition\n");
14826 				rval = ENOTTY;
14827 				break;
14828 			}
14829 
14830 			/*
14831 			 * If the logical block number is not what we expected.
14832 			 */
14833 			if (dest->lgclblkno != value) {
14834 				if (flag)
14835 					flag++;
14836 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14837 				    "LONG_POS current logical 0x%"PRIx64
14838 				    " read 0x%"PRIx64"\n",
14839 				    dest->lgclblkno, value);
14840 			}
14841 			dest->lgclblkno = value;
14842 
14843 			/*
14844 			 * If the begining of partition is true and the
14845 			 * block number is zero we will beleive that it is
14846 			 * rewound. Promote the pmode to legacy.
14847 			 */
14848 			if ((long_pos_info->begin_of_part == 1) &&
14849 			    (long_pos_info->block_number == 0)) {
14850 				dest->blkno = 0;
14851 				dest->fileno = 0;
14852 				if (dest->pmode != legacy)
14853 					dest->pmode = legacy;
14854 			/*
14855 			 * otherwise if the pmode was invalid,
14856 			 * promote it to logical.
14857 			 */
14858 			} else if (dest->pmode == invalid) {
14859 				dest->pmode = logical;
14860 			}
14861 
14862 			part = long_pos_info->partition;
14863 			FIX_ENDIAN32(&part);
14864 			if (dest->partition != part) {
14865 				if (flag)
14866 					flag++;
14867 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14868 				    "LONG_POS current partition %d"
14869 				    " read %d\n", dest->partition, part);
14870 			}
14871 			dest->partition = part;
14872 		} else {
14873 			/*
14874 			 * If the drive doesn't know location,
14875 			 * we don't either.
14876 			 */
14877 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14878 			    "Tape drive reported block position as unknown\n");
14879 			dest->pmode = invalid;
14880 		}
14881 
14882 		/* Is file position valid */
14883 		if (long_pos_info->mrk_posi_unkwn == 0) {
14884 			value = long_pos_info->file_number;
14885 			FIX_ENDIAN64(&value);
14886 			/*
14887 			 * If it says we are at the begining of partition
14888 			 * the block value better be 0.
14889 			 */
14890 			if ((long_pos_info->begin_of_part == 1) &&
14891 			    (value != 0)) {
14892 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14893 				    "LONG_POS returned begin of partition but"
14894 				    " block number was 0x%"PRIx64"\n", value);
14895 				rval = ENOTTY;
14896 				break;
14897 			}
14898 			if (((dest->pmode == legacy) ||
14899 			    (dest->pmode == logical)) &&
14900 			    (dest->fileno != value)) {
14901 				if (flag)
14902 					flag++;
14903 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14904 				    "LONG_POS fileno 0x%"PRIx64
14905 				    " not un_pos %x\n", value,
14906 				    dest->fileno);
14907 			} else if (dest->pmode == invalid) {
14908 				dest->pmode = logical;
14909 			}
14910 			dest->fileno = (int32_t)value;
14911 		}
14912 
14913 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14914 			dest->eof = ST_EOT;
14915 		}
14916 
14917 		break;
14918 	}
14919 
14920 	case EXT_POS: /* Extended data format */
14921 	{
14922 		uint64_t value;
14923 		uint16_t len;
14924 		tape_position_ext_t *ext_pos_info =
14925 		    (tape_position_ext_t *)responce;
14926 
14927 		/* Make sure that there is enough data there */
14928 		if (data_sz < 16) {
14929 			break;
14930 		}
14931 
14932 		/* If reserved fields are non zero don't use the data */
14933 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14934 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14935 			    "EXT_POS reserved fields not zero\n");
14936 			rval = ENOTTY;
14937 			break;
14938 		}
14939 
14940 		/*
14941 		 * In the unlikely event of overflowing 64 bits of position.
14942 		 */
14943 		if (ext_pos_info->posi_err != 0) {
14944 			rval = ERANGE;
14945 			break;
14946 		}
14947 
14948 		len = ext_pos_info->parameter_len;
14949 		FIX_ENDIAN16(&len);
14950 
14951 		if (len != 0x1c) {
14952 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14953 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14954 			    len);
14955 			rval = ENOTTY;
14956 			break;
14957 		}
14958 
14959 		/* Is block position information valid */
14960 		if (ext_pos_info->blk_posi_unkwn == 0) {
14961 
14962 			value = ext_pos_info->host_block;
14963 			FIX_ENDIAN64(&value);
14964 			if ((ext_pos_info->begin_of_part == 1) &&
14965 			    (value != 0)) {
14966 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14967 				    "EXT_POS returned begining of partition but"
14968 				    " the host block was 0x%"PRIx64"\n", value);
14969 				rval = ENOTTY;
14970 				break;
14971 			}
14972 
14973 			if (dest->lgclblkno != value) {
14974 				if (flag)
14975 					flag++;
14976 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14977 				    "EXT_POS current logical 0x%"PRIx64
14978 				    " read 0x%"PRIx64"\n",
14979 				    dest->lgclblkno, value);
14980 			}
14981 			dest->lgclblkno = value;
14982 
14983 			/*
14984 			 * If the begining of partition is true and the
14985 			 * block number is zero we will beleive that it is
14986 			 * rewound. Promote the pmode to legacy.
14987 			 */
14988 			if ((ext_pos_info->begin_of_part == 1) &&
14989 			    (ext_pos_info->host_block == 0)) {
14990 				dest->blkno = 0;
14991 				dest->fileno = 0;
14992 				if (dest->pmode != legacy) {
14993 					dest->pmode = legacy;
14994 				}
14995 			/*
14996 			 * otherwise if the pmode was invalid,
14997 			 * promote it to logical.
14998 			 */
14999 			} else if (dest->pmode == invalid) {
15000 				dest->pmode = logical;
15001 			}
15002 
15003 			if (dest->partition != ext_pos_info->partition) {
15004 				if (flag)
15005 					flag++;
15006 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
15007 				    "EXT_POS current partition %d read %d\n",
15008 				    dest->partition,
15009 				    ext_pos_info->partition);
15010 			}
15011 			dest->partition = ext_pos_info->partition;
15012 
15013 		} else {
15014 			dest->pmode = invalid;
15015 		}
15016 		break;
15017 	}
15018 
15019 	default:
15020 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15021 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
15022 		rval = EIO;
15023 	}
15024 
15025 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
15026 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15027 		    "position read in", &org);
15028 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
15029 		    "position read out", dest);
15030 	}
15031 
15032 	return (rval);
15033 }
15034 
15035 static int
15036 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
15037     uint64_t lblk, uchar_t partition)
15038 {
15039 	int rval;
15040 	char cdb[CDB_GROUP4];
15041 	struct uscsi_cmd *cmd;
15042 	struct scsi_extended_sense sense;
15043 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
15044 
15045 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
15046 	/*
15047 	 * Not sure what to do when doing recovery and not wanting
15048 	 * to update un_pos
15049 	 */
15050 
15051 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
15052 
15053 	if (lblk <= INT32_MAX) {
15054 		cmd->uscsi_cdblen = CDB_GROUP1;
15055 		cdb[0] = SCMD_LOCATE;
15056 		cdb[1] = pos->partition == partition ? 0 : 2;
15057 		cdb[2] = 0;
15058 		cdb[3] = (char)(lblk >> 24);
15059 		cdb[4] = (char)(lblk >> 16);
15060 		cdb[5] = (char)(lblk >> 8);
15061 		cdb[6] = (char)(lblk);
15062 		cdb[7] = 0;
15063 		cdb[8] = partition;
15064 		cdb[9] = 0;
15065 	} else {
15066 		/*
15067 		 * If the drive doesn't give a 64 bit read position data
15068 		 * it is unlikely it will accept 64 bit locates.
15069 		 */
15070 		if (un->un_read_pos_type != LONG_POS) {
15071 			kmem_free(cmd, sizeof (struct uscsi_cmd));
15072 			return (ERANGE);
15073 		}
15074 		cmd->uscsi_cdblen = CDB_GROUP4;
15075 		cdb[0] = (char)SCMD_LOCATE_G4;
15076 		cdb[1] = pos->partition == partition ? 0 : 2;
15077 		cdb[2] = 0;
15078 		cdb[3] = partition;
15079 		cdb[4] = (char)(lblk >> 56);
15080 		cdb[5] = (char)(lblk >> 48);
15081 		cdb[6] = (char)(lblk >> 40);
15082 		cdb[7] = (char)(lblk >> 32);
15083 		cdb[8] = (char)(lblk >> 24);
15084 		cdb[9] = (char)(lblk >> 16);
15085 		cdb[10] = (char)(lblk >> 8);
15086 		cdb[11] = (char)(lblk);
15087 		cdb[12] = 0;
15088 		cdb[13] = 0;
15089 		cdb[14] = 0;
15090 		cdb[15] = 0;
15091 	}
15092 
15093 
15094 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15095 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15096 	cmd->uscsi_rqlen = sizeof (sense);
15097 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15098 	cmd->uscsi_cdb = cdb;
15099 
15100 	rval = ubf(un, cmd, FKIOCTL);
15101 
15102 	pos->pmode = logical;
15103 	pos->eof = ST_NO_EOF;
15104 
15105 	if (lblk > INT32_MAX) {
15106 		/*
15107 		 * XXX This is a work around till we handle Descriptor format
15108 		 * sense data. Since we are sending a command where the standard
15109 		 * sense data can not correctly represent a correct residual in
15110 		 * 4 bytes.
15111 		 */
15112 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15113 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15114 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15115 			/* Doesn't like big locate command */
15116 			un->un_status = 0;
15117 			rval = ERANGE;
15118 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15119 			/* Aborted big locate command */
15120 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15121 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15122 			    rval);
15123 			un->un_status = 0;
15124 			rval = EIO;
15125 		} else if (st_update_block_pos(un, bf, 1)) {
15126 			/* read position failed */
15127 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15128 			    "Big LOCATE and read pos: rval = %d\n", rval);
15129 			rval = EIO;
15130 		} else if (lblk > un->un_pos.lgclblkno) {
15131 			/* read position worked but position was not expected */
15132 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15133 			    "Big LOCATE and recover read less then desired 0x%"
15134 			    PRIx64"\n", un->un_pos.lgclblkno);
15135 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15136 			un->un_status = KEY_BLANK_CHECK;
15137 			rval = ESPIPE;
15138 		} else if (lblk == un->un_pos.lgclblkno) {
15139 			/* read position was what was expected */
15140 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15141 			    "Big LOCATE and recover seems to have worked\n");
15142 			un->un_err_resid = 0;
15143 			rval = 0;
15144 		} else {
15145 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15146 			    "BIGLOCATE end up going backwards");
15147 			un->un_err_resid = lblk;
15148 			rval = EIO;
15149 		}
15150 
15151 	} else if (rval == 0) {
15152 		/* Worked as requested */
15153 		pos->lgclblkno = lblk;
15154 
15155 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15156 	    (cmd->uscsi_resid != 0)) {
15157 		/* Got part way there but wasn't enough blocks on tape */
15158 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15159 		un->un_err_resid = cmd->uscsi_resid;
15160 		un->un_status = KEY_BLANK_CHECK;
15161 		rval = ESPIPE;
15162 
15163 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15164 		/* Got part way there but drive didn't tell what we missed by */
15165 		un->un_err_resid = lblk - pos->lgclblkno;
15166 		un->un_status = KEY_BLANK_CHECK;
15167 		rval = ESPIPE;
15168 
15169 	} else {
15170 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15171 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15172 		    rval, cmd->uscsi_status);
15173 		un->un_err_resid = lblk;
15174 		un->un_status = KEY_ILLEGAL_REQUEST;
15175 		pos->pmode = invalid;
15176 		rval = EIO;
15177 	}
15178 
15179 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15180 
15181 	return (rval);
15182 }
15183 
15184 static int
15185 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15186 {
15187 	int rval;
15188 
15189 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15190 
15191 
15192 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15193 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15194 #if 0
15195 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15196 		un->un_pos.fileno++;
15197 		un->un_pos.blkno = 0;
15198 		return (0);
15199 	}
15200 #endif
15201 	/* pmode == invalid already handled */
15202 	if (un->un_pos.pmode == legacy) {
15203 		/*
15204 		 * forward space over filemark
15205 		 *
15206 		 * For ASF we allow a count of 0 on fsf which means
15207 		 * we just want to go to beginning of current file.
15208 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15209 		 * Allow stepping over double fmk with reel
15210 		 */
15211 		if ((un->un_pos.eof >= ST_EOT) &&
15212 		    (files > 0) &&
15213 		    ((un->un_dp->options & ST_REEL) == 0)) {
15214 			/* we're at EOM */
15215 			un->un_err_resid = files;
15216 			un->un_status = KEY_BLANK_CHECK;
15217 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15218 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15219 			return (EIO);
15220 		}
15221 
15222 		/*
15223 		 * physical tape position may not be what we've been
15224 		 * telling the user; adjust the request accordingly
15225 		 */
15226 		if (IN_EOF(un->un_pos)) {
15227 			un->un_pos.fileno++;
15228 			un->un_pos.blkno = 0;
15229 			/*
15230 			 * For positive direction case, we're now covered.
15231 			 * For zero or negative direction, we're covered
15232 			 * (almost)
15233 			 */
15234 			files--;
15235 		}
15236 
15237 	}
15238 
15239 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15240 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15241 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15242 		return (EIO);
15243 	}
15244 
15245 
15246 	/*
15247 	 * Forward space file marks.
15248 	 * We leave ourselves at block zero
15249 	 * of the target file number.
15250 	 */
15251 	if (files < 0) {
15252 		rval = st_backward_space_files(un, -files, 0);
15253 	} else {
15254 		rval = st_forward_space_files(un, files);
15255 	}
15256 
15257 	return (rval);
15258 }
15259 
15260 static int
15261 st_forward_space_files(struct scsi_tape *un, int64_t count)
15262 {
15263 	int rval;
15264 
15265 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15266 
15267 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15268 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15269 
15270 	ASSERT(count >= 0);
15271 	ASSERT(un->un_pos.pmode != invalid);
15272 
15273 	/*
15274 	 * A space with a count of zero means take me to the start of file.
15275 	 */
15276 	if (count == 0) {
15277 
15278 		/* Hay look were already there */
15279 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15280 			un->un_err_resid = 0;
15281 			COPY_POS(&un->un_err_pos, &un->un_pos);
15282 			return (0);
15283 		}
15284 
15285 		/*
15286 		 * Well we are in the first file.
15287 		 * A rewind will get to the start.
15288 		 */
15289 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15290 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15291 
15292 		/*
15293 		 * Can we backspace to get there?
15294 		 * This should work in logical mode.
15295 		 */
15296 		} else if (un->un_dp->options & ST_BSF) {
15297 			rval = st_space_to_begining_of_file(un);
15298 
15299 		/*
15300 		 * Can't back space but current file number is known,
15301 		 * So rewind and space from the begining of the partition.
15302 		 */
15303 		} else if (un->un_pos.pmode == legacy) {
15304 			rval = st_scenic_route_to_begining_of_file(un,
15305 			    un->un_pos.fileno);
15306 
15307 		/*
15308 		 * pmode is logical and ST_BSF is not set.
15309 		 * The LONG_POS read position contains the fileno.
15310 		 * If the read position works, rewind and space.
15311 		 */
15312 		} else if (un->un_read_pos_type == LONG_POS) {
15313 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15314 			if (rval) {
15315 				/*
15316 				 * We didn't get the file position from the
15317 				 * read position command.
15318 				 * We are going to trust the drive to backspace
15319 				 * and then position after the filemark.
15320 				 */
15321 				rval = st_space_to_begining_of_file(un);
15322 			}
15323 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15324 			    32, (caddr_t)un->un_read_pos_data, 0);
15325 			if ((rval) && (un->un_pos.pmode == invalid)) {
15326 				rval = st_space_to_begining_of_file(un);
15327 			} else {
15328 				rval = st_scenic_route_to_begining_of_file(un,
15329 				    un->un_pos.fileno);
15330 			}
15331 		} else {
15332 			rval = EIO;
15333 		}
15334 		/*
15335 		 * If something didn't work we are lost
15336 		 */
15337 		if (rval != 0) {
15338 			un->un_pos.pmode = invalid;
15339 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15340 			    "st_mtioctop : EIO : fspace pmode invalid");
15341 
15342 			rval = EIO;
15343 		}
15344 
15345 	} else {
15346 		rval = st_space_fmks(un, count);
15347 	}
15348 
15349 	if (rval != EIO && count < 0) {
15350 		/*
15351 		 * we came here with a count < 0; we now need
15352 		 * to skip back to end up before the filemark
15353 		 */
15354 		rval = st_backward_space_files(un, 1, 1);
15355 	}
15356 
15357 	return (rval);
15358 }
15359 
15360 static int
15361 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15362 {
15363 	int rval;
15364 
15365 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15366 
15367 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15368 		rval = EIO;
15369 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15370 		rval = EIO;
15371 	}
15372 
15373 	return (rval);
15374 }
15375 
15376 static int
15377 st_space_to_begining_of_file(struct scsi_tape *un)
15378 {
15379 	int rval;
15380 
15381 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15382 
15383 	/*
15384 	 * Back space of the file at the begining of the file.
15385 	 */
15386 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15387 	if (rval) {
15388 		rval = EIO;
15389 		return (rval);
15390 	}
15391 
15392 	/*
15393 	 * Other interesting answers might be crashed BOT which isn't bad.
15394 	 */
15395 	if (un->un_status == SUN_KEY_BOT) {
15396 		return (rval);
15397 	}
15398 
15399 	un->un_running.pmode = invalid;
15400 
15401 	/*
15402 	 * Now we are on the BOP side of the filemark. Forward space to
15403 	 * the EOM side and we are at the begining of the file.
15404 	 */
15405 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15406 	if (rval) {
15407 		rval = EIO;
15408 	}
15409 
15410 	return (rval);
15411 }
15412 
15413 static int
15414 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15415 {
15416 
15417 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15418 
15419 	/*
15420 	 * forward space to inter-record gap
15421 	 *
15422 	 */
15423 
15424 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15425 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15426 
15427 	if (un->un_pos.pmode == legacy) {
15428 		/*
15429 		 * If were are at end of tape and count is forward.
15430 		 * Return blank check.
15431 		 */
15432 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15433 			/* we're at EOM */
15434 			un->un_err_resid = count;
15435 			un->un_status = KEY_BLANK_CHECK;
15436 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15437 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15438 			return (EIO);
15439 		}
15440 
15441 		/*
15442 		 * If count is zero there is nothing to do.
15443 		 */
15444 		if (count == 0) {
15445 			un->un_err_pos.fileno = un->un_pos.fileno;
15446 			un->un_err_pos.blkno = un->un_pos.blkno;
15447 			un->un_err_resid = 0;
15448 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15449 				un->un_status = SUN_KEY_EOF;
15450 			}
15451 			return (0);
15452 		}
15453 
15454 		/*
15455 		 * physical tape position may not be what we've been
15456 		 * telling the user; adjust the position accordingly
15457 		 */
15458 		if (IN_EOF(un->un_pos)) {
15459 			daddr_t blkno = un->un_pos.blkno;
15460 			int fileno = un->un_pos.fileno;
15461 
15462 			optype lastop = un->un_lastop;
15463 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15464 			    == -1) {
15465 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15466 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15467 				return (EIO);
15468 			}
15469 
15470 			un->un_pos.blkno = blkno;
15471 			un->un_pos.fileno = fileno;
15472 			un->un_lastop = lastop;
15473 		}
15474 	}
15475 
15476 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15477 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15478 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15479 		return (EIO);
15480 	}
15481 
15482 	return (st_space_records(un, count));
15483 }
15484 
15485 static int
15486 st_space_records(struct scsi_tape *un, int64_t count)
15487 {
15488 	int64_t dblk;
15489 	int rval = 0;
15490 
15491 	ST_FUNC(ST_DEVINFO, st_space_records);
15492 
15493 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15494 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15495 	    count, un->un_pos.eof);
15496 
15497 	if (un->un_pos.pmode == logical) {
15498 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15499 		if (rval != 0) {
15500 			rval = EIO;
15501 		}
15502 		return (rval);
15503 	}
15504 
15505 	dblk = count + un->un_pos.blkno;
15506 
15507 	/* Already there */
15508 	if (dblk == un->un_pos.blkno) {
15509 		un->un_err_resid = 0;
15510 		COPY_POS(&un->un_err_pos, &un->un_pos);
15511 		return (0);
15512 	}
15513 
15514 	/*
15515 	 * If the destination block is forward
15516 	 * or the drive will backspace records.
15517 	 */
15518 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15519 		/*
15520 		 * If we're spacing forward, or the device can
15521 		 * backspace records, we can just use the SPACE
15522 		 * command.
15523 		 */
15524 		dblk -= un->un_pos.blkno;
15525 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15526 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15527 			    "st_space_records:EIO:space_records can't spc");
15528 			rval = EIO;
15529 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15530 			/*
15531 			 * check if we hit BOT/EOT
15532 			 */
15533 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15534 				un->un_status = SUN_KEY_BOT;
15535 				un->un_pos.eof = ST_NO_EOF;
15536 			} else if (dblk < 0 &&
15537 			    un->un_pos.eof == ST_EOF_PENDING) {
15538 				int residue = un->un_err_resid;
15539 				/*
15540 				 * we skipped over a filemark
15541 				 * and need to go forward again
15542 				 */
15543 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15544 					ST_DEBUG2(ST_DEVINFO, st_label,
15545 					    SCSI_DEBUG, "st_space_records: EIO"
15546 					    " : can't space #2");
15547 					rval = EIO;
15548 				}
15549 				un->un_err_resid = residue;
15550 			}
15551 			if (rval == 0) {
15552 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15553 				    "st_space_records: EIO : space_rec rval"
15554 				    " == 0");
15555 				rval = EIO;
15556 			}
15557 		}
15558 	} else {
15559 		/*
15560 		 * else we rewind, space forward across filemarks to
15561 		 * the desired file, and then space records to the
15562 		 * desired block.
15563 		 */
15564 
15565 		int dfile = un->un_pos.fileno;	/* save current file */
15566 
15567 		if (dblk < 0) {
15568 			/*
15569 			 * Wups - we're backing up over a filemark
15570 			 */
15571 			if (un->un_pos.blkno != 0 &&
15572 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15573 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15574 				un->un_pos.pmode = invalid;
15575 			}
15576 			un->un_err_resid = -dblk;
15577 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15578 				un->un_status = SUN_KEY_BOT;
15579 				un->un_pos.eof = ST_NO_EOF;
15580 			} else if (un->un_pos.fileno > 0) {
15581 				un->un_status = SUN_KEY_EOF;
15582 				un->un_pos.eof = ST_NO_EOF;
15583 			}
15584 			COPY_POS(&un->un_err_pos, &un->un_pos);
15585 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15586 			    "st_space_records:EIO:space_records : dblk < 0");
15587 			rval = EIO;
15588 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15589 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15590 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15591 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15592 			    "st_space_records: EIO :space_records : rewind "
15593 			    "and space failed");
15594 			un->un_pos.pmode = invalid;
15595 			rval = EIO;
15596 		}
15597 	}
15598 
15599 	return (rval);
15600 }
15601 
15602 static int
15603 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15604 {
15605 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15606 
15607 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15608 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15609 	/*
15610 	 * backward space of file filemark (1/2" and 8mm)
15611 	 * tape position will end on the beginning of tape side
15612 	 * of the desired file mark
15613 	 */
15614 	if ((un->un_dp->options & ST_BSF) == 0) {
15615 		return (ENOTTY);
15616 	}
15617 
15618 	if (un->un_pos.pmode == legacy) {
15619 
15620 		/*
15621 		 * If a negative count (which implies a forward space op)
15622 		 * is specified, and we're at logical or physical eot,
15623 		 * bounce the request.
15624 		 */
15625 
15626 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15627 			un->un_err_resid = files;
15628 			un->un_status = SUN_KEY_EOT;
15629 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15630 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15631 			return (EIO);
15632 		}
15633 		/*
15634 		 * physical tape position may not be what we've been
15635 		 * telling the user; adjust the request accordingly
15636 		 */
15637 		if (IN_EOF(un->un_pos)) {
15638 			un->un_pos.fileno++;
15639 			un->un_pos.blkno = 0;
15640 			files++;
15641 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15642 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15643 			    files, MTBSF);
15644 
15645 		}
15646 	}
15647 
15648 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15649 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15650 		    "st_ioctl : EIO : MTBSF : check den wfm");
15651 		return (EIO);
15652 	}
15653 
15654 	if (files <= 0) {
15655 		/*
15656 		 * for a negative count, we need to step forward
15657 		 * first and then step back again
15658 		 */
15659 		files = -files + 1;
15660 		return (st_forward_space_files(un, files));
15661 	}
15662 	return (st_backward_space_files(un, files, 1));
15663 }
15664 
15665 static int
15666 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15667 {
15668 	int64_t end_fileno;
15669 	int64_t skip_cnt;
15670 	int rval = 0;
15671 
15672 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15673 
15674 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15675 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15676 	    count, un->un_pos.eof);
15677 	/*
15678 	 * Backspace files (MTNBSF): infront == 0
15679 	 *
15680 	 *	For tapes that can backspace, backspace
15681 	 *	count+1 filemarks and then run forward over
15682 	 *	a filemark
15683 	 *
15684 	 *	For tapes that can't backspace,
15685 	 *		calculate desired filenumber
15686 	 *		(un->un_pos.fileno - count), rewind,
15687 	 *		and then space forward this amount
15688 	 *
15689 	 * Backspace filemarks (MTBSF) infront == 1
15690 	 *
15691 	 *	For tapes that can backspace, backspace count
15692 	 *	filemarks
15693 	 *
15694 	 *	For tapes that can't backspace, calculate
15695 	 *	desired filenumber (un->un_pos.fileno - count),
15696 	 *	add 1, rewind, space forward this amount,
15697 	 *	and mark state as ST_EOF_PENDING appropriately.
15698 	 */
15699 
15700 	if (un->un_pos.pmode == logical) {
15701 
15702 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15703 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15704 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15705 		    un->un_pos.lgclblkno);
15706 
15707 
15708 		/* In case a drive that won't back space gets in logical mode */
15709 		if ((un->un_dp->options & ST_BSF) == 0) {
15710 			rval = EIO;
15711 			return (rval);
15712 		}
15713 		if ((infront == 1) &&
15714 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15715 			rval = EIO;
15716 			return (rval);
15717 		} else if ((infront == 0) &&
15718 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15719 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15720 			rval = EIO;
15721 			return (rval);
15722 		}
15723 		return (rval);
15724 	}
15725 
15726 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15727 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15728 	    "fileno=%x blkno=%x\n",
15729 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15730 
15731 
15732 
15733 	/*
15734 	 * Handle the simple case of BOT
15735 	 * playing a role in these cmds.
15736 	 * We do this by calculating the
15737 	 * ending file number. If the ending
15738 	 * file is < BOT, rewind and set an
15739 	 * error and mark resid appropriately.
15740 	 * If we're backspacing a file (not a
15741 	 * filemark) and the target file is
15742 	 * the first file on the tape, just
15743 	 * rewind.
15744 	 */
15745 
15746 	/* figure expected destination of this SPACE command */
15747 	end_fileno = un->un_pos.fileno - count;
15748 
15749 	/*
15750 	 * Would the end effect of this SPACE be the same as rewinding?
15751 	 * If so just rewind instead.
15752 	 */
15753 	if ((infront != 0) && (end_fileno < 0) ||
15754 	    (infront == 0) && (end_fileno <= 0)) {
15755 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15756 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15757 			    "st_backward_space_files: EIO : "
15758 			    "rewind in lou of BSF failed\n");
15759 			rval = EIO;
15760 		}
15761 		if (end_fileno < 0) {
15762 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15763 			    "st_backward_space_files: EIO : "
15764 			    "back space file greater then fileno\n");
15765 			rval = EIO;
15766 			un->un_err_resid = -end_fileno;
15767 			un->un_status = SUN_KEY_BOT;
15768 		}
15769 		return (rval);
15770 	}
15771 
15772 	if (un->un_dp->options & ST_BSF) {
15773 		skip_cnt = 1 - infront;
15774 		/*
15775 		 * If we are going to end up at the beginning
15776 		 * of the file, we have to space one extra file
15777 		 * first, and then space forward later.
15778 		 */
15779 		end_fileno = -(count + skip_cnt);
15780 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15781 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15782 		    skip_cnt, end_fileno);
15783 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15784 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15785 			    "st_backward_space_files:EIO:back space fm failed");
15786 			rval = EIO;
15787 		}
15788 	} else {
15789 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15790 			rval = EIO;
15791 		} else {
15792 			skip_cnt = end_fileno + infront;
15793 		}
15794 	}
15795 
15796 	/*
15797 	 * If we have to space forward, do so...
15798 	 */
15799 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15800 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15801 
15802 	if (rval == 0 && skip_cnt) {
15803 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15804 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15805 			    "st_backward_space_files:EIO:space fm skip count");
15806 			rval = EIO;
15807 		} else if (infront) {
15808 			/*
15809 			 * If we had to space forward, and we're
15810 			 * not a tape that can backspace, mark state
15811 			 * as if we'd just seen a filemark during a
15812 			 * a read.
15813 			 */
15814 			if ((un->un_dp->options & ST_BSF) == 0) {
15815 				un->un_pos.eof = ST_EOF_PENDING;
15816 				un->un_pos.fileno -= 1;
15817 				un->un_pos.blkno = LASTBLK;
15818 				un->un_running.pmode = invalid;
15819 			}
15820 		}
15821 	}
15822 
15823 	if (rval != 0) {
15824 		un->un_pos.pmode = invalid;
15825 	}
15826 
15827 	return (rval);
15828 }
15829 
15830 static int
15831 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15832 {
15833 	int rval;
15834 
15835 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15836 
15837 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15838 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15839 
15840 	if (un->un_pos.pmode == legacy) {
15841 		/*
15842 		 * backward space file to beginning of file
15843 		 *
15844 		 * If a negative count (which implies a forward space op)
15845 		 * is specified, and we're at logical or physical eot,
15846 		 * bounce the request.
15847 		 */
15848 
15849 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15850 			un->un_err_resid = count;
15851 			un->un_status = SUN_KEY_EOT;
15852 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15853 			    "st_ioctl : EIO : > EOT and count < 0");
15854 			return (EIO);
15855 		}
15856 		/*
15857 		 * physical tape position may not be what we've been
15858 		 * telling the user; adjust the request accordingly
15859 		 */
15860 		if (IN_EOF(un->un_pos)) {
15861 			un->un_pos.fileno++;
15862 			un->un_pos.blkno = 0;
15863 			count++;
15864 		}
15865 	}
15866 
15867 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15868 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15869 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15870 		return (EIO);
15871 	}
15872 
15873 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15874 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15875 
15876 	if (count <= 0) {
15877 		rval = st_forward_space_files(un, -count);
15878 	} else {
15879 		rval = st_backward_space_files(un, count, 0);
15880 	}
15881 	return (rval);
15882 }
15883 
15884 static int
15885 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15886 {
15887 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15888 
15889 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15890 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15891 
15892 	if (un->un_pos.pmode == legacy) {
15893 		/*
15894 		 * backward space into inter-record gap
15895 		 *
15896 		 * If a negative count (which implies a forward space op)
15897 		 * is specified, and we're at logical or physical eot,
15898 		 * bounce the request.
15899 		 */
15900 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15901 			un->un_err_resid = num;
15902 			un->un_status = SUN_KEY_EOT;
15903 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15904 			    "st_ioctl : EIO : MTBSR > EOT");
15905 			return (EIO);
15906 		}
15907 
15908 		if (num == 0) {
15909 			COPY_POS(&un->un_err_pos, &un->un_pos);
15910 			un->un_err_resid = 0;
15911 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15912 				un->un_status = SUN_KEY_EOF;
15913 			}
15914 			return (0);
15915 		}
15916 
15917 		/*
15918 		 * physical tape position may not be what we've been
15919 		 * telling the user; adjust the position accordingly.
15920 		 * bsr can not skip filemarks and continue to skip records
15921 		 * therefore if we are logically before the filemark but
15922 		 * physically at the EOT side of the filemark, we need to step
15923 		 * back; this allows fsr N where N > number of blocks in file
15924 		 * followed by bsr 1 to position at the beginning of last block
15925 		 */
15926 		if (IN_EOF(un->un_pos)) {
15927 			tapepos_t save;
15928 			optype lastop = un->un_lastop;
15929 
15930 			COPY_POS(&save, &un->un_pos);
15931 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15932 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15933 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15934 				return (EIO);
15935 			}
15936 
15937 			COPY_POS(&un->un_pos, &save);
15938 			un->un_lastop = lastop;
15939 		}
15940 	}
15941 
15942 	un->un_pos.eof = ST_NO_EOF;
15943 
15944 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15945 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15946 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15947 		return (EIO);
15948 	}
15949 
15950 	num = -num;
15951 	return (st_space_records(un, num));
15952 }
15953 
15954 static int
15955 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15956 {
15957 	int rval;
15958 
15959 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15960 
15961 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15962 	if (rval == 0) {
15963 		un->un_pos.pmode = logical;
15964 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15965 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15966 		/*
15967 		 * Drive says invalid field in cdb.
15968 		 * Doesn't like space multiple. Position isn't lost.
15969 		 */
15970 		un->un_err_resid = cnt;
15971 		un->un_status = 0;
15972 		rval = ENOTTY;
15973 	} else {
15974 		un->un_err_resid = cnt;
15975 		un->un_pos.pmode = invalid;
15976 	}
15977 	return (rval);
15978 }
15979 
15980 static int
15981 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15982 {
15983 	int rval;
15984 
15985 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15986 
15987 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15988 	if (rval == 0) {
15989 		un->un_pos.pmode = logical;
15990 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15991 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15992 		/*
15993 		 * Drive says invalid field in cdb.
15994 		 * Doesn't like space multiple. Position isn't lost.
15995 		 */
15996 		un->un_err_resid = cnt;
15997 		un->un_status = 0;
15998 		rval = ENOTTY;
15999 	} else {
16000 		un->un_err_resid = cnt;
16001 		un->un_pos.pmode = invalid;
16002 	}
16003 	return (rval);
16004 }
16005 
16006 #ifdef	__x86
16007 
16008 /*
16009  * release contig_mem and wake up waiting thread, if any
16010  */
16011 static void
16012 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
16013 {
16014 	mutex_enter(ST_MUTEX);
16015 
16016 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
16017 
16018 	cp->cm_next = un->un_contig_mem;
16019 	un->un_contig_mem = cp;
16020 	un->un_contig_mem_available_num++;
16021 	cv_broadcast(&un->un_contig_mem_cv);
16022 
16023 	mutex_exit(ST_MUTEX);
16024 }
16025 
16026 /*
16027  * St_get_contig_mem will return a contig_mem if there is one available
16028  * in current system. Otherwise, it will try to alloc one, if the total
16029  * number of contig_mem is within st_max_contig_mem_num.
16030  * It will sleep, if allowed by caller or return NULL, if no contig_mem
16031  * is available for now.
16032  */
16033 static struct contig_mem *
16034 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
16035 {
16036 	size_t rlen;
16037 	struct contig_mem *cp = NULL;
16038 	ddi_acc_handle_t acc_hdl;
16039 	caddr_t addr;
16040 	int big_enough = 0;
16041 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
16042 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
16043 
16044 	/* Try to get one available contig_mem */
16045 	mutex_enter(ST_MUTEX);
16046 
16047 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
16048 
16049 	if (un->un_contig_mem_available_num > 0) {
16050 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16051 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
16052 		/*
16053 		 * we failed to get one. we're going to
16054 		 * alloc one more contig_mem for this I/O
16055 		 */
16056 		mutex_exit(ST_MUTEX);
16057 		cp = (struct contig_mem *)kmem_zalloc(
16058 		    sizeof (struct contig_mem) + biosize(),
16059 		    alloc_flags);
16060 		if (cp == NULL) {
16061 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16062 			    "alloc contig_mem failure\n");
16063 			return (NULL); /* cannot get one */
16064 		}
16065 		cp->cm_bp = (struct buf *)
16066 		    (((caddr_t)cp) + sizeof (struct contig_mem));
16067 		bioinit(cp->cm_bp);
16068 		mutex_enter(ST_MUTEX);
16069 		un->un_contig_mem_total_num++; /* one more available */
16070 	} else {
16071 		/*
16072 		 * we failed to get one and we're NOT allowed to
16073 		 * alloc more contig_mem
16074 		 */
16075 		if (alloc_flags == KM_SLEEP) {
16076 			while (un->un_contig_mem_available_num <= 0) {
16077 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16078 			}
16079 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16080 		} else {
16081 			mutex_exit(ST_MUTEX);
16082 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16083 			    "alloc contig_mem failure\n");
16084 			return (NULL); /* cannot get one */
16085 		}
16086 	}
16087 	mutex_exit(ST_MUTEX);
16088 
16089 	/* We need to check if this block of mem is big enough for this I/O */
16090 	if (cp->cm_len < len) {
16091 		/* not big enough, need to alloc a new one */
16092 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16093 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16094 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16095 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16096 			    "alloc contig_mem failure: not enough mem\n");
16097 			st_release_contig_mem(un, cp);
16098 			cp = NULL;
16099 		} else {
16100 			if (cp->cm_addr) {
16101 				/* release previous one before attach new one */
16102 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16103 			}
16104 			mutex_enter(ST_MUTEX);
16105 			un->un_max_contig_mem_len =
16106 			    un->un_max_contig_mem_len >= len ?
16107 			    un->un_max_contig_mem_len : len;
16108 			mutex_exit(ST_MUTEX);
16109 
16110 			/* attach new mem to this cp */
16111 			cp->cm_addr = addr;
16112 			cp->cm_acc_hdl = acc_hdl;
16113 			cp->cm_len = len;
16114 
16115 			goto alloc_ok; /* get one usable cp */
16116 		}
16117 	} else {
16118 		goto alloc_ok; /* get one usable cp */
16119 	}
16120 
16121 	/* cannot find/alloc a usable cp, when we get here */
16122 
16123 	mutex_enter(ST_MUTEX);
16124 	if ((un->un_max_contig_mem_len < len) ||
16125 	    (alloc_flags != KM_SLEEP)) {
16126 		mutex_exit(ST_MUTEX);
16127 		return (NULL);
16128 	}
16129 
16130 	/*
16131 	 * we're allowed to sleep, and there is one big enough
16132 	 * contig mem in the system, which is currently in use,
16133 	 * wait for it...
16134 	 */
16135 	big_enough = 1;
16136 	do {
16137 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16138 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16139 	} while (cp == NULL);
16140 	mutex_exit(ST_MUTEX);
16141 
16142 	/* we get the big enough contig mem, finally */
16143 
16144 alloc_ok:
16145 	/* init bp attached to this cp */
16146 	bioreset(cp->cm_bp);
16147 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16148 	cp->cm_bp->b_private = (void *)cp;
16149 
16150 	return (cp);
16151 }
16152 
16153 /*
16154  * this is the biodone func for the bp used in big block I/O
16155  */
16156 static int
16157 st_bigblk_xfer_done(struct buf *bp)
16158 {
16159 	struct contig_mem *cp;
16160 	struct buf *orig_bp;
16161 	int ioerr;
16162 	struct scsi_tape *un;
16163 
16164 	/* sanity check */
16165 	if (bp == NULL) {
16166 		return (DDI_FAILURE);
16167 	}
16168 
16169 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16170 	if (un == NULL) {
16171 		return (DDI_FAILURE);
16172 	}
16173 
16174 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16175 
16176 	cp = (struct contig_mem *)bp->b_private;
16177 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16178 	cp->cm_bp = bp;
16179 
16180 	/* special handling for special I/O */
16181 	if (cp->cm_use_sbuf) {
16182 #ifndef __lock_lint
16183 		ASSERT(un->un_sbuf_busy);
16184 #endif
16185 		un->un_sbufp = orig_bp;
16186 		cp->cm_use_sbuf = 0;
16187 	}
16188 
16189 	orig_bp->b_resid = bp->b_resid;
16190 	ioerr = geterror(bp);
16191 	if (ioerr != 0) {
16192 		bioerror(orig_bp, ioerr);
16193 	} else if (orig_bp->b_flags & B_READ) {
16194 		/* copy data back to original bp */
16195 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16196 		    bp->b_bcount - bp->b_resid);
16197 	}
16198 
16199 	st_release_contig_mem(un, cp);
16200 
16201 	biodone(orig_bp);
16202 
16203 	return (DDI_SUCCESS);
16204 }
16205 
16206 /*
16207  * We use this func to replace original bp that may not be able to do I/O
16208  * in big block size with one that can
16209  */
16210 static struct buf *
16211 st_get_bigblk_bp(struct buf *bp)
16212 {
16213 	struct contig_mem *cp;
16214 	struct scsi_tape *un;
16215 	struct buf *cont_bp;
16216 
16217 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16218 	if (un == NULL) {
16219 		return (bp);
16220 	}
16221 
16222 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16223 
16224 	/* try to get one contig_mem */
16225 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16226 	if (!cp) {
16227 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16228 		    "Cannot alloc contig buf for I/O for %lu blk size",
16229 		    bp->b_bcount);
16230 		return (bp);
16231 	}
16232 	cont_bp = cp->cm_bp;
16233 	cp->cm_bp = bp;
16234 
16235 	/* make sure that we "are" using un_sbufp for special I/O */
16236 	if (bp == un->un_sbufp) {
16237 #ifndef __lock_lint
16238 		ASSERT(un->un_sbuf_busy);
16239 #endif
16240 		un->un_sbufp = cont_bp;
16241 		cp->cm_use_sbuf = 1;
16242 	}
16243 
16244 	/* clone bp */
16245 	cont_bp->b_bcount = bp->b_bcount;
16246 	cont_bp->b_resid = bp->b_resid;
16247 	cont_bp->b_iodone = st_bigblk_xfer_done;
16248 	cont_bp->b_file = bp->b_file;
16249 	cont_bp->b_offset = bp->b_offset;
16250 	cont_bp->b_dip = bp->b_dip;
16251 	cont_bp->b_error = 0;
16252 	cont_bp->b_proc = NULL;
16253 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16254 	cont_bp->b_shadow = NULL;
16255 	cont_bp->b_pages = NULL;
16256 	cont_bp->b_edev = bp->b_edev;
16257 	cont_bp->b_dev = bp->b_dev;
16258 	cont_bp->b_lblkno = bp->b_lblkno;
16259 	cont_bp->b_forw = bp->b_forw;
16260 	cont_bp->b_back = bp->b_back;
16261 	cont_bp->av_forw = bp->av_forw;
16262 	cont_bp->av_back = bp->av_back;
16263 	cont_bp->b_bufsize = bp->b_bufsize;
16264 
16265 	/* get data in original bp */
16266 	if (bp->b_flags & B_WRITE) {
16267 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16268 	}
16269 
16270 	return (cont_bp);
16271 }
16272 #else
16273 #ifdef __lock_lint
16274 static int
16275 st_bigblk_xfer_done(struct buf *bp)
16276 {
16277 	return (0);
16278 }
16279 #endif
16280 #endif
16281 
16282 static const char *eof_status[] =
16283 {
16284 	"NO_EOF",
16285 	"EOF_PENDING",
16286 	"EOF",
16287 	"EOT_PENDING",
16288 	"EOT",
16289 	"EOM",
16290 	"AFTER_EOM"
16291 };
16292 static const char *mode[] = {
16293 	"invalid",
16294 	"legacy",
16295 	"logical"
16296 };
16297 
16298 static void
16299 st_print_position(dev_info_t *dev, char *label, uint_t level,
16300 const char *comment, tapepos_t *pos)
16301 {
16302 	ST_FUNC(dev, st_print_position);
16303 
16304 	scsi_log(dev, label, level,
16305 	    "%s Position data:\n", comment);
16306 	scsi_log(dev, label, CE_CONT,
16307 	    "Positioning mode = %s", mode[pos->pmode]);
16308 	scsi_log(dev, label, CE_CONT,
16309 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16310 	scsi_log(dev, label, CE_CONT,
16311 	    "File Number      = 0x%x", pos->fileno);
16312 	scsi_log(dev, label, CE_CONT,
16313 	    "Block Number     = 0x%x", pos->blkno);
16314 	scsi_log(dev, label, CE_CONT,
16315 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16316 	scsi_log(dev, label, CE_CONT,
16317 	    "Partition Number = 0x%x", pos->partition);
16318 }
16319 static int
16320 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16321 {
16322 
16323 	int result = 0;
16324 	int i;
16325 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16326 
16327 	/*
16328 	 * find non alpha numeric working from the end.
16329 	 */
16330 	for (i = size - 1; i >= 0; i--) {
16331 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16332 			data[i] = 0;
16333 			size = i;
16334 		}
16335 	}
16336 
16337 	if (size == 1) {
16338 		/*
16339 		 * Drive seems to think its returning useful data
16340 		 * but it looks like all junk
16341 		 */
16342 		return (result);
16343 	}
16344 
16345 	size++;
16346 
16347 	/*
16348 	 * Actually got a valid serial number.
16349 	 * If never stored one before alloc space for it.
16350 	 */
16351 	if (un->un_media_id_len == 0) {
16352 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16353 		un->un_media_id_len = size;
16354 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16355 		un->un_media_id[min(size, strlen(data))] = 0;
16356 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16357 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16358 	} else if (size > un->un_media_id_len) {
16359 		if (strncmp(un->un_media_id, data, size) != 0) {
16360 			result = ESPIPE;
16361 		}
16362 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16363 		    "Longer Media Id old ID:%s new ID:%s\n",
16364 		    un->un_media_id, data);
16365 		kmem_free(un->un_media_id, un->un_media_id_len);
16366 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16367 		un->un_media_id_len = size;
16368 		(void) strncpy(un->un_media_id, data, size);
16369 		un->un_media_id[size] = 0;
16370 	} else if (strncmp(data, un->un_media_id,
16371 	    min(size, un->un_media_id_len)) != 0) {
16372 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16373 		    "Old Media Id %s length = %d New %s length = %d\n",
16374 		    un->un_media_id, un->un_media_id_len, data, size);
16375 		bzero(un->un_media_id, un->un_media_id_len);
16376 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16377 		un->un_media_id[min(size, strlen(data))] = 0;
16378 		result = ESPIPE;
16379 	} else {
16380 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16381 		    "Media Id still %s\n", un->un_media_id);
16382 	}
16383 
16384 	ASSERT(strlen(un->un_media_id) <= size);
16385 
16386 	return (result);
16387 }
16388 #define	ID_SIZE 32
16389 typedef struct
16390 {
16391 	uchar_t avilable_data0;
16392 	uchar_t avilable_data1;
16393 	uchar_t avilable_data2;
16394 	uchar_t avilable_data3;
16395 	uchar_t attribute_msb;
16396 	uchar_t attribute_lsb;
16397 #ifdef _BIT_FIELDS_LTOH
16398 	uchar_t format		: 2,
16399 				: 5,
16400 		read_only	: 1;
16401 #else
16402 	uchar_t read_only	: 1,
16403 				: 5,
16404 		format		: 2;
16405 #endif
16406 	uchar_t attribute_len_msb;
16407 	uchar_t attribute_len_lsb;
16408 }attribute_header;
16409 
16410 typedef struct {
16411 	attribute_header header;
16412 	char data[1];
16413 }mam_attribute;
16414 
16415 static int
16416 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16417 {
16418 	int result;
16419 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16420 	int i;
16421 	uchar_t byte;
16422 	char *format;
16423 	uchar_t *data = (uchar_t *)pnt;
16424 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16425 
16426 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16427 
16428 	(void) sprintf(buf, "0x");
16429 	for (i = 0; i < size; i++) {
16430 		byte = data[i];
16431 		if (byte < 0x10)
16432 			format = "0%x";
16433 		else
16434 			format = "%x";
16435 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16436 	}
16437 	result = st_check_if_media_changed(un, buf, newsize);
16438 
16439 	kmem_free(buf, newsize);
16440 
16441 	return (result);
16442 }
16443 
16444 
16445 static int
16446 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16447 {
16448 	int result;
16449 	mam_attribute *buffer;
16450 	int size;
16451 	int newsize;
16452 
16453 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16454 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16455 again:
16456 	buffer = kmem_zalloc(size, KM_SLEEP);
16457 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16458 	if (result == 0) {
16459 
16460 		newsize = (buffer->header.attribute_len_msb << 8) |
16461 		    buffer->header.attribute_len_lsb;
16462 
16463 		if (newsize + sizeof (attribute_header) > size) {
16464 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16465 			    "resizing read attribute data from %d to %d format"
16466 			    " %d\n", size, (int)sizeof (attribute_header) +
16467 			    newsize, buffer->header.format);
16468 			kmem_free(buffer, size);
16469 			size = newsize + sizeof (attribute_header);
16470 			goto again;
16471 		}
16472 
16473 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16474 		if (buffer->header.format == 0) {
16475 			result =
16476 			    st_handle_hex_media_id(un, buffer->data, newsize);
16477 		} else {
16478 			result = st_check_if_media_changed(un, buffer->data,
16479 			    newsize);
16480 		}
16481 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16482 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16483 		    "Read Attribute Command for Media Identification is not "
16484 		    "supported on the HBA that this drive is attached to.");
16485 		result = ENOTTY;
16486 	}
16487 
16488 	kmem_free(buffer, size);
16489 	un->un_status = 0;
16490 
16491 	return (result);
16492 }
16493 
16494 
16495 static int
16496 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16497 {
16498 	char cdb[CDB_GROUP5];
16499 	struct uscsi_cmd *ucmd;
16500 	struct scsi_extended_sense sense;
16501 	int rval;
16502 	int size = max(un->un_media_id_len, ID_SIZE);
16503 	caddr_t buf;
16504 
16505 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16506 
16507 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16508 		return (ENOTTY);
16509 	}
16510 
16511 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16512 upsize:
16513 	buf = kmem_alloc(size, KM_SLEEP);
16514 
16515 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16516 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16517 	cdb[2] = 0;
16518 	cdb[3] = 0;
16519 	cdb[4] = 0;
16520 	cdb[5] = 0;
16521 	cdb[6] = (char)(size >> 24);
16522 	cdb[7] = (char)(size >> 16);
16523 	cdb[8] = (char)(size >> 8);
16524 	cdb[9] = (char)(size);
16525 	cdb[10] = 0;
16526 	cdb[11] = 0;
16527 
16528 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16529 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16530 	ucmd->uscsi_cdb = &cdb[0];
16531 	ucmd->uscsi_cdblen = sizeof (cdb);
16532 	ucmd->uscsi_bufaddr = buf;
16533 	ucmd->uscsi_buflen = size;
16534 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16535 	ucmd->uscsi_rqlen = sizeof (sense);
16536 
16537 	rval = bufunc(un, ucmd, FKIOCTL);
16538 
16539 	if (rval || ucmd->uscsi_status != 0) {
16540 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16541 		    "media serial command returned %d scsi_status %d"
16542 		    " rqstatus %d", rval, ucmd->uscsi_status,
16543 		    ucmd->uscsi_rqstatus);
16544 		/*
16545 		 * If this returns invalid operation code don't try again.
16546 		 */
16547 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16548 		    sense.es_add_code == 0x20) {
16549 			rval = ENOTTY;
16550 		} else if (rval == 0) {
16551 			rval = EIO;
16552 		}
16553 		un->un_status = 0;
16554 	} else {
16555 		int act_size;
16556 
16557 		/*
16558 		 * get reported size.
16559 		 */
16560 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16561 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16562 
16563 		/* documentation says mod 4. */
16564 		while (act_size & 3) {
16565 			act_size++;
16566 		}
16567 
16568 		/*
16569 		 * If reported size is larger that we our buffer.
16570 		 * Free the old one and allocate one that is larger
16571 		 * enough and re-issuse the command.
16572 		 */
16573 		if (act_size + 4 > size) {
16574 			kmem_free(buf, size);
16575 			size = act_size + 4;
16576 			goto upsize;
16577 		}
16578 
16579 		if (act_size == 0) {
16580 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16581 			    "media serial number is not available");
16582 			un->un_status = 0;
16583 			rval = 0;
16584 		} else {
16585 			/*
16586 			 * set data pointer to point to the start
16587 			 * of that serial number.
16588 			 */
16589 			un->un_media_id_method =
16590 			    st_get_media_id_via_media_serial_cmd;
16591 			rval =
16592 			    st_check_if_media_changed(un, &buf[4], act_size);
16593 		}
16594 	}
16595 
16596 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16597 	kmem_free(buf, size);
16598 
16599 	return (rval);
16600 }
16601 
16602 
16603 /* ARGSUSED */
16604 static int
16605 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16606 {
16607 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16608 
16609 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16610 	ASSERT(un->un_media_id_len == 0);
16611 	un->un_media_id = (char *)bogusID;
16612 	un->un_media_id_len = 0;
16613 	return (0);
16614 }
16615 
16616 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16617 
16618 media_chk_function media_chk_functions[] = {
16619 	st_get_media_id_via_media_serial_cmd,
16620 	st_get_media_id_via_read_attribute,
16621 	st_bogus_media_id
16622 };
16623 
16624 static int
16625 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16626 {
16627 	int result = 0;
16628 	int i;
16629 
16630 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16631 
16632 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16633 		if (result == ENOTTY) {
16634 			/*
16635 			 * Last operation type not supported by this device.
16636 			 * Make so next time it doesn`t do that again.
16637 			 */
16638 			un->un_media_id_method = media_chk_functions[i];
16639 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16640 		    un->un_media_id_method != st_get_media_identification) {
16641 			continue;
16642 		}
16643 		result = media_chk_functions[i](un, bufunc);
16644 		/*
16645 		 * If result indicates the function was successful or
16646 		 * that the media is not the same as last known, break.
16647 		 */
16648 		if (result == 0 || result == ESPIPE) {
16649 			break;
16650 		}
16651 	}
16652 
16653 	return (result);
16654 }
16655 
16656 static errstate
16657 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16658     errstate onentry)
16659 {
16660 
16661 	int ret;
16662 	st_err_info *errinfo;
16663 	recov_info *ri = (recov_info *)pkt->pkt_private;
16664 
16665 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16666 
16667 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16668 
16669 	ASSERT(un->un_recov_buf_busy == 0);
16670 
16671 	/*
16672 	 * Don't try and recover a reset that this device sent.
16673 	 */
16674 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16675 	    onentry == DEVICE_RESET) {
16676 		return (COMMAND_DONE_ERROR);
16677 	}
16678 
16679 	/*
16680 	 * See if expected position was passed with scsi_pkt.
16681 	 */
16682 	if (ri->privatelen == sizeof (recov_info)) {
16683 
16684 		/*
16685 		 * Not for this command.
16686 		 */
16687 		if (ri->cmd_attrib->do_not_recover) {
16688 			return (COMMAND_DONE_ERROR);
16689 		}
16690 
16691 		/*
16692 		 * Create structure to hold all error state info.
16693 		 */
16694 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16695 		errinfo->ei_error_type = onentry;
16696 		errinfo->ei_failing_bp = ri->cmd_bp;
16697 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16698 	} else {
16699 		/* disabled */
16700 		return (COMMAND_DONE_ERROR);
16701 	}
16702 
16703 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16704 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16705 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16706 	    DDI_NOSLEEP);
16707 	ASSERT(ret == DDI_SUCCESS);
16708 	if (ret != DDI_SUCCESS) {
16709 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16710 		return (COMMAND_DONE_ERROR);
16711 	}
16712 	return (JUST_RETURN); /* release calling thread */
16713 }
16714 
16715 
16716 static void
16717 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16718 {
16719 	int error_number;
16720 	buf_t *bp;
16721 
16722 
16723 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16724 
16725 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16726 #if !defined(lint)
16727 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16728 #endif
16729 
16730 	bp = errinfo->ei_failing_bp;
16731 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16732 
16733 	switch (err) {
16734 	case JUST_RETURN:
16735 		mutex_exit(&un->un_sd->sd_mutex);
16736 		return;
16737 
16738 	case COMMAND_DONE:
16739 	case COMMAND_DONE_ERROR_RECOVERED:
16740 		ST_DO_KSTATS(bp, kstat_runq_exit);
16741 		error_number = 0;
16742 		break;
16743 
16744 	default:
16745 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16746 		    "st_recov_ret with unhandled errstat %d\n", err);
16747 		/* FALLTHROUGH */
16748 	case COMMAND_DONE_ERROR:
16749 		un->un_pos.pmode = invalid;
16750 		un->un_running.pmode = invalid;
16751 		/* FALLTHROUGH */
16752 	case COMMAND_DONE_EACCES:
16753 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16754 		ST_DO_ERRSTATS(un, st_transerrs);
16755 		error_number = EIO;
16756 		st_set_pe_flag(un);
16757 		break;
16758 
16759 	}
16760 
16761 	st_bioerror(bp, error_number);
16762 	st_done_and_mutex_exit(un, bp);
16763 }
16764 
16765 
16766 static void
16767 st_recover(void *arg)
16768 {
16769 	st_err_info *const errinfo = (st_err_info *)arg;
16770 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16771 	struct scsi_tape *un;
16772 	tapepos_t cur_pos;
16773 	int rval;
16774 	errstate status = COMMAND_DONE_ERROR;
16775 	recov_info *rcv;
16776 	buf_t *bp;
16777 
16778 
16779 	rcv = errinfo->ei_failed_pkt.pkt_private;
16780 	ASSERT(rcv->privatelen == sizeof (recov_info));
16781 	bp = rcv->cmd_bp;
16782 
16783 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16784 
16785 	ASSERT(un != NULL);
16786 
16787 	mutex_enter(ST_MUTEX);
16788 
16789 	ST_FUNC(ST_DEVINFO, st_recover);
16790 
16791 	ST_CDB(ST_DEVINFO, "Recovering command",
16792 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16793 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16794 	    (caddr_t)&errinfo->ei_failing_status,
16795 	    sizeof (struct scsi_arq_status));
16796 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16797 	    "starting position for recovery command" :
16798 	    "expected position for recovery command",
16799 	    &errinfo->ei_expected_pos);
16800 
16801 	rval = st_test_path_to_device(un);
16802 
16803 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16804 	    "st_recover called with %s, TUR returned %d\n",
16805 	    errstatenames[errinfo->ei_error_type], rval);
16806 	/*
16807 	 * If the drive responed to the TUR lets try and get it to sync
16808 	 * any data it might have in the buffer.
16809 	 */
16810 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16811 		rval = st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16812 		if (rval) {
16813 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16814 			    "st_recover failed to flush, returned %d\n", rval);
16815 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16816 			return;
16817 		}
16818 	}
16819 	switch (errinfo->ei_error_type) {
16820 	case ATTEMPT_RETRY:
16821 	case COMMAND_TIMEOUT:
16822 	case DEVICE_RESET:
16823 	case PATH_FAILED:
16824 		/*
16825 		 * For now if we can't talk to the device we are done.
16826 		 * If the drive is reserved we can try to get it back.
16827 		 */
16828 		if (rval != 0 && rval != EACCES) {
16829 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16830 			return;
16831 		}
16832 
16833 		/*
16834 		 * If reservation conflict and do a preempt, fail it.
16835 		 */
16836 		if ((un->un_rsvd_status &
16837 		    (ST_APPLICATION_RESERVATIONS | ST_RESERVE)) != 0) {
16838 			if ((errinfo->ei_failed_pkt.pkt_cdbp[0] ==
16839 			    SCMD_PERSISTENT_RESERVE_OUT) &&
16840 			    (errinfo->ei_failed_pkt.pkt_cdbp[1] ==
16841 			    ST_SA_SCSI3_PREEMPT) &&
16842 			    (SCBP_C(&errinfo->ei_failed_pkt) ==
16843 			    STATUS_RESERVATION_CONFLICT)) {
16844 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16845 				return;
16846 			}
16847 		}
16848 
16849 		/*
16850 		 * If scsi II lost reserve try and get it back.
16851 		 */
16852 		if ((((un->un_rsvd_status &
16853 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16854 		    ST_LOST_RESERVE)) &&
16855 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16856 			rval = st_reserve_release(un, ST_RESERVE,
16857 			    st_uscsi_rcmd);
16858 			if (rval != 0) {
16859 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16860 					st_recov_ret(un, errinfo,
16861 					    COMMAND_DONE_EACCES);
16862 					return;
16863 				}
16864 			}
16865 			un->un_rsvd_status |= ST_RESERVE;
16866 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16867 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16868 		}
16869 		rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16870 		if (rval) {
16871 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16872 			    un->un_mspl, sizeof (struct seq_mode));
16873 		}
16874 		if (rval) {
16875 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16876 			return;
16877 		}
16878 		break;
16879 	case DEVICE_TAMPER:
16880 		/*
16881 		 * Check if the ASC/ASCQ says mode data has changed.
16882 		 */
16883 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16884 		    0x2a) &&
16885 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16886 		    0x01)) {
16887 			/*
16888 			 * See if mode sense changed.
16889 			 */
16890 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16891 			if (rval) {
16892 				/*
16893 				 * If so change it back.
16894 				 */
16895 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16896 				    un->un_mspl, sizeof (struct seq_mode));
16897 			}
16898 			if (rval) {
16899 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16900 				return;
16901 			}
16902 		}
16903 		/*
16904 		 * if we have a media id and its not bogus.
16905 		 * Check to see if it the same.
16906 		 */
16907 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16908 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16909 			if (rval == ESPIPE) {
16910 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16911 				return;
16912 			}
16913 		}
16914 		break;
16915 	default:
16916 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16917 		    "Unhandled error type %s in st_recover() 0x%x\n",
16918 		    errstatenames[errinfo->ei_error_type], com);
16919 	}
16920 
16921 	/*
16922 	 * if command is retriable retry it.
16923 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16924 	 * does not say that it is retriable. That because if you reissue a
16925 	 * request sense and the target responds the sense data will have
16926 	 * been consumed and no long be valid. If we get a busy status on
16927 	 * request sense while the state is ST_STATE_SENSING this will
16928 	 * reissue that pkt.
16929 	 *
16930 	 * XXX If this request sense gets sent to a different port then
16931 	 * the original command that failed was sent on it will not get
16932 	 * valid sense data for that command.
16933 	 */
16934 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16935 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16936 
16937 	/*
16938 	 * if drive doesn't support read position we are done
16939 	 */
16940 	} else if (un->un_read_pos_type == NO_POS) {
16941 		status = COMMAND_DONE_ERROR;
16942 	/*
16943 	 * If this command results in a changed tape position,
16944 	 * lets see where we are.
16945 	 */
16946 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16947 		/*
16948 		 * XXX May be a reason to choose a different type here.
16949 		 * Long format has file position information.
16950 		 * Short and Extended have information about whats
16951 		 * in the buffer. St's positioning assumes in the buffer
16952 		 * to be the same as on tape.
16953 		 */
16954 		rval = st_compare_expected_position(un, errinfo,
16955 		    rcv->cmd_attrib, &cur_pos);
16956 		if (rval == 0) {
16957 			status = COMMAND_DONE;
16958 		} else if (rval == EAGAIN) {
16959 			status = st_recover_reissue_pkt(un,
16960 			    &errinfo->ei_failed_pkt);
16961 		} else {
16962 			status = COMMAND_DONE_ERROR;
16963 		}
16964 	} else {
16965 		ASSERT(0);
16966 	}
16967 
16968 	st_recov_ret(un, errinfo, status);
16969 }
16970 
16971 static void
16972 st_recov_cb(struct scsi_pkt *pkt)
16973 {
16974 	struct scsi_tape *un;
16975 	struct buf *bp;
16976 	recov_info *rcv;
16977 	errstate action = COMMAND_DONE_ERROR;
16978 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16979 
16980 	/*
16981 	 * Get the buf from the packet.
16982 	 */
16983 	rcv = pkt->pkt_private;
16984 	ASSERT(rcv->privatelen == sizeof (recov_info));
16985 	bp = rcv->cmd_bp;
16986 
16987 	/*
16988 	 * get the unit from the buf.
16989 	 */
16990 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16991 	ASSERT(un != NULL);
16992 
16993 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16994 
16995 	mutex_enter(ST_MUTEX);
16996 
16997 	ASSERT(bp == un->un_recov_buf);
16998 
16999 
17000 	switch (pkt->pkt_reason) {
17001 	case CMD_CMPLT:
17002 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
17003 			action = st_handle_autosense(un, bp, &rcv->pos);
17004 		} else  if ((SCBP(pkt)->sts_busy) ||
17005 		    (SCBP(pkt)->sts_chk) ||
17006 		    (SCBP(pkt)->sts_vu7)) {
17007 			action = st_check_error(un, pkt);
17008 		} else {
17009 			action = COMMAND_DONE;
17010 		}
17011 		break;
17012 	case CMD_TIMEOUT:
17013 		action = COMMAND_TIMEOUT;
17014 		break;
17015 	case CMD_TRAN_ERR:
17016 		action = QUE_COMMAND;
17017 		break;
17018 	default:
17019 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17020 		    "pkt_reason not handled yet %s",
17021 		    scsi_rname(pkt->pkt_reason));
17022 		action = COMMAND_DONE_ERROR;
17023 	}
17024 
17025 	/*
17026 	 * check for undetected path failover.
17027 	 */
17028 	if (un->un_multipath) {
17029 		if (scsi_pkt_allocated_correctly(pkt) &&
17030 		    (un->un_last_path_instance != pkt->pkt_path_instance)) {
17031 			if (un->un_state > ST_STATE_OPENING) {
17032 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17033 				    "Failover detected in recovery, action is "
17034 				    "%s\n", errstatenames[action]);
17035 			}
17036 			un->un_last_path_instance = pkt->pkt_path_instance;
17037 		}
17038 	}
17039 
17040 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
17041 	    "Recovery call back got %s status on %s\n",
17042 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
17043 
17044 	switch (action) {
17045 	case COMMAND_DONE:
17046 		break;
17047 
17048 	case COMMAND_DONE_EACCES:
17049 		bioerror(bp, EACCES);
17050 		break;
17051 
17052 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
17053 		ASSERT(0);
17054 		break;
17055 
17056 	case COMMAND_TIMEOUT:
17057 	case COMMAND_DONE_ERROR:
17058 		bioerror(bp, EIO);
17059 		break;
17060 
17061 	case DEVICE_RESET:
17062 	case QUE_BUSY_COMMAND:
17063 	case PATH_FAILED:
17064 		/* longish timeout */
17065 		timout = ST_STATUS_BUSY_TIMEOUT;
17066 		/* FALLTHRU */
17067 	case QUE_COMMAND:
17068 	case DEVICE_TAMPER:
17069 	case ATTEMPT_RETRY:
17070 		/*
17071 		 * let st_handle_intr_busy put this bp back on waitq and make
17072 		 * checks to see if it is ok to requeue the command.
17073 		 */
17074 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
17075 
17076 		/*
17077 		 * Save the throttle before setting up the timeout
17078 		 */
17079 		if (un->un_throttle) {
17080 			un->un_last_throttle = un->un_throttle;
17081 		}
17082 		mutex_exit(ST_MUTEX);
17083 		if (st_handle_intr_busy(un, bp, timout) == 0) {
17084 			return;		/* timeout is setup again */
17085 		}
17086 		mutex_enter(ST_MUTEX);
17087 		un->un_pos.pmode = invalid;
17088 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17089 		st_bioerror(bp, EIO);
17090 		st_set_pe_flag(un);
17091 		break;
17092 
17093 	default:
17094 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
17095 		    "Unhandled recovery state 0x%x\n", action);
17096 		un->un_pos.pmode = invalid;
17097 		un->un_err_resid = bp->b_resid = bp->b_bcount;
17098 		st_bioerror(bp, EIO);
17099 		st_set_pe_flag(un);
17100 		break;
17101 	}
17102 
17103 	st_done_and_mutex_exit(un, bp);
17104 }
17105 
17106 static int
17107 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
17108 {
17109 	struct buf *bp;
17110 	int err;
17111 
17112 	ST_FUNC(ST_DEVINFO, st_rcmd);
17113 
17114 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
17115 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
17116 	    (void *)un, com, count, wait);
17117 
17118 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17119 	ASSERT(mutex_owned(ST_MUTEX));
17120 
17121 #ifdef STDEBUG
17122 	if ((st_debug & 0x7)) {
17123 		st_debug_cmds(un, com, count, wait);
17124 	}
17125 #endif
17126 
17127 	while (un->un_recov_buf_busy)
17128 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17129 	un->un_recov_buf_busy = 1;
17130 
17131 	bp = un->un_recov_buf;
17132 	bzero(bp, sizeof (buf_t));
17133 
17134 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17135 
17136 	err = st_setup_cmd(un, bp, com, count);
17137 
17138 	un->un_recov_buf_busy = 0;
17139 
17140 	cv_signal(&un->un_recov_buf_cv);
17141 
17142 	return (err);
17143 }
17144 
17145 /* args used */
17146 static int
17147 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17148 {
17149 	int rval;
17150 	buf_t *bp;
17151 
17152 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17153 	ASSERT(flag == FKIOCTL);
17154 
17155 	/*
17156 	 * Get buffer resources...
17157 	 */
17158 	while (un->un_recov_buf_busy)
17159 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17160 	un->un_recov_buf_busy = 1;
17161 
17162 	bp = un->un_recov_buf;
17163 	bzero(bp, sizeof (buf_t));
17164 
17165 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17166 	bp->b_back = (struct buf *)ucmd;
17167 
17168 	mutex_exit(ST_MUTEX);
17169 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17170 	    st_strategy, bp, NULL);
17171 	mutex_enter(ST_MUTEX);
17172 
17173 	ucmd->uscsi_resid = bp->b_resid;
17174 
17175 	/*
17176 	 * Free resources
17177 	 */
17178 	un->un_recov_buf_busy = 0;
17179 	cv_signal(&un->un_recov_buf_cv);
17180 
17181 	return (rval);
17182 }
17183 
17184 /*
17185  * Add data to scsi_pkt to help know what to do if the command fails.
17186  */
17187 static void
17188 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17189     struct scsi_pkt *pkt)
17190 {
17191 	uint64_t count;
17192 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17193 
17194 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17195 
17196 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17197 	    rinfo->privatelen == sizeof (recov_info));
17198 
17199 	SET_BP_PKT(bp, pkt);
17200 	rinfo->cmd_bp = bp;
17201 
17202 	if (rinfo->privatelen != sizeof (recov_info)) {
17203 		return;
17204 	}
17205 
17206 	rinfo->cmd_bp = bp;
17207 
17208 	rinfo->cmd_attrib = NULL;
17209 
17210 	/*
17211 	 * lookup the command attributes and add them to the recovery info.
17212 	 */
17213 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17214 
17215 	ASSERT(rinfo->cmd_attrib);
17216 
17217 	/*
17218 	 * For commands that there is no way to figure the expected position
17219 	 * once completed, we save the position the command was started from
17220 	 * so that if they fail we can position back and try again.
17221 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17222 	 */
17223 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17224 		/* save current position as the starting position. */
17225 		COPY_POS(&rinfo->pos, &un->un_pos);
17226 		un->un_running.pmode = invalid;
17227 		return;
17228 	}
17229 
17230 	/*
17231 	 * Don't want to update the running position for recovery.
17232 	 */
17233 	if (bp == un->un_recov_buf) {
17234 		rinfo->pos.pmode = un->un_running.pmode;
17235 		return;
17236 	}
17237 	/*
17238 	 * If running position is invalid copy the current position.
17239 	 * Running being set invalid means we are not in a read, write
17240 	 * or write filemark sequence.
17241 	 * We'll copy the current position and start from there.
17242 	 */
17243 	if (un->un_running.pmode == invalid) {
17244 		COPY_POS(&un->un_running, &un->un_pos);
17245 		COPY_POS(&rinfo->pos, &un->un_running);
17246 	} else {
17247 		COPY_POS(&rinfo->pos, &un->un_running);
17248 		if (rinfo->pos.pmode == legacy) {
17249 			/*
17250 			 * Always should be more logical blocks then
17251 			 * data blocks and files marks.
17252 			 */
17253 			ASSERT((rinfo->pos.blkno >= 0) ?
17254 			    rinfo->pos.lgclblkno >=
17255 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17256 		}
17257 	}
17258 
17259 	/*
17260 	 * If the command is not expected to change the drive position
17261 	 * then the running position should be the expected position.
17262 	 */
17263 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17264 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17265 		return;
17266 	}
17267 
17268 	if (rinfo->cmd_attrib->explicit_cmd_set) {
17269 		ASSERT(rinfo->pos.pmode != invalid);
17270 		ASSERT(rinfo->cmd_attrib->get_cnt);
17271 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17272 		/*
17273 		 * This is a user generated CDB.
17274 		 */
17275 		if (bp == un->un_sbufp) {
17276 			uint64_t lbn;
17277 
17278 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17279 
17280 			/*
17281 			 * See if this CDB will generate a locate or change
17282 			 * partition.
17283 			 */
17284 			if ((lbn != un->un_running.lgclblkno) ||
17285 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17286 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17287 				rinfo->pos.pmode = logical;
17288 				rinfo->pos.lgclblkno = lbn;
17289 				un->un_running.partition = pkt->pkt_cdbp[3];
17290 				un->un_running.pmode = logical;
17291 				un->un_running.lgclblkno = lbn;
17292 			}
17293 		} else {
17294 			uint64_t lbn = un->un_running.lgclblkno;
17295 
17296 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17297 
17298 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17299 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17300 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17301 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17302 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17303 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17304 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17305 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17306 		}
17307 		rinfo->pos.lgclblkno += count;
17308 		rinfo->pos.blkno += count;
17309 		un->un_running.lgclblkno += count;
17310 		return;
17311 	}
17312 
17313 	if (rinfo->cmd_attrib->chg_tape_pos) {
17314 
17315 		/* should not have got an invalid position from running. */
17316 		if (un->un_mediastate == MTIO_INSERTED) {
17317 			ASSERT(rinfo->pos.pmode != invalid);
17318 		}
17319 
17320 		/* should have either a get count or or get lba function */
17321 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17322 		    rinfo->cmd_attrib->get_lba != NULL);
17323 
17324 		/* only explicit commands have both and they're handled above */
17325 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17326 		    rinfo->cmd_attrib->get_lba != NULL));
17327 
17328 		/* if it has a get count function */
17329 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17330 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17331 			if (count == 0) {
17332 				return;
17333 			}
17334 			/*
17335 			 * Changes position but doesn't transfer data.
17336 			 * i.e. rewind, write_file_mark and load.
17337 			 */
17338 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17339 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17340 				case DIR_NONE: /* Erase */
17341 					ASSERT(rinfo->cmd_attrib->cmd ==
17342 					    SCMD_ERASE);
17343 					break;
17344 				case DIR_FORW: /* write_file_mark */
17345 					rinfo->pos.fileno += count;
17346 					rinfo->pos.lgclblkno += count;
17347 					rinfo->pos.blkno = 0;
17348 					un->un_running.fileno += count;
17349 					un->un_running.lgclblkno += count;
17350 					un->un_running.blkno = 0;
17351 					break;
17352 				case DIR_REVC: /* rewind */
17353 					rinfo->pos.fileno = 0;
17354 					rinfo->pos.lgclblkno = 0;
17355 					rinfo->pos.blkno = 0;
17356 					rinfo->pos.eof = ST_NO_EOF;
17357 					rinfo->pos.pmode = legacy;
17358 					un->un_running.fileno = 0;
17359 					un->un_running.lgclblkno = 0;
17360 					un->un_running.blkno = 0;
17361 					un->un_running.eof = ST_NO_EOF;
17362 					if (un->un_running.pmode != legacy)
17363 						un->un_running.pmode = legacy;
17364 					break;
17365 				case DIR_EITH: /* Load unload */
17366 					ASSERT(rinfo->cmd_attrib->cmd ==
17367 					    SCMD_LOAD);
17368 					switch (count & (LD_LOAD | LD_RETEN |
17369 					    LD_RETEN | LD_HOLD)) {
17370 					case LD_UNLOAD:
17371 					case LD_RETEN:
17372 					case LD_HOLD:
17373 					case LD_LOAD | LD_HOLD:
17374 					case LD_EOT | LD_HOLD:
17375 					case LD_RETEN | LD_HOLD:
17376 						rinfo->pos.pmode = invalid;
17377 						un->un_running.pmode = invalid;
17378 						break;
17379 					case LD_EOT:
17380 					case LD_LOAD | LD_EOT:
17381 						rinfo->pos.eof = ST_EOT;
17382 						rinfo->pos.pmode = invalid;
17383 						un->un_running.eof = ST_EOT;
17384 						un->un_running.pmode = invalid;
17385 						break;
17386 					case LD_LOAD:
17387 					case LD_RETEN | LD_LOAD:
17388 						rinfo->pos.fileno = 0;
17389 						rinfo->pos.lgclblkno = 0;
17390 						rinfo->pos.blkno = 0;
17391 						rinfo->pos.eof = ST_NO_EOF;
17392 						rinfo->pos.pmode = legacy;
17393 						un->un_running.fileno = 0;
17394 						un->un_running.lgclblkno = 0;
17395 						un->un_running.blkno = 0;
17396 						un->un_running.eof = ST_NO_EOF;
17397 						break;
17398 					default:
17399 						ASSERT(0);
17400 					}
17401 					break;
17402 				default:
17403 					ASSERT(0);
17404 					break;
17405 				}
17406 			} else {
17407 				/*
17408 				 * Changes position and does transfer data.
17409 				 * i.e. read or write.
17410 				 */
17411 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17412 				case DIR_FORW:
17413 					rinfo->pos.lgclblkno += count;
17414 					rinfo->pos.blkno += count;
17415 					un->un_running.lgclblkno += count;
17416 					un->un_running.blkno += count;
17417 					break;
17418 				case DIR_REVC:
17419 					rinfo->pos.lgclblkno -= count;
17420 					rinfo->pos.blkno -= count;
17421 					un->un_running.lgclblkno -= count;
17422 					un->un_running.blkno -= count;
17423 					break;
17424 				default:
17425 					ASSERT(0);
17426 					break;
17427 				}
17428 			}
17429 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17430 			/* Have a get LBA fuction. i.e. Locate */
17431 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17432 			    DIR_EITH);
17433 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17434 			un->un_running.lgclblkno = count;
17435 			un->un_running.blkno = 0;
17436 			un->un_running.fileno = 0;
17437 			un->un_running.pmode = logical;
17438 			rinfo->pos.lgclblkno = count;
17439 			rinfo->pos.pmode = invalid;
17440 		} else {
17441 			ASSERT(0);
17442 		}
17443 		return;
17444 	}
17445 
17446 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17447 	    (char *)pkt->pkt_cdbp);
17448 
17449 }
17450 
17451 static int
17452 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17453 {
17454 	struct seq_mode *current;
17455 	int rval;
17456 	int i;
17457 	caddr_t this;
17458 	caddr_t that;
17459 
17460 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17461 
17462 	/* recovery called with mode tamper before mode selection */
17463 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17464 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17465 		    "Mode Select not done yet");
17466 		return (0);
17467 	}
17468 
17469 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17470 
17471 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17472 	    sizeof (struct seq_mode));
17473 	if (rval != 0) {
17474 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17475 		    "Mode Sense for mode verification failed");
17476 		kmem_free(current, sizeof (struct seq_mode));
17477 		return (rval);
17478 	}
17479 
17480 	this = (caddr_t)current;
17481 	that = (caddr_t)un->un_mspl;
17482 
17483 	rval = bcmp(this, that, sizeof (struct seq_mode));
17484 	if (rval == 0) {
17485 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17486 		    "Found no changes in mode data");
17487 	}
17488 #ifdef STDEBUG
17489 	else {
17490 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17491 			if (this[i] != that[i]) {
17492 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17493 				    "sense data changed at byte %d was "
17494 				    "0x%x now 0x%x", i,
17495 				    (uchar_t)that[i], (uchar_t)this[i]);
17496 			}
17497 		}
17498 	}
17499 #endif
17500 	kmem_free(current, sizeof (struct seq_mode));
17501 
17502 	return (rval);
17503 }
17504 
17505 static int
17506 st_test_path_to_device(struct scsi_tape *un)
17507 {
17508 	int rval = 0;
17509 	int limit = st_retry_count;
17510 
17511 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17512 
17513 	/*
17514 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17515 	 */
17516 	do {
17517 		if (rval != 0) {
17518 			mutex_exit(ST_MUTEX);
17519 			delay(drv_usectohz(1000000));
17520 			mutex_enter(ST_MUTEX);
17521 		}
17522 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17523 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17524 		    "ping TUR returned 0x%x", rval);
17525 		limit--;
17526 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17527 
17528 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17529 		rval = 0;
17530 
17531 	return (rval);
17532 }
17533 
17534 /*
17535  * Does read position using recov_buf and doesn't update un_pos.
17536  * Does what ever kind of read position you want.
17537  */
17538 static int
17539 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17540     read_pos_data_t *raw)
17541 {
17542 	int rval;
17543 	struct uscsi_cmd cmd;
17544 	struct scsi_arq_status status;
17545 	char cdb[CDB_GROUP1];
17546 
17547 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17548 	bzero(&cmd, sizeof (cmd));
17549 
17550 	cdb[0] = SCMD_READ_POSITION;
17551 	cdb[1] = type;
17552 	cdb[2] = 0;
17553 	cdb[3] = 0;
17554 	cdb[4] = 0;
17555 	cdb[5] = 0;
17556 	cdb[6] = 0;
17557 	cdb[7] = 0;
17558 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17559 	cdb[9] = 0;
17560 
17561 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17562 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17563 	cmd.uscsi_cdb = cdb;
17564 	cmd.uscsi_cdblen = sizeof (cdb);
17565 	cmd.uscsi_rqlen = sizeof (status);
17566 	cmd.uscsi_rqbuf = (caddr_t)&status;
17567 	cmd.uscsi_bufaddr = (caddr_t)raw;
17568 	switch (type) {
17569 	case SHORT_POS:
17570 		cmd.uscsi_buflen = sizeof (tape_position_t);
17571 		break;
17572 	case LONG_POS:
17573 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17574 		break;
17575 	case EXT_POS:
17576 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17577 		break;
17578 	default:
17579 		ASSERT(0);
17580 	}
17581 
17582 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17583 	if (cmd.uscsi_status) {
17584 		rval = EIO;
17585 	}
17586 	return (rval);
17587 }
17588 
17589 static int
17590 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17591     read_pos_data_t *raw)
17592 {
17593 	int rval;
17594 	read_p_types type = un->un_read_pos_type;
17595 
17596 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17597 
17598 	do {
17599 		rval = st_recovery_read_pos(un, type, raw);
17600 		if (rval != 0) {
17601 			switch (type) {
17602 			case SHORT_POS:
17603 				type = NO_POS;
17604 				break;
17605 
17606 			case LONG_POS:
17607 				type = EXT_POS;
17608 				break;
17609 
17610 			case EXT_POS:
17611 				type = SHORT_POS;
17612 				break;
17613 
17614 			default:
17615 				type = LONG_POS;
17616 				break;
17617 
17618 			}
17619 		} else {
17620 			if (type != un->un_read_pos_type) {
17621 				un->un_read_pos_type = type;
17622 			}
17623 			break;
17624 		}
17625 	} while (type != NO_POS);
17626 
17627 	if (rval == 0) {
17628 		rval = st_interpret_read_pos(un, read, type,
17629 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17630 	}
17631 	return (rval);
17632 }
17633 
17634 /*
17635  * based on the command do we retry, continue or give up?
17636  * possable return values?
17637  *	zero do nothing looks fine.
17638  *	EAGAIN retry.
17639  *	EIO failed makes no sense.
17640  */
17641 static int
17642 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17643     cmd_attribute const * cmd_att, tapepos_t *read)
17644 {
17645 	int rval;
17646 	read_pos_data_t *readp_datap;
17647 
17648 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17649 
17650 	ASSERT(un != NULL);
17651 	ASSERT(ei != NULL);
17652 	ASSERT(read != NULL);
17653 	ASSERT(cmd_att->chg_tape_pos);
17654 
17655 	COPY_POS(read, &ei->ei_expected_pos);
17656 
17657 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17658 
17659 	rval = st_recovery_get_position(un, read, readp_datap);
17660 
17661 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17662 
17663 	if (rval != 0) {
17664 		return (EIO);
17665 	}
17666 
17667 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17668 
17669 	if ((read->pmode == invalid) ||
17670 	    (ei->ei_expected_pos.pmode == invalid)) {
17671 		return (EIO);
17672 	}
17673 
17674 	/*
17675 	 * Command that changes tape position and have an expected position
17676 	 * if it were to chave completed sucessfully.
17677 	 */
17678 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17679 		uint32_t count;
17680 		int64_t difference;
17681 		uchar_t reposition = 0;
17682 
17683 		ASSERT(cmd_att->get_cnt);
17684 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17685 
17686 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17687 		    "Got count from CDB and it was %d\n", count);
17688 
17689 		/*
17690 		 * At expected?
17691 		 */
17692 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17693 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17694 			    "Found drive to be at expected position\n");
17695 
17696 			/*
17697 			 * If the command should move tape and it got a busy
17698 			 * it shouldn't be in the expected position.
17699 			 */
17700 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17701 				reposition = 1;
17702 
17703 			/*
17704 			 * If the command doesn't transfer data should be good.
17705 			 */
17706 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17707 				return (0); /* Good */
17708 
17709 			/*
17710 			 * Command transfers data, should have done so.
17711 			 */
17712 			} else if (ei->ei_failed_pkt.pkt_state &
17713 			    STATE_XFERRED_DATA) {
17714 				return (0); /* Good */
17715 			} else {
17716 				reposition = 1;
17717 			}
17718 		}
17719 
17720 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17721 			difference =
17722 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17723 
17724 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17725 			    "difference between expected and actual is %"
17726 			    PRId64"\n", difference);
17727 			if (count == difference && reposition == 0) {
17728 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17729 				    "Found failed FORW command, retrying\n");
17730 				return (EAGAIN);
17731 			}
17732 
17733 			/*
17734 			 * If rewound or somewhere between the starting position
17735 			 * and the expected position (partial read or write).
17736 			 * Locate to the starting position and try the whole
17737 			 * thing over again.
17738 			 */
17739 			if ((read->lgclblkno == 0) ||
17740 			    ((difference > 0) && (difference < count))) {
17741 				rval = st_logical_block_locate(un,
17742 				    st_uscsi_rcmd, read,
17743 				    ei->ei_expected_pos.lgclblkno - count,
17744 				    ei->ei_expected_pos.partition);
17745 				if (rval == 0) {
17746 					ST_RECOV(ST_DEVINFO, st_label,
17747 					    CE_NOTE, "reestablished FORW"
17748 					    " command retrying\n");
17749 					return (EAGAIN);
17750 				}
17751 			/*
17752 			 * This handles flushed read ahead on the drive or
17753 			 * an aborted read that presents as a busy and advanced
17754 			 * the tape position.
17755 			 */
17756 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17757 			    ((difference < 0) || (reposition == 1))) {
17758 				rval = st_logical_block_locate(un,
17759 				    st_uscsi_rcmd, read,
17760 				    ei->ei_expected_pos.lgclblkno - count,
17761 				    ei->ei_expected_pos.partition);
17762 				if (rval == 0) {
17763 					ST_RECOV(ST_DEVINFO, st_label,
17764 					    CE_NOTE, "reestablished FORW"
17765 					    " read command retrying\n");
17766 					return (EAGAIN);
17767 				}
17768 			/*
17769 			 * XXX swag seeing difference of 2 on write filemark.
17770 			 * If the space to the starting position works on a
17771 			 * write that means the previous write made it to tape.
17772 			 * If not we lost data and have to give up.
17773 			 *
17774 			 * The plot thickens. Now I am attempting to cover a
17775 			 * count of 1 and a differance of 2 on a write.
17776 			 */
17777 			} else if ((difference > count) || (reposition == 1)) {
17778 				rval = st_logical_block_locate(un,
17779 				    st_uscsi_rcmd, read,
17780 				    ei->ei_expected_pos.lgclblkno - count,
17781 				    ei->ei_expected_pos.partition);
17782 				if (rval == 0) {
17783 					ST_RECOV(ST_DEVINFO, st_label,
17784 					    CE_NOTE, "reestablished FORW"
17785 					    " write command retrying\n");
17786 					return (EAGAIN);
17787 				}
17788 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17789 				    "Seek to block %"PRId64" returned %d\n",
17790 				    ei->ei_expected_pos.lgclblkno - count,
17791 				    rval);
17792 			} else {
17793 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17794 				    "Not expected transfers_data = %d "
17795 				    "difference = %"PRId64,
17796 				    cmd_att->transfers_data, difference);
17797 			}
17798 
17799 			return (EIO);
17800 
17801 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17802 			/* Don't think we can write backwards */
17803 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17804 			difference =
17805 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17806 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17807 			    "difference between expected and actual is %"
17808 			    PRId64"\n", difference);
17809 			if (count == difference && reposition == 0) {
17810 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17811 				    "Found failed REVC command, retrying\n");
17812 				return (EAGAIN);
17813 			}
17814 			if ((read->lgclblkno == 0) ||
17815 			    ((difference > 0) && (difference < count))) {
17816 				rval = st_logical_block_locate(un,
17817 				    st_uscsi_rcmd, read,
17818 				    ei->ei_expected_pos.lgclblkno + count,
17819 				    ei->ei_expected_pos.partition);
17820 				if (rval == 0) {
17821 					ST_RECOV(ST_DEVINFO, st_label,
17822 					    CE_NOTE, "reestablished REVC"
17823 					    " command retrying\n");
17824 					return (EAGAIN);
17825 				}
17826 			/* This handles read ahead in reverse direction */
17827 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17828 			    (difference < 0) || (reposition == 1)) {
17829 				rval = st_logical_block_locate(un,
17830 				    st_uscsi_rcmd, read,
17831 				    ei->ei_expected_pos.lgclblkno - count,
17832 				    ei->ei_expected_pos.partition);
17833 				if (rval == 0) {
17834 					ST_RECOV(ST_DEVINFO, st_label,
17835 					    CE_NOTE, "reestablished REVC"
17836 					    " read command retrying\n");
17837 					return (EAGAIN);
17838 				}
17839 			} else {
17840 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17841 				    "Not expected transfers_data = %d "
17842 				    "difference = %"PRId64,
17843 				    cmd_att->transfers_data, difference);
17844 			}
17845 			return (EIO);
17846 
17847 		} else {
17848 			/*
17849 			 * Commands that change tape position either
17850 			 * direction or don't change position should not
17851 			 * get here.
17852 			 */
17853 			ASSERT(0);
17854 		}
17855 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17856 		    "Didn't find a recoverable position, Failing\n");
17857 
17858 	/*
17859 	 * Command that changes tape position and can only be recovered
17860 	 * by going back to the point of origin and retrying.
17861 	 *
17862 	 * Example SCMD_SPACE.
17863 	 */
17864 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17865 		/*
17866 		 * This type of command stores the starting position.
17867 		 * If the read position is the starting position,
17868 		 * reissue the command.
17869 		 */
17870 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17871 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17872 			    "Found Space command at starting position, "
17873 			    "Reissuing\n");
17874 			return (EAGAIN);
17875 		}
17876 		/*
17877 		 * Not in the position that the command was originally issued,
17878 		 * Attempt to locate to that position.
17879 		 */
17880 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17881 		    ei->ei_expected_pos.lgclblkno,
17882 		    ei->ei_expected_pos.partition);
17883 		if (rval) {
17884 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17885 			    "Found Space at an unexpected position and locate "
17886 			    "back to starting position failed\n");
17887 			return (EIO);
17888 		}
17889 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17890 		    "Found Space at an unexpected position and locate "
17891 		    "back to starting position worked, Reissuing\n");
17892 		return (EAGAIN);
17893 	}
17894 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17895 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17896 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17897 	    "Read position above did not make sense", read);
17898 	ASSERT(0);
17899 	return (EIO);
17900 }
17901 
17902 static errstate
17903 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17904 {
17905 	buf_t *bp;
17906 	buf_t *pkt_bp;
17907 	struct scsi_pkt *newpkt;
17908 	cmd_attribute const *attrib;
17909 	recov_info *rcv = oldpkt->pkt_private;
17910 	uint_t cdblen;
17911 	int queued = 0;
17912 	int rval;
17913 	int flags = 0;
17914 	int stat_size =
17915 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17916 
17917 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17918 
17919 	bp = rcv->cmd_bp;
17920 
17921 	if (rcv->privatelen == sizeof (recov_info)) {
17922 		attrib = rcv->cmd_attrib;
17923 	} else {
17924 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17925 	}
17926 
17927 	/*
17928 	 * Some non-uscsi commands use the b_bcount for values that
17929 	 * have nothing to do with how much data is transfered.
17930 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17931 	 */
17932 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17933 		pkt_bp = bp;
17934 	} else if (attrib->transfers_data == TRAN_NONE) {
17935 		pkt_bp = NULL;
17936 	} else {
17937 		pkt_bp = bp;
17938 	}
17939 
17940 	/*
17941 	 * if this is a queued command make sure it the only one in the
17942 	 * run queue.
17943 	 */
17944 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17945 		ASSERT(un->un_runqf == un->un_runql);
17946 		ASSERT(un->un_runqf == bp);
17947 		queued = 1;
17948 	}
17949 
17950 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17951 
17952 	if (pkt_bp == un->un_rqs_bp) {
17953 		flags |= PKT_CONSISTENT;
17954 		stat_size = 1;
17955 	}
17956 
17957 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17958 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
17959 	if (newpkt == NULL) {
17960 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17961 		    "Reissue pkt scsi_init_pkt() failure\n");
17962 		return (COMMAND_DONE_ERROR);
17963 	}
17964 
17965 	ASSERT(newpkt->pkt_resid == 0);
17966 	bp->b_flags &= ~(B_DONE);
17967 	bp->b_resid = 0;
17968 	st_bioerror(bp, 0);
17969 
17970 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17971 
17972 	newpkt->pkt_comp = oldpkt->pkt_comp;
17973 	newpkt->pkt_time = oldpkt->pkt_time;
17974 
17975 	bzero(newpkt->pkt_scbp, stat_size);
17976 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17977 
17978 	newpkt->pkt_state = 0;
17979 	newpkt->pkt_statistics = 0;
17980 
17981 	/*
17982 	 * oldpkt passed in was a copy of the original.
17983 	 * to distroy we need the address of the original.
17984 	 */
17985 	oldpkt = BP_PKT(bp);
17986 
17987 	if (oldpkt == un->un_rqs) {
17988 		ASSERT(bp == un->un_rqs_bp);
17989 		un->un_rqs = newpkt;
17990 	}
17991 
17992 	SET_BP_PKT(bp, newpkt);
17993 
17994 	scsi_destroy_pkt(oldpkt);
17995 
17996 	rval = st_transport(un, newpkt);
17997 	if (rval == TRAN_ACCEPT) {
17998 		return (JUST_RETURN);
17999 	}
18000 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
18001 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
18002 	if (rval != TRAN_BUSY) {
18003 		return (COMMAND_DONE_ERROR);
18004 	}
18005 	mutex_exit(ST_MUTEX);
18006 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
18007 	mutex_enter(ST_MUTEX);
18008 	if (rval) {
18009 		return (COMMAND_DONE_ERROR);
18010 	}
18011 
18012 	return (JUST_RETURN);
18013 }
18014 
18015 static int
18016 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
18017 {
18018 	int status;
18019 
18020 	ST_FUNC(ST_DEVINFO, st_transport);
18021 
18022 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
18023 
18024 	mutex_exit(ST_MUTEX);
18025 
18026 	status = scsi_transport(pkt);
18027 
18028 	mutex_enter(ST_MUTEX);
18029 
18030 	return (status);
18031 }
18032 
18033 /*
18034  * Removed the buf_t bp from the queue referenced to by head and tail.
18035  * Returns the buf_t pointer if it is found in the queue.
18036  * Returns NULL if it is not found.
18037  */
18038 static buf_t *
18039 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
18040 {
18041 	buf_t *runqbp;
18042 	buf_t *prevbp = NULL;
18043 
18044 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
18045 		if (runqbp == bp) {
18046 			/* found it, is it at the head? */
18047 			if (runqbp == *head) {
18048 				*head = bp->av_forw;
18049 			} else {
18050 				prevbp->av_forw = bp->av_forw;
18051 			}
18052 			if (*tail == bp) {
18053 				*tail = prevbp;
18054 			}
18055 			bp->av_forw = NULL;
18056 			return (bp); /* found and removed */
18057 		}
18058 		prevbp = runqbp;
18059 	}
18060 	return (NULL);
18061 }
18062 
18063 /*
18064  * Adds a buf_t to the queue pointed to by head and tail.
18065  * Adds it either to the head end or the tail end based on which
18066  * the passed variable end (head or tail) points at.
18067  */
18068 static void
18069 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
18070 {
18071 
18072 	bp->av_forw = NULL;
18073 	if (*head) {
18074 		/* Queue is not empty */
18075 		if (end == *head) {
18076 			/* Add at front of queue */
18077 			bp->av_forw = *head;
18078 			*head = bp;
18079 		} else if (end == *tail) {
18080 			/* Add at end of queue */
18081 			(*tail)->av_forw = bp;
18082 			*tail = bp;
18083 		} else {
18084 			ASSERT(0);
18085 		}
18086 	} else {
18087 		/* Queue is empty */
18088 		*head = bp;
18089 		*tail = bp;
18090 	}
18091 }
18092 
18093 
18094 static uint64_t
18095 st_get_cdb_g0_rw_count(uchar_t *cdb)
18096 {
18097 	uint64_t count;
18098 
18099 	if ((cdb[1]) & 1) {
18100 		/* fixed block mode, the count is the number of blocks */
18101 		count =
18102 		    cdb[2] << 16 |
18103 		    cdb[3] << 8 |
18104 		    cdb[4];
18105 	} else {
18106 		/* variable block mode, the count is the block size */
18107 		count = 1;
18108 	}
18109 	return (count);
18110 }
18111 
18112 static uint64_t
18113 st_get_cdb_g0_sign_count(uchar_t *cdb)
18114 {
18115 	uint64_t count;
18116 
18117 	count =
18118 	    cdb[2] << 16 |
18119 	    cdb[3] << 8 |
18120 	    cdb[4];
18121 	/*
18122 	 * If the sign bit of the 3 byte value is set, extended it.
18123 	 */
18124 	if (count & 0x800000) {
18125 		count |= 0xffffffffff000000;
18126 	}
18127 	return (count);
18128 }
18129 
18130 static uint64_t
18131 st_get_cdb_g0_count(uchar_t *cdb)
18132 {
18133 	uint64_t count;
18134 
18135 	count =
18136 	    cdb[2] << 16 |
18137 	    cdb[3] << 8 |
18138 	    cdb[4];
18139 	return (count);
18140 }
18141 
18142 static uint64_t
18143 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18144 {
18145 	uint64_t count;
18146 
18147 	if ((cdb[1]) & 1) {
18148 		/* fixed block mode */
18149 		count =
18150 		    cdb[12] << 16 |
18151 		    cdb[13] << 8 |
18152 		    cdb[14];
18153 	} else {
18154 		/* variable block mode */
18155 		count = 1;
18156 	}
18157 	return (count);
18158 }
18159 
18160 static uint64_t
18161 st_get_no_count(uchar_t *cdb)
18162 {
18163 	ASSERT(cdb[0] == SCMD_REWIND);
18164 	return ((uint64_t)cdb[0]);
18165 }
18166 
18167 static uint64_t
18168 st_get_load_options(uchar_t *cdb)
18169 {
18170 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18171 }
18172 
18173 static uint64_t
18174 st_get_erase_options(uchar_t *cdb)
18175 {
18176 	return (cdb[1] | (cdb[0] << 8));
18177 }
18178 
18179 static uint64_t
18180 st_get_cdb_g1_lba(uchar_t *cdb)
18181 {
18182 	uint64_t lba;
18183 
18184 	lba =
18185 	    cdb[3] << 24 |
18186 	    cdb[4] << 16 |
18187 	    cdb[5] << 8 |
18188 	    cdb[6];
18189 	return (lba);
18190 }
18191 
18192 static uint64_t
18193 st_get_cdb_g5_count(uchar_t *cdb)
18194 {
18195 	uint64_t count =
18196 	    cdb[12] << 16 |
18197 	    cdb[13] << 8 |
18198 	    cdb[14];
18199 
18200 	return (count);
18201 }
18202 
18203 static uint64_t
18204 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18205 {
18206 	uint64_t lba;
18207 
18208 	lba =
18209 	    (uint64_t)cdb[4] << 56 |
18210 	    (uint64_t)cdb[5] << 48 |
18211 	    (uint64_t)cdb[6] << 40 |
18212 	    (uint64_t)cdb[7] << 32 |
18213 	    (uint64_t)cdb[8] << 24 |
18214 	    (uint64_t)cdb[9] << 16 |
18215 	    (uint64_t)cdb[10] << 8 |
18216 	    (uint64_t)cdb[11];
18217 	return (lba);
18218 }
18219 
18220 static const cmd_attribute cmd_attributes[] = {
18221 	{ SCMD_READ,
18222 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18223 	    0, 0, 0, st_get_cdb_g0_rw_count },
18224 	{ SCMD_WRITE,
18225 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18226 	    0, 0, 0, st_get_cdb_g0_rw_count },
18227 	{ SCMD_TEST_UNIT_READY,
18228 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18229 	    0, 0, 0 },
18230 	{ SCMD_REWIND,
18231 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18232 	    0, 0, 0, st_get_no_count },
18233 	{ SCMD_REQUEST_SENSE,
18234 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18235 	    0, 0, 0 },
18236 	{ SCMD_READ_BLKLIM,
18237 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18238 	    0, 0, 0 },
18239 	{ SCMD_READ_G4,
18240 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18241 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18242 	{ SCMD_WRITE_G4,
18243 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18244 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18245 	{ SCMD_READ_REVERSE,
18246 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18247 	    0, 0, 0, st_get_cdb_g0_rw_count },
18248 	{ SCMD_READ_REVERSE_G4,
18249 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18250 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18251 	{ SCMD_WRITE_FILE_MARK,
18252 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18253 	    0, 0, 0, st_get_cdb_g0_count },
18254 	{ SCMD_WRITE_FILE_MARK_G4,
18255 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18256 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18257 	{ SCMD_SPACE,
18258 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18259 	    0, 0, 0, st_get_cdb_g0_sign_count },
18260 	{ SCMD_SPACE_G4,
18261 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18262 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18263 	{ SCMD_INQUIRY,
18264 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18265 	    0, 0, 0 },
18266 	{ SCMD_VERIFY_G0,
18267 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18268 	    0, 0, 0, st_get_cdb_g0_rw_count },
18269 	{ SCMD_VERIFY_G4,
18270 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18271 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18272 	{ SCMD_RECOVER_BUF,
18273 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18274 	    0, 0, 0 },
18275 	{ SCMD_MODE_SELECT,
18276 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18277 	    0, 0, 0 },
18278 	{ SCMD_RESERVE,
18279 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18280 	    0, 0, 0 },
18281 	{ SCMD_RELEASE,
18282 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18283 	    0, 0, 0 },
18284 	{ SCMD_ERASE,
18285 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18286 	    0, 0, 0, st_get_erase_options },
18287 	{ SCMD_MODE_SENSE,
18288 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18289 	    0, 0, 0 },
18290 	{ SCMD_LOAD,
18291 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18292 	    0, 0, 0, st_get_load_options },
18293 	{ SCMD_GDIAG,
18294 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18295 	    1, 0, 0 },
18296 	{ SCMD_SDIAG,
18297 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18298 	    1, 0, 0 },
18299 	{ SCMD_DOORLOCK,
18300 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18301 	    0, 4, 3 },
18302 	{ SCMD_LOCATE,
18303 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18304 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18305 	{ SCMD_READ_POSITION,
18306 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18307 	    0, 0, 0 },
18308 	{ SCMD_WRITE_BUFFER,
18309 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18310 	    1, 0, 0 },
18311 	{ SCMD_READ_BUFFER,
18312 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18313 	    1, 0, 0 },
18314 	{ SCMD_REPORT_DENSITIES,
18315 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18316 	    0, 0, 0 },
18317 	{ SCMD_LOG_SELECT_G1,
18318 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18319 	    0, 0, 0 },
18320 	{ SCMD_LOG_SENSE_G1,
18321 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18322 	    0, 0, 0 },
18323 	{ SCMD_PRIN,
18324 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18325 	    0, 0, 0 },
18326 	{ SCMD_PROUT,
18327 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18328 	    0, 0, 0 },
18329 	{ SCMD_READ_ATTRIBUTE,
18330 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18331 	    0, 0, 0 },
18332 	{ SCMD_WRITE_ATTRIBUTE,
18333 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18334 	    0, 0, 0 },
18335 	{ SCMD_LOCATE_G4,
18336 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18337 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18338 	{ SCMD_REPORT_LUNS,
18339 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18340 	    0, 0, 0 },
18341 	{ SCMD_SVC_ACTION_IN_G5,
18342 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18343 	    0, 0, 0 },
18344 	{ SCMD_MAINTENANCE_IN,
18345 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18346 	    0, 0, 0 },
18347 	{ SCMD_MAINTENANCE_OUT,
18348 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18349 	    0, 0, 0 },
18350 	{ 0xff, /* Default attribute for unsupported commands */
18351 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18352 	    1, 0, 0, NULL, NULL }
18353 };
18354 
18355 static const cmd_attribute *
18356 st_lookup_cmd_attribute(unsigned char cmd)
18357 {
18358 	int i;
18359 	cmd_attribute const *attribute;
18360 
18361 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18362 		attribute = &cmd_attributes[i];
18363 		if (attribute->cmd == cmd) {
18364 			return (attribute);
18365 		}
18366 	}
18367 	ASSERT(attribute);
18368 	return (attribute);
18369 }
18370 
18371 static int
18372 st_reset(struct scsi_tape *un, int reset_type)
18373 {
18374 	int rval;
18375 
18376 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18377 
18378 	ST_FUNC(ST_DEVINFO, st_reset);
18379 	un->un_rsvd_status |= ST_INITIATED_RESET;
18380 	mutex_exit(ST_MUTEX);
18381 	do {
18382 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18383 		if (rval == 0) {
18384 			switch (reset_type) {
18385 			case RESET_LUN:
18386 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18387 				    "LUN reset failed trying target reset");
18388 				reset_type = RESET_TARGET;
18389 				break;
18390 			case RESET_TARGET:
18391 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18392 				    "target reset failed trying bus reset");
18393 				reset_type = RESET_BUS;
18394 				break;
18395 			case RESET_BUS:
18396 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18397 				    "bus reset failed trying all reset");
18398 				reset_type = RESET_ALL;
18399 			default:
18400 				mutex_enter(ST_MUTEX);
18401 				return (rval);
18402 			}
18403 		}
18404 	} while (rval == 0);
18405 	mutex_enter(ST_MUTEX);
18406 	return (rval);
18407 }
18408 
18409 
18410 static void
18411 st_reset_notification(caddr_t arg)
18412 {
18413 	struct scsi_tape *un = (struct scsi_tape *)arg;
18414 
18415 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18416 	mutex_enter(ST_MUTEX);
18417 
18418 	un->un_unit_attention_flags |= 2;
18419 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18420 	    ST_RESERVE) {
18421 		un->un_rsvd_status |= ST_LOST_RESERVE;
18422 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18423 		    "Lost Reservation notification");
18424 	} else {
18425 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18426 		    "reset notification");
18427 	}
18428 
18429 	if ((un->un_restore_pos == 0) &&
18430 	    (un->un_state == ST_STATE_CLOSED) ||
18431 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18432 	    (un->un_state == ST_STATE_CLOSING)) {
18433 		un->un_restore_pos = 1;
18434 	}
18435 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18436 	    "reset and state was %d\n", un->un_state);
18437 	mutex_exit(ST_MUTEX);
18438 }
18439