xref: /titanic_51/usr/src/uts/common/io/scsi/targets/st.c (revision d29f5a711240f866521445b1656d114da090335e)
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 2008 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 };
481 
482 /*
483  * Local Function Declarations
484  */
485 static char *st_print_scsi_cmd(char cmd);
486 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
487     char *title, char *cdb);
488 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
489     char *title, char *data, int len);
490 static int st_doattach(struct scsi_device *devp, int (*canwait)());
491 static void st_known_tape_type(struct scsi_tape *un);
492 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
493     struct st_drivetype *);
494 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
495     struct st_drivetype *);
496 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
497     struct st_drivetype *);
498 static int st_get_densities_from_tape_drive(struct scsi_tape *,
499     struct st_drivetype *);
500 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
501     struct st_drivetype *);
502 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
503     ushort_t);
504 static int st_get_default_conf(struct scsi_tape *, char *,
505     struct st_drivetype *);
506 static int st_rw(dev_t dev, struct uio *uio, int flag);
507 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
508 static int st_find_eod(struct scsi_tape *un);
509 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
510 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
511 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
512 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
514 static void st_start(struct scsi_tape *un);
515 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
516     clock_t timeout_interval, int queued);
517 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
518     clock_t timeout_interval);
519 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
520 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
521 static void st_init(struct scsi_tape *un);
522 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
523     int (*func)(caddr_t));
524 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
525     struct buf *bp, int (*func)(caddr_t));
526 static void st_intr(struct scsi_pkt *pkt);
527 static void st_set_state(struct scsi_tape *un, buf_t *bp);
528 static void st_test_append(struct buf *bp);
529 static int st_runout(caddr_t);
530 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
531 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
532     int64_t count);
533 static int st_set_compression(struct scsi_tape *un);
534 static int st_write_fm(dev_t dev, int wfm);
535 static int st_determine_generic(struct scsi_tape *un);
536 static int st_determine_density(struct scsi_tape *un, int rw);
537 static int st_get_density(struct scsi_tape *un);
538 static int st_set_density(struct scsi_tape *un);
539 static int st_loadtape(struct scsi_tape *un);
540 static int st_modesense(struct scsi_tape *un);
541 static int st_modeselect(struct scsi_tape *un);
542 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
543 static int st_wrongtapetype(struct scsi_tape *un);
544 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
545 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
546     tapepos_t *);
547 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
548     tapepos_t *);
549 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
550 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
551     struct scsi_arq_status *cmd);
552 static void st_empty_error_stack(struct scsi_tape *un);
553 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
554     struct scsi_arq_status *, tapepos_t *);
555 static int st_report_soft_errors(dev_t dev, int flag);
556 static void st_delayed_cv_broadcast(void *arg);
557 static int st_check_media(dev_t dev, enum mtio_state state);
558 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
559 static void st_intr_restart(void *arg);
560 static void st_start_restart(void *arg);
561 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
562     struct seq_mode *page_data, int page_size);
563 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
564 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
565     struct seq_mode *page_data, int page_size);
566 static int st_read_block_limits(struct scsi_tape *un,
567     struct read_blklim *read_blk);
568 static int st_report_density_support(struct scsi_tape *un,
569     uchar_t *density_data, size_t buflen);
570 static int st_report_supported_operation(struct scsi_tape *un,
571     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
572 static int st_tape_init(struct scsi_tape *un);
573 static void st_flush(struct scsi_tape *un);
574 static void st_set_pe_errno(struct scsi_tape *un);
575 static void st_hba_unflush(struct scsi_tape *un);
576 static void st_turn_pe_on(struct scsi_tape *un);
577 static void st_turn_pe_off(struct scsi_tape *un);
578 static void st_set_pe_flag(struct scsi_tape *un);
579 static void st_clear_pe(struct scsi_tape *un);
580 static void st_wait_for_io(struct scsi_tape *un);
581 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
582 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
583 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
584 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
585 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
586     int count);
587 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
588 static int st_check_asc_ascq(struct scsi_tape *un);
589 static int st_check_clean_bit(struct scsi_tape *un);
590 static int st_check_alert_flags(struct scsi_tape *un);
591 static int st_check_sequential_clean_bit(struct scsi_tape *un);
592 static int st_check_sense_clean_bit(struct scsi_tape *un);
593 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
594 static void st_calculate_timeouts(struct scsi_tape *un);
595 static writablity st_is_drive_worm(struct scsi_tape *un);
596 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
597     void *buf, size_t size, ubufunc_t bufunc);
598 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
599     caddr_t dest, uchar_t page);
600 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
601     int post_space);
602 static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
603     read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
604 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
605 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
606     tapepos_t *pos, uint64_t lblk, uchar_t partition);
607 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
608 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
609 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
610 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
611 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
612 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
613 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
615     int infront);
616 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
617 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
618     int32_t fileno);
619 static int st_space_to_begining_of_file(struct scsi_tape *un);
620 static int st_space_records(struct scsi_tape *un, int64_t records);
621 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
622 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
623     errstate onentry);
624 static void st_recover(void *arg);
625 static void st_recov_cb(struct scsi_pkt *pkt);
626 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
627 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
628     int flag);
629 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
630     struct scsi_pkt *cmd);
631 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
632 static int st_test_path_to_device(struct scsi_tape *un);
633 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
634     read_pos_data_t *raw);
635 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
636     read_pos_data_t *raw);
637 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
638     cmd_attribute const * cmd_att, tapepos_t *read);
639 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
640     struct scsi_pkt *pkt);
641 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
642 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
643 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
644 static int st_reset(struct scsi_tape *un, int reset_type);
645 static void st_reset_notification(caddr_t arg);
646 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
647 
648 #ifdef	__x86
649 /*
650  * routines for I/O in big block size
651  */
652 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
653 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
654     int alloc_flags);
655 static int st_bigblk_xfer_done(struct buf *bp);
656 static struct buf *st_get_bigblk_bp(struct buf *bp);
657 #endif
658 static void st_print_position(dev_info_t *dev, char *label, uint_t level,
659     const char *comment, tapepos_t *pos);
660 
661 /*
662  * error statistics create/update functions
663  */
664 static int st_create_errstats(struct scsi_tape *, int);
665 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
666     tapepos_t *pos);
667 
668 #ifdef STDEBUG
669 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
670 #endif /* STDEBUG */
671 static char *st_dev_name(dev_t dev);
672 
673 #if !defined(lint)
674 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
675     scsi_pkt buf uio scsi_cdb uscsi_cmd))
676 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
677 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
678 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
679 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
680 #endif
681 
682 /*
683  * autoconfiguration routines.
684  */
685 char _depends_on[] = "misc/scsi";
686 
687 static struct modldrv modldrv = {
688 	&mod_driverops,		/* Type of module. This one is a driver */
689 	"SCSI tape Driver", 	/* Name of the module. */
690 	&st_ops			/* driver ops */
691 };
692 
693 static struct modlinkage modlinkage = {
694 	MODREV_1, &modldrv, NULL
695 };
696 
697 /*
698  * Notes on Post Reset Behavior in the tape driver:
699  *
700  * When the tape drive is opened, the driver  attempts  to make sure that
701  * the tape head is positioned exactly where it was left when it was last
702  * closed  provided  the  medium  is not  changed.  If the tape  drive is
703  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
704  * of position due to reset) will happen when the first tape operation or
705  * I/O occurs.  The repositioning (if required) may not be possible under
706  * certain situations such as when the device firmware not able to report
707  * the medium  change in the REQUEST  SENSE data  because of a reset or a
708  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
709  * extraordinary  situations, where the driver fails to position the head
710  * at its  original  position,  it will fail the open the first  time, to
711  * save the applications from overwriting the data.  All further attempts
712  * to open the tape device will result in the driver  attempting  to load
713  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
714  * indicate  that further  attempts to open the tape device may result in
715  * the tape being  loaded at BOT will be printed on the  console.  If the
716  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
717  * original tape head  position,  will result in the failure of the first
718  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
719  * internal tape position  which will  necessitate  the  applications  to
720  * validate the position by using either a tape  positioning  ioctl (such
721  * as MTREW) or closing and reopening the tape device.
722  *
723  */
724 
725 int
726 _init(void)
727 {
728 	int e;
729 
730 	if (((e = ddi_soft_state_init(&st_state,
731 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
732 		return (e);
733 	}
734 
735 	if ((e = mod_install(&modlinkage)) != 0) {
736 		ddi_soft_state_fini(&st_state);
737 	} else {
738 #ifdef STDEBUG
739 		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
740 #endif
741 
742 #if defined(__x86)
743 		/* set the max physical address for iob allocs on x86 */
744 		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
745 
746 		/*
747 		 * set the sgllen for iob allocs on x86. If this is set less
748 		 * than the number of pages the buffer will take
749 		 * (taking into account alignment), it would force the
750 		 * allocator to try and allocate contiguous pages.
751 		 */
752 		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
753 #endif
754 	}
755 
756 	return (e);
757 }
758 
759 int
760 _fini(void)
761 {
762 	int e;
763 
764 	if ((e = mod_remove(&modlinkage)) != 0) {
765 		return (e);
766 	}
767 
768 #ifdef STDEBUG
769 	mutex_destroy(&st_debug_mutex);
770 #endif
771 
772 	ddi_soft_state_fini(&st_state);
773 
774 	return (e);
775 }
776 
777 int
778 _info(struct modinfo *modinfop)
779 {
780 	return (mod_info(&modlinkage, modinfop));
781 }
782 
783 
784 static int
785 st_probe(dev_info_t *devi)
786 {
787 	int instance;
788 	struct scsi_device *devp;
789 	int rval;
790 
791 #if !defined(__sparc)
792 	char    *tape_prop;
793 	int	tape_prop_len;
794 #endif
795 
796 	ST_ENTR(devi, st_probe);
797 
798 	/* If self identifying device */
799 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
800 		return (DDI_PROBE_DONTCARE);
801 	}
802 
803 #if !defined(__sparc)
804 	/*
805 	 * Since some x86 HBAs have devnodes that look like SCSI as
806 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
807 	 * we check for the presence of the "tape" property.
808 	 */
809 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
810 	    DDI_PROP_CANSLEEP, "tape",
811 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
812 		return (DDI_PROBE_FAILURE);
813 	}
814 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
815 		kmem_free(tape_prop, tape_prop_len);
816 		return (DDI_PROBE_FAILURE);
817 	}
818 	kmem_free(tape_prop, tape_prop_len);
819 #endif
820 
821 	devp = ddi_get_driver_private(devi);
822 	instance = ddi_get_instance(devi);
823 
824 	if (ddi_get_soft_state(st_state, instance) != NULL) {
825 		return (DDI_PROBE_PARTIAL);
826 	}
827 
828 
829 	/*
830 	 * Turn around and call probe routine to see whether
831 	 * we actually have a tape at this SCSI nexus.
832 	 */
833 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
834 
835 		/*
836 		 * In checking the whole inq_dtype byte we are looking at both
837 		 * the Peripheral Qualifier and the Peripheral Device Type.
838 		 * For this driver we are only interested in sequential devices
839 		 * that are connected or capable if connecting to this logical
840 		 * unit.
841 		 */
842 		if (devp->sd_inq->inq_dtype ==
843 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
844 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
845 			    "probe exists\n");
846 			rval = DDI_PROBE_SUCCESS;
847 		} else {
848 			rval = DDI_PROBE_FAILURE;
849 		}
850 	} else {
851 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
852 		    "probe failure: nothing there\n");
853 		rval = DDI_PROBE_FAILURE;
854 	}
855 	scsi_unprobe(devp);
856 	return (rval);
857 }
858 
859 static int
860 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
861 {
862 	int 	instance;
863 	int	wide;
864 	int 	dev_instance;
865 	int	ret_status;
866 	struct	scsi_device *devp;
867 	int	node_ix;
868 	struct	scsi_tape *un;
869 
870 	ST_ENTR(devi, st_attach);
871 
872 	devp = ddi_get_driver_private(devi);
873 	instance = ddi_get_instance(devi);
874 
875 	switch (cmd) {
876 		case DDI_ATTACH:
877 			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
878 			    "tape-command-recovery-disable", 0) != 0) {
879 				st_recov_sz = sizeof (pkt_info);
880 			}
881 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
882 				return (DDI_FAILURE);
883 			}
884 			break;
885 		case DDI_RESUME:
886 			/*
887 			 * Suspend/Resume
888 			 *
889 			 * When the driver suspended, there might be
890 			 * outstanding cmds and therefore we need to
891 			 * reset the suspended flag and resume the scsi
892 			 * watch thread and restart commands and timeouts
893 			 */
894 
895 			if (!(un = ddi_get_soft_state(st_state, instance))) {
896 				return (DDI_FAILURE);
897 			}
898 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
899 			    un->un_dev);
900 
901 			mutex_enter(ST_MUTEX);
902 
903 			un->un_throttle = un->un_max_throttle;
904 			un->un_tids_at_suspend = 0;
905 			un->un_pwr_mgmt = ST_PWR_NORMAL;
906 
907 			if (un->un_swr_token) {
908 				scsi_watch_resume(un->un_swr_token);
909 			}
910 
911 			/*
912 			 * Restart timeouts
913 			 */
914 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
915 				mutex_exit(ST_MUTEX);
916 				un->un_delay_tid = timeout(
917 				    st_delayed_cv_broadcast, un,
918 				    drv_usectohz((clock_t)
919 				    MEDIA_ACCESS_DELAY));
920 				mutex_enter(ST_MUTEX);
921 			}
922 
923 			if (un->un_tids_at_suspend & ST_HIB_TID) {
924 				mutex_exit(ST_MUTEX);
925 				un->un_hib_tid = timeout(st_intr_restart, un,
926 				    ST_STATUS_BUSY_TIMEOUT);
927 				mutex_enter(ST_MUTEX);
928 			}
929 
930 			ret_status = st_clear_unit_attentions(dev_instance, 5);
931 
932 			/*
933 			 * now check if we need to restore the tape position
934 			 */
935 			if ((un->un_suspend_pos.pmode != invalid) &&
936 			    ((un->un_suspend_pos.fileno > 0) ||
937 			    (un->un_suspend_pos.blkno > 0)) ||
938 			    (un->un_suspend_pos.lgclblkno > 0)) {
939 				if (ret_status != 0) {
940 					/*
941 					 * tape didn't get good TUR
942 					 * just print out error messages
943 					 */
944 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
945 					    "st_attach-RESUME: tape failure "
946 					    " tape position will be lost");
947 				} else {
948 					/* this prints errors */
949 					(void) st_validate_tapemarks(un,
950 					    st_uscsi_cmd, &un->un_suspend_pos);
951 				}
952 				/*
953 				 * there are no retries, if there is an error
954 				 * we don't know if the tape has changed
955 				 */
956 				un->un_suspend_pos.pmode = invalid;
957 			}
958 
959 			/* now we are ready to start up any queued I/Os */
960 			if (un->un_ncmds || un->un_quef) {
961 				st_start(un);
962 			}
963 
964 			cv_broadcast(&un->un_suspend_cv);
965 			mutex_exit(ST_MUTEX);
966 			return (DDI_SUCCESS);
967 
968 		default:
969 			return (DDI_FAILURE);
970 	}
971 
972 	un = ddi_get_soft_state(st_state, instance);
973 
974 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
975 	    "st_attach: instance=%x\n", instance);
976 
977 	/*
978 	 * Add a zero-length attribute to tell the world we support
979 	 * kernel ioctls (for layered drivers)
980 	 */
981 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
982 	    DDI_KERNEL_IOCTL, NULL, 0);
983 
984 	ddi_report_dev((dev_info_t *)devi);
985 
986 	/*
987 	 * If it's a SCSI-2 tape drive which supports wide,
988 	 * tell the host adapter to use wide.
989 	 */
990 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
991 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
992 
993 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
994 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
995 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
996 	}
997 
998 	/*
999 	 * enable autorequest sense; keep the rq packet around in case
1000 	 * the autorequest sense fails because of a busy condition
1001 	 * do a getcap first in case the capability is not variable
1002 	 */
1003 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1004 		un->un_arq_enabled = 1;
1005 	} else {
1006 		un->un_arq_enabled =
1007 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1008 	}
1009 
1010 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1011 	    (un->un_arq_enabled ? "enabled" : "disabled"));
1012 
1013 	un->un_untagged_qing =
1014 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1015 
1016 	/*
1017 	 * XXX - This is just for 2.6.  to tell users that write buffering
1018 	 *	has gone away.
1019 	 */
1020 	if (un->un_arq_enabled && un->un_untagged_qing) {
1021 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1022 		    "tape-driver-buffering", 0) != 0) {
1023 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1024 			    "Write Data Buffering has been depricated. Your "
1025 			    "applications should continue to work normally.\n"
1026 			    " But, they should  ported to use Asynchronous "
1027 			    " I/O\n"
1028 			    " For more information, read about "
1029 			    " tape-driver-buffering "
1030 			    "property in the st(7d) man page\n");
1031 		}
1032 	}
1033 
1034 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1035 	un->un_flush_on_errors = 0;
1036 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1037 
1038 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1039 	    "throttle=%x, max_throttle = %x\n",
1040 	    un->un_throttle, un->un_max_throttle);
1041 
1042 	/* initialize persistent errors to nil */
1043 	un->un_persistence = 0;
1044 	un->un_persist_errors = 0;
1045 
1046 	/*
1047 	 * Get dma-max from HBA driver. If it is not defined, use 64k
1048 	 */
1049 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1050 	if (un->un_maxdma == -1) {
1051 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1052 		    "Received a value that looked like -1. Using 64k maxdma");
1053 		un->un_maxdma = (64 * ONE_K);
1054 	}
1055 
1056 #ifdef	__x86
1057 	/*
1058 	 * for x86, the device may be able to DMA more than the system will
1059 	 * allow under some circumstances. We need account for both the HBA's
1060 	 * and system's contraints.
1061 	 *
1062 	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1063 	 * device constraints, the max copy buffer size, and the worse case
1064 	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1065 	 * doesn't take the worse case framentation into account.
1066 	 *
1067 	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1068 	 * if none of the pages are contiguous. Keeping track of both of these
1069 	 * values allows us to support larger tape block sizes on some devices.
1070 	 */
1071 	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1072 	    1);
1073 
1074 	/*
1075 	 * If the dma-max-arch capability is not implemented, or the value
1076 	 * comes back higher than what was reported in dma-max, use dma-max.
1077 	 */
1078 	if ((un->un_maxdma_arch == -1) ||
1079 	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1080 		un->un_maxdma_arch = un->un_maxdma;
1081 	}
1082 #endif
1083 
1084 	/*
1085 	 * Get the max allowable cdb size
1086 	 */
1087 	un->un_max_cdb_sz =
1088 	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1089 	if (un->un_max_cdb_sz < CDB_GROUP0) {
1090 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1091 		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1092 		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1093 	}
1094 
1095 	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1096 		un->un_multipath = 0;
1097 	} else {
1098 		un->un_multipath = 1;
1099 	}
1100 
1101 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1102 
1103 	un->un_mediastate = MTIO_NONE;
1104 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1105 
1106 	/*
1107 	 * initialize kstats
1108 	 */
1109 	un->un_stats = kstat_create("st", instance, NULL, "tape",
1110 	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1111 	if (un->un_stats) {
1112 		un->un_stats->ks_lock = ST_MUTEX;
1113 		kstat_install(un->un_stats);
1114 	}
1115 	(void) st_create_errstats(un, instance);
1116 
1117 	/*
1118 	 * find the drive type for this target
1119 	 */
1120 	mutex_enter(ST_MUTEX);
1121 	un->un_dev = MTMINOR(instance);
1122 	st_known_tape_type(un);
1123 	un->un_dev = 0;
1124 	mutex_exit(ST_MUTEX);
1125 
1126 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1127 		int minor;
1128 		char *name;
1129 
1130 		name  = st_minor_data[node_ix].name;
1131 		minor = st_minor_data[node_ix].minor;
1132 
1133 		/*
1134 		 * For default devices set the density to the
1135 		 * preferred default density for this device.
1136 		 */
1137 		if (node_ix <= DEF_BSD_NR) {
1138 			minor |= un->un_dp->default_density;
1139 		}
1140 		minor |= MTMINOR(instance);
1141 
1142 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1143 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
1144 			continue;
1145 		}
1146 
1147 		ddi_remove_minor_node(devi, NULL);
1148 
1149 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1150 		    st_reset_notification, (caddr_t)un);
1151 		cv_destroy(&un->un_clscv);
1152 		cv_destroy(&un->un_sbuf_cv);
1153 		cv_destroy(&un->un_queue_cv);
1154 		cv_destroy(&un->un_state_cv);
1155 #ifdef	__x86
1156 		cv_destroy(&un->un_contig_mem_cv);
1157 #endif
1158 		cv_destroy(&un->un_suspend_cv);
1159 		cv_destroy(&un->un_tape_busy_cv);
1160 		cv_destroy(&un->un_recov_buf_cv);
1161 		if (un->un_recov_taskq) {
1162 			ddi_taskq_destroy(un->un_recov_taskq);
1163 		}
1164 		if (un->un_sbufp) {
1165 			freerbuf(un->un_sbufp);
1166 		}
1167 		if (un->un_recov_buf) {
1168 			freerbuf(un->un_recov_buf);
1169 		}
1170 		if (un->un_uscsi_rqs_buf) {
1171 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1172 		}
1173 		if (un->un_mspl) {
1174 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1175 		}
1176 		if (un->un_dp_size) {
1177 			kmem_free(un->un_dp, un->un_dp_size);
1178 		}
1179 		if (un->un_state) {
1180 			kstat_delete(un->un_stats);
1181 		}
1182 		if (un->un_errstats) {
1183 			kstat_delete(un->un_errstats);
1184 		}
1185 
1186 		scsi_destroy_pkt(un->un_rqs);
1187 		scsi_free_consistent_buf(un->un_rqs_bp);
1188 		ddi_soft_state_free(st_state, instance);
1189 		devp->sd_private = NULL;
1190 		devp->sd_sense = NULL;
1191 
1192 		ddi_prop_remove_all(devi);
1193 		return (DDI_FAILURE);
1194 	}
1195 
1196 	return (DDI_SUCCESS);
1197 }
1198 
1199 /*
1200  * st_detach:
1201  *
1202  * we allow a detach if and only if:
1203  *	- no tape is currently inserted
1204  *	- tape position is at BOT or unknown
1205  *		(if it is not at BOT then a no rewind
1206  *		device was opened and we have to preserve state)
1207  *	- it must be in a closed state : no timeouts or scsi_watch requests
1208  *		will exist if it is closed, so we don't need to check for
1209  *		them here.
1210  */
1211 /*ARGSUSED*/
1212 static int
1213 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1214 {
1215 	int instance;
1216 	int result;
1217 	struct scsi_device *devp;
1218 	struct scsi_tape *un;
1219 	clock_t wait_cmds_complete;
1220 
1221 	ST_ENTR(devi, st_detach);
1222 
1223 	instance = ddi_get_instance(devi);
1224 
1225 	if (!(un = ddi_get_soft_state(st_state, instance))) {
1226 		return (DDI_FAILURE);
1227 	}
1228 
1229 	mutex_enter(ST_MUTEX);
1230 
1231 	/*
1232 	 * Clear error entry stack
1233 	 */
1234 	st_empty_error_stack(un);
1235 
1236 	mutex_exit(ST_MUTEX);
1237 
1238 	switch (cmd) {
1239 
1240 	case DDI_DETACH:
1241 		/*
1242 		 * Undo what we did in st_attach & st_doattach,
1243 		 * freeing resources and removing things we installed.
1244 		 * The system framework guarantees we are not active
1245 		 * with this devinfo node in any other entry points at
1246 		 * this time.
1247 		 */
1248 
1249 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1250 		    "st_detach: instance=%x, un=%p\n", instance,
1251 		    (void *)un);
1252 
1253 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1254 		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1255 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1256 		    (un->un_state != ST_STATE_CLOSED)) {
1257 			/*
1258 			 * we cannot unload some targets because the
1259 			 * inquiry returns junk unless immediately
1260 			 * after a reset
1261 			 */
1262 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1263 			    "cannot unload instance %x\n", instance);
1264 			un->un_unit_attention_flags |= 4;
1265 			return (DDI_FAILURE);
1266 		}
1267 
1268 		/*
1269 		 * if the tape has been removed then we may unload;
1270 		 * do a test unit ready and if it returns NOT READY
1271 		 * then we assume that it is safe to unload.
1272 		 * as a side effect, pmode may be set to invalid if the
1273 		 * the test unit ready fails;
1274 		 * also un_state may be set to non-closed, so reset it
1275 		 */
1276 		if ((un->un_dev) &&		/* Been opened since attach */
1277 		    ((un->un_pos.pmode == legacy) &&
1278 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1279 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1280 		    ((un->un_pos.pmode == logical) &&
1281 		    (un->un_pos.lgclblkno > 0))) {
1282 			mutex_enter(ST_MUTEX);
1283 			/*
1284 			 * Send Test Unit Ready in the hopes that if
1285 			 * the drive is not in the state we think it is.
1286 			 * And the state will be changed so it can be detached.
1287 			 * If the command fails to reach the device and
1288 			 * the drive was not rewound or unloaded we want
1289 			 * to fail the detach till a user command fails
1290 			 * where after the detach will succead.
1291 			 */
1292 			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1293 			/*
1294 			 * After TUR un_state may be set to non-closed,
1295 			 * so reset it back.
1296 			 */
1297 			un->un_state = ST_STATE_CLOSED;
1298 			mutex_exit(ST_MUTEX);
1299 		}
1300 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1301 		    "un_status=%x, fileno=%x, blkno=%x\n",
1302 		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1303 
1304 		/*
1305 		 * check again:
1306 		 * if we are not at BOT then it is not safe to unload
1307 		 */
1308 		if ((un->un_dev) &&		/* Been opened since attach */
1309 		    (result != EACCES) &&	/* drive is use by somebody */
1310 		    (((un->un_pos.pmode == legacy) &&
1311 		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1312 		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1313 		    ((un->un_pos.pmode == logical) &&
1314 		    (un->un_pos.lgclblkno > 0)))) {
1315 
1316 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1317 			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1318 			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1319 			    un->un_pos.fileno, un->un_pos.blkno,
1320 			    un->un_pos.lgclblkno);
1321 			un->un_unit_attention_flags |= 4;
1322 			return (DDI_FAILURE);
1323 		}
1324 
1325 		/*
1326 		 * Just To make sure that we have released the
1327 		 * tape unit .
1328 		 */
1329 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1330 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1331 			mutex_enter(ST_MUTEX);
1332 			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1333 			mutex_exit(ST_MUTEX);
1334 		}
1335 
1336 		/*
1337 		 * now remove other data structures allocated in st_doattach()
1338 		 */
1339 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1340 		    "destroying/freeing\n");
1341 
1342 		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1343 		    st_reset_notification, (caddr_t)un);
1344 		cv_destroy(&un->un_clscv);
1345 		cv_destroy(&un->un_sbuf_cv);
1346 		cv_destroy(&un->un_queue_cv);
1347 		cv_destroy(&un->un_suspend_cv);
1348 		cv_destroy(&un->un_tape_busy_cv);
1349 		cv_destroy(&un->un_recov_buf_cv);
1350 
1351 		if (un->un_recov_taskq) {
1352 			ddi_taskq_destroy(un->un_recov_taskq);
1353 		}
1354 
1355 		if (un->un_hib_tid) {
1356 			(void) untimeout(un->un_hib_tid);
1357 			un->un_hib_tid = 0;
1358 		}
1359 
1360 		if (un->un_delay_tid) {
1361 			(void) untimeout(un->un_delay_tid);
1362 			un->un_delay_tid = 0;
1363 		}
1364 		cv_destroy(&un->un_state_cv);
1365 
1366 #ifdef	__x86
1367 		cv_destroy(&un->un_contig_mem_cv);
1368 
1369 		if (un->un_contig_mem_hdl != NULL) {
1370 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1371 		}
1372 #endif
1373 		if (un->un_sbufp) {
1374 			freerbuf(un->un_sbufp);
1375 		}
1376 		if (un->un_recov_buf) {
1377 			freerbuf(un->un_recov_buf);
1378 		}
1379 		if (un->un_uscsi_rqs_buf) {
1380 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1381 		}
1382 		if (un->un_mspl) {
1383 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1384 		}
1385 		if (un->un_rqs) {
1386 			scsi_destroy_pkt(un->un_rqs);
1387 			scsi_free_consistent_buf(un->un_rqs_bp);
1388 		}
1389 		if (un->un_mkr_pkt) {
1390 			scsi_destroy_pkt(un->un_mkr_pkt);
1391 		}
1392 		if (un->un_arq_enabled) {
1393 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1394 		}
1395 		if (un->un_dp_size) {
1396 			kmem_free(un->un_dp, un->un_dp_size);
1397 		}
1398 		if (un->un_stats) {
1399 			kstat_delete(un->un_stats);
1400 			un->un_stats = (kstat_t *)0;
1401 		}
1402 		if (un->un_errstats) {
1403 			kstat_delete(un->un_errstats);
1404 			un->un_errstats = (kstat_t *)0;
1405 		}
1406 		if (un->un_media_id_len) {
1407 			kmem_free(un->un_media_id, un->un_media_id_len);
1408 		}
1409 		devp = ST_SCSI_DEVP;
1410 		ddi_soft_state_free(st_state, instance);
1411 		devp->sd_private = NULL;
1412 		devp->sd_sense = NULL;
1413 		scsi_unprobe(devp);
1414 		ddi_prop_remove_all(devi);
1415 		ddi_remove_minor_node(devi, NULL);
1416 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1417 		return (DDI_SUCCESS);
1418 
1419 	case DDI_SUSPEND:
1420 
1421 		/*
1422 		 * Suspend/Resume
1423 		 *
1424 		 * To process DDI_SUSPEND, we must do the following:
1425 		 *
1426 		 *  - check ddi_removing_power to see if power will be turned
1427 		 *    off. if so, return DDI_FAILURE
1428 		 *  - check if we are already suspended,
1429 		 *    if so, return DDI_FAILURE
1430 		 *  - check if device state is CLOSED,
1431 		 *    if not, return DDI_FAILURE.
1432 		 *  - wait until outstanding operations complete
1433 		 *  - save tape state
1434 		 *  - block new operations
1435 		 *  - cancel pending timeouts
1436 		 *
1437 		 */
1438 
1439 		if (ddi_removing_power(devi)) {
1440 			return (DDI_FAILURE);
1441 		}
1442 		mutex_enter(ST_MUTEX);
1443 
1444 		/*
1445 		 * Shouldn't already be suspended, if so return failure
1446 		 */
1447 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1448 			mutex_exit(ST_MUTEX);
1449 			return (DDI_FAILURE);
1450 		}
1451 		if (un->un_state != ST_STATE_CLOSED) {
1452 			mutex_exit(ST_MUTEX);
1453 			return (DDI_FAILURE);
1454 		}
1455 
1456 		/*
1457 		 * Wait for all outstanding I/O's to complete
1458 		 *
1459 		 * we wait on both ncmds and the wait queue for times
1460 		 * when we are flushing after persistent errors are
1461 		 * flagged, which is when ncmds can be 0, and the
1462 		 * queue can still have I/O's.  This way we preserve
1463 		 * order of biodone's.
1464 		 */
1465 		wait_cmds_complete = ddi_get_lbolt();
1466 		wait_cmds_complete +=
1467 		    st_wait_cmds_complete * drv_usectohz(1000000);
1468 		while (un->un_ncmds || un->un_quef ||
1469 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1470 
1471 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1472 			    wait_cmds_complete) == -1) {
1473 				/*
1474 				 * Time expired then cancel the command
1475 				 */
1476 				if (st_reset(un, RESET_LUN) == 0) {
1477 					if (un->un_last_throttle) {
1478 						un->un_throttle =
1479 						    un->un_last_throttle;
1480 					}
1481 					mutex_exit(ST_MUTEX);
1482 					return (DDI_FAILURE);
1483 				} else {
1484 					break;
1485 				}
1486 			}
1487 		}
1488 
1489 		/*
1490 		 * DDI_SUSPEND says that the system "may" power down, we
1491 		 * remember the file and block number before rewinding.
1492 		 * we also need to save state before issuing
1493 		 * any WRITE_FILE_MARK command.
1494 		 */
1495 		(void) st_update_block_pos(un, st_cmd, 0);
1496 		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1497 
1498 
1499 		/*
1500 		 * Issue a zero write file fmk command to tell the drive to
1501 		 * flush any buffered tape marks
1502 		 */
1503 		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1504 
1505 		/*
1506 		 * Because not all tape drives correctly implement buffer
1507 		 * flushing with the zero write file fmk command, issue a
1508 		 * synchronous rewind command to force data flushing.
1509 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1510 		 * anyway.
1511 		 */
1512 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1513 
1514 		/* stop any new operations */
1515 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1516 		un->un_throttle = 0;
1517 
1518 		/*
1519 		 * cancel any outstanding timeouts
1520 		 */
1521 		if (un->un_delay_tid) {
1522 			timeout_id_t temp_id = un->un_delay_tid;
1523 			un->un_delay_tid = 0;
1524 			un->un_tids_at_suspend |= ST_DELAY_TID;
1525 			mutex_exit(ST_MUTEX);
1526 			(void) untimeout(temp_id);
1527 			mutex_enter(ST_MUTEX);
1528 		}
1529 
1530 		if (un->un_hib_tid) {
1531 			timeout_id_t temp_id = un->un_hib_tid;
1532 			un->un_hib_tid = 0;
1533 			un->un_tids_at_suspend |= ST_HIB_TID;
1534 			mutex_exit(ST_MUTEX);
1535 			(void) untimeout(temp_id);
1536 			mutex_enter(ST_MUTEX);
1537 		}
1538 
1539 		/*
1540 		 * Suspend the scsi_watch_thread
1541 		 */
1542 		if (un->un_swr_token) {
1543 			opaque_t temp_token = un->un_swr_token;
1544 			mutex_exit(ST_MUTEX);
1545 			scsi_watch_suspend(temp_token);
1546 		} else {
1547 			mutex_exit(ST_MUTEX);
1548 		}
1549 
1550 		return (DDI_SUCCESS);
1551 
1552 	default:
1553 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1554 		return (DDI_FAILURE);
1555 	}
1556 }
1557 
1558 
1559 /* ARGSUSED */
1560 static int
1561 st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1562 {
1563 	dev_t dev;
1564 	struct scsi_tape *un;
1565 	int instance, error;
1566 
1567 	ST_ENTR(dip, st_info);
1568 
1569 	switch (infocmd) {
1570 	case DDI_INFO_DEVT2DEVINFO:
1571 		dev = (dev_t)arg;
1572 		instance = MTUNIT(dev);
1573 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1574 			return (DDI_FAILURE);
1575 		*result = (void *) ST_DEVINFO;
1576 		error = DDI_SUCCESS;
1577 		break;
1578 	case DDI_INFO_DEVT2INSTANCE:
1579 		dev = (dev_t)arg;
1580 		instance = MTUNIT(dev);
1581 		*result = (void *)(uintptr_t)instance;
1582 		error = DDI_SUCCESS;
1583 		break;
1584 	default:
1585 		error = DDI_FAILURE;
1586 	}
1587 	return (error);
1588 }
1589 
1590 static int
1591 st_doattach(struct scsi_device *devp, int (*canwait)())
1592 {
1593 	struct scsi_tape *un = NULL;
1594 	recov_info *ri;
1595 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1596 	int instance;
1597 	size_t rlen;
1598 
1599 	ST_FUNC(devp->sd_dev, st_doattach);
1600 	/*
1601 	 * Call the routine scsi_probe to do some of the dirty work.
1602 	 * If the INQUIRY command succeeds, the field sd_inq in the
1603 	 * device structure will be filled in.
1604 	 */
1605 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1606 	    "st_doattach(): probing\n");
1607 
1608 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1609 
1610 		/*
1611 		 * In checking the whole inq_dtype byte we are looking at both
1612 		 * the Peripheral Qualifier and the Peripheral Device Type.
1613 		 * For this driver we are only interested in sequential devices
1614 		 * that are connected or capable if connecting to this logical
1615 		 * unit.
1616 		 */
1617 		if (devp->sd_inq->inq_dtype ==
1618 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1619 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1620 			    "probe exists\n");
1621 		} else {
1622 			/* Something there but not a tape device */
1623 			scsi_unprobe(devp);
1624 			return (DDI_FAILURE);
1625 		}
1626 	} else {
1627 		/* Nothing there */
1628 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1629 		    "probe failure: nothing there\n");
1630 		scsi_unprobe(devp);
1631 		return (DDI_FAILURE);
1632 	}
1633 
1634 
1635 	/*
1636 	 * The actual unit is present.
1637 	 * Now is the time to fill in the rest of our info..
1638 	 */
1639 	instance = ddi_get_instance(devp->sd_dev);
1640 
1641 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1642 		goto error;
1643 	}
1644 	un = ddi_get_soft_state(st_state, instance);
1645 
1646 	ASSERT(un != NULL);
1647 
1648 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1649 	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1650 	if (un->un_rqs_bp == NULL) {
1651 		goto error;
1652 	}
1653 	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1654 	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1655 	if (!un->un_rqs) {
1656 		goto error;
1657 	}
1658 	ASSERT(un->un_rqs->pkt_resid == 0);
1659 	devp->sd_sense =
1660 	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1661 	ASSERT(geterror(un->un_rqs_bp) == NULL);
1662 
1663 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1664 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1665 	FILL_SCSI1_LUN(devp, un->un_rqs);
1666 	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1667 	un->un_rqs->pkt_time = st_io_time;
1668 	un->un_rqs->pkt_comp = st_intr;
1669 	ri = (recov_info *)un->un_rqs->pkt_private;
1670 	if (st_recov_sz == sizeof (recov_info)) {
1671 		ri->privatelen = sizeof (recov_info);
1672 	} else {
1673 		ri->privatelen = sizeof (pkt_info);
1674 	}
1675 
1676 	un->un_sbufp = getrbuf(km_flags);
1677 	un->un_recov_buf = getrbuf(km_flags);
1678 
1679 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1680 
1681 	/*
1682 	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1683 	 * memory for DMA which doesn't require a DMA handle. ddi_iopb_alloc()
1684 	 * is obsolete and we want more flexibility in controlling the DMA
1685 	 * address constraints.
1686 	 */
1687 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1688 	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1689 	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1690 
1691 	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1692 	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1693 	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1694 
1695 	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1696 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1697 		    "probe partial failure: no space\n");
1698 		goto error;
1699 	}
1700 
1701 	bzero(un->un_mspl, sizeof (struct seq_mode));
1702 
1703 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1704 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1705 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1706 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1707 #ifdef	__x86
1708 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1709 #endif
1710 
1711 	/* Initialize power managemnet condition variable */
1712 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1713 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1714 	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1715 
1716 	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1717 	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1718 
1719 	ASSERT(un->un_recov_taskq != NULL);
1720 
1721 	un->un_pos.pmode = invalid;
1722 	un->un_sd	= devp;
1723 	un->un_swr_token = (opaque_t)NULL;
1724 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1725 	un->un_wormable = st_is_drive_worm;
1726 	un->un_media_id_method = st_get_media_identification;
1727 	/*
1728 	 * setting long a initial as it contains logical file info.
1729 	 * support for long format is mandatory but many drive don't do it.
1730 	 */
1731 	un->un_read_pos_type = LONG_POS;
1732 
1733 	un->un_suspend_pos.pmode = invalid;
1734 
1735 	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1736 
1737 #ifdef	__x86
1738 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1739 	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1740 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1741 		    "allocation of contiguous memory dma handle failed!");
1742 		un->un_contig_mem_hdl = NULL;
1743 		goto error;
1744 	}
1745 #endif
1746 
1747 	/*
1748 	 * Since this driver manages devices with "remote" hardware,
1749 	 * i.e. the devices themselves have no "reg" properties,
1750 	 * the SUSPEND/RESUME commands in detach/attach will not be
1751 	 * called by the power management framework unless we request
1752 	 * it by creating a "pm-hardware-state" property and setting it
1753 	 * to value "needs-suspend-resume".
1754 	 */
1755 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1756 	    "pm-hardware-state", "needs-suspend-resume") !=
1757 	    DDI_PROP_SUCCESS) {
1758 
1759 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1760 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1761 		goto error;
1762 	}
1763 
1764 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1765 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1766 
1767 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1768 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1769 		    "failed\n");
1770 		goto error;
1771 	}
1772 
1773 	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1774 	    st_reset_notification, (caddr_t)un);
1775 
1776 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1777 	return (DDI_SUCCESS);
1778 
1779 error:
1780 	devp->sd_sense = NULL;
1781 
1782 	ddi_remove_minor_node(devp->sd_dev, NULL);
1783 	if (un) {
1784 		if (un->un_mspl) {
1785 			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1786 		}
1787 		if (un->un_read_pos_data) {
1788 			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1789 		}
1790 		if (un->un_sbufp) {
1791 			freerbuf(un->un_sbufp);
1792 		}
1793 		if (un->un_recov_buf) {
1794 			freerbuf(un->un_recov_buf);
1795 		}
1796 		if (un->un_uscsi_rqs_buf) {
1797 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1798 		}
1799 #ifdef	__x86
1800 		if (un->un_contig_mem_hdl != NULL) {
1801 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1802 		}
1803 #endif
1804 		if (un->un_rqs) {
1805 			scsi_destroy_pkt(un->un_rqs);
1806 		}
1807 
1808 		if (un->un_rqs_bp) {
1809 			scsi_free_consistent_buf(un->un_rqs_bp);
1810 		}
1811 
1812 		ddi_soft_state_free(st_state, instance);
1813 		devp->sd_private = NULL;
1814 	}
1815 
1816 	if (devp->sd_inq) {
1817 		scsi_unprobe(devp);
1818 	}
1819 	return (DDI_FAILURE);
1820 }
1821 
1822 typedef int
1823 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1824 
1825 static cfg_functp config_functs[] = {
1826 	st_get_conf_from_st_dot_conf,
1827 	st_get_conf_from_st_conf_dot_c,
1828 	st_get_conf_from_tape_drive,
1829 	st_get_default_conf
1830 };
1831 
1832 
1833 /*
1834  * determine tape type, using tape-config-list or built-in table or
1835  * use a generic tape config entry
1836  */
1837 static void
1838 st_known_tape_type(struct scsi_tape *un)
1839 {
1840 	struct st_drivetype *dp;
1841 	cfg_functp *config_funct;
1842 	uchar_t reserved;
1843 
1844 	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1845 
1846 	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1847 	    : ST_RELEASE;
1848 
1849 	/*
1850 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1851 	 *	 no vid & pid inquiry data.  So, we provide one.
1852 	 */
1853 	if (ST_INQUIRY->inq_len == 0 ||
1854 	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1855 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1856 	}
1857 
1858 	if (un->un_dp_size == 0) {
1859 		un->un_dp_size = sizeof (struct st_drivetype);
1860 		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1861 		un->un_dp = dp;
1862 	} else {
1863 		dp = un->un_dp;
1864 	}
1865 
1866 	un->un_dp->non_motion_timeout = st_io_time;
1867 	/*
1868 	 * Loop through the configuration methods till one works.
1869 	 */
1870 	for (config_funct = &config_functs[0]; ; config_funct++) {
1871 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1872 			break;
1873 		}
1874 	}
1875 
1876 	/*
1877 	 * If we didn't just make up this configuration and
1878 	 * all the density codes are the same..
1879 	 * Set Auto Density over ride.
1880 	 */
1881 	if (*config_funct != st_get_default_conf) {
1882 		/*
1883 		 * If this device is one that is configured and all
1884 		 * densities are the same, This saves doing gets and set
1885 		 * that yield nothing.
1886 		 */
1887 		if ((dp->densities[0]) == (dp->densities[1]) &&
1888 		    (dp->densities[0]) == (dp->densities[2]) &&
1889 		    (dp->densities[0]) == (dp->densities[3])) {
1890 
1891 			dp->options |= ST_AUTODEN_OVERRIDE;
1892 		}
1893 	}
1894 
1895 
1896 	/*
1897 	 * Store tape drive characteristics.
1898 	 */
1899 	un->un_status = 0;
1900 	un->un_attached = 1;
1901 	un->un_init_options = dp->options;
1902 
1903 	/* setup operation time-outs based on options */
1904 	st_calculate_timeouts(un);
1905 
1906 	/* make sure if we are supposed to be variable, make it variable */
1907 	if (dp->options & ST_VARIABLE) {
1908 		dp->bsize = 0;
1909 	}
1910 
1911 	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1912 	    : ST_RELEASE)) {
1913 		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1914 	}
1915 
1916 	un->un_unit_attention_flags |= 1;
1917 
1918 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1919 
1920 }
1921 
1922 
1923 typedef struct {
1924 	int mask;
1925 	int bottom;
1926 	int top;
1927 	char *name;
1928 } conf_limit;
1929 
1930 static const conf_limit conf_limits[] = {
1931 
1932 	-1,		1,		2,		"conf version",
1933 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1934 	-1,		0,		0xffffff,	"block size",
1935 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1936 	-1,		0,		4,		"number of densities",
1937 	-1,		0,		UINT8_MAX,	"density code",
1938 	-1,		0,		3,		"default density",
1939 	-1,		0,		UINT16_MAX,	"non motion timeout",
1940 	-1,		0,		UINT16_MAX,	"I/O timeout",
1941 	-1,		0,		UINT16_MAX,	"space timeout",
1942 	-1,		0,		UINT16_MAX,	"load timeout",
1943 	-1,		0,		UINT16_MAX,	"unload timeout",
1944 	-1,		0,		UINT16_MAX,	"erase timeout",
1945 	0,		0,		0,		NULL
1946 };
1947 
1948 static int
1949 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1950     const char *conf_name)
1951 {
1952 	int dens;
1953 	int ndens;
1954 	int value;
1955 	int type;
1956 	int count;
1957 	const conf_limit *limit = &conf_limits[0];
1958 
1959 	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1960 
1961 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1962 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1963 
1964 	count = list_len;
1965 	type = *list;
1966 	for (;  count && limit->name; count--, list++, limit++) {
1967 
1968 		value = *list;
1969 		if (value & ~limit->mask) {
1970 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1971 			    "%s %s value invalid bits set: 0x%X\n",
1972 			    conf_name, limit->name, value & ~limit->mask);
1973 			*list &= limit->mask;
1974 		} else if (value < limit->bottom) {
1975 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1976 			    "%s %s value too low: value = %d limit %d\n",
1977 			    conf_name, limit->name, value, limit->bottom);
1978 		} else if (value > limit->top) {
1979 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1980 			    "%s %s value too high: value = %d limit %d\n",
1981 			    conf_name, limit->name, value, limit->top);
1982 		} else {
1983 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1984 			    "%s %s value = 0x%X\n",
1985 			    conf_name, limit->name, value);
1986 		}
1987 
1988 		/* If not the number of densities continue */
1989 		if (limit != &conf_limits[4]) {
1990 			continue;
1991 		}
1992 
1993 		/* If number of densities is not in range can't use config */
1994 		if (value < limit->bottom || value > limit->top) {
1995 			return (-1);
1996 		}
1997 
1998 		ndens = min(value, NDENSITIES);
1999 		if ((type == 1) && (list_len - ndens) != 6) {
2000 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2001 			    "%s conf version 1 with %d densities has %d items"
2002 			    " should have %d",
2003 			    conf_name, ndens, list_len, 6 + ndens);
2004 		} else if ((type == 2) && (list_len - ndens) != 13) {
2005 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2006 			    "%s conf version 2 with %d densities has %d items"
2007 			    " should have %d",
2008 			    conf_name, ndens, list_len, 13 + ndens);
2009 		}
2010 
2011 		limit++;
2012 		for (dens = 0; dens < ndens && count; dens++) {
2013 			count--;
2014 			list++;
2015 			value = *list;
2016 			if (value < limit->bottom) {
2017 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2018 				    "%s density[%d] value too low: value ="
2019 				    " 0x%X limit 0x%X\n",
2020 				    conf_name, dens, value, limit->bottom);
2021 			} else if (value > limit->top) {
2022 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2023 				    "%s density[%d] value too high: value ="
2024 				    " 0x%X limit 0x%X\n",
2025 				    conf_name, dens, value, limit->top);
2026 			} else {
2027 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2028 				    "%s density[%d] value = 0x%X\n",
2029 				    conf_name, dens, value);
2030 			}
2031 		}
2032 	}
2033 
2034 	return (0);
2035 }
2036 
2037 static int
2038 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2039     struct st_drivetype *dp)
2040 {
2041 	caddr_t config_list = NULL;
2042 	caddr_t data_list = NULL;
2043 	int	*data_ptr;
2044 	caddr_t vidptr, prettyptr, datanameptr;
2045 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2046 	int config_list_len, data_list_len, len, i;
2047 	int version;
2048 	int found = 0;
2049 
2050 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2051 
2052 	/*
2053 	 * Determine type of tape controller. Type is determined by
2054 	 * checking the vendor ids of the earlier inquiry command and
2055 	 * comparing those with vids in tape-config-list defined in st.conf
2056 	 */
2057 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2058 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2059 	    != DDI_PROP_SUCCESS) {
2060 		return (found);
2061 	}
2062 
2063 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2064 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2065 
2066 	/*
2067 	 * Compare vids in each triplet - if it matches, get value for
2068 	 * data_name and contruct a st_drivetype struct
2069 	 * tripletlen is not set yet!
2070 	 */
2071 	for (len = config_list_len, vidptr = config_list;
2072 	    len > 0;
2073 	    vidptr += tripletlen, len -= tripletlen) {
2074 
2075 		vidlen = strlen(vidptr);
2076 		prettyptr = vidptr + vidlen + 1;
2077 		prettylen = strlen(prettyptr);
2078 		datanameptr = prettyptr + prettylen + 1;
2079 		datanamelen = strlen(datanameptr);
2080 		tripletlen = vidlen + prettylen + datanamelen + 3;
2081 
2082 		if (vidlen == 0) {
2083 			continue;
2084 		}
2085 
2086 		/*
2087 		 * If inquiry vid dosen't match this triplets vid,
2088 		 * try the next.
2089 		 */
2090 		if (strncasecmp(vidpid, vidptr, vidlen)) {
2091 			continue;
2092 		}
2093 
2094 		/*
2095 		 * if prettylen is zero then use the vid string
2096 		 */
2097 		if (prettylen == 0) {
2098 			prettyptr = vidptr;
2099 			prettylen = vidlen;
2100 		}
2101 
2102 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2103 		    "vid = %s, pretty=%s, dataname = %s\n",
2104 		    vidptr, prettyptr, datanameptr);
2105 
2106 		/*
2107 		 * get the data list
2108 		 */
2109 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2110 		    datanameptr, (caddr_t)&data_list,
2111 		    &data_list_len) != DDI_PROP_SUCCESS) {
2112 			/*
2113 			 * Error in getting property value
2114 			 * print warning!
2115 			 */
2116 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2117 			    "data property (%s) has no value\n",
2118 			    datanameptr);
2119 			continue;
2120 		}
2121 
2122 		/*
2123 		 * now initialize the st_drivetype struct
2124 		 */
2125 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2126 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2127 		(void) strncpy(dp->vid, vidptr, dp->length);
2128 		data_ptr = (int *)data_list;
2129 		/*
2130 		 * check if data is enough for version, type,
2131 		 * bsize, options, # of densities, density1,
2132 		 * density2, ..., default_density
2133 		 */
2134 		if ((data_list_len < 5 * sizeof (int)) ||
2135 		    (data_list_len < 6 * sizeof (int) +
2136 		    *(data_ptr + 4) * sizeof (int))) {
2137 			/*
2138 			 * print warning and skip to next triplet.
2139 			 */
2140 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2141 			    "data property (%s) incomplete\n",
2142 			    datanameptr);
2143 			kmem_free(data_list, data_list_len);
2144 			continue;
2145 		}
2146 
2147 		if (st_validate_conf_data(un, data_ptr,
2148 		    data_list_len / sizeof (int), datanameptr)) {
2149 			kmem_free(data_list, data_list_len);
2150 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2151 			    "data property (%s) rejected\n",
2152 			    datanameptr);
2153 			continue;
2154 		}
2155 
2156 		/*
2157 		 * check version
2158 		 */
2159 		version = *data_ptr++;
2160 		if (version != 1 && version != 2) {
2161 			/* print warning but accept it */
2162 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2163 			    "Version # for data property (%s) "
2164 			    "not set to 1 or 2\n", datanameptr);
2165 		}
2166 
2167 		dp->type    = *data_ptr++;
2168 		dp->bsize   = *data_ptr++;
2169 		dp->options = *data_ptr++;
2170 		dp->options |= ST_DYNAMIC;
2171 		len = *data_ptr++;
2172 		for (i = 0; i < NDENSITIES; i++) {
2173 			if (i < len) {
2174 				dp->densities[i] = *data_ptr++;
2175 			}
2176 		}
2177 		dp->default_density = *data_ptr << 3;
2178 		if (version == 2 &&
2179 		    data_list_len >= (13 + len) * sizeof (int)) {
2180 			data_ptr++;
2181 			dp->non_motion_timeout	= *data_ptr++;
2182 			dp->io_timeout		= *data_ptr++;
2183 			dp->rewind_timeout	= *data_ptr++;
2184 			dp->space_timeout	= *data_ptr++;
2185 			dp->load_timeout	= *data_ptr++;
2186 			dp->unload_timeout	= *data_ptr++;
2187 			dp->erase_timeout	= *data_ptr++;
2188 		}
2189 		kmem_free(data_list, data_list_len);
2190 		found = 1;
2191 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2192 		    "found in st.conf: vid = %s, pretty=%s\n",
2193 		    dp->vid, dp->name);
2194 		break;
2195 	}
2196 
2197 	/*
2198 	 * free up the memory allocated by ddi_getlongprop
2199 	 */
2200 	if (config_list) {
2201 		kmem_free(config_list, config_list_len);
2202 	}
2203 	return (found);
2204 }
2205 
2206 static int
2207 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2208     struct st_drivetype *dp)
2209 {
2210 	int i;
2211 
2212 	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2213 	/*
2214 	 * Determine type of tape controller.  Type is determined by
2215 	 * checking the result of the earlier inquiry command and
2216 	 * comparing vendor ids with strings in a table declared in st_conf.c.
2217 	 */
2218 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2219 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2220 
2221 	for (i = 0; i < st_ndrivetypes; i++) {
2222 		if (st_drivetypes[i].length == 0) {
2223 			continue;
2224 		}
2225 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2226 		    st_drivetypes[i].length)) {
2227 			continue;
2228 		}
2229 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2230 		return (1);
2231 	}
2232 	return (0);
2233 }
2234 
2235 static int
2236 st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2237     struct st_drivetype *dp)
2238 {
2239 	int bsize;
2240 	ulong_t maxbsize;
2241 	caddr_t buf;
2242 	struct st_drivetype *tem_dp;
2243 	struct read_blklim *blklim;
2244 	int rval;
2245 	int i;
2246 
2247 	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2248 
2249 	/*
2250 	 * Determine the type of tape controller. Type is determined by
2251 	 * sending SCSI commands to tape drive and deriving the type from
2252 	 * the returned data.
2253 	 */
2254 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2255 	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2256 
2257 	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2258 
2259 	/*
2260 	 * Make up a name
2261 	 */
2262 	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2263 	tem_dp->name[VIDPIDLEN] = '\0';
2264 	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2265 	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2266 	/*
2267 	 * 'clean' vendor and product strings of non-printing chars
2268 	 */
2269 	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2270 		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2271 			tem_dp->name[i] = '.';
2272 		}
2273 	}
2274 
2275 	/*
2276 	 * MODE SENSE to determine block size.
2277 	 */
2278 	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2279 	rval = st_modesense(un);
2280 	if (rval) {
2281 		if (rval == EACCES) {
2282 			un->un_dp->type = ST_TYPE_INVALID;
2283 			rval = 1;
2284 		} else {
2285 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2286 			rval = 0;
2287 		}
2288 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2289 		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2290 		goto exit;
2291 	}
2292 
2293 	/* Can mode sense page 0x10 or 0xf */
2294 	tem_dp->options |= ST_MODE_SEL_COMP;
2295 	bsize = (un->un_mspl->high_bl << 16)	|
2296 	    (un->un_mspl->mid_bl << 8)		|
2297 	    (un->un_mspl->low_bl);
2298 
2299 	if (bsize == 0) {
2300 		tem_dp->options |= ST_VARIABLE;
2301 		tem_dp->bsize = 0;
2302 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2303 		rval = st_change_block_size(un, 0);
2304 		if (rval) {
2305 			if (rval == EACCES) {
2306 				un->un_dp->type = ST_TYPE_INVALID;
2307 				rval = 1;
2308 			} else {
2309 				rval = 0;
2310 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2311 				    "st_get_conf_from_tape_drive(): "
2312 				    "Fixed record size is too large and"
2313 				    "cannot switch to variable record size");
2314 			}
2315 			goto exit;
2316 		}
2317 		tem_dp->options |= ST_VARIABLE;
2318 	} else {
2319 		rval = st_change_block_size(un, 0);
2320 		if (rval == 0) {
2321 			tem_dp->options |= ST_VARIABLE;
2322 			tem_dp->bsize = 0;
2323 		} else if (rval != EACCES) {
2324 			tem_dp->bsize = bsize;
2325 		} else {
2326 			un->un_dp->type = ST_TYPE_INVALID;
2327 			rval = 1;
2328 			goto exit;
2329 		}
2330 	}
2331 
2332 	/*
2333 	 * If READ BLOCk LIMITS works and upper block size limit is
2334 	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2335 	 */
2336 	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2337 	rval = st_read_block_limits(un, blklim);
2338 	if (rval) {
2339 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2340 		    "st_get_conf_from_tape_drive(): "
2341 		    "fail to read block limits.\n");
2342 		rval = 0;
2343 		kmem_free(blklim, sizeof (struct read_blklim));
2344 		goto exit;
2345 	}
2346 	maxbsize = (blklim->max_hi << 16) +
2347 	    (blklim->max_mid << 8) + blklim->max_lo;
2348 	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2349 		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2350 	}
2351 	kmem_free(blklim, sizeof (struct read_blklim));
2352 
2353 	/*
2354 	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2355 	 */
2356 	buf = kmem_zalloc(6, KM_SLEEP);
2357 	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2358 	if (rval) {
2359 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2360 		    "st_get_conf_from_tape_drive(): "
2361 		    "fail to read vitial inquiry.\n");
2362 		rval = 0;
2363 		kmem_free(buf, 6);
2364 		goto exit;
2365 	}
2366 	if (buf[4] & 1) {
2367 		tem_dp->options |= ST_WORMABLE;
2368 	}
2369 	kmem_free(buf, 6);
2370 
2371 	/* Assume BSD BSR KNOWS_EOD */
2372 	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2373 	tem_dp->max_rretries = -1;
2374 	tem_dp->max_wretries = -1;
2375 
2376 	/*
2377 	 * Decide the densities supported by tape drive by sending
2378 	 * REPORT DENSITY SUPPORT command.
2379 	 */
2380 	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2381 		goto exit;
2382 	}
2383 
2384 	/*
2385 	 * Decide the timeout values for several commands by sending
2386 	 * REPORT SUPPORTED OPERATION CODES command.
2387 	 */
2388 	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2389 	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2390 		goto exit;
2391 	}
2392 
2393 	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2394 	rval = 1;
2395 
2396 exit:
2397 	un->un_status = KEY_NO_SENSE;
2398 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2399 	return (rval);
2400 }
2401 
2402 static int
2403 st_get_densities_from_tape_drive(struct scsi_tape *un,
2404     struct st_drivetype *dp)
2405 {
2406 	int i, p;
2407 	size_t buflen;
2408 	ushort_t des_len;
2409 	uchar_t *den_header;
2410 	uchar_t num_den;
2411 	uchar_t den[NDENSITIES];
2412 	uchar_t deflt[NDENSITIES];
2413 	struct report_density_desc *den_desc;
2414 
2415 	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2416 
2417 	/*
2418 	 * Since we have no idea how many densitiy support entries
2419 	 * will be returned, we send the command firstly assuming
2420 	 * there is only one. Then we can decide the number of
2421 	 * entries by available density support length. If multiple
2422 	 * entries exist, we will resend the command with enough
2423 	 * buffer size.
2424 	 */
2425 	buflen = sizeof (struct report_density_header) +
2426 	    sizeof (struct report_density_desc);
2427 	den_header = kmem_zalloc(buflen, KM_SLEEP);
2428 	if (st_report_density_support(un, den_header, buflen) != 0) {
2429 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2430 		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2431 		kmem_free(den_header, buflen);
2432 		return (0);
2433 	}
2434 	des_len =
2435 	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2436 	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2437 
2438 	if (num_den > 1) {
2439 		kmem_free(den_header, buflen);
2440 		buflen = sizeof (struct report_density_header) +
2441 		    sizeof (struct report_density_desc) * num_den;
2442 		den_header = kmem_zalloc(buflen, KM_SLEEP);
2443 		if (st_report_density_support(un, den_header, buflen) != 0) {
2444 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2445 			    "st_get_conf_from_tape_drive(): "
2446 			    "fail to report density.\n");
2447 			kmem_free(den_header, buflen);
2448 			return (0);
2449 		}
2450 	}
2451 
2452 	den_desc = (struct report_density_desc *)(den_header
2453 	    + sizeof (struct report_density_header));
2454 
2455 	/*
2456 	 * Decide the drive type by assigning organization
2457 	 */
2458 	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2459 		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2460 		    8) == 0) {
2461 			dp->type = st_vid_dt[i].type;
2462 			break;
2463 		}
2464 	}
2465 	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2466 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2467 		    "st_get_conf_from_tape_drive(): "
2468 		    "can't find match of assigned ort.\n");
2469 		kmem_free(den_header, buflen);
2470 		return (0);
2471 	}
2472 
2473 	/*
2474 	 * The tape drive may support many tape formats, but the st driver
2475 	 * supports only the four highest densities. Since density code
2476 	 * values are returned by ascending sequence, we start from the
2477 	 * last entry of density support data block descriptor.
2478 	 */
2479 	p = 0;
2480 	den_desc += num_den - 1;
2481 	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2482 		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2483 			if (p != 0) {
2484 				if (den_desc->pri_den >= den[p - 1]) {
2485 					continue;
2486 				}
2487 			}
2488 			den[p] = den_desc->pri_den;
2489 			deflt[p] = den_desc->deflt;
2490 			p ++;
2491 		}
2492 	}
2493 
2494 	switch (p) {
2495 	case 0:
2496 		bzero(dp->densities, NDENSITIES);
2497 		dp->options |= ST_AUTODEN_OVERRIDE;
2498 		dp->default_density = MT_DENSITY4;
2499 		break;
2500 
2501 	case 1:
2502 		(void) memset(dp->densities, den[0], NDENSITIES);
2503 		dp->options |= ST_AUTODEN_OVERRIDE;
2504 		dp->default_density = MT_DENSITY4;
2505 		break;
2506 
2507 	case 2:
2508 		dp->densities[0] = den[1];
2509 		dp->densities[1] = den[1];
2510 		dp->densities[2] = den[0];
2511 		dp->densities[3] = den[0];
2512 		if (deflt[0]) {
2513 			dp->default_density = MT_DENSITY4;
2514 		} else {
2515 			dp->default_density = MT_DENSITY2;
2516 		}
2517 		break;
2518 
2519 	case 3:
2520 		dp->densities[0] = den[2];
2521 		dp->densities[1] = den[1];
2522 		dp->densities[2] = den[0];
2523 		dp->densities[3] = den[0];
2524 		if (deflt[0]) {
2525 			dp->default_density = MT_DENSITY4;
2526 		} else if (deflt[1]) {
2527 			dp->default_density = MT_DENSITY2;
2528 		} else {
2529 			dp->default_density = MT_DENSITY1;
2530 		}
2531 		break;
2532 
2533 	default:
2534 		for (i = p; i > p - NDENSITIES; i --) {
2535 			dp->densities[i - 1] = den[p - i];
2536 		}
2537 		if (deflt[0]) {
2538 			dp->default_density = MT_DENSITY4;
2539 		} else if (deflt[1]) {
2540 			dp->default_density = MT_DENSITY3;
2541 		} else if (deflt[2]) {
2542 			dp->default_density = MT_DENSITY2;
2543 		} else {
2544 			dp->default_density = MT_DENSITY1;
2545 		}
2546 		break;
2547 	}
2548 
2549 	bzero(dp->mediatype, NDENSITIES);
2550 
2551 	kmem_free(den_header, buflen);
2552 	return (1);
2553 }
2554 
2555 static int
2556 st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2557     struct st_drivetype *dp)
2558 {
2559 	ushort_t timeout;
2560 	int rval;
2561 
2562 	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2563 
2564 	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2565 	if (rval) {
2566 		if (rval == EACCES) {
2567 			un->un_dp->type = ST_TYPE_INVALID;
2568 			dp->type = ST_TYPE_INVALID;
2569 			return (1);
2570 		}
2571 		return (0);
2572 	}
2573 	dp->erase_timeout = timeout;
2574 
2575 	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2576 	if (rval) {
2577 		if (rval == EACCES) {
2578 			un->un_dp->type = ST_TYPE_INVALID;
2579 			dp->type = ST_TYPE_INVALID;
2580 			return (1);
2581 		}
2582 		return (0);
2583 	}
2584 	dp->io_timeout = timeout;
2585 
2586 	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2587 	if (rval) {
2588 		if (rval == EACCES) {
2589 			un->un_dp->type = ST_TYPE_INVALID;
2590 			dp->type = ST_TYPE_INVALID;
2591 			return (1);
2592 		}
2593 		return (0);
2594 	}
2595 	dp->io_timeout = max(dp->io_timeout, timeout);
2596 
2597 	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2598 	if (rval) {
2599 		if (rval == EACCES) {
2600 			un->un_dp->type = ST_TYPE_INVALID;
2601 			dp->type = ST_TYPE_INVALID;
2602 			return (1);
2603 		}
2604 		return (0);
2605 	}
2606 	dp->space_timeout = timeout;
2607 
2608 	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2609 	if (rval) {
2610 		if (rval == EACCES) {
2611 			un->un_dp->type = ST_TYPE_INVALID;
2612 			dp->type = ST_TYPE_INVALID;
2613 			return (1);
2614 		}
2615 		return (0);
2616 	}
2617 	dp->load_timeout = timeout;
2618 	dp->unload_timeout = timeout;
2619 
2620 	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2621 	if (rval) {
2622 		if (rval == EACCES) {
2623 			un->un_dp->type = ST_TYPE_INVALID;
2624 			dp->type = ST_TYPE_INVALID;
2625 			return (1);
2626 		}
2627 		return (0);
2628 	}
2629 	dp->rewind_timeout = timeout;
2630 
2631 	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2632 	if (rval) {
2633 		if (rval == EACCES) {
2634 			un->un_dp->type = ST_TYPE_INVALID;
2635 			dp->type = ST_TYPE_INVALID;
2636 			return (1);
2637 		}
2638 		return (0);
2639 	}
2640 	dp->non_motion_timeout = timeout;
2641 
2642 	return (1);
2643 }
2644 
2645 static int
2646 st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2647     ushort_t *timeout_value, ushort_t service_action)
2648 {
2649 	uchar_t *timeouts;
2650 	uchar_t *oper;
2651 	uchar_t support;
2652 	uchar_t cdbsize;
2653 	uchar_t ctdp;
2654 	size_t buflen;
2655 	int rval;
2656 
2657 	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2658 
2659 	buflen = sizeof (struct one_com_des) +
2660 	    sizeof (struct com_timeout_des);
2661 	oper = kmem_zalloc(buflen, KM_SLEEP);
2662 	rval = st_report_supported_operation(un, oper, option_code,
2663 	    service_action);
2664 
2665 	if (rval) {
2666 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2667 		    "st_get_timeouts_value(): "
2668 		    "fail to timeouts value for command %d.\n", option_code);
2669 		kmem_free(oper, buflen);
2670 		return (rval);
2671 	}
2672 
2673 	support = ((struct one_com_des *)oper)->support;
2674 	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2675 	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2676 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2677 		    "st_get_timeouts_value(): "
2678 		    "command %d is not supported.\n", option_code);
2679 		kmem_free(oper, buflen);
2680 		return (ENOTSUP);
2681 	}
2682 
2683 	ctdp = ((struct one_com_des *)oper)->ctdp;
2684 	if (!ctdp) {
2685 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2686 		    "st_get_timeouts_value(): "
2687 		    "command timeout is not included.\n");
2688 		kmem_free(oper, buflen);
2689 		return (ENOTSUP);
2690 	}
2691 
2692 	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2693 	timeouts = (uchar_t *)(oper + cdbsize + 4);
2694 
2695 	/*
2696 	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2697 	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2698 	 * to 0xFFFF.
2699 	 */
2700 	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2701 		*timeout_value = USHRT_MAX;
2702 	} else {
2703 		*timeout_value = ((*(timeouts + 10)) << 8) |
2704 		    (*(timeouts + 11));
2705 	}
2706 
2707 	kmem_free(oper, buflen);
2708 	return (0);
2709 }
2710 
2711 static int
2712 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2713 {
2714 	int i;
2715 
2716 	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2717 
2718 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2719 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2720 
2721 	/*
2722 	 * Make up a name
2723 	 */
2724 	bcopy("Vendor '", dp->name, 8);
2725 	bcopy(vidpid, &dp->name[8], VIDLEN);
2726 	bcopy("' Product '", &dp->name[16], 11);
2727 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2728 	dp->name[ST_NAMESIZE - 2] = '\'';
2729 	dp->name[ST_NAMESIZE - 1] = '\0';
2730 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2731 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2732 	/*
2733 	 * 'clean' vendor and product strings of non-printing chars
2734 	 */
2735 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2736 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2737 			dp->name[i] = '.';
2738 		}
2739 	}
2740 	dp->type = ST_TYPE_INVALID;
2741 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2742 
2743 	return (1); /* Can Not Fail */
2744 }
2745 
2746 /*
2747  * Regular Unix Entry points
2748  */
2749 
2750 
2751 
2752 /* ARGSUSED */
2753 static int
2754 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2755 {
2756 	dev_t dev = *dev_p;
2757 	int rval = 0;
2758 
2759 	GET_SOFT_STATE(dev);
2760 
2761 	ST_ENTR(ST_DEVINFO, st_open);
2762 
2763 	/*
2764 	 * validate that we are addressing a sensible unit
2765 	 */
2766 	mutex_enter(ST_MUTEX);
2767 
2768 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2769 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2770 	    st_dev_name(dev), *dev_p, flag, otyp);
2771 
2772 	/*
2773 	 * All device accesss go thru st_strategy() where we check
2774 	 * suspend status
2775 	 */
2776 
2777 	if (!un->un_attached) {
2778 		st_known_tape_type(un);
2779 		if (!un->un_attached) {
2780 			rval = ENXIO;
2781 			goto exit;
2782 		}
2783 
2784 	}
2785 
2786 	/*
2787 	 * Check for the case of the tape in the middle of closing.
2788 	 * This isn't simply a check of the current state, because
2789 	 * we could be in state of sensing with the previous state
2790 	 * that of closing.
2791 	 *
2792 	 * And don't allow multiple opens.
2793 	 */
2794 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2795 		un->un_laststate = un->un_state;
2796 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2797 		while (IS_CLOSING(un) ||
2798 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2799 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2800 				rval = EINTR;
2801 				un->un_state = un->un_laststate;
2802 				goto exit;
2803 			}
2804 		}
2805 	} else if (un->un_state != ST_STATE_CLOSED) {
2806 		rval = EBUSY;
2807 		goto busy;
2808 	}
2809 
2810 	/*
2811 	 * record current dev
2812 	 */
2813 	un->un_dev = dev;
2814 	un->un_oflags = flag;	/* save for use in st_tape_init() */
2815 	un->un_errno = 0;	/* no errors yet */
2816 	un->un_restore_pos = 0;
2817 	un->un_rqs_state = 0;
2818 
2819 	/*
2820 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2821 	 * anything, leave internal states alone, if fileno >= 0
2822 	 */
2823 	if (flag & (FNDELAY | FNONBLOCK)) {
2824 		switch (un->un_pos.pmode) {
2825 
2826 		case invalid:
2827 			un->un_state = ST_STATE_OFFLINE;
2828 			break;
2829 
2830 		case legacy:
2831 			/*
2832 			 * If position is anything other than rewound.
2833 			 */
2834 			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2835 				/*
2836 				 * set un_read_only/write-protect status.
2837 				 *
2838 				 * If the tape is not bot we can assume
2839 				 * that mspl->wp_status is set properly.
2840 				 * else
2841 				 * we need to do a mode sense/Tur once
2842 				 * again to get the actual tape status.(since
2843 				 * user might have replaced the tape)
2844 				 * Hence make the st state OFFLINE so that
2845 				 * we re-intialize the tape once again.
2846 				 */
2847 				un->un_read_only =
2848 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2849 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2850 			} else {
2851 				un->un_state = ST_STATE_OFFLINE;
2852 			}
2853 			break;
2854 		case logical:
2855 			if (un->un_pos.lgclblkno == 0) {
2856 				un->un_state = ST_STATE_OFFLINE;
2857 			} else {
2858 				un->un_read_only =
2859 				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2860 				un->un_state = ST_STATE_OPEN_PENDING_IO;
2861 			}
2862 			break;
2863 		}
2864 		rval = 0;
2865 	} else {
2866 		/*
2867 		 * Not opening O_NDELAY.
2868 		 */
2869 		un->un_state = ST_STATE_OPENING;
2870 
2871 		/*
2872 		 * Clear error entry stack
2873 		 */
2874 		st_empty_error_stack(un);
2875 
2876 		rval = st_tape_init(un);
2877 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2878 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2879 			rval = 0; /* so open doesn't fail */
2880 		} else if (rval) {
2881 			/*
2882 			 * Release the tape unit, if reserved and not
2883 			 * preserve reserve.
2884 			 */
2885 			if ((un->un_rsvd_status &
2886 			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2887 				(void) st_reserve_release(un, ST_RELEASE,
2888 				    st_uscsi_cmd);
2889 			}
2890 		} else {
2891 			un->un_state = ST_STATE_OPEN_PENDING_IO;
2892 		}
2893 	}
2894 
2895 exit:
2896 	/*
2897 	 * we don't want any uninvited guests scrogging our data when we're
2898 	 * busy with something, so for successful opens or failed opens
2899 	 * (except for EBUSY), reset these counters and state appropriately.
2900 	 */
2901 	if (rval != EBUSY) {
2902 		if (rval) {
2903 			un->un_state = ST_STATE_CLOSED;
2904 		}
2905 		un->un_err_resid = 0;
2906 		un->un_retry_ct = 0;
2907 	}
2908 busy:
2909 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2910 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2911 	mutex_exit(ST_MUTEX);
2912 	return (rval);
2913 
2914 }
2915 
2916 static int
2917 st_tape_init(struct scsi_tape *un)
2918 {
2919 	int err;
2920 	int rval = 0;
2921 
2922 	ST_FUNC(ST_DEVINFO, st_tape_init);
2923 
2924 	ASSERT(mutex_owned(ST_MUTEX));
2925 
2926 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2927 	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2928 
2929 	/*
2930 	 * Clean up after any errors left by 'last' close.
2931 	 * This also handles the case of the initial open.
2932 	 */
2933 	if (un->un_state != ST_STATE_INITIALIZING) {
2934 		un->un_laststate = un->un_state;
2935 		un->un_state = ST_STATE_OPENING;
2936 	}
2937 
2938 	un->un_kbytes_xferred = 0;
2939 
2940 	/*
2941 	 * do a throw away TUR to clear check condition
2942 	 */
2943 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2944 
2945 	/*
2946 	 * If test unit ready fails because the drive is reserved
2947 	 * by another host fail the open for no access.
2948 	 */
2949 	if (err) {
2950 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2951 			un->un_state = ST_STATE_CLOSED;
2952 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2953 			    "st_tape_init: RESERVATION CONFLICT\n");
2954 			rval = EACCES;
2955 			goto exit;
2956 		} else if ((un->un_rsvd_status &
2957 		    ST_APPLICATION_RESERVATIONS) != 0) {
2958 			if ((ST_RQSENSE != NULL) &&
2959 			    (ST_RQSENSE->es_add_code == 0x2a &&
2960 			    ST_RQSENSE->es_qual_code == 0x03)) {
2961 				un->un_state = ST_STATE_CLOSED;
2962 				rval = EACCES;
2963 				goto exit;
2964 			}
2965 		}
2966 	}
2967 
2968 	/*
2969 	 * Tape self identification could fail if the tape drive is used by
2970 	 * another host during attach time. We try to get the tape type
2971 	 * again. This is also applied to any posponed configuration methods.
2972 	 */
2973 	if (un->un_dp->type == ST_TYPE_INVALID) {
2974 		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
2975 		st_known_tape_type(un);
2976 	}
2977 
2978 	/*
2979 	 * If the tape type is still invalid, try to determine the generic
2980 	 * configuration.
2981 	 */
2982 	if (un->un_dp->type == ST_TYPE_INVALID) {
2983 		rval = st_determine_generic(un);
2984 		if (rval) {
2985 			if (rval != EACCES) {
2986 				rval = EIO;
2987 			}
2988 			un->un_state = ST_STATE_CLOSED;
2989 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2990 			    "st_tape_init: %s invalid type\n",
2991 			    rval == EACCES ? "EACCES" : "EIO");
2992 			goto exit;
2993 		}
2994 		/*
2995 		 * If this is a Unknown Type drive,
2996 		 * Use the READ BLOCK LIMITS to determine if
2997 		 * allow large xfer is approprate if not globally
2998 		 * disabled with st_allow_large_xfer.
2999 		 */
3000 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3001 	} else {
3002 
3003 		/*
3004 		 * If we allow_large_xfer (ie >64k) and have not yet found out
3005 		 * the max block size supported by the drive,
3006 		 * find it by issueing a READ_BLKLIM command.
3007 		 * if READ_BLKLIM cmd fails, assume drive doesn't
3008 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3009 		 */
3010 		un->un_allow_large_xfer = st_allow_large_xfer &&
3011 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3012 	}
3013 	/*
3014 	 * if maxbsize is unknown, set the maximum block size.
3015 	 */
3016 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3017 
3018 		/*
3019 		 * Get the Block limits of the tape drive.
3020 		 * if un->un_allow_large_xfer = 0 , then make sure
3021 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3022 		 */
3023 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3024 
3025 		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3026 		if (err) {
3027 			/* Retry */
3028 			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3029 		}
3030 		if (!err) {
3031 
3032 			/*
3033 			 * if cmd successful, use limit returned
3034 			 */
3035 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3036 			    (un->un_rbl->max_mid << 8) +
3037 			    un->un_rbl->max_lo;
3038 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3039 			    un->un_rbl->min_lo;
3040 			un->un_data_mod = 1 << un->un_rbl->granularity;
3041 			if ((un->un_maxbsize == 0) ||
3042 			    (un->un_allow_large_xfer == 0 &&
3043 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3044 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3045 
3046 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3047 				/*
3048 				 * Drive is not one that is configured, But the
3049 				 * READ BLOCK LIMITS tells us it can do large
3050 				 * xfers.
3051 				 */
3052 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3053 					un->un_dp->options |=
3054 					    ST_NO_RECSIZE_LIMIT;
3055 				}
3056 				/*
3057 				 * If max and mimimum block limits are the
3058 				 * same this is a fixed block size device.
3059 				 */
3060 				if (un->un_maxbsize == un->un_minbsize) {
3061 					un->un_dp->options &= ~ST_VARIABLE;
3062 				}
3063 			}
3064 
3065 			if (un->un_minbsize == 0) {
3066 				un->un_minbsize = 1;
3067 			}
3068 
3069 		} else { /* error on read block limits */
3070 
3071 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3072 			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3073 			    " errno = %d un_rsvd_status = 0x%X\n",
3074 			    err, un->un_rsvd_status);
3075 
3076 			/*
3077 			 * since read block limits cmd failed,
3078 			 * do not allow large xfers.
3079 			 * use old values in st_minphys
3080 			 */
3081 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3082 				rval = EACCES;
3083 			} else {
3084 				un->un_allow_large_xfer = 0;
3085 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3086 				    "!Disabling large transfers\n");
3087 
3088 				/*
3089 				 * we guess maxbsize and minbsize
3090 				 */
3091 				if (un->un_bsize) {
3092 					un->un_maxbsize = un->un_minbsize =
3093 					    un->un_bsize;
3094 				} else {
3095 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3096 					un->un_minbsize = 1;
3097 				}
3098 				/*
3099 				 * Data Mod must be set,
3100 				 * Even if read block limits fails.
3101 				 * Prevents Divide By Zero in st_rw().
3102 				 */
3103 				un->un_data_mod = 1;
3104 			}
3105 		}
3106 		if (un->un_rbl) {
3107 			kmem_free(un->un_rbl, RBLSIZE);
3108 			un->un_rbl = NULL;
3109 		}
3110 
3111 		if (rval) {
3112 			goto exit;
3113 		}
3114 	}
3115 
3116 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3117 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3118 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3119 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3120 
3121 	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3122 
3123 	if (err != 0) {
3124 		if (err == EINTR) {
3125 			un->un_laststate = un->un_state;
3126 			un->un_state = ST_STATE_CLOSED;
3127 			rval = EINTR;
3128 			goto exit;
3129 		}
3130 		/*
3131 		 * Make sure the tape is ready
3132 		 */
3133 		un->un_pos.pmode = invalid;
3134 		if (un->un_status != KEY_UNIT_ATTENTION) {
3135 			/*
3136 			 * allow open no media.  Subsequent MTIOCSTATE
3137 			 * with media present will complete the open
3138 			 * logic.
3139 			 */
3140 			un->un_laststate = un->un_state;
3141 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3142 				un->un_mediastate = MTIO_EJECTED;
3143 				un->un_state = ST_STATE_OFFLINE;
3144 				rval = 0;
3145 				goto exit;
3146 			} else {
3147 				un->un_state = ST_STATE_CLOSED;
3148 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3149 				    "st_tape_init EIO no media, not opened "
3150 				    "O_NONBLOCK|O_EXCL\n");
3151 				rval = EIO;
3152 				goto exit;
3153 			}
3154 		}
3155 	}
3156 
3157 	/*
3158 	 * On each open, initialize block size from drivetype struct,
3159 	 * as it could have been changed by MTSRSZ ioctl.
3160 	 * Now, ST_VARIABLE simply means drive is capable of variable
3161 	 * mode. All drives are assumed to support fixed records.
3162 	 * Hence, un_bsize tells what mode the drive is in.
3163 	 *	un_bsize	= 0	- variable record length
3164 	 *			= x	- fixed record length is x
3165 	 */
3166 	un->un_bsize = un->un_dp->bsize;
3167 
3168 	/*
3169 	 * If saved position is valid go there
3170 	 */
3171 	if (un->un_restore_pos) {
3172 		un->un_restore_pos = 0;
3173 		un->un_pos.fileno = un->un_save_fileno;
3174 		un->un_pos.blkno = un->un_save_blkno;
3175 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3176 		if (rval != 0) {
3177 			if (rval != EACCES) {
3178 				rval = EIO;
3179 			}
3180 			un->un_laststate = un->un_state;
3181 			un->un_state = ST_STATE_CLOSED;
3182 			goto exit;
3183 		}
3184 	}
3185 
3186 	if (un->un_pos.pmode == invalid) {
3187 		rval = st_loadtape(un);
3188 		if (rval) {
3189 			if (rval != EACCES) {
3190 				rval = EIO;
3191 			}
3192 			un->un_laststate = un->un_state;
3193 			un->un_state = ST_STATE_CLOSED;
3194 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3195 			    "st_tape_init: %s can't open tape\n",
3196 			    rval == EACCES ? "EACCES" : "EIO");
3197 			goto exit;
3198 		}
3199 	}
3200 
3201 	/*
3202 	 * do a mode sense to pick up state of current write-protect,
3203 	 * Could cause reserve and fail due to conflict.
3204 	 */
3205 	if (un->un_unit_attention_flags) {
3206 		rval = st_modesense(un);
3207 		if (rval == EACCES) {
3208 			goto exit;
3209 		}
3210 	}
3211 
3212 	/*
3213 	 * If we are opening the tape for writing, check
3214 	 * to make sure that the tape can be written.
3215 	 */
3216 	if (un->un_oflags & FWRITE) {
3217 		err = 0;
3218 		if (un->un_mspl->wp) {
3219 			un->un_status = KEY_WRITE_PROTECT;
3220 			un->un_laststate = un->un_state;
3221 			un->un_state = ST_STATE_CLOSED;
3222 			rval = EACCES;
3223 			/*
3224 			 * STK sets the wp bit if volsafe tape is loaded.
3225 			 */
3226 			if ((un->un_dp->type == MT_ISSTK9840) &&
3227 			    (un->un_dp->options & ST_WORMABLE)) {
3228 				un->un_read_only = RDONLY;
3229 			} else {
3230 				goto exit;
3231 			}
3232 		} else {
3233 			un->un_read_only = RDWR;
3234 		}
3235 	} else {
3236 		un->un_read_only = RDONLY;
3237 	}
3238 
3239 	if (un->un_dp->options & ST_WORMABLE &&
3240 	    un->un_unit_attention_flags) {
3241 		un->un_read_only |= un->un_wormable(un);
3242 
3243 		if (((un->un_read_only == WORM) ||
3244 		    (un->un_read_only == RDWORM)) &&
3245 		    ((un->un_oflags & FWRITE) == FWRITE)) {
3246 			un->un_status = KEY_DATA_PROTECT;
3247 			rval = EACCES;
3248 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3249 			    "read_only = %d eof = %d oflag = %d\n",
3250 			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3251 		}
3252 	}
3253 
3254 	/*
3255 	 * If we're opening the tape write-only, we need to
3256 	 * write 2 filemarks on the HP 1/2 inch drive, to
3257 	 * create a null file.
3258 	 */
3259 	if ((un->un_read_only == RDWR) ||
3260 	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3261 		if (un->un_dp->options & ST_REEL) {
3262 			un->un_fmneeded = 2;
3263 		} else {
3264 			un->un_fmneeded = 1;
3265 		}
3266 	} else {
3267 		un->un_fmneeded = 0;
3268 	}
3269 
3270 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3271 	    "fmneeded = %x\n", un->un_fmneeded);
3272 
3273 	/*
3274 	 * Make sure the density can be selected correctly.
3275 	 * If WORM can only write at the append point which in most cases
3276 	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3277 	 * to set and try densities if a BOP.
3278 	 */
3279 	if (st_determine_density(un,
3280 	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3281 		un->un_status = KEY_ILLEGAL_REQUEST;
3282 		un->un_laststate = un->un_state;
3283 		un->un_state = ST_STATE_CLOSED;
3284 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3285 		    "st_tape_init: EIO can't determine density\n");
3286 		rval = EIO;
3287 		goto exit;
3288 	}
3289 
3290 	/*
3291 	 * Destroy the knowledge that we have 'determined'
3292 	 * density so that a later read at BOT comes along
3293 	 * does the right density determination.
3294 	 */
3295 
3296 	un->un_density_known = 0;
3297 
3298 
3299 	/*
3300 	 * Okay, the tape is loaded and either at BOT or somewhere past.
3301 	 * Mark the state such that any I/O or tape space operations
3302 	 * will get/set the right density, etc..
3303 	 */
3304 	un->un_laststate = un->un_state;
3305 	un->un_lastop = ST_OP_NIL;
3306 	un->un_mediastate = MTIO_INSERTED;
3307 	cv_broadcast(&un->un_state_cv);
3308 
3309 	/*
3310 	 *  Set test append flag if writing.
3311 	 *  First write must check that tape is positioned correctly.
3312 	 */
3313 	un->un_test_append = (un->un_oflags & FWRITE);
3314 
3315 	/*
3316 	 * if there are pending unit attention flags.
3317 	 * Check that the media has not changed.
3318 	 */
3319 	if (un->un_unit_attention_flags) {
3320 		rval = st_get_media_identification(un, st_uscsi_cmd);
3321 		if (rval != 0 && rval != EACCES) {
3322 			rval = EIO;
3323 		}
3324 		un->un_unit_attention_flags = 0;
3325 	}
3326 
3327 exit:
3328 	un->un_err_resid = 0;
3329 	un->un_last_resid = 0;
3330 	un->un_last_count = 0;
3331 
3332 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3333 	    "st_tape_init: return val = %x\n", rval);
3334 	return (rval);
3335 
3336 }
3337 
3338 
3339 
3340 /* ARGSUSED */
3341 static int
3342 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3343 {
3344 	int err = 0;
3345 	int count, last_state;
3346 	minor_t minor = getminor(dev);
3347 #ifdef	__x86
3348 	struct contig_mem *cp, *cp_temp;
3349 #endif
3350 
3351 	GET_SOFT_STATE(dev);
3352 
3353 	ST_ENTR(ST_DEVINFO, st_close);
3354 
3355 	/*
3356 	 * wait till all cmds in the pipeline have been completed
3357 	 */
3358 	mutex_enter(ST_MUTEX);
3359 
3360 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3361 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3362 
3363 	st_wait_for_io(un);
3364 
3365 	/* turn off persistent errors on close, as we want close to succeed */
3366 	st_turn_pe_off(un);
3367 
3368 	/*
3369 	 * set state to indicate that we are in process of closing
3370 	 */
3371 	last_state = un->un_laststate = un->un_state;
3372 	un->un_state = ST_STATE_CLOSING;
3373 
3374 	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3375 
3376 	/*
3377 	 * BSD behavior:
3378 	 * a close always causes a silent span to the next file if we've hit
3379 	 * an EOF (but not yet read across it).
3380 	 */
3381 	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3382 		if (un->un_pos.pmode != invalid) {
3383 			un->un_pos.fileno++;
3384 			un->un_pos.blkno = 0;
3385 		}
3386 		un->un_pos.eof = ST_NO_EOF;
3387 	}
3388 
3389 	/*
3390 	 * SVR4 behavior for skipping to next file:
3391 	 *
3392 	 * If we have not seen a filemark, space to the next file
3393 	 *
3394 	 * If we have already seen the filemark we are physically in the next
3395 	 * file and we only increment the filenumber
3396 	 */
3397 	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3398 	    (flag & FREAD) &&		/* reading or at least asked to */
3399 	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3400 	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3401 	    ((un->un_pos.blkno != 0) && 		/* inside a file */
3402 	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3403 	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3404 		switch (un->un_pos.eof) {
3405 		case ST_NO_EOF:
3406 			/*
3407 			 * if we were reading and did not read the complete file
3408 			 * skip to the next file, leaving the tape correctly
3409 			 * positioned to read the first record of the next file
3410 			 * Check first for REEL if we are at EOT by trying to
3411 			 * read a block
3412 			 */
3413 			if ((un->un_dp->options & ST_REEL) &&
3414 			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3415 			    (un->un_pos.blkno == 0)) {
3416 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3417 					ST_DEBUG2(ST_DEVINFO, st_label,
3418 					    SCSI_DEBUG,
3419 					    "st_close : EIO can't space\n");
3420 					err = EIO;
3421 					goto error_out;
3422 				}
3423 				if (un->un_pos.eof >= ST_EOF_PENDING) {
3424 					un->un_pos.eof = ST_EOT_PENDING;
3425 					un->un_pos.fileno += 1;
3426 					un->un_pos.blkno   = 0;
3427 					break;
3428 				}
3429 			}
3430 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3431 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3432 				    "st_close: EIO can't space #2\n");
3433 				err = EIO;
3434 				goto error_out;
3435 			} else {
3436 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3437 				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3438 				    un->un_pos.fileno, un->un_pos.blkno,
3439 				    un->un_pos.eof);
3440 				un->un_pos.eof = ST_NO_EOF;
3441 			}
3442 			break;
3443 
3444 		case ST_EOF_PENDING:
3445 		case ST_EOF:
3446 			un->un_pos.fileno += 1;
3447 			un->un_pos.lgclblkno += 1;
3448 			un->un_pos.blkno   = 0;
3449 			un->un_pos.eof = ST_NO_EOF;
3450 			break;
3451 
3452 		case ST_EOT:
3453 		case ST_EOT_PENDING:
3454 		case ST_EOM:
3455 			/* nothing to do */
3456 			break;
3457 		default:
3458 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3459 			    "Undefined state 0x%x", un->un_pos.eof);
3460 
3461 		}
3462 	}
3463 
3464 
3465 	/*
3466 	 * For performance reasons (HP 88780), the driver should
3467 	 * postpone writing the second tape mark until just before a file
3468 	 * positioning ioctl is issued (e.g., rewind).	This means that
3469 	 * the user must not manually rewind the tape because the tape will
3470 	 * be missing the second tape mark which marks EOM.
3471 	 * However, this small performance improvement is not worth the risk.
3472 	 */
3473 
3474 	/*
3475 	 * We need to back up over the filemark we inadvertently popped
3476 	 * over doing a read in between the two filemarks that constitute
3477 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3478 	 * set while reading.
3479 	 *
3480 	 * If we happen to be at physical eot (ST_EOM) (writing case),
3481 	 * the writing of filemark(s) will clear the ST_EOM state, which
3482 	 * we don't want, so we save this state and restore it later.
3483 	 */
3484 
3485 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3486 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3487 	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3488 
3489 	if (un->un_pos.eof == ST_EOT_PENDING) {
3490 		if (minor & MT_NOREWIND) {
3491 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3492 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3493 				    "st_close: EIO can't space #3\n");
3494 				err = EIO;
3495 				goto error_out;
3496 			} else {
3497 				un->un_pos.blkno = 0;
3498 				un->un_pos.eof = ST_EOT;
3499 			}
3500 		} else {
3501 			un->un_pos.eof = ST_NO_EOF;
3502 		}
3503 
3504 	/*
3505 	 * Do we need to write a file mark?
3506 	 *
3507 	 * only write filemarks if there are fmks to be written and
3508 	 *   - open for write (possibly read/write)
3509 	 *   - the last operation was a write
3510 	 * or:
3511 	 *   -	opened for wronly
3512 	 *   -	no data was written
3513 	 */
3514 	} else if ((un->un_pos.pmode != invalid) &&
3515 	    (un->un_fmneeded > 0) &&
3516 	    (((flag & FWRITE) &&
3517 	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3518 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3519 
3520 		/* save ST_EOM state */
3521 		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3522 
3523 		/*
3524 		 * Note that we will write a filemark if we had opened
3525 		 * the tape write only and no data was written, thus
3526 		 * creating a null file.
3527 		 *
3528 		 * If the user already wrote one, we only have to write 1 more.
3529 		 * If they wrote two, we don't have to write any.
3530 		 */
3531 
3532 		count = un->un_fmneeded;
3533 		if (count > 0) {
3534 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3535 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3536 				    "st_close : EIO can't wfm\n");
3537 				err = EIO;
3538 				goto error_out;
3539 			}
3540 			if ((un->un_dp->options & ST_REEL) &&
3541 			    (minor & MT_NOREWIND)) {
3542 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3543 					ST_DEBUG2(ST_DEVINFO, st_label,
3544 					    SCSI_DEBUG,
3545 					    "st_close : EIO space fmk(-1)\n");
3546 					err = EIO;
3547 					goto error_out;
3548 				}
3549 				un->un_pos.eof = ST_NO_EOF;
3550 				/* fix up block number */
3551 				un->un_pos.blkno = 0;
3552 			}
3553 		}
3554 
3555 		/*
3556 		 * If we aren't going to be rewinding, and we were at
3557 		 * physical eot, restore the state that indicates we
3558 		 * are at physical eot. Once you have reached physical
3559 		 * eot, and you close the tape, the only thing you can
3560 		 * do on the next open is to rewind. Access to trailer
3561 		 * records is only allowed without closing the device.
3562 		 */
3563 		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3564 			un->un_pos.eof = ST_EOM;
3565 		}
3566 	}
3567 
3568 	/*
3569 	 * report soft errors if enabled and available, if we never accessed
3570 	 * the drive, don't get errors. This will prevent some DAT error
3571 	 * messages upon LOG SENSE.
3572 	 */
3573 	if (st_report_soft_errors_on_close &&
3574 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3575 	    (last_state != ST_STATE_OFFLINE)) {
3576 		if (st_report_soft_errors(dev, flag)) {
3577 			err = EIO;
3578 			goto error_out;
3579 		}
3580 	}
3581 
3582 
3583 	/*
3584 	 * Do we need to rewind? Can we rewind?
3585 	 */
3586 	if ((minor & MT_NOREWIND) == 0 &&
3587 	    un->un_pos.pmode != invalid && err == 0) {
3588 		/*
3589 		 * We'd like to rewind with the
3590 		 * 'immediate' bit set, but this
3591 		 * causes problems on some drives
3592 		 * where subsequent opens get a
3593 		 * 'NOT READY' error condition
3594 		 * back while the tape is rewinding,
3595 		 * which is impossible to distinguish
3596 		 * from the condition of 'no tape loaded'.
3597 		 *
3598 		 * Also, for some targets, if you disconnect
3599 		 * with the 'immediate' bit set, you don't
3600 		 * actually return right away, i.e., the
3601 		 * target ignores your request for immediate
3602 		 * return.
3603 		 *
3604 		 * Instead, we'll fire off an async rewind
3605 		 * command. We'll mark the device as closed,
3606 		 * and any subsequent open will stall on
3607 		 * the first TEST_UNIT_READY until the rewind
3608 		 * completes.
3609 		 */
3610 
3611 		/*
3612 		 * Used to be if reserve was not supported we'd send an
3613 		 * asynchronious rewind. Comments above may be slightly invalid
3614 		 * as the immediate bit was never set. Doing an immedate rewind
3615 		 * makes sense, I think fixes to not ready status might handle
3616 		 * the problems described above.
3617 		 */
3618 		if (un->un_sd->sd_inq->inq_ansi < 2) {
3619 			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3620 				err = EIO;
3621 			}
3622 		} else {
3623 			/* flush data for older drives per scsi spec. */
3624 			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3625 				err = EIO;
3626 			} else if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3627 				err = EIO;
3628 			}
3629 		}
3630 		/*
3631 		 * Setting positions invalid in case the rewind doesn't
3632 		 * happen. Drives don't like to rewind if resets happen
3633 		 * they will tend to move back to where the rewind was
3634 		 * issued if a reset or something happens so that if a
3635 		 * write happens the data doesn't get clobbered.
3636 		 *
3637 		 * Not a big deal if the position is invalid when the
3638 		 * open occures it will do a read position.
3639 		 */
3640 		un->un_pos.pmode = invalid;
3641 		un->un_running.pmode = invalid;
3642 
3643 		if (err == EIO) {
3644 			goto error_out;
3645 		}
3646 	}
3647 
3648 	/*
3649 	 * eject tape if necessary
3650 	 */
3651 	if (un->un_eject_tape_on_failure) {
3652 		un->un_eject_tape_on_failure = 0;
3653 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3654 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3655 			    "st_close : can't unload tape\n");
3656 			err = EIO;
3657 			goto error_out;
3658 		} else {
3659 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3660 			    "st_close : tape unloaded \n");
3661 			un->un_pos.eof = ST_NO_EOF;
3662 			un->un_mediastate = MTIO_EJECTED;
3663 		}
3664 	}
3665 	/*
3666 	 * Release the tape unit, if default reserve/release
3667 	 * behaviour.
3668 	 */
3669 	if ((un->un_rsvd_status &
3670 	    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
3671 		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3672 	}
3673 error_out:
3674 	/*
3675 	 * clear up state
3676 	 */
3677 	un->un_laststate = un->un_state;
3678 	un->un_state = ST_STATE_CLOSED;
3679 	un->un_lastop = ST_OP_NIL;
3680 	un->un_throttle = 1;	/* assume one request at time, for now */
3681 	un->un_retry_ct = 0;
3682 	un->un_errno = 0;
3683 	un->un_swr_token = (opaque_t)NULL;
3684 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3685 
3686 	/* Restore the options to the init time settings */
3687 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3688 		un->un_dp->options |= ST_READ_IGNORE_ILI;
3689 	} else {
3690 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3691 	}
3692 
3693 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3694 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3695 	} else {
3696 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3697 	}
3698 
3699 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3700 		un->un_dp->options |= ST_SHORT_FILEMARKS;
3701 	} else {
3702 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3703 	}
3704 
3705 	ASSERT(mutex_owned(ST_MUTEX));
3706 
3707 	/*
3708 	 * Signal anyone awaiting a close operation to complete.
3709 	 */
3710 	cv_signal(&un->un_clscv);
3711 
3712 	/*
3713 	 * any kind of error on closing causes all state to be tossed
3714 	 */
3715 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3716 		/*
3717 		 * note that st_intr has already set
3718 		 * un_pos.pmode to invalid.
3719 		 */
3720 		un->un_density_known = 0;
3721 	}
3722 
3723 #ifdef	__x86
3724 	/*
3725 	 * free any contiguous mem alloc'ed for big block I/O
3726 	 */
3727 	cp = un->un_contig_mem;
3728 	while (cp) {
3729 		if (cp->cm_addr) {
3730 			ddi_dma_mem_free(&cp->cm_acc_hdl);
3731 		}
3732 		cp_temp = cp;
3733 		cp = cp->cm_next;
3734 		kmem_free(cp_temp,
3735 		    sizeof (struct contig_mem) + biosize());
3736 	}
3737 	un->un_contig_mem_total_num = 0;
3738 	un->un_contig_mem_available_num = 0;
3739 	un->un_contig_mem = NULL;
3740 	un->un_max_contig_mem_len = 0;
3741 #endif
3742 
3743 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3744 	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3745 	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3746 
3747 	mutex_exit(ST_MUTEX);
3748 	return (err);
3749 }
3750 
3751 /*
3752  * These routines perform raw i/o operations.
3753  */
3754 
3755 /* ARGSUSED2 */
3756 static int
3757 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3758 {
3759 #ifdef STDEBUG
3760 	GET_SOFT_STATE(dev);
3761 	ST_ENTR(ST_DEVINFO, st_aread);
3762 #endif
3763 	return (st_arw(dev, aio, B_READ));
3764 }
3765 
3766 
3767 /* ARGSUSED2 */
3768 static int
3769 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3770 {
3771 #ifdef STDEBUG
3772 	GET_SOFT_STATE(dev);
3773 	ST_ENTR(ST_DEVINFO, st_awrite);
3774 #endif
3775 	return (st_arw(dev, aio, B_WRITE));
3776 }
3777 
3778 
3779 
3780 /* ARGSUSED */
3781 static int
3782 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3783 {
3784 #ifdef STDEBUG
3785 	GET_SOFT_STATE(dev);
3786 	ST_ENTR(ST_DEVINFO, st_read);
3787 #endif
3788 	return (st_rw(dev, uiop, B_READ));
3789 }
3790 
3791 /* ARGSUSED */
3792 static int
3793 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3794 {
3795 #ifdef STDEBUG
3796 	GET_SOFT_STATE(dev);
3797 	ST_ENTR(ST_DEVINFO, st_write);
3798 #endif
3799 	return (st_rw(dev, uiop, B_WRITE));
3800 }
3801 
3802 /*
3803  * Due to historical reasons, old limits are: For variable-length devices:
3804  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3805  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3806  * (let it through unmodified. For fixed-length record devices:
3807  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3808  *
3809  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3810  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3811  * command to the drive).
3812  *
3813  */
3814 static void
3815 st_minphys(struct buf *bp)
3816 {
3817 	struct scsi_tape *un;
3818 
3819 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3820 
3821 	ST_FUNC(ST_DEVINFO, st_minphys);
3822 
3823 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3824 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3825 	    bp->b_bcount);
3826 
3827 	if (un->un_allow_large_xfer) {
3828 
3829 		/*
3830 		 * check un_maxbsize for variable length devices only
3831 		 */
3832 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3833 			bp->b_bcount = un->un_maxbsize;
3834 		}
3835 		/*
3836 		 * can't go more that HBA maxdma limit in either fixed-length
3837 		 * or variable-length tape drives.
3838 		 */
3839 		if (bp->b_bcount > un->un_maxdma) {
3840 			bp->b_bcount = un->un_maxdma;
3841 		}
3842 	} else {
3843 
3844 		/*
3845 		 *  use old fixed limits
3846 		 */
3847 		if (un->un_bsize == 0) {
3848 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3849 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3850 			}
3851 		} else {
3852 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3853 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3854 			}
3855 		}
3856 	}
3857 
3858 	/*
3859 	 * For regular raw I/O and Fixed Block length devices, make sure
3860 	 * the adjusted block count is a whole multiple of the device
3861 	 * block size.
3862 	 */
3863 	if (bp != un->un_sbufp && un->un_bsize) {
3864 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3865 	}
3866 }
3867 
3868 static int
3869 st_rw(dev_t dev, struct uio *uio, int flag)
3870 {
3871 	int rval = 0;
3872 	long len;
3873 
3874 	GET_SOFT_STATE(dev);
3875 
3876 	ST_FUNC(ST_DEVINFO, st_rw);
3877 
3878 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3879 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3880 	    (flag == B_READ ? rd_str: wr_str));
3881 
3882 	/* get local copy of transfer length */
3883 	len = uio->uio_iov->iov_len;
3884 
3885 	mutex_enter(ST_MUTEX);
3886 
3887 	/*
3888 	 * Clear error entry stack
3889 	 */
3890 	st_empty_error_stack(un);
3891 
3892 	/*
3893 	 * If in fixed block size mode and requested read or write
3894 	 * is not an even multiple of that block size.
3895 	 */
3896 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3897 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3898 		    "%s: not modulo %d block size\n",
3899 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3900 		rval = EINVAL;
3901 	}
3902 
3903 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3904 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3905 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3906 		    "%s: not modulo %d device granularity\n",
3907 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3908 		rval = EINVAL;
3909 	}
3910 
3911 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3912 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3913 		rval = EFAULT;
3914 	}
3915 
3916 	if (rval != 0) {
3917 		un->un_errno = rval;
3918 		mutex_exit(ST_MUTEX);
3919 		return (rval);
3920 	}
3921 
3922 	/*
3923 	 * Reset this so it can be set if Berkeley and read over a filemark.
3924 	 */
3925 	un->un_silent_skip = 0;
3926 	mutex_exit(ST_MUTEX);
3927 
3928 	len = uio->uio_resid;
3929 
3930 	rval = physio(st_queued_strategy, (struct buf *)NULL,
3931 	    dev, flag, st_minphys, uio);
3932 	/*
3933 	 * if we have hit logical EOT during this xfer and there is not a
3934 	 * full residue, then set eof back  to ST_EOM to make sure that
3935 	 * the user will see at least one zero write
3936 	 * after this short write
3937 	 */
3938 	mutex_enter(ST_MUTEX);
3939 	if (un->un_pos.eof > ST_NO_EOF) {
3940 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3941 		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3942 	}
3943 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3944 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3945 			un->un_pos.eof = ST_EOM;
3946 		} else if (uio->uio_resid == len) {
3947 			un->un_pos.eof = ST_NO_EOF;
3948 		}
3949 	}
3950 
3951 	if (un->un_silent_skip && uio->uio_resid != len) {
3952 		un->un_pos.eof = ST_EOF;
3953 		un->un_pos.blkno = un->un_save_blkno;
3954 		un->un_pos.fileno--;
3955 	}
3956 
3957 	un->un_errno = rval;
3958 
3959 	mutex_exit(ST_MUTEX);
3960 
3961 	return (rval);
3962 }
3963 
3964 static int
3965 st_arw(dev_t dev, struct aio_req *aio, int flag)
3966 {
3967 	struct uio *uio = aio->aio_uio;
3968 	int rval = 0;
3969 	long len;
3970 
3971 	GET_SOFT_STATE(dev);
3972 
3973 	ST_FUNC(ST_DEVINFO, st_arw);
3974 
3975 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3976 	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
3977 	    (flag == B_READ ? rd_str: wr_str));
3978 
3979 	/* get local copy of transfer length */
3980 	len = uio->uio_iov->iov_len;
3981 
3982 	mutex_enter(ST_MUTEX);
3983 
3984 	/*
3985 	 * If in fixed block size mode and requested read or write
3986 	 * is not an even multiple of that block size.
3987 	 */
3988 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3989 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3990 		    "%s: not modulo %d block size\n",
3991 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3992 		rval = EINVAL;
3993 	}
3994 
3995 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3996 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3997 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3998 		    "%s: not modulo %d device granularity\n",
3999 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4000 		rval = EINVAL;
4001 	}
4002 
4003 	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4004 		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4005 		rval = EFAULT;
4006 	}
4007 
4008 	if (rval != 0) {
4009 		un->un_errno = rval;
4010 		mutex_exit(ST_MUTEX);
4011 		return (rval);
4012 	}
4013 
4014 	mutex_exit(ST_MUTEX);
4015 
4016 	len = uio->uio_resid;
4017 
4018 	rval =
4019 	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4020 
4021 	/*
4022 	 * if we have hit logical EOT during this xfer and there is not a
4023 	 * full residue, then set eof back  to ST_EOM to make sure that
4024 	 * the user will see at least one zero write
4025 	 * after this short write
4026 	 *
4027 	 * we keep this here just in case the application is not using
4028 	 * persistent errors
4029 	 */
4030 	mutex_enter(ST_MUTEX);
4031 	if (un->un_pos.eof > ST_NO_EOF) {
4032 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4033 		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4034 	}
4035 	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4036 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4037 			un->un_pos.eof = ST_EOM;
4038 		} else if (uio->uio_resid == len &&
4039 		    !(un->un_persistence && un->un_persist_errors)) {
4040 			un->un_pos.eof = ST_NO_EOF;
4041 		}
4042 	}
4043 	un->un_errno = rval;
4044 	mutex_exit(ST_MUTEX);
4045 
4046 	return (rval);
4047 }
4048 
4049 
4050 
4051 static int
4052 st_queued_strategy(buf_t *bp)
4053 {
4054 	struct scsi_tape *un;
4055 	char reading = bp->b_flags & B_READ;
4056 	int wasopening = 0;
4057 
4058 	/*
4059 	 * validate arguments
4060 	 */
4061 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4062 	if (un == NULL) {
4063 		bp->b_resid = bp->b_bcount;
4064 		bioerror(bp, ENXIO);
4065 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4066 		    "st_queued_strategy: ENXIO error exit\n");
4067 		biodone(bp);
4068 		return (0);
4069 	}
4070 
4071 	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4072 
4073 	mutex_enter(ST_MUTEX);
4074 
4075 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4076 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4077 	}
4078 
4079 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4080 	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4081 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4082 
4083 	/*
4084 	 * If persistent errors have been flagged, just nix this one. We wait
4085 	 * for any outstanding I/O's below, so we will be in order.
4086 	 */
4087 	if (un->un_persistence && un->un_persist_errors) {
4088 		goto exit;
4089 	}
4090 
4091 	/*
4092 	 * If last command was non queued, wait till it finishes.
4093 	 */
4094 	while (un->un_sbuf_busy) {
4095 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4096 		/* woke up because of an error */
4097 		if (un->un_persistence && un->un_persist_errors) {
4098 			goto exit;
4099 		}
4100 	}
4101 
4102 	/*
4103 	 * s_buf and recovery commands shouldn't come here.
4104 	 */
4105 	ASSERT(bp != un->un_recov_buf);
4106 	ASSERT(bp != un->un_sbufp);
4107 
4108 	/*
4109 	 * If we haven't done/checked reservation on the tape unit
4110 	 * do it now.
4111 	 */
4112 	if ((un->un_rsvd_status &
4113 	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4114 		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4115 			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4116 				st_bioerror(bp, un->un_errno);
4117 				goto exit;
4118 			}
4119 		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4120 			/*
4121 			 * Enter here to restore position for possible
4122 			 * resets when the device was closed and opened
4123 			 * in O_NDELAY mode subsequently
4124 			 */
4125 			un->un_state = ST_STATE_INITIALIZING;
4126 			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4127 			    0, SYNC_CMD);
4128 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4129 		}
4130 		un->un_rsvd_status |= ST_INIT_RESERVE;
4131 	}
4132 
4133 	/*
4134 	 * If we are offline, we have to initialize everything first.
4135 	 * This is to handle either when opened with O_NDELAY, or
4136 	 * we just got a new tape in the drive, after an offline.
4137 	 * We don't observe O_NDELAY past the open,
4138 	 * as it will not make sense for tapes.
4139 	 */
4140 	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4141 		/*
4142 		 * reset state to avoid recursion
4143 		 */
4144 		un->un_laststate = un->un_state;
4145 		un->un_state = ST_STATE_INITIALIZING;
4146 		if (st_tape_init(un)) {
4147 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4148 			    "stioctl : OFFLINE init failure ");
4149 			un->un_state = ST_STATE_OFFLINE;
4150 			un->un_pos.pmode = invalid;
4151 			goto b_done_err;
4152 		}
4153 		/* un_restore_pos make invalid */
4154 		un->un_state = ST_STATE_OPEN_PENDING_IO;
4155 		un->un_restore_pos = 0;
4156 	}
4157 	/*
4158 	 * Check for legal operations
4159 	 */
4160 	if (un->un_pos.pmode == invalid) {
4161 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4162 		    "strategy with un->un_pos.pmode invalid\n");
4163 		goto b_done_err;
4164 	}
4165 
4166 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4167 	    "st_queued_strategy(): regular io\n");
4168 
4169 	/*
4170 	 * Process this first. If we were reading, and we're pending
4171 	 * logical eot, that means we've bumped one file mark too far.
4172 	 */
4173 
4174 	/*
4175 	 * Recursion warning: st_cmd will route back through here.
4176 	 * Not anymore st_cmd will go through st_strategy()!
4177 	 */
4178 	if (un->un_pos.eof == ST_EOT_PENDING) {
4179 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4180 			un->un_pos.pmode = invalid;
4181 			un->un_density_known = 0;
4182 			goto b_done_err;
4183 		}
4184 		un->un_pos.blkno = 0; /* fix up block number.. */
4185 		un->un_pos.eof = ST_EOT;
4186 	}
4187 
4188 	/*
4189 	 * If we are in the process of opening, we may have to
4190 	 * determine/set the correct density. We also may have
4191 	 * to do a test_append (if QIC) to see whether we are
4192 	 * in a position to append to the end of the tape.
4193 	 *
4194 	 * If we're already at logical eot, we transition
4195 	 * to ST_NO_EOF. If we're at physical eot, we punt
4196 	 * to the switch statement below to handle.
4197 	 */
4198 	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4199 	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4200 
4201 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4202 			if (st_determine_density(un, (int)reading)) {
4203 				goto b_done_err;
4204 			}
4205 		}
4206 
4207 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4208 		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4209 		    un->un_pos.fileno, (int)reading,
4210 		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4211 		    un->un_pos.eof);
4212 
4213 		if (!reading && un->un_pos.eof != ST_EOM) {
4214 			if (un->un_pos.eof == ST_EOT) {
4215 				un->un_pos.eof = ST_NO_EOF;
4216 			} else if (un->un_pos.pmode != invalid &&
4217 			    (un->un_dp->options & ST_QIC)) {
4218 				/*
4219 				 * st_test_append() will do it all
4220 				 */
4221 				st_test_append(bp);
4222 				mutex_exit(ST_MUTEX);
4223 				return (0);
4224 			}
4225 		}
4226 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4227 			wasopening = 1;
4228 		}
4229 		un->un_laststate = un->un_state;
4230 		un->un_state = ST_STATE_OPEN;
4231 	}
4232 
4233 
4234 	/*
4235 	 * Process rest of END OF FILE and END OF TAPE conditions
4236 	 */
4237 
4238 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4239 	    "eof=%x, wasopening=%x\n",
4240 	    un->un_pos.eof, wasopening);
4241 
4242 	switch (un->un_pos.eof) {
4243 	case ST_EOM:
4244 		/*
4245 		 * This allows writes to proceed past physical
4246 		 * eot. We'll *really* be in trouble if the
4247 		 * user continues blindly writing data too
4248 		 * much past this point (unwind the tape).
4249 		 * Physical eot really means 'early warning
4250 		 * eot' in this context.
4251 		 *
4252 		 * Every other write from now on will succeed
4253 		 * (if sufficient  tape left).
4254 		 * This write will return with resid == count
4255 		 * but the next one should be successful
4256 		 *
4257 		 * Note that we only transition to logical EOT
4258 		 * if the last state wasn't the OPENING state.
4259 		 * We explicitly prohibit running up to physical
4260 		 * eot, closing the device, and then re-opening
4261 		 * to proceed. Trailer records may only be gotten
4262 		 * at by keeping the tape open after hitting eot.
4263 		 *
4264 		 * Also note that ST_EOM cannot be set by reading-
4265 		 * this can only be set during writing. Reading
4266 		 * up to the end of the tape gets a blank check
4267 		 * or a double-filemark indication (ST_EOT_PENDING),
4268 		 * and we prohibit reading after that point.
4269 		 *
4270 		 */
4271 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4272 		if (wasopening == 0) {
4273 			/*
4274 			 * this allows st_rw() to reset it back to
4275 			 * will see a zero write
4276 			 */
4277 			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4278 		}
4279 		un->un_status = SUN_KEY_EOT;
4280 		goto b_done;
4281 
4282 	case ST_WRITE_AFTER_EOM:
4283 	case ST_EOT:
4284 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4285 		un->un_status = SUN_KEY_EOT;
4286 		if (SVR4_BEHAVIOR && reading) {
4287 			goto b_done_err;
4288 		}
4289 
4290 		if (reading) {
4291 			goto b_done;
4292 		}
4293 		un->un_pos.eof = ST_NO_EOF;
4294 		break;
4295 
4296 	case ST_EOF_PENDING:
4297 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4298 		    "EOF PENDING\n");
4299 		un->un_status = SUN_KEY_EOF;
4300 		if (SVR4_BEHAVIOR) {
4301 			un->un_pos.eof = ST_EOF;
4302 			goto b_done;
4303 		}
4304 		/* FALLTHROUGH */
4305 	case ST_EOF:
4306 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4307 		un->un_status = SUN_KEY_EOF;
4308 		if (SVR4_BEHAVIOR) {
4309 			goto b_done_err;
4310 		}
4311 
4312 		if (BSD_BEHAVIOR) {
4313 			un->un_pos.eof = ST_NO_EOF;
4314 			un->un_pos.fileno += 1;
4315 			un->un_pos.blkno   = 0;
4316 		}
4317 
4318 		if (reading) {
4319 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4320 			    "now file %d (read)\n",
4321 			    un->un_pos.fileno);
4322 			goto b_done;
4323 		}
4324 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4325 		    "now file %d (write)\n", un->un_pos.fileno);
4326 		break;
4327 	default:
4328 		un->un_status = 0;
4329 		break;
4330 	}
4331 
4332 	bp->b_flags &= ~(B_DONE);
4333 	st_bioerror(bp, 0);
4334 	bp->av_forw = NULL;
4335 	bp->b_resid = 0;
4336 	SET_BP_PKT(bp, 0);
4337 
4338 
4339 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4340 	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4341 	    " pkt=0x%p\n",
4342 	    (void *)bp->b_forw, bp->b_bcount,
4343 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4344 
4345 #ifdef	__x86
4346 	/*
4347 	 * We will replace bp with a new bp that can do big blk xfer
4348 	 * if the requested xfer size is bigger than un->un_maxdma_arch
4349 	 *
4350 	 * Also, we need to make sure that we're handling real I/O
4351 	 * by checking group 0/1 SCSI I/O commands, if needed
4352 	 */
4353 	if (bp->b_bcount > un->un_maxdma_arch &&
4354 	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4355 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4356 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4357 	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4358 		mutex_exit(ST_MUTEX);
4359 		bp = st_get_bigblk_bp(bp);
4360 		mutex_enter(ST_MUTEX);
4361 	}
4362 #endif
4363 
4364 	/* put on wait queue */
4365 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4366 	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4367 	    (void *)un->un_quef, (void *)bp);
4368 
4369 	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4370 
4371 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4372 
4373 	st_start(un);
4374 
4375 	mutex_exit(ST_MUTEX);
4376 	return (0);
4377 
4378 b_done_err:
4379 	st_bioerror(bp, EIO);
4380 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4381 	    "st_queued_strategy : EIO b_done_err\n");
4382 
4383 b_done:
4384 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4385 	    "st_queued_strategy: b_done\n");
4386 
4387 exit:
4388 	/*
4389 	 * make sure no commands are outstanding or waiting before closing,
4390 	 * so we can guarantee order
4391 	 */
4392 	st_wait_for_io(un);
4393 	un->un_err_resid = bp->b_resid = bp->b_bcount;
4394 
4395 	/* override errno here, if persistent errors were flagged */
4396 	if (un->un_persistence && un->un_persist_errors)
4397 		bioerror(bp, un->un_errno);
4398 
4399 	mutex_exit(ST_MUTEX);
4400 
4401 	biodone(bp);
4402 	ASSERT(mutex_owned(ST_MUTEX) == 0);
4403 	return (0);
4404 }
4405 
4406 
4407 static int
4408 st_strategy(struct buf *bp)
4409 {
4410 	struct scsi_tape *un;
4411 
4412 	/*
4413 	 * validate arguments
4414 	 */
4415 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4416 	if (un == NULL) {
4417 		bp->b_resid = bp->b_bcount;
4418 		bioerror(bp, ENXIO);
4419 		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4420 		    "st_strategy: ENXIO error exit\n");
4421 
4422 		biodone(bp);
4423 		return (0);
4424 
4425 	}
4426 
4427 	ST_ENTR(ST_DEVINFO, st_strategy);
4428 
4429 	mutex_enter(ST_MUTEX);
4430 
4431 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4432 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4433 	}
4434 
4435 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4436 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4437 	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4438 
4439 	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4440 
4441 	bp->b_flags &= ~(B_DONE);
4442 	st_bioerror(bp, 0);
4443 	bp->av_forw = NULL;
4444 	bp->b_resid = 0;
4445 	SET_BP_PKT(bp, 0);
4446 
4447 
4448 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4449 	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4450 	    " pkt=0x%p\n",
4451 	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4452 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4453 	ST_DO_KSTATS(bp, kstat_waitq_enter);
4454 
4455 	st_start(un);
4456 
4457 	mutex_exit(ST_MUTEX);
4458 	return (0);
4459 }
4460 
4461 /*
4462  * this routine spaces forward over filemarks
4463  */
4464 static int
4465 st_space_fmks(struct scsi_tape *un, int64_t count)
4466 {
4467 	int rval = 0;
4468 
4469 	ST_FUNC(ST_DEVINFO, st_space_fmks);
4470 
4471 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4472 	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4473 	    un->un_dev, count);
4474 
4475 	ASSERT(mutex_owned(ST_MUTEX));
4476 
4477 	/*
4478 	 * the risk with doing only one space operation is that we
4479 	 * may accidentily jump in old data
4480 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4481 	 * because the 8200 does not append a marker; in order not to
4482 	 * sacrifice the fast file skip, we do a slow skip if the low
4483 	 * density device has been opened
4484 	 */
4485 
4486 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4487 	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4488 	    MT_DENSITY(un->un_dev) == 0))) {
4489 		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4490 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4491 			    "space_fmks : EIO can't do space cmd #1\n");
4492 			rval = EIO;
4493 		}
4494 	} else {
4495 		while (count > 0) {
4496 			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4497 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4498 				    "space_fmks : EIO can't do space cmd #2\n");
4499 				rval = EIO;
4500 				break;
4501 			}
4502 			count -= 1;
4503 			/*
4504 			 * read a block to see if we have reached
4505 			 * end of medium (double filemark for reel or
4506 			 * medium error for others)
4507 			 */
4508 			if (count > 0) {
4509 				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4510 					ST_DEBUG2(ST_DEVINFO, st_label,
4511 					    SCSI_DEBUG,
4512 					    "space_fmks : EIO can't do "
4513 					    "space cmd #3\n");
4514 					rval = EIO;
4515 					break;
4516 				}
4517 				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4518 				    (un->un_dp->options & ST_REEL)) {
4519 					un->un_status = SUN_KEY_EOT;
4520 					ST_DEBUG2(ST_DEVINFO, st_label,
4521 					    SCSI_DEBUG,
4522 					    "space_fmks : EIO ST_REEL\n");
4523 					rval = EIO;
4524 					break;
4525 				} else if (IN_EOF(un->un_pos)) {
4526 					un->un_pos.eof = ST_NO_EOF;
4527 					un->un_pos.fileno++;
4528 					un->un_pos.blkno = 0;
4529 					count--;
4530 				} else if (un->un_pos.eof > ST_EOF) {
4531 					ST_DEBUG2(ST_DEVINFO, st_label,
4532 					    SCSI_DEBUG,
4533 					    "space_fmks, EIO > ST_EOF\n");
4534 					rval = EIO;
4535 					break;
4536 				}
4537 
4538 			}
4539 		}
4540 		un->un_err_resid = count;
4541 		COPY_POS(&un->un_pos, &un->un_err_pos);
4542 	}
4543 	ASSERT(mutex_owned(ST_MUTEX));
4544 	return (rval);
4545 }
4546 
4547 /*
4548  * this routine spaces to EOD
4549  *
4550  * it keeps track of the current filenumber and returns the filenumber after
4551  * the last successful space operation, we keep the number high because as
4552  * tapes are getting larger, the possibility of more and more files exist,
4553  * 0x100000 (1 Meg of files) probably will never have to be changed any time
4554  * soon
4555  */
4556 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4557 
4558 static int
4559 st_find_eod(struct scsi_tape *un)
4560 {
4561 	tapepos_t savepos;
4562 	int64_t sp_type;
4563 	int result;
4564 
4565 	if (un == NULL) {
4566 		return (-1);
4567 	}
4568 
4569 	ST_FUNC(ST_DEVINFO, st_find_eod);
4570 
4571 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4572 	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4573 	    un->un_pos.fileno);
4574 
4575 	ASSERT(mutex_owned(ST_MUTEX));
4576 
4577 	COPY_POS(&savepos, &un->un_pos);
4578 
4579 	/*
4580 	 * see if the drive is smart enough to do the skips in
4581 	 * one operation; 1/2" use two filemarks
4582 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4583 	 * because the 8200 does not append a marker; in order not to
4584 	 * sacrifice the fast file skip, we do a slow skip if the low
4585 	 * density device has been opened
4586 	 */
4587 	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4588 		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4589 		    (MT_DENSITY(un->un_dev) == 0)) {
4590 			sp_type = Fmk(1);
4591 		} else if (un->un_pos.pmode == logical) {
4592 			sp_type = SPACE(SP_EOD, 0);
4593 		} else {
4594 			sp_type = Fmk(MAX_SKIP);
4595 		}
4596 	} else {
4597 		sp_type = Fmk(1);
4598 	}
4599 
4600 	for (;;) {
4601 		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4602 
4603 		if (result == 0) {
4604 			COPY_POS(&savepos, &un->un_pos);
4605 		}
4606 
4607 		if (sp_type == SPACE(SP_EOD, 0)) {
4608 			if (result != 0) {
4609 				sp_type = Fmk(MAX_SKIP);
4610 				continue;
4611 			}
4612 
4613 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4614 			    "st_find_eod: 0x%"PRIx64"\n",
4615 			    savepos.lgclblkno);
4616 			/*
4617 			 * What we return will become the current file position.
4618 			 * After completing the space command with the position
4619 			 * mode that is not invalid a read position command will
4620 			 * be automaticly issued. If the drive support the long
4621 			 * read position format a valid file position can be
4622 			 * returned.
4623 			 */
4624 			return (un->un_pos.fileno);
4625 		}
4626 
4627 		if (result != 0) {
4628 			break;
4629 		}
4630 
4631 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4632 		    "count=%"PRIx64", eof=%x, status=%x\n",
4633 		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4634 
4635 		/*
4636 		 * If we're not EOM smart,  space a record
4637 		 * to see whether we're now in the slot between
4638 		 * the two sequential filemarks that logical
4639 		 * EOM consists of (REEL) or hit nowhere land
4640 		 * (8mm).
4641 		 */
4642 		if (sp_type == Fmk(1)) {
4643 			/*
4644 			 * no fast skipping, check a record
4645 			 */
4646 			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4647 				break;
4648 			}
4649 			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4650 			    (un->un_dp->options & ST_REEL)) {
4651 				un->un_status = KEY_BLANK_CHECK;
4652 				un->un_pos.fileno++;
4653 				un->un_pos.blkno = 0;
4654 				break;
4655 			}
4656 			if (IN_EOF(un->un_pos)) {
4657 				un->un_pos.eof = ST_NO_EOF;
4658 				un->un_pos.fileno++;
4659 				un->un_pos.blkno = 0;
4660 			}
4661 			if (un->un_pos.eof > ST_EOF) {
4662 				break;
4663 			}
4664 		} else {
4665 			if (un->un_pos.eof > ST_EOF) {
4666 				break;
4667 			}
4668 		}
4669 	}
4670 
4671 	if (un->un_dp->options & ST_KNOWS_EOD) {
4672 		COPY_POS(&savepos, &un->un_pos);
4673 	}
4674 
4675 	ASSERT(mutex_owned(ST_MUTEX));
4676 
4677 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4678 	    "st_find_eod: %x\n", savepos.fileno);
4679 	return (savepos.fileno);
4680 }
4681 
4682 
4683 /*
4684  * this routine is frequently used in ioctls below;
4685  * it determines whether we know the density and if not will
4686  * determine it
4687  * if we have written the tape before, one or more filemarks are written
4688  *
4689  * depending on the stepflag, the head is repositioned to where it was before
4690  * the filemarks were written in order not to confuse step counts
4691  */
4692 #define	STEPBACK    0
4693 #define	NO_STEPBACK 1
4694 
4695 static int
4696 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4697 {
4698 
4699 	GET_SOFT_STATE(dev);
4700 
4701 	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4702 
4703 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4704 	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4705 	    "\n", dev, wfm, mode, stepflag);
4706 
4707 	ASSERT(mutex_owned(ST_MUTEX));
4708 
4709 	/*
4710 	 * If we don't yet know the density of the tape we have inserted,
4711 	 * we have to either unconditionally set it (if we're 'writing'),
4712 	 * or we have to determine it. As side effects, check for any
4713 	 * write-protect errors, and for the need to put out any file-marks
4714 	 * before positioning a tape.
4715 	 *
4716 	 * If we are going to be spacing forward, and we haven't determined
4717 	 * the tape density yet, we have to do so now...
4718 	 */
4719 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4720 		if (st_determine_density(un, mode)) {
4721 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4722 			    "check_density_or_wfm : EIO can't determine "
4723 			    "density\n");
4724 			un->un_errno = EIO;
4725 			return (EIO);
4726 		}
4727 		/*
4728 		 * Presumably we are at BOT. If we attempt to write, it will
4729 		 * either work okay, or bomb. We don't do a st_test_append
4730 		 * unless we're past BOT.
4731 		 */
4732 		un->un_laststate = un->un_state;
4733 		un->un_state = ST_STATE_OPEN;
4734 
4735 	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4736 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4737 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4738 
4739 		tapepos_t spos;
4740 
4741 		COPY_POS(&spos, &un->un_pos);
4742 
4743 		/*
4744 		 * We need to write one or two filemarks.
4745 		 * In the case of the HP, we need to
4746 		 * position the head between the two
4747 		 * marks.
4748 		 */
4749 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4750 			wfm = un->un_fmneeded;
4751 			un->un_fmneeded = 0;
4752 		}
4753 
4754 		if (st_write_fm(dev, wfm)) {
4755 			un->un_pos.pmode = invalid;
4756 			un->un_density_known = 0;
4757 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4758 			    "check_density_or_wfm : EIO can't write fm\n");
4759 			un->un_errno = EIO;
4760 			return (EIO);
4761 		}
4762 
4763 		if (stepflag == STEPBACK) {
4764 			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4765 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4766 				    "check_density_or_wfm : EIO can't space "
4767 				    "(-wfm)\n");
4768 				un->un_errno = EIO;
4769 				return (EIO);
4770 			}
4771 			COPY_POS(&un->un_pos, &spos);
4772 		}
4773 	}
4774 
4775 	/*
4776 	 * Whatever we do at this point clears the state of the eof flag.
4777 	 */
4778 
4779 	un->un_pos.eof = ST_NO_EOF;
4780 
4781 	/*
4782 	 * If writing, let's check that we're positioned correctly
4783 	 * at the end of tape before issuing the next write.
4784 	 */
4785 	if (un->un_read_only == RDWR) {
4786 		un->un_test_append = 1;
4787 	}
4788 
4789 	ASSERT(mutex_owned(ST_MUTEX));
4790 	return (0);
4791 }
4792 
4793 
4794 /*
4795  * Wait for all outstaning I/O's to complete
4796  *
4797  * we wait on both ncmds and the wait queue for times when we are flushing
4798  * after persistent errors are flagged, which is when ncmds can be 0, and the
4799  * queue can still have I/O's.  This way we preserve order of biodone's.
4800  */
4801 static void
4802 st_wait_for_io(struct scsi_tape *un)
4803 {
4804 	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4805 	ASSERT(mutex_owned(ST_MUTEX));
4806 	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4807 		cv_wait(&un->un_queue_cv, ST_MUTEX);
4808 	}
4809 }
4810 
4811 /*
4812  * This routine implements the ioctl calls.  It is called
4813  * from the device switch at normal priority.
4814  */
4815 /*ARGSUSED*/
4816 static int
4817 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4818     int *rval_p)
4819 {
4820 	int tmp, rval = 0;
4821 
4822 	GET_SOFT_STATE(dev);
4823 
4824 	ST_ENTR(ST_DEVINFO, st_ioctl);
4825 
4826 	mutex_enter(ST_MUTEX);
4827 
4828 	ASSERT(un->un_recov_buf_busy == 0);
4829 
4830 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4831 	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4832 	    "pe_flag = %d\n",
4833 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4834 	    un->un_persistence && un->un_persist_errors);
4835 
4836 	/*
4837 	 * We don't want to block on these, so let them through
4838 	 * and we don't care about setting driver states here.
4839 	 */
4840 	if ((cmd == MTIOCGETDRIVETYPE) ||
4841 	    (cmd == MTIOCGUARANTEEDORDER) ||
4842 	    (cmd == MTIOCPERSISTENTSTATUS)) {
4843 		goto check_commands;
4844 	}
4845 
4846 	/*
4847 	 * We clear error entry stack except command
4848 	 * MTIOCGETERROR and MTIOCGET
4849 	 */
4850 	if ((cmd != MTIOCGETERROR) &&
4851 	    (cmd != MTIOCGET)) {
4852 		st_empty_error_stack(un);
4853 	}
4854 
4855 	/*
4856 	 * wait for all outstanding commands to complete, or be dequeued.
4857 	 * And because ioctl's are synchronous commands, any return value
4858 	 * after this,  will be in order
4859 	 */
4860 	st_wait_for_io(un);
4861 
4862 	/*
4863 	 * allow only a through clear errors and persistent status, and
4864 	 * status
4865 	 */
4866 	if (un->un_persistence && un->un_persist_errors) {
4867 		if ((cmd == MTIOCLRERR) ||
4868 		    (cmd == MTIOCPERSISTENT) ||
4869 		    (cmd == MTIOCGET)) {
4870 			goto check_commands;
4871 		} else {
4872 			rval = un->un_errno;
4873 			goto exit;
4874 		}
4875 	}
4876 
4877 	ASSERT(un->un_throttle != 0);
4878 	un->un_throttle = 1;	/* > 1 will never happen here */
4879 	un->un_errno = 0;	/* start clean from here */
4880 
4881 	/*
4882 	 * first and foremost, handle any ST_EOT_PENDING cases.
4883 	 * That is, if a logical eot is pending notice, notice it.
4884 	 */
4885 	if (un->un_pos.eof == ST_EOT_PENDING) {
4886 		int resid = un->un_err_resid;
4887 		uchar_t status = un->un_status;
4888 		uchar_t lastop = un->un_lastop;
4889 
4890 		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4891 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4892 			    "stioctl : EIO can't space fmk(-1)\n");
4893 			rval = EIO;
4894 			goto exit;
4895 		}
4896 		un->un_lastop = lastop; /* restore last operation */
4897 		if (status == SUN_KEY_EOF) {
4898 			un->un_status = SUN_KEY_EOT;
4899 		} else {
4900 			un->un_status = status;
4901 		}
4902 		un->un_err_resid  = resid;
4903 		/* fix up block number */
4904 		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4905 		/* now we're at logical eot */
4906 		un->un_pos.eof = ST_EOT;
4907 	}
4908 
4909 	/*
4910 	 * now, handle the rest of the situations
4911 	 */
4912 check_commands:
4913 	switch (cmd) {
4914 	case MTIOCGET:
4915 	{
4916 #ifdef _MULTI_DATAMODEL
4917 		/*
4918 		 * For use when a 32 bit app makes a call into a
4919 		 * 64 bit ioctl
4920 		 */
4921 		struct mtget32		mtg_local32;
4922 		struct mtget32 		*mtget_32 = &mtg_local32;
4923 #endif /* _MULTI_DATAMODEL */
4924 
4925 			/* Get tape status */
4926 		struct mtget mtg_local;
4927 		struct mtget *mtget = &mtg_local;
4928 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4929 		    "st_ioctl: MTIOCGET\n");
4930 
4931 		bzero((caddr_t)mtget, sizeof (struct mtget));
4932 		mtget->mt_erreg = un->un_status;
4933 		mtget->mt_resid = un->un_err_resid;
4934 		mtget->mt_dsreg = un->un_retry_ct;
4935 		if (un->un_err_pos.pmode == legacy) {
4936 			mtget->mt_fileno = un->un_err_pos.fileno;
4937 		} else {
4938 			mtget->mt_fileno = -1;
4939 		}
4940 		/*
4941 		 * If the value is positive fine.
4942 		 * If its negative we need to return a value based on the
4943 		 * old way if counting backwards from INF (1,000,000,000).
4944 		 */
4945 		if (un->un_err_pos.blkno >= 0) {
4946 			mtget->mt_blkno = un->un_err_pos.blkno;
4947 		} else {
4948 			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4949 		}
4950 		mtget->mt_type = un->un_dp->type;
4951 		mtget->mt_flags = MTF_SCSI | MTF_ASF;
4952 		if (un->un_read_pos_type != NO_POS) {
4953 			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
4954 		}
4955 		if (un->un_dp->options & ST_REEL) {
4956 			mtget->mt_flags |= MTF_REEL;
4957 			mtget->mt_bf = 20;
4958 		} else {		/* 1/4" cartridges */
4959 			switch (mtget->mt_type) {
4960 			/* Emulex cartridge tape */
4961 			case MT_ISMT02:
4962 				mtget->mt_bf = 40;
4963 				break;
4964 			default:
4965 				mtget->mt_bf = 126;
4966 				break;
4967 			}
4968 		}
4969 
4970 		/*
4971 		 * If large transfers are allowed and drive options
4972 		 * has no record size limit set. Calculate blocking
4973 		 * factor from the lesser of maxbsize and maxdma.
4974 		 */
4975 		if ((un->un_allow_large_xfer) &&
4976 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
4977 			mtget->mt_bf = min(un->un_maxbsize,
4978 			    un->un_maxdma) / SECSIZE;
4979 		}
4980 
4981 		if (un->un_read_only == WORM ||
4982 		    un->un_read_only == RDWORM) {
4983 			mtget->mt_flags |= MTF_WORM_MEDIA;
4984 		}
4985 
4986 		/*
4987 		 * In persistent error mode sending a non-queued can hang
4988 		 * because this ioctl gets to be run without turning off
4989 		 * persistense. Fake the answer based on previous info.
4990 		 */
4991 		if (un->un_persistence) {
4992 			rval = 0;
4993 		} else {
4994 			rval = st_check_clean_bit(un);
4995 		}
4996 		if (rval == 0) {
4997 			/*
4998 			 * If zero is returned or in persistent mode,
4999 			 * use the old data.
5000 			 */
5001 			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5002 			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5003 			    != TAPE_ALERT_NOT_SUPPORTED) {
5004 				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5005 			}
5006 			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5007 			    TAPE_ALERT_STILL_DIRTY)) {
5008 				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5009 			}
5010 		} else {
5011 			mtget->mt_flags |= (ushort_t)rval;
5012 			rval = 0;
5013 		}
5014 
5015 		un->un_status = 0;		/* Reset status */
5016 		un->un_err_resid = 0;
5017 		tmp = sizeof (struct mtget);
5018 
5019 #ifdef _MULTI_DATAMODEL
5020 
5021 		switch (ddi_model_convert_from(flag & FMODELS)) {
5022 		case DDI_MODEL_ILP32:
5023 			/*
5024 			 * Convert 64 bit back to 32 bit before doing
5025 			 * copyout. This is what the ILP32 app expects.
5026 			 */
5027 			mtget_32->mt_erreg = 	mtget->mt_erreg;
5028 			mtget_32->mt_resid = 	mtget->mt_resid;
5029 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
5030 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
5031 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
5032 			mtget_32->mt_type =  	mtget->mt_type;
5033 			mtget_32->mt_flags = 	mtget->mt_flags;
5034 			mtget_32->mt_bf = 	mtget->mt_bf;
5035 
5036 			if (ddi_copyout(mtget_32, (void *)arg,
5037 			    sizeof (struct mtget32), flag)) {
5038 				rval = EFAULT;
5039 			}
5040 			break;
5041 
5042 		case DDI_MODEL_NONE:
5043 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5044 				rval = EFAULT;
5045 			}
5046 			break;
5047 		}
5048 #else /* ! _MULTI_DATAMODE */
5049 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5050 			rval = EFAULT;
5051 		}
5052 #endif /* _MULTI_DATAMODE */
5053 
5054 		break;
5055 	}
5056 	case MTIOCGETERROR:
5057 			/*
5058 			 * get error entry from error stack
5059 			 */
5060 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5061 			    "st_ioctl: MTIOCGETERROR\n");
5062 
5063 			rval = st_get_error_entry(un, arg, flag);
5064 
5065 			break;
5066 
5067 	case MTIOCSTATE:
5068 		{
5069 			/*
5070 			 * return when media presence matches state
5071 			 */
5072 			enum mtio_state state;
5073 
5074 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5075 			    "st_ioctl: MTIOCSTATE\n");
5076 
5077 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5078 				rval = EFAULT;
5079 
5080 			mutex_exit(ST_MUTEX);
5081 
5082 			rval = st_check_media(dev, state);
5083 
5084 			mutex_enter(ST_MUTEX);
5085 
5086 			if (rval != 0) {
5087 				break;
5088 			}
5089 
5090 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5091 			    sizeof (int), flag))
5092 				rval = EFAULT;
5093 			break;
5094 
5095 		}
5096 
5097 	case MTIOCGETDRIVETYPE:
5098 		{
5099 #ifdef _MULTI_DATAMODEL
5100 		/*
5101 		 * For use when a 32 bit app makes a call into a
5102 		 * 64 bit ioctl
5103 		 */
5104 		struct mtdrivetype_request32	mtdtrq32;
5105 #endif /* _MULTI_DATAMODEL */
5106 
5107 			/*
5108 			 * return mtdrivetype
5109 			 */
5110 			struct mtdrivetype_request mtdtrq;
5111 			struct mtdrivetype mtdrtyp;
5112 			struct mtdrivetype *mtdt = &mtdrtyp;
5113 			struct st_drivetype *stdt = un->un_dp;
5114 
5115 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5116 			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5117 
5118 #ifdef _MULTI_DATAMODEL
5119 		switch (ddi_model_convert_from(flag & FMODELS)) {
5120 		case DDI_MODEL_ILP32:
5121 		{
5122 			if (ddi_copyin((void *)arg, &mtdtrq32,
5123 			    sizeof (struct mtdrivetype_request32), flag)) {
5124 				rval = EFAULT;
5125 				break;
5126 			}
5127 			mtdtrq.size = mtdtrq32.size;
5128 			mtdtrq.mtdtp =
5129 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5130 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5131 			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5132 			break;
5133 		}
5134 		case DDI_MODEL_NONE:
5135 			if (ddi_copyin((void *)arg, &mtdtrq,
5136 			    sizeof (struct mtdrivetype_request), flag)) {
5137 				rval = EFAULT;
5138 				break;
5139 			}
5140 			break;
5141 		}
5142 
5143 #else /* ! _MULTI_DATAMODEL */
5144 		if (ddi_copyin((void *)arg, &mtdtrq,
5145 		    sizeof (struct mtdrivetype_request), flag)) {
5146 			rval = EFAULT;
5147 			break;
5148 		}
5149 #endif /* _MULTI_DATAMODEL */
5150 
5151 			/*
5152 			 * if requested size is < 0 then return
5153 			 * error.
5154 			 */
5155 			if (mtdtrq.size < 0) {
5156 				rval = EINVAL;
5157 				break;
5158 			}
5159 			bzero(mtdt, sizeof (struct mtdrivetype));
5160 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5161 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5162 			mtdt->type = stdt->type;
5163 			mtdt->bsize = stdt->bsize;
5164 			mtdt->options = stdt->options;
5165 			mtdt->max_rretries = stdt->max_rretries;
5166 			mtdt->max_wretries = stdt->max_wretries;
5167 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5168 				mtdt->densities[tmp] = stdt->densities[tmp];
5169 			}
5170 			mtdt->default_density = stdt->default_density;
5171 			/*
5172 			 * Speed hasn't been used since the hayday of reel tape.
5173 			 * For all drives not setting the option ST_KNOWS_MEDIA
5174 			 * the speed member renamed to mediatype are zeros.
5175 			 * Those drives that have ST_KNOWS_MEDIA set use the
5176 			 * new mediatype member which is used to figure the
5177 			 * type of media loaded.
5178 			 *
5179 			 * So as to not break applications speed in the
5180 			 * mtdrivetype structure is not renamed.
5181 			 */
5182 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5183 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5184 			}
5185 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5186 			mtdt->io_timeout = stdt->io_timeout;
5187 			mtdt->rewind_timeout = stdt->rewind_timeout;
5188 			mtdt->space_timeout = stdt->space_timeout;
5189 			mtdt->load_timeout = stdt->load_timeout;
5190 			mtdt->unload_timeout = stdt->unload_timeout;
5191 			mtdt->erase_timeout = stdt->erase_timeout;
5192 
5193 			/*
5194 			 * Limit the maximum length of the result to
5195 			 * sizeof (struct mtdrivetype).
5196 			 */
5197 			tmp = sizeof (struct mtdrivetype);
5198 			if (mtdtrq.size < tmp)
5199 				tmp = mtdtrq.size;
5200 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5201 				rval = EFAULT;
5202 			}
5203 			break;
5204 		}
5205 	case MTIOCPERSISTENT:
5206 
5207 		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5208 			rval = EFAULT;
5209 			break;
5210 		}
5211 
5212 		if (tmp) {
5213 			st_turn_pe_on(un);
5214 		} else {
5215 			st_turn_pe_off(un);
5216 		}
5217 
5218 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5219 		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5220 		    un->un_persistence);
5221 
5222 		break;
5223 
5224 	case MTIOCPERSISTENTSTATUS:
5225 		tmp = (int)un->un_persistence;
5226 
5227 		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5228 			rval = EFAULT;
5229 		}
5230 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5231 		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5232 		    un->un_persistence);
5233 
5234 		break;
5235 
5236 	case MTIOCLRERR:
5237 		{
5238 			/* clear persistent errors */
5239 
5240 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5241 			    "st_ioctl: MTIOCLRERR\n");
5242 
5243 			st_clear_pe(un);
5244 
5245 			break;
5246 		}
5247 
5248 	case MTIOCGUARANTEEDORDER:
5249 		{
5250 			/*
5251 			 * this is just a holder to make a valid ioctl and
5252 			 * it won't be in any earlier release
5253 			 */
5254 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5255 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5256 
5257 			break;
5258 		}
5259 
5260 	case MTIOCRESERVE:
5261 		{
5262 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5263 			    "st_ioctl: MTIOCRESERVE\n");
5264 
5265 			/*
5266 			 * Check if Reserve/Release is supported.
5267 			 */
5268 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5269 				rval = ENOTTY;
5270 				break;
5271 			}
5272 
5273 			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5274 
5275 			if (rval == 0) {
5276 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5277 			}
5278 			break;
5279 		}
5280 
5281 	case MTIOCRELEASE:
5282 		{
5283 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5284 			    "st_ioctl: MTIOCRELEASE\n");
5285 
5286 			/*
5287 			 * Check if Reserve/Release is supported.
5288 			 */
5289 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5290 				rval = ENOTTY;
5291 				break;
5292 			}
5293 
5294 			/*
5295 			 * Used to just clear ST_PRESERVE_RESERVE which
5296 			 * made the reservation release at next close.
5297 			 * As the user may have opened and then done a
5298 			 * persistant reservation we now need to drop
5299 			 * the reservation without closing if the user
5300 			 * attempts to do this.
5301 			 */
5302 			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5303 
5304 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5305 
5306 			break;
5307 		}
5308 
5309 	case MTIOCFORCERESERVE:
5310 	{
5311 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5312 		    "st_ioctl: MTIOCFORCERESERVE\n");
5313 
5314 		/*
5315 		 * Check if Reserve/Release is supported.
5316 		 */
5317 		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5318 			rval = ENOTTY;
5319 			break;
5320 		}
5321 		/*
5322 		 * allow only super user to run this.
5323 		 */
5324 		if (drv_priv(cred_p) != 0) {
5325 			rval = EPERM;
5326 			break;
5327 		}
5328 		/*
5329 		 * Throw away reserve,
5330 		 * not using test-unit-ready
5331 		 * since reserve can succeed without tape being
5332 		 * present in the drive.
5333 		 */
5334 		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5335 
5336 		rval = st_take_ownership(un, st_uscsi_cmd);
5337 
5338 		break;
5339 	}
5340 
5341 	case USCSICMD:
5342 	{
5343 		cred_t	*cr;
5344 
5345 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5346 		    "st_ioctl: USCSICMD\n");
5347 
5348 		cr = ddi_get_cred();
5349 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5350 			rval = EPERM;
5351 		} else {
5352 			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5353 		}
5354 		break;
5355 	}
5356 	case MTIOCTOP:
5357 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5358 		    "st_ioctl: MTIOCTOP\n");
5359 		rval = st_mtioctop(un, arg, flag);
5360 		break;
5361 
5362 	case MTIOCLTOP:
5363 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5364 		    "st_ioctl: MTIOLCTOP\n");
5365 		rval = st_mtiocltop(un, arg, flag);
5366 		break;
5367 
5368 	case MTIOCREADIGNOREILI:
5369 		{
5370 			int set_ili;
5371 
5372 			if (ddi_copyin((void *)arg, &set_ili,
5373 			    sizeof (set_ili), flag)) {
5374 				rval = EFAULT;
5375 				break;
5376 			}
5377 
5378 			if (un->un_bsize) {
5379 				rval = ENOTTY;
5380 				break;
5381 			}
5382 
5383 			switch (set_ili) {
5384 			case 0:
5385 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5386 				break;
5387 
5388 			case 1:
5389 				un->un_dp->options |= ST_READ_IGNORE_ILI;
5390 				break;
5391 
5392 			default:
5393 				rval = EINVAL;
5394 				break;
5395 			}
5396 			break;
5397 		}
5398 
5399 	case MTIOCREADIGNOREEOFS:
5400 		{
5401 			int ignore_eof;
5402 
5403 			if (ddi_copyin((void *)arg, &ignore_eof,
5404 			    sizeof (ignore_eof), flag)) {
5405 				rval = EFAULT;
5406 				break;
5407 			}
5408 
5409 			if (!(un->un_dp->options & ST_REEL)) {
5410 				rval = ENOTTY;
5411 				break;
5412 			}
5413 
5414 			switch (ignore_eof) {
5415 			case 0:
5416 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5417 				break;
5418 
5419 			case 1:
5420 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5421 				break;
5422 
5423 			default:
5424 				rval = EINVAL;
5425 				break;
5426 			}
5427 			break;
5428 		}
5429 
5430 	case MTIOCSHORTFMK:
5431 	{
5432 		int short_fmk;
5433 
5434 		if (ddi_copyin((void *)arg, &short_fmk,
5435 		    sizeof (short_fmk), flag)) {
5436 			rval = EFAULT;
5437 			break;
5438 		}
5439 
5440 		switch (un->un_dp->type) {
5441 		case ST_TYPE_EXB8500:
5442 		case ST_TYPE_EXABYTE:
5443 			if (!short_fmk) {
5444 				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5445 			} else if (short_fmk == 1) {
5446 				un->un_dp->options |= ST_SHORT_FILEMARKS;
5447 			} else {
5448 				rval = EINVAL;
5449 			}
5450 			break;
5451 
5452 		default:
5453 			rval = ENOTTY;
5454 			break;
5455 		}
5456 		break;
5457 	}
5458 
5459 	case MTIOCGETPOS:
5460 		rval = st_update_block_pos(un, st_cmd, 0);
5461 		if (rval == 0) {
5462 			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5463 			    sizeof (tapepos_t), flag)) {
5464 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5465 				    "MTIOCGETPOS copy out failed\n");
5466 				rval = EFAULT;
5467 			}
5468 		}
5469 		break;
5470 
5471 	case MTIOCRESTPOS:
5472 	{
5473 		tapepos_t dest;
5474 
5475 		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5476 		    flag) != 0) {
5477 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5478 			    "MTIOCRESTPOS copy in failed\n");
5479 			rval = EFAULT;
5480 			break;
5481 		}
5482 		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5483 		if (rval != 0) {
5484 			rval = EIO;
5485 		}
5486 		break;
5487 	}
5488 	default:
5489 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5490 		    "st_ioctl: unknown ioctl\n");
5491 		rval = ENOTTY;
5492 	}
5493 
5494 exit:
5495 	if (!(un->un_persistence && un->un_persist_errors)) {
5496 		un->un_errno = rval;
5497 	}
5498 
5499 	mutex_exit(ST_MUTEX);
5500 
5501 	return (rval);
5502 }
5503 
5504 
5505 /*
5506  * do some MTIOCTOP tape operations
5507  */
5508 static int
5509 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5510 {
5511 #ifdef _MULTI_DATAMODEL
5512 	/*
5513 	 * For use when a 32 bit app makes a call into a
5514 	 * 64 bit ioctl
5515 	 */
5516 	struct mtop32	mtop_32_for_64;
5517 #endif /* _MULTI_DATAMODEL */
5518 	struct mtop passed;
5519 	struct mtlop local;
5520 	int rval = 0;
5521 
5522 	ST_FUNC(ST_DEVINFO, st_mtioctop);
5523 
5524 	ASSERT(mutex_owned(ST_MUTEX));
5525 
5526 #ifdef _MULTI_DATAMODEL
5527 	switch (ddi_model_convert_from(flag & FMODELS)) {
5528 	case DDI_MODEL_ILP32:
5529 		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5530 		    sizeof (struct mtop32), flag)) {
5531 			return (EFAULT);
5532 		}
5533 		local.mt_op = mtop_32_for_64.mt_op;
5534 		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5535 		break;
5536 
5537 	case DDI_MODEL_NONE:
5538 		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5539 			return (EFAULT);
5540 		}
5541 		local.mt_op = passed.mt_op;
5542 		/* prevent sign extention */
5543 		local.mt_count = (UINT32_MAX & passed.mt_count);
5544 		break;
5545 	}
5546 
5547 #else /* ! _MULTI_DATAMODEL */
5548 	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5549 		return (EFAULT);
5550 	}
5551 	local.mt_op = passed.mt_op;
5552 	/* prevent sign extention */
5553 	local.mt_count = (UINT32_MAX & passed.mt_count);
5554 #endif /* _MULTI_DATAMODEL */
5555 
5556 	rval = st_do_mtioctop(un, &local);
5557 
5558 #ifdef _MULTI_DATAMODEL
5559 	switch (ddi_model_convert_from(flag & FMODELS)) {
5560 	case DDI_MODEL_ILP32:
5561 		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5562 			rval = ERANGE;
5563 			break;
5564 		}
5565 		/*
5566 		 * Convert 64 bit back to 32 bit before doing
5567 		 * copyout. This is what the ILP32 app expects.
5568 		 */
5569 		mtop_32_for_64.mt_op = local.mt_op;
5570 		mtop_32_for_64.mt_count = local.mt_count;
5571 
5572 		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5573 		    sizeof (struct mtop32), flag)) {
5574 			rval = EFAULT;
5575 		}
5576 		break;
5577 
5578 	case DDI_MODEL_NONE:
5579 		passed.mt_count = local.mt_count;
5580 		passed.mt_op = local.mt_op;
5581 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5582 			rval = EFAULT;
5583 		}
5584 		break;
5585 	}
5586 #else /* ! _MULTI_DATAMODE */
5587 	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5588 		rval = ERANGE;
5589 	} else {
5590 		passed.mt_op = local.mt_op;
5591 		passed.mt_count = local.mt_count;
5592 		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5593 			rval = EFAULT;
5594 		}
5595 	}
5596 #endif /* _MULTI_DATAMODE */
5597 
5598 
5599 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5600 	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5601 	    un->un_pos.blkno, un->un_pos.eof);
5602 
5603 	if (un->un_pos.pmode == invalid) {
5604 		un->un_density_known = 0;
5605 	}
5606 
5607 	ASSERT(mutex_owned(ST_MUTEX));
5608 	return (rval);
5609 }
5610 
5611 static int
5612 st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5613 {
5614 	struct mtlop local;
5615 	int rval;
5616 
5617 	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5618 	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5619 		return (EFAULT);
5620 	}
5621 
5622 	rval = st_do_mtioctop(un, &local);
5623 
5624 	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5625 		rval = EFAULT;
5626 	}
5627 	return (rval);
5628 }
5629 
5630 
5631 static int
5632 st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5633 {
5634 	dev_t dev = un->un_dev;
5635 	int savefile;
5636 	int rval = 0;
5637 
5638 	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5639 
5640 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5641 	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5642 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5643 	    "fileno=%x, blkno=%x, eof=%x\n",
5644 	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5645 
5646 	un->un_status = 0;
5647 
5648 	/*
5649 	 * if we are going to mess with a tape, we have to make sure we have
5650 	 * one and are not offline (i.e. no tape is initialized).  We let
5651 	 * commands pass here that don't actually touch the tape, except for
5652 	 * loading and initialization (rewinding).
5653 	 */
5654 	if (un->un_state == ST_STATE_OFFLINE) {
5655 		switch (mtop->mt_op) {
5656 		case MTLOAD:
5657 		case MTNOP:
5658 			/*
5659 			 * We don't want strategy calling st_tape_init here,
5660 			 * so, change state
5661 			 */
5662 			un->un_state = ST_STATE_INITIALIZING;
5663 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5664 			    "st_do_mtioctop : OFFLINE state = %d\n",
5665 			    un->un_state);
5666 			break;
5667 		default:
5668 			/*
5669 			 * reinitialize by normal means
5670 			 */
5671 			rval = st_tape_init(un);
5672 			if (rval) {
5673 				un->un_state = ST_STATE_INITIALIZING;
5674 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5675 				    "st_do_mtioctop : OFFLINE init failure ");
5676 				un->un_state = ST_STATE_OFFLINE;
5677 				un->un_pos.pmode = invalid;
5678 				if (rval != EACCES) {
5679 					rval = EIO;
5680 				}
5681 				return (rval);
5682 			}
5683 			un->un_state = ST_STATE_OPEN_PENDING_IO;
5684 			break;
5685 		}
5686 	}
5687 
5688 	/*
5689 	 * If the file position is invalid, allow only those
5690 	 * commands that properly position the tape and fail
5691 	 * the rest with EIO
5692 	 */
5693 	if (un->un_pos.pmode == invalid) {
5694 		switch (mtop->mt_op) {
5695 		case MTWEOF:
5696 		case MTRETEN:
5697 		case MTERASE:
5698 		case MTEOM:
5699 		case MTFSF:
5700 		case MTFSR:
5701 		case MTBSF:
5702 		case MTNBSF:
5703 		case MTBSR:
5704 		case MTSRSZ:
5705 		case MTGRSZ:
5706 		case MTSEEK:
5707 		case MTBSSF:
5708 		case MTFSSF:
5709 			return (EIO);
5710 			/* NOTREACHED */
5711 		case MTREW:
5712 		case MTLOAD:
5713 		case MTOFFL:
5714 		case MTNOP:
5715 		case MTTELL:
5716 		case MTLOCK:
5717 		case MTUNLOCK:
5718 			break;
5719 
5720 		default:
5721 			return (ENOTTY);
5722 			/* NOTREACHED */
5723 		}
5724 	}
5725 
5726 	switch (mtop->mt_op) {
5727 	case MTERASE:
5728 		/*
5729 		 * MTERASE rewinds the tape, erase it completely, and returns
5730 		 * to the beginning of the tape
5731 		 */
5732 		if (un->un_mspl->wp || un->un_read_only & WORM) {
5733 			un->un_status = KEY_WRITE_PROTECT;
5734 			un->un_err_resid = mtop->mt_count;
5735 			COPY_POS(&un->un_err_pos, &un->un_pos);
5736 			return (EACCES);
5737 		}
5738 		if (un->un_dp->options & ST_REEL) {
5739 			un->un_fmneeded = 2;
5740 		} else {
5741 			un->un_fmneeded = 1;
5742 		}
5743 		mtop->mt_count = mtop->mt_count ? 1 : 0;
5744 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5745 		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5746 		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5747 			un->un_pos.pmode = invalid;
5748 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5749 			    "st_do_mtioctop : EIO space or erase or "
5750 			    "check den)\n");
5751 			rval = EIO;
5752 		} else {
5753 			/* QIC and helical scan rewind after erase */
5754 			if (un->un_dp->options & ST_REEL) {
5755 				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5756 			}
5757 		}
5758 		break;
5759 
5760 	case MTWEOF:
5761 		/*
5762 		 * write an end-of-file record
5763 		 */
5764 		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5765 			un->un_status = KEY_WRITE_PROTECT;
5766 			un->un_err_resid = mtop->mt_count;
5767 			COPY_POS(&un->un_err_pos, &un->un_pos);
5768 			return (EACCES);
5769 		}
5770 
5771 		/*
5772 		 * zero count means just flush buffers
5773 		 * negative count is not permitted
5774 		 */
5775 		if (mtop->mt_count < 0) {
5776 			return (EINVAL);
5777 		}
5778 
5779 		/* Not on worm */
5780 		if (un->un_read_only == RDWR) {
5781 			un->un_test_append = 1;
5782 		}
5783 
5784 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5785 			if (st_determine_density(un, B_WRITE)) {
5786 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5787 				    "st_do_mtioctop : EIO : MTWEOF can't "
5788 				    "determine density");
5789 				return (EIO);
5790 			}
5791 		}
5792 
5793 		rval = st_write_fm(dev, (int)mtop->mt_count);
5794 		if ((rval != 0) && (rval != EACCES)) {
5795 			/*
5796 			 * Failure due to something other than illegal
5797 			 * request results in loss of state (st_intr).
5798 			 */
5799 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5800 			    "st_do_mtioctop : EIO : MTWEOF can't write "
5801 			    "file mark");
5802 			rval = EIO;
5803 		}
5804 		break;
5805 
5806 	case MTRETEN:
5807 		/*
5808 		 * retension the tape
5809 		 */
5810 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5811 		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5812 			un->un_pos.pmode = invalid;
5813 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5814 			    "st_do_mtioctop : EIO : MTRETEN ");
5815 			rval = EIO;
5816 		}
5817 		break;
5818 
5819 	case MTREW:
5820 		/*
5821 		 * rewind  the tape
5822 		 */
5823 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5824 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5825 			    "st_do_mtioctop : EIO:MTREW check "
5826 			    "density/wfm failed");
5827 			return (EIO);
5828 		}
5829 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5830 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5831 			    "st_do_mtioctop : EIO : MTREW ");
5832 			rval = EIO;
5833 		}
5834 		break;
5835 
5836 	case MTOFFL:
5837 		/*
5838 		 * rewinds, and, if appropriate, takes the device offline by
5839 		 * unloading the tape
5840 		 */
5841 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5842 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5843 			    "st_do_mtioctop :EIO:MTOFFL check "
5844 			    "density/wfm failed");
5845 			return (EIO);
5846 		}
5847 		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5848 		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5849 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5850 			    "st_do_mtioctop : EIO : MTOFFL");
5851 			return (EIO);
5852 		}
5853 		un->un_pos.eof = ST_NO_EOF;
5854 		un->un_laststate = un->un_state;
5855 		un->un_state = ST_STATE_OFFLINE;
5856 		un->un_mediastate = MTIO_EJECTED;
5857 		break;
5858 
5859 	case MTLOAD:
5860 		/*
5861 		 * This is to load a tape into the drive
5862 		 * Note that if the tape is not loaded, the device will have
5863 		 * to be opened via O_NDELAY or O_NONBLOCK.
5864 		 */
5865 		/*
5866 		 * Let's try and clean things up, if we are not
5867 		 * initializing, and then send in the load command, no
5868 		 * matter what.
5869 		 *
5870 		 * load after a media change by the user.
5871 		 */
5872 
5873 		if (un->un_state > ST_STATE_INITIALIZING) {
5874 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5875 		}
5876 		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5877 		/* Load command to a drive that doesn't support load */
5878 		if ((rval == EIO) &&
5879 		    ((un->un_status == KEY_NOT_READY) &&
5880 			/* Medium not present */
5881 		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5882 		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5883 		    (un->un_dp->type == MT_ISSTK9840) &&
5884 			/* CSL not present */
5885 		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5886 			rval = ENOTTY;
5887 			break;
5888 		} else if (rval != EACCES && rval != 0) {
5889 			rval = EIO;
5890 		}
5891 		if (rval) {
5892 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5893 			    "st_do_mtioctop : %s : MTLOAD\n",
5894 			    rval == EACCES ? "EACCES" : "EIO");
5895 			/*
5896 			 * If load tape fails, who knows what happened...
5897 			 */
5898 			un->un_pos.pmode = invalid;
5899 			break;
5900 		}
5901 
5902 		/*
5903 		 * reset all counters appropriately using rewind, as if LOAD
5904 		 * succeeds, we are at BOT
5905 		 */
5906 		un->un_state = ST_STATE_INITIALIZING;
5907 
5908 		rval = st_tape_init(un);
5909 		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5910 			rval = 0;
5911 			break;
5912 		}
5913 
5914 		if (rval != 0) {
5915 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5916 			    "st_do_mtioctop : EIO : MTLOAD calls "
5917 			    "st_tape_init\n");
5918 			rval = EIO;
5919 			un->un_state = ST_STATE_OFFLINE;
5920 		}
5921 
5922 		break;
5923 
5924 	case MTNOP:
5925 		un->un_status = 0;		/* Reset status */
5926 		un->un_err_resid = 0;
5927 		mtop->mt_count = MTUNIT(dev);
5928 		break;
5929 
5930 	case MTEOM:
5931 		/*
5932 		 * positions the tape at a location just after the last file
5933 		 * written on the tape. For cartridge and 8 mm, this after
5934 		 * the last file mark; for reel, this is inbetween the two
5935 		 * last 2 file marks
5936 		 */
5937 		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5938 		    (un->un_lastop == ST_OP_WRITE) ||
5939 		    (un->un_lastop == ST_OP_WEOF)) {
5940 			/*
5941 			 * If the command wants to move to logical end
5942 			 * of media, and we're already there, we're done.
5943 			 * If we were at logical eot, we reset the state
5944 			 * to be *not* at logical eot.
5945 			 *
5946 			 * If we're at physical or logical eot, we prohibit
5947 			 * forward space operations (unconditionally).
5948 			 *
5949 			 * Also if the last operation was a write of any
5950 			 * kind the tape is at EOD.
5951 			 */
5952 			return (0);
5953 		}
5954 		/*
5955 		 * physical tape position may not be what we've been
5956 		 * telling the user; adjust the request accordingly
5957 		 */
5958 		if (IN_EOF(un->un_pos)) {
5959 			un->un_pos.fileno++;
5960 			un->un_pos.blkno = 0;
5961 		}
5962 
5963 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
5964 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5965 			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
5966 			    " failed");
5967 			return (EIO);
5968 		}
5969 
5970 		/*
5971 		 * st_find_eod() returns the last fileno we knew about;
5972 		 */
5973 		savefile = st_find_eod(un);
5974 
5975 		if ((un->un_status != KEY_BLANK_CHECK) &&
5976 		    (un->un_status != SUN_KEY_EOT)) {
5977 			un->un_pos.pmode = invalid;
5978 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5979 			    "st_do_mtioctop : EIO : MTEOM status check failed");
5980 			rval = EIO;
5981 		} else {
5982 			/*
5983 			 * For 1/2" reel tapes assume logical EOT marked
5984 			 * by two file marks or we don't care that we may
5985 			 * be extending the last file on the tape.
5986 			 */
5987 			if (un->un_dp->options & ST_REEL) {
5988 				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
5989 					un->un_pos.pmode = invalid;
5990 					ST_DEBUG2(ST_DEVINFO, st_label,
5991 					    SCSI_DEBUG,
5992 					    "st_do_mtioctop : EIO : MTEOM space"
5993 					    " cmd failed");
5994 					rval = EIO;
5995 					break;
5996 				}
5997 				/*
5998 				 * Fix up the block number.
5999 				 */
6000 				un->un_pos.blkno = 0;
6001 				un->un_err_pos.blkno = 0;
6002 			}
6003 			un->un_err_resid = 0;
6004 			un->un_pos.fileno = savefile;
6005 			un->un_pos.eof = ST_EOT;
6006 		}
6007 		un->un_status = 0;
6008 		break;
6009 
6010 	case MTFSF:
6011 		MAX_SPACE_CNT(mtop->mt_count);
6012 		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6013 		break;
6014 
6015 	case MTFSR:
6016 		MAX_SPACE_CNT(mtop->mt_count);
6017 		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6018 		break;
6019 
6020 	case MTBSF:
6021 		MAX_SPACE_CNT(mtop->mt_count);
6022 		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6023 		break;
6024 
6025 	case MTNBSF:
6026 		MAX_SPACE_CNT(mtop->mt_count);
6027 		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6028 		break;
6029 
6030 	case MTBSR:
6031 		MAX_SPACE_CNT(mtop->mt_count);
6032 		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6033 		break;
6034 
6035 	case MTBSSF:
6036 		MAX_SPACE_CNT(mtop->mt_count);
6037 		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6038 		break;
6039 
6040 	case MTFSSF:
6041 		MAX_SPACE_CNT(mtop->mt_count);
6042 		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6043 		break;
6044 
6045 	case MTSRSZ:
6046 
6047 		/*
6048 		 * Set record-size to that sent by user
6049 		 * Check to see if there is reason that the requested
6050 		 * block size should not be set.
6051 		 */
6052 
6053 		/* If requesting variable block size is it ok? */
6054 		if ((mtop->mt_count == 0) &&
6055 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6056 			return (ENOTTY);
6057 		}
6058 
6059 		/*
6060 		 * If requested block size is not variable "0",
6061 		 * is it less then minimum.
6062 		 */
6063 		if ((mtop->mt_count != 0) &&
6064 		    (mtop->mt_count < un->un_minbsize)) {
6065 			return (EINVAL);
6066 		}
6067 
6068 		/* Is the requested block size more then maximum */
6069 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6070 		    (un->un_maxbsize != 0)) {
6071 			return (EINVAL);
6072 		}
6073 
6074 		/* Is requested block size a modulus the device likes */
6075 		if ((mtop->mt_count % un->un_data_mod) != 0) {
6076 			return (EINVAL);
6077 		}
6078 
6079 		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6080 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6081 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6082 			return (EIO);
6083 		}
6084 
6085 		return (0);
6086 
6087 	case MTGRSZ:
6088 		/*
6089 		 * Get record-size to the user
6090 		 */
6091 		mtop->mt_count = un->un_bsize;
6092 		rval = 0;
6093 		break;
6094 
6095 	case MTTELL:
6096 		rval = st_update_block_pos(un, st_cmd, 0);
6097 		mtop->mt_count = un->un_pos.lgclblkno;
6098 		break;
6099 
6100 	case MTSEEK:
6101 		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6102 		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6103 		/*
6104 		 * This bit of magic make mt print the actual position if
6105 		 * the resulting position was not what was asked for.
6106 		 */
6107 		if (rval == ESPIPE) {
6108 			rval = EIO;
6109 			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6110 				mtop->mt_op = MTTELL;
6111 				mtop->mt_count = un->un_pos.lgclblkno;
6112 			}
6113 		}
6114 		break;
6115 
6116 	case MTLOCK:
6117 		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6118 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6119 			    "st_do_mtioctop : EIO : MTLOCK");
6120 			rval = EIO;
6121 		}
6122 		break;
6123 
6124 	case MTUNLOCK:
6125 		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6126 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6127 			    "st_do_mtioctop : EIO : MTUNLOCK");
6128 			rval = EIO;
6129 		}
6130 		break;
6131 
6132 	default:
6133 		rval = ENOTTY;
6134 	}
6135 
6136 	return (rval);
6137 }
6138 
6139 
6140 /*
6141  * Run a command for uscsi ioctl.
6142  */
6143 static int
6144 st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6145 {
6146 	struct uscsi_cmd	*uscmd;
6147 	struct buf	*bp;
6148 	enum uio_seg	uioseg;
6149 	int	offline_state = 0;
6150 	int	err = 0;
6151 	dev_t dev = un->un_dev;
6152 
6153 	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6154 
6155 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6156 	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6157 
6158 	ASSERT(mutex_owned(ST_MUTEX));
6159 
6160 	/*
6161 	 * We really don't know what commands are coming in here and
6162 	 * we don't want to limit the commands coming in.
6163 	 *
6164 	 * If st_tape_init() gets called from st_strategy(), then we
6165 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6166 	 * which it never will, as we set it below.  To prevent
6167 	 * st_tape_init() from getting called, we have to set state to other
6168 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6169 	 * achieves this purpose already.
6170 	 *
6171 	 * We use offline_state to preserve the OFFLINE state, if it exists,
6172 	 * so other entry points to the driver might have the chance to call
6173 	 * st_tape_init().
6174 	 */
6175 	if (un->un_state == ST_STATE_OFFLINE) {
6176 		un->un_laststate = ST_STATE_OFFLINE;
6177 		un->un_state = ST_STATE_INITIALIZING;
6178 		offline_state = 1;
6179 	}
6180 
6181 	mutex_exit(ST_MUTEX);
6182 	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6183 	mutex_enter(ST_MUTEX);
6184 	if (err != 0) {
6185 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6186 		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6187 		goto exit;
6188 	}
6189 
6190 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6191 
6192 	/* check to see if this command requires the drive to be reserved */
6193 	if (uscmd->uscsi_cdb != NULL) {
6194 		err = st_check_cdb_for_need_to_reserve(un,
6195 		    (uchar_t *)uscmd->uscsi_cdb);
6196 		if (err) {
6197 			goto exit_free;
6198 		}
6199 		/*
6200 		 * If this is a space command we need to save the starting
6201 		 * point so we can retry from there if the command fails.
6202 		 */
6203 		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6204 		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6205 			(void) st_update_block_pos(un, st_cmd, 0);
6206 		}
6207 	}
6208 
6209 	/*
6210 	 * Forground should not be doing anything while recovery is active.
6211 	 */
6212 	ASSERT(un->un_recov_buf_busy == 0);
6213 
6214 	/*
6215 	 * Get buffer resources...
6216 	 */
6217 	while (un->un_sbuf_busy)
6218 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6219 	un->un_sbuf_busy = 1;
6220 
6221 #ifdef STDEBUG
6222 	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6223 		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6224 		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6225 		    "uscsi cdb", uscmd->uscsi_cdb);
6226 		if (uscmd->uscsi_buflen) {
6227 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6228 			    "uscsi %s of %ld bytes %s %s space\n",
6229 			    (rw == B_READ) ? rd_str : wr_str,
6230 			    uscmd->uscsi_buflen,
6231 			    (rw == B_READ) ? "to" : "from",
6232 			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6233 		}
6234 	}
6235 #endif /* STDEBUG */
6236 
6237 	/*
6238 	 * Although st_uscsi_cmd() never makes use of these
6239 	 * now, we are just being safe and consistent.
6240 	 */
6241 	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6242 	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6243 
6244 	un->un_srqbufp = uscmd->uscsi_rqbuf;
6245 	bp = un->un_sbufp;
6246 	bzero(bp, sizeof (buf_t));
6247 	if (uscmd->uscsi_cdb != NULL) {
6248 		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6249 	}
6250 	bp->b_back = (struct buf *)uscmd;
6251 
6252 	mutex_exit(ST_MUTEX);
6253 	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6254 	mutex_enter(ST_MUTEX);
6255 
6256 	/*
6257 	 * If scsi reset successful, don't write any filemarks.
6258 	 */
6259 	if ((err == 0) && (uscmd->uscsi_flags &
6260 	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6261 		un->un_fmneeded = 0;
6262 	}
6263 
6264 exit_free:
6265 	/*
6266 	 * Free resources
6267 	 */
6268 	un->un_sbuf_busy = 0;
6269 	un->un_srqbufp = NULL;
6270 
6271 	/*
6272 	 * If was a space command need to update logical block position.
6273 	 * If the command failed such that positioning is invalid, Don't
6274 	 * update the position as the user must do this to validate the
6275 	 * position for data protection.
6276 	 */
6277 	if ((uscmd->uscsi_cdb != NULL) &&
6278 	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6279 	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6280 	    (un->un_pos.pmode != invalid)) {
6281 		un->un_running.pmode = invalid;
6282 		(void) st_update_block_pos(un, st_cmd, 1);
6283 		/*
6284 		 * Set running position to invalid so it updates on the
6285 		 * next command.
6286 		 */
6287 		un->un_running.pmode = invalid;
6288 	}
6289 	cv_signal(&un->un_sbuf_cv);
6290 	mutex_exit(ST_MUTEX);
6291 	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6292 	mutex_enter(ST_MUTEX);
6293 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6294 	    "st_uscsi_cmd returns 0x%x\n", err);
6295 
6296 exit:
6297 	/* don't lose offline state */
6298 	if (offline_state) {
6299 		un->un_state = ST_STATE_OFFLINE;
6300 	}
6301 
6302 	ASSERT(mutex_owned(ST_MUTEX));
6303 	return (err);
6304 }
6305 
6306 static int
6307 st_write_fm(dev_t dev, int wfm)
6308 {
6309 	int i;
6310 	int rval;
6311 
6312 	GET_SOFT_STATE(dev);
6313 
6314 	ST_FUNC(ST_DEVINFO, st_write_fm);
6315 
6316 	ASSERT(mutex_owned(ST_MUTEX));
6317 
6318 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6319 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6320 
6321 	/*
6322 	 * write one filemark at the time after EOT
6323 	 */
6324 	if (un->un_pos.eof >= ST_EOT) {
6325 		for (i = 0; i < wfm; i++) {
6326 			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6327 			if (rval == EACCES) {
6328 				return (rval);
6329 			}
6330 			if (rval != 0) {
6331 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6332 				    "st_write_fm : EIO : write EOT file mark");
6333 				return (EIO);
6334 			}
6335 		}
6336 	} else {
6337 		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6338 		if (rval == EACCES) {
6339 			return (rval);
6340 		}
6341 		if (rval) {
6342 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6343 			    "st_write_fm : EIO : write file mark");
6344 			return (EIO);
6345 		}
6346 	}
6347 
6348 	ASSERT(mutex_owned(ST_MUTEX));
6349 	return (0);
6350 }
6351 
6352 #ifdef STDEBUG
6353 static void
6354 st_start_dump(struct scsi_tape *un, struct buf *bp)
6355 {
6356 	struct scsi_pkt *pkt = BP_PKT(bp);
6357 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6358 
6359 	ST_FUNC(ST_DEVINFO, st_start_dump);
6360 
6361 	if ((st_debug & 0x7) < 6)
6362 		return;
6363 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6364 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6365 	    (void *)bp->b_forw, bp->b_bcount,
6366 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6367 	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6368 	    "st_start: cdb",  (caddr_t)cdbp);
6369 	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6370 	    "st_start: fileno=%d, blk=%d\n",
6371 	    un->un_pos.fileno, un->un_pos.blkno);
6372 }
6373 #endif
6374 
6375 
6376 /*
6377  * Command start && done functions
6378  */
6379 
6380 /*
6381  * st_start()
6382  *
6383  * Called from:
6384  *  st_strategy() to start a command.
6385  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6386  *  st_attach() when resuming from power down state.
6387  *  st_start_restart() to retry transport when device was previously busy.
6388  *  st_done_and_mutex_exit() to start the next command when previous is done.
6389  *
6390  * On entry:
6391  *  scsi_pkt may or may not be allocated.
6392  *
6393  */
6394 static void
6395 st_start(struct scsi_tape *un)
6396 {
6397 	struct buf *bp;
6398 	int status;
6399 	int queued;
6400 
6401 	ST_FUNC(ST_DEVINFO, st_start);
6402 	ASSERT(mutex_owned(ST_MUTEX));
6403 
6404 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6405 	    "st_start(): dev = 0x%lx\n", un->un_dev);
6406 
6407 	if (un->un_recov_buf_busy) {
6408 		/* recovery commands can happen anytime */
6409 		bp = un->un_recov_buf;
6410 		queued = 0;
6411 	} else if (un->un_sbuf_busy) {
6412 		/* sbuf commands should only happen with an empty queue. */
6413 		ASSERT(un->un_quef == NULL);
6414 		ASSERT(un->un_runqf == NULL);
6415 		bp = un->un_sbufp;
6416 		queued = 0;
6417 	} else if (un->un_quef != NULL) {
6418 		if (un->un_persistence && un->un_persist_errors) {
6419 			return;
6420 		}
6421 		bp = un->un_quef;
6422 		queued = 1;
6423 	} else {
6424 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6425 		    "st_start() returning no buf found\n");
6426 		return;
6427 	}
6428 
6429 	ASSERT((bp->b_flags & B_DONE) == 0);
6430 
6431 	/*
6432 	 * Don't send more than un_throttle commands to the HBA
6433 	 */
6434 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6435 		/*
6436 		 * if doing recovery we know there is outstanding commands.
6437 		 */
6438 		if (bp != un->un_recov_buf) {
6439 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6440 			    "st_start returning throttle = %d or ncmds = %d\n",
6441 			    un->un_throttle, un->un_ncmds);
6442 			if (un->un_ncmds == 0) {
6443 				typedef void (*func)();
6444 				func fnc = (func)st_runout;
6445 
6446 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6447 				    "Sending delayed start to st_runout()\n");
6448 				mutex_exit(ST_MUTEX);
6449 				(void) timeout(fnc, un, drv_usectohz(1000000));
6450 				mutex_enter(ST_MUTEX);
6451 			}
6452 			return;
6453 		}
6454 	}
6455 
6456 	/*
6457 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
6458 	 * build the command.
6459 	 */
6460 	if (BP_PKT(bp) == NULL) {
6461 		ASSERT((bp->b_flags & B_DONE) == 0);
6462 		st_make_cmd(un, bp, st_runout);
6463 		ASSERT((bp->b_flags & B_DONE) == 0);
6464 		status = geterror(bp);
6465 
6466 		/*
6467 		 * Some HBA's don't call bioerror() to set an error.
6468 		 * And geterror() returns zero if B_ERROR is not set.
6469 		 * So if we get zero we must check b_error.
6470 		 */
6471 		if (status == 0 && bp->b_error != 0) {
6472 			status = bp->b_error;
6473 			bioerror(bp, status);
6474 		}
6475 
6476 		/*
6477 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
6478 		 * In tape ENOMEM has special meaning so we'll change it.
6479 		 */
6480 		if (status == ENOMEM) {
6481 			status = 0;
6482 			bioerror(bp, status);
6483 		}
6484 
6485 		/*
6486 		 * Did it fail and is it retryable?
6487 		 * If so return and wait for the callback through st_runout.
6488 		 * Also looks like scsi_init_pkt() will setup a callback even
6489 		 * if it isn't retryable.
6490 		 */
6491 		if (BP_PKT(bp) == NULL) {
6492 			if (status == 0) {
6493 				/*
6494 				 * If first attempt save state.
6495 				 */
6496 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
6497 					un->un_laststate = un->un_state;
6498 					un->un_state = ST_STATE_RESOURCE_WAIT;
6499 				}
6500 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6501 				    "temp no resources for pkt\n");
6502 			} else if (status == EINVAL) {
6503 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6504 				    "scsi_init_pkt rejected pkt as too big\n");
6505 				if (un->un_persistence) {
6506 					st_set_pe_flag(un);
6507 				}
6508 			} else {
6509 				/*
6510 				 * Unlikely that it would be retryable then not.
6511 				 */
6512 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6513 					un->un_state = un->un_laststate;
6514 				}
6515 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6516 				    "perm no resources for pkt errno = 0x%x\n",
6517 				    status);
6518 			}
6519 			return;
6520 		}
6521 		/*
6522 		 * Worked this time set the state back.
6523 		 */
6524 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
6525 			un->un_state = un->un_laststate;
6526 		}
6527 	}
6528 
6529 	if (queued) {
6530 		/*
6531 		 * move from waitq to runq
6532 		 */
6533 		(void) st_remove_from_queue(&un->un_quef, &un->un_quel, bp);
6534 		st_add_to_queue(&un->un_runqf, &un->un_runql, un->un_runql, bp);
6535 	}
6536 
6537 
6538 #ifdef STDEBUG
6539 	st_start_dump(un, bp);
6540 #endif
6541 
6542 	/* could not get here if throttle was zero */
6543 	un->un_last_throttle = un->un_throttle;
6544 	un->un_throttle = 0;	/* so nothing else will come in here */
6545 	un->un_ncmds++;
6546 
6547 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6548 
6549 	status = st_transport(un, BP_PKT(bp));
6550 
6551 	if (un->un_last_throttle) {
6552 		un->un_throttle = un->un_last_throttle;
6553 	}
6554 
6555 	if (status != TRAN_ACCEPT) {
6556 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6557 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
6558 		    "Unhappy transport packet status 0x%x\n", status);
6559 
6560 		if (status == TRAN_BUSY) {
6561 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
6562 
6563 			/*
6564 			 * If command recovery is enabled and this isn't
6565 			 * a recovery command try command recovery.
6566 			 */
6567 			if (pkti->privatelen == sizeof (recov_info) &&
6568 			    bp != un->un_recov_buf) {
6569 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
6570 				    "Command Recovery called on busy send\n");
6571 				if (st_command_recovery(un, BP_PKT(bp),
6572 				    ATTEMPT_RETRY) == JUST_RETURN) {
6573 					return;
6574 				}
6575 			} else {
6576 				mutex_exit(ST_MUTEX);
6577 				if (st_handle_start_busy(un, bp,
6578 				    ST_TRAN_BUSY_TIMEOUT, queued) == 0) {
6579 					mutex_enter(ST_MUTEX);
6580 					return;
6581 				}
6582 				/*
6583 				 * if too many retries, fail the transport
6584 				 */
6585 				mutex_enter(ST_MUTEX);
6586 			}
6587 		}
6588 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6589 		    "transport rejected %d\n", status);
6590 		bp->b_resid = bp->b_bcount;
6591 
6592 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6593 		ST_DO_ERRSTATS(un, st_transerrs);
6594 		if ((bp == un->un_recov_buf) && (status == TRAN_BUSY)) {
6595 			st_bioerror(bp, EBUSY);
6596 		} else {
6597 			st_bioerror(bp, EIO);
6598 			st_set_pe_flag(un);
6599 		}
6600 		st_done_and_mutex_exit(un, bp);
6601 		mutex_enter(ST_MUTEX);
6602 	}
6603 
6604 	ASSERT(mutex_owned(ST_MUTEX));
6605 }
6606 
6607 /*
6608  * if the transport is busy, then put this bp back on the waitq
6609  */
6610 static int
6611 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6612     clock_t timeout_interval, int queued)
6613 {
6614 
6615 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
6616 
6617 	ST_FUNC(ST_DEVINFO, st_handle_start_busy);
6618 
6619 	mutex_enter(ST_MUTEX);
6620 
6621 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6622 	    "st_handle_start_busy()\n");
6623 
6624 	/*
6625 	 * Check to see if we hit the retry timeout and one last check for
6626 	 * making sure this is the last on the runq, if it is not, we have
6627 	 * to fail
6628 	 */
6629 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
6630 	    ((queued) && (un->un_runql != bp))) {
6631 		mutex_exit(ST_MUTEX);
6632 		return (-1);
6633 	}
6634 
6635 	if (queued) {
6636 		/* put the bp back on the waitq */
6637 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
6638 	}
6639 
6640 	/*
6641 	 * Decrement un_ncmds so that this
6642 	 * gets thru' st_start() again.
6643 	 */
6644 	un->un_ncmds--;
6645 
6646 	if (queued) {
6647 		/*
6648 		 * since this is an error case, we won't have to do this list
6649 		 * walking much. We've already made sure this bp was the
6650 		 * last on the runq
6651 		 */
6652 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6653 
6654 		/*
6655 		 * send a marker pkt, if appropriate
6656 		 */
6657 		st_hba_unflush(un);
6658 
6659 	}
6660 	/*
6661 	 * all queues are aligned, we are just waiting to
6662 	 * transport, don't alloc any more buf p's, when
6663 	 * st_start is reentered.
6664 	 */
6665 	(void) timeout(st_start_restart, un, timeout_interval);
6666 
6667 	mutex_exit(ST_MUTEX);
6668 	return (0);
6669 }
6670 
6671 
6672 /*
6673  * st_runout a callback that is called what a resource allocatation failed
6674  */
6675 static int
6676 st_runout(caddr_t arg)
6677 {
6678 	struct scsi_tape *un = (struct scsi_tape *)arg;
6679 	struct buf *bp;
6680 	int queued;
6681 
6682 	ASSERT(un != NULL);
6683 
6684 	ST_FUNC(ST_DEVINFO, st_runout);
6685 
6686 	mutex_enter(ST_MUTEX);
6687 
6688 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6689 
6690 	if (un->un_recov_buf_busy != 0) {
6691 		bp = un->un_recov_buf;
6692 		queued = 0;
6693 	} else if (un->un_sbuf_busy != 0) {
6694 		/* sbuf commands should only happen with an empty queue. */
6695 		ASSERT(un->un_quef == NULL);
6696 		ASSERT(un->un_runqf == NULL);
6697 		bp = un->un_sbufp;
6698 		queued = 0;
6699 	} else if (un->un_quef != NULL) {
6700 		bp = un->un_quef;
6701 		if (un->un_persistence && un->un_persist_errors) {
6702 			mutex_exit(ST_MUTEX);
6703 			bp->b_resid = bp->b_bcount;
6704 			biodone(bp);
6705 			return (1);
6706 		}
6707 		queued = 1;
6708 	} else {
6709 		ASSERT(1 == 0);
6710 		mutex_exit(ST_MUTEX);
6711 		return (1);
6712 	}
6713 
6714 	/*
6715 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6716 	 */
6717 	if ((bp != NULL) && (geterror(bp) != 0)) {
6718 
6719 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6720 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6721 		    bp->b_flags, geterror(bp));
6722 		ASSERT((bp->b_flags & B_DONE) == 0);
6723 
6724 		if (queued) {
6725 			(void) st_remove_from_queue(&un->un_quef, &un->un_quel,
6726 			    bp);
6727 		}
6728 		mutex_exit(ST_MUTEX);
6729 
6730 		ASSERT((bp->b_flags & B_DONE) == 0);
6731 
6732 		/*
6733 		 * Set resid, Error already set, then unblock calling thread.
6734 		 */
6735 		bp->b_resid = bp->b_bcount;
6736 		biodone(bp);
6737 	} else {
6738 		/*
6739 		 * Try Again
6740 		 */
6741 		st_start(un);
6742 		mutex_exit(ST_MUTEX);
6743 	}
6744 
6745 	/*
6746 	 * Comments courtesy of sd.c
6747 	 * The scsi_init_pkt routine allows for the callback function to
6748 	 * return a 0 indicating the callback should be rescheduled or a 1
6749 	 * indicating not to reschedule. This routine always returns 1
6750 	 * because the driver always provides a callback function to
6751 	 * scsi_init_pkt. This results in a callback always being scheduled
6752 	 * (via the scsi_init_pkt callback implementation) if a resource
6753 	 * failure occurs.
6754 	 */
6755 
6756 	return (1);
6757 }
6758 
6759 /*
6760  * st_done_and_mutex_exit()
6761  *	- remove bp from runq
6762  *	- start up the next request
6763  *	- if this was an asynch bp, clean up
6764  *	- exit with released mutex
6765  */
6766 static void
6767 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6768 {
6769 	int pe_flagged = 0;
6770 	struct scsi_pkt *pkt = BP_PKT(bp);
6771 	pkt_info *pktinfo = pkt->pkt_private;
6772 
6773 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6774 #if !defined(lint)
6775 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6776 #endif
6777 
6778 	ST_FUNC(ST_DEVINFO, st_done_and_mutex_exit);
6779 
6780 	ASSERT(mutex_owned(ST_MUTEX));
6781 
6782 	(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
6783 
6784 	un->un_ncmds--;
6785 	cv_signal(&un->un_queue_cv);
6786 
6787 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6788 	    "st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags="
6789 	    "0x%x\n", pkt->pkt_cdbp[0], bp->b_bcount,
6790 	    bp->b_resid, bp->b_flags);
6791 
6792 
6793 	/*
6794 	 * update kstats with transfer count info
6795 	 */
6796 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6797 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6798 		if (bp->b_flags & B_READ) {
6799 			IOSP->reads++;
6800 			IOSP->nread += n_done;
6801 		} else {
6802 			IOSP->writes++;
6803 			IOSP->nwritten += n_done;
6804 		}
6805 	}
6806 
6807 	/*
6808 	 * Start the next one before releasing resources on this one, if
6809 	 * there is something on the queue and persistent errors has not been
6810 	 * flagged
6811 	 */
6812 
6813 	if ((pe_flagged = (un->un_persistence && un->un_persist_errors)) != 0) {
6814 		un->un_last_resid = bp->b_resid;
6815 		un->un_last_count = bp->b_bcount;
6816 	}
6817 
6818 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6819 		cv_broadcast(&un->un_tape_busy_cv);
6820 	} else if (un->un_quef && un->un_throttle && !pe_flagged &&
6821 	    (bp != un->un_recov_buf)) {
6822 		st_start(un);
6823 	}
6824 
6825 	un->un_retry_ct = max(pktinfo->pkt_retry_cnt, pktinfo->str_retry_cnt);
6826 
6827 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6828 		/*
6829 		 * Since we marked this ourselves as ASYNC,
6830 		 * there isn't anybody around waiting for
6831 		 * completion any more.
6832 		 */
6833 		uchar_t *cmd = pkt->pkt_cdbp;
6834 		if (*cmd == SCMD_READ || *cmd == SCMD_WRITE) {
6835 			bp->b_un.b_addr = (caddr_t)0;
6836 		}
6837 		ST_DEBUG(ST_DEVINFO, st_label, CE_NOTE,
6838 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6839 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
6840 		    "CDB sent with B_ASYNC",  (caddr_t)cmd);
6841 		if (pkt) {
6842 			scsi_destroy_pkt(pkt);
6843 		}
6844 		un->un_sbuf_busy = 0;
6845 		cv_signal(&un->un_sbuf_cv);
6846 		mutex_exit(ST_MUTEX);
6847 		return;
6848 	}
6849 
6850 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6851 		/*
6852 		 * Copy status from scsi_pkt to uscsi_cmd
6853 		 * since st_uscsi_cmd needs it
6854 		 */
6855 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6856 	}
6857 
6858 
6859 #ifdef STDEBUG
6860 	if (((st_debug & 0x7) >= 4) &&
6861 	    (((un->un_pos.blkno % 100) == 0) ||
6862 	    (un->un_persistence && un->un_persist_errors))) {
6863 
6864 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6865 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6866 		    "un_errno = %d, un_pe = %d\n",
6867 		    un->un_ncmds, un->un_throttle, un->un_errno,
6868 		    un->un_persist_errors);
6869 	}
6870 
6871 #endif
6872 
6873 	mutex_exit(ST_MUTEX);
6874 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6875 	    "st_done_and_mutex_exit: freeing pkt\n");
6876 
6877 	if (pkt) {
6878 		scsi_destroy_pkt(pkt);
6879 	}
6880 
6881 	biodone(bp);
6882 
6883 	/*
6884 	 * now that we biodoned that command, if persistent errors have been
6885 	 * flagged, flush the waitq
6886 	 */
6887 	if (pe_flagged)
6888 		st_flush(un);
6889 }
6890 
6891 
6892 /*
6893  * Tape error, flush tape driver queue.
6894  */
6895 static void
6896 st_flush(struct scsi_tape *un)
6897 {
6898 	struct buf *bp;
6899 
6900 	ST_FUNC(ST_DEVINFO, st_flush);
6901 
6902 	mutex_enter(ST_MUTEX);
6903 
6904 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6905 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6906 	    un->un_ncmds, (void *)un->un_quef);
6907 
6908 	/*
6909 	 * if we still have commands outstanding, wait for them to come in
6910 	 * before flushing the queue, and make sure there is a queue
6911 	 */
6912 	if (un->un_ncmds || !un->un_quef)
6913 		goto exit;
6914 
6915 	/*
6916 	 * we have no more commands outstanding, so let's deal with special
6917 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6918 	 * is 0, then we know there was no error and we return a 0 read or
6919 	 * write before showing errors
6920 	 */
6921 
6922 	/* Flush the wait queue. */
6923 	while ((bp = un->un_quef) != NULL) {
6924 		un->un_quef = bp->b_actf;
6925 
6926 		bp->b_resid = bp->b_bcount;
6927 
6928 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6929 		    "st_flush() : blkno=%d, err=%d, b_bcount=%ld\n",
6930 		    un->un_pos.blkno, un->un_errno, bp->b_bcount);
6931 
6932 		st_set_pe_errno(un);
6933 
6934 		bioerror(bp, un->un_errno);
6935 
6936 		mutex_exit(ST_MUTEX);
6937 		/* it should have one, but check anyway */
6938 		if (BP_PKT(bp)) {
6939 			scsi_destroy_pkt(BP_PKT(bp));
6940 		}
6941 		biodone(bp);
6942 		mutex_enter(ST_MUTEX);
6943 	}
6944 
6945 	/*
6946 	 * It's not a bad practice to reset the
6947 	 * waitq tail pointer to NULL.
6948 	 */
6949 	un->un_quel = NULL;
6950 
6951 exit:
6952 	/* we mucked with the queue, so let others know about it */
6953 	cv_signal(&un->un_queue_cv);
6954 	mutex_exit(ST_MUTEX);
6955 }
6956 
6957 
6958 /*
6959  * Utility functions
6960  */
6961 static int
6962 st_determine_generic(struct scsi_tape *un)
6963 {
6964 	int bsize;
6965 	static char *cart = "0.25 inch cartridge";
6966 	char *sizestr;
6967 
6968 	ST_FUNC(ST_DEVINFO, st_determine_generic);
6969 
6970 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6971 	    "st_determine_generic(un = 0x%p)\n", (void*)un);
6972 
6973 	ASSERT(mutex_owned(ST_MUTEX));
6974 
6975 	if (st_modesense(un)) {
6976 		return (-1);
6977 	}
6978 
6979 	bsize = (un->un_mspl->high_bl << 16)	|
6980 	    (un->un_mspl->mid_bl << 8)	|
6981 	    (un->un_mspl->low_bl);
6982 
6983 	if (bsize == 0) {
6984 		un->un_dp->options |= ST_VARIABLE;
6985 		un->un_dp->bsize = 0;
6986 		un->un_bsize = 0;
6987 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6988 		/*
6989 		 * record size of this device too big.
6990 		 * try and convert it to variable record length.
6991 		 *
6992 		 */
6993 		un->un_dp->options |= ST_VARIABLE;
6994 		if (st_change_block_size(un, 0) != 0) {
6995 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6996 			    "Fixed Record Size %d is too large\n", bsize);
6997 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6998 			    "Cannot switch to variable record size\n");
6999 			un->un_dp->options &= ~ST_VARIABLE;
7000 			return (-1);
7001 		}
7002 	} else if (st_change_block_size(un, 0) == 0) {
7003 		/*
7004 		 * If the drive was set to a non zero block size,
7005 		 * See if it can be set to a zero block size.
7006 		 * If it works, ST_VARIABLE so user can set it as they want.
7007 		 */
7008 		un->un_dp->options |= ST_VARIABLE;
7009 		un->un_dp->bsize = 0;
7010 		un->un_bsize = 0;
7011 	} else {
7012 		un->un_dp->bsize = bsize;
7013 		un->un_bsize = bsize;
7014 	}
7015 
7016 
7017 	switch (un->un_mspl->density) {
7018 	default:
7019 	case 0x0:
7020 		/*
7021 		 * default density, cannot determine any other
7022 		 * information.
7023 		 */
7024 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
7025 		un->un_dp->type = ST_TYPE_DEFAULT;
7026 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
7027 		break;
7028 	case 0x1:
7029 	case 0x2:
7030 	case 0x3:
7031 	case 0x6:
7032 		/*
7033 		 * 1/2" reel
7034 		 */
7035 		sizestr = "0.50 inch reel";
7036 		un->un_dp->type = ST_TYPE_REEL;
7037 		un->un_dp->options |= ST_REEL;
7038 		un->un_dp->densities[0] = 0x1;
7039 		un->un_dp->densities[1] = 0x2;
7040 		un->un_dp->densities[2] = 0x6;
7041 		un->un_dp->densities[3] = 0x3;
7042 		break;
7043 	case 0x4:
7044 	case 0x5:
7045 	case 0x7:
7046 	case 0x0b:
7047 
7048 		/*
7049 		 * Quarter inch.
7050 		 */
7051 		sizestr = cart;
7052 		un->un_dp->type = ST_TYPE_DEFAULT;
7053 		un->un_dp->options |= ST_QIC;
7054 
7055 		un->un_dp->densities[1] = 0x4;
7056 		un->un_dp->densities[2] = 0x5;
7057 		un->un_dp->densities[3] = 0x7;
7058 		un->un_dp->densities[0] = 0x0b;
7059 		break;
7060 
7061 	case 0x0f:
7062 	case 0x10:
7063 	case 0x11:
7064 	case 0x12:
7065 		/*
7066 		 * QIC-120, QIC-150, QIC-320, QIC-600
7067 		 */
7068 		sizestr = cart;
7069 		un->un_dp->type = ST_TYPE_DEFAULT;
7070 		un->un_dp->options |= ST_QIC;
7071 		un->un_dp->densities[0] = 0x0f;
7072 		un->un_dp->densities[1] = 0x10;
7073 		un->un_dp->densities[2] = 0x11;
7074 		un->un_dp->densities[3] = 0x12;
7075 		break;
7076 
7077 	case 0x09:
7078 	case 0x0a:
7079 	case 0x0c:
7080 	case 0x0d:
7081 		/*
7082 		 * 1/2" cartridge tapes. Include HI-TC.
7083 		 */
7084 		sizestr = cart;
7085 		sizestr[2] = '5';
7086 		sizestr[3] = '0';
7087 		un->un_dp->type = ST_TYPE_HIC;
7088 		un->un_dp->densities[0] = 0x09;
7089 		un->un_dp->densities[1] = 0x0a;
7090 		un->un_dp->densities[2] = 0x0c;
7091 		un->un_dp->densities[3] = 0x0d;
7092 		break;
7093 
7094 	case 0x13:
7095 			/* DDS-2/DDS-3 scsi spec densities */
7096 	case 0x24:
7097 	case 0x25:
7098 	case 0x26:
7099 		sizestr = "DAT Data Storage (DDS)";
7100 		un->un_dp->type = ST_TYPE_DAT;
7101 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7102 		break;
7103 
7104 	case 0x14:
7105 		/*
7106 		 * Helical Scan (Exabyte) devices
7107 		 */
7108 		sizestr = "8mm helical scan cartridge";
7109 		un->un_dp->type = ST_TYPE_EXABYTE;
7110 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
7111 		break;
7112 	}
7113 
7114 	/*
7115 	 * Assume LONG ERASE, BSF and BSR
7116 	 */
7117 
7118 	un->un_dp->options |=
7119 	    (ST_LONG_ERASE | ST_UNLOADABLE | ST_BSF | ST_BSR | ST_KNOWS_EOD);
7120 
7121 	/*
7122 	 * Only if mode sense data says no buffered write, set NOBUF
7123 	 */
7124 	if (un->un_mspl->bufm == 0)
7125 		un->un_dp->options |= ST_NOBUF;
7126 
7127 	/*
7128 	 * set up large read and write retry counts
7129 	 */
7130 
7131 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
7132 
7133 	/*
7134 	 * If this is a 0.50 inch reel tape, and
7135 	 * it is *not* variable mode, try and
7136 	 * set it to variable record length
7137 	 * mode.
7138 	 */
7139 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
7140 	    (un->un_dp->options & ST_VARIABLE)) {
7141 		if (st_change_block_size(un, 0) == 0) {
7142 			un->un_dp->bsize = 0;
7143 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
7144 			    un->un_mspl->low_bl = 0;
7145 		}
7146 	}
7147 
7148 	/*
7149 	 * Write to console about type of device found
7150 	 */
7151 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
7152 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
7153 	    sizestr);
7154 	if (un->un_dp->options & ST_VARIABLE) {
7155 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7156 		    "!Variable record length I/O\n");
7157 	} else {
7158 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7159 		    "!Fixed record length (%d byte blocks) I/O\n",
7160 		    un->un_dp->bsize);
7161 	}
7162 	ASSERT(mutex_owned(ST_MUTEX));
7163 	return (0);
7164 }
7165 
7166 static int
7167 st_determine_density(struct scsi_tape *un, int rw)
7168 {
7169 	int rval = 0;
7170 
7171 	ST_FUNC(ST_DEVINFO, st_determine_density);
7172 
7173 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7174 	    "st_determine_density(un = 0x%p, rw = %s)\n",
7175 	    (void*)un, (rw == B_WRITE ? wr_str: rd_str));
7176 
7177 	ASSERT(mutex_owned(ST_MUTEX));
7178 
7179 	/*
7180 	 * If we're past BOT, density is determined already.
7181 	 */
7182 	if (un->un_pos.pmode == logical) {
7183 		if (un->un_pos.lgclblkno != 0) {
7184 			goto exit;
7185 		}
7186 	} else if (un->un_pos.pmode == legacy) {
7187 		if ((un->un_pos.fileno != 0) || (un->un_pos.blkno != 0)) {
7188 			/*
7189 			 * XXX: put in a bitch message about attempting to
7190 			 * XXX: change density past BOT.
7191 			 */
7192 			goto exit;
7193 		}
7194 	} else {
7195 		goto exit;
7196 	}
7197 	if ((un->un_pos.pmode == logical) &&
7198 	    (un->un_pos.lgclblkno != 0)) {
7199 		goto exit;
7200 	}
7201 
7202 
7203 	/*
7204 	 * If we're going to be writing, we set the density
7205 	 */
7206 	if (rw == 0 || rw == B_WRITE) {
7207 		/* un_curdens is used as an index into densities table */
7208 		un->un_curdens = MT_DENSITY(un->un_dev);
7209 		if (st_set_density(un)) {
7210 			rval = -1;
7211 		}
7212 		goto exit;
7213 	}
7214 
7215 	/*
7216 	 * If density is known already,
7217 	 * we don't have to get it again.(?)
7218 	 */
7219 	if (!un->un_density_known) {
7220 		if (st_get_density(un)) {
7221 			rval = -1;
7222 		}
7223 	}
7224 
7225 exit:
7226 	ASSERT(mutex_owned(ST_MUTEX));
7227 	return (rval);
7228 }
7229 
7230 
7231 /*
7232  * Try to determine density. We do this by attempting to read the
7233  * first record off the tape, cycling through the available density
7234  * codes as we go.
7235  */
7236 
7237 static int
7238 st_get_density(struct scsi_tape *un)
7239 {
7240 	int succes = 0, rval = -1, i;
7241 	uint_t size;
7242 	uchar_t dens, olddens;
7243 
7244 	ST_FUNC(ST_DEVINFO, st_get_density);
7245 
7246 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7247 	    "st_get_density(un = 0x%p)\n", (void*)un);
7248 
7249 	ASSERT(mutex_owned(ST_MUTEX));
7250 
7251 	/*
7252 	 * If Auto Density override is enabled The drive has
7253 	 * only one density and there is no point in attempting
7254 	 * find the correct one.
7255 	 *
7256 	 * Since most modern drives auto detect the density
7257 	 * and format of the recorded media before they come
7258 	 * ready. What this function does is a legacy behavior
7259 	 * and modern drives not only don't need it, The backup
7260 	 * utilities that do positioning via uscsi find the un-
7261 	 * expected rewinds problematic.
7262 	 *
7263 	 * The drives that need this are old reel to reel devices.
7264 	 * I took a swag and said they must be scsi-1 or older.
7265 	 * I don't beleave there will any of the newer devices
7266 	 * that need this. There will be some scsi-1 devices that
7267 	 * don't need this but I don't think they will be using the
7268 	 * BIG aftermarket backup and restore utilitys.
7269 	 */
7270 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
7271 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
7272 		un->un_density_known = 1;
7273 		rval = 0;
7274 		goto exit;
7275 	}
7276 
7277 	/*
7278 	 * This will only work on variable record length tapes
7279 	 * if and only if all variable record length tapes autodensity
7280 	 * select.
7281 	 */
7282 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
7283 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
7284 
7285 	/*
7286 	 * Start at the specified density
7287 	 */
7288 
7289 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
7290 
7291 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
7292 	    (un->un_curdens = 0) : (un->un_curdens += 1))) {
7293 		/*
7294 		 * If we've done this density before,
7295 		 * don't bother to do it again.
7296 		 */
7297 		dens = un->un_dp->densities[un->un_curdens];
7298 		if (i > 0 && dens == olddens)
7299 			continue;
7300 		olddens = dens;
7301 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7302 		    "trying density 0x%x\n", dens);
7303 		if (st_set_density(un)) {
7304 			continue;
7305 		}
7306 
7307 		/*
7308 		 * XXX - the creates lots of headaches and slowdowns - must
7309 		 * fix.
7310 		 */
7311 		succes = (st_cmd(un, SCMD_READ, (int)size, SYNC_CMD) == 0);
7312 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
7313 			break;
7314 		}
7315 		if (succes) {
7316 			st_init(un);
7317 			rval = 0;
7318 			un->un_density_known = 1;
7319 			break;
7320 		}
7321 	}
7322 	kmem_free(un->un_tmpbuf, size);
7323 	un->un_tmpbuf = 0;
7324 
7325 exit:
7326 	ASSERT(mutex_owned(ST_MUTEX));
7327 	return (rval);
7328 }
7329 
7330 static int
7331 st_set_density(struct scsi_tape *un)
7332 {
7333 	int rval = 0;
7334 
7335 	ST_FUNC(ST_DEVINFO, st_set_density);
7336 
7337 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7338 	    "st_set_density(un = 0x%p): density = 0x%x\n", (void*)un,
7339 	    un->un_dp->densities[un->un_curdens]);
7340 
7341 	ASSERT(mutex_owned(ST_MUTEX));
7342 
7343 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7344 
7345 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
7346 		/*
7347 		 * If auto density override is not set, Use mode select
7348 		 * to set density and compression.
7349 		 */
7350 		if (st_modeselect(un)) {
7351 			rval = -1;
7352 		}
7353 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
7354 		/*
7355 		 * If auto density and mode select compression are set,
7356 		 * This is a drive with one density code but compression
7357 		 * can be enabled or disabled.
7358 		 * Set compression but no need to set density.
7359 		 */
7360 		rval = st_set_compression(un);
7361 		if ((rval != 0) && (rval != EALREADY)) {
7362 			rval = -1;
7363 		} else {
7364 			rval = 0;
7365 		}
7366 	}
7367 
7368 	/* If sucessful set density and/or compression, mark density known */
7369 	if (rval == 0) {
7370 		un->un_density_known = 1;
7371 	}
7372 
7373 	ASSERT(mutex_owned(ST_MUTEX));
7374 	return (rval);
7375 }
7376 
7377 static int
7378 st_loadtape(struct scsi_tape *un)
7379 {
7380 	int rval;
7381 
7382 	ST_FUNC(ST_DEVINFO, st_loadtape);
7383 
7384 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7385 	    "st_loadtape(un = 0x%p)\n", (void*) un);
7386 
7387 	ASSERT(mutex_owned(ST_MUTEX));
7388 
7389 	rval = st_update_block_pos(un, st_cmd, 0);
7390 	if (rval == EACCES) {
7391 		return (rval);
7392 	}
7393 
7394 	/*
7395 	 * 'LOAD' the tape to BOT by rewinding
7396 	 */
7397 	rval = st_cmd(un, SCMD_REWIND, 1, SYNC_CMD);
7398 	if (rval == 0) {
7399 		st_init(un);
7400 		un->un_density_known = 0;
7401 	}
7402 
7403 	ASSERT(mutex_owned(ST_MUTEX));
7404 	return (rval);
7405 }
7406 
7407 
7408 /*
7409  * Note: QIC devices aren't so smart.  If you try to append
7410  * after EOM, the write can fail because the device doesn't know
7411  * it's at EOM.	 In that case, issue a read.  The read should fail
7412  * because there's no data, but the device knows it's at EOM,
7413  * so a subsequent write should succeed.  To further confuse matters,
7414  * the target returns the same error if the tape is positioned
7415  * such that a write would overwrite existing data.  That's why
7416  * we have to do the append test.  A read in the middle of
7417  * recorded data would succeed, thus indicating we're attempting
7418  * something illegal.
7419  */
7420 
7421 
7422 static void
7423 st_test_append(struct buf *bp)
7424 {
7425 	dev_t dev = bp->b_edev;
7426 	struct scsi_tape *un;
7427 	uchar_t status;
7428 	unsigned bcount;
7429 
7430 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
7431 
7432 	ST_FUNC(ST_DEVINFO, st_test_append);
7433 
7434 	ASSERT(mutex_owned(ST_MUTEX));
7435 
7436 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7437 	    "st_test_append(): fileno %d\n", un->un_pos.fileno);
7438 
7439 	un->un_laststate = un->un_state;
7440 	un->un_state = ST_STATE_APPEND_TESTING;
7441 	un->un_test_append = 0;
7442 
7443 	/*
7444 	 * first, map in the buffer, because we're doing a double write --
7445 	 * first into the kernel, then onto the tape.
7446 	 */
7447 	bp_mapin(bp);
7448 
7449 	/*
7450 	 * get a copy of the data....
7451 	 */
7452 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
7453 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7454 
7455 	/*
7456 	 * attempt the write..
7457 	 */
7458 
7459 	if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
7460 success:
7461 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7462 		    "append write succeeded\n");
7463 		bp->b_resid = un->un_sbufp->b_resid;
7464 		mutex_exit(ST_MUTEX);
7465 		bcount = (unsigned)bp->b_bcount;
7466 		biodone(bp);
7467 		mutex_enter(ST_MUTEX);
7468 		un->un_laststate = un->un_state;
7469 		un->un_state = ST_STATE_OPEN;
7470 		kmem_free(un->un_tmpbuf, bcount);
7471 		un->un_tmpbuf = NULL;
7472 		return;
7473 	}
7474 
7475 	/*
7476 	 * The append failed. Do a short read. If that fails,  we are at EOM
7477 	 * so we can retry the write command. If that succeeds, than we're
7478 	 * all screwed up (the controller reported a real error).
7479 	 *
7480 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
7481 	 * XXX: block size?
7482 	 *
7483 	 */
7484 	status = un->un_status;
7485 	un->un_status = 0;
7486 	(void) st_cmd(un, SCMD_READ, SECSIZE, SYNC_CMD);
7487 	if (un->un_status == KEY_BLANK_CHECK) {
7488 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7489 		    "append at EOM\n");
7490 		/*
7491 		 * Okay- the read failed. We should actually have confused
7492 		 * the controller enough to allow writing. In any case, the
7493 		 * i/o is on its own from here on out.
7494 		 */
7495 		un->un_laststate = un->un_state;
7496 		un->un_state = ST_STATE_OPEN;
7497 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
7498 		if (st_cmd(un, (int)SCMD_WRITE, (int)bp->b_bcount,
7499 		    SYNC_CMD) == 0) {
7500 			goto success;
7501 		}
7502 	}
7503 
7504 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7505 	    "append write failed- not at EOM\n");
7506 	bp->b_resid = bp->b_bcount;
7507 	st_bioerror(bp, EIO);
7508 
7509 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
7510 	    "st_test_append : EIO : append write failed - not at EOM");
7511 
7512 	/*
7513 	 * backspace one record to get back to where we were
7514 	 */
7515 	if (st_cmd(un, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
7516 		un->un_pos.pmode = invalid;
7517 	}
7518 
7519 	un->un_err_resid = bp->b_resid;
7520 	un->un_status = status;
7521 
7522 	/*
7523 	 * Note: biodone will do a bp_mapout()
7524 	 */
7525 	mutex_exit(ST_MUTEX);
7526 	bcount = (unsigned)bp->b_bcount;
7527 	biodone(bp);
7528 	mutex_enter(ST_MUTEX);
7529 	un->un_laststate = un->un_state;
7530 	un->un_state = ST_STATE_OPEN_PENDING_IO;
7531 	kmem_free(un->un_tmpbuf, bcount);
7532 	un->un_tmpbuf = NULL;
7533 }
7534 
7535 /*
7536  * Special command handler
7537  */
7538 
7539 /*
7540  * common st_cmd code. The fourth parameter states
7541  * whether the caller wishes to await the results
7542  * Note the release of the mutex during most of the function
7543  */
7544 static int
7545 st_cmd(struct scsi_tape *un, int com, int64_t count, int wait)
7546 {
7547 	struct buf *bp;
7548 	int err;
7549 	uint_t last_err_resid;
7550 
7551 	ST_FUNC(ST_DEVINFO, st_cmd);
7552 
7553 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7554 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %"PRIx64", wait = %d)\n",
7555 	    un->un_dev, com, count, wait);
7556 
7557 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7558 	ASSERT(mutex_owned(ST_MUTEX));
7559 
7560 #ifdef STDEBUG
7561 	if ((st_debug & 0x7)) {
7562 		st_debug_cmds(un, com, count, wait);
7563 	}
7564 #endif
7565 
7566 	st_wait_for_io(un);
7567 
7568 	/* check to see if this command requires the drive to be reserved */
7569 	err = st_check_cmd_for_need_to_reserve(un, com, count);
7570 
7571 	if (err) {
7572 		return (err);
7573 	}
7574 
7575 	/*
7576 	 * A space command is not recoverable if we don't know were we
7577 	 * were when it was issued.
7578 	 */
7579 	if ((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) {
7580 		(void) st_update_block_pos(un, st_cmd, 0);
7581 	}
7582 
7583 	/*
7584 	 * Forground should not be doing anything while recovery is active.
7585 	 */
7586 	ASSERT(un->un_recov_buf_busy == 0);
7587 
7588 	while (un->un_sbuf_busy)
7589 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7590 	un->un_sbuf_busy = 1;
7591 
7592 	bp = un->un_sbufp;
7593 	bzero(bp, sizeof (buf_t));
7594 
7595 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7596 
7597 	err = st_setup_cmd(un, bp, com, count);
7598 
7599 	un->un_sbuf_busy = 0;
7600 
7601 	/*
7602 	 * If was a space command need to update logical block position.
7603 	 * Only do this if the command was sucessful or it will mask the fact
7604 	 * that the space command failed by promoting the pmode to logical.
7605 	 */
7606 	if (((com == SCMD_SPACE) || (com == SCMD_SPACE_G4)) &&
7607 	    (un->un_pos.pmode != invalid)) {
7608 		un->un_running.pmode = invalid;
7609 		last_err_resid = un->un_err_resid;
7610 		(void) st_update_block_pos(un, st_cmd, 1);
7611 		/*
7612 		 * Set running position to invalid so it updates on the
7613 		 * next command.
7614 		 */
7615 		un->un_running.pmode = invalid;
7616 		un->un_err_resid = last_err_resid;
7617 	}
7618 
7619 	cv_signal(&un->un_sbuf_cv);
7620 
7621 	return (err);
7622 }
7623 
7624 static int
7625 st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com, int64_t count)
7626 {
7627 	int err;
7628 	dev_t dev = un->un_dev;
7629 
7630 	ST_FUNC(ST_DEVINFO, st_setup_cmd);
7631 	/*
7632 	 * Set count to the actual size of the data tranfer.
7633 	 * For commands with no data transfer, set bp->b_bcount
7634 	 * to the value to be used when constructing the
7635 	 * cdb in st_make_cmd().
7636 	 */
7637 	switch (com) {
7638 	case SCMD_READ:
7639 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7640 		    "special read %"PRId64"\n", count);
7641 		bp->b_flags |= B_READ;
7642 		bp->b_un.b_addr = un->un_tmpbuf;
7643 		break;
7644 
7645 	case SCMD_WRITE:
7646 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7647 		    "special write %"PRId64"\n", count);
7648 		bp->b_un.b_addr = un->un_tmpbuf;
7649 		break;
7650 
7651 	case SCMD_WRITE_FILE_MARK:
7652 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7653 		    "write %"PRId64" file marks\n", count);
7654 		bp->b_bcount = count;
7655 		count = 0;
7656 		break;
7657 
7658 	case SCMD_REWIND:
7659 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7660 		bp->b_bcount = count;
7661 		count = 0;
7662 		break;
7663 
7664 	case SCMD_SPACE:
7665 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7666 		/*
7667 		 * If the user could have entered a number that will
7668 		 * not fit in the 12 bit count field of space(8),
7669 		 * use space(16).
7670 		 */
7671 		if (((int64_t)SPACE_CNT(count) > 0x7fffff) ||
7672 		    ((int64_t)SPACE_CNT(count) < -(0x7fffff))) {
7673 			com = SCMD_SPACE_G4;
7674 		}
7675 		bp->b_bcount = count;
7676 		count = 0;
7677 		break;
7678 
7679 	case SCMD_RESERVE:
7680 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7681 		bp->b_bcount = 0;
7682 		count = 0;
7683 		break;
7684 
7685 	case SCMD_RELEASE:
7686 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7687 		bp->b_bcount = 0;
7688 		count = 0;
7689 		break;
7690 
7691 	case SCMD_LOAD:
7692 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7693 		    "%s tape\n", (count & LD_LOAD) ? "load" : "unload");
7694 		bp->b_bcount = count;
7695 		count = 0;
7696 		break;
7697 
7698 	case SCMD_ERASE:
7699 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7700 		    "erase tape\n");
7701 		bp->b_bcount = count;
7702 		count = 0;
7703 		break;
7704 
7705 	case SCMD_MODE_SENSE:
7706 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7707 		    "mode sense\n");
7708 		bp->b_flags |= B_READ;
7709 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7710 		break;
7711 
7712 	case SCMD_MODE_SELECT:
7713 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7714 		    "mode select\n");
7715 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7716 		break;
7717 
7718 	case SCMD_READ_BLKLIM:
7719 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7720 		    "read block limits\n");
7721 		bp->b_bcount = count;
7722 		bp->b_flags |= B_READ;
7723 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7724 		break;
7725 
7726 	case SCMD_TEST_UNIT_READY:
7727 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7728 		    "test unit ready\n");
7729 		bp->b_bcount = 0;
7730 		count = 0;
7731 		break;
7732 
7733 	case SCMD_DOORLOCK:
7734 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7735 		    "%s tape\n", (count & MR_LOCK) ? "lock" : "unlock");
7736 		bp->b_bcount = count = 0;
7737 		break;
7738 
7739 	case SCMD_READ_POSITION:
7740 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7741 		    "read position\n");
7742 		switch (un->un_read_pos_type) {
7743 		case LONG_POS:
7744 			count = sizeof (tape_position_long_t);
7745 			break;
7746 		case EXT_POS:
7747 			count = min(count, sizeof (tape_position_ext_t));
7748 			break;
7749 		case SHORT_POS:
7750 			count = sizeof (tape_position_t);
7751 			break;
7752 		default:
7753 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7754 			    "Unknown read position type 0x%x in "
7755 			    "st_make_cmd()\n", un->un_read_pos_type);
7756 		}
7757 		bp->b_bcount = count;
7758 		bp->b_flags |= B_READ;
7759 		bp->b_un.b_addr = (caddr_t)un->un_read_pos_data;
7760 		break;
7761 
7762 	default:
7763 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7764 		    "Unhandled scsi command 0x%x in st_setup_cmd()\n", com);
7765 	}
7766 
7767 	mutex_exit(ST_MUTEX);
7768 
7769 	if (count > 0) {
7770 		int flg = (bp->b_flags & B_READ) ? B_READ : B_WRITE;
7771 		/*
7772 		 * We're going to do actual I/O.
7773 		 * Set things up for physio.
7774 		 */
7775 		struct iovec aiov;
7776 		struct uio auio;
7777 		struct uio *uio = &auio;
7778 
7779 		bzero(&auio, sizeof (struct uio));
7780 		bzero(&aiov, sizeof (struct iovec));
7781 		aiov.iov_base = bp->b_un.b_addr;
7782 		aiov.iov_len = count;
7783 
7784 		uio->uio_iov = &aiov;
7785 		uio->uio_iovcnt = 1;
7786 		uio->uio_resid = aiov.iov_len;
7787 		uio->uio_segflg = UIO_SYSSPACE;
7788 
7789 		/*
7790 		 * Let physio do the rest...
7791 		 */
7792 		bp->b_forw = (struct buf *)(uintptr_t)com;
7793 		bp->b_back = NULL;
7794 		err = physio(st_strategy, bp, dev, flg, st_minphys, uio);
7795 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7796 		    "st_setup_cmd: physio returns %d\n", err);
7797 	} else {
7798 		/*
7799 		 * Mimic physio
7800 		 */
7801 		bp->b_forw = (struct buf *)(uintptr_t)com;
7802 		bp->b_back = NULL;
7803 		bp->b_edev = dev;
7804 		bp->b_dev = cmpdev(dev);
7805 		bp->b_blkno = 0;
7806 		bp->b_resid = 0;
7807 		(void) st_strategy(bp);
7808 		if (bp->b_flags & B_ASYNC) {
7809 			/*
7810 			 * This is an async command- the caller won't wait
7811 			 * and doesn't care about errors.
7812 			 */
7813 			mutex_enter(ST_MUTEX);
7814 			return (0);
7815 		}
7816 
7817 		/*
7818 		 * BugTraq #4260046
7819 		 * ----------------
7820 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7821 		 * unconditionally. The old comment said...
7822 		 *
7823 		 * "if strategy was flagged with  persistent errors, we would
7824 		 *  have an error here, and the bp would never be sent, so we
7825 		 *  don't want to wait on a bp that was never sent...or hang"
7826 		 *
7827 		 * The new rationale, courtesy of Chitrank...
7828 		 *
7829 		 * "we should unconditionally biowait() here because
7830 		 *  st_strategy() will do a biodone() in the persistent error
7831 		 *  case and the following biowait() will return immediately.
7832 		 *  If not, in the case of "errors after pkt alloc" in
7833 		 *  st_start(), we will not biowait here which will cause the
7834 		 *  next biowait() to return immediately which will cause
7835 		 *  us to send out the next command. In the case where both of
7836 		 *  these use the sbuf, when the first command completes we'll
7837 		 *  free the packet attached to sbuf and the same pkt will
7838 		 *  get freed again when we complete the second command.
7839 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7840 		 *  st_start() for the pkt alloc failure case because physio()
7841 		 *  does biowait() and will hang if we don't do biodone()"
7842 		 */
7843 
7844 		err = biowait(bp);
7845 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7846 		    "st_setup_cmd: biowait returns %d\n", err);
7847 	}
7848 
7849 	mutex_enter(ST_MUTEX);
7850 
7851 	return (err);
7852 }
7853 
7854 static int
7855 st_set_compression(struct scsi_tape *un)
7856 {
7857 	int rval;
7858 	int turn_compression_on;
7859 	minor_t minor;
7860 
7861 	ST_FUNC(ST_DEVINFO, st_set_compression);
7862 
7863 	/*
7864 	 * Drive either dosn't have compression or it is controlled with
7865 	 * special density codes. Return ENOTTY so caller
7866 	 * knows nothing was done.
7867 	 */
7868 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7869 		un->un_comp_page = 0;
7870 		return (ENOTTY);
7871 	}
7872 
7873 	/* set compression based on minor node opened */
7874 	minor = MT_DENSITY(un->un_dev);
7875 
7876 	/*
7877 	 * If this the compression density or
7878 	 * the drive has two densities and uses mode select for
7879 	 * control of compression turn on compression for MT_DENSITY2
7880 	 * as well.
7881 	 */
7882 	if ((minor == ST_COMPRESSION_DENSITY) ||
7883 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7884 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7885 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7886 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7887 
7888 		turn_compression_on = 1;
7889 	} else {
7890 		turn_compression_on = 0;
7891 	}
7892 
7893 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7894 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7895 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7896 
7897 	/*
7898 	 * Need to determine which page does the device use for compression.
7899 	 * First try the data compression page. If this fails try the device
7900 	 * configuration page
7901 	 */
7902 
7903 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7904 		rval = st_set_datacomp_page(un, turn_compression_on);
7905 		if (rval == EALREADY) {
7906 			return (rval);
7907 		}
7908 		if (rval != 0) {
7909 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7910 				/*
7911 				 * This device does not support data
7912 				 * compression page
7913 				 */
7914 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7915 			} else if (un->un_state >= ST_STATE_OPEN) {
7916 				un->un_pos.pmode = invalid;
7917 				rval = EIO;
7918 			} else {
7919 				rval = -1;
7920 			}
7921 		} else {
7922 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7923 		}
7924 	}
7925 
7926 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7927 		rval = st_set_devconfig_page(un, turn_compression_on);
7928 		if (rval == EALREADY) {
7929 			return (rval);
7930 		}
7931 		if (rval != 0) {
7932 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7933 				/*
7934 				 * This device does not support
7935 				 * compression at all advice the
7936 				 * user and unset ST_MODE_SEL_COMP
7937 				 */
7938 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7939 				un->un_comp_page = 0;
7940 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7941 				    "Device Does Not Support Compression\n");
7942 			} else if (un->un_state >= ST_STATE_OPEN) {
7943 				un->un_pos.pmode = invalid;
7944 				rval = EIO;
7945 			} else {
7946 				rval = -1;
7947 			}
7948 		}
7949 	}
7950 
7951 	return (rval);
7952 }
7953 
7954 /*
7955  * set or unset compression thru device configuration page.
7956  */
7957 static int
7958 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7959 {
7960 	unsigned char cflag;
7961 	int rval = 0;
7962 
7963 
7964 	ST_FUNC(ST_DEVINFO, st_set_devconfig_page);
7965 
7966 	ASSERT(mutex_owned(ST_MUTEX));
7967 	/*
7968 	 * Figure what to set compression flag to.
7969 	 */
7970 	if (compression_on) {
7971 		/* They have selected a compression node */
7972 		if (un->un_dp->type == ST_TYPE_FUJI) {
7973 			cflag = 0x84;   /* use EDRC */
7974 		} else {
7975 			cflag = ST_DEV_CONFIG_DEF_COMP;
7976 		}
7977 	} else {
7978 		cflag = ST_DEV_CONFIG_NO_COMP;
7979 	}
7980 
7981 	/*
7982 	 * If compression is already set the way it was requested.
7983 	 * And if this not the first time we has tried.
7984 	 */
7985 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7986 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7987 		return (EALREADY);
7988 	}
7989 
7990 	un->un_mspl->page.dev.comp_alg = cflag;
7991 	/*
7992 	 * need to send mode select even if correct compression is
7993 	 * already set since need to set density code
7994 	 */
7995 
7996 #ifdef STDEBUG
7997 	if ((st_debug & 0x7) >= 6) {
7998 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7999 		    "st_set_devconfig_page: sense data for mode select",
8000 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8001 	}
8002 #endif
8003 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8004 	    sizeof (struct seq_mode));
8005 
8006 	return (rval);
8007 }
8008 
8009 /*
8010  * set/reset compression bit thru data compression page
8011  */
8012 static int
8013 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
8014 {
8015 	int compression_on_already;
8016 	int rval = 0;
8017 
8018 
8019 	ST_FUNC(ST_DEVINFO, st_set_datacomp_page);
8020 
8021 	ASSERT(mutex_owned(ST_MUTEX));
8022 	/*
8023 	 * If drive is not capable of compression (at this time)
8024 	 * return EALREADY so caller doesn't think that this page
8025 	 * is not supported. This check is for drives that can
8026 	 * disable compression from the front panel or configuration.
8027 	 * I doubt that a drive that supports this page is not really
8028 	 * capable of compression.
8029 	 */
8030 	if (un->un_mspl->page.comp.dcc == 0) {
8031 		return (EALREADY);
8032 	}
8033 
8034 	/* See if compression currently turned on */
8035 	if (un->un_mspl->page.comp.dce) {
8036 		compression_on_already = 1;
8037 	} else {
8038 		compression_on_already = 0;
8039 	}
8040 
8041 	/*
8042 	 * If compression is already set the way it was requested.
8043 	 * And if this not the first time we has tried.
8044 	 */
8045 	if ((compression_on == compression_on_already) &&
8046 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
8047 		return (EALREADY);
8048 	}
8049 
8050 	/*
8051 	 * if we are already set to the appropriate compression
8052 	 * mode, don't set it again
8053 	 */
8054 	if (compression_on) {
8055 		/* compression selected */
8056 		un->un_mspl->page.comp.dce = 1;
8057 	} else {
8058 		un->un_mspl->page.comp.dce = 0;
8059 	}
8060 
8061 
8062 #ifdef STDEBUG
8063 	if ((st_debug & 0x7) >= 6) {
8064 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8065 		    "st_set_datacomp_page: sense data for mode select",
8066 		    (char *)un->un_mspl, sizeof (struct seq_mode));
8067 	}
8068 #endif
8069 	rval = st_gen_mode_select(un, st_uscsi_cmd, un->un_mspl,
8070 	    sizeof (struct seq_mode));
8071 
8072 	return (rval);
8073 }
8074 
8075 static int
8076 st_modesense(struct scsi_tape *un)
8077 {
8078 	int rval;
8079 	uchar_t page;
8080 
8081 	ST_FUNC(ST_DEVINFO, st_modesense);
8082 
8083 	page = un->un_comp_page;
8084 
8085 	switch (page) {
8086 	case ST_DEV_DATACOMP_PAGE:
8087 	case ST_DEV_CONFIG_PAGE: /* FALLTHROUGH */
8088 		rval = st_gen_mode_sense(un, st_uscsi_cmd, page, un->un_mspl,
8089 		    sizeof (struct seq_mode));
8090 		break;
8091 
8092 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
8093 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
8094 			page = ST_DEV_CONFIG_PAGE;
8095 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8096 			    un->un_mspl, sizeof (struct seq_mode));
8097 			if (rval == 0 && un->un_mspl->page_code == page) {
8098 				un->un_comp_page = page;
8099 				break;
8100 			}
8101 			page = ST_DEV_DATACOMP_PAGE;
8102 			rval = st_gen_mode_sense(un, st_uscsi_cmd, page,
8103 			    un->un_mspl, sizeof (struct seq_mode));
8104 			if (rval == 0 && un->un_mspl->page_code == page) {
8105 				un->un_comp_page = page;
8106 				break;
8107 			}
8108 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
8109 			un->un_comp_page = 0;
8110 		} else {
8111 			un->un_comp_page = 0;
8112 		}
8113 
8114 	default:	/* FALLTHROUGH */
8115 		rval = st_cmd(un, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
8116 	}
8117 	return (rval);
8118 }
8119 
8120 static int
8121 st_modeselect(struct scsi_tape *un)
8122 {
8123 	int rval = 0;
8124 	int ix;
8125 
8126 	ST_FUNC(ST_DEVINFO, st_modeselect);
8127 
8128 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8129 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
8130 	    un->un_dev, un->un_mspl->density);
8131 
8132 	ASSERT(mutex_owned(ST_MUTEX));
8133 
8134 	/*
8135 	 * The parameter list should be the same for all of the
8136 	 * cases that follow so set them here
8137 	 *
8138 	 * Try mode select first if if fails set fields manually
8139 	 */
8140 	rval = st_modesense(un);
8141 	if (rval != 0) {
8142 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8143 		    "st_modeselect: First mode sense failed\n");
8144 		un->un_mspl->bd_len  = 8;
8145 		un->un_mspl->high_nb = 0;
8146 		un->un_mspl->mid_nb  = 0;
8147 		un->un_mspl->low_nb  = 0;
8148 	}
8149 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
8150 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
8151 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
8152 
8153 
8154 	/*
8155 	 * If configured to use a specific density code for a media type.
8156 	 * curdens is previously set by the minor node opened.
8157 	 * If the media type doesn't match the minor node we change it so it
8158 	 * looks like the correct one was opened.
8159 	 */
8160 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
8161 		uchar_t best;
8162 
8163 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
8164 			if (un->un_mspl->media_type ==
8165 			    un->un_dp->mediatype[ix]) {
8166 				best = ix;
8167 				/*
8168 				 * It matches but it might not be the only one.
8169 				 * Use the highest matching media type but not
8170 				 * to exceed the density selected by the open.
8171 				 */
8172 				if (ix < un->un_curdens) {
8173 					continue;
8174 				}
8175 				un->un_curdens = ix;
8176 				break;
8177 			}
8178 		}
8179 		/* If a match was found best will not be 0xff any more */
8180 		if (best < NDENSITIES) {
8181 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8182 			    "found media 0x%X using density 0x%X\n",
8183 			    un->un_mspl->media_type,
8184 			    un->un_dp->densities[best]);
8185 			un->un_mspl->density = un->un_dp->densities[best];
8186 		} else {
8187 			/* Otherwise set density based on minor node opened */
8188 			un->un_mspl->density =
8189 			    un->un_dp->densities[un->un_curdens];
8190 		}
8191 	} else {
8192 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
8193 	}
8194 
8195 	if (un->un_dp->options & ST_NOBUF) {
8196 		un->un_mspl->bufm = 0;
8197 	} else {
8198 		un->un_mspl->bufm = 1;
8199 	}
8200 
8201 	rval = st_set_compression(un);
8202 
8203 	/*
8204 	 * If st_set_compression returned invalid or already it
8205 	 * found no need to do the mode select.
8206 	 * So do it here.
8207 	 */
8208 	if ((rval == ENOTTY) || (rval == EALREADY)) {
8209 
8210 		/* Zero non-writeable fields */
8211 		un->un_mspl->data_len = 0;
8212 		un->un_mspl->media_type = 0;
8213 		un->un_mspl->wp = 0;
8214 
8215 		/* need to set the density code */
8216 		rval = st_cmd(un, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
8217 		if (rval != 0) {
8218 			if (un->un_state >= ST_STATE_OPEN) {
8219 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8220 				    "unable to set tape mode\n");
8221 				un->un_pos.pmode = invalid;
8222 				rval = EIO;
8223 			} else {
8224 				rval = -1;
8225 			}
8226 		}
8227 	}
8228 
8229 	/*
8230 	 * The spec recommends to send a mode sense after a mode select
8231 	 */
8232 	(void) st_modesense(un);
8233 
8234 	ASSERT(mutex_owned(ST_MUTEX));
8235 
8236 	return (rval);
8237 }
8238 
8239 /*
8240  * st_gen_mode_sense
8241  *
8242  * generic mode sense.. it allows for any page
8243  */
8244 static int
8245 st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
8246     struct seq_mode *page_data, int page_size)
8247 {
8248 
8249 	int r;
8250 	char	cdb[CDB_GROUP0];
8251 	struct uscsi_cmd *com;
8252 	struct scsi_arq_status status;
8253 
8254 	ST_FUNC(ST_DEVINFO, st_gen_mode_sense);
8255 
8256 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8257 
8258 	bzero(cdb, CDB_GROUP0);
8259 	cdb[0] = SCMD_MODE_SENSE;
8260 	cdb[2] = (char)page;
8261 	cdb[4] = (char)page_size;
8262 
8263 	com->uscsi_cdb = cdb;
8264 	com->uscsi_cdblen = CDB_GROUP0;
8265 	com->uscsi_bufaddr = (caddr_t)page_data;
8266 	com->uscsi_buflen = page_size;
8267 	com->uscsi_rqlen = sizeof (status);
8268 	com->uscsi_rqbuf = (caddr_t)&status;
8269 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8270 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8271 
8272 	r = ubf(un, com, FKIOCTL);
8273 	kmem_free(com, sizeof (*com));
8274 	return (r);
8275 }
8276 
8277 /*
8278  * st_gen_mode_select
8279  *
8280  * generic mode select.. it allows for any page
8281  */
8282 static int
8283 st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
8284     struct seq_mode *page_data, int page_size)
8285 {
8286 
8287 	int r;
8288 	char cdb[CDB_GROUP0];
8289 	struct uscsi_cmd *com;
8290 	struct scsi_arq_status status;
8291 
8292 	ST_FUNC(ST_DEVINFO, st_gen_mode_select);
8293 
8294 	/* Zero non-writeable fields */
8295 	page_data->data_len = 0;
8296 	page_data->media_type = 0;
8297 	page_data->wp = 0;
8298 
8299 	/*
8300 	 * If mode select has any page data, zero the ps (Page Savable) bit.
8301 	 */
8302 	if (page_size > MSIZE) {
8303 		page_data->ps = 0;
8304 	}
8305 
8306 
8307 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8308 
8309 	/*
8310 	 * then, do a mode select to set what ever info
8311 	 */
8312 	bzero(cdb, CDB_GROUP0);
8313 	cdb[0] = SCMD_MODE_SELECT;
8314 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
8315 	cdb[4] = (char)page_size;
8316 
8317 	com->uscsi_cdb = cdb;
8318 	com->uscsi_cdblen = CDB_GROUP0;
8319 	com->uscsi_bufaddr = (caddr_t)page_data;
8320 	com->uscsi_buflen = page_size;
8321 	com->uscsi_rqlen = sizeof (status);
8322 	com->uscsi_rqbuf = (caddr_t)&status;
8323 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8324 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_WRITE;
8325 
8326 	r = ubf(un, com, FKIOCTL);
8327 
8328 	kmem_free(com, sizeof (*com));
8329 	return (r);
8330 }
8331 
8332 static int
8333 st_read_block_limits(struct scsi_tape *un, struct read_blklim *read_blk)
8334 {
8335 	int rval;
8336 	char cdb[CDB_GROUP0];
8337 	struct uscsi_cmd *com;
8338 	struct scsi_arq_status status;
8339 
8340 	ST_FUNC(ST_DEVINFO, st_read_block_limits);
8341 
8342 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8343 
8344 	bzero(cdb, CDB_GROUP0);
8345 	cdb[0] = SCMD_READ_BLKLIM;
8346 
8347 	com->uscsi_cdb = cdb;
8348 	com->uscsi_cdblen = CDB_GROUP0;
8349 	com->uscsi_bufaddr = (caddr_t)read_blk;
8350 	com->uscsi_buflen = sizeof (struct read_blklim);
8351 	com->uscsi_rqlen = sizeof (status);
8352 	com->uscsi_rqbuf = (caddr_t)&status;
8353 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8354 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8355 
8356 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8357 	if (com->uscsi_status || com->uscsi_resid) {
8358 		rval = -1;
8359 	}
8360 
8361 	kmem_free(com, sizeof (*com));
8362 	return (rval);
8363 }
8364 
8365 static int
8366 st_report_density_support(struct scsi_tape *un, uchar_t *density_data,
8367     size_t buflen)
8368 {
8369 	int rval;
8370 	char cdb[CDB_GROUP1];
8371 	struct uscsi_cmd *com;
8372 	struct scsi_arq_status status;
8373 
8374 	ST_FUNC(ST_DEVINFO, st_report_density_support);
8375 
8376 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8377 
8378 	bzero(cdb, CDB_GROUP1);
8379 	cdb[0] = SCMD_REPORT_DENSITIES;
8380 	cdb[7] = (buflen & 0xff00) >> 8;
8381 	cdb[8] = buflen & 0xff;
8382 
8383 	com->uscsi_cdb = cdb;
8384 	com->uscsi_cdblen = CDB_GROUP1;
8385 	com->uscsi_bufaddr = (caddr_t)density_data;
8386 	com->uscsi_buflen = buflen;
8387 	com->uscsi_rqlen = sizeof (status);
8388 	com->uscsi_rqbuf = (caddr_t)&status;
8389 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8390 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8391 
8392 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8393 	if (com->uscsi_status || com->uscsi_resid) {
8394 		rval = -1;
8395 	}
8396 
8397 	kmem_free(com, sizeof (*com));
8398 	return (rval);
8399 }
8400 
8401 static int
8402 st_report_supported_operation(struct scsi_tape *un, uchar_t *oper_data,
8403     uchar_t option_code, ushort_t service_action)
8404 {
8405 	int rval;
8406 	char cdb[CDB_GROUP5];
8407 	struct uscsi_cmd *com;
8408 	struct scsi_arq_status status;
8409 	uint32_t allo_length;
8410 
8411 	ST_FUNC(ST_DEVINFO, st_report_supported_operation);
8412 
8413 	allo_length = sizeof (struct one_com_des) +
8414 	    sizeof (struct com_timeout_des);
8415 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
8416 
8417 	bzero(cdb, CDB_GROUP5);
8418 	cdb[0] = (char)SCMD_MAINTENANCE_IN;
8419 	cdb[1] = SSVC_ACTION_GET_SUPPORTED_OPERATIONS;
8420 	if (service_action) {
8421 		cdb[2] = (char)(ONE_COMMAND_DATA_FORMAT | 0x80); /* RCTD */
8422 		cdb[4] = (service_action & 0xff00) >> 8;
8423 		cdb[5] = service_action & 0xff;
8424 	} else {
8425 		cdb[2] = (char)(ONE_COMMAND_NO_SERVICE_DATA_FORMAT |
8426 		    0x80); /* RCTD */
8427 	}
8428 	cdb[3] = option_code;
8429 	cdb[6] = (allo_length & 0xff000000) >> 24;
8430 	cdb[7] = (allo_length & 0xff0000) >> 16;
8431 	cdb[8] = (allo_length & 0xff00) >> 8;
8432 	cdb[9] = allo_length & 0xff;
8433 
8434 	com->uscsi_cdb = cdb;
8435 	com->uscsi_cdblen = CDB_GROUP5;
8436 	com->uscsi_bufaddr = (caddr_t)oper_data;
8437 	com->uscsi_buflen = allo_length;
8438 	com->uscsi_rqlen = sizeof (status);
8439 	com->uscsi_rqbuf = (caddr_t)&status;
8440 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
8441 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
8442 
8443 	rval = st_uscsi_cmd(un, com, FKIOCTL);
8444 	if (com->uscsi_status) {
8445 		rval = -1;
8446 	}
8447 
8448 	kmem_free(com, sizeof (*com));
8449 	return (rval);
8450 }
8451 
8452 /*
8453  * Changes devices blocksize and bsize to requested blocksize nblksz.
8454  * Returns returned value from first failed call or zero on success.
8455  */
8456 static int
8457 st_change_block_size(struct scsi_tape *un, uint32_t nblksz)
8458 {
8459 	struct seq_mode *current;
8460 	int rval;
8461 	uint32_t oldblksz;
8462 
8463 	ST_FUNC(ST_DEVINFO, st_change_block_size);
8464 
8465 	current = kmem_zalloc(MSIZE, KM_SLEEP);
8466 
8467 	/*
8468 	 * If we haven't got the compression page yet, do that first.
8469 	 */
8470 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
8471 		(void) st_modesense(un);
8472 	}
8473 
8474 	/* Read current settings */
8475 	rval = st_gen_mode_sense(un, st_uscsi_cmd, 0, current, MSIZE);
8476 	if (rval != 0) {
8477 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8478 		    "mode sense for change block size failed: rval = %d", rval);
8479 		goto finish;
8480 	}
8481 
8482 	/* Figure the current block size */
8483 	oldblksz =
8484 	    (current->high_bl << 16) |
8485 	    (current->mid_bl << 8) |
8486 	    (current->low_bl);
8487 
8488 	/* If current block size is the same as requested were done */
8489 	if (oldblksz == nblksz) {
8490 		un->un_bsize = nblksz;
8491 		rval = 0;
8492 		goto finish;
8493 	}
8494 
8495 	/* Change to requested block size */
8496 	current->high_bl = (uchar_t)(nblksz >> 16);
8497 	current->mid_bl  = (uchar_t)(nblksz >> 8);
8498 	current->low_bl  = (uchar_t)(nblksz);
8499 
8500 	/* Attempt to change block size */
8501 	rval = st_gen_mode_select(un, st_uscsi_cmd, current, MSIZE);
8502 	if (rval != 0) {
8503 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8504 		    "Set new block size failed: rval = %d", rval);
8505 		goto finish;
8506 	}
8507 
8508 	/* Read back and verify setting */
8509 	rval = st_modesense(un);
8510 	if (rval == 0) {
8511 		un->un_bsize =
8512 		    (un->un_mspl->high_bl << 16) |
8513 		    (un->un_mspl->mid_bl << 8) |
8514 		    (un->un_mspl->low_bl);
8515 
8516 		if (un->un_bsize != nblksz) {
8517 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
8518 			    "Blocksize set does not equal requested blocksize"
8519 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
8520 			rval = EIO;
8521 		}
8522 	}
8523 finish:
8524 	kmem_free(current, MSIZE);
8525 	return (rval);
8526 }
8527 
8528 
8529 static void
8530 st_init(struct scsi_tape *un)
8531 {
8532 	ST_FUNC(ST_DEVINFO, st_init);
8533 
8534 	ASSERT(mutex_owned(ST_MUTEX));
8535 
8536 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8537 	    "st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n",
8538 	    un->un_dev);
8539 
8540 	un->un_pos.blkno = 0;
8541 	un->un_pos.fileno = 0;
8542 	un->un_lastop = ST_OP_NIL;
8543 	un->un_pos.eof = ST_NO_EOF;
8544 	un->un_pwr_mgmt = ST_PWR_NORMAL;
8545 	if (st_error_level != SCSI_ERR_ALL) {
8546 		if (DEBUGGING) {
8547 			st_error_level = SCSI_ERR_ALL;
8548 		} else {
8549 			st_error_level = SCSI_ERR_RETRYABLE;
8550 		}
8551 	}
8552 }
8553 
8554 
8555 static void
8556 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
8557 {
8558 	struct scsi_pkt *pkt;
8559 	struct uscsi_cmd *ucmd;
8560 	recov_info *ri;
8561 	int tval = 0;
8562 	int64_t count;
8563 	uint32_t additional = 0;
8564 	uint32_t address = 0;
8565 	union scsi_cdb *ucdb;
8566 	int flags = 0;
8567 	int cdb_len = CDB_GROUP0; /* default */
8568 	uchar_t com;
8569 	char fixbit;
8570 	char short_fm = 0;
8571 	optype prev_op = un->un_lastop;
8572 	int stat_size =
8573 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
8574 
8575 	ST_FUNC(ST_DEVINFO, st_make_cmd);
8576 
8577 	ASSERT(mutex_owned(ST_MUTEX));
8578 
8579 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8580 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
8581 
8582 
8583 	/*
8584 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
8585 	 * Length Indicator bits on read/write commands, for setting
8586 	 * the Long bit on erase commands, and for setting the Code
8587 	 * Field bits on space commands.
8588 	 */
8589 
8590 	/* regular raw I/O */
8591 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
8592 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
8593 		    CDB_GROUP0, stat_size, st_recov_sz, 0, func,
8594 		    (caddr_t)un);
8595 		if (pkt == NULL) {
8596 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8597 			    "Read Write scsi_init_pkt() failure\n");
8598 			goto exit;
8599 		}
8600 		ASSERT(pkt->pkt_resid == 0);
8601 #ifdef STDEBUG
8602 		bzero(pkt->pkt_private, st_recov_sz);
8603 		bzero(pkt->pkt_scbp, stat_size);
8604 #endif
8605 		ri = (recov_info *)pkt->pkt_private;
8606 		ri->privatelen = st_recov_sz;
8607 		if (un->un_bsize == 0) {
8608 			count = bp->b_bcount;
8609 			fixbit = 0;
8610 		} else {
8611 			count = bp->b_bcount / un->un_bsize;
8612 			fixbit = 1;
8613 		}
8614 		if (bp->b_flags & B_READ) {
8615 			com = SCMD_READ;
8616 			un->un_lastop = ST_OP_READ;
8617 			if ((un->un_bsize == 0) && /* Not Fixed Block */
8618 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
8619 				fixbit = 2;
8620 			}
8621 		} else {
8622 			com = SCMD_WRITE;
8623 			un->un_lastop = ST_OP_WRITE;
8624 		}
8625 		tval = un->un_dp->io_timeout;
8626 
8627 		/*
8628 		 * For really large xfers, increase timeout
8629 		 */
8630 		if (bp->b_bcount > (10 * ONE_MEG))
8631 			tval *= bp->b_bcount/(10 * ONE_MEG);
8632 
8633 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8634 		    "%s %d amt 0x%lx\n", (com == SCMD_WRITE) ?
8635 		    wr_str: rd_str, un->un_pos.blkno, bp->b_bcount);
8636 
8637 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
8638 		/*
8639 		 * uscsi - build command, allocate scsi resources
8640 		 */
8641 		st_make_uscsi_cmd(un, ucmd, bp, func);
8642 		goto exit;
8643 
8644 	} else {				/* special I/O */
8645 		struct buf *allocbp = NULL;
8646 		com = (uchar_t)(uintptr_t)bp->b_forw;
8647 		count = bp->b_bcount;
8648 
8649 		switch (com) {
8650 		case SCMD_READ:
8651 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8652 			    "special read %"PRId64"\n", count);
8653 			if (un->un_bsize == 0) {
8654 				fixbit = 2;	/* suppress SILI */
8655 			} else {
8656 				fixbit = 1;	/* Fixed Block Mode */
8657 				count /= un->un_bsize;
8658 			}
8659 			allocbp = bp;
8660 			un->un_lastop = ST_OP_READ;
8661 			tval = un->un_dp->io_timeout;
8662 			break;
8663 
8664 		case SCMD_WRITE:
8665 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8666 			    "special write %"PRId64"\n", count);
8667 			if (un->un_bsize != 0) {
8668 				fixbit = 1;	/* Fixed Block Mode */
8669 				count /= un->un_bsize;
8670 			} else {
8671 				fixbit = 0;
8672 			}
8673 			allocbp = bp;
8674 			un->un_lastop = ST_OP_WRITE;
8675 			tval = un->un_dp->io_timeout;
8676 			break;
8677 
8678 		case SCMD_WRITE_FILE_MARK:
8679 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8680 			    "write %"PRId64" file marks\n", count);
8681 			un->un_lastop = ST_OP_WEOF;
8682 			fixbit = 0;
8683 			tval = un->un_dp->io_timeout;
8684 			/*
8685 			 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
8686 			 * device, set the Vendor Unique bit to
8687 			 * write Short File Mark.
8688 			 */
8689 			if ((un->un_dp->options & ST_SHORT_FILEMARKS) &&
8690 			    ((un->un_dp->type == ST_TYPE_EXB8500) ||
8691 			    (un->un_dp->type == ST_TYPE_EXABYTE))) {
8692 				/*
8693 				 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8694 				 * is set to to write Short File Mark
8695 				 */
8696 				short_fm = 1;
8697 			}
8698 			break;
8699 
8700 		case SCMD_REWIND:
8701 			/*
8702 			 * In the case of rewind we're gona do the rewind with
8703 			 * the immediate bit set so status will be retured when
8704 			 * the command is accepted by the device. We clear the
8705 			 * B_ASYNC flag so we wait for that acceptance.
8706 			 */
8707 			if (bp->b_flags & B_ASYNC) {
8708 				allocbp = bp;
8709 				if (count) {
8710 					fixbit = 1;
8711 					bp->b_flags &= ~B_ASYNC;
8712 				}
8713 			} else {
8714 				fixbit = 0;
8715 			}
8716 			count = 0;
8717 			bp->b_bcount = 0;
8718 			un->un_lastop = ST_OP_CTL;
8719 			tval = un->un_dp->rewind_timeout;
8720 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8721 			    "rewind\n");
8722 			break;
8723 
8724 		case SCMD_SPACE_G4:
8725 			cdb_len = CDB_GROUP4;
8726 			fixbit = SPACE_TYPE(bp->b_bcount);
8727 			count = SPACE_CNT(bp->b_bcount);
8728 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8729 			    " %s space %s %"PRId64" from file %d blk %d\n",
8730 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8731 			    space_strs[fixbit & 7], count,
8732 			    un->un_pos.fileno, un->un_pos.blkno);
8733 			address = (count >> 48) & 0x1fff;
8734 			additional = (count >> 16) & 0xffffffff;
8735 			count &= 0xffff;
8736 			count <<= 16;
8737 			un->un_lastop = ST_OP_CTL;
8738 			tval = un->un_dp->space_timeout;
8739 			break;
8740 
8741 		case SCMD_SPACE:
8742 			fixbit = SPACE_TYPE(bp->b_bcount);
8743 			count = SPACE_CNT(bp->b_bcount);
8744 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8745 			    " %s space %s %"PRId64" from file %d blk %d\n",
8746 			    bp->b_bcount & SP_BACKSP ? "backward" : "forward",
8747 			    space_strs[fixbit & 7], count,
8748 			    un->un_pos.fileno, un->un_pos.blkno);
8749 			count &= 0xffffffff;
8750 			un->un_lastop = ST_OP_CTL;
8751 			tval = un->un_dp->space_timeout;
8752 			break;
8753 
8754 		case SCMD_LOAD:
8755 			ASSERT(count < 10);
8756 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8757 			    "%s tape\n", load_strs[count]);
8758 			fixbit = 0;
8759 
8760 			/* Loading or Unloading */
8761 			if (count & LD_LOAD) {
8762 				tval = un->un_dp->load_timeout;
8763 			} else {
8764 				tval = un->un_dp->unload_timeout;
8765 			}
8766 			/* Is Retension requested */
8767 			if (count & LD_RETEN) {
8768 				tval += un->un_dp->rewind_timeout;
8769 			}
8770 			un->un_lastop = ST_OP_CTL;
8771 			break;
8772 
8773 		case SCMD_ERASE:
8774 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8775 			    "erase tape\n");
8776 			ASSERT(count == 1); /* mt sets this */
8777 			if (count == 1) {
8778 				/*
8779 				 * do long erase
8780 				 */
8781 				fixbit = 1; /* Long */
8782 
8783 				/* Drive might not honor immidiate bit */
8784 				tval = un->un_dp->erase_timeout;
8785 			} else {
8786 				/* Short Erase */
8787 				tval = un->un_dp->erase_timeout;
8788 				fixbit = 0;
8789 			}
8790 			un->un_lastop = ST_OP_CTL;
8791 			count = 0;
8792 			break;
8793 
8794 		case SCMD_MODE_SENSE:
8795 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8796 			    "mode sense\n");
8797 			allocbp = bp;
8798 			fixbit = 0;
8799 			tval = un->un_dp->non_motion_timeout;
8800 			un->un_lastop = ST_OP_CTL;
8801 			break;
8802 
8803 		case SCMD_MODE_SELECT:
8804 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8805 			    "mode select\n");
8806 			allocbp = bp;
8807 			fixbit = 0;
8808 			tval = un->un_dp->non_motion_timeout;
8809 			un->un_lastop = ST_OP_CTL;
8810 			break;
8811 
8812 		case SCMD_RESERVE:
8813 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8814 			    "reserve\n");
8815 			fixbit = 0;
8816 			tval = un->un_dp->non_motion_timeout;
8817 			un->un_lastop = ST_OP_CTL;
8818 			break;
8819 
8820 		case SCMD_RELEASE:
8821 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8822 			    "release\n");
8823 			fixbit = 0;
8824 			tval = un->un_dp->non_motion_timeout;
8825 			un->un_lastop = ST_OP_CTL;
8826 			break;
8827 
8828 		case SCMD_READ_BLKLIM:
8829 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8830 			    "read block limits\n");
8831 			allocbp = bp;
8832 			fixbit = count = 0;
8833 			tval = un->un_dp->non_motion_timeout;
8834 			un->un_lastop = ST_OP_CTL;
8835 			break;
8836 
8837 		case SCMD_TEST_UNIT_READY:
8838 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8839 			    "test unit ready\n");
8840 			fixbit = 0;
8841 			tval = un->un_dp->non_motion_timeout;
8842 			un->un_lastop = ST_OP_CTL;
8843 			break;
8844 
8845 		case SCMD_DOORLOCK:
8846 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8847 			    "prevent/allow media removal\n");
8848 			fixbit = 0;
8849 			tval = un->un_dp->non_motion_timeout;
8850 			un->un_lastop = ST_OP_CTL;
8851 			break;
8852 
8853 		case SCMD_READ_POSITION:
8854 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8855 			    "read position\n");
8856 			fixbit = un->un_read_pos_type;
8857 			cdb_len = CDB_GROUP1;
8858 			tval = un->un_dp->non_motion_timeout;
8859 			allocbp = bp;
8860 			un->un_lastop = ST_OP_CTL;
8861 			switch (un->un_read_pos_type) {
8862 			case LONG_POS:
8863 				count = 0;
8864 				break;
8865 			case EXT_POS:
8866 				count = sizeof (tape_position_ext_t);
8867 				break;
8868 			case SHORT_POS:
8869 				count = 0;
8870 				break;
8871 			default:
8872 				ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8873 				    "Unknown read position type 0x%x in "
8874 				    " st_make_cmd()\n", un->un_read_pos_type);
8875 			}
8876 			break;
8877 
8878 		default:
8879 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
8880 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
8881 			    com);
8882 		}
8883 
8884 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp, cdb_len, stat_size,
8885 		    st_recov_sz, 0, func, (caddr_t)un);
8886 		if (pkt == NULL) {
8887 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8888 			    "generic command scsi_init_pkt() failure\n");
8889 			goto exit;
8890 		}
8891 
8892 		ASSERT(pkt->pkt_resid == 0);
8893 #ifdef STDEBUG
8894 		bzero(pkt->pkt_private, st_recov_sz);
8895 		bzero(pkt->pkt_scbp, stat_size);
8896 #endif
8897 		ri = (recov_info *)pkt->pkt_private;
8898 		ri->privatelen = st_recov_sz;
8899 		if (allocbp) {
8900 			ASSERT(geterror(allocbp) == 0);
8901 		}
8902 
8903 	}
8904 
8905 	ucdb = (union scsi_cdb *)pkt->pkt_cdbp;
8906 
8907 	(void) scsi_setup_cdb(ucdb, com, address, (uint_t)count, additional);
8908 	FILL_SCSI1_LUN(un->un_sd, pkt);
8909 	/*
8910 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
8911 	 */
8912 	ucdb->t_code = fixbit;
8913 	ucdb->g0_vu_1 = short_fm;
8914 	pkt->pkt_flags = flags;
8915 
8916 	ASSERT(tval);
8917 	pkt->pkt_time = tval;
8918 	if (bp == un->un_recov_buf) {
8919 		pkt->pkt_comp = st_recov_cb;
8920 	} else {
8921 		pkt->pkt_comp = st_intr;
8922 	}
8923 
8924 	st_add_recovery_info_to_pkt(un, bp, pkt);
8925 
8926 	/*
8927 	 * If we just write data to tape and did a command that doesn't
8928 	 * change position, we still need to write a filemark.
8929 	 */
8930 	if ((prev_op == ST_OP_WRITE) || (prev_op == ST_OP_WEOF)) {
8931 		recov_info *rcvi = pkt->pkt_private;
8932 		cmd_attribute const *atrib;
8933 
8934 		if (rcvi->privatelen == sizeof (recov_info)) {
8935 			atrib = rcvi->cmd_attrib;
8936 		} else {
8937 			atrib = st_lookup_cmd_attribute(com);
8938 		}
8939 		if (atrib->chg_tape_direction == DIR_NONE) {
8940 			un->un_lastop = prev_op;
8941 		}
8942 	}
8943 
8944 exit:
8945 	ASSERT(mutex_owned(ST_MUTEX));
8946 }
8947 
8948 
8949 /*
8950  * Build a command based on a uscsi command;
8951  */
8952 static void
8953 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8954     struct buf *bp, int (*func)(caddr_t))
8955 {
8956 	struct scsi_pkt *pkt;
8957 	recov_info *ri;
8958 	caddr_t cdb;
8959 	int	cdblen;
8960 	int	stat_size = 1;
8961 	int	flags = 0;
8962 
8963 	ST_FUNC(ST_DEVINFO, st_make_uscsi_cmd);
8964 
8965 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8966 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8967 
8968 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8969 		if (un->un_arq_enabled) {
8970 			if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
8971 				stat_size = (int)(ucmd->uscsi_rqlen) +
8972 				    sizeof (struct scsi_arq_status) -
8973 				    sizeof (struct scsi_extended_sense);
8974 				flags = PKT_XARQ;
8975 			} else {
8976 				stat_size = sizeof (struct scsi_arq_status);
8977 			}
8978 		}
8979 	}
8980 
8981 	ASSERT(mutex_owned(ST_MUTEX));
8982 
8983 	cdb = ucmd->uscsi_cdb;
8984 	cdblen = ucmd->uscsi_cdblen;
8985 
8986 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8987 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8988 	    ucmd->uscsi_buflen, bp->b_bcount);
8989 	pkt = scsi_init_pkt(ROUTE, NULL,
8990 	    (bp->b_bcount > 0) ? bp : NULL,
8991 	    cdblen, stat_size, st_recov_sz, flags, func, (caddr_t)un);
8992 	if (pkt == NULL) {
8993 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
8994 		    "uscsi command scsi_init_pkt() failure\n");
8995 		goto exit;
8996 	}
8997 
8998 	ASSERT(pkt->pkt_resid == 0);
8999 #ifdef STDEBUG
9000 	bzero(pkt->pkt_private, st_recov_sz);
9001 	bzero(pkt->pkt_scbp, stat_size);
9002 #endif
9003 	ri = (recov_info *)pkt->pkt_private;
9004 	ri->privatelen = st_recov_sz;
9005 
9006 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
9007 
9008 #ifdef STDEBUG
9009 	if ((st_debug & 0x7) >= 6) {
9010 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
9011 		    "pkt_cdbp", (char *)cdb, cdblen);
9012 	}
9013 #endif
9014 
9015 	if (ucmd->uscsi_flags & USCSI_SILENT) {
9016 		pkt->pkt_flags |= FLAG_SILENT;
9017 	}
9018 
9019 	pkt->pkt_time = ucmd->uscsi_timeout;
9020 	if (bp == un->un_recov_buf) {
9021 		pkt->pkt_comp = st_recov_cb;
9022 	} else {
9023 		pkt->pkt_comp = st_intr;
9024 	}
9025 	st_add_recovery_info_to_pkt(un, bp, pkt);
9026 exit:
9027 	ASSERT(mutex_owned(ST_MUTEX));
9028 }
9029 
9030 
9031 /*
9032  * restart cmd currently at the head of the runq
9033  *
9034  * If scsi_transport() succeeds or the retries
9035  * count exhausted, restore the throttle that was
9036  * zeroed out in st_handle_intr_busy().
9037  *
9038  */
9039 static void
9040 st_intr_restart(void *arg)
9041 {
9042 	struct scsi_tape *un = arg;
9043 	struct buf *bp;
9044 	int queued;
9045 	int status = TRAN_ACCEPT;
9046 
9047 	mutex_enter(ST_MUTEX);
9048 
9049 	ST_FUNC(ST_DEVINFO, st_intr_restart);
9050 
9051 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9052 	    "st_intr_restart(), un = 0x%p\n", (void *)un);
9053 
9054 	un->un_hib_tid = 0;
9055 
9056 	if (un->un_recov_buf_busy != 0) {
9057 		bp = un->un_recov_buf;
9058 		queued = 0;
9059 	} else if (un->un_sbuf_busy != 0) {
9060 		bp = un->un_sbufp;
9061 		queued = 0;
9062 	} else if (un->un_quef != NULL) {
9063 		bp = un->un_quef;
9064 		queued = 1;
9065 	} else {
9066 		mutex_exit(ST_MUTEX);
9067 		return;
9068 	}
9069 
9070 	/*
9071 	 * Here we know :
9072 	 *	throttle = 0, via st_handle_intr_busy
9073 	 */
9074 
9075 	if (queued) {
9076 		/*
9077 		 * move from waitq to runq, if there is anything on the waitq
9078 		 */
9079 		(void) st_remove_from_queue(&un->un_quef, &un->un_quef, bp);
9080 
9081 		if (un->un_runqf) {
9082 			/*
9083 			 * not good, we don't want to requeue something after
9084 			 * another.
9085 			 */
9086 			goto done_error;
9087 		} else {
9088 			un->un_runqf = bp;
9089 			un->un_runql = bp;
9090 		}
9091 	}
9092 
9093 	ST_CDB(ST_DEVINFO, "Interrupt restart CDB",
9094 	    (char *)BP_PKT(bp)->pkt_cdbp);
9095 
9096 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
9097 
9098 	status = st_transport(un, BP_PKT(bp));
9099 
9100 	if (status != TRAN_ACCEPT) {
9101 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9102 
9103 		if (status == TRAN_BUSY) {
9104 			pkt_info *pkti = BP_PKT(bp)->pkt_private;
9105 
9106 			if (pkti->privatelen == sizeof (recov_info) &&
9107 			    un->un_unit_attention_flags &&
9108 			    bp != un->un_recov_buf) {
9109 			un->un_unit_attention_flags = 0;
9110 				ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9111 				    "Command Recovery called on busy resend\n");
9112 				if (st_command_recovery(un, BP_PKT(bp),
9113 				    ATTEMPT_RETRY) == JUST_RETURN) {
9114 					mutex_exit(ST_MUTEX);
9115 					return;
9116 				}
9117 			}
9118 			mutex_exit(ST_MUTEX);
9119 			if (st_handle_intr_busy(un, bp,
9120 			    ST_TRAN_BUSY_TIMEOUT) == 0)
9121 				return;	/* timeout is setup again */
9122 			mutex_enter(ST_MUTEX);
9123 		}
9124 
9125 done_error:
9126 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9127 		    "restart transport rejected\n");
9128 		bp->b_resid = bp->b_bcount;
9129 
9130 		if (un->un_last_throttle) {
9131 			un->un_throttle = un->un_last_throttle;
9132 		}
9133 		if (status != TRAN_ACCEPT) {
9134 			ST_DO_ERRSTATS(un, st_transerrs);
9135 		}
9136 		ST_DO_KSTATS(bp, kstat_waitq_exit);
9137 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9138 		    "busy restart aborted\n");
9139 		st_set_pe_flag(un);
9140 		st_bioerror(bp, EIO);
9141 		st_done_and_mutex_exit(un, bp);
9142 	} else {
9143 		if (un->un_last_throttle) {
9144 			un->un_throttle = un->un_last_throttle;
9145 		}
9146 		mutex_exit(ST_MUTEX);
9147 	}
9148 }
9149 
9150 /*
9151  * st_check_media():
9152  * Periodically check the media state using scsi_watch service;
9153  * this service calls back after TUR and possibly request sense
9154  * the callback handler (st_media_watch_cb()) decodes the request sense
9155  * data (if any)
9156  */
9157 
9158 static int
9159 st_check_media(dev_t dev, enum mtio_state state)
9160 {
9161 	int rval = 0;
9162 	enum mtio_state	prev_state;
9163 	opaque_t token = NULL;
9164 
9165 	GET_SOFT_STATE(dev);
9166 
9167 	ST_FUNC(ST_DEVINFO, st_check_media);
9168 
9169 	mutex_enter(ST_MUTEX);
9170 
9171 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9172 	    "st_check_media:state=%x, mediastate=%x\n",
9173 	    state, un->un_mediastate);
9174 
9175 	prev_state = un->un_mediastate;
9176 
9177 	/*
9178 	 * is there anything to do?
9179 	 */
9180 retry:
9181 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
9182 		/*
9183 		 * submit the request to the scsi_watch service;
9184 		 * scsi_media_watch_cb() does the real work
9185 		 */
9186 		mutex_exit(ST_MUTEX);
9187 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
9188 		    st_check_media_time, SENSE_LENGTH,
9189 		    st_media_watch_cb, (caddr_t)dev);
9190 		if (token == NULL) {
9191 			rval = EAGAIN;
9192 			goto done;
9193 		}
9194 		mutex_enter(ST_MUTEX);
9195 
9196 		un->un_swr_token = token;
9197 		un->un_specified_mediastate = state;
9198 
9199 		/*
9200 		 * now wait for media change
9201 		 * we will not be signalled unless mediastate == state but it
9202 		 * still better to test for this condition, since there
9203 		 * is a 5 sec cv_broadcast delay when
9204 		 *  mediastate == MTIO_INSERTED
9205 		 */
9206 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9207 		    "st_check_media:waiting for media state change\n");
9208 		while (un->un_mediastate == state) {
9209 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
9210 				mutex_exit(ST_MUTEX);
9211 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9212 				    "st_check_media:waiting for media state "
9213 				    "was interrupted\n");
9214 				rval = EINTR;
9215 				goto done;
9216 			}
9217 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9218 			    "st_check_media:received signal, state=%x\n",
9219 			    un->un_mediastate);
9220 		}
9221 	}
9222 
9223 	/*
9224 	 * if we transitioned to MTIO_INSERTED, media has really been
9225 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
9226 	 * Reset and retry the state change.  If everything is ok, replay
9227 	 * the open() logic.
9228 	 */
9229 	if ((un->un_mediastate == MTIO_INSERTED) &&
9230 	    (un->un_state == ST_STATE_OFFLINE)) {
9231 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9232 		    "st_check_media: calling st_cmd to confirm inserted\n");
9233 
9234 		/*
9235 		 * set this early so that TUR will make it through strategy
9236 		 * without triggering a st_tape_init().  We needed it set
9237 		 * before calling st_tape_init() ourselves anyway.  If TUR
9238 		 * fails, set it back
9239 		 */
9240 		un->un_state = ST_STATE_INITIALIZING;
9241 
9242 		/*
9243 		 * If not reserved fail as getting reservation conflict
9244 		 * will make this hang forever.
9245 		 */
9246 		if ((un->un_rsvd_status &
9247 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9248 			mutex_exit(ST_MUTEX);
9249 			rval = EACCES;
9250 			goto done;
9251 		}
9252 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
9253 		if (rval == EACCES) {
9254 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9255 			    "st_check_media: TUR got Reservation Conflict\n");
9256 			mutex_exit(ST_MUTEX);
9257 			goto done;
9258 		}
9259 		if (rval) {
9260 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9261 			    "st_check_media: TUR failed, going to retry\n");
9262 			un->un_mediastate = prev_state;
9263 			un->un_state = ST_STATE_OFFLINE;
9264 			goto retry;
9265 		}
9266 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9267 		    "st_check_media: media inserted\n");
9268 
9269 		/* this also rewinds the tape */
9270 		rval = st_tape_init(un);
9271 		if (rval != 0) {
9272 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9273 			    "st_check_media : OFFLINE init failure ");
9274 			un->un_state = ST_STATE_OFFLINE;
9275 			un->un_pos.pmode = invalid;
9276 		} else {
9277 			un->un_state = ST_STATE_OPEN_PENDING_IO;
9278 		}
9279 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
9280 	    (un->un_state != ST_STATE_OFFLINE)) {
9281 		/*
9282 		 * supported devices must be rewound before ejection
9283 		 * rewind resets fileno & blkno
9284 		 */
9285 		un->un_laststate = un->un_state;
9286 		un->un_state = ST_STATE_OFFLINE;
9287 	}
9288 	mutex_exit(ST_MUTEX);
9289 done:
9290 	if (token) {
9291 		(void) scsi_watch_request_terminate(token,
9292 		    SCSI_WATCH_TERMINATE_WAIT);
9293 		mutex_enter(ST_MUTEX);
9294 		un->un_swr_token = (opaque_t)NULL;
9295 		mutex_exit(ST_MUTEX);
9296 	}
9297 
9298 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
9299 
9300 	return (rval);
9301 }
9302 
9303 /*
9304  * st_media_watch_cb() is called by scsi_watch_thread for
9305  * verifying the request sense data (if any)
9306  */
9307 static int
9308 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
9309 {
9310 	struct scsi_status *statusp = resultp->statusp;
9311 	struct scsi_extended_sense *sensep = resultp->sensep;
9312 	uchar_t actual_sense_length = resultp->actual_sense_length;
9313 	struct scsi_tape *un;
9314 	enum mtio_state state = MTIO_NONE;
9315 	int instance;
9316 	dev_t dev = (dev_t)arg;
9317 
9318 	instance = MTUNIT(dev);
9319 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
9320 		return (-1);
9321 	}
9322 
9323 	mutex_enter(ST_MUTEX);
9324 	ST_FUNC(ST_DEVINFO, st_media_watch_cb);
9325 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9326 	    "st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
9327 	    *((char *)statusp), (void *)sensep,
9328 	    actual_sense_length);
9329 
9330 
9331 	/*
9332 	 * if there was a check condition then sensep points to valid
9333 	 * sense data
9334 	 * if status was not a check condition but a reservation or busy
9335 	 * status then the new state is MTIO_NONE
9336 	 */
9337 	if (sensep) {
9338 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9339 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
9340 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
9341 
9342 		switch (un->un_dp->type) {
9343 		default:
9344 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9345 			    "st_media_watch_cb: unknown drive type %d, "
9346 			    "default to ST_TYPE_HP\n", un->un_dp->type);
9347 		/* FALLTHROUGH */
9348 
9349 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
9350 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
9351 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
9352 			if (un->un_dp->type == ST_TYPE_FUJI) {
9353 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9354 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
9355 			} else {
9356 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9357 				    "st_media_watch_cb: ST_TYPE_HP\n");
9358 			}
9359 			switch (sensep->es_key) {
9360 			case KEY_UNIT_ATTENTION:
9361 				/* not ready to ready transition */
9362 				/* hp/es_qual_code == 80 on>off>on */
9363 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
9364 				if (sensep->es_add_code == 0x28) {
9365 					state = MTIO_INSERTED;
9366 				}
9367 				break;
9368 			case KEY_NOT_READY:
9369 				/* in process, rewinding or loading */
9370 				if ((sensep->es_add_code == 0x04) &&
9371 				    (sensep->es_qual_code == 0x00)) {
9372 					state = MTIO_EJECTED;
9373 				}
9374 				break;
9375 			}
9376 			break;
9377 
9378 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
9379 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9380 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
9381 			switch (sensep->es_key) {
9382 			case KEY_UNIT_ATTENTION:
9383 				/* operator medium removal request */
9384 				if ((sensep->es_add_code == 0x5a) &&
9385 				    (sensep->es_qual_code == 0x01)) {
9386 					state = MTIO_EJECTED;
9387 				/* not ready to ready transition */
9388 				} else if ((sensep->es_add_code == 0x28) &&
9389 				    (sensep->es_qual_code == 0x00)) {
9390 					state = MTIO_INSERTED;
9391 				}
9392 				break;
9393 			case KEY_NOT_READY:
9394 				/* medium not present */
9395 				if (sensep->es_add_code == 0x3a) {
9396 					state = MTIO_EJECTED;
9397 				}
9398 				break;
9399 			}
9400 			break;
9401 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
9402 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9403 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
9404 			switch (sensep->es_key) {
9405 			case KEY_NOT_READY:
9406 				if ((sensep->es_add_code == 0x04) &&
9407 				    (sensep->es_qual_code == 0x00)) {
9408 					/* volume not mounted? */
9409 					state = MTIO_EJECTED;
9410 				} else if (sensep->es_add_code == 0x3a) {
9411 					state = MTIO_EJECTED;
9412 				}
9413 				break;
9414 			case KEY_UNIT_ATTENTION:
9415 				state = MTIO_EJECTED;
9416 				break;
9417 			}
9418 			break;
9419 
9420 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
9421 			switch (sensep->es_key) {
9422 			case KEY_UNIT_ATTENTION:
9423 				if (sensep->es_add_code == 0x28) {
9424 					state = MTIO_INSERTED;
9425 				}
9426 				break;
9427 			case KEY_NOT_READY:
9428 				if (sensep->es_add_code == 0x04) {
9429 					/* in transition but could be either */
9430 					state = un->un_specified_mediastate;
9431 				} else if ((sensep->es_add_code == 0x3a) &&
9432 				    (sensep->es_qual_code == 0x00)) {
9433 					state = MTIO_EJECTED;
9434 				}
9435 				break;
9436 			}
9437 			break;
9438 		}
9439 	} else if (*((char *)statusp) == STATUS_GOOD) {
9440 		state = MTIO_INSERTED;
9441 	}
9442 
9443 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9444 	    "st_media_watch_cb:state=%x, specified=%x\n",
9445 	    state, un->un_specified_mediastate);
9446 
9447 	/*
9448 	 * now signal the waiting thread if this is *not* the specified state;
9449 	 * delay the signal if the state is MTIO_INSERTED
9450 	 * to allow the target to recover
9451 	 */
9452 	if (state != un->un_specified_mediastate) {
9453 		un->un_mediastate = state;
9454 		if (state == MTIO_INSERTED) {
9455 			/*
9456 			 * delay the signal to give the drive a chance
9457 			 * to do what it apparently needs to do
9458 			 */
9459 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9460 			    "st_media_watch_cb:delayed cv_broadcast\n");
9461 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
9462 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
9463 		} else {
9464 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9465 			    "st_media_watch_cb:immediate cv_broadcast\n");
9466 			cv_broadcast(&un->un_state_cv);
9467 		}
9468 	}
9469 	mutex_exit(ST_MUTEX);
9470 	return (0);
9471 }
9472 
9473 /*
9474  * delayed cv_broadcast to allow for target to recover
9475  * from media insertion
9476  */
9477 static void
9478 st_delayed_cv_broadcast(void *arg)
9479 {
9480 	struct scsi_tape *un = arg;
9481 
9482 	ST_FUNC(ST_DEVINFO, st_delayed_cv_broadcast);
9483 
9484 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9485 	    "st_delayed_cv_broadcast:delayed cv_broadcast\n");
9486 
9487 	mutex_enter(ST_MUTEX);
9488 	cv_broadcast(&un->un_state_cv);
9489 	mutex_exit(ST_MUTEX);
9490 }
9491 
9492 /*
9493  * restart cmd currently at the start of the waitq
9494  */
9495 static void
9496 st_start_restart(void *arg)
9497 {
9498 	struct scsi_tape *un = arg;
9499 
9500 	ST_FUNC(ST_DEVINFO, st_start_restart);
9501 
9502 	ASSERT(un != NULL);
9503 
9504 	mutex_enter(ST_MUTEX);
9505 
9506 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_tran_restart()\n");
9507 
9508 	st_start(un);
9509 
9510 	mutex_exit(ST_MUTEX);
9511 }
9512 
9513 
9514 /*
9515  * Command completion processing
9516  *
9517  */
9518 static void
9519 st_intr(struct scsi_pkt *pkt)
9520 {
9521 	recov_info *rcv = pkt->pkt_private;
9522 	struct buf *bp = rcv->cmd_bp;
9523 	struct scsi_tape *un;
9524 	errstate action = COMMAND_DONE;
9525 	clock_t	timout;
9526 	int	status;
9527 
9528 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
9529 
9530 	ST_FUNC(ST_DEVINFO, st_intr);
9531 
9532 	ASSERT(un != NULL);
9533 
9534 	mutex_enter(ST_MUTEX);
9535 
9536 	ASSERT(bp != un->un_recov_buf);
9537 
9538 	un->un_rqs_state &= ~(ST_RQS_ERROR);
9539 
9540 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
9541 
9542 	if (pkt->pkt_reason != CMD_CMPLT) {
9543 		ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9544 		    "Unhappy packet status reason = %s statistics = 0x%x\n",
9545 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9546 
9547 		/* If device has gone away not much else to do */
9548 		if (pkt->pkt_reason == CMD_DEV_GONE) {
9549 			action = COMMAND_DONE_ERROR;
9550 		} else if ((pkt == un->un_rqs) ||
9551 		    (un->un_state == ST_STATE_SENSING)) {
9552 			ASSERT(pkt == un->un_rqs);
9553 			ASSERT(un->un_state == ST_STATE_SENSING);
9554 			un->un_state = un->un_laststate;
9555 			rcv->cmd_bp = un->un_rqs_bp;
9556 			ST_DO_ERRSTATS(un, st_transerrs);
9557 			action = COMMAND_DONE_ERROR;
9558 		} else {
9559 			action = st_handle_incomplete(un, bp);
9560 		}
9561 	/*
9562 	 * At this point we know that the command was successfully
9563 	 * completed. Now what?
9564 	 */
9565 	} else if ((pkt == un->un_rqs) || (un->un_state == ST_STATE_SENSING)) {
9566 		/*
9567 		 * okay. We were running a REQUEST SENSE. Find
9568 		 * out what to do next.
9569 		 */
9570 		ASSERT(pkt == un->un_rqs);
9571 		ASSERT(un->un_state == ST_STATE_SENSING);
9572 		scsi_sync_pkt(pkt);
9573 		action = st_handle_sense(un, bp, &un->un_pos);
9574 		/*
9575 		 * Make rqs isn't going to be retied.
9576 		 */
9577 		if (action != QUE_BUSY_COMMAND && action != QUE_COMMAND) {
9578 			/*
9579 			 * set pkt back to original packet in case we will have
9580 			 * to requeue it
9581 			 */
9582 			pkt = BP_PKT(bp);
9583 			rcv->cmd_bp = un->un_rqs_bp;
9584 			/*
9585 			 * some actions are based on un_state, hence
9586 			 * restore the state st was in before ST_STATE_SENSING.
9587 			 */
9588 			un->un_state = un->un_laststate;
9589 		}
9590 
9591 	} else if (un->un_arq_enabled && (pkt->pkt_state & STATE_ARQ_DONE)) {
9592 		/*
9593 		 * the transport layer successfully completed an autorqsense
9594 		 */
9595 		action = st_handle_autosense(un, bp, &un->un_pos);
9596 
9597 	} else  if ((SCBP(pkt)->sts_busy) ||
9598 	    (SCBP(pkt)->sts_chk) ||
9599 	    (SCBP(pkt)->sts_vu7)) {
9600 		/*
9601 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
9602 		 * to see if the status bits we're okay. If a request sense
9603 		 * is to be run, that will happen.
9604 		 */
9605 		action = st_check_error(un, pkt);
9606 	}
9607 
9608 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9609 		switch (action) {
9610 			case QUE_COMMAND:
9611 				/*
9612 				 * return cmd to head to the queue
9613 				 * since we are suspending so that
9614 				 * it gets restarted during resume
9615 				 */
9616 				st_add_to_queue(&un->un_runqf, &un->un_runql,
9617 				    un->un_runqf, bp);
9618 
9619 				action = JUST_RETURN;
9620 				break;
9621 
9622 			case QUE_SENSE:
9623 				action = COMMAND_DONE_ERROR;
9624 				break;
9625 
9626 			default:
9627 				break;
9628 		}
9629 	}
9630 
9631 	/*
9632 	 * check for undetected path failover.
9633 	 */
9634 	if ((un->un_multipath) &&
9635 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
9636 		if (un->un_state > ST_STATE_OPENING) {
9637 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
9638 			    "Failover detected, action is %s\n",
9639 			    errstatenames[action]);
9640 			if (action == COMMAND_DONE) {
9641 				action = PATH_FAILED;
9642 			}
9643 		}
9644 		un->un_last_path_instance = pkt->pkt_path_instance;
9645 	}
9646 
9647 	/*
9648 	 * Restore old state if we were sensing.
9649 	 */
9650 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
9651 		un->un_state = un->un_laststate;
9652 	}
9653 
9654 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9655 	    "st_intr: pkt=%p, bp=%p, action=%s, status=%x\n",
9656 	    (void *)pkt, (void *)bp, errstatenames[action], SCBP_C(pkt));
9657 
9658 again:
9659 	switch (action) {
9660 	case COMMAND_DONE_EACCES:
9661 		/* this is to report a reservation conflict */
9662 		st_bioerror(bp, EACCES);
9663 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
9664 		    "Reservation Conflict \n");
9665 		un->un_pos.pmode = invalid;
9666 
9667 		/*FALLTHROUGH*/
9668 	case COMMAND_DONE_ERROR:
9669 		if (un->un_pos.eof < ST_EOT_PENDING &&
9670 		    un->un_state >= ST_STATE_OPEN) {
9671 			/*
9672 			 * all errors set state of the tape to 'unknown'
9673 			 * unless we're at EOT or are doing append testing.
9674 			 * If sense key was illegal request, preserve state.
9675 			 */
9676 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
9677 				un->un_pos.pmode = invalid;
9678 			}
9679 		}
9680 
9681 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9682 		/*
9683 		 * since we have an error (COMMAND_DONE_ERROR), we want to
9684 		 * make sure an error ocurrs, so make sure at least EIO is
9685 		 * returned
9686 		 */
9687 		if (geterror(bp) == 0)
9688 			st_bioerror(bp, EIO);
9689 
9690 		st_set_pe_flag(un);
9691 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9692 		    (un->un_errno == EIO)) {
9693 			un->un_rqs_state &= ~(ST_RQS_VALID);
9694 		}
9695 		break;
9696 
9697 	case COMMAND_DONE_ERROR_RECOVERED:
9698 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9699 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
9700 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
9701 		if (geterror(bp) == 0) {
9702 			st_bioerror(bp, EIO);
9703 		}
9704 		st_set_pe_flag(un);
9705 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
9706 		    (un->un_errno == EIO)) {
9707 			un->un_rqs_state &= ~(ST_RQS_VALID);
9708 		}
9709 		/*FALLTHROUGH*/
9710 	case COMMAND_DONE:
9711 		st_set_state(un, bp);
9712 		break;
9713 
9714 	case QUE_SENSE:
9715 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
9716 			goto sense_error;
9717 
9718 		if (un->un_state != ST_STATE_SENSING) {
9719 			un->un_laststate = un->un_state;
9720 			un->un_state = ST_STATE_SENSING;
9721 		}
9722 
9723 		/*
9724 		 * zero the sense data.
9725 		 */
9726 		bzero(un->un_rqs->pkt_scbp, SENSE_LENGTH);
9727 
9728 		/*
9729 		 * If this is not a retry on QUE_SENSE point to the original
9730 		 * bp of the command that got us here.
9731 		 */
9732 		if (pkt != un->un_rqs) {
9733 			((recov_info *)un->un_rqs->pkt_private)->cmd_bp = bp;
9734 		}
9735 
9736 		if (un->un_throttle) {
9737 			un->un_last_throttle = un->un_throttle;
9738 			un->un_throttle = 0;
9739 		}
9740 
9741 		ST_CDB(ST_DEVINFO, "Queue sense CDB",
9742 		    (char *)BP_PKT(bp)->pkt_cdbp);
9743 
9744 		/*
9745 		 * never retry this, some other command will have nuked the
9746 		 * sense, anyway
9747 		 */
9748 		status = st_transport(un, un->un_rqs);
9749 
9750 		if (un->un_last_throttle) {
9751 			un->un_throttle = un->un_last_throttle;
9752 		}
9753 
9754 		if (status == TRAN_ACCEPT) {
9755 			mutex_exit(ST_MUTEX);
9756 			return;
9757 		}
9758 		if (status != TRAN_BUSY)
9759 			ST_DO_ERRSTATS(un, st_transerrs);
9760 sense_error:
9761 		un->un_pos.pmode = invalid;
9762 		st_bioerror(bp, EIO);
9763 		st_set_pe_flag(un);
9764 		break;
9765 
9766 	case QUE_BUSY_COMMAND:
9767 		/* longish timeout */
9768 		timout = ST_STATUS_BUSY_TIMEOUT;
9769 		goto que_it_up;
9770 
9771 	case QUE_COMMAND:
9772 		/* short timeout */
9773 		timout = ST_TRAN_BUSY_TIMEOUT;
9774 que_it_up:
9775 		/*
9776 		 * let st_handle_intr_busy put this bp back on waitq and make
9777 		 * checks to see if it is ok to requeue the command.
9778 		 */
9779 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9780 
9781 		/*
9782 		 * Save the throttle before setting up the timeout
9783 		 */
9784 		if (un->un_throttle) {
9785 			un->un_last_throttle = un->un_throttle;
9786 		}
9787 		mutex_exit(ST_MUTEX);
9788 		if (st_handle_intr_busy(un, bp, timout) == 0)
9789 			return;		/* timeout is setup again */
9790 
9791 		mutex_enter(ST_MUTEX);
9792 		un->un_pos.pmode = invalid;
9793 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9794 		st_bioerror(bp, EIO);
9795 		st_set_pe_flag(un);
9796 		break;
9797 
9798 	case QUE_LAST_COMMAND:
9799 
9800 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
9801 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9802 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
9803 			goto last_command_error;
9804 		}
9805 		mutex_exit(ST_MUTEX);
9806 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
9807 			return;
9808 		mutex_enter(ST_MUTEX);
9809 last_command_error:
9810 		un->un_err_resid = bp->b_resid = bp->b_bcount;
9811 		un->un_pos.pmode = invalid;
9812 		st_bioerror(bp, EIO);
9813 		st_set_pe_flag(un);
9814 		break;
9815 
9816 	case COMMAND_TIMEOUT:
9817 	case DEVICE_RESET:
9818 	case DEVICE_TAMPER:
9819 	case ATTEMPT_RETRY:
9820 	case PATH_FAILED:
9821 		ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
9822 		    "Command Recovery called on %s status\n",
9823 		    errstatenames[action]);
9824 		action = st_command_recovery(un, pkt, action);
9825 		goto again;
9826 
9827 	default:
9828 		ASSERT(0);
9829 		/* FALLTHRU */
9830 	case JUST_RETURN:
9831 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9832 		mutex_exit(ST_MUTEX);
9833 		return;
9834 	}
9835 
9836 	ST_DO_KSTATS(bp, kstat_runq_exit);
9837 	st_done_and_mutex_exit(un, bp);
9838 }
9839 
9840 static errstate
9841 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
9842 {
9843 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
9844 	recov_info *rinfo;
9845 	errstate rval = COMMAND_DONE_ERROR;
9846 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
9847 	    un->un_rqs : BP_PKT(bp);
9848 	int result;
9849 
9850 	ST_FUNC(ST_DEVINFO, st_handle_incomplete);
9851 
9852 	rinfo = (recov_info *)pkt->pkt_private;
9853 
9854 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9855 	    "st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
9856 
9857 	ASSERT(mutex_owned(ST_MUTEX));
9858 
9859 	switch (pkt->pkt_reason) {
9860 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
9861 		/*
9862 		 * this occurs when accessing a powered down drive, no
9863 		 * need to complain; just fail the open
9864 		 */
9865 		ST_CDB(ST_DEVINFO, "Incomplete CDB", (char *)pkt->pkt_cdbp);
9866 
9867 		/*
9868 		 * if we have commands outstanding in HBA, and a command
9869 		 * comes back incomplete, we're hosed, so reset target
9870 		 * If we have the bus, but cmd_incomplete, we probably just
9871 		 * have a failed selection, so don't reset the target, just
9872 		 * requeue the command and try again
9873 		 */
9874 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
9875 			goto reset_target;
9876 		}
9877 
9878 		/*
9879 		 * Retry selection a couple more times if we're
9880 		 * open.  If opening, we only try just once to
9881 		 * reduce probe time for nonexistant devices.
9882 		 */
9883 		if ((un->un_laststate > ST_STATE_OPENING) &&
9884 		    (rinfo->pkt_retry_cnt < st_selection_retry_count)) {
9885 			/* XXX check retriable? */
9886 			rval = QUE_COMMAND;
9887 		}
9888 		ST_DO_ERRSTATS(un, st_transerrs);
9889 		break;
9890 
9891 	case CMD_ABORTED:
9892 		/*
9893 		 * most likely this is caused by flush-on-error support. If
9894 		 * it was not there, the we're in trouble.
9895 		 */
9896 		if (!un->un_flush_on_errors) {
9897 			un->un_status = SUN_KEY_FATAL;
9898 			goto reset_target;
9899 		}
9900 
9901 		st_set_pe_errno(un);
9902 		bioerror(bp, un->un_errno);
9903 		if (un->un_errno)
9904 			return (COMMAND_DONE_ERROR);
9905 		else
9906 			return (COMMAND_DONE);
9907 
9908 	case CMD_TIMEOUT:	/* Command timed out */
9909 		un->un_status = SUN_KEY_TIMEOUT;
9910 		return (COMMAND_TIMEOUT);
9911 
9912 	case CMD_TRAN_ERR:
9913 	case CMD_RESET:
9914 		if (pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET)) {
9915 			if ((un->un_rsvd_status &
9916 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
9917 			    ST_RESERVE) {
9918 				un->un_rsvd_status |= ST_LOST_RESERVE;
9919 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
9920 				    "Lost Reservation\n");
9921 			}
9922 			rval = DEVICE_RESET;
9923 			return (rval);
9924 		}
9925 		if (pkt->pkt_statistics & (STAT_ABORTED | STAT_TERMINATED)) {
9926 			rval = DEVICE_RESET;
9927 			return (rval);
9928 		}
9929 		/*FALLTHROUGH*/
9930 	default:
9931 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9932 		    "Unhandled packet status reason = %s statistics = 0x%x\n",
9933 		    scsi_rname(pkt->pkt_reason), pkt->pkt_statistics);
9934 reset_target:
9935 
9936 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9937 		    "transport completed with %s\n",
9938 		    scsi_rname(pkt->pkt_reason));
9939 		ST_DO_ERRSTATS(un, st_transerrs);
9940 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
9941 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
9942 		    STAT_ABORTED)) == 0)) {
9943 
9944 			/*
9945 			 * If we haven't reserved the drive don't reset it.
9946 			 */
9947 			if ((un->un_rsvd_status &
9948 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
9949 				return (rval);
9950 			}
9951 
9952 			/*
9953 			 * if we aren't lost yet we will be soon.
9954 			 */
9955 			un->un_pos.pmode = invalid;
9956 
9957 			result = st_reset(un, RESET_LUN);
9958 
9959 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
9960 				/* no hope left to recover */
9961 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
9962 				    "recovery by resets failed\n");
9963 				return (rval);
9964 			}
9965 		}
9966 	}
9967 
9968 
9969 	if (rinfo->pkt_retry_cnt++ < st_retry_count) {
9970 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
9971 			rval = QUE_COMMAND;
9972 		} else if (bp == un->un_sbufp) {
9973 			if (rinfo->privatelen == sizeof (recov_info)) {
9974 				if (rinfo->cmd_attrib->retriable) {
9975 					/*
9976 					 * These commands can be rerun
9977 					 * with impunity
9978 					 */
9979 					rval = QUE_COMMAND;
9980 				}
9981 			} else {
9982 				cmd_attribute const *attrib;
9983 				attrib =
9984 				    st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
9985 				if (attrib->retriable) {
9986 					rval = QUE_COMMAND;
9987 				}
9988 			}
9989 		}
9990 	} else {
9991 		rval = COMMAND_DONE_ERROR;
9992 	}
9993 
9994 	if (un->un_state >= ST_STATE_OPEN) {
9995 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
9996 		    fail, scsi_rname(pkt->pkt_reason),
9997 		    (rval == COMMAND_DONE_ERROR)?
9998 		    "giving up" : "retrying command");
9999 	}
10000 	return (rval);
10001 }
10002 
10003 /*
10004  * if the device is busy, then put this bp back on the waitq, on the
10005  * interrupt thread, where we want the head of the queue and not the
10006  * end
10007  *
10008  * The callers of this routine should take measures to save the
10009  * un_throttle in un_last_throttle which will be restored in
10010  * st_intr_restart(). The only exception should be st_intr_restart()
10011  * calling this routine for which the saving is already done.
10012  */
10013 static int
10014 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
10015 	clock_t timeout_interval)
10016 {
10017 
10018 	int queued;
10019 	int rval = 0;
10020 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
10021 
10022 	mutex_enter(ST_MUTEX);
10023 
10024 	ST_FUNC(ST_DEVINFO, st_handle_intr_busy);
10025 
10026 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10027 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
10028 
10029 	if ((bp != un->un_sbufp) && (bp != un->un_recov_buf)) {
10030 		queued = 1;
10031 	} else {
10032 		queued = 0;
10033 	}
10034 
10035 	/*
10036 	 * Check to see if we hit the retry timeout. We check to make sure
10037 	 * this is the first one on the runq and make sure we have not
10038 	 * queued up any more, so this one has to be the last on the list
10039 	 * also. If it is not, we have to fail.  If it is not the first, but
10040 	 * is the last we are in trouble anyway, as we are in the interrupt
10041 	 * context here.
10042 	 */
10043 	if ((pktinfo->str_retry_cnt++ > st_retry_count) ||
10044 	    ((un->un_runqf != bp) && (un->un_runql != bp) && (queued))) {
10045 		rval = -1;
10046 		goto exit;
10047 	}
10048 
10049 	/* put the bp back on the waitq */
10050 	if (queued) {
10051 		(void) st_remove_from_queue(&un->un_runqf, &un->un_runql, bp);
10052 		st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quef, bp);
10053 	}
10054 
10055 	/*
10056 	 * We don't want any other commands being started in the mean time.
10057 	 * If start had just released mutex after putting something on the
10058 	 * runq, we won't even get here.
10059 	 */
10060 	un->un_throttle = 0;
10061 
10062 	/*
10063 	 * send a marker pkt, if appropriate
10064 	 */
10065 	st_hba_unflush(un);
10066 
10067 	/*
10068 	 * all queues are aligned, we are just waiting to
10069 	 * transport
10070 	 */
10071 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
10072 
10073 exit:
10074 	mutex_exit(ST_MUTEX);
10075 	return (rval);
10076 }
10077 
10078 /*
10079  * To get one error entry from error stack
10080  */
10081 static int
10082 st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag)
10083 {
10084 #ifdef _MULTI_DATAMODEL
10085 	/*
10086 	 * For use when a 32 bit app makes a call into a
10087 	 * 64 bit ioctl
10088 	 */
10089 	struct mterror_entry32 err_entry32;
10090 #endif /* _MULTI_DATAMODEL */
10091 
10092 	int rval = 0;
10093 	struct mterror_entry err_entry;
10094 	struct mterror_entry_stack *err_link_entry_p;
10095 	size_t arq_status_len_in, arq_status_len_kr;
10096 
10097 	ST_FUNC(ST_DEVINFO, st_get_error_entry);
10098 
10099 	ASSERT(mutex_owned(ST_MUTEX));
10100 
10101 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10102 	    "st_get_error_entry()\n");
10103 
10104 	/*
10105 	 * if error record stack empty, return ENXIO
10106 	 */
10107 	if (un->un_error_entry_stk == NULL) {
10108 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10109 		    "st_get_error_entry: Error Entry Stack Empty!\n");
10110 		rval = ENXIO;
10111 		goto ret;
10112 	}
10113 
10114 	/*
10115 	 * get the top entry from stack
10116 	 */
10117 	err_link_entry_p = un->un_error_entry_stk;
10118 	arq_status_len_kr =
10119 	    err_link_entry_p->mtees_entry.mtee_arq_status_len;
10120 
10121 #ifdef _MULTI_DATAMODEL
10122 	switch (ddi_model_convert_from(flag & FMODELS)) {
10123 	case DDI_MODEL_ILP32:
10124 		if (ddi_copyin((void *)arg, &err_entry32,
10125 		    MTERROR_ENTRY_SIZE_32, flag)) {
10126 			rval = EFAULT;
10127 			goto ret;
10128 		}
10129 
10130 		arq_status_len_in =
10131 		    (size_t)err_entry32.mtee_arq_status_len;
10132 
10133 		err_entry32.mtee_cdb_len =
10134 		    (size32_t)err_link_entry_p->mtees_entry.mtee_cdb_len;
10135 
10136 		if (arq_status_len_in > arq_status_len_kr)
10137 			err_entry32.mtee_arq_status_len =
10138 			    (size32_t)arq_status_len_kr;
10139 
10140 		if (ddi_copyout(
10141 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10142 		    (void *)(uintptr_t)err_entry32.mtee_cdb_buf,
10143 		    err_entry32.mtee_cdb_len, flag)) {
10144 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10145 			    "st_get_error_entry: Copy cdb buffer error!");
10146 			rval = EFAULT;
10147 		}
10148 
10149 		if (ddi_copyout(
10150 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10151 		    (void *)(uintptr_t)err_entry32.mtee_arq_status,
10152 		    err_entry32.mtee_arq_status_len, flag)) {
10153 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10154 			    "st_get_error_entry: copy arq status error!");
10155 			rval = EFAULT;
10156 		}
10157 
10158 		if (ddi_copyout(&err_entry32, (void *)arg,
10159 		    MTERROR_ENTRY_SIZE_32, flag)) {
10160 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10161 			    "st_get_error_entry: copy arq status out error!");
10162 			rval = EFAULT;
10163 		}
10164 		break;
10165 
10166 	case DDI_MODEL_NONE:
10167 		if (ddi_copyin((void *)arg, &err_entry,
10168 		    MTERROR_ENTRY_SIZE_64, flag)) {
10169 			rval = EFAULT;
10170 			goto ret;
10171 		}
10172 		arq_status_len_in = err_entry.mtee_arq_status_len;
10173 
10174 		err_entry.mtee_cdb_len =
10175 		    err_link_entry_p->mtees_entry.mtee_cdb_len;
10176 
10177 		if (arq_status_len_in > arq_status_len_kr)
10178 			err_entry.mtee_arq_status_len =
10179 			    arq_status_len_kr;
10180 
10181 		if (ddi_copyout(
10182 		    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10183 		    err_entry.mtee_cdb_buf,
10184 		    err_entry.mtee_cdb_len, flag)) {
10185 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10186 			    "st_get_error_entry: Copy cdb buffer error!");
10187 			rval = EFAULT;
10188 		}
10189 
10190 		if (ddi_copyout(
10191 		    err_link_entry_p->mtees_entry.mtee_arq_status,
10192 		    err_entry.mtee_arq_status,
10193 		    err_entry.mtee_arq_status_len, flag)) {
10194 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10195 			    "st_get_error_entry: copy arq status error!");
10196 			rval = EFAULT;
10197 		}
10198 
10199 		if (ddi_copyout(&err_entry, (void *)arg,
10200 		    MTERROR_ENTRY_SIZE_64, flag)) {
10201 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10202 			    "st_get_error_entry: copy arq status out error!");
10203 			rval = EFAULT;
10204 		}
10205 		break;
10206 	}
10207 #else /* _MULTI_DATAMODEL */
10208 	if (ddi_copyin((void *)arg, &err_entry,
10209 	    MTERROR_ENTRY_SIZE_64, flag)) {
10210 		rval = EFAULT;
10211 		goto ret;
10212 	}
10213 	arq_status_len_in = err_entry.mtee_arq_status_len;
10214 
10215 	err_entry.mtee_cdb_len =
10216 	    err_link_entry_p->mtees_entry.mtee_cdb_len;
10217 
10218 	if (arq_status_len_in > arq_status_len_kr)
10219 		err_entry.mtee_arq_status_len =
10220 		    arq_status_len_kr;
10221 
10222 	if (ddi_copyout(
10223 	    err_link_entry_p->mtees_entry.mtee_cdb_buf,
10224 	    err_entry.mtee_cdb_buf,
10225 	    err_entry.mtee_cdb_len, flag)) {
10226 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10227 		    "st_get_error_entry: Copy cdb buffer error!");
10228 		rval = EFAULT;
10229 	}
10230 
10231 	if (ddi_copyout(
10232 	    err_link_entry_p->mtees_entry.mtee_arq_status,
10233 	    err_entry.mtee_arq_status,
10234 	    err_entry.mtee_arq_status_len, flag)) {
10235 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10236 		    "st_get_error_entry: copy arq status buffer error!");
10237 		rval = EFAULT;
10238 	}
10239 
10240 	if (ddi_copyout(&err_entry, (void *)arg,
10241 	    MTERROR_ENTRY_SIZE_64, flag)) {
10242 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10243 		    "st_get_error_entry: copy arq status out error!");
10244 		rval = EFAULT;
10245 	}
10246 #endif /* _MULTI_DATAMODEL */
10247 
10248 	/*
10249 	 * update stack
10250 	 */
10251 	un->un_error_entry_stk = err_link_entry_p->mtees_nextp;
10252 
10253 	kmem_free(err_link_entry_p->mtees_entry.mtee_cdb_buf,
10254 	    err_link_entry_p->mtees_entry.mtee_cdb_len);
10255 	err_link_entry_p->mtees_entry.mtee_cdb_buf = NULL;
10256 
10257 	kmem_free(err_link_entry_p->mtees_entry.mtee_arq_status,
10258 	    SECMDS_STATUS_SIZE);
10259 	err_link_entry_p->mtees_entry.mtee_arq_status = NULL;
10260 
10261 	kmem_free(err_link_entry_p, MTERROR_LINK_ENTRY_SIZE);
10262 	err_link_entry_p = NULL;
10263 ret:
10264 	return (rval);
10265 }
10266 
10267 /*
10268  * MTIOCGETERROR ioctl needs to retrieve the current sense data along with
10269  * the scsi CDB command which causes the error and generates sense data and
10270  * the scsi status.
10271  *
10272  *      error-record stack
10273  *
10274  *
10275  *             TOP                                     BOTTOM
10276  *              ------------------------------------------
10277  *              |   0   |   1   |   2   |   ...  |   n   |
10278  *              ------------------------------------------
10279  *                  ^
10280  *                  |
10281  *       pointer to error entry
10282  *
10283  * when st driver generates one sense data record, it creates a error-entry
10284  * and pushes it onto the stack.
10285  *
10286  */
10287 
10288 static void
10289 st_update_error_stack(struct scsi_tape *un,
10290 			struct scsi_pkt *pkt,
10291 			struct scsi_arq_status *cmd)
10292 {
10293 	struct mterror_entry_stack *err_entry_tmp;
10294 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
10295 	size_t cdblen = scsi_cdb_size[CDB_GROUPID(cdbp[0])];
10296 
10297 	ST_FUNC(ST_DEVINFO, st_update_error_stack);
10298 
10299 	ASSERT(mutex_owned(ST_MUTEX));
10300 
10301 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10302 	    "st_update_error_stack()\n");
10303 
10304 	ASSERT(cmd);
10305 	ASSERT(cdbp);
10306 	if (cdblen == 0) {
10307 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10308 		    "st_update_error_stack: CDB length error!\n");
10309 		return;
10310 	}
10311 
10312 	err_entry_tmp = kmem_alloc(MTERROR_LINK_ENTRY_SIZE, KM_SLEEP);
10313 	ASSERT(err_entry_tmp != NULL);
10314 
10315 	err_entry_tmp->mtees_entry.mtee_cdb_buf =
10316 	    kmem_alloc(cdblen, KM_SLEEP);
10317 	ASSERT(err_entry_tmp->mtees_entry.mtee_cdb_buf != NULL);
10318 
10319 	err_entry_tmp->mtees_entry.mtee_arq_status =
10320 	    kmem_alloc(SECMDS_STATUS_SIZE, KM_SLEEP);
10321 	ASSERT(err_entry_tmp->mtees_entry.mtee_arq_status != NULL);
10322 
10323 	/*
10324 	 * copy cdb command & length to current error entry
10325 	 */
10326 	err_entry_tmp->mtees_entry.mtee_cdb_len = cdblen;
10327 	bcopy(cdbp, err_entry_tmp->mtees_entry.mtee_cdb_buf, cdblen);
10328 
10329 	/*
10330 	 * copy scsi status length to current error entry
10331 	 */
10332 	err_entry_tmp->mtees_entry.mtee_arq_status_len =
10333 	    SECMDS_STATUS_SIZE;
10334 
10335 	/*
10336 	 * copy sense data and scsi status to current error entry
10337 	 */
10338 	bcopy(cmd, err_entry_tmp->mtees_entry.mtee_arq_status,
10339 	    SECMDS_STATUS_SIZE);
10340 
10341 	err_entry_tmp->mtees_nextp = un->un_error_entry_stk;
10342 	un->un_error_entry_stk = err_entry_tmp;
10343 
10344 }
10345 
10346 /*
10347  * Empty all the error entry in stack
10348  */
10349 static void
10350 st_empty_error_stack(struct scsi_tape *un)
10351 {
10352 	struct mterror_entry_stack *linkp;
10353 
10354 	ST_FUNC(ST_DEVINFO, st_empty_error_stack);
10355 
10356 	ASSERT(mutex_owned(ST_MUTEX));
10357 
10358 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10359 	    "st_empty_entry_stack()\n");
10360 
10361 	while (un->un_error_entry_stk != NULL) {
10362 		linkp = un->un_error_entry_stk;
10363 		un->un_error_entry_stk =
10364 		    un->un_error_entry_stk->mtees_nextp;
10365 
10366 		if (linkp->mtees_entry.mtee_cdb_buf != NULL)
10367 			kmem_free(linkp->mtees_entry.mtee_cdb_buf,
10368 			    linkp->mtees_entry.mtee_cdb_len);
10369 
10370 		if (linkp->mtees_entry.mtee_arq_status != NULL)
10371 			kmem_free(linkp->mtees_entry.mtee_arq_status,
10372 			    linkp->mtees_entry.mtee_arq_status_len);
10373 
10374 		kmem_free(linkp, MTERROR_LINK_ENTRY_SIZE);
10375 		linkp = NULL;
10376 	}
10377 }
10378 
10379 static errstate
10380 st_handle_sense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10381 {
10382 	struct scsi_pkt *pkt = BP_PKT(bp);
10383 	struct scsi_pkt *rqpkt = un->un_rqs;
10384 	struct scsi_arq_status arqstat;
10385 	recov_info *rcif = pkt->pkt_private;
10386 
10387 	errstate rval = COMMAND_DONE_ERROR;
10388 	int amt;
10389 
10390 	ST_FUNC(ST_DEVINFO, st_handle_sense);
10391 
10392 	ASSERT(mutex_owned(ST_MUTEX));
10393 
10394 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10395 	    "st_handle_sense()\n");
10396 
10397 	if (SCBP(rqpkt)->sts_busy) {
10398 		if (rcif->privatelen == sizeof (recov_info)) {
10399 			ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
10400 			    "Attempt recovery of busy unit on request sense\n");
10401 			rval = ATTEMPT_RETRY;
10402 		} else if (rcif->pkt_retry_cnt++ < st_retry_count) {
10403 			ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10404 			    "Retry busy unit on request sense\n");
10405 			rval = QUE_BUSY_COMMAND;
10406 		}
10407 		return (rval);
10408 	} else if (SCBP(rqpkt)->sts_chk) {
10409 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10410 		    "Check Condition on REQUEST SENSE\n");
10411 		return (rval);
10412 	}
10413 
10414 	/*
10415 	 * Make sure there is sense data to look at.
10416 	 */
10417 	if ((rqpkt->pkt_state & (STATE_GOT_BUS | STATE_GOT_TARGET |
10418 	    STATE_SENT_CMD | STATE_GOT_STATUS)) != (STATE_GOT_BUS |
10419 	    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) {
10420 		return (rval);
10421 	}
10422 
10423 	/* was there enough data? */
10424 	amt = (int)MAX_SENSE_LENGTH - rqpkt->pkt_resid;
10425 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
10426 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10427 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10428 		    "REQUEST SENSE couldn't get sense data\n");
10429 		return (rval);
10430 	}
10431 
10432 	bcopy(SCBP(pkt), &arqstat.sts_status,
10433 	    sizeof (struct scsi_status));
10434 	bcopy(SCBP(rqpkt), &arqstat.sts_rqpkt_status,
10435 	    sizeof (struct scsi_status));
10436 	arqstat.sts_rqpkt_reason = rqpkt->pkt_reason;
10437 	arqstat.sts_rqpkt_resid = rqpkt->pkt_resid;
10438 	arqstat.sts_rqpkt_state = rqpkt->pkt_state;
10439 	arqstat.sts_rqpkt_statistics = rqpkt->pkt_statistics;
10440 	bcopy(ST_RQSENSE, &arqstat.sts_sensedata, SENSE_LENGTH);
10441 
10442 	/*
10443 	 * copy one arqstat entry in the sense data buffer
10444 	 */
10445 	st_update_error_stack(un, pkt, &arqstat);
10446 	return (st_decode_sense(un, bp, amt, &arqstat, pos));
10447 }
10448 
10449 static errstate
10450 st_handle_autosense(struct scsi_tape *un, struct buf *bp, tapepos_t *pos)
10451 {
10452 	struct scsi_pkt *pkt = BP_PKT(bp);
10453 	struct scsi_arq_status *arqstat =
10454 	    (struct scsi_arq_status *)pkt->pkt_scbp;
10455 	errstate rval = COMMAND_DONE_ERROR;
10456 	int amt;
10457 
10458 	ST_FUNC(ST_DEVINFO, st_handle_autosense);
10459 
10460 	ASSERT(mutex_owned(ST_MUTEX));
10461 
10462 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10463 	    "st_handle_autosense()\n");
10464 
10465 	if (arqstat->sts_rqpkt_status.sts_busy) {
10466 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
10467 		    "busy unit on request sense\n");
10468 		/*
10469 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
10470 		 * the disadvantage is that we do not have any delay for the
10471 		 * second retry of rqsense and we have to keep a packet around
10472 		 */
10473 		return (QUE_SENSE);
10474 
10475 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
10476 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10477 		    "transport error on REQUEST SENSE\n");
10478 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
10479 		    ((arqstat->sts_rqpkt_statistics &
10480 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
10481 			if (st_reset(un, RESET_LUN) == 0) {
10482 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10483 				    "recovery by resets failed\n");
10484 			}
10485 		}
10486 		return (rval);
10487 
10488 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
10489 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10490 		    "Check Condition on REQUEST SENSE\n");
10491 		return (rval);
10492 	}
10493 
10494 
10495 	/* was there enough data? */
10496 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10497 		amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10498 	} else {
10499 		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
10500 			amt = (int)MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10501 		} else {
10502 			amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
10503 		}
10504 	}
10505 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
10506 	    (amt < SUN_MIN_SENSE_LENGTH)) {
10507 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10508 		    "REQUEST SENSE couldn't get sense data\n");
10509 		return (rval);
10510 	}
10511 
10512 	if (pkt->pkt_state & STATE_XARQ_DONE) {
10513 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, MAX_SENSE_LENGTH);
10514 	} else {
10515 		bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
10516 	}
10517 
10518 	/*
10519 	 * copy one arqstat entry in the sense data buffer
10520 	 */
10521 	st_update_error_stack(un, pkt, arqstat);
10522 
10523 	return (st_decode_sense(un, bp, amt, arqstat, pos));
10524 }
10525 
10526 static errstate
10527 st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
10528     struct scsi_arq_status *statusp, tapepos_t *pos)
10529 {
10530 	struct scsi_pkt *pkt = BP_PKT(bp);
10531 	recov_info *ri = pkt->pkt_private;
10532 	errstate rval = COMMAND_DONE_ERROR;
10533 	cmd_attribute const *attrib;
10534 	long resid;
10535 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10536 	int severity;
10537 	int get_error;
10538 
10539 	ST_FUNC(ST_DEVINFO, st_decode_sense);
10540 
10541 	ASSERT(mutex_owned(ST_MUTEX));
10542 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10543 	    "st_decode_sense()\n");
10544 
10545 	/*
10546 	 * For uscsi commands, squirrel away a copy of the
10547 	 * results of the Request Sense.
10548 	 */
10549 	if (USCSI_CMD(bp)) {
10550 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
10551 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
10552 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
10553 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
10554 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
10555 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
10556 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10557 			    "st_decode_sense: stat=0x%x resid=0x%x\n",
10558 			    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
10559 		}
10560 	}
10561 
10562 	if (ri->privatelen == sizeof (recov_info)) {
10563 		attrib = ri->cmd_attrib;
10564 	} else {
10565 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
10566 	}
10567 
10568 	/*
10569 	 * If the drive is an MT-02, reposition the
10570 	 * secondary error code into the proper place.
10571 	 *
10572 	 * XXX	MT-02 is non-CCS tape, so secondary error code
10573 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
10574 	 * so it's in byte 12.
10575 	 */
10576 	if (un->un_dp->type == ST_TYPE_EMULEX) {
10577 		sensep->es_code = sensep->es_add_info[0];
10578 	}
10579 
10580 	ST_CDB(ST_DEVINFO, "st_decode_sense failed CDB",
10581 	    (caddr_t)&CDBP(pkt)->scc_cmd);
10582 
10583 	ST_SENSE(ST_DEVINFO, "st_decode_sense sense data", (caddr_t)statusp,
10584 	    sizeof (*statusp));
10585 
10586 	/* for normal I/O check extract the resid values. */
10587 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
10588 		if (sensep->es_valid) {
10589 			resid =
10590 			    (sensep->es_info_1 << 24) |
10591 			    (sensep->es_info_2 << 16) |
10592 			    (sensep->es_info_3 << 8)  |
10593 			    (sensep->es_info_4);
10594 			/* If fixed block */
10595 			if (un->un_bsize) {
10596 				resid *= un->un_bsize;
10597 			}
10598 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
10599 			resid = pkt->pkt_resid;
10600 		} else {
10601 			resid = bp->b_bcount;
10602 		}
10603 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10604 		    "st_decode_sense (rw): xferred bit = %d, resid=%ld (%d), "
10605 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
10606 		    resid,
10607 		    (sensep->es_info_1 << 24) |
10608 		    (sensep->es_info_2 << 16) |
10609 		    (sensep->es_info_3 << 8)  |
10610 		    (sensep->es_info_4),
10611 		    pkt->pkt_resid);
10612 		/*
10613 		 * The problem is, what should we believe?
10614 		 */
10615 		if (resid && (pkt->pkt_resid == 0)) {
10616 			pkt->pkt_resid = resid;
10617 		}
10618 	} else {
10619 		/*
10620 		 * If the command is SCMD_SPACE, we need to get the
10621 		 * residual as returned in the sense data, to adjust
10622 		 * our idea of current tape position correctly
10623 		 */
10624 		if ((sensep->es_valid) &&
10625 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10626 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10627 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) ||
10628 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE_G4) ||
10629 		    (CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK)) {
10630 			resid =
10631 			    (sensep->es_info_1 << 24) |
10632 			    (sensep->es_info_2 << 16) |
10633 			    (sensep->es_info_3 << 8)  |
10634 			    (sensep->es_info_4);
10635 			bp->b_resid = resid;
10636 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10637 			    "st_decode_sense(other):	resid=%ld\n", resid);
10638 		} else {
10639 			/*
10640 			 * If the special command is SCMD_READ,
10641 			 * the correct resid will be set later.
10642 			 */
10643 			if (attrib->get_cnt != NULL) {
10644 				resid = attrib->get_cnt(pkt->pkt_cdbp);
10645 			} else {
10646 				resid = bp->b_bcount;
10647 			}
10648 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10649 			    "st_decode_sense(special read):  resid=%ld\n",
10650 			    resid);
10651 		}
10652 	}
10653 
10654 	if ((un->un_state >= ST_STATE_OPEN) &&
10655 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
10656 		st_print_cdb(ST_DEVINFO, st_label, CE_NOTE,
10657 		    "Failed CDB", (char *)pkt->pkt_cdbp);
10658 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
10659 		    "sense data", (char *)sensep, amt);
10660 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
10661 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
10662 		    bp->b_bcount, resid, pkt->pkt_resid);
10663 	}
10664 
10665 	switch (un->un_status = sensep->es_key) {
10666 	case KEY_NO_SENSE:
10667 		severity = SCSI_ERR_INFO;
10668 
10669 		/*
10670 		 * Erase, locate or rewind operation in progress, retry
10671 		 * ASC  ASCQ
10672 		 *  00   18    Erase operation in progress
10673 		 *  00   19    Locate operation in progress
10674 		 *  00   1A    Rewind operation in progress
10675 		 */
10676 		if (sensep->es_add_code == 0 &&
10677 		    ((sensep->es_qual_code == 0x18) ||
10678 		    (sensep->es_qual_code == 0x19) ||
10679 		    (sensep->es_qual_code == 0x1a))) {
10680 			rval = QUE_BUSY_COMMAND;
10681 			break;
10682 		}
10683 
10684 		goto common;
10685 
10686 	case KEY_RECOVERABLE_ERROR:
10687 		severity = SCSI_ERR_RECOVERED;
10688 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
10689 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
10690 			if (un->un_dp->options &
10691 			    ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
10692 				rval = QUE_LAST_COMMAND;
10693 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10694 				    severity, pos->lgclblkno,
10695 				    un->un_err_pos.lgclblkno, scsi_cmds,
10696 				    sensep);
10697 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10698 				    "Command will be retried\n");
10699 			} else {
10700 				severity = SCSI_ERR_FATAL;
10701 				rval = COMMAND_DONE_ERROR_RECOVERED;
10702 				ST_DO_ERRSTATS(un, st_softerrs);
10703 				scsi_errmsg(ST_SCSI_DEVP, pkt, st_label,
10704 				    severity, pos->lgclblkno,
10705 				    un->un_err_pos.lgclblkno, scsi_cmds,
10706 				    sensep);
10707 			}
10708 			break;
10709 		}
10710 common:
10711 		/*
10712 		 * XXX only want reads to be stopped by filemarks.
10713 		 * Don't want them to be stopped by EOT.  EOT matters
10714 		 * only on write.
10715 		 */
10716 		if (sensep->es_filmk && !sensep->es_eom) {
10717 			rval = COMMAND_DONE;
10718 		} else if (sensep->es_eom) {
10719 			rval = COMMAND_DONE;
10720 		} else if (sensep->es_ili) {
10721 			/*
10722 			 * Fun with variable length record devices:
10723 			 * for specifying larger blocks sizes than the
10724 			 * actual physical record size.
10725 			 */
10726 			if (un->un_bsize == 0 && resid > 0) {
10727 				/*
10728 				 * XXX! Ugly.
10729 				 * The requested blocksize is > tape blocksize,
10730 				 * so this is ok, so we just return the
10731 				 * actual size xferred.
10732 				 */
10733 				pkt->pkt_resid = resid;
10734 				rval = COMMAND_DONE;
10735 			} else if (un->un_bsize == 0 && resid < 0) {
10736 				/*
10737 				 * The requested blocksize is < tape blocksize,
10738 				 * so this is not ok, so we err with ENOMEM
10739 				 */
10740 				rval = COMMAND_DONE_ERROR_RECOVERED;
10741 				st_bioerror(bp, ENOMEM);
10742 			} else {
10743 				ST_DO_ERRSTATS(un, st_softerrs);
10744 				severity = SCSI_ERR_FATAL;
10745 				rval = COMMAND_DONE_ERROR;
10746 				st_bioerror(bp, EINVAL);
10747 				un->un_running.pmode = invalid;
10748 			}
10749 		} else {
10750 			/*
10751 			 * we hope and pray for this just being
10752 			 * something we can ignore (ie. a
10753 			 * truly recoverable soft error)
10754 			 */
10755 			rval = COMMAND_DONE;
10756 		}
10757 		if (sensep->es_filmk) {
10758 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10759 			    "filemark\n");
10760 			un->un_status = SUN_KEY_EOF;
10761 			pos->eof = ST_EOF_PENDING;
10762 			st_set_pe_flag(un);
10763 		}
10764 
10765 		/*
10766 		 * ignore eom when reading, a fmk should terminate reading
10767 		 */
10768 		if ((sensep->es_eom) &&
10769 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10770 			if ((sensep->es_add_code == 0) &&
10771 			    (sensep->es_qual_code == 4)) {
10772 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10773 				    "bot\n");
10774 				un->un_status = SUN_KEY_BOT;
10775 				pos->eof = ST_NO_EOF;
10776 				pos->lgclblkno = 0;
10777 				pos->fileno = 0;
10778 				pos->blkno = 0;
10779 				if (pos->pmode != legacy)
10780 					pos->pmode = legacy;
10781 			} else {
10782 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10783 				    "eom\n");
10784 				un->un_status = SUN_KEY_EOT;
10785 				pos->eof = ST_EOM;
10786 			}
10787 			st_set_pe_flag(un);
10788 		}
10789 
10790 		break;
10791 
10792 	case KEY_ILLEGAL_REQUEST:
10793 
10794 		if (un->un_laststate >= ST_STATE_OPEN) {
10795 			ST_DO_ERRSTATS(un, st_softerrs);
10796 			severity = SCSI_ERR_FATAL;
10797 		} else {
10798 			severity = SCSI_ERR_INFO;
10799 		}
10800 		break;
10801 
10802 	case KEY_MEDIUM_ERROR:
10803 		ST_DO_ERRSTATS(un, st_harderrs);
10804 		severity = SCSI_ERR_FATAL;
10805 check_keys:
10806 		/*
10807 		 * attempt to process the keys in the presence of
10808 		 * other errors
10809 		 */
10810 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
10811 			/*
10812 			 * Fun with variable length record devices:
10813 			 * for specifying larger blocks sizes than the
10814 			 * actual physical record size.
10815 			 */
10816 			if (un->un_bsize == 0 && resid > 0) {
10817 				/*
10818 				 * XXX! Ugly
10819 				 */
10820 				pkt->pkt_resid = resid;
10821 			} else if (un->un_bsize == 0 && resid < 0) {
10822 				st_bioerror(bp, EINVAL);
10823 			} else {
10824 				severity = SCSI_ERR_FATAL;
10825 				rval = COMMAND_DONE_ERROR;
10826 				st_bioerror(bp, EINVAL);
10827 			}
10828 		}
10829 		if (sensep->es_filmk) {
10830 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10831 			    "filemark\n");
10832 			un->un_status = SUN_KEY_EOF;
10833 			pos->eof = ST_EOF_PENDING;
10834 			st_set_pe_flag(un);
10835 		}
10836 
10837 		/*
10838 		 * ignore eom when reading, a fmk should terminate reading
10839 		 */
10840 		if ((sensep->es_eom) &&
10841 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
10842 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
10843 			un->un_status = SUN_KEY_EOT;
10844 			pos->eof = ST_EOM;
10845 			st_set_pe_flag(un);
10846 		}
10847 
10848 		break;
10849 
10850 	case KEY_VOLUME_OVERFLOW:
10851 		ST_DO_ERRSTATS(un, st_softerrs);
10852 		pos->eof = ST_EOM;
10853 		severity = SCSI_ERR_FATAL;
10854 		rval = COMMAND_DONE_ERROR;
10855 		goto check_keys;
10856 
10857 	case KEY_HARDWARE_ERROR:
10858 		ST_DO_ERRSTATS(un, st_harderrs);
10859 		severity = SCSI_ERR_FATAL;
10860 		rval = COMMAND_DONE_ERROR;
10861 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
10862 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
10863 		break;
10864 
10865 	case KEY_BLANK_CHECK:
10866 		ST_DO_ERRSTATS(un, st_softerrs);
10867 		severity = SCSI_ERR_INFO;
10868 
10869 		/*
10870 		 * if not a special request and some data was xferred then it
10871 		 * it is not an error yet
10872 		 */
10873 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
10874 			/*
10875 			 * no error for read with or without data xferred
10876 			 */
10877 			un->un_status = SUN_KEY_EOT;
10878 			pos->eof = ST_EOT;
10879 			rval = COMMAND_DONE_ERROR;
10880 			un->un_running.pmode = invalid;
10881 			st_set_pe_flag(un);
10882 			goto check_keys;
10883 		} else if (bp != un->un_sbufp &&
10884 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
10885 			rval = COMMAND_DONE;
10886 		} else {
10887 			rval = COMMAND_DONE_ERROR_RECOVERED;
10888 		}
10889 
10890 		if (un->un_laststate >= ST_STATE_OPEN) {
10891 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10892 			    "blank check\n");
10893 			pos->eof = ST_EOM;
10894 		}
10895 		if ((CDBP(pkt)->scc_cmd == SCMD_LOCATE) ||
10896 		    (CDBP(pkt)->scc_cmd == SCMD_LOCATE_G4) ||
10897 		    (CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
10898 		    (un->un_dp->options & ST_KNOWS_EOD)) {
10899 			/*
10900 			 * we were doing a fast forward by skipping
10901 			 * multiple fmk at the time
10902 			 */
10903 			st_bioerror(bp, EIO);
10904 			severity = SCSI_ERR_RECOVERED;
10905 			rval	 = COMMAND_DONE;
10906 		}
10907 		st_set_pe_flag(un);
10908 		goto check_keys;
10909 
10910 	case KEY_WRITE_PROTECT:
10911 		if (st_wrongtapetype(un)) {
10912 			un->un_status = SUN_KEY_WRONGMEDIA;
10913 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10914 			    "wrong tape for writing- use DC6150 tape "
10915 			    "(or equivalent)\n");
10916 			severity = SCSI_ERR_UNKNOWN;
10917 		} else {
10918 			severity = SCSI_ERR_FATAL;
10919 		}
10920 		ST_DO_ERRSTATS(un, st_harderrs);
10921 		rval = COMMAND_DONE_ERROR;
10922 		st_bioerror(bp, EACCES);
10923 		break;
10924 
10925 	case KEY_UNIT_ATTENTION:
10926 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
10927 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
10928 
10929 		un->un_unit_attention_flags |= 1;
10930 		/*
10931 		 * If we have detected a Bus Reset and the tape
10932 		 * drive has been reserved.
10933 		 */
10934 		if (ST_RQSENSE->es_add_code == 0x29) {
10935 			rval = DEVICE_RESET;
10936 			if ((un->un_rsvd_status &
10937 			    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
10938 			    ST_RESERVE) {
10939 				un->un_rsvd_status |= ST_LOST_RESERVE;
10940 				ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
10941 				    "st_decode_sense: Lost Reservation\n");
10942 			}
10943 		}
10944 
10945 		/*
10946 		 * If this is a recovery command and retrable, retry.
10947 		 */
10948 		if (bp == un->un_recov_buf) {
10949 			severity = SCSI_ERR_INFO;
10950 			if (attrib->retriable &&
10951 			    ri->pkt_retry_cnt++ < st_retry_count) {
10952 				rval = QUE_COMMAND;
10953 			} else {
10954 				rval = COMMAND_DONE_ERROR;
10955 			}
10956 			break; /* Don't set position invalid */
10957 		}
10958 
10959 		/*
10960 		 * If ST_APPLICATION_RESERVATIONS is set,
10961 		 * If the asc/ascq indicates that the reservation
10962 		 * has been cleared just allow the write to continue
10963 		 * which would force a scsi 2 reserve.
10964 		 * If preempted that persistent reservation
10965 		 * the scsi 2 reserve would get a reservation conflict.
10966 		 */
10967 		if ((un->un_rsvd_status &
10968 		    ST_APPLICATION_RESERVATIONS) != 0) {
10969 			/*
10970 			 * RESERVATIONS PREEMPTED
10971 			 * With MPxIO this could be a fail over? XXX
10972 			 */
10973 			if (ST_RQSENSE->es_add_code == 0x2a &&
10974 			    ST_RQSENSE->es_qual_code == 0x03) {
10975 				severity = SCSI_ERR_INFO;
10976 				rval = COMMAND_DONE_ERROR;
10977 				pos->pmode = invalid;
10978 				break;
10979 			/*
10980 			 * RESERVATIONS RELEASED
10981 			 */
10982 			} else if (ST_RQSENSE->es_add_code == 0x2a &&
10983 			    ST_RQSENSE->es_qual_code == 0x04) {
10984 				severity = SCSI_ERR_INFO;
10985 				rval = COMMAND_DONE;
10986 				break;
10987 			}
10988 		}
10989 
10990 		if (un->un_state <= ST_STATE_OPENING) {
10991 			/*
10992 			 * Look, the tape isn't open yet, now determine
10993 			 * if the cause is a BUS RESET, Save the file
10994 			 * and Block positions for the callers to
10995 			 * recover from the loss of position.
10996 			 */
10997 			severity = SCSI_ERR_INFO;
10998 			if ((pos->pmode != invalid) &&
10999 			    (rval == DEVICE_RESET) &&
11000 			    (un->un_restore_pos != 1)) {
11001 				un->un_save_fileno = pos->fileno;
11002 				un->un_save_blkno = pos->blkno;
11003 				un->un_restore_pos = 1;
11004 			}
11005 
11006 			if (attrib->retriable &&
11007 			    ri->pkt_retry_cnt++ < st_retry_count) {
11008 				rval = QUE_COMMAND;
11009 			} else if (rval == DEVICE_RESET) {
11010 				break;
11011 			} else {
11012 				rval = COMMAND_DONE_ERROR;
11013 			}
11014 		/*
11015 		 * Means it thinks the mode parameters have changed.
11016 		 * This is the result of a reset clearing settings or
11017 		 * another initiator changing what we set.
11018 		 */
11019 		}
11020 		if (ST_RQSENSE->es_add_code == 0x2a) {
11021 			if (ST_RQSENSE->es_qual_code == 0x1) {
11022 				/* Error recovery will modeselect and retry. */
11023 				rval = DEVICE_TAMPER;
11024 				severity = SCSI_ERR_INFO;
11025 				break; /* don't set position invalid */
11026 			}
11027 			if (ST_RQSENSE->es_qual_code == 0x0 ||
11028 			    ST_RQSENSE->es_qual_code == 0x2 ||
11029 			    ST_RQSENSE->es_qual_code == 0x3 ||
11030 			    ST_RQSENSE->es_qual_code == 0x4 ||
11031 			    ST_RQSENSE->es_qual_code == 0x5 ||
11032 			    ST_RQSENSE->es_qual_code == 0x6 ||
11033 			    ST_RQSENSE->es_qual_code == 0x7) {
11034 				rval = DEVICE_TAMPER;
11035 				severity = SCSI_ERR_INFO;
11036 			}
11037 		} else if (ST_RQSENSE->es_add_code == 0x28 &&
11038 		    ((ST_RQSENSE->es_qual_code == 0x0) ||
11039 		    ST_RQSENSE->es_qual_code == 0x5)) {
11040 			/*
11041 			 * Not Ready to Ready change, Media may have changed.
11042 			 */
11043 			rval = DEVICE_TAMPER;
11044 			severity = SCSI_ERR_RETRYABLE;
11045 		} else {
11046 			if (rval != DEVICE_RESET) {
11047 				rval = COMMAND_DONE_ERROR;
11048 			} else {
11049 				/*
11050 				 * Returning DEVICE_RESET will call
11051 				 * error recovery.
11052 				 */
11053 				severity = SCSI_ERR_INFO;
11054 				break; /* don't set position invalid */
11055 			}
11056 			/*
11057 			 * Check if it is an Unexpected Unit Attention.
11058 			 * If state is >= ST_STATE_OPEN, we have
11059 			 * already done the initialization .
11060 			 * In this case it is Fatal Error
11061 			 * since no further reading/writing
11062 			 * can be done with fileno set to < 0.
11063 			 */
11064 			if (un->un_state >= ST_STATE_OPEN) {
11065 				ST_DO_ERRSTATS(un, st_harderrs);
11066 				severity = SCSI_ERR_FATAL;
11067 			} else {
11068 				severity = SCSI_ERR_INFO;
11069 			}
11070 		}
11071 
11072 		pos->pmode = invalid;
11073 
11074 		break;
11075 
11076 	case KEY_NOT_READY:
11077 		/*
11078 		 * If in process of getting ready retry.
11079 		 */
11080 		if (sensep->es_add_code  == 0x04 &&
11081 		    sensep->es_qual_code == 0x01 &&
11082 		    ri->pkt_retry_cnt++ < st_retry_count) {
11083 			rval = QUE_COMMAND;
11084 			severity = SCSI_ERR_INFO;
11085 		} else {
11086 			/* give up */
11087 			rval = COMMAND_DONE_ERROR;
11088 			severity = SCSI_ERR_FATAL;
11089 		}
11090 
11091 		/*
11092 		 * If this was an error and after device opened
11093 		 * do error stats.
11094 		 */
11095 		if (rval == COMMAND_DONE_ERROR &&
11096 		    un->un_state > ST_STATE_OPENING) {
11097 			ST_DO_ERRSTATS(un, st_harderrs);
11098 		}
11099 
11100 		if (ST_RQSENSE->es_add_code == 0x3a) {
11101 			if (st_error_level >= SCSI_ERR_FATAL)
11102 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
11103 				    "Tape not inserted in drive\n");
11104 			un->un_mediastate = MTIO_EJECTED;
11105 			cv_broadcast(&un->un_state_cv);
11106 		}
11107 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
11108 		    (rval != QUE_COMMAND))
11109 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
11110 		break;
11111 
11112 	case KEY_ABORTED_COMMAND:
11113 		/* XXX Do drives return this when they see a lost light? */
11114 		/* Testing would say yes */
11115 
11116 		if (ri->pkt_retry_cnt++ < st_retry_count) {
11117 			rval = ATTEMPT_RETRY;
11118 			severity = SCSI_ERR_RETRYABLE;
11119 			goto check_keys;
11120 		}
11121 		/*
11122 		 * Probably a parity error...
11123 		 * if we retry here then this may cause data to be
11124 		 * written twice or data skipped during reading
11125 		 */
11126 		ST_DO_ERRSTATS(un, st_harderrs);
11127 		severity = SCSI_ERR_FATAL;
11128 		rval = COMMAND_DONE_ERROR;
11129 		goto check_keys;
11130 
11131 	default:
11132 		/*
11133 		 * Undecoded sense key.	 Try retries and hope
11134 		 * that will fix the problem.  Otherwise, we're
11135 		 * dead.
11136 		 */
11137 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11138 		    "Unhandled Sense Key '%s'\n",
11139 		    sense_keys[un->un_status]);
11140 		ST_DO_ERRSTATS(un, st_harderrs);
11141 		severity = SCSI_ERR_FATAL;
11142 		rval = COMMAND_DONE_ERROR;
11143 		goto check_keys;
11144 	}
11145 
11146 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
11147 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
11148 	    (un->un_laststate > ST_STATE_OPENING) &&
11149 	    (severity >= st_error_level))) {
11150 
11151 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
11152 		    pos->lgclblkno, un->un_err_pos.lgclblkno,
11153 		    scsi_cmds, sensep);
11154 		if (sensep->es_filmk) {
11155 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11156 			    "File Mark Detected\n");
11157 		}
11158 		if (sensep->es_eom) {
11159 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11160 			    "End-of-Media Detected\n");
11161 		}
11162 		if (sensep->es_ili) {
11163 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
11164 			    "Incorrect Length Indicator Set\n");
11165 		}
11166 	}
11167 	get_error = geterror(bp);
11168 	if (((rval == COMMAND_DONE_ERROR) ||
11169 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
11170 	    ((get_error == EIO) || (get_error == 0))) {
11171 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
11172 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
11173 		if (un->un_rqs_state & ST_RQS_READ) {
11174 			un->un_rqs_state &= ~(ST_RQS_READ);
11175 		} else {
11176 			un->un_rqs_state |= ST_RQS_OVR;
11177 		}
11178 	}
11179 
11180 	return (rval);
11181 }
11182 
11183 
11184 static int
11185 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
11186 {
11187 	int status = TRAN_ACCEPT;
11188 	pkt_info *pktinfo = BP_PKT(bp)->pkt_private;
11189 
11190 	mutex_enter(ST_MUTEX);
11191 
11192 	ST_FUNC(ST_DEVINFO, st_handle_intr_retry_lcmd);
11193 
11194 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11195 	    "st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
11196 
11197 	/*
11198 	 * Check to see if we hit the retry timeout. We check to make sure
11199 	 * this is the first one on the runq and make sure we have not
11200 	 * queued up any more, so this one has to be the last on the list
11201 	 * also. If it is not, we have to fail.  If it is not the first, but
11202 	 * is the last we are in trouble anyway, as we are in the interrupt
11203 	 * context here.
11204 	 */
11205 	if ((pktinfo->pkt_retry_cnt > st_retry_count) ||
11206 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
11207 		goto exit;
11208 	}
11209 
11210 	if (un->un_throttle) {
11211 		un->un_last_throttle = un->un_throttle;
11212 		un->un_throttle = 0;
11213 	}
11214 
11215 	/*
11216 	 * Here we know : bp is the first and last one on the runq
11217 	 * it is not necessary to put it back on the head of the
11218 	 * waitq and then move from waitq to runq. Save this queuing
11219 	 * and call scsi_transport.
11220 	 */
11221 	ST_CDB(ST_DEVINFO, "Retry lcmd CDB", (char *)BP_PKT(bp)->pkt_cdbp);
11222 
11223 	status = st_transport(un, BP_PKT(bp));
11224 
11225 	if (status == TRAN_ACCEPT) {
11226 		if (un->un_last_throttle) {
11227 			un->un_throttle = un->un_last_throttle;
11228 		}
11229 		mutex_exit(ST_MUTEX);
11230 
11231 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11232 		    "restart transport \n");
11233 		return (0);
11234 	}
11235 
11236 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
11237 	mutex_exit(ST_MUTEX);
11238 
11239 	if (status == TRAN_BUSY) {
11240 		if (st_handle_intr_busy(un, bp, ST_TRAN_BUSY_TIMEOUT) == 0) {
11241 			return (0);
11242 		}
11243 	}
11244 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11245 	    "restart transport rejected\n");
11246 	mutex_enter(ST_MUTEX);
11247 	ST_DO_ERRSTATS(un, st_transerrs);
11248 	if (un->un_last_throttle) {
11249 		un->un_throttle = un->un_last_throttle;
11250 	}
11251 exit:
11252 	mutex_exit(ST_MUTEX);
11253 	return (-1);
11254 }
11255 
11256 static int
11257 st_wrongtapetype(struct scsi_tape *un)
11258 {
11259 
11260 	ST_FUNC(ST_DEVINFO, st_wrongtapetype);
11261 
11262 	ASSERT(mutex_owned(ST_MUTEX));
11263 
11264 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_wrongtapetype()\n");
11265 
11266 	/*
11267 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
11268 	 */
11269 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
11270 		switch (un->un_dp->type) {
11271 		case ST_TYPE_WANGTEK:
11272 		case ST_TYPE_ARCHIVE:
11273 			/*
11274 			 * If this really worked, we could go off of
11275 			 * the density codes set in the modesense
11276 			 * page. For this drive, 0x10 == QIC-120,
11277 			 * 0xf == QIC-150, and 0x5 should be for
11278 			 * both QIC-24 and, maybe, QIC-11. However,
11279 			 * the h/w doesn't do what the manual says
11280 			 * that it should, so we'll key off of
11281 			 * getting a WRITE PROTECT error AND wp *not*
11282 			 * set in the mode sense information.
11283 			 */
11284 			/*
11285 			 * XXX but we already know that status is
11286 			 * write protect, so don't check it again.
11287 			 */
11288 
11289 			if (un->un_status == KEY_WRITE_PROTECT &&
11290 			    un->un_mspl->wp == 0) {
11291 				return (1);
11292 			}
11293 			break;
11294 		default:
11295 			break;
11296 		}
11297 	}
11298 	return (0);
11299 }
11300 
11301 static errstate
11302 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
11303 {
11304 	errstate action;
11305 	recov_info *rcvi = pkt->pkt_private;
11306 	buf_t *bp = rcvi->cmd_bp;
11307 	struct scsi_arq_status *stat = (struct scsi_arq_status *)pkt->pkt_scbp;
11308 
11309 	ST_FUNC(ST_DEVINFO, st_check_error);
11310 
11311 	ASSERT(mutex_owned(ST_MUTEX));
11312 
11313 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
11314 
11315 	switch (SCBP_C(pkt)) {
11316 	case STATUS_RESERVATION_CONFLICT:
11317 		/*
11318 		 * Command recovery is enabled, not just opening,
11319 		 * we had the drive reserved and we thing its ours.
11320 		 * Call recovery to attempt to take it back.
11321 		 */
11322 		if ((rcvi->privatelen == sizeof (recov_info)) &&
11323 		    (bp != un->un_recov_buf) &&
11324 		    (un->un_state > ST_STATE_OPEN_PENDING_IO) &&
11325 		    ((un->un_rsvd_status & (ST_RESERVE |
11326 		    ST_APPLICATION_RESERVATIONS)) != 0)) {
11327 			action = ATTEMPT_RETRY;
11328 			un->un_rsvd_status |= ST_LOST_RESERVE;
11329 		} else {
11330 			action = COMMAND_DONE_EACCES;
11331 			un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
11332 		}
11333 		break;
11334 
11335 	case STATUS_BUSY:
11336 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
11337 		if (rcvi->privatelen == sizeof (recov_info) &&
11338 		    un->un_multipath && (pkt->pkt_state == (STATE_GOT_BUS |
11339 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS))) {
11340 			/*
11341 			 * Status returned by scsi_vhci indicating path
11342 			 * has failed over.
11343 			 */
11344 			action = PATH_FAILED;
11345 			break;
11346 		}
11347 		/* FALLTHRU */
11348 	case STATUS_QFULL:
11349 		if (rcvi->privatelen == sizeof (recov_info)) {
11350 			/*
11351 			 * If recovery is inabled use it instead of
11352 			 * blind reties.
11353 			 */
11354 			action = ATTEMPT_RETRY;
11355 		} else if (rcvi->pkt_retry_cnt++ < st_retry_count) {
11356 			action = QUE_BUSY_COMMAND;
11357 		} else if ((un->un_rsvd_status &
11358 		    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
11359 			/*
11360 			 * If this is a command done before reserve is done
11361 			 * don't reset.
11362 			 */
11363 			action = COMMAND_DONE_ERROR;
11364 		} else {
11365 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11366 			    "unit busy too long\n");
11367 			(void) st_reset(un, RESET_ALL);
11368 			action = COMMAND_DONE_ERROR;
11369 		}
11370 		break;
11371 
11372 	case STATUS_CHECK:
11373 	case STATUS_TERMINATED:
11374 		/*
11375 		 * we should only get here if the auto rqsense failed
11376 		 * thru a uscsi cmd without autorequest sense
11377 		 * so we just try again
11378 		 */
11379 		if (un->un_arq_enabled &&
11380 		    stat->sts_rqpkt_reason == CMD_CMPLT &&
11381 		    (stat->sts_rqpkt_state & (STATE_GOT_BUS |
11382 		    STATE_GOT_TARGET | STATE_SENT_CMD | STATE_GOT_STATUS)) ==
11383 		    (STATE_GOT_BUS | STATE_GOT_TARGET | STATE_SENT_CMD |
11384 		    STATE_GOT_STATUS)) {
11385 
11386 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11387 			    "Really got sense data\n");
11388 			action = st_decode_sense(un, bp, MAX_SENSE_LENGTH -
11389 			    pkt->pkt_resid, stat, &un->un_pos);
11390 		} else {
11391 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11392 			    "Trying to queue sense command\n");
11393 			action = QUE_SENSE;
11394 		}
11395 		break;
11396 
11397 	case STATUS_TASK_ABORT:
11398 		/*
11399 		 * This is an aborted task. This can be a reset on the other
11400 		 * port of a multiport drive. Lets try and recover it.
11401 		 */
11402 		action = DEVICE_RESET;
11403 		break;
11404 
11405 	default:
11406 		action = COMMAND_DONE;
11407 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
11408 		    "Unexpected scsi status byte 0x%x\n", SCBP_C(pkt));
11409 	}
11410 	return (action);
11411 }
11412 
11413 static void
11414 st_calc_bnum(struct scsi_tape *un, struct buf *bp, struct scsi_pkt *pkt)
11415 {
11416 	int nblks;
11417 	int nfiles;
11418 	long count;
11419 	recov_info *ri = pkt->pkt_private;
11420 	cmd_attribute const *attrib;
11421 
11422 	ST_FUNC(ST_DEVINFO, st_calc_bnum);
11423 
11424 	ASSERT(mutex_owned(ST_MUTEX));
11425 
11426 	if (ri->privatelen == sizeof (recov_info)) {
11427 		attrib = ri->cmd_attrib;
11428 		ASSERT(attrib->recov_pos_type == POS_EXPECTED);
11429 		ASSERT(attrib->chg_tape_pos);
11430 	} else {
11431 		ri = NULL;
11432 		attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
11433 	}
11434 
11435 	count = bp->b_bcount - bp->b_resid;
11436 
11437 	/* Command reads or writes data */
11438 	if (attrib->transfers_data != TRAN_NONE) {
11439 		if (count == 0) {
11440 			/* failed writes should not make it here */
11441 			ASSERT(attrib->transfers_data == TRAN_READ);
11442 			nblks = 0;
11443 			nfiles = 1;
11444 		} else if (un->un_bsize == 0) {
11445 			/*
11446 			 * If variable block mode.
11447 			 * Fixed bit in CBD should be zero.
11448 			 */
11449 			ASSERT((pkt->pkt_cdbp[1] & 1) == 0);
11450 			nblks = 1;
11451 			un->un_kbytes_xferred += (count / ONE_K);
11452 			nfiles = 0;
11453 		} else {
11454 			/*
11455 			 * If fixed block mode.
11456 			 * Fixed bit in CBD should be one.
11457 			 */
11458 			ASSERT((pkt->pkt_cdbp[1] & 1) == 1);
11459 			nblks = (count / un->un_bsize);
11460 			un->un_kbytes_xferred += (nblks * un->un_bsize) / ONE_K;
11461 			nfiles = 0;
11462 		}
11463 		/*
11464 		 * So its possable to read some blocks and hit a filemark.
11465 		 * Example reading in fixed block mode where more then one
11466 		 * block at a time is requested. In this case because the
11467 		 * filemark is hit something less then the requesed number
11468 		 * of blocks is read.
11469 		 */
11470 		if (un->un_pos.eof == ST_EOF_PENDING && bp->b_resid) {
11471 			nfiles = 1;
11472 		}
11473 	} else {
11474 		nblks = 0;
11475 		nfiles = count;
11476 	}
11477 
11478 	/*
11479 	 * If some command failed after this one started and it seems
11480 	 * to have finshed without error count the position.
11481 	 */
11482 	if (un->un_persistence && un->un_persist_errors) {
11483 		ASSERT(un->un_pos.pmode != invalid);
11484 	}
11485 
11486 	if (attrib->chg_tape_direction == DIR_FORW) {
11487 		un->un_pos.blkno += nblks;
11488 		un->un_pos.lgclblkno += nblks;
11489 		un->un_pos.lgclblkno += nfiles;
11490 	} else if (attrib->chg_tape_direction == DIR_REVC) {
11491 		un->un_pos.blkno -= nblks;
11492 		un->un_pos.lgclblkno -= nblks;
11493 		un->un_pos.lgclblkno -= nfiles;
11494 	} else {
11495 		ASSERT(0);
11496 	}
11497 
11498 	/* recovery disabled */
11499 	if (ri == NULL) {
11500 		un->un_running.pmode = invalid;
11501 		return;
11502 	}
11503 
11504 	/*
11505 	 * If we didn't just read a filemark.
11506 	 */
11507 	if (un->un_pos.eof != ST_EOF_PENDING) {
11508 		ASSERT(nblks != 0 && nfiles == 0);
11509 		/*
11510 		 * If Previously calulated expected position does not match
11511 		 * debug the expected position.
11512 		 */
11513 		if ((ri->pos.pmode != invalid) && nblks &&
11514 		    ((un->un_pos.blkno != ri->pos.blkno) ||
11515 		    (un->un_pos.lgclblkno != ri->pos.lgclblkno))) {
11516 #ifdef STDEBUG
11517 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11518 			    "Expected", &ri->pos);
11519 			st_print_position(ST_DEVINFO, st_label, CE_NOTE,
11520 			    "But Got", &un->un_pos);
11521 #endif
11522 			un->un_running.pmode = invalid;
11523 		}
11524 	} else {
11525 		ASSERT(nfiles != 0);
11526 		if (un->un_running.pmode != invalid) {
11527 			/*
11528 			 * blkno and lgclblkno already counted in
11529 			 * st_add_recovery_info_to_pkt(). Since a block was not
11530 			 * read and a filemark was.
11531 			 */
11532 			if (attrib->chg_tape_direction == DIR_FORW) {
11533 				un->un_running.fileno++;
11534 				un->un_running.blkno = 0;
11535 			} else if (attrib->chg_tape_direction == DIR_REVC) {
11536 				un->un_running.fileno--;
11537 				un->un_running.blkno = LASTBLK;
11538 			}
11539 		}
11540 	}
11541 }
11542 
11543 static void
11544 st_set_state(struct scsi_tape *un, struct buf *bp)
11545 {
11546 	struct scsi_pkt *sp = BP_PKT(bp);
11547 	struct uscsi_cmd *ucmd;
11548 
11549 	ST_FUNC(ST_DEVINFO, st_set_state);
11550 
11551 	ASSERT(mutex_owned(ST_MUTEX));
11552 	ASSERT(bp != un->un_recov_buf);
11553 
11554 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
11555 	    "st_set_state(): eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
11556 	    un->un_pos.eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
11557 
11558 	if (bp != un->un_sbufp) {
11559 #ifdef STDEBUG
11560 		if (DEBUGGING && sp->pkt_resid) {
11561 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11562 			    "pkt_resid %ld bcount %ld\n",
11563 			    sp->pkt_resid, bp->b_bcount);
11564 		}
11565 #endif
11566 		bp->b_resid = sp->pkt_resid;
11567 		if (geterror(bp) != EIO) {
11568 			st_calc_bnum(un, bp, sp);
11569 		}
11570 		if (bp->b_flags & B_READ) {
11571 			un->un_lastop = ST_OP_READ;
11572 			un->un_fmneeded = 0;
11573 		} else {
11574 			un->un_lastop = ST_OP_WRITE;
11575 			if (un->un_dp->options & ST_REEL) {
11576 				un->un_fmneeded = 2;
11577 			} else {
11578 				un->un_fmneeded = 1;
11579 			}
11580 		}
11581 		/*
11582 		 * all is honky dory at this point, so let's
11583 		 * readjust the throttle, to increase speed, if we
11584 		 * have not throttled down.
11585 		 */
11586 		if (un->un_throttle) {
11587 			un->un_throttle = un->un_max_throttle;
11588 		}
11589 	} else {
11590 		optype new_lastop = ST_OP_NIL;
11591 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
11592 
11593 		switch (cmd) {
11594 		case SCMD_WRITE:
11595 		case SCMD_WRITE_G4:
11596 			bp->b_resid = sp->pkt_resid;
11597 			new_lastop = ST_OP_WRITE;
11598 			if (geterror(bp) == EIO) {
11599 				break;
11600 			}
11601 			st_calc_bnum(un, bp, sp);
11602 			if (un->un_dp->options & ST_REEL) {
11603 				un->un_fmneeded = 2;
11604 			} else {
11605 				un->un_fmneeded = 1;
11606 			}
11607 			break;
11608 		case SCMD_READ:
11609 		case SCMD_READ_G4:
11610 			bp->b_resid = sp->pkt_resid;
11611 			new_lastop = ST_OP_READ;
11612 			if (geterror(bp) == EIO) {
11613 				break;
11614 			}
11615 			st_calc_bnum(un, bp, sp);
11616 			un->un_fmneeded = 0;
11617 			break;
11618 		case SCMD_WRITE_FILE_MARK_G4:
11619 		case SCMD_WRITE_FILE_MARK:
11620 		{
11621 			int fmdone;
11622 
11623 			if (un->un_pos.eof != ST_EOM) {
11624 				un->un_pos.eof = ST_NO_EOF;
11625 			}
11626 			fmdone = (bp->b_bcount - bp->b_resid);
11627 			if (fmdone > 0) {
11628 				un->un_lastop = new_lastop = ST_OP_WEOF;
11629 				un->un_pos.lgclblkno += fmdone;
11630 				un->un_pos.fileno += fmdone;
11631 				un->un_pos.blkno = 0;
11632 			} else {
11633 				new_lastop = ST_OP_CTL;
11634 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11635 				    "Flushed buffer\n");
11636 			}
11637 			if (fmdone > un->un_fmneeded) {
11638 				un->un_fmneeded = 0;
11639 			} else {
11640 				un->un_fmneeded -= fmdone;
11641 			}
11642 			break;
11643 		}
11644 		case SCMD_REWIND:
11645 			un->un_pos.eof = ST_NO_EOF;
11646 			un->un_pos.fileno = 0;
11647 			un->un_pos.blkno = 0;
11648 			un->un_pos.lgclblkno = 0;
11649 			if (un->un_pos.pmode != legacy)
11650 				un->un_pos.pmode = legacy;
11651 			new_lastop = ST_OP_CTL;
11652 			un->un_restore_pos = 0;
11653 			break;
11654 
11655 		case SCMD_SPACE:
11656 		case SCMD_SPACE_G4:
11657 		{
11658 			int64_t count;
11659 			int64_t resid;
11660 			int64_t done;
11661 			cmd_attribute const *attrib;
11662 			recov_info *ri = sp->pkt_private;
11663 
11664 			if (ri->privatelen == sizeof (recov_info)) {
11665 				attrib = ri->cmd_attrib;
11666 			} else {
11667 				attrib =
11668 				    st_lookup_cmd_attribute(sp->pkt_cdbp[0]);
11669 			}
11670 
11671 			resid = (int64_t)SPACE_CNT(bp->b_resid);
11672 			count = (int64_t)attrib->get_cnt(sp->pkt_cdbp);
11673 
11674 			if (count >= 0) {
11675 				done = (count - resid);
11676 			} else {
11677 				done = ((-count) - resid);
11678 			}
11679 			if (done > 0) {
11680 				un->un_lastop = new_lastop = ST_OP_CTL;
11681 			} else {
11682 				new_lastop = ST_OP_CTL;
11683 			}
11684 
11685 			ST_SPAC(ST_DEVINFO, st_label, CE_WARN,
11686 			    "space cmd: cdb[1] = %s\n"
11687 			    "space data:       = 0x%lx\n"
11688 			    "space count:      = %"PRId64"\n"
11689 			    "space resid:      = %"PRId64"\n"
11690 			    "spaces done:      = %"PRId64"\n"
11691 			    "fileno before     = %d\n"
11692 			    "blkno before      = %d\n",
11693 			    space_strs[sp->pkt_cdbp[1] & 7],
11694 			    bp->b_bcount,
11695 			    count, resid, done,
11696 			    un->un_pos.fileno, un->un_pos.blkno);
11697 
11698 			switch (sp->pkt_cdbp[1]) {
11699 			case SPACE_TYPE(SP_FLM):
11700 				/* Space file forward */
11701 				if (count >= 0) {
11702 					if (un->un_pos.eof <= ST_EOF) {
11703 						un->un_pos.eof = ST_NO_EOF;
11704 					}
11705 					un->un_pos.fileno += done;
11706 					un->un_pos.blkno = 0;
11707 					break;
11708 				}
11709 				/* Space file backward */
11710 				if (done > un->un_pos.fileno) {
11711 					un->un_pos.fileno = 0;
11712 					un->un_pos.blkno = 0;
11713 				} else {
11714 					un->un_pos.fileno -= done;
11715 					un->un_pos.blkno = LASTBLK;
11716 					un->un_running.pmode = invalid;
11717 				}
11718 				break;
11719 			case SPACE_TYPE(SP_BLK):
11720 				/* Space block forward */
11721 				if (count >= 0) {
11722 					un->un_pos.blkno += done;
11723 					break;
11724 				}
11725 				/* Space block backward */
11726 				if (un->un_pos.eof >= ST_EOF_PENDING) {
11727 				/*
11728 				 * we stepped back into
11729 				 * a previous file; we are not
11730 				 * making an effort to pretend that
11731 				 * we are still in the current file
11732 				 * ie. logical == physical position
11733 				 * and leave it to st_ioctl to correct
11734 				 */
11735 					if (done > un->un_pos.blkno) {
11736 						un->un_pos.blkno = 0;
11737 					} else {
11738 						un->un_pos.fileno--;
11739 						un->un_pos.blkno = LASTBLK;
11740 						un->un_running.pmode = invalid;
11741 					}
11742 				} else {
11743 					un->un_pos.blkno -= done;
11744 				}
11745 				break;
11746 			case SPACE_TYPE(SP_SQFLM):
11747 				un->un_pos.pmode = logical;
11748 				un->un_pos.blkno = 0;
11749 				un->un_lastop = new_lastop = ST_OP_CTL;
11750 				break;
11751 			case SPACE_TYPE(SP_EOD):
11752 				un->un_pos.pmode = logical;
11753 				un->un_pos.eof = ST_EOM;
11754 				un->un_status = KEY_BLANK_CHECK;
11755 				break;
11756 			default:
11757 				un->un_pos.pmode = invalid;
11758 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
11759 				    "Unsupported space cmd: %s\n",
11760 				    space_strs[sp->pkt_cdbp[1] & 7]);
11761 
11762 				un->un_lastop = new_lastop = ST_OP_CTL;
11763 			}
11764 
11765 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11766 			    "after_space rs %"PRId64" fil %d blk %d\n",
11767 			    resid, un->un_pos.fileno, un->un_pos.blkno);
11768 
11769 			break;
11770 		}
11771 		case SCMD_LOAD:
11772 			if ((bp->b_bcount & (LD_LOAD | LD_EOT)) == LD_LOAD) {
11773 				un->un_pos.fileno = 0;
11774 				if (un->un_pos.pmode != legacy)
11775 					un->un_pos.pmode = legacy;
11776 			} else {
11777 				un->un_state = ST_STATE_OFFLINE;
11778 				un->un_pos.pmode = invalid;
11779 
11780 			}
11781 			/*
11782 			 * If we are loading or unloading we expect the media id
11783 			 * to change. Lets make it unknown.
11784 			 */
11785 			if (un->un_media_id != bogusID && un->un_media_id_len) {
11786 				kmem_free(un->un_media_id, un->un_media_id_len);
11787 				un->un_media_id = NULL;
11788 				un->un_media_id_len = 0;
11789 			}
11790 			un->un_density_known = 0;
11791 			un->un_pos.eof = ST_NO_EOF;
11792 			un->un_pos.blkno = 0;
11793 			un->un_lastop = new_lastop = ST_OP_CTL;
11794 			break;
11795 		case SCMD_ERASE:
11796 			un->un_pos.eof = ST_NO_EOF;
11797 			un->un_pos.blkno = 0;
11798 			un->un_pos.fileno = 0;
11799 			un->un_pos.lgclblkno = 0;
11800 			if (un->un_pos.pmode != legacy)
11801 				un->un_pos.pmode = legacy;
11802 			new_lastop = ST_OP_CTL;
11803 			break;
11804 		case SCMD_RESERVE:
11805 			un->un_rsvd_status |= ST_RESERVE;
11806 			un->un_rsvd_status &=
11807 			    ~(ST_RELEASE | ST_LOST_RESERVE |
11808 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11809 			new_lastop = ST_OP_CTL;
11810 			break;
11811 		case SCMD_RELEASE:
11812 			un->un_rsvd_status |= ST_RELEASE;
11813 			un->un_rsvd_status &=
11814 			    ~(ST_RESERVE | ST_LOST_RESERVE |
11815 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
11816 			new_lastop = ST_OP_CTL;
11817 			break;
11818 		case SCMD_PERSISTENT_RESERVE_IN:
11819 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11820 			    "PGR_IN command\n");
11821 			new_lastop = ST_OP_CTL;
11822 			break;
11823 		case SCMD_PERSISTENT_RESERVE_OUT:
11824 			switch (sp->pkt_cdbp[1] & ST_SA_MASK) {
11825 			case ST_SA_SCSI3_RESERVE:
11826 			case ST_SA_SCSI3_PREEMPT:
11827 			case ST_SA_SCSI3_PREEMPTANDABORT:
11828 				un->un_rsvd_status |=
11829 				    (ST_APPLICATION_RESERVATIONS | ST_RESERVE);
11830 				un->un_rsvd_status &= ~(ST_RELEASE |
11831 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11832 				    ST_INITIATED_RESET);
11833 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11834 				    "PGR Reserve and set: entering"
11835 				    " ST_APPLICATION_RESERVATIONS mode");
11836 				break;
11837 			case ST_SA_SCSI3_REGISTER:
11838 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11839 				    "PGR Reserve register key");
11840 				un->un_rsvd_status |= ST_INIT_RESERVE;
11841 				break;
11842 			case ST_SA_SCSI3_CLEAR:
11843 				un->un_rsvd_status &= ~ST_INIT_RESERVE;
11844 				/* FALLTHROUGH */
11845 			case ST_SA_SCSI3_RELEASE:
11846 				un->un_rsvd_status &=
11847 				    ~(ST_APPLICATION_RESERVATIONS | ST_RESERVE |
11848 				    ST_LOST_RESERVE | ST_RESERVATION_CONFLICT |
11849 				    ST_INITIATED_RESET);
11850 				un->un_rsvd_status |= ST_RELEASE;
11851 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
11852 				    "PGR Release and reset: exiting"
11853 				    " ST_APPLICATION_RESERVATIONS mode");
11854 				break;
11855 			}
11856 			new_lastop = ST_OP_CTL;
11857 			break;
11858 		case SCMD_TEST_UNIT_READY:
11859 		case SCMD_READ_BLKLIM:
11860 		case SCMD_REQUEST_SENSE:
11861 		case SCMD_INQUIRY:
11862 		case SCMD_RECOVER_BUF:
11863 		case SCMD_MODE_SELECT:
11864 		case SCMD_MODE_SENSE:
11865 		case SCMD_DOORLOCK:
11866 		case SCMD_READ_BUFFER:
11867 		case SCMD_REPORT_DENSITIES:
11868 		case SCMD_LOG_SELECT_G1:
11869 		case SCMD_LOG_SENSE_G1:
11870 		case SCMD_REPORT_LUNS:
11871 		case SCMD_READ_ATTRIBUTE:
11872 		case SCMD_WRITE_ATTRIBUTE:
11873 		case SCMD_SVC_ACTION_IN_G5:
11874 			new_lastop = ST_OP_CTL;
11875 			break;
11876 		case SCMD_READ_POSITION:
11877 			new_lastop = ST_OP_CTL;
11878 			/*
11879 			 * Only if the buf used was un_sbufp.
11880 			 * Among other things the prevents read positions used
11881 			 * as part of error recovery from messing up our
11882 			 * current position as they will use un_recov_buf.
11883 			 */
11884 			if (USCSI_CMD(bp)) {
11885 				(void) st_get_read_pos(un, bp);
11886 			}
11887 			break;
11888 		case SCMD_LOCATE:
11889 		case SCMD_LOCATE_G4:
11890 			/* Locate makes position mode no longer legacy */
11891 			un->un_lastop = new_lastop = ST_OP_CTL;
11892 			break;
11893 		case SCMD_MAINTENANCE_IN:
11894 			switch (sp->pkt_cdbp[1]) {
11895 			case SSVC_ACTION_GET_SUPPORTED_OPERATIONS:
11896 			case SSVC_ACTION_SET_TARGET_PORT_GROUPS:
11897 				new_lastop = ST_OP_CTL;
11898 				break;
11899 			}
11900 			if (new_lastop != ST_OP_NIL) {
11901 				break;
11902 			}
11903 		default:
11904 			/*
11905 			 * Unknown command, If was USCSI and USCSI_SILENT
11906 			 * flag was not set, set position to unknown.
11907 			 */
11908 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
11909 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
11910 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
11911 				    "unknown cmd 0x%X caused loss of state\n",
11912 				    cmd);
11913 			} else {
11914 				/*
11915 				 * keep the old agreement to allow unknown
11916 				 * commands with the USCSI_SILENT set.
11917 				 * This prevents ASSERT below.
11918 				 */
11919 				new_lastop = ST_OP_CTL;
11920 				break;
11921 			}
11922 			/* FALLTHROUGH */
11923 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
11924 			un->un_pos.pmode = invalid;
11925 			un->un_lastop = new_lastop = ST_OP_CTL;
11926 			break;
11927 		}
11928 
11929 		/* new_lastop should have been changed */
11930 		ASSERT(new_lastop != ST_OP_NIL);
11931 
11932 		/* If un_lastop should copy new_lastop  */
11933 		if (((un->un_lastop == ST_OP_WRITE) ||
11934 		    (un->un_lastop == ST_OP_WEOF)) &&
11935 		    new_lastop != ST_OP_CTL) {
11936 			un->un_lastop = new_lastop;
11937 		}
11938 	}
11939 
11940 	/*
11941 	 * In the st driver we have a logical and physical file position.
11942 	 * Under BSD behavior, when you get a zero read, the logical position
11943 	 * is before the filemark but after the last record of the file.
11944 	 * The physical position is after the filemark. MTIOCGET should always
11945 	 * return the logical file position.
11946 	 *
11947 	 * The next read gives a silent skip to the next file.
11948 	 * Under SVR4, the logical file position remains before the filemark
11949 	 * until the file is closed or a space operation is performed.
11950 	 * Hence set err_resid and err_file before changing fileno if case
11951 	 * BSD Behaviour.
11952 	 */
11953 	un->un_err_resid = bp->b_resid;
11954 	COPY_POS(&un->un_err_pos, &un->un_pos);
11955 
11956 
11957 	/*
11958 	 * If we've seen a filemark via the last read operation
11959 	 * advance the file counter, but mark things such that
11960 	 * the next read operation gets a zero count. We have
11961 	 * to put this here to handle the case of sitting right
11962 	 * at the end of a tape file having seen the file mark,
11963 	 * but the tape is closed and then re-opened without
11964 	 * any further i/o. That is, the position information
11965 	 * must be updated before a close.
11966 	 */
11967 
11968 	if (un->un_lastop == ST_OP_READ && un->un_pos.eof == ST_EOF_PENDING) {
11969 		/*
11970 		 * If we're a 1/2" tape, and we get a filemark
11971 		 * right on block 0, *AND* we were not in the
11972 		 * first file on the tape, and we've hit logical EOM.
11973 		 * We'll mark the state so that later we do the
11974 		 * right thing (in st_close(), st_strategy() or
11975 		 * st_ioctl()).
11976 		 *
11977 		 */
11978 		if ((un->un_dp->options & ST_REEL) &&
11979 		    !(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
11980 		    un->un_pos.blkno == 0 && un->un_pos.fileno > 0) {
11981 			un->un_pos.eof = ST_EOT_PENDING;
11982 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11983 			    "eot pending\n");
11984 			un->un_pos.fileno++;
11985 			un->un_pos.blkno = 0;
11986 		} else if (BSD_BEHAVIOR) {
11987 			/*
11988 			 * If the read of the filemark was a side effect
11989 			 * of reading some blocks (i.e., data was actually
11990 			 * read), then the EOF mark is pending and the
11991 			 * bump into the next file awaits the next read
11992 			 * operation (which will return a zero count), or
11993 			 * a close or a space operation, else the bump
11994 			 * into the next file occurs now.
11995 			 */
11996 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
11997 			    "resid=%lx, bcount=%lx\n",
11998 			    bp->b_resid, bp->b_bcount);
11999 
12000 			if (bp->b_resid != bp->b_bcount) {
12001 				un->un_pos.eof = ST_EOF;
12002 			} else {
12003 				un->un_silent_skip = 1;
12004 				un->un_pos.eof = ST_NO_EOF;
12005 				un->un_pos.fileno++;
12006 				un->un_pos.lgclblkno++;
12007 				un->un_save_blkno = un->un_pos.blkno;
12008 				un->un_pos.blkno = 0;
12009 			}
12010 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12011 			    "eof of file %d, eof=%d\n",
12012 			    un->un_pos.fileno, un->un_pos.eof);
12013 		} else if (SVR4_BEHAVIOR) {
12014 			/*
12015 			 * If the read of the filemark was a side effect
12016 			 * of reading some blocks (i.e., data was actually
12017 			 * read), then the next read should return 0
12018 			 */
12019 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12020 			    "resid=%lx, bcount=%lx\n",
12021 			    bp->b_resid, bp->b_bcount);
12022 			if (bp->b_resid == bp->b_bcount) {
12023 				un->un_pos.eof = ST_EOF;
12024 			}
12025 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
12026 			    "eof of file=%d, eof=%d\n",
12027 			    un->un_pos.fileno, un->un_pos.eof);
12028 		}
12029 	}
12030 }
12031 
12032 /*
12033  * set the correct un_errno, to take corner cases into consideration
12034  */
12035 static void
12036 st_set_pe_errno(struct scsi_tape *un)
12037 {
12038 	ST_FUNC(ST_DEVINFO, st_set_pe_errno);
12039 
12040 	ASSERT(mutex_owned(ST_MUTEX));
12041 
12042 	/* if errno is already set, don't reset it */
12043 	if (un->un_errno)
12044 		return;
12045 
12046 	/* here un_errno == 0 */
12047 	/*
12048 	 * if the last transfer before flushing all the
12049 	 * waiting I/O's, was 0 (resid = count), then we
12050 	 * want to give the user an error on all the rest,
12051 	 * so here.  If there was a transfer, we set the
12052 	 * resid and counts to 0, and let it drop through,
12053 	 * giving a zero return.  the next I/O will then
12054 	 * give an error.
12055 	 */
12056 	if (un->un_last_resid == un->un_last_count) {
12057 		switch (un->un_pos.eof) {
12058 		case ST_EOM:
12059 			un->un_errno = ENOMEM;
12060 			break;
12061 		case ST_EOT:
12062 		case ST_EOF:
12063 			un->un_errno = EIO;
12064 			break;
12065 		}
12066 	} else {
12067 		/*
12068 		 * we know they did not have a zero, so make
12069 		 * sure they get one
12070 		 */
12071 		un->un_last_resid = un->un_last_count = 0;
12072 	}
12073 }
12074 
12075 
12076 /*
12077  * send in a marker pkt to terminate flushing of commands by BBA (via
12078  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
12079  */
12080 static void
12081 st_hba_unflush(struct scsi_tape *un)
12082 {
12083 	ST_FUNC(ST_DEVINFO, st_hba_unflush);
12084 
12085 	ASSERT(mutex_owned(ST_MUTEX));
12086 
12087 	if (!un->un_flush_on_errors)
12088 		return;
12089 
12090 #ifdef FLUSH_ON_ERRORS
12091 
12092 	if (!un->un_mkr_pkt) {
12093 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
12094 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
12095 
12096 		/* we slept, so it must be there */
12097 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
12098 	}
12099 
12100 	st_transport(un, un->un_mkr_pkt);
12101 #endif
12102 }
12103 
12104 static char *
12105 st_print_scsi_cmd(char cmd)
12106 {
12107 	char tmp[64];
12108 	char *cpnt;
12109 
12110 	cpnt = scsi_cmd_name(cmd, scsi_cmds, tmp);
12111 	/* tmp goes out of scope on return and caller sees garbage */
12112 	if (cpnt == tmp) {
12113 		cpnt = "Unknown Command";
12114 	}
12115 	return (cpnt);
12116 }
12117 
12118 static void
12119 st_print_cdb(dev_info_t *dip, char *label, uint_t level,
12120     char *title, char *cdb)
12121 {
12122 	int len = scsi_cdb_size[CDB_GROUPID(cdb[0])];
12123 	char buf[256];
12124 	struct scsi_tape *un;
12125 	int instance = ddi_get_instance(dip);
12126 
12127 	un = ddi_get_soft_state(st_state, instance);
12128 
12129 	ST_FUNC(dip, st_print_cdb);
12130 
12131 	/* force one line output so repeated commands are printed once */
12132 	if ((st_debug & 0x180) == 0x100) {
12133 		scsi_log(dip, label, level, "node %s cmd %s\n",
12134 		    st_dev_name(un->un_dev), st_print_scsi_cmd(*cdb));
12135 		return;
12136 	}
12137 
12138 	/* force one line output so repeated CDB's are printed once */
12139 	if ((st_debug & 0x180) == 0x80) {
12140 		st_clean_print(dip, label, level, NULL, cdb, len);
12141 	} else {
12142 		(void) sprintf(buf, "%s for cmd(%s)", title,
12143 		    st_print_scsi_cmd(*cdb));
12144 		st_clean_print(dip, label, level, buf, cdb, len);
12145 	}
12146 }
12147 
12148 static void
12149 st_clean_print(dev_info_t *dev, char *label, uint_t level,
12150     char *title, char *data, int len)
12151 {
12152 	int	i;
12153 	int 	c;
12154 	char	*format;
12155 	char	buf[256];
12156 	uchar_t	byte;
12157 
12158 	ST_FUNC(dev, st_clean_print);
12159 
12160 
12161 	if (title) {
12162 		(void) sprintf(buf, "%s:\n", title);
12163 		scsi_log(dev, label, level, "%s", buf);
12164 		level = CE_CONT;
12165 	}
12166 
12167 	for (i = 0; i < len; ) {
12168 		buf[0] = 0;
12169 		for (c = 0; c < 8 && i < len; c++, i++) {
12170 			byte = (uchar_t)data[i];
12171 			if (byte < 0x10)
12172 				format = "0x0%x ";
12173 			else
12174 				format = "0x%x ";
12175 			(void) sprintf(&buf[(int)strlen(buf)], format, byte);
12176 		}
12177 		(void) sprintf(&buf[(int)strlen(buf)], "\n");
12178 
12179 		scsi_log(dev, label, level, "%s\n", buf);
12180 		level = CE_CONT;
12181 	}
12182 }
12183 
12184 /*
12185  * Conditionally enabled debugging
12186  */
12187 #ifdef	STDEBUG
12188 static void
12189 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
12190 {
12191 	char tmpbuf[64];
12192 
12193 	ST_FUNC(ST_DEVINFO, st_debug_cmds);
12194 
12195 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12196 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
12197 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
12198 	    count, count,
12199 	    wait == ASYNC_CMD ? "a" : "");
12200 }
12201 #endif	/* STDEBUG */
12202 
12203 /*
12204  * Returns pointer to name of minor node name of device 'dev'.
12205  */
12206 static char *
12207 st_dev_name(dev_t dev)
12208 {
12209 	struct scsi_tape *un;
12210 	const char density[] = { 'l', 'm', 'h', 'c' };
12211 	static char name[32];
12212 	minor_t minor;
12213 	int instance;
12214 	int nprt = 0;
12215 
12216 	minor = getminor(dev);
12217 	instance = ((minor & 0xff80) >> 5) | (minor & 3);
12218 	un = ddi_get_soft_state(st_state, instance);
12219 	if (un) {
12220 		ST_FUNC(ST_DEVINFO, st_dev_name);
12221 	}
12222 
12223 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
12224 
12225 	if (minor & MT_BSD) {
12226 		name[++nprt] = 'b';
12227 	}
12228 
12229 	if (minor & MT_NOREWIND) {
12230 		name[++nprt] = 'n';
12231 	}
12232 
12233 	/* NULL terminator */
12234 	name[++nprt] = 0;
12235 
12236 	return (name);
12237 }
12238 
12239 /*
12240  * Soft error reporting, so far unique to each drive
12241  *
12242  * Currently supported: exabyte and DAT soft error reporting
12243  */
12244 static int
12245 st_report_exabyte_soft_errors(dev_t dev, int flag)
12246 {
12247 	uchar_t *sensep;
12248 	int amt;
12249 	int rval = 0;
12250 	char cdb[CDB_GROUP0], *c = cdb;
12251 	struct uscsi_cmd *com;
12252 
12253 	GET_SOFT_STATE(dev);
12254 
12255 	ST_FUNC(ST_DEVINFO, st_report_exabyte_soft_errors);
12256 
12257 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12258 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
12259 	    dev, flag);
12260 
12261 	ASSERT(mutex_owned(ST_MUTEX));
12262 
12263 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12264 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
12265 
12266 	*c++ = SCMD_REQUEST_SENSE;
12267 	*c++ = 0;
12268 	*c++ = 0;
12269 	*c++ = 0;
12270 	*c++ = TAPE_SENSE_LENGTH;
12271 	/*
12272 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
12273 	 */
12274 	*c   = (char)0x80;
12275 
12276 	com->uscsi_cdb = cdb;
12277 	com->uscsi_cdblen = CDB_GROUP0;
12278 	com->uscsi_bufaddr = (caddr_t)sensep;
12279 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
12280 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
12281 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12282 
12283 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12284 	if (rval || com->uscsi_status) {
12285 		goto done;
12286 	}
12287 
12288 	/*
12289 	 * was there enough data?
12290 	 */
12291 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
12292 
12293 	if ((amt >= 19) && un->un_kbytes_xferred) {
12294 		uint_t count, error_rate;
12295 		uint_t rate;
12296 
12297 		if (sensep[21] & CLN) {
12298 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12299 			    "Periodic head cleaning required");
12300 		}
12301 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/ONE_K)) {
12302 			goto done;
12303 		}
12304 		/*
12305 		 * check if soft error reporting needs to be done.
12306 		 */
12307 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
12308 		count &= 0xffffff;
12309 		error_rate = (count * 100)/un->un_kbytes_xferred;
12310 
12311 #ifdef	STDEBUG
12312 		if (st_soft_error_report_debug) {
12313 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
12314 			    "Exabyte Soft Error Report:\n");
12315 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12316 			    "read/write error counter: %d\n", count);
12317 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12318 			    "number of bytes transferred: %dK\n",
12319 			    un->un_kbytes_xferred);
12320 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12321 			    "error_rate: %d%%\n", error_rate);
12322 
12323 			if (amt >= 22) {
12324 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12325 				    "unit sense: 0x%b 0x%b 0x%b\n",
12326 				    sensep[19], SENSE_19_BITS,
12327 				    sensep[20], SENSE_20_BITS,
12328 				    sensep[21], SENSE_21_BITS);
12329 			}
12330 			if (amt >= 27) {
12331 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12332 				    "tracking retry counter: %d\n",
12333 				    sensep[26]);
12334 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12335 				    "read/write retry counter: %d\n",
12336 				    sensep[27]);
12337 			}
12338 		}
12339 #endif
12340 
12341 		if (flag & FWRITE) {
12342 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
12343 		} else {
12344 			rate = EXABYTE_READ_ERROR_THRESHOLD;
12345 		}
12346 		if (error_rate >= rate) {
12347 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12348 			    "Soft error rate (%d%%) during %s was too high",
12349 			    error_rate,
12350 			    ((flag & FWRITE) ? wrg_str : rdg_str));
12351 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
12352 			    "Please, replace tape cartridge\n");
12353 		}
12354 	}
12355 
12356 done:
12357 	kmem_free(com, sizeof (*com));
12358 	kmem_free(sensep, TAPE_SENSE_LENGTH);
12359 
12360 	if (rval != 0) {
12361 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12362 		    "exabyte soft error reporting failed\n");
12363 	}
12364 	return (rval);
12365 }
12366 
12367 /*
12368  * this is very specific to Archive 4mm dat
12369  */
12370 #define	ONE_GIG	(ONE_K * ONE_K * ONE_K)
12371 
12372 static int
12373 st_report_dat_soft_errors(dev_t dev, int flag)
12374 {
12375 	uchar_t *sensep;
12376 	int amt, i;
12377 	int rval = 0;
12378 	char cdb[CDB_GROUP1], *c = cdb;
12379 	struct uscsi_cmd *com;
12380 	struct scsi_arq_status status;
12381 
12382 	GET_SOFT_STATE(dev);
12383 
12384 	ST_FUNC(ST_DEVINFO, st_report_dat_soft_errors);
12385 
12386 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12387 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12388 
12389 	ASSERT(mutex_owned(ST_MUTEX));
12390 
12391 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
12392 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
12393 
12394 	*c++ = SCMD_LOG_SENSE_G1;
12395 	*c++ = 0;
12396 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
12397 	*c++ = 0;
12398 	*c++ = 0;
12399 	*c++ = 0;
12400 	*c++ = 2;
12401 	*c++ = 0;
12402 	*c++ = (char)LOG_SENSE_LENGTH;
12403 	*c   = 0;
12404 	com->uscsi_cdb    = cdb;
12405 	com->uscsi_cdblen  = CDB_GROUP1;
12406 	com->uscsi_bufaddr = (caddr_t)sensep;
12407 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
12408 	com->uscsi_rqlen = sizeof (status);
12409 	com->uscsi_rqbuf = (caddr_t)&status;
12410 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
12411 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
12412 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12413 	if (rval) {
12414 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12415 		    "DAT soft error reporting failed\n");
12416 	}
12417 	if (rval || com->uscsi_status) {
12418 		goto done;
12419 	}
12420 
12421 	/*
12422 	 * was there enough data?
12423 	 */
12424 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
12425 
12426 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
12427 		int total, retries, param_code;
12428 
12429 		total = -1;
12430 		retries = -1;
12431 		amt = sensep[3] + 4;
12432 
12433 
12434 #ifdef STDEBUG
12435 		if (st_soft_error_report_debug) {
12436 			(void) printf("logsense:");
12437 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
12438 				if (i % 16 == 0) {
12439 					(void) printf("\t\n");
12440 				}
12441 				(void) printf(" %x", sensep[i]);
12442 			}
12443 			(void) printf("\n");
12444 		}
12445 #endif
12446 
12447 		/*
12448 		 * parse the param_codes
12449 		 */
12450 		if (sensep[0] == 2 || sensep[0] == 3) {
12451 			for (i = 4; i < amt; i++) {
12452 				param_code = (sensep[i++] << 8);
12453 				param_code += sensep[i++];
12454 				i++; /* skip control byte */
12455 				if (param_code == 5) {
12456 					if (sensep[i++] == 4) {
12457 						total = (sensep[i++] << 24);
12458 						total += (sensep[i++] << 16);
12459 						total += (sensep[i++] << 8);
12460 						total += sensep[i];
12461 					}
12462 				} else if (param_code == 0x8007) {
12463 					if (sensep[i++] == 2) {
12464 						retries = sensep[i++] << 8;
12465 						retries += sensep[i];
12466 					}
12467 				} else {
12468 					i += sensep[i];
12469 				}
12470 			}
12471 		}
12472 
12473 		/*
12474 		 * if the log sense returned valid numbers then determine
12475 		 * the read and write error thresholds based on the amount of
12476 		 * data transferred
12477 		 */
12478 
12479 		if (total > 0 && retries > 0) {
12480 			short normal_retries = 0;
12481 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12482 			    "total xferred (%s) =%x, retries=%x\n",
12483 			    ((flag & FWRITE) ? wrg_str : rdg_str),
12484 			    total, retries);
12485 
12486 			if (flag & FWRITE) {
12487 				if (total <=
12488 				    WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
12489 					normal_retries =
12490 					    DAT_SMALL_WRITE_ERROR_THRESHOLD;
12491 				} else {
12492 					normal_retries =
12493 					    DAT_LARGE_WRITE_ERROR_THRESHOLD;
12494 				}
12495 			} else {
12496 				if (total <=
12497 				    READ_SOFT_ERROR_WARNING_THRESHOLD) {
12498 					normal_retries =
12499 					    DAT_SMALL_READ_ERROR_THRESHOLD;
12500 				} else {
12501 					normal_retries =
12502 					    DAT_LARGE_READ_ERROR_THRESHOLD;
12503 				}
12504 			}
12505 
12506 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
12507 			"normal retries=%d\n", normal_retries);
12508 
12509 			if (retries >= normal_retries) {
12510 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
12511 				    "Soft error rate (retries = %d) during "
12512 				    "%s was too high",  retries,
12513 				    ((flag & FWRITE) ? wrg_str : rdg_str));
12514 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
12515 				    "Periodic head cleaning required "
12516 				    "and/or replace tape cartridge\n");
12517 			}
12518 
12519 		} else if (total == -1 || retries == -1) {
12520 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
12521 			    "log sense parameter code does not make sense\n");
12522 		}
12523 	}
12524 
12525 	/*
12526 	 * reset all values
12527 	 */
12528 	c = cdb;
12529 	*c++ = SCMD_LOG_SELECT_G1;
12530 	*c++ = 2;	/* this resets all values */
12531 	*c++ = (char)0xc0;
12532 	*c++ = 0;
12533 	*c++ = 0;
12534 	*c++ = 0;
12535 	*c++ = 0;
12536 	*c++ = 0;
12537 	*c++ = 0;
12538 	*c   = 0;
12539 	com->uscsi_bufaddr = NULL;
12540 	com->uscsi_buflen  = 0;
12541 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
12542 	rval = st_uscsi_cmd(un, com, FKIOCTL);
12543 	if (rval) {
12544 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
12545 		    "DAT soft error reset failed\n");
12546 	}
12547 done:
12548 	kmem_free(com, sizeof (*com));
12549 	kmem_free(sensep, LOG_SENSE_LENGTH);
12550 	return (rval);
12551 }
12552 
12553 static int
12554 st_report_soft_errors(dev_t dev, int flag)
12555 {
12556 	GET_SOFT_STATE(dev);
12557 
12558 	ST_FUNC(ST_DEVINFO, st_report_soft_errors);
12559 
12560 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12561 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
12562 
12563 	ASSERT(mutex_owned(ST_MUTEX));
12564 
12565 	switch (un->un_dp->type) {
12566 	case ST_TYPE_EXB8500:
12567 	case ST_TYPE_EXABYTE:
12568 		return (st_report_exabyte_soft_errors(dev, flag));
12569 		/*NOTREACHED*/
12570 	case ST_TYPE_PYTHON:
12571 		return (st_report_dat_soft_errors(dev, flag));
12572 		/*NOTREACHED*/
12573 	default:
12574 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
12575 		return (-1);
12576 	}
12577 }
12578 
12579 /*
12580  * persistent error routines
12581  */
12582 
12583 /*
12584  * enable persistent errors, and set the throttle appropriately, checking
12585  * for flush-on-errors capability
12586  */
12587 static void
12588 st_turn_pe_on(struct scsi_tape *un)
12589 {
12590 	ST_FUNC(ST_DEVINFO, st_turn_pe_on);
12591 
12592 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
12593 	ASSERT(mutex_owned(ST_MUTEX));
12594 
12595 	un->un_persistence = 1;
12596 
12597 	/*
12598 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
12599 	 * enabled.  This will simplify the error handling for request senses
12600 	 */
12601 
12602 	if (un->un_arq_enabled && un->un_untagged_qing) {
12603 		uchar_t f_o_e;
12604 
12605 		mutex_exit(ST_MUTEX);
12606 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
12607 		    1 : 0;
12608 		mutex_enter(ST_MUTEX);
12609 
12610 		un->un_flush_on_errors = f_o_e;
12611 	} else {
12612 		un->un_flush_on_errors = 0;
12613 	}
12614 
12615 	if (un->un_flush_on_errors)
12616 		un->un_max_throttle = (uchar_t)st_max_throttle;
12617 	else
12618 		un->un_max_throttle = 1;
12619 
12620 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
12621 		un->un_max_throttle = 1;
12622 
12623 	/* this will send a marker pkt */
12624 	st_clear_pe(un);
12625 }
12626 
12627 /*
12628  * This turns persistent errors permanently off
12629  */
12630 static void
12631 st_turn_pe_off(struct scsi_tape *un)
12632 {
12633 	ST_FUNC(ST_DEVINFO, st_turn_pe_off);
12634 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
12635 	ASSERT(mutex_owned(ST_MUTEX));
12636 
12637 	/* turn it off for good */
12638 	un->un_persistence = 0;
12639 
12640 	/* this will send a marker pkt */
12641 	st_clear_pe(un);
12642 
12643 	/* turn off flush on error capability, if enabled */
12644 	if (un->un_flush_on_errors) {
12645 		mutex_exit(ST_MUTEX);
12646 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
12647 		mutex_enter(ST_MUTEX);
12648 	}
12649 
12650 
12651 	un->un_flush_on_errors = 0;
12652 }
12653 
12654 /*
12655  * This clear persistent errors, allowing more commands through, and also
12656  * sending a marker packet.
12657  */
12658 static void
12659 st_clear_pe(struct scsi_tape *un)
12660 {
12661 	ST_FUNC(ST_DEVINFO, st_clear_pe);
12662 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
12663 	ASSERT(mutex_owned(ST_MUTEX));
12664 
12665 	un->un_persist_errors = 0;
12666 	un->un_throttle = un->un_last_throttle = 1;
12667 	un->un_errno = 0;
12668 	st_hba_unflush(un);
12669 }
12670 
12671 /*
12672  * This will flag persistent errors, shutting everything down, if the
12673  * application had enabled persistent errors via MTIOCPERSISTENT
12674  */
12675 static void
12676 st_set_pe_flag(struct scsi_tape *un)
12677 {
12678 	ST_FUNC(ST_DEVINFO, st_set_pe_flag);
12679 	ASSERT(mutex_owned(ST_MUTEX));
12680 
12681 	if (un->un_persistence) {
12682 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
12683 		un->un_persist_errors = 1;
12684 		un->un_throttle = un->un_last_throttle = 0;
12685 		cv_broadcast(&un->un_sbuf_cv);
12686 	}
12687 }
12688 
12689 static int
12690 st_do_reserve(struct scsi_tape *un)
12691 {
12692 	int rval;
12693 	int was_lost = un->un_rsvd_status & ST_LOST_RESERVE;
12694 
12695 	ST_FUNC(ST_DEVINFO, st_do_reserve);
12696 
12697 	/*
12698 	 * Issue a Throw-Away reserve command to clear the
12699 	 * check condition.
12700 	 * If the current behaviour of reserve/release is to
12701 	 * hold reservation across opens , and if a Bus reset
12702 	 * has been issued between opens then this command
12703 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
12704 	 * In this case return an EACCES so that user knows that
12705 	 * reservation has been lost in between opens.
12706 	 * If this error is not returned and we continue with
12707 	 * successful open , then user may think position of the
12708 	 * tape is still the same but inreality we would rewind the
12709 	 * tape and continue from BOT.
12710 	 */
12711 	rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12712 	if (rval) {
12713 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
12714 		    ST_LOST_RESERVE_BETWEEN_OPENS) {
12715 			un->un_rsvd_status &= ~(ST_LOST_RESERVE | ST_RESERVE);
12716 			un->un_errno = EACCES;
12717 			return (EACCES);
12718 		}
12719 		rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
12720 	}
12721 	if (rval == 0) {
12722 		un->un_rsvd_status |= ST_INIT_RESERVE;
12723 	}
12724 	if (was_lost) {
12725 		un->un_running.pmode = invalid;
12726 	}
12727 
12728 	return (rval);
12729 }
12730 
12731 static int
12732 st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb)
12733 {
12734 	int rval;
12735 	cmd_attribute const *attrib;
12736 
12737 	ST_FUNC(ST_DEVINFO, st_check_cdb_for_need_to_reserve);
12738 
12739 	/*
12740 	 * If already reserved no need to do it again.
12741 	 * Also if Reserve and Release are disabled Just return.
12742 	 */
12743 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12744 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12745 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12746 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12747 		    "st_check_cdb_for_need_to_reserve() reserve unneeded %s",
12748 		    st_print_scsi_cmd((uchar_t)cdb[0]));
12749 		return (0);
12750 	}
12751 
12752 	/* See if command is on the list */
12753 	attrib = st_lookup_cmd_attribute(cdb[0]);
12754 
12755 	if (attrib == NULL) {
12756 		rval = 1; /* Not found, when in doubt reserve */
12757 	} else if ((attrib->requires_reserve) != 0) {
12758 		rval = 1;
12759 	} else if ((attrib->reserve_byte) != 0) {
12760 		/*
12761 		 * cmd is on list.
12762 		 * if byte is zero always allowed.
12763 		 */
12764 		rval = 1;
12765 	} else if (((cdb[attrib->reserve_byte]) &
12766 	    (attrib->reserve_mask)) != 0) {
12767 		rval = 1;
12768 	} else {
12769 		rval = 0;
12770 	}
12771 
12772 	if (rval) {
12773 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12774 		    "Command %s requires reservation",
12775 		    st_print_scsi_cmd(cdb[0]));
12776 
12777 		rval = st_do_reserve(un);
12778 	}
12779 
12780 	return (rval);
12781 }
12782 
12783 static int
12784 st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd, int cnt)
12785 {
12786 	int rval;
12787 	cmd_attribute const *attrib;
12788 
12789 	ST_FUNC(ST_DEVINFO, st_check_cmd_for_need_to_reserve);
12790 
12791 	if ((un->un_rsvd_status & (ST_APPLICATION_RESERVATIONS)) ||
12792 	    ((un->un_rsvd_status & (ST_RESERVE | ST_LOST_RESERVE)) ==
12793 	    ST_RESERVE) || (un->un_dp->options & ST_NO_RESERVE_RELEASE)) {
12794 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12795 		    "st_check_cmd_for_need_to_reserve() reserve unneeded %s",
12796 		    st_print_scsi_cmd(cmd));
12797 		return (0);
12798 	}
12799 
12800 	/* search for this command on the list */
12801 	attrib = st_lookup_cmd_attribute(cmd);
12802 
12803 	if (attrib == NULL) {
12804 		rval = 1; /* Not found, when in doubt reserve */
12805 	} else if ((attrib->requires_reserve) != 0) {
12806 		rval = 1;
12807 	} else if ((attrib->reserve_byte) != 0) {
12808 		/*
12809 		 * cmd is on list.
12810 		 * if byte is zero always allowed.
12811 		 */
12812 		rval = 1;
12813 	} else if (((attrib->reserve_mask) & cnt) != 0) {
12814 		rval = 1;
12815 	} else {
12816 		rval = 0;
12817 	}
12818 
12819 	if (rval) {
12820 		ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
12821 		    "Cmd %s requires reservation", st_print_scsi_cmd(cmd));
12822 
12823 		rval = st_do_reserve(un);
12824 	}
12825 
12826 	return (rval);
12827 }
12828 
12829 static int
12830 st_reserve_release(struct scsi_tape *un, int cmd, ubufunc_t ubf)
12831 {
12832 	struct uscsi_cmd	uscsi_cmd;
12833 	int			rval;
12834 	char			cdb[CDB_GROUP0];
12835 	struct scsi_arq_status	stat;
12836 
12837 
12838 
12839 	ST_FUNC(ST_DEVINFO, st_reserve_release);
12840 
12841 	ASSERT(mutex_owned(ST_MUTEX));
12842 
12843 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12844 	    "st_reserve_release: %s \n",
12845 	    (cmd == ST_RELEASE)?  "Releasing":"Reserving");
12846 
12847 	bzero(&cdb, CDB_GROUP0);
12848 	if (cmd == ST_RELEASE) {
12849 		cdb[0] = SCMD_RELEASE;
12850 	} else {
12851 		cdb[0] = SCMD_RESERVE;
12852 	}
12853 	bzero(&uscsi_cmd, sizeof (struct uscsi_cmd));
12854 	uscsi_cmd.uscsi_flags = USCSI_WRITE | USCSI_RQENABLE;
12855 	uscsi_cmd.uscsi_cdb = cdb;
12856 	uscsi_cmd.uscsi_cdblen = CDB_GROUP0;
12857 	uscsi_cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
12858 	uscsi_cmd.uscsi_rqbuf = (caddr_t)&stat;
12859 	uscsi_cmd.uscsi_rqlen = sizeof (stat);
12860 
12861 	rval = ubf(un, &uscsi_cmd, FKIOCTL);
12862 
12863 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12864 	    "st_reserve_release: rval(1)=%d\n", rval);
12865 
12866 	if (rval) {
12867 		if (uscsi_cmd.uscsi_status == STATUS_RESERVATION_CONFLICT) {
12868 			rval = EACCES;
12869 		}
12870 		/*
12871 		 * dynamically turn off reserve/release support
12872 		 * in case of drives which do not support
12873 		 * reserve/release command(ATAPI drives).
12874 		 */
12875 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
12876 			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
12877 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
12878 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12879 				    "Tape unit does not support "
12880 				    "reserve/release \n");
12881 			}
12882 			rval = 0;
12883 		}
12884 	}
12885 	return (rval);
12886 }
12887 
12888 static int
12889 st_take_ownership(struct scsi_tape *un, ubufunc_t ubf)
12890 {
12891 	int rval;
12892 
12893 	ST_FUNC(ST_DEVINFO, st_take_ownership);
12894 
12895 	ASSERT(mutex_owned(ST_MUTEX));
12896 
12897 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
12898 	    "st_take_ownership: Entering ...\n");
12899 
12900 
12901 	rval = st_reserve_release(un, ST_RESERVE, ubf);
12902 	/*
12903 	 * XXX -> Should reset be done only if we get EACCES.
12904 	 * .
12905 	 */
12906 	if (rval) {
12907 		if (st_reset(un, RESET_LUN) == 0) {
12908 			return (EIO);
12909 		}
12910 		un->un_rsvd_status &=
12911 		    ~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
12912 
12913 		mutex_exit(ST_MUTEX);
12914 		delay(drv_usectohz(ST_RESERVATION_DELAY));
12915 		mutex_enter(ST_MUTEX);
12916 		/*
12917 		 * remove the check condition.
12918 		 */
12919 		(void) st_reserve_release(un, ST_RESERVE, ubf);
12920 		rval = st_reserve_release(un, ST_RESERVE, ubf);
12921 		if (rval != 0) {
12922 			if ((st_reserve_release(un, ST_RESERVE, ubf))
12923 			    != 0) {
12924 				rval = (un->un_rsvd_status &
12925 				    ST_RESERVATION_CONFLICT) ? EACCES : EIO;
12926 				return (rval);
12927 			}
12928 		}
12929 		/*
12930 		 * Set tape state to ST_STATE_OFFLINE , in case if
12931 		 * the user wants to continue and start using
12932 		 * the tape.
12933 		 */
12934 		un->un_state = ST_STATE_OFFLINE;
12935 		un->un_rsvd_status |= ST_INIT_RESERVE;
12936 	}
12937 	return (rval);
12938 }
12939 
12940 static int
12941 st_create_errstats(struct scsi_tape *un, int instance)
12942 {
12943 	char	kstatname[KSTAT_STRLEN];
12944 
12945 	ST_FUNC(ST_DEVINFO, st_create_errstats);
12946 
12947 	/*
12948 	 * Create device error kstats
12949 	 */
12950 
12951 	if (un->un_errstats == (kstat_t *)0) {
12952 		(void) sprintf(kstatname, "st%d,err", instance);
12953 		un->un_errstats = kstat_create("sterr", instance, kstatname,
12954 		    "device_error", KSTAT_TYPE_NAMED,
12955 		    sizeof (struct st_errstats) / sizeof (kstat_named_t),
12956 		    KSTAT_FLAG_PERSISTENT);
12957 
12958 		if (un->un_errstats) {
12959 			struct st_errstats	*stp;
12960 
12961 			stp = (struct st_errstats *)un->un_errstats->ks_data;
12962 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
12963 			    KSTAT_DATA_ULONG);
12964 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
12965 			    KSTAT_DATA_ULONG);
12966 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
12967 			    KSTAT_DATA_ULONG);
12968 			kstat_named_init(&stp->st_vid, "Vendor",
12969 			    KSTAT_DATA_CHAR);
12970 			kstat_named_init(&stp->st_pid, "Product",
12971 			    KSTAT_DATA_CHAR);
12972 			kstat_named_init(&stp->st_revision, "Revision",
12973 			    KSTAT_DATA_CHAR);
12974 			kstat_named_init(&stp->st_serial, "Serial No",
12975 			    KSTAT_DATA_CHAR);
12976 			un->un_errstats->ks_private = un;
12977 			un->un_errstats->ks_update = nulldev;
12978 			kstat_install(un->un_errstats);
12979 			/*
12980 			 * Fill in the static data
12981 			 */
12982 			(void) strncpy(&stp->st_vid.value.c[0],
12983 			    ST_INQUIRY->inq_vid, 8);
12984 			/*
12985 			 * XXX:  Emulex MT-02 (and emulators) predates
12986 			 *	 SCSI-1 and has no vid & pid inquiry data.
12987 			 */
12988 			if (ST_INQUIRY->inq_len != 0) {
12989 				(void) strncpy(&stp->st_pid.value.c[0],
12990 				    ST_INQUIRY->inq_pid, 16);
12991 				(void) strncpy(&stp->st_revision.value.c[0],
12992 				    ST_INQUIRY->inq_revision, 4);
12993 				(void) strncpy(&stp->st_serial.value.c[0],
12994 				    ST_INQUIRY->inq_serial, 12);
12995 			}
12996 		}
12997 	}
12998 	return (0);
12999 }
13000 
13001 static int
13002 st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos)
13003 {
13004 	int rval;
13005 	bufunc_t bf = (ubf == st_uscsi_rcmd) ? st_rcmd : st_cmd;
13006 
13007 	ST_FUNC(ST_DEVINFO, st_validate_tapemarks);
13008 
13009 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
13010 	ASSERT(mutex_owned(ST_MUTEX));
13011 
13012 	/* Can't restore an invalid position */
13013 	if (pos->pmode == invalid) {
13014 		return (4);
13015 	}
13016 
13017 	/*
13018 	 * Assumtions:
13019 	 *	If a position was read and is in logical position mode.
13020 	 *	If a drive supports read position it supports locate.
13021 	 *	If the read position type is not NO_POS. even though
13022 	 *	   a read position make not have been attemped yet.
13023 	 *
13024 	 *	The drive can locate to the position.
13025 	 */
13026 	if (pos->pmode == logical || un->un_read_pos_type != NO_POS) {
13027 		/*
13028 		 * If position mode is logical or legacy mode try
13029 		 * to locate there as it is faster.
13030 		 * If it fails try the old way.
13031 		 */
13032 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13033 		    "Restoring tape position to lgclblkbo=0x%"PRIx64"....",
13034 		    pos->lgclblkno);
13035 
13036 		if (st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
13037 		    pos->lgclblkno, pos->partition) == 0) {
13038 			/* Assume we are there copy rest of position back */
13039 			if (un->un_pos.lgclblkno == pos->lgclblkno) {
13040 				COPY_POS(&un->un_pos, pos);
13041 			}
13042 			return (0);
13043 		}
13044 
13045 		/*
13046 		 * If logical block locate failed to restore a logical
13047 		 * position, can't recover.
13048 		 */
13049 		if (pos->pmode == logical) {
13050 			return (-1);
13051 		}
13052 	}
13053 
13054 
13055 	scsi_log(ST_DEVINFO, st_label, CE_NOTE,
13056 	    "Restoring tape position at fileno=%x, blkno=%x....",
13057 	    pos->fileno, pos->blkno);
13058 
13059 	/*
13060 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
13061 	 * so as not to rewind tape on RESETS: Gee, Has life ever
13062 	 * been simple in tape land ?
13063 	 */
13064 	rval = bf(un, SCMD_REWIND, 0, SYNC_CMD);
13065 	if (rval) {
13066 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
13067 		    "Failed to restore the last file and block position: In"
13068 		    " this state, Tape will be loaded at BOT during next open");
13069 		un->un_pos.pmode = invalid;
13070 		return (rval);
13071 	}
13072 
13073 	/* If the position was as the result of back space file */
13074 	if (pos->blkno > (INF / 2)) {
13075 		/* Go one extra file forward */
13076 		pos->fileno++;
13077 		/* Figure how many blocks to back into the previous file */
13078 		pos->blkno = -(INF - pos->blkno);
13079 	}
13080 
13081 	/* Go to requested fileno */
13082 	if (pos->fileno) {
13083 		rval = st_cmd(un, SCMD_SPACE, Fmk(pos->fileno), SYNC_CMD);
13084 		if (rval) {
13085 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13086 			    "Failed to restore the last file position: In this "
13087 			    " state, Tape will be loaded at BOT during next"
13088 			    " open %d", __LINE__);
13089 			un->un_pos.pmode = invalid;
13090 			pos->pmode = invalid;
13091 			return (rval);
13092 		}
13093 	}
13094 
13095 	/*
13096 	 * If backing into a file we already did an extra file forward.
13097 	 * Now we have to back over the filemark to get to the end of
13098 	 * the previous file. The blkno has been ajusted to a negative
13099 	 * value so we will get to the expected location.
13100 	 */
13101 	if (pos->blkno) {
13102 		rval = bf(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
13103 		if (rval) {
13104 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
13105 			    "Failed to restore the last file position: In this "
13106 			    " state, Tape will be loaded at BOT during next"
13107 			    " open %d", __LINE__);
13108 			un->un_pos.pmode = invalid;
13109 			pos->pmode = invalid;
13110 			return (rval);
13111 		}
13112 	}
13113 
13114 	/*
13115 	 * The position mode, block and fileno should be correct,
13116 	 * This updates eof and logical position information.
13117 	 */
13118 	un->un_pos.eof = pos->eof;
13119 	un->un_pos.lgclblkno = pos->lgclblkno;
13120 
13121 	return (0);
13122 }
13123 
13124 /*
13125  * check sense key, ASC, ASCQ in order to determine if the tape needs
13126  * to be ejected
13127  */
13128 
13129 static int
13130 st_check_asc_ascq(struct scsi_tape *un)
13131 {
13132 	struct scsi_extended_sense *sensep = ST_RQSENSE;
13133 	struct tape_failure_code   *code;
13134 
13135 	ST_FUNC(ST_DEVINFO, st_check_asc_ascq);
13136 
13137 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
13138 		if ((code->key  == sensep->es_key) &&
13139 		    (code->add_code  == sensep->es_add_code) &&
13140 		    (code->qual_code == sensep->es_qual_code))
13141 			return (1);
13142 	}
13143 	return (0);
13144 }
13145 
13146 /*
13147  * st_logpage_supported() sends a Log Sense command with
13148  * page code = 0 = Supported Log Pages Page to the device,
13149  * to see whether the page 'page' is supported.
13150  * Return values are:
13151  * -1 if the Log Sense command fails
13152  * 0 if page is not supported
13153  * 1 if page is supported
13154  */
13155 
13156 static int
13157 st_logpage_supported(struct scsi_tape *un, uchar_t page)
13158 {
13159 	uchar_t *sp, *sensep;
13160 	unsigned length;
13161 	struct uscsi_cmd *com;
13162 	struct scsi_arq_status status;
13163 	int rval;
13164 	char cdb[CDB_GROUP1] = {
13165 		SCMD_LOG_SENSE_G1,
13166 		0,
13167 		SUPPORTED_LOG_PAGES_PAGE,
13168 		0,
13169 		0,
13170 		0,
13171 		0,
13172 		0,
13173 		(char)LOG_SENSE_LENGTH,
13174 		0
13175 	};
13176 
13177 	ST_FUNC(ST_DEVINFO, st_logpage_supported);
13178 
13179 	ASSERT(mutex_owned(ST_MUTEX));
13180 
13181 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13182 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
13183 
13184 	com->uscsi_cdb = cdb;
13185 	com->uscsi_cdblen = CDB_GROUP1;
13186 	com->uscsi_bufaddr = (caddr_t)sensep;
13187 	com->uscsi_buflen = LOG_SENSE_LENGTH;
13188 	com->uscsi_rqlen = sizeof (status);
13189 	com->uscsi_rqbuf = (caddr_t)&status;
13190 	com->uscsi_flags =
13191 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13192 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13193 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13194 	if (rval || com->uscsi_status) {
13195 		/* uscsi-command failed */
13196 		rval = -1;
13197 	} else {
13198 
13199 		sp = sensep + 3;
13200 
13201 		for (length = *sp++; length > 0; length--, sp++) {
13202 
13203 			if (*sp == page) {
13204 				rval = 1;
13205 				break;
13206 			}
13207 		}
13208 	}
13209 	kmem_free(com, sizeof (struct uscsi_cmd));
13210 	kmem_free(sensep, LOG_SENSE_LENGTH);
13211 	return (rval);
13212 }
13213 
13214 
13215 /*
13216  * st_check_clean_bit() gets the status of the tape's cleaning bit.
13217  *
13218  * If the device does support the TapeAlert log page, then the cleaning bit
13219  * information will be read from this page. Otherwise we will see if one of
13220  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
13221  * the device, which means, that we can get the cleaning bit information via
13222  * a RequestSense command.
13223  * If both methods of getting cleaning bit information are not supported
13224  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
13225  * returns with
13226  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
13227  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
13228  * If the call to st_uscsi_cmd() to do the Log Sense or the Request Sense
13229  * command fails, or if the amount of Request Sense data is not enough, then
13230  *  st_check_clean_bit() returns with -1.
13231  */
13232 
13233 static int
13234 st_check_clean_bit(struct scsi_tape *un)
13235 {
13236 	int rval = 0;
13237 
13238 	ST_FUNC(ST_DEVINFO, st_check_clean_bit);
13239 
13240 	ASSERT(mutex_owned(ST_MUTEX));
13241 
13242 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
13243 		return (rval);
13244 	}
13245 
13246 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13247 
13248 		rval = st_logpage_supported(un, TAPE_SEQUENTIAL_PAGE);
13249 		if (rval == -1) {
13250 			return (0);
13251 		}
13252 		if (rval == 1) {
13253 
13254 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
13255 		}
13256 
13257 		rval = st_logpage_supported(un, TAPE_ALERT_PAGE);
13258 		if (rval == -1) {
13259 			return (0);
13260 		}
13261 		if (rval == 1) {
13262 
13263 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
13264 		}
13265 
13266 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
13267 
13268 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
13269 		}
13270 	}
13271 
13272 	rval = 0;
13273 
13274 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
13275 
13276 		rval = st_check_sequential_clean_bit(un);
13277 		if (rval == -1) {
13278 			return (0);
13279 		}
13280 	}
13281 
13282 	if ((rval == 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
13283 
13284 		rval = st_check_alert_flags(un);
13285 		if (rval == -1) {
13286 			return (0);
13287 		}
13288 	}
13289 
13290 	if ((rval == 0) && (un->un_dp->options & ST_CLN_MASK)) {
13291 
13292 		rval = st_check_sense_clean_bit(un);
13293 		if (rval == -1) {
13294 			return (0);
13295 		}
13296 	}
13297 
13298 	/*
13299 	 * If found a supported means to check need to clean.
13300 	 */
13301 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
13302 
13303 		/*
13304 		 * head needs to be cleaned.
13305 		 */
13306 		if (rval & MTF_TAPE_HEAD_DIRTY) {
13307 
13308 			/*
13309 			 * Print log message only first time
13310 			 * found needing cleaned.
13311 			 */
13312 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
13313 
13314 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
13315 				    "Periodic head cleaning required");
13316 
13317 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
13318 			}
13319 
13320 		} else {
13321 
13322 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
13323 		}
13324 	}
13325 
13326 	return (rval);
13327 }
13328 
13329 
13330 static int
13331 st_check_sequential_clean_bit(struct scsi_tape *un)
13332 {
13333 	int rval;
13334 	int ix;
13335 	ushort_t parameter;
13336 	struct uscsi_cmd *cmd;
13337 	struct log_sequential_page *sp;
13338 	struct log_sequential_page_parameter *prm;
13339 	struct scsi_arq_status status;
13340 	char cdb[CDB_GROUP1] = {
13341 		SCMD_LOG_SENSE_G1,
13342 		0,
13343 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
13344 		0,
13345 		0,
13346 		0,
13347 		0,
13348 		(char)(sizeof (struct log_sequential_page) >> 8),
13349 		(char)(sizeof (struct log_sequential_page)),
13350 		0
13351 	};
13352 
13353 	ST_FUNC(ST_DEVINFO, st_check_sequential_clean_bit);
13354 
13355 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13356 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
13357 
13358 	cmd->uscsi_flags   =
13359 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13360 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13361 	cmd->uscsi_cdb	   = cdb;
13362 	cmd->uscsi_cdblen  = CDB_GROUP1;
13363 	cmd->uscsi_bufaddr = (caddr_t)sp;
13364 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
13365 	cmd->uscsi_rqlen   = sizeof (status);
13366 	cmd->uscsi_rqbuf   = (caddr_t)&status;
13367 
13368 	rval = st_uscsi_cmd(un, cmd, FKIOCTL);
13369 
13370 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
13371 
13372 		rval = -1;
13373 
13374 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
13375 
13376 		rval = -1;
13377 	}
13378 
13379 	prm = &sp->param[0];
13380 
13381 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
13382 
13383 		if (prm->log_param.length == 0) {
13384 			break;
13385 		}
13386 
13387 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
13388 		    (prm->log_param.pc_lo & 0xff));
13389 
13390 		if (parameter == SEQUENTIAL_NEED_CLN) {
13391 
13392 			rval = MTF_TAPE_CLN_SUPPORTED;
13393 			if (prm->param_value[prm->log_param.length - 1]) {
13394 
13395 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13396 				    "sequential log says head dirty\n");
13397 				rval |= MTF_TAPE_HEAD_DIRTY;
13398 			}
13399 		}
13400 		prm = (struct log_sequential_page_parameter *)
13401 		    &prm->param_value[prm->log_param.length];
13402 	}
13403 
13404 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13405 	kmem_free(sp,  sizeof (struct log_sequential_page));
13406 
13407 	return (rval);
13408 }
13409 
13410 
13411 static int
13412 st_check_alert_flags(struct scsi_tape *un)
13413 {
13414 	struct st_tape_alert *ta;
13415 	struct uscsi_cmd *com;
13416 	struct scsi_arq_status status;
13417 	unsigned ix, length;
13418 	int rval;
13419 	tape_alert_flags flag;
13420 	char cdb[CDB_GROUP1] = {
13421 		SCMD_LOG_SENSE_G1,
13422 		0,
13423 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
13424 		0,
13425 		0,
13426 		0,
13427 		0,
13428 		(char)(sizeof (struct st_tape_alert) >> 8),
13429 		(char)(sizeof (struct st_tape_alert)),
13430 		0
13431 	};
13432 
13433 	ST_FUNC(ST_DEVINFO, st_check_alert_clean_bit);
13434 
13435 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13436 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
13437 
13438 	com->uscsi_cdb = cdb;
13439 	com->uscsi_cdblen = CDB_GROUP1;
13440 	com->uscsi_bufaddr = (caddr_t)ta;
13441 	com->uscsi_buflen = sizeof (struct st_tape_alert);
13442 	com->uscsi_rqlen = sizeof (status);
13443 	com->uscsi_rqbuf = (caddr_t)&status;
13444 	com->uscsi_flags =
13445 	    USCSI_DIAGNOSE | USCSI_RQENABLE | USCSI_READ;
13446 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13447 
13448 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13449 
13450 	if (rval || com->uscsi_status || com->uscsi_resid) {
13451 
13452 		rval = -1; /* uscsi-command failed */
13453 
13454 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
13455 
13456 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13457 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
13458 		rval = -1;
13459 	}
13460 
13461 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
13462 
13463 
13464 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
13465 
13466 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13467 		    "TapeAlert length %d\n", length);
13468 	}
13469 
13470 
13471 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
13472 
13473 		/*
13474 		 * if rval is bad before the first pass don't bother
13475 		 */
13476 		if (ix == 0 && rval != 0) {
13477 
13478 			break;
13479 		}
13480 
13481 		flag = ((ta->param[ix].log_param.pc_hi << 8) +
13482 		    ta->param[ix].log_param.pc_lo);
13483 
13484 		if ((ta->param[ix].param_value & 1) == 0) {
13485 			continue;
13486 		}
13487 		/*
13488 		 * check to see if current parameter is of interest.
13489 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
13490 		 */
13491 		if ((flag == TAF_CLEAN_NOW) ||
13492 		    (flag == TAF_CLEAN_PERIODIC) ||
13493 		    ((flag == CLEAN_FOR_ERRORS) &&
13494 		    (un->un_dp->type == ST_TYPE_STK9840))) {
13495 
13496 			rval = MTF_TAPE_CLN_SUPPORTED;
13497 
13498 
13499 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13500 			    "alert_page drive needs clean %d\n", flag);
13501 			un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
13502 			rval |= MTF_TAPE_HEAD_DIRTY;
13503 
13504 		} else if (flag == TAF_CLEANING_MEDIA) {
13505 
13506 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13507 			    "alert_page drive was cleaned\n");
13508 			un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
13509 		}
13510 
13511 	}
13512 
13513 	/*
13514 	 * Report it as dirty till we see it cleaned
13515 	 */
13516 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
13517 
13518 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13519 		    "alert_page still dirty\n");
13520 		rval |= MTF_TAPE_HEAD_DIRTY;
13521 	}
13522 
13523 	kmem_free(com, sizeof (struct uscsi_cmd));
13524 	kmem_free(ta,  sizeof (struct st_tape_alert));
13525 
13526 	return (rval);
13527 }
13528 
13529 
13530 static int
13531 st_check_sense_clean_bit(struct scsi_tape *un)
13532 {
13533 	uchar_t *sensep;
13534 	char cdb[CDB_GROUP0];
13535 	struct uscsi_cmd *com;
13536 	ushort_t byte_pos;
13537 	uchar_t bit_mask;
13538 	unsigned length;
13539 	int index;
13540 	int rval;
13541 
13542 	ST_FUNC(ST_DEVINFO, st_check_sense_clean_bit);
13543 
13544 	/*
13545 	 * Since this tape does not support Tape Alert,
13546 	 * we now try to get the cleanbit status via
13547 	 * Request Sense.
13548 	 */
13549 
13550 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
13551 
13552 		index = 0;
13553 
13554 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
13555 
13556 		index = 1;
13557 
13558 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
13559 
13560 		index = 2;
13561 
13562 	} else {
13563 
13564 		return (-1);
13565 	}
13566 
13567 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
13568 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
13569 	length = byte_pos + 1;
13570 
13571 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13572 	sensep = kmem_zalloc(length, KM_SLEEP);
13573 
13574 	cdb[0] = SCMD_REQUEST_SENSE;
13575 	cdb[1] = 0;
13576 	cdb[2] = 0;
13577 	cdb[3] = 0;
13578 	cdb[4] = (char)length;
13579 	cdb[5] = 0;
13580 
13581 	com->uscsi_cdb = cdb;
13582 	com->uscsi_cdblen = CDB_GROUP0;
13583 	com->uscsi_bufaddr = (caddr_t)sensep;
13584 	com->uscsi_buflen = length;
13585 	com->uscsi_flags =
13586 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
13587 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
13588 
13589 	rval = st_uscsi_cmd(un, com, FKIOCTL);
13590 
13591 	if (rval || com->uscsi_status || com->uscsi_resid) {
13592 
13593 		rval = -1;
13594 
13595 	} else {
13596 
13597 		rval = MTF_TAPE_CLN_SUPPORTED;
13598 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
13599 
13600 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13601 			    "sense data says head dirty\n");
13602 			rval |= MTF_TAPE_HEAD_DIRTY;
13603 		}
13604 	}
13605 
13606 	kmem_free(com, sizeof (struct uscsi_cmd));
13607 	kmem_free(sensep, length);
13608 	return (rval);
13609 }
13610 
13611 /*
13612  * st_clear_unit_attention
13613  *
13614  *  	run test unit ready's to clear out outstanding
13615  * 	unit attentions.
13616  * 	returns zero for SUCCESS or the errno from st_cmd call
13617  */
13618 static int
13619 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
13620 {
13621 	int	i    = 0;
13622 	int	rval;
13623 
13624 	GET_SOFT_STATE(dev_instance);
13625 	ST_FUNC(ST_DEVINFO, st_clear_unit_attentions);
13626 
13627 	do {
13628 		rval = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
13629 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
13630 	return (rval);
13631 }
13632 
13633 static void
13634 st_calculate_timeouts(struct scsi_tape *un)
13635 {
13636 	ST_FUNC(ST_DEVINFO, st_calculate_timeouts);
13637 
13638 	if (un->un_dp->non_motion_timeout == 0) {
13639 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13640 			un->un_dp->non_motion_timeout =
13641 			    st_io_time * st_long_timeout_x;
13642 		} else {
13643 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
13644 		}
13645 	}
13646 
13647 	if (un->un_dp->io_timeout == 0) {
13648 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13649 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
13650 		} else {
13651 			un->un_dp->io_timeout = (ushort_t)st_io_time;
13652 		}
13653 	}
13654 
13655 	if (un->un_dp->rewind_timeout == 0) {
13656 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13657 			un->un_dp->rewind_timeout =
13658 			    st_space_time * st_long_timeout_x;
13659 		} else {
13660 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
13661 		}
13662 	}
13663 
13664 	if (un->un_dp->space_timeout == 0) {
13665 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13666 			un->un_dp->space_timeout =
13667 			    st_space_time * st_long_timeout_x;
13668 		} else {
13669 			un->un_dp->space_timeout = (ushort_t)st_space_time;
13670 		}
13671 	}
13672 
13673 	if (un->un_dp->load_timeout == 0) {
13674 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13675 			un->un_dp->load_timeout =
13676 			    st_space_time * st_long_timeout_x;
13677 		} else {
13678 			un->un_dp->load_timeout = (ushort_t)st_space_time;
13679 		}
13680 	}
13681 
13682 	if (un->un_dp->unload_timeout == 0) {
13683 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
13684 			un->un_dp->unload_timeout =
13685 			    st_space_time * st_long_timeout_x;
13686 		} else {
13687 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
13688 		}
13689 	}
13690 
13691 	if (un->un_dp->erase_timeout == 0) {
13692 		if (un->un_dp->options & ST_LONG_ERASE) {
13693 			un->un_dp->erase_timeout =
13694 			    st_space_time * st_long_space_time_x;
13695 		} else {
13696 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
13697 		}
13698 	}
13699 }
13700 
13701 
13702 static writablity
13703 st_is_not_wormable(struct scsi_tape *un)
13704 {
13705 	ST_FUNC(ST_DEVINFO, st_is_not_wormable);
13706 	return (RDWR);
13707 }
13708 
13709 static writablity
13710 st_is_hp_dat_tape_worm(struct scsi_tape *un)
13711 {
13712 	writablity wrt;
13713 
13714 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_tape_worm);
13715 
13716 	/* Mode sense should be current */
13717 	if (un->un_mspl->media_type == 1) {
13718 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13719 		    "Drive has WORM media loaded\n");
13720 		wrt = WORM;
13721 	} else {
13722 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13723 		    "Drive has non WORM media loaded\n");
13724 		wrt = RDWR;
13725 	}
13726 	return (wrt);
13727 }
13728 
13729 #define	HP_DAT_INQUIRY 0x4A
13730 static writablity
13731 st_is_hp_dat_worm(struct scsi_tape *un)
13732 {
13733 	char *buf;
13734 	int result;
13735 	writablity wrt;
13736 
13737 	ST_FUNC(ST_DEVINFO, st_is_hp_dat_worm);
13738 
13739 	buf = kmem_zalloc(HP_DAT_INQUIRY, KM_SLEEP);
13740 
13741 	result = st_get_special_inquiry(un, HP_DAT_INQUIRY, buf, 0);
13742 
13743 	if (result != 0) {
13744 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13745 		    "Read Standard Inquiry for WORM support failed");
13746 		wrt = FAILED;
13747 	} else if ((buf[40] & 1) == 0) {
13748 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13749 		    "Drive is NOT WORMable\n");
13750 		/* This drive doesn't support it so don't check again */
13751 		un->un_dp->options &= ~ST_WORMABLE;
13752 		wrt = RDWR;
13753 		un->un_wormable = st_is_not_wormable;
13754 	} else {
13755 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13756 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13757 		un->un_wormable = st_is_hp_dat_tape_worm;
13758 		wrt = un->un_wormable(un);
13759 	}
13760 
13761 	kmem_free(buf, HP_DAT_INQUIRY);
13762 
13763 	/*
13764 	 * If drive doesn't support it no point in checking further.
13765 	 */
13766 	return (wrt);
13767 }
13768 
13769 static writablity
13770 st_is_hp_lto_tape_worm(struct scsi_tape *un)
13771 {
13772 	writablity wrt;
13773 
13774 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_tape_worm);
13775 
13776 	/* Mode sense should be current */
13777 	switch (un->un_mspl->media_type) {
13778 	case 0x00:
13779 		switch (un->un_mspl->density) {
13780 		case 0x40:
13781 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13782 			    "Drive has standard Gen I media loaded\n");
13783 			break;
13784 		case 0x42:
13785 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13786 			    "Drive has standard Gen II media loaded\n");
13787 			break;
13788 		case 0x44:
13789 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13790 			    "Drive has standard Gen III media loaded\n");
13791 			break;
13792 		case 0x46:
13793 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13794 			    "Drive has standard Gen IV media loaded\n");
13795 			break;
13796 		default:
13797 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13798 			    "Drive has standard unknown 0x%X media loaded\n",
13799 			    un->un_mspl->density);
13800 		}
13801 		wrt = RDWR;
13802 		break;
13803 	case 0x01:
13804 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13805 		    "Drive has WORM medium loaded\n");
13806 		wrt = WORM;
13807 		break;
13808 	case 0x80:
13809 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13810 		    "Drive has CD-ROM emulation medium loaded\n");
13811 		wrt = WORM;
13812 		break;
13813 	default:
13814 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13815 		    "Drive has an unexpected medium type 0x%X loaded\n",
13816 		    un->un_mspl->media_type);
13817 		wrt = RDWR;
13818 	}
13819 
13820 	return (wrt);
13821 }
13822 
13823 #define	LTO_REQ_INQUIRY 44
13824 static writablity
13825 st_is_hp_lto_worm(struct scsi_tape *un)
13826 {
13827 	char *buf;
13828 	int result;
13829 	writablity wrt;
13830 
13831 	ST_FUNC(ST_DEVINFO, st_is_hp_lto_worm);
13832 
13833 	buf = kmem_zalloc(LTO_REQ_INQUIRY, KM_SLEEP);
13834 
13835 	result = st_get_special_inquiry(un, LTO_REQ_INQUIRY, buf, 0);
13836 
13837 	if (result != 0) {
13838 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13839 		    "Read Standard Inquiry for WORM support failed");
13840 		wrt = FAILED;
13841 	} else if ((buf[40] & 1) == 0) {
13842 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13843 		    "Drive is NOT WORMable\n");
13844 		/* This drive doesn't support it so don't check again */
13845 		un->un_dp->options &= ~ST_WORMABLE;
13846 		wrt = RDWR;
13847 		un->un_wormable = st_is_not_wormable;
13848 	} else {
13849 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13850 		    "Drive supports WORM version %d\n", buf[40] >> 1);
13851 		un->un_wormable = st_is_hp_lto_tape_worm;
13852 		wrt = un->un_wormable(un);
13853 	}
13854 
13855 	kmem_free(buf, LTO_REQ_INQUIRY);
13856 
13857 	/*
13858 	 * If drive doesn't support it no point in checking further.
13859 	 */
13860 	return (wrt);
13861 }
13862 
13863 static writablity
13864 st_is_t10_worm_device(struct scsi_tape *un)
13865 {
13866 	writablity wrt;
13867 
13868 	ST_FUNC(ST_DEVINFO, st_is_t10_worm_device);
13869 
13870 	if (un->un_mspl->media_type == 0x3c) {
13871 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13872 		    "Drive has WORM media loaded\n");
13873 		wrt = WORM;
13874 	} else {
13875 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13876 		    "Drive has non WORM media loaded\n");
13877 		wrt = RDWR;
13878 	}
13879 	return (wrt);
13880 }
13881 
13882 #define	SEQ_CAP_PAGE	(char)0xb0
13883 static writablity
13884 st_is_t10_worm(struct scsi_tape *un)
13885 {
13886 	char *buf;
13887 	int result;
13888 	writablity wrt;
13889 
13890 	ST_FUNC(ST_DEVINFO, st_is_t10_worm);
13891 
13892 	buf = kmem_zalloc(6, KM_SLEEP);
13893 
13894 	result = st_get_special_inquiry(un, 6, buf, SEQ_CAP_PAGE);
13895 
13896 	if (result != 0) {
13897 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13898 		    "Read Vitial Inquiry for Sequental Capability"
13899 		    " WORM support failed %x", result);
13900 		wrt = FAILED;
13901 	} else if ((buf[4] & 1) == 0) {
13902 		ASSERT(buf[1] == SEQ_CAP_PAGE);
13903 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13904 		    "Drive is NOT WORMable\n");
13905 		/* This drive doesn't support it so don't check again */
13906 		un->un_dp->options &= ~ST_WORMABLE;
13907 		wrt = RDWR;
13908 		un->un_wormable = st_is_not_wormable;
13909 	} else {
13910 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13911 		    "Drive supports WORM\n");
13912 		un->un_wormable = st_is_t10_worm_device;
13913 		wrt = un->un_wormable(un);
13914 	}
13915 
13916 	kmem_free(buf, 6);
13917 
13918 	return (wrt);
13919 }
13920 
13921 
13922 #define	STK_REQ_SENSE 26
13923 
13924 static writablity
13925 st_is_stk_worm(struct scsi_tape *un)
13926 {
13927 	char cdb[CDB_GROUP0] = {SCMD_REQUEST_SENSE, 0, 0, 0, STK_REQ_SENSE, 0};
13928 	struct scsi_extended_sense *sense;
13929 	struct uscsi_cmd *cmd;
13930 	char *buf;
13931 	int result;
13932 	writablity wrt;
13933 
13934 	ST_FUNC(ST_DEVINFO, st_is_stk_worm);
13935 
13936 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
13937 	buf = kmem_alloc(STK_REQ_SENSE, KM_SLEEP);
13938 	sense = (struct scsi_extended_sense *)buf;
13939 
13940 	cmd->uscsi_flags = USCSI_READ;
13941 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
13942 	cmd->uscsi_cdb = &cdb[0];
13943 	cmd->uscsi_bufaddr = buf;
13944 	cmd->uscsi_buflen = STK_REQ_SENSE;
13945 	cmd->uscsi_cdblen = CDB_GROUP0;
13946 	cmd->uscsi_rqlen = 0;
13947 	cmd->uscsi_rqbuf = NULL;
13948 
13949 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
13950 
13951 	if (result != 0 || cmd->uscsi_status != 0) {
13952 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13953 		    "Request Sense for WORM failed");
13954 		wrt = RDWR;
13955 	} else if (sense->es_add_len + 8 < 24) {
13956 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13957 		    "Drive didn't send enough sense data for WORM byte %d\n",
13958 		    sense->es_add_len + 8);
13959 		wrt = RDWR;
13960 		un->un_wormable = st_is_not_wormable;
13961 	} else if ((buf[24]) & 0x02) {
13962 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13963 		    "Drive has WORM tape loaded\n");
13964 		wrt = WORM;
13965 		un->un_wormable = st_is_stk_worm;
13966 	} else {
13967 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
13968 		    "Drive has normal tape loaded\n");
13969 		wrt = RDWR;
13970 		un->un_wormable = st_is_stk_worm;
13971 	}
13972 
13973 	kmem_free(buf, STK_REQ_SENSE);
13974 	kmem_free(cmd, sizeof (struct uscsi_cmd));
13975 	return (wrt);
13976 }
13977 
13978 #define	DLT_INQ_SZ 44
13979 
13980 static writablity
13981 st_is_dlt_tape_worm(struct scsi_tape *un)
13982 {
13983 	caddr_t buf;
13984 	int result;
13985 	writablity wrt;
13986 
13987 	ST_FUNC(ST_DEVINFO, st_is_dlt_tape_worm);
13988 
13989 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
13990 
13991 	/* Read Attribute Media Type */
13992 
13993 	result = st_read_attributes(un, 0x0408, buf, 10, st_uscsi_cmd);
13994 
13995 	/*
13996 	 * If this quantum drive is attached via an HBA that cannot
13997 	 * support thr read attributes command return error in the
13998 	 * hope that someday they will support the t10 method.
13999 	 */
14000 	if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
14001 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14002 		    "Read Attribute Command for WORM Media detection is not "
14003 		    "supported on the HBA that this drive is attached to.");
14004 		wrt = RDWR;
14005 		un->un_wormable = st_is_not_wormable;
14006 		goto out;
14007 	}
14008 
14009 	if (result != 0) {
14010 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14011 		    "Read Attribute Command for WORM Media returned 0x%x",
14012 		    result);
14013 		wrt = RDWR;
14014 		un->un_dp->options &= ~ST_WORMABLE;
14015 		goto out;
14016 	}
14017 
14018 	if ((uchar_t)buf[9] == 0x80) {
14019 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14020 		    "Drive media is WORM\n");
14021 		wrt = WORM;
14022 	} else {
14023 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14024 		    "Drive media is not WORM Media 0x%x\n", (uchar_t)buf[9]);
14025 		wrt = RDWR;
14026 	}
14027 
14028 out:
14029 	kmem_free(buf, DLT_INQ_SZ);
14030 	return (wrt);
14031 }
14032 
14033 static writablity
14034 st_is_dlt_worm(struct scsi_tape *un)
14035 {
14036 	caddr_t buf;
14037 	int result;
14038 	writablity wrt;
14039 
14040 	ST_FUNC(ST_DEVINFO, st_is_dlt_worm);
14041 
14042 	buf = kmem_alloc(DLT_INQ_SZ, KM_SLEEP);
14043 
14044 	result = st_get_special_inquiry(un, DLT_INQ_SZ, buf, 0xC0);
14045 
14046 	if (result != 0) {
14047 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14048 		    "Read Vendor Specific Inquiry for WORM support failed");
14049 		wrt = RDWR;
14050 		goto out;
14051 	}
14052 
14053 	if ((buf[2] & 1) == 0) {
14054 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14055 		    "Drive is not WORMable\n");
14056 		wrt = RDWR;
14057 		un->un_dp->options &= ~ST_WORMABLE;
14058 		un->un_wormable = st_is_not_wormable;
14059 		goto out;
14060 	} else {
14061 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14062 		    "Drive is WORMable\n");
14063 		un->un_wormable = st_is_dlt_tape_worm;
14064 		wrt = un->un_wormable(un);
14065 	}
14066 out:
14067 	kmem_free(buf, DLT_INQ_SZ);
14068 
14069 	return (wrt);
14070 }
14071 
14072 typedef struct {
14073 	struct modeheader_seq header;
14074 #if defined(_BIT_FIELDS_LTOH) /* X86 */
14075 	uchar_t pagecode	:6,
14076 				:2;
14077 	uchar_t page_len;
14078 	uchar_t syslogalive	:2,
14079 		device		:1,
14080 		abs		:1,
14081 		ulpbot		:1,
14082 		prth		:1,
14083 		ponej		:1,
14084 		ait		:1;
14085 	uchar_t span;
14086 
14087 	uchar_t			:6,
14088 		worm		:1,
14089 		mic		:1;
14090 	uchar_t worm_cap	:1,
14091 				:7;
14092 	uint32_t		:32;
14093 #else /* SPARC */
14094 	uchar_t			:2,
14095 		pagecode	:6;
14096 	uchar_t page_len;
14097 	uchar_t ait		:1,
14098 		device		:1,
14099 		abs		:1,
14100 		ulpbot		:1,
14101 		prth		:1,
14102 		ponej		:1,
14103 		syslogalive	:2;
14104 	uchar_t span;
14105 	uchar_t mic		:1,
14106 		worm		:1,
14107 				:6;
14108 	uchar_t			:7,
14109 		worm_cap	:1;
14110 	uint32_t		:32;
14111 #endif
14112 }ait_dev_con;
14113 
14114 #define	AIT_DEV_PAGE 0x31
14115 static writablity
14116 st_is_sony_worm(struct scsi_tape *un)
14117 {
14118 	int result;
14119 	writablity wrt;
14120 	ait_dev_con *ait_conf;
14121 
14122 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14123 
14124 	ait_conf = kmem_zalloc(sizeof (ait_dev_con), KM_SLEEP);
14125 
14126 	result = st_gen_mode_sense(un, st_uscsi_cmd, AIT_DEV_PAGE,
14127 	    (struct seq_mode *)ait_conf, sizeof (ait_dev_con));
14128 
14129 	if (result == 0) {
14130 
14131 		if (ait_conf->pagecode != AIT_DEV_PAGE) {
14132 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14133 			    "returned page 0x%x not 0x%x AIT_DEV_PAGE\n",
14134 			    ait_conf->pagecode, AIT_DEV_PAGE);
14135 			wrt = RDWR;
14136 			un->un_wormable = st_is_not_wormable;
14137 
14138 		} else if (ait_conf->worm_cap) {
14139 
14140 			un->un_wormable = st_is_sony_worm;
14141 
14142 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14143 			    "Drives is WORMable\n");
14144 			if (ait_conf->worm) {
14145 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14146 				    "Media is WORM\n");
14147 				wrt = WORM;
14148 			} else {
14149 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14150 				    "Media is not WORM\n");
14151 				wrt = RDWR;
14152 			}
14153 
14154 		} else {
14155 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14156 			    "Drives not is WORMable\n");
14157 			wrt = RDWR;
14158 			/* No further checking required */
14159 			un->un_dp->options &= ~ST_WORMABLE;
14160 		}
14161 
14162 	} else {
14163 
14164 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14165 		    "AIT device config mode sense page read command failed"
14166 		    " result = %d ", result);
14167 		wrt = FAILED;
14168 		un->un_wormable = st_is_not_wormable;
14169 	}
14170 
14171 	kmem_free(ait_conf, sizeof (ait_dev_con));
14172 	return (wrt);
14173 }
14174 
14175 static writablity
14176 st_is_drive_worm(struct scsi_tape *un)
14177 {
14178 	writablity wrt;
14179 
14180 	ST_FUNC(ST_DEVINFO, st_is_sony_worm);
14181 
14182 	switch (un->un_dp->type) {
14183 	case MT_ISDLT:
14184 		wrt = st_is_dlt_worm(un);
14185 		break;
14186 
14187 	case MT_ISSTK9840:
14188 		wrt = st_is_stk_worm(un);
14189 		break;
14190 
14191 	case MT_IS8MM:
14192 	case MT_ISAIT:
14193 		wrt = st_is_sony_worm(un);
14194 		break;
14195 
14196 	case MT_LTO:
14197 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14198 			wrt = st_is_hp_lto_worm(un);
14199 		} else {
14200 			wrt = st_is_t10_worm(un);
14201 		}
14202 		break;
14203 
14204 	case MT_ISDAT:
14205 		if (strncmp("HP ", un->un_dp->vid, 3) == 0) {
14206 			wrt = st_is_hp_dat_worm(un);
14207 		} else {
14208 			wrt = st_is_t10_worm(un);
14209 		}
14210 		break;
14211 
14212 	default:
14213 		wrt = FAILED;
14214 		break;
14215 	}
14216 
14217 	/*
14218 	 * If any of the above failed try the t10 standard method.
14219 	 */
14220 	if (wrt == FAILED) {
14221 		wrt = st_is_t10_worm(un);
14222 	}
14223 
14224 	/*
14225 	 * Unknown method for detecting WORM media.
14226 	 */
14227 	if (wrt == FAILED) {
14228 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14229 		    "Unknown method for WORM media detection\n");
14230 		wrt = RDWR;
14231 		un->un_dp->options &= ~ST_WORMABLE;
14232 	}
14233 
14234 	return (wrt);
14235 }
14236 
14237 static int
14238 st_read_attributes(struct scsi_tape *un, uint16_t attribute, void *pnt,
14239     size_t size, ubufunc_t bufunc)
14240 {
14241 	char cdb[CDB_GROUP4];
14242 	int result;
14243 	struct uscsi_cmd *cmd;
14244 	struct scsi_arq_status status;
14245 
14246 	caddr_t buf = (caddr_t)pnt;
14247 
14248 	ST_FUNC(ST_DEVINFO, st_read_attributes);
14249 
14250 	if (un->un_sd->sd_inq->inq_ansi < 3) {
14251 		return (ENOTTY);
14252 	}
14253 
14254 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14255 
14256 	cdb[0] = (char)SCMD_READ_ATTRIBUTE;
14257 	cdb[1] = 0;
14258 	cdb[2] = 0;
14259 	cdb[3] = 0;
14260 	cdb[4] = 0;
14261 	cdb[5] = 0;
14262 	cdb[6] = 0;
14263 	cdb[7] = 0;
14264 	cdb[8] = (char)(attribute >> 8);
14265 	cdb[9] = (char)(attribute);
14266 	cdb[10] = (char)(size >> 24);
14267 	cdb[11] = (char)(size >> 16);
14268 	cdb[12] = (char)(size >> 8);
14269 	cdb[13] = (char)(size);
14270 	cdb[14] = 0;
14271 	cdb[15] = 0;
14272 
14273 
14274 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE | USCSI_DIAGNOSE;
14275 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14276 	cmd->uscsi_cdb = &cdb[0];
14277 	cmd->uscsi_bufaddr = (caddr_t)buf;
14278 	cmd->uscsi_buflen = size;
14279 	cmd->uscsi_cdblen = sizeof (cdb);
14280 	cmd->uscsi_rqlen = sizeof (status);
14281 	cmd->uscsi_rqbuf = (caddr_t)&status;
14282 
14283 	result = bufunc(un, cmd, FKIOCTL);
14284 
14285 	if (result != 0 || cmd->uscsi_status != 0) {
14286 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
14287 		    "st_read_attribute failed: result %d status %d\n",
14288 		    result, cmd->uscsi_status);
14289 		/*
14290 		 * If this returns invalid operation code don't try again.
14291 		 */
14292 		if (un->un_sd->sd_sense->es_key == KEY_ILLEGAL_REQUEST &&
14293 		    un->un_sd->sd_sense->es_add_code == 0x20) {
14294 			result = ENOTTY;
14295 		} else if (result == 0) {
14296 			result = EIO;
14297 		}
14298 
14299 	} else {
14300 
14301 		/*
14302 		 * The attribute retured should match the attribute requested.
14303 		 */
14304 		if (buf[4] != cdb[8] || buf[5] != cdb[9]) {
14305 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14306 			    "st_read_attribute got wrong data back expected "
14307 			    "0x%x got 0x%x\n", attribute, buf[6] << 8 | buf[7]);
14308 			st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14309 			    "bad? data", buf, size);
14310 			result = EIO;
14311 		}
14312 	}
14313 
14314 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14315 
14316 	return (result);
14317 }
14318 
14319 static int
14320 st_get_special_inquiry(struct scsi_tape *un, uchar_t size, caddr_t dest,
14321     uchar_t page)
14322 {
14323 	char cdb[CDB_GROUP0];
14324 	struct scsi_extended_sense *sense;
14325 	struct uscsi_cmd *cmd;
14326 	int result;
14327 
14328 	ST_FUNC(ST_DEVINFO, st_get_special_inquiry);
14329 
14330 	cdb[0] = SCMD_INQUIRY;
14331 	cdb[1] = page ? 1 : 0;
14332 	cdb[2] = page;
14333 	cdb[3] = 0;
14334 	cdb[4] = size;
14335 	cdb[5] = 0;
14336 
14337 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14338 	sense = kmem_alloc(sizeof (struct scsi_extended_sense), KM_SLEEP);
14339 
14340 	cmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
14341 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
14342 	cmd->uscsi_cdb = &cdb[0];
14343 	cmd->uscsi_bufaddr = dest;
14344 	cmd->uscsi_buflen = size;
14345 	cmd->uscsi_cdblen = CDB_GROUP0;
14346 	cmd->uscsi_rqlen = sizeof (struct scsi_extended_sense);
14347 	cmd->uscsi_rqbuf = (caddr_t)sense;
14348 
14349 	result = st_uscsi_cmd(un, cmd, FKIOCTL);
14350 
14351 	if (result != 0 || cmd->uscsi_status != 0) {
14352 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
14353 		    "st_get_special_inquiry() failed for page %x", page);
14354 		if (result == 0) {
14355 			result = EIO;
14356 		}
14357 	}
14358 
14359 	kmem_free(sense, sizeof (struct scsi_extended_sense));
14360 	kmem_free(cmd, sizeof (struct uscsi_cmd));
14361 
14362 	return (result);
14363 }
14364 
14365 
14366 static int
14367 st_update_block_pos(struct scsi_tape *un, bufunc_t bf, int post_space)
14368 {
14369 	int rval = ENOTTY;
14370 	uchar_t status = un->un_status;
14371 	posmode previous_pmode = un->un_running.pmode;
14372 
14373 	ST_FUNC(ST_DEVINFO, st_update_block_pos);
14374 
14375 	while (un->un_read_pos_type != NO_POS) {
14376 		rval = bf(un, SCMD_READ_POSITION, 32, SYNC_CMD);
14377 
14378 		/*
14379 		 * If read position command returned good status
14380 		 * Parse the data to see if the position can be interpreted.
14381 		 */
14382 		if ((rval == 0) &&
14383 		    ((rval = st_interpret_read_pos(un, &un->un_pos,
14384 		    un->un_read_pos_type, 32, (caddr_t)un->un_read_pos_data,
14385 		    post_space)) == 0)) {
14386 			/*
14387 			 * Update the running position as well if un_pos was
14388 			 * ok. But only if recovery is enabled.
14389 			 */
14390 			if (st_recov_sz != sizeof (recov_info)) {
14391 				break;
14392 			}
14393 			rval = st_interpret_read_pos(un, &un->un_running,
14394 			    un->un_read_pos_type, 32,
14395 			    (caddr_t)un->un_read_pos_data, post_space);
14396 			un->un_status = status;
14397 			break;
14398 		} else if (un->un_status == KEY_UNIT_ATTENTION) {
14399 			un->un_running.pmode = previous_pmode;
14400 			continue;
14401 		} else if (un->un_status != KEY_ILLEGAL_REQUEST) {
14402 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
14403 			    "st_update_block_pos() read position cmd 0x%x"
14404 			    " returned 0x%x un_status = %d",
14405 			    un->un_read_pos_type, rval, un->un_status);
14406 			/* ENOTTY means it read garbage. try something else. */
14407 			if (rval == ENOTTY) {
14408 				rval = EIO; /* so ENOTTY is not final rval */
14409 			} else {
14410 				break;
14411 			}
14412 		} else {
14413 			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
14414 			    "st_update_block_pos() read position cmd %x"
14415 			    " returned %x", un->un_read_pos_type, rval);
14416 			un->un_running.pmode = previous_pmode;
14417 		}
14418 
14419 		switch (un->un_read_pos_type) {
14420 		case SHORT_POS:
14421 			un->un_read_pos_type = NO_POS;
14422 			break;
14423 
14424 		case LONG_POS:
14425 			un->un_read_pos_type = EXT_POS;
14426 			break;
14427 
14428 		case EXT_POS:
14429 			un->un_read_pos_type = SHORT_POS;
14430 			break;
14431 
14432 		default:
14433 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14434 			    "Unexpected read position type 0x%x",
14435 			    un->un_read_pos_type);
14436 		}
14437 		un->un_status = KEY_NO_SENSE;
14438 	}
14439 
14440 	return (rval);
14441 }
14442 
14443 static int
14444 st_get_read_pos(struct scsi_tape *un, buf_t *bp)
14445 {
14446 	int result;
14447 	size_t d_sz;
14448 	caddr_t pos_info;
14449 	struct uscsi_cmd *cmd = (struct uscsi_cmd *)bp->b_back;
14450 
14451 	ST_FUNC(ST_DEVINFO, st_get_read_pos);
14452 
14453 	if (cmd->uscsi_bufaddr == NULL || cmd->uscsi_buflen <= 0) {
14454 		return (0);
14455 	}
14456 
14457 	if (bp_mapin_common(bp, VM_NOSLEEP) == NULL) {
14458 
14459 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14460 		    "bp_mapin_common() failed");
14461 
14462 		return (EIO);
14463 	}
14464 
14465 	d_sz = bp->b_bcount - bp->b_resid;
14466 	if (d_sz == 0) {
14467 		bp_mapout(bp);
14468 		return (EIO);
14469 	}
14470 
14471 	/*
14472 	 * Copy the buf to a double-word aligned memory that can hold the
14473 	 * tape_position_t data structure.
14474 	 */
14475 	if ((pos_info = kmem_alloc(d_sz, KM_NOSLEEP)) == NULL) {
14476 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
14477 		    "kmem_alloc() failed");
14478 		bp_mapout(bp);
14479 		return (EIO);
14480 	}
14481 	bcopy(bp->b_un.b_addr, pos_info, d_sz);
14482 
14483 #ifdef STDEBUG
14484 	if ((st_debug & 0x7) > 2) {
14485 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
14486 		    "st_get_read_pos() position info",
14487 		    pos_info, bp->b_bcount);
14488 	}
14489 #endif
14490 
14491 	result = st_interpret_read_pos(un, &un->un_pos, cmd->uscsi_cdb[1],
14492 	    d_sz, pos_info, 0);
14493 
14494 	COPY_POS(&un->un_running, &un->un_pos);
14495 
14496 	kmem_free(pos_info, d_sz);
14497 	bp_mapout(bp);
14498 
14499 	return (result);
14500 }
14501 
14502 #if defined(_BIG_ENDIAN)
14503 
14504 #define	FIX_ENDIAN16(x)
14505 #define	FIX_ENDIAN32(x)
14506 #define	FIX_ENDIAN64(x)
14507 
14508 #elif defined(_LITTLE_ENDIAN)
14509 
14510 static void
14511 st_swap16(uint16_t *val)
14512 {
14513 	uint16_t tmp;
14514 
14515 	tmp = (*val >>  8) & 0xff;
14516 	tmp |= (*val <<  8) & 0xff00;
14517 
14518 	*val = tmp;
14519 }
14520 
14521 static void
14522 st_swap32(uint32_t *val)
14523 {
14524 	uint32_t tmp;
14525 
14526 	tmp =  (*val >> 24) & 0xff;
14527 	tmp |= (*val >>  8) & 0xff00;
14528 	tmp |= (*val <<  8) & 0xff0000;
14529 	tmp |= (*val << 24) & 0xff000000;
14530 
14531 	*val = tmp;
14532 }
14533 
14534 static void
14535 st_swap64(uint64_t *val)
14536 {
14537 	uint32_t low;
14538 	uint32_t high;
14539 
14540 	low =  (uint32_t)(*val);
14541 	high = (uint32_t)(*val >> 32);
14542 
14543 	st_swap32(&low);
14544 	st_swap32(&high);
14545 
14546 	*val =  high;
14547 	*val |= ((uint64_t)low << 32);
14548 }
14549 
14550 #define	FIX_ENDIAN16(x) st_swap16(x)
14551 #define	FIX_ENDIAN32(x) st_swap32(x)
14552 #define	FIX_ENDIAN64(x) st_swap64(x)
14553 #endif
14554 
14555 /*
14556  * st_interpret_read_pos()
14557  *
14558  * Returns:
14559  *	0	If secsessful.
14560  *	EIO	If read postion responce data was unuseable or invalid.
14561  *	ERANGE	If the position of the drive is too large for the read_p_type.
14562  *	ENOTTY	If the responce data looks invalid for the read position type.
14563  */
14564 
14565 static int
14566 st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
14567     read_p_types type, size_t data_sz, const caddr_t responce, int post_space)
14568 {
14569 	int rval = 0;
14570 	int flag = 0;
14571 	tapepos_t org;
14572 
14573 	ST_FUNC(ST_DEVINFO, st_interpret_read_pos);
14574 
14575 	/*
14576 	 * We expect the position value to change after a space command.
14577 	 * So if post_space is set we don't print out what has changed.
14578 	 */
14579 	if ((dest != &un->un_pos) && (post_space == 0) &&
14580 	    (st_recov_sz == sizeof (recov_info))) {
14581 		COPY_POS(&org, dest);
14582 		flag = 1;
14583 	}
14584 
14585 	/*
14586 	 * See what kind of read position was requested.
14587 	 */
14588 	switch (type) {
14589 
14590 	case SHORT_POS: /* Short data format */
14591 	{
14592 		tape_position_t *pos_info = (tape_position_t *)responce;
14593 		uint32_t value;
14594 
14595 		/* If reserved fields are non zero don't use the data */
14596 		if (pos_info->reserved0 || pos_info->reserved1 ||
14597 		    pos_info->reserved2[0] || pos_info->reserved2[1] ||
14598 		    pos_info->reserved3) {
14599 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14600 			    "Invalid Read Short Position Data returned\n");
14601 			rval = EIO;
14602 			break;
14603 		}
14604 		/*
14605 		 * Position is to large to use this type of read position.
14606 		 */
14607 		if (pos_info->posi_err == 1) {
14608 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14609 			    "Drive reported position error\n");
14610 			rval = ERANGE;
14611 			break;
14612 		}
14613 		/*
14614 		 * If your at the begining of partition and end at the same
14615 		 * time it's very small partition or bad data.
14616 		 */
14617 		if (pos_info->begin_of_part && pos_info->end_of_part) {
14618 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14619 			    "SHORT_POS returned begin and end of"
14620 			    " partition\n");
14621 			rval = EIO;
14622 			break;
14623 		}
14624 
14625 		if (pos_info->blk_posi_unkwn == 0) {
14626 
14627 			value = pos_info->host_block;
14628 			FIX_ENDIAN32(&value);
14629 
14630 			/*
14631 			 * If the tape is rewound the host blcok should be 0.
14632 			 */
14633 			if ((pos_info->begin_of_part == 1) &&
14634 			    (value != 0)) {
14635 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14636 				    "SHORT_POS returned begin of partition"
14637 				    " but host block was 0x%x\n", value);
14638 				rval = EIO;
14639 				break;
14640 			}
14641 
14642 			if (dest->lgclblkno != value) {
14643 				if (flag)
14644 					flag++;
14645 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14646 				    "SHORT_POS current logical 0x%"PRIx64" read"
14647 				    " 0x%x\n", dest->lgclblkno, value);
14648 			}
14649 
14650 			dest->lgclblkno = (uint64_t)value;
14651 
14652 			/*
14653 			 * If the begining of partition is true and the
14654 			 * block number is zero we will beleive that it is
14655 			 * rewound. Promote the pmode to legacy.
14656 			 */
14657 			if ((pos_info->begin_of_part == 1) &&
14658 			    (value == 0)) {
14659 				dest->blkno = 0;
14660 				dest->fileno = 0;
14661 				if (dest->pmode != legacy)
14662 					dest->pmode = legacy;
14663 			/*
14664 			 * otherwise if the pmode was invalid,
14665 			 * promote it to logical.
14666 			 */
14667 			} else if (dest->pmode == invalid) {
14668 				dest->pmode = logical;
14669 			}
14670 
14671 			if (dest->partition != pos_info->partition_number) {
14672 				if (flag)
14673 					flag++;
14674 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14675 				    "SHORT_POS current partition %d read %d\n",
14676 				    dest->partition,
14677 				    pos_info->partition_number);
14678 			}
14679 
14680 			dest->partition = pos_info->partition_number;
14681 
14682 		} else {
14683 			dest->pmode = invalid;
14684 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14685 			    "Tape drive reported block position as unknown\n");
14686 		}
14687 		break;
14688 	}
14689 
14690 	case LONG_POS: /* Long data format */
14691 	{
14692 		uint64_t value;
14693 		tape_position_long_t *long_pos_info =
14694 		    (tape_position_long_t *)responce;
14695 
14696 		/* If reserved fields are non zero don't use the data */
14697 		if ((long_pos_info->reserved0) ||
14698 		    (long_pos_info->reserved1) ||
14699 		    (long_pos_info->reserved2)) {
14700 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14701 			    "Invalid Read Long Position Data returned\n");
14702 			rval = ENOTTY;
14703 			break;
14704 		}
14705 
14706 		/* Is position Valid */
14707 		if (long_pos_info->blk_posi_unkwn == 0) {
14708 			uint32_t part;
14709 
14710 			value = long_pos_info->block_number;
14711 			FIX_ENDIAN64(&value);
14712 
14713 			/*
14714 			 * If it says we are at the begining of partition
14715 			 * the block value better be 0.
14716 			 */
14717 			if ((long_pos_info->begin_of_part == 1) &&
14718 			    (value != 0)) {
14719 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14720 				    "LONG_POS returned begin of partition but"
14721 				    " block number was 0x%"PRIx64"\n", value);
14722 				rval = ENOTTY;
14723 				break;
14724 			}
14725 			/*
14726 			 * Can't be at the start and the end of the partition
14727 			 * at the same time if the partition is larger the 0.
14728 			 */
14729 			if (long_pos_info->begin_of_part &&
14730 			    long_pos_info->end_of_part) {
14731 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14732 				    "LONG_POS returned begin and end of"
14733 				    " partition\n");
14734 				rval = ENOTTY;
14735 				break;
14736 			}
14737 
14738 			/*
14739 			 * If the logical block number is not what we expected.
14740 			 */
14741 			if (dest->lgclblkno != value) {
14742 				if (flag)
14743 					flag++;
14744 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14745 				    "LONG_POS current logical 0x%"PRIx64
14746 				    " read 0x%"PRIx64"\n",
14747 				    dest->lgclblkno, value);
14748 			}
14749 			dest->lgclblkno = value;
14750 
14751 			/*
14752 			 * If the begining of partition is true and the
14753 			 * block number is zero we will beleive that it is
14754 			 * rewound. Promote the pmode to legacy.
14755 			 */
14756 			if ((long_pos_info->begin_of_part == 1) &&
14757 			    (long_pos_info->block_number == 0)) {
14758 				dest->blkno = 0;
14759 				dest->fileno = 0;
14760 				if (dest->pmode != legacy)
14761 					dest->pmode = legacy;
14762 			/*
14763 			 * otherwise if the pmode was invalid,
14764 			 * promote it to logical.
14765 			 */
14766 			} else if (dest->pmode == invalid) {
14767 				dest->pmode = logical;
14768 			}
14769 
14770 			part = long_pos_info->partition;
14771 			FIX_ENDIAN32(&part);
14772 			if (dest->partition != part) {
14773 				if (flag)
14774 					flag++;
14775 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14776 				    "LONG_POS current partition %d"
14777 				    " read %d\n", dest->partition, part);
14778 			}
14779 			dest->partition = part;
14780 		} else {
14781 			/*
14782 			 * If the drive doesn't know location,
14783 			 * we don't either.
14784 			 */
14785 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14786 			    "Tape drive reported block position as unknown\n");
14787 			dest->pmode = invalid;
14788 		}
14789 
14790 		/* Is file position valid */
14791 		if (long_pos_info->mrk_posi_unkwn == 0) {
14792 			value = long_pos_info->file_number;
14793 			FIX_ENDIAN64(&value);
14794 			/*
14795 			 * If it says we are at the begining of partition
14796 			 * the block value better be 0.
14797 			 */
14798 			if ((long_pos_info->begin_of_part == 1) &&
14799 			    (value != 0)) {
14800 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14801 				    "LONG_POS returned begin of partition but"
14802 				    " block number was 0x%"PRIx64"\n", value);
14803 				rval = ENOTTY;
14804 				break;
14805 			}
14806 			if (((dest->pmode == legacy) ||
14807 			    (dest->pmode == logical)) &&
14808 			    (dest->fileno != value)) {
14809 				if (flag)
14810 					flag++;
14811 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14812 				    "LONG_POS fileno 0x%"PRIx64
14813 				    " not un_pos %x\n", value,
14814 				    dest->fileno);
14815 			} else if (dest->pmode == invalid) {
14816 				dest->pmode = logical;
14817 			}
14818 			dest->fileno = (int32_t)value;
14819 		}
14820 
14821 		if (dest->pmode != invalid && long_pos_info->end_of_part) {
14822 			dest->eof = ST_EOT;
14823 		}
14824 
14825 		break;
14826 	}
14827 
14828 	case EXT_POS: /* Extended data format */
14829 	{
14830 		uint64_t value;
14831 		uint16_t len;
14832 		tape_position_ext_t *ext_pos_info =
14833 		    (tape_position_ext_t *)responce;
14834 
14835 		/* Make sure that there is enough data there */
14836 		if (data_sz < 16) {
14837 			break;
14838 		}
14839 
14840 		/* If reserved fields are non zero don't use the data */
14841 		if (ext_pos_info->reserved0 || ext_pos_info->reserved1) {
14842 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14843 			    "EXT_POS reserved fields not zero\n");
14844 			rval = ENOTTY;
14845 			break;
14846 		}
14847 
14848 		/*
14849 		 * In the unlikely event of overflowing 64 bits of position.
14850 		 */
14851 		if (ext_pos_info->posi_err != 0) {
14852 			rval = ERANGE;
14853 			break;
14854 		}
14855 
14856 		len = ext_pos_info->parameter_len;
14857 		FIX_ENDIAN16(&len);
14858 
14859 		if (len != 0x1c) {
14860 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14861 			    "EXT_POS parameter_len should be 0x1c was 0x%x\n",
14862 			    len);
14863 			rval = ENOTTY;
14864 			break;
14865 		}
14866 
14867 		/* Is block position information valid */
14868 		if (ext_pos_info->blk_posi_unkwn == 0) {
14869 
14870 			value = ext_pos_info->host_block;
14871 			FIX_ENDIAN64(&value);
14872 			if ((ext_pos_info->begin_of_part == 1) &&
14873 			    (value != 0)) {
14874 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14875 				    "EXT_POS returned begining of partition but"
14876 				    " the host block was 0x%"PRIx64"\n", value);
14877 				rval = ENOTTY;
14878 				break;
14879 			}
14880 
14881 			if (dest->lgclblkno != value) {
14882 				if (flag)
14883 					flag++;
14884 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14885 				    "EXT_POS current logical 0x%"PRIx64
14886 				    " read 0x%"PRIx64"\n",
14887 				    dest->lgclblkno, value);
14888 			}
14889 			dest->lgclblkno = value;
14890 
14891 			/*
14892 			 * If the begining of partition is true and the
14893 			 * block number is zero we will beleive that it is
14894 			 * rewound. Promote the pmode to legacy.
14895 			 */
14896 			if ((ext_pos_info->begin_of_part == 1) &&
14897 			    (ext_pos_info->host_block == 0)) {
14898 				dest->blkno = 0;
14899 				dest->fileno = 0;
14900 				if (dest->pmode != legacy) {
14901 					dest->pmode = legacy;
14902 				}
14903 			/*
14904 			 * otherwise if the pmode was invalid,
14905 			 * promote it to logical.
14906 			 */
14907 			} else if (dest->pmode == invalid) {
14908 				dest->pmode = logical;
14909 			}
14910 
14911 			if (dest->partition != ext_pos_info->partition) {
14912 				if (flag)
14913 					flag++;
14914 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
14915 				    "EXT_POS current partition %d read %d\n",
14916 				    dest->partition,
14917 				    ext_pos_info->partition);
14918 			}
14919 			dest->partition = ext_pos_info->partition;
14920 
14921 		} else {
14922 			dest->pmode = invalid;
14923 		}
14924 		break;
14925 	}
14926 
14927 	default:
14928 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
14929 		    "Got unexpected SCMD_READ_POSITION type %d\n", type);
14930 		rval = EIO;
14931 	}
14932 
14933 	if ((flag > 1) && (rval == 0) && (org.pmode != invalid)) {
14934 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14935 		    "position read in", &org);
14936 		st_print_position(ST_DEVINFO, st_label, CE_NOTE,
14937 		    "position read out", dest);
14938 	}
14939 
14940 	return (rval);
14941 }
14942 
14943 static int
14944 st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf, tapepos_t *pos,
14945     uint64_t lblk, uchar_t partition)
14946 {
14947 	int rval;
14948 	char cdb[CDB_GROUP4];
14949 	struct uscsi_cmd *cmd;
14950 	struct scsi_extended_sense sense;
14951 	bufunc_t bf = (ubf == st_uscsi_cmd) ? st_cmd : st_rcmd;
14952 
14953 	ST_FUNC(ST_DEVINFO, st_logical_block_locate);
14954 	/*
14955 	 * Not sure what to do when doing recovery and not wanting
14956 	 * to update un_pos
14957 	 */
14958 
14959 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
14960 
14961 	if (lblk <= INT32_MAX) {
14962 		cmd->uscsi_cdblen = CDB_GROUP1;
14963 		cdb[0] = SCMD_LOCATE;
14964 		cdb[1] = pos->partition == partition ? 0 : 2;
14965 		cdb[2] = 0;
14966 		cdb[3] = (char)(lblk >> 24);
14967 		cdb[4] = (char)(lblk >> 16);
14968 		cdb[5] = (char)(lblk >> 8);
14969 		cdb[6] = (char)(lblk);
14970 		cdb[7] = 0;
14971 		cdb[8] = partition;
14972 		cdb[9] = 0;
14973 	} else {
14974 		/*
14975 		 * If the drive doesn't give a 64 bit read position data
14976 		 * it is unlikely it will accept 64 bit locates.
14977 		 */
14978 		if (un->un_read_pos_type != LONG_POS) {
14979 			kmem_free(cmd, sizeof (struct uscsi_cmd));
14980 			return (ERANGE);
14981 		}
14982 		cmd->uscsi_cdblen = CDB_GROUP4;
14983 		cdb[0] = (char)SCMD_LOCATE_G4;
14984 		cdb[1] = pos->partition == partition ? 0 : 2;
14985 		cdb[2] = 0;
14986 		cdb[3] = partition;
14987 		cdb[4] = (char)(lblk >> 56);
14988 		cdb[5] = (char)(lblk >> 48);
14989 		cdb[6] = (char)(lblk >> 40);
14990 		cdb[7] = (char)(lblk >> 32);
14991 		cdb[8] = (char)(lblk >> 24);
14992 		cdb[9] = (char)(lblk >> 16);
14993 		cdb[10] = (char)(lblk >> 8);
14994 		cdb[11] = (char)(lblk);
14995 		cdb[12] = 0;
14996 		cdb[13] = 0;
14997 		cdb[14] = 0;
14998 		cdb[15] = 0;
14999 	}
15000 
15001 
15002 	cmd->uscsi_flags = USCSI_WRITE | USCSI_DIAGNOSE | USCSI_RQENABLE;
15003 	cmd->uscsi_rqbuf = (caddr_t)&sense;
15004 	cmd->uscsi_rqlen = sizeof (sense);
15005 	cmd->uscsi_timeout = un->un_dp->space_timeout;
15006 	cmd->uscsi_cdb = cdb;
15007 
15008 	rval = ubf(un, cmd, FKIOCTL);
15009 
15010 	pos->pmode = logical;
15011 	pos->eof = ST_NO_EOF;
15012 
15013 	if (lblk > INT32_MAX) {
15014 		/*
15015 		 * XXX This is a work around till we handle Descriptor format
15016 		 * sense data. Since we are sending a command where the standard
15017 		 * sense data can not correctly represent a correct residual in
15018 		 * 4 bytes.
15019 		 */
15020 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
15021 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15022 			    "Big LOCATE ILLEGAL_REQUEST: rval = %d\n", rval);
15023 			/* Doesn't like big locate command */
15024 			un->un_status = 0;
15025 			rval = ERANGE;
15026 		} else if ((un->un_pos.pmode == invalid) || (rval != 0)) {
15027 			/* Aborted big locate command */
15028 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15029 			    "Big LOCATE resulted in invalid pos: rval = %d\n",
15030 			    rval);
15031 			un->un_status = 0;
15032 			rval = EIO;
15033 		} else if (st_update_block_pos(un, bf, 1)) {
15034 			/* read position failed */
15035 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15036 			    "Big LOCATE and read pos: rval = %d\n", rval);
15037 			rval = EIO;
15038 		} else if (lblk > un->un_pos.lgclblkno) {
15039 			/* read position worked but position was not expected */
15040 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15041 			    "Big LOCATE and recover read less then desired 0x%"
15042 			    PRIx64"\n", un->un_pos.lgclblkno);
15043 			un->un_err_resid = lblk - un->un_pos.lgclblkno;
15044 			un->un_status = KEY_BLANK_CHECK;
15045 			rval = ESPIPE;
15046 		} else if (lblk == un->un_pos.lgclblkno) {
15047 			/* read position was what was expected */
15048 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15049 			    "Big LOCATE and recover seems to have worked\n");
15050 			un->un_err_resid = 0;
15051 			rval = 0;
15052 		} else {
15053 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
15054 			    "BIGLOCATE end up going backwards");
15055 			un->un_err_resid = lblk;
15056 			rval = EIO;
15057 		}
15058 
15059 	} else if (rval == 0) {
15060 		/* Worked as requested */
15061 		pos->lgclblkno = lblk;
15062 
15063 	} else if (((cmd->uscsi_status & ST_STATUS_MASK) == STATUS_CHECK) &&
15064 	    (cmd->uscsi_resid != 0)) {
15065 		/* Got part way there but wasn't enough blocks on tape */
15066 		pos->lgclblkno = lblk - cmd->uscsi_resid;
15067 		un->un_err_resid = cmd->uscsi_resid;
15068 		un->un_status = KEY_BLANK_CHECK;
15069 		rval = ESPIPE;
15070 
15071 	} else if (st_update_block_pos(un, bf, 1) == 0) {
15072 		/* Got part way there but drive didn't tell what we missed by */
15073 		un->un_err_resid = lblk - pos->lgclblkno;
15074 		un->un_status = KEY_BLANK_CHECK;
15075 		rval = ESPIPE;
15076 
15077 	} else {
15078 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
15079 		    "Failed LOCATE and recover pos: rval = %d status = %d\n",
15080 		    rval, cmd->uscsi_status);
15081 		un->un_err_resid = lblk;
15082 		un->un_status = KEY_ILLEGAL_REQUEST;
15083 		pos->pmode = invalid;
15084 		rval = EIO;
15085 	}
15086 
15087 	kmem_free(cmd, sizeof (struct uscsi_cmd));
15088 
15089 	return (rval);
15090 }
15091 
15092 static int
15093 st_mtfsf_ioctl(struct scsi_tape *un, int64_t files)
15094 {
15095 	int rval;
15096 
15097 	ST_FUNC(ST_DEVINFO, st_mtfsf_ioctl);
15098 
15099 
15100 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15101 	    "st_mtfsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15102 #if 0
15103 	if ((IN_EOF(un->un_pos)) && (files == 1)) {
15104 		un->un_pos.fileno++;
15105 		un->un_pos.blkno = 0;
15106 		return (0);
15107 	}
15108 #endif
15109 	/* pmode == invalid already handled */
15110 	if (un->un_pos.pmode == legacy) {
15111 		/*
15112 		 * forward space over filemark
15113 		 *
15114 		 * For ASF we allow a count of 0 on fsf which means
15115 		 * we just want to go to beginning of current file.
15116 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
15117 		 * Allow stepping over double fmk with reel
15118 		 */
15119 		if ((un->un_pos.eof >= ST_EOT) &&
15120 		    (files > 0) &&
15121 		    ((un->un_dp->options & ST_REEL) == 0)) {
15122 			/* we're at EOM */
15123 			un->un_err_resid = files;
15124 			un->un_status = KEY_BLANK_CHECK;
15125 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15126 			    "st_mtfsf_ioctl: EIO : MTFSF at EOM");
15127 			return (EIO);
15128 		}
15129 
15130 		/*
15131 		 * physical tape position may not be what we've been
15132 		 * telling the user; adjust the request accordingly
15133 		 */
15134 		if (IN_EOF(un->un_pos)) {
15135 			un->un_pos.fileno++;
15136 			un->un_pos.blkno = 0;
15137 			/*
15138 			 * For positive direction case, we're now covered.
15139 			 * For zero or negative direction, we're covered
15140 			 * (almost)
15141 			 */
15142 			files--;
15143 		}
15144 
15145 	}
15146 
15147 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15148 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15149 		    "st_mtfsf_ioctl: EIO : MTFSF density/wfm failed");
15150 		return (EIO);
15151 	}
15152 
15153 
15154 	/*
15155 	 * Forward space file marks.
15156 	 * We leave ourselves at block zero
15157 	 * of the target file number.
15158 	 */
15159 	if (files < 0) {
15160 		rval = st_backward_space_files(un, -files, 0);
15161 	} else {
15162 		rval = st_forward_space_files(un, files);
15163 	}
15164 
15165 	return (rval);
15166 }
15167 
15168 static int
15169 st_forward_space_files(struct scsi_tape *un, int64_t count)
15170 {
15171 	int rval;
15172 
15173 	ST_FUNC(ST_DEVINFO, st_forward_space_files);
15174 
15175 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15176 	    "fspace: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15177 
15178 	ASSERT(count >= 0);
15179 	ASSERT(un->un_pos.pmode != invalid);
15180 
15181 	/*
15182 	 * A space with a count of zero means take me to the start of file.
15183 	 */
15184 	if (count == 0) {
15185 
15186 		/* Hay look were already there */
15187 		if (un->un_pos.pmode == legacy && un->un_pos.blkno == 0) {
15188 			un->un_err_resid = 0;
15189 			COPY_POS(&un->un_err_pos, &un->un_pos);
15190 			return (0);
15191 		}
15192 
15193 		/*
15194 		 * Well we are in the first file.
15195 		 * A rewind will get to the start.
15196 		 */
15197 		if (un->un_pos.pmode == legacy && un->un_pos.fileno == 0) {
15198 			rval = st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
15199 
15200 		/*
15201 		 * Can we backspace to get there?
15202 		 * This should work in logical mode.
15203 		 */
15204 		} else if (un->un_dp->options & ST_BSF) {
15205 			rval = st_space_to_begining_of_file(un);
15206 
15207 		/*
15208 		 * Can't back space but current file number is known,
15209 		 * So rewind and space from the begining of the partition.
15210 		 */
15211 		} else if (un->un_pos.pmode == legacy) {
15212 			rval = st_scenic_route_to_begining_of_file(un,
15213 			    un->un_pos.fileno);
15214 
15215 		/*
15216 		 * pmode is logical and ST_BSF is not set.
15217 		 * The LONG_POS read position contains the fileno.
15218 		 * If the read position works, rewind and space.
15219 		 */
15220 		} else if (un->un_read_pos_type == LONG_POS) {
15221 			rval = st_cmd(un, SCMD_READ_POSITION, 0, SYNC_CMD);
15222 			if (rval) {
15223 				/*
15224 				 * We didn't get the file position from the
15225 				 * read position command.
15226 				 * We are going to trust the drive to backspace
15227 				 * and then position after the filemark.
15228 				 */
15229 				rval = st_space_to_begining_of_file(un);
15230 			}
15231 			rval = st_interpret_read_pos(un, &un->un_pos, LONG_POS,
15232 			    32, (caddr_t)un->un_read_pos_data, 0);
15233 			if ((rval) && (un->un_pos.pmode == invalid)) {
15234 				rval = st_space_to_begining_of_file(un);
15235 			} else {
15236 				rval = st_scenic_route_to_begining_of_file(un,
15237 				    un->un_pos.fileno);
15238 			}
15239 		} else {
15240 			rval = EIO;
15241 		}
15242 		/*
15243 		 * If something didn't work we are lost
15244 		 */
15245 		if (rval != 0) {
15246 			un->un_pos.pmode = invalid;
15247 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15248 			    "st_mtioctop : EIO : fspace pmode invalid");
15249 
15250 			rval = EIO;
15251 		}
15252 
15253 	} else {
15254 		rval = st_space_fmks(un, count);
15255 	}
15256 
15257 	if (rval != EIO && count < 0) {
15258 		/*
15259 		 * we came here with a count < 0; we now need
15260 		 * to skip back to end up before the filemark
15261 		 */
15262 		rval = st_backward_space_files(un, 1, 1);
15263 	}
15264 
15265 	return (rval);
15266 }
15267 
15268 static int
15269 st_scenic_route_to_begining_of_file(struct scsi_tape *un, int32_t fileno)
15270 {
15271 	int rval;
15272 
15273 	ST_FUNC(ST_DEVINFO, st_scenic_route_to_begining_of_file);
15274 
15275 	if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15276 		rval = EIO;
15277 	} else if (st_cmd(un, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
15278 		rval = EIO;
15279 	}
15280 
15281 	return (rval);
15282 }
15283 
15284 static int
15285 st_space_to_begining_of_file(struct scsi_tape *un)
15286 {
15287 	int rval;
15288 
15289 	ST_FUNC(ST_DEVINFO, st_space_to_begining_of_file);
15290 
15291 	/*
15292 	 * Back space of the file at the begining of the file.
15293 	 */
15294 	rval = st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD);
15295 	if (rval) {
15296 		rval = EIO;
15297 		return (rval);
15298 	}
15299 
15300 	/*
15301 	 * Other interesting answers might be crashed BOT which isn't bad.
15302 	 */
15303 	if (un->un_status == SUN_KEY_BOT) {
15304 		return (rval);
15305 	}
15306 
15307 	un->un_running.pmode = invalid;
15308 
15309 	/*
15310 	 * Now we are on the BOP side of the filemark. Forward space to
15311 	 * the EOM side and we are at the begining of the file.
15312 	 */
15313 	rval = st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD);
15314 	if (rval) {
15315 		rval = EIO;
15316 	}
15317 
15318 	return (rval);
15319 }
15320 
15321 static int
15322 st_mtfsr_ioctl(struct scsi_tape *un, int64_t count)
15323 {
15324 
15325 	ST_FUNC(ST_DEVINFO, st_mtfsr_ioctl);
15326 
15327 	/*
15328 	 * forward space to inter-record gap
15329 	 *
15330 	 */
15331 
15332 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15333 	    "st_ioctl_fsr: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15334 
15335 	if (un->un_pos.pmode == legacy) {
15336 		/*
15337 		 * If were are at end of tape and count is forward.
15338 		 * Return blank check.
15339 		 */
15340 		if ((un->un_pos.eof >= ST_EOT) && (count > 0)) {
15341 			/* we're at EOM */
15342 			un->un_err_resid = count;
15343 			un->un_status = KEY_BLANK_CHECK;
15344 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15345 			    "st_mtfsr_ioctl: EIO : MTFSR eof > ST_EOT");
15346 			return (EIO);
15347 		}
15348 
15349 		/*
15350 		 * If count is zero there is nothing to do.
15351 		 */
15352 		if (count == 0) {
15353 			un->un_err_pos.fileno = un->un_pos.fileno;
15354 			un->un_err_pos.blkno = un->un_pos.blkno;
15355 			un->un_err_resid = 0;
15356 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15357 				un->un_status = SUN_KEY_EOF;
15358 			}
15359 			return (0);
15360 		}
15361 
15362 		/*
15363 		 * physical tape position may not be what we've been
15364 		 * telling the user; adjust the position accordingly
15365 		 */
15366 		if (IN_EOF(un->un_pos)) {
15367 			daddr_t blkno = un->un_pos.blkno;
15368 			int fileno = un->un_pos.fileno;
15369 
15370 			optype lastop = un->un_lastop;
15371 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)
15372 			    == -1) {
15373 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15374 				    "st_mtfsr_ioctl:EIO:MTFSR count && IN_EOF");
15375 				return (EIO);
15376 			}
15377 
15378 			un->un_pos.blkno = blkno;
15379 			un->un_pos.fileno = fileno;
15380 			un->un_lastop = lastop;
15381 		}
15382 	}
15383 
15384 	if (st_check_density_or_wfm(un->un_dev, 1, B_READ, STEPBACK)) {
15385 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15386 		    "st_mtfsr_ioctl: EIO : MTFSR st_check_den");
15387 		return (EIO);
15388 	}
15389 
15390 	return (st_space_records(un, count));
15391 }
15392 
15393 static int
15394 st_space_records(struct scsi_tape *un, int64_t count)
15395 {
15396 	int64_t dblk;
15397 	int rval = 0;
15398 
15399 	ST_FUNC(ST_DEVINFO, st_space_records);
15400 
15401 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15402 	    "st_space_records: count=%"PRIx64", eof=%x\n",
15403 	    count, un->un_pos.eof);
15404 
15405 	if (un->un_pos.pmode == logical) {
15406 		rval = st_cmd(un, SCMD_SPACE, Blk(count), SYNC_CMD);
15407 		if (rval != 0) {
15408 			rval = EIO;
15409 		}
15410 		return (rval);
15411 	}
15412 
15413 	dblk = count + un->un_pos.blkno;
15414 
15415 	/* Already there */
15416 	if (dblk == un->un_pos.blkno) {
15417 		un->un_err_resid = 0;
15418 		COPY_POS(&un->un_err_pos, &un->un_pos);
15419 		return (0);
15420 	}
15421 
15422 	/*
15423 	 * If the destination block is forward
15424 	 * or the drive will backspace records.
15425 	 */
15426 	if (un->un_pos.blkno < dblk || (un->un_dp->options & ST_BSR)) {
15427 		/*
15428 		 * If we're spacing forward, or the device can
15429 		 * backspace records, we can just use the SPACE
15430 		 * command.
15431 		 */
15432 		dblk -= un->un_pos.blkno;
15433 		if (st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15434 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15435 			    "st_space_records:EIO:space_records can't spc");
15436 			rval = EIO;
15437 		} else if (un->un_pos.eof >= ST_EOF_PENDING) {
15438 			/*
15439 			 * check if we hit BOT/EOT
15440 			 */
15441 			if (dblk < 0 && un->un_pos.eof == ST_EOM) {
15442 				un->un_status = SUN_KEY_BOT;
15443 				un->un_pos.eof = ST_NO_EOF;
15444 			} else if (dblk < 0 &&
15445 			    un->un_pos.eof == ST_EOF_PENDING) {
15446 				int residue = un->un_err_resid;
15447 				/*
15448 				 * we skipped over a filemark
15449 				 * and need to go forward again
15450 				 */
15451 				if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
15452 					ST_DEBUG2(ST_DEVINFO, st_label,
15453 					    SCSI_DEBUG, "st_space_records: EIO"
15454 					    " : can't space #2");
15455 					rval = EIO;
15456 				}
15457 				un->un_err_resid = residue;
15458 			}
15459 			if (rval == 0) {
15460 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15461 				    "st_space_records: EIO : space_rec rval"
15462 				    " == 0");
15463 				rval = EIO;
15464 			}
15465 		}
15466 	} else {
15467 		/*
15468 		 * else we rewind, space forward across filemarks to
15469 		 * the desired file, and then space records to the
15470 		 * desired block.
15471 		 */
15472 
15473 		int dfile = un->un_pos.fileno;	/* save current file */
15474 
15475 		if (dblk < 0) {
15476 			/*
15477 			 * Wups - we're backing up over a filemark
15478 			 */
15479 			if (un->un_pos.blkno != 0 &&
15480 			    (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15481 			    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD))) {
15482 				un->un_pos.pmode = invalid;
15483 			}
15484 			un->un_err_resid = -dblk;
15485 			if (un->un_pos.fileno == 0 && un->un_pos.blkno == 0) {
15486 				un->un_status = SUN_KEY_BOT;
15487 				un->un_pos.eof = ST_NO_EOF;
15488 			} else if (un->un_pos.fileno > 0) {
15489 				un->un_status = SUN_KEY_EOF;
15490 				un->un_pos.eof = ST_NO_EOF;
15491 			}
15492 			COPY_POS(&un->un_err_pos, &un->un_pos);
15493 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15494 			    "st_space_records:EIO:space_records : dblk < 0");
15495 			rval = EIO;
15496 		} else if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
15497 		    st_cmd(un, SCMD_SPACE, Fmk(dfile), SYNC_CMD) ||
15498 		    st_cmd(un, SCMD_SPACE, Blk(dblk), SYNC_CMD)) {
15499 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15500 			    "st_space_records: EIO :space_records : rewind "
15501 			    "and space failed");
15502 			un->un_pos.pmode = invalid;
15503 			rval = EIO;
15504 		}
15505 	}
15506 
15507 	return (rval);
15508 }
15509 
15510 static int
15511 st_mtbsf_ioctl(struct scsi_tape *un, int64_t files)
15512 {
15513 	ST_FUNC(ST_DEVINFO, st_mtbsf_ioctl);
15514 
15515 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15516 	    "st_mtbsf_ioctl: count=%"PRIx64", eof=%x\n", files, un->un_pos.eof);
15517 	/*
15518 	 * backward space of file filemark (1/2" and 8mm)
15519 	 * tape position will end on the beginning of tape side
15520 	 * of the desired file mark
15521 	 */
15522 	if ((un->un_dp->options & ST_BSF) == 0) {
15523 		return (ENOTTY);
15524 	}
15525 
15526 	if (un->un_pos.pmode == legacy) {
15527 
15528 		/*
15529 		 * If a negative count (which implies a forward space op)
15530 		 * is specified, and we're at logical or physical eot,
15531 		 * bounce the request.
15532 		 */
15533 
15534 		if (un->un_pos.eof >= ST_EOT && files < 0) {
15535 			un->un_err_resid = files;
15536 			un->un_status = SUN_KEY_EOT;
15537 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15538 			    "st_ioctl_mt_bsf : EIO : MTBSF : eof > ST_EOF");
15539 			return (EIO);
15540 		}
15541 		/*
15542 		 * physical tape position may not be what we've been
15543 		 * telling the user; adjust the request accordingly
15544 		 */
15545 		if (IN_EOF(un->un_pos)) {
15546 			un->un_pos.fileno++;
15547 			un->un_pos.blkno = 0;
15548 			files++;
15549 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15550 			    "st_mtbsf_ioctl in eof: count=%"PRIx64", op=%x\n",
15551 			    files, MTBSF);
15552 
15553 		}
15554 	}
15555 
15556 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15557 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15558 		    "st_ioctl : EIO : MTBSF : check den wfm");
15559 		return (EIO);
15560 	}
15561 
15562 	if (files <= 0) {
15563 		/*
15564 		 * for a negative count, we need to step forward
15565 		 * first and then step back again
15566 		 */
15567 		files = -files + 1;
15568 		return (st_forward_space_files(un, files));
15569 	}
15570 	return (st_backward_space_files(un, files, 1));
15571 }
15572 
15573 static int
15574 st_backward_space_files(struct scsi_tape *un, int64_t count, int infront)
15575 {
15576 	int64_t end_fileno;
15577 	int64_t skip_cnt;
15578 	int rval = 0;
15579 
15580 	ST_FUNC(ST_DEVINFO, st_backward_space_files);
15581 
15582 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15583 	    "st_backward_space_files: count=%"PRIx64" eof=%x\n",
15584 	    count, un->un_pos.eof);
15585 	/*
15586 	 * Backspace files (MTNBSF): infront == 0
15587 	 *
15588 	 *	For tapes that can backspace, backspace
15589 	 *	count+1 filemarks and then run forward over
15590 	 *	a filemark
15591 	 *
15592 	 *	For tapes that can't backspace,
15593 	 *		calculate desired filenumber
15594 	 *		(un->un_pos.fileno - count), rewind,
15595 	 *		and then space forward this amount
15596 	 *
15597 	 * Backspace filemarks (MTBSF) infront == 1
15598 	 *
15599 	 *	For tapes that can backspace, backspace count
15600 	 *	filemarks
15601 	 *
15602 	 *	For tapes that can't backspace, calculate
15603 	 *	desired filenumber (un->un_pos.fileno - count),
15604 	 *	add 1, rewind, space forward this amount,
15605 	 *	and mark state as ST_EOF_PENDING appropriately.
15606 	 */
15607 
15608 	if (un->un_pos.pmode == logical) {
15609 
15610 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15611 		    "st_backward_space_files: mt_op=%x count=%"PRIx64
15612 		    "lgclblkno=%"PRIx64"\n", infront?MTBSF:MTNBSF, count,
15613 		    un->un_pos.lgclblkno);
15614 
15615 
15616 		/* In case a drive that won't back space gets in logical mode */
15617 		if ((un->un_dp->options & ST_BSF) == 0) {
15618 			rval = EIO;
15619 			return (rval);
15620 		}
15621 		if ((infront == 1) &&
15622 		    (st_cmd(un, SCMD_SPACE, Fmk(-count), SYNC_CMD))) {
15623 			rval = EIO;
15624 			return (rval);
15625 		} else if ((infront == 0) &&
15626 		    (st_cmd(un, SCMD_SPACE, Fmk((-count)-1), SYNC_CMD)) &&
15627 		    (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD))) {
15628 			rval = EIO;
15629 			return (rval);
15630 		}
15631 		return (rval);
15632 	}
15633 
15634 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15635 	    "st_backward_space_files: mt_op=%x count=%"PRIx64
15636 	    "fileno=%x blkno=%x\n",
15637 	    infront?MTBSF:MTNBSF, count, un->un_pos.fileno, un->un_pos.blkno);
15638 
15639 
15640 
15641 	/*
15642 	 * Handle the simple case of BOT
15643 	 * playing a role in these cmds.
15644 	 * We do this by calculating the
15645 	 * ending file number. If the ending
15646 	 * file is < BOT, rewind and set an
15647 	 * error and mark resid appropriately.
15648 	 * If we're backspacing a file (not a
15649 	 * filemark) and the target file is
15650 	 * the first file on the tape, just
15651 	 * rewind.
15652 	 */
15653 
15654 	/* figure expected destination of this SPACE command */
15655 	end_fileno = un->un_pos.fileno - count;
15656 
15657 	/*
15658 	 * Would the end effect of this SPACE be the same as rewinding?
15659 	 * If so just rewind instead.
15660 	 */
15661 	if ((infront != 0) && (end_fileno < 0) ||
15662 	    (infront == 0) && (end_fileno <= 0)) {
15663 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15664 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15665 			    "st_backward_space_files: EIO : "
15666 			    "rewind in lou of BSF failed\n");
15667 			rval = EIO;
15668 		}
15669 		if (end_fileno < 0) {
15670 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15671 			    "st_backward_space_files: EIO : "
15672 			    "back space file greater then fileno\n");
15673 			rval = EIO;
15674 			un->un_err_resid = -end_fileno;
15675 			un->un_status = SUN_KEY_BOT;
15676 		}
15677 		return (rval);
15678 	}
15679 
15680 	if (un->un_dp->options & ST_BSF) {
15681 		skip_cnt = 1 - infront;
15682 		/*
15683 		 * If we are going to end up at the beginning
15684 		 * of the file, we have to space one extra file
15685 		 * first, and then space forward later.
15686 		 */
15687 		end_fileno = -(count + skip_cnt);
15688 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15689 		    "skip_cnt=%"PRIx64", tmp=%"PRIx64"\n",
15690 		    skip_cnt, end_fileno);
15691 		if (st_cmd(un, SCMD_SPACE, Fmk(end_fileno), SYNC_CMD)) {
15692 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15693 			    "st_backward_space_files:EIO:back space fm failed");
15694 			rval = EIO;
15695 		}
15696 	} else {
15697 		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
15698 			rval = EIO;
15699 		} else {
15700 			skip_cnt = end_fileno + infront;
15701 		}
15702 	}
15703 
15704 	/*
15705 	 * If we have to space forward, do so...
15706 	 */
15707 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
15708 	    "space forward skip_cnt=%"PRIx64", rval=%x\n", skip_cnt, rval);
15709 
15710 	if (rval == 0 && skip_cnt) {
15711 		if (st_cmd(un, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
15712 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15713 			    "st_backward_space_files:EIO:space fm skip count");
15714 			rval = EIO;
15715 		} else if (infront) {
15716 			/*
15717 			 * If we had to space forward, and we're
15718 			 * not a tape that can backspace, mark state
15719 			 * as if we'd just seen a filemark during a
15720 			 * a read.
15721 			 */
15722 			if ((un->un_dp->options & ST_BSF) == 0) {
15723 				un->un_pos.eof = ST_EOF_PENDING;
15724 				un->un_pos.fileno -= 1;
15725 				un->un_pos.blkno = LASTBLK;
15726 				un->un_running.pmode = invalid;
15727 			}
15728 		}
15729 	}
15730 
15731 	if (rval != 0) {
15732 		un->un_pos.pmode = invalid;
15733 	}
15734 
15735 	return (rval);
15736 }
15737 
15738 static int
15739 st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count)
15740 {
15741 	int rval;
15742 
15743 	ST_FUNC(ST_DEVINFO, st_mtnbsf_ioctl);
15744 
15745 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15746 	    "nbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15747 
15748 	if (un->un_pos.pmode == legacy) {
15749 		/*
15750 		 * backward space file to beginning of file
15751 		 *
15752 		 * If a negative count (which implies a forward space op)
15753 		 * is specified, and we're at logical or physical eot,
15754 		 * bounce the request.
15755 		 */
15756 
15757 		if (un->un_pos.eof >= ST_EOT && count < 0) {
15758 			un->un_err_resid = count;
15759 			un->un_status = SUN_KEY_EOT;
15760 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15761 			    "st_ioctl : EIO : > EOT and count < 0");
15762 			return (EIO);
15763 		}
15764 		/*
15765 		 * physical tape position may not be what we've been
15766 		 * telling the user; adjust the request accordingly
15767 		 */
15768 		if (IN_EOF(un->un_pos)) {
15769 			un->un_pos.fileno++;
15770 			un->un_pos.blkno = 0;
15771 			count++;
15772 		}
15773 	}
15774 
15775 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15776 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15777 		    "st_ioctl : EIO : MTNBSF check den and wfm");
15778 		return (EIO);
15779 	}
15780 
15781 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15782 	    "mtnbsf: count=%"PRIx64", eof=%x\n", count, un->un_pos.eof);
15783 
15784 	if (count <= 0) {
15785 		rval = st_forward_space_files(un, -count);
15786 	} else {
15787 		rval = st_backward_space_files(un, count, 0);
15788 	}
15789 	return (rval);
15790 }
15791 
15792 static int
15793 st_mtbsr_ioctl(struct scsi_tape *un, int64_t num)
15794 {
15795 	ST_FUNC(ST_DEVINFO, st_mtbsr_ioctl);
15796 
15797 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
15798 	    "bsr: count=%"PRIx64", eof=%x\n", num, un->un_pos.eof);
15799 
15800 	if (un->un_pos.pmode == legacy) {
15801 		/*
15802 		 * backward space into inter-record gap
15803 		 *
15804 		 * If a negative count (which implies a forward space op)
15805 		 * is specified, and we're at logical or physical eot,
15806 		 * bounce the request.
15807 		 */
15808 		if (un->un_pos.eof >= ST_EOT && num < 0) {
15809 			un->un_err_resid = num;
15810 			un->un_status = SUN_KEY_EOT;
15811 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15812 			    "st_ioctl : EIO : MTBSR > EOT");
15813 			return (EIO);
15814 		}
15815 
15816 		if (num == 0) {
15817 			COPY_POS(&un->un_err_pos, &un->un_pos);
15818 			un->un_err_resid = 0;
15819 			if (IN_EOF(un->un_pos) && SVR4_BEHAVIOR) {
15820 				un->un_status = SUN_KEY_EOF;
15821 			}
15822 			return (0);
15823 		}
15824 
15825 		/*
15826 		 * physical tape position may not be what we've been
15827 		 * telling the user; adjust the position accordingly.
15828 		 * bsr can not skip filemarks and continue to skip records
15829 		 * therefore if we are logically before the filemark but
15830 		 * physically at the EOT side of the filemark, we need to step
15831 		 * back; this allows fsr N where N > number of blocks in file
15832 		 * followed by bsr 1 to position at the beginning of last block
15833 		 */
15834 		if (IN_EOF(un->un_pos)) {
15835 			tapepos_t save;
15836 			optype lastop = un->un_lastop;
15837 
15838 			COPY_POS(&save, &un->un_pos);
15839 			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD) == -1) {
15840 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15841 				    "st_mtbsr_ioctl: EIO : MTBSR can't space");
15842 				return (EIO);
15843 			}
15844 
15845 			COPY_POS(&un->un_pos, &save);
15846 			un->un_lastop = lastop;
15847 		}
15848 	}
15849 
15850 	un->un_pos.eof = ST_NO_EOF;
15851 
15852 	if (st_check_density_or_wfm(un->un_dev, 1, 0, STEPBACK)) {
15853 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15854 		    "st_ioctl : EIO : MTBSR : can't set density or wfm");
15855 		return (EIO);
15856 	}
15857 
15858 	num = -num;
15859 	return (st_space_records(un, num));
15860 }
15861 
15862 static int
15863 st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15864 {
15865 	int rval;
15866 
15867 	ST_FUNC(ST_DEVINFO, st_mtfsfm_ioctl);
15868 
15869 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, cnt), SYNC_CMD);
15870 	if (rval == 0) {
15871 		un->un_pos.pmode = logical;
15872 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15873 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15874 		/*
15875 		 * Drive says invalid field in cdb.
15876 		 * Doesn't like space multiple. Position isn't lost.
15877 		 */
15878 		un->un_err_resid = cnt;
15879 		un->un_status = 0;
15880 		rval = ENOTTY;
15881 	} else {
15882 		un->un_err_resid = cnt;
15883 		un->un_pos.pmode = invalid;
15884 	}
15885 	return (rval);
15886 }
15887 
15888 static int
15889 st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt)
15890 {
15891 	int rval;
15892 
15893 	ST_FUNC(ST_DEVINFO, st_mtbsfm_ioctl);
15894 
15895 	rval = st_cmd(un, SCMD_SPACE, SPACE(SP_SQFLM, -cnt), SYNC_CMD);
15896 	if (rval == 0) {
15897 		un->un_pos.pmode = logical;
15898 	} else if ((un->un_status == KEY_ILLEGAL_REQUEST) &&
15899 	    (un->un_sd->sd_sense->es_add_code == 0x24)) {
15900 		/*
15901 		 * Drive says invalid field in cdb.
15902 		 * Doesn't like space multiple. Position isn't lost.
15903 		 */
15904 		un->un_err_resid = cnt;
15905 		un->un_status = 0;
15906 		rval = ENOTTY;
15907 	} else {
15908 		un->un_err_resid = cnt;
15909 		un->un_pos.pmode = invalid;
15910 	}
15911 	return (rval);
15912 }
15913 
15914 #ifdef	__x86
15915 
15916 /*
15917  * release contig_mem and wake up waiting thread, if any
15918  */
15919 static void
15920 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
15921 {
15922 	mutex_enter(ST_MUTEX);
15923 
15924 	ST_FUNC(ST_DEVINFO, st_release_contig_mem);
15925 
15926 	cp->cm_next = un->un_contig_mem;
15927 	un->un_contig_mem = cp;
15928 	un->un_contig_mem_available_num++;
15929 	cv_broadcast(&un->un_contig_mem_cv);
15930 
15931 	mutex_exit(ST_MUTEX);
15932 }
15933 
15934 /*
15935  * St_get_contig_mem will return a contig_mem if there is one available
15936  * in current system. Otherwise, it will try to alloc one, if the total
15937  * number of contig_mem is within st_max_contig_mem_num.
15938  * It will sleep, if allowed by caller or return NULL, if no contig_mem
15939  * is available for now.
15940  */
15941 static struct contig_mem *
15942 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
15943 {
15944 	size_t rlen;
15945 	struct contig_mem *cp = NULL;
15946 	ddi_acc_handle_t acc_hdl;
15947 	caddr_t addr;
15948 	int big_enough = 0;
15949 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
15950 	    DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
15951 
15952 	/* Try to get one available contig_mem */
15953 	mutex_enter(ST_MUTEX);
15954 
15955 	ST_FUNC(ST_DEVINFO, st_get_contig_mem);
15956 
15957 	if (un->un_contig_mem_available_num > 0) {
15958 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15959 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
15960 		/*
15961 		 * we failed to get one. we're going to
15962 		 * alloc one more contig_mem for this I/O
15963 		 */
15964 		mutex_exit(ST_MUTEX);
15965 		cp = (struct contig_mem *)kmem_zalloc(
15966 		    sizeof (struct contig_mem) + biosize(),
15967 		    alloc_flags);
15968 		if (cp == NULL) {
15969 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15970 			    "alloc contig_mem failure\n");
15971 			return (NULL); /* cannot get one */
15972 		}
15973 		cp->cm_bp = (struct buf *)
15974 		    (((caddr_t)cp) + sizeof (struct contig_mem));
15975 		bioinit(cp->cm_bp);
15976 		mutex_enter(ST_MUTEX);
15977 		un->un_contig_mem_total_num++; /* one more available */
15978 	} else {
15979 		/*
15980 		 * we failed to get one and we're NOT allowed to
15981 		 * alloc more contig_mem
15982 		 */
15983 		if (alloc_flags == KM_SLEEP) {
15984 			while (un->un_contig_mem_available_num <= 0) {
15985 				cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
15986 			}
15987 			ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
15988 		} else {
15989 			mutex_exit(ST_MUTEX);
15990 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
15991 			    "alloc contig_mem failure\n");
15992 			return (NULL); /* cannot get one */
15993 		}
15994 	}
15995 	mutex_exit(ST_MUTEX);
15996 
15997 	/* We need to check if this block of mem is big enough for this I/O */
15998 	if (cp->cm_len < len) {
15999 		/* not big enough, need to alloc a new one */
16000 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
16001 		    DDI_DMA_STREAMING, dma_alloc_cb, NULL,
16002 		    &addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
16003 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
16004 			    "alloc contig_mem failure: not enough mem\n");
16005 			st_release_contig_mem(un, cp);
16006 			cp = NULL;
16007 		} else {
16008 			if (cp->cm_addr) {
16009 				/* release previous one before attach new one */
16010 				ddi_dma_mem_free(&cp->cm_acc_hdl);
16011 			}
16012 			mutex_enter(ST_MUTEX);
16013 			un->un_max_contig_mem_len =
16014 			    un->un_max_contig_mem_len >= len ?
16015 			    un->un_max_contig_mem_len : len;
16016 			mutex_exit(ST_MUTEX);
16017 
16018 			/* attach new mem to this cp */
16019 			cp->cm_addr = addr;
16020 			cp->cm_acc_hdl = acc_hdl;
16021 			cp->cm_len = len;
16022 
16023 			goto alloc_ok; /* get one usable cp */
16024 		}
16025 	} else {
16026 		goto alloc_ok; /* get one usable cp */
16027 	}
16028 
16029 	/* cannot find/alloc a usable cp, when we get here */
16030 
16031 	mutex_enter(ST_MUTEX);
16032 	if ((un->un_max_contig_mem_len < len) ||
16033 	    (alloc_flags != KM_SLEEP)) {
16034 		mutex_exit(ST_MUTEX);
16035 		return (NULL);
16036 	}
16037 
16038 	/*
16039 	 * we're allowed to sleep, and there is one big enough
16040 	 * contig mem in the system, which is currently in use,
16041 	 * wait for it...
16042 	 */
16043 	big_enough = 1;
16044 	do {
16045 		cv_wait(&un->un_contig_mem_cv, ST_MUTEX);
16046 		ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough);
16047 	} while (cp == NULL);
16048 	mutex_exit(ST_MUTEX);
16049 
16050 	/* we get the big enough contig mem, finally */
16051 
16052 alloc_ok:
16053 	/* init bp attached to this cp */
16054 	bioreset(cp->cm_bp);
16055 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
16056 	cp->cm_bp->b_private = (void *)cp;
16057 
16058 	return (cp);
16059 }
16060 
16061 /*
16062  * this is the biodone func for the bp used in big block I/O
16063  */
16064 static int
16065 st_bigblk_xfer_done(struct buf *bp)
16066 {
16067 	struct contig_mem *cp;
16068 	struct buf *orig_bp;
16069 	int ioerr;
16070 	struct scsi_tape *un;
16071 
16072 	/* sanity check */
16073 	if (bp == NULL) {
16074 		return (DDI_FAILURE);
16075 	}
16076 
16077 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16078 	if (un == NULL) {
16079 		return (DDI_FAILURE);
16080 	}
16081 
16082 	ST_FUNC(ST_DEVINFO, st_bigblk_xfer_done);
16083 
16084 	cp = (struct contig_mem *)bp->b_private;
16085 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
16086 	cp->cm_bp = bp;
16087 
16088 	/* special handling for special I/O */
16089 	if (cp->cm_use_sbuf) {
16090 #ifndef __lock_lint
16091 		ASSERT(un->un_sbuf_busy);
16092 #endif
16093 		un->un_sbufp = orig_bp;
16094 		cp->cm_use_sbuf = 0;
16095 	}
16096 
16097 	orig_bp->b_resid = bp->b_resid;
16098 	ioerr = geterror(bp);
16099 	if (ioerr != 0) {
16100 		bioerror(orig_bp, ioerr);
16101 	} else if (orig_bp->b_flags & B_READ) {
16102 		/* copy data back to original bp */
16103 		(void) bp_copyout(bp->b_un.b_addr, orig_bp, 0,
16104 		    bp->b_bcount - bp->b_resid);
16105 	}
16106 
16107 	st_release_contig_mem(un, cp);
16108 
16109 	biodone(orig_bp);
16110 
16111 	return (DDI_SUCCESS);
16112 }
16113 
16114 /*
16115  * We use this func to replace original bp that may not be able to do I/O
16116  * in big block size with one that can
16117  */
16118 static struct buf *
16119 st_get_bigblk_bp(struct buf *bp)
16120 {
16121 	struct contig_mem *cp;
16122 	struct scsi_tape *un;
16123 	struct buf *cont_bp;
16124 
16125 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16126 	if (un == NULL) {
16127 		return (bp);
16128 	}
16129 
16130 	ST_FUNC(ST_DEVINFO, st_get_bigblk_bp);
16131 
16132 	/* try to get one contig_mem */
16133 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
16134 	if (!cp) {
16135 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
16136 		    "Cannot alloc contig buf for I/O for %lu blk size",
16137 		    bp->b_bcount);
16138 		return (bp);
16139 	}
16140 	cont_bp = cp->cm_bp;
16141 	cp->cm_bp = bp;
16142 
16143 	/* make sure that we "are" using un_sbufp for special I/O */
16144 	if (bp == un->un_sbufp) {
16145 #ifndef __lock_lint
16146 		ASSERT(un->un_sbuf_busy);
16147 #endif
16148 		un->un_sbufp = cont_bp;
16149 		cp->cm_use_sbuf = 1;
16150 	}
16151 
16152 	/* clone bp */
16153 	cont_bp->b_bcount = bp->b_bcount;
16154 	cont_bp->b_resid = bp->b_resid;
16155 	cont_bp->b_iodone = st_bigblk_xfer_done;
16156 	cont_bp->b_file = bp->b_file;
16157 	cont_bp->b_offset = bp->b_offset;
16158 	cont_bp->b_dip = bp->b_dip;
16159 	cont_bp->b_error = 0;
16160 	cont_bp->b_proc = NULL;
16161 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
16162 	cont_bp->b_shadow = NULL;
16163 	cont_bp->b_pages = NULL;
16164 	cont_bp->b_edev = bp->b_edev;
16165 	cont_bp->b_dev = bp->b_dev;
16166 	cont_bp->b_lblkno = bp->b_lblkno;
16167 	cont_bp->b_forw = bp->b_forw;
16168 	cont_bp->b_back = bp->b_back;
16169 	cont_bp->av_forw = bp->av_forw;
16170 	cont_bp->av_back = bp->av_back;
16171 	cont_bp->b_bufsize = bp->b_bufsize;
16172 
16173 	/* get data in original bp */
16174 	if (bp->b_flags & B_WRITE) {
16175 		(void) bp_copyin(bp, cont_bp->b_un.b_addr, 0, bp->b_bcount);
16176 	}
16177 
16178 	return (cont_bp);
16179 }
16180 #else
16181 #ifdef __lock_lint
16182 static int
16183 st_bigblk_xfer_done(struct buf *bp)
16184 {
16185 	return (0);
16186 }
16187 #endif
16188 #endif
16189 
16190 static const char *eof_status[] =
16191 {
16192 	"NO_EOF",
16193 	"EOF_PENDING",
16194 	"EOF",
16195 	"EOT_PENDING",
16196 	"EOT",
16197 	"EOM",
16198 	"AFTER_EOM"
16199 };
16200 static const char *mode[] = {
16201 	"invalid",
16202 	"legacy",
16203 	"logical"
16204 };
16205 
16206 static void
16207 st_print_position(dev_info_t *dev, char *label, uint_t level,
16208 const char *comment, tapepos_t *pos)
16209 {
16210 	ST_FUNC(dev, st_print_position);
16211 
16212 	scsi_log(dev, label, level,
16213 	    "%s Position data:\n", comment);
16214 	scsi_log(dev, label, CE_CONT,
16215 	    "Positioning mode = %s", mode[pos->pmode]);
16216 	scsi_log(dev, label, CE_CONT,
16217 	    "End Of File/Tape = %s", eof_status[pos->eof]);
16218 	scsi_log(dev, label, CE_CONT,
16219 	    "File Number      = 0x%x", pos->fileno);
16220 	scsi_log(dev, label, CE_CONT,
16221 	    "Block Number     = 0x%x", pos->blkno);
16222 	scsi_log(dev, label, CE_CONT,
16223 	    "Logical Block    = 0x%"PRIx64, pos->lgclblkno);
16224 	scsi_log(dev, label, CE_CONT,
16225 	    "Partition Number = 0x%x", pos->partition);
16226 }
16227 static int
16228 st_check_if_media_changed(struct scsi_tape *un, caddr_t data, int size)
16229 {
16230 
16231 	int result = 0;
16232 	int i;
16233 	ST_FUNC(ST_DEVINFO, st_check_if_media_changed);
16234 
16235 	/*
16236 	 * find non alpha numeric working from the end.
16237 	 */
16238 	for (i = size - 1; i >= 0; i--) {
16239 		if (ISALNUM(data[i]) == 0 || data[i] == ' ') {
16240 			data[i] = 0;
16241 			size = i;
16242 		}
16243 	}
16244 
16245 	if (size == 1) {
16246 		/*
16247 		 * Drive seems to think its returning useful data
16248 		 * but it looks like all junk
16249 		 */
16250 		return (result);
16251 	}
16252 
16253 	size++;
16254 
16255 	/*
16256 	 * Actually got a valid serial number.
16257 	 * If never stored one before alloc space for it.
16258 	 */
16259 	if (un->un_media_id_len == 0) {
16260 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16261 		un->un_media_id_len = size;
16262 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16263 		un->un_media_id[min(size, strlen(data))] = 0;
16264 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16265 		    "Found Media Id %s length = %d\n", un->un_media_id, size);
16266 	} else if (size > un->un_media_id_len) {
16267 		if (strncmp(un->un_media_id, data, size) != 0) {
16268 			result = ESPIPE;
16269 		}
16270 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16271 		    "Longer Media Id old ID:%s new ID:%s\n",
16272 		    un->un_media_id, data);
16273 		kmem_free(un->un_media_id, un->un_media_id_len);
16274 		un->un_media_id = kmem_zalloc(size, KM_SLEEP);
16275 		un->un_media_id_len = size;
16276 		(void) strncpy(un->un_media_id, data, size);
16277 		un->un_media_id[size] = 0;
16278 	} else if (strncmp(data, un->un_media_id,
16279 	    min(size, un->un_media_id_len)) != 0) {
16280 		ST_DEBUG1(ST_DEVINFO, st_label, SCSI_DEBUG,
16281 		    "Old Media Id %s length = %d New %s length = %d\n",
16282 		    un->un_media_id, un->un_media_id_len, data, size);
16283 		bzero(un->un_media_id, un->un_media_id_len);
16284 		(void) strncpy(un->un_media_id, data, min(size, strlen(data)));
16285 		un->un_media_id[min(size, strlen(data))] = 0;
16286 		result = ESPIPE;
16287 	} else {
16288 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
16289 		    "Media Id still %s\n", un->un_media_id);
16290 	}
16291 
16292 	ASSERT(strlen(un->un_media_id) <= size);
16293 
16294 	return (result);
16295 }
16296 #define	ID_SIZE 32
16297 typedef struct
16298 {
16299 	uchar_t avilable_data0;
16300 	uchar_t avilable_data1;
16301 	uchar_t avilable_data2;
16302 	uchar_t avilable_data3;
16303 	uchar_t attribute_msb;
16304 	uchar_t attribute_lsb;
16305 #ifdef _BIT_FIELDS_LTOH
16306 	uchar_t format		: 2,
16307 				: 5,
16308 		read_only	: 1;
16309 #else
16310 	uchar_t read_only	: 1,
16311 				: 5,
16312 		format		: 2;
16313 #endif
16314 	uchar_t attribute_len_msb;
16315 	uchar_t attribute_len_lsb;
16316 }attribute_header;
16317 
16318 typedef struct {
16319 	attribute_header header;
16320 	char data[1];
16321 }mam_attribute;
16322 
16323 static int
16324 st_handle_hex_media_id(struct scsi_tape *un, void *pnt, int size)
16325 {
16326 	int result;
16327 	int newsize = (size << 1) + 3; /* extra for leading 0x and null term */
16328 	int i;
16329 	uchar_t byte;
16330 	char *format;
16331 	uchar_t *data = (uchar_t *)pnt;
16332 	char *buf = kmem_alloc(newsize, KM_SLEEP);
16333 
16334 	ST_FUNC(ST_DEVINFO, st_handle_hex_media_id);
16335 
16336 	(void) sprintf(buf, "0x");
16337 	for (i = 0; i < size; i++) {
16338 		byte = data[i];
16339 		if (byte < 0x10)
16340 			format = "0%x";
16341 		else
16342 			format = "%x";
16343 		(void) sprintf(&buf[(int)strlen(buf)], format, byte);
16344 	}
16345 	result = st_check_if_media_changed(un, buf, newsize);
16346 
16347 	kmem_free(buf, newsize);
16348 
16349 	return (result);
16350 }
16351 
16352 
16353 static int
16354 st_get_media_id_via_read_attribute(struct scsi_tape *un, ubufunc_t bufunc)
16355 {
16356 	int result;
16357 	mam_attribute *buffer;
16358 	int size;
16359 	int newsize;
16360 
16361 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_read_attribute);
16362 	size = sizeof (attribute_header) + max(un->un_media_id_len, ID_SIZE);
16363 again:
16364 	buffer = kmem_zalloc(size, KM_SLEEP);
16365 	result = st_read_attributes(un, 0x0401, buffer, size, bufunc);
16366 	if (result == 0) {
16367 
16368 		newsize = (buffer->header.attribute_len_msb << 8) |
16369 		    buffer->header.attribute_len_lsb;
16370 
16371 		if (newsize + sizeof (attribute_header) > size) {
16372 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
16373 			    "resizing read attribute data from %d to %d format"
16374 			    " %d\n", size, (int)sizeof (attribute_header) +
16375 			    newsize, buffer->header.format);
16376 			kmem_free(buffer, size);
16377 			size = newsize + sizeof (attribute_header);
16378 			goto again;
16379 		}
16380 
16381 		un->un_media_id_method = st_get_media_id_via_read_attribute;
16382 		if (buffer->header.format == 0) {
16383 			result =
16384 			    st_handle_hex_media_id(un, buffer->data, newsize);
16385 		} else {
16386 			result = st_check_if_media_changed(un, buffer->data,
16387 			    newsize);
16388 		}
16389 	} else if (result == EINVAL && un->un_max_cdb_sz < CDB_GROUP4) {
16390 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
16391 		    "Read Attribute Command for Media Identification is not "
16392 		    "supported on the HBA that this drive is attached to.");
16393 		result = ENOTTY;
16394 	}
16395 
16396 	kmem_free(buffer, size);
16397 	un->un_status = 0;
16398 
16399 	return (result);
16400 }
16401 
16402 
16403 static int
16404 st_get_media_id_via_media_serial_cmd(struct scsi_tape *un, ubufunc_t bufunc)
16405 {
16406 	char cdb[CDB_GROUP5];
16407 	struct uscsi_cmd *ucmd;
16408 	struct scsi_extended_sense sense;
16409 	int rval;
16410 	int size = max(un->un_media_id_len, ID_SIZE);
16411 	caddr_t buf;
16412 
16413 	ST_FUNC(ST_DEVINFO, st_get_media_id_via_media_serial_cmd);
16414 
16415 	if (un->un_sd->sd_inq->inq_ansi < 3) {
16416 		return (ENOTTY);
16417 	}
16418 
16419 	ucmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
16420 upsize:
16421 	buf = kmem_alloc(size, KM_SLEEP);
16422 
16423 	cdb[0] = (char)SCMD_SVC_ACTION_IN_G5;
16424 	cdb[1] = SSVC_ACTION_READ_MEDIA_SERIAL;
16425 	cdb[2] = 0;
16426 	cdb[3] = 0;
16427 	cdb[4] = 0;
16428 	cdb[5] = 0;
16429 	cdb[6] = (char)(size >> 24);
16430 	cdb[7] = (char)(size >> 16);
16431 	cdb[8] = (char)(size >> 8);
16432 	cdb[9] = (char)(size);
16433 	cdb[10] = 0;
16434 	cdb[11] = 0;
16435 
16436 	ucmd->uscsi_flags = USCSI_READ | USCSI_RQENABLE;
16437 	ucmd->uscsi_timeout = un->un_dp->non_motion_timeout;
16438 	ucmd->uscsi_cdb = &cdb[0];
16439 	ucmd->uscsi_cdblen = sizeof (cdb);
16440 	ucmd->uscsi_bufaddr = buf;
16441 	ucmd->uscsi_buflen = size;
16442 	ucmd->uscsi_rqbuf = (caddr_t)&sense;
16443 	ucmd->uscsi_rqlen = sizeof (sense);
16444 
16445 	rval = bufunc(un, ucmd, FKIOCTL);
16446 
16447 	if (rval || ucmd->uscsi_status != 0) {
16448 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16449 		    "media serial command returned %d scsi_status %d"
16450 		    " rqstatus %d", rval, ucmd->uscsi_status,
16451 		    ucmd->uscsi_rqstatus);
16452 		/*
16453 		 * If this returns invalid operation code don't try again.
16454 		 */
16455 		if (sense.es_key == KEY_ILLEGAL_REQUEST &&
16456 		    sense.es_add_code == 0x20) {
16457 			rval = ENOTTY;
16458 		} else if (rval == 0) {
16459 			rval = EIO;
16460 		}
16461 		un->un_status = 0;
16462 	} else {
16463 		int act_size;
16464 
16465 		/*
16466 		 * get reported size.
16467 		 */
16468 		act_size = (int)buf[3] | (int)(buf[2] << 8) |
16469 		    (int)(buf[1] << 16) | (int)(buf[0] << 24);
16470 
16471 		/* documentation says mod 4. */
16472 		while (act_size & 3) {
16473 			act_size++;
16474 		}
16475 
16476 		/*
16477 		 * If reported size is larger that we our buffer.
16478 		 * Free the old one and allocate one that is larger
16479 		 * enough and re-issuse the command.
16480 		 */
16481 		if (act_size + 4 > size) {
16482 			kmem_free(buf, size);
16483 			size = act_size + 4;
16484 			goto upsize;
16485 		}
16486 
16487 		if (act_size == 0) {
16488 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16489 			    "media serial number is not available");
16490 			un->un_status = 0;
16491 			rval = 0;
16492 		} else {
16493 			/*
16494 			 * set data pointer to point to the start
16495 			 * of that serial number.
16496 			 */
16497 			un->un_media_id_method =
16498 			    st_get_media_id_via_media_serial_cmd;
16499 			rval =
16500 			    st_check_if_media_changed(un, &buf[4], act_size);
16501 		}
16502 	}
16503 
16504 	kmem_free(ucmd, sizeof (struct uscsi_cmd));
16505 	kmem_free(buf, size);
16506 
16507 	return (rval);
16508 }
16509 
16510 
16511 /* ARGSUSED */
16512 static int
16513 st_bogus_media_id(struct scsi_tape *un, ubufunc_t bufunc)
16514 {
16515 	ST_FUNC(ST_DEVINFO, st_bogus_media_id);
16516 
16517 	ASSERT(un->un_media_id == NULL || un->un_media_id == bogusID);
16518 	ASSERT(un->un_media_id_len == 0);
16519 	un->un_media_id = (char *)bogusID;
16520 	un->un_media_id_len = 0;
16521 	return (0);
16522 }
16523 
16524 typedef int (*media_chk_function)(struct scsi_tape *, ubufunc_t bufunc);
16525 
16526 media_chk_function media_chk_functions[] = {
16527 	st_get_media_id_via_media_serial_cmd,
16528 	st_get_media_id_via_read_attribute,
16529 	st_bogus_media_id
16530 };
16531 
16532 static int
16533 st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc)
16534 {
16535 	int result = 0;
16536 	int i;
16537 
16538 	ST_FUNC(ST_DEVINFO, st_get_media_identification);
16539 
16540 	for (i = 0; i < ST_NUM_MEMBERS(media_chk_functions); i++) {
16541 		if (result == ENOTTY) {
16542 			/*
16543 			 * Last operation type not supported by this device.
16544 			 * Make so next time it doesn`t do that again.
16545 			 */
16546 			un->un_media_id_method = media_chk_functions[i];
16547 		} else if (un->un_media_id_method != media_chk_functions[i] &&
16548 		    un->un_media_id_method != st_get_media_identification) {
16549 			continue;
16550 		}
16551 		result = media_chk_functions[i](un, bufunc);
16552 		/*
16553 		 * If result indicates the function was successful or
16554 		 * that the media is not the same as last known, break.
16555 		 */
16556 		if (result == 0 || result == ESPIPE) {
16557 			break;
16558 		}
16559 	}
16560 
16561 	return (result);
16562 }
16563 
16564 static errstate
16565 st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
16566     errstate onentry)
16567 {
16568 
16569 	int ret;
16570 	st_err_info *errinfo;
16571 	recov_info *ri = (recov_info *)pkt->pkt_private;
16572 
16573 	ST_FUNC(ST_DEVINFO, st_command_recovery);
16574 
16575 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16576 
16577 	ASSERT(un->un_recov_buf_busy == 0);
16578 
16579 	/*
16580 	 * Don't try and recover a reset that this device sent.
16581 	 */
16582 	if (un->un_rsvd_status & ST_INITIATED_RESET &&
16583 	    onentry == DEVICE_RESET) {
16584 		return (COMMAND_DONE_ERROR);
16585 	}
16586 
16587 	/*
16588 	 * See if expected position was passed with scsi_pkt.
16589 	 */
16590 	if (ri->privatelen == sizeof (recov_info)) {
16591 
16592 		/*
16593 		 * Not for this command.
16594 		 */
16595 		if (ri->cmd_attrib->do_not_recover) {
16596 			return (COMMAND_DONE_ERROR);
16597 		}
16598 
16599 		/*
16600 		 * Create structure to hold all error state info.
16601 		 */
16602 		errinfo = kmem_zalloc(ST_ERR_INFO_SIZE, KM_SLEEP);
16603 		errinfo->ei_error_type = onentry;
16604 		errinfo->ei_failing_bp = ri->cmd_bp;
16605 		COPY_POS(&errinfo->ei_expected_pos, &ri->pos);
16606 	} else {
16607 		/* disabled */
16608 		return (COMMAND_DONE_ERROR);
16609 	}
16610 
16611 	bcopy(pkt, &errinfo->ei_failed_pkt, scsi_pkt_size());
16612 	bcopy(pkt->pkt_scbp, &errinfo->ei_failing_status, SECMDS_STATUS_SIZE);
16613 	ret = ddi_taskq_dispatch(un->un_recov_taskq, st_recover, errinfo,
16614 	    DDI_NOSLEEP);
16615 	ASSERT(ret == DDI_SUCCESS);
16616 	if (ret != DDI_SUCCESS) {
16617 		kmem_free(errinfo, ST_ERR_INFO_SIZE);
16618 		return (COMMAND_DONE_ERROR);
16619 	}
16620 	return (JUST_RETURN); /* release calling thread */
16621 }
16622 
16623 
16624 static void
16625 st_recov_ret(struct scsi_tape *un, st_err_info *errinfo, errstate err)
16626 {
16627 	int error_number;
16628 	buf_t *bp;
16629 
16630 
16631 	ST_FUNC(ST_DEVINFO, st_recov_ret);
16632 
16633 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
16634 #if !defined(lint)
16635 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
16636 #endif
16637 
16638 	bp = errinfo->ei_failing_bp;
16639 	kmem_free(errinfo, ST_ERR_INFO_SIZE);
16640 
16641 	switch (err) {
16642 	case JUST_RETURN:
16643 		mutex_exit(&un->un_sd->sd_mutex);
16644 		return;
16645 
16646 	case COMMAND_DONE:
16647 	case COMMAND_DONE_ERROR_RECOVERED:
16648 		ST_DO_KSTATS(bp, kstat_runq_exit);
16649 		error_number = 0;
16650 		break;
16651 
16652 	default:
16653 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16654 		    "st_recov_ret with unhandled errstat %d\n", err);
16655 		/* FALLTHROUGH */
16656 	case COMMAND_DONE_ERROR:
16657 	case COMMAND_DONE_EACCES:
16658 		ST_DO_KSTATS(bp, kstat_waitq_exit);
16659 		ST_DO_ERRSTATS(un, st_transerrs);
16660 		error_number = EIO;
16661 		st_set_pe_flag(un);
16662 		break;
16663 
16664 	}
16665 
16666 	st_bioerror(bp, error_number);
16667 	st_done_and_mutex_exit(un, bp);
16668 }
16669 
16670 
16671 static void
16672 st_recover(void *arg)
16673 {
16674 	st_err_info *const errinfo = (st_err_info *)arg;
16675 	uchar_t com = errinfo->ei_failed_pkt.pkt_cdbp[0];
16676 	struct scsi_tape *un;
16677 	tapepos_t cur_pos;
16678 	int rval;
16679 	errstate status = COMMAND_DONE_ERROR;
16680 	recov_info *rcv;
16681 	buf_t *bp;
16682 
16683 
16684 	rcv = errinfo->ei_failed_pkt.pkt_private;
16685 	ASSERT(rcv->privatelen == sizeof (recov_info));
16686 	bp = rcv->cmd_bp;
16687 
16688 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16689 
16690 	ASSERT(un != NULL);
16691 
16692 	mutex_enter(ST_MUTEX);
16693 
16694 	ST_FUNC(ST_DEVINFO, st_recover);
16695 
16696 	ST_CDB(ST_DEVINFO, "Recovering command",
16697 	    (caddr_t)errinfo->ei_failed_pkt.pkt_cdbp);
16698 	ST_SENSE(ST_DEVINFO, "sense status for failed command",
16699 	    (caddr_t)&errinfo->ei_failing_status,
16700 	    sizeof (struct scsi_arq_status));
16701 	ST_POS(ST_DEVINFO, rcv->cmd_attrib->recov_pos_type == POS_STARTING ?
16702 	    "starting position for recovery command" :
16703 	    "expected position for recovery command",
16704 	    &errinfo->ei_expected_pos);
16705 
16706 	rval = st_test_path_to_device(un);
16707 
16708 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16709 	    "st_recover called with %s, TUR returned %d\n",
16710 	    errstatenames[errinfo->ei_error_type], rval);
16711 	/*
16712 	 * If the drive responed to the TUR lets try and get it to sync
16713 	 * any data it might have in the buffer.
16714 	 */
16715 	if (rval == 0 && rcv->cmd_attrib->chg_tape_data) {
16716 		(void) st_rcmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
16717 	}
16718 	switch (errinfo->ei_error_type) {
16719 	case ATTEMPT_RETRY:
16720 	case COMMAND_TIMEOUT:
16721 	case DEVICE_RESET:
16722 	case PATH_FAILED:
16723 		/*
16724 		 * For now if we can't talk to the device we are done.
16725 		 * If the drive is reserved we can try to get it back.
16726 		 */
16727 		if (rval != 0 && rval != EACCES) {
16728 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16729 			return;
16730 		}
16731 
16732 		/*
16733 		 * If scsi II lost reserve try and get it back.
16734 		 */
16735 		if ((((un->un_rsvd_status &
16736 		    (ST_LOST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
16737 		    ST_LOST_RESERVE)) &&
16738 		    (errinfo->ei_failed_pkt.pkt_cdbp[0] != SCMD_RELEASE)) {
16739 			rval = st_reserve_release(un, ST_RESERVE,
16740 			    st_uscsi_rcmd);
16741 			if (rval != 0) {
16742 				if (st_take_ownership(un, st_uscsi_rcmd) != 0) {
16743 					st_recov_ret(un, errinfo,
16744 					    COMMAND_DONE_EACCES);
16745 					return;
16746 				}
16747 			}
16748 			un->un_rsvd_status |= ST_RESERVE;
16749 			un->un_rsvd_status &= ~(ST_RELEASE | ST_LOST_RESERVE |
16750 			    ST_RESERVATION_CONFLICT | ST_INITIATED_RESET);
16751 		}
16752 		rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16753 		if (rval) {
16754 			rval = st_gen_mode_select(un, st_uscsi_rcmd,
16755 			    un->un_mspl, sizeof (struct seq_mode));
16756 		}
16757 		if (rval) {
16758 			st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16759 			return;
16760 		}
16761 		break;
16762 	case DEVICE_TAMPER:
16763 		/*
16764 		 * Check if the ASC/ASCQ says mode data has changed.
16765 		 */
16766 		if ((errinfo->ei_failing_status.sts_sensedata.es_add_code ==
16767 		    0x2a) &&
16768 		    (errinfo->ei_failing_status.sts_sensedata.es_qual_code ==
16769 		    0x01)) {
16770 			/*
16771 			 * See if mode sense changed.
16772 			 */
16773 			rval = st_check_mode_for_change(un, st_uscsi_rcmd);
16774 			if (rval) {
16775 				/*
16776 				 * If so change it back.
16777 				 */
16778 				rval = st_gen_mode_select(un, st_uscsi_rcmd,
16779 				    un->un_mspl, sizeof (struct seq_mode));
16780 			}
16781 			if (rval) {
16782 				st_recov_ret(un, errinfo, COMMAND_DONE_ERROR);
16783 				return;
16784 			}
16785 		}
16786 		/*
16787 		 * if we have a media id and its not bogus.
16788 		 * Check to see if it the same.
16789 		 */
16790 		if (un->un_media_id != NULL && un->un_media_id != bogusID) {
16791 			rval = st_get_media_identification(un, st_uscsi_rcmd);
16792 			if (rval == ESPIPE) {
16793 				st_recov_ret(un, errinfo, COMMAND_DONE_EACCES);
16794 				return;
16795 			}
16796 		}
16797 		break;
16798 	default:
16799 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16800 		    "Unhandled error type %s in st_recover() 0x%x\n",
16801 		    errstatenames[errinfo->ei_error_type], com);
16802 	}
16803 
16804 	/*
16805 	 * if command is retriable retry it.
16806 	 * Special case here. The command attribute for SCMD_REQUEST_SENSE
16807 	 * does not say that it is retriable. That because if you reissue a
16808 	 * request sense and the target responds the sense data will have
16809 	 * been consumed and no long be valid. If we get a busy status on
16810 	 * request sense while the state is ST_STATE_SENSING this will
16811 	 * reissue that pkt.
16812 	 *
16813 	 * XXX If this request sense gets sent to a different port then
16814 	 * the original command that failed was sent on it will not get
16815 	 * valid sense data for that command.
16816 	 */
16817 	if (rcv->cmd_attrib->retriable || un->un_rqs_bp == bp) {
16818 		status = st_recover_reissue_pkt(un, &errinfo->ei_failed_pkt);
16819 
16820 	/*
16821 	 * if drive doesn't support read position we are done
16822 	 */
16823 	} else if (un->un_read_pos_type == NO_POS) {
16824 		status = COMMAND_DONE_ERROR;
16825 	/*
16826 	 * If this command results in a changed tape position,
16827 	 * lets see where we are.
16828 	 */
16829 	} else if (rcv->cmd_attrib->chg_tape_pos) {
16830 		/*
16831 		 * XXX May be a reason to choose a different type here.
16832 		 * Long format has file position information.
16833 		 * Short and Extended have information about whats
16834 		 * in the buffer. St's positioning assumes in the buffer
16835 		 * to be the same as on tape.
16836 		 */
16837 		rval = st_compare_expected_position(un, errinfo,
16838 		    rcv->cmd_attrib, &cur_pos);
16839 		if (rval == 0) {
16840 			status = COMMAND_DONE;
16841 		} else if (rval == EAGAIN) {
16842 			status = st_recover_reissue_pkt(un,
16843 			    &errinfo->ei_failed_pkt);
16844 		} else {
16845 			status = COMMAND_DONE_ERROR;
16846 		}
16847 	} else {
16848 		ASSERT(0);
16849 	}
16850 
16851 	st_recov_ret(un, errinfo, status);
16852 }
16853 
16854 static void
16855 st_recov_cb(struct scsi_pkt *pkt)
16856 {
16857 	struct scsi_tape *un;
16858 	struct buf *bp;
16859 	recov_info *rcv;
16860 	errstate action = COMMAND_DONE_ERROR;
16861 	int timout = ST_TRAN_BUSY_TIMEOUT; /* short (default) timeout */
16862 
16863 	/*
16864 	 * Get the buf from the packet.
16865 	 */
16866 	rcv = pkt->pkt_private;
16867 	ASSERT(rcv->privatelen == sizeof (recov_info));
16868 	bp = rcv->cmd_bp;
16869 
16870 	/*
16871 	 * get the unit from the buf.
16872 	 */
16873 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
16874 	ASSERT(un != NULL);
16875 
16876 	ST_FUNC(ST_DEVINFO, st_recov_cb);
16877 
16878 	mutex_enter(ST_MUTEX);
16879 
16880 	ASSERT(bp == un->un_recov_buf);
16881 
16882 
16883 	switch (pkt->pkt_reason) {
16884 	case CMD_CMPLT:
16885 		if (un->un_arq_enabled && pkt->pkt_state & STATE_ARQ_DONE) {
16886 			action = st_handle_autosense(un, bp, &rcv->pos);
16887 		} else  if ((SCBP(pkt)->sts_busy) ||
16888 		    (SCBP(pkt)->sts_chk) ||
16889 		    (SCBP(pkt)->sts_vu7)) {
16890 			action = st_check_error(un, pkt);
16891 		} else {
16892 			action = COMMAND_DONE;
16893 		}
16894 		break;
16895 	case CMD_TIMEOUT:
16896 		action = COMMAND_TIMEOUT;
16897 		break;
16898 	case CMD_TRAN_ERR:
16899 		action = QUE_COMMAND;
16900 		break;
16901 	default:
16902 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16903 		    "pkt_reason not handled yet %s",
16904 		    scsi_rname(pkt->pkt_reason));
16905 		action = COMMAND_DONE_ERROR;
16906 	}
16907 
16908 	/*
16909 	 * check for undetected path failover.
16910 	 */
16911 	if ((un->un_multipath) &&
16912 	    (un->un_last_path_instance != pkt->pkt_path_instance)) {
16913 		if (un->un_state > ST_STATE_OPENING) {
16914 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
16915 			    "Failover detected in recovery, action is %s\n",
16916 			    errstatenames[action]);
16917 		}
16918 		un->un_last_path_instance = pkt->pkt_path_instance;
16919 	}
16920 
16921 	ST_RECOV(ST_DEVINFO, st_label, CE_WARN,
16922 	    "Recovery call back got %s status on %s\n",
16923 	    errstatenames[action], st_print_scsi_cmd(pkt->pkt_cdbp[0]));
16924 
16925 	switch (action) {
16926 	case COMMAND_DONE:
16927 		break;
16928 
16929 	case COMMAND_DONE_EACCES:
16930 		bioerror(bp, EACCES);
16931 		break;
16932 
16933 	case COMMAND_DONE_ERROR_RECOVERED: /* XXX maybe wrong */
16934 		ASSERT(0);
16935 		break;
16936 
16937 	case COMMAND_TIMEOUT:
16938 	case COMMAND_DONE_ERROR:
16939 		bioerror(bp, EIO);
16940 		break;
16941 
16942 	case DEVICE_RESET:
16943 	case QUE_BUSY_COMMAND:
16944 	case PATH_FAILED:
16945 		/* longish timeout */
16946 		timout = ST_STATUS_BUSY_TIMEOUT;
16947 		/* FALLTHRU */
16948 	case QUE_COMMAND:
16949 	case DEVICE_TAMPER:
16950 	case ATTEMPT_RETRY:
16951 		/*
16952 		 * let st_handle_intr_busy put this bp back on waitq and make
16953 		 * checks to see if it is ok to requeue the command.
16954 		 */
16955 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
16956 
16957 		/*
16958 		 * Save the throttle before setting up the timeout
16959 		 */
16960 		if (un->un_throttle) {
16961 			un->un_last_throttle = un->un_throttle;
16962 		}
16963 		mutex_exit(ST_MUTEX);
16964 		if (st_handle_intr_busy(un, bp, timout) == 0) {
16965 			return;		/* timeout is setup again */
16966 		}
16967 		mutex_enter(ST_MUTEX);
16968 		un->un_pos.pmode = invalid;
16969 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16970 		st_bioerror(bp, EIO);
16971 		st_set_pe_flag(un);
16972 		break;
16973 
16974 	default:
16975 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
16976 		    "Unhandled recovery state 0x%x\n", action);
16977 		un->un_pos.pmode = invalid;
16978 		un->un_err_resid = bp->b_resid = bp->b_bcount;
16979 		st_bioerror(bp, EIO);
16980 		st_set_pe_flag(un);
16981 		break;
16982 	}
16983 
16984 	st_done_and_mutex_exit(un, bp);
16985 }
16986 
16987 static int
16988 st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait)
16989 {
16990 	struct buf *bp;
16991 	int err;
16992 
16993 	ST_FUNC(ST_DEVINFO, st_rcmd);
16994 
16995 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
16996 	    "st_rcmd(un = 0x%p, com = 0x%x, count = %"PRIx64", wait = %d)\n",
16997 	    (void *)un, com, count, wait);
16998 
16999 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
17000 	ASSERT(mutex_owned(ST_MUTEX));
17001 
17002 #ifdef STDEBUG
17003 	if ((st_debug & 0x7)) {
17004 		st_debug_cmds(un, com, count, wait);
17005 	}
17006 #endif
17007 
17008 	while (un->un_recov_buf_busy)
17009 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17010 	un->un_recov_buf_busy = 1;
17011 
17012 	bp = un->un_recov_buf;
17013 	bzero(bp, sizeof (buf_t));
17014 
17015 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
17016 
17017 	err = st_setup_cmd(un, bp, com, count);
17018 
17019 	un->un_recov_buf_busy = 0;
17020 
17021 	cv_signal(&un->un_recov_buf_cv);
17022 
17023 	return (err);
17024 }
17025 
17026 /* args used */
17027 static int
17028 st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
17029 {
17030 	int rval;
17031 	buf_t *bp;
17032 
17033 	ST_FUNC(ST_DEVINFO, st_uscsi_rcmd);
17034 	ASSERT(flag == FKIOCTL);
17035 
17036 	/*
17037 	 * Get buffer resources...
17038 	 */
17039 	while (un->un_recov_buf_busy)
17040 		cv_wait(&un->un_recov_buf_cv, ST_MUTEX);
17041 	un->un_recov_buf_busy = 1;
17042 
17043 	bp = un->un_recov_buf;
17044 	bzero(bp, sizeof (buf_t));
17045 
17046 	bp->b_forw = (struct buf *)(uintptr_t)ucmd->uscsi_cdb[0];
17047 	bp->b_back = (struct buf *)ucmd;
17048 
17049 	mutex_exit(ST_MUTEX);
17050 	rval = scsi_uscsi_handle_cmd(un->un_dev, UIO_SYSSPACE, ucmd,
17051 	    st_strategy, bp, NULL);
17052 	mutex_enter(ST_MUTEX);
17053 
17054 	ucmd->uscsi_resid = bp->b_resid;
17055 
17056 	/*
17057 	 * Free resources
17058 	 */
17059 	un->un_recov_buf_busy = 0;
17060 	cv_signal(&un->un_recov_buf_cv);
17061 
17062 	return (rval);
17063 }
17064 
17065 /*
17066  * Add data to scsi_pkt to help know what to do if the command fails.
17067  */
17068 static void
17069 st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
17070     struct scsi_pkt *pkt)
17071 {
17072 	uint64_t count;
17073 	recov_info *rinfo = (recov_info *)pkt->pkt_private;
17074 
17075 	ST_FUNC(ST_DEVINFO, st_add_recovery_info_to_pkt);
17076 
17077 	ASSERT(rinfo->privatelen == sizeof (pkt_info) ||
17078 	    rinfo->privatelen == sizeof (recov_info));
17079 
17080 	SET_BP_PKT(bp, pkt);
17081 	rinfo->cmd_bp = bp;
17082 
17083 	if (rinfo->privatelen != sizeof (recov_info)) {
17084 		return;
17085 	}
17086 
17087 	rinfo->cmd_bp = bp;
17088 
17089 	rinfo->cmd_attrib = NULL;
17090 
17091 	/*
17092 	 * lookup the command attributes and add them to the recovery info.
17093 	 */
17094 	rinfo->cmd_attrib = st_lookup_cmd_attribute(pkt->pkt_cdbp[0]);
17095 
17096 	ASSERT(rinfo->cmd_attrib);
17097 
17098 	/*
17099 	 * For commands that there is no way to figure the expected position
17100 	 * once completed, we save the position the command was started from
17101 	 * so that if they fail we can position back and try again.
17102 	 * This has already been done in st_cmd() or st_iscsi_cmd().
17103 	 */
17104 	if (rinfo->cmd_attrib->recov_pos_type == POS_STARTING) {
17105 		/* save current position as the starting position. */
17106 		COPY_POS(&rinfo->pos, &un->un_pos);
17107 		un->un_running.pmode = invalid;
17108 		return;
17109 	}
17110 
17111 	/*
17112 	 * Don't want to update the running position for recovery.
17113 	 */
17114 	if (bp == un->un_recov_buf) {
17115 		rinfo->pos.pmode = un->un_running.pmode;
17116 		return;
17117 	}
17118 	/*
17119 	 * If running position is invalid copy the current position.
17120 	 * Running being set invalid means we are not in a read, write
17121 	 * or write filemark sequence.
17122 	 * We'll copy the current position and start from there.
17123 	 */
17124 	if (un->un_running.pmode == invalid) {
17125 		COPY_POS(&un->un_running, &un->un_pos);
17126 		COPY_POS(&rinfo->pos, &un->un_running);
17127 	} else {
17128 		COPY_POS(&rinfo->pos, &un->un_running);
17129 		if (rinfo->pos.pmode == legacy) {
17130 			/*
17131 			 * Always should be more logical blocks then
17132 			 * data blocks and files marks.
17133 			 */
17134 			ASSERT((rinfo->pos.blkno >= 0) ?
17135 			    rinfo->pos.lgclblkno >=
17136 			    (rinfo->pos.blkno + rinfo->pos.fileno) : 1);
17137 		}
17138 	}
17139 
17140 	/*
17141 	 * If the command is not expected to change the drive position
17142 	 * then the running position should be the expected position.
17143 	 */
17144 	if (rinfo->cmd_attrib->chg_tape_pos == 0) {
17145 		ASSERT(rinfo->cmd_attrib->chg_tape_direction == DIR_NONE);
17146 		return;
17147 	}
17148 
17149 	if (rinfo->cmd_attrib->explicit) {
17150 		ASSERT(rinfo->pos.pmode != invalid);
17151 		ASSERT(rinfo->cmd_attrib->get_cnt);
17152 		count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17153 		/*
17154 		 * This is a user generated CDB.
17155 		 */
17156 		if (bp == un->un_sbufp) {
17157 			uint64_t lbn;
17158 
17159 			lbn = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17160 
17161 			/*
17162 			 * See if this CDB will generate a locate or change
17163 			 * partition.
17164 			 */
17165 			if ((lbn != un->un_running.lgclblkno) ||
17166 			    (pkt->pkt_cdbp[3] != un->un_running.partition)) {
17167 				rinfo->pos.partition = pkt->pkt_cdbp[3];
17168 				rinfo->pos.pmode = logical;
17169 				rinfo->pos.lgclblkno = lbn;
17170 				un->un_running.partition = pkt->pkt_cdbp[3];
17171 				un->un_running.pmode = logical;
17172 				un->un_running.lgclblkno = lbn;
17173 			}
17174 		} else {
17175 			uint64_t lbn = un->un_running.lgclblkno;
17176 
17177 			pkt->pkt_cdbp[3]  = (uchar_t)un->un_running.partition;
17178 
17179 			pkt->pkt_cdbp[4]  = (uchar_t)(lbn >> 56);
17180 			pkt->pkt_cdbp[5]  = (uchar_t)(lbn >> 48);
17181 			pkt->pkt_cdbp[6]  = (uchar_t)(lbn >> 40);
17182 			pkt->pkt_cdbp[7]  = (uchar_t)(lbn >> 32);
17183 			pkt->pkt_cdbp[8]  = (uchar_t)(lbn >> 24);
17184 			pkt->pkt_cdbp[9]  = (uchar_t)(lbn >> 16);
17185 			pkt->pkt_cdbp[10] = (uchar_t)(lbn >> 8);
17186 			pkt->pkt_cdbp[11] = (uchar_t)(lbn);
17187 		}
17188 		rinfo->pos.lgclblkno += count;
17189 		rinfo->pos.blkno += count;
17190 		un->un_running.lgclblkno += count;
17191 		return;
17192 	}
17193 
17194 	if (rinfo->cmd_attrib->chg_tape_pos) {
17195 
17196 		/* should not have got an invalid position from running. */
17197 		if (un->un_mediastate == MTIO_INSERTED) {
17198 			ASSERT(rinfo->pos.pmode != invalid);
17199 		}
17200 
17201 		/* should have either a get count or or get lba function */
17202 		ASSERT(rinfo->cmd_attrib->get_cnt != NULL ||
17203 		    rinfo->cmd_attrib->get_lba != NULL);
17204 
17205 		/* only explicit commands have both and they're handled above */
17206 		ASSERT(!(rinfo->cmd_attrib->get_cnt != NULL &&
17207 		    rinfo->cmd_attrib->get_lba != NULL));
17208 
17209 		/* if it has a get count function */
17210 		if (rinfo->cmd_attrib->get_cnt != NULL) {
17211 			count = rinfo->cmd_attrib->get_cnt(pkt->pkt_cdbp);
17212 			if (count == 0) {
17213 				return;
17214 			}
17215 			/*
17216 			 * Changes position but doesn't transfer data.
17217 			 * i.e. rewind, write_file_mark and load.
17218 			 */
17219 			if (rinfo->cmd_attrib->transfers_data == TRAN_NONE) {
17220 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17221 				case DIR_NONE: /* Erase */
17222 					ASSERT(rinfo->cmd_attrib->cmd ==
17223 					    SCMD_ERASE);
17224 					break;
17225 				case DIR_FORW: /* write_file_mark */
17226 					rinfo->pos.fileno += count;
17227 					rinfo->pos.lgclblkno += count;
17228 					rinfo->pos.blkno = 0;
17229 					un->un_running.fileno += count;
17230 					un->un_running.lgclblkno += count;
17231 					un->un_running.blkno = 0;
17232 					break;
17233 				case DIR_REVC: /* rewind */
17234 					rinfo->pos.fileno = 0;
17235 					rinfo->pos.lgclblkno = 0;
17236 					rinfo->pos.blkno = 0;
17237 					rinfo->pos.eof = ST_NO_EOF;
17238 					rinfo->pos.pmode = legacy;
17239 					un->un_running.fileno = 0;
17240 					un->un_running.lgclblkno = 0;
17241 					un->un_running.blkno = 0;
17242 					un->un_running.eof = ST_NO_EOF;
17243 					if (un->un_running.pmode != legacy)
17244 						un->un_running.pmode = legacy;
17245 					break;
17246 				case DIR_EITH: /* Load unload */
17247 					ASSERT(rinfo->cmd_attrib->cmd ==
17248 					    SCMD_LOAD);
17249 					switch (count & (LD_LOAD | LD_RETEN |
17250 					    LD_RETEN | LD_HOLD)) {
17251 					case LD_UNLOAD:
17252 					case LD_RETEN:
17253 					case LD_HOLD:
17254 					case LD_LOAD | LD_HOLD:
17255 					case LD_EOT | LD_HOLD:
17256 					case LD_RETEN | LD_HOLD:
17257 						rinfo->pos.pmode = invalid;
17258 						un->un_running.pmode = invalid;
17259 						break;
17260 					case LD_EOT:
17261 					case LD_LOAD | LD_EOT:
17262 						rinfo->pos.eof = ST_EOT;
17263 						rinfo->pos.pmode = invalid;
17264 						un->un_running.eof = ST_EOT;
17265 						un->un_running.pmode = invalid;
17266 						break;
17267 					case LD_LOAD:
17268 					case LD_RETEN | LD_LOAD:
17269 						rinfo->pos.fileno = 0;
17270 						rinfo->pos.lgclblkno = 0;
17271 						rinfo->pos.blkno = 0;
17272 						rinfo->pos.eof = ST_NO_EOF;
17273 						rinfo->pos.pmode = legacy;
17274 						un->un_running.fileno = 0;
17275 						un->un_running.lgclblkno = 0;
17276 						un->un_running.blkno = 0;
17277 						un->un_running.eof = ST_NO_EOF;
17278 						break;
17279 					default:
17280 						ASSERT(0);
17281 					}
17282 					break;
17283 				default:
17284 					ASSERT(0);
17285 					break;
17286 				}
17287 			} else {
17288 				/*
17289 				 * Changes position and does transfer data.
17290 				 * i.e. read or write.
17291 				 */
17292 				switch (rinfo->cmd_attrib->chg_tape_direction) {
17293 				case DIR_FORW:
17294 					rinfo->pos.lgclblkno += count;
17295 					rinfo->pos.blkno += count;
17296 					un->un_running.lgclblkno += count;
17297 					un->un_running.blkno += count;
17298 					break;
17299 				case DIR_REVC:
17300 					rinfo->pos.lgclblkno -= count;
17301 					rinfo->pos.blkno -= count;
17302 					un->un_running.lgclblkno -= count;
17303 					un->un_running.blkno -= count;
17304 					break;
17305 				default:
17306 					ASSERT(0);
17307 					break;
17308 				}
17309 			}
17310 		} else if (rinfo->cmd_attrib->get_lba != NULL) {
17311 			/* Have a get LBA fuction. i.e. Locate */
17312 			ASSERT(rinfo->cmd_attrib->chg_tape_direction ==
17313 			    DIR_EITH);
17314 			count = rinfo->cmd_attrib->get_lba(pkt->pkt_cdbp);
17315 			un->un_running.lgclblkno = count;
17316 			un->un_running.blkno = 0;
17317 			un->un_running.fileno = 0;
17318 			un->un_running.pmode = logical;
17319 			rinfo->pos.lgclblkno = count;
17320 			rinfo->pos.pmode = invalid;
17321 		} else {
17322 			ASSERT(0);
17323 		}
17324 		return;
17325 	}
17326 
17327 	ST_CDB(ST_DEVINFO, "Unhanded CDB for position prediction",
17328 	    (char *)pkt->pkt_cdbp);
17329 
17330 }
17331 
17332 static int
17333 st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf)
17334 {
17335 	struct seq_mode *current;
17336 	int rval;
17337 	int i;
17338 	caddr_t this;
17339 	caddr_t that;
17340 
17341 	ST_FUNC(ST_DEVINFO, st_check_mode_for_change);
17342 
17343 	/* recovery called with mode tamper before mode selection */
17344 	if (un->un_comp_page == (ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE)) {
17345 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17346 		    "Mode Select not done yet");
17347 		return (0);
17348 	}
17349 
17350 	current = kmem_zalloc(sizeof (struct seq_mode), KM_SLEEP);
17351 
17352 	rval = st_gen_mode_sense(un, ubf, un->un_comp_page, current,
17353 	    sizeof (struct seq_mode));
17354 	if (rval != 0) {
17355 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17356 		    "Mode Sense for mode verification failed");
17357 		kmem_free(current, sizeof (struct seq_mode));
17358 		return (rval);
17359 	}
17360 
17361 	this = (caddr_t)current;
17362 	that = (caddr_t)un->un_mspl;
17363 
17364 	rval = bcmp(this, that, sizeof (struct seq_mode));
17365 	if (rval == 0) {
17366 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17367 		    "Found no changes in mode data");
17368 	}
17369 #ifdef STDEBUG
17370 	else {
17371 		for (i = 1; i < sizeof (struct seq_mode); i++) {
17372 			if (this[i] != that[i]) {
17373 				ST_RECOV(ST_DEVINFO, st_label, CE_CONT,
17374 				    "sense data changed at byte %d was "
17375 				    "0x%x now 0x%x", i,
17376 				    (uchar_t)that[i], (uchar_t)this[i]);
17377 			}
17378 		}
17379 	}
17380 #endif
17381 	kmem_free(current, sizeof (struct seq_mode));
17382 
17383 	return (rval);
17384 }
17385 
17386 static int
17387 st_test_path_to_device(struct scsi_tape *un)
17388 {
17389 	int rval = 0;
17390 	int limit = st_retry_count;
17391 
17392 	ST_FUNC(ST_DEVINFO, st_test_path_to_device);
17393 
17394 	/*
17395 	 * XXX Newer drives may not RESEVATION CONFLICT a TUR.
17396 	 */
17397 	do {
17398 		if (rval != 0) {
17399 			mutex_exit(ST_MUTEX);
17400 			delay(drv_usectohz(1000000));
17401 			mutex_enter(ST_MUTEX);
17402 		}
17403 		rval = st_rcmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
17404 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17405 		    "ping TUR returned 0x%x", rval);
17406 		limit--;
17407 	} while (((rval == EACCES) || (rval == EBUSY)) && limit);
17408 
17409 	if (un->un_status == KEY_NOT_READY || un->un_mediastate == MTIO_EJECTED)
17410 		rval = 0;
17411 
17412 	return (rval);
17413 }
17414 
17415 /*
17416  * Does read position using recov_buf and doesn't update un_pos.
17417  * Does what ever kind of read position you want.
17418  */
17419 static int
17420 st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
17421     read_pos_data_t *raw)
17422 {
17423 	int rval;
17424 	struct uscsi_cmd cmd;
17425 	struct scsi_arq_status status;
17426 	char cdb[CDB_GROUP1];
17427 
17428 	ST_FUNC(ST_DEVINFO, st_recovery_read_pos);
17429 	bzero(&cmd, sizeof (cmd));
17430 
17431 	cdb[0] = SCMD_READ_POSITION;
17432 	cdb[1] = type;
17433 	cdb[2] = 0;
17434 	cdb[3] = 0;
17435 	cdb[4] = 0;
17436 	cdb[5] = 0;
17437 	cdb[6] = 0;
17438 	cdb[7] = 0;
17439 	cdb[8] = (type == EXT_POS) ? 28 : 0;
17440 	cdb[9] = 0;
17441 
17442 	cmd.uscsi_flags = USCSI_READ | USCSI_RQENABLE;
17443 	cmd.uscsi_timeout = un->un_dp->non_motion_timeout;
17444 	cmd.uscsi_cdb = cdb;
17445 	cmd.uscsi_cdblen = sizeof (cdb);
17446 	cmd.uscsi_rqlen = sizeof (status);
17447 	cmd.uscsi_rqbuf = (caddr_t)&status;
17448 	cmd.uscsi_bufaddr = (caddr_t)raw;
17449 	switch (type) {
17450 	case SHORT_POS:
17451 		cmd.uscsi_buflen = sizeof (tape_position_t);
17452 		break;
17453 	case LONG_POS:
17454 		cmd.uscsi_buflen = sizeof (tape_position_long_t);
17455 		break;
17456 	case EXT_POS:
17457 		cmd.uscsi_buflen = sizeof (tape_position_ext_t);
17458 		break;
17459 	default:
17460 		ASSERT(0);
17461 	}
17462 
17463 	rval = st_uscsi_rcmd(un, &cmd, FKIOCTL);
17464 	if (cmd.uscsi_status) {
17465 		rval = EIO;
17466 	}
17467 	return (rval);
17468 }
17469 
17470 static int
17471 st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
17472     read_pos_data_t *raw)
17473 {
17474 	int rval;
17475 	read_p_types type = un->un_read_pos_type;
17476 
17477 	ST_FUNC(ST_DEVINFO, st_recovery_get_position);
17478 
17479 	do {
17480 		rval = st_recovery_read_pos(un, type, raw);
17481 		if (rval != 0) {
17482 			switch (type) {
17483 			case SHORT_POS:
17484 				type = NO_POS;
17485 				break;
17486 
17487 			case LONG_POS:
17488 				type = EXT_POS;
17489 				break;
17490 
17491 			case EXT_POS:
17492 				type = SHORT_POS;
17493 				break;
17494 
17495 			default:
17496 				type = LONG_POS;
17497 				break;
17498 
17499 			}
17500 		} else {
17501 			if (type != un->un_read_pos_type) {
17502 				un->un_read_pos_type = type;
17503 			}
17504 			break;
17505 		}
17506 	} while (type != NO_POS);
17507 
17508 	if (rval == 0) {
17509 		rval = st_interpret_read_pos(un, read, type,
17510 		    sizeof (read_pos_data_t), (caddr_t)raw, 1);
17511 	}
17512 	return (rval);
17513 }
17514 
17515 /*
17516  * based on the command do we retry, continue or give up?
17517  * possable return values?
17518  *	zero do nothing looks fine.
17519  *	EAGAIN retry.
17520  *	EIO failed makes no sense.
17521  */
17522 static int
17523 st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
17524     cmd_attribute const * cmd_att, tapepos_t *read)
17525 {
17526 	int rval;
17527 	read_pos_data_t *readp_datap;
17528 
17529 	ST_FUNC(ST_DEVINFO, st_compare_expected_position);
17530 
17531 	ASSERT(un != NULL);
17532 	ASSERT(ei != NULL);
17533 	ASSERT(read != NULL);
17534 	ASSERT(cmd_att->chg_tape_pos);
17535 
17536 	COPY_POS(read, &ei->ei_expected_pos);
17537 
17538 	readp_datap = kmem_zalloc(sizeof (read_pos_data_t), KM_SLEEP);
17539 
17540 	rval = st_recovery_get_position(un, read, readp_datap);
17541 
17542 	kmem_free(readp_datap, sizeof (read_pos_data_t));
17543 
17544 	if (rval != 0) {
17545 		return (EIO);
17546 	}
17547 
17548 	ST_POS(ST_DEVINFO, "st_compare_expected_position", read);
17549 
17550 	if ((read->pmode == invalid) ||
17551 	    (ei->ei_expected_pos.pmode == invalid)) {
17552 		return (EIO);
17553 	}
17554 
17555 	/*
17556 	 * Command that changes tape position and have an expected position
17557 	 * if it were to chave completed sucessfully.
17558 	 */
17559 	if (cmd_att->recov_pos_type == POS_EXPECTED) {
17560 		uint32_t count;
17561 		int64_t difference;
17562 		uchar_t reposition = 0;
17563 
17564 		ASSERT(cmd_att->get_cnt);
17565 		count = cmd_att->get_cnt(ei->ei_failed_pkt.pkt_cdbp);
17566 
17567 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17568 		    "Got count from CDB and it was %d\n", count);
17569 
17570 		/*
17571 		 * At expected?
17572 		 */
17573 		if (read->lgclblkno == ei->ei_expected_pos.lgclblkno) {
17574 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17575 			    "Found drive to be at expected position\n");
17576 
17577 			/*
17578 			 * If the command should move tape and it got a busy
17579 			 * it shouldn't be in the expected position.
17580 			 */
17581 			if (ei->ei_failing_status.sts_status.sts_busy != 0) {
17582 				reposition = 1;
17583 
17584 			/*
17585 			 * If the command doesn't transfer data should be good.
17586 			 */
17587 			} else if (cmd_att->transfers_data == TRAN_NONE) {
17588 				return (0); /* Good */
17589 
17590 			/*
17591 			 * Command transfers data, should have done so.
17592 			 */
17593 			} else if (ei->ei_failed_pkt.pkt_state &
17594 			    STATE_XFERRED_DATA) {
17595 				return (0); /* Good */
17596 			} else {
17597 				reposition = 1;
17598 			}
17599 		}
17600 
17601 		if (cmd_att->chg_tape_direction == DIR_FORW) {
17602 			difference =
17603 			    ei->ei_expected_pos.lgclblkno - read->lgclblkno;
17604 
17605 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17606 			    "difference between expected and actual is %"
17607 			    PRId64"\n", difference);
17608 			if (count == difference && reposition == 0) {
17609 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17610 				    "Found failed FORW command, retrying\n");
17611 				return (EAGAIN);
17612 			}
17613 
17614 			/*
17615 			 * If rewound or somewhere between the starting position
17616 			 * and the expected position (partial read or write).
17617 			 * Locate to the starting position and try the whole
17618 			 * thing over again.
17619 			 */
17620 			if ((read->lgclblkno == 0) ||
17621 			    ((difference > 0) && (difference < count))) {
17622 				rval = st_logical_block_locate(un,
17623 				    st_uscsi_rcmd, read,
17624 				    ei->ei_expected_pos.lgclblkno - count,
17625 				    ei->ei_expected_pos.partition);
17626 				if (rval == 0) {
17627 					ST_RECOV(ST_DEVINFO, st_label,
17628 					    CE_NOTE, "reestablished FORW"
17629 					    " command retrying\n");
17630 					return (EAGAIN);
17631 				}
17632 			/*
17633 			 * This handles flushed read ahead on the drive or
17634 			 * an aborted read that presents as a busy and advanced
17635 			 * the tape position.
17636 			 */
17637 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17638 			    ((difference < 0) || (reposition == 1))) {
17639 				rval = st_logical_block_locate(un,
17640 				    st_uscsi_rcmd, read,
17641 				    ei->ei_expected_pos.lgclblkno - count,
17642 				    ei->ei_expected_pos.partition);
17643 				if (rval == 0) {
17644 					ST_RECOV(ST_DEVINFO, st_label,
17645 					    CE_NOTE, "reestablished FORW"
17646 					    " read command retrying\n");
17647 					return (EAGAIN);
17648 				}
17649 			/*
17650 			 * XXX swag seeing difference of 2 on write filemark.
17651 			 * If the space to the starting position works on a
17652 			 * write that means the previous write made it to tape.
17653 			 * If not we lost data and have to give up.
17654 			 *
17655 			 * The plot thickens. Now I am attempting to cover a
17656 			 * count of 1 and a differance of 2 on a write.
17657 			 */
17658 			} else if ((difference > count) || (reposition == 1)) {
17659 				rval = st_logical_block_locate(un,
17660 				    st_uscsi_rcmd, read,
17661 				    ei->ei_expected_pos.lgclblkno - count,
17662 				    ei->ei_expected_pos.partition);
17663 				if (rval == 0) {
17664 					ST_RECOV(ST_DEVINFO, st_label,
17665 					    CE_NOTE, "reestablished FORW"
17666 					    " write command retrying\n");
17667 					return (EAGAIN);
17668 				}
17669 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17670 				    "Seek to block %"PRId64" returned %d\n",
17671 				    ei->ei_expected_pos.lgclblkno - count,
17672 				    rval);
17673 			} else {
17674 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17675 				    "Not expected transfers_data = %d "
17676 				    "difference = %"PRId64,
17677 				    cmd_att->transfers_data, difference);
17678 			}
17679 
17680 			return (EIO);
17681 
17682 		} else if (cmd_att->chg_tape_direction == DIR_REVC) {
17683 			/* Don't think we can write backwards */
17684 			ASSERT(cmd_att->transfers_data != TRAN_WRTE);
17685 			difference =
17686 			    read->lgclblkno - ei->ei_expected_pos.lgclblkno;
17687 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17688 			    "difference between expected and actual is %"
17689 			    PRId64"\n", difference);
17690 			if (count == difference && reposition == 0) {
17691 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17692 				    "Found failed REVC command, retrying\n");
17693 				return (EAGAIN);
17694 			}
17695 			if ((read->lgclblkno == 0) ||
17696 			    ((difference > 0) && (difference < count))) {
17697 				rval = st_logical_block_locate(un,
17698 				    st_uscsi_rcmd, read,
17699 				    ei->ei_expected_pos.lgclblkno + count,
17700 				    ei->ei_expected_pos.partition);
17701 				if (rval == 0) {
17702 					ST_RECOV(ST_DEVINFO, st_label,
17703 					    CE_NOTE, "reestablished REVC"
17704 					    " command retrying\n");
17705 					return (EAGAIN);
17706 				}
17707 			/* This handles read ahead in reverse direction */
17708 			} else if ((cmd_att->transfers_data == TRAN_READ) &&
17709 			    (difference < 0) || (reposition == 1)) {
17710 				rval = st_logical_block_locate(un,
17711 				    st_uscsi_rcmd, read,
17712 				    ei->ei_expected_pos.lgclblkno - count,
17713 				    ei->ei_expected_pos.partition);
17714 				if (rval == 0) {
17715 					ST_RECOV(ST_DEVINFO, st_label,
17716 					    CE_NOTE, "reestablished REVC"
17717 					    " read command retrying\n");
17718 					return (EAGAIN);
17719 				}
17720 			} else {
17721 				ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17722 				    "Not expected transfers_data = %d "
17723 				    "difference = %"PRId64,
17724 				    cmd_att->transfers_data, difference);
17725 			}
17726 			return (EIO);
17727 
17728 		} else {
17729 			/*
17730 			 * Commands that change tape position either
17731 			 * direction or don't change position should not
17732 			 * get here.
17733 			 */
17734 			ASSERT(0);
17735 		}
17736 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17737 		    "Didn't find a recoverable position, Failing\n");
17738 
17739 	/*
17740 	 * Command that changes tape position and can only be recovered
17741 	 * by going back to the point of origin and retrying.
17742 	 *
17743 	 * Example SCMD_SPACE.
17744 	 */
17745 	} else if (cmd_att->recov_pos_type == POS_STARTING) {
17746 		/*
17747 		 * This type of command stores the starting position.
17748 		 * If the read position is the starting position,
17749 		 * reissue the command.
17750 		 */
17751 		if (ei->ei_expected_pos.lgclblkno == read->lgclblkno) {
17752 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17753 			    "Found Space command at starting position, "
17754 			    "Reissuing\n");
17755 			return (EAGAIN);
17756 		}
17757 		/*
17758 		 * Not in the position that the command was originally issued,
17759 		 * Attempt to locate to that position.
17760 		 */
17761 		rval = st_logical_block_locate(un, st_uscsi_rcmd, read,
17762 		    ei->ei_expected_pos.lgclblkno,
17763 		    ei->ei_expected_pos.partition);
17764 		if (rval) {
17765 			ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17766 			    "Found Space at an unexpected position and locate "
17767 			    "back to starting position failed\n");
17768 			return (EIO);
17769 		}
17770 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17771 		    "Found Space at an unexpected position and locate "
17772 		    "back to starting position worked, Reissuing\n");
17773 		return (EAGAIN);
17774 	}
17775 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17776 	    "Unhandled attribute/expected position", &ei->ei_expected_pos);
17777 	st_print_position(ST_DEVINFO, st_label, CE_NOTE,
17778 	    "Read position above did not make sense", read);
17779 	ASSERT(0);
17780 	return (EIO);
17781 }
17782 
17783 static errstate
17784 st_recover_reissue_pkt(struct scsi_tape *un, struct scsi_pkt *oldpkt)
17785 {
17786 	buf_t *bp;
17787 	buf_t *pkt_bp;
17788 	struct scsi_pkt *newpkt;
17789 	cmd_attribute const *attrib;
17790 	recov_info *rcv = oldpkt->pkt_private;
17791 	uint_t cdblen;
17792 	int queued = 0;
17793 	int rval;
17794 	int flags = 0;
17795 	int stat_size =
17796 	    (un->un_arq_enabled ? sizeof (struct scsi_arq_status) : 1);
17797 
17798 	ST_FUNC(ST_DEVINFO, st_recover_reissue_pkt);
17799 
17800 	bp = rcv->cmd_bp;
17801 
17802 	if (rcv->privatelen == sizeof (recov_info)) {
17803 		attrib = rcv->cmd_attrib;
17804 	} else {
17805 		attrib = st_lookup_cmd_attribute(oldpkt->pkt_cdbp[0]);
17806 	}
17807 
17808 	/*
17809 	 * Some non-uscsi commands use the b_bcount for values that
17810 	 * have nothing to do with how much data is transfered.
17811 	 * In those cases we need to hide the buf_t from scsi_init_pkt().
17812 	 */
17813 	if ((BP_UCMD(bp)) && (bp->b_bcount)) {
17814 		pkt_bp = bp;
17815 	} else if (attrib->transfers_data == TRAN_NONE) {
17816 		pkt_bp = NULL;
17817 	} else {
17818 		pkt_bp = bp;
17819 	}
17820 
17821 	/*
17822 	 * if this is a queued command make sure it the only one in the
17823 	 * run queue.
17824 	 */
17825 	if (bp != un->un_sbufp && bp != un->un_recov_buf) {
17826 		ASSERT(un->un_runqf == un->un_runql);
17827 		ASSERT(un->un_runqf == bp);
17828 		queued = 1;
17829 	}
17830 
17831 	cdblen = scsi_cdb_size[CDB_GROUPID(oldpkt->pkt_cdbp[0])];
17832 
17833 	if (pkt_bp == un->un_rqs_bp) {
17834 		flags |= PKT_CONSISTENT;
17835 		stat_size = 1;
17836 	}
17837 
17838 	newpkt = scsi_init_pkt(ROUTE, NULL, pkt_bp, cdblen,
17839 	    stat_size, rcv->privatelen, flags, NULL_FUNC, NULL);
17840 	if (newpkt == NULL) {
17841 		ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17842 		    "Reissue pkt scsi_init_pkt() failure\n");
17843 		return (COMMAND_DONE_ERROR);
17844 	}
17845 
17846 	ASSERT(newpkt->pkt_resid == 0);
17847 	bp->b_flags &= ~(B_DONE);
17848 	bp->b_resid = 0;
17849 	st_bioerror(bp, 0);
17850 
17851 	bcopy(oldpkt->pkt_private, newpkt->pkt_private, rcv->privatelen);
17852 
17853 	newpkt->pkt_comp = oldpkt->pkt_comp;
17854 	newpkt->pkt_time = oldpkt->pkt_time;
17855 
17856 	bzero(newpkt->pkt_scbp, stat_size);
17857 	bcopy(oldpkt->pkt_cdbp, newpkt->pkt_cdbp, cdblen);
17858 
17859 	newpkt->pkt_state = 0;
17860 	newpkt->pkt_statistics = 0;
17861 
17862 	/*
17863 	 * oldpkt passed in was a copy of the original.
17864 	 * to distroy we need the address of the original.
17865 	 */
17866 	oldpkt = BP_PKT(bp);
17867 
17868 	if (oldpkt == un->un_rqs) {
17869 		ASSERT(bp == un->un_rqs_bp);
17870 		un->un_rqs = newpkt;
17871 	}
17872 
17873 	SET_BP_PKT(bp, newpkt);
17874 
17875 	scsi_destroy_pkt(oldpkt);
17876 
17877 	rval = st_transport(un, newpkt);
17878 	if (rval == TRAN_ACCEPT) {
17879 		return (JUST_RETURN);
17880 	}
17881 	ST_RECOV(ST_DEVINFO, st_label, CE_NOTE,
17882 	    "Reissue pkt st_transport(0x%x) failure\n", rval);
17883 	if (rval != TRAN_BUSY) {
17884 		return (COMMAND_DONE_ERROR);
17885 	}
17886 	mutex_exit(ST_MUTEX);
17887 	rval = st_handle_start_busy(un, bp, ST_TRAN_BUSY_TIMEOUT, queued);
17888 	mutex_enter(ST_MUTEX);
17889 	if (rval) {
17890 		return (COMMAND_DONE_ERROR);
17891 	}
17892 
17893 	return (JUST_RETURN);
17894 }
17895 
17896 static int
17897 st_transport(struct scsi_tape *un, struct scsi_pkt *pkt)
17898 {
17899 	int status;
17900 
17901 	ST_FUNC(ST_DEVINFO, st_transport);
17902 
17903 	ST_CDB(ST_DEVINFO, "transport CDB", (caddr_t)pkt->pkt_cdbp);
17904 
17905 	mutex_exit(ST_MUTEX);
17906 
17907 	status = scsi_transport(pkt);
17908 
17909 	mutex_enter(ST_MUTEX);
17910 
17911 	return (status);
17912 }
17913 
17914 /*
17915  * Removed the buf_t bp from the queue referenced to by head and tail.
17916  * Returns the buf_t pointer if it is found in the queue.
17917  * Returns NULL if it is not found.
17918  */
17919 static buf_t *
17920 st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp)
17921 {
17922 	buf_t *runqbp;
17923 	buf_t *prevbp = NULL;
17924 
17925 	for (runqbp = *head; runqbp != 0; runqbp = runqbp->av_forw) {
17926 		if (runqbp == bp) {
17927 			/* found it, is it at the head? */
17928 			if (runqbp == *head) {
17929 				*head = bp->av_forw;
17930 			} else {
17931 				prevbp->av_forw = bp->av_forw;
17932 			}
17933 			if (*tail == bp) {
17934 				*tail = prevbp;
17935 			}
17936 			bp->av_forw = NULL;
17937 			return (bp); /* found and removed */
17938 		}
17939 		prevbp = runqbp;
17940 	}
17941 	return (NULL);
17942 }
17943 
17944 /*
17945  * Adds a buf_t to the queue pointed to by head and tail.
17946  * Adds it either to the head end or the tail end based on which
17947  * the passed variable end (head or tail) points at.
17948  */
17949 static void
17950 st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp)
17951 {
17952 
17953 	bp->av_forw = NULL;
17954 	if (*head) {
17955 		/* Queue is not empty */
17956 		if (end == *head) {
17957 			/* Add at front of queue */
17958 			bp->av_forw = *head;
17959 			*head = bp;
17960 		} else if (end == *tail) {
17961 			/* Add at end of queue */
17962 			(*tail)->av_forw = bp;
17963 			*tail = bp;
17964 		} else {
17965 			ASSERT(0);
17966 		}
17967 	} else {
17968 		/* Queue is empty */
17969 		*head = bp;
17970 		*tail = bp;
17971 	}
17972 }
17973 
17974 
17975 static uint64_t
17976 st_get_cdb_g0_rw_count(uchar_t *cdb)
17977 {
17978 	uint64_t count;
17979 
17980 	if ((cdb[1]) & 1) {
17981 		/* fixed block mode, the count is the number of blocks */
17982 		count =
17983 		    cdb[2] << 16 |
17984 		    cdb[3] << 8 |
17985 		    cdb[4];
17986 	} else {
17987 		/* variable block mode, the count is the block size */
17988 		count = 1;
17989 	}
17990 	return (count);
17991 }
17992 
17993 static uint64_t
17994 st_get_cdb_g0_sign_count(uchar_t *cdb)
17995 {
17996 	uint64_t count;
17997 
17998 	count =
17999 	    cdb[2] << 16 |
18000 	    cdb[3] << 8 |
18001 	    cdb[4];
18002 	/*
18003 	 * If the sign bit of the 3 byte value is set, extended it.
18004 	 */
18005 	if (count & 0x800000) {
18006 		count |= 0xffffffffff000000;
18007 	}
18008 	return (count);
18009 }
18010 
18011 static uint64_t
18012 st_get_cdb_g0_count(uchar_t *cdb)
18013 {
18014 	uint64_t count;
18015 
18016 	count =
18017 	    cdb[2] << 16 |
18018 	    cdb[3] << 8 |
18019 	    cdb[4];
18020 	return (count);
18021 }
18022 
18023 static uint64_t
18024 st_get_cdb_g5_rw_cnt(uchar_t *cdb)
18025 {
18026 	uint64_t count;
18027 
18028 	if ((cdb[1]) & 1) {
18029 		/* fixed block mode */
18030 		count =
18031 		    cdb[12] << 16 |
18032 		    cdb[13] << 8 |
18033 		    cdb[14];
18034 	} else {
18035 		/* variable block mode */
18036 		count = 1;
18037 	}
18038 	return (count);
18039 }
18040 
18041 static uint64_t
18042 st_get_no_count(uchar_t *cdb)
18043 {
18044 	ASSERT(cdb[0] == SCMD_REWIND);
18045 	return ((uint64_t)cdb[0]);
18046 }
18047 
18048 static uint64_t
18049 st_get_load_options(uchar_t *cdb)
18050 {
18051 	return ((uint64_t)(cdb[4] | (LD_HOLD << 1)));
18052 }
18053 
18054 static uint64_t
18055 st_get_erase_options(uchar_t *cdb)
18056 {
18057 	return (cdb[1] | (cdb[0] << 8));
18058 }
18059 
18060 static uint64_t
18061 st_get_cdb_g1_lba(uchar_t *cdb)
18062 {
18063 	uint64_t lba;
18064 
18065 	lba =
18066 	    cdb[3] << 24 |
18067 	    cdb[4] << 16 |
18068 	    cdb[5] << 8 |
18069 	    cdb[6];
18070 	return (lba);
18071 }
18072 
18073 static uint64_t
18074 st_get_cdb_g5_count(uchar_t *cdb)
18075 {
18076 	uint64_t count =
18077 	    cdb[12] << 16 |
18078 	    cdb[13] << 8 |
18079 	    cdb[14];
18080 
18081 	return (count);
18082 }
18083 
18084 static uint64_t
18085 st_get_cdb_g4g5_cnt(uchar_t *cdb)
18086 {
18087 	uint64_t lba;
18088 
18089 	lba =
18090 	    (uint64_t)cdb[4] << 56 |
18091 	    (uint64_t)cdb[5] << 48 |
18092 	    (uint64_t)cdb[6] << 40 |
18093 	    (uint64_t)cdb[7] << 32 |
18094 	    (uint64_t)cdb[8] << 24 |
18095 	    (uint64_t)cdb[9] << 16 |
18096 	    (uint64_t)cdb[10] << 8 |
18097 	    (uint64_t)cdb[11];
18098 	return (lba);
18099 }
18100 
18101 static const cmd_attribute cmd_attributes[] = {
18102 	{ SCMD_READ,
18103 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_READ, POS_EXPECTED,
18104 	    0, 0, 0, st_get_cdb_g0_rw_count },
18105 	{ SCMD_WRITE,
18106 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18107 	    0, 0, 0, st_get_cdb_g0_rw_count },
18108 	{ SCMD_TEST_UNIT_READY,
18109 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18110 	    0, 0, 0 },
18111 	{ SCMD_REWIND,
18112 	    1, 1, 1, 0, 0, DIR_REVC, TRAN_NONE, POS_EXPECTED,
18113 	    0, 0, 0, st_get_no_count },
18114 	{ SCMD_REQUEST_SENSE,
18115 	    0, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18116 	    0, 0, 0 },
18117 	{ SCMD_READ_BLKLIM,
18118 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18119 	    0, 0, 0 },
18120 	{ SCMD_READ_G4,
18121 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_READ, POS_EXPECTED,
18122 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18123 	{ SCMD_WRITE_G4,
18124 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_WRTE, POS_EXPECTED,
18125 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18126 	{ SCMD_READ_REVERSE,
18127 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18128 	    0, 0, 0, st_get_cdb_g0_rw_count },
18129 	{ SCMD_READ_REVERSE_G4,
18130 	    1, 0, 1, 1, 1, DIR_REVC, TRAN_READ, POS_EXPECTED,
18131 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18132 	{ SCMD_WRITE_FILE_MARK,
18133 	    1, 0, 1, 1, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18134 	    0, 0, 0, st_get_cdb_g0_count },
18135 	{ SCMD_WRITE_FILE_MARK_G4,
18136 	    1, 0, 1, 1, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18137 	    0, 0, 0, st_get_cdb_g5_count, st_get_cdb_g4g5_cnt },
18138 	{ SCMD_SPACE,
18139 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18140 	    0, 0, 0, st_get_cdb_g0_sign_count },
18141 	{ SCMD_SPACE_G4,
18142 	    1, 0, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_STARTING,
18143 	    0, 0, 0, st_get_cdb_g4g5_cnt },
18144 	{ SCMD_INQUIRY,
18145 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18146 	    0, 0, 0 },
18147 	{ SCMD_VERIFY_G0,
18148 	    1, 0, 1, 0, 0, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18149 	    0, 0, 0, st_get_cdb_g0_rw_count },
18150 	{ SCMD_VERIFY_G4,
18151 	    1, 0, 1, 0, 1, DIR_FORW, TRAN_NONE, POS_EXPECTED,
18152 	    0, 0, 0, st_get_cdb_g5_rw_cnt, st_get_cdb_g4g5_cnt },
18153 	{ SCMD_RECOVER_BUF,
18154 	    1, 0, 1, 1, 0, DIR_REVC, TRAN_READ, POS_EXPECTED,
18155 	    0, 0, 0 },
18156 	{ SCMD_MODE_SELECT,
18157 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18158 	    0, 0, 0 },
18159 	{ SCMD_RESERVE,
18160 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18161 	    0, 0, 0 },
18162 	{ SCMD_RELEASE,
18163 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18164 	    0, 0, 0 },
18165 	{ SCMD_ERASE,
18166 	    1, 0, 1, 1, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18167 	    0, 0, 0, st_get_erase_options },
18168 	{ SCMD_MODE_SENSE,
18169 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18170 	    0, 0, 0 },
18171 	{ SCMD_LOAD,
18172 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18173 	    0, 0, 0, st_get_load_options },
18174 	{ SCMD_GDIAG,
18175 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18176 	    1, 0, 0 },
18177 	{ SCMD_SDIAG,
18178 	    1, 0, 1, 1, 0, DIR_EITH, TRAN_WRTE, POS_EXPECTED,
18179 	    1, 0, 0 },
18180 	{ SCMD_DOORLOCK,
18181 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_EXPECTED,
18182 	    0, 4, 3 },
18183 	{ SCMD_LOCATE,
18184 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18185 	    0, 0, 0, NULL, st_get_cdb_g1_lba },
18186 	{ SCMD_READ_POSITION,
18187 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18188 	    0, 0, 0 },
18189 	{ SCMD_WRITE_BUFFER,
18190 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18191 	    1, 0, 0 },
18192 	{ SCMD_READ_BUFFER,
18193 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18194 	    1, 0, 0 },
18195 	{ SCMD_REPORT_DENSITIES,
18196 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18197 	    0, 0, 0 },
18198 	{ SCMD_LOG_SELECT_G1,
18199 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18200 	    0, 0, 0 },
18201 	{ SCMD_LOG_SENSE_G1,
18202 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18203 	    0, 0, 0 },
18204 	{ SCMD_PRIN,
18205 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18206 	    0, 0, 0 },
18207 	{ SCMD_PROUT,
18208 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18209 	    0, 0, 0 },
18210 	{ SCMD_READ_ATTRIBUTE,
18211 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18212 	    0, 0, 0 },
18213 	{ SCMD_WRITE_ATTRIBUTE,
18214 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18215 	    0, 0, 0 },
18216 	{ SCMD_LOCATE_G4,
18217 	    1, 1, 1, 0, 0, DIR_EITH, TRAN_NONE, POS_EXPECTED,
18218 	    0, 0, 0, NULL, st_get_cdb_g4g5_cnt },
18219 	{ SCMD_REPORT_LUNS,
18220 	    0, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18221 	    0, 0, 0 },
18222 	{ SCMD_SVC_ACTION_IN_G5,
18223 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18224 	    0, 0, 0 },
18225 	{ SCMD_MAINTENANCE_IN,
18226 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_READ, POS_EXPECTED,
18227 	    0, 0, 0 },
18228 	{ SCMD_MAINTENANCE_OUT,
18229 	    1, 1, 0, 0, 0, DIR_NONE, TRAN_WRTE, POS_EXPECTED,
18230 	    0, 0, 0 },
18231 	{ 0xff, /* Default attribute for unsupported commands */
18232 	    1, 0, 0, 0, 0, DIR_NONE, TRAN_NONE, POS_STARTING,
18233 	    1, 0, 0, NULL, NULL }
18234 };
18235 
18236 static const cmd_attribute *
18237 st_lookup_cmd_attribute(unsigned char cmd)
18238 {
18239 	int i;
18240 	cmd_attribute const *attribute;
18241 
18242 	for (i = 0; i < ST_NUM_MEMBERS(cmd_attributes); i++) {
18243 		attribute = &cmd_attributes[i];
18244 		if (attribute->cmd == cmd) {
18245 			return (attribute);
18246 		}
18247 	}
18248 	ASSERT(attribute);
18249 	return (attribute);
18250 }
18251 
18252 static int
18253 st_reset(struct scsi_tape *un, int reset_type)
18254 {
18255 	int rval;
18256 
18257 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
18258 
18259 	ST_FUNC(ST_DEVINFO, st_reset);
18260 	un->un_rsvd_status |= ST_INITIATED_RESET;
18261 	mutex_exit(ST_MUTEX);
18262 	do {
18263 		rval = scsi_reset(&un->un_sd->sd_address, reset_type);
18264 		if (rval == 0) {
18265 			switch (reset_type) {
18266 			case RESET_LUN:
18267 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18268 				    "LUN reset failed trying target reset");
18269 				reset_type = RESET_TARGET;
18270 				break;
18271 			case RESET_TARGET:
18272 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18273 				    "target reset failed trying bus reset");
18274 				reset_type = RESET_BUS;
18275 				break;
18276 			case RESET_BUS:
18277 				ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
18278 				    "bus reset failed trying all reset");
18279 				reset_type = RESET_ALL;
18280 			default:
18281 				mutex_enter(ST_MUTEX);
18282 				return (rval);
18283 			}
18284 		}
18285 	} while (rval == 0);
18286 	mutex_enter(ST_MUTEX);
18287 	return (rval);
18288 }
18289 
18290 
18291 static void
18292 st_reset_notification(caddr_t arg)
18293 {
18294 	struct scsi_tape *un = (struct scsi_tape *)arg;
18295 
18296 	ST_FUNC(ST_DEVINFO, st_reset_notification);
18297 	mutex_enter(ST_MUTEX);
18298 
18299 	un->un_unit_attention_flags |= 2;
18300 	if ((un->un_rsvd_status & (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) ==
18301 	    ST_RESERVE) {
18302 		un->un_rsvd_status |= ST_LOST_RESERVE;
18303 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18304 		    "Lost Reservation notification");
18305 	} else {
18306 		ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
18307 		    "reset notification");
18308 	}
18309 
18310 	if ((un->un_restore_pos == 0) &&
18311 	    (un->un_state == ST_STATE_CLOSED) ||
18312 	    (un->un_state == ST_STATE_OPEN_PENDING_IO) ||
18313 	    (un->un_state == ST_STATE_CLOSING)) {
18314 		un->un_restore_pos = 1;
18315 	}
18316 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
18317 	    "reset and state was %d\n", un->un_state);
18318 	mutex_exit(ST_MUTEX);
18319 }
18320